Subversion Repositories camp_sysinfo_client_3

Rev

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

Rev Author Line No. Line
16 rodolico 1
#!/usr/bin/env perl
20 rodolico 2
use warnings;
26 rodolico 3
use strict;  
2 rodolico 4
 
5
# sysinfo
6
# Author: R. W. Rodolico
7
# Primary client portion of sysinfo system. Will collect information about its current
8
# host and create a report containing the information. This report can then be processed
9
# by process_sysinfo.pl on the collection computer.
112 rodolico 10
# output file consists of a YAML file of the form:
2 rodolico 11
#  <sysinfo3.0.0>
12
#    <diskinfo name='/dev/xvda3'>
13
#      <fstype>ext3</fstype>
14
#      <mount>/home</mount>
15
#      <size>51606140</size>
16
#      <used>331472</used>
17
#    </diskinfo>
18
#    <network name='eth0'>
19
#      <address>192.168.1.3</address>
20
#      <ip6address>fe80::216:3eff:fefb:4e10</ip6address>
21
#      <ip6networkbits>64</ip6networkbits>
22
#      <mac>00:16:3e:fb:4e:10</mac>
23
#      <mtu>1500</mtu>
24
#      <netmask>255.255.255.0</netmask>
25
#    </network>
26
#    <operatingsystem>
27
#      <codename>squeeze</codename>
28
#      <description>Debian GNU/Linux 6.0.4 (squeeze)</description>
29
#      <distribution>Debian</distribution>
30
#      <kernel>2.6.32-5-xen-686</kernel>
31
#      <os_name>Linux</os_name>
32
#      <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>
33
#      <release>6.0.4</release>
34
#    </operatingsystem>
35
#    <pci name='0000:00:00.0'>
36
#      <class>RAM memory</class>
37
#      <device>MCP55 Memory Controller</device>
38
#      <rev>a2</rev>
39
#      <sdevice>Device cb84</sdevice>
40
#      <slot>0000:00:00.0</slot>
41
#      <svendor>nVidia Corporation</svendor>
42
#      <vendor>nVidia Corporation</vendor>
43
#    </pci>
44
#    <report>
45
#      <client>Staffmasters</client>
46
#      <date>2012-05-01 03:00</date>
47
#      <version>2.0.0</version>
48
#    </report>
49
#    <software name='aptitude'>
50
#      <description>terminal-based package manager (terminal interface only)</description>
51
#      <version>0.6.3-3.2+squeeze1</version>
52
#    </software>
53
#    <system>
54
#      <cpu_speed>1800.103</cpu_speed>
55
#      <cpu_sub>i686</cpu_sub>
56
#      <cpu_type>GenuineIntel</cpu_type>
57
#      <hostname>backup.staffmasters.local</hostname>
58
#      <last_boot>1333259809</last_boot>
59
#      <memory>520852</memory>
60
#      <num_cpu>1</num_cpu>
61
#    </system>
62
#  </sysinfo3.0.0>
63
 
64
 
65
#
66
# Version 1.3 20071104
67
# added capability of e-mailing the results by itself and external configuration file
68
 
69
# Version 1.3.1 20071110
70
# added du -sk to explicitly do directory sizes in 'k'. Also, fixed some documentation
71
 
72
# Version 1.3.3 20081104
73
# modified hostname to hostname -f, and allowed user to place custom value in configuration file
74
# also, modified to go with Debian standards in preparation to creating a debian package.
75
 
76
# Version 2.0 20081208
77
# Modified to use different libraries for different OS's in preparation to porting to Windows
78
# Uses different packages based on which OS it is on.
79
 
80
# Version 3.0 20120923
81
# Major revision. Most internal intelligence pulled out and put into modules and data transfer format has been changed to YAML
82
#
83
# Base system only pulls client name, machine name and machine number, all of which can be set in the configuration file
84
# if the value is not set, it attempts various means to determine the values and, if it fails, aborts with an error message
85
#    client name -- REQUIRED, must come from configuration file
86
#    machine name --  REQUIRED, if not set via conf file, attempts hostname command (hostname -f) or module getHostName
87
#    machine number -- REQUIRED, if not set via conf file, attempts "echo `hostname -f`-clientname | md5sum" or module getSerial
88
# modules are stored in "configuration directory/modules" (/etc/sysinfo/modules on most Linux systems) and are processed in 
89
# standard sort order (case sensitive). 
90
# Module filenames may contain alpha-numeric, underscore and the period only (files containing other characters are ignored).
91
# Modules should set their exit code to 0 for success, and non-zero for failure
92
# Modules should return 0 or more tab delimited, newline terminated strings, processed as one record per line
93
# A module return string line is processed as follows:
94
#     category \t [category \t ...] \t key \t value
95
# example:
96
#    System \t num_cpu \t 1
97
#    System \t Users \t root \t /root/
98
# (note, if non-zero exit code returned, return value is assumed to be error message and is printed to STDERR) 
99
# sysinfo stores the result in a hash, using categories as the keys (case sensitive), thus, the above results in
100
# $store{'System'}{'num_cpu'} = '1';
101
# $store{'System'}{'Users'}{'root'} = '/root';
102
# upon completion, sysinfo converts the $store hash into an XML or YAML string for transfer
103
# It then sends it to the main server as defined in the conf file.
104
# NOTE: YAML is hand crafted to kill any requirements for external libraries
105
# see sub hashToYAML for details
106
 
