Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HiveStatistics/sources/HeuristicLab.Services.Hive/3.3/Manager/NewHeartbeatManager.cs @ 12773

Last change on this file since 12773 was 12773, checked in by dglaser, 9 years ago

#2388:

HeuristicLab.Services.WebApp-3.3:

  • The font is now loaded properly even when accessing the page over https
  • Added no-cache to the index page
  • Added no-cache to the views in addition to the existing (datetime) cache buster
    • Caching can be enabled when required

HeuristicLab.Services.Hive-3.3:

  • Improved performance of NewHeartbeatManager by adding an additional check if the collection is empty

HeuristicLab.Services.WebApp.Statistics-3.3:

  • Removed invalid link from the exception page

Projects:

  • Added the '-3.3' affix to the assembly names
File size: 9.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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.Threading;
26using HeuristicLab.Services.Hive.DataAccess;
27using HeuristicLab.Services.Hive.DataAccess.Interfaces;
28using HeuristicLab.Services.Hive.DataTransfer;
29using DA = HeuristicLab.Services.Hive.DataAccess;
30
31namespace HeuristicLab.Services.Hive.Manager {
32  public class NewHeartbeatManager {
33    private const string MutexName = "HiveTaskSchedulingMutex";
34
35    private IPersistenceManager PersistenceManager {
36      get { return ServiceLocator.Instance.PersistenceManager; }
37    }
38
39    private ITaskScheduler TaskScheduler {
40      get { return ServiceLocator.Instance.NewTaskScheduler; }
41    }
42
43    /// <summary>
44    /// This method will be called every time a slave sends a heartbeat (-> very often; concurrency is important!)
45    /// </summary>
46    /// <returns>a list of actions the slave should do</returns>
47    public List<MessageContainer> ProcessHeartbeat(Heartbeat heartbeat) {
48      List<MessageContainer> actions = new List<MessageContainer>();
49      using (var pm = PersistenceManager) {
50        var slaveDao = pm.SlaveDao;
51        var taskDao = pm.TaskDao;
52        var slave = pm.UseTransaction(() => slaveDao.GetById(heartbeat.SlaveId));
53        if (slave == null) {
54          actions.Add(new MessageContainer(MessageContainer.MessageType.SayHello));
55        } else {
56          if (heartbeat.HbInterval != slave.HbInterval) {
57            actions.Add(new MessageContainer(MessageContainer.MessageType.NewHBInterval));
58          }
59          if (slaveDao.SlaveHasToShutdownComputer(slave.ResourceId)) {
60            actions.Add(new MessageContainer(MessageContainer.MessageType.ShutdownComputer));
61          }
62          // update slave data 
63          slave.FreeCores = heartbeat.FreeCores;
64          slave.FreeMemory = heartbeat.FreeMemory;
65          slave.CpuUtilization = heartbeat.CpuUtilization;
66          slave.SlaveState = (heartbeat.JobProgress != null && heartbeat.JobProgress.Count > 0)
67            ? DA.SlaveState.Calculating
68            : DA.SlaveState.Idle;
69          slave.LastHeartbeat = DateTime.Now;
70          pm.UseTransaction(() => {
71            slave.IsAllowedToCalculate = slaveDao.SlaveIsAllowedToCalculate(slave.ResourceId);
72            pm.SubmitChanges();
73          });
74
75          // update task data
76          actions.AddRange(UpdateTasks(pm, heartbeat, slave.IsAllowedToCalculate));
77
78          // assign new task
79          if (heartbeat.AssignJob && slave.IsAllowedToCalculate && heartbeat.FreeCores > 0) {
80            bool mutexAquired = false;
81            var mutex = new Mutex(false, MutexName);
82            try {
83              mutexAquired = mutex.WaitOne(Properties.Settings.Default.SchedulingPatience);
84              if (mutexAquired) {
85                var waitingTasks = pm.UseTransaction(() => taskDao.GetWaitingTasks(slave)
86                    .Select(x => new TaskInfoForScheduler {
87                      TaskId = x.TaskId,
88                      JobId = x.JobId,
89                      Priority = x.Priority
90                    })
91                    .ToList()
92                );
93                var availableTasks = TaskScheduler.Schedule(waitingTasks);
94                if (availableTasks.Any()) {
95                  var task = availableTasks.First();
96                  AssignTask(pm, slave, task.TaskId);
97                  actions.Add(new MessageContainer(MessageContainer.MessageType.CalculateTask, task.TaskId));
98                }
99              } else {
100                LogFactory.GetLogger(this.GetType().Namespace).Log("HeartbeatManager: The mutex used for scheduling could not be aquired.");
101              }
102            }
103            catch (AbandonedMutexException) {
104              LogFactory.GetLogger(this.GetType().Namespace).Log("HeartbeatManager: The mutex used for scheduling has been abandoned.");
105            }
106            catch (Exception ex) {
107              LogFactory.GetLogger(this.GetType().Namespace).Log(string.Format("HeartbeatManager threw an exception in ProcessHeartbeat: {0}", ex));
108            }
109            finally {
110              if (mutexAquired) mutex.ReleaseMutex();
111            }
112          }
113        }
114      }
115      return actions;
116    }
117
118    private void AssignTask(IPersistenceManager pm, DA.Slave slave, Guid taskId) {
119      const DA.TaskState transferring = DA.TaskState.Transferring;
120      DateTime now = DateTime.Now;
121      var taskDao = pm.TaskDao;
122      var stateLogDao = pm.StateLogDao;
123      pm.UseTransaction(() => {
124        var task = taskDao.GetById(taskId);
125        stateLogDao.Save(new DA.StateLog {
126          State = transferring,
127          DateTime = now,
128          TaskId = taskId,
129          SlaveId = slave.ResourceId,
130          UserId = null,
131          Exception = null
132        });
133        task.State = transferring;
134        task.LastHeartbeat = now;
135        pm.SubmitChanges();
136      });
137    }
138
139    /// <summary>
140    /// Update the progress of each task
141    /// Checks if all the task sent by heartbeat are supposed to be calculated by this slave
142    /// </summary>
143    private IEnumerable<MessageContainer> UpdateTasks(IPersistenceManager pm, Heartbeat heartbeat, bool isAllowedToCalculate) {
144      var taskDao = pm.TaskDao;
145      var assignedResourceDao = pm.AssignedResourceDao;
146      var actions = new List<MessageContainer>();
147      if (heartbeat.JobProgress == null || !heartbeat.JobProgress.Any())
148        return actions;
149
150      if (!isAllowedToCalculate && heartbeat.JobProgress.Count != 0) {
151        actions.Add(new MessageContainer(MessageContainer.MessageType.PauseAll));
152      } else {
153        // select all tasks and statelogs with one query
154        var taskIds = heartbeat.JobProgress.Select(x => x.Key).ToList();
155        var taskInfos = pm.UseTransaction(() =>
156          (from task in taskDao.GetAll()
157           where taskIds.Contains(task.TaskId)
158           let lastStateLog = task.StateLogs.OrderByDescending(x => x.DateTime).FirstOrDefault()
159           select new {
160             TaskId = task.TaskId,
161             Command = task.Command,
162             SlaveId = lastStateLog != null ? lastStateLog.SlaveId : default(Guid)
163           }).ToList()
164        );
165
166        // process the jobProgresses
167        foreach (var jobProgress in heartbeat.JobProgress) {
168          var progress = jobProgress;
169          var curTask = taskInfos.SingleOrDefault(x => x.TaskId == progress.Key);
170          if (curTask == null) {
171            actions.Add(new MessageContainer(MessageContainer.MessageType.AbortTask, progress.Key));
172            LogFactory.GetLogger(this.GetType().Namespace).Log("Task on slave " + heartbeat.SlaveId + " does not exist in DB: " + jobProgress.Key);
173          } else {
174            var slaveId = curTask.SlaveId;
175            if (slaveId == Guid.Empty || slaveId != heartbeat.SlaveId) {
176              // assigned slave does not match heartbeat
177              actions.Add(new MessageContainer(MessageContainer.MessageType.AbortTask, curTask.TaskId));
178              LogFactory.GetLogger(this.GetType().Namespace).Log("The slave " + heartbeat.SlaveId + " is not supposed to calculate task: " + curTask.TaskId);
179            } else if (!assignedResourceDao.TaskIsAllowedToBeCalculatedBySlave(curTask.TaskId, heartbeat.SlaveId)) {
180              // assigned resources ids of task do not match with slaveId (and parent resourceGroupIds); this might happen when slave is moved to different group
181              actions.Add(new MessageContainer(MessageContainer.MessageType.PauseTask, curTask.TaskId));
182            } else {
183              // update task execution time
184              pm.UseTransaction(() => {
185                taskDao.UpdateExecutionTime(curTask.TaskId, progress.Value.TotalMilliseconds);
186              });
187              switch (curTask.Command) {
188                case DA.Command.Stop:
189                  actions.Add(new MessageContainer(MessageContainer.MessageType.StopTask, curTask.TaskId));
190                  break;
191                case DA.Command.Pause:
192                  actions.Add(new MessageContainer(MessageContainer.MessageType.PauseTask, curTask.TaskId));
193                  break;
194                case DA.Command.Abort:
195                  actions.Add(new MessageContainer(MessageContainer.MessageType.AbortTask, curTask.TaskId));
196                  break;
197              }
198            }
199          }
200        }
201      }
202      return actions;
203    }
204  }
205}
Note: See TracBrowser for help on using the repository browser.