aboutsummaryrefslogtreecommitdiff
path: root/lib/Plugins.Essentials.ServiceStack/src/PluginManager.cs
blob: 2013a5878007ca5671ea2da70874b271ccc163c2 (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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
/*
* Copyright (c) 2023 Vaughn Nugent
* 
* Library: VNLib
* Package: VNLib.Plugins.Essentials.ServiceStack
* File: PluginManager.cs 
*
* PluginManager.cs is part of VNLib.Plugins.Essentials.ServiceStack which 
* is part of the larger VNLib collection of libraries and utilities.
*
* VNLib.Plugins.Essentials.ServiceStack is free software: you can redistribute it and/or modify 
* it under the terms of the GNU Affero 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.Essentials.ServiceStack 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program.  If not, see https://www.gnu.org/licenses/.
*/


using System;
using System.IO;
using System.Linq;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Collections.Generic;

using VNLib.Utils;
using VNLib.Utils.IO;
using VNLib.Utils.Logging;
using VNLib.Utils.Extensions;
using VNLib.Plugins.Runtime;

namespace VNLib.Plugins.Essentials.ServiceStack
{

    /// <summary>
    /// A sealed type that manages the plugin interaction layer. Manages the lifetime of plugin
    /// instances, exposes controls, and relays stateful plugin events.
    /// </summary>
    internal sealed class PluginManager : VnDisposeable, IPluginManager, IPluginEventListener
    {
        private const string PLUGIN_FILE_EXTENSION = ".dll";

        private readonly List<ManagedPlugin> _plugins;
        private readonly IReadOnlyCollection<ServiceGroup> _dependents;
      

        private IEnumerable<LivePlugin> _livePlugins => _plugins.SelectMany(static p => p.Controller.Plugins);

        /// <summary>
        /// The collection of internal controllers
        /// </summary>
        public IEnumerable<IManagedPlugin> Plugins => _plugins;

        public PluginManager(IReadOnlyCollection<ServiceGroup> dependents)
        {
            _plugins = new();
            _dependents = dependents;
        }

        /// <inheritdoc/>
        /// <exception cref="ObjectDisposedException"></exception>
        public void LoadPlugins(IPluginLoadConfiguration config, ILogProvider appLog)
        {
            Check();            

            //Load all virtual file assemblies withing the plugin folder
            DirectoryInfo dir = new(config.PluginDir);

            if (!dir.Exists)
            {
                appLog.Warn("Plugin directory {dir} does not exist. No plugins were loaded", config.PluginDir);
                return;
            }

            appLog.Information("Loading managed plugins");

            //Enumerate all dll files within this dir
            IEnumerable<DirectoryInfo> dirs = dir.EnumerateDirectories("*", SearchOption.TopDirectoryOnly);

            //Select only dirs with a dll that is named after the directory name
            IEnumerable<string> pluginPaths = GetPluginPaths(dirs);

            IEnumerable<string> pluginFileNames = pluginPaths.Select(static s => $"{Path.GetFileName(s)}\n");

            appLog.Debug("Found plugin files: \n{files}", string.Concat(pluginFileNames));

            /*
             * We need to get the assembly loader for the plugin file, then create its 
             * RuntimePluginLoader which will be passed to the Managed plugin instance
             */

            ManagedPlugin[] wrappers = pluginPaths.Select(pw => config.AssemblyLoaderFactory.GetLoaderForPluginFile(pw))
                                        .Select(l => new RuntimePluginLoader(l, config.HostConfig, config.PluginErrorLog))
                                        .Select(loader => new ManagedPlugin(loader, this))
                                        .ToArray();

            //Add to loaded plugins
            _plugins.AddRange(wrappers);

            //Load plugins
            InitiailzeAndLoad(appLog);
        }

        private static IEnumerable<string> GetPluginPaths(IEnumerable<DirectoryInfo> dirs)
        {
            //Select only dirs with a dll that is named after the directory name
            return dirs.Where(static pdir =>
            {
                string compined = Path.Combine(pdir.FullName, pdir.Name);
                string FilePath = string.Concat(compined, PLUGIN_FILE_EXTENSION);
                return FileOperations.FileExists(FilePath);
            })
            //Return the name of the dll file to import
            .Select(static pdir =>
            {
                string compined = Path.Combine(pdir.FullName, pdir.Name);
                return string.Concat(compined, PLUGIN_FILE_EXTENSION);
            });
        }

        private void InitiailzeAndLoad(ILogProvider debugLog) 
        {
            //Load all async
            _plugins.ToArray().TryForeach(p => InitializePlugin(p, debugLog));           

            //Load stage, load all multithreaded
            Parallel.ForEach(_plugins, p => LoadPlugin(p, debugLog));

            debugLog.Information("Plugin loading completed");
        }

        private void InitializePlugin(ManagedPlugin plugin, ILogProvider debugLog)
        {
            void LogAndRemovePlugin(Exception ex)
            {
                debugLog.Error(ex, $"Exception raised during initialzation of {plugin.PluginFileName}. It has been removed from the collection\n{ex}");

                //Remove the plugin from the list while locking it
                lock (_plugins)
                {
                    _plugins.Remove(plugin);
                }

                //Dispose the plugin
                plugin.Dispose();
            }

            try
            {
                //Load wrapper
                plugin.InitializePlugins();
            }
            catch (Exception ex)
            {
                LogAndRemovePlugin(ex);
            }
        }

        private static void LoadPlugin(ManagedPlugin plugin, ILogProvider debugLog)
        {
            Stopwatch sw = new();
            try
            {
                sw.Start();

                //Load wrapper
                plugin.LoadPlugins();

                sw.Stop();

                /*
                 * If the plugin assembly does not expose any plugin types or there is an issue loading the assembly, 
                 * its types my not unify, then we should give the user feedback insead of a silent fail.
                 */
                if (!plugin.Controller.Plugins.Any())
                {
                    debugLog.Warn("No plugin instances were exposed via {ams} assembly. This may be due to an assebmly mismatch", plugin.PluginFileName);
                }
                else
                {
                    debugLog.Verbose("Loaded {pl} in {tm} ms", plugin.PluginFileName, sw.ElapsedMilliseconds);
                }

            }
            catch (Exception ex) 
            {
                debugLog.Error(ex, $"Exception raised during loading {plugin.PluginFileName}. Failed to load plugin \n{ex}");
            }
            finally
            {
                sw.Stop();
            }
        }

        /// <inheritdoc/>
        public bool SendCommandToPlugin(string pluginName, string message, StringComparison nameComparison = StringComparison.Ordinal)
        {
            Check();

            //Find the single plugin by its name
            LivePlugin? pl = _livePlugins.Where(p => pluginName.Equals(p.PluginName, nameComparison)).SingleOrDefault();

            //Send the command
            return pl?.SendConsoleMessage(message) ?? false;
        }

        /// <inheritdoc/>
        public void ForceReloadAllPlugins()
        {
            //Reload all plugin managers
            _plugins.TryForeach(static p => p.ReloadPlugins());
        }

        /// <inheritdoc/>
        public void UnloadPlugins()
        {
            //Unload all plugin controllers
            _plugins.TryForeach(static p => p.UnloadPlugins());

            /*
             * All plugin instances must be destroyed because the 
             * only way they will be loaded is from their files 
             * again, so they must be released
             */
            _plugins.TryForeach(static p => p.Dispose());
            _plugins.Clear();
        }

        protected override void Free()
        {
            //Cleanup on dispose if unload failed
            _plugins.TryForeach(static p => p.Dispose());
            _plugins.Clear();
        }

        void IPluginEventListener.OnPluginLoaded(PluginController controller, object? state)
        {
            //Get event listeners at event time because deps may be modified by the domain
            ServiceGroup[] deps = _dependents.Select(static d => d).ToArray();

            //run onload method
            deps.TryForeach(d => d.OnPluginLoaded((IManagedPlugin)state!));
        }

        void IPluginEventListener.OnPluginUnloaded(PluginController controller, object? state)
        {
            //Get event listeners at event time because deps may be modified by the domain
            ServiceGroup[] deps = _dependents.Select(static d => d).ToArray();

            //Run unloaded method
            deps.TryForeach(d => d.OnPluginUnloaded((IManagedPlugin)state!));
        }
    }
}