9 rodolico 107
# Version 3.0.1 20160321
108
# Renamed to sysinfo-client to not conflict with Linux package sysinfo
109
# created installer in Perl to not rely on package managers
110
# default path for configuration file changed to /etc/camp/sysinfo-client.conf
111
# $VERSION changed to $DATA_VERSION to not conflict with $main::VERSION (script version vs data format version)
13 rodolico 112
#
113
# Version 3.1.0 20160401
114
# module and script dirs now arrays to be searched. Idea is that default
115
#    modules/scripts are in installdir/modules or installdir/scripts, and
116
#    user supplied are in /etc/scripts and /etc/modules
14 rodolico 117
# Tightened up the file systems checks, requiring all scripts and modules
118
#    be set 0700 at least, and owned by root
18 rodolico 119
# Transport layers now an array, and if one fails to send the report, the others
120
#    are tried in turn
14 rodolico 121
# Worked on logic for sendReport to give better error checking.
122
# Doing a search for the configuration file matching cwd, then /etc/camp, then /usr/local/etc/camp
21 rodolico 123
# Self documenting, ie a key for software\tsysinfo-client\version\current version is inserted
28 rodolico 124
#
125
# Version 3.1.1 20160915 RWR
126
# set use strict and use warnings, then fixed errors
37 rodolico 127
#
128
# Version 3.1.2 20160922 RWR
129
# $exitCode 1 (not applicable to this machine) does not throw warning
130
#
42 rodolico 131
# Version 3.1.3 20161010 RWR
132
# Removed extra use warnings
47 rodolico 133
#
134
# Version 3.1.4 20161023 RWR
135
# Would error out if moduledir does not exist, added a return
51 rodolico 136
#
137
# Version 3.1.5 20170327 RWR
138
# On freeBSD systems, was looking in wrong place for configuration file
59 rodolico 139
#
140
# Version 3.2.0 20180320 RWR
62 rodolico 141
# Major change in the configuration file format; All entries are loaded into 
142
# hash %configuration, so clientname is no longer $clientname, but is now
143
# $configuration{'clientname'}
144
# NOT backwards compatible
59 rodolico 145
# changed configuration to be loaded into hash (vs directly loaded into variables)
146
# added UUID to configuration file
62 rodolico 147
#
148
# Version 3.2.1 20180424 RWR
149
# Finally got a semi-stable version of this running. Fixed a bunch of bugs
150
# and appears to be working correctly.
112 rodolico 151
#
152
# Version 3.3.0 20190419 RWR
153
# Converted to use YAML config file
135 rodolico 154
#
155
# Version 3.4.0 20191111 RWR
156
# adding logging with priority. logging is a hash inside of %cvonfiguration which contains the following
157
# $configuration{ 'logging' } = {
158
#    'log type'  => 'string',
159
#    'log level' => #,
160
#    'other params' => something,
161
# };
138 rodolico 162
#
163
# The default log type is cache, which builds an array of all messages passed. When the log type is changed, the cache is
164
# checked for values and, if they exist, they are dumped to the log, then removed.
165
#
135 rodolico 166
# Currently, the only log type is 'file', which has one other additional parameter, 'log path' which
167
# points to the actual log to be created. The log is NOT limited in size, so use something else to
168
# do that.
169
# log level is an integer which is compared the a priority passed to the logging function. The
170
# higher log level is set, the more verbose the log.
171
# 0 - Normal, basically logs when the program starts and ends, and any warnings.
172
# 1 - a little more information about flow
173
# 2 - Gives ending information on structures
174
# 3 - Gives a lot of info about structures when they are initialized and at the end
175
# 4 - Crazy. Dumps just about every structure every time they are changed
176
#
177
# $TESTING has been set to a binary. If true, the report is not sent via the transports, but is dumped to /tmp/sysinfo.testing.yaml
144 rodolico 178
#
179
# Version 3.4.1 20191117 RWR
180
# Added syslog as a possible option for logging.
181
#
135 rodolico 182
 
112 rodolico 183
# find our location and use it for searching for libraries
184
BEGIN {
185
   use FindBin;
186
   use File::Spec;
187
   use lib File::Spec->catdir($FindBin::Bin);
154 rodolico 188
   eval( 'use YAML::Tiny;' );
189
   eval( 'use Data::Dumper;' );
112 rodolico 190
}
62 rodolico 191
 
