Subversion Repositories computer_asset_manager_v1

Rev

Rev 36 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
3 rodolico 1
<?php
2
 
3
/*
4
 * Requires php-pear and libyaml under Debian Wheezy
11 rodolico 5
 *
6
 * apt-get install php-pear php5-dev libyaml-dev libyaml-0-2 libyaml-0-2-dbg
3 rodolico 7
 * pecl install yaml
11 rodolico 8
 * echo 'extension=yaml.so' >> /etc/php5/cli/php.ini
9
 * echo 'extension=yaml.so' >> /etc/apache2/cli/php.ini
5 rodolico 10
 *
11
 * V0.9 20160203 RWR
12
 * Changed to use yaml for the configuration file. Had to take the
13
 * anonymous functions which parsed the different file types and convert
14
 * them to simpl eval() blocks.
15
 * 
16 rodolico 16
 * V0.9.2 20160217 RWR
17
 * Fixed issue where if a device was marked as part of a Xen machine, it
18
 * was being deleted by pci updates.
36 rodolico 19
 * Fixed issue where serial number was not being updated
110 rodolico 20
 *
21
 * v0.9.3 20200218 RWR
22
 * Fixed invalid table name (attrib_device vs device_attrib) and set up to read a new section, attributes
16 rodolico 23
 * 
3 rodolico 24
*/
25
 
26
require 'library.php';
110 rodolico 27
$VERSION='0.9.3';
3 rodolico 28
 
29
 
