-
Notifications
You must be signed in to change notification settings - Fork 2
/
f5-cfg
executable file
·3000 lines (2819 loc) · 95.9 KB
/
f5-cfg
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 -w
#
# (C) Krystian Baniak 2021
#
# contact: [email protected]
# license: MIT
# program: f5-cfg
# description: tool for managing F5 LTM devices via iControl REST
# allows for batch processing for complex transactions
#
use strict;
use warnings;
# remember from where we are called
my $rundir = $ENV{PWD};
BEGIN {
use Cwd;
use File::Basename;
$rundir = getcwd();
my $__base = dirname(__FILE__);
if ( -l __FILE__) {
$__base = dirname(readlink(__FILE__));
}
chdir($__base) || die ". cannot chdir into $__base";
push (@INC, "./lib");
}
use Switch;
use JSON;
use Data::Dumper;
use HTTP::Request::Common;
use HTTP::Request;
use Getopt::Std;
use LWP::UserAgent;
use Digest::SHA qw(sha1 sha1_hex sha1_base64);
use File::Path qw(remove_tree);
use POSIX qw(strftime);
use Text::Diff;
use IO::Tee;
use URI::Escape;
use CAudit;
use CCache;
use COpts;
my $version = '1.5.1';
my $tee = \*STDOUT;
# --------- DEB -----------------
my $debug_vs = 0;
my $debug_prof = 0;
my $debug_rules = 0;
# --------- DEB -----------------
# -- hack needed to support F5 iCR API transactions
{
no warnings;
unless (defined &PATCH) {
print "+: adding a PATCH subroutine for LWP agent\n";
sub PATCH { _simple_req('PATCH', @_); }
}
}
# --
our ( %opts );
getopts('u:p:O:t:q:fdhAikKTrQc:C:I:JsSx:R:w:l:b:B:Z:P:D:v:M:', \%opts);
unless ($opts{'Q'}) {
printf ". runtime location: %s, rundir: %s\n", getcwd(), $rundir;
print("\x1b[92m(C) 2021, Krystian Baniak <krystian.baniak\@exios.pl>, F5 restful configuration tool, version: $version\x1b[0m\n");
}
#-------------------------------------------------
# advanced options parser
my $popts = COpts->new();
if ($opts{'O'}) {
$popts->parse( $opts{'O'} );
if ($popts->isFailed()){
print "-- error in parsing options! Aborting ...\n";
exit 3;
}
}
#-------------------------------------------------
# help message
if ($opts{'h'}){
my $__odefs = $popts->describe;
my $__bdefs = $popts->batch_describe;
print <<QQQ
--- [*] help section:
invocation:
$0 <options>
options:
--------------------------------------------------------------------------------------------
-h : this help message
-d : debug mode
-q query : single query mode, will not produce output file
-u user : user, default is admin
-p password : password, default is admin
-f : password will be read from the stdin after a prompt
-t host : f5 mgmt interface's IP address to query
-A : create archive containing iRules and iCall scripts
-l name : label used to create archive file name (affects -A option)
-i : identify f5 box
-k : verify iRule versions and allocation to virtual servers
-K : verify listeners and their allocation to virtual servers
-M seconds : timeout for iCR and iCR REST queries
-c name : create iRule or other resource from a file given in -I option
-C name : update iRule or other resource from a file given in -I option
-D name : dump given iRule to a working directory
-I : input resource
-J : modifies batch mode to return silently json response
-P : port to connect to
-r : retain temporal objects (used with -A option)
-s : save config
-S : sync cluster
-w : working directory
-l name : affect -a and -A by unifying the name of the resource
-b name : batch mode that uses json file as input
-B steps : semicolon delimited list of steps, mutually exclusive with -b option
-Z step : select step set from a step set list, used only with a -b option
-x cmd : execute advanced script action
-R name : run special report name [ availability depends on version ]
-T : use token based authentication
-Q : quiet mode - supress logs to a file
-O opts : list of options param=value,param=value, use %20 to escape a white space
example: base=gen8.2/test,label=ala%20ma%20kota
-v string : batch mode variables (see opts for syntax)
--------------------------------------------------------------------------------------------
list of known options:
$__odefs
list of known batch commands
$__bdefs
--- *
QQQ
;
exit;
}
STDOUT->autoflush(1);
# -- Orange F5 nodes
my %nodes = %{ load_dataset_from_file('./cfg/nodes.json', 'nodes') };
my %props = ();
my %srun = ();
# ----------------- SETTINGS --------------------
my $usr = $opts{'u'} || 'admin';
my $pass = $opts{'p'} || 'admin';
my $host = $opts{'t'} || '192.168.1.254';
my $ifns = $opts{'I'} || 'input.txt';
my $wDir = $opts{'w'} || '';
my $Label = $opts{'l'} || '';
my $bstep = $opts{'Z'} || '';
my $cport = $opts{'P'} || 443;
my $reqTm = 600;
# update default request timeout for both iCR and iCR REST queries
if ($opts{'M'}) {
$reqTm = int($opts{'M'});
}
my $URL_BARE = "https://$host/";
my $URL = "https://$host/mgmt/tm/";
my $URLB = "https://$host/mgmt/shared/authn/login";
my $host_name = $host;
my $tmp_stmp = &gen_tmstmp;
my %ems;
my $tks = '';
if ($opts{'P'}) {
$URL_BARE = "https://$host:$opts{'P'}/";
$URL = "https://$host:$opts{'P'}/mgmt/tm/";
$URLB = "https://$host:$opts{'P'}/mgmt/shared/authn/login";
}
# global operation flags
my %rflags = (
'req_not_fatal' => 0,
'req_error_silent' => 0
);
# CAudit heper
sub createSoapCtx
{
my ($_h, $_u, $_s, $_p, $_t) = @_;
my $k = new CAudit($_h, $_u, $_s, $_p);
$k->setTimeout($_t);
return $k;
}
#-------------------------------------------------
# Authentication Cache
my $cache = CCache->new("./cfg/.ccache.json");
unless (-e "./cfg/.ccache.json") {
print "-- creating new empty cache file.\n";
$cache->setup_authcache( \%nodes );
$cache->save;
}
$cache->open;
# interactive password retrieval
if ($opts{'f'}) {
$pass = $cache->getUserCredentials;
}
#-------------------------------------------------
# Log file settings
# by default we make a transation log fom every script invocation
# the results are kept in the logfiles directory
unless (-e "logfiles" && -d "logfiles") {
mkdir "logfiles";
}
my $log_fname = "logfiles/config-audit-log-${tmp_stmp}.log";
if ($popts->get('onelog') eq "yes") {
$log_fname = "logfiles/config-audit-log.log";
}
if ($opts{'Q'} or ($popts->get('supress_log') eq "yes")) {
#print "+ supressing transactional logging...\n";
} else {
$tee = new IO::Tee(\*STDOUT, new IO::File(">$log_fname"));
}
#-------------------------------------------------
# determine host and authentication details
update_host( $host );
#-------------------------------------------------
# working directory settings
my $remove_temp = 1;
if ($opts{'r'}) { $remove_temp = 0; }
if ($wDir ne '') {
if (! -e $wDir) {
printf $tee "!-- working directory not found: $wDir\n";
exit;
}
} else {
$wDir = $rundir;
}
# -----------------------------------------------
# Debug settings
my $db_cr = 0;
if ($opts{'d'}) {
# enable all kinds of debug
$debug_vs = $debug_prof = 1;
$db_cr = 1;
}
#------------------------------------------------
# LWP settings
my $ua = new LWP::UserAgent;
$ua->timeout($reqTm);
$ua->ssl_opts( verify_hostname => 0, SSL_verify_mode => 0x00 );
#------------------------------------------------
# F5 token based authentication
if ($opts{'T'}) {
$tks = &tokenRequest;
#print Dumper($tks);
if ($tks->{token}) {
$tks = $tks->{token}{token};
print "++ token: $tks\n";
}
}
#-----------------------------------------------
# Properties are needed for Batch mode
if ($popts->get('bigiq') ne '') {
} else {
# get big-ip properties
&update_platform_properties;
if ($opts{'i'}){
&print_platform_properties;
}
}
#-----------------------------------------------
# batch mode
if ($opts{'b'}) {
if (!$opts{Q}) {
print $tee "+-- running in a batch mode\n";
print $tee "+-- processing input file: \x1b[33m$opts{'b'}\x1b[0m\n";
}
if ($opts{'B'}) { print $tee "!-- you cannot use -b and -B simultaneously\n"; exit 4; }
batch_mode( $opts{'b'}, 'file' );
exit;
}
if ($opts{'B'}) {
if ($opts{'b'}) { print $tee "!-- you cannot use -b and -B simultaneously\n"; exit 4; }
batch_mode( $opts{'B'}, 'inline' );
exit;
}
# -- iRule dump mode
if ($opts{'D'} && $opts{'D'} ne "") {
my $_f = 0;
my $rules = query2object( $URL . 'ltm/rule');
foreach my $r ( @{ $rules->{'items'} }) {
next if ($r->{'name'} =~ /^_sys_/);
if ($r->{'name'} eq $opts{'D'}) {
print $tee ". dumping iRule: $r->{'name'}, partition: $r->{'partition'}\n";
if (-e "$wDir/$opts{'D'}.tcl") {
printf $tee "\x1b[33m** Warning:\x1b[0m the iRule with that name already found in your current directory!, old: %s, dumped: %s\n", sha1_hex(get_file_content("$wDir/$opts{'D'}.tcl")), sha1_hex( $r->{'apiAnonymous'} );
}
open my $fh, ">", "$wDir/$r->{'name'}.tcl.$tmp_stmp" or terminate_with_error($tee, 'file create', "Error creating iRule file");
print $fh $r->{'apiAnonymous'};
close($fh);
$_f = 1;
last;
}
}
unless ($_f) {
print $tee "! iRule not found: $opts{'D'}\n";
}
exit;
}
# single query mode
if ($opts{'q'}) {
unless ($opts{'Q'}) { print $tee "received query: $opts{'q'}\n"; }
my $p = $opts{'q'};
if ($p and $p ne '-') {
my $curl = $URL;
if ($popts->get('bigiq') ne '') {
$curl = $URL_BARE;
}
if ($opts{'J'} or ($popts->get('format') eq 'json')) {
print $tee query2json( $curl . $p );
} else {
print $tee Dumper( query2object( $curl . $p ));
}
}
exit;
}
#------------------------------------------------
# cmd mode
if ($opts{'x'}) {
my $data = runGenericCommand($opts{'x'});
if ($popts->get("respOnly") ne "") {
if (defined $data->{'commandResult'}) {
print $tee $data->{'commandResult'};
} else {
print $tee "-- command failed. \n";
}
} else {
print Dumper( $data );
}
exit;
}
#-----------------------------------------------
# Report mode
if ($opts{'R'}) {
if ($opts{'i'}){
&update_platform_properties;
&print_platform_properties;
}
print $tee "+ running report: $opts{'R'} \n";
my $tms = strftime("%a %d %b %H:%M:%S %Y", localtime);
printf $tee "+ timestamp: %s\n", $tms;
switch ($opts{'R'}) {
case 'RULE' {
&report_irules($popts->get('base'), $popts->get('diff'));
}
case 'ISTATS' {
&report_istats_generic;
}
default {
&run_custom_report($opts{'R'});
}
}
exit;
}
#-----------------------------------------------
# create commands
if ($opts{'c'} or $opts{'C'}) {
my $_t = 'rule';
my $floc = $ifns;
if (substr($ifns,0,2) eq './') {
substr($floc,0,1) = $rundir;
}
if (scalar( grep {! /\//} $ifns)) {
$floc = $rundir . '/' . $ifns;
}
if ($popts->get('ctype') ne "") {
$_t = $popts->get('ctype');
}
if ($opts{'c'}) {
print $tee "+ creating resource of type: $_t: $opts{'c'} from: $floc\n";
createResource($_t, $opts{'c'}, 'Common', $floc, '', undef);
} else {
print $tee "+ updating resource of type: $_t: $opts{'C'} from: $floc\n";
updateResource($_t, $opts{'C'}, 'Common', $floc, undef);
}
exit;
}
#-----------------------------------------------
if ($opts{'k'}) {
print $tee "+ analysing iRules and their alloactions ...\n";
checkRules( 1 );
exit;
}
#-----------------------------------------------
if ($opts{'K'}) {
print $tee "+ analysing Listeners and their alloactions ...\n";
&checkVirtuals;
exit;
}
#-----------------------------------------------
if ($opts{'s'}) {
print $tee "+ saving configuration ...\n";
&saveRunConfig;
exit;
}
#-----------------------------------------------
if ($opts{'S'}) {
if (defined $props{'failover cluster'}) {
print $tee "+ synchronizing configuration in the cluster: $props{'failover cluster'}...\n";
syncCluster( $props{'failover cluster'} );
}
exit;
}
#-----------------------------------------------
# save iRules and iCall scripts into an archive
#
if ( $opts{'A'} ) {
if ($wDir ne '') { printf $tee "++ using workdir: $wDir\n"; }
my $d = "${host_name}_archive";
if ($Label ne '') {
$d = "${Label}_archive_${host_name}_${tmp_stmp}";
}
print "++ creating databook archive: $d\n";
mkdir $d;
mkdir "$d/iRules";
my $rules = query2object( $URL . 'ltm/rule');
if ($debug_rules) { print Dumper($rules); }
foreach my $r ( @{ $rules->{'items'} }) {
next if ($r->{'name'} =~ /^_sys_/);
print $tee "dumping iRule: $r->{'name'}, partition: $r->{'partition'}\n";
unless (-e "$d/iRules/$r->{'partition'}"){
mkdir "$d/iRules/$r->{'partition'}";
}
open my $fh, ">", "$d/iRules/$r->{'partition'}/$r->{'name'}.tcl" or terminate_with_error($tee, 'irule create', "cannot save iRule file on local disk");
print $fh $r->{'apiAnonymous'};
close($fh);
}
mkdir "$d/Scripts";
my $scr = query2object( $URL . 'cli/script' );
foreach my $r ( @{ $scr->{'items'} } ) {
print $tee "dumping cli script: $r->{'name'}, partition: $r->{'partition'}\n";
unless (-e "$d/Scripts/$r->{'partition'}"){
mkdir "$d/Scripts/$r->{'partition'}";
}
open my $fh, ">", "$d/Scripts/$r->{'partition'}/$r->{'name'}.tcl" or terminate_with_error($tee, 'irule create', "cannot save iRule file on local disk");
print $fh $r->{'apiAnonymous'};
close($fh);
}
my $dg = query2object( $URL . 'ltm/data-group/internal');
my $js = JSON->new;
$js->pretty();
open my $fh, ">", "$d/data-groups-internal.json" or terminate_with_error($tee, 'data-group create', "cannot save data-group on a local disk");
foreach my $r ( @{ $dg->{'items'} }) {
print $fh $js->encode($r);
}
close($fh);
if ($^O eq "MSWin32") {
`tar -cf $wDir/$d.tar $d/`;
} else {
`tar -cf $wDir/$d.tar $d/`;
}
if ($remove_temp) {
print $tee "... trying to remove directory";
remove_tree("$d");
}
}
#print $tee "+++ job's done.";
exit;
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# Routines
sub generate_JSON_response
{
my ($def) = @_;
my $k = {
appName => '(C) 2021 f5-cfg-tool by Krystian Baniak',
version => $version,
};
foreach my $pr (sort keys %{ $def }) {
$k->{$pr} = $def->{$pr};
}
return $k
}
#
# rflags
sub set_rflag
{
my ($p, $v) = @_;
$rflags{$p} = $v;
}
# finds all static variable declarations from a stream and stores in hash reference
# params: ref to hash and buffer with iRule contents
sub find_static_vars
{
my ($ref, $data, $rname) = @_;
my $reg=0;
if (! defined($ref->{'errors'})) {
$ref->{'errors'} = qw();
}
foreach my $k ( split(/[\r\n]/, $data)) {
if ($reg) {
if ($k =~ /^when/) {
last;
}
chomp($k);
if ($k !~ /array set static/) {
if ($k =~ /set static::(.+?)\s+(.+?)$/) {
#print ". found a static variable: $1 $2\n";
if (defined $ref->{$1}) {
# this static var is redefined
#print "ERROR\n";
push @{ $ref->{'errors'} }, "collision in: $rname, var: $1 = $2, previosly found in: $ref->{$1}{'rule_name'} = $ref->{$1}{'value'}";
} else {
$ref->{$1} = { value => $2, rule_name => $rname };
}
}
}
}
$reg=1 if $k =~ /^when RULE_INIT/;
}
return $ref;
}
sub terminate_with_error {
my ($hf, $heading, $msg) = @_;
printf $hf "[\x1b[31m fatal \x1b[0m]: %s: \x1b[31m%s\x1b[0m\n", $heading, $msg;
exit 1;
}
#
# load config from a file with json encoding
sub load_dataset_from_file
{
my ($fname, $type) = @_;
open my $fh, "<", "$fname" or terminate_with_error($tee, 'file open', "Error opening resource file: $fname");
read $fh, my $buffer, -s $fh;
close $fh;
my $k = decode_json( $buffer );
if (defined($k->{$type})) {
return $k->{$type};
} else {
return undef;
}
}
# update platform structures
sub update_platform_properties {
%props = &get_propsy;
%srun = &get_running_software;
}
# print information about F5 device (or a cluster node)
sub print_platform_properties {
if ($opts{'J'}) {
my $js = JSON->new;
$js->pretty;
print $tee $js->encode(\%props);
} else {
print $tee "system properties: \n";
foreach my $k (sort keys %props){
printf $tee " %40s: %s\n", $k, $props{$k};
}
foreach my $k (sort keys %srun){
printf $tee " %40s: %s\n", $k, $srun{$k};
}
}
}
#
# update host structures
sub update_host {
my $_h = shift;
my $md = shift || 'full';
if ($_h =~ /^[a-zA-Z]/) {
$host_name = $_h;
if (defined( $nodes{ $_h } )){
$host = $nodes{ $_h };
} else {
print $tee "--- unknown host given!\n";
exit 100;
}
} elsif ($_h =~ /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/) {
$host_name = $host = $_h;
} else {
print $tee "fatal: cannot switch host\n";
exit 101
}
# update all globals
if ($cport != 443) {
$URL_BARE = "https://$host:$cport/";
$URL = "https://$host:$cport/mgmt/tm/";
$URLB = "https://$host:$cport/mgmt/shared/authn/login";
} else {
$URL_BARE = "https://$host/";
$URL = "https://$host/mgmt/tm/";
$URLB = "https://$host/mgmt/shared/authn/login";
}
unless ($opts{'Q'}) { print $tee "+ host $host_name mapped to: [ $host ]\n"; }
# perform auth cache scan if needed
if ($md eq 'full') {
my ($_u, $_p) = $cache->check_auth( $_h );
if (($_u ne 'x') and ($_u ne $usr)) { $usr = $_u; }
if (($_p ne 'x') and ($_p ne $pass)) { $pass = $_p; }
}
}
#
# generate timestamp
sub gen_tmstmp {
my $ss = strftime "%d%m%y-%H%M%S", localtime;
return $ss;
}
#
# get system properties
sub get_propsy {
my %p;
my $r = query2object( $URL . 'sys/hardware');
$p{'marketingName'} = $r->{'entries'}{'https://localhost/mgmt/tm/sys/hardware/platform'}{'nestedStats'}{'entries'}{'https://localhost/mgmt/tm/sys/hardware/platform/0'}{'nestedStats'}{'entries'}{'marketingName'}{'description'};
$p{'baseMac'} = $r->{'entries'}{'https://localhost/mgmt/tm/sys/hardware/platform'}{'nestedStats'}{'entries'}{'https://localhost/mgmt/tm/sys/hardware/platform/0'}{'nestedStats'}{'entries'}{'baseMac'}{'description'};
$p{'bigipChassisSerialNum'} = $r->{'entries'}{'https://localhost/mgmt/tm/sys/hardware/system-info'}{'nestedStats'}{'entries'}{'https://localhost/mgmt/tm/sys/hardware/system-info/0'}{'nestedStats'}{'entries'}{'bigipChassisSerialNum'}{'description'};
$p{'platform'} = $r->{'entries'}{'https://localhost/mgmt/tm/sys/hardware/system-info'}{'nestedStats'}{'entries'}{'https://localhost/mgmt/tm/sys/hardware/system-info/0'}{'nestedStats'}{'entries'}{'platform'}{'description'};
$r = query2object( $URL . 'cm/device-group');
foreach my $e ( @{ $r->{'items'} }) {
if ($e->{'type'} eq 'sync-failover') {
$p{'failover cluster'} = $e->{'name'};
}
}
$r = query2object( $URL . 'cm/device' );
$p{'fovState'} = 'unknown';
foreach my $e ( @{ $r->{'items'}} ) {
if ($e->{'managementIp'} eq $host) {
$p{'fovState'} = $e->{'failoverState'};
}
}
return %p;
}
#
# query 2 JSON
sub query2json
{
my $uri = shift;
my $mode = shift || 'no';
if ($mode eq 'yes') {
$uri =~ s/localhost/$host/;
}
if ($opts{'P'}){
if ($uri =~ /^https:\/\/([^\/:]+)\/(.+)$/) {
$uri = "https://$1:$opts{'P'}/$2";
print ". modif --> $uri\n";
}
}
my $r = GET $uri;
if ($opts{'T'}){
$r = GET $uri, 'X-F5-Auth-Token' => $tks;
} else {
$r->authorization_basic($usr, $pass);
}
my $res = $ua->request( $r );
my $cd = $res->code;
my $resp = $res->content;
my $js = JSON->new;
$js->pretty;
if (not $cd =~ /(200|202)/) {
if (($cd eq 404) && ($resp =~ /was not found/ || $resp =~ /Public URI path not registered/)){
return $js->encode( { error => 'not found' } );
} else {
if ($mode eq 'do_not_fail') {
return $js->encode( { error => '404' } );
} else {
print $tee "--- http get req error, code: $cd\n";
print $tee "--- response: $resp\n";
exit;
}
}
}
# we get final response
if ($popts->get('save_query_result') eq 'yes') {
if (! -e "$wDir/.creq-cache") {
print $tee "- creating json cache dir: $wDir/.creq-cache\n";
mkdir "$wDir/.creq-cache";
}
my $curi;
if ($uri =~ /^https:\/\/.+\/mgmt\/tm\/(.+)$/) {
$curi = $1;
$curi =~ s/\?.*//;
$curi = join('-', split('/', $curi));
my $lcfile = "$wDir/.creq-cache/$host-$curi-$tmp_stmp.json";
open my $fh, ">", $lcfile or terminate_with_error($tee, 'file create', "Error creating json file: $lcfile");
print $fh $res->content;
close $fh;
}
}
# return results
return $js->encode( $js->decode($res->content) );
}
#
# query 2 perl object
sub query2object
{
my $uri = shift;
my $mode = shift || 'no';
return decode_json( query2json( $uri, $mode ) );
}
sub tokenRequest
{
my $js = JSON->new;
my $z = {
username => $usr,
password => $pass,
loginProviderName => 'tmos',
};
$js->pretty();
my $r = POST $URLB, 'Content-Type' => 'application/json', 'Content' => $js->encode( $z );
$r->authorization_basic($usr, $pass);
my $res = $ua->request( $r );
my $cd = $res->code;
my $resp = $res->content;
if (not $cd =~ /(200|202)/) {
print $tee "--- http post req error, code: $cd\n";
print $tee "--- response: $resp\n";
exit;
}
return decode_json($res->content);
}
sub rawRequest
{
my ($method, $uri, $js) = @_;
my $r;
switch ($method) {
case 'POST' {
$r = POST $uri, 'Content-Type' => 'application/json', 'Content' => $js;
}
};
$r->authorization_basic($usr, $pass);
return $ua->request( $r );
}
sub postRequest
{
my $u = shift;
my $js = shift;
my $deb = shift || 'no';
my $r = POST $u, 'Content-Type' => 'application/json', 'Content' => $js;
$r->authorization_basic($usr, $pass);
my $res = $ua->request( $r );
my $cd = $res->code;
my $resp = $res->content;
if ($deb eq 'yes') {
print $tee "--- response: $resp\n";
}
if ($cd !~ /(200|202)/) {
unless ($rflags{'req_error_silent'}) {
print $tee "--- http post req error, code: $cd\n";
print $tee "--- response: $resp\n";
}
unless ($rflags{'req_not_fatal'}) { exit } else { return 'failed' }
}
return decode_json($res->content);
}
sub putRequest
{
my $u = shift;
my $js = shift;
my $r = PUT $u, 'Content-Type' => 'application/json', 'Content' => $js;
$r->authorization_basic($usr, $pass);
my $res = $ua->request( $r );
my $cd = $res->code;
my $resp = $res->content;
if ($cd !~ /(200|202)/) {
unless ($rflags{'req_error_silent'}) {
print $tee "--- http put req error, code: $cd\n";
print $tee "--- response: $resp\n";
}
unless ($rflags{'req_not_fatal'}) { exit } else { return 'failed' }
}
return decode_json($res->content);
}
sub patchRequest
{
my $u = shift;
my $js = shift;
my $r = HTTP::Request->new(PATCH => $u);
$r->header( 'Content-Type' => 'application/json' );
$r->content( $js );
$r->authorization_basic($usr, $pass);
my $res = $ua->request( $r );
my $cd = $res->code;
my $resp = $res->content;
if ($cd !~ /(200|202)/) {
unless ($rflags{'req_error_silent'}) {
print $tee "--- http patch req error, code: $cd\n";
print $tee "--- response: $resp\n";
}
unless ($rflags{'req_not_fatal'}) { exit } else { return 'failed' }
}
return decode_json($res->content);
}
sub deleteRequest
{
my $u = shift;
my $r = HTTP::Request->new(DELETE => $u);
$r->authorization_basic($usr, $pass);
my $res = $ua->request( $r );
my $cd = $res->code;
my $resp = $res->content;
if ($cd !~ /(200|202)/) {
if (($cd eq 404) && ($resp =~ /was not found/)){
return 2;
} else {
unless ($rflags{'req_error_silent'}) {
print $tee "--- http delete req error, code: $cd\n";
print $tee "--- response: $resp\n";
}
unless ($rflags{'req_not_fatal'}) { exit } else { return 'failed' }
}
}
return 0
}
#
# Converts Object to string
#
sub obj2str
{
my $obj = shift;
my $ret = "-";
if (not defined($obj) or $obj eq '') {
return $ret;
}
if (ref $obj eq 'ARRAY'){
$ret = join("\n", map { &obj2str($_) } @{ $obj });
} elsif (ref $obj eq 'HASH'){
my @a = qw( { );
foreach my $i (sort keys %{ $obj }){
# filter common not displayable properties
unless ($i =~ /^(selfLink|kind|fullPath|generation)$/) {
push @a, $i . ": " . &obj2str( $obj->{$i} );
}
}
push @a, '}';
$ret = join("\n", @a);
} else {
$ret = $obj;
$ret =~ tr/[\n\r]//;
}
return $ret;
}
#
# Convert array of Objects to a string
#
sub objectarray2string
{
my $a = shift;
my @ret;
foreach my $it ( @{ $a } ){
my @hh = qw( { );
foreach my $_t (sort keys %{ $it }) {
unless ($_t =~ /^(selfLink|kind|fullPath|generation)$/) {
push @hh, $_t . ': ' . $it->{ $_t };
}
}
push @hh, '}';
push @ret, join( "\n", @hh);
}
return join( "\n", @ret );
}
#
# follow references and expand them by converting into objects
#
sub checkReference
{
my $r = shift;
my $ar = [];
if ($db_cr) { print " debug: checkReference\n"; }
foreach my $e ( @{ $$r->{'items'} }){
my $z = {};
foreach my $p (keys %{ $e } ) {
if ($p =~ /^(.+)Reference$/){
my $ct = ref $e->{$p};
# print "checkReference: $ct: $p\n";
#
# since version 12.0 additional references are included in ARRAY for given property such as iRule, vlan, profile
#
if ($ct eq 'HASH') {
my $qe = query2object( $e->{$p}{'link'}, 'yes');
#$z->{$p} = objectarray2string( $qe->{'items'} );
$z->{$p} = $qe->{'items'};
}
} else {
$z->{$p} = $e->{$p};
}
}
push @{ $ar }, $z;
}
$$r->{'items'} = $ar;
}
#
# same as above but for flat type of collections
#
sub checkReferenceFlat
{
my $r = shift;
my $z = {};
if ($db_cr) { print " debug: checkReferenceFlat\n"; }
foreach my $p (keys %{ $$r } ){
if ($p =~ /^(.+)Reference$/){
my $ct = ref $$r->{$p};
#print " cRF: $p : $ct";
if ($ct eq 'HASH') {
my $qe = query2object( $$r->{$p}{'link'}, 'yes');
$z->{$p} = objectarray2string( $qe->{'items'} );
}
} else {
$z->{$p} = $$r->{$p};
}
}
$$r = $z;
}
sub dumpObject2Array {
my $obj = shift;
my $hea = shift || 0;
my @a = qw( name );
if ( ref $obj eq 'HASH' ){
foreach my $e (sort keys %{ $obj }) {
unless ($e =~ /^(selfLink|kind|name|fullPath|generation)$/) {
push @a, $e;
}
}
if ($hea) {
return @a;
} else {
return map { if ($_ eq 'name'){ $obj->{'name'} } else { obj2str( $obj->{$_} ) } } @a;
}
}
return @a;
}
#
# analyze virtual servers
#
sub checkVirtuals {
my $vs = query2object( $URL . 'ltm/virtual' );
printf $tee "\n %40s | %9s | %14s | %9s | %-40s\n",'name','partition','folder','type','vlan';
printf $tee "%s\n", '-' x 110;
foreach my $r ( @{ $vs->{'items'} } ) {
my $v = $r->{'vlans'};
if ( ref $v eq 'ARRAY' ){
$v = join ', ', @{ $v };
} else {
$v = "-empty-";
}
my $subp = '';
if (defined($r->{'subPath'})) {
$subp = $r->{'subPath'};
}
printf $tee " %40s | %9s | %14s | %9s | %-40s\n", $r->{'name'}, $r->{'partition'}, $subp, $r->{'ipProtocol'}, $v;
}
printf $tee "%s\n", '-' x 110;