154 rodolico 192
# contains the directory our script is in
193
my $sourceDir = File::Spec->catdir($FindBin::Bin);
112 rodolico 194
 
154 rodolico 195
# define the version number
196
# see https://metacpan.org/pod/release/JPEACOCK/version-0.97/lib/version.pod
197
use version;
198
our $VERSION = version->declare("v3.5.0");
199
our $DATA_VERSION = version->declare( 'v3.0.0' ); # used in sending the data file. sets version of XML/YAML data file
200
 
201
# see https://perldoc.perl.org/Getopt/Long.html
202
use Getopt::Long;
203
# allow -vvn (ie, --verbose --verbose --dryrun)
204
Getopt::Long::Configure ("bundling");
205
 
2 rodolico 206
# Following are global variables overridden if configuration file exists
207
 
135 rodolico 208
my $TESTING = 0; # if set to 1, will do everything, but will dump output to /tmp/sysinfo.testing.yaml
9 rodolico 209
 
2 rodolico 210
my $indentLevel = 2; # number of spaces to indent per level in XML or YAML
211
 
13 rodolico 212
# paths to search for configuration file
51 rodolico 213
my @confFileSearchPath = ( '.', '/etc/camp/sysinfo-client', '/etc/camp', '/usr/local/etc/camp/sysinfo-client' );
2 rodolico 214
 
112 rodolico 215
my $configurationFile = 'sysinfo-client.yaml'; # name of the configuration file
2 rodolico 216
 
135 rodolico 217
my $reportDate = &timeStamp(); # set report date
2 rodolico 218
 
154 rodolico 219
my $interactive = 0; # if set to 1, will go into interactive mode and output to local file
220
my $periodicOverrideFile = '/tmp/sysinfo.firstrun'; # if this file exists, library.pm will tell all periodic modules to run anyway
221
my $periodic = 0; # if set to 1, will do modules which are only supposed to run weekly, monthly, etc...
222
 
223
my $version;
224
my $help;
225
 
59 rodolico 226
my %configuration = (
142 rodolico 227
   'logging' => { 'log type' => 'cache', 'log level' => 0 },    # if set, will point to logging
154 rodolico 228
   'moduleDirs' => ["$sourceDir/modules"], # search paths for modules
229
   'scriptDirs' => ["$sourceDir/scripts"], # search paths for scripts
59 rodolico 230
   'clientName' => '',  # Required!! Must be set in conf file (no defaults)
231
   'serialNumber' => '', # serial number of machine
232
   'UUID'         => '', # UUID of machine
154 rodolico 233
   'transports'   => {'3' => { '-name-' => 'saveLocal', 'sendScript' => 'save_local', 'output directory' => "$sourceDir/reports" }  }, # hash with various transports
61 rodolico 234
   'hostname' => &getHostName() # fully qualified host name of machine
154 rodolico 235
);
2 rodolico 236
 
237
 
13 rodolico 238
 
136 rodolico 239
#######################################################
240
#
241
# timeStamp
242
#
243
# return current system date as YYYY-MM-DD HH:MM:SS
244
#
245
#######################################################
246
sub timeStamp {
247
   my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
142 rodolico 248
   return sprintf "%4d-%02d-%02d %02d:%02d:%02d",$year+1900,$mon+1,$mday,$hour,$min,$sec;
136 rodolico 249
}
250
 
138 rodolico 251
#######################################################
252
# function to simply log things
135 rodolico 253
# first parameter is the priority, if <= $logDef->{'log level'} will print
254
# all subsequent parameters assumed to be strings to sent to the log
255
# returns 0 on failure
256
#         1 on success
257
#         2 if priority > log level
258
#        -1 if $logDef is unset
259
# currently, only logs to a file
138 rodolico 260
#######################################################
135 rodolico 261
sub logIt {
262
   my $priority = shift;
13 rodolico 263
 
135 rodolico 264
   return -1 unless exists $configuration{'logging'};
265
   return 2 unless $priority <= $configuration{'logging'}{'log level'};
138 rodolico 266
   if ( $configuration{'logging'}{'log type'} eq 'cache' ) {
267
      push @{ $configuration{'logging'}{'cache'} }, @_;
268
      return;
269
   } elsif ( defined( $configuration{'logging'}{'cache'} ) ) {
270
      unshift @_, @{ $configuration{'logging'}{'cache'} };
271
      delete $configuration{'logging'}{'cache'};
272
   }
135 rodolico 273
   if ( $configuration{'logging'}{'log type'} eq 'file' ) {
274
      if ( open LOG, '>>' . $configuration{'logging'}{'log path'} ) {
275
         while ( my $t = shift ) {
276
            print LOG &timeStamp() . "\t$t\n";
277
         }
278
         close LOG;
279
      }
144 rodolico 280
   } elsif ( $configuration{'logging'}{'log type'} eq 'syslog' ) {
281
      use Sys::Syslog;                        # all except setlogsock()
282
      use Sys::Syslog qw(:standard :macros);  # standard functions & macros
283
 
284
      my $syslogName = 'sysinfo-client';
285
      my $logopt = 'nofatal';
286
      my $facility = 'LOG_LOCAL0';
287
      my $priority = 'LOG_NOTICE';
288
 
289
      openlog( $syslogName, $logopt, $facility);
290
      syslog($priority, '%s', @_ );
291
      closelog();
135 rodolico 292
   } else {
293
      warn "Log type $configuration{'logging'} incorrectly configured\n";
294
      return 0;
295
   }
296
   return 1;
297
}
298
 
