Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive-3.4/sources/HeuristicLab.Clients.Hive.Slave/3.4/HeartbeatManager.cs @ 5778

Last change on this file since 5778 was 5721, checked in by ascheibe, 13 years ago

#1233 worked on slave and slave service installer

File size: 5.1 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.Threading;
25using HeuristicLab.Common;
26
27namespace HeuristicLab.Clients.Hive.SlaveCore {
28  /// <summary>
29  /// Heartbeat class. It sends every x ms a heartbeat to the server and receives a Message
30  /// </summary>
31  public class HeartbeatManager {
32    private static object locker = new object();
33    public TimeSpan Interval { get; set; }
34    private Thread heartBeatThread;
35    private AutoResetEvent waitHandle;
36    private WcfService wcfService;
37    private bool threadStopped;
38    ReaderWriterLockSlim heartBeatThreadIsSleepingLock = new ReaderWriterLockSlim();
39
40    public HeartbeatManager() {
41      Interval = new TimeSpan(0, 0, 10);
42    }
43
44    public HeartbeatManager(TimeSpan interval) {
45      Interval = interval;
46    }
47
48    /// <summary>
49    /// Starts the Heartbeat signal.
50    /// </summary>
51    public void StartHeartbeat() {
52      this.waitHandle = new AutoResetEvent(true);
53      wcfService = WcfService.Instance;
54      threadStopped = false;
55      heartBeatThread = new Thread(RunHeartBeatThread);
56      heartBeatThread.Start();
57    }
58
59    /// <summary>
60    /// Stop the heartbeat
61    /// </summary>
62    public void StopHeartBeat() {
63      threadStopped = true;
64      waitHandle.Set();
65      heartBeatThread.Join();
66    }
67
68    /// <summary>
69    /// use this method to singalize there is work to do (to avoid the waiting period if its clear that actions are required)
70    /// </summary>
71    public void AwakeHeartBeatThread() {
72      if (!threadStopped)
73        waitHandle.Set();
74    }
75
76    private void RunHeartBeatThread() {
77      bool sleepForever;
78      while (!threadStopped) {
79        sleepForever = false;
80        try {
81          lock (locker) {
82            if (wcfService.ConnState != NetworkEnum.WcfConnState.Connected) {
83              wcfService.Connect(ConfigManager.Instance.GetClientInfo()); // Login happens automatically upon successfull connection
84            }
85            if (wcfService.ConnState == NetworkEnum.WcfConnState.Connected) {
86              Slave info = ConfigManager.Instance.GetClientInfo();
87
88              Heartbeat heartBeatData = new Heartbeat {
89                SlaveId = info.Id,
90                FreeCores = info.Cores.HasValue ? info.Cores.Value - ConfigManager.Instance.GetUsedCores() : 0,
91                FreeMemory = ConfigManager.GetFreeMemory(),
92                JobProgress = ConfigManager.Instance.GetExecutionTimeOfAllJobs(),
93                AssignJob = true //TODO: check if we want another job
94              };
95
96              SlaveClientCom.Instance.ClientCom.LogMessage("Sending Heartbeat: " + heartBeatData);
97              List<MessageContainer> msgs = wcfService.SendHeartbeat(heartBeatData);
98
99              if (msgs == null) {
100                SlaveClientCom.Instance.ClientCom.LogMessage("Error getting response from Heartbeat");
101                OnExceptionOccured(new Exception("Error getting response from Heartbeat"));
102              } else {
103                SlaveClientCom.Instance.ClientCom.LogMessage("Heartbeat Response received (" + msgs.Count + "): ");
104                msgs.ForEach(mc => SlaveClientCom.Instance.ClientCom.LogMessage(mc.Message.ToString()));
105                msgs.ForEach(mc => MessageQueue.GetInstance().AddMessage(mc));
106                //after fetching a job, we sleep until the core wakes us up!!
107                msgs.ForEach(s => { if (s.Message == MessageContainer.MessageType.CalculateJob) sleepForever = true; });
108              }
109            }
110          }
111        }
112        catch (Exception e) {
113          SlaveClientCom.Instance.ClientCom.LogMessage("Heartbeat Thread failed badly: " + e.Message);
114          OnExceptionOccured(e);
115        }
116        if (sleepForever)
117          waitHandle.WaitOne();
118        else
119          waitHandle.WaitOne(this.Interval);
120      }
121      waitHandle.Close();
122      SlaveClientCom.Instance.ClientCom.LogMessage("Heartbeat thread stopped");
123    }
124
125
126    #region Eventhandler
127    public event EventHandler<EventArgs<Exception>> ExceptionOccured;
128    private void OnExceptionOccured(Exception e) {
129      var handler = ExceptionOccured;
130      if (handler != null) handler(this, new EventArgs<Exception>(e));
131    }
132    #endregion
133  }
134}
Note: See TracBrowser for help on using the repository browser.