Subversion Repositories computer_asset_manager_v1

Rev

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