Subversion Repositories camp_sysinfo_client_3

Rev

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