Subversion Repositories camp_sysinfo_client_3

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
16 rodolico 1
#!/usr/bin/env perl
20 rodolico 2
use warnings;
2 rodolico 3
 
4
# sysinfo
5
# Author: R. W. Rodolico
6
# Primary client portion of sysinfo system. Will collect information about its current
7
# host and create a report containing the information. This report can then be processed
8
# by process_sysinfo.pl on the collection computer.
9
# output file consists of an XML file of the form:
10
#  <sysinfo3.0.0>
11
#    <diskinfo name='/dev/xvda3'>
12
#      <fstype>ext3</fstype>
13
#      <mount>/home</mount>
14
#      <size>51606140</size>
15
#      <used>331472</used>
16
#    </diskinfo>
17
#    <network name='eth0'>
18
#      <address>192.168.1.3</address>
19
#      <ip6address>fe80::216:3eff:fefb:4e10</ip6address>
20
#      <ip6networkbits>64</ip6networkbits>
21
#      <mac>00:16:3e:fb:4e:10</mac>
22
#      <mtu>1500</mtu>
23
#      <netmask>255.255.255.0</netmask>
24
#    </network>
25
#    <operatingsystem>
26
#      <codename>squeeze</codename>
27
#      <description>Debian GNU/Linux 6.0.4 (squeeze)</description>
28
#      <distribution>Debian</distribution>
29
#      <kernel>2.6.32-5-xen-686</kernel>
30
#      <os_name>Linux</os_name>
31
#      <os_version>Linux version 2.6.32-5-xen-686 (Debian 2.6.32-41) (ben@decadent.org.uk) (gcc version 4.3.5 (Debian 4.3.5-4) ) #1 SMP Mon Jan 16 19:46:09 UTC 2012</os_version>
32
#      <release>6.0.4</release>
33
#    </operatingsystem>
34
#    <pci name='0000:00:00.0'>
35
#      <class>RAM memory</class>
36
#      <device>MCP55 Memory Controller</device>
37
#      <rev>a2</rev>
38
#      <sdevice>Device cb84</sdevice>
39
#      <slot>0000:00:00.0</slot>
40
#      <svendor>nVidia Corporation</svendor>
41
#      <vendor>nVidia Corporation</vendor>
42
#    </pci>
43
#    <report>
44
#      <client>Staffmasters</client>
45
#      <date>2012-05-01 03:00</date>
46
#      <version>2.0.0</version>
47
#    </report>
48
#    <software name='aptitude'>
49
#      <description>terminal-based package manager (terminal interface only)</description>
50
#      <version>0.6.3-3.2+squeeze1</version>
51
#    </software>
52
#    <system>
53
#      <cpu_speed>1800.103</cpu_speed>
54
#      <cpu_sub>i686</cpu_sub>
55
#      <cpu_type>GenuineIntel</cpu_type>
56
#      <hostname>backup.staffmasters.local</hostname>
57
#      <last_boot>1333259809</last_boot>
58
#      <memory>520852</memory>
59
#      <num_cpu>1</num_cpu>
60
#    </system>
61
#  </sysinfo3.0.0>
62
 
63
 
64
#
65
# Version 1.3 20071104
66
# added capability of e-mailing the results by itself and external configuration file
67
 
68
# Version 1.3.1 20071110
69
# added du -sk to explicitly do directory sizes in 'k'. Also, fixed some documentation
70
 
71
# Version 1.3.3 20081104
72
# modified hostname to hostname -f, and allowed user to place custom value in configuration file
73
# also, modified to go with Debian standards in preparation to creating a debian package.
74
 
75
# Version 2.0 20081208
76
# Modified to use different libraries for different OS's in preparation to porting to Windows
77
# Uses different packages based on which OS it is on.
78
 
