Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OaaS/HeuristicLab.Clients.Hive.Slave/3.3/Manager/PluginManager.cs @ 13749

Last change on this file since 13749 was 9365, checked in by fschoepp, 12 years ago

#1888:

  • WorkerRole of Slave now logs all exceptions during startup to the blobstore (slavelog).
  • The PluginManager throws an exception during CheckWorkingDirectories() (Save method) which will be caught now, preventing crashes in Windows Azure.
  • "db.DeferredLocal = false" has been removed to prevent loading bugs.
  • HiveScenarioManager doesn't crash anymore, if he can't find an algorithm within a job during retrieval of the run results.
File size: 12.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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.IO;
25using System.Linq;
26using System.Reflection;
27using System.Runtime.Serialization.Formatters.Binary;
28using System.Threading;
29using HeuristicLab.Core;
30using CoreProperties = HeuristicLab.Clients.Hive.SlaveCore.Properties;
31
32namespace HeuristicLab.Clients.Hive.SlaveCore {
33  public class PluginManager {
34    private static object locker = new object();
35    private string lastUsedFileName = CoreProperties.Settings.Default.LastUsedFileName;
36    //maximum number of days after which a plugin gets deleted if not used
37    private int pluginLifetime = CoreProperties.Settings.Default.PluginLifetime;
38
39    private string PluginCacheDir { get; set; }
40    public string PluginTempBaseDir { get; set; }
41    private ILog log;
42    private IPluginProvider pluginService;
43    private List<Guid> cachedPluginsGuids = new List<Guid>();
44
45    public PluginManager(IPluginProvider pluginService, ILog log) {
46      this.pluginService = pluginService;
47      this.log = log;
48      CheckWorkingDirectories();
49      PluginCacheDir = CoreProperties.Settings.Default.PluginCacheDir;
50      PluginTempBaseDir = CoreProperties.Settings.Default.PluginTempBaseDir;
51      DoUpdateRun();
52    }
53
54    /// <summary>
55    /// Normally the configuration file just contains the folder names of the PluginCache and the AppDomain working directory.
56    /// This means that these folders are created in the current directory which is ok for the console client and the windows service.
57    /// For the HL client we can't do that because the plugin infrastructure gets confused when starting HeuristicLab.
58    /// Therefore if there is only a relative path in the config, we change that to the temp path.
59    /// </summary>
60    private void CheckWorkingDirectories() {
61      if (!Path.IsPathRooted(CoreProperties.Settings.Default.PluginCacheDir)) {
62        CoreProperties.Settings.Default.PluginCacheDir = Path.Combine(Path.GetTempPath(), CoreProperties.Settings.Default.PluginCacheDir);
63        try {
64          CoreProperties.Settings.Default.Save();
65        }
66        catch (Exception ex) {
67          log.LogException(ex);
68        }
69      }
70
71      if (!Path.IsPathRooted(CoreProperties.Settings.Default.PluginTempBaseDir)) {
72        CoreProperties.Settings.Default.PluginTempBaseDir = Path.Combine(Path.GetTempPath(), CoreProperties.Settings.Default.PluginTempBaseDir);
73        try {
74          CoreProperties.Settings.Default.Save();       
75        }
76        catch (Exception ex) {
77          log.LogException(ex);
78        }       
79      }
80    }
81
82    /// <summary>
83    /// Returns the last directory of a path
84    /// </summary>   
85    private string GetFilenameFromPath(string path) {
86      string[] dirParts = path.Split(Path.DirectorySeparatorChar);
87      if (dirParts.Length > 0) {
88        string fileGuid = dirParts[dirParts.Length - 1];
89        return fileGuid;
90      } else
91        return "";
92    }
93
94    private void DoUpdateRun() {
95      SafelyCreateDirectory(PluginCacheDir);
96      lock (cachedPluginsGuids) {
97        cachedPluginsGuids.Clear();
98        foreach (string dir in Directory.EnumerateDirectories(PluginCacheDir)) {
99          cachedPluginsGuids.Add(Guid.Parse(GetFilenameFromPath(dir)));
100        }
101      }
102    }
103
104    public void CopyPluginsForJob(List<Plugin> requests, Guid jobId, out string configFileName) {
105      configFileName = string.Empty;
106      String targetDir = Path.Combine(PluginTempBaseDir, jobId.ToString());
107
108      RecreateDirectory(targetDir);
109
110      foreach (Plugin requestedPlugin in requests) {
111        var filePaths = GetPluginFilePaths(requestedPlugin.Id);
112        foreach (string filePath in filePaths) {
113          File.Copy(filePath, Path.Combine(targetDir, Path.GetFileName(filePath)));
114        }
115
116        if (requestedPlugin.Name == CoreProperties.Settings.Default.ConfigurationName) {
117          // configuration plugin consists only of 1 file (usually the "HeuristicLab X.X.exe.config")
118          configFileName = Path.Combine(targetDir, Path.GetFileName(filePaths.SingleOrDefault()));
119        }
120      }
121
122      // copy files from PluginInfrastructure (which are not declared in any plugins)
123      string baseDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
124      CopyFile(baseDir, targetDir, CoreProperties.Settings.Default.PluginInfrastructureDll);
125      CopyFile(baseDir, targetDir, CoreProperties.Settings.Default.SharpZipLibDll);
126      CopyFile(baseDir, targetDir, CoreProperties.Settings.Default.SharpZipLibLicense);
127
128      // copy slave plugins, otherwise its not possible to register the UnhandledException handler to the appdomain       
129      CopyFile(baseDir, targetDir, CoreProperties.Settings.Default.ClientsHiveSlaveCoreDll);
130      CopyFile(baseDir, targetDir, CoreProperties.Settings.Default.ClientsHiveDll);
131      CopyFile(baseDir, targetDir, CoreProperties.Settings.Default.HiveDll);
132      CopyFile(baseDir, targetDir, CoreProperties.Settings.Default.ClientsCommonDll);
133    }
134
135    private static DirectoryInfo RecreateDirectory(String targetDir) {
136      var di = new DirectoryInfo(targetDir);
137      if (di.Exists) Directory.Delete(targetDir, true);
138      di.Refresh();
139      while (di.Exists) {
140        Thread.Sleep(CoreProperties.Settings.Default.DirOpSleepTime);
141        di.Refresh();
142      }
143      return SafelyCreateDirectory(targetDir);
144    }
145
146    private static DirectoryInfo SafelyCreateDirectory(String targetDir) {
147      var di = new DirectoryInfo(targetDir);
148      if (!di.Exists) {
149        di = Directory.CreateDirectory(targetDir);
150        while (!di.Exists) {
151          Thread.Sleep(CoreProperties.Settings.Default.DirOpSleepTime);
152          di.Refresh();
153        }
154      }
155      return di;
156    }
157
158    private void CopyFile(string baseDir, string targetDir, string fileName) {
159      if (!File.Exists(Path.Combine(targetDir, fileName))) File.Copy(Path.Combine(baseDir, fileName), Path.Combine(targetDir, fileName));
160    }
161
162    /// <summary>
163    /// Updates the plugin cache with missing plugins and
164    /// then copies the required plugins for the task.
165    /// </summary>       
166    public void PreparePlugins(Task task, out string configFileName) {
167      lock (locker) {
168        log.LogMessage("Fetching plugins for task " + task.Id);
169
170        List<Guid> missingGuids = new List<Guid>();
171        List<Plugin> neededPlugins = new List<Plugin>();
172        lock (cachedPluginsGuids) {
173          foreach (Guid pluginId in task.PluginsNeededIds) {
174            Plugin plugin = pluginService.GetPlugin(pluginId);
175            if (plugin != null) {
176              neededPlugins.Add(plugin);
177            }
178
179            if (!cachedPluginsGuids.Contains(pluginId)) {
180              missingGuids.Add(pluginId);
181            }
182          }
183        }
184
185        IEnumerable<PluginData> pluginDatas = pluginService.GetPluginDatas(missingGuids);
186
187        if (pluginDatas != null) {
188          foreach (PluginData pluginData in pluginDatas) {
189            string pluginDir = Path.Combine(PluginCacheDir, pluginData.PluginId.ToString());
190
191            //put all files belonging to a plugin in the same directory
192            SafelyCreateDirectory(pluginDir);
193            File.WriteAllBytes(Path.Combine(pluginDir, Path.GetFileName(pluginData.FileName)), pluginData.Data);
194          }
195
196          if (missingGuids.Count > 0) {
197            DoUpdateRun();
198          }
199          CopyPluginsForJob(neededPlugins, task.Id, out configFileName);
200        } else {
201          configFileName = "";
202        }
203        log.LogMessage(string.Format("Fetched {0} plugins for task {1}", missingGuids.Count, task.Id));
204      }
205    }
206
207    /// <summary>
208    /// Returns a list of files which belong to a plugin from the plugincache
209    /// </summary>
210    private IEnumerable<string> GetPluginFilePaths(Guid pluginId) {
211      string pluginPath = Path.Combine(PluginCacheDir, pluginId.ToString());
212
213      if (Directory.Exists(pluginPath)) {
214        WriteDateLastUsed(pluginPath);
215        foreach (string filePath in Directory.GetFiles(pluginPath)) {
216          string fn = Path.GetFileName(filePath);
217          if (fn != lastUsedFileName)
218            yield return filePath;
219        }
220      }
221    }
222
223    /// <summary>
224    /// creates a file in path with the current date;
225    /// this can later be used to find plugins which are outdated
226    /// </summary>   
227    private void WriteDateLastUsed(string path) {
228      FileStream fs = null;
229      try {
230        fs = new FileStream(Path.Combine(path, lastUsedFileName), FileMode.Create);
231        BinaryFormatter formatter = new BinaryFormatter();
232        formatter.Serialize(fs, DateTime.Now);
233      }
234      catch (IOException) {
235        log.LogMessage(string.Format("No used date written in path {0}.", path));
236      }
237      catch (SerializationException) {
238        //rethrow...
239        throw;
240      }
241      finally {
242        if (fs != null) {
243          fs.Close();
244        }
245      }
246    }
247
248    /// <summary>
249    /// Checks the PluginTemp directory for orphaned directories and deletes them.
250    /// This should be only called if no jobs are currently running.
251    /// </summary>   
252    public void CleanPluginTemp() {
253      if (Directory.Exists(PluginTempBaseDir)) {
254        foreach (string dir in Directory.EnumerateDirectories(PluginTempBaseDir)) {
255          try {
256            log.LogMessage("Deleting orphaned directory " + dir);
257            Directory.Delete(dir, true);
258          }
259          catch (Exception ex) {
260            log.LogMessage("Error cleaning up PluginTemp directory " + dir + ": " + ex.ToString());
261          }
262        }
263      }
264    }
265
266    /// <summary>
267    /// checks the pluginCacheDirectory and deletes plugin folders which are not used anymore
268    /// </summary>   
269    private void CleanPluginCache() {
270      FileStream fs = null;
271      DateTime luDate;
272      bool changed = false;
273
274      if (Directory.Exists(PluginCacheDir)) {
275        lock (locker) {
276          foreach (string dir in Directory.EnumerateDirectories(PluginCacheDir)) {
277            try {
278              fs = new FileStream(Path.Combine(dir, lastUsedFileName), FileMode.Open);
279              BinaryFormatter formatter = new BinaryFormatter();
280              luDate = (DateTime)formatter.Deserialize(fs);
281              fs.Close();
282
283              if (luDate.AddDays(pluginLifetime) < DateTime.Now) {
284                Directory.Delete(dir, true);
285                changed = true;
286              }
287            }
288            catch (FileNotFoundException) {
289              //nerver used
290              Directory.Delete(dir, true);
291              changed = true;
292            }
293            catch (Exception ex) {
294              if (fs != null) {
295                fs.Close();
296              }
297              log.LogMessage(string.Format("CleanPluginCache threw exception: {0}", ex.ToString()));
298            }
299          }
300
301          if (changed)
302            DoUpdateRun();
303        }
304      }
305    }
306
307    public void DeletePluginsForJob(Guid id) {
308      try {
309        log.LogMessage("Deleting plugins...");
310        int tries = CoreProperties.Settings.Default.PluginDeletionRetries;
311        string path = Path.Combine(PluginTempBaseDir, id.ToString());
312        while (tries > 0) {
313          try {
314            if (Directory.Exists(path)) Directory.Delete(path, true);
315            tries = 0;
316          }
317          catch (Exception) {
318            Thread.Sleep(CoreProperties.Settings.Default.PluginDeletionTimeout);
319            tries--;
320            if (tries == 0) throw;
321          }
322        }
323      }
324      catch (Exception ex) {
325        log.LogMessage("failed while unloading " + id + " with exception " + ex);
326      }
327      CleanPluginCache();
328    }
329  }
330}
Note: See TracBrowser for help on using the repository browser.