Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive/sources/HeuristicLab.Hive/HeuristicLab.Hive.Slave.Core/3.3/HeartbeatManager.cs @ 4550

Last change on this file since 4550 was 4424, checked in by cneumuel, 14 years ago
  • Added and updated License Information in every file
  • Sort and remove usings in every file
  • Deleted obsolete DataAccess.ADOHelper
  • Deleted some obsolete files
File size: 5.4 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.Hive.Contracts;
27using HeuristicLab.Hive.Contracts.BusinessObjects;
28using HeuristicLab.Hive.Slave.Common;
29using HeuristicLab.Hive.Slave.Communication;
30using HeuristicLab.Hive.Slave.Communication.SlaveFacade;
31using HeuristicLab.Hive.Slave.Core.ConfigurationManager;
32using HeuristicLab.Tracing;
33
34namespace HeuristicLab.Hive.Slave.Core {
35  /// <summary>
36  /// Heartbeat class. It sends every x ms a heartbeat to the server and receives a Message
37  /// </summary>
38  public class HeartbeatManager {
39    private static object locker = new object();
40    public TimeSpan Interval { get; set; }
41    private Thread heartBeatThread;
42    private AutoResetEvent waitHandle;
43
44    public HeartbeatManager() {
45      Interval = new TimeSpan(0, 0, 10);
46    }
47
48    public HeartbeatManager(TimeSpan interval) {
49      Interval = interval;
50    }
51
52    private WcfService wcfService;
53
54    private bool abortThreadPending;
55
56    ReaderWriterLockSlim heartBeatThreadIsSleepingLock = new ReaderWriterLockSlim();
57    private bool heartBeatThreadIsSleeping = false;
58
59    /// <summary>
60    /// Starts the Heartbeat signal.
61    /// </summary>
62    public void StartHeartbeat() {
63      this.waitHandle = new AutoResetEvent(true);
64      wcfService = WcfService.Instance;
65      wcfService.ProcessHeartBeatCompleted += new EventHandler<ProcessHeartBeatCompletedEventArgs>(wcfService_ProcessHeartBeatCompleted);
66      abortThreadPending = false;
67      heartBeatThread = new Thread(RunHeartBeatThread);
68      heartBeatThread.Start();
69    }
70
71    /// <summary>
72    /// Stop the heartbeat
73    /// </summary>
74    public void StopHeartBeat() {
75      abortThreadPending = true;
76      waitHandle.Set();
77      heartBeatThread.Join();
78    }
79   
80    /// <summary>
81    /// use this method to singalize there is work to do (to avoid the waiting period if its clear that actions are required)
82    /// </summary>
83    public void AwakeHeartBeatThread() {
84      waitHandle.Set();
85    }
86
87    private void RunHeartBeatThread() {
88      while (!abortThreadPending) {
89        try {
90          lock (locker) {
91            if (wcfService.ConnState != NetworkEnum.WcfConnState.Connected) {
92              wcfService.Connect(ConfigManager.Instance.GetClientInfo()); // Login happens automatically upon successufl connection
93            }
94            if(wcfService.ConnState == NetworkEnum.WcfConnState.Connected) {
95              SlaveDto info = ConfigManager.Instance.GetClientInfo();
96
97              HeartBeatData heartBeatData = new HeartBeatData {
98                SlaveId = info.Id,
99                FreeCores = info.NrOfCores.HasValue ? info.NrOfCores.Value - ConfigManager.Instance.GetUsedCores() : 0,
100                FreeMemory = GetFreeMemory(),
101                JobProgress = ConfigManager.Instance.GetExecutionTimeOfAllJobs(),
102                IsAllowedToCalculate = UptimeManager.Instance.IsAllowedToCalculate() && UptimeManager.Instance.CalendarAvailable
103              };
104
105              if (!heartBeatData.IsAllowedToCalculate) {
106                // stop all running jobs and send snapshots to server
107                MessageQueue.GetInstance().AddMessage(MessageContainer.MessageType.UptimeLimitDisconnect);
108              }
109
110              Logger.Debug("Sending Heartbeat: " + heartBeatData);
111              wcfService.ProcessHeartBeatSync(heartBeatData);
112            }
113          } // lock
114        }
115        catch (Exception e) {
116          Logger.Error("Heartbeat Thread failed badly: " + e.Message);
117          OnExceptionOccured(e);
118        }
119        waitHandle.WaitOne(this.Interval);
120      } // while
121      waitHandle.Close();
122      abortThreadPending = false;
123      Logger.Debug("Heartbeat thread stopped");
124    }
125
126    void wcfService_ProcessHeartBeatCompleted(object sender, ProcessHeartBeatCompletedEventArgs e) {
127      Logger.Debug("Heartbeat Response received");
128      e.Result.ActionRequest.ForEach(mc => MessageQueue.GetInstance().AddMessage(mc));
129    }
130
131    #region Eventhandler
132    public event EventHandler<EventArgs<Exception>> ExceptionOccured;
133    private void OnExceptionOccured(Exception e) {
134      var handler = ExceptionOccured;
135      if (handler != null) handler(this, new EventArgs<Exception>(e));
136    }
137    #endregion
138
139    #region Helpers
140    private int GetFreeMemory() {
141      PerformanceCounter counter = new PerformanceCounter("Memory", "Available Bytes", true);
142      int mb = (int)(counter.NextValue() / 1024 / 1024);
143      return mb;
144    }
145    #endregion
146  }
147}
Note: See TracBrowser for help on using the repository browser.