Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.PluginInfrastructure/PluginManager.cs @ 1035

Last change on this file since 1035 was 997, checked in by kgrading, 16 years ago

improved sandbox (#410)

File size: 10.4 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      PermissionSet pset;
164
165      DiscoveryService dService = new DiscoveryService();
166      //get the declaring plugin of the job
167      PluginInfo jobPlugin = dService.GetDeclaringPlugin(jobType);
168
169      //get all the plugins that have dependencies with the jobplugin
170      List<PluginInfo> depPlugins = GetDependentPlugins(jobPlugin);
171      //insert all jobs into one list
172      depPlugins.Add(jobPlugin);
173     
174      if (sandboxed) {
175        pset = new PermissionSet(PermissionState.None);
176        pset.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
177        pset.AddPermission(new ReflectionPermission(PermissionState.Unrestricted));
178        /*foreach (PluginInfo plugin in depPlugins) {
179            foreach(String assemblies in plugin.Assemblies)
180              pset.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, assemblies));
181        }*/
182        pset.AddPermission(new FileIOPermission(PermissionState.Unrestricted));
183      } else {
184        pset = new PermissionSet(PermissionState.Unrestricted);
185      }
186      AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
187      setup.PrivateBinPath = pluginDir;
188      setup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;     
189      AppDomain applicationDomain = AppDomain.CreateDomain(friendlyName, AppDomain.CurrentDomain.Evidence, setup, pset, CreateStrongName(Assembly.GetExecutingAssembly()));
190                     
191      Runner remoteRunner = (Runner)applicationDomain.CreateInstanceAndUnwrap(typeof(Runner).Assembly.GetName().Name, typeof(Runner).FullName);
192      NotifyListeners(PluginManagerAction.Initializing, "All plugins");
193
194      if (depPlugins != null && depPlugins.Count > 0) {
195        remoteRunner.LoadPlugins(depPlugins);
196      }
197      NotifyListeners(PluginManagerAction.Initialized, "All plugins");
198      return applicationDomain;
199    }
200
201    /// <summary>
202    /// Calculates a set of plugins that directly or transitively depend on the plugin given in the argument.
203    /// </summary>
204    /// <param name="pluginInfo"></param>
205    /// <returns>a list of plugins that are directly of transitively dependent.</returns>
206    public List<PluginInfo> GetDependentPlugins(PluginInfo pluginInfo) {
207      List<PluginInfo> mergedList = new List<PluginInfo>();
208      foreach (PluginInfo plugin in InstalledPlugins) {
209        if (plugin.Dependencies.Contains(pluginInfo)) {
210          if (!mergedList.Contains(plugin)) {
211            mergedList.Add(plugin);
212          }
213          // for each of the dependent plugins add the list of transitively dependent plugins
214          // make sure that only one entry for each plugin is added to the merged list
215          GetDependentPlugins(plugin).ForEach(delegate(PluginInfo dependentPlugin) {
216            if (!mergedList.Contains(dependentPlugin)) {
217              mergedList.Add(dependentPlugin);
218            }
219          });
220        }
221      }
222      return mergedList;
223    }
224
225    public void UnloadAllPlugins() {
226      AppDomain.Unload(pluginDomain);
227    }
228
229    public void LoadAllPlugins() {
230      Initialize();
231    }
232
233    public void OnDelete(PluginInfo pluginInfo) {
234      remoteLoader.OnDelete(pluginInfo);
235    }
236
237    public void OnInstall(PluginInfo pluginInfo) {
238      remoteLoader.OnInstall(pluginInfo);
239    }
240
241    public void OnPreUpdate(PluginInfo pluginInfo) {
242      remoteLoader.OnPreUpdate(pluginInfo);
243    }
244
245    public void OnPostUpdate(PluginInfo pluginInfo) {
246      remoteLoader.OnPostUpdate(pluginInfo);
247    }
248
249    private void NotifyListeners(PluginManagerAction action, string text) {
250      if (Action != null) {
251        Action(this, new PluginManagerActionEventArgs(text, action));
252      }
253    }
254  }
255}
Note: See TracBrowser for help on using the repository browser.