Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 6216 was 6216, checked in by ascheibe, 13 years ago

#1233

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