Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1233

  • Implemented communication interface between Slave and a Slave Client using Named Pipes and callbacks
  • Added new project for testing Slave - Client communication
  • Added some copyright info headers
File size: 5.0 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.Diagnostics;
25using System.Threading;
26using HeuristicLab.Common;
27using HeuristicLab.Services.Hive.Common;
28using HeuristicLab.Services.Hive.Common.DataTransfer;
29
30namespace HeuristicLab.Clients.Hive.Salve {
31  /// <summary>
32  /// Heartbeat class. It sends every x ms a heartbeat to the server and receives a Message
33  /// </summary>
34  public class HeartbeatManager {
35    private static object locker = new object();
36    public TimeSpan Interval { get; set; }
37    private Thread heartBeatThread;
38    private AutoResetEvent waitHandle;
39
40    public HeartbeatManager() {
41      Interval = new TimeSpan(0, 0, 10);
42    }
43
44    public HeartbeatManager(TimeSpan interval) {
45      Interval = interval;
46    }
47
48    private WcfService wcfService;
49
50    private bool threadStopped;
51
52    ReaderWriterLockSlim heartBeatThreadIsSleepingLock = new ReaderWriterLockSlim();
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          lock (locker) {
86            if (wcfService.ConnState != NetworkEnum.WcfConnState.Connected) {
87              wcfService.Connect(ConfigManager.Instance.GetClientInfo()); // Login happens automatically upon successfull connection
88            }
89            if (wcfService.ConnState == NetworkEnum.WcfConnState.Connected) {
90              HeuristicLab.Services.Hive.Common.DataTransfer.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 = GetFreeMemory(),
96                JobProgress = ConfigManager.Instance.GetExecutionTimeOfAllJobs()
97              };
98
99              SlaveClientCom.Instance.ClientCom.LogMessage("Sending Heartbeat: " + heartBeatData);
100              List<MessageContainer> msgs = wcfService.SendHeartbeat(heartBeatData);
101
102              if (msgs == null) {
103                SlaveClientCom.Instance.ClientCom.LogMessage("Error getting response from Heartbeat");
104                OnExceptionOccured(new Exception("Error getting response from Heartbeat"));
105              }
106
107              SlaveClientCom.Instance.ClientCom.LogMessage("Heartbeat Response received: ");
108              msgs.ForEach(mc => SlaveClientCom.Instance.ClientCom.LogMessage(mc.Message.ToString()));
109              msgs.ForEach(mc => MessageQueue.GetInstance().AddMessage(mc));
110            }
111          }
112        }
113        catch (Exception e) {
114          SlaveClientCom.Instance.ClientCom.LogMessage("Heartbeat Thread failed badly: " + e.Message);
115          OnExceptionOccured(e);
116        }
117        waitHandle.WaitOne(this.Interval);
118      }
119      waitHandle.Close();
120      SlaveClientCom.Instance.ClientCom.LogMessage("Heartbeat thread stopped");
121    }
122
123
124    #region Eventhandler
125    public event EventHandler<EventArgs<Exception>> ExceptionOccured;
126    private void OnExceptionOccured(Exception e) {
127      var handler = ExceptionOccured;
128      if (handler != null) handler(this, new EventArgs<Exception>(e));
129    }
130    #endregion
131
132    #region Helpers
133    private int GetFreeMemory() {
134      PerformanceCounter counter = new PerformanceCounter("Memory", "Available Bytes", true);
135      int mb = (int)(counter.NextValue() / 1024 / 1024);
136      return mb;
137    }
138    #endregion
139  }
140}
Note: See TracBrowser for help on using the repository browser.