Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3.3-HiveMigration/sources/HeuristicLab.Hive/HeuristicLab.Hive.Slave.Core/3.3/HeartbeatManager.cs @ 4337

Last change on this file since 4337 was 4337, checked in by cneumuel, 14 years ago

changed Slave.Core WCF-Proxy to stateless object

File size: 6.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2008 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.Linq;
25using System.Text;
26using System.Timers;
27using HeuristicLab.Hive.Slave.Common;
28using HeuristicLab.Hive.Slave.Communication;
29using System.Diagnostics;
30using HeuristicLab.Hive.Contracts.BusinessObjects;
31using HeuristicLab.Hive.Contracts;
32using HeuristicLab.Hive.Slave.Core.ConfigurationManager;
33using HeuristicLab.Tracing;
34using System.Threading;
35using HeuristicLab.Hive.Slave.Communication.SlaveService;
36
37namespace HeuristicLab.Hive.Slave.Core {
38  /// <summary>
39  /// Heartbeat class. It sends every x ms a heartbeat to the server and receives a Message
40  /// </summary>
41  public class HeartbeatManager {
42
43    private bool offline;
44
45    public TimeSpan Interval { get; set; }
46
47    private Thread heartBeatThread;
48
49    private static object locker = new object();
50
51    public HeartbeatManager() {
52      Interval = new TimeSpan(0,0,10);
53    }
54
55    public HeartbeatManager(TimeSpan interval) {
56      Interval = interval;
57    }
58
59    private WcfService wcfService;
60
61    private bool abortThreadPending;
62
63    ReaderWriterLockSlim heartBeatThreadIsSleepingLock = new ReaderWriterLockSlim();
64    private bool heartBeatThreadIsSleeping = false;
65
66    /// <summary>
67    /// Starts the Heartbeat signal.
68    /// </summary>
69    public void StartHeartbeat() {
70      wcfService = WcfService.Instance;
71      wcfService.ProcessHeartBeatCompleted += new EventHandler<ProcessHeartBeatCompletedEventArgs>(wcfService_ProcessHeartBeatCompleted);
72      abortThreadPending = false;
73      heartBeatThread = GetHeartBeatThread();
74      heartBeatThread.Start();
75    }
76
77    private Thread GetHeartBeatThread() {
78      return new Thread(() => {
79        while (!abortThreadPending) {
80          try {
81            lock (locker) {
82              if (wcfService.ConnState != NetworkEnum.WcfConnState.Connected) {
83                wcfService.Connect(); // Login happens automatically upon successufl connection
84              }
85              if (!wcfService.LoggedIn) {
86                wcfService.Login(ConfigManager.Instance.GetClientInfo()); // if login faild previously try again
87              }
88
89              if (wcfService.LoggedIn) {
90                SlaveDto info = ConfigManager.Instance.GetClientInfo();
91
92                HeartBeatData heartBeatData = new HeartBeatData {
93                  SlaveId = info.Id,
94                  FreeCores = info.NrOfCores - ConfigManager.Instance.GetUsedCores(),
95                  FreeMemory = GetFreeMemory(),
96                  JobProgress = ConfigManager.Instance.GetProgressOfAllJobs(),
97                  IsAllowedToCalculate = UptimeManager.Instance.IsAllowedToCalculate() && UptimeManager.Instance.CalendarAvailable
98                };
99
100                if (!heartBeatData.IsAllowedToCalculate) {
101                  // stop all running jobs and send snapshots to server
102                  MessageQueue.GetInstance().AddMessage(MessageContainer.MessageType.UptimeLimitDisconnect);
103                }
104
105                Logger.Debug("Sending Heartbeat: " + heartBeatData);
106                wcfService.ProcessHeartBeatAsync(heartBeatData);
107              }
108
109            } // lock
110            try {
111              heartBeatThreadIsSleepingLock.EnterWriteLock();
112              heartBeatThreadIsSleeping = true;
113              heartBeatThreadIsSleepingLock.ExitWriteLock();
114
115              Thread.Sleep(Interval);
116
117              heartBeatThreadIsSleepingLock.EnterWriteLock();
118              heartBeatThreadIsSleeping = false;
119              heartBeatThreadIsSleepingLock.ExitWriteLock();
120            }
121            catch (ThreadInterruptedException e) {
122              Logger.Debug("Heartbeat sleep interrupted");
123            }
124          }
125          catch (Exception e) {
126            Logger.Error("Heartbeat Thread failed badly: " + e.Message);
127          }
128        } // while
129        abortThreadPending = false;
130        Logger.Debug("Heartbeat thread stopped");
131      });
132    }
133
134    private int GetFreeMemory() {
135      PerformanceCounter counter = new PerformanceCounter("Memory", "Available Bytes", true);
136      int mb = (int)(counter.NextValue() / 1024 / 1024);
137      return mb;
138    }
139
140    void wcfService_ProcessHeartBeatCompleted(object sender, ProcessHeartBeatCompletedEventArgs e) {
141      Logger.Debug("Heartbeat Response received");
142      e.Result.ActionRequest.ForEach(mc => MessageQueue.GetInstance().AddMessage(mc));
143    }
144
145    public void StopHeartBeat() {
146      abortThreadPending = true;
147      heartBeatThread.Interrupt();
148      heartBeatThread.Join();
149    }
150
151    /// <summary>
152    /// use this method to singalize there is work to do (to avoid the waiting period if its clear that actions are required)
153    /// </summary>
154    public void InterruptHeartBeatThread() {
155      // deal with ReadWriteLock to avoid interrupting the thread while it is in SleepOrWait due to another reason (like waiting for a resource in a lock-statement)
156      heartBeatThreadIsSleepingLock.EnterReadLock();
157      Debug.WriteLine("InterruptHeartBeatThread");
158      if (heartBeatThreadIsSleeping) {
159        Debug.WriteLine("will interrupt heartbeatthread");
160        heartBeatThread.Interrupt();
161      } else {
162        Debug.WriteLine("will not interrupt heartbeatthread");
163      }
164      heartBeatThreadIsSleepingLock.ExitReadLock();
165    }
166  }
167}
Note: See TracBrowser for help on using the repository browser.