Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Clients.Hive.Slave/3.3/Manager/ConfigManager.cs @ 12089

Last change on this file since 12089 was 12009, checked in by ascheibe, 10 years ago

#2212 updated copyright year

File size: 9.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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.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;
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      }
70      slave.Memory = GetPhysicalMemory();
71      slave.CpuArchitecture = Environment.Is64BitOperatingSystem ? CpuArchitecture.x64 : CpuArchitecture.x86;
72      slave.OperatingSystem = Environment.OSVersion.VersionString;
73      slave.CpuSpeed = GetCpuSpeed();
74      slave.IsDisposable = true;
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
120      st.Jobs = jobManager.GetExecutionTimes().Select(x => new TaskStatus { TaskId = x.Key, ExecutionTime = x.Value }).ToList();
121
122      return st;
123    }
124
125    public Dictionary<Guid, TimeSpan> GetExecutionTimeOfAllJobs() {
126      Dictionary<Guid, TimeSpan> prog = new Dictionary<Guid, TimeSpan>();
127      try {
128        prog = jobManager.GetExecutionTimes();
129      }
130      catch (Exception ex) {
131        SlaveClientCom.Instance.LogMessage(string.Format("Exception was thrown while trying to get execution times: {0}", ex.Message));
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    /// and the machine name.
169    /// Format:
170    ///
171    ///  D1      D2  D3  Res.   D4
172    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
173    /// |n a m e|0 0|0 0|0 0 mac address|
174    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
175    ///
176    /// The mac address is saved in the last 48 bits of the Data 4 segment
177    /// of the guid (first 2 bytes of Data 4 are reserved).
178    /// D1 contains the hash of the machinename.
179    /// </summary>   
180    private static Guid GetUniqueMachineIdFromMac() {
181      ManagementClass mgtClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
182      ManagementObjectCollection mgtCol = mgtClass.GetInstances();
183
184      foreach (ManagementObject mgtObj in mgtCol) {
185        foreach (var prop in mgtObj.Properties) {
186          if (prop.Value != null && prop.Name == "MACAddress") {
187            try {
188              //simply take the first nic
189              string mac = prop.Value.ToString();
190              byte[] b = new byte[8];
191              string[] macParts = mac.Split(':');
192              if (macParts.Length == 6) {
193                for (int i = 0; i < macParts.Length; i++) {
194                  b[i + 2] = (byte)((ParseNybble(macParts[i][0]) << 4) | ParseNybble(macParts[i][1]));
195                }
196
197                // also get machine name and save it to the first 4 bytes               
198                Guid guid = new Guid(Environment.MachineName.GetHashCode(), 0, 0, b);
199                return guid;
200              } else
201                throw new Exception("Error getting mac addresse");
202            }
203            catch {
204              throw new Exception("Error getting mac addresse");
205            }
206          }
207        }
208      }
209      throw new Exception("Error getting mac addresse");
210    }
211
212    /// <summary>
213    /// return numeric value of a single hex-char
214    /// (see: http://stackoverflow.com/questions/854012/how-to-convert-hex-to-a-byte-array)
215    /// </summary>   
216    static int ParseNybble(char c) {
217      if (c >= '0' && c <= '9') {
218        return c - '0';
219      }
220      if (c >= 'A' && c <= 'F') {
221        return c - 'A' + 10;
222      }
223      if (c >= 'a' && c <= 'f') {
224        return c - 'a' + 10;
225      }
226      throw new ArgumentException("Invalid hex digit: " + c);
227    }
228
229    private static long? GetWMIValue(string clazz, string property) {
230      ManagementClass mgtClass = new ManagementClass(clazz);
231      ManagementObjectCollection mgtCol = mgtClass.GetInstances();
232
233      foreach (ManagementObject mgtObj in mgtCol) {
234        foreach (var prop in mgtObj.Properties) {
235          if (prop.Value != null && prop.Name == property) {
236            try {
237              return long.Parse(prop.Value.ToString());
238            }
239            catch {
240              return null;
241            }
242          }
243        }
244      }
245      return null;
246    }
247
248    /// <summary>
249    /// returns free memory of machine in MB
250    /// </summary>   
251    public int GetFreeMemory() {
252      int mb = 0;
253
254      try {
255        mb = (int)(memCounter.NextValue() / 1024 / 1024);
256      }
257      catch { }
258      return mb;
259    }
260
261    public float GetCpuUtilization() {
262      float cpuVal = 0.0F;
263
264      try {
265        return cpuCounter.NextValue();
266      }
267      catch { }
268      return cpuVal;
269    }
270  }
271}
Note: See TracBrowser for help on using the repository browser.