Subversion Repositories camp_sysinfo_client_3

Rev

Rev 112 | Rev 115 | 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
45 rodolico 15
 
21 rodolico 16
package sysinfoconf;
17
 
42 rodolico 18
 
94 rodolico 19
our $VERSION = '2.0';
21 rodolico 20
use warnings;
26 rodolico 21
use strict;  
22
 
92 rodolico 23
#use Data::Dumper;
101 rodolico 24
use YAML::Tiny;
35 rodolico 25
use File::Basename;
26
 
21 rodolico 27
use Exporter;
28
 
29
our @ISA = qw( Exporter );
30
our @EXPORT = qw( $clientName $serialNumber $hostname @moduleDirs @scriptDirs 
44 rodolico 31
                  $transports $sysinfo3 %sendTypes $binDir $moduleDir
32
                  $scriptDir $confDir $binName $confName
21 rodolico 33
                  &showConf &transportsToConfig &getAnswer &yesno  
35 rodolico 34
                  &writeConfig &processParameters $TESTING &checkDirectoryExists
114 rodolico 35
                  &runCommand &setDryRun &enableModules &makeConfig &findConf &deepmerge
21 rodolico 36
                );
37
 
36 rodolico 38
our $TESTING = 0;
35 rodolico 39
our $dryRun;
28 rodolico 40
our $clientName = '';
41
our $serialNumber = '';
42
our $hostname = '';
53 rodolico 43
 
104 rodolico 44
 
45
 
53 rodolico 46
my @installDirs = ( '/opt/camp/sysinfo-client', '/usr/local/opt/camp/sysinfo-client' );
47
my @confDirs =    ( '/etc/camp/sysinfo-client', '/usr/local/etc/camp/sysinfo-client' );
48
 
49
 
28 rodolico 50
our @moduleDirs = ( '/opt/camp/sysinfo-client/modules', '/etc/camp/sysinfo-client/modules' );
51
our @scriptDirs = ( '/opt/camp/sysinfo-client/scripts', '/etc/camp/sysinfo-client/scripts' );
111 rodolico 52
our $transports = {}; # holds transportation mechanisms
21 rodolico 53
 
103 rodolico 54
our $sysinfo3 = 'sysinfo-client.yaml';
21 rodolico 55
 
28 rodolico 56
our $binDir = '/opt/camp/sysinfo-client';
44 rodolico 57
our $moduleDir = $binDir . '/modules';
58
our $scriptDir = $binDir . '/scripts';
28 rodolico 59
our $confDir = '/etc/camp/sysinfo-client';
21 rodolico 60
 
28 rodolico 61
our $binName = 'sysinfo-client';
107 rodolico 62
our $confName = 'sysinfo-client.yaml';
21 rodolico 63
 
35 rodolico 64
sub setDryRun {
65
   $dryRun = shift;
66
}
21 rodolico 67
 
28 rodolico 68
our %sendTypes = ( 
21 rodolico 69
                  'SendEmail' =>    { 'sendScript' => 'sendEmailScript',
70
                                      'keys' => 
71
                                      [
72
                                        'mailTo',
73
                                        'mailSubject',
74
                                        'mailCC',
75
                                        'mailBCC',
76
                                        'mailServer',
77
                                        'mailFrom',
78
                                        'logFile',
79
                                        'otherCLParams',
80
                                        'tls',
81
                                        'smtpUser',
82
                                        'smtpPass',
83
                                        'sendEmailScriptLocation'
84
                                      ],
85
                                    },
86
                  'HTTP Upload' =>  { 'sendScript' => 'upload_http',
87
                                      'keys' => 
88
                                      [
89
                                        'URL',
90
                                        'key for report',
91
                                        'key for date',
92
                                        'key for hostname',
93
                                        'key for client',
94
                                        'key for serial number'
95
                                      ]
86 rodolico 96
                                    },
97
                  'Save Local' =>   { 'sendScript' => 'save_local',
98
                                      'keys' =>
99
                                      [
100
                                         'output directory'
101
                                      ]
102
                                   }
21 rodolico 103
                );
104
 
105
 
