Subversion Repositories camp_sysinfo_client_3

Rev

Go to most recent revision | Details | 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
 
45 rodolico 189
sub makeConfig {
190
   my @configFileNames = @_;
218 rodolico 191
   my $config;
45 rodolico 192
 
218 rodolico 193
   use Hash::Merge;
194
   my $merge = Hash::Merge->new('RIGHT_PRECEDENT');
195
   foreach my $configFile ( @configFileNames ) {
196
      next unless $configFile && -e $configFile;
197
      print "Processing config file $configFile\n";
198
      my $thisConfig = &readConfig( $configFile );
94 rodolico 199
      # add the new config to %config, overwriting any existing keys which are duplicated
218 rodolico 200
      $config = $merge->merge( $config, $thisConfig );
201
      #@config{keys %$thisConfig} = values %$thisConfig;
45 rodolico 202
   }
94 rodolico 203
   # now, ensure the correct values are loaded in some areas
218 rodolico 204
   unless ( $config->{'hostname'} ) {
45 rodolico 205
      $hostname = `hostname -f`;
206
      chomp $hostname;
218 rodolico 207
      $config->{'hostname'} = $hostname;
45 rodolico 208
   }
218 rodolico 209
   unless ( $config->{'serialNumber'} ) {
219 rodolico 210
      $serialNumber = `dmidecode -s system-serial-number` if `which dmidecode`;
53 rodolico 211
      chomp $serialNumber;
212
      $serialNumber =~ s/\s//gi;
218 rodolico 213
      $config->{'serialNumber'} = $serialNumber;
53 rodolico 214
   }
218 rodolico 215
   unless ( $config->{'UUID'} ) {
129 rodolico 216
      my $UUID = `which dmidecode` ?  `dmidecode -t 1 | grep -i uuid | cut -d':' -f2` : '';
77 rodolico 217
      $UUID =~ s/\s//gi;
218 rodolico 218
      $config->{'UUID'} = $UUID;
77 rodolico 219
   }
219 rodolico 220
 
218 rodolico 221
   return $config;
45 rodolico 222
}
223
 
21 rodolico 224
# prompt the user for a response, then allow them to enter it
225
# the first response is considered the default and is printed
226
# in all caps if more than one exists
227
# first answer is used if they simply press the Enter
228
# key. The response is returned all lower case if more than one
229
# exists.
230
# it is assumed 
231
sub getAnswer {
232
   my ( $prompt, @answers ) = @_;
233
   $answers[0] = '' unless defined( $answers[0] );
234
   my $default = $answers[0];
235
   my $onlyOneAnswer = scalar( @answers ) == 1;
236
   print $prompt . '[ ';
237
   $answers[0] = uc $answers[0] unless $onlyOneAnswer;
238
   print join( ' | ', @answers ) . ' ]: ';
28 rodolico 239
   my $thisAnswer = <>;
21 rodolico 240
   chomp $thisAnswer;
241
   $thisAnswer = $default unless $thisAnswer;
242
   return $thisAnswer;
243
}
244
 
245
sub yesno {
40 rodolico 246
   my ( $prompt, $default ) = @_;
247
   $default = 'yes' unless $default;
248
   my $answer = &getAnswer( $prompt, $default eq 'yes' ? ('yes','no' ) : ('no', 'yes') );
21 rodolico 249
   return lc( substr( $answer, 0, 1 ) ) eq 'y';
250
}
251
 
252
sub writeConfig {
132 rodolico 253
   use File::Temp qw / tempfile /;
35 rodolico 254
   my ( $filename,$content ) = @_;
129 rodolico 255
   if ( $filename ) { # they sent us a filename
256
      my $path;
257
      ($filename, $path ) = fileparse( $filename );
258
      `mkdir -p $path` unless -d $path;
259
      $filename = $path . '/' . $filename;
21 rodolico 260
      `cp $filename $filename.bak` if ( -e $filename );
129 rodolico 261
      unless ( $dryRun ) {
262
         open CONF,">$filename" or die "Could not write to $filename: $!\n";
263
         print CONF $content;
264
         close CONF;
265
         `chmod 600 $filename`;
266
      }
267
   } else { # no path provided, so just create a temp file
268
      # we will create a temporary file and return the name
269
      # it is the calling programs responsiblity to remove the file
270
      my $fh;
271
      ($fh,$filename) = tempfile( UNLINK => 0 );
272
      print $fh $content;
273
      close $fh
21 rodolico 274
   }
129 rodolico 275
   return $filename;
21 rodolico 276
}
277
 
278
sub processParameters {
279
   while ( my $parameter = shift ) {
280
      if ( $parameter eq '-v' ) {
26 rodolico 281
         print "$VERSION\n";
21 rodolico 282
         exit;
283
      }
284
   } # while
285
}
286
 
