Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 6521 was 6521, checked in by ascheibe, 12 years ago

#1233 catch exception when querying execution times

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