Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive-3.4/sources/HeuristicLab.Clients.Hive.Slave/3.4/PluginCache.cs @ 5156

Last change on this file since 5156 was 5156, checked in by ascheibe, 13 years ago

#1233

  • Implemented communication interface between Slave and a Slave Client using Named Pipes and callbacks
  • Added new project for testing Slave - Client communication
  • Added some copyright info headers
File size: 8.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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.CompilerServices;
28using System.Threading;
29using HeuristicLab.Clients.Hive.Salve;
30using HeuristicLab.PluginInfrastructure;
31using HeuristicLab.PluginInfrastructure.Manager;
32using HeuristicLab.Services.Hive.Common.DataTransfer;
33
34namespace HeuristicLab.Clients.Hive.Slave {
35  public class PluginCache {
36    private static object locker = new object();
37    public const string ConfigFileName = "Sandbox.config";
38
39    private static PluginCache instance = null;
40
41    public string PluginCacheDir { get; set; }
42    public string PluginTempBaseDir { get; set; }
43
44    private List<PluginDescription> cachedPlugins = new List<PluginDescription>();
45
46    private PluginManager pm;
47
48    public static PluginCache Instance {
49      get {
50        if (instance == null)
51          instance = new PluginCache();
52        return instance;
53      }
54    }
55
56    public string ConfigFilePath {
57      get {
58        return Path.Combine(PluginCacheDir, ConfigFileName);
59      }
60    }
61
62    public PluginCache() {
63      PluginCacheDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PluginCache");
64      PluginTempBaseDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PluginTemp");
65
66      this.pm = new PluginManager(PluginCacheDir);
67      DoUpdateRun();
68    }
69
70    private void DoUpdateRun() {
71      if (!Directory.Exists(PluginCacheDir)) {
72        Directory.CreateDirectory(PluginCacheDir);
73      }
74      pm.DiscoverAndCheckPlugins();
75      cachedPlugins = new List<PluginDescription>(pm.Plugins);
76    }
77
78    [MethodImpl(MethodImplOptions.Synchronized)]
79    public void CopyPluginsForJob(List<Plugin> requests, Guid jobId) {
80      lock (locker) {
81        String targetDir = Path.Combine(PluginTempBaseDir, jobId.ToString());
82
83        if (Directory.Exists(targetDir)) {
84          Directory.Delete(targetDir, true);
85        }
86
87        DirectoryInfo di = Directory.CreateDirectory(targetDir);
88
89        foreach (Plugin requestedPlugin in requests) {
90          PluginDescription pd = cachedPlugins.Where(cp =>
91            cp.Name == requestedPlugin.Name &&
92            cp.Version.Major == requestedPlugin.Version.Major &&
93            cp.Version.Minor == requestedPlugin.Version.Minor).SingleOrDefault();
94          if (pd != null) {
95            foreach (IPluginFile ipf in pd.Files) {
96              File.Copy(ipf.Name, Path.Combine(targetDir, Path.GetFileName(ipf.Name)));
97            }
98          }
99        }
100
101        // copy config file
102        File.Copy(ConfigFilePath, Path.Combine(targetDir, ConfigFileName));
103
104        // copy files from PluginInfrastructure, which are not declared
105        string baseDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
106        CopyFile(baseDir, targetDir, "HeuristicLab.PluginInfrastructure-3.3.dll");
107        CopyFile(baseDir, targetDir, "ICSharpCode.SharpZipLib.dll");
108        CopyFile(baseDir, targetDir, "ICSharpCode.SharpZipLib License.txt");
109
110        // copy slave plugins, otherwise its not possible to register the UnhandledException handler to the appdomain
111        CopyFile(baseDir, targetDir, "HeuristicLab.Clients.Hive.Slave-3.4.dll");
112        CopyFile(baseDir, targetDir, "HeuristicLab.Clients.Hive-3.4.dll");
113        CopyFile(baseDir, targetDir, "HeuristicLab.Services.Hive.Common-3.4.dll");
114        CopyFile(baseDir, targetDir, "HeuristicLab.Hive-3.4.dll");
115
116        //TODO: remove, just needed for unit tests
117        CopyFile(baseDir, targetDir, "HeuristicLab.Clients.Hive.Slave.Tests-3.4.dll");
118      }
119    }
120
121    private void CopyFile(string baseDir, string targetDir, string fileName) {
122      if (!File.Exists(Path.Combine(targetDir, fileName))) File.Copy(Path.Combine(baseDir, fileName), Path.Combine(targetDir, fileName));
123    }
124
125    [MethodImpl(MethodImplOptions.Synchronized)]
126    internal void PreparePlugins(Job myJob, JobData jobData) {
127      lock (locker) {
128        SlaveClientCom.Instance.ClientCom.LogMessage("Fetching plugins for job");
129
130        IEnumerable<Plugin> pluginDescriptions = WcfService.Instance.GetPlugins();
131        List<Plugin> requiredPlugins = new List<Plugin>();
132        foreach (Guid pluginId in myJob.PluginsNeededIds) {
133          Plugin pl = pluginDescriptions.FirstOrDefault(p => p.Id == pluginId);
134          if (pl != null)
135            requiredPlugins.Add(pl);
136        }
137
138        List<Plugin> localPlugins = new List<Plugin>();
139        List<Plugin> missingPlugins = new List<Plugin>();
140        List<Guid> missingGuids = new List<Guid>();
141        bool found = false;
142
143        foreach (Plugin info in requiredPlugins) {
144          //we MAY run in problems here - if there is a plugin twice in requests, there may be added two different versions of the plugin
145          foreach (PluginDescription cachedPlugin in cachedPlugins) {
146            if (info.Name == cachedPlugin.Name && info.Version == cachedPlugin.Version) {
147              localPlugins.Add(new Plugin() { Id = new Guid(), Name = info.Name, Version = info.Version });
148              found = true;
149
150              break;
151            }
152          }
153          if (!found) {
154            SlaveClientCom.Instance.ClientCom.LogMessage("Plugin NOT found " + info.Name + ", " + info.Version);
155            missingPlugins.Add(info);
156            missingGuids.Add(info.Id);
157          }
158          found = false;
159        }
160
161        SlaveClientCom.Instance.ClientCom.LogMessage("First run - Update the plugins in the cache");
162        localPlugins.AddRange(missingPlugins);
163
164        IEnumerable<PluginData> updateablePlugins = WcfService.Instance.GetPluginDatas(missingGuids);
165
166        foreach (PluginData updateablePlugin in updateablePlugins) {
167          Plugin pluginDescription = pluginDescriptions.Where(desc => desc.Id == updateablePlugin.PluginId).SingleOrDefault();
168          if (pluginDescription != null) {
169
170            PluginDescription pd = cachedPlugins.Where(cachedPlugin =>
171                cachedPlugin.Name == pluginDescription.Name &&
172                cachedPlugin.Version.Major == pluginDescription.Version.Major &&
173                cachedPlugin.Version.Minor == pluginDescription.Version.Major).SingleOrDefault();
174
175            if (pd != null) {
176              foreach (IPluginFile ipf in pd.Files) {
177                SlaveClientCom.Instance.ClientCom.LogMessage(string.Format("deleting {0}", Path.GetFileName(ipf.Name)));
178                File.Delete(ipf.Name);
179              }
180            }
181            File.WriteAllBytes(Path.Combine(PluginCacheDir, Path.GetFileName(pluginDescription.Name)), updateablePlugin.Data);
182          }
183          //TODO: error handling on pluginDescription, should be found
184        }
185
186        PluginData configFile = WcfService.Instance.GetConfigurationFile();
187        File.WriteAllBytes(ConfigFilePath, configFile.Data);
188
189        DoUpdateRun();
190        CopyPluginsForJob(requiredPlugins, myJob.Id);
191      }
192    }
193
194    internal void DeletePluginsForJob(Guid id) {
195      try {
196        SlaveClientCom.Instance.ClientCom.LogMessage("unloading...");
197        int tries = 5;
198        while (tries > 0) {
199          try {
200            Directory.Delete(Path.Combine(PluginTempBaseDir, id.ToString()), true);
201            tries = 0;
202          }
203          catch {
204            Thread.Sleep(1000);
205            tries--;
206            if (tries == 0) throw;
207          }
208        }
209      }
210      catch (Exception ex) {
211        SlaveClientCom.Instance.ClientCom.LogMessage("failed while unloading " + id + " with exception " + ex);
212      }
213    }
214
215
216  }
217}
Note: See TracBrowser for help on using the repository browser.