Free cookie consent management tool by TermsFeed Policy Generator

source: branches/CEDMA-Refactoring-Ticket419/HeuristicLab.PluginInfrastructure/PluginManager.cs @ 978

Last change on this file since 978 was 886, checked in by kgrading, 16 years ago

worked on #410

File size: 9.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Security.Policy;
25using System.Reflection;
26using System.Diagnostics;
27using System.Security.Permissions;
28using System.Security;
29
30namespace HeuristicLab.PluginInfrastructure {
31
32  // must extend MarshalByRefObject because of event passing between Loader and PluginManager (each in it's own AppDomain)
33  public class PluginManager : MarshalByRefObject {
34
35    // singleton: only one manager allowed in each AppDomain
36    private static PluginManager manager = new PluginManager();
37    public static PluginManager Manager {
38      get { return manager; }
39    }
40
41    // singleton: only one control manager allowed in each applicatoin (i.e. AppDomain)
42    private static IControlManager controlManager;
43    public static IControlManager ControlManager {
44      get { return controlManager; }
45      set { controlManager = value; }
46    }
47
48    public event PluginManagerActionEventHandler Action;
49
50    // holds a proxy for the loader in the special AppDomain for PluginManagament
51    private Loader remoteLoader;
52    private AppDomain pluginDomain;
53    private string pluginDir;
54
55    // singleton pattern
56    private PluginManager() {
57      this.pluginDir = HeuristicLab.PluginInfrastructure.Properties.Settings.Default.PluginDir;
58    }
59
60    public ICollection<PluginInfo> InstalledPlugins {
61      get { return remoteLoader.InstalledPlugins; }
62    }
63
64    public ICollection<PluginInfo> DisabledPlugins {
65      get { return remoteLoader.DisabledPlugins; }
66    }
67
68    public ICollection<PluginInfo> ActivePlugins {
69      get { return remoteLoader.ActivePlugins; }
70    }
71
72    public ICollection<ApplicationInfo> InstalledApplications {
73      get { return remoteLoader.InstalledApplications; }
74    }
75
76    private ICollection<PluginInfo> loadedPlugins;
77    public ICollection<PluginInfo> LoadedPlugins {
78      get { return loadedPlugins; }
79      internal set { loadedPlugins = value; }
80    }
81
82    /// <summary>
83    /// Creates a dedicated AppDomain for loading all plugins and checking dependencies.
84    /// </summary>
85    public void Initialize() {
86      NotifyListeners(PluginManagerAction.Initializing, "-");
87      AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
88      setup.PrivateBinPath = pluginDir;
89      pluginDomain = AppDomain.CreateDomain("plugin domain", null, setup);
90      remoteLoader = (Loader)pluginDomain.CreateInstanceAndUnwrap("HeuristicLab.PluginInfraStructure", "HeuristicLab.PluginInfrastructure.Loader");
91      remoteLoader.PluginAction += delegate(object sender, PluginManagerActionEventArgs args) { if (Action != null) Action(this, args); };
92      remoteLoader.Init();
93      NotifyListeners(PluginManagerAction.Initialized, "-");
94    }
95
96    /// <summary>
97    /// Creates a separate AppDomain.
98    /// Loads all active plugin assemblies and starts the application in the new AppDomain via a PluginRunner instance activated in the new AppDomain
99    /// </summary>
100    /// <param name="appInfo">application to run</param>
101    public void Run(ApplicationInfo appInfo) {
102      // create a separate AppDomain for the application
103      // activate a PluginRunner instance in the application
104      // and remotely tell it to start the application
105
106      NotifyListeners(PluginManagerAction.Starting, appInfo.Name);
107      AppDomain applicationDomain = null;
108      try {
109        applicationDomain = CreateAndInitAppDomain(appInfo.Name + " AppDomain");
110        Runner remoteRunner = (Runner)applicationDomain.CreateInstanceAndUnwrap(typeof(Runner).Assembly.GetName().Name, typeof(Runner).FullName);
111        remoteRunner.Run(appInfo);
112      }
113      finally {
114        // make sure domain is unloaded in all cases
115        if (applicationDomain != null) AppDomain.Unload(applicationDomain);
116      }
117    }
118
119    /// <summary>
120    /// Creates a new AppDomain with all plugins preloaded.
121    /// </summary>
122    /// <param name="friendlyName">Name of the new AppDomain</param>
123    /// <returns>the new AppDomain with all plugins preloaded.</returns>
124    public AppDomain CreateAndInitAppDomain(string friendlyName) {
125      AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
126      setup.PrivateBinPath = pluginDir;
127      AppDomain applicationDomain = AppDomain.CreateDomain(friendlyName, null, setup);
128      Runner remoteRunner = (Runner)applicationDomain.CreateInstanceAndUnwrap(typeof(Runner).Assembly.GetName().Name, typeof(Runner).FullName);
129      NotifyListeners(PluginManagerAction.Initializing, "All plugins");
130      if (remoteLoader != null) {
131        remoteRunner.LoadPlugins(remoteLoader.ActivePlugins);
132      } else if (LoadedPlugins != null && LoadedPlugins.Count > 0) {
133        remoteRunner.LoadPlugins(LoadedPlugins);
134      }
135      NotifyListeners(PluginManagerAction.Initialized, "All plugins");
136      return applicationDomain;
137    }
138
139    /// <summary>
140    /// Creates a new AppDomain with all plugins preloaded and Sandboxing capability
141    /// </summary>
142    /// <param name="assembly">Assembly reference</param>
143    /// <returns>the strongname of the assembly</returns>
144    private StrongName CreateStrongName(Assembly assembly) {
145      if (assembly == null)
146        throw new ArgumentNullException("assembly");
147
148      AssemblyName assemblyName = assembly.GetName();
149      Debug.Assert(assemblyName != null, "Could not get assembly name");
150
151      // get the public key blob
152      byte[] publicKey = assemblyName.GetPublicKey();
153      if (publicKey == null || publicKey.Length == 0)
154        throw new InvalidOperationException("Assembly is not strongly named");
155
156      StrongNamePublicKeyBlob keyBlob = new StrongNamePublicKeyBlob(publicKey);
157
158      // and create the StrongName
159      return new StrongName(keyBlob, assemblyName.Name, assemblyName.Version);
160    }
161
162    public AppDomain CreateAndInitAppDomainWithSandbox(string friendlyName, bool sandboxed, Type jobType) {
163
164      PermissionSet pset;
165      if (sandboxed) {
166        pset = new PermissionSet(PermissionState.None);
167        pset.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));       
168      } else {
169        pset = new PermissionSet(PermissionState.Unrestricted);
170      }
171      AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
172      setup.PrivateBinPath = pluginDir;
173      setup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;     
174      AppDomain applicationDomain = AppDomain.CreateDomain(friendlyName, AppDomain.CurrentDomain.Evidence, setup, pset, CreateStrongName(Assembly.GetExecutingAssembly()));
175                     
176      Runner remoteRunner = (Runner)applicationDomain.CreateInstanceAndUnwrap(typeof(Runner).Assembly.GetName().Name, typeof(Runner).FullName);
177      NotifyListeners(PluginManagerAction.Initializing, "All plugins");
178
179      DiscoveryService dService = new DiscoveryService();
180      PluginInfo jobPlugin = dService.GetDeclaringPlugin(jobType);
181
182      List<PluginInfo> depPlugins = GetDependentPlugins(jobPlugin);
183
184      if (depPlugins != null && depPlugins.Count > 0) {
185        remoteRunner.LoadPlugins(depPlugins);
186      }
187      NotifyListeners(PluginManagerAction.Initialized, "All plugins");
188      return applicationDomain;
189    }
190
191    /// <summary>
192    /// Calculates a set of plugins that directly or transitively depend on the plugin given in the argument.
193    /// </summary>
194    /// <param name="pluginInfo"></param>
195    /// <returns>a list of plugins that are directly of transitively dependent.</returns>
196    public List<PluginInfo> GetDependentPlugins(PluginInfo pluginInfo) {
197      List<PluginInfo> mergedList = new List<PluginInfo>();
198      foreach (PluginInfo plugin in InstalledPlugins) {
199        if (plugin.Dependencies.Contains(pluginInfo)) {
200          if (!mergedList.Contains(plugin)) {
201            mergedList.Add(plugin);
202          }
203          // for each of the dependent plugins add the list of transitively dependent plugins
204          // make sure that only one entry for each plugin is added to the merged list
205          GetDependentPlugins(plugin).ForEach(delegate(PluginInfo dependentPlugin) {
206            if (!mergedList.Contains(dependentPlugin)) {
207              mergedList.Add(dependentPlugin);
208            }
209          });
210        }
211      }
212      return mergedList;
213    }
214
215    public void UnloadAllPlugins() {
216      AppDomain.Unload(pluginDomain);
217    }
218
219    public void LoadAllPlugins() {
220      Initialize();
221    }
222
223    public void OnDelete(PluginInfo pluginInfo) {
224      remoteLoader.OnDelete(pluginInfo);
225    }
226
227    public void OnInstall(PluginInfo pluginInfo) {
228      remoteLoader.OnInstall(pluginInfo);
229    }
230
231    public void OnPreUpdate(PluginInfo pluginInfo) {
232      remoteLoader.OnPreUpdate(pluginInfo);
233    }
234
235    public void OnPostUpdate(PluginInfo pluginInfo) {
236      remoteLoader.OnPostUpdate(pluginInfo);
237    }
238
239    private void NotifyListeners(PluginManagerAction action, string text) {
240      if (Action != null) {
241        Action(this, new PluginManagerActionEventArgs(text, action));
242      }
243    }
244  }
245}
Note: See TracBrowser for help on using the repository browser.