299
 
2 rodolico 300
#######################################################
301
#
13 rodolico 302
# findFile( $filename, @directories )
303
#
304
# Locates a file by searching sequentially in one or more
305
# directories, returning the first one found
306
# 
307
# Returns '' if not found
308
#
309
#######################################################
310
 
311
sub findFile {
59 rodolico 312
   my ( $filename, $directories ) = @_;
138 rodolico 313
   &logIt( 3, "Looking for $filename in findFile" );
59 rodolico 314
   for ( my $i = 0; $i < scalar( @{$directories} ); $i++ ) {
315
      my $confFile = $$directories[$i] . '/' . $filename;
138 rodolico 316
      &logIt( 4, "Looking for $filename in $confFile" );
13 rodolico 317
      return $confFile if ( -f $confFile );
318
   }
319
   return '';
320
}
321
 
322
 
323
#######################################################
324
#
2 rodolico 325
# loadConfigurationFile($confFile)
326
#
327
# Loads configuration file defined by $configurationFile, and dies if not available
112 rodolico 328
# This is a YAML file containing serialized contents of 
154 rodolico 329
# Parameters:
330
#    $fileName - name of file to look for
331
#    @searchPath - array of paths to find $filename
2 rodolico 332
#
333
#######################################################
334
 
135 rodolico 335
sub loadConfigurationFile {   
14 rodolico 336
   my ( $fileName, @searchPath ) = @_;
141 rodolico 337
   &logIt( 2, "Looking for config file $fileName in " . join( ', ', @searchPath ) );
13 rodolico 338
   my $confFile;
59 rodolico 339
   if ( $confFile = &findFile( $fileName, \@searchPath ) ) {
138 rodolico 340
      &logIt( 3, "Opening configuration from $confFile" );
112 rodolico 341
      my $yaml = YAML::Tiny->read( $confFile );
138 rodolico 342
      &logIt( 4, "Configuration file contents\n$yaml" );
112 rodolico 343
      return $yaml->[0];
13 rodolico 344
   }
14 rodolico 345
   die "Can not find $fileName in any of " . join( "\n\t", @searchPath ) . "\n";
2 rodolico 346
}
347
 
348
#######################################################
349
#
350
# sendResults( $parameters, $message, $scriptDirectory )
351
#
352
# Sends results of run to server using external script. If external
353
# script not defined, just print to STDOUT
354
#
355
# Parameters
356
#  $parameters - a hash containing the information necessary to make the transfer
357
#  $message - the message to be sent
358
#  $scriptDirectory - path (not filename) of script to be executed
359
# 
360
# $parameters contains different key/value pairs depending on the script used
361
#             for example, a stand-alone SMTP script may need a username/password,
362
#             smtp server name, port number, from and to address
363
#             while an http transfer may only need a script name
364
#             See the individual scripts to determine what parameters need to be
365
#             filled in.
366
#             The only required parameter is 'sendScript' which must contain the
367
#             name of the script to execute (and it must be located in $scriptDirectory)
368
# SCRIPT must contain one sub named doit, that accepts three parameters, the hash, 
369
#       the message, and, optionally, the script directory
370
#
371
# If script not defined, just dump to STDOUT. With a properly set up cron job, the output
372
# would then be sent via e-mail to an administrative account, possibly root
373
#
374
#######################################################
375
sub sendResults {
62 rodolico 376
   my ( $globals, $transports, $message, $scriptDirectory ) = @_;
135 rodolico 377
   &logIt( 3, "Entering sendResults" );
113 rodolico 378
   foreach my $key ( sort { $a <=> $b } %$transports ) {
379
      if ( $transports->{$key}->{'sendScript'} ) {
135 rodolico 380
         &logIt( 3, "Trying to find file " . $transports->{$key}->{'sendScript'} . " in " . join( "\n\t", @{$scriptDirectory} ) );
113 rodolico 381
         my $sendScript = &findFile( $transports->{$key}->{'sendScript'}, $scriptDirectory );
19 rodolico 382
         if ( $sendScript ) {
18 rodolico 383
            # load the chosen script into memory
384
            require $sendScript;
19 rodolico 385
            # merge the globals in
386
            while ( my ( $gkey, $value ) = each %$globals ) { 
113 rodolico 387
               $transports->{$key}->{$gkey} = $value; 
19 rodolico 388
            }
20 rodolico 389
            # do variable substitution for any values which need it
113 rodolico 390
            foreach my $thisOne ( keys %{$transports->{$key}} ) {
135 rodolico 391
               &logIt( 4, "$thisOne" );
113 rodolico 392
               if ( $transports->{$key}->{$thisOne} =~ m/(\$configuration\{'hostname'\})|(\$reportDate)|(\$configuration\{'clientName'\})|(\$configuration\{'serialNumber'\})/ ) {
393
                  $transports->{$key}->{$thisOne} = eval "\"$transports->{$key}->{$thisOne}\"";
20 rodolico 394
               }
395
            }
396
 
62 rodolico 397
            #%$transports{$key}{keys %$globals} = values %$globals;
398
            #print Dumper( $$transports[$key] );
20 rodolico 399
            #next;
18 rodolico 400
            # execute the "doit" sub from that script
135 rodolico 401
            &logIt( 3, $message );
402
            my $return = &doit( $transports->{$key}, $message );
403
            return $return if ( $return == 1 );
18 rodolico 404
         } else {
135 rodolico 405
            &logIt( 0,"Could not find " . $$transports[$key]{'sendScript'} . ", trying next transport" );
18 rodolico 406
         } # if..else
407
      } # if
408
   } # foreach
409
   # if we made it here, we have not sent the report, so just return it to the user
85 rodolico 410
   # if called from a cron job, it will (hopefully) be sent to root
135 rodolico 411
   &logIt( 0, 'Error, reached ' . __LINE__ . " which should not happen, message was\n$message" );
85 rodolico 412
   print $message;
16 rodolico 413
   return 1;
2 rodolico 414
}
415
 
