source: trunk/sources/HeuristicLab.Hive.Server.Core/ClientCommunicator.cs @ 1121

Last change on this file since 1121 was 1121, checked in by msteinbi, 12 years ago

Add licencse information where missing, added method description comments (#466)

File size: 11.3 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 HeuristicLab.Hive.Contracts.BusinessObjects;
27using HeuristicLab.Hive.Contracts.Interfaces;
28using HeuristicLab.Hive.Contracts;
29using HeuristicLab.Core;
30using HeuristicLab.Hive.Server.Core.InternalInterfaces.DataAccess;
31using System.Resources;
32using System.Reflection;
33using HeuristicLab.Hive.JobBase;
34using System.Runtime.CompilerServices;
35
36namespace HeuristicLab.Hive.Server.Core {
37  /// <summary>
38  /// The ClientCommunicator manages the whole communication with the client
39  /// </summary>
40  public class ClientCommunicator: IClientCommunicator {
41    Dictionary<Guid, DateTime> lastHeartbeats =
42      new Dictionary<Guid,DateTime>();
43
44    IClientAdapter clientAdapter;
45    IJobAdapter jobAdapter;
46    IJobResultsAdapter jobResultAdapter;
47    ILifecycleManager lifecycleManager;
48
49    /// <summary>
50    /// Initialization of the Adapters to the database
51    /// Initialization of Eventhandler for the lifecycle management
52    /// Initialization of lastHearbeats Dictionary
53    /// </summary>
54    public ClientCommunicator() {
55      clientAdapter = ServiceLocator.GetClientAdapter();
56      jobAdapter = ServiceLocator.GetJobAdapter();
57      jobResultAdapter = ServiceLocator.GetJobResultsAdapter();
58      lifecycleManager = ServiceLocator.GetLifecycleManager();
59
60      lifecycleManager.OnServerHeartbeat +=
61        new EventHandler(lifecycleManager_OnServerHeartbeat);
62
63      lastHeartbeats = new Dictionary<Guid, DateTime>();
64    }
65
66    /// <summary>
67    /// Check if online clients send their hearbeats
68    /// if not -> set them offline and check if they where calculating a job
69    /// </summary>
70    /// <param name="sender"></param>
71    /// <param name="e"></param>
72    [MethodImpl(MethodImplOptions.Synchronized)]
73    void lifecycleManager_OnServerHeartbeat(object sender, EventArgs e) {
74      List<ClientInfo> allClients = new List<ClientInfo>(clientAdapter.GetAll());
75      List<Job> allJobs = new List<Job>(jobAdapter.GetAll());
76
77      foreach (ClientInfo client in allClients) {
78        if (client.State != State.offline && client.State != State.nullState) {
79          if (!lastHeartbeats.ContainsKey(client.ClientId)) {
80            client.State = State.offline;
81            clientAdapter.Update(client);
82          } else {
83            DateTime lastHbOfClient = lastHeartbeats[client.ClientId];
84            TimeSpan dif = DateTime.Now.Subtract(lastHbOfClient);
85            // check if time between last hearbeat and now is greather than HEARTBEAT_MAX_DIF
86            if (dif.Seconds > ApplicationConstants.HEARTBEAT_MAX_DIF) {
87              // if client calculated jobs, the job must be reset
88              if (client.State == State.calculating) {
89                // check wich job the client was calculating and reset it
90                foreach (Job job in allJobs) {
91                  if (job.Client.ClientId == client.ClientId) {
92                    // TODO check for job results
93                    job.Client = null;
94                    job.Percentage = 0;
95                    job.State = State.idle;
96                  }
97                }
98              }
99             
100              // client must be set offline
101              client.State = State.offline;
102              clientAdapter.Update(client);
103              lastHeartbeats.Remove(client.ClientId);
104            }
105          }
106        } else {
107          if (lastHeartbeats.ContainsKey(client.ClientId))
108            lastHeartbeats.Remove(client.ClientId);
109        }
110      }
111    }
112
113    #region IClientCommunicator Members
114
115    /// <summary>
116    /// Login process for the client
117    /// A hearbeat entry is created as well (login is the first hearbeat)
118    /// </summary>
119    /// <param name="clientInfo"></param>
120    /// <returns></returns>
121    [MethodImpl(MethodImplOptions.Synchronized)]
122    public Response Login(ClientInfo clientInfo) {
123      Response response = new Response();
124
125      if (lastHeartbeats.ContainsKey(clientInfo.ClientId)) {
126        lastHeartbeats[clientInfo.ClientId] = DateTime.Now;
127      } else {
128        lastHeartbeats.Add(clientInfo.ClientId, DateTime.Now);
129      }
130
131      ICollection<ClientInfo> allClients = clientAdapter.GetAll();
132      ClientInfo client = clientAdapter.GetById(clientInfo.ClientId);
133      if (client != null && client.State != State.offline && client.State != State.nullState) {
134        response.Success = false;
135        response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_LOGIN_USER_ALLREADY_ONLINE;
136        return response;
137      }
138      clientInfo.State = State.idle;
139      clientAdapter.Update(clientInfo);
140      response.Success = true;
141      response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_LOGIN_SUCCESS;
142
143      return response;
144    }
145
146    /// <summary>
147    /// The client has to send regulary heartbeats
148    /// this hearbeats will be stored in the heartbeats dictionary
149    /// check if there is work for the client and send the client a response if he should pull a job
150    /// </summary>
151    /// <param name="hbData"></param>
152    /// <returns></returns>
153    [MethodImpl(MethodImplOptions.Synchronized)]
154    public ResponseHB SendHeartBeat(HeartBeatData hbData) {
155      ResponseHB response = new ResponseHB();
156
157      response.ActionRequest = new List<MessageContainer>();
158      if (clientAdapter.GetById(hbData.ClientId).State == State.offline ||
159          clientAdapter.GetById(hbData.ClientId).State == State.nullState) {
160        response.Success = false;
161        response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_USER_NOT_LOGGED_IN;
162        response.ActionRequest.Add(new MessageContainer(MessageContainer.MessageType.NoMessage));
163        return response;
164      }
165
166      if (lastHeartbeats.ContainsKey(hbData.ClientId)) {
167        lastHeartbeats[hbData.ClientId] = DateTime.Now;
168      } else {
169        lastHeartbeats.Add(hbData.ClientId, DateTime.Now);
170      }
171
172      response.Success = true;
173      response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_HARDBEAT_RECEIVED;
174      List<Job> allOfflineJobs = new List<Job>(jobAdapter.GetJobsByState(State.offline));
175      if (allOfflineJobs.Count > 0 && hbData.freeCores > 0)
176        response.ActionRequest.Add(new MessageContainer(MessageContainer.MessageType.FetchJob));
177      else
178        response.ActionRequest.Add(new MessageContainer(MessageContainer.MessageType.NoMessage));
179
180      return response;
181    }
182   
183    /// <summary>
184    /// if the client asked to pull a job he calls this method
185    /// the server selects a job and sends it to the client
186    /// </summary>
187    /// <param name="clientId"></param>
188    /// <returns></returns>
189    [MethodImpl(MethodImplOptions.Synchronized)]
190    public ResponseJob PullJob(Guid clientId) {
191      ResponseJob response = new ResponseJob();
192      lock (this) {
193        LinkedList<Job> allOfflineJobs = new LinkedList<Job>(jobAdapter.GetJobsByState(State.offline));
194        if (allOfflineJobs != null && allOfflineJobs.Count > 0) {
195          Job job2Calculate = allOfflineJobs.First.Value;
196          job2Calculate.State = State.calculating;
197          response.Job = job2Calculate;
198          jobAdapter.Update(job2Calculate);
199          response.Success = true;
200          response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_JOB_PULLED;
201          return response;
202        }
203      }
204      response.Success = true;
205      response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_NO_JOBS_LEFT;
206      return response;
207    }
208
209    /// <summary>
210    /// the client can send job results during calculating
211    /// and will send a final job result when he finished calculating
212    /// these job results will be stored in the database
213    /// </summary>
214    /// <param name="clientId"></param>
215    /// <param name="jobId"></param>
216    /// <param name="result"></param>
217    /// <param name="exception"></param>
218    /// <param name="finished"></param>
219    /// <returns></returns>
220    [MethodImpl(MethodImplOptions.Synchronized)]
221    public ResponseResultReceived SendJobResult(Guid clientId,
222      long jobId,
223      byte[] result,
224      Exception exception, 
225      bool finished) {
226      ResponseResultReceived response = new ResponseResultReceived();
227      ClientInfo client =
228        clientAdapter.GetById(clientId);
229
230      Job job =
231        jobAdapter.GetById(jobId);
232      if (job == null) {
233        response.Success = false;
234        response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_NO_JO_WITH_THIS_ID;
235        return response;
236      }
237      if (job.State != State.calculating) {
238        response.Success = false;
239        response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_WRONG_JOB_STATE;
240        return response;
241      }
242      if (finished) {
243        job.State = State.finished;
244        jobAdapter.Update(job);
245
246        List<JobResult> jobResults = new List<JobResult>(jobResultAdapter.GetResultsOf(job));
247        foreach (JobResult currentResult in jobResults)
248          jobResultAdapter.Delete(currentResult);
249      }
250
251      JobResult jobResult =
252        new JobResult();
253      jobResult.Client = client;
254      jobResult.Job = job;
255      jobResult.Result = result;
256      jobResult.Exception = exception;
257
258      jobResultAdapter.Update(jobResult);   
259
260      response.Success = true;
261      response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_JOBRESULT_RECEIVED;
262      response.JobId = jobId;
263
264      return response;
265    }
266
267    /// <summary>
268    /// when a client logs out the state will be set
269    /// and the entry in the last hearbeats dictionary will be removed
270    /// </summary>
271    /// <param name="clientId"></param>
272    /// <returns></returns>
273    [MethodImpl(MethodImplOptions.Synchronized)]                       
274    public Response Logout(Guid clientId) {
275      Response response = new Response();
276
277      if (lastHeartbeats.ContainsKey(clientId))
278        lastHeartbeats.Remove(clientId);
279
280      ClientInfo client = clientAdapter.GetById(clientId);
281      if (client == null) {
282        response.Success = false;
283        response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_LOGOUT_CLIENT_NOT_REGISTERED;
284        return response;
285      }
286      client.State = State.offline;
287      clientAdapter.Update(client);
288
289      response.Success = true;
290      response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_LOGOUT_SUCCESS;
291     
292      return response;
293    }
294
295    #endregion
296  }
297}
Note: See TracBrowser for help on using the repository browser.