79
# Version 3.0 20120923
80
# Major revision. Most internal intelligence pulled out and put into modules and data transfer format has been changed to YAML
81
#
82
# Base system only pulls client name, machine name and machine number, all of which can be set in the configuration file
83
# if the value is not set, it attempts various means to determine the values and, if it fails, aborts with an error message
84
#    client name -- REQUIRED, must come from configuration file
85
#    machine name --  REQUIRED, if not set via conf file, attempts hostname command (hostname -f) or module getHostName
86
#    machine number -- REQUIRED, if not set via conf file, attempts "echo `hostname -f`-clientname | md5sum" or module getSerial
87
# modules are stored in "configuration directory/modules" (/etc/sysinfo/modules on most Linux systems) and are processed in 
88
# standard sort order (case sensitive). 
89
# Module filenames may contain alpha-numeric, underscore and the period only (files containing other characters are ignored).
90
# Modules should set their exit code to 0 for success, and non-zero for failure
91
# Modules should return 0 or more tab delimited, newline terminated strings, processed as one record per line
92
# A module return string line is processed as follows:
93
#     category \t [category \t ...] \t key \t value
94
# example:
95
#    System \t num_cpu \t 1
96
#    System \t Users \t root \t /root/
97
# (note, if non-zero exit code returned, return value is assumed to be error message and is printed to STDERR) 
98
# sysinfo stores the result in a hash, using categories as the keys (case sensitive), thus, the above results in
99
# $store{'System'}{'num_cpu'} = '1';
100
# $store{'System'}{'Users'}{'root'} = '/root';
101
# upon completion, sysinfo converts the $store hash into an XML or YAML string for transfer
102
# It then sends it to the main server as defined in the conf file.
103
# NOTE: YAML is hand crafted to kill any requirements for external libraries
104
# see sub hashToYAML for details
105
 
9 rodolico 106
# Version 3.0.1 20160321
107
# Renamed to sysinfo-client to not conflict with Linux package sysinfo
108
# created installer in Perl to not rely on package managers
109
# default path for configuration file changed to /etc/camp/sysinfo-client.conf
110
# $VERSION changed to $DATA_VERSION to not conflict with $main::VERSION (script version vs data format version)
13 rodolico 111
#
112
# Version 3.1.0 20160401
113
# module and script dirs now arrays to be searched. Idea is that default
114
#    modules/scripts are in installdir/modules or installdir/scripts, and
115
#    user supplied are in /etc/scripts and /etc/modules
14 rodolico 116
# Tightened up the file systems checks, requiring all scripts and modules
117
#    be set 0700 at least, and owned by root
18 rodolico 118
# Transport layers now an array, and if one fails to send the report, the others
119
#    are tried in turn
14 rodolico 120
# Worked on logic for sendReport to give better error checking.
121
# Doing a search for the configuration file matching cwd, then /etc/camp, then /usr/local/etc/camp
21 rodolico 122
# Self documenting, ie a key for software\tsysinfo-client\version\current version is inserted
9 rodolico 123
 
124
 
2 rodolico 125
# Following are global variables overridden if configuration file exists
126
 
16 rodolico 127
use warnings;
128
 
2 rodolico 129
my $TESTING = 0; # level's 0 (none) to 3 defined and increase verbosity while decreasing functionality
13 rodolico 130
$main::VERSION = '3.1.0';
9 rodolico 131
 
2 rodolico 132
my $indentLevel = 2; # number of spaces to indent per level in XML or YAML
133
 
134
$indentLevel = 3 if $TESTING;
135
if ($TESTING) {
136
   use Data::Dumper;
137
}
138
 
13 rodolico 139
# paths to search for configuration file
19 rodolico 140
my @confFileSearchPath = ( '.', '/etc/camp/sysinfo-client', '/etc/camp', '/usr/local/etc/camp' );
2 rodolico 141
 
13 rodolico 142
my $configurationFile = 'sysinfo-client.conf'; # name of the configuration file
2 rodolico 143
 
144
# default values may be overridden in conf file
14 rodolico 145
my @moduleDirs;
146
my @scriptDirs;
2 rodolico 147
my $reportDate = &getReportDate; # set report date
148
 
