Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive/sources/HeuristicLab.Hive/HeuristicLab.Hive.Server.LINQDataAccess/3.3/JobDao.cs @ 5037

Last change on this file since 5037 was 5037, checked in by cneumuel, 13 years ago

#1260

  • changed ExecutionTime column datatype in DB to string (because time only allows 24-hours, but TimeSpan can be more)
File size: 11.5 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.Collections.Generic;
24using System.Data.SqlClient;
25using System.IO;
26using System.Linq;
27using HeuristicLab.Hive.Contracts.BusinessObjects;
28using HeuristicLab.Hive.Server.DataAccess;
29
30namespace HeuristicLab.Hive.Server.LINQDataAccess {
31  public class JobDao : BaseDao<JobDto, Job>, IJobDao {
32
33    #region IGenericDao<JobDto,Job> Members
34
35    public JobDto FindById(Guid id) {
36      return (from job in Context.Jobs
37              where job.JobId.Equals(id)
38              select EntityToDto(job, null)).SingleOrDefault();
39    }
40
41    public IEnumerable<JobDto> FindAll() {
42      return (from job in Context.Jobs
43              select EntityToDto(job, null)).ToList();
44    }
45
46    public IEnumerable<JobDto> FindWithLimitations(JobState jobState, int offset, int count) {
47      IQueryable<JobDto> query = null;
48      if (jobState == JobState.Finished) {
49        query = from job in Context.Jobs
50                where job.JobState == Enum.GetName(typeof(JobState), jobState)
51                orderby job.DateFinished
52                select EntityToDto(job, null);
53      } else if (jobState == JobState.Calculating || jobState == JobState.SnapshotRequested || jobState == JobState.SnapshotSent) {
54        query = from job in Context.Jobs
55                where job.JobState == Enum.GetName(typeof(JobState), jobState)
56                orderby job.DateCalculated
57                select EntityToDto(job, null);
58      } else {
59        query = from job in Context.Jobs
60                where job.JobState == Enum.GetName(typeof(JobState), jobState)
61                orderby job.DateCreated
62                select EntityToDto(job, null);
63      }
64
65      return query.Skip(offset).Take(count).ToList();
66    }
67
68
69    public byte[] GetBinaryJobFile(Guid jobId) {
70      return (from job in Context.Jobs
71              where job.JobId.Equals(jobId)
72              select job.SerializedJob).SingleOrDefault().ToArray();
73    }
74
75    public JobDto Insert(JobDto bObj) {
76      Job j = DtoToEntity(bObj, null);
77      Context.Jobs.InsertOnSubmit(j);
78      CommitChanges();
79      bObj.Id = j.JobId;
80      return bObj;
81    }
82
83    public void SetBinaryJobFile(Guid jobId, byte[] data) {
84      Job j = (from job in Context.Jobs
85               where job.JobId.Equals(jobId)
86               select job).SingleOrDefault();
87      j.SerializedJob = data;
88      CommitChanges();
89    }
90
91    public SerializedJob InsertWithAttachedJob(SerializedJob job) {
92      Job j = DtoToEntity(job.JobInfo, null);
93      j.SerializedJob = job.SerializedJobData;
94      //foreach (Guid assignRessourceId in job.JobInfo.AssignedResourceIds)
95      //  j.AssignedResources.Add(new AssignedResource { ResourceId = assignRessourceId });
96      Context.Jobs.InsertOnSubmit(j);
97      CommitChanges();
98      job.JobInfo.Id = j.JobId;
99      return job;
100    }
101
102    public void Delete(Guid id) {
103      Job job = Context.Jobs.SingleOrDefault(j => j.JobId.Equals(id));
104      Context.Jobs.DeleteOnSubmit(job);
105      CommitChanges();
106    }
107
108    public void Update(JobDto bObj) {
109      Job job = Context.Jobs.SingleOrDefault(j => j.JobId.Equals(bObj.Id));
110      DtoToEntity(bObj, job);
111      CommitChanges();
112    }
113
114    public IEnumerable<JobDto> FindActiveJobsOfSlave(SlaveDto slave) {
115      return (from j in Context.Jobs
116              where (j.JobState == Enum.GetName(typeof(JobState), JobState.Calculating) ||
117                     j.JobState == Enum.GetName(typeof(JobState), JobState.Aborted) ||
118                     j.JobState == Enum.GetName(typeof(JobState), JobState.SnapshotRequested) ||
119                     j.JobState == Enum.GetName(typeof(JobState), JobState.SnapshotSent) ||
120                     j.JobState == Enum.GetName(typeof(JobState), JobState.WaitForChildJobs)) &&
121                    (j.ResourceId.Equals(slave.Id))
122              select EntityToDto(j, null)).ToList();
123    }
124
125    public IEnumerable<JobDto> FindFittingJobs(JobState state, int freeCores, int freeMemory, Guid slaveId) {
126      SlaveGroupDao cgd = new SlaveGroupDao();
127
128      List<Guid> idList = new List<Guid>(cgd.FindAllGroupAndParentGroupIdsForSlave(slaveId));
129      //Add myself too - enables jobs for one specific host!
130      idList.Add(slaveId);
131
132      var q = (from ar in Context.AssignedResources
133               where ar.Job.JobState == Enum.GetName(typeof(JobState), state) &&
134                     ar.Job.CoresNeeded <= freeCores &&
135                     ar.Job.MemoryNeeded <= freeMemory &&
136                     idList.Contains(ar.ResourceId)
137               orderby ar.Job.Priority descending
138               select EntityToDto(ar.Job, null));
139      return q.ToList();
140    }
141
142    public IEnumerable<JobDto> FindJobsWithFinishedChilds(Guid slaveId) {
143      SlaveGroupDao cgd = new SlaveGroupDao();
144     
145      List<Guid> idList = new List<Guid>(cgd.FindAllGroupAndParentGroupIdsForSlave(slaveId));
146      //Add myself too - enables jobs for one specific host!
147      idList.Add(slaveId);
148
149      var query = from ar in Context.AssignedResources
150                  where ar.Job.JobState == Enum.GetName(typeof(JobState), JobState.WaitForChildJobs) &&
151                    (from child in Context.Jobs
152                     where child.ParentJobId == ar.Job.JobId
153                     select
154                      (child.JobState == Enum.GetName(typeof(JobState), JobState.Finished) ||
155                       child.JobState == Enum.GetName(typeof(JobState), JobState.Failed) ||
156                       child.JobState == Enum.GetName(typeof(JobState), JobState.Aborted))
157                      ).All(x => x) &&
158                    (from child in Context.Jobs // avoid returning WaitForChildJobs jobs where no child-jobs exist (yet)
159                     where child.ParentJobId == ar.Job.JobId
160                     select child).Count() > 0
161                  orderby ar.Job.Priority descending
162                  select EntityToDto(ar.Job, null);
163      var list = query.ToList();
164      return list;
165    }
166
167    public IEnumerable<JobDto> GetJobsByState(JobState state) {
168      return (from j in Context.Jobs
169              where (j.JobState == Enum.GetName(typeof(JobState), state))
170              select EntityToDto(j, null)).ToList();
171    }
172
173    public void AssignSlaveToJob(Guid slaveId, Guid jobId) {
174      Slave s = Context.Resources.OfType<Slave>().SingleOrDefault(slave => slave.ResourceId.Equals(slaveId));
175      Job j = Context.Jobs.SingleOrDefault(job => job.JobId.Equals(jobId));
176      s.Jobs.Add(j);
177      j.Slave = s;
178      CommitChanges();
179    }
180
181    public void UnAssignSlaveToJob(Guid jobId) {
182      Job j = Context.Jobs.SingleOrDefault(job => job.JobId.Equals(jobId));
183      j.Slave = null;
184      CommitChanges();
185    }
186
187    public void SetJobOffline(JobDto job) {
188      Job j = Context.Jobs.SingleOrDefault(jq => jq.JobId.Equals(job.Id));
189      j.Slave = null;
190
191      var childJobs = Context.Jobs.Where(child => child.ParentJobId == j.JobId);
192
193      if (childJobs.Count() > 0) {
194        j.JobState = JobState.WaitForChildJobs.ToString();
195      } else {
196        j.JobState = JobState.Offline.ToString();
197      }
198
199      CommitChanges();
200    }
201
202    public Stream GetSerializedJobStream(Guid jobId) {
203      VarBinarySource source = new VarBinarySource((SqlConnection)Context.Connection, null, "Job", "SerializedJob", "JobId", jobId);
204      return new VarBinaryStream(source);
205    }
206
207    public IEnumerable<JobDto> FindJobsById(IEnumerable<Guid> jobIds) {
208      IQueryable<JobDto> jobs = from job in Context.Jobs
209                                where jobIds.Contains(job.JobId)
210                                select EntityToDto(job, null);
211      return jobs.ToList();
212    }
213
214    public bool IsUserAuthorizedForJobs(Guid userId, params Guid[] jobIds) {
215      var jobs = from job in Context.Jobs
216                 where jobIds.Contains(job.JobId)
217                 select job;
218      return jobs.All(job => job.UserId == userId);
219    }
220
221    public IEnumerable<JobDto> FindJobsByParentId(Guid? parentJobId, bool recursive) {
222      IQueryable<JobDto> query = from job in Context.Jobs
223                                 where parentJobId == null ? !job.ParentJobId.HasValue : job.ParentJobId.Value == parentJobId
224                                 select EntityToDto(job, null);
225      List<JobDto> jobs = query.ToList();
226      if (recursive) {
227        List<JobDto> childs = new List<JobDto>();
228        foreach (JobDto job in jobs) {
229          childs.AddRange(FindJobsByParentId(job.Id, recursive));
230        }
231        jobs.AddRange(childs);
232      }
233      return jobs;
234    }
235
236    #endregion
237
238    public override Job DtoToEntity(JobDto source, Job target) {
239      if (source == null)
240        return null;
241      if (target == null)
242        target = new Job();
243
244      target.CoresNeeded = source.CoresNeeded;
245      target.MemoryNeeded = source.MemoryNeeded;
246
247      target.DateCalculated = source.DateCalculated;
248      target.DateCreated = source.DateCreated;
249      target.DateFinished = source.DateFinished;
250      target.JobId = source.Id;
251
252      target.ExecutionTime = source.ExecutionTime.ToString();
253      target.Exception = source.Exception;
254
255      target.Priority = source.Priority;
256      target.JobState = Enum.GetName(typeof(JobState), source.State);
257      target.UserId = source.UserId;
258      target.ParentJobId = source.ParentJobId;
259     
260      foreach (Guid assignRessourceId in source.AssignedResourceIds) {
261        if (!target.AssignedResources.Select(x => x.ResourceId).Contains(assignRessourceId)) {
262          target.AssignedResources.Add(new AssignedResource { ResourceId = assignRessourceId });
263        }
264      }
265
266      return target;
267    }
268
269    //Slave is not used ATM - not sure when we stopped using those...
270    public override JobDto EntityToDto(Job source, JobDto target) {
271      if (source == null)
272        return null;
273      if (target == null)
274        target = new JobDto();
275
276      target.CoresNeeded = source.CoresNeeded;
277      target.MemoryNeeded = source.MemoryNeeded;
278
279      target.DateCalculated = source.DateCalculated;
280      target.DateCreated = source.DateCreated;
281      target.DateFinished = source.DateFinished;
282      target.Id = source.JobId;
283
284      target.Exception = source.Exception;
285      TimeSpan ts;
286      if (!TimeSpan.TryParse(source.ExecutionTime, out ts)) ts = TimeSpan.Zero;
287      target.ExecutionTime = ts;
288
289      target.Priority = source.Priority;
290      target.State = (JobState)Enum.Parse(typeof(JobState), source.JobState, true);
291      target.UserId = source.UserId;
292      target.ParentJobId = source.ParentJobId;
293     
294      target.AssignedResourceIds = source.AssignedResources.Select(x => x.ResourceId).ToList();
295
296      return target;
297    }
298  }
299}
Note: See TracBrowser for help on using the repository browser.