30
class sysinfo {
31
   private $report; // this will hold an entire report
32
   private $messages = array();
33
   private $FATAL = false;
34
   private $parsingArray;   // this is a required array that teaches how to properly parse the input
35
 
36
   // following are used internally to track important information
37
   private $clientID;   // id in database
38
   private $clientName; // name from report
39
   private $machineID;  // id in database
40
   private $machineName;// name in report
41
   private $reportDate; // unix timestamp of report
42
   private $reportDateSQL; // used for inserts and compares in the database
43
   private $serialNumber; // the serial number, which is assumed to be unique
44
   private $fileContents;
45
   private $processDuplicates = false; // used for testing; allows duplicate reports
46
   private $returnCode = 0; // how we returned from this
47
   private $errors = array( 1 => 'Could not process file, not xml, yaml or ini',
48
                            2 => 'Invalid report, does not have one or more of report date, client name or computer name',
49
                            3 => 'Invalid Report, invalid machine name',
50
                            4 => 'Duplicate Report',
51
                            5 => 'New Report, must be added to CAMP',
36 rodolico 52
                            6 => 'Report is in queue for addition after updates to CAMP',
53
                            7 => 'Too many entries match criteria of name, client and serial number'
3 rodolico 54
                          );
55
 
56
   /*
57
    * $parsingArray contains one or more rows, each of which have three rows, starttag, endtag and eval
58
    * starttag and endtag are regex's which match the beginning and end of a document (ie, --- and ... for yaml)
59
    * eval is an anonymous function which will evaluate a particular type of document, returning it as an
60
    * array which we store in $report
61
    */
62
 
63
   function __construct( $parsingArray ) {
64
      $this->parsingArray = $parsingArray;
65
   }
66
 
67
   public function processReport () {
68
      $this->validateReport(); // validate the report appears to be ok
69
      // prepend the name of the report to messages BEFORE any error messages that may have appeared
70
      array_unshift( $this->messages,
71
            "Report on $this->reportDateSQL, client $this->clientName, system $this->machineName ($this->fileType)");
72
      // now, we do every step in turn. If they set the FATAL flag, we exit.
73
      if ( $this->FATAL ) return $this->returnCode;
74
      $this->getMachineID();
36 rodolico 75
      if ( empty( $this->machineID ) or $this->FATAL ) return $this->returnCode;
9 rodolico 76
      $this->checkDuplicate();
3 rodolico 77
      if ( $this->FATAL) return $this->returnCode;
78
      $this->updateComputerMakeup();
79
      $this->updateOS();
80
      $this->updateBootTime();
81
      $this->doIPAddresses();
82
      $this->processPCI();
83
      $this->processSoftwarePackages();
36 rodolico 84
      $this->processXen();
110 rodolico 85
      $this->processAttributes();
9 rodolico 86
      // at this point, we don't really need the report title information
87
      // so we will remove it before recordReport has a chance to put it
88
      // in database
89
      array_shift( $this->messages );
90
      // now record the report
91
      $this->recordReport();
3 rodolico 92
      return $this->returnCode;;
93
   } // function processReport
94
 
95
   /* 
96
    * Name: loadFromFile
97
    * Parameters: filename (path to load file from)
98
    * Returns: true if on success, false if not
99
    * Modifies: 
100
    *    report - added messages on why the report is not valid
101
    *    FATAL    - set to true if any of the required values do not exist
102
    */
103
 
104
   public function loadFromFile ( $filename ) {
105
      // load file into memory. Additionally, remove any \r's from it (leaving \n's for newlines)
106
      $this->fileContents = str_replace("\r","", file_get_contents( $filename ) );
107
      // try to parse the body out
108
      $this->getBody();
109
      if ( isset( $this->report ) ) {
110
         if ( $this->fileType == 'xml' ) $this->fixXML();
111
         if ( $this->fileType == 'ini' ) {
112
            $this->messages[] = 'We do not process ini files, but storing it instead';
113
         }
114
         return $this->fileType;
115
      } else { // we don't know what it is
116
         $this->FATAL = true;
117
         $this->messages[] = "Unable to parse [$filename] using YAML, XML or INI";
118
         return false;
119
      }
120
      //unset( $this->fileContents ); // free up memory
121
   } // function loadFromFile
122
 
123
 
124
   // once the file has been loaded, we need to figure out what kind of file it is
125
   // then use the function embedded in $parsingArray to import it.
126
   private function getBody ( ) {
127
      foreach ( $this->parsingArray as $key => $regexes ) {
128
         $matches;
129
         $pattern = $regexes['startTag'] . '.*' . $regexes['endTag'];
130
         if ( preg_match( "/$pattern/ms", $this->fileContents, $matches ) ) {
131
            $this->fileType = $key;
132
            $this->fileContents = $matches[0];
5 rodolico 133
            $body = $this->fileContents;
134
            $this->report = eval( $regexes['eval'] );
135
            if ( $this->report ) return true;
3 rodolico 136
         } // if
137
      } // foreach
138
      return false;
139
   }
140
 
141
   /*
142
    * Name: fixXML
143
    * Parameters: None
144
    * Returns: nothing
145
    * Modifies: $this->report
146
    * YAML creates the entries as ['network']['interface name']
147
    * XML  creates the entries as ["network"][x][name]=>
148
    * We will simply copy the XML information into a duplicate
149
    * in YAML style
150
    */
151
   private function fixXML() {
152
       $oldInfo = $this->report['network'];
153
       unset ($this->report['network']);
154
       foreach ( $oldInfo as $entry ) {
155
          #$this->messages[] = "Duplicating network entry for $entry[name]";
156
          foreach ($entry as $key => $value ) {
157
             $this->report['network'][$entry['name']][$key] = $value;
158
             #$this->messages[] = "  Adding  $value as value for network.name.$key";
159
          } // inner foreach
160
       } // outer foreach
161
   } // fixXML
162
 
163
 
164
   private function processINI() {
165
      return false;
166
   }
167
 
168
   public function dumpMessages () {
9 rodolico 169
      $return = '';
170
      if ( $this->messages ) {
171
         $return = implode( "\n", $this->messages );
172
         $return .= "\n";
173
      }
3 rodolico 174
      return $return;
175
   }
176
 
177
   /* 
178
    * Name: validateReport
179
    * Parameters: none
180
    * Returns: true if valid, false if not
181
    * Modifies: 
182
    *    messages - added messages on why the report is not valid
183
    *    FATAL    - set to true if any of the required values do not exist
184
    */
185
 
186
      public function validateReport () {
187
      /*
188
       * A report is considered valid if it has a date, client name and hostname
189
       * No check is made at this time for validity of that data
190
       */
191
      if ( empty( $this->report['report']['date']) ) {
192
         $this->messages[] = 'No report date';
193
      } else {
194
         $this->reportDate = strtotime( $this->report['report']['date'] ); // store in Unix timestamp
195
         $this->reportDateSQL = strftime( '%F %T', $this->reportDate ); // save a copy of the date in SQL format
196
         if ( empty( $this->reportDate ) )
197
            $this->messages[] = "Unable to parse report date [$this->report['report']['date']]";
198
      }
199
 
200
      if ( empty( $this->report['report']['client'] ) ) {
201
         $this->messages[] = 'No client name';
202
      } else {
203
         $this->clientName = $this->report['report']['client'];
204
      }
205
 
206
      if ( empty ( $this->report['system']['hostname'] ) ) {
207
         $this->messages[] = 'No Computer Name';
208
      } else {
209
         $this->machineName = $this->report['system']['hostname'];
210
      }
211
      $this->FATAL = ! empty( $this->messages );
212
 
213
      // serial number is fairly new, so it is not a critical error
214
      // it will be set in getMachineID if we have it here, but not there
215
      if ( empty ( $this->report['system']['serial'] ) ) {
216
         $this->messages[] = 'No Serial Number';
217
      } else {
218
         $this->serialNumber = $this->report['system']['serial'];
219
      }
220
 
221
   } // function validateReport
222
 
223
 
224
   /* 
225
    * Name: getMachineID
226
    * Parameters: none
227
    * Returns: true if found, false if not
228
    * Modifies: 
229
    *    clientID - index value of client in database
230
    *    machineID - index value of machine in database
231
    */
232
   private function getMachineID () {
233
      $this->clientID = getClientID( $this->clientName );
234
      if ( $this->clientID ) {
36 rodolico 235
         try {
236
            $this->machineID = getMachineID( $this->machineName, $this->clientID, $this->serialNumber );
237
         }
238
         catch (Exception $e) {
239
            $this->messages[] = "Duplicate entries found when trying to process Machine [$this->machineName], Client [$this->clientID], Serial [$this->serialNumber]";
240
            $this->FATAL = true;
241
            $this->returnCode = 7;
242
            return false;
243
         }
3 rodolico 244
      }
245
      if ( empty( $this->machineID ) ) {
246
         $this->messages[] = $this->makeUnknown( $this->clientName, $this->machineName, $this->reportDateSQL );
247
         return false;
248
      }
249
      return true;
250
   } // function getMachineID
251
 
36 rodolico 252
 
253
 
3 rodolico 254
   /* 
255
    * checks for a duplicate report, ie one that has already been run.
256
    * if this computer has a report already for this date/time
257
    */ 
9 rodolico 258
   private function checkDuplicate() {
3 rodolico 259
      $count = getOneDBValue("select count(*) from sysinfo_report where device_id = $this->machineID and report_date = '$this->reportDateSQL'");
260
      if ( $this->processDuplicates ) { $count = 0; } // for testing
261
      if ( $count ) {
262
         $this->messages[] = "Duplicate Report for $this->machineName (id $this->machineID) on $this->reportDateSQL";
263
         $this->returnCode = 4;
264
         $this->FATAL = true;
265
         return false;
266
      }
9 rodolico 267
      return true;
268
   } // recordReport
269
 
270
 
271
   /* 
272
    * Creates an entry in the sysinfo_report table
273
    */ 
274
   private function recordReport() {
3 rodolico 275
      $version = $this->report['report']['version'];
9 rodolico 276
      $messages = makeSafeSQLValue( $this->dumpMessages() );
277
      // if we made it this far, we are ok, so just add the report id
278
      queryDatabaseExtended("insert into sysinfo_report(device_id,version,report_date, notes,added_date) values ($this->machineID ,'$version','$this->reportDateSQL',$messages,now())");
3 rodolico 279
      $this->reportID = getOneDBValue("select max( sysinfo_report_id ) from sysinfo_report where device_id = $this->machineID and report_date = '$this->reportDateSQL'");
280
      return true;
9 rodolico 281
   } // recordReport
3 rodolico 282
 
283
 
284
   function makeUnknown( $clientName, $machineName, $reportDate ) {
285
      $result = getOneDBValue("select report_date from unknown_entry where client_name = '$clientName' and device_name = '$machineName'");
286
      if ( empty( $result ) ) {
287
         queryDatabaseExtended( "insert into unknown_entry(client_name,device_name,report_date) values ('$clientName', '$machineName', '$reportDate')");
288
         $this->returnCode = 5;
289
         return "New entry, client=$clientName, device=$machineName. You must update Camp before this report can be processed";
290
      } else {
291
         $this->returnCode = 6;
292
         return "New entry detected, but entry already made. You must update Camp before this can be processed";
293
      }
294
   }
295
 
110 rodolico 296
   // simply used to get an attrib_id. If it does not exist, will create it
3 rodolico 297
 
298
   private function getAttributeID ( $attributeName, $reportDate ) {
299
      $attributeName = makeSafeSQLValue( $attributeName );
300
      $result = getOneDBValue( "select attrib_id from attrib where name = $attributeName and removed_date is null" );
301
      if ( !isset( $result) ) {
302
         $result = queryDatabaseExtended( "insert into attrib (name,added_date) values ($attributeName,'$reportDate')");
303
         $this->messages[] = "Added a new attribute type [$attributeName]";
304
         $result = $result['insert_id'];
305
      }
306
      return $result;
307
   }
308
 
309
   /*
36 rodolico 310
    * checks to values to see if they are equal
311
    * If they are both numeric, and $fuzzyValue is non-zero, will determine
312
    * if $value2 is within $value1 +/- percentage of $fuzzyValue.
313
    * Thus, if $fuzzyValue is 0.10, they are "equal" as long as $value1 is 
314
    * within $value2 +/- 10%
315
    */
316
   private function sloppyEqual ( $value1, $value2, $fuzzyValue ) {
317
      return 
318
         ( is_numeric( $value1 ) and is_numeric( $value2 ) and $fuzzyValue and
319
            $value1 <= $value2 + $value2 * $fuzzyValue and
320
            $value1 >= $value2 - $value2 * $fuzzyValue 
321
         )
322
         or
323
         $value1 == $value2;
324
   }
325
 
326
 
327
   /*
110 rodolico 328
    * Checks an attribute from the attrib_deviceurtes table. If the value has
3 rodolico 329
    * changed, sets the old one's removed_date to this report date, then adds
330
    * new record for new value.
36 rodolico 331
    * If value is not off by more than $slop, will not update. Useful for memory and speed on
332
    * virtual devices where the values may be slightly different at different readings
3 rodolico 333
    * If the record does not exist, simply creates it
334
    */
36 rodolico 335
   public function checkAndUpdateAttribute( $attribute, $value, $slop = 0 ) {
3 rodolico 336
      if ( !isset($attribute) || !isset($value ) ) {
337
         $this->messages[] = "Error: attempt to use null value for [$attribute], value [$value] for ID $this->machineID in checkAndUPdateAttribute";
338
         return false;
339
      }
340
      $attrib_id = $this->getAttributeID( $attribute, $this->reportDateSQL );
110 rodolico 341
      $result = getOneDBValue( "select attrib_device.value
342
         from attrib_device join attrib using (attrib_id)
343
         where attrib_device.device_id = $this->machineID
344
               and attrib_device.removed_date is null
3 rodolico 345
               and attrib.attrib_id = $attrib_id
346
         ");
36 rodolico 347
      if ( isset( $result ) && ! $this->sloppyEqual( $value, $result, $slop ) ) { # got it, now see if it compares ok
348
         $this->messages[] = "New value [$value] for $attribute for device $this->machineID, voiding previous";
349
         $value = makeSafeSQLValue($value); # we want to always quote the value on this particular one
110 rodolico 350
         queryDatabaseExtended( "update attrib_device
36 rodolico 351
                                    set removed_date = '$this->reportDateSQL'
352
                                 where device_id = $this->machineID
353
                                       and attrib_id = $attrib_id
354
                                       and removed_date is null");
355
         unset( $result ); # this will force the insert in the next block of code
3 rodolico 356
      } # if ($result)
357
      if ( ! isset( $result ) ) { # we have no valid entry for this attribute
110 rodolico 358
         //$this->messages[] = "In checkAndUpdateAttribute, adding new record with insert into attrib_device(device_id,attrib_id,value,added_date) values ($this->machineID,$attrib_id,$value,$this->reportDateSQL)";
359
         queryDatabaseExtended( "insert into attrib_device(device_id,attrib_id,value,added_date)
3 rodolico 360
                                 values ($this->machineID,$attrib_id,$value,'$this->reportDateSQL')");
361
         return true;
362
      }
363
      return false;
364
   } // checkAndUpdateAttribute
365
 
366
   # simply verifies some attributes of the computer
367
   private function updateComputerMakeup() {
36 rodolico 368
      $this->checkAndUpdateAttribute('Memory',        $this->report['system']['memory'], 0.30); // memory can be plus/minus 30%
3 rodolico 369
      $this->checkAndUpdateAttribute('Number of CPUs',$this->report['system']['num_cpu']);
370
      $this->checkAndUpdateAttribute('CPU Type',      $this->report['system']['cpu_type']);
371
      $this->checkAndUpdateAttribute('CPU SubType',   $this->report['system']['cpu_sub']);
36 rodolico 372
      $this->checkAndUpdateAttribute('CPU Speed',     $this->report['system']['cpu_speed'], 0.30 ); // cpu speed can be plus/minus 30%
373
      // validate serial number and update if necessary
374
      if ( $this->serialNumber ) {
375
         $dbSerial = getOneDBValue( "select serial from device where device_id = $this->machineID" );
376
         if ( ! isset ( $dbSerial ) or $dbSerial != $this->serialNumber ) {
377
            $this->messages[] = "Updating serial number to $this->serialNumber";
378
            queryDatabaseExtended( "update device set serial = '$this->serialNumber' where device_id = $this->machineID" );
379
         }
380
      }
3 rodolico 381
   } // updateComputerMakeup
382
 
110 rodolico 383
   /* several report entries are simply designed to add/update the attributes table (attrib_device), so we'll just go through them
384
    * one by one
385
    */
386
   private function processAttributes() {
387
      foreach ( $this->report['attributes'] as $key => $value ) {
388
         $this->checkAndUpdateAttribute( $key, $value );
389
      }
390
   } // processAttributes
36 rodolico 391
 
392
 
3 rodolico 393
   // This is kind of funky, because column = null does not work, it must be column is null, so we have to look for it.
394
   function makeSQLEquals ( $field, $value ) {
395
      return "$field " . ( $value == 'null' ? 'is null' : '=' . $value );
396
   }
397
 
398
 
399
   private function updateOS () {
400
      // find os
401
      $osName =         makeSafeSQLValue( isset($this->report['operatingsystem']['os_name'])         ? $this->report['operatingsystem']['os_name'] : '');
402
      $kernel =         makeSafeSQLValue( isset($this->report['operatingsystem']['kernel'])          ? $this->report['operatingsystem']['kernel'] : '');
403
      $distro_name =    makeSafeSQLValue( isset($this->report['operatingsystem']['os_distribution']) ? $this->report['operatingsystem']['distribution'] : '');
404
      $release =        makeSafeSQLValue( isset($this->report['operatingsystem']['os_release'])      ? $this->report['operatingsystem']['release'] : '');
405
      $version =        makeSafeSQLValue( isset($this->report['operatingsystem']['os_version'])      ? $this->report['operatingsystem']['os_version'] : '');
406
      $description =    makeSafeSQLValue( isset($this->report['operatingsystem']['description'])     ? $this->report['operatingsystem']['description'] : '');
407
      $codename =       makeSafeSQLValue( isset($this->report['operatingsystem']['codename'])        ? $this->report['operatingsystem']['codename'] : '');
408
 
409
      $osID = getOneDBValue( "select operating_system_id from operating_system
410
               where " . $this->makeSQLEquals( 'name', $osName ) . "
411
                  and " . $this->makeSQLEquals( 'kernel', $kernel ) . "
412
                  and " . $this->makeSQLEquals( 'distro', $distro_name ) . "
413
                  and " . $this->makeSQLEquals( 'distro_release', $release ) );
414
      if ( !isset( $osID ) ) {
415
         $this->messages[] = "Creating a new OS with name = $osName, kernel = $kernel, distro = $distro_name,  distro_release = $release";
416
         $result = queryDatabaseExtended( "insert into operating_system (name,version,kernel,distro,distro_description,distro_release,distro_codename, added_date) values
417
                                          ($osName,$version,$kernel,$distro_name,$description,$release,$codename, '$this->reportDateSQL')" );
418
         $osID = $result['insert_id'];
419
      }
420
 
421
      # verify the operating system
422
      $registeredOS = getOneDBValue( "select operating_system_id from device_operating_system where device_id = $this->machineID and removed_date is null" );
423
      if ( ! $registeredOS || $registeredOS != $osID ) {
424
         if ( $registeredOS ) { #we have the same computer, but a new OS???
425
            queryDatabaseExtended( "update device_operating_system set removed_date = '$this->reportDateSQL' where device_id = $this->machineID and removed_date is null");
426
            $this->messages[] = "Computer $this->machineName has a new OS";
427
         }
428
         queryDatabaseExtended( "insert into device_operating_system( device_id,operating_system_id,added_date) values ($this->machineID,$osID,'$this->reportDateSQL')");
429
      }
430
   }
431
 
6 rodolico 432
   /* every time we get a report, we need to see if the computer was rebooted
433
    * There is some slop in the last reboot date, so we assume if it is less than
434
    * $fuzzyRebootTimes, it was not rebooted. $fuzzyRebootTimes is calculated in
435
    * seconds. Since most of our machines take a minimum of 5 minutes to reboot
436
    * we'll go with that (300), though it would be just as good to go with a day
437
    * (86400) since we only run this report daily
438
    * When one is found, we remove the old report and add a new one.
439
    */
3 rodolico 440
   private function updateBootTime() {
6 rodolico 441
      $fuzzyRebootTimes = 300; // this allows slop of this many seconds before we assume a machine has been rebooted, ie
3 rodolico 442
      $lastReboot;
443
      if ( isset( $this->report['system']['last_boot'] ) ) {
444
         $lastReboot = strftime( '%F %T',$this->report['system']['last_boot'] ); // convert unix timestamp to sql value
445
         if ( isset( $lastReboot ) ) {
6 rodolico 446
            //if ( ! getOneDBValue( "select computer_uptime_id from computer_uptime where device_id = $this->machineID and last_reboot = '$lastReboot'" ) ) {
447
            if ( ! getOneDBValue( "select computer_uptime_id from computer_uptime where abs(TIME_TO_SEC(timediff( last_reboot, '$lastReboot' ))) < 3600 and device_id = $this->machineID" ) ) {
3 rodolico 448
               $this->messages[] = "Computer was rebooted at $lastReboot";
449
               queryDatabaseExtended( "update computer_uptime set removed_date = '$this->reportDateSQL' where device_id = $this->machineID and removed_date is null" );
450
               queryDatabaseExtended( "insert into computer_uptime (device_id,added_date,last_reboot) values ($this->machineID,'$this->reportDateSQL','$lastReboot')");
451
            }
452
         } else {
453
            $this->messages[] = 'Invalid reboot time [' . $this->Report['system']['last_boot'] . ']';
454
         }
455
      } else {
456
         $this->messages[] = 'No Boot time given';
457
      }
458
   }
459
 
460
 
461
   // checks if the report and the database values are the same
462
   private function checkInterfaceEquals( $report, $database ) {
463
      //var_dump( $report );
464
      //var_dump( $database );
465
      return ( 
466
         $report['address'] == $database['address'] and
467
         $report['netmask'] == $database['netmask'] and
468
         $report['ip6address'] == $database['ip6'] and
469
         $report['ip6networkbits'] == $database['ip6net'] and
470
         $report['mtu'] == $database['mtu'] and
471
         $report['mac'] == $database['mac'] 
472
         );
473
   } // checkInterfaceEquals
474
 
475
 
476
   /*
477
    * routine will check for all IP addresses reported and check against those recorded in the
478
    * database. It will remove any no longer in the database, and add any new ones
479
    */
480
   private function doIPAddresses () {
481
      /*
482
       * get all interfaces from the database
483
       * remove any interfaces from database which are not in report
484
       * add any interfaces from report which are not in database or which have changed
485
       */
486
      $network = $this->report['network']; // make a copy so we don't modify the original report
487
      // we won't process lo
488
      unset ($network['lo']);
489
      // at this point, we could get rid of tun's also, if we wanted to
490
 
491
      // let's ensure that all rows in report have the minimum required data
492
      foreach ( array_keys( $network ) as $interface ) {
493
         foreach ( array( 'address','netmask','ip6address','ip6networkbits','mtu','mac' ) as $required ) {
494
            if ( ! isset( $network[$interface][$required] ) ) { 
495
               $network[$interface][$required]  = NULL; 
496
            }
497
         } // checking all keys
498
      } // checking all report rows
499
      // var_dump( $network );   
500
 
501
      // get current information on all active interfaces in the database
502
      $dbInterfaces = queryDatabaseExtended( "select network_id,interface,address,netmask,ip6,ip6net,mac,mtu from network where device_id = $this->machineID and removed_date is null" );
503
      //print "select network_id,interface,address,netmask,ip6,ip6net,mac,mtu from network where device_id = $this->machineID and removed_date is null\n";
504
      //var_dump($dbInterfaces);
505
 
506
      // now, get rid of any interfaces which are no longer in the database
507
      // get a list of interfaces being passed in by report as a comma delimited list for processing.
508
      foreach ( array_keys( $network) as $temp ) {
509
         $interfaces[] = "'$temp'";
510
      }
511
      $interfaces = implode( ',', $interfaces );
512
      if ( $interfaces ) { // are there any? Then simply remove anything not in their set.
513
         queryDatabaseExtended( "update network set removed_date = '$this->reportDateSQL' where device_id = $this->machineID and removed_date is null and interface not in ($interfaces)");
514
         // print "update network set removed_date = '$this->reportDateSQL' where device_id = $this->machineID and removed_date is null and interface not in ($interfaces)\n";
515
         // reload the database results to exclude the ones we removed above
516
         $dbInterfaces = queryDatabaseExtended( "select network_id,interface,address,netmask,ip6,ip6net,mac,mtu from network where device_id = $this->machineID and removed_date is null" );
517
         // print "select network_id,interface,address,netmask,ip6,ip6net,mac,mtu from network where device_id = $this->machineID and removed_date is null\n";
518
      } // if
519
      // at this point, the database is a subset of the report, ie there are no entries in the database which are not also in the report.
520
      // let's remove the ones which are the same from both sets.
521
      // we can take a shortcut since the database is a subset of the report, ie we can remove entries from the report as we process
522
      if ( $dbInterfaces ) { // do we have anything in the database?
523
         foreach ( $dbInterfaces['data'] as $row => $value ) {
524
            // print "checking if " . $network[$value['interface']] . " equals $value\n";
525
            if ( $this->checkInterfaceEquals( $network[$value['interface']], $value ) ) { // compare the two entries
526
               // print "\tIt Does, so deleting it from updates\n";
527
               unset( $network[$value['interface']] );
528
            } else { // they are not equal. We will simply void out the existing one and it will treat the report entry as a new entry.
529
               // print "\tit is an update, so setting to removed in database\n";
530
               queryDatabaseExtended( "update network set removed_date = '$this->reportDateSQL' where device_id = $this->machineID and removed_date is null and interface = '" . $value['interface'] . "'");
531
               // print "update network set removed_date = '$this->reportDateSQL' where device_id = $this->machineID and removed_date is null and interface = '" . $value['interface'] . "'\n";
532
            } // if..else
533
         } // foreach
534
      }
535
      // finally, we should have only new entries, or entries which have changed and have been voided
536
      // a new row should be created for anything left.
537
      foreach ( $network as $interface => $values ) {
538
         //var_dump( $values );
539
         $sql = implode ( ',', array( 
540
                              $this->machineID,
541
                              makeSafeSQLValue($this->reportDateSQL),
542
                              makeSafeSQLValue($interface),
543
                              makeSafeSQLValue($values['address']),
544
                              makeSafeSQLValue($values['netmask']),
545
                              makeSafeSQLValue($values['ip6address']),
546
                              makeSafeSQLValue($values['ip6networkbits']),
547
                              makeSafeSQLValue($values['mtu']),
548
                              makeSafeSQLValue($values['mac'])
549
                              )
550
                         );
551
         $sql = "insert into network (device_id,added_date,interface,address,netmask,ip6,ip6net,mtu,mac) values (" . $sql . ")";
552
         //$this->messages[] = $sql;
553
         queryDatabaseExtended( $sql );
554
         $this->messages[] = "Network Device $interface was added/modified";
555
      }
556
   } // doIPAddresses
557
 
558
 
559
   /*
560
    * function looks through every element of $report, for a subkey
561
    * named 'keyfield'. It turns those into a string appropriate for
562
    * inclusion in a query as 
563
    * where fieldname in ( $keylist )
564
    * For example, with values a, b, c, 54, q'
565
    * returns 'a','b','c','54','q\''
566
    * where $keylist is generated by this function
567
    * returns null if no values found
568
    */ 
569
   function getKeyList ( $report ) {
570
      $keys = array();
571
      $keyset = null;
572
      // every row should have a key 'keyfield'.Since we don't know 
573
      // what they are, be sure to make sure they are SQL Safe
574
      foreach ( $report as $key => $value ) {
575
         $keys[] = makeSafeSQLValue( $value['keyfield'] );
576
      }
577
      return $keys ? implode( ",\n", $keys ) : null;
578
   }
579
 
580
   /*
581
    * function checks all keys in $first and $second to see if they
582
    * match. If they do, returns true, else returns false
583
    * ignores any keys passed in as array $ignore
584
    */
585
   function rowMatches ( $first, $second, $ignore = array() ) {
586
      foreach ( $first as $fkey => $fValue ) {
587
         if ( in_array( $fkey, $ignore ) )
588
            continue;
589
         if ( $fValue == $second[$fkey] )
590
            continue;
591
         return false;
592
      }
593
      return true;
594
   } // rowMatches
595
 
596
   /* Generic function that will 
597
    * delete items in database not found in report
598
    * Clean up report to contain only those items which are to be added
599
    * Return a copy of the report.
600
    * 
601
    * NOTE: since we are deleting items not found in the report, we will then
602
    * subsequently add them. This is the update process since we never actually
603
    * "delete" anything from the database.
604
    * 
605
    * Requires the report, and report must have a key for each entry named
606
    * 'keyfield' which the query below may use (as special tag <keys>
607
    * Also uses the following queries. If a query does not exist, that
608
    * process is ignored
609
    * 'remove old' - should have an entry as <device_id> which will have the current
610
    *       machine ID placed in it
611
    * 'delete' - <ids> which will be replaced with a list of keys from the 
612
    *         report.
613
    * 'find' - should return a column named 'id' which is a primary key on the
614
    *          table (used by delete query), and a column named 'keyfield'
615
    *          which matches the same one in the report. Any other fields in
616
    *          the query are checked against the report, and the report and
617
    *          database entry are only considered matching if all query fields
618
    *          match a report entry.
619
    * 
620
    * Before passing in report, you should go through the entries and create
621
    * a new one called 'keyfield' for each entry which will be a unique key
622
    * for an entry. For example, software packages may be the package name
623
    * and the version.
624
    */
625
   private function AddDeleteUpdate ( $report, $queries, $reportLabel, $testing=false ) {
626
 
627
      if ( $testing ) {
628
         print "*****************Starting\n"; 
629
         print_r( $report ); 
630
         print "*****************Starting\n";
631
      }
632
      $database = null;
633
      $keySet = $this->getKeyList( $report );
634
      if ( is_null( $keySet ) ) // bail if we don't have any data
635
         return null;
636
 
637
      // find values which are in database but not in report and delete them from database
638
      if ( $queries['remove old'] ) {
639
         $queries['remove old'] = str_replace( '<keys>', $keySet, $queries['remove old'] );
640
         $queries['remove old'] = str_replace( '<device_id>', $this->machineID, $queries['remove old'] );
641
         if ( $testing )
642
            print "Remove Query***************************\n" . $queries['remove old'] . "\n***********************************\n";
643
         else {
644
            $database = queryDatabaseExtended( $queries['remove old'] );
645
            if ( $database and $database['affected_rows'] ) 
646
               $this->messages[] = $database['affected_rows'] . " $reportLabel removed from database because they were removed for superceded";
647
         } // else
648
      } // if
649
 
650
      // now, let's get all the values left in the database
651
      if ( $queries['find'] ) {
652
         $queries['find'] = str_replace( '<keys>', $keySet, $queries['find'] );
653
         $queries['find'] = str_replace( '<device_id>', $this->machineID, $queries['find'] );
654
         if ( $testing )
655
            print "Find Query***************************\n" . $queries['find'] . "\n***********************************\n";
656
         else
657
            $database = queryDatabaseExtended( $queries['find'] );
658
      }
659
      if ( $database ) { // there were entries in the database still
660
         $database = $database['data']; // get to the data
661
         $keysToDelete = array();
662
         // find values which are different in report, and delete the database entry
663
         foreach ( $database as $row => $entries ) {
664
            foreach ( $report as $key => $values ) {
665
               if ( $report[$key]['keyfield'] != $entries['keyfield'] )
666
                  continue;
667
               // if we made it here, our keyfields match, so we check
668
               // the contents of the other fields
669
               if ( $this->rowMatches( $entries, $values, array( 'keyfield', 'id' ) ) ) {
670
                  // they match, so remove it from the report
671
                  unset( $report[$key] );
672
               } else { // they are different in the report, so remove from database
673
                  $keysToDelete[] = $entries['id'];
674
               }
675
            } // inner foreach
676
         } // outer foreach
677
         if ( $keysToDelete and $queries['delete'] ) {
678
            $queries['delete'] = str_replace( '<ids>', implode( ',', $keysToDelete ), $queries['delete'] );
679
            if ( $testing )
680
               print "Delete Query***************************\n" . $queries['delete'] . "\n***********************************\n";
681
            else {
682
               $updates = queryDatabaseExtended( $queries['delete'] );
683
               $this->messages[] = $updates['affected_rows'] . " $reportLabel modified";
684
            }
685
         }
686
      } // if $database
687
      // return items to be added
688
      if ( $testing ) {
689
         print "*****************Ending\n"; 
690
         print_r( $report ); 
691
         print "*****************Ending\n";
692
      }
693
      return $report;
694
   } // function AddDeleteUpdate
695
 
696
 
697
   /*
698
    * routine to ensure the hardware returned as PCI hardware is in the attributes area
699
    */ 
700
   private function processPCI ( ) {
701
      // following are some of the synonyms we will use from the PCI
702
      // tables for the "name" of the device. They are listed in the
703
      // order of priority (ie, first one found is chosen).
704
      $nameSynomyms = array('name','device','sdevice','device0');
705
 
706
      // query which removes devices from database that are not in report
707
      // we assume if the report doesn't have it, it has been removed
708
      $queries['remove old'] = 
709
                    "update device
710
                        set removed_date = '$this->reportDateSQL'
711
                        where device_id in (
712
                           select device_id from (
713
                              select
714
                                    device_id
715
                                 from
716
                                    device join device_type using (device_type_id)
717
                                 where
718
                                    device.part_of = <device_id>
16 rodolico 719
                                    and device_type.show_as_system <> 'Y'
3 rodolico 720
                                    and device.removed_date is null
721
                                    and device.name not in ( <keys> )
722
                              ) as b
723
                              )";
724
 
725
 
726
      $queries['find'] = 
727
                    "select
728
                        device_id id,
729
                        device.name  'keyfield',
730
                        device.notes 'info'
731
                     from device join device_type using (device_type_id) 
732
                     where
733
                        device_type.name = 'PCI Card' 
734
                        and device.removed_date is null
735
                        and device.part_of = <device_id>";
736
 
737
      $queries['delete'] =
738
                    "update device
739
                        set removed_date = '$this->reportDateSQL'
740
                        where device_id in ( <ids> )";
741
 
742
 
743
      if ( ! isset( $this->report['pci'] ) ) return;
744
      // make a local copy so we can modify as needed
745
      $pciHash = $this->report['pci'];
746
      # normalize the data
747
      foreach ( array_keys( $pciHash ) as $key ) {
748
         if ( ! is_array( $pciHash[$key] ) ) {
749
            $this->messages[] = 'Invalid PCI format, not recording';
750
            return false;
751
         }
752
         if ( ! isset( $pciHash[$key]['slot'] ) ) { // doesn't have a slot field
753
            $slotField = '';
754
            foreach ( array_keys( $pciHash[$key] ) as $subkey ) { // scan through all keys and see if there is something with a "slot looking" value in it
755
               if ( preg_match ( '/^[0-9a-f:.]+$/' , $pciHash[$key][$subkey] ) )
756
                  $slotField = $subkey;
757
            }
758
            if ( $slotField ) {
759
               $pciHash[$key]['slot'] = $pciHash[$key][$slotField];
760
            } else {
761
               $pciHash[$key]['slot'] = 'Unknown';
762
            }
763
         }
764
         // Each entry must have a name. Use 'device' if it doesn't exist
765
         // Basically, we try each option in turn, with the first test having
766
         // priority.
767
 
768
         if ( ! isset( $pciHash[$key]['name'] ) ) {
769
            // if there is no name, try to use one of the synonyms
770
            foreach ( $nameSynomyms as $testName ) {
771
               if ( isset ( $pciHash[$key][$testName] ) ) {
772
                  $pciHash[$key]['name'] = $pciHash[$key][$testName];
773
                  break;
774
               } // if
775
            } // foreach
776
            if ( empty( $pciHash[$key]['name'] ) ) {
777
               $this->messages[] = "No name given for one or more PCI devices at normalize, Computer ID: [$this->machineID], Report Date: [$this->reportDate]";
778
               //print_r( $pciHash ); 
779
               //die;
780
               return;
781
            }
782
         } elseif ( $pciHash[$key]['name'] == $pciHash[$key]['slot'] ) {
783
            $pciHash[$key]['name'] = $pciHash[$key]['device'];
784
         } // if..else
785
         // Following is what will actually be put in the device table, ie device.name
786
         $pciHash[$key]['keyfield'] = $pciHash[$key]['slot'] . ' - ' . $pciHash[$key]['name'];
787
         ksort( $pciHash[$key] );
788
         $ignore = array( 'keyfield' );
789
         $info = '';
790
         foreach ( $pciHash[$key] as $subkey => $value ) {
791
            if ( in_array( $subkey, $ignore ) )
792
               continue;
793
            $info .= "[$subkey]=$value\n";
794
         }
795
         $pciHash[$key]['info'] = $info;
796
      } // foreach
797
      // at this point, we should have a slot and a name field in all pci devices
798
      $toAdd = $this->AddDeleteUpdate( $pciHash, $queries, 'PCI Devices' );
799
      if ( $toAdd ) {
800
         $pciCardID = getOneDBValue( "select device_type_id from device_type where name = 'PCI Card'");
801
         $count = 0;
802
         foreach ( $toAdd as $entry => $values ) {
803
            $keyfield = makeSafeSQLValue( $values['keyfield'] );
804
            $info = makeSafeSQLValue( $values['info'] );
805
            $query = "insert into device 
806
                        select 
807
                           null,
808
                           site_id,
809
                           $pciCardID,
810
                           $keyfield,
811
                           $info,
812
                           device_id,
813
                           '$this->reportDateSQL',
814
                           null,
815
                           null 
816
                        from device 
817
                        where device_id = $this->machineID";
818
            queryDatabaseExtended( $query );
819
            $count++;
820
         } // foreach
821
         $this->messages[] = "$count PCI devices added/modified";
822
      } // if
823
   } // processPCI
824
 
825
   function getSoftwareID ( $packageName,$versionInfo,$description ) {
826
      $packageName = makeSafeSQLValue( $packageName );
827
      $versionInfo = makeSafeSQLValue( $versionInfo );
828
      $description = makeSafeSQLValue( $description );
829
      // does the package exist?
830
      $packageID = getOneDBValue("select software_id from software where package_name = $packageName and removed_date is null");
831
      if ( !$packageID ) { # NO, package doesn't exist, so add it to the database
832
         $packageID = queryDatabaseExtended( "insert into software (package_name,description, added_date) values ($packageName,$description, '$this->reportDateSQL')");
833
         if ( $packageID['insert_id'] )
834
            $packageID = $packageID['insert_id'];
835
         else {
836
            $this->messages[] = "ERROR: Software Packages - Could not find version $packageName and could not add to database";
837
            $packageID = null;
838
         }
839
      }
840
      // does this version number exist?
841
      $versionID = getOneDBValue( "select software_version_id from software_version where version = $versionInfo and removed_date is null" );
842
      if ( ! $versionID ) { # nope, so add it
843
         $versionID = queryDatabaseExtended( "insert into software_version ( version,added_date ) values ($versionInfo,'$this->reportDateSQL')");
844
         if ( $versionID['insert_id'] )
845
            $versionID = $versionID['insert_id'];
846
         else {
847
            $this->messages[] = "ERROR: Software Packages - Could not find version $versionInfo and could not add to database";
848
            $versionID = null;
849
         }
850
      }
851
      return array( 'package id' => $packageID,'version id' => $versionID);
852
   } // getSoftwareID
853
 
854
 
855
   function processSoftwarePackages (  ) {
856
      // query which removes devices from database that are not in report
857
      // we assume if the report doesn't have it, it has been removed
858
      $queries['remove old'] = 
859
                    "update installed_packages
860
                        set removed_date = '$this->reportDateSQL'
861
                        where installed_packages_id in (
862
                           select installed_packages_id from (
863
                              select
864
                                    installed_packages_id
865
                              from 
866
                                 installed_packages 
867
                                 join software using ( software_id )
868
                                 join software_version using (software_version_id)
869
                              where
870
                                    installed_packages.device_id = <device_id>
871
                                    and installed_packages.removed_date is null
872
                                    and concat(software.package_name,software_version.version) not in ( <keys> )
873
                              ) as b
874
                              )";
875
      $queries['find'] = 
876
           "select 
877
               installed_packages.installed_packages_id 'id',
878
               concat(software.package_name,software_version.version) 'keyfield'
879
            from 
880
               installed_packages 
881
               join software using ( software_id )
882
               join software_version using (software_version_id)
883
            where 
884
               device_id = <device_id>
885
               and installed_packages.removed_date is null";
886
      $queries['delete'] =
887
                    "update installed_packages
888
                        set removed_date = '$this->reportDateSQL'
889
                        where installed_packages_id in ( <ids> )";
890
 
891
      if ( ! isset( $this->report['software'] ) ) return;
892
      // make a local copy so we can modify as needed
893
      $softwareHash = $this->report['software'];
894
      foreach ( array_keys( $softwareHash ) as $key ) {
895
         if ( ! isset( $softwareHash[$key]['name'] ) )
896
            $softwareHash[$key]['name'] = $key;
897
         if ( ! isset( $softwareHash[$key]['description'] ) )
898
            $softwareHash[$key]['description'] = '';
14 rodolico 899
         if ( isset( $softwareHash[$key]['release'] ) ) // some of them have a release number, so we just add that to the version
900
            $softwareHash[$key]['version'] = $softwareHash[$key]['version'] . '-r' . $softwareHash[$key]['release'];
3 rodolico 901
         // This is needed for matching
902
         $softwareHash[$key]['keyfield'] = $softwareHash[$key]['name'] . $softwareHash[$key]['version'];
903
      } // foreach
904
      // at this point, we should have a slot and a name field in all pci devices
905
      $toAdd = $this->AddDeleteUpdate( $softwareHash, $queries, 'Software Packages' );
906
      if ( $toAdd ) {
907
         $count = 0;
908
         foreach ( $toAdd as $key => $value ) {
909
            $ids = $this->getSoftwareID ( $value['name'],$value['version'],$value['description'] );
910
            if ( is_null( $ids['package id'] ) or is_null( $ids['version id'] ) ) {
911
               $this->messages[] = "Could not create entry for package " . $value['name'] . ", version " . $value['version'];
912
            } else {
913
               $insertValues = implode( ',', array( $this->machineID, $ids['package id'], $ids['version id'], "'$this->reportDateSQL'" ) );
914
               $query = "insert into installed_packages
915
                           (device_id,software_id,software_version_id,added_date) 
916
                           values 
917
                           ( $insertValues )";
918
               $database = queryDatabaseExtended( $query );
919
               if ( $database )
920
                  $count++;
921
            } // if..else
922
         } // foreach
923
         if ( $count )
924
            $this->messages[] = "$count software packages added/updated";
925
      }
926
   } // processSoftwarePackages
36 rodolico 927
 
928
 
929
   function processXenVirtual ( $name, $values ) {
930
      // Determine if the virtual is on a new machine or not
931
      $virtualID = getMachineID( $name ); // see if we can find the virtual
3 rodolico 932
 
36 rodolico 933
      if ( $virtualID ) {
934
         if ( $this->machineID == getOneDBValue( "select part_of from device where device.device_id = $virtualID" ) ) {
935
            return;
936
         }
937
      } else { // we could not find the device
938
         $this->messages[] = "Could not locate id for virtual $name which is running on $this->machineName";
939
         return;
940
      }
941
      // we made it this far, which means we found the virtual's ID, but it does not have
942
      // this machine as its parent, so we need to update it.
943
      queryDatabaseExtended( "update device set part_of = $this->machineID where device_id = $virtualID" );
944
      $this->messages[] = "Virtual $name ($virtualID) now running on $this->machineName";
945
   } // processXenVirtual
946
 
947
   function processXen ( ) {
948
      // Is this a Xen DOM0?
949
      if ( ! isset( $this->report['xen'] ) ) return;
950
      $machineID;  // id in database
951
      $machineName;// name in report
952
 
953
      foreach ( $this->report['xen']['virtual'] as $virtual => $data ) {
954
         $this->processXenVirtual( $virtual, $data );
955
      }
956
   } // processXen
957
 
3 rodolico 958
} // class sysinfo
959
 
960
 
961
 
5 rodolico 962
/*
963
 * we don't know where the configuration file will be, so we have a list
964
 * below (searchPaths) to look for it. It will load the first one it 
965
 * finds, then exit. THUS, you could have multiple configuration files
966
 * but only the first one in the list will be used
967
 */
3 rodolico 968
 
5 rodolico 969
$confFileName = "sysinfoRead.conf.yaml";
970
$searchPaths = array( '/etc/camp', '/opt/camp', '/opt/camp/sysinfo', $_SERVER['SCRIPT_FILENAME'], getcwd() );
971
$configuration = array();
972
foreach ( $searchPaths as $path ) {
973
   if ( file_exists( "$path/$confFileName" ) ) {
974
      #print "Found $path/$confFileName\n";
975
      $configuration = yaml_parse_file( "$path/$confFileName" );
976
      #require "$path/$confFileName";
977
      break; // exit out of the loop; we don't try to load it more than once
978
   } // if
979
} // foreach
3 rodolico 980
 
5 rodolico 981
mysql_connect( $configuration['database']['databaseServer'], $configuration['database']['databaseUsername'], $configuration['database']['databasePassword'] ) or die(mysql_error());
982
mysql_select_db( $configuration['database']['database'] ) or die(mysql_error());
983
 
984
 
985
$thisReport = new sysinfo( $configuration['bodyContents'] );
3 rodolico 986
$result; 
987
 
988
$result = $thisReport->loadFromFile( $argc > 1 ? $argv[1] : "php://stdin" );
989
if ( $result == 'ini' ) {
990
   print $thisReport->dumpMessages();
991
   exit(0);
992
}
993
if ( ! $result )
994
   exit ( 1 );
995
$result = $thisReport->processReport();
996
print $thisReport->dumpMessages();
36 rodolico 997
// var_dump( $thisReport );
3 rodolico 998
exit ( $result );
999
 
1000
?>