Subversion Repositories camp_sysinfo_client_3

Rev

Rev 223 | Rev 228 | 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
47
                  %sendTypes
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
 
194 rodolico 74
my $configurationFile = 'sysinfo-client.yaml'; # name of the configuration file
104 rodolico 75
 
194 rodolico 76
 
53 rodolico 77
my @installDirs = ( '/opt/camp/sysinfo-client', '/usr/local/opt/camp/sysinfo-client' );
78
my @confDirs =    ( '/etc/camp/sysinfo-client', '/usr/local/etc/camp/sysinfo-client' );
79
 
80
 
28 rodolico 81
our @moduleDirs = ( '/opt/camp/sysinfo-client/modules', '/etc/camp/sysinfo-client/modules' );
82
our @scriptDirs = ( '/opt/camp/sysinfo-client/scripts', '/etc/camp/sysinfo-client/scripts' );
111 rodolico 83
our $transports = {}; # holds transportation mechanisms
21 rodolico 84
 
103 rodolico 85
our $sysinfo3 = 'sysinfo-client.yaml';
21 rodolico 86
 
28 rodolico 87
our $binDir = '/opt/camp/sysinfo-client';
44 rodolico 88
our $moduleDir = $binDir . '/modules';
89
our $scriptDir = $binDir . '/scripts';
28 rodolico 90
our $confDir = '/etc/camp/sysinfo-client';
21 rodolico 91
 
28 rodolico 92
our $binName = 'sysinfo-client';
107 rodolico 93
our $confName = 'sysinfo-client.yaml';
21 rodolico 94
 
35 rodolico 95
sub setDryRun {
96
   $dryRun = shift;
97
}
21 rodolico 98
 
28 rodolico 99
our %sendTypes = ( 
21 rodolico 100
                  'SendEmail' =>    { 'sendScript' => 'sendEmailScript',
101
                                      'keys' => 
102
                                      [
103
                                        'mailTo',
104
                                        'mailSubject',
105
                                        'mailCC',
106
                                        'mailBCC',
107
                                        'mailServer',
108
                                        'mailFrom',
109
                                        'logFile',
110
                                        'otherCLParams',
111
                                        'tls',
112
                                        'smtpUser',
113
                                        'smtpPass',
114
                                        'sendEmailScriptLocation'
115
                                      ],
116
                                    },
117
                  'HTTP Upload' =>  { 'sendScript' => 'upload_http',
118
                                      'keys' => 
119
                                      [
120
                                        'URL',
121
                                        'key for report',
122
                                        'key for date',
123
                                        'key for hostname',
124
                                        'key for client',
125
                                        'key for serial number'
126
                                      ]
86 rodolico 127
                                    },
128
                  'Save Local' =>   { 'sendScript' => 'save_local',
129
                                      'keys' =>
130
                                      [
131
                                         'output directory'
132
                                      ]
133
                                   }
21 rodolico 134
                );
135
 
136
 
135 rodolico 137
#######################################################
138
#
139
# timeStamp
140
#
141
# return current system date as YYYY-MM-DD HH:MM:SS
142
#
143
#######################################################
144
sub timeStamp {
145
   my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
143 rodolico 146
   return sprintf "%4d-%02d-%02d %02d:%02d:%02d",$year+1900,$mon+1,$mday,$hour,$min,$sec;
135 rodolico 147
}
148
 
149
 