53 rodolico 287
sub findConf {
288
   my $confName = shift;
289
   for ( my $i = 0; $i < @confDirs; $i++ ) {
290
      if ( -d $confDirs[ $i ] ) {
55 rodolico 291
         return ( $confDirs[$i],  $confName );
53 rodolico 292
      }
293
   }
104 rodolico 294
   return ( '', $confName );
53 rodolico 295
}
21 rodolico 296
 
194 rodolico 297
#######################################################
298
#
299
# findFile( $filename, @directories )
300
#
301
# Locates a file by searching sequentially in one or more
302
# directories, returning the first one found
303
# 
304
# Returns '' if not found
305
#
306
#######################################################
104 rodolico 307
 
194 rodolico 308
sub findFile {
309
   my ( $filename, $directories ) = @_;
310
   &logIt( 3, "Looking for $filename in findFile" );
311
   for ( my $i = 0; $i < scalar( @{$directories} ); $i++ ) {
312
      my $confFile = $$directories[$i] . '/' . $filename;
313
      &logIt( 4, "Looking for $filename in $confFile" );
314
      return $confFile if ( -f $confFile );
315
   }
316
   return '';
317
}
318
 
104 rodolico 319
 
194 rodolico 320
#######################################################
321
#
322
# loadConfigurationFile($confFile)
323
#
324
# Loads configuration file defined by $configurationFile, and dies if not available
325
# This is a YAML file containing serialized contents of 
326
# Parameters:
327
#    $$fileName - name of file to look for (reference)
328
#    @searchPath - array of paths to find $filename
329
#
330
#######################################################
104 rodolico 331
 
194 rodolico 332
sub loadConfigurationFile {   
333
   my ( $fileName, @searchPath ) = @_;
334
   $$fileName = $configurationFile unless $$fileName;
335
   @searchPath = @confFileSearchPath unless @searchPath;
336
   &logIt( 2, "Looking for config file $$fileName in " . join( ', ', @searchPath ) );
337
   my $confFile;
338
   if ( $confFile = &findFile( $$fileName, \@searchPath ) ) {
339
      &logIt( 3, "Opening configuration from $confFile" );
340
      my $yaml = YAML::Tiny->read( $confFile );
341
      &logIt( 4, "Configuration file contents\n$yaml" );
342
      $$fileName = $confFile;
343
      return $yaml->[0];
344
   }
345
   die "Can not find $fileName in any of " . join( "\n\t", @searchPath ) . "\n";
346
}
347
 
348
 
349
#######################################################
350
# function to simply log things
351
# first parameter is the priority, if <= $logDef->{'log level'} will print
352
# all subsequent parameters assumed to be strings to sent to the log
353
# returns 0 on failure
354
#         1 on success
355
#         2 if priority > log level
356
#        -1 if $logDef is unset
357
# currently, only logs to a file
358
#######################################################
359
sub logIt {
360
   my $priority = shift;
361
 
362
   # turn off variable checking so it doesn't blow up on lack of %configuration file
363
   no strict 'vars';
364
 
365
   return -1 unless exists $configuration{'logging'};
366
   return 2 unless $priority <= $configuration{'logging'}{'log level'};
367
   if ( $configuration{'logging'}{'log type'} eq 'cache' ) {
368
      push @{ $configuration{'logging'}{'cache'} }, @_;
369
      return;
370
   } elsif ( defined( $configuration{'logging'}{'cache'} ) ) {
371
      unshift @_, @{ $configuration{'logging'}{'cache'} };
372
      delete $configuration{'logging'}{'cache'};
373
   }
374
   if ( $configuration{'logging'}{'log type'} eq 'file' ) {
375
      if ( open LOG, '>>' . $configuration{'logging'}{'log path'} ) {
376
         while ( my $t = shift ) {
377
            print LOG &timeStamp() . "\t$t\n";
378
         }
379
         close LOG;
380
      }
381
   } elsif ( $configuration{'logging'}{'log type'} eq 'syslog' ) {
382
      use Sys::Syslog;                        # all except setlogsock()
383
      use Sys::Syslog qw(:standard :macros);  # standard functions & macros
384
 
385
      my $syslogName = 'sysinfo-client';
386
      my $logopt = 'nofatal';
387
      my $facility = 'LOG_LOCAL0';
388
      my $priority = 'LOG_NOTICE';
389
 
390
      openlog( $syslogName, $logopt, $facility);
391
      syslog($priority, '%s', @_ );
392
      closelog();
393
   } else {
394
      warn "Log type $configuration{'logging'} incorrectly configured\n";
395
      return 0;
396
   }
397
   return 1;
398
}
399
 
400
 
401
 
21 rodolico 402
1;