149
# defined only in configuration file
150
my $clientName; # Required!! Must be set in conf file (no defaults)
13 rodolico 151
my $hostname = &getHostName; # set hostname to default to hostname -f, unless overridden in conf file
2 rodolico 152
my $serialNumber; # defined in configuration file, or later in here if not defined there
18 rodolico 153
my $transports; # hash which can optionally use a script to send the report to the server
2 rodolico 154
 
9 rodolico 155
my $DATA_VERSION = '3.0.0'; # used in sending the data file. sets version of XML/YAML data file
2 rodolico 156
 
13 rodolico 157
 
158
 
2 rodolico 159
#######################################################
160
#
13 rodolico 161
# findFile( $filename, @directories )
162
#
163
# Locates a file by searching sequentially in one or more
164
# directories, returning the first one found
165
# 
166
# Returns '' if not found
167
#
168
#######################################################
169
 
170
sub findFile {
171
   my ( $filename, @directories ) = @_;
172
   for ( $i = 0; $i < scalar( @directories ); $i++ ) {
14 rodolico 173
      $confFile = $directories[$i] . '/' . $filename;
13 rodolico 174
      return $confFile if ( -f $confFile );
175
   }
176
   return '';
177
}
178
 
179
 
180
#######################################################
181
#
2 rodolico 182
# loadConfigurationFile($confFile)
183
#
184
# Loads configuration file defined by $configurationFile, and dies if not available
185
# Reads entire contents into memory where it is eval'd in main program
186
# Parameters: configuration file fully path/file name
187
# NOTE: conf file must be a valid Perl file
188
#
189
#######################################################
190
 
191
sub loadConfigurationFile {
14 rodolico 192
   my ( $fileName, @searchPath ) = @_;
13 rodolico 193
   my $confFile;
14 rodolico 194
   if ( $confFile = &findFile( $fileName, @searchPath ) ) {
13 rodolico 195
      open CONFFILE, "<$confFile" or die "Can not open configuration file $confFile: $!\n";
196
      my $confFileContents = join( '', <CONFFILE> ); # just slurp it into memory
197
      close CONFFILE;
198
      return ($confFileContents);
199
   }
14 rodolico 200
   die "Can not find $fileName in any of " . join( "\n\t", @searchPath ) . "\n";
2 rodolico 201
}
202
 
203
#######################################################
204
#
205
# sendResults( $parameters, $message, $scriptDirectory )
206
#
207
# Sends results of run to server using external script. If external
208
# script not defined, just print to STDOUT
209
#
210
# Parameters
211
#  $parameters - a hash containing the information necessary to make the transfer
212
#  $message - the message to be sent
213
#  $scriptDirectory - path (not filename) of script to be executed
214
# 
215
# $parameters contains different key/value pairs depending on the script used
216
#             for example, a stand-alone SMTP script may need a username/password,
217
#             smtp server name, port number, from and to address
218
#             while an http transfer may only need a script name
219
#             See the individual scripts to determine what parameters need to be
220
#             filled in.
221
#             The only required parameter is 'sendScript' which must contain the
222
#             name of the script to execute (and it must be located in $scriptDirectory)
223
# SCRIPT must contain one sub named doit, that accepts three parameters, the hash, 
224
#       the message, and, optionally, the script directory
225
#
226
# If script not defined, just dump to STDOUT. With a properly set up cron job, the output
227
# would then be sent via e-mail to an administrative account, possibly root
228
#
229
#######################################################
230
sub sendResults {
19 rodolico 231
   my ( $globals, $parameters, $message, @scriptDirectory ) = @_;
18 rodolico 232
   foreach my $key ( sort { $a <=> $b } keys %$parameters ) {
19 rodolico 233
      if ( $$parameters{$key}{'sendScript'} ) {
234
         # print "Trying to find file " . $$parameters{$key}{'sendScript'} . " in " . join( "\n\t", @scriptDirectory ) . "\n";
235
         my $sendScript = &findFile( $$parameters{$key}{'sendScript'}, @scriptDirectory );
236
         if ( $sendScript ) {
18 rodolico 237
            # load the chosen script into memory
238
            require $sendScript;
19 rodolico 239
            # merge the globals in
240
            while ( my ( $gkey, $value ) = each %$globals ) { 
241
               $$parameters{$key}{$gkey} = $value; 
242
            }
20 rodolico 243
            # do variable substitution for any values which need it
244
            foreach my $thisOne ( keys %{$$parameters{$key}} ) {
245
               #print "$thisOne\n";
246
               if ( $$parameters{$key}{$thisOne} =~ m/(\$hostname)|(\$reportDate)|(\$clientName)|(\$serialNumber)/ ) {
247
                  $$parameters{$key}{$thisOne} = eval "\"$$parameters{$key}{$thisOne}\"";
248
               }
249
            }
250
 
19 rodolico 251
            #%$parameters{$key}{keys %$globals} = values %$globals;
252
            #print Dumper( $$parameters{$key} );
20 rodolico 253
            #next;
18 rodolico 254
            # execute the "doit" sub from that script
255
            $return = &doit( $$parameters{$key}, $message );
256
            return $return if ( $return == 1 );
257
         } else {
258
            print "Could not find " . $$parameters{$key}{'sendScript'} . ", trying next transport\n";
259
         } # if..else
260
      } # if
261
   } # foreach
262
   # if we made it here, we have not sent the report, so just return it to the user
263
   print $message;
16 rodolico 264
   return 1;
2 rodolico 265
}
266
 
