Free cookie consent management tool by TermsFeed Policy Generator

source: branches/XmlTextWriterBranch/HeuristicLab.DistributedEngine/DistributedEngine.cs @ 119

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

created a branch that uses XmlTextWriter instead of XMLDocument to save documents. Investigating ticket #103.

File size: 8.2 KB
RevLine 
[2]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;
[33]36    private Dictionary<Guid, AtomicOperation> engineOperations = new Dictionary<Guid, AtomicOperation>();
37    private List<Guid> runningEngines = new List<Guid>();
[2]38    private string serverAddress;
[35]39    private bool cancelRequested;
[36]40    private CompositeOperation waitingOperations;
[2]41    public string ServerAddress {
42      get { return serverAddress; }
43      set {
44        if(value != serverAddress) {
45          serverAddress = value;
46        }
47      }
48    }
[33]49    public override bool Terminated {
50      get {
[36]51        return myExecutionStack.Count == 0 && runningEngines.Count == 0 && waitingOperations==null;
[33]52      }
53    }
[2]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;
[24]72      binding.Security.Mode = SecurityMode.None;
[2]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() {
[35]84      lock(runningEngines) {
85        cancelRequested = true;
86        foreach(Guid engineGuid in runningEngines) {
87          server.AbortEngine(engineGuid);
88        }
[2]89      }
90    }
[35]91    public override void Reset() {
92      base.Reset();
93      engineOperations.Clear();
94      runningEngines.Clear();
95      cancelRequested = false;
96    }
[2]97
98    protected override void ProcessNextOperation() {
[35]99      lock(runningEngines) {
100        if(runningEngines.Count == 0 && cancelRequested) {
101          base.Abort();
102          cancelRequested = false;
[36]103          if(waitingOperations != null && waitingOperations.Operations.Count != 0) {
104            myExecutionStack.Push(waitingOperations);
105            waitingOperations = null;
106          }
[35]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]);
[36]124
125            if(cancelRequested & resultEngine.ExecutionStack.Count != 0) {
126              if(waitingOperations == null) {
127                waitingOperations = new CompositeOperation();
128                waitingOperations.ExecuteInParallel = false;
[35]129              }
[36]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);
[35]139            }
140            runningEngines.Remove(engineGuid);
141            engineOperations.Remove(engineGuid);
[33]142          }
[35]143          return;
[33]144        }
[35]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); });
[2]156          }
[35]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          }
[2]178        }
179      }
180    }
181
182    #region Persistence Methods
[119]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 Persist(string name, XmlWriter writer, IDictionary<Guid, IStorable> persistedObjects) {
191      base.Persist(name, writer, persistedObjects);
192      writer.WriteAttributeString("ServerAddress", ServerAddress);
[2]193    }
194    public override void Populate(XmlNode node, IDictionary<Guid, IStorable> restoredObjects) {
195      base.Populate(node, restoredObjects);
196      ServerAddress = node.Attributes["ServerAddress"].Value;
197    }
198    #endregion
199  }
200}
Note: See TracBrowser for help on using the repository browser.