Free cookie consent management tool by TermsFeed Policy Generator

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

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

ported most of the slave code to 3.4 #1233

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.Diagnostics;
24using System.Threading;
25using HeuristicLab.Common;
26using HeuristicLab.Clients.Hive.Salve;
27using HeuristicLab.Services.Hive.Common.DataTransfer;
28using HeuristicLab.Services.Hive.Common;
29using System.Collections.Generic;
30
31namespace HeuristicLab.Clients.Hive.Salve {
32  /// <summary>
33  /// Heartbeat class. It sends every x ms a heartbeat to the server and receives a Message
34  /// </summary>
35  public class HeartbeatManager {
36    private static object locker = new object();
37    public TimeSpan Interval { get; set; }
38    private Thread heartBeatThread;
39    private AutoResetEvent waitHandle;
40
41    public HeartbeatManager() {
42      Interval = new TimeSpan(0, 0, 10);
43    }
44
45    public HeartbeatManager(TimeSpan interval) {
46      Interval = interval;
47    }
48
49    private WcfService wcfService;
50
51    private bool abortThreadPending;
52
53    ReaderWriterLockSlim heartBeatThreadIsSleepingLock = new ReaderWriterLockSlim();
54   
55    /// <summary>
56    /// Starts the Heartbeat signal.
57    /// </summary>
58    public void StartHeartbeat() {
59      this.waitHandle = new AutoResetEvent(true);
60      wcfService = WcfService.Instance;     
61      abortThreadPending = false;
62      heartBeatThread = new Thread(RunHeartBeatThread);
63      heartBeatThread.Start();
64    }
65
66    /// <summary>
67    /// Stop the heartbeat
68    /// </summary>
69    public void StopHeartBeat() {
70      abortThreadPending = true;
71      waitHandle.Set();
72      heartBeatThread.Join();
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      waitHandle.Set();
80    }
81
82    private void RunHeartBeatThread() {
83      while (!abortThreadPending) {
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              {
94                SlaveId = info.Id,
95                FreeCores = info.Cores.HasValue ? info.Cores.Value - ConfigManager.Instance.GetUsedCores() : 0,
96                FreeMemory = GetFreeMemory(),
97                JobProgress = ConfigManager.Instance.GetExecutionTimeOfAllJobs()               
98              };
99                             
100              Logger.Debug("Sending Heartbeat: " + heartBeatData);
101              List<MessageContainer> msgs =  wcfService.SendHeartbeat(heartBeatData);
102             
103              if (msgs == null) {
104                Logger.Debug("Error getting response from Heartbeat");
105                OnExceptionOccured(new Exception("Error getting response from Heartbeat"));
106              }
107
108              Logger.Debug("Heartbeat Response received: ");
109              msgs.ForEach(mc => Logger.Debug(mc.Message.ToString()));
110              msgs.ForEach(mc => MessageQueue.GetInstance().AddMessage(mc));     
111            }
112          } // lock
113        }
114        catch (Exception e) {
115          Logger.Error("Heartbeat Thread failed badly: " + e.Message);
116          OnExceptionOccured(e);
117        }
118        waitHandle.WaitOne(this.Interval);
119      } // while
120      waitHandle.Close();
121      abortThreadPending = false;
122      Logger.Debug("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    #region Helpers
135    private int GetFreeMemory() {
136      PerformanceCounter counter = new PerformanceCounter("Memory", "Available Bytes", true);
137      int mb = (int)(counter.NextValue() / 1024 / 1024);
138      return mb;
139    }
140    #endregion
141  }
142}
Note: See TracBrowser for help on using the repository browser.