Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ClientUserManagement/HeuristicLab.Clients.Access/3.3/ClientInformationUtils.cs @ 7557

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

#1648 adapted client management for use with Hive

File size: 7.5 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.Diagnostics;
24using System.Management;
25using System.Reflection;
26using HeuristicLab.Algorithms.Benchmarks;
27using HeuristicLab.Data;
28using HeuristicLab.Optimization;
29
30namespace HeuristicLab.Clients.Access {
31  public static class ClientInformationUtils {
32
33    public static Client CollectClientInformation() {
34      Client client = new Client();
35      OperatingSystem os = new OperatingSystem();
36      ClientType cType = new ClientType();
37      cType.Name = "HLClient";
38
39      client.Id = GetUniqueMachineId();
40      client.HeuristicLabVersion = GetHLVersion();
41      client.Name = GetMachineName();
42      client.MemorySize = GetPhysicalMemory().GetValueOrDefault();
43      client.NumberOfCores = GetNumberOfCores();
44      os.Name = GetOperatingSystem();
45      client.OperatingSystem = os;
46      client.ProcessorType = GetCpuInfo();
47      client.ClientType = cType;
48      //client.ClientConfiguration = GetClientConfiguration();
49      client.Timestamp = DateTime.Now;
50      client.PerformanceValue = RunBenchmark();
51
52      return client;
53    }
54
55    public static string GetClientConfiguration() {
56      //TODO: does it make sense to send the client configuration to the server? for what do we need this?
57      return string.Empty;
58    }
59
60    public static string GetHLVersion() {
61      FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);
62      return versionInfo.FileVersion;
63    }
64
65    public static bool IsClientHeuristicLab() {
66      return Process.GetCurrentProcess().ProcessName == Settings.Default.HLExeName;
67    }
68
69    public static int GetNumberOfCores() {
70      return Environment.ProcessorCount;
71    }
72
73    public static string GetOperatingSystem() {
74      return Environment.OSVersion.VersionString;
75    }
76
77    public static string GetMachineName() {
78      return Environment.MachineName;
79    }
80
81    public static Guid GetUniqueMachineId() {
82      Guid id;
83      try {
84        id = GetUniqueMachineIdFromMac();
85      }
86      catch {
87        // fallback if something goes wrong...       
88        id = new Guid(Environment.MachineName.GetHashCode(), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
89      }
90      return id;
91    }
92
93    /// <summary>
94    /// returns total physical memory of the machine in MB
95    /// </summary>
96    public static int? GetPhysicalMemory() {
97      long? res = GetWMIValue("Win32_ComputerSystem", "TotalPhysicalMemory");
98      if (res != null)
99        return (int)(res / 1024 / 1024);
100      else
101        return null;
102    }
103
104    /// <summary>
105    /// returns CPU frequence of the machine in Mhz
106    /// </summary>
107    public static string GetCpuInfo() {
108      string name = GetWMIString("Win32_Processor", "Name");
109      string manufacturer = GetWMIString("Win32_Processor", "Manufacturer");
110      return manufacturer + " " + name;
111    }
112
113    /// <summary>
114    /// Generate a guid based on mac address of the first found nic (yes, mac addresses are not unique...)
115    /// and the machine name.
116    /// Format:
117    ///
118    ///  D1      D2  D3  Res.   D4
119    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
120    /// |n a m e|0 0|0 0|0 0 mac address|
121    /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
122    ///
123    /// The mac address is saved in the last 48 bits of the Data 4 segment
124    /// of the guid (first 2 bytes of Data 4 are reserved).
125    /// D1 contains the hash of the machinename.
126    /// </summary>   
127    private static Guid GetUniqueMachineIdFromMac() {
128      ManagementClass mgtClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
129      ManagementObjectCollection mgtCol = mgtClass.GetInstances();
130
131      foreach (ManagementObject mgtObj in mgtCol) {
132        foreach (var prop in mgtObj.Properties) {
133          if (prop.Value != null && prop.Name == "MACAddress") {
134            try {
135              //simply take the first nic
136              string mac = prop.Value.ToString();
137              byte[] b = new byte[8];
138              string[] macParts = mac.Split(':');
139              if (macParts.Length == 6) {
140                for (int i = 0; i < macParts.Length; i++) {
141                  b[i + 2] = (byte)((ParseNybble(macParts[i][0]) << 4) | ParseNybble(macParts[i][1]));
142                }
143
144                // also get machine name and save it to the first 4 bytes               
145                Guid guid = new Guid(Environment.MachineName.GetHashCode(), 0, 0, b);
146                return guid;
147              } else
148                throw new Exception("Error getting mac addresse");
149            }
150            catch {
151              throw new Exception("Error getting mac addresse");
152            }
153          }
154        }
155      }
156      throw new Exception("Error getting mac addresse");
157    }
158
159    /// <summary>
160    /// return numeric value of a single hex-char
161    /// (see: http://stackoverflow.com/questions/854012/how-to-convert-hex-to-a-byte-array)
162    /// </summary>   
163    private static int ParseNybble(char c) {
164      if (c >= '0' && c <= '9') {
165        return c - '0';
166      }
167      if (c >= 'A' && c <= 'F') {
168        return c - 'A' + 10;
169      }
170      if (c >= 'a' && c <= 'f') {
171        return c - 'a' + 10;
172      }
173      throw new ArgumentException("Invalid hex digit: " + c);
174    }
175
176    private static long? GetWMIValue(string clazz, string property) {
177      ManagementClass mgtClass = new ManagementClass(clazz);
178      ManagementObjectCollection mgtCol = mgtClass.GetInstances();
179
180      foreach (ManagementObject mgtObj in mgtCol) {
181        foreach (var prop in mgtObj.Properties) {
182          if (prop.Value != null && prop.Name == property) {
183            try {
184              return long.Parse(prop.Value.ToString());
185            }
186            catch {
187              return null;
188            }
189          }
190        }
191      }
192      return null;
193    }
194
195    private static string GetWMIString(string clazz, string property) {
196      ManagementClass mgtClass = new ManagementClass(clazz);
197      ManagementObjectCollection mgtCol = mgtClass.GetInstances();
198
199      foreach (ManagementObject mgtObj in mgtCol) {
200        foreach (var prop in mgtObj.Properties) {
201          if (prop.Value != null && prop.Name == property) {
202            try {
203              return prop.Value.ToString();
204            }
205            catch {
206              return string.Empty;
207            }
208          }
209        }
210      }
211      return string.Empty;
212    }
213
214    public static double RunBenchmark() {
215      Linpack linpack = new Linpack();
216      ResultCollection results = new ResultCollection();
217      linpack.Run(new System.Threading.CancellationToken(), results);
218      DoubleValue mflops = (DoubleValue)results["Mflops/s"].Value;
219      return mflops.Value;
220    }
221  }
222}
Note: See TracBrowser for help on using the repository browser.