Subversion Repositories camp_sysinfo_client_3

Rev

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