Subversion Repositories camp_sysinfo_client_3

Rev

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

Rev Author Line No. Line
21 rodolico 1
#!/usr/bin/env perl
2
 
45 rodolico 3
# v1.2.0 20161022 RWR
4
# moved makeConfig here so it is usable by install and configure
77 rodolico 5
#
6
# v1.3.0 20190108 RWR
7
# added UUID and set defaults for config file
85 rodolico 8
#
9
# v1.4.0 20190204 RWR
10
# added autoconvert from v1.2 configuration file to v1.3
11
# using dumper to set configuration file
94 rodolico 12
#
13
# version 2.0 20190330 RWR
14
# changed it so all configs are YAML
125 rodolico 15
#
16
# version 2.1 20191101 RWR
17
# changed --name-- tag to name
129 rodolico 18
#
19
# version 2.2 20191105 RWR
20
# fixed where dmidecode missing caused exception
135 rodolico 21
#
22
# version 2.2.1 20191112 RWR
23
# added timeStamp
194 rodolico 24
#
25
# version 2.3.0 20220609 RWR
26
# moved loadConfigurationFile and timeStamp here
45 rodolico 27
 
21 rodolico 28
package sysinfoconf;
29
 
42 rodolico 30
 
194 rodolico 31
our $VERSION = '2.3.0';
21 rodolico 32
use warnings;
26 rodolico 33
use strict;  
34
 
92 rodolico 35
#use Data::Dumper;
144 rodolico 36
use YAML::Tiny;
35 rodolico 37
use File::Basename;
227 rodolico 38
use Data::Dumper;
35 rodolico 39
 
21 rodolico 40
use Exporter;
41
 
42
our @ISA = qw( Exporter );
194 rodolico 43
our @EXPORT = qw( $clientName $serialNumber $hostname 
44
                  $transports $sysinfo3 $binDir $moduleDir
45
                  $scriptDir $confDir $binName $confName $configurationFile
46
                  @confFileSearchPath  @moduleDirs @scriptDirs
228 rodolico 47
                  %sendTypes %displayOrder
21 rodolico 48
                  &showConf &transportsToConfig &getAnswer &yesno  
144 rodolico 49
                  &writeConfig &processParameters $TESTING
50
                  &setDryRun &enableModules &makeConfig &findConf &timeStamp
197 rodolico 51
                  &loadConfigurationFile &logIt &findFile
21 rodolico 52
                );
53
 
36 rodolico 54
our $TESTING = 0;
35 rodolico 55
our $dryRun;
28 rodolico 56
our $clientName = '';
57
our $serialNumber = '';
58
our $hostname = '';
53 rodolico 59
 
227 rodolico 60
my %serialNumberTranslation = ( 
61
   'notspecified' => '', # not set in DMI
62
   '0123456789' => '' # used by some SuperMicro computers
63
);
64
 
65
my %UUIDTranslation = ( 
66
   '03000200-0400-0500-0006-000700080009' => '', # some routers
67
   'sot settable' => '' # not set in DMI
68
);
69
 
194 rodolico 70
# paths to search for configuration file
71
my @confFileSearchPath = ( '.', '/etc/camp/sysinfo-client', '/etc/camp', '/usr/local/etc/camp/sysinfo-client' );
227 rodolico 72
my $serverInfoFileName = '/etc/server.info';
104 rodolico 73
 
228 rodolico 74
our %displayOrder = (
75
      '1' => {
76
         'fieldname' => 'clientName',
77
         'display' => 'Client Name',
78
         'type' => 'scalar',
79
         },
80
      '2' => {
81
         'fieldname' => 'hostname',
82
         'display' => 'Hostname',
83
         'type' => 'scalar',
84
         },
85
      '3' => {
86
         'fieldname' => 'UUID',
87
         'display' => 'UUID',
88
         'type' => 'scalar',
89
         },
90
      '4' => {
91
         'fieldname' => 'serialNumber',
92
         'display' => 'Serial Number',
93
         'type' => 'scalar',
94
         },
95
      '5' => {
96
         'fieldname' => 'location',
97
         'display' => 'Location',
98
         'type' => 'scalar',
99
         },
100
      '6' => {
101
         'fieldname' => 'os_type',
102
         'display' => 'OS Type',
103
         'type' => 'scalar',
104
         },
105
      '7' => {
106
         'fieldname' => 'tags',
107
         'display' => 'Tags',
108
         'type' => 'array',
109
         },
110
      '8' => {
111
         'fieldname' => 'moduleDirs',
112
         'display' => 'Module Directories',
113
         'type' => 'array',
114
         },
115
      '9' => {
116
         'fieldname' => 'scriptDirs',
117
         'display' => 'Script Directories',
118
         'type' => 'array',
119
         },
120
      'a' => {
121
         'fieldname' => 'transports',
122
         'display' => 'Transports',
123
         'type' => 'function',
124
         'function' => 'editTransports'
125
         },
126
   );
