Subversion Repositories camp_sysinfo_client_3

Rev

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