Free cookie consent management tool by TermsFeed Policy Generator

source: branches/FunctionsAndStructIdRefactoring/HeuristicLab.DistributedEngine/DistributedEngine.cs @ 153

Last change on this file since 153 was 36, checked in by gkronber, 17 years ago

shaky version of stop functionality (ticket #2). Open problem: continue distributed execution after engine stop. Right now after stopping the engine the waiting operations are executed locally.

File size: 8.0 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.Text;
25using System.Xml;
26using System.Threading;
27using HeuristicLab.Core;
28using HeuristicLab.Grid;
29using System.ServiceModel;
30using System.IO;
31using System.IO.Compression;
32
33namespace HeuristicLab.DistributedEngine {
34  public class DistributedEngine : EngineBase, IEditable {
35    private IGridServer server;
36    private Dictionary<Guid, AtomicOperation> engineOperations = new Dictionary<Guid, AtomicOperation>();
37    private List<Guid> runningEngines = new List<Guid>();
38    private string serverAddress;
39    private bool cancelRequested;
40    private CompositeOperation waitingOperations;
41    public string ServerAddress {
42      get { return serverAddress; }
43      set {
44        if(value != serverAddress) {
45          serverAddress = value;
46        }
47      }
48    }
49    public override bool Terminated {
50      get {
51        return myExecutionStack.Count == 0 && runningEngines.Count == 0 && waitingOperations==null;
52      }
53    }
54    public override object Clone(IDictionary<Guid, object> clonedObjects) {
55      DistributedEngine clone = (DistributedEngine)base.Clone(clonedObjects);
56      clone.ServerAddress = serverAddress;
57      return clone;
58    }
59
60    public override IView CreateView() {
61      return new DistributedEngineEditor(this);
62    }
63    public virtual IEditor CreateEditor() {
64      return new DistributedEngineEditor(this);
65    }
66
67    public override void Execute() {
68      NetTcpBinding binding = new NetTcpBinding();
69      binding.MaxReceivedMessageSize = 100000000; // 100Mbytes
70      binding.ReaderQuotas.MaxStringContentLength = 100000000; // also 100M chars
71      binding.ReaderQuotas.MaxArrayLength = 100000000; // also 100M elements;
72      binding.Security.Mode = SecurityMode.None;
73      ChannelFactory<IGridServer> factory = new ChannelFactory<IGridServer>(binding);
74      server = factory.CreateChannel(new EndpointAddress(serverAddress));
75
76      base.Execute();
77    }
78
79    public override void ExecuteSteps(int steps) {
80      throw new InvalidOperationException("DistributedEngine doesn't support stepwise execution");
81    }
82
83    public override void Abort() {
84      lock(runningEngines) {
85        cancelRequested = true;
86        foreach(Guid engineGuid in runningEngines) {
87          server.AbortEngine(engineGuid);
88        }
89      }
90    }
91    public override void Reset() {
92      base.Reset();
93      engineOperations.Clear();
94      runningEngines.Clear();
95      cancelRequested = false;
96    }
97
98    protected override void ProcessNextOperation() {
99      lock(runningEngines) {
100        if(runningEngines.Count == 0 && cancelRequested) {
101          base.Abort();
102          cancelRequested = false;
103          if(waitingOperations != null && waitingOperations.Operations.Count != 0) {
104            myExecutionStack.Push(waitingOperations);
105            waitingOperations = null;
106          }
107          return;
108        }
109        if(runningEngines.Count != 0) {
110          Guid engineGuid = runningEngines[0];
111          byte[] resultXml = server.TryEndExecuteEngine(engineGuid, 100);
112          if(resultXml != null) {
113            GZipStream stream = new GZipStream(new MemoryStream(resultXml), CompressionMode.Decompress);
114            ProcessingEngine resultEngine = (ProcessingEngine)PersistenceManager.Load(stream);
115            IScope oldScope = engineOperations[engineGuid].Scope;
116            oldScope.Clear();
117            foreach(IVariable variable in resultEngine.InitialOperation.Scope.Variables) {
118              oldScope.AddVariable(variable);
119            }
120            foreach(IScope subScope in resultEngine.InitialOperation.Scope.SubScopes) {
121              oldScope.AddSubScope(subScope);
122            }
123            OnOperationExecuted(engineOperations[engineGuid]);
124
125            if(cancelRequested & resultEngine.ExecutionStack.Count != 0) {
126              if(waitingOperations == null) {
127                waitingOperations = new CompositeOperation();
128                waitingOperations.ExecuteInParallel = false;
129              }
130              CompositeOperation task = new CompositeOperation();
131              while(resultEngine.ExecutionStack.Count > 0) {
132                AtomicOperation oldOperation = (AtomicOperation)resultEngine.ExecutionStack.Pop();
133                if(oldOperation.Scope == resultEngine.InitialOperation.Scope) {
134                  oldOperation = new AtomicOperation(oldOperation.Operator, oldScope);
135                }
136                task.AddOperation(oldOperation);
137              }
138              waitingOperations.AddOperation(task);
139            }
140            runningEngines.Remove(engineGuid);
141            engineOperations.Remove(engineGuid);
142          }
143          return;
144        }
145        IOperation operation = myExecutionStack.Pop();
146        if(operation is AtomicOperation) {
147          AtomicOperation atomicOperation = (AtomicOperation)operation;
148          IOperation next = null;
149          try {
150            next = atomicOperation.Operator.Execute(atomicOperation.Scope);
151          } catch(Exception ex) {
152            // push operation on stack again
153            myExecutionStack.Push(atomicOperation);
154            Abort();
155            ThreadPool.QueueUserWorkItem(delegate(object state) { OnExceptionOccurred(ex); });
156          }
157          if(next != null)
158            myExecutionStack.Push(next);
159          OnOperationExecuted(atomicOperation);
160          if(atomicOperation.Operator.Breakpoint) Abort();
161        } else if(operation is CompositeOperation) {
162          CompositeOperation compositeOperation = (CompositeOperation)operation;
163          if(compositeOperation.ExecuteInParallel) {
164            foreach(AtomicOperation parOperation in compositeOperation.Operations) {
165              ProcessingEngine engine = new ProcessingEngine(OperatorGraph, GlobalScope, parOperation); // OperatorGraph not needed?
166              MemoryStream memStream = new MemoryStream();
167              GZipStream stream = new GZipStream(memStream, CompressionMode.Compress, true);
168              PersistenceManager.Save(engine, stream);
169              stream.Close();
170              Guid currentEngineGuid = server.BeginExecuteEngine(memStream.ToArray());
171              runningEngines.Add(currentEngineGuid);
172              engineOperations[currentEngineGuid] = parOperation;
173            }
174          } else {
175            for(int i = compositeOperation.Operations.Count - 1; i >= 0; i--)
176              myExecutionStack.Push(compositeOperation.Operations[i]);
177          }
178        }
179      }
180    }
181
182    #region Persistence Methods
183    public override XmlNode GetXmlNode(string name, XmlDocument document, IDictionary<Guid, IStorable> persistedObjects) {
184      XmlNode node = base.GetXmlNode(name, document, persistedObjects);
185      XmlAttribute addressAttribute = document.CreateAttribute("ServerAddress");
186      addressAttribute.Value = ServerAddress;
187      node.Attributes.Append(addressAttribute);
188      return node;
189    }
190    public override void Populate(XmlNode node, IDictionary<Guid, IStorable> restoredObjects) {
191      base.Populate(node, restoredObjects);
192      ServerAddress = node.Attributes["ServerAddress"].Value;
193    }
194    #endregion
195  }
196}
Note: See TracBrowser for help on using the repository browser.