Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.ExternalEvaluation/3.3/Drivers/EvaluationProcessChannel.cs @ 3895

Last change on this file since 3895 was 3895, checked in by abeham, 13 years ago

#866

  • Improved exception handling and added default client
File size: 5.8 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.Diagnostics;
24using System.IO;
25using Google.ProtocolBuffers;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
29
30namespace HeuristicLab.Problems.ExternalEvaluation {
31  [Item("EvaluationProcessChannel", "A channel that launches an external application in a new process and communicates with that process via stdin and stdout.")]
32  [StorableClass]
33  public class EvaluationProcessChannel : EvaluationChannel {
34
35    private Process process;
36    [Storable]
37    private string executable;
38    public string Executable {
39      get { return executable; }
40      set {
41        if (IsInitialized) throw new InvalidOperationException(Name + ": Cannot change the executable path as the process has already been started.");
42        string oldExecutable = executable;
43        executable = value;
44        if (!oldExecutable.Equals(executable)) OnExecutableChanged();
45      }
46    }
47    [Storable]
48    private string arguments;
49    public string Arguments {
50      get { return arguments; }
51      set {
52        if (IsInitialized) throw new InvalidOperationException(Name + ": Cannot change the arguments as the process has already been started.");
53        string oldArguments = arguments;
54        arguments = value;
55        if (!oldArguments.Equals(arguments)) OnArgumentsChanged();
56      }
57    }
58    private EvaluationStreamChannel streamingChannel;
59
60    public EvaluationProcessChannel() : this(String.Empty, String.Empty) { }
61    public EvaluationProcessChannel(string executable, string arguments)
62      : base() {
63      this.executable = executable;
64      this.arguments = arguments;
65    }
66
67    public override IDeepCloneable Clone(Cloner cloner) {
68      EvaluationProcessChannel clone = (EvaluationProcessChannel)base.Clone(cloner);
69      clone.executable = executable;
70      clone.arguments = arguments;
71      return clone;
72    }
73
74    #region IExternalEvaluationChannel Members
75
76    public override void Open() {
77      if (!String.IsNullOrEmpty(executable.Trim())) {
78        base.Open();
79        process = new Process();
80        process.StartInfo = new ProcessStartInfo(executable, arguments);
81        process.StartInfo.UseShellExecute = false;
82        process.StartInfo.RedirectStandardInput = true;
83        process.StartInfo.RedirectStandardOutput = true;
84        process.EnableRaisingEvents = true; // required to be notified of exit
85        process.Start();
86        Stream processStdOut = process.StandardOutput.BaseStream;
87        Stream processStdIn = process.StandardInput.BaseStream;
88        OnProcessStarted();
89        process.Exited += new EventHandler(process_Exited);
90        streamingChannel = new EvaluationStreamChannel(processStdOut, processStdIn);
91        streamingChannel.Open();
92      } else throw new InvalidOperationException(Name + ": Cannot open the process channel because the executable is not defined.");
93    }
94
95    public override void Send(IMessage message) {
96      try {
97        streamingChannel.Send(message);
98      } catch {
99        Close();
100        throw;
101      }
102    }
103
104    public override IMessage Receive(IBuilder builder) {
105      try {
106        return streamingChannel.Receive(builder);
107      } catch {
108        Close();
109        throw;
110      }
111    }
112
113    public override void Close() {
114      base.Close();
115      if (process != null) {
116        if (!process.HasExited) {
117          streamingChannel.Close();
118          if (!process.HasExited) {
119            try {
120              process.CloseMainWindow();
121              process.WaitForExit(1000);
122              process.Close();
123            } catch { }
124          }
125          // for some reasons the event process_Exited does not fire
126          OnProcessExited();
127        }
128        process = null;
129      }
130    }
131
132    #endregion
133
134    #region Event handlers (process)
135    private void process_Exited(object sender, EventArgs e) {
136      if (IsInitialized) {
137        if (streamingChannel.IsInitialized) streamingChannel.Close();
138        IsInitialized = false;
139        process = null;
140      }
141      OnProcessExited();
142    }
143    #endregion
144
145    #region Events
146    public event EventHandler ExecutableChanged;
147    protected void OnExecutableChanged() {
148      EventHandler handler = ExecutableChanged;
149      if (handler != null) handler(this, EventArgs.Empty);
150    }
151
152    public event EventHandler ArgumentsChanged;
153    protected void OnArgumentsChanged() {
154      EventHandler handler = ArgumentsChanged;
155      if (handler != null) handler(this, EventArgs.Empty);
156    }
157
158    public event EventHandler ProcessStarted;
159    private void OnProcessStarted() {
160      EventHandler handler = ProcessStarted;
161      if (handler != null) handler(this, EventArgs.Empty);
162    }
163
164    public event EventHandler ProcessExited;
165    private void OnProcessExited() {
166      EventHandler handler = ProcessExited;
167      if (handler != null) handler(this, EventArgs.Empty);
168    }
169    #endregion
170  }
171}
Note: See TracBrowser for help on using the repository browser.