Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Hive.Server.Core/3.2/JobManager.cs @ 2092

Last change on this file since 2092 was 2092, checked in by svonolfe, 15 years ago

Small refactoring (#372)

File size: 16.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.Interfaces;
27using HeuristicLab.Hive.Contracts.BusinessObjects;
28using HeuristicLab.Hive.Contracts;
29using HeuristicLab.Hive.Server.DataAccess;
30using HeuristicLab.Hive.Server.Core.InternalInterfaces;
31using HeuristicLab.DataAccess.Interfaces;
32using System.Data;
33
34namespace HeuristicLab.Hive.Server.Core {
35  class JobManager: IJobManager, IInternalJobManager {
36
37    ISessionFactory factory;
38    ILifecycleManager lifecycleManager;
39
40    #region IJobManager Members
41
42    public JobManager() {
43      factory = ServiceLocator.GetSessionFactory();
44      lifecycleManager = ServiceLocator.GetLifecycleManager();
45
46      lifecycleManager.RegisterStartup(new EventHandler(lifecycleManager_OnStartup));
47      lifecycleManager.RegisterStartup(new EventHandler(lifecycleManager_OnShutdown));
48    }
49
50    private JobResult GetLastJobResult(Job job) {
51      ISession session = factory.GetSessionForCurrentThread();
52
53      try {
54        IJobResultsAdapter jobResultAdapter =
55            session.GetDataAdapter<JobResult, IJobResultsAdapter>();
56
57        return jobResultAdapter.GetLastResultOf(job);
58      }
59      finally {
60        if (session != null)
61          session.EndSession();
62      }
63    }
64
65    public void ResetJobsDependingOnResults(Job job) {
66      ISession session = factory.GetSessionForCurrentThread();
67      ITransaction tx = null;
68
69      try {
70        IJobAdapter jobAdapter =
71            session.GetDataAdapter<Job, IJobAdapter>();
72
73        tx = session.BeginTransaction();
74
75        if (job != null) {
76          SerializedJob computableJob =
77              new SerializedJob();
78          computableJob.JobInfo =
79            job;
80
81          JobResult lastJobResult = GetLastJobResult(job);
82          if (lastJobResult != null) {
83            computableJob.JobInfo.Percentage = lastJobResult.Percentage;
84            computableJob.SerializedJobData = lastJobResult.Result;
85
86            jobAdapter.UpdateComputableJob(computableJob);
87          } else {
88            computableJob.JobInfo.Percentage = 0;
89          }
90
91          computableJob.JobInfo.Client = null;
92          computableJob.JobInfo.State = State.offline;
93
94          jobAdapter.Update(computableJob.JobInfo);
95        }
96
97        tx.Commit();
98      }
99      catch (Exception ex) {
100        if (tx != null)
101          tx.Rollback();
102        throw ex;
103      }
104      finally {
105        if (session != null)
106          session.EndSession();
107      }
108    }
109
110    void checkForDeadJobs() {
111       ISession session = factory.GetSessionForCurrentThread();
112
113       try {
114         IJobAdapter jobAdapter =
115             session.GetDataAdapter<Job, IJobAdapter>();
116
117         List<Job> allJobs = new List<Job>(jobAdapter.GetAll());
118         foreach (Job curJob in allJobs) {
119           if (curJob.State == State.calculating) {
120             ResetJobsDependingOnResults(curJob);
121           }
122         }
123       }
124       finally {
125         if (session != null)
126           session.EndSession();
127       }
128    }
129
130    void lifecycleManager_OnStartup(object sender, EventArgs e) {
131      checkForDeadJobs();
132    }
133
134    void lifecycleManager_OnShutdown(object sender, EventArgs e) {
135      checkForDeadJobs();
136    }
137
138    /// <summary>
139    /// returns all jobs stored in the database
140    /// </summary>
141    /// <returns></returns>
142    public ResponseList<Job> GetAllJobs() {
143       ISession session = factory.GetSessionForCurrentThread();
144
145       try {
146         IJobAdapter jobAdapter =
147             session.GetDataAdapter<Job, IJobAdapter>();
148
149         ResponseList<Job> response = new ResponseList<Job>();
150
151         response.List = new List<Job>(jobAdapter.GetAll());
152         response.Success = true;
153         response.StatusMessage = ApplicationConstants.RESPONSE_JOB_ALL_JOBS;
154
155         return response;
156       }
157       finally {
158         if (session != null)
159           session.EndSession();
160       }
161    }
162
163    /// <summary>
164    /// returns the job with the specified id
165    /// </summary>
166    /// <returns></returns>
167    public ResponseObject<Job> GetJobById(Guid jobId) {
168      ISession session = factory.GetSessionForCurrentThread();
169
170      try {
171        IJobAdapter jobAdapter =
172            session.GetDataAdapter<Job, IJobAdapter>();
173
174        ResponseObject<Job> response = new ResponseObject<Job>();
175
176        response.Obj = jobAdapter.GetById(jobId);
177        if (response.Obj != null) {
178          response.Success = true;
179          response.StatusMessage = ApplicationConstants.RESPONSE_JOB_GET_JOB_BY_ID;
180        } else {
181          response.Success = false;
182          response.StatusMessage = ApplicationConstants.RESPONSE_JOB_JOB_DOESNT_EXIST;
183        }
184
185        return response;
186      }
187      finally {
188        if (session != null)
189          session.EndSession();
190      }
191    }
192
193    /// <summary>
194    /// Adds a new job into the database
195    /// </summary>
196    /// <param name="job"></param>
197    /// <returns></returns>
198    public ResponseObject<Job> AddNewJob(SerializedJob job) {
199      ISession session = factory.GetSessionForCurrentThread();
200
201      try {
202        IJobAdapter jobAdapter =
203            session.GetDataAdapter<Job, IJobAdapter>();
204
205        ResponseObject<Job> response = new ResponseObject<Job>();
206
207        if (job != null && job.JobInfo != null) {
208          if (job.JobInfo.State != State.offline) {
209            response.Success = false;
210            response.StatusMessage = ApplicationConstants.RESPONSE_JOB_JOBSTATE_MUST_BE_OFFLINE;
211            return response;
212          }
213          if (job.JobInfo.Id != Guid.Empty) {
214            response.Success = false;
215            response.StatusMessage = ApplicationConstants.RESPONSE_JOB_ID_MUST_NOT_BE_SET;
216            return response;
217          }
218          if (job.SerializedJobData == null) {
219            response.StatusMessage = ApplicationConstants.RESPONSE_JOB_JOB_NULL;
220            response.Success = false;
221            return response;
222          }
223
224          job.JobInfo.DateCreated = DateTime.Now;
225          jobAdapter.UpdateComputableJob(job);
226          response.Success = true;
227          response.Obj = job.JobInfo;
228          response.StatusMessage = ApplicationConstants.RESPONSE_JOB_JOB_ADDED;
229        } else {
230          response.Success = false;
231          response.StatusMessage = ApplicationConstants.RESPONSE_JOB_JOB_NULL;
232        }
233
234        return response;
235      }
236      finally {
237        if (session != null)
238          session.EndSession();
239      }
240    }
241
242    /// <summary>
243    /// Removes a job from the database
244    /// </summary>
245    /// <param name="jobId"></param>
246    /// <returns></returns>
247    public Response RemoveJob(Guid jobId) {
248      ISession session = factory.GetSessionForCurrentThread();
249
250      try {
251        IJobAdapter jobAdapter =
252            session.GetDataAdapter<Job, IJobAdapter>();
253        Response response = new Response();
254
255        Job job = jobAdapter.GetById(jobId);
256        if (job == null) {
257          response.Success = false;
258          response.StatusMessage = ApplicationConstants.RESPONSE_JOB_JOB_DOESNT_EXIST;
259          return response;
260        }
261        jobAdapter.Delete(job);
262        response.Success = false;
263        response.StatusMessage = ApplicationConstants.RESPONSE_JOB_JOB_REMOVED;
264
265        return response;
266      }
267      finally {
268        if (session != null)
269          session.EndSession();
270      }
271    }
272
273    public ResponseObject<JobResult> GetLastJobResultOf(Guid jobId, bool requested) {
274      ISession session = factory.GetSessionForCurrentThread();
275
276      try {
277        IJobAdapter jobAdapter =
278            session.GetDataAdapter<Job, IJobAdapter>();
279
280        ResponseObject<JobResult> response = new ResponseObject<JobResult>();
281
282        Job job = jobAdapter.GetById(jobId);
283        if (requested && (job.State == State.requestSnapshot || job.State == State.requestSnapshotSent)) {
284          response.Success = true;
285          response.StatusMessage = ApplicationConstants.RESPONSE_JOB_RESULT_NOT_YET_HERE;
286          return response;
287        }
288         
289        response.Success = true;
290        response.StatusMessage = ApplicationConstants.RESPONSE_JOB_JOB_RESULT_SENT;
291        response.Obj = GetLastJobResult(job);
292
293        return response;
294      }
295      finally {
296        if(session != null)
297          session.EndSession();
298      }
299    }
300
301    public Response RequestSnapshot(Guid jobId) {
302      ISession session = factory.GetSessionForCurrentThread();
303      Response response = new Response();
304     
305      try {
306        IJobAdapter jobAdapter = session.GetDataAdapter<Job, IJobAdapter>();
307
308        Job job = jobAdapter.GetById(jobId);
309        if (job.State == State.requestSnapshot || job.State == State.requestSnapshotSent) {
310          response.Success = true;
311          response.StatusMessage = ApplicationConstants.RESPONSE_JOB_REQUEST_ALLREADY_SET;
312          return response; // no commit needed
313        }
314        if (job.State != State.calculating) {
315          response.Success = false;
316          response.StatusMessage = ApplicationConstants.RESPONSE_JOB_IS_NOT_BEEING_CALCULATED;
317          return response; // no commit needed
318        }
319        // job is in correct state
320        job.State = State.requestSnapshot;
321        jobAdapter.Update(job);
322
323        response.Success = true;
324        response.StatusMessage = ApplicationConstants.RESPONSE_JOB_REQUEST_SET;
325
326        return response;
327      }
328      finally {
329        if (session != null)
330          session.EndSession();
331      }
332    }
333
334    public Response AbortJob(Guid jobId) {
335      ISession session = factory.GetSessionForCurrentThread();
336      Response response = new Response();
337
338      try {
339        IJobAdapter jobAdapter = session.GetDataAdapter<Job, IJobAdapter>();
340
341        Job job = jobAdapter.GetById(jobId);
342        if (job == null) {
343          response.Success = false;
344          response.StatusMessage = ApplicationConstants.RESPONSE_JOB_JOB_DOESNT_EXIST;
345          return response; // no commit needed
346        }
347        if (job.State == State.abort) {
348          response.Success = true;
349          response.StatusMessage = ApplicationConstants.RESPONSE_JOB_ABORT_REQUEST_ALLREADY_SET;
350          return response; // no commit needed
351        }
352        if (job.State != State.calculating && job.State != State.requestSnapshot && job.State != State.requestSnapshotSent) {
353          response.Success = false;
354          response.StatusMessage = ApplicationConstants.RESPONSE_JOB_IS_NOT_BEEING_CALCULATED;
355          return response; // no commit needed
356        }
357        // job is in correct state
358        job.State = State.abort;
359        jobAdapter.Update(job);
360
361        response.Success = true;
362        response.StatusMessage = ApplicationConstants.RESPONSE_JOB_ABORT_REQUEST_SET;
363
364        return response;
365      }
366      finally {
367        if (session != null)
368          session.EndSession();
369      }
370    }
371
372    public ResponseList<JobResult> GetAllJobResults(Guid jobId) {
373      ISession session = factory.GetSessionForCurrentThread();
374      ResponseList<JobResult> response = new ResponseList<JobResult>();
375
376      try {
377        IJobResultsAdapter jobResultAdapter =
378            session.GetDataAdapter<JobResult, IJobResultsAdapter>();
379        IJobAdapter jobAdapter = session.GetDataAdapter<Job, IJobAdapter>();
380
381        Job job = jobAdapter.GetById(jobId);
382        if (job == null) {
383          response.Success = false;
384          response.StatusMessage = ApplicationConstants.RESPONSE_JOB_JOB_DOESNT_EXIST;
385          return response;
386        }
387        response.List = new List<JobResult>(jobResultAdapter.GetResultsOf(job));
388        response.Success = true;
389        response.StatusMessage = ApplicationConstants.RESPONSE_JOB_JOB_RESULT_SENT;
390
391        return response;
392      }
393      finally {
394        if(session != null)
395          session.EndSession();
396      }
397    }
398
399    public ResponseList<Project> GetAllProjects() {
400      ISession session = factory.GetSessionForCurrentThread();
401      ResponseList<Project> response = new ResponseList<Project>();
402
403      try {
404        IProjectAdapter projectAdapter =
405          session.GetDataAdapter<Project, IProjectAdapter>();
406
407        List<Project> allProjects = new List<Project>(projectAdapter.GetAll());
408        response.List = allProjects;
409        response.Success = true;
410        return response;
411      }
412      finally {
413        if (session != null)
414          session.EndSession();
415      }
416    }
417
418    private Response createUpdateProject(Project project) {
419      ISession session = factory.GetSessionForCurrentThread();
420      Response response = new Response();
421      ITransaction tx = null;
422
423      try {
424        IProjectAdapter projectAdapter =
425          session.GetDataAdapter<Project, IProjectAdapter>();
426
427        if (project.Name == null || project.Name == "") {
428          response.Success = false;
429          response.StatusMessage = ApplicationConstants.RESPONSE_JOB_PROJECT_NAME_EMPTY;
430          return response;
431        }
432        tx = session.BeginTransaction();
433        projectAdapter.Update(project);
434
435        tx.Commit();
436        response.Success = true;
437        response.StatusMessage = ApplicationConstants.RESPONSE_JOB_PROJECT_ADDED;
438      } catch (ConstraintException ce) {
439        if (tx != null)
440          tx.Rollback();
441        response.Success = false;
442        response.StatusMessage = ce.Message;
443      }
444      catch (Exception ex) {
445        if (tx != null)
446          tx.Rollback();
447        throw ex;
448      }
449      finally {
450        if (session != null)
451          session.EndSession();
452      }
453      return response;
454    }
455
456    public Response CreateProject(Project project) {
457      return createUpdateProject(project);
458    }
459
460    public Response ChangeProject(Project project) {
461      return createUpdateProject(project);
462    }
463
464    public Response DeleteProject(Guid projectId) {
465      ISession session = factory.GetSessionForCurrentThread();
466      Response response = new Response();
467      ITransaction tx = null;
468
469      try {
470        IProjectAdapter projectAdapter =
471          session.GetDataAdapter<Project, IProjectAdapter>();
472
473        Project project = projectAdapter.GetById(projectId);
474        if (project == null) {
475          response.Success = false;
476          response.StatusMessage = ApplicationConstants.RESPONSE_JOB_PROJECT_DOESNT_EXIST;
477          return response;
478        }
479        projectAdapter.Delete(project);
480        tx.Commit();
481        response.Success = true;
482        response.StatusMessage = ApplicationConstants.RESPONSE_JOB_PROJECT_DELETED;
483      }
484      catch (Exception e) {
485        if (tx != null)
486          tx.Rollback();
487        response.Success = false;
488        response.StatusMessage = e.Message;
489      }
490      finally {
491        if (session != null)
492          session.EndSession();
493      }
494      return response;
495    }
496
497    public ResponseList<Job> GetJobsByProject(Guid projectId) {
498      ISession session = factory.GetSessionForCurrentThread();
499      ResponseList<Job> response = new ResponseList<Job>();
500
501      try {
502        IJobAdapter jobAdapter =
503          session.GetDataAdapter<Job, IJobAdapter>();
504        List<Job> jobsByProject = new List<Job>(jobAdapter.GetJobsByProject(projectId));
505        response.List = jobsByProject;
506        response.Success = true;
507      }
508      finally {
509        if (session != null)
510          session.EndSession();
511      }
512      return response;
513    }
514
515    #endregion
516  }
517}
Note: See TracBrowser for help on using the repository browser.