127
 
128
 
194 rodolico 129
my $configurationFile = 'sysinfo-client.yaml'; # name of the configuration file
104 rodolico 130
 
194 rodolico 131
 
53 rodolico 132
my @installDirs = ( '/opt/camp/sysinfo-client', '/usr/local/opt/camp/sysinfo-client' );
133
my @confDirs =    ( '/etc/camp/sysinfo-client', '/usr/local/etc/camp/sysinfo-client' );
134
 
135
 
28 rodolico 136
our @moduleDirs = ( '/opt/camp/sysinfo-client/modules', '/etc/camp/sysinfo-client/modules' );
137
our @scriptDirs = ( '/opt/camp/sysinfo-client/scripts', '/etc/camp/sysinfo-client/scripts' );
111 rodolico 138
our $transports = {}; # holds transportation mechanisms
21 rodolico 139
 
103 rodolico 140
our $sysinfo3 = 'sysinfo-client.yaml';
21 rodolico 141
 
28 rodolico 142
our $binDir = '/opt/camp/sysinfo-client';
44 rodolico 143
our $moduleDir = $binDir . '/modules';
144
our $scriptDir = $binDir . '/scripts';
28 rodolico 145
our $confDir = '/etc/camp/sysinfo-client';
21 rodolico 146
 
28 rodolico 147
our $binName = 'sysinfo-client';
107 rodolico 148
our $confName = 'sysinfo-client.yaml';
21 rodolico 149
 
35 rodolico 150
sub setDryRun {
151
   $dryRun = shift;
152
}
21 rodolico 153
 
28 rodolico 154
our %sendTypes = ( 
21 rodolico 155
                  'SendEmail' =>    { 'sendScript' => 'sendEmailScript',
156
                                      'keys' => 
157
                                      [
158
                                        'mailTo',
159
                                        'mailSubject',
160
                                        'mailCC',
161
                                        'mailBCC',
162
                                        'mailServer',
163
                                        'mailFrom',
164
                                        'logFile',
165
                                        'otherCLParams',
166
                                        'tls',
167
                                        'smtpUser',
168
                                        'smtpPass',
169
                                        'sendEmailScriptLocation'
170
                                      ],
171
                                    },
172
                  'HTTP Upload' =>  { 'sendScript' => 'upload_http',
173
                                      'keys' => 
174
                                      [
175
                                        'URL',
176
                                        'key for report',
177
                                        'key for date',
178
                                        'key for hostname',
179
                                        'key for client',
180
                                        'key for serial number'
181
                                      ]
86 rodolico 182
                                    },
183
                  'Save Local' =>   { 'sendScript' => 'save_local',
184
                                      'keys' =>
185
                                      [
186
                                         'output directory'
187
                                      ]
188
                                   }
21 rodolico 189
                );
190
 
191
 
135 rodolico 192
#######################################################
193
#
194
# timeStamp
195
#
196
# return current system date as YYYY-MM-DD HH:MM:SS
197
#
198
#######################################################
199
sub timeStamp {
200
   my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
143 rodolico 201
   return sprintf "%4d-%02d-%02d %02d:%02d:%02d",$year+1900,$mon+1,$mday,$hour,$min,$sec;
135 rodolico 202
}
203
 
204
 
