[6212] | 1 | #region License Information
|
---|
| 2 | /* HeuristicLab
|
---|
| 3 | * Copyright (C) 2002-2011 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 |
|
---|
| 22 | using System;
|
---|
[5958] | 23 | using System.Collections.Generic;
|
---|
| 24 | using System.Linq;
|
---|
| 25 | using System.Threading;
|
---|
| 26 | using System.Threading.Tasks;
|
---|
| 27 | using HeuristicLab.Clients.Hive;
|
---|
| 28 | using HeuristicLab.Common;
|
---|
| 29 | using HeuristicLab.Core;
|
---|
| 30 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
| 31 |
|
---|
| 32 | namespace HeuristicLab.HiveEngine {
|
---|
| 33 | /// <summary>
|
---|
| 34 | /// Represents an engine that executes operations which can be executed in parallel on the hive
|
---|
| 35 | /// </summary>
|
---|
| 36 | [StorableClass]
|
---|
| 37 | [Item("Hive Engine", "Engine for parallel execution on the hive. You need enable `Parallel` for at least one operator in your operator graph to have all childoperations parallelized. Also those childoperations must not have sideeffects on a higher scope.")]
|
---|
| 38 | public class HiveEngine : Engine {
|
---|
[6200] | 39 | private static object logLocker = new object();
|
---|
[5958] | 40 | private CancellationToken cancellationToken;
|
---|
[6200] | 41 |
|
---|
[5958] | 42 | [Storable]
|
---|
| 43 | private IOperator currentOperator;
|
---|
| 44 |
|
---|
| 45 | [Storable]
|
---|
[6006] | 46 | public string ResourceNames { get; set; }
|
---|
[5958] | 47 |
|
---|
| 48 | [Storable]
|
---|
| 49 | private int priority;
|
---|
| 50 | public int Priority {
|
---|
| 51 | get { return priority; }
|
---|
| 52 | set { priority = value; }
|
---|
| 53 | }
|
---|
| 54 |
|
---|
| 55 | [Storable]
|
---|
| 56 | private TimeSpan executionTimeOnHive;
|
---|
| 57 | public TimeSpan ExecutionTimeOnHive {
|
---|
| 58 | get { return executionTimeOnHive; }
|
---|
| 59 | set {
|
---|
| 60 | if (value != executionTimeOnHive) {
|
---|
| 61 | executionTimeOnHive = value;
|
---|
| 62 | OnExecutionTimeOnHiveChanged();
|
---|
| 63 | }
|
---|
| 64 | }
|
---|
| 65 | }
|
---|
| 66 |
|
---|
[6006] | 67 | [Storable]
|
---|
| 68 | private bool useLocalPlugins;
|
---|
| 69 | public bool UseLocalPlugins {
|
---|
| 70 | get { return useLocalPlugins; }
|
---|
| 71 | set { useLocalPlugins = value; }
|
---|
| 72 | }
|
---|
| 73 |
|
---|
[6200] | 74 | // [Storable] -> HiveExperiment can't be storable, so RefreshableHiveExperiment can't be stored
|
---|
| 75 | private ItemCollection<RefreshableHiveExperiment> hiveExperiments = new ItemCollection<RefreshableHiveExperiment>();
|
---|
[6033] | 76 | public ItemCollection<RefreshableHiveExperiment> HiveExperiments {
|
---|
[6006] | 77 | get { return hiveExperiments; }
|
---|
| 78 | set { hiveExperiments = value; }
|
---|
| 79 | }
|
---|
| 80 |
|
---|
[6000] | 81 | private List<Plugin> onlinePlugins;
|
---|
| 82 | public List<Plugin> OnlinePlugins {
|
---|
[5958] | 83 | get { return onlinePlugins; }
|
---|
| 84 | set { onlinePlugins = value; }
|
---|
| 85 | }
|
---|
[6000] | 86 |
|
---|
[5958] | 87 | private List<Plugin> alreadyUploadedPlugins;
|
---|
| 88 | public List<Plugin> AlreadyUploadedPlugins {
|
---|
| 89 | get { return alreadyUploadedPlugins; }
|
---|
| 90 | set { alreadyUploadedPlugins = value; }
|
---|
| 91 | }
|
---|
| 92 |
|
---|
| 93 | #region constructors and cloning
|
---|
| 94 | public HiveEngine() {
|
---|
[6006] | 95 | ResourceNames = "HEAL";
|
---|
| 96 | Priority = 0;
|
---|
[5958] | 97 | }
|
---|
| 98 |
|
---|
| 99 | [StorableConstructor]
|
---|
| 100 | protected HiveEngine(bool deserializing) : base(deserializing) { }
|
---|
| 101 | protected HiveEngine(HiveEngine original, Cloner cloner)
|
---|
| 102 | : base(original, cloner) {
|
---|
[6006] | 103 | this.ResourceNames = original.ResourceNames;
|
---|
[5958] | 104 | this.currentOperator = cloner.Clone(original.currentOperator);
|
---|
| 105 | this.priority = original.priority;
|
---|
| 106 | this.executionTimeOnHive = original.executionTimeOnHive;
|
---|
[6006] | 107 | this.useLocalPlugins = original.useLocalPlugins;
|
---|
[6200] | 108 | this.hiveExperiments = cloner.Clone(original.hiveExperiments);
|
---|
[5958] | 109 | }
|
---|
| 110 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
| 111 | return new HiveEngine(this, cloner);
|
---|
| 112 | }
|
---|
| 113 | #endregion
|
---|
| 114 |
|
---|
| 115 | #region Events
|
---|
| 116 | protected override void OnPrepared() {
|
---|
| 117 | base.OnPrepared();
|
---|
| 118 | this.ExecutionTimeOnHive = TimeSpan.Zero;
|
---|
| 119 | }
|
---|
| 120 |
|
---|
| 121 | public event EventHandler ExecutionTimeOnHiveChanged;
|
---|
| 122 | protected virtual void OnExecutionTimeOnHiveChanged() {
|
---|
| 123 | var handler = ExecutionTimeOnHiveChanged;
|
---|
| 124 | if (handler != null) handler(this, EventArgs.Empty);
|
---|
| 125 | }
|
---|
| 126 | #endregion
|
---|
| 127 |
|
---|
| 128 | protected override void Run(CancellationToken cancellationToken) {
|
---|
| 129 | this.cancellationToken = cancellationToken;
|
---|
| 130 | Run(ExecutionStack);
|
---|
| 131 | }
|
---|
| 132 |
|
---|
| 133 | private void Run(object state) {
|
---|
| 134 | Stack<IOperation> executionStack = (Stack<IOperation>)state;
|
---|
| 135 | IOperation next;
|
---|
| 136 | OperationCollection coll;
|
---|
| 137 | IAtomicOperation operation;
|
---|
| 138 | TaskScheduler.UnobservedTaskException += new EventHandler<UnobservedTaskExceptionEventArgs>(TaskScheduler_UnobservedTaskException);
|
---|
| 139 |
|
---|
[6000] | 140 | this.OnlinePlugins = ServiceLocator.Instance.CallHiveService(s => s.GetPlugins()).Where(x => x.IsLocal == false).ToList();
|
---|
[5958] | 141 | this.AlreadyUploadedPlugins = new List<Plugin>();
|
---|
| 142 |
|
---|
| 143 | while (ExecutionStack.Count > 0) {
|
---|
| 144 | cancellationToken.ThrowIfCancellationRequested();
|
---|
| 145 |
|
---|
| 146 | next = ExecutionStack.Pop();
|
---|
| 147 | if (next is OperationCollection) {
|
---|
| 148 | coll = (OperationCollection)next;
|
---|
| 149 | if (coll.Parallel) {
|
---|
| 150 | // clone the parent scope here and reuse it for each operation. otherwise for each job the whole scope-tree first needs to be copied and then cleaned, which causes a lot of work for the Garbage Collector
|
---|
| 151 | IScope parentScopeClone = (IScope)((IAtomicOperation)coll.First()).Scope.Parent.Clone();
|
---|
| 152 | parentScopeClone.SubScopes.Clear();
|
---|
| 153 | parentScopeClone.ClearParentScopes();
|
---|
| 154 |
|
---|
| 155 | EngineJob[] jobs = new EngineJob[coll.Count];
|
---|
| 156 | for (int i = 0; i < coll.Count; i++) {
|
---|
| 157 | jobs[i] = new EngineJob(coll[i], new SequentialEngine.SequentialEngine());
|
---|
| 158 | }
|
---|
| 159 |
|
---|
| 160 | IScope[] scopes = ExecuteOnHive(jobs, parentScopeClone, cancellationToken);
|
---|
[6178] | 161 | //IScope[] scopes = ExecuteLocally(jobs, parentScopeClone, cancellationToken);
|
---|
| 162 |
|
---|
[5958] | 163 | for (int i = 0; i < coll.Count; i++) {
|
---|
| 164 | if (coll[i] is IAtomicOperation) {
|
---|
| 165 | ExchangeScope(scopes[i], ((IAtomicOperation)coll[i]).Scope);
|
---|
| 166 | } else if (coll[i] is OperationCollection) {
|
---|
| 167 | // todo ??
|
---|
| 168 | }
|
---|
| 169 | }
|
---|
| 170 | } else {
|
---|
| 171 | for (int i = coll.Count - 1; i >= 0; i--)
|
---|
| 172 | if (coll[i] != null) executionStack.Push(coll[i]);
|
---|
| 173 | }
|
---|
| 174 | } else if (next is IAtomicOperation) {
|
---|
| 175 | operation = (IAtomicOperation)next;
|
---|
| 176 | try {
|
---|
| 177 | next = operation.Operator.Execute((IExecutionContext)operation, cancellationToken);
|
---|
| 178 | }
|
---|
| 179 | catch (Exception ex) {
|
---|
| 180 | ExecutionStack.Push(operation);
|
---|
| 181 | if (ex is OperationCanceledException) throw ex;
|
---|
| 182 | else throw new OperatorExecutionException(operation.Operator, ex);
|
---|
| 183 | }
|
---|
| 184 | if (next != null) ExecutionStack.Push(next);
|
---|
| 185 |
|
---|
| 186 | if (operation.Operator.Breakpoint) {
|
---|
| 187 | LogMessage(string.Format("Breakpoint: {0}", operation.Operator.Name != string.Empty ? operation.Operator.Name : operation.Operator.ItemName));
|
---|
| 188 | Pause();
|
---|
| 189 | }
|
---|
| 190 | }
|
---|
| 191 | }
|
---|
| 192 | }
|
---|
| 193 |
|
---|
| 194 | private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e) {
|
---|
| 195 | e.SetObserved(); // avoid crash of process
|
---|
| 196 | }
|
---|
| 197 |
|
---|
| 198 | private IRandom FindRandomParameter(IExecutionContext ec) {
|
---|
| 199 | try {
|
---|
| 200 | if (ec == null)
|
---|
| 201 | return null;
|
---|
| 202 |
|
---|
| 203 | foreach (var p in ec.Parameters) {
|
---|
| 204 | if (p.Name == "Random" && p is IValueParameter)
|
---|
| 205 | return ((IValueParameter)p).Value as IRandom;
|
---|
| 206 | }
|
---|
| 207 | return FindRandomParameter(ec.Parent);
|
---|
| 208 | }
|
---|
| 209 | catch { return null; }
|
---|
| 210 | }
|
---|
| 211 |
|
---|
| 212 | private static void ReIntegrateScope(IAtomicOperation source, IAtomicOperation target) {
|
---|
| 213 | ExchangeScope(source.Scope, target.Scope);
|
---|
| 214 | }
|
---|
| 215 |
|
---|
| 216 | private static void ExchangeScope(IScope source, IScope target) {
|
---|
| 217 | target.Variables.Clear();
|
---|
| 218 | target.Variables.AddRange(source.Variables);
|
---|
| 219 | target.SubScopes.Clear();
|
---|
| 220 | target.SubScopes.AddRange(source.SubScopes);
|
---|
| 221 | // TODO: validate if parent scopes match - otherwise source is invalid
|
---|
| 222 | }
|
---|
| 223 |
|
---|
| 224 | /// <summary>
|
---|
| 225 | /// This method blocks until all jobs are finished
|
---|
| 226 | /// TODO: Cancelation needs to be refined; all tasks currently stay in Semaphore.WaitOne after cancelation
|
---|
| 227 | /// </summary>
|
---|
| 228 | /// <param name="jobs"></param>
|
---|
| 229 | private IScope[] ExecuteOnHive(EngineJob[] jobs, IScope parentScopeClone, CancellationToken cancellationToken) {
|
---|
| 230 | LogMessage(string.Format("Executing {0} operations on the hive.", jobs.Length));
|
---|
| 231 | IScope[] scopes = new Scope[jobs.Length];
|
---|
| 232 | object locker = new object();
|
---|
| 233 | IDictionary<Guid, int> jobIndices = new Dictionary<Guid, int>();
|
---|
[6111] | 234 | var hiveExperiment = new HiveExperiment();
|
---|
[5958] | 235 |
|
---|
| 236 | try {
|
---|
| 237 | List<Guid> remainingJobIds = new List<Guid>();
|
---|
| 238 |
|
---|
[6006] | 239 | // create hive experiment
|
---|
| 240 | hiveExperiment.Name = "HiveEngine Run " + hiveExperiments.Count;
|
---|
[6178] | 241 | hiveExperiment.DateCreated = DateTime.Now;
|
---|
[6006] | 242 | hiveExperiment.UseLocalPlugins = this.UseLocalPlugins;
|
---|
| 243 | hiveExperiment.ResourceNames = this.ResourceNames;
|
---|
[6111] | 244 | var refreshableHiveExperiment = new RefreshableHiveExperiment(hiveExperiment);
|
---|
[6178] | 245 | refreshableHiveExperiment.IsControllable = false;
|
---|
[6111] | 246 | hiveExperiments.Add(refreshableHiveExperiment);
|
---|
[6006] | 247 |
|
---|
[5958] | 248 | // create upload-tasks
|
---|
| 249 | var uploadTasks = new List<Task<Job>>();
|
---|
| 250 | for (int i = 0; i < jobs.Length; i++) {
|
---|
[6178] | 251 | hiveExperiment.HiveJobs.Add(new EngineHiveJob(jobs[i], parentScopeClone));
|
---|
[5958] | 252 |
|
---|
| 253 | // shuffle random variable to avoid the same random sequence in each operation; todo: does not yet work (it cannot find the random variable)
|
---|
[6178] | 254 | IRandom random = FindRandomParameter(jobs[i].InitialOperation as IExecutionContext);
|
---|
[5958] | 255 | if (random != null)
|
---|
| 256 | random.Reset(random.Next());
|
---|
| 257 | }
|
---|
[6200] | 258 | ExperimentManagerClient.StartExperiment((e) => {
|
---|
| 259 | LogException(e);
|
---|
| 260 | }, refreshableHiveExperiment);
|
---|
| 261 |
|
---|
[6178] | 262 | // do polling until experiment is finished and all jobs are downloaded
|
---|
[6111] | 263 | while (!refreshableHiveExperiment.AllJobsFinished()) {
|
---|
[6178] | 264 | Thread.Sleep(500);
|
---|
| 265 | this.ExecutionTimeOnHive = TimeSpan.FromMilliseconds(hiveExperiments.Sum(x => x.HiveExperiment.ExecutionTime.TotalMilliseconds));
|
---|
[6198] | 266 | cancellationToken.ThrowIfCancellationRequested();
|
---|
[6111] | 267 | }
|
---|
[6178] | 268 | LogMessage(string.Format("{0} finished (TotalExecutionTime: {1}).", refreshableHiveExperiment.ToString(), refreshableHiveExperiment.HiveExperiment.ExecutionTime));
|
---|
[6111] | 269 |
|
---|
[6178] | 270 | // get scopes
|
---|
| 271 | int j = 0;
|
---|
| 272 | foreach (var hiveJob in hiveExperiment.HiveJobs) {
|
---|
| 273 | var scope = ((IAtomicOperation) ((EngineJob)hiveJob.ItemJob).InitialOperation).Scope;
|
---|
| 274 | scopes[j++] = scope;
|
---|
[5958] | 275 | }
|
---|
[6178] | 276 | refreshableHiveExperiment.RefreshAutomatically = false;
|
---|
[6006] | 277 | DeleteHiveExperiment(hiveExperiment.Id);
|
---|
[6200] | 278 | ClearData(refreshableHiveExperiment);
|
---|
[5958] | 279 | return scopes;
|
---|
| 280 | }
|
---|
| 281 | catch (OperationCanceledException e) {
|
---|
| 282 | lock (locker) {
|
---|
[6006] | 283 | if (jobIndices != null) DeleteHiveExperiment(hiveExperiment.Id);
|
---|
[5958] | 284 | }
|
---|
| 285 | throw e;
|
---|
| 286 | }
|
---|
| 287 | catch (Exception e) {
|
---|
| 288 | lock (locker) {
|
---|
[6006] | 289 | if (jobIndices != null) DeleteHiveExperiment(hiveExperiment.Id);
|
---|
[5958] | 290 | }
|
---|
| 291 | LogException(e);
|
---|
| 292 | throw e;
|
---|
| 293 | }
|
---|
| 294 | }
|
---|
| 295 |
|
---|
[6200] | 296 | private void ClearData(RefreshableHiveExperiment refreshableHiveExperiment) {
|
---|
| 297 | var jobs = refreshableHiveExperiment.HiveExperiment.GetAllHiveJobs();
|
---|
| 298 | foreach (var job in jobs) {
|
---|
| 299 | job.ClearData();
|
---|
| 300 | }
|
---|
| 301 | }
|
---|
| 302 |
|
---|
[6006] | 303 | private void DeleteHiveExperiment(Guid hiveExperimentId) {
|
---|
[6200] | 304 | ExperimentManagerClient.TryAndRepeat(() => {
|
---|
[6006] | 305 | ServiceLocator.Instance.CallHiveService(s => s.DeleteHiveExperiment(hiveExperimentId));
|
---|
| 306 | }, 5, string.Format("Could not delete jobs"));
|
---|
[5958] | 307 | }
|
---|
[6200] | 308 |
|
---|
[5958] | 309 | private List<Guid> GetResourceIds() {
|
---|
| 310 | return ServiceLocator.Instance.CallHiveService(service => {
|
---|
[6006] | 311 | var resourceNames = ResourceNames.Split(';');
|
---|
[5958] | 312 | var resourceIds = new List<Guid>();
|
---|
| 313 | foreach (var resourceName in resourceNames) {
|
---|
| 314 | Guid resourceId = service.GetResourceId(resourceName);
|
---|
| 315 | if (resourceId == Guid.Empty) {
|
---|
| 316 | throw new ResourceNotFoundException(string.Format("Could not find the resource '{0}'", resourceName));
|
---|
| 317 | }
|
---|
| 318 | resourceIds.Add(resourceId);
|
---|
| 319 | }
|
---|
| 320 | return resourceIds;
|
---|
| 321 | });
|
---|
| 322 | }
|
---|
| 323 |
|
---|
| 324 | /// <summary>
|
---|
| 325 | /// Threadsafe message logging
|
---|
| 326 | /// </summary>
|
---|
| 327 | private void LogMessage(string message) {
|
---|
[6200] | 328 | lock (logLocker) {
|
---|
[5958] | 329 | Log.LogMessage(message);
|
---|
| 330 | }
|
---|
| 331 | }
|
---|
| 332 |
|
---|
| 333 | /// <summary>
|
---|
| 334 | /// Threadsafe exception logging
|
---|
| 335 | /// </summary>
|
---|
| 336 | private void LogException(Exception exception) {
|
---|
[6200] | 337 | lock (logLocker) {
|
---|
[5958] | 338 | Log.LogException(exception);
|
---|
| 339 | }
|
---|
| 340 | }
|
---|
| 341 |
|
---|
[6200] | 342 | // testfunction:
|
---|
| 343 | //private IScope[] ExecuteLocally(EngineJob[] jobs, IScope parentScopeClone, CancellationToken cancellationToken) {
|
---|
| 344 | // IScope[] scopes = new Scope[jobs.Length];
|
---|
| 345 | // for (int i = 0; i < jobs.Length; i++) {
|
---|
| 346 | // var serialized = PersistenceUtil.Serialize(jobs[i]);
|
---|
| 347 | // var deserialized = PersistenceUtil.Deserialize<IJob>(serialized);
|
---|
| 348 | // deserialized.Start();
|
---|
| 349 | // while (deserialized.ExecutionState != ExecutionState.Stopped) {
|
---|
| 350 | // Thread.Sleep(100);
|
---|
| 351 | // }
|
---|
| 352 | // var serialized2 = PersistenceUtil.Serialize(deserialized);
|
---|
| 353 | // var deserialized2 = PersistenceUtil.Deserialize<EngineJob>(serialized2);
|
---|
| 354 | // var newScope = ((IAtomicOperation)deserialized2.InitialOperation).Scope;
|
---|
| 355 | // scopes[i] = newScope;
|
---|
| 356 | // }
|
---|
| 357 | // return scopes;
|
---|
| 358 | //}
|
---|
[5958] | 359 | }
|
---|
| 360 | }
|
---|