37 rodolico 150
sub enableModules {
151
   my $moduleDir = shift;
152
   my %modules;
153
   if ( opendir( my $dh, "$moduleDir" ) ) {
154
      %modules = map{ $_ => { 'enabled' => -x "$moduleDir/$_" } } 
155
                 grep { ! /^\./ } 
156
                 readdir $dh;
157
      closedir( $dh );
158
      foreach my $filename ( keys %modules ) {
159
         if ( open FILE,"<$moduleDir/$_" ) {
160
            my @descript = grep{ /^# Description: (.*)/ } <FILE>;
161
            close FILE;
162
            chomp @descript;
163
            $modules{$filename}{'description'} = $descript[0];
164
         } # if
165
      } # foreach
166
   } # if
167
} # enableModules
168
 
21 rodolico 169
sub showConf {
81 rodolico 170
 
35 rodolico 171
   my $configuration = shift;
92 rodolico 172
   $configuration = Dump($configuration);
84 rodolico 173
   return $configuration;
21 rodolico 174
}
175
 
176
sub transportsToConfig {
35 rodolico 177
   my $transports = shift;
21 rodolico 178
   my $config;
179
   foreach my $priority ( sort { $a <=> $b } keys %$transports ) {
124 rodolico 180
      my $name = $$transports{ $priority }{'name'};
21 rodolico 181
      $config .= "# Tranport $name at priority $priority\n";
182
      my $thisOne = $$transports{ $priority };
183
      foreach my $key ( sort keys %$thisOne ) {
184
         $config .= "\$\$transports{$priority}{'$key'} = '$$thisOne{$key}';\n";
185
      } # foreach
186
   } # foreach
187
   return $config;
188
} # transportsToConfig
189
 
227 rodolico 190
sub readServerInfo {
191
   my $serverInfoName = shift;
192
   my %return;
94 rodolico 193
 
227 rodolico 194
   print "Reading server info from $serverInfoName\n";
195
 
196
   if ( -f $serverInfoName ) {
197
      print "found $serverInfoName\n";
198
      open DATA, $serverInfoName or die "Could not read $serverInfoName: $!\n";
199
      print "opened $serverInfoName\n";
200
      while ( my $line = <DATA> ) {
201
         next if $line =~ m/^#/;
202
         chomp $line;
203
         my ($key,$value) = split( ':', $line );
204
         $key =~ s/^\s+|\s+$//g;
205
         $value =~ s/^\s+|\s+$//g;
206
         # note, we make the key lower case so we can find it
207
         $return{ lc $key} = $value;
223 rodolico 208
      }
209
   }
227 rodolico 210
   return \%return;
223 rodolico 211
}
212
 
227 rodolico 213
 
45 rodolico 214
sub makeConfig {
227 rodolico 215
   my $configFile = shift;
223 rodolico 216
   my $config = {}; # make sure it is a ref to a hash so mergeHash can recognize it
227 rodolico 217
   my $serverInfo = readServerInfo( $serverInfoFileName );
218
   # die Dumper( $serverInfo );
219
   if ( -f $configFile ) {
218 rodolico 220
      print "Processing config file $configFile\n";
227 rodolico 221
      my $yaml = YAML::Tiny->read( $configFile );
222
      $config = $yaml->[0];
45 rodolico 223
   }
227 rodolico 224
 
225
   # Fill in any values we are missing but which are found in $serverInfo (/etc/server.info)
226
   $config->{'clientName'} = defined( $serverInfo->{'owner'} ) ? $serverInfo->{'owner'} : '' unless $config->{'clientName'};
227
   $config->{'hostname'} = defined( $serverInfo->{'hostname'} ) ? $serverInfo->{'hostname'} : '' unless $config->{'hostname'};
228
   $config->{'serialNumber'} = defined( $serverInfo->{'serial'} ) ? $serverInfo->{'serial'} : '' unless $config->{'serialNumber'};
229
   $config->{'UUID'} = defined( $serverInfo->{'uuid'} ) ? $serverInfo->{'uuid'} : '' unless $config->{'UUID'};
230
   $config->{'location'} = defined( $serverInfo->{'location'} ) ? $serverInfo->{'location'} : '' unless $config->{'location'};
231
   $config->{'os_type'} = defined( $serverInfo->{'os_type'} ) ? $serverInfo->{'os_type'} : '' unless $config->{'os_type'};
232
   $config->{'tags'} = defined( $serverInfo->{'tags'} ) ? [ split ',', $serverInfo->{'tags'} ] : [] unless $config->{'tags'};
233
 
234
   # if these are still missing, we can try to run a program to get the values
218 rodolico 235
   unless ( $config->{'hostname'} ) {
227 rodolico 236
      $config->{'hostname'} = `hostname -f`;
237
      chomp $config->{'hostname'};
45 rodolico 238
   }
218 rodolico 239
   unless ( $config->{'serialNumber'} ) {
227 rodolico 240
      $config->{'serialNumber'} = `dmidecode -s system-serial-number` if `which dmidecode`;
241
      chomp $config->{'serialNumber'};
242
      $config->{'serialNumber'} =~ s/\s//gi;
243
      $config->{'serialNumber'} = $serialNumberTranslation{lc($config->{'serialNumber'})} if defined( $serialNumberTranslation{lc($config->{'serialNumber'})} );
53 rodolico 244
   }
218 rodolico 245
   unless ( $config->{'UUID'} ) {
227 rodolico 246
      $config->{'UUID'} = `which dmidecode` ?  `dmidecode -t 1 | grep -i uuid | cut -d':' -f2` : '' if `which dmidecode`;
247
      $config->{'UUID'} =~ s/\s//gi;
248
      $config->{'UUID'} = $UUIDTranslation{lc($config->{'UUID'})} if defined( $UUIDTranslation{lc($config->{'UUID'})} );
77 rodolico 249
   }
227 rodolico 250
   unless ( $config->{'os_type'} ) {
251
      $config->{'os_type'} = `installer/determineOS` if -x 'installer/determineOS';
252
   }
219 rodolico 253
 
218 rodolico 254
   return $config;
45 rodolico 255
}
256
 
21 rodolico 257
# prompt the user for a response, then allow them to enter it
258
# the first response is considered the default and is printed
259
# in all caps if more than one exists
260
# first answer is used if they simply press the Enter
261
# key. The response is returned all lower case if more than one
262
# exists.
263
# it is assumed 
264
sub getAnswer {
265
   my ( $prompt, @answers ) = @_;
266
   $answers[0] = '' unless defined( $answers[0] );
267
   my $default = $answers[0];
268
   my $onlyOneAnswer = scalar( @answers ) == 1;
269
   print $prompt . '[ ';
270
   $answers[0] = uc $answers[0] unless $onlyOneAnswer;
271
   print join( ' | ', @answers ) . ' ]: ';
28 rodolico 272
   my $thisAnswer = <>;
21 rodolico 273
   chomp $thisAnswer;
274
   $thisAnswer = $default unless $thisAnswer;
275
   return $thisAnswer;
276
}
277
 
278
sub yesno {
40 rodolico 279
   my ( $prompt, $default ) = @_;
280
   $default = 'yes' unless $default;
281
   my $answer = &getAnswer( $prompt, $default eq 'yes' ? ('yes','no' ) : ('no', 'yes') );
21 rodolico 282
   return lc( substr( $answer, 0, 1 ) ) eq 'y';
283
}
284
 
285
sub writeConfig {
132 rodolico 286
   use File::Temp qw / tempfile /;
35 rodolico 287
   my ( $filename,$content ) = @_;
129 rodolico 288
   if ( $filename ) { # they sent us a filename
289
      my $path;
290
      ($filename, $path ) = fileparse( $filename );
291
      `mkdir -p $path` unless -d $path;
292
      $filename = $path . '/' . $filename;
21 rodolico 293
      `cp $filename $filename.bak` if ( -e $filename );
129 rodolico 294
      unless ( $dryRun ) {
295
         open CONF,">$filename" or die "Could not write to $filename: $!\n";
296
         print CONF $content;
297
         close CONF;
298
         `chmod 600 $filename`;
299
      }
300
   } else { # no path provided, so just create a temp file
301
      # we will create a temporary file and return the name
302
      # it is the calling programs responsiblity to remove the file
303
      my $fh;
304
      ($fh,$filename) = tempfile( UNLINK => 0 );
305
      print $fh $content;
306
      close $fh
21 rodolico 307
   }
129 rodolico 308
   return $filename;
21 rodolico 309
}
310
 
311
sub processParameters {
312
   while ( my $parameter = shift ) {
313
      if ( $parameter eq '-v' ) {
26 rodolico 314
         print "$VERSION\n";
21 rodolico 315
         exit;
316
      }
317
   } # while
318
}
319
 
53 rodolico 320
sub findConf {
321
   my $confName = shift;
322
   for ( my $i = 0; $i < @confDirs; $i++ ) {
323
      if ( -d $confDirs[ $i ] ) {
55 rodolico 324
         return ( $confDirs[$i],  $confName );
53 rodolico 325
      }
326
   }
104 rodolico 327
   return ( '', $confName );
53 rodolico 328
}
21 rodolico 329
 
194 rodolico 330
#######################################################
331
#
332
# findFile( $filename, @directories )
333
#
334
# Locates a file by searching sequentially in one or more
335
# directories, returning the first one found
336
# 
337
# Returns '' if not found
338
#
339
#######################################################
104 rodolico 340
 
194 rodolico 341
sub findFile {
342
   my ( $filename, $directories ) = @_;
343
   &logIt( 3, "Looking for $filename in findFile" );
344
   for ( my $i = 0; $i < scalar( @{$directories} ); $i++ ) {
345
      my $confFile = $$directories[$i] . '/' . $filename;
346
      &logIt( 4, "Looking for $filename in $confFile" );
347
      return $confFile if ( -f $confFile );
348
   }
349
   return '';
350
}
351
 
104 rodolico 352
 
194 rodolico 353
#######################################################
354
#
355
# loadConfigurationFile($confFile)
356
#
357
# Loads configuration file defined by $configurationFile, and dies if not available
358
# This is a YAML file containing serialized contents of 
359
# Parameters:
360
#    $$fileName - name of file to look for (reference)
361
#    @searchPath - array of paths to find $filename
362
#
363
#######################################################
104 rodolico 364
 
194 rodolico 365
sub loadConfigurationFile {   
366
   my ( $fileName, @searchPath ) = @_;
367
   $$fileName = $configurationFile unless $$fileName;
368
   @searchPath = @confFileSearchPath unless @searchPath;
369
   &logIt( 2, "Looking for config file $$fileName in " . join( ', ', @searchPath ) );
370
   my $confFile;
371
   if ( $confFile = &findFile( $$fileName, \@searchPath ) ) {
372
      &logIt( 3, "Opening configuration from $confFile" );
373
      my $yaml = YAML::Tiny->read( $confFile );
374
      &logIt( 4, "Configuration file contents\n$yaml" );
375
      $$fileName = $confFile;
376
      return $yaml->[0];
377
   }
378
   die "Can not find $fileName in any of " . join( "\n\t", @searchPath ) . "\n";
379
}
380
 
381
 
382
#######################################################
383
# function to simply log things
384
# first parameter is the priority, if <= $logDef->{'log level'} will print
385
# all subsequent parameters assumed to be strings to sent to the log
386
# returns 0 on failure
387
#         1 on success
388
#         2 if priority > log level
389
#        -1 if $logDef is unset
390
# currently, only logs to a file
391
#######################################################
392
sub logIt {
393
   my $priority = shift;
394
 
395
   # turn off variable checking so it doesn't blow up on lack of %configuration file
396
   no strict 'vars';
397
 
398
   return -1 unless exists $configuration{'logging'};
399
   return 2 unless $priority <= $configuration{'logging'}{'log level'};
400
   if ( $configuration{'logging'}{'log type'} eq 'cache' ) {
401
      push @{ $configuration{'logging'}{'cache'} }, @_;
402
      return;
403
   } elsif ( defined( $configuration{'logging'}{'cache'} ) ) {
404
      unshift @_, @{ $configuration{'logging'}{'cache'} };
405
      delete $configuration{'logging'}{'cache'};
406
   }
407
   if ( $configuration{'logging'}{'log type'} eq 'file' ) {
408
      if ( open LOG, '>>' . $configuration{'logging'}{'log path'} ) {
409
         while ( my $t = shift ) {
410
            print LOG &timeStamp() . "\t$t\n";
411
         }
412
         close LOG;
413
      }
414
   } elsif ( $configuration{'logging'}{'log type'} eq 'syslog' ) {
415
      use Sys::Syslog;                        # all except setlogsock()
416
      use Sys::Syslog qw(:standard :macros);  # standard functions & macros
417
 
418
      my $syslogName = 'sysinfo-client';
419
      my $logopt = 'nofatal';
420
      my $facility = 'LOG_LOCAL0';
421
      my $priority = 'LOG_NOTICE';
422
 
423
      openlog( $syslogName, $logopt, $facility);
424
      syslog($priority, '%s', @_ );
425
      closelog();
426
   } else {
427
      warn "Log type $configuration{'logging'} incorrectly configured\n";
428
      return 0;
429
   }
430
   return 1;
431
}
432
 
433
 
434
 
21 rodolico 435
1;