Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HivePerformance/sources/HeuristicLab.Clients.Hive.Slave/3.3/Manager/HeartbeatManager.cs @ 9394

Last change on this file since 9394 was 9394, checked in by pfleck, 11 years ago

#2030
Fixed amespace bug in ConfigFile.
Disabled OutOfCoreExeption and OutOfMemoryException for MultiSlave-testing.
Added random waiting time for HartbeatManager to start to avoid simultaneously heartbeats for MultiSlave-testing.

File size: 5.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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.Clients.Hive.SlaveCore.Properties;
26using HeuristicLab.Common;
27
28namespace HeuristicLab.Clients.Hive.SlaveCore {
29  /// <summary>
30  /// Heartbeat Manager sends every x ms a heartbeat to the server and receives a message.
31  /// The message is added to the MessageQueue from where the Core pulls them and decides what to do.
32  /// </summary>
33  public class HeartbeatManager {
34    private static object locker = new object();
35    private TimeSpan interval;
36
37    public TimeSpan Interval {
38      get { return interval; }
39      set {
40        interval = value;
41        Settings.Default.HeartbeatInterval = interval;
42        Settings.Default.Save();
43      }
44    }
45    private Thread heartBeatThread;
46    private AutoResetEvent waitHandle;
47    private WcfService wcfService;
48    private bool threadStopped;
49
50    public HeartbeatManager() {
51      interval = Settings.Default.HeartbeatInterval;
52    }
53
54    /// <summary>
55    /// Starts the Heartbeat signal.
56    /// </summary>
57    public void StartHeartbeat() {
58      this.waitHandle = new AutoResetEvent(true);
59      wcfService = WcfService.Instance;
60      threadStopped = false;
61      heartBeatThread = new Thread(RunHeartBeatThread);
62      heartBeatThread.Start();
63    }
64
65    /// <summary>
66    /// Stop the heartbeat
67    /// </summary>
68    public void StopHeartBeat() {
69      threadStopped = true;
70      waitHandle.Set();
71      heartBeatThread.Join();
72      waitHandle.Close();
73    }
74
75    /// <summary>
76    /// use this method to singalize there is work to do (to avoid the waiting period if its clear that actions are required)
77    /// </summary>
78    public void AwakeHeartBeatThread() {
79      if (!threadStopped)
80        waitHandle.Set();
81    }
82
83    private void RunHeartBeatThread() {
84      Thread.Sleep(new Random().Next((int)Interval.TotalMilliseconds));
85
86      while (!threadStopped) {
87        try {
88          SlaveClientCom.Instance.StatusChanged(ConfigManager.Instance.GetStatusForClientConsole());
89        }
90        catch (Exception ex) {
91          EventLogManager.LogMessage("Couldn't sent status information to client ui. Exception is: " + Environment.NewLine + ex.ToString());
92        }
93
94        try {
95          lock (locker) {
96            if (wcfService.ConnState != NetworkEnum.WcfConnState.Connected) {
97              // login happens automatically upon successfull connection
98              wcfService.Connect(ConfigManager.Instance.GetClientInfo());
99              SlaveStatusInfo.LoginTime = DateTime.Now;
100            }
101            if (wcfService.ConnState == NetworkEnum.WcfConnState.Connected) {
102              Slave info = ConfigManager.Instance.GetClientInfo();
103
104              Heartbeat heartBeatData = new Heartbeat {
105                SlaveId = info.Id,
106                FreeCores = info.Cores.HasValue ? info.Cores.Value - SlaveStatusInfo.UsedCores : 0,
107                FreeMemory = ConfigManager.Instance.GetFreeMemory(),
108                CpuUtilization = ConfigManager.Instance.GetCpuUtilization(),
109                JobProgress = ConfigManager.Instance.GetExecutionTimeOfAllJobs(),
110                AssignJob = !ConfigManager.Instance.Asleep,
111                HbInterval = (int)interval.TotalSeconds
112              };
113
114              SlaveClientCom.Instance.LogMessage("Send HB: " + heartBeatData);
115              List<MessageContainer> msgs = wcfService.SendHeartbeat(heartBeatData);
116
117              if (msgs == null) {
118                SlaveClientCom.Instance.LogMessage("Error getting response from HB");
119                OnExceptionOccured(new Exception("Error getting response from HB"));
120              } else {
121                SlaveClientCom.Instance.LogMessage("HB Response received (" + msgs.Count + "): ");
122                msgs.ForEach(mc => SlaveClientCom.Instance.LogMessage(mc.Message.ToString()));
123                msgs.ForEach(mc => MessageQueue.GetInstance().AddMessage(mc));
124              }
125            }
126          }
127        }
128        catch (Exception e) {
129          SlaveClientCom.Instance.LogMessage("Heartbeat thread failed: " + e.ToString());
130          OnExceptionOccured(e);
131        }
132        waitHandle.WaitOne(this.interval);
133      }
134      SlaveClientCom.Instance.LogMessage("Heartbeat thread stopped");
135    }
136
137    #region Eventhandler
138    public event EventHandler<EventArgs<Exception>> ExceptionOccured;
139    private void OnExceptionOccured(Exception e) {
140      var handler = ExceptionOccured;
141      if (handler != null) handler(this, new EventArgs<Exception>(e));
142    }
143    #endregion
144  }
145}
Note: See TracBrowser for help on using the repository browser.