267
#######################################################
268
#
269
# getReportDate
270
#
271
# return current system date as YYYY-MM-DD HH:MM:SS
272
#
273
#######################################################
274
sub getReportDate {
275
   ($second, $minute, $hour, $dayOfMonth, $month, $year) = localtime();
276
   return sprintf( "%4u-%02u-%02u %02u:%02u:%02u", $year+1900, $month+1, $dayOfMonth, $hour, $minute, $second );
277
}
278
 
279
#######################################################
280
#
281
# getHostName
282
#
283
# return hostname from hostname -f
284
#
285
#######################################################
286
sub getHostName {
287
   $hostname = `hostname -f`;
288
   chomp $hostname;
289
   return $hostname;
290
}
291
 
292
#######################################################
293
#
18 rodolico 294
# escapeForYAML
2 rodolico 295
#
18 rodolico 296
# Escapes values put into YAML report
2 rodolico 297
#
298
#######################################################
299
sub escapeForYAML {
300
   my $value = shift;
301
   $value =~ s/'/\\'/gi; # escape single quotes
302
   $value =~ s/"/\\"/gi; # escape double quotes
303
   # pound sign indicates start of a comment and thus loses part
304
   # of strings. Surrounding it by double quotes in next statement
305
   # allows 
306
   $value = '"' . $value . '"' if ( $value =~ m/[#:]/ );
307
   return $value;
308
}
309
 
310
#######################################################
311
#
312
# hashToYAML( $hashRef, $indent )
313
#
314
# Converts a hash to a YAML string
315
#
316
# NOTE: This routine recursively calls itself for every level
317
#       in the hash
318
#
319
# Parameters
320
#     $hashref - reference (address) of a hash
321
#     $indent  - current indent level, defaults to 0
322
#
323
# Even though there are some very good libraries that do this
324
# I chose to hand-code it so sysinfo can be run with no libraries
325
# loaded. I chose to NOT do a full implementation, so special chars
326
# that would normally be escaped are not in here. 
327
# However, I followed all the RFC for the values that were given, so
328
# assume any YAML reader can parse this
329
# NOTE: YAML appears to give a resulting file 1/3 smaller than the above
330
#       XML, and compresses down in like manner
331
#
332
#######################################################
333
sub hashToYAML {
334
   my ($hashRef, $indent) = @_;
335
   $indent = 0 unless $indent; # default to 0 if not defined
336
 
337
   my $output; # where the output is stored
338
   foreach my $key ( keys %$hashRef ) { # for each key in the current reference
339
      print "Looking at $key\n" if $TESTING > 3;
340
      # see http://www.perlmonks.org/?node_id=175651 for isa function
341
      if ( UNIVERSAL::isa( $$hashRef{$key}, 'HASH' ) ) { # is the value another hash?
342
            # NOTE: unlike xml, indentation is NOT optional in YAML, so the following line verifies $indentlevel is non-zero
343
            #       and, if it is, uses a default 3 character indentation
344
            $output .= (' ' x $indent ) . &escapeForYAML($key) . ":\n" . # key, plus colon, plus newline
345
                    &hashToYAML( $$hashRef{$key}, $indent+($indentLevel ? $indentLevel : 3) ) . # add results of recursive call
346
                    "\n";
347
      } elsif ( UNIVERSAL::isa( $$hashRef{$key}, 'ARRAY' ) ) { # is it an array? ignore it
348
      } else { # it is a scalar, so just do <key>value</key>
349
         $output .= (' ' x $indent ) . &escapeForYAML($key) . ': ' . &escapeForYAML($$hashRef{$key}) . "\n";
350
      }
351
   }
352
   return $output;
353
}
354
 
355
 
356
#######################################################
357
#
358
# tabDelimitedToHash ($hashRef, $tabdelim)
359
#
360
# Takes a tab delimited multi line string and adds it
361
# to a hash. The final field in each line is considered to
362
# be the value, and all prior fields are considered to be
363
# hierachial keys.
364
#
365
# Parameters
366
#     $hashref - reference (address) of a hash
367
#     $tabdelim - A tab delimited, newline terminated set of records
368
#
369
#
370
#######################################################
371
sub tabDelimitedToHash {
372
   my ($hashRef, $tabdelim) = @_;
373
   foreach my $line ( split( "\n", $tabdelim ) ) { # split on newlines, then process each line in turn
374
      $line =~ s/'/\\'/gi; # escape single quotes
375
      @fields = split( / *\t */, $line ); # get all the field values into array
376
      my $theValue = pop @fields; # the last one is the value, so save it
377
      # now, we build a Perl statement that would create the assignment. The goal is
378
      # to have a string that says something like $$hashRef{'key'}{'key'} = $value;
379
      # then, eval that.
380
      my $command = '$$hashRef'; # start with the name of the dereferenced hash (parameter 1)
381
      while (my $key = shift @fields) { # while we have a key, from left to right
382
         $command .= '{' . "'$key'" . '}'; # build it as {'key'} concated to string
383
      }
384
      $command .= "='$theValue';"; # add the assignment
385
      #print STDERR "$command\n"; 
386
      eval $command; # eval the string to make the actual assignment
387
   }
388
}
389
 
390
#######################################################
391
#
13 rodolico 392
# validatePermission ( $file )
393
#
394
# Checks that file is owned by root, and has permission
395
# 0700 or less
396
# 
397
# Returns empty string on success, error message
398
# on failure
399
#
400
#######################################################
401
 
402
sub validatePermission {
403
   my $file = shift;
14 rodolico 404
   my $return;
13 rodolico 405
   # must be owned by root
406
   $owner = (stat($file))[4];
407
   $return .= " - Bad Owner [$owner]" if $owner;
408
   # must not have any permissions for group or world
409
   # ie, 0700 or less
410
   $mode = (stat($file))[2];
411
   $mode = sprintf( '%04o', $mode & 07777 );
412
   $return .= " - Bad Permission [$mode]" unless $mode =~ m/0.00/;
413
   return $return ? $file . $return : '';
414
}
415
 
416
#######################################################
417
#
2 rodolico 418
# ProcessModules ( $system, $moduleDir )
419
#
420
# Processes all modules in $moduleDir, adding result to $system hash
421
# 
422
# Parameters
423
#     $system - reference (address) of a hash
424
#     $moduleDir - full path to a directory containing executable scripts
425
#  
426
# Each file in the $moduleDir directory that matches the regex in the grep
427
# and is executable is run. It is assumed the script will return 0 on success
428
# or a non-zero on failure
429
# The output of the script is assumed to be a tab delimited, newline separated
430
# list of records that should be added to the hash $system. This is done by calling 
431
# &parseModule above.
432
# on failure, the returned output of the script is assumed to be an error message
433
# and is displayed on STDERR
434
#######################################################
435
sub ProcessModules {
436
   my ( $system, $moduleDir ) = @_;
437
   # open the module directory
438
   opendir( my $dh, $moduleDir ) || die "Module Directory $moduleDir can not be opened: $!\n";
439
   # and get all files which are executable and contain nothing but alpha-numerics and underscores (must begin with alpha-numeric)
440
   my @modules = grep { /^[a-zA-Z0-9][a-zA-Z0-9_]+$/ && -x "$moduleDir/$_" } readdir( $dh );
441
   closedir $dh;
442
   foreach $modFile ( sort @modules ) { # for each valid script
14 rodolico 443
      if ( my $error = &validatePermission( "$moduleDir$modFile" ) ) {
13 rodolico 444
         print STDERR "Not Processed: $error\n";
445
         next;
446
      }
2 rodolico 447
      print "Processing module $moduleDir$modFile\n" if $TESTING > 2;
448
      my $output = qx/$moduleDir$modFile $moduleDir/; # execute it and grab the output
449
      my $exitCode = $? >> 8; # process the exitCode
450
      if ( $exitCode ) { # if non-zero, error, so show an error message
451
         warn "Error in $moduleDir$modFile, [$output]\n";
452
      } else { # otherwise, call tabDelimitedToHash to save the data
453
         &tabDelimitedToHash( $system, $output );
21 rodolico 454
      } # if
455
   } # foreach
456
   # add sysinfo-client (me) to the software list, since we're obviously installed
457
   &tabDelimitedToHash( $system, "software\tsysinfo-client\tversion\t$main::VERSION\n" );
2 rodolico 458
}
459
 
20 rodolico 460
sub processParameters {
461
   while ( my $parameter = shift ) {
462
      if ( $parameter eq '-v' ) {
463
         print "$main::VERSION\n";
464
         exit;
465
      }
466
   } # while
467
}
468
 
469
&processParameters( @ARGV );
470
 
14 rodolico 471
# load the configuration file
13 rodolico 472
 
14 rodolico 473
#die "Searching for $configurationFile in = \n" . join( "\n", @confFileSearchPath ) . "\n";
13 rodolico 474
eval ( &loadConfigurationFile( $configurationFile, @confFileSearchPath) );
2 rodolico 475
# user did not define a serial number, so make something up
18 rodolico 476
$serialNumber = '' unless $serialNumber;
2 rodolico 477
# oops, no client name (required) so tell them and exit
478
die "You must configure this package in $configurationFile" unless $clientName;
479
 
480
my $System; # hash reference that will store all info we are going to send to the server
481
# some defaults.
9 rodolico 482
$$System{'report'}{'version'} = $DATA_VERSION;
2 rodolico 483
$$System{'report'}{'date'} = $reportDate;
484
$$System{'report'}{'client'} = $clientName;
485
$$System{'system'}{'hostname'} = $hostname;
486
$$System{'system'}{'serial'} = $serialNumber;
487
 
488
# process any modules in the system
13 rodolico 489
foreach $moduleDir ( @moduleDirs ) {
490
   &ProcessModules( $System, "$moduleDir/" );
491
}
2 rodolico 492
 
493
# now, everything ins in $System, so convert it to the proper output format
20 rodolico 494
my $out =  "#sysinfo: $VERSION YAML\n---\n" . &hashToYAML( $System ) . "...\n";
2 rodolico 495
 
496
print Data::Dumper->Dump([$System],['System']) if $TESTING>3;
497
 
19 rodolico 498
# load some global values for use in the script, if required
499
my $globals = { 
500
      'data version' => $DATA_VERSION,
501
      'report date'  => $reportDate,
502
      'client name'  => $clientName,
503
      'host name'    => $hostname,
504
      'serial number'=> $serialNumber
505
      };
14 rodolico 506
 
2 rodolico 507
# and send the results to the server
19 rodolico 508
if ( my $success = &sendResults( $globals, $transports, $out, @scriptDirs ) != 1 ) {
16 rodolico 509
   print "Error $success while sending report from $hostname\n";
510
}
2 rodolico 511
 
9 rodolico 512
1;