416
#######################################################
417
#
418
# getHostName
419
#
420
# return hostname from hostname -f
421
#
422
#######################################################
423
sub getHostName {
135 rodolico 424
   &logIt( 3, "Entering getHostName" );
28 rodolico 425
   my $hostname = `hostname -f`;
2 rodolico 426
   chomp $hostname;
427
   return $hostname;
428
}
429
 
430
#######################################################
431
#
18 rodolico 432
# escapeForYAML
2 rodolico 433
#
18 rodolico 434
# Escapes values put into YAML report
2 rodolico 435
#
112 rodolico 436
# DEPRECATED AS OF VERSION 3.3.0
437
# uses YAML::Tiny
438
#
2 rodolico 439
#######################################################
112 rodolico 440
#sub escapeForYAML {
441
#   my $value = shift;
442
#   $value =~ s/'/\\'/gi; # escape single quotes
443
#   $value =~ s/"/\\"/gi; # escape double quotes
444
#   # pound sign indicates start of a comment and thus loses part
445
#   # of strings. Surrounding it by double quotes in next statement
446
#   # allows 
447
#   $value = '"' . $value . '"' if ( $value =~ m/[#:]/ );
448
#   return $value;
449
#}
2 rodolico 450
 
451
#######################################################
452
#
453
# hashToYAML( $hashRef, $indent )
454
#
455
# Converts a hash to a YAML string
456
#
457
# NOTE: This routine recursively calls itself for every level
458
#       in the hash
459
#
460
# Parameters
461
#     $hashref - reference (address) of a hash
462
#     $indent  - current indent level, defaults to 0
463
#
464
# Even though there are some very good libraries that do this
465
# I chose to hand-code it so sysinfo can be run with no libraries
466
# loaded. I chose to NOT do a full implementation, so special chars
467
# that would normally be escaped are not in here. 
468
# However, I followed all the RFC for the values that were given, so
469
# assume any YAML reader can parse this
470
# NOTE: YAML appears to give a resulting file 1/3 smaller than the above
471
#       XML, and compresses down in like manner
472
#
112 rodolico 473
# DEPRECATED AS OF VERSION 3.3.0
474
# uses YAML::Tiny
475
#
2 rodolico 476
#######################################################
112 rodolico 477
#sub hashToYAML {
478
#   my ($hashRef, $indent) = @_;
479
#   $indent = 0 unless $indent; # default to 0 if not defined
480
#   
481
#   my $output; # where the output is stored
482
#   foreach my $key ( keys %$hashRef ) { # for each key in the current reference
483
#      print "Looking at $key\n" if $TESTING > 3;
484
#      # see http://www.perlmonks.org/?node_id=175651 for isa function
485
#      if ( UNIVERSAL::isa( $$hashRef{$key}, 'HASH' ) ) { # is the value another hash?
486
#            # NOTE: unlike xml, indentation is NOT optional in YAML, so the following line verifies $indentlevel is non-zero
487
#            #       and, if it is, uses a default 3 character indentation
488
#            $output .= (' ' x $indent ) . &escapeForYAML($key) . ":\n" . # key, plus colon, plus newline
489
#                    &hashToYAML( $$hashRef{$key}, $indent+($indentLevel ? $indentLevel : 3) ) . # add results of recursive call
490
#                    "\n";
491
#      } elsif ( UNIVERSAL::isa( $$hashRef{$key}, 'ARRAY' ) ) { # is it an array? ignore it
492
#      } else { # it is a scalar, so just do <key>value</key>
493
#         $output .= (' ' x $indent ) . &escapeForYAML($key) . ': ' . &escapeForYAML($$hashRef{$key}) . "\n";
494
#      }
495
#   }
496
#   return $output;
497
#}
2 rodolico 498
 
