Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive-3.4/sources/HeuristicLab.Clients.Hive.Slave/3.4/ConfigManager.cs @ 6269

Last change on this file since 6269 was 6269, checked in by cneumuel, 13 years ago

#1233

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