Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Clients.Hive.Slave/3.3/Manager/ConfigManager.cs @ 8679

Last change on this file since 8679 was 7857, checked in by jkarder, 12 years ago

#1854:

  • integrated marker attribute (IsDisposable) into the Hive components
  • adjusted database scheme
  • extended administration user interface
File size: 9.0 KB
RevLine 
[6983]1#region License Information
2/* HeuristicLab
[7259]3 * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[6983]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.Linq;
26using System.Management;
27using HeuristicLab.Clients.Hive.SlaveCore.Properties;
28
29
30namespace HeuristicLab.Clients.Hive.SlaveCore {
31  /// <summary>
32  /// accesses the server and sends his data (uuid, uptimes, hardware config)
33  /// </summary>
34  public class ConfigManager {
35    private static ConfigManager instance = null;
36    public static ConfigManager Instance {
37      get { return instance; }
38      set { instance = value; }
39    }
40
41    /// <summary>
42    /// if Asleep is true, the Slave won't accept any new jobs
43    /// </summary>
44    public bool Asleep { get; set; }
45    private TaskManager jobManager;
46    private Slave slave;
47    private PerformanceCounter cpuCounter;
48    private PerformanceCounter memCounter;
49
50    /// <summary>
51    /// Constructor for the singleton, must recover Guid, Calendar, ...
52    /// </summary>
53    public ConfigManager(TaskManager jobManager) {
54      this.jobManager = jobManager;
55      cpuCounter = new PerformanceCounter();
56      cpuCounter.CategoryName = "Processor";
57      cpuCounter.CounterName = "% Processor Time";
58      cpuCounter.InstanceName = "_Total";
59      memCounter = new PerformanceCounter("Memory", "Available Bytes", true);
60
61      Asleep = false;
62      slave = new Slave();
63      slave.Id = GetUniqueMachineId();
64      slave.Name = Environment.MachineName;
[7777]65      if (Settings.Default.NrOfCoresToScavenge < 1 || Settings.Default.NrOfCoresToScavenge > Environment.ProcessorCount) {
66        slave.Cores = Environment.ProcessorCount;
67      } else {
68        slave.Cores = Settings.Default.NrOfCoresToScavenge;
69      }
[6983]70      slave.Memory = GetPhysicalMemory();
71      slave.CpuArchitecture = Environment.Is64BitOperatingSystem ? CpuArchitecture.x64 : CpuArchitecture.x86;
72      slave.OperatingSystem = Environment.OSVersion.VersionString;
73      slave.CpuSpeed = GetCpuSpeed();
[7857]74      slave.IsDisposable = true;
[6983]75
76      UpdateSlaveInfo();
77    }
78
79    private void UpdateSlaveInfo() {
80      if (slave != null) {
81        slave.FreeMemory = GetFreeMemory();
82        slave.HbInterval = (int)Settings.Default.HeartbeatInterval.TotalSeconds;
83      }
84    }
85
86    /// <summary>
87    /// Get all the Information about the client
88    /// </summary>
89    /// <returns>the ClientInfo object</returns>
90    public Slave GetClientInfo() {
91      UpdateSlaveInfo();
92      return slave;
93    }
94
95    public int GetFreeCores() {
96      return slave.Cores.HasValue ? slave.Cores.Value - SlaveStatusInfo.UsedCores : 0;
97    }
98
99    /// <summary>
100    /// collects and returns information that get displayed by the Client Console
101    /// </summary>
102    /// <returns></returns>
103    public StatusCommons GetStatusForClientConsole() {
104      StatusCommons st = new StatusCommons();
105      st.ClientGuid = slave.Id;
106
107      st.Status = WcfService.Instance.ConnState;
108      st.ConnectedSince = WcfService.Instance.ConnectedSince;
109
110      st.TotalCores = slave.Cores.HasValue ? slave.Cores.Value : 0;
111      st.FreeCores = GetFreeCores();
112      st.Asleep = this.Asleep;
113
114      st.JobsStarted = SlaveStatusInfo.TasksStarted;
115      st.JobsAborted = SlaveStatusInfo.TasksAborted;
116      st.JobsFinished = SlaveStatusInfo.TasksFinished;
117      st.JobsFetched = SlaveStatusInfo.TasksFetched;
118      st.JobsFailed = SlaveStatusInfo.TasksFailed;
119      st.ExceptionsOccured = SlaveStatusInfo.ExceptionsOccured;
120
121      st.Jobs = jobManager.GetExecutionTimes().Select(x => new TaskStatus { TaskId = x.Key, ExecutionTime = x.Value }).ToList();
122
123      return st;
124    }
125
126    public Dictionary<Guid, TimeSpan> GetExecutionTimeOfAllJobs() {
127      Dictionary<Guid, TimeSpan> prog = new Dictionary<Guid, TimeSpan>();
128      try {
129        prog = jobManager.GetExecutionTimes();
130      }
131      catch (Exception ex) {
[7171]132        SlaveClientCom.Instance.LogMessage(string.Format("Exception was thrown while trying to get execution times: {0}", ex.Message));
[6983]133      }
134      return prog;
135    }
136
137    public static Guid GetUniqueMachineId() {
138      Guid id;
139      try {
140        id = GetUniqueMachineIdFromMac();
141      }
142      catch {
143        // fallback if something goes wrong...       
144        id = new Guid(Environment.MachineName.GetHashCode(), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
145      }
146      return id;
147    }
148
149    /// <summary>
150    /// returns total physical memory of the machine in MB
151    /// </summary>
152    private static int? GetPhysicalMemory() {
153      long? res = GetWMIValue("Win32_ComputerSystem", "TotalPhysicalMemory");
154      if (res != null)
155        return (int)(res / 1024 / 1024);
156      else
157        return null;
158    }
159
160    /// <summary>
161    /// returns CPU frequence of the machine in Mhz
162    /// </summary>
163    private static int? GetCpuSpeed() {
164      return (int)GetWMIValue("Win32_Processor", "MaxClockSpeed");
165    }
166
167    /// <summary>
168    /// Generate a guid based on mac address of the first found nic (yes, mac addresses are not unique...)
169    /// and the machine name.
170    /// Format:
171    ///
172    ///  D1      D2  D3  Res.   D4
173    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
174    /// |n a m e|0 0|0 0|0 0 mac address|
175    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
176    ///
177    /// The mac address is saved in the last 48 bits of the Data 4 segment
178    /// of the guid (first 2 bytes of Data 4 are reserved).
179    /// D1 contains the hash of the machinename.
180    /// </summary>   
181    private static Guid GetUniqueMachineIdFromMac() {
182      ManagementClass mgtClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
183      ManagementObjectCollection mgtCol = mgtClass.GetInstances();
184
185      foreach (ManagementObject mgtObj in mgtCol) {
186        foreach (var prop in mgtObj.Properties) {
187          if (prop.Value != null && prop.Name == "MACAddress") {
188            try {
189              //simply take the first nic
190              string mac = prop.Value.ToString();
191              byte[] b = new byte[8];
192              string[] macParts = mac.Split(':');
193              if (macParts.Length == 6) {
194                for (int i = 0; i < macParts.Length; i++) {
195                  b[i + 2] = (byte)((ParseNybble(macParts[i][0]) << 4) | ParseNybble(macParts[i][1]));
196                }
197
198                // also get machine name and save it to the first 4 bytes               
199                Guid guid = new Guid(Environment.MachineName.GetHashCode(), 0, 0, b);
200                return guid;
201              } else
202                throw new Exception("Error getting mac addresse");
203            }
204            catch {
205              throw new Exception("Error getting mac addresse");
206            }
207          }
208        }
209      }
210      throw new Exception("Error getting mac addresse");
211    }
212
213    /// <summary>
214    /// return numeric value of a single hex-char
215    /// (see: http://stackoverflow.com/questions/854012/how-to-convert-hex-to-a-byte-array)
216    /// </summary>   
217    static int ParseNybble(char c) {
218      if (c >= '0' && c <= '9') {
219        return c - '0';
220      }
221      if (c >= 'A' && c <= 'F') {
222        return c - 'A' + 10;
223      }
224      if (c >= 'a' && c <= 'f') {
225        return c - 'a' + 10;
226      }
227      throw new ArgumentException("Invalid hex digit: " + c);
228    }
229
230    private static long? GetWMIValue(string clazz, string property) {
231      ManagementClass mgtClass = new ManagementClass(clazz);
232      ManagementObjectCollection mgtCol = mgtClass.GetInstances();
233
234      foreach (ManagementObject mgtObj in mgtCol) {
235        foreach (var prop in mgtObj.Properties) {
236          if (prop.Value != null && prop.Name == property) {
237            try {
238              return long.Parse(prop.Value.ToString());
239            }
240            catch {
241              return null;
242            }
243          }
244        }
245      }
246      return null;
247    }
248
249    /// <summary>
250    /// returns free memory of machine in MB
251    /// </summary>   
252    public int GetFreeMemory() {
253      int mb = 0;
254
255      try {
256        mb = (int)(memCounter.NextValue() / 1024 / 1024);
257      }
258      catch { }
259      return mb;
260    }
261
262    public float GetCpuUtilization() {
263      float cpuVal = 0.0F;
264
265      try {
266        return cpuCounter.NextValue();
267      }
268      catch { }
269      return cpuVal;
270    }
271  }
272}
Note: See TracBrowser for help on using the repository browser.