499
 
500
#######################################################
501
#
502
# tabDelimitedToHash ($hashRef, $tabdelim)
503
#
504
# Takes a tab delimited multi line string and adds it
505
# to a hash. The final field in each line is considered to
506
# be the value, and all prior fields are considered to be
507
# hierachial keys.
508
#
509
# Parameters
510
#     $hashref - reference (address) of a hash
511
#     $tabdelim - A tab delimited, newline terminated set of records
512
#
513
#
514
#######################################################
515
sub tabDelimitedToHash {
516
   my ($hashRef, $tabdelim) = @_;
135 rodolico 517
   &logIt( 3, "Entering tabDelimitedToHash" );
2 rodolico 518
   foreach my $line ( split( "\n", $tabdelim ) ) { # split on newlines, then process each line in turn
519
      $line =~ s/'/\\'/gi; # escape single quotes
28 rodolico 520
      my @fields = split( / *\t */, $line ); # get all the field values into array
2 rodolico 521
      my $theValue = pop @fields; # the last one is the value, so save it
522
      # now, we build a Perl statement that would create the assignment. The goal is
523
      # to have a string that says something like $$hashRef{'key'}{'key'} = $value;
524
      # then, eval that.
525
      my $command = '$$hashRef'; # start with the name of the dereferenced hash (parameter 1)
526
      while (my $key = shift @fields) { # while we have a key, from left to right
527
         $command .= '{' . "'$key'" . '}'; # build it as {'key'} concated to string
528
      }
529
      $command .= "='$theValue';"; # add the assignment
530
      #print STDERR "$command\n"; 
531
      eval $command; # eval the string to make the actual assignment
532
   }
533
}
534
 
535
#######################################################
536
#
13 rodolico 537
# validatePermission ( $file )
538
#
539
# Checks that file is owned by root, and has permission
540
# 0700 or less
541
# 
542
# Returns empty string on success, error message
543
# on failure
544
#
545
#######################################################
546
 
547
sub validatePermission {
548
   my $file = shift;
135 rodolico 549
   &logIt( 3, "Entering validatePermission with $file" );
14 rodolico 550
   my $return;
13 rodolico 551
   # must be owned by root
28 rodolico 552
   my $owner = (stat($file))[4];
13 rodolico 553
   $return .= " - Bad Owner [$owner]" if $owner;
554
   # must not have any permissions for group or world
555
   # ie, 0700 or less
28 rodolico 556
   my $mode = (stat($file))[2];
13 rodolico 557
   $mode = sprintf( '%04o', $mode & 07777 );
558
   $return .= " - Bad Permission [$mode]" unless $mode =~ m/0.00/;
559
   return $return ? $file . $return : '';
560
}
561
 
562
#######################################################
563
#
2 rodolico 564
# ProcessModules ( $system, $moduleDir )
565
#
566
# Processes all modules in $moduleDir, adding result to $system hash
567
# 
568
# Parameters
569
#     $system - reference (address) of a hash
570
#     $moduleDir - full path to a directory containing executable scripts
571
#  
572
# Each file in the $moduleDir directory that matches the regex in the grep
573
# and is executable is run. It is assumed the script will return 0 on success
574
# or a non-zero on failure
575
# The output of the script is assumed to be a tab delimited, newline separated
576
# list of records that should be added to the hash $system. This is done by calling 
577
# &parseModule above.
578
# on failure, the returned output of the script is assumed to be an error message
579
# and is displayed on STDERR
580
#######################################################
581
sub ProcessModules {
582
   my ( $system, $moduleDir ) = @_;
135 rodolico 583
   &logIt( 3, "Entering processModules" );
2 rodolico 584
   # open the module directory
47 rodolico 585
   return unless -d $moduleDir;
2 rodolico 586
   opendir( my $dh, $moduleDir ) || die "Module Directory $moduleDir can not be opened: $!\n";
587
   # and get all files which are executable and contain nothing but alpha-numerics and underscores (must begin with alpha-numeric)
588
   my @modules = grep { /^[a-zA-Z0-9][a-zA-Z0-9_]+$/ && -x "$moduleDir/$_" } readdir( $dh );
589
   closedir $dh;
28 rodolico 590
   foreach my $modFile ( sort @modules ) { # for each valid script
14 rodolico 591
      if ( my $error = &validatePermission( "$moduleDir$modFile" ) ) {
13 rodolico 592
         print STDERR "Not Processed: $error\n";
593
         next;
594
      }
135 rodolico 595
      &logIt( 3, "Processing module $moduleDir$modFile");
2 rodolico 596
      my $output = qx/$moduleDir$modFile $moduleDir/; # execute it and grab the output
597
      my $exitCode = $? >> 8; # process the exitCode
37 rodolico 598
      # exitCode 0 - processed normally
599
      # exitCode 1 - not applicable to this machine
600
      if ( $exitCode && $exitCode > 1) { # if non-zero, error, so show an error message
2 rodolico 601
         warn "Error in $moduleDir$modFile, [$output]\n";
135 rodolico 602
         &logIt( 0, "Error in $moduleDir$modFile, [$output]" );
2 rodolico 603
      } else { # otherwise, call tabDelimitedToHash to save the data
604
         &tabDelimitedToHash( $system, $output );
21 rodolico 605
      } # if
606
   } # foreach
607
   # add sysinfo-client (me) to the software list, since we're obviously installed
608
   &tabDelimitedToHash( $system, "software\tsysinfo-client\tversion\t$main::VERSION\n" );
2 rodolico 609
}
610
 
