aboutsummaryrefslogtreecommitdiff
path: root/lib/Plugins.Runtime/src/RuntimePluginLoader.cs
blob: 60edf55ddb4bbcea2e95466d3330de211caf805b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
/*
* Copyright (c) 2024 Vaughn Nugent
* 
* Library: VNLib
* Package: VNLib.Plugins.Runtime
* File: RuntimePluginLoader.cs 
*
* RuntimePluginLoader.cs is part of VNLib.Plugins.Runtime which is part of the larger 
* VNLib collection of libraries and utilities.
*
* VNLib.Plugins.Runtime is free software: you can redistribute it and/or modify 
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 2 of the License,
* or (at your option) any later version.
*
* VNLib.Plugins.Runtime is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License 
* along with VNLib.Plugins.Runtime. If not, see http://www.gnu.org/licenses/.
*/

using System;
using System.IO;
using System.Reflection;

using VNLib.Utils;
using VNLib.Utils.IO;
using VNLib.Utils.Logging;

namespace VNLib.Plugins.Runtime
{
    /// <summary>
    /// A runtime .NET assembly loader specialized to load
    /// assemblies that export <see cref="IPlugin"/> types.
    /// </summary>
    public sealed class RuntimePluginLoader : VnDisposeable, IPluginReloadEventHandler
    {
        private static readonly IPluginAssemblyWatcher Watcher = new AssemblyWatcher();
       
        private readonly IPluginAssemblyLoader Loader;      
        private readonly ILogProvider? Log;

        /// <summary>
        /// Gets the plugin assembly loader configuration information
        /// </summary>
        public IPluginAssemblyLoadConfig Config => Loader.Config;

        /// <summary>
        /// Gets the plugin lifecycle controller
        /// </summary>
        public PluginController Controller { get; }

        /// <summary>
        /// Creates a new <see cref="RuntimePluginLoader"/> with the specified config and host config dom.
        /// </summary>
        /// <param name="loader">The plugin's assembly loader</param>
        /// <param name="log">A log provider to write plugin unload log events to</param>
        /// <exception cref="ArgumentNullException"></exception>
        public RuntimePluginLoader(IPluginAssemblyLoader loader, ILogProvider? log)
        {
            Log = log;
            Loader = loader ?? throw new ArgumentNullException(nameof(loader));

            //Configure watcher if requested
            if (loader.Config.WatchForReload)
            {
                Watcher.WatchAssembly(this, loader);
            }

            //Init container
            Controller = new();
        }

        /// <summary>
        /// Initializes the plugin loader, and populates the <see cref="Controller"/>
        /// with initialized plugins.
        /// </summary>
        /// <returns>A task that represents the initialization</returns>
        /// <exception cref="IOException"></exception>
        /// <exception cref="FileNotFoundException"></exception>
        public void InitializeController()
        {
            //Prep the assembly loader
            Loader.Load();

            //Load the main assembly
            Assembly PluginAsm = Loader.GetAssembly();

            //Init container from the assembly
            Controller.InitializePlugins(PluginAsm);

            string[] cliArgs = Environment.GetCommandLineArgs();

            //Write the config to binary to pass it to the plugin
            using VnMemoryStream vms = new();

            //Read config data
            Loader.Config.ReadConfigurationData(vms);

            //Reset memstream
            vms.Seek(0, SeekOrigin.Begin);

            //Configure log/doms
            Controller.ConfigurePlugins(vms, cliArgs);
        }

        /// <summary>
        /// Loads all configured plugins by calling <see cref="IPlugin.Load"/>
        /// event hook on the current thread. Loading exceptions are aggregated so not
        /// to block individual loading.
        /// </summary>
        /// <exception cref="AggregateException"></exception>
        public void LoadPlugins() => Controller.LoadPlugins();

        /// <summary>
        /// Manually reload the internal <see cref="IPluginAssemblyLoader"/>
        /// which will reload the assembly and re-initialize the controller
        /// </summary>
        /// <param name="forceGc">A value that indicates if the current unload should cause a manual garbage collection</param>
        /// <exception cref="AggregateException"></exception>
        /// <exception cref="NotSupportedException"></exception>
        public void ReloadPlugins(bool forceGc)
        {
            //Not unloadable
            if (!Config.Unloadable)
            {
                throw new NotSupportedException("The loading context is not unloadable, you may not dynamically reload plugins");
            }

            //All plugins must be unloaded first
            UnloadAll(forceGc);

            //Reload the assembly and 
            InitializeController();

            //Load plugins
            LoadPlugins();
        }

        /// <summary>
        /// Calls the <see cref="IPlugin.Unload"/> method for all plugins within the lifecycle controller
        /// and invokes the <see cref="IPluginEventListener.OnPluginUnloaded(PluginController, object?)"/>
        /// for all listeners.
        /// </summary>
        /// <exception cref="AggregateException"></exception>
        public void UnloadPlugins() => Controller.UnloadPlugins();

        /// <summary>
        /// Attempts to unload all plugins within the lifecycle controller, all event handlers
        /// then attempts to unload the <see cref="IPluginAssemblyLoader"/> if dynamic unloading 
        /// is enabled, otherwise does nothing.
        /// </summary>
        /// <param name="forceGc">A value that indicates if the current unload should cause a manual garbage collection</param>
        /// <exception cref="AggregateException"></exception>
        public void UnloadAll(bool forceGc)
        {
            UnloadPlugins();

            //If the assembly loader is unloadable calls its unload method
            if (Config.Unloadable)
            {
                Loader.Unload();
            }

            //Optionally wait for GC to finish
            if (forceGc)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }

        //Process unload events

        void IPluginReloadEventHandler.OnPluginUnloaded(IPluginAssemblyLoader loader)
        {
            try
            {
                //All plugins must be unloaded before the assembly loader
                UnloadPlugins();

                //Unload the loader before initializing
                loader.Unload();

                //Reload the assembly and controller
                InitializeController();

                //Load plugins
                LoadPlugins();
            }
            catch (Exception ex)
            {
                Log?.Error("Failed reload plugins for {loader}\n{ex}", Config.AssemblyFile, ex);
            }
        }

        ///<inheritdoc/>
        protected override void Free()
        {
            //Stop watching for events
            Watcher.StopWatching(this);

            //Cleanup
            Controller.Dispose();
            Loader.Dispose();
        }
    }
}