Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.TimeSeries/HeuristicLab.Clients.Hive.Slave/3.3/Manager/HeartbeatManager.cs @ 7383

Last change on this file since 7383 was 7268, checked in by gkronber, 13 years ago

#1081: merged r7214:7266 from trunk into time series branch.

File size: 5.3 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    }
73
74    /// <summary>
75    /// use this method to singalize there is work to do (to avoid the waiting period if its clear that actions are required)
76    /// </summary>
77    public void AwakeHeartBeatThread() {
78      if (!threadStopped)
79        waitHandle.Set();
80    }
81
82    private void RunHeartBeatThread() {
83      while (!threadStopped) {
84        try {
85          SlaveClientCom.Instance.StatusChanged(ConfigManager.Instance.GetStatusForClientConsole());
86        }
87        catch (Exception ex) {
88          EventLogManager.LogMessage("Couldn't sent status information to client ui. Exception is: " + Environment.NewLine + ex.ToString());
89        }
90
91        try {
92          lock (locker) {
93            if (wcfService.ConnState != NetworkEnum.WcfConnState.Connected) {
94              // login happens automatically upon successfull connection
95              wcfService.Connect(ConfigManager.Instance.GetClientInfo());
96              SlaveStatusInfo.LoginTime = DateTime.Now;
97            }
98            if (wcfService.ConnState == NetworkEnum.WcfConnState.Connected) {
99              Slave info = ConfigManager.Instance.GetClientInfo();
100
101              Heartbeat heartBeatData = new Heartbeat {
102                SlaveId = info.Id,
103                FreeCores = info.Cores.HasValue ? info.Cores.Value - SlaveStatusInfo.UsedCores : 0,
104                FreeMemory = ConfigManager.Instance.GetFreeMemory(),
105                CpuUtilization = ConfigManager.Instance.GetCpuUtilization(),
106                JobProgress = ConfigManager.Instance.GetExecutionTimeOfAllJobs(),
107                AssignJob = !ConfigManager.Instance.Asleep,
108                HbInterval = (int)interval.TotalSeconds
109              };
110
111              SlaveClientCom.Instance.LogMessage("Send HB: " + heartBeatData);
112              List<MessageContainer> msgs = wcfService.SendHeartbeat(heartBeatData);
113
114              if (msgs == null) {
115                SlaveClientCom.Instance.LogMessage("Error getting response from HB");
116                OnExceptionOccured(new Exception("Error getting response from HB"));
117              } else {
118                SlaveClientCom.Instance.LogMessage("HB Response received (" + msgs.Count + "): ");
119                msgs.ForEach(mc => SlaveClientCom.Instance.LogMessage(mc.Message.ToString()));
120                msgs.ForEach(mc => MessageQueue.GetInstance().AddMessage(mc));
121              }
122            }
123          }
124        }
125        catch (Exception e) {
126          SlaveClientCom.Instance.LogMessage("Heartbeat thread failed: " + e.ToString());
127          OnExceptionOccured(e);
128        }
129        waitHandle.WaitOne(this.interval);
130      }
131      waitHandle.Close();
132      SlaveClientCom.Instance.LogMessage("Heartbeat thread stopped");
133    }
134
135    #region Eventhandler
136    public event EventHandler<EventArgs<Exception>> ExceptionOccured;
137    private void OnExceptionOccured(Exception e) {
138      var handler = ExceptionOccured;
139      if (handler != null) handler(this, new EventArgs<Exception>(e));
140    }
141    #endregion
142  }
143}
Note: See TracBrowser for help on using the repository browser.