Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ParameterBinding/HeuristicLab.Problems.ExternalEvaluation/3.3/Drivers/EvaluationProcessChannel.cs @ 9793

Last change on this file since 9793 was 4722, checked in by swagner, 14 years ago

Merged cloning refactoring branch back into trunk (#922)

File size: 6.0 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    [StorableConstructor]
61    protected EvaluationProcessChannel(bool deserializing) : base(deserializing) { }
62    protected EvaluationProcessChannel(EvaluationProcessChannel original, Cloner cloner)
63      : base(original, cloner) {
64      executable = original.executable;
65      arguments = original.arguments;
66    }
67    public override IDeepCloneable Clone(Cloner cloner) {
68      return new EvaluationProcessChannel(this, cloner);
69    }
70
71    public EvaluationProcessChannel() : this(String.Empty, String.Empty) { }
72    public EvaluationProcessChannel(string executable, string arguments)
73      : base() {
74      this.executable = executable;
75      this.arguments = arguments;
76    }
77
78    #region IExternalEvaluationChannel Members
79
80    public override void Open() {
81      if (!String.IsNullOrEmpty(executable.Trim())) {
82        base.Open();
83        process = new Process();
84        process.StartInfo = new ProcessStartInfo(executable, arguments);
85        process.StartInfo.UseShellExecute = false;
86        process.StartInfo.RedirectStandardInput = true;
87        process.StartInfo.RedirectStandardOutput = true;
88        process.EnableRaisingEvents = true; // required to be notified of exit
89        process.Start();
90        Stream processStdOut = process.StandardOutput.BaseStream;
91        Stream processStdIn = process.StandardInput.BaseStream;
92        OnProcessStarted();
93        process.Exited += new EventHandler(process_Exited);
94        streamingChannel = new EvaluationStreamChannel(processStdOut, processStdIn);
95        streamingChannel.Open();
96      } else throw new InvalidOperationException(Name + ": Cannot open the process channel because the executable is not defined.");
97    }
98
99    public override void Send(IMessage message) {
100      try {
101        streamingChannel.Send(message);
102      }
103      catch {
104        Close();
105        throw;
106      }
107    }
108
109    public override IMessage Receive(IBuilder builder) {
110      try {
111        return streamingChannel.Receive(builder);
112      }
113      catch {
114        Close();
115        throw;
116      }
117    }
118
119    public override void Close() {
120      base.Close();
121      if (process != null) {
122        if (!process.HasExited) {
123          streamingChannel.Close();
124          if (!process.HasExited) {
125            try {
126              process.CloseMainWindow();
127              process.WaitForExit(1000);
128              process.Close();
129            }
130            catch { }
131          }
132          // for some reasons the event process_Exited does not fire
133          OnProcessExited();
134        }
135        process = null;
136      }
137    }
138
139    #endregion
140
141    #region Event handlers (process)
142    private void process_Exited(object sender, EventArgs e) {
143      if (IsInitialized) {
144        if (streamingChannel.IsInitialized) streamingChannel.Close();
145        IsInitialized = false;
146        process = null;
147      }
148      OnProcessExited();
149    }
150    #endregion
151
152    #region Events
153    public event EventHandler ExecutableChanged;
154    protected void OnExecutableChanged() {
155      EventHandler handler = ExecutableChanged;
156      if (handler != null) handler(this, EventArgs.Empty);
157    }
158
159    public event EventHandler ArgumentsChanged;
160    protected void OnArgumentsChanged() {
161      EventHandler handler = ArgumentsChanged;
162      if (handler != null) handler(this, EventArgs.Empty);
163    }
164
165    public event EventHandler ProcessStarted;
166    private void OnProcessStarted() {
167      EventHandler handler = ProcessStarted;
168      if (handler != null) handler(this, EventArgs.Empty);
169    }
170
171    public event EventHandler ProcessExited;
172    private void OnProcessExited() {
173      EventHandler handler = ProcessExited;
174      if (handler != null) handler(this, EventArgs.Empty);
175    }
176    #endregion
177  }
178}
Note: See TracBrowser for help on using the repository browser.