-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnokia_ipsla.pl
1587 lines (1411 loc) · 55.1 KB
/
nokia_ipsla.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
use lib "/opt/nimsoft/perllib";
use lib "/opt/nimsoft/perl/lib";
# Set env variable NIM_ROOT
$ENV{'NIM_ROOT'} = '/opt/nimsoft';
# Use Perl core Package(s)
use strict;
use POSIX;
use threads;
use Thread::Queue;
use threads::shared;
use Data::Dumper;
use Time::Piece;
use List::Util qw( min max sum );
# Use Third-party Package(s)
use Nimbus::API;
use Nimbus::PDS;
use Nimbus::Session;
use Nimbus::CFG;
use DBI;
# Use internals Package(s)
use src::xmlreader;
use src::dbmanager;
use src::snmpmanager;
use src::utils;
# Declare Script CONSTANT(S) and Global(s)
use constant {
PROBE_NAME => "nokia_ipsla",
CFG_FILE => "nokia_ipsla.cfg",
VERSION => "1.8.2"
};
my $XMLDirectory: shared;
my ($ProvisioningInterval, $T_CheckInterval, $T_HealthInterval, $HealthThreads, $ProvisioningOnStart, $T_PollingInterval);
my ($RemoveDevicesInterval, $T_RemoveDevicesInterval, $DecommissionSQLTable);
my ($DB_ConnectionString, $DB_User, $DB_Password);
my $CRED_KEY = "secret_key";
my $PollingInterval: shared;
my $HealthInterval: shared;
my $BOOL_DeleteXML: shared = 1;
my $readXML_open: shared = 0;
my $updateDevicesAttr: shared = 0;
my $alarmThreadRunning: shared = 0;
my $removeDevicesRunning: shared = 0;
my $STR_RobotName: shared = "";
my $sess;
# Set array average!
sub mean {
return @_ ? sum(@_) / @_ : 0
}
# SNMP QoS Parser routines
# This table has been created to parse SNMP output by values
# For example some values are return like this "45 microseconds", so we only want to extract "45"
# Only two values are supported by the probe (Microseconds and Boolean).
my $SnmpQoSValueParser = {
Microseconds => sub {
my ($strValue) = @_;
my @matches = $strValue =~ /(.*)\smicroseconds/g;
return $matches[0];
},
State => sub {
my ($strValue) = @_;
return $strValue eq "success";
},
count => sub {
my ($strValue) = @_;
my @matches = $strValue =~ /^([0-9]+)/g;
return $matches[0];
}
};
# Hash table to retrieve metricId by the metric name
# This table has been created because of the difficulties to retrieve these with the $SnmpQoSSchema table
my $QOSMetrics = {
QOS_RESPONSEPATHTEST_TESTRUNRESULT => "9.1.2.1:0",
QOS_RESPONSEPATHTEST_MINIMUMRTT => "9.1.2.1:1",
QOS_RESPONSEPATHTEST_AVERAGERTT => "9.1.2.1:3",
QOS_RESPONSEPATHTEST_MAXIMUMRTT => "9.1.2.1:2",
QOS_RESPONSEPATHTEST_MINIMUMTT => "9.1.2.1:4",
QOS_RESPONSEPATHTEST_AVERAGETT => "9.1.2.1:10",
QOS_RESPONSEPATHTEST_MAXIMUMTT => "9.1.2.1:5",
QOS_RESPONSEPATHTEST_JITTERIN => "9.1.2.1:9",
QOS_RESPONSEPATHTEST_JITTEROUT => "9.1.2.1:8",
QOS_RESPONSEPATHTEST_RTJITTER => "9.1.2.1:12",
QOS_RESPONSEPATHTEST_MINIMUMTTIN => "9.1.2.1:6",
QOS_RESPONSEPATHTEST_AVERAGETTIN => "9.1.2.1:11",
QOS_RESPONSEPATHTEST_MAXIMUMTTIN => "9.1.2.1:7",
QOS_RESPONSEPATHTEST_PROBEFAILURES => "9.1.2.1:13",
QOS_RESPONSEPATHTEST_SENTPROBES => "9.1.2.1:14"
};
# Complete QoS Schema to publish for the probe!
# These are published in Nimsoft by the processProbeConfiguration method
my $SnmpQoSSchema = {
tmnxOamPingResultsTestRunResult => {
name => "QOS_RESPONSEPATHTEST_TESTRUNRESULT",
unit => "State",
short => "",
group => "QOS_NETWORK",
description => "Test RUN Result",
flags => 1,
ci_type => "9.1.2.1",
metric_name => "9.1.2.1:0"
},
tmnxOamPingResultsMinRtt => {
name => "QOS_RESPONSEPATHTEST_MINIMUMRTT",
unit => "Microseconds",
short => "us",
group => "QOS_NETWORK",
description => "Minimum Round Trip Time",
flags => 0,
ci_type => "9.1.2.1",
metric_name => "9.1.2.1:1"
},
tmnxOamPingResultsAverageRtt => {
name => "QOS_RESPONSEPATHTEST_AVERAGERTT",
unit => "Microseconds",
short => "us",
group => "QOS_NETWORK",
description => "Average Round Trip Time",
flags => 0,
ci_type => "9.1.2.1",
metric_name => "9.1.2.1:3"
},
tmnxOamPingResultsMaxRtt => {
name => "QOS_RESPONSEPATHTEST_MAXIMUMRTT",
unit => "Microseconds",
short => "us",
group => "QOS_NETWORK",
description => "Maximum Round Trip Time",
flags => 0,
ci_type => "9.1.2.1",
metric_name => "9.1.2.1:2"
},
tmnxOamPingResultsMinTt => {
name => "QOS_RESPONSEPATHTEST_MINIMUMTT",
unit => "Microseconds",
short => "us",
group => "QOS_NETWORK",
description => "Minimum Trip Time",
flags => 0,
ci_type => "9.1.2.1",
metric_name => "9.1.2.1:4"
},
tmnxOamPingResultsAverageTt => {
name => "QOS_RESPONSEPATHTEST_AVERAGETT",
unit => "Microseconds",
short => "us",
group => "QOS_NETWORK",
description => "Average Trip Time",
flags => 0,
ci_type => "9.1.2.1",
metric_name => "9.1.2.1:10"
},
tmnxOamPingResultsMaxTt => {
name => "QOS_RESPONSEPATHTEST_MAXIMUMTT",
unit => "Microseconds",
short => "us",
group => "QOS_NETWORK",
description => "Maximum Trip Time",
flags => 0,
ci_type => "9.1.2.1",
metric_name => "9.1.2.1:5"
},
tmnxOamPingResultsInJitter => {
name => "QOS_RESPONSEPATHTEST_JITTERIN",
unit => "Microseconds",
short => "us",
group => "QOS_NETWORK",
description => "IN Jitter",
flags => 0,
ci_type => "9.1.2.1",
metric_name => "9.1.2.1:9"
},
tmnxOamPingResultsOutJitter => {
name => "QOS_RESPONSEPATHTEST_JITTEROUT",
unit => "Microseconds",
short => "us",
group => "QOS_NETWORK",
description => "OUT Jitter",
flags => 0,
ci_type => "9.1.2.1",
metric_name => "9.1.2.1:8"
},
tmnxOamPingResultsRtJitter => {
name => "QOS_RESPONSEPATHTEST_RTJITTER",
unit => "Microseconds",
short => "us",
group => "QOS_NETWORK",
description => "Round Trip Jitter",
flags => 0,
ci_type => "9.1.2.1",
metric_name => "9.1.2.1:12"
},
tmnxOamPingResultsMinInTt => {
name => "QOS_RESPONSEPATHTEST_MINIMUMTTIN",
unit => "Microseconds",
short => "us",
group => "QOS_NETWORK",
description => "Minimum Trip Time IN",
flags => 0,
ci_type => "9.1.2.1",
metric_name => "9.1.2.1:6"
},
tmnxOamPingResultsAverageInTt => {
name => "QOS_RESPONSEPATHTEST_AVERAGETTIN",
unit => "Microseconds",
short => "us",
group => "QOS_NETWORK",
description => "Average Trip Time IN",
flags => 0,
ci_type => "9.1.2.1",
metric_name => "9.1.2.1:11"
},
tmnxOamPingResultsMaxInTt => {
name => "QOS_RESPONSEPATHTEST_MAXIMUMTTIN",
unit => "Microseconds",
short => "us",
group => "QOS_NETWORK",
description => "Maximum Trip Time IN",
flags => 0,
ci_type => "9.1.2.1",
metric_name => "9.1.2.1:7"
},
tmnxOamPingResultsProbeFailures => {
name => "QOS_RESPONSEPATHTEST_PROBEFAILURES",
unit => "count",
short => "#",
group => "QOS_NETWORK",
description => "Probe failures",
flags => 0,
ci_type => "9.1.2.1",
metric_name => "9.1.2.1:13"
},
tmnxOamPingResultsSentProbes => {
name => "QOS_RESPONSEPATHTEST_SENTPROBES",
unit => "count",
short => "#",
group => "QOS_NETWORK",
description => "Probes sent",
flags => 0,
ci_type => "9.1.2.1",
metric_name => "9.1.2.1:14"
}
};
# Shared Queues. These are used among multiple threads to publish/exchange data
my $AlarmQueue = Thread::Queue->new();
my $deviceHandlerQueue = Thread::Queue->new();
my $QoSHandlers = Thread::Queue->new();
# Execute the routine scriptDieHandler if the script die for any reasons
$SIG{__DIE__} = \&scriptDieHandler;
# @subroutine scriptDieHandler
# @desc Routine triggered when the script have to die
sub scriptDieHandler {
my ($err) = @_;
print STDERR "$err\n";
nimLog(0, "$err");
exit(1);
}
# @subroutine getMySQLConnector
# @desc Connect the Perl DBI Driver to the MySQL database. It will return undef if the connection failed !
sub getMySQLConnector {
nimLog(3, "Initialize MySQL connection: (CS: $DB_ConnectionString)");
my $dbh = DBI->connect($DB_ConnectionString, $DB_User, $DB_Password);
if(!defined($dbh)) {
print STDERR "Failed to connect to the MySQL Database...\n";
nimLog(1, "Failed to connect to the MySQL Database...");
}
else {
nimLog(3, "Successfully connected to MySQL database!");
print STDOUT "Successfully connected to MySQL database!\n";
}
return $dbh;
}
# @subroutine openLocalDB
# @desc Open LocalDB (SQLite) properly. Return undef if the connector fail.
sub openLocalDB {
my ($importDef) = @_;
my $SQLDB;
eval {
$SQLDB = src::dbmanager->new('./db/nokia_ipsla.db', $CRED_KEY);
if ($importDef == 1) {
$SQLDB->import_def('./db/database_definition.sql');
}
};
if($@) {
print STDERR $@;
nimLog(1, $@);
return undef;
}
return $SQLDB;
}
# @subroutine processProbeConfiguration
# @desc Read/Parse and apply default probe Configuration !
sub processProbeConfiguration {
# Launch method timer
my $processProbeConfigurationTime = nimTimerCreate();
nimTimerStart($processProbeConfigurationTime);
# Open Configuration File handler
my $CFG = Nimbus::CFG->new(CFG_FILE);
# Setup section
my $STR_Login = $CFG->{"setup"}->{"nim_login"} || "administrator";
my $STR_Password = $CFG->{"setup"}->{"nim_password"};
my $INT_LogLevel = defined($CFG->{"setup"}->{"loglevel"}) ? $CFG->{"setup"}->{"loglevel"} : 3;
my $INT_LogSize = $CFG->{"setup"}->{"logsize"} || 1024;
my $STR_LogFile = $CFG->{"setup"}->{"logfile"} || "nokia_ipsla.log";
scriptDieHandler("Configuration <provisioning> section is not mandatory!") if not defined($CFG->{"provisioning"});
# Database Section
my $DBName = $CFG->{"database"}->{"database"} || "ca_uim";
my $DBHost = $CFG->{"database"}->{"host"};
my $DBPort = $CFG->{"database"}->{"port"} || 3306;
$DB_ConnectionString = "DBI:mysql:database=$DBName;host=$DBHost;port=$DBPort";
$DB_User = $CFG->{"database"}->{"user"};
$DB_Password = $CFG->{"database"}->{"password"};
# Encrypt/Decrypt CFG Credential keys!
if($DB_Password =~ /^==/) {
my $TPassword = substr($DB_Password, 2);
if (src::utils::isBase64($TPassword)) {
$DB_Password = nimDecryptString($CRED_KEY, $TPassword);
}
else {
print STDOUT "Failed to detect base64 password for config->database->password \n";
exit(0);
}
}
else {
my $CFGNapi = cfgOpen(CFG_FILE, 0);
my $cValue = "==".nimEncryptString($CRED_KEY, $DB_Password);
cfgKeyWrite($CFGNapi, "/database/", "password", $cValue);
cfgSync($CFGNapi);
cfgClose($CFGNapi);
}
# provisioning Section
$XMLDirectory = $CFG->{"provisioning"}->{"xml_dir"} || "./xml";
$RemoveDevicesInterval = $CFG->{"provisioning"}->{"decommission_interval"} || 900;
$DecommissionSQLTable = "nokia_ipsla_decommission";
$ProvisioningInterval = $CFG->{"provisioning"}->{"provisioning_interval"} || 3600;
$PollingInterval = $CFG->{"provisioning"}->{"polling_snmp_interval"} || 300;
$HealthInterval = $CFG->{"provisioning"}->{"polling_health_interval"} || 1800;
$HealthThreads = $CFG->{"provisioning"}->{"polling_health_threads"} || 3;
$ProvisioningOnStart = defined($CFG->{"provisioning"}->{"provisioning_on_start"}) ? $CFG->{"provisioning"}->{"provisioning_on_start"} : 1;
$BOOL_DeleteXML = defined($CFG->{"provisioning"}->{"delete_xml_files"}) ? $CFG->{"provisioning"}->{"delete_xml_files"} : 0;
my @filters = ();
if(defined($CFG->{"provisioning"}->{"xml_device_filters"})) {
foreach my $index (keys $CFG->{"provisioning"}->{"xml_device_filters"}) {
my $hash = $CFG->{"provisioning"}->{"xml_device_filters"}->{$index};
foreach my $filterKey (keys $hash) {
$hash->{$filterKey} = qr/$hash->{$filterKey}/;
}
push(@filters, $hash);
}
}
$src::xmlreader::filters = \@filters;
# Login to Nimsoft if required
nimLogin("$STR_Login","$STR_Password") if defined($STR_Login) && defined($STR_Password);
# Configure Nimsoft Log!
nimLogSet($STR_LogFile, '', $INT_LogLevel, NIM_LOGF_NOTRUNC);
nimLogTruncateSize($INT_LogSize * 1024);
nimLog(3, "Probe Nokia_ipsla started!");
# Minmum security threshold for PollingInterval
if($PollingInterval < 60 || $PollingInterval > 1800) {
print STDOUT "SNMP Polling interval minimum and threshold is <60/1800> seconds!\n";
nimLog(2, "SNMP Polling interval minimum and threshold is <60/1800> seconds!");
$PollingInterval = 60;
}
# Minimum security threshold for CheckInterval
if($ProvisioningInterval < 10) {
print STDOUT "Provisioning interval threshold is 10 seconds!\n";
nimLog(2, "Provisioning interval threshold is 10 seconds!");
$ProvisioningInterval = 10;
}
# Nimsoft timer (init /or/ re-init).
$T_CheckInterval = nimTimerCreate();
$T_HealthInterval = nimTimerCreate();
$T_PollingInterval = nimTimerCreate();
$T_RemoveDevicesInterval = nimTimerCreate();
nimTimerStart($T_CheckInterval);
nimTimerStart($T_HealthInterval);
nimTimerStart($T_PollingInterval);
nimTimerStart($T_RemoveDevicesInterval);
# Send Nimsoft QoS definitions
nimQoSSendDefinition(
"QOS_REACHABILITY",
"QOS_NETWORK",
"Nokia Network connectivity response",
"State",
"",
NIMQOS_DEF_BOOLEAN
);
foreach my $QoSName (keys %{ $SnmpQoSSchema }) {
my $QoS = $SnmpQoSSchema->{$QoSName};
print STDOUT "Send QoSDefinition $QoS->{name}\n";
nimLog(3, "Send QoSDefinition $QoS->{name}");
nimQoSSendDefinition(
$QoS->{name},
$QoS->{group},
$QoS->{description},
$QoS->{unit},
$QoS->{short},
$QoS->{flags}
);
}
# Stdout the time taken to read the configuration!
nimTimerStop($processProbeConfigurationTime);
my $executionTimeMs = nimTimerDiff($processProbeConfigurationTime);
nimTimerFree($processProbeConfigurationTime);
print STDOUT "processProbeConfiguration() has been executed in ${executionTimeMs}ms\n";
nimLog(3, "processProbeConfiguration() has been executed in ${executionTimeMs}ms");
# Start provisioning if $ProvisioningOnStart is equal to 1
if($ProvisioningOnStart == 1) {
print STDOUT "Provisioning on start activated: Triggering updateInterval() method!\n";
nimLog(3, "Provisioning on start activated: Triggering updateInterval() method!");
updateInterval();
}
}
# @subroutine alarmsThread
# @desc Thread responsible for creating and publishing new alarm in the Product
sub alarmsThread {
$alarmThreadRunning = 1;
print STDOUT "Run a new thread for alarming!\n";
nimLog(3, "Run a new thread for alarming!");
# Open and Read CFG File
my $CFG = Nimbus::CFG->new(CFG_FILE);
my $Alarm = defined($CFG->{"messages"}) ? $CFG->{"messages"} : {};
# Request local (agent/robot) informations
# Retrieve robot informations!
my ($RC, $getInfoPDS) = nimNamedRequest("controller", "get_info", Nimbus::PDS->new);
scriptDieHandler(
"Failed to establish a communication with the local controller probe!"
) if $RC != NIME_OK;
my $localAgent = Nimbus::PDS->new($getInfoPDS)->asHash();
my $defaultOrigin = defined($Alarm->{default_origin}) ? $Alarm->{default_origin} : $localAgent->{origin};
# Wait for new alarm to be publish into the AlarmQueue
while ( defined ( my $hAlarm = $AlarmQueue->dequeue() ) ) {
# Verify Alarm Type
next if not defined($hAlarm->{type});
next if not defined($Alarm->{$hAlarm->{type}});
my $type = $Alarm->{$hAlarm->{type}};
my $severity = defined($hAlarm->{severity}) ? $hAlarm->{severity} : $type->{severity};
print "[ALARM] Receiving new alarm of type: $hAlarm->{type} and severity: $severity\n";
nimLog(3, "[ALARM] Receiving new alarm of type: $hAlarm->{type} and severity: $severity");
# Parse and Define alarms variables by merging payload into suppkey & message fields
my $hVariablesRef = defined($hAlarm->{payload}) ? $hAlarm->{payload} : {};
$hVariablesRef->{host} = $hAlarm->{device};
my $suppkey = src::utils::parseAlarmVariable($type->{supp_key}, $hVariablesRef);
my $message = src::utils::parseAlarmVariable($severity == 0 ? $type->{clear_message} : $type->{message}, $hVariablesRef);
undef $hVariablesRef;
if(defined($hAlarm->{hCI})) {
my $hCI = $hAlarm->{hCI};
my ($RC, $nimid) = ciAlarm(
$hCI,
$hAlarm->{metric},
$severity,
$message,
"",
Nimbus::PDS->new()->data,
$type->{subsys},
$suppkey,
$hAlarm->{source}
);
print STDOUT "[ALARM] (id: $nimid) new CI alarm, severity: $type->{severity}, source: $hAlarm->{source}\n";
nimLog(3, "[ALARM] (id: $nimid) new CI alarm, severity: $type->{severity}, source: $hAlarm->{source}");
if($RC != NIME_OK) {
my $errorTxt = nimError2Txt($RC);
print STDERR "[ALARM] (id: $nimid) Failed to generate alarm, RC => $RC :: $errorTxt\n";
nimLog(2, "[ALARM] (id: $nimid) Failed to generate alarm, RC => $RC :: $errorTxt");
}
ciClose($hCI);
}
else {
# Generate Alarm PDS
my ($PDSAlarm, $nimid) = src::utils::generateAlarm("alarm", {
robot => $hAlarm->{device},
source => $hAlarm->{source},
met_id => $hAlarm->{met_id} || "",
dev_id => $hAlarm->{dev_id},
hubName => $localAgent->{hubname},
domain => $localAgent->{domain},
usertag1 => $localAgent->{os_user1},
usertag2 => $localAgent->{os_user2},
severity => $type->{severity},
subsys => $type->{subsys},
origin => $defaultOrigin,
probe => PROBE_NAME,
message => $message,
supp_key => $suppkey,
suppression => $suppkey
});
print STDOUT "Generate new (raw) alarm with id $nimid\n";
nimLog(3, "Generate new (raw) alarm with id $nimid");
# Launch alarm!
my ($RC) = nimRequest($localAgent->{robotname}, 48001, "post_raw", $PDSAlarm->data);
if($RC != NIME_OK) {
my $errorTxt = nimError2Txt($RC);
print STDERR "Failed to generate alarm, RC => $RC :: $errorTxt\n";
nimLog(2, "Failed to generate alarm, RC => $RC :: $errorTxt");
}
}
}
$alarmThreadRunning = 0;
}
# @subroutine startAlarmThread
# @desc Manage and start Alarm thread (work for restarting it too!).
sub startAlarmThread {
# Create independant thread!
threads->create(sub {
# Stop alarm thread if already active!
if($alarmThreadRunning == 1) {
$AlarmQueue->enqueue(undef);
unless($alarmThreadRunning == 0) {
select(undef, undef, undef, 0.25); # wait 250ms
}
}
eval {
threads->create(\&alarmsThread)->join;
};
if($@) {
$alarmThreadRunning = 0;
nimLog(0, $@);
}
})->detach;
}
# @subroutine processXMLFiles
# @desc Process XML Files to get Devices and SNMP Profiles
sub processXMLFiles {
$readXML_open = 1;
print STDOUT "Entering processXMLFiles() !\n";
nimLog(3, "Entering processXMLFiles() !");
# Create method timer
my $processXMLFilesTimer = nimTimerCreate();
nimTimerStart($processXMLFilesTimer);
# Open local DB
my $SQLDB = openLocalDB(1);
if (!defined($SQLDB)) {
$readXML_open = 0;
return;
}
# Connect to MySQL (optionaly)
my $devicesUUID = {};
eval {
my $dbh = getMySQLConnector();
if(defined($dbh)) {
my $sth = $dbh->prepare("SELECT device FROM $DecommissionSQLTable");
$sth->execute();
while(my $row = $sth->fetchrow_hashref) {
$devicesUUID->{$row->{device}} = 0;
}
}
};
if ($@) {
print STDERR $@;
nimLog(1, $@);
}
print STDOUT "Start XML File(s) processing !\n";
nimLog(3, "Start XML File(s) processing !");
print STDOUT "XML Directory (from CFG) = $XMLDirectory\n";
nimLog(3, "XML Directory (from CFG) = $XMLDirectory");
opendir(DIR, $XMLDirectory) or die("Error: Failed to open the root directory /xml\n");
my @files = sort { (stat $a)[10] <=> (stat $b)[10] } readdir(DIR); # Sort by date (older to recent)
# Proceed each XML files
my $processed_files = 0;
foreach my $file (@files) {
next unless ($file =~ m/^.*\.xml$/); # Skip non-xml files
print STDOUT "XML File detected => $file\n";
nimLog(3, "XML File detected => $file\n");
eval {
my $XML = src::xmlreader->new("$XMLDirectory/$file")->parse($devicesUUID);
$SQLDB->upsertXMLObject($XML);
$XML->deleteFile() if $BOOL_DeleteXML == 1;
$processed_files++;
};
nimLog(2, $@) if $@;
print STDERR $@ if $@;
}
nimTimerStop($processXMLFilesTimer);
my $execution_time = nimTimerDiff($processXMLFilesTimer);
nimTimerFree($processXMLFilesTimer);
if ($processed_files > 0) {
print STDOUT "Successfully processed $processed_files XML file(s) in ${execution_time}ms !\n";
nimLog(3, "Successfully processed $processed_files XML file(s) in ${execution_time}ms !");
}
else {
print STDOUT "No local XML files detected!\n";
nimLog(3, "No local XML files detected!");
}
# Run hydrateDevicesAttributes only if at least one XML file has been processed!
if($processed_files > 0) {
eval {
hydrateDevicesAttributes() if $updateDevicesAttr == 0;
};
if($@) {
print STDERR $@;
nimLog(1, $@);
$updateDevicesAttr = 0;
}
}
$readXML_open = 0;
}
# @subroutine hydrateDevicesAttributes
# @desc Update device attributes (Make SNMP request to get system informations).
sub hydrateDevicesAttributes {
# Return if one hydratation is already running
return if $updateDevicesAttr == 1;
$updateDevicesAttr = 1;
my $hydrateDevicesAttributesTimer = nimTimerCreate();
nimTimerStart($hydrateDevicesAttributesTimer);
print STDOUT "Starting hydratation of Devices attributes\n";
nimLog(3, "Starting hydratation of Devices attributes");
# Open local DB
my $SQLDB = openLocalDB(0);
if (!defined($SQLDB)) {
$updateDevicesAttr = 0;
return;
}
# Get all pollable devices from SQLite!
my $threadQueue = Thread::Queue->new();
my $pollableResponseQueue = Thread::Queue->new();
$threadQueue->enqueue($_) for @{ $SQLDB->pollable_devices() };
$threadQueue->enqueue($_) for @{ $SQLDB->unpollable_devices() };
# If threadQueue is empty, then exit method!
my $QPending = $threadQueue->pending();
if($QPending == 0) {
print STDOUT "No devices to be polled (health_check), Exiting hydrateDevicesAttributes() method!\n";
nimLog(2, "No devices to be polled (health_check), Exiting hydrateDevicesAttributes() method!");
$updateDevicesAttr = 0;
return;
}
# Re-allocate right number of threads!
my $t_healthThreadsCount = $HealthThreads;
if($QPending < $t_healthThreadsCount) {
$t_healthThreadsCount = $threadQueue->pending();
print STDOUT "Adjusting (in running context) health_threads count to $t_healthThreadsCount\n";
nimLog(2, "Adjusting (in running context) health_threads count to $t_healthThreadsCount");
}
my $pollingThread = sub {
my $tid = threads->tid();
print STDOUT "[$tid] Health Polling thread started\n";
nimLog(3, "[$tid] Health Polling thread started");
# Open local DB
my $SQLDB = openLocalDB(0);
return if not defined $SQLDB;
# Create new SNMP Manager!
my $snmpManager = src::snmpmanager->new();
while ( defined ( my $Device = $threadQueue->dequeue() ) ) {
my $result;
eval {
$result = $snmpManager->snmpSysInformations($Device);
};
if($@) {
nimLog(1, "[$tid][$Device->{name}] $@");
print STDERR "[$tid][$Device->{name}] $@\n";
next;
}
my $isPollable = ref($result) eq "HASH" ? 1 : 0;
my $isPollableStr = $isPollable ? "true" : "false";
print STDOUT "[$tid][$Device->{name}] is pollable: $isPollableStr\n";
nimLog(2, "[$tid][$Device->{name}] is pollable: $isPollableStr");
# Generate Reachability QoS
my $hCI = ciOpenRemoteDevice("9.1.2", "Reachability", $Device->{ip});
my $QOS = nimQoSCreate("QOS_REACHABILITY", $Device->{name}, $HealthInterval, -1);
ciBindQoS($hCI, $QOS, "9.1.2:1");
nimQoSSendValue($QOS, "reachability", $isPollable);
ciUnBindQoS($QOS);
nimQoSFree($QOS);
ciClose($hCI);
# Update SQLite attributes and trigger an Alarm (clear or not).
$SQLDB->checkAttributes($result, $Device->{dev_uuid}) if $isPollable == 1;
my $hCIAlarm = ciOpenRemoteDevice("9.1.2", $Device->{name}, $Device->{ip});
$AlarmQueue->enqueue({
type => $isPollable ? "device_responding" : "device_not_responding",
device => $STR_RobotName,
source => $Device->{name},
dev_id => $Device->{dev_id},
hCI => $hCIAlarm,
metric => "9.1.2:0",
payload => {
device => $STR_RobotName,
source => $Device->{name}
}
});
# Exlude NON-NOKIA IPSLA SNMP Devices
if ($result->{"sysObjectID"} !~ /^tmnx/) {
print STDOUT "[$tid][$Device->{name}] Not detected as a NOKIA-IPSLA Device, set is_pollable to 0\n";
nimLog(2, "[$tid][$Device->{name}] Not detected as a NOKIA-IPSLA Device, set is_pollable to 0");
$isPollable = 0;
}
$pollableResponseQueue->enqueue({
uuid => $Device->{dev_uuid},
pollable => $isPollable
});
}
print STDOUT "[$tid] Health Polling thread finished\n";
nimLog(3, "[$tid] Health Polling thread finished");
};
# Wait for polling threads
my @thr = map {
threads->create(\&$pollingThread);
} 1..$t_healthThreadsCount;
for(my $i = 0; $i < $t_healthThreadsCount; $i++) {
$threadQueue->enqueue(undef);
}
$_->join() for @thr;
$pollableResponseQueue->enqueue(undef);
# Update pollable values!
my $SQLDB = openLocalDB(0);
if (!defined($SQLDB)) {
$updateDevicesAttr = 0;
return;
}
$SQLDB->{DB}->begin_work;
while ( defined ( my $Device = $pollableResponseQueue->dequeue() ) ) {
$SQLDB->updatePollable($Device->{uuid}, $Device->{pollable});
}
$SQLDB->{DB}->commit;
nimTimerStop($hydrateDevicesAttributesTimer);
my $execution_time = nimTimerDiff($hydrateDevicesAttributesTimer);
nimTimerFree($hydrateDevicesAttributesTimer);
print STDOUT "Successfully hydrate devices attributes in ${execution_time}ms !\n";
nimLog(3, "Successfully hydrate devices attributes in ${execution_time}ms !");
$updateDevicesAttr = 0;
}
# @subroutine removeDevices
# @desc Remove Devices from probe!
sub removeDevices {
$removeDevicesRunning = 1;
print STDOUT "Remove Devices method triggered!\n";
nimLog(3, "Remove Devices method triggered!");
# Connect to MySQL!
my $dbh = getMySQLConnector();
if(!defined($dbh)) {
nimLog(1, "Exiting removeDevices()... MySQL database KO");
$removeDevicesRunning = 0;
return;
}
my $sth = $dbh->prepare("SELECT device FROM $DecommissionSQLTable");
$sth->execute();
my $devicesNames = {};
while(my $row = $sth->fetchrow_hashref) {
$devicesNames->{$row->{device}} = 0;
}
undef $sth;
undef $dbh;
# Stop if we have no devicesUUID!
if(scalar keys %{ $devicesNames } == 0) {
nimLog(3, "No devices to remove has been found in the MySQL database");
return;
}
my @deviceToRemove = ();
# Open local DB
my $SQLDB = openLocalDB(0);
if (!defined($SQLDB)) {
$removeDevicesRunning = 0;
return;
}
my $sth = $SQLDB->{DB}->prepare("SELECT name, uuid, snmp_uuid FROM nokia_ipsla_device WHERE is_active=1");
$sth->execute();
while(my $row = $sth->fetchrow_hashref) {
push(@deviceToRemove, {
snmp_uuid => $row->{snmp_uuid},
uuid => $row->{uuid},
}) if defined($devicesNames->{$row->{name}});
}
undef $sth;
undef $devicesNames;
# Remove Device from SQLite table!
$SQLDB->{DB}->begin_work;
foreach(@deviceToRemove) {
nimLog(3, "Remove (Decommission) of the Device with UUID => $_->{uuid}");
$SQLDB->{DB}->prepare('UPDATE nokia_ipsla_device SET is_active=? WHERE uuid=?')->execute(0, $_->{uuid});
$SQLDB->{DB}->prepare('DELETE FROM nokia_ipsla_device_attr WHERE dev_uuid=?')->execute($_->{uuid});
}
$SQLDB->{DB}->commit;
$removeDevicesRunning = 0;
}
# @subroutine updateInterval
# @desc Launch a new provisioning interval
sub updateInterval {
# Return if updateInterval is already launched!
if($readXML_open == 1) {
return;
}
print STDOUT "Triggering provisioning interval...\n";
nimLog(3, "Triggering provisioning interval...");
# Create separated thread to handle provisioning mechanism
threads->create(sub {
eval {
threads->create(\&processXMLFiles)->join;
};
if($@) {
$readXML_open = 0;
nimLog(0, $@);
}
})->detach;
# Reset interval
$T_CheckInterval = nimTimerCreate();
nimTimerStart($T_CheckInterval);
}
# @subroutine healthPollingInterval
# @desc Health polling interval (will set device.is_pollable to 1 or 0)
sub healthPollingInterval {
# Return if updateDevicesAttr is already launched!
if($updateDevicesAttr == 1) {
return;
}
print STDOUT "Triggering health polling interval\n";
nimLog(3, "Triggering health polling interval");
# Create separated thread to handle provisioning mechanism
threads->create(sub {
eval {
threads->create(\&hydrateDevicesAttributes)->join;
};
if($@) {
$updateDevicesAttr = 0;
nimLog(0, $@);
}
})->detach;
# Reset interval
$T_HealthInterval = nimTimerCreate();
nimTimerStart($T_HealthInterval);
}
# @subroutine removeDevicesInterval
# @desc Remove devices interval
sub removeDevicesInterval {
# Return if updateDevicesAttr is already launched!
if($removeDevicesRunning == 1) {
return;
}
$removeDevicesRunning = 1;
print STDOUT "Triggering remove devices interval\n";
nimLog(3, "Triggering remove devices interval");
# Create separated thread to handle provisioning mechanism
threads->create(sub {
eval {
threads->create(\&removeDevices)->join;
};
if($@) {
$removeDevicesRunning = 0;
nimLog(0, $@);
}
})->detach;
# Reset interval
$T_RemoveDevicesInterval = nimTimerCreate();
nimTimerStart($T_RemoveDevicesInterval);
}
# @subroutine snmpPollingInterval
# @desc Snmp polling interval
sub snmpPollingInterval {
print STDOUT "Triggering snmp polling interval\n";
nimLog(3, "Triggering snmp polling interval");
# Create separated thread to handle provisioning mechanism
threads->create(sub {
eval {
threads->create(\&polling)->join;
};
if($@) {
print STDERR $@."\n";
nimLog(0, $@);
}
})->detach;
# Reset interval
$T_PollingInterval = nimTimerCreate();
nimTimerStart($T_PollingInterval);
}
# @subroutine startMetricHistoryThread
# @desc Thread to handle all Metric QoS history
sub startMetricHistoryThread {
print STDOUT "Triggering QoS history metric thread\n";
nimLog(3, "Triggering QoS history metric thread");
# Create separated thread to handle provisioning mechanism
threads->create(sub {
eval {
threads->create(\&SNMPMetricsHistory)->join;
};
if($@) {
print STDERR $@."\n";
nimLog(0, $@);
}
})->detach;
}
# @subroutine SNMPMetricsHistory
# @desc Handle alerting on the SNMP metrics history
sub SNMPMetricsHistory {
# Parse alerting profiles
my $Profiles = {};
{
my $CFG = Nimbus::CFG->new(CFG_FILE);
my @sections = $CFG->getSections($CFG->{alerting});
foreach my $secId (@sections) {
my $sec = $CFG->{alerting}->{$secId};
my $keys = {};
my @tmnxKeys = $CFG->getSections($sec);
foreach my $tmnxKey (@tmnxKeys) {
my @ret = ();
my @messages = $CFG->getSections($sec->{$tmnxKey});
foreach(@messages) {
my $threshold = $sec->{$tmnxKey}->{$_}->{threshold};
my $active = defined($sec->{$tmnxKey}->{$_}->{active}) ? $sec->{$tmnxKey}->{$_}->{active} : "yes";
push(@ret, {
threshold => $threshold,
message => $_
}) if $active eq "yes";
}
$keys->{$tmnxKey} = \@ret;
}
$Profiles->{$secId} = {
name => qr/$sec->{saa_name}/,
keys => $keys
};
}