154 rodolico 611
sub getDMIDecode {
612
   my ( $key, $type ) = @_;
613
   my $command = 'dmidecode ';
614
   $command .= "-t $type " if $type;
615
   $command .= " | grep -i '$key'";
616
   my $value = `$command`;
617
   chomp $value;
618
   if ( $value =~ m/:\s*(.*)\s*$/ ) {
619
      return $1;
620
   } else {
621
      return '';
622
   }
623
}
624
 
625
sub interactiveConfig {
626
   my $config = shift;
627
   $config->{'moduleDirs'} = $config->{'moduleDirs'}[0];
628
   $config->{'scriptDirs'} = $config->{'scriptDirs'}[0];
629
   $config->{'UUID'} = getDMIDecode( 'uuid', 'system' ) unless $config->{'UUID'};
630
   $config->{'serialNumber'} = getDMIDecode( 'serial number', 'system' ) unless $config->{'serialNumber'};
631
 
632
   my %menu = (
633
      1 => {'prompt' => 'Host Name', 'key' => 'hostname' },
634
      2 => {'prompt' => 'Client Name', 'key' => 'clientName' },
635
      3 => {'prompt' => 'Serial Number', 'key' => 'serialNumber' },
636
      4 => {'prompt' => 'UUID', 'key' => 'UUID' },
637
      5 => {'prompt' => 'Modules Directory', 'key' => 'moduleDirs' },
638
      6 => {'prompt' => 'Scripts Directory', 'key' => 'scriptDirs' }
639
   );
640
   my $choice = 'quit';
641
   while ( $choice ) {
642
      foreach my $menuItem ( sort keys %menu ) {
643
         print "$menuItem\. " . $menu{$menuItem}{'prompt'} . ': ' . $config->{$menu{$menuItem}{'key'}} . "\n";
20 rodolico 644
      }
154 rodolico 645
      print "Enter Menu Item to change, or press Enter to proceed ";
646
      $choice = <>;
647
      chomp $choice;
648
      last unless $choice;
649
      print $menu{$choice}{'prompt'} . ' [' . $config->{$menu{$choice}{'key'}} . '] : ';
650
      my $value = <>;
651
      chomp $value;
652
      $config->{$menu{$choice}{'key'}} = $value if ($value);
653
   }
654
   $config->{'moduleDirs'} = [ $config->{'moduleDirs'} ];
655
   $config->{'scriptDirs'} = [ $config->{'scriptDirs'} ];
656
   return $config;
20 rodolico 657
}
658
 
154 rodolico 659
# simple display if --help is passed
660
sub help {
661
   use File::Basename;
662
   print basename($0) . " $VERSION\n";
663
   print <<END
664
$0 [options]
665
Options:
666
   -i,
667
   --interactive    - do not read configuration file
668
   --version        - display version and exit
669
   -c,
670
   --client='xxx'   - Client name for interactive mode
671
   -s,
672
   --serial='xxx'   - Serial Number for interactive mode
673
   -h,
674
   --hostname='xxx' - override hostname
675
   -m,
676
   --modules=/path/ - override path to modules
677
   --scripts=/path/ - override path to scripts
678
   -p,
679
   --periodic       - runs modules designed to be run only weekly, monthly, etc...
680
END
681
}
20 rodolico 682
 
154 rodolico 683
 
684
# handle any command line parameters that may have been passed in
685
 
