Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1233

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