37 rodolico 205
sub enableModules {
206
   my $moduleDir = shift;
207
   my %modules;
208
   if ( opendir( my $dh, "$moduleDir" ) ) {
209
      %modules = map{ $_ => { 'enabled' => -x "$moduleDir/$_" } } 
210
                 grep { ! /^\./ } 
211
                 readdir $dh;
212
      closedir( $dh );
213
      foreach my $filename ( keys %modules ) {
214
         if ( open FILE,"<$moduleDir/$_" ) {
215
            my @descript = grep{ /^# Description: (.*)/ } <FILE>;
216
            close FILE;
217
            chomp @descript;
218
            $modules{$filename}{'description'} = $descript[0];
219
         } # if
220
      } # foreach
221
   } # if
222
} # enableModules
223
 
21 rodolico 224
sub showConf {
81 rodolico 225
 
35 rodolico 226
   my $configuration = shift;
92 rodolico 227
   $configuration = Dump($configuration);
84 rodolico 228
   return $configuration;
21 rodolico 229
}
230
 
231
sub transportsToConfig {
35 rodolico 232
   my $transports = shift;
21 rodolico 233
   my $config;
234
   foreach my $priority ( sort { $a <=> $b } keys %$transports ) {
124 rodolico 235
      my $name = $$transports{ $priority }{'name'};
21 rodolico 236
      $config .= "# Tranport $name at priority $priority\n";
237
      my $thisOne = $$transports{ $priority };
238
      foreach my $key ( sort keys %$thisOne ) {
239
         $config .= "\$\$transports{$priority}{'$key'} = '$$thisOne{$key}';\n";
240
      } # foreach
241
   } # foreach
242
   return $config;
243
} # transportsToConfig
244
 
227 rodolico 245
sub readServerInfo {
246
   my $serverInfoName = shift;
247
   my %return;
94 rodolico 248
 
227 rodolico 249
   print "Reading server info from $serverInfoName\n";
250
 
251
   if ( -f $serverInfoName ) {
252
      print "found $serverInfoName\n";
253
      open DATA, $serverInfoName or die "Could not read $serverInfoName: $!\n";
254
      print "opened $serverInfoName\n";
255
      while ( my $line = <DATA> ) {
256
         next if $line =~ m/^#/;
257
         chomp $line;
258
         my ($key,$value) = split( ':', $line );
259
         $key =~ s/^\s+|\s+$//g;
260
         $value =~ s/^\s+|\s+$//g;
261
         # note, we make the key lower case so we can find it
262
         $return{ lc $key} = $value;
223 rodolico 263
      }
264
   }
227 rodolico 265
   return \%return;
223 rodolico 266
}
267
 
227 rodolico 268
 
45 rodolico 269
sub makeConfig {
227 rodolico 270
   my $configFile = shift;
223 rodolico 271
   my $config = {}; # make sure it is a ref to a hash so mergeHash can recognize it
227 rodolico 272
   my $serverInfo = readServerInfo( $serverInfoFileName );
273
   # die Dumper( $serverInfo );
274
   if ( -f $configFile ) {
218 rodolico 275
      print "Processing config file $configFile\n";
227 rodolico 276
      my $yaml = YAML::Tiny->read( $configFile );
277
      $config = $yaml->[0];
45 rodolico 278
   }
227 rodolico 279
 
280
   # Fill in any values we are missing but which are found in $serverInfo (/etc/server.info)
281
   $config->{'clientName'} = defined( $serverInfo->{'owner'} ) ? $serverInfo->{'owner'} : '' unless $config->{'clientName'};
282
   $config->{'hostname'} = defined( $serverInfo->{'hostname'} ) ? $serverInfo->{'hostname'} : '' unless $config->{'hostname'};
283
   $config->{'serialNumber'} = defined( $serverInfo->{'serial'} ) ? $serverInfo->{'serial'} : '' unless $config->{'serialNumber'};
284
   $config->{'UUID'} = defined( $serverInfo->{'uuid'} ) ? $serverInfo->{'uuid'} : '' unless $config->{'UUID'};
285
   $config->{'location'} = defined( $serverInfo->{'location'} ) ? $serverInfo->{'location'} : '' unless $config->{'location'};
286
   $config->{'os_type'} = defined( $serverInfo->{'os_type'} ) ? $serverInfo->{'os_type'} : '' unless $config->{'os_type'};
287
   $config->{'tags'} = defined( $serverInfo->{'tags'} ) ? [ split ',', $serverInfo->{'tags'} ] : [] unless $config->{'tags'};
288
 
289
   # if these are still missing, we can try to run a program to get the values
218 rodolico 290
   unless ( $config->{'hostname'} ) {
227 rodolico 291
      $config->{'hostname'} = `hostname -f`;
292
      chomp $config->{'hostname'};
45 rodolico 293
   }
218 rodolico 294
   unless ( $config->{'serialNumber'} ) {
227 rodolico 295
      $config->{'serialNumber'} = `dmidecode -s system-serial-number` if `which dmidecode`;
296
      chomp $config->{'serialNumber'};
297
      $config->{'serialNumber'} =~ s/\s//gi;
298
      $config->{'serialNumber'} = $serialNumberTranslation{lc($config->{'serialNumber'})} if defined( $serialNumberTranslation{lc($config->{'serialNumber'})} );
53 rodolico 299
   }
218 rodolico 300
   unless ( $config->{'UUID'} ) {
227 rodolico 301
      $config->{'UUID'} = `which dmidecode` ?  `dmidecode -t 1 | grep -i uuid | cut -d':' -f2` : '' if `which dmidecode`;
302
      $config->{'UUID'} =~ s/\s//gi;
303
      $config->{'UUID'} = $UUIDTranslation{lc($config->{'UUID'})} if defined( $UUIDTranslation{lc($config->{'UUID'})} );
77 rodolico 304
   }
227 rodolico 305
   unless ( $config->{'os_type'} ) {
306
      $config->{'os_type'} = `installer/determineOS` if -x 'installer/determineOS';
307
   }
219 rodolico 308
 
228 rodolico 309
   unless ( $config->{'moduleDirs'} ) {
310
      $config->{'moduleDirs'} = [];
311
      push @{ $config->{'moduleDirs'} }, $binDir . '/modules';
312
      push @{ $config->{'moduleDirs'} }, $confDir . '/modules';
313
   }
314
 
315
   unless ( $config->{'scriptDirs'} ) {
316
      $config->{'scriptDirs'} = [];
317
      push @{ $config->{'scriptDirs'} }, $binDir . '/scripts';
318
      push @{ $config->{'scriptDirs'} }, $confDir . '/scripts';
319
   }
320
 
321
   unless ( $config->{'transports'} ) {
322
      $config->{'transports'}->{'30'} = {
323
         'name' => 'SaveLocal',
324
         'output directory' => '/tmp',
325
         'sendScript' => 'save_local'
326
      }
327
   }
328
 
218 rodolico 329
   return $config;
45 rodolico 330
}
331
 
21 rodolico 332
# prompt the user for a response, then allow them to enter it
333
# the first response is considered the default and is printed
334
# in all caps if more than one exists
335
# first answer is used if they simply press the Enter
336
# key. The response is returned all lower case if more than one
337
# exists.
338
# it is assumed 
339
sub getAnswer {
340
   my ( $prompt, @answers ) = @_;
341
   $answers[0] = '' unless defined( $answers[0] );
342
   my $default = $answers[0];
343
   my $onlyOneAnswer = scalar( @answers ) == 1;
344
   print $prompt . '[ ';
345
   $answers[0] = uc $answers[0] unless $onlyOneAnswer;
346
   print join( ' | ', @answers ) . ' ]: ';
28 rodolico 347
   my $thisAnswer = <>;
21 rodolico 348
   chomp $thisAnswer;
349
   $thisAnswer = $default unless $thisAnswer;
350
   return $thisAnswer;
351
}
352
 
353
sub yesno {
40 rodolico 354
   my ( $prompt, $default ) = @_;
355
   $default = 'yes' unless $default;
356
   my $answer = &getAnswer( $prompt, $default eq 'yes' ? ('yes','no' ) : ('no', 'yes') );
21 rodolico 357
   return lc( substr( $answer, 0, 1 ) ) eq 'y';
358
}
359
 
360
sub writeConfig {
132 rodolico 361
   use File::Temp qw / tempfile /;
35 rodolico 362
   my ( $filename,$content ) = @_;
129 rodolico 363
   if ( $filename ) { # they sent us a filename
364
      my $path;
365
      ($filename, $path ) = fileparse( $filename );
366
      `mkdir -p $path` unless -d $path;
367
      $filename = $path . '/' . $filename;
21 rodolico 368
      `cp $filename $filename.bak` if ( -e $filename );
129 rodolico 369
      unless ( $dryRun ) {
370
         open CONF,">$filename" or die "Could not write to $filename: $!\n";
371
         print CONF $content;
372
         close CONF;
373
         `chmod 600 $filename`;
374
      }
375
   } else { # no path provided, so just create a temp file
376
      # we will create a temporary file and return the name
377
      # it is the calling programs responsiblity to remove the file
378
      my $fh;
379
      ($fh,$filename) = tempfile( UNLINK => 0 );
380
      print $fh $content;
381
      close $fh
21 rodolico 382
   }
129 rodolico 383
   return $filename;
21 rodolico 384
}
385
 
386
sub processParameters {
387
   while ( my $parameter = shift ) {
388
      if ( $parameter eq '-v' ) {
26 rodolico 389
         print "$VERSION\n";
21 rodolico 390
         exit;
391
      }
392
   } # while
393
}
394
 
53 rodolico 395
sub findConf {
396
   my $confName = shift;
397
   for ( my $i = 0; $i < @confDirs; $i++ ) {
398
      if ( -d $confDirs[ $i ] ) {
55 rodolico 399
         return ( $confDirs[$i],  $confName );
53 rodolico 400
      }
401
   }
104 rodolico 402
   return ( '', $confName );
53 rodolico 403
}
21 rodolico 404
 
194 rodolico 405
#######################################################
406
#
407
# findFile( $filename, @directories )
408
#
409
# Locates a file by searching sequentially in one or more
410
# directories, returning the first one found
411
# 
412
# Returns '' if not found
413
#
414
#######################################################
104 rodolico 415
 
194 rodolico 416
sub findFile {
417
   my ( $filename, $directories ) = @_;
418
   &logIt( 3, "Looking for $filename in findFile" );
419
   for ( my $i = 0; $i < scalar( @{$directories} ); $i++ ) {
420
      my $confFile = $$directories[$i] . '/' . $filename;
421
      &logIt( 4, "Looking for $filename in $confFile" );
422
      return $confFile if ( -f $confFile );
423
   }
424
   return '';
425
}
426
 
104 rodolico 427
 
194 rodolico 428
#######################################################
429
#
430
# loadConfigurationFile($confFile)
431
#
432
# Loads configuration file defined by $configurationFile, and dies if not available
433
# This is a YAML file containing serialized contents of 
434
# Parameters:
435
#    $$fileName - name of file to look for (reference)
436
#    @searchPath - array of paths to find $filename
437
#
438
#######################################################
104 rodolico 439
 
194 rodolico 440
sub loadConfigurationFile {   
441
   my ( $fileName, @searchPath ) = @_;
442
   $$fileName = $configurationFile unless $$fileName;
443
   @searchPath = @confFileSearchPath unless @searchPath;
444
   &logIt( 2, "Looking for config file $$fileName in " . join( ', ', @searchPath ) );
445
   my $confFile;
446
   if ( $confFile = &findFile( $$fileName, \@searchPath ) ) {
447
      &logIt( 3, "Opening configuration from $confFile" );
448
      my $yaml = YAML::Tiny->read( $confFile );
449
      &logIt( 4, "Configuration file contents\n$yaml" );
450
      $$fileName = $confFile;
451
      return $yaml->[0];
452
   }
453
   die "Can not find $fileName in any of " . join( "\n\t", @searchPath ) . "\n";
454
}
455
 
456
 
457
#######################################################
458
# function to simply log things
459
# first parameter is the priority, if <= $logDef->{'log level'} will print
460
# all subsequent parameters assumed to be strings to sent to the log
461
# returns 0 on failure
462
#         1 on success
463
#         2 if priority > log level
464
#        -1 if $logDef is unset
465
# currently, only logs to a file
466
#######################################################
467
sub logIt {
468
   my $priority = shift;
469
 
470
   # turn off variable checking so it doesn't blow up on lack of %configuration file
471
   no strict 'vars';
472
 
473
   return -1 unless exists $configuration{'logging'};
474
   return 2 unless $priority <= $configuration{'logging'}{'log level'};
475
   if ( $configuration{'logging'}{'log type'} eq 'cache' ) {
476
      push @{ $configuration{'logging'}{'cache'} }, @_;
477
      return;
478
   } elsif ( defined( $configuration{'logging'}{'cache'} ) ) {
479
      unshift @_, @{ $configuration{'logging'}{'cache'} };
480
      delete $configuration{'logging'}{'cache'};
481
   }
482
   if ( $configuration{'logging'}{'log type'} eq 'file' ) {
483
      if ( open LOG, '>>' . $configuration{'logging'}{'log path'} ) {
484
         while ( my $t = shift ) {
485
            print LOG &timeStamp() . "\t$t\n";
486
         }
487
         close LOG;
488
      }
489
   } elsif ( $configuration{'logging'}{'log type'} eq 'syslog' ) {
490
      use Sys::Syslog;                        # all except setlogsock()
491
      use Sys::Syslog qw(:standard :macros);  # standard functions & macros
492
 
493
      my $syslogName = 'sysinfo-client';
494
      my $logopt = 'nofatal';
495
      my $facility = 'LOG_LOCAL0';
496
      my $priority = 'LOG_NOTICE';
497
 
498
      openlog( $syslogName, $logopt, $facility);
499
      syslog($priority, '%s', @_ );
500
      closelog();
501
   } else {
502
      warn "Log type $configuration{'logging'} incorrectly configured\n";
503
      return 0;
504
   }
505
   return 1;
506
}
507
 
508
 
509
 
21 rodolico 510
1;