Subversion Repositories camp_sysinfo_client_3

Rev

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

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