-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathinstaller
executable file
·1293 lines (1145 loc) · 37.8 KB
/
installer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl
#
# Copyright (C) Opmantek Limited (www.opmantek.com)
#
# ALL CODE MODIFICATIONS MUST BE SENT TO CODE@OPMANTEK.COM
#
# This file is part of Network Management Information System ("NMIS").
#
# NMIS is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# NMIS is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with NMIS (most likely in a file named LICENSE).
# If not, see <http://www.gnu.org/licenses/>
#
# For further information on NMIS or for a license other than GPL please see
# www.opmantek.com or email contact@opmantek.com
#
# User group details:
# http://support.opmantek.com/users/
#
# *****************************************************************************
use strict;
use File::Copy;
use File::Find;
use File::Basename;
use File::Path;
use Cwd;
use POSIX qw();
no warnings; # noisy module checking
use version 0.77;
use Getopt::Std;
my $me = basename($0);
my $usage = "NMIS Copyright (C) Opmantek Limited (www.opmantek.com)
This program comes with ABSOLUTELY NO WARRANTY;
Usage: $me [-hyd] [-t /some/path] [-m T|t|F|f] [[-p|-P] /some/file] [optX=valX...]
-h: show this help screen
-d: produce extra debug output and logs
-t: Installation target directory
-y: non-interactive mode, all questions are answered
with the default choice
-p: pre-seeded non-interactive mode, answers come from
the file given as argument
-P: generate default preseed file\n\n
-m: mongodb TRUE|true|T|t Do install, setup and upgrade MongoDB (default)
FALSE|false|F|f Don't install, setup or upgrade MongoDB\n";
my (%options, %extras);
die $usage if ( @ARGV == 1 && $ARGV[0] =~ /^-(\?|h|-help)$/i
|| !getopts("yldnt:p:P:m:", \%options));
for my $maybe (@ARGV)
{
my ($k,$v) = split(/=/,$maybe, 2);
next if ($k =~ /[^a-zA-Z0-9_-]/); # ignore extras with problematic chars in the key
$extras{$k} = $v;
}
my $sourcedir = getcwd;
my $targetdir = $options{t} || "/usr/local/nmis9";
my $hookdir = "$sourcedir/installer_hooks";
my $debug = $options{d}? 1 : 0;
my $simulate = $options{n}? 1 : 0;
my $noninteractive = $options{y} || $options{p}? 1 : 0 ; # preseed is also a noninteractive mode
my $logfile = undef; # until we have a dir
my $answers; # preseed mode
#do mongo?
my $no_mongo=0;
if (defined $options{m})
{
my $m_uc_option = uc($options{m});
if ($m_uc_option eq 'F' or $m_uc_option eq 'FALSE' or $m_uc_option eq 'T' or $m_uc_option eq 'TRUE')
{
$no_mongo = ($m_uc_option eq 'F' or $m_uc_option eq 'FALSE')? 1 : 0;
}
else
{
die $usage;
}
$m_uc_option = undef;
}
# preseed generation requested?
if (my $newseed = $options{P})
{
die "Error: will not overwrite existing preseed file $newseed!\n"
if (-e $newseed);
my @candidates = ("$sourcedir/installer",
"$sourcedir/admin/setup_mongodb.pl",
glob("${sourcedir}/installer_hooks/*"));
# tag -> question, file, line nr, default
my %tags;
my $perlre = qr/(^|\W)(input_yn|input_text)\s*\(\s*(["'].+?["'])\s*,\s*"([a-f0-9]{4})"\s*\)/;
my $shellre = qr/(^|\W)(input_yn|input_text)\s+(["'].+?["'])\s+"([a-f0-9]{4})"/;
# read file, determine format, look for all input_yn and input_text
# calls that carry a unique tag and collect filename, line nr, tag and question
#
# attention: to find input_yn and input_text instances correctly
# the whole invocation must be given on a single line!
for my $onefn (@candidates)
{
print STDERR "checking file $onefn...\n";
open(F, $onefn) or die "cannot open $onefn: $!\n";
my @incoming = <F>;
close(F);
my $isperl = $incoming[0] =~ /perl/;
my $whichre = $isperl? $perlre : $shellre;
for my $lineno (0..$#incoming)
{
chomp(my $line = $incoming[$lineno]);
while ($line =~ /$whichre/g)
{
my ($querytype, $question, $tag) = ($2,$3,$4);
# dupl detection also required for tags previously generated or
# generated by hand or whatever...
die "\nerror: duplicate tag \"$tag\" found!\npresent in $tags{$tag}->{file} and $onefn\n"
if (ref($tags{$tag}));
$tags{$tag} = {
question => $question,
file => $onefn,
linenr => $lineno,
default => $querytype eq "input_text"? "": "y" };
}
}
}
open(F, ">$newseed") or die "cannot write to $newseed: $!\n";
print F gen_preseed(\%tags);
close(F);
exit 0;
}
$answers = load_preseed($options{p}) if ($options{p});
my %modules; # check_installed_modules et.al.
die "This installer must be run as root, terminating now.\n" if ($> != 0 && !$simulate);
delete $ENV{"PERL_CPANM_OPT"};
if ($noninteractive)
{
$ENV{"PERL_MM_USE_DEFAULT"}=1;
}
else
{
$ENV{"PERL_MM_USE_DEFAULT"}=0;
}
# there are some slight but annoying differences
my ($osflavour,$osmajor,$osminor,$ospatch,$osiscentos,$osisrocky);
if (-f "/etc/redhat-release")
{
$osflavour="redhat";
logmsg(0, "detected OS flavour RedHat/CentOS");
open(F, "/etc/redhat-release") or die "cannot read redhat-release: $!\n";
my $reldata = join('',<F>);
close(F);
($osmajor,$osminor,$ospatch) = ($1,$2,$4)
if ($reldata =~ /(\d+)\.(\d+)(\.(\d+))?/);
if ($reldata =~ /CentOS/)
{
$osiscentos = 1;
}
if ($reldata =~ /Rocky/)
{
$osisrocky = 1;
}
}
elsif (-f "/etc/os-release")
{
open(F,"/etc/os-release") or die "cannot read os-release: $!\n";
my $osinfo = join("",<F>);
close(F);
if ($osinfo =~ /ID=[\"\']?debian/)
{
$osflavour="debian";
logmsg(0, "detected OS flavour Debian");
}
elsif ($osinfo =~ /ID=[\"\']?ubuntu/)
{
$osflavour="ubuntu";
logmsg(0, "detected OS flavour Ubuntu");
}
($osmajor,$osminor,$ospatch) = ($1,$3,$5)
if ($osinfo =~ /VERSION_ID=\"(\d+)(\.(\d+))?(\.(\d+))?\"/);
# This code should mimic that in ./installer_hooks/common_functions.sh flavour () function
# grep 'ID_LIKE' as a catch-all for debian and ubuntu repectively - done last to not affect existing tried and tested code:
if ( ! defined($osflavour) )
{
if ($osinfo =~ /ID_LIKE=[\"\']?debian/)
{
$osflavour="debian";
my $debian_codename=$1 if ($osinfo =~ /DEBIAN_CODENAME=\s*[\"\']?(.+)[\"\']?\s*/);
# we dont need 'else' catch-all blocks here as we fall back to the debian version
# populated in the generic block above:
if ( defined($debian_codename) )
{
if ($debian_codename =~ /bookworm/i)
{
$osmajor=12;
$osminor=0;
$ospatch=0;
}
elsif ($debian_codename =~ /bullseye/i)
{
$osmajor=11;
$osminor=0;
$ospatch=0;
}
elsif ($debian_codename =~ /buster/i)
{
$osmajor=10;
$osminor=0;
$ospatch=0;
}
elsif ($debian_codename =~ /stretch/i)
{
$osmajor=9;
$osminor=0;
$ospatch=0;
}
elsif ($debian_codename =~ /jessie/i)
{
$osmajor=8;
$osminor=0;
$ospatch=0;
}
}
logmsg(0, "detected OS derivative of Debian: \$osmajor='$osmajor'; \$osminor='$osminor'; \$ospatch='$ospatch'");
}
elsif ($osinfo =~ /ID_LIKE=[\"\']?ubuntu/)
{
$osflavour="ubuntu";
logmsg(0, "detected OS derivative Ubuntu");
my $ubuntu_codename=$1 if ($osinfo =~ /UBUNTU_CODENAME=\s*[\"\']?(.+)[\"\']?\s*/);
# we dont need 'else' catch-all blocks here as we fall back to the ubuntu version
# populated in the generic block above:
if ( defined($ubuntu_codename) )
{
if ($ubuntu_codename =~ /lunar/i)
{
$osmajor=23;
$osminor=04;
$ospatch=0;
}
elsif ($ubuntu_codename =~ /kinetic/i)
{
$osmajor=22;
$osminor=10;
$ospatch=0;
}
elsif ($ubuntu_codename =~ /jammy/i)
{
$osmajor=22;
$osminor=04;
$ospatch=0;
}
elsif ($ubuntu_codename =~ /impish/i)
{
$osmajor=21;
$osminor=10;
$ospatch=0;
}
elsif ($ubuntu_codename =~ /hirsute/i)
{
$osmajor=21;
$osminor=04;
$ospatch=0;
}
elsif ($ubuntu_codename =~ /groovy/i)
{
$osmajor=20;
$osminor=10;
$ospatch=0;
}
elsif ($ubuntu_codename =~ /focal/i)
{
$osmajor=20;
$osminor=04;
$ospatch=0;
}
elsif ($ubuntu_codename =~ /eoan/i)
{
$osmajor=19;
$osminor=10;
$ospatch=0;
}
elsif ($ubuntu_codename =~ /disco/i)
{
$osmajor=19;
$osminor=04;
$ospatch=0;
}
elsif ($ubuntu_codename =~ /cosmic/i)
{
$osmajor=18;
$osminor=10;
$ospatch=0;
}
elsif ($ubuntu_codename =~ /bionic/i)
{
$osmajor=18;
$osminor=04;
$ospatch=0;
}
elsif ($ubuntu_codename =~ /xenial/i)
{
$osmajor=16;
$osminor=04;
$ospatch=0;
}
}
logmsg(0, "detected OS derivative of Ubuntu: \$osmajor='$osmajor'; \$osminor='$osminor'; \$ospatch='$ospatch'");
}
}
if ( ! defined($osflavour) )
{
logdie("Unsupported or unknown distribution!\n");
}
}
# ensure we don't create unworkable dirs and files, if the parent shell
# has a super-restrictive umask...
umask(0022);
# is this an initial installation or an upgrade?
# this is a bit of guesswork.
my $is_initial_install = (-d $targetdir && -f "$targetdir/conf/Config.nmis")? 0:1;
# figure out version - build infra will have saved that in .version
# but we need to also cater for install from source, in which case we use regex to extract version from NMISNG.pm:
my $prodversion;
if ( -e "./.version" )
{
$prodversion = eval { do "./.version" };
logdie("Invalid release (1) - no version!") if ($@ or !$prodversion);
}
elsif ( -e "./lib/NMISNG.pm" )
{
open(F,"./lib/NMISNG.pm") or die "cannot read NMISNG.pm: $!\n";
my $nmisng_source= join("",<F>);
close(F);
if ($nmisng_source =~ /our\s+\$VERSION\s*=\s*(?:"|')(.+)(?:"|')\s*/)
{
$prodversion = $1;
if ($@ or !$prodversion)
{
logdie("Invalid release (2) - no version!");
}
}
}
logdie("Invalid release (3) - no version!") if (!$prodversion);
printBanner("NMIS ($prodversion) Installation script");
my $hostname = `hostname --fqdn`; chomp $hostname;
print "This installer will install NMIS into $targetdir.
To select a different installation location please rerun the
installer with the -t option.\n\n";
my $response = input_yn("Ok to proceed with installation?","52cc");
logdie("User cancelled installation.") if (!$response);
if (!-d $targetdir && !$simulate)
{
safemkdir($targetdir) or die("Can not mkdir $targetdir!\n");
}
$logfile = "$targetdir/install.log";
logmsg(0,"Installation of NMIS ($prodversion)\n",
"started: ".scalar(localtime).", host: $hostname\n",
"source: $sourcedir, target: $targetdir\n",
"debug: $debug, simulate: $simulate, unattended install: $noninteractive\n",
"initial install into blank $targetdir: $is_initial_install\n",
"no_mongo: $no_mongo\n");
# first, run the pre phase plugins - especially dependency!
# these are mainly for stuff like checking pre-reqs, massaging the environment etc.
printBanner("Performing pre-installation steps");
run_hooks("pre");
# dependencies should now be satisfied as far as easily doable
# now check the modules as-is and whether they're satisfied
printBanner("Checking Perl Module Dependencies...");
my ($isok,@missingones) = check_installed_modules();
if (!$isok)
{
print "The installer can use CPAN to install the missing Perl packages
that NMIS depends on, if your system has Internet access.
These modules can be installed with CPAN:
perl -MCPAN -e shell
install [module name]
or more conveniently by running
cpan [module name] [module name...]\n\n";
# curl is present in most basic redhat install
# wget is present on debian/ubuntu via priority:important
# however, ca-certificates may be missing/incomplete at this time
# logic is duplicated in is_web_available in common_repos.sh
my $testres = system("curl --connect-timeout 3 --insecure -L -s --retry 2 -o /dev/null https://services.opmantek.com/ping 2>/dev/null") >> 8;
$testres = system("wget --timeout=3 --no-check-certificate -q --tries=3 -O /dev/null https://services.opmantek.com/ping 2>/dev/null") >> 8
if ($testres);
my $can_use_web = !$testres;
if (!$can_use_web or !input_yn("OK to use CPAN to install missing modules?","9849"))
{
logmsg(0, "Cannot install missing CPAN modules: ".join(" ",@missingones));
print "Cannot install missing CPAN modules!\nNMIS will not work properly until the following Perl modules are installed (from CPAN):\n\n"
.join(" ",@missingones)
."\n\nWe recommend that you stop the installer now, resolve the dependencies,
and then restart the installer.\n\n";
if (input_yn("Stop the installer?","365b"))
{
die "\nAborting the installation. Please install the missing Perl packages\nwith cpan, then restart the installer.\n";
}
}
else
{
# installed cpanm for installing cpan modules
# as it is far more robust at handling failed tests which hang on cpan installs
my $cpanm = "cpanm";
if ($debug)
{
my $type_which_cpanm = type_which($cpanm);
logmsg(0,"type_which_cpanm: $type_which_cpanm\n");
}
# fix cpanm path if not set
if (system("type $cpanm >/dev/null") != 0)
{
$cpanm = type_which($cpanm);
}
# centos + rhel 7 install of MongoDB-v2.2.1 fails at crud_spec.t, but MongoDB-v2.2.0 installs okay
my $rhel7_mongodb_module='MongoDB@2.2.0';
if (defined $cpanm)
{
logmsg(0,"CPANM installation complete, proceeding with module installation using cpanm");
logmsg(0,"cpanm: $cpanm");
# --prompt option looks really useful to investigate and decide on failed tests, but we must honor $noniteractive
#
# Prompts when a test fails so that you can skip, force install, retry or look in the shell to see what's going wrong.
# It also prompts when one of the dependency failed if you want to proceed the installation.
# Defaults to false, and you can say --no-prompt to override if it's set in the default options in PERL_CPANM_OPT.
my $prompt;
if ($noninteractive)
{
$prompt = "";
}
else
{
$prompt = "--prompt";
}
# We pre-install HTTP::Daemon with --notest for this module that often hangs on testing on ubuntu, redhat and centos
# HTTP::Daemon is a dependency of WWW::Mechanize
if ( grep( /^WWW::Mechanize$/, @missingones) or grep( /^HTTP::Daemon$/, @missingones) )
{
system("cpanm HTTP::Daemon --sudo $prompt --notest 2>&1"); # can't use execprint as cpanm may be interactive
}
# We pre-install WWW::Mechanize with --notest for this module that often hangs on testing on ubuntu, redhat and centos
if ( grep( /^WWW::Mechanize$/, @missingones) )
{
system("cpanm WWW::Mechanize --sudo $prompt --notest 2>&1"); # can't use execprint as cpan is interactive: but is cpanm interactive?
}
# centos + rhel 7 install of MongoDB-v2.2.1 fails at crud_spec.t, but MongoDB-v2.2.0 installs okay
if ($osflavour eq "redhat" and $osmajor = 7)
{
$_ eq 'MongoDB' and $_ = $rhel7_mongodb_module for @missingones;
}
# force install Mojolicious where not being installed to fix the upgrade from apt installed earlier version than 8.11
# we no longer apt install Mojolicious for this reason:
if (! grep( /^Mojolicious$/, @missingones) )
{
push @missingones, "Mojolicious";
}
# default test-timeout is 30 mins: install will return exit code 1 on test timeout
# retry 3 times
# can't use execprint as cpanm may be interactive
system("cpanm --sudo $prompt ".join(" ",@missingones)." 2>&1||cpanm --sudo $prompt ".join(" ",@missingones)." 2>&1||cpanm --sudo $prompt ".join(" ",@missingones)." 2>&1");
# special case: always retry centos + rhel 7 MongoDB module
# as the cpanm install fails to install this module randomly (not often)
if ($osflavour eq "redhat" and $osmajor = 7)
{
system("cpanm --sudo $prompt $rhel7_mongodb_module 2>&1");
}
}
else
{
logmsg(0,"CPANM installation failed");
# we fallback to cpan code used prior to cpanm
logmsg(0,"Installing modules with CPAN");
# prime cpan if necessary: non-interactive, follow prereqs,
if (!-e $ENV{"HOME"}."/.cpan") # might be symlink
{
print "Performing initial CPAN configuration\n";
if ($noninteractive)
{
# no inputs, all defaults
execPrint('cpan');
# adjust options unsuitable for noninteractive work
open(X,"|cpan") or die "cannot fork cpan: $!\n";
print X "o conf prerequisites_policy follow\no conf commit\n";
close X;
}
else
{
# there doesn't seem an easy way to prime the cpan shell with args,
# then let interact with the user via stdin/stdout... and not all versions
# of cpan seem to start it automatically
print "\n
If the CPAN configuration doesn't start automatically, then please
enter 'o conf init' on the CPAN prompt.
Should you get prompted to choose Perl Library directories, 'local::lib'
or the like, please choose 'sudo' or 'manual' - NOT 'local::lib'!
To return to the installer when done, please exit the CPAN shell with 'exit'.\n";
input_ok();
system("cpan");
}
logmsg(0,"CPAN configuration complete, proceeding with module installation");
}
system("cpan ".join(" ",@missingones)); # can't use execprint as cpan is interactive
}
}
}
# ready to install/upgrade,
# before copying anything, lock nmis
# fixme: make these into precopy stage!
open(F,">$targetdir/conf/NMIS_IS_LOCKED");
print F "$0 is operating, started at ".(scalar localtime)."\n";
close F;
open(F, ">/tmp/nmis_install_running");
print F $$;
close(F);
printBanner("Copying Files");
find(sub {
my ($name,$dir,$fn) = ($_, $File::Find::dir, $File::Find::name);
next if ($name =~ /^\./ # no hidden files
or $name =~ /^(installer|pre-install.sh)$/ # or installer files
or $dir =~ m!/installer_hooks$! # installer files
or ($name eq "installer_hooks" && -d $fn)); # installer files
print ".";
# $dir includes sourcedir prefix
my $destdir = $dir;
$destdir =~ s/^$sourcedir//;
if (-d $fn)
{
safemkdir("$targetdir/$destdir/$name");
}
elsif (-f $fn)
{
my $dest = "$targetdir/$destdir/$name";
safecopy($fn, $dest); # logs and dies on errors
}
}, $sourcedir);
printBanner("Performing Initialisation Operations");
run_hooks("postcopy"); # users config stuff, migrations, patching
printBanner("Performing Final Operations");
run_hooks("postinstall"); # unlock
# ensure the logfile and manifest are rwr-r-, regardless of system umask
# fixme move chmod(0644, $logfile) if (-f $logfile);
printBanner("Installation complete.");
exit 0;
# called for every file found by file::find
# args: none, $_ and file::find::stuff
# updates %modules
# returns: nothing
# note: callback from file::find means DON'T use the same filehandle F as elsewhere!
sub getModules
{
my ($dirname, $shortname, $fullpath) = ($File::Find::dir, $_, $File::Find::name);
# interesting? yes if it's a .pm or .pl, or if it lives in bin (no extensions there)
return if (-d $fullpath
or $shortname =~ /^\./
or !($shortname =~ /\.p[ml]$/ or $dirname eq "$sourcedir/bin"));
my $fh;
open($fh, $fullpath) or logdie("cannot read $fullpath: $!");
logmsg(1,"reading file $fullpath...");
while (my $line = <$fh>)
{
return if ($line =~ /^\x{7f}ELF/); # compiled binary
chomp $line;
next if (!$line or $line =~ /^\s*#/);
# test for module use 'xxx' or 'xxx::yyy' or deeper, plus numeric min version
if ( $line =~ /^\s*(use|require)\s+((\w+::)*\w+)(\s+([0-9\.]+))?.*;/ )
{
my ($usetype, $mod, $minversion) = ($1,$2,$4);
logmsg(1,"$shortname: '$line' => module $mod, minversion $minversion\n");
# ignore "use 5.10.11"
next if ($mod =~ /^[0-9\.]+$/);
$modules{$mod}->{file} = undef; # mark as not found, resolved later
$modules{$mod}->{usetype} = $usetype; # only last one is kept
# keep highest
$modules{$mod}->{minversion} = $minversion if (defined($minversion)
&& (!defined($modules{$mod}->{minversion})
or version->parse($modules{$mod}->{minversion}) < version->parse($minversion)));
$modules{$mod}->{priority} = 10; # low default
push @{$modules{$mod}->{usedby}}, $fullpath
if (!grep($_ eq $fullpath, @{$modules{$mod}->{usedby}}))
}
}
close $fh;
}
# returns (1) if no critical modules missing,
# (0,critical modules) otherwise
# args: none, walks the $sourcedir
sub check_installed_modules
{
printBanner("Checking for required Perl modules");
# walk the walk...
find(\&getModules, $sourcedir);
# fudge in a few indirectly needed ones
# these are critical for getting mojolicious installed, as centos 6 perl has a much too old perl
# these modules are in core since 5.19 or thereabouts
$modules{"IO::Socket::IP"} = { file => undef, usetype => "use",
usedby => "lib/NMISNG/Auth.pm", priority => 98 };
# io socket ip needs at least this version of socket...
# and that must be FIRST
$modules{"Socket"} = { file => undef, usetype => "use",
usedby => "lib/NMISNG/Auth.pm",
minversion => "1.97",
priority => 99 };
# and socket needs at least this version of extutils constant to build
$modules{"ExtUtils::Constant"} = { file => undef, usetype => "use",
usedby => "lib/NMISNG/Auth.pm",
minversion => "0.23",
priority => 100 };
# and mojolicious needs all these
$modules{"JSON::PP"} = { file => undef, usetype => "use",
usedby => "lib/NMISNG/Auth.pm", priority => 99 };
$modules{"Time::Local"} = { file => undef, usetype => "use",
usedby => "lib/NMISNG/Auth.pm",
minversion => "1.2", priority => 99 };
# and time::local needs at least this version of test::More
$modules{"Test::More"} = { file => undef, usetype => "use",
usedby => "lib/NMISNG/Auth.pm",
minversion => "0.96", priority => 100 };
# for compiling the mongodb perl driver
$modules{"Config::AutoConf"} = { file => undef, usetype => "use",
usedby => "lib/NMISNG/DB.pm",
minversion => "0.3", priority => 100 };
$modules{"Path::Tiny"} = { file => undef, usetype => "use",
usedby => "lib/NMISNG/DB.pm",
# minversion => "0.3",
priority => 100 };
# must be cpan'd before datetime and mongodb
$modules{"DateTime::Locale"} = { file => undef, usetype => "use",
usedby => "lib/NMISNG/DB.pm",
# minversion => "0.3",
priority => 100 };
# we strictly require mojolicious 8.11 or newer,
# as the older mojo::log api is too different
$modules{"Mojolicious"} = { file => undef, usetype => "use",
usedby => "lib/NMISNG/Log.pm",
minversion => "8.11", };
my $libprefix = "$sourcedir/lib";
# now determine if installed or not.
# sort by the required cpan sequencing (no priority is last)
foreach my $modname (keys %modules)
{
my $mFile = "$modname.pm";
$mFile =~ s/::/\//g; # translate logical namespaced name into path
my $thisentry = $modules{$modname};
next if ($thisentry->{version}); # already checked
# do we have it?
if (-f (my $ours = "$libprefix/$mFile" ))
{
$thisentry->{file} = $ours;
$thisentry->{version} = moduleVersion($ours, $modname);
}
else
{
# Now look in @INC for module path and name and record the highest-versioned one
for my $incpath (@INC)
{
if (-f (my $upstream = "$incpath/$mFile"))
{
my $thisversion = moduleVersion($upstream, $modname);
if (!$thisentry->{version}
or version->parse($thisversion) >= version->parse($thisentry->{version}))
{
$thisentry->{file} = $upstream;
$thisentry->{version} = $thisversion;
}
}
}
}
}
# now figure out what's missing (and which might be ignorable)
# note that they need to be returned in order of cpan sequencing priority!
my (@missing, @critmissing);
my %noncritical = ("Net::LDAP"=>1, "Net::LDAPS"=>1, "IO::Socket::SSL"=>1,
"Crypt::UnixCrypt"=>1, "Authen::TacacsPlus"=>1, "Authen::Simple::RADIUS"=>1,
"SOAP::Lite" => 1, "Net::SFTP::Foreign" => 1, "CiscoMerakiCloud" => 1);
logmsg(0, "Detected Module Status:\nName - Minimum Version - Current Version - Current Path\n");
# sort by install prio (highest first), or file
foreach my $k ( sort { $modules{$b}->{priority} <=> $modules{$a}->{priority}
or $modules{$a}->{file} cmp $modules{$b}->{file} } keys %modules)
{
my $thisentry = $modules{$k};
logmsg(0, join("\t", $k, ($thisentry->{minversion} || "N/A"),
($thisentry->{version}||"N/A"),
($thisentry->{file} || "NOT FOUND")));
# report as missing: if not present, or version below required minimum
push @missing, $k if (!defined $thisentry->{file}
or (defined $thisentry->{minversion}
and version->parse($thisentry->{version})
< version->parse($thisentry->{minversion})));
}
# We don't need to install our own stuff.
my @ourStuffArr = qx{find lib -type f -print | sed 's#lib/##' | sed 's#/#::#g'};
my %ourStuffMap;
# Bogus stuff we find ???
$ourStuffMap{"NMIS::IPSLA"} = 1;
$ourStuffMap{"NMIS::UUID"} = 1;
$ourStuffMap{"rrdfunc"} = 1;
$ourStuffMap{"t"} = 1;
$ourStuffMap{"NMIS::Connect"} = 1;
$ourStuffMap{"Compat::Connect"} = 1;
foreach my $modname (@ourStuffArr)
{
chomp($modname);
## for debugging: print ("Our Stuff Includes '$modname'\n");
$ourStuffMap{$modname} = 1;
}
my @editMissing;
foreach my $modname (@missing)
{
push(@editMissing, $modname) if (!exists($ourStuffMap{$modname}));
}
if (@editMissing)
{
@critmissing = grep( !$noncritical{$_}, @editMissing);
my @optionals = grep ($noncritical{$_}, @editMissing);
if (@optionals)
{
printBanner("Some Optional Perl Modules are missing (or too old)");
print qq|The following optional modules are missing or too old:\n| .join(" ", @optionals)
.qq|\n\nNote: The modules Net::LDAP, Net::LDAPS, IO::Socket::SSL, Crypt::UnixCrypt,
Authen::TacacsPlus, Authen::Simple::RADIUS are optional components for the
NMIS AAA system.\n\n|;
}
if (@critmissing)
{
printBanner("Some Required Perl Modules are missing (or too old)!");
print qq|The following Perl modules are missing or too old and must
be installed (or upgraded) before NMIS will work fully:\n\n| . join(" ", @critmissing)."\n\n";
logmsg(0, "Missing Required modules: ".join(" ", @critmissing));
}
}
return (@critmissing?0:1, @critmissing);
}
# get the module version
# note: this is non-optimal, and fails on a few modules (e.g. Encode)
# args: actual file, and module name
# returns: module version or undef
sub moduleVersion
{
my ($mFile, $modname) = @_;
my $ver;
open FH, "$mFile" or return undef;
while (<FH>)
{
if (/^\s*((our|my)\s+\$|\$(\w+::)*)VERSION\s*=\s*['"]?\s*[vV]?([0-9\.a-zA-Z]+)\s*['"]?s*;/)
{
close FH;
if ($ver = $4)
{
logmsg(1,"got version $ver for $modname from $mFile");
return $ver;
}
}
}
close FH;
# present but didn't match? load and ask the module then...
logmsg(1,"loading module $modname from $mFile for version check...");
eval { no warnings; require $mFile; };
if ($@)
{
logmsg(1,"failed to load $modname: $@");
return undef;
}
# encode doesn't like this variant
logmsg(1,"trying version check type one on $modname");
$ver = eval { $modname->VERSION };
if (!$ver or $@)
{
logmsg(1,"trying version check type two on $modname");
$ver = eval '$'."$modname"."::VERSION";
}
logmsg(1,"got version $ver for $modname");
return $ver;
}
# print prompt, read and return response string if interactive;
# or return default response in noninteractive mode.
#
# default is "", except in preseed mode where the default
# is looked up from the preseed data tagged by the seedling argument
sub input_text
{
my ($query,$seedling) = @_;
print $query;
if ($noninteractive)
{
if ($seedling && ref($answers) && defined($answers->{$seedling}))
{
my $answer = $answers->{$seedling};
print " (preseeded answer \"$answer\")\n";
logmsg(0, "preseeded answer \"$answer\" for \"$query\"");
return $answer;
}
else
{
print " (auto-default \"\")\n\n";
logmsg(0,"auto-default answer \"\" for \"$query\"");
return "";
}
}
else
{
print "\nEnter new value or hit <Enter> to accept default: ";
my $input = <STDIN>;
chomp $input;
logmsg(0, "User input for \"$query\": \"$input\"");
return $input;
}
}
# print question, return true if y (or in unattended mode).
# default is yes, except in preseed mode where the default
# is looked up from the preseed data tagged by the seedling argument
sub input_yn
{
my ($query, $seedling) = @_;
while (1)
{
print $query;
if ($noninteractive)
{
if ($seedling && ref($answers) && defined($answers->{$seedling}))
{
my $answer = $answers->{$seedling};
my $result = ( $answer =~ /^\s*(y(?:es)?)\s*$/i? 1:0);
print " (preseeded answer \"$answer\" interpreted as \""
.($result? "YES":"NO")."\")\n\n";
logmsg(0,"preseeded answer \"$answer\" for \"$query\" interpreted as \""
.($result? "YES":"NO"));
return $result;
}
else
{
print " (auto-default YES)\n\n";
logmsg(0,"auto-default answer YES for \"$query\"");
return 1;
}
}
else
{
print "\nType 'y' or <Enter> to accept, or 'n' to decline: ";
my $input = <STDIN>;
chomp $input;
logmsg(0, "User input for \"$query\": \"$input\"");
if ($input !~ /^\s*(y(?:es)?|n(?:o)?)?\s*$/i)
{
print "Invalid input \"$input\"\n\n";
next;
}
return ($input =~ /^\s*(y(?:es)?)?\s*$/i)? 1:0;
}
}
}
# prints prompt, waits for confirmation
sub input_ok
{
print "\nHit <Enter> to continue:\n";
my $x = <STDIN> if (!$noninteractive);
}
# run program synchronously but non-interactively, through the shell!
# log output, print+return errors
# if in simulation mode, print what would be done and DON'T execute anything
sub execPrint
{
my ($cmd) = @_;
if ($simulate)
{
print "\nSIMULATION MODE, NOT executing command '$cmd'\n\n";
return 0;
}
logmsg(0,"\n###+++\nEXEC: $cmd");
# robust: retry on failure
my $out;
my $res;
foreach ( 1, 2, 3, 4, 5, 6) {
$out = `$cmd 2>&1`;
my $rawstatus = $?;
$res = POSIX::WIFEXITED($rawstatus)? POSIX::WEXITSTATUS($rawstatus): -1;
if ($res == 0)
{
logmsg($debug,"\n###+++\nexecPrint '$cmd' succeeded\n\n");
last;
}