Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1233 slave ui now receives status information and displays it in doughnut chart

File size: 5.2 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        SlaveClientCom.Instance.ClientCom.StatusChanged(ConfigManager.Instance.GetStatusForClientConsole());
81
82        try {
83          lock (locker) {
84            if (wcfService.ConnState != NetworkEnum.WcfConnState.Connected) {
85              // login happens automatically upon successfull connection
86              wcfService.Connect(ConfigManager.Instance.GetClientInfo());
87              SlaveStatusInfo.LoginTime = DateTime.Now;
88            }
89            if (wcfService.ConnState == NetworkEnum.WcfConnState.Connected) {
90              Slave info = ConfigManager.Instance.GetClientInfo();
91
92              Heartbeat heartBeatData = new Heartbeat {
93                SlaveId = info.Id,
94                FreeCores = info.Cores.HasValue ? info.Cores.Value - ConfigManager.Instance.GetUsedCores() : 0,
95                FreeMemory = ConfigManager.GetFreeMemory(),
96                JobProgress = ConfigManager.Instance.GetExecutionTimeOfAllJobs(),
97                AssignJob = true //TODO: check if we want another job
98              };
99
100              SlaveClientCom.Instance.ClientCom.LogMessage("Sending Heartbeat: " + heartBeatData);
101              List<MessageContainer> msgs = wcfService.SendHeartbeat(heartBeatData);
102
103              if (msgs == null) {
104                SlaveClientCom.Instance.ClientCom.LogMessage("Error getting response from Heartbeat");
105                OnExceptionOccured(new Exception("Error getting response from Heartbeat"));
106              } else {
107                SlaveClientCom.Instance.ClientCom.LogMessage("Heartbeat Response received (" + msgs.Count + "): ");
108                msgs.ForEach(mc => SlaveClientCom.Instance.ClientCom.LogMessage(mc.Message.ToString()));
109                msgs.ForEach(mc => MessageQueue.GetInstance().AddMessage(mc));
110                //after fetching a job, we sleep until the core wakes us up!!
111                msgs.ForEach(s => { if (s.Message == MessageContainer.MessageType.CalculateJob) sleepForever = true; });
112              }
113            }
114          }
115        }
116        catch (Exception e) {
117          SlaveClientCom.Instance.ClientCom.LogMessage("Heartbeat thread failed: " + e.ToString());
118          OnExceptionOccured(e);
119        }
120        if (sleepForever)
121          waitHandle.WaitOne();
122        else
123          waitHandle.WaitOne(this.Interval);
124      }
125      waitHandle.Close();
126      SlaveClientCom.Instance.ClientCom.LogMessage("Heartbeat thread stopped");
127    }
128
129
130    #region Eventhandler
131    public event EventHandler<EventArgs<Exception>> ExceptionOccured;
132    private void OnExceptionOccured(Exception e) {
133      var handler = ExceptionOccured;
134      if (handler != null) handler(this, new EventArgs<Exception>(e));
135    }
136    #endregion
137  }
138}
Note: See TracBrowser for help on using the repository browser.