Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Hive.Client.Communication/3.2/WcfService.cs @ 1835

Last change on this file since 1835 was 1812, checked in by kgrading, 16 years ago

changed job restart behaviour - the job will now be restarted when the serialization is done, not before (#571)

File size: 10.5 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.Linq;
25using System.Text;
26using System.ServiceModel;
27using HeuristicLab.Hive.Contracts.Interfaces;
28using HeuristicLab.Hive.Contracts;
29using HeuristicLab.Hive.Contracts.BusinessObjects;
30using HeuristicLab.Hive.Client.Common;
31using HeuristicLab.Hive.Client.Communication.ServerService;
32using HeuristicLab.PluginInfrastructure;
33
34namespace HeuristicLab.Hive.Client.Communication {
35  /// <summary>
36  /// WcfService class is implemented as a Singleton and works as a communication Layer with the Server
37  /// </summary>
38  public class WcfService {
39    private static WcfService instance;
40    /// <summary>
41    /// Getter for the Instance of the WcfService
42    /// </summary>
43    /// <returns>the Instance of the WcfService class</returns>
44    public static WcfService Instance {
45      get {
46        if (instance == null) {
47          instance = new WcfService();
48        }
49        return instance;
50      }
51    }
52
53    public DateTime ConnectedSince { get; private set; }   
54    public NetworkEnum.WcfConnState ConnState { get; private set; }
55    public string ServerIP { get; private set; }
56    public int ServerPort { get; private set; }
57
58    public event EventHandler ConnectionRestored;   
59    public event EventHandler ServerChanged;
60    public event EventHandler Connected;   
61
62    public ClientCommunicatorClient proxy = null;
63
64    /// <summary>
65    /// Constructor
66    /// </summary>
67    private WcfService() {
68      ConnState = NetworkEnum.WcfConnState.Disconnected;
69    }
70
71    /// <summary>
72    /// Connects with the Server, registers the events and fires the Connected (and quiet possibly the ConnectionRestored) Event.
73    /// </summary>
74    public void Connect() {
75      try {
76        proxy = new ClientCommunicatorClient(
77          WcfSettings.GetBinding(),
78          new EndpointAddress("net.tcp://" + ServerIP + ":" + ServerPort + "/HiveServer/ClientCommunicator")
79        );
80
81        proxy.LoginCompleted += new EventHandler<LoginCompletedEventArgs>(proxy_LoginCompleted);
82        proxy.SendJobCompleted += new EventHandler<SendJobCompletedEventArgs>(proxy_SendJobCompleted);
83        proxy.StoreFinishedJobResultCompleted += new EventHandler<StoreFinishedJobResultCompletedEventArgs>(proxy_StoreFinishedJobResultCompleted);
84        proxy.ProcessSnapshotCompleted += new EventHandler<ProcessSnapshotCompletedEventArgs>(proxy_ProcessSnapshotCompleted);
85        proxy.ProcessHeartBeatCompleted += new EventHandler<ProcessHeartBeatCompletedEventArgs>(proxy_ProcessHeartBeatCompleted);
86        proxy.Open();
87
88        ConnState = NetworkEnum.WcfConnState.Connected;
89        ConnectedSince = DateTime.Now;
90       
91        if (Connected != null)
92          Connected(this, new EventArgs());                               
93        //Todo: This won't be hit. EVER       
94        if (ConnState == NetworkEnum.WcfConnState.Failed)
95          ConnectionRestored(this, new EventArgs());       
96      }
97      catch (Exception ex) {     
98        HandleNetworkError(ex);
99      }
100    }
101
102
103
104    /// <summary>
105    /// Changes the Connectionsettings (serverIP & serverPort) and reconnects
106    /// </summary>
107    /// <param name="serverIP">current Server IP</param>
108    /// <param name="serverPort">current Server Port</param>
109    public void Connect(String serverIP, int serverPort) {
110      String oldIp = this.ServerIP;
111      int oldPort = this.ServerPort;
112      this.ServerIP = serverIP;
113      this.ServerPort = serverPort;     
114      Connect();
115      if (oldIp != serverIP || oldPort != ServerPort)
116        if(ServerChanged != null)
117          ServerChanged(this, new EventArgs());
118    }
119   
120    /// <summary>
121    /// Disconnects the Client from the Server
122    /// </summary>
123    public void Disconnect() {
124      ConnState = NetworkEnum.WcfConnState.Disconnected;
125    }
126
127    /// <summary>
128    /// Network communication Error Handler - Every network error gets logged and the connection switches to faulted state
129    /// </summary>
130    /// <param name="e">The Exception</param>
131    private void HandleNetworkError(Exception e) {
132      ConnState = NetworkEnum.WcfConnState.Failed;
133      Logging.Instance.Error(this.ToString(), "exception: ", e);
134    }
135
136   
137
138    /// <summary>
139    /// Methods for the Server Login
140    /// </summary>
141    #region Login
142    public event System.EventHandler<LoginCompletedEventArgs> LoginCompleted;
143    public void LoginAsync(ClientInfo clientInfo) {
144      if (ConnState == NetworkEnum.WcfConnState.Connected)
145        proxy.LoginAsync(clientInfo);
146    }
147    private void proxy_LoginCompleted(object sender, LoginCompletedEventArgs e) {
148      if (e.Error == null)
149        LoginCompleted(sender, e);
150      else
151        HandleNetworkError(e.Error.InnerException);
152    }
153
154    public void LoginSync(ClientInfo clientInfo) {
155      try {
156        if (ConnState == NetworkEnum.WcfConnState.Connected) {
157          Response res = proxy.Login(clientInfo);
158          ConnState = NetworkEnum.WcfConnState.Loggedin;
159          Logging.Instance.Info(this.ToString(), res.StatusMessage);
160        }
161      }
162      catch (Exception e) {
163        HandleNetworkError(e);
164      }
165    }
166
167    #endregion
168
169    /// <summary>
170    /// Pull a Job from the Server
171    /// </summary>
172    #region PullJob
173    public event System.EventHandler<SendJobCompletedEventArgs> SendJobCompleted;
174    public void SendJobAsync(Guid guid) {
175      if (ConnState == NetworkEnum.WcfConnState.Loggedin)       
176        proxy.SendJobAsync(guid);
177    }
178    void proxy_SendJobCompleted(object sender, SendJobCompletedEventArgs e) {
179      if (e.Error == null)
180        SendJobCompleted(sender, e);
181      else
182        HandleNetworkError(e.Error);
183    }
184    #endregion
185
186    /// <summary>
187    /// Send back finished Job Results
188    /// </summary>
189    #region SendJobResults
190    public event System.EventHandler<StoreFinishedJobResultCompletedEventArgs> StoreFinishedJobResultCompleted;
191    public void StoreFinishedJobResultAsync(Guid clientId, Guid jobId, byte[] result, double percentage, Exception exception, bool finished) {
192      if (ConnState == NetworkEnum.WcfConnState.Loggedin)
193        proxy.StoreFinishedJobResultAsync(clientId, jobId, result, percentage, exception, finished);
194    }
195    private void proxy_StoreFinishedJobResultCompleted(object sender, StoreFinishedJobResultCompletedEventArgs e) {
196      if (e.Error == null)
197        StoreFinishedJobResultCompleted(sender, e);
198      else
199        HandleNetworkError(e.Error);
200    }
201
202    #endregion
203
204    #region Processsnapshots
205    public event System.EventHandler<ProcessSnapshotCompletedEventArgs> ProcessSnapshotCompleted;
206    public void ProcessSnapshotAsync(Guid clientId, Guid jobId, byte[] result, double percentage, Exception exception, bool finished) {
207      if(ConnState == NetworkEnum.WcfConnState.Loggedin)
208        proxy.ProcessSnapshotAsync(clientId, jobId, result, percentage, exception);
209    }
210    void proxy_ProcessSnapshotCompleted(object sender, ProcessSnapshotCompletedEventArgs e) {
211      if (e.Error == null)
212        ProcessSnapshotCompleted(sender, e);
213      else
214        HandleNetworkError(e.Error);
215    }   
216   
217    #endregion
218
219    /// <summary>
220    /// Methods for sending the periodically Heartbeat
221    /// </summary>
222    #region Heartbeat
223
224    public event System.EventHandler<ProcessHeartBeatCompletedEventArgs> SendHeartBeatCompleted;
225    public void SendHeartBeatAsync(HeartBeatData hbd) {
226      if (ConnState == NetworkEnum.WcfConnState.Loggedin)
227        proxy.ProcessHeartBeatAsync(hbd);
228    }
229
230    private void proxy_ProcessHeartBeatCompleted(object sender, ProcessHeartBeatCompletedEventArgs e) {
231      if (e.Error == null)
232        SendHeartBeatCompleted(sender, e);
233      else
234        HandleNetworkError(e.Error);
235    }
236
237    #endregion 
238
239    /// <summary>
240    /// Send back finished and Stored Job Results
241    /// </summary>
242    /*#region SendJobResults
243    public event System.EventHandler<StoreFinishedJobResultCompletedEventArgs> ProcessStoredJobResultCompleted;
244    public void ProcessStoredJobResultAsync(Guid clientId, long jobId, byte[] result, double percentage, Exception exception, bool finished) {
245      if (ConnState == NetworkEnum.WcfConnState.Loggedin)
246        //TODO: some sort of algo for the stored jobs
247        proxy.ProcessJobResultAsync(clientId, jobId, result, percentage, exception, finished);
248    } 
249    #endregion  */
250
251    public ResponseResultReceived SendStoredJobResultsSync(Guid clientId, Guid jobId, byte[] result, double percentage, Exception exception, bool finished) {     
252      return proxy.StoreFinishedJobResult(clientId, jobId, result, percentage, exception);   
253    }
254
255    public ResponseResultReceived ProcessSnapshotSync(Guid clientId, Guid jobId, byte[] result, double percentage, Exception exception) {
256      try {
257        ResponseResultReceived res = proxy.ProcessSnapshot(clientId, jobId, result, percentage, null);
258        Logging.Instance.Info(this.ToString(), "Snapshot for Job " + jobId + " submitted");
259        return res;
260      }
261      catch (Exception e) {
262        HandleNetworkError(e);
263        return null;
264      }
265    }
266
267    public List<CachedHivePluginInfo> RequestPlugins(List<HivePluginInfo> requestedPlugins) {
268      try {
269        ResponsePlugin response = proxy.SendPlugins(requestedPlugins.ToArray());
270        return response.Plugins;       
271      }
272      catch (Exception e) {
273        HandleNetworkError(e);
274        return null;
275      }
276    }
277
278    public void Logout(Guid guid) {
279      try {
280        proxy.Logout(guid);
281      }
282      catch (Exception e) {
283        HandleNetworkError(e);
284      }
285    }
286  }
287}
Note: See TracBrowser for help on using the repository browser.