Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Clients.Access/3.3/ClientInformationUtils.cs @ 12338

Last change on this file since 12338 was 12012, checked in by ascheibe, 10 years ago

#2212 merged r12008, r12009, r12010 back into trunk

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