Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 6168 was 6168, checked in by cneumuel, 13 years ago

#1233

  • removed Job-dto objects from slave core (since it stores outdated objects)
  • added command textbox to HiveJobView
  • improved the way the control buttons behave in HiveJobView
  • improved job control (pause and stop is also possible when job is not currently calculating)
  • improved gantt chart view (last state log entry is also displayed)
  • unified code for downloading jobs between experiment manager and hive engine
File size: 8.1 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 - GetUsedCores() : 0;
82
83      st.JobsAborted = SlaveStatusInfo.JobsAborted;
84      st.JobsDone = SlaveStatusInfo.JobsProcessed;
85      st.JobsFetched = SlaveStatusInfo.JobsFetched;
86
87      Dictionary<Guid, Executor> engines = Core.Executors;
88      st.Jobs = new List<JobStatus>();
89
90      lock (engines) {
91        foreach (KeyValuePair<Guid, Executor> kvp in engines) {
92          Executor e = kvp.Value;
93          st.Jobs.Add(new JobStatus { JobId = e.JobId, ExecutionTime = e.ExecutionTime, Since = e.CreationTime });
94        }
95      }
96      return st;
97    }
98
99    public Dictionary<Guid, TimeSpan> GetExecutionTimeOfAllJobs() {
100      Dictionary<Guid, TimeSpan> prog = new Dictionary<Guid, TimeSpan>();
101      Dictionary<Guid, Executor> engines = Core.Executors;
102      lock (engines) {
103        foreach (KeyValuePair<Guid, Executor> kvp in engines) {
104          Executor e = kvp.Value;
105          //don't include jobs in hb's which are currently serializing
106          if (e.SendHeartbeatForExecutor) {
107            prog[e.JobId] = e.ExecutionTime;
108          }
109        }
110      }
111      return prog;
112    }
113
114    public int GetUsedCores() {
115      return Core.GetCoresNeeded();
116    }
117
118    public static Guid GetUniqueMachineId() {
119      Guid id;
120      try {
121        id = GetUniqueMachineIdFromMac();
122      }
123      catch {
124        // fallback if something goes wrong...       
125        id = new Guid(Environment.MachineName.GetHashCode(), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
126      }
127      return id;
128    }
129
130    /// <summary>
131    /// returns total physical memory of the machine in MB
132    /// </summary>
133    private static int? GetPhysicalMemory() {
134      long? res = GetWMIValue("Win32_ComputerSystem", "TotalPhysicalMemory");
135      if (res != null)
136        return (int)(res / 1024 / 1024);
137      else
138        return null;
139    }
140
141    /// <summary>
142    /// returns CPU frequence of the machine in Mhz
143    /// </summary>
144    private static int? GetCpuSpeed() {
145      return (int)GetWMIValue("Win32_Processor", "MaxClockSpeed");
146    }
147
148    /// <summary>
149    /// Generate a guid based on mac address of the first found nic (yes, mac addresses are not unique...).
150    /// Format:
151    ///
152    ///  D1      D2  D3  Res.   D4
153    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
154    /// |n a m e|0 0|0 0|0 0 mac address|
155    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
156    ///
157    /// The mac address is saved in the last 48 bits of the Data 4 segment
158    /// of the guid (first 2 bytes of Data 4 are reserved).
159    /// D1 contains the name of the machine.
160    /// </summary>   
161    private static Guid GetUniqueMachineIdFromMac() {
162      ManagementClass mgtClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
163      ManagementObjectCollection mgtCol = mgtClass.GetInstances();
164
165      foreach (ManagementObject mgtObj in mgtCol) {
166        foreach (var prop in mgtObj.Properties) {
167          if (prop.Value != null && prop.Name == "MACAddress") {
168            try {
169              //simply take the first nic
170              string mac = prop.Value.ToString();
171              byte[] b = new byte[8];
172              string[] macParts = mac.Split(':');
173              if (macParts.Length == 6) {
174                for (int i = 0; i < macParts.Length; i++) {
175                  b[i + 2] = (byte)((ParseNybble(macParts[i][0]) << 4) | ParseNybble(macParts[i][1]));
176                }
177
178                // also get machine name and save it to the first 4 bytes               
179                Guid guid = new Guid(Environment.MachineName.GetHashCode(), 0, 0, b);
180                return guid;
181              } else
182                throw new Exception("Error getting mac addresse");
183            }
184            catch {
185              throw new Exception("Error getting mac addresse");
186            }
187          }
188        }
189      }
190      throw new Exception("Error getting mac addresse");
191    }
192
193    /// <summary>
194    /// return numeric value of a single hex-char
195    /// (see: http://stackoverflow.com/questions/854012/how-to-convert-hex-to-a-byte-array)
196    /// </summary>   
197    static int ParseNybble(char c) {
198      if (c >= '0' && c <= '9') {
199        return c - '0';
200      }
201      if (c >= 'A' && c <= 'F') {
202        return c - 'A' + 10;
203      }
204      if (c >= 'a' && c <= 'f') {
205        return c - 'a' + 10;
206      }
207      throw new ArgumentException("Invalid hex digit: " + c);
208    }
209
210    private static long? GetWMIValue(string clazz, string property) {
211      ManagementClass mgtClass = new ManagementClass(clazz);
212      ManagementObjectCollection mgtCol = mgtClass.GetInstances();
213
214      foreach (ManagementObject mgtObj in mgtCol) {
215        foreach (var prop in mgtObj.Properties) {
216          if (prop.Value != null && prop.Name == property) {
217            try {
218              return long.Parse(prop.Value.ToString());
219            }
220            catch {
221              return null;
222            }
223          }
224        }
225      }
226      return null;
227    }
228
229    /// <summary>
230    /// returns free memory of machine in MB
231    /// </summary>   
232    public static int GetFreeMemory() {
233      int mb = 0;
234
235      try {
236        PerformanceCounter counter = new PerformanceCounter("Memory", "Available Bytes", true);
237        mb = (int)(counter.NextValue() / 1024 / 1024);
238      }
239      catch { }
240      return mb;
241    }
242  }
243}
Note: See TracBrowser for help on using the repository browser.