-
Notifications
You must be signed in to change notification settings - Fork 0
/
zyppm.pl
executable file
·3190 lines (2781 loc) · 96.9 KB
/
zyppm.pl
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
use strict;
use warnings;
use threads;
use threads::shared;
use zypp;
use Date::Parse;
use POSIX qw(strftime);
use Cwd;
use Mojolicious::Lite;
plugin 'Subprocess';
use Mojo::IOLoop;
use Mojo::Upload;
use Mojo::Log;
use Mojo::UserAgent;
use File::Temp qw(tempfile tempdir);
use File::Path qw(rmtree);
use JSON::XS;
use Scalar::Util 'weaken';
use MIME::Base64 qw(decode_base64 encode_base64);
use Digest::MD5 qw(md5_hex);
use Crypt::CBC;
use Data::Dumper;
=head1 NAME
zyppm.pl - Zypper monitor tool by Victor Zhestkov. The tool is monitoring installed packages and the history of changes.
=cut
use utf8;
# Set encoding for all open handles including STDIN/OUT
use open ':encoding(UTF-8)';
# With some perl versions the string abowe causing Segmentation fault on starting a thread. (ex. SLES-12SP3 perl v5.18.2)
#use open ':std';
=head1 CONFIGURATION CONSTANTS
Configuration constants are used to set basic configuration to store the data and to set the format of names for systems files.
=over 4
=item B<UPLOAD_DIR>
Sets the directory to upload files used to import systems information: supportconfigs, zypper dumps, rpm.txt and so on.
Default: "/tmp/upload/"
=item B<SYSTEMS_DIR>
Sets the directory to store systems JSON files.
Default: "systems/"
=item B<SYSTEMS_LIST>
Sets the name of the file to store systems list.
Default: "systems/systems.json"
=item B<SYSTEM_EXTENSION>
System file extansion.
Default: ".json"
=item B<BATCH_TIME_DELTA>
Sets the number of seconds to define as minimum gap between the changes considered as different batches.
The intervals smaller than the value specified considered as one batch.
Default: 600
=item B<MAX_RETURN_ITEMS>
Sets the maximum number of items to be returned with B</packages>, B</history>, B</USID/packages> and B</USID/history> web requests.
Could be overridden with B<mxcnt> parameter for the particular request on your own risk
as it could take much time to be processed with the client.
Default: 1000
=back
=cut
my $zmc;
BEGIN {
glob $zmc;
if ( open(my $cfg_fh, '<', "config.json") ) {
eval {
$zmc = JSON::XS->new->allow_nonref->decode(join('', <$cfg_fh>));
};
if ( $@ ) {
print("Error: Unable to parse config file.\n");
exit(1);
}
close($cfg_fh);
}
$ENV{MOJO_MAX_MESSAGE_SIZE} = 134217728;
};
sub getConfigValue {
my ($name, $default) = @_;
return (defined($zmc) && defined($zmc->{$name})) ? $zmc->{$name} : $default;
}
use constant {
# Configuration constants
UPLOAD_DIR => getConfigValue('UPLOAD_DIR', "upload/"),
SYSTEMS_DIR => getConfigValue('SYSTEMS_DIR', "systems/"),
SYSTEMS_LIST => getConfigValue('SYSTEMS_LIST', "systems/systems.json"),
SYSTEM_EXTENSION => ".json",
AUTHKEY_ALIVE => 5,
AUTHKEY_INTERVAL => 10,
AUTH_ORDER => getConfigValue('AUTH_ORDER', "none"),
AUTH_PTOKEN => getConfigValue('AUTH_PTOKEN', ""),
BOOTSTRAP_LOGIN => getConfigValue('BOOTSTRAP_LOGIN', ""),
BOOTSTRAP_PASSWD => getConfigValue('BOOTSTRAP_PASSWD', ""),
MONGODB_ENABLED => getConfigValue('MONGODB_ENABLED', 0),
MONGODB_HOST => 'mongodb://'.getConfigValue('MONGODB_USER', "zyppmon").':'.getConfigValue('MONGODB_PASSWORD', "zyppmon").'@'.
getConfigValue('MONGODB_HOST', "localhost").'/'.getConfigValue('MONGODB_AUTHDB', "zyppmon"),
MONGODB_DB => getConfigValue('MONGODB_DB', "zyppmon"),
MONGODB_SYSTEMS => getConfigValue('MONGODB_SYSTEMS', "systems"),
MONGODB_SYSDATA => getConfigValue('MONGODB_SYSDATA', "sysdata"),
MONGODB_CMPDATA => getConfigValue('MONGODB_CMPDATA', "cmpdata"),
LISTEN_PORT => getConfigValue('LISTEN_PORT', 8880),
FORCE_SECURE => getConfigValue('FORCE_SECURE', 0),
LISTEN_SECURE => getConfigValue('LISTEN_SECURE', 0),
LISTEN_SECURE_PORT => getConfigValue('LISTEN_SECURE_PORT', 8843),
SECURE_CERT => getConfigValue('SECURE_CERT', "zyppmon.cert.pem"),
SECURE_KEY => getConfigValue('SECURE_KEY', "zyppmon.key.pem"),
CACHE_TTL => 300,
BATCH_TIME_DELTA => 600,
MAX_RETURN_ITEMS => 1000,
INACTIVITY_TIMEOUT => 80,
# /Configuration constants
# Internal constants
ZDFLAG_INSTALLED => 1,
ZDFLAG_HISTORY => 2,
ZDFLAG_UPDATE => 5,
ZDFLAG_SETREPO => 8,
RLP_UNKNOWN => 0,
RLP_SR_QUERY => 1,
RLP_QA_LAST => 2,
RLP_SR_VERIFY => 3,
RLP_QUERY_CUSTOM => 4,
RLP_SKIP => 99,
INF_UNKNOWN => 0,
INF_OSINFO => 1,
INF_ENV => 2,
INF_SKIP => 99,
HIST_READ => 0,
HIST_TAIL => 1,
HIST_DONE => 2,
HIST_STOP => 4,
HIST_UPREPOS => 8,
# /Internal constants
};
if ( MONGODB_ENABLED ) {
eval {
use MongoDB;
};
die $@ if $@;
}
my $cache = {};
# This hash is related to fixing non-English date strings
my %to_en = (
# Russian monthes
'Янв' => 'Jan', 'Фев' => 'Feb', 'Мар' => 'Mar',
'Апр' => 'Apr', 'Май' => 'May', 'Июн' => 'Jun',
'Июл' => 'Jul', 'Авг' => 'Aug', 'Сен' => 'Sep',
'Окт' => 'Oct', 'Ноя' => 'Nov', 'Дек' => 'Dec',
# Russian days of week
'Пнд' => 'Mon', 'Пн' => 'Mon',
'Втр' => 'Tue', 'Вт' => 'Tue',
'Срд' => 'Wed', 'Ср' => 'Wed',
'Чтв' => 'Thu', 'Чт' => 'Thu',
'Птн' => 'Fri', 'Пт' => 'Fri',
'Сбт' => 'Sat', 'Сб' => 'Sat',
'Вск' => 'Sun', 'Вс' => 'Sun',
);
# Building regexp pattern to search substrings to fix
my $to_en_rx = join("|", map {quotemeta} keys %to_en);
my @env_v = qw/HOST HOSTNAME HOSTTYPE OSTYPE MACHTYPE CPU/;
# Redefine Mojolicious log output function to change the time format
{
no warnings 'redefine';
*Mojo::Log::_default = sub {
return '' if $_[2] eq 'Routing to a callback';
'[' . strftime("%Y-%m-%d %T", localtime(shift)) . '] [' . shift() . '] ' . join "\n", @_, '';
};
}
app->secrets(['ZyppMonSecretPhrase']);
app->log->info("Starting Zypper Monitor");
# Set root directory to look static files from
#app->static->paths->[0] = getcwd().'/zwebapp/';
app->static->paths->[0] = '/zyppmon/webapp/';
my $tthread;
=head1 SHARED GLOBALS
=over 4
=item B<%pkgs>
B<%pkgs> shared hash is a main data structure the tool using to store packages and the history of packages operations.
=cut
my %pkgs: shared;
=item B<@packages>
B<@packages> shared array contains plain list of packages extracted from B<%pkgs>.
=cut
my @packages: shared;
=item B<@history>
B<@history> shared array contains plain list of packages history operations extracted from B<%pkgs>.
=cut
my @history: shared;
=item B<%repos>
B<%repos> shared hash contains a list of system repositories.
=cut
my %repos: shared;
=item B<@systems>
B<@systems> shared array contains plain list of systems stored in JSON file defined by B<SYSTEMS_LIST> global constant.
=cut
my @systems: shared;
my $ext_systems;
=item B<$self_usid>
B<@systems> shared scalar contains the USID of running system.
It's usually autogenerated on first run and stored in JSON file defined by B<SYSTEMS_LIST> global constant.
=cut
my $self_usid: shared;
=item B<$history_ctrl>
B<$history_ctrl> shared scalar is used to control the thread reading zypper history log file.
=cut
my $history_ctrl: shared = 0;
=item B<%state>
B<$history_ctrl> shared hash contains the state variables of current system available with B</check> web service call.
=cut
my %state: shared = ("history-last-id" => 0,
"history-count" => 0,
"history-rm" => 0,
"history-rf" => 0,
"history-up" => 0,
"history-dn" => 0,
"history-in" => 0,
"systems-ts" => 0,
"count" => 0,
"installed" => 0,
"removed" => 0);
=back
=cut
#my ($mongo, $mongo_db, $mongo_systems, $mongo_sysdata);
app->log->debug("Initializing Zypper instance");
# Initializing zypper instance
my $zypp_factory = zyppc::ZYppFactory_instance();
my $zypp = $zypp_factory->getZYpp();
$zypp->initializeTarget(zypp::Pathname::new("/"));
app->log->debug("Cleaning cache and loading data...");
$zypp->target->cleanCache();
$zypp->target->load();
app->log->debug("... done");
=head1 FUNCTIONS
=over 4
=item B<vrcmp>
The function to compare versions/release or version-release of the package
2 or 4 arguments could be accepted:
=over 5
"VERSION1", "VERSION2"
"RELEASE1", "RELEASE2"
"VERSION1-RELEASE1", "VERSION2-RELEASE2"
"VERSION1", "RELEASE1", "VERSION2", "RELEASE2"
=back
=cut
sub vrcmp {
my $q = [];
# Internal function to enqueue the components to compare to LIFO queue
sub enque_cmp {
my $q = shift;
while ( my $p = shift ) {
$p->[0] = '' unless defined($p->[0]);
$p->[1] = '' unless defined($p->[1]);
unshift(@$q, $p) if $p->[0] ne $p->[1];
}
}
# Put the function arguments to the queue to be processed
if ( @_ == 2 ) {
enque_cmp($q, [$_[0], $_[1]]);
} elsif ( @_ == 4 ) {
enque_cmp($q, [$_[1], $_[3]], [$_[0], $_[2]]);
} else {
return undef;
}
my $c = 0;
# Processing the LIFO queue
while( my $next = shift @$q ) {
$c++;
my ($a, $b) = @$next;
my ($ax, $ay, $bx, $by);
if ( (($ax, $ay) = $a =~ /\A([^\-]+)(?:\-(.*)|)\z/) &&
(($bx, $by) = $b =~ /\A([^\-]+)(?:\-(.*)|)\z/) && (defined($ay) || defined($by)) ) {
# Splitting VERSION-RELEASE stings
enque_cmp($q, [$ay, $by], [$ax, $bx]);
} elsif ( (($ax, $ay) = $a =~ /\A([^\.]+)(?:\.(.*)|)/) &&
(($bx, $by) = $b =~ /\A([^\.]+)(?:\.(.*)|)/) && (defined($ay) || defined($by)) ) {
# Splitting stings to before '.' component and everything after
enque_cmp($q, [$ay, $by], [$ax, $bx]);
} elsif ( $a =~ /\A\d+\z/ && $b =~ /\A\d+\z/ ) {
# Continue if numeric components are equal or return the result based on comparison of these components
next if $a == $b;
return $a > $b ? 1 : -1;
} elsif ( $a =~ /\A\D+\z/ && $b =~ /\A\D+\z/ ) {
# Continue if NON numeric components are equal or return the result based on comparison of these components
next if $a eq $b;
return $a gt $b ? 1 : -1;
} elsif ( (($ax, $ay) = $a =~ /\A(\d+)(.*)/) && (($bx, $by) = $b =~ /\A(\d+)(.*)/) ) {
# Splitting components to numeric and NON numeric parts
if ($ay ne '' && $by ne '') {
# Enqueue if NON numeric parts are not blank
enque_cmp($q, [$ay, $by], [$ax, $bx]);
} elsif ( $ax != $bx ) {
# Return the result based on comparison of numeric parts
return $ax > $bx ? 1 : -1;
} else {
# Return the result that the version-release componen with blank value is less than the other
return $ay eq '' ? -1 : 1;
}
} elsif ( (($ax, $ay) = $a =~ /\A(\D+)(.*)/) && (($bx, $by) = $b =~ /\A(\D+)(.*)/) ) {
# Splitting components to NON numeric and everything last parts
enque_cmp($q, [$ay, $by], [$ax, $bx]);
} elsif ( ((($ax, $ay) = $a =~ /\A(\d+)(.*)/) && (($bx, $by) = $b =~ /\A(\D+)(.*)/)) ||
((($ax, $ay) = $a =~ /\A(\D+)(.*)/) && (($bx, $by) = $b =~ /\A(\d+)(.*)/))) {
# Processing the situation if one component starts with numeric symbol while the other with NON numeric
# The component with numeric symbol at start wins. Not sure if it right, but zypper return the same result in such condition
return $ax =~ /\A\d/ ? 1 : -1;
} elsif ( $a eq '' || $b eq '' ) {
# Compare blank an non blank components. Non blank wins
return $a eq '' ? -1 : 1;
} else {
# It shouldn't happen in real life, but...
return $a gt $b ? 1 : -1;
}
}
return 0;
}
=item B<getvr>
The function splits VERSION and RELEASE components from the string.
Argument: "VERSION-RELEASE" string
Returns: array of 2 elements: ("VERSION" string, "RELEASE" string)
=cut
sub getvr {
my $s = shift;
if ( my @r = $s =~ /\A([^\-]+)\-(.*)\z/ ) {
return @r;
}
return undef;
}
=item B<splitNameVerRelArch>
The function splits NAME, VERSION, RELEASE and ARCH components from the string and returns an hash reference.
Argument: "VERSION-RELEASE.ARCH" string, ARCH could be omited
Returns: hash reference: {name => NAME, ver => VERSION, rel => RELEASE, arch => ARCH}
=cut
sub splitNameVerRelArch {
my ($s) = @_;
my ($ver, $rel, $arch);
($s, $arch) = ($1, $2) if ( $s =~ /(.*)\.(noarch|x86_64|i[3-6]86|aarch64)$/ );
($s, $ver, $rel) = ($1, $2, $3) if ( $s =~ /(?:(.*)\-|)([\w\.\+~]+)\-([\w\.\+]+)/ );
return {name => $s, ver => $ver, rel => $rel, arch => $arch};
}
=item B<getLimitedArray>
The function returns the array reference to the array made with limited amount of the source items from first argument array reference.
Arguments:
=over 5
=item 1: array reference
The source of the data to return. If this argument is not an array reference it will be returned immidiately as return value.
=item 2: integer
The starting index of the element.
If not specified, the 0 is used.
=item 3: integer
The maximum amount of the elements to be returned.
If not specified, B<MAX_RETURN_ITEMS> configuration constant is used.
=back
Return: hash reference - data item contains the array from 1st argument starting from 2nd argument or 0 if not set
and limited by count specified in 3rd argument or B<MAX_RETURN_ITEMS> if 3rd argument is not defined.
ctrl item of the hash contains the control information.
=cut
sub getLimitedArray {
my $r = shift;
my ($st, $mx) = @_;
if ( ref($r) ne 'ARRAY' ) {
return $r;
}
my @a;
$st = defined($st) ? int($st) : 0;
$mx = defined($mx) ? int($mx) : MAX_RETURN_ITEMS;
my $c = 0;
my $i = $st;
my $sz = scalar(@{$r});
while ( $i < $sz ) {
my %h = %{$r->[$i]};
push(@a, \%h);
$c++;
$i++;
if ( $c >= $mx ) {
last;
}
}
my $ret = {size => $sz, start => $st, items => $c, 'maxReturn' => $mx};
if ( $i < $sz || $c < $sz ) {
$ret->{'next'} = $i if ($sz - $i >= 1);
}
return {ctrl => $ret, data => \@a};
}
=item B<updateHistoryArray>
The function to update global B<@history> shared array if second argument is not specified
or b<history> section of second argument hash reference.
Arguments:
=over 5
=item 1: integer
Last insert ID value to get only records with History ID larger than this value.
=item 2: hash reference
The reference to the system structure with B<pkgs> and B<history> sections. If not specified global B<%pkgs> and B<@history> are used.
=back
The function returns nothing.
=cut
sub updateHistoryArray {
my ($lid, $ref) = @_;
my $p = \%pkgs;
my $h = \@history;
my $to_ref = defined($ref);
$lid = defined($lid) ? $lid : 0;
if ( $to_ref ) {
$p = $ref->{pkgs};
$h = $ref->{history};
} else {
lock(@history);
}
@$h = () if ( $lid == 0 );
app->log->debug("Updating history array (".$lid.")...") if $to_ref;
my $tstamp = time();
foreach my $arch ( keys(%{$p}) ) {
foreach my $name ( keys(%{$p->{$arch}}) ) {
if (defined($p->{$arch}{$name}{h})) {
my ($ver, $rel, $op, $ts);
foreach my $hrow ( @{$p->{$arch}{$name}{h}} ) {
if ( $lid == 0 || $hrow->{hid} > $lid ) {
my ($preVer, $preRel);
($preVer, $preRel) = ($ver, $rel) if ( $hrow->{op} =~ /\A(?:up|dn)\z/ );
my %hr = %{$hrow};
$hr{name} = $name;
$hr{arch} = $arch;
$hr{preVer} = $preVer if defined($preVer);
$hr{preRel} = $preRel if defined($preRel);
$hrow->{ts} = $tstamp unless defined($hrow->{ts});
$hr{ts} = $hrow->{ts};
push(@$h, $to_ref ? \%hr : shared_clone(\%hr));
}
($ver, $rel, $op, $ts) = ($hrow->{ver}, $hrow->{rel}, $hrow->{op}, $hrow->{ts});
$state{"history-last-id"} = $hrow->{hid} if ( $to_ref && $hrow->{hid} > $state{"history-last-id"} );
}
}
}
}
@history = sort({$a->{hid} <=> $b->{hid}} @history);
app->log->debug("... done #".scalar(@history)) if $to_ref;
}
=item B<s2time>
The function converts string to unix timestamp
Argument: string - time in text format
Return: integer - unix timestamp
=cut
sub s2time {
my ($t) = @_;
$t =~ s/(?:\b($to_en_rx)\b)/$to_en{$1}/ig;
return str2time($t);
}
sub randString { join'', @_[ map { rand @_ } 1 .. shift ] }
=item B<genUSID>
The function generates USID based on system's data.
Arguments:
=over 5
=item 1: hash ref
Hash reference to the system.
=back
Return: string - USID generated based on the system's data specified.
=cut
sub genUSID {
my ($sys) = @_;
my $in;
if ( defined($sys) && $sys->{type} eq 'template' && defined($sys->{usids}) && ref($sys->{usids}) eq 'ARRAY' ) {
$in = join(':', sort(@{$sys->{usids}}));
} elsif ( defined($sys) ) {
$in = $sys->{ts}.':'.$sys->{type}.':'.$sys->{name};
} else {
$in = time().':'.randString(128, 'A'..'Z', 'a'..'z', 0..9);
}
my $usid = md5_hex($in);
$usid =~ s/\A(.{8})(.{4})(.{4})(.{4})(.{4})/$1-$2-$3-$4-$5/;
return $usid;
}
=item B<loadSystemsList>
The function loads systems list from JSON file specified in global constant B<SYSTEMS_LIST> to B<@systems> global sharerd array.
It also generates self USID and put it back to the systems file if it doesn't contain self system.
The function takes no arguments.
The function returns nothing.
=cut
sub loadSystemsList {
my $sl_fh;
app->log->debug("Loading systems list ...");
my $s;
if ( open($sl_fh, '<', SYSTEMS_LIST) ) {
$s = JSON::XS->new->allow_nonref->decode(join('', <$sl_fh>));
close($sl_fh);
my $sf = 0;
foreach ( @$s ) {
if ( defined($_->{type}) && defined($_->{usid}) && $_->{type} eq "self" ) {
$sf = 1;
$self_usid = $_->{usid};
}
push(@systems, shared_clone($_)) if ( defined($_->{name}) && defined($_->{usid}) &&
defined($_->{type}) && defined($_->{ts}) &&
((($_->{type} eq 'file' || $_->{type} eq 'template') && defined($_->{ufl}) && defined($_->{file})) ||
($_->{type} eq 'host' && defined($_->{host})) || $_->{type} eq 'self') );
}
} else {
app->log->debug("... unable to open systems list file: ".SYSTEMS_LIST);
}
unless ( defined($self_usid) ) {
app->log->debug("Generating self USID...");
my $host = $ENV{HOSTNAME};
$host = $ENV{HOST} unless defined($host);
$host = 'unknown' unless defined($host);
$host =~ s/\..*//;
$self_usid = updateSystem({name => $host, type => 'self', ts => time()});
}
app->log->info("Self USID: ".$self_usid);
app->log->debug("... done (systems loaded: ".scalar(@systems).")");
$state{"systems-ts"} = time();
}
=item B<mongoDBinit>
The function initializing MongoDB subsystem. This system could significantly improve web service performance
in case of retriving systems packages list and history.
The function also checks if all systems contained in MongoDB and import it from file otherwise.
The function takes no arguments.
The function returns nothing.
=cut
sub mongoDBinit {
if ( !MONGODB_ENABLED ) {
app->log->info("MongoDB subsystem is disabled. You may enable it to improve web service performance.");
return;
}
app->log->debug("Initializing MongoDB subsystem ...");
my ($mongo, $mongo_db, $mongo_systems, $mongo_sysdata);
$mongo = MongoDB->connect(MONGODB_HOST);
$mongo_db = $mongo->get_database(MONGODB_DB);
$mongo_systems = $mongo_db->get_collection(MONGODB_SYSTEMS);
$mongo_sysdata = $mongo_db->get_collection(MONGODB_SYSDATA);
foreach my $sys ( @systems ) {
app->log->debug(sprintf("checking [%s] (%s)", $sys->{usid}, $sys->{name}));
my $mongo_sys = $mongo_systems->find({usid => $sys->{usid}});
$mongo_sys->result();
my $n = $mongo_sys->info()->{num};
if ( $n == 1 ) {
app->log->debug("... ok");
} else {
$mongo_systems->delete_many({usid => $sys->{usid}});
$sys->{'_id'} = $sys->{usid};
$mongo_systems->insert_one($sys);
if ( $sys->{type} eq 'file' ) {
if ( open(my $sys_fh, '<', $sys->{file}) ) {
my $sd = JSON::XS->new->allow_nonref->decode(join('', <$sys_fh>));
close($sys_fh);
delete($sd->{pkgs});
$sd->{'_id'} = $sys->{usid};
$mongo_sysdata->insert_one($sd);
} else {
app->log->error(sprintf("Unable to open system file: %s", $sys->{file}));
}
}
app->log->debug("... exported");
}
}
app->log->debug("... done");
}
=item B<updateSystem>
The function updates system's data and save it. It's also used to generate USID for new systems before parsing the data into.
Arguments:
=over 5
=item 1: hash reference
First arguments is an hash reference to system's information to be stored in systems list.
If not defined only USID will be generated.
=item 2: string
USID of the system to be updated with the information from 1st argument.
If not defined, but 1st argument hash reference contains B<usid> key than this value will be used as USID.
=back
Return: string - USID of the system
=cut
sub updateSystem {
my ($s, $usid) = @_;
$s->{ts} = time() unless defined($s->{ts});
$usid = $s->{usid} if ( !defined($usid) && defined($s) && defined($s->{usid}) );
unless ( defined($usid) ) {
$usid = genUSID($s);
# Just return USID if no system data specified
return $usid unless defined($s);
}
return unless defined($s);
$s->{usid} = $usid unless defined $s->{usid};
if ( MONGODB_ENABLED ) {
my ($mongo, $mongo_db, $mongo_systems);
eval {
$mongo = MongoDB->connect(MONGODB_HOST);
$mongo_db = $mongo->get_database(MONGODB_DB);
$mongo_systems = $mongo_db->get_collection(MONGODB_SYSTEMS);
$mongo_systems->delete_many({usid => $usid});
unless ( defined($s->{remove}) && $s->{remove} ) {
$s->{'_id'} = $usid;
$mongo_systems->insert_one($s);
}
};
}
{
my $fs;
lock(@systems);
for ( my $i = 0; $i < @systems; $i++ ) {
if ( defined($systems[$i]->{usid}) && $systems[$i]->{usid} eq $usid ) {
unlink($systems[$i]->{file}) if ( defined($s->{remove}) && $s->{remove} && defined($systems[$i]->{file}) );
$systems[$i] = shared_clone($s);
$fs = $i;
last;
}
}
push(@systems, shared_clone($s)) unless defined($fs);
}
@systems = grep({ !(defined($_->{remove}) && $_->{remove}) } @systems);
my $json_fh;
unless ( open($json_fh, '>', SYSTEMS_LIST) ) {
app->log->debug("Unable to open systems list file for writing: ".SYSTEMS_LIST);
return $usid;
}
print($json_fh JSON::XS->new->pretty->allow_nonref->encode(\@systems));
close($json_fh);
app->log->debug("Systems list saved (systems saved: ".scalar(@systems).")");
$state{"systems-ts"} = time();
return $usid;
}
sub updateExtSystems {
my ($sr, $parent) = @_;
return -1 if ( ref($sr) ne 'ARRAY' );
foreach my $sys ( @{$sr} ) {
if ( defined($sys->{usid}) ) {
my %sys = %{$sys};
$sys{prnt_usid} = $parent;
$sys{prnt_sys} = getSystem($parent);
$ext_systems->{$sys->{usid}} = \%sys;
}
}
}
=item B<getSystem>
The function return hash reference with system's data by USID specified.
Argument: string - USID to get system's data
Return: hash reference - system's data
=cut
sub getSystem {
my ($usid, $ext) = @_;
foreach ( @systems ) {
if ( $_->{usid} eq $usid ) {
return $_;
}
}
return undef unless $ext;
return $ext_systems->{$usid} if defined($ext_systems->{$usid});
return undef;
}
=item B<getPackagesArray>
The function creates plain array list of the packages based on data from B<pkgs> structure from B<pkgs> section
of the system's structure or B<%pkgs> global shared hash in case if 1st variable not defined.
Arguments:
=over 5
=item 1: hash reference
The reference to B<pkgs> structure, if not specified B<%pkgs> global shared hash is used.
=item 2: array reference
The reference to the array to store plain list into. If not defined, new array will be created and the reference to this array will be returned.
=back
Return: array reference - the reference to the array containing the plain list of the packages, the same as 2nd argument if it was specified.
=cut
sub getPackagesArray {
my ($ref, $ret, $g_insd) = @_;
$g_insd = (defined($g_insd) && $g_insd) ? 1 : 0;
my @a = ();
my $rr = \@a;
$rr = $ret if defined($ret);
my $p = \%pkgs;
my %s = (count => 0, installed => 0, removed => 0);
$p = $ref->{pkgs} if defined($ref);
foreach my $arch ( keys(%{$p}) ) {
foreach my $name ( keys(%{$p->{$arch}}) ) {
if ( defined($p->{$arch}{$name}{i}) || $g_insd ) {
if ( defined($p->{$arch}{$name}{i}) && ref($p->{$arch}{$name}{i}) eq 'HASH' ) {
$s{count}++;
$s{installed}++;
my %arow = %{$p->{$arch}{$name}{i}};
$arow{name} = $name;
$arow{arch} = $arch;
$arow{mods} = defined($p->{$arch}{$name}{h}) ? scalar(@{$p->{$arch}{$name}{h}})-1 : 0;
push(@{$rr}, shared_clone(\%arow));
} elsif ( defined($p->{$arch}{$name}{i}) ) {
my $hix = 0;
my $hls = scalar(@{$p->{$arch}{$name}{i}})-1;
foreach my $irow ( @{$p->{$arch}{$name}{i}} ) {
$s{count}++;
$s{installed}++;
my %arow = %{$irow};
$arow{name} = $name;
$arow{arch} = $arch;
$arow{mods} = ($hix == $hls) ? (defined($p->{$arch}{$name}{h}) ? scalar(@{$p->{$arch}{$name}{h}})-1 : 0) : 0;
push(@{$rr}, shared_clone(\%arow));
$hix++;
}
} elsif ( $g_insd && defined($p->{$arch}{$name}{h}) ) {
foreach my $hrow ( reverse(@{$p->{$arch}{$name}{h}}) ) {
if ( $hrow->{op} ne 'rm' ) {
$s{count}++;
$s{installed}++;
my $gip = {name => $name, arch => $arch, installTime => $hrow->{ts},
mods => scalar(@{$p->{$arch}{$name}{h}})};
foreach my $vl ( ('ver', 'rel', 'repoName', 'repoAlias', 'vendor') ) {
$gip->{$vl} = $hrow->{$vl} if defined($hrow->{$vl});
}
push(@{$rr}, shared_clone($gip));
last;
}
}
}
} else {
$s{count}++;
$s{removed}++;
push(@{$rr}, shared_clone({name => $name, arch => $arch, removed => 1,
mods => defined($p->{$arch}{$name}{h}) ? scalar(@{$p->{$arch}{$name}{h}}) : 0}));
}
}
}
if ( defined($ref) ) {
foreach ( keys(%s) ) {
$ref->{'stat'}{$_} = $s{$_};
}
} else {
foreach ( keys(%s) ) {
$state{$_} = $s{$_};
}
}
return $rr;
}
=item B<getHistoryArray>
The function returns items from B<@history> array according to the argument specified. The argument limits the number of items to return.
Argument: integer - last insert ID, the function returns only the records with B<hid> field larger than value specified
or full array if the value is 0.
Return: array reference - the reference to the array with items meet the limitation.
=cut
sub getHistoryArray {
my $lid = shift;
$lid = defined($lid) ? int($lid) : 0;
updateHistoryArray($state{"history-last-id"}) if ( $lid > $state{"history-last-id"} );
return \@history if ( $lid == 0 );
my @a = ();
app->log->debug("Returning partial history (>$lid)...");
foreach ( @history ) {
if ( $_->{hid} > $lid ) {
my %hr = %{$_};
push(@a, \%hr);
}
}
app->log->debug("... done #".scalar(@a));
return \@a;
}
=item B<getOSinfo>
The function returns hash reference containing basic environment information about running system.
This information is returning on B</info> requests.
The function takes no arguments.
Return: hash reference - basic environment information
=cut
sub getOSinfo {
my %os_info;
foreach ( glob("/etc/*-release") ) {
textReadENV($_, \%os_info);
}
foreach (@env_v) {
if ( defined($ENV{$_}) ) {
$os_info{'ENV_'.$_} = $ENV{$_};
}
}
return \%os_info;
}
=item B<getRepos>
The function returns array reference to the repositories list ordered by priority.
The function takes no arguments.
The
=cut
sub getRepos {
my @repos;
foreach ( sort({$repos{$a}{priority} <=> $repos{$b}{priority}} keys(%repos)) ) {
push(@repos, $repos{$_});
}
return \@repos;
}
=item B<textReadRPM>
The function is used to parse RPM lists text files.
Arguments:
=over 5
=item 1: string
The path to the file to parse.
=item 2: hash reference
The reference to the B<pkgs> structure to store the parsed data into.
=back
The function returns nothing.
=cut
sub textReadRPM {
my ($fl, $pr) = @_;
my $fl_fh;
app->log->debug("Reading RPM txt $fl ...");
open($fl_fh, '<', $fl) or return;
app->log->debug("... open OK");
my ($t, $cp, $tm, $dist, $vr, $vfy);
$t = RLP_UNKNOWN;
my ($qod, $sep);
while ( my $l = <$fl_fh> ) {
if ( $l =~ m!^# (?:[/\w]+|)rpm -qa --(?:queryformat|qf) (.*)! ) {
my $qf = $1;
$qf =~ s/^"//;
$qf =~ s/"$//;
my (@qfvs) = $qf =~ /\%\-?\d*\{\w+\}/g;
my (@qvs) = $qf =~ /\%\{\w+\}/g;