Subversion Repositories computer_asset_manager_v1

Rev

Rev 102 | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

<?php

   /*
    * dmidecode2array.php
    * 
    * Set of routines which convert the output of dmidecode into an array containing key/value pairs.
    *
    * Use this by including the file in your script, load the output of a dmidecode run into an array of lines, then call
    * $array = dmidecode2array( $contentsOfFile ).
    * Sample code to read a file name from ARGV, process the file and dump the resulting array using print_r shown at
    * bottom of this file, commented out.
    * 
    * Copyright (c) 2020 by the Daily Data, Inc. All rights reserved. Redistribution and use in source and binary forms, with or
    * without modification, are permitted provided that the following conditions are met:
    *     Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    *     Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
    *        disclaimer in the documentation and/or other materials provided with the distribution.
    *     Neither the name of the nor the names of its contributors may be used to endorse or promote products derived from this
    *       software without specific prior written permission.
    *
    * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
    * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
    * SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
    * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    *
    * 20200113 rodo@dailydata.net v0.1
    * Initial build
    * 
    */



   /*
    * Trims a value, then compares it to several 'null' possibilities
    * if it is a null, returns empty string, otherwise returns value
    */
   function cleanUpDMIValue( $value ) {
      $value = trim( $value );
      switch (strtolower( $value )) {
         case 'unknown':
         case 'Default string' :
         case 'unspecified' :
         case 'not available':
         case 'to be filled by o.e.m.':
         case 'not specified': return '';
      }
      return $value;
   }

   /*
    * Read value from array of hash, return array of "$outputKey\tvalue" for each entry found
    * If nothing found, returns empty array
    * if $unique is true, returns first non-empty value found
    * if $outputKey is not defined, uses $key
    */
   function getDMIInformation( $data, $type, $key, $outputKey = '', $unique = true ) {
      $return = array();
      foreach ( $data[$type] as $handle ) {
         if ( isset( $handle[$key]) ) {
            $a = cleanUpDMIValue( $handle[$key] );
            if ( $a ) {
               $return[] = ( $outputKey ? $outputKey : $key ) . "\t" . $a;
               if ( $unique ) {
                  return $return;
               }
            }
         }
      }
      return $return;
   }

   /*
    * adds $value to array
    * if $value is scalar, simply adds it
    * if $value is array, adds every row
    * returns modified array
    *
    * Can be done more efficiently with some PHP built-ins, but I forgot how.
    */
   function mergeArrays( $array, $value ) {
      if ( $value ) {
         switch (gettype( $value ) ) {
            case 'array' : foreach ( $value as $thisVal ) {
                              $array[] = $thisVal;
                           }
                           break;
            case 'boolean' :
            case 'integer' :
            case 'double'  :
            case 'string'  : $array[] = $value;
         } // switch
      }
      return $array;
   } //mergeArrays


   /*
    * Function will take an array of lines representing the output of a dmidecode file
    * and pick and choose the values we want to put into CAMP attributes.
    * It will return an array of key/value pairs to be added into the attributes table
    *
    * NOTE: this is a summary of values we decided to store. dmidecode files have a lot of
    * additional information we chose not to include, but they can be added by simply modifying the 
    * 
    */

   function dmidecode2array( $contents ) {

   // allows us to group the dmi types by function. not implemented
   $dmiGroups = array(
         "bios" => "0,13",
         "system" => "1,12,15,23,32",
         "baseboard" => "2,10,41",
         "chassis" => "3",
         "processor" => "4",
         "memory" => "5,6,16,17",
         "cache" => "7",
         "connector" => "8",
         "slot" => "9"
   );

   // This contains the standard DMI types, ie no OEM stuff. For reference, not used in code

   $standardDMITypes = array( 
         "0" => "BIOS",
         "1" => "System",
         "2" => "Baseboard",
         "3" => "Chassis",
         "4" => "Processor",
         "5" => "Memory Controller",
         "6" => "Memory Module",
         "7" => "Cache",
         "8" => "Port Connector",
         "9" => "System Slots",
         "10" => "On Board Devices",
         "11" => "OEM Strings",
         "12" => "System Configuration Options",
         "13" => "BIOS Language",
         "14" => "Group Associations",
         "15" => "System Event Log",
         "16" => "Physical Memory Array",
         "17" => "Memory Device",
         "18" => "32-bit Memory Error",
         "19" => "Memory Array Mapped Address",
         "20" => "Memory Device Mapped Address",
         "21" => "Built-in Pointing Device",
         "22" => "Portable Battery",
         "23" => "System Reset",
         "24" => "Hardware Security",
         "25" => "System Power Controls",
         "26" => "Voltage Probe",
         "27" => "Cooling Device",
         "28" => "Temperature Probe",
         "29" => "Electrical Current Probe",
         "30" => "Out-of-band Remote Access",
         "31" => "Boot Integrity Services",
         "32" => "System Boot",
         "33" => "64-bit Memory Error",
         "34" => "Management Device",
         "35" => "Management Device Component",
         "36" => "Management Device Threshold Data",
         "37" => "Memory Channel",
         "38" => "IPMI Device",
         "39" => "Power Supply",
         "40" => "Additional Information",
         "41" => "Onboard Devices Extended Information",
         "42" => "Management Controller Host Interface"
   );
      
      // verify this is something we can work with, First line should be the version of dmidecode found
      if ( preg_match('/dmidecode ([0-9.]+)/', $contents[0], $results) ) {
         $dmidecodeVersion = $results[1];
      } else {
         return "Not a valid dmidecode file";
      }
      // first, let's parse it into a hash
      $currentHandle = '';
      $currentType;
      $data = array();
      for ( $i = 0; $i < count($contents); $i++ ) {
         if ( preg_match('/^Handle ([0-9a-zx]+).*DMI type[^0-9]*(\d+),/i', $contents[$i], $outputArray) ) {
            //print "matched\n"; print_r($outputArray); die;
            $currentType = $outputArray[2];
            $currentHandle = $outputArray[1];
            if ( isset( $standardDMITypes[$currentType] ) || array_key_exists( $currentType,$standardDMITypes ) ) {
               $name = $contents[$i+1];
               $data[$currentType][$currentHandle]['name'] = $name;
               $i += 2; // skip the line with the name, and go to the next line
            } else {
               $currentType = $currentHandle = '';
            }
         }
         if ( $currentHandle &&  preg_match('/^\s+(.*):\s+(.*)$/i', $contents[$i], $outputArray) ) {
            $data[$currentType][$currentHandle][$outputArray[1]] = $outputArray[2];
         }
      }
      # well, we have at least one entry, so let's go
      $return = array();
      $return[] = "attribute\tvalue";

      /*
       * Grab the information we want from the file. Note tht we are renaming some of the fields from the dmidecode output
       * to match the keyfields used by our system (4th parameter in getDMIInformation).
       *
       * First, we'll get the easy stuff; stuff which only has one value we care about.
       * 
       */
      // manufacturer info
      $return = mergeArrays( $return, getDMIInformation( $data, '1','Manufacturer' ) );
      $return = mergeArrays( $return, getDMIInformation( $data, '1','Product Name', 'Model' ) );
      $return = mergeArrays( $return, getDMIInformation( $data, '1','Serial Number' ) );
      $return = mergeArrays( $return, getDMIInformation( $data, '1','UUID' ) );
      // physical machine
      $return = mergeArrays( $return, getDMIInformation( $data, '3','Type', 'Enclosure Type' ) );
      $return = mergeArrays( $return, getDMIInformation( $data, '3','Asset Tag', 'Enclosure Asset Tag' ) );
      $return = mergeArrays( $return, getDMIInformation( $data, '3','Height', 'Enclosure Height' ) );
      // firmware version
      $return = mergeArrays( $return, getDMIInformation( $data, '0','Vendor', 'Firmware Vendor' ) );
      $return = mergeArrays( $return, getDMIInformation( $data, '0','Release Date', 'Firmware Release' ) );
      $return = mergeArrays( $return, getDMIInformation( $data, '0','Version', 'Firmware Version' ) );
      $return = mergeArrays( $return, getDMIInformation( $data, '0','Firmware Revision', 'Firmware Revision' ) );
      // processor information. NOTE: assumes all sockets populated and all processors the same. If this is not the case
      // we will need to modify the following to dump each individual socket, similar to the meory information below.
      if ( isset( $data['4'] ) ) // count the number of sockets
         $return[] = "CPU Count\t" . count( $data['4'] );
      $return = mergeArrays( $return, getDMIInformation( $data, '4','Family', 'CPU Family' ) );
      $return = mergeArrays( $return, getDMIInformation( $data, '4','Manufacturer', 'CPU Manufacturer' ) );
      $return = mergeArrays( $return, getDMIInformation( $data, '4','Version', 'CPU Version' ) );
      $return = mergeArrays( $return, getDMIInformation( $data, '4','Current Speed', 'CPU Speed' ) );
      $return = mergeArrays( $return, getDMIInformation( $data, '4','Core Count', 'CPU Cores (ea)' ) );
      $return = mergeArrays( $return, getDMIInformation( $data, '4','Thread Count', 'CPU Threads (ea)' ) );

      /*
       * memory information. We want details on each slot for this, so we have to go through each entry, one at a time.
       * For readability, we also want to take several values and turn them into one human
       * readable string for each socket. So, we go through each entry in the memory socket, determine if it is populated
       * then concat it together for a pretty output
       */
      
      if ( isset( $data['17'] ) ) {
         $return[] = "Memory Slots\t" . count( $data['17'] );
         $totalRAM = 0; // we'll accumulate the total size as we find slots populated
         foreach ( $data['17'] as $entry ) { // type 17 has one entry for every DIMM slot
            $mem = array(); // fill this up with the values we want to turn into a string, then we'll implode it into the string
            $mem[] = trim($entry['Locator'] ? $entry['Locator'] : ($entry['Bank Locator'] ? $entry['Bank Locator'] : '' ));
            if ( $entry['Size'] == 'No Module Installed' ) {
               $mem[] = 'Unpopulated';
            } else {
               $mem[] = trim($entry['Size']); // size can be kilo, meg, gig, tera, so convert it to mega
               if ( preg_match('/(\d+)\s+(GB|MB|TB|kb)/i', $entry['Size'] , $outputArray) ) {
                  switch ( strtolower( $outputArray[2] ) ) {
                     case 'gb' :
                              $outputArray[1] *= 1024;
                              break;
                     case 'tb' : 
                              $outputArray[1] *= 1024 * 1024;
                              break;
                     case 'kb' : 
                              $outputArray[1] /= 1024;
                              break;
                  }
                  $totalRAM += $outputArray[1];
               }
               $mem[] = trim($entry['Form Factor']);
               $mem[] = trim($entry['Type']);
               $mem[] = trim($entry['Data Width']);
               if ( isset( $entry['Configured Clock Speed']) && isset($entry['Speed']) && cleanUpDMIValue($entry['Configured Clock Speed']) && cleanUpDMIValue($entry['Speed']) )
                  $mem[] = cleanUpDMIValue($entry['Configured Clock Speed'] . '/' . cleanUpDMIValue($entry['Speed']) );
               if ( isset($entry['Manufacturer']) && cleanUpDMIValue($entry['Manufacturer']) )
                  $mem[] = cleanUpDMIValue($entry['Manufacturer']);
               if ( isset($entry['Part Number']) && cleanUpDMIValue( $entry['Part Number'] ) )
                  $mem[] = 'p/n ' . cleanUpDMIValue($entry['Part Number']);
               if ( isset($entry['Serial Number']) && trim($entry['Serial Number']) != 'Not Specified' )
                  $mem[] = 's/n ' . cleanUpDMIValue($entry['Serial Number']);
            }
            $return[] = "Memory\t" . implode( ', ', $mem );
         }
         $return[] = "Memory Total\t$totalRAM MB";
      }

      /*
       * power supplies. Most workstations will not even have an entry here, but for servers we will have details on each individual
       * power supply, including the part number, serial number, etc..., so like memory, we want a detailed listing with a human
       * readable string for each psu
       */
      if ( isset( $data['39'] ) ) {
         $return[] = "Power Supply Count\t" . count( $data['39'] );
         foreach ( $data['39'] as $entry ) {
            if ( preg_match('/^Present/i', $entry['Status'] ) ) {
               $psu = array();
               $psu[] = trim($entry['Name']);
               $psu[] = trim($entry['Max Power Capacity']);
               $psu[] = trim($entry['Manufacturer']);
               $psu[] = 'p/n ' . trim($entry['Model Part Number']);
               $psu[] = 's/n ' . trim($entry['Serial Number']);
               $return[] = "Power Supply\t" . implode( ', ', $psu );
            }
         }
      }
      return $return;
   }  // dmidecode2array

   /*
    * Test code for dmidecode input
    * call from cli as
    * php dmidecode2array FILENAME
    * the array will be dumped to STDOUT by print_r
    * 
    */
   /* remove this line for testing

   $filename = $argv[1]; // get first parameter from cli
   if ( $filename ) {
      // slurp file into array, ignore empty lines and remove line endings
      $contents = file( $filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
      // $out will contain the key/value pairs
      $out = dmidecode2array( $contents );
      // dump it
      print_r( $out );
   } else {
      print "You must pass the file as the first command line parameter\n";
   }

   remove this line for testing */

?>