Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 1138 was 1137, checked in by msteinbi, 16 years ago

Implementing Lifecycle Management (#453)

File size: 13.4 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.RegisterHeartbeat(
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                    resetJobsDependingOnResults(job);
93                  }
94                }
95              }
96             
97              // client must be set offline
98              client.State = State.offline;
99              clientAdapter.Update(client);
100              lastHeartbeats.Remove(client.ClientId);
101            }
102          }
103        } else {
104          if (lastHeartbeats.ContainsKey(client.ClientId))
105            lastHeartbeats.Remove(client.ClientId);
106        }
107      }
108    }
109
110    private void resetJobsDependingOnResults(Job job) {
111      List<JobResult> allJobResults = new List<JobResult>(jobResultAdapter.GetAll());
112      JobResult lastJobResult = null;
113      foreach (JobResult jR in allJobResults) {
114        if (jR.Job != null && jR.Job.Id == job.Id) {
115          if (lastJobResult != null) {
116            // if lastJobResult was before the current jobResult the lastJobResult must be updated
117            if ((jR.timestamp.Subtract(lastJobResult.timestamp)).Seconds > 0)
118              lastJobResult = jR;
119          }
120        }
121      }
122      if (lastJobResult != null) {
123        job.Client = null;
124        job.Percentage = lastJobResult.Percentage;
125        job.State = State.idle;
126        job.SerializedJob = lastJobResult.Result;
127      } else {
128        job.Client = null;
129        job.Percentage = 0;
130        job.State = State.idle;
131      }
132    }
133
134    #region IClientCommunicator Members
135
136    /// <summary>
137    /// Login process for the client
138    /// A hearbeat entry is created as well (login is the first hearbeat)
139    /// </summary>
140    /// <param name="clientInfo"></param>
141    /// <returns></returns>
142    [MethodImpl(MethodImplOptions.Synchronized)]
143    public Response Login(ClientInfo clientInfo) {
144      Response response = new Response();
145
146      if (lastHeartbeats.ContainsKey(clientInfo.ClientId)) {
147        lastHeartbeats[clientInfo.ClientId] = DateTime.Now;
148      } else {
149        lastHeartbeats.Add(clientInfo.ClientId, DateTime.Now);
150      }
151
152      ICollection<ClientInfo> allClients = clientAdapter.GetAll();
153      ClientInfo client = clientAdapter.GetById(clientInfo.ClientId);
154      if (client != null && client.State != State.offline && client.State != State.nullState) {
155        response.Success = false;
156        response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_LOGIN_USER_ALLREADY_ONLINE;
157        return response;
158      }
159      clientInfo.State = State.idle;
160      clientAdapter.Update(clientInfo);
161      response.Success = true;
162      response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_LOGIN_SUCCESS;
163
164      return response;
165    }
166
167    /// <summary>
168    /// The client has to send regulary heartbeats
169    /// this hearbeats will be stored in the heartbeats dictionary
170    /// check if there is work for the client and send the client a response if he should pull a job
171    /// </summary>
172    /// <param name="hbData"></param>
173    /// <returns></returns>
174    [MethodImpl(MethodImplOptions.Synchronized)]
175    public ResponseHB SendHeartBeat(HeartBeatData hbData) {
176      ResponseHB response = new ResponseHB();
177
178      response.ActionRequest = new List<MessageContainer>();
179      if (clientAdapter.GetById(hbData.ClientId).State == State.offline ||
180          clientAdapter.GetById(hbData.ClientId).State == State.nullState) {
181        response.Success = false;
182        response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_USER_NOT_LOGGED_IN;
183        response.ActionRequest.Add(new MessageContainer(MessageContainer.MessageType.NoMessage));
184        return response;
185      }
186
187      if (lastHeartbeats.ContainsKey(hbData.ClientId)) {
188        lastHeartbeats[hbData.ClientId] = DateTime.Now;
189      } else {
190        lastHeartbeats.Add(hbData.ClientId, DateTime.Now);
191      }
192
193      response.Success = true;
194      response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_HARDBEAT_RECEIVED;
195      List<Job> allOfflineJobs = new List<Job>(jobAdapter.GetJobsByState(State.offline));
196      if (allOfflineJobs.Count > 0 && hbData.freeCores > 0)
197        response.ActionRequest.Add(new MessageContainer(MessageContainer.MessageType.FetchJob));
198      else
199        response.ActionRequest.Add(new MessageContainer(MessageContainer.MessageType.NoMessage));
200
201      if (hbData.jobProgress != null) {
202        foreach (KeyValuePair<long, double> jobProgress in hbData.jobProgress) {
203          Job curJob = jobAdapter.GetById(jobProgress.Key);
204          curJob.Percentage = jobProgress.Value;
205          jobAdapter.Update(curJob);
206        }
207      }
208
209      return response;
210    }
211   
212    /// <summary>
213    /// if the client asked to pull a job he calls this method
214    /// the server selects a job and sends it to the client
215    /// </summary>
216    /// <param name="clientId"></param>
217    /// <returns></returns>
218    [MethodImpl(MethodImplOptions.Synchronized)]
219    public ResponseJob PullJob(Guid clientId) {
220      ResponseJob response = new ResponseJob();
221      lock (this) {
222        LinkedList<Job> allOfflineJobs = new LinkedList<Job>(jobAdapter.GetJobsByState(State.offline));
223        if (allOfflineJobs != null && allOfflineJobs.Count > 0) {
224          Job job2Calculate = allOfflineJobs.First.Value;
225          job2Calculate.State = State.calculating;
226          job2Calculate.Client = clientAdapter.GetById(clientId);
227          response.Job = job2Calculate;
228          jobAdapter.Update(job2Calculate);
229          response.Success = true;
230          response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_JOB_PULLED;
231          return response;
232        }
233      }
234      response.Success = true;
235      response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_NO_JOBS_LEFT;
236      return response;
237    }
238
239    /// <summary>
240    /// the client can send job results during calculating
241    /// and will send a final job result when he finished calculating
242    /// these job results will be stored in the database
243    /// </summary>
244    /// <param name="clientId"></param>
245    /// <param name="jobId"></param>
246    /// <param name="result"></param>
247    /// <param name="exception"></param>
248    /// <param name="finished"></param>
249    /// <returns></returns>
250    [MethodImpl(MethodImplOptions.Synchronized)]
251    public ResponseResultReceived SendJobResult(Guid clientId,
252      long jobId,
253      byte[] result,
254      double percentage,
255      Exception exception, 
256      bool finished) {
257      ResponseResultReceived response = new ResponseResultReceived();
258      ClientInfo client =
259        clientAdapter.GetById(clientId);
260
261      Job job =
262        jobAdapter.GetById(jobId);
263
264      if (job.Client == null)    {
265        response.Success = false;
266        response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_JOB_IS_NOT_BEEING_CALCULATED;
267        return response;
268      }
269      if (job.Client.ClientId != clientId) {
270        response.Success = false;
271        response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_WRONG_CLIENT_FOR_JOB;
272        return response;
273      }
274      if (job == null) {
275        response.Success = false;
276        response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_NO_JOB_WITH_THIS_ID;
277        return response;
278      }
279      if (job.State != State.calculating) {
280        response.Success = false;
281        response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_WRONG_JOB_STATE;
282        return response;
283      }
284      job.SerializedJob = result;
285      job.Percentage = percentage;
286
287      if (finished) {
288        job.State = State.finished;
289        jobAdapter.Update(job);
290
291        List<JobResult> jobResults = new List<JobResult>(jobResultAdapter.GetResultsOf(job));
292        foreach (JobResult currentResult in jobResults)
293          jobResultAdapter.Delete(currentResult);
294      }
295
296      JobResult jobResult =
297        new JobResult();
298      jobResult.Client = client;
299      jobResult.Job = job;
300      jobResult.Result = result;
301      jobResult.Percentage = percentage;
302      jobResult.Exception = exception;
303
304      jobResultAdapter.Update(jobResult);
305      jobAdapter.Update(job);
306
307      response.Success = true;
308      response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_JOBRESULT_RECEIVED;
309      response.JobId = jobId;
310      response.finished = finished;
311
312      return response;
313    }
314
315    /// <summary>
316    /// when a client logs out the state will be set
317    /// and the entry in the last hearbeats dictionary will be removed
318    /// </summary>
319    /// <param name="clientId"></param>
320    /// <returns></returns>
321    [MethodImpl(MethodImplOptions.Synchronized)]                       
322    public Response Logout(Guid clientId) {
323      Response response = new Response();
324
325      if (lastHeartbeats.ContainsKey(clientId))
326        lastHeartbeats.Remove(clientId);
327
328      ClientInfo client = clientAdapter.GetById(clientId);
329      if (client == null) {
330        response.Success = false;
331        response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_LOGOUT_CLIENT_NOT_REGISTERED;
332        return response;
333      }
334      List<Job> allJobs = new List<Job>(jobAdapter.GetAll());
335      if (client.State == State.calculating) {
336        // check wich job the client was calculating and reset it
337        foreach (Job job in allJobs) {
338          if (job.Client.ClientId == client.ClientId) {
339            resetJobsDependingOnResults(job);
340          }
341        }
342      }
343
344      client.State = State.offline;
345      clientAdapter.Update(client);
346
347      response.Success = true;
348      response.StatusMessage = ApplicationConstants.RESPONSE_COMMUNICATOR_LOGOUT_SUCCESS;
349     
350      return response;
351    }
352
353    #endregion
354  }
355}
Note: See TracBrowser for help on using the repository browser.