Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HivePerformance/sources/HeuristicLab.Clients.Hive.Slave/3.3/Manager/ConfigManager.cs @ 9373

Last change on this file since 9373 was 9373, checked in by pfleck, 11 years ago

#2030
Added MultiSlaveRunner for starting multiple Slave Cores on a single Machine.
Mocked GUID generation for slaves to random GUID.
Deactivated PerformanceCounter measurements from ConfigManager to avoid shared resource locks.

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