114 rodolico 106
# recursively merge multiple hashes/arrays to an arbitrary depth
107
# stolen from
108
# https://stackoverflow.com/questions/2767477/how-can-i-merge-several-hashes-into-one-hash-in-perl
109
sub deepmerge {
110
    my (@structs) = @_;
111
    my $new;
112
 
113
    # filter out non-existant structs
114
    @structs = grep {defined($_)} @structs;
115
 
116
    my $ref = ref($structs[0]);
117
    if (not all(map {ref($_) eq $ref} @structs)) { 
118
        warn("deepmerge: all structs are not $ref\n");
119
    } 
120
 
121
    my @tomerge = grep {ref($_) eq $ref} @structs;
122
    return qr/$tomerge[0]/ if scalar(@tomerge) == 1 and $ref eq 'Regexp';
123
    return $tomerge[0] if scalar(@tomerge) == 1;
124
 
125
    if ($ref eq '') { 
126
        $new = pop(@tomerge); # prefer farthest right
127
    } elsif ($ref eq 'Regexp') { 
128
        $new = qr/$tomerge[$#tomerge]/;
129
    } elsif ($ref eq 'ARRAY') { 
130
        $new = [];
131
        for my $i (0 .. max(map {scalar(@$_) - 1} @tomerge)) { 
132
            $new->[$i] = deepmerge(map {$_->[$i]} @tomerge);
133
        }
134
    } elsif ($ref eq 'HASH') { 
135
        $new = {};
136
        for my $key (uniq(map {keys %$_} @tomerge)) { 
137
            $new->{$key} = deepmerge(map {$_->{$key}} @tomerge);
138
        }
139
    } else {
140
        # ignore all other structures...
141
        $new = '';
142
    }
143
 
144
    return $new;
145
}
146
 
37 rodolico 147
sub enableModules {
148
   my $moduleDir = shift;
149
   my %modules;
150
   if ( opendir( my $dh, "$moduleDir" ) ) {
151
      %modules = map{ $_ => { 'enabled' => -x "$moduleDir/$_" } } 
152
                 grep { ! /^\./ } 
153
                 readdir $dh;
154
      closedir( $dh );
155
      foreach my $filename ( keys %modules ) {
156
         if ( open FILE,"<$moduleDir/$_" ) {
157
            my @descript = grep{ /^# Description: (.*)/ } <FILE>;
158
            close FILE;
159
            chomp @descript;
160
            $modules{$filename}{'description'} = $descript[0];
161
         } # if
162
      } # foreach
163
   } # if
164
} # enableModules
165
 
21 rodolico 166
sub showConf {
81 rodolico 167
 
35 rodolico 168
   my $configuration = shift;
92 rodolico 169
   $configuration = Dump($configuration);
84 rodolico 170
   return $configuration;
81 rodolico 171
 
83 rodolico 172
   #return $conf;
173
   #my $conf;
174
   #$conf .= "\$clientName = '" .   ( defined( $$configuration{'clientName'}   ) ? $$configuration{'clientName'}   : '' ) . "';\n";
175
   #$conf .= "\$serialNumber = '" . ( defined( $$configuration{'serialNumber'} ) ? $$configuration{'serialNumber'} : '' ) . "';\n";
176
   #$conf .= "\$hostname = '" .     ( defined( $$configuration{'hostname'}     ) ? $$configuration{'hostname'}     : '' ) . "';\n";
177
   #$conf .= "\$UUID = '" .      ( defined( $$configuration{'UUID'}     ) ? $$configuration{'UUID'}     : '' ) . "';\n";
178
   #$conf .= "\@moduleDirs = ('" . join( "','", @{ $$configuration{ 'moduleDirs' } } ) . "');\n";
179
   #$conf .= "\@scriptDirs = ('" . join( "','", @{ $$configuration{ 'scriptDirs' } } ) . "');\n";
180
   #$conf .= &transportsToConfig( $$configuration{ 'transports' } ) if defined( $$configuration{ 'transports' } );
181
   #return $conf;
21 rodolico 182
}
183
 
184
sub transportsToConfig {
35 rodolico 185
   my $transports = shift;
21 rodolico 186
   my $config;
187
   foreach my $priority ( sort { $a <=> $b } keys %$transports ) {
188
      my $name = $$transports{ $priority }{'-name-'};
189
      $config .= "# Tranport $name at priority $priority\n";
190
      my $thisOne = $$transports{ $priority };
191
      foreach my $key ( sort keys %$thisOne ) {
192
         $config .= "\$\$transports{$priority}{'$key'} = '$$thisOne{$key}';\n";
193
      } # foreach
194
   } # foreach
195
   return $config;
196
} # transportsToConfig
197
 
94 rodolico 198
 
199
# read the configuration file passed in and return a reference to it
200
# to the calling routine
201
sub readConfig {
202
   my $filename = shift;
203
   my $config;
204
   return $config unless -e $filename;
205
   if ( open CONF,"<$filename" ) {
206
      my $contents = join( '', <CONF> );
207
      close CONF;
208
      # now, look to see what kind of file this is.
209
      if ( $contents =~ m/^---(\s*#.*)?$/m ) {
210
         print "Reading $filename as YAML\n";
211
         #print "Contents are:\n\n=====================$contents\n=====================\n";
212
         # this is a yaml file
213
         #$contents = YAML::Tiny->read( $config );
214
         $config = Load( $contents );
215
      } elsif ( $contents =~ m/\$clientName/ ) {
216
         # this is old style
217
         print "Reading $filename as old school file\n";
218
         my $clientName = '';
219
         my $serialNumber = '';
220
         my $hostname = '';
221
         my @moduleDirs;
222
         my @scriptDirs;
223
         my $UUID = '';
224
         my $transports;
225
         # now, eval the information we just read.
226
         # NOTE: we must turn off strict while doing this, and we die if something breaks.
227
         no strict "vars";
228
         eval( $contents );
229
         use strict "vars";
230
         die "Error during eval: $@\n" if $@;
231
         $config->{'clientName'} = $clientName if $clientName;
232
         $config->{'serialNumber'} = $serialNumber if $serialNumber;
233
         $config->{'UUID'} = $UUID unless $config->{'UUID'};
234
         $config->{'hostname'} = $hostname if $hostname;
235
         $config->{'moduleDirs'} = [ @moduleDirs ] if @moduleDirs;
236
         $config->{'scriptDirs'} = [ @scriptDirs ] if @scriptDirs;
237
         $config->{'transports'} = $transports if $transports;
238
      }
239
   } else {
240
         warn "Could not read config file $filename, skipped: $!\n";
241
   }
242
   return $config;
243
}
244
 
45 rodolico 245
sub makeConfig {
246
   my @configFileNames = @_;
247
   my %config;
248
 
249
   foreach my $config ( @configFileNames ) {
112 rodolico 250
      my $thisConfig = &readConfig( $config );
94 rodolico 251
      # add the new config to %config, overwriting any existing keys which are duplicated
252
      @config{keys %$thisConfig} = values %$thisConfig;
45 rodolico 253
   }
94 rodolico 254
   # now, ensure the correct values are loaded in some areas
81 rodolico 255
   unless ( $config{'hostname'} ) {
45 rodolico 256
      $hostname = `hostname -f`;
257
      chomp $hostname;
81 rodolico 258
      $config{'hostname'} = $hostname;
45 rodolico 259
   }
84 rodolico 260
   unless ( $config{'serialNumber'} ) {
53 rodolico 261
      $serialNumber = `dmidecode -t 1 | grep 'Serial Number' | cut -d':' -f2` if `which dmidecode`;
262
      chomp $serialNumber;
263
      $serialNumber =~ s/\s//gi;
84 rodolico 264
      $config{'serialNumber'} = $serialNumber;
53 rodolico 265
   }
81 rodolico 266
   unless ( $config{'UUID'} ) {
94 rodolico 267
      my $UUID = `dmidecode -t 1 | grep -i uuid | cut -d':' -f2` if `which dmidecode`;
77 rodolico 268
      $UUID =~ s/\s//gi;
81 rodolico 269
      $config{'UUID'} = $UUID;
77 rodolico 270
   }
45 rodolico 271
 
110 rodolico 272
   # ensure we have the default SaveLocal transport defined
273
   unless ( defined $config{'transports'}{'99'} ) {
274
      $config{'transports'}{'99'} = {
275
                         'name'=> 'SaveLocal',
276
                         'output directory' => '/tmp',
277
                         'sendScript' => 'save_local'
278
                        };
279
   }
280
 
45 rodolico 281
   return \%config;
282
}
283
 
21 rodolico 284
# prompt the user for a response, then allow them to enter it
285
# the first response is considered the default and is printed
286
# in all caps if more than one exists
287
# first answer is used if they simply press the Enter
288
# key. The response is returned all lower case if more than one
289
# exists.
290
# it is assumed 
291
sub getAnswer {
292
   my ( $prompt, @answers ) = @_;
293
   $answers[0] = '' unless defined( $answers[0] );
294
   my $default = $answers[0];
295
   my $onlyOneAnswer = scalar( @answers ) == 1;
296
   print $prompt . '[ ';
297
   $answers[0] = uc $answers[0] unless $onlyOneAnswer;
298
   print join( ' | ', @answers ) . ' ]: ';
28 rodolico 299
   my $thisAnswer = <>;
21 rodolico 300
   chomp $thisAnswer;
301
   $thisAnswer = $default unless $thisAnswer;
302
   return $thisAnswer;
303
}
304
 
305
sub yesno {
40 rodolico 306
   my ( $prompt, $default ) = @_;
307
   $default = 'yes' unless $default;
308
   my $answer = &getAnswer( $prompt, $default eq 'yes' ? ('yes','no' ) : ('no', 'yes') );
21 rodolico 309
   return lc( substr( $answer, 0, 1 ) ) eq 'y';
310
}
311
 
35 rodolico 312
# runs a system command. Also, if in testing mode, simply shows what
313
# would have been done.
314
sub runCommand {
315
   while ( my $command = shift ) {
316
      if ( $dryRun ) {
317
         print "$command\n";
318
      } else {
319
         `$command`;
320
      }
321
   }
322
   return 1;
323
} # runCommand
324
 
325
# checks if a directory exists and, if not, creates it
326
my %directories; # holds list of directories already created so no need to do an I/O
327
 
328
sub checkDirectoryExists {
329
   my ( $filename,$mod,$owner ) = @_;
330
   $mod = "0700" unless $mod;
331
   $owner = "root:root" unless $owner;
332
   print "Checking Directory for $filename with $mod and $owner\n" if $TESTING > 2;
333
   my ($fn, $dirname) = fileparse( $filename );
334
   print "\tParsing out $dirname and $filename\n" if $TESTING > 2;
335
   return '' if exists $directories{$dirname};
336
   if ( -d $dirname ) {
337
      $directories{$dirname} = 1;
338
      return '';
339
   }
340
   if ( &runCommand( "mkdir -p $dirname", "chmod $mod $dirname", "chown $owner $dirname" ) ) {
341
      $directories{$dirname} = 1;
342
   }
343
   return '';   
344
}
345
 
21 rodolico 346
sub writeConfig {
35 rodolico 347
   my ( $filename,$content ) = @_;
348
   my $path;
349
   ($filename, $path ) = fileparse( $filename );
350
 
21 rodolico 351
   my $return;
352
   `mkdir -p $path` unless -d $path;
353
   $filename = $path . '/' . $filename;
354
   if ( -e $filename ) {
355
      `cp $filename $filename.bak` if ( -e $filename );
356
      $return .= "Old config copied to $filename.bak\n";
357
   }
35 rodolico 358
   if ( $dryRun ) {
359
      $return .= "Not writing to configuration file\n";
360
   } else {
361
      open CONF,">$filename" or die "Could not write to $filename: $!\n";
362
      print CONF $content;
363
      close CONF;
364
      `chmod 600 $filename`;
365
      $return .= "Configuration successfully written to $filename\n";
366
   }
21 rodolico 367
   return $return;
368
}
369
 
370
sub processParameters {
371
   while ( my $parameter = shift ) {
372
      if ( $parameter eq '-v' ) {
26 rodolico 373
         print "$VERSION\n";
21 rodolico 374
         exit;
375
      }
376
   } # while
377
}
378
 
53 rodolico 379
sub findConf {
380
   my $confName = shift;
381
   my @confDirs =    ( '/etc/camp/sysinfo-client', '/usr/local/etc/camp/sysinfo-client' );
382
   for ( my $i = 0; $i < @confDirs; $i++ ) {
383
      if ( -d $confDirs[ $i ] ) {
55 rodolico 384
         return ( $confDirs[$i],  $confName );
53 rodolico 385
      }
386
   }
104 rodolico 387
   return ( '', $confName );
53 rodolico 388
}
21 rodolico 389
 
104 rodolico 390
 
391
 
392
 
21 rodolico 393
1;