686
GetOptions (
687
            'interactive|i' => \$interactive, # ask questions instead of using config file
688
            'periodic|p'    => \$periodic,    # will do modules which are marked as periodic
689
            'help|h'        => \$help,
690
            'version'       => \$version,
691
            'client|c=s'    => \$configuration{clientName},
692
            'serial|s=s'    => \$configuration{serialNumber},
693
            'hostname=s'    => \$configuration{hostname},
694
            'modules|m=s'   => \$configuration{moduleDirs},
695
            'scripts=s'     => \$configuration{scriptDirs},
696
            ) or die "Error parsing command line\n";
697
 
698
 
699
if ( $help ) { &help() ; exit; }
700
if ( $version ) { use File::Basename; print basename($0) . " $VERSION\n"; exit; }
701
 
702
if ( $interactive ) {
703
   %configuration = %{ &interactiveConfig( \%configuration ) };
704
} else {
705
   # load the configuration file
706
   %configuration = %{ &loadConfigurationFile( $configurationFile, @confFileSearchPath) };
707
}
708
 
709
`touch $periodicOverrideFile` if $periodic; # tells periodic modules to run
710
 
711
#die Dumper (\%configuration );
135 rodolico 712
 
2 rodolico 713
# user did not define a serial number, so make something up
59 rodolico 714
$configuration{'serialNumber'} = '' unless $configuration{'serialNumber'};
2 rodolico 715
# oops, no client name (required) so tell them and exit
61 rodolico 716
die "No client name defined in $configurationFile" unless $configuration{'clientName'};
2 rodolico 717
 
135 rodolico 718
&logIt( 0, 'Starting sysinfo Run' );
719
&logIt( 3, "Configuration is\n" . Data::Dumper->Dump( [\%configuration], [ qw($configuration) ] ) );
720
 
61 rodolico 721
$TESTING = $configuration{'TESTING'} if defined $configuration{'TESTING'};
722
 
135 rodolico 723
&logIt( 0, "Testing => $TESTING" ) if $TESTING;
76 rodolico 724
 
725
 
2 rodolico 726
my $System; # hash reference that will store all info we are going to send to the server
727
# some defaults.
154 rodolico 728
$System->{'report'}->{'version'} = $DATA_VERSION->normal;
135 rodolico 729
$System->{'report'}->{'date'} = $reportDate;
730
$System->{'report'}->{'client'} = $configuration{'clientName'};
731
$System->{'system'}->{'hostname'} = $configuration{'hostname'};
732
$System->{'system'}->{'serial'} = $configuration{'serialNumber'};
733
$System->{'system'}->{'UUID'} = $configuration{'UUID'};
2 rodolico 734
 
135 rodolico 735
&logIt( 3, "Initial System\n" . Data::Dumper->Dump( [$System], [qw( $System )] ) );
736
 
2 rodolico 737
# process any modules in the system
59 rodolico 738
foreach my $moduleDir ( @{$configuration{'moduleDirs'}} ) {
135 rodolico 739
   &logIt( 3, "Processing modules from $moduleDir" );
13 rodolico 740
   &ProcessModules( $System, "$moduleDir/" );
741
}
2 rodolico 742
 
135 rodolico 743
&logIt( 4, "After processing modules\n" . Data::Dumper->Dump( [$System], [qw( $System )] ) );
744
 
154 rodolico 745
my $out =  sprintf( "#sysinfo: %s YAML\n", $VERSION->normal ) . &Dump( $System );
2 rodolico 746
 
135 rodolico 747
&logIt( 4, 'At line number ' . __LINE__ . "\n" . Data::Dumper->Dump([$System],[qw($System)]) );
2 rodolico 748
 
19 rodolico 749
# load some global values for use in the script, if required
750
my $globals = { 
154 rodolico 751
      'data version' => $DATA_VERSION->normal,
19 rodolico 752
      'report date'  => $reportDate,
59 rodolico 753
      'client name'  => $configuration{'clientName'},
754
      'host name'    => $configuration{'hostname'},
61 rodolico 755
      'serial number'=> $configuration{'serialNumber'},
756
      'UUID'         => $configuration{'UUID'}
19 rodolico 757
      };
62 rodolico 758
 
135 rodolico 759
&logIt( 4, "Globals initialized\n" . Data::Dumper->Dump([$globals],[qw($globals)]) );
760
 
761
if ( $TESTING ) {
762
   open DATA, ">/tmp/sysinfo.testing.yaml" or die "Could not write to /tmp/sysinfo.testing.yaml: $!\n";
763
   print DATA $out;
764
   close DATA;
765
} else {
766
   # and send the results to the server
767
   if ( my $success = &sendResults( $globals, $configuration{'transports'}, $out, $configuration{'scriptDirs'} ) != 1 ) {
768
      &logIt( 0, "Error $success while sending report from $configuration{'hostname'}" );
769
   }
16 rodolico 770
}
2 rodolico 771
 
154 rodolico 772
unlink ( $periodicOverrideFile ) if -e $periodicOverrideFile;
135 rodolico 773
&logIt( 0, 'Ending sysinfo Run' );
774
 
154 rodolico 775
 
9 rodolico 776
1;