-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsupervisor.c
5763 lines (5114 loc) · 242 KB
/
supervisor.c
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
/**
* \file supervisor.c
* \brief Supervisor implementation.
* \author Marek Svepes <[email protected]>
* \author Tomas Cejka <[email protected]>
* \date 2013
* \date 2014
*/
/*
* Copyright (C) 2013-2014 CESNET
*
* LICENSE TERMS
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name of the Company nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* ALTERNATIVELY, provided that this notice is retained in full, this
* product may be distributed under the terms of the GNU General Public
* License (GPL) version 2 or later, in which case the provisions
* of the GPL apply INSTEAD OF those given above.
*
* This software is provided ``as is'', and any express or implied
* warranties, including, but not limited to, the implied warranties of
* merchantability and fitness for a particular purpose are disclaimed.
* In no event shall the company or contributors be liable for any
* direct, indirect, incidental, special, exemplary, or consequential
* damages (including, but not limited to, procurement of substitute
* goods or services; loss of use, data, or profits; or business
* interruption) however caused and on any theory of liability, whether
* in contract, strict liability, or tort (including negligence or
* otherwise) arising in any way out of the use of this software, even
* if advised of the possibility of such damage.
*
*/
#define _GNU_SOURCE
#ifdef nemea_plugin
#include "./ncnemea/ncnemea.h"
#endif
#include "supervisor.h"
#include "supervisor_api.h"
#include "internal.h"
#include <arpa/inet.h>
#include <netinet/in.h>
#include <getopt.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <ifaddrs.h>
#include <libtrap/trap.h>
#define TRAP_PARAM "-i" ///< Interface parameter for libtrap
#define DEFAULT_MODULE_RESTARTS_NUM 3 ///< Default number of module restarts per minute
#define MAX_MODULE_RESTARTS_NUM 30 ///< Maximum number of module restarts per minute (loaded from configuration file)
#define MAX_SERVICE_IFC_CONN_FAILS 3
#define DEFAULT_DAEMON_SERVER_SOCKET DEFAULT_PATH_TO_SOCKET ///< Daemon server socket
#define DEFAULT_NETCONF_SERVER_SOCKET "/tmp/netconf_supervisor.sock" ///< Netconf server socket
#define DEFAULT_PATH_TO_CONFIGSS DEFAULT_PATH_TO_CONFIGS
#define BACKUP_FILE_PREFIX SUP_TMP_DIR
#define BACKUP_FILE_SUFIX "_sup_backup_file.xml"
#define GENER_CONFIG_FILE_NAME "supervisor_config_gener.xml"
#define MODULES_LOGS_DIR_NAME "modules_logs"
#define RET_ERROR -1
#define MAX_NUMBER_SUP_CLIENTS 5
#define NUM_SERVICE_IFC_PERIODS 30
/* Values for non-blocking sending and receiving service data. */
#define SERVICE_WAIT_BEFORE_TIMEOUT 25000 ///< Timeout after EAGAIN or EWOULDBLOCK errno returned from service send() and recv().
#define SERVICE_WAIT_MAX_TRY 8 ///< A maximal count of repeated timeouts per each service recv() and send() function call.
#define SERVICE_GET_COM 10
#define SERVICE_SET_COM 11
#define SERVICE_OK_REPLY 12
/*
* Time in micro seconds the service thread spends sleeping after each period.
* (the period means all tasks service thread has to complete - restart and stop modules according to their enable flag,
* receive their statistics etc.)
*/
#define SERVICE_THREAD_SLEEP_IN_MICSEC 1500000
/*
* Time in micro seconds between sending SIGINT and SIGKILL to running modules.
* Service thread sends SIGINT to stop running module, after time defined by this constant it checks modules status
* and if the module is still running service thread sends SIGKILL to stop it.
*/
#define SERVICE_WAIT_FOR_MODULES_TO_FINISH 500000
#define TIME_BUFFER_SIZE 26
/*******GLOBAL VARIABLES*******/
/* Loaded modules variables */
running_module_t *running_modules = NULL; ///< Information about running modules
unsigned int running_modules_array_size = 0; ///< Current size of running_modules array.
unsigned int loaded_modules_cnt = 0; ///< Current number of loaded modules.
/* Profiles variables */
modules_profile_t *first_profile_ptr = NULL;
modules_profile_t *actual_profile_ptr = NULL;
unsigned int loaded_profile_cnt = 0;
/* paths variables */
char *templ_config_file = NULL;
char *gener_config_file = NULL;
char *config_files_path = NULL;
char *socket_path = NULL;
char *logs_path = NULL;
/* Sup flags */
int supervisor_initialized = FALSE;
int service_thread_initialized = FALSE;
int daemon_mode_initialized = FALSE;
int daemon_flag = FALSE; // --daemon
int netconf_flag = FALSE;
int service_thread_continue = FALSE; ///< condition variable of main loop of the service_thread
int service_stop_all_modules = FALSE;
unsigned long int last_total_cpu = 0; // Variable with total cpu usage of whole operating system
pthread_mutex_t running_modules_lock; ///< mutex for locking counters
int module_restarts_num_config = DEFAULT_MODULE_RESTARTS_NUM;
pthread_t service_thread_id; ///< Service thread identificator.
pthread_t netconf_server_thread_id;
time_t sup_init_time = 0;
server_internals_t *server_internals = NULL;
/**************************************/
int get_digits_num(const int number)
{
int cnt = 1, num = number / 10;
while (num != 0) {
cnt++;
num = num / 10;
}
return cnt;
}
// Checks if str ends with suffix.
int strsuffixis(const char *str, const char *suffix)
{
return strcmp(str + strlen(str) - strlen(suffix), suffix) == 0;
}
// Returns absolute path of the file / directory passed in file_name parameter
char *get_absolute_file_path(char *file_name)
{
if (file_name == NULL) {
return NULL;
}
static char absolute_file_path[PATH_MAX];
memset(absolute_file_path, 0, PATH_MAX * sizeof(char));
if (realpath(file_name, absolute_file_path) == NULL) {
return NULL;
}
return absolute_file_path;
}
// Creates backup file path using configuration file name
char *create_backup_file_path()
{
uint x = 0;
char *absolute_config_file_path = NULL;
uint32_t letter_sum = 0;
char *buffer = NULL;
// Get absolute path of the configuration file
absolute_config_file_path = get_absolute_file_path(templ_config_file);
if (absolute_config_file_path == NULL) {
return NULL;
}
// Add up all letters of the absolute path multiplied by their index
for (x = 0; x < strlen(absolute_config_file_path); x++) {
letter_sum += absolute_config_file_path[x] * (x+1);
}
// Create path of the backup file: "/tmp/sup_tmp_dir/" + letter_sum + "_sup_backup.xml"
if (asprintf(&buffer, "%s/%d%s", BACKUP_FILE_PREFIX, letter_sum, BACKUP_FILE_SUFIX) < 0) {
return NULL;
}
return buffer;
}
void create_shutdown_info(char **backup_file_path)
{
FILE *info_file_fd = NULL;
char *info_file_name = NULL;
char timebuf[TIME_BUFFER_SIZE];
if (asprintf(&info_file_name, "%s_info", *backup_file_path) < 0) {
return;
}
info_file_fd = fopen(info_file_name, "w");
if (info_file_fd == NULL) {
NULLP_TEST_AND_FREE(info_file_name)
return;
}
fprintf(info_file_fd, "Supervisor shutdown info:\n==========================\n\n");
fprintf(info_file_fd, "Supervisor package version: %s\n", sup_package_version);
fprintf(info_file_fd, "Supervisor git version: %s\n", sup_git_version);
fprintf(info_file_fd, "Started: %s", ctime_r(&sup_init_time, timebuf));
fprintf(info_file_fd, "Actual date and time: %s\n", get_formatted_time());
fprintf(info_file_fd, "Number of modules in configuration: %d\n", loaded_modules_cnt);
fprintf(info_file_fd, "Number of running modules: %d\n", service_check_modules_status());
fprintf(info_file_fd, "Logs directory: %s\n", logs_path);
fprintf(info_file_fd, "Configuration file: %s\n\n", templ_config_file);
fprintf(info_file_fd, "Run supervisor with this configuration file to load generated backup file. It will connect to running modules.\n");
NULLP_TEST_AND_FREE(info_file_name)
fclose(info_file_fd);
}
void print_xmlDoc_to_stream(xmlDocPtr doc_ptr, FILE *stream)
{
if (doc_ptr != NULL && stream != NULL) {
xmlChar *formated_xml_output = NULL;
int size = 0;
xmlDocDumpFormatMemory(doc_ptr, &formated_xml_output, &size, 1);
if (formated_xml_output == NULL) {
return;
} else {
fprintf(stream, "%s\n", formated_xml_output);
fflush(stream);
xmlFree(formated_xml_output);
}
}
}
char *get_formatted_time()
{
time_t rawtime;
static char formatted_time_buffer[DEFAULT_SIZE_OF_BUFFER];
char timebuf[TIME_BUFFER_SIZE];
memset(formatted_time_buffer,0,DEFAULT_SIZE_OF_BUFFER);
time(&rawtime);
sprintf(formatted_time_buffer, "%s", ctime_r(&rawtime, timebuf));
formatted_time_buffer[strlen(formatted_time_buffer) - 1] = 0;
return formatted_time_buffer;
}
char **parse_module_params(const uint32_t module_idx, uint32_t *params_num)
{
uint32_t params_arr_size = 5, params_cnt = 0;
char **params = (char **) calloc(params_arr_size, sizeof(char *));
char *buffer = NULL;
uint32_t x = 0, y = 0, act_param_len = 0;
int params_len = strlen(running_modules[module_idx].module_params);
buffer = (char *) calloc(params_len + 1, sizeof(char));
if (buffer == NULL) {
VERBOSE(N_STDOUT, "%s [ERROR] Could not allocate memory for \"%s\" params before module execution.\n", get_formatted_time(), running_modules[module_idx].module_name);
goto err_cleanup;
}
for (x = 0; x < params_len; x++) {
switch (running_modules[module_idx].module_params[x]) {
/* parameter in apostrophes */
case '\'':
{
if (act_param_len > 0) { // check whether the ''' character is not in the middle of the word
VERBOSE(MODULE_EVENT, "%s [ERROR] Bad format of \"%s\" params element - used \'\'\' in the middle of the word.\n", get_formatted_time(), running_modules[module_idx].module_name);
goto err_cleanup;
}
for (y = (x + 1); y < params_len; y++) {
if (running_modules[module_idx].module_params[y] == '\'') { // parameter in apostrophes MATCH
if (act_param_len == 0) { // check for empty apostrophes
VERBOSE(MODULE_EVENT, "%s [ERROR] Bad format of \"%s\" params element - used empty apostrophes.\n", get_formatted_time(), running_modules[module_idx].module_name);
goto err_cleanup;
}
x = y;
goto add_param;
} else { // add character to parameter in apostrophes
buffer[act_param_len] = running_modules[module_idx].module_params[y];
act_param_len++;
}
}
// the terminating ''' was not found
VERBOSE(MODULE_EVENT, "%s [ERROR] Bad format of \"%s\" params element - used single \'\'\'.\n", get_formatted_time(), running_modules[module_idx].module_name);
goto err_cleanup;
break;
}
/* parameter in quotes */
case '\"':
{
if (act_param_len > 0) { // check whether the '"' character is not in the middle of the word
VERBOSE(MODULE_EVENT, "%s [ERROR] Bad format of \"%s\" params element - used \'\"\' in the middle of the word.\n", get_formatted_time(), running_modules[module_idx].module_name);
goto err_cleanup;
}
for (y = (x + 1); y < params_len; y++) {
if (running_modules[module_idx].module_params[y] == '\"') { // parameter in quotes MATCH
if (act_param_len == 0) { // check for empty quotes
VERBOSE(MODULE_EVENT, "%s [ERROR] Bad format of \"%s\" params element - used empty quotes.\n", get_formatted_time(), running_modules[module_idx].module_name);
goto err_cleanup;
}
x = y;
goto add_param;
} else if (running_modules[module_idx].module_params[y] != '\'') { // add character to parameter in quotes
buffer[act_param_len] = running_modules[module_idx].module_params[y];
act_param_len++;
} else {
VERBOSE(MODULE_EVENT, "%s [ERROR] Found apostrophe in \"%s\" params element in quotes.\n", get_formatted_time(), running_modules[module_idx].module_name);
goto err_cleanup;
}
}
// the terminating '"' was not found
VERBOSE(MODULE_EVENT, "%s [ERROR] Bad format of \"%s\" params element - used single \'\"\'.\n", get_formatted_time(), running_modules[module_idx].module_name);
goto err_cleanup;
break;
}
/* parameter delimiter */
case ' ':
{
if (act_param_len == 0) {
continue; // skip white-spaces between parameters
}
add_param:
if (params_cnt == params_arr_size) { // if needed, resize the array of parsed parameters
params_arr_size += params_arr_size;
params = (char **) realloc(params, sizeof(char *) * params_arr_size);
memset(params + (params_arr_size / 2), 0, ((params_arr_size / 2) * sizeof(char *)));
}
params[params_cnt] = strdup(buffer);
params_cnt++;
memset(buffer, 0, (params_len + 1) * sizeof(char));
act_param_len = 0;
break;
}
/* adding one character to parameter out of quotes and apostrophes */
default:
{
buffer[act_param_len] = running_modules[module_idx].module_params[x];
act_param_len++;
if (x == (params_len - 1)) { // if last character of the params element was added, add current module parameter to the params array
goto add_param;
}
break;
}
} // end of switch
}
*params_num = params_cnt;
NULLP_TEST_AND_FREE(buffer);
return params;
err_cleanup:
for (x = 0; x < params_cnt; x++) {
NULLP_TEST_AND_FREE(params[x]);
}
NULLP_TEST_AND_FREE(params)
NULLP_TEST_AND_FREE(buffer);
*params_num = 0;
return NULL;
}
char **prep_module_args(const uint32_t module_idx)
{
uint32_t x = 0, y = 0, act_dir = 0, ptr = 0;
uint32_t ifc_spec_size = DEFAULT_SIZE_OF_BUFFER;
char *ifc_spec = (char *) calloc(ifc_spec_size, sizeof(char));
memset(ifc_spec, 0, ifc_spec_size);
char *addr = NULL;
char *port = NULL;
char **module_params = NULL;
uint32_t module_params_num = 0;
char **bin_args = NULL;
uint32_t bin_args_num = 2; // initially 2 - at least the name of the future process and terminating NULL pointer
uint32_t bin_args_pos = 0;
/* if the module has trap interfaces, one argument for "-i" and one for interfaces specifier */
if (running_modules[module_idx].config_ifces_cnt > 0) {
bin_args_num += 2;
}
/* if the module has non-empty params, try to parse them */
if (running_modules[module_idx].module_params != NULL) {
module_params = parse_module_params(module_idx, &module_params_num);
if (module_params != NULL && module_params_num > 0) {
bin_args_num += module_params_num; // after successful params parsing, increment the number of binary arguments
}
}
/* pointers allocation */
bin_args = (char **) calloc(bin_args_num, sizeof(char *));
bin_args[0] = strdup(running_modules[module_idx].module_name); // first argument is a name of the future process
bin_args[bin_args_num - 1] = NULL; // last pointer is NULL because of exec function
bin_args_pos = 1;
/* copy already allocated module params strings returned by parse_module_params function */
if (module_params != NULL && module_params_num > 0) {
for (x = 0; x < module_params_num; x++) {
bin_args[bin_args_pos] = module_params[x];
bin_args_pos++;
}
NULLP_TEST_AND_FREE(module_params)
}
/* prepare trap interfaces specifier (e.g. "t:1234,u:sock,s:service_sock") */
if (running_modules[module_idx].config_ifces_cnt > 0) {
for (y = 0; y < 2; y++) {
// To get first input ifces and than output ifces
switch (y) {
case 0:
act_dir = IN_MODULE_IFC_DIRECTION;
break;
case 1:
act_dir = OUT_MODULE_IFC_DIRECTION;
break;
}
for (x = 0; x < running_modules[module_idx].config_ifces_cnt; x++) {
if (running_modules[module_idx].config_ifces[x].int_ifc_direction == act_dir) {
// Get interface type
if (running_modules[module_idx].config_ifces[x].int_ifc_type == TCP_MODULE_IFC_TYPE) {
strncpy(ifc_spec + ptr, "t:", 3);
ptr+=2;
} else if (running_modules[module_idx].config_ifces[x].int_ifc_type == UNIXSOCKET_MODULE_IFC_TYPE) {
strncpy(ifc_spec + ptr, "u:", 3);
ptr+=2;
} else if (running_modules[module_idx].config_ifces[x].int_ifc_type == FILE_MODULE_IFC_TYPE) {
strncpy(ifc_spec + ptr, "f:", 3);
ptr+=2;
} else if (running_modules[module_idx].config_ifces[x].int_ifc_type == BLACKHOLE_MODULE_IFC_TYPE) {
strncpy(ifc_spec + ptr, "b:", 3);
ptr+=2;
} else if (running_modules[module_idx].config_ifces[x].int_ifc_type == TLS_MODULE_IFC_TYPE) {
strncpy(ifc_spec + ptr, "T:", 3);
ptr+=2;
} else {
VERBOSE(MODULE_EVENT, "%s [WARNING] Wrong ifc_type in module %d (interface number %d).\n", get_formatted_time(), module_idx, x);
NULLP_TEST_AND_FREE(ifc_spec)
for (uint32_t i = 0; i < bin_args_pos; i++) {
free(bin_args[i]);
}
free(bin_args);
return NULL;
}
// Get interface params
if (running_modules[module_idx].config_ifces[x].ifc_params != NULL) {
if ((strlen(ifc_spec) + strlen(running_modules[module_idx].config_ifces[x].ifc_params) + 1) >= (3 * ifc_spec_size) / 5) {
ifc_spec_size += strlen(running_modules[module_idx].config_ifces[x].ifc_params) + (ifc_spec_size / 2);
ifc_spec = (char *) realloc(ifc_spec, ifc_spec_size * sizeof(char));
memset(ifc_spec + ptr, 0, ifc_spec_size - ptr);
}
// Compatible with previous format of libtrap -i parameter ("address,port" for one input interface)
port = NULL;
port = get_param_by_delimiter(running_modules[module_idx].config_ifces[x].ifc_params, &addr, ',');
if (port == NULL) {
sprintf(ifc_spec + ptr,"%s,",running_modules[module_idx].config_ifces[x].ifc_params);
} else {
sprintf(ifc_spec + ptr,"%s:%s,", addr, port);
}
ptr += strlen(running_modules[module_idx].config_ifces[x].ifc_params) + 1;
NULLP_TEST_AND_FREE(addr)
}
}
}
}
// Remove last comma
memset(ifc_spec + ptr - 1, 0, 1 * sizeof(char));
bin_args[bin_args_pos] = strdup(TRAP_PARAM); // add "-i" argument
bin_args_pos++;
bin_args[bin_args_pos] = strdup(ifc_spec); // add trap interfaces specifier argument
bin_args_pos++;
}
fprintf(stdout,"%s [INFO] Supervisor - executed command: %s", get_formatted_time(), running_modules[module_idx].module_path);
fprintf(stderr,"%s [INFO] Supervisor - executed command: %s", get_formatted_time(), running_modules[module_idx].module_path);
for (x = 1; x < bin_args_num; x++) {
fprintf(stdout," %s",bin_args[x]);
fprintf(stderr," %s",bin_args[x]);
}
fprintf(stdout,"\n");
fprintf(stderr,"\n");
NULLP_TEST_AND_FREE(ifc_spec)
return bin_args;
}
int get_number_from_input_choosing_option()
{
int x = 0;
int option = 0;
char *input_p = NULL;
int input_len = 0;
input_p = get_input_from_stream(input_fd);
if (input_p == NULL) {
goto error_label;
} else {
input_len = strlen(input_p);
// Input must be min 1 and max 3 characters long
if (input_len > 3 || input_len < 1) {
goto error_label;
}
// Check if all characters are digits
for (x = 0; x < input_len; x++) {
if (input_p[x] < '0' || input_p[x] > '9') {
goto error_label;
}
}
if (sscanf(input_p, "%d", &option) < 1 || option < 0) {
goto error_label;
}
}
NULLP_TEST_AND_FREE(input_p)
return option;
error_label:
NULLP_TEST_AND_FREE(input_p)
return RET_ERROR;
}
/* Returns count of numbers in input (separated by commas) or -1 */
int parse_numbers_user_selection(int **array)
{
uint8_t is_num = FALSE;
uint8_t is_interval = FALSE;
uint8_t duplicated = FALSE;
int cur_num = 0;
int interval_beg = 0;
int x = 0, y = 0, z = 0;
int module_nums_cnt = 0;
int *module_nums = NULL;
char *input_p = NULL;
int input_len = 0;
uint32_t module_nums_size = 10;
module_nums = (int *) calloc(module_nums_size, sizeof(int));
input_p = get_input_from_stream(input_fd);
if (input_p == NULL) {
goto error_label;
} else if (strlen(input_p) == 0) {
VERBOSE(N_STDOUT, FORMAT_WARNING "[WARNING] Wrong input - empty string.\n" FORMAT_RESET);
goto error_label;
} else {
input_len = strlen(input_p);
for (x = 0; x < input_len; x++) {
if (input_p[x] <= '9' && input_p[x] >= '0') {
is_num = TRUE;
cur_num *= 10;
cur_num += (input_p[x] - '0');
if ((input_len - 1) > x) {
continue;
}
} else if (input_p[x] == ',') {
if (x == (strlen(input_p) -1)) {
VERBOSE(N_STDOUT, FORMAT_WARNING "[WARNING] Wrong input - comma at the end.\n" FORMAT_RESET);
goto error_label;
break;
}
if (is_num == FALSE) {
VERBOSE(N_STDOUT, FORMAT_WARNING "[WARNING] Wrong input - comma without a number before it.\n" FORMAT_RESET);
goto error_label;
break;
}
} else if (input_p[x] == '-') {
if (is_num == TRUE && is_interval == FALSE) {
is_num = FALSE;
is_interval = TRUE;
interval_beg = cur_num;
cur_num = 0;
continue;
} else {
VERBOSE(N_STDOUT, FORMAT_WARNING "[WARNING] Wrong input - dash with no number before it.\n" FORMAT_RESET);
goto error_label;
break;
}
} else {
VERBOSE(N_STDOUT, FORMAT_WARNING "[WARNING] Wrong input - acceptable characters are digits, comma and dash.\n" FORMAT_RESET);
goto error_label;
break;
}
// Add current number(s)
if (is_interval == FALSE) {
interval_beg = cur_num;
} else if (interval_beg > cur_num) {
y = interval_beg;
interval_beg = cur_num;
cur_num = y;
}
for (y = interval_beg; y <= cur_num; y++) {
duplicated = FALSE;
// Check whether the current number is already in the array
for (z = 0; z < module_nums_cnt; z++) {
if (y == module_nums[z]) {
duplicated = TRUE;
break;
}
}
if (duplicated == TRUE) {
continue;
} else {
if (module_nums_size == module_nums_cnt) {
// reallocate the array with numbers
module_nums_size += 20;
module_nums = (int *) realloc(module_nums, module_nums_size * sizeof(int));
}
module_nums[module_nums_cnt] = y;
module_nums_cnt++;
}
}
cur_num = 0;
is_num = FALSE;
is_interval = FALSE;
}
}
NULLP_TEST_AND_FREE(input_p)
*array = module_nums;
return module_nums_cnt;
error_label:
NULLP_TEST_AND_FREE(module_nums)
NULLP_TEST_AND_FREE(input_p)
*array = NULL;
return RET_ERROR;
}
void init_module_variables(int module_number)
{
running_modules[module_number].module_running = TRUE;
// Initialize modules variables
running_modules[module_number].sent_sigint = FALSE;
running_modules[module_number].virtual_memory_size = 0;
running_modules[module_number].resident_set_size = 0;
running_modules[module_number].last_period_cpu_usage_kernel_mode = 0;
running_modules[module_number].last_period_cpu_usage_user_mode = 0;
running_modules[module_number].last_period_percent_cpu_usage_kernel_mode = 0;
running_modules[module_number].last_period_percent_cpu_usage_user_mode = 0;
running_modules[module_number].module_service_sd = -1;
running_modules[module_number].module_service_ifc_isconnected = FALSE;
running_modules[module_number].service_ifc_conn_timer = 0;
}
char *get_param_by_delimiter(const char *source, char **dest, const char delimiter)
{
char *param_end = NULL;
unsigned int param_size = 0;
if (source == NULL) {
return NULL;
}
param_end = strchr(source, delimiter);
if (param_end == NULL) {
/* no delimiter found, copy the whole source */
*dest = strdup(source);
return NULL;
}
param_size = param_end - source;
*dest = (char *) calloc(1, param_size + 1);
if (*dest == NULL) {
return (NULL);
}
strncpy(*dest, source, param_size);
return param_end + 1;
}
void print_statistics()
{
char timebuf[TIME_BUFFER_SIZE];
time_t t = 0;
time(&t);
char *stats_buffer = make_formated_statistics((uint8_t) 1);
if (stats_buffer == NULL) {
return;
}
VERBOSE(STATISTICS, "------> %s", ctime_r(&t, timebuf));
VERBOSE(STATISTICS, "%s", stats_buffer);
NULLP_TEST_AND_FREE(stats_buffer);
}
void print_statistics_legend()
{
VERBOSE(STATISTICS,"Legend for an interface statistics:\n"
"\tCNT_RM - counter of received messages on the input interface\n"
"\tCNT_RB - counter of received buffers on the input interface\n"
"\tCNT_SM - counter of sent messages on the output interface\n"
"\tCNT_SB - counter of sent buffers on the output interface\n"
"\tCNT_DM - counter of dropped messages on the output interface\n"
"\tCNT_AF - autoflush counter of the output interface\n"
"Statistics example:\n"
"\tmodule_name,interface_direction,interface_number,stats\n"
"\tmodule,in,number,CNT_RM,CNT_RB\n"
"\tmodule,out,number,CNT_SM,CNT_SB,CNT_DM,CNT_AF\n"
"--------------------------------------------------------\n");
}
char *make_json_modules_info(uint8_t info_mask)
{
uint x = 0, y = 0;
char ifc_type[2];
ifc_type[1] = 0;
char *result_data = NULL;
json_t *module_info = NULL;
json_t *module = NULL;
json_t *ifc_info = NULL;
json_t *in_ifc_arr = NULL;
json_t *out_ifc_arr = NULL;
json_t *modules_obj = NULL;
uint8_t print_details = FALSE;
// Decide which information should be included according to the info mask
if ((info_mask & (uint8_t) 1) == (uint8_t) 1) {
print_details = TRUE;
}
for (x = 0; x < loaded_modules_cnt; x++) {
if (print_details == FALSE && running_modules[x].module_status == FALSE) {
continue;
}
in_ifc_arr = json_array();
out_ifc_arr = json_array();
if (in_ifc_arr == NULL || out_ifc_arr == NULL) {
VERBOSE(SUP_LOG, "[ERROR] Could not create JSON arrays (probably not enough memory).\n");
goto clean_up;
}
// Array of input ifces
for (y = 0; y < running_modules[x].total_in_ifces_cnt; y++) {
ifc_type[0] = running_modules[x].in_ifces_data[y].ifc_type;
ifc_info = json_pack("{sssssisIsI}", "type", ifc_type,
"ID", running_modules[x].in_ifces_data[y].ifc_id,
"is-conn", running_modules[x].in_ifces_data[y].ifc_state,
"messages", running_modules[x].in_ifces_data[y].recv_msg_cnt,
"buffers", running_modules[x].in_ifces_data[y].recv_buffer_cnt);
if (ifc_info == NULL || json_array_append_new(in_ifc_arr, ifc_info) == -1) {
VERBOSE(SUP_LOG, "[ERROR] Could not append module input ifc info to JSON array (module \"%s\").\n", running_modules[x].module_name);
goto clean_up;
}
}
// Array of output ifces
for (y = 0; y < running_modules[x].total_out_ifces_cnt; y++) {
ifc_type[0] = running_modules[x].out_ifces_data[y].ifc_type;
ifc_info = json_pack("{sssssisIsIsIsI}", "type", ifc_type,
"ID", running_modules[x].out_ifces_data[y].ifc_id,
"cli-num", running_modules[x].out_ifces_data[y].num_clients,
"sent-msg", running_modules[x].out_ifces_data[y].sent_msg_cnt,
"drop-msg", running_modules[x].out_ifces_data[y].dropped_msg_cnt,
"buffers", running_modules[x].out_ifces_data[y].sent_buffer_cnt,
"autoflush", running_modules[x].out_ifces_data[y].autoflush_cnt);
if (ifc_info == NULL || json_array_append_new(out_ifc_arr, ifc_info) == -1) {
VERBOSE(SUP_LOG, "[ERROR] Could not append module output ifc info to JSON array (module \"%s\").\n", running_modules[x].module_name);
goto clean_up;
}
}
if (print_details == TRUE) {
module_info = json_pack("{sisssssssisisIsIsoso}",
"idx", x,
"params", (running_modules[x].module_params == NULL ? "none" : running_modules[x].module_params),
"path", running_modules[x].module_path,
"status", (running_modules[x].module_status == TRUE ? "running" : "stopped"),
"CPU-u", running_modules[x].last_period_percent_cpu_usage_user_mode,
"CPU-s", running_modules[x].last_period_percent_cpu_usage_kernel_mode,
"MEM-vms", running_modules[x].virtual_memory_size,
"MEM-rss", running_modules[x].resident_set_size * 1024, // Output RSS in bytes as well as VMS
"inputs", in_ifc_arr,
"outputs", out_ifc_arr);
} else {
module_info = json_pack("{sisisIsIsoso}",
"CPU-u", running_modules[x].last_period_percent_cpu_usage_user_mode,
"CPU-s", running_modules[x].last_period_percent_cpu_usage_kernel_mode,
"MEM-vms", running_modules[x].virtual_memory_size,
"MEM-rss", running_modules[x].resident_set_size * 1024, // Output RSS in bytes as well as VMS
"inputs", in_ifc_arr,
"outputs", out_ifc_arr);
}
if (module_info == NULL) {
VERBOSE(SUP_LOG, "[ERROR] Could not create JSON object of a module \"%s\".\n", running_modules[x].module_name);
goto clean_up;
}
module = json_pack("{so}", running_modules[x].module_name, module_info);
if (module == NULL) {
VERBOSE(SUP_LOG, "[ERROR] Could not create JSON object of a module \"%s\".\n", running_modules[x].module_name);
goto clean_up;
}
if (modules_obj == NULL) {
modules_obj = module;
} else {
if (json_object_update(modules_obj, module) == -1) {
VERBOSE(SUP_LOG, "[ERROR] Could not append module \"%s\" final JSON object.\n", running_modules[x].module_name);
goto clean_up;
}
json_decref(module);
}
}
result_data = json_dumps(modules_obj, 0);
if (modules_obj != NULL) {
json_decref(modules_obj);
}
return result_data;
clean_up:
if (modules_obj != NULL) {
json_decref(modules_obj);
}
return NULL;
}
char *make_formated_statistics(uint8_t stats_mask)
{
uint8_t print_ifc_stats = FALSE, print_cpu_stats = FALSE, print_memory_stats = FALSE;
unsigned int size_of_buffer = 5 * DEFAULT_SIZE_OF_BUFFER;
char *buffer = (char *) calloc(size_of_buffer, sizeof(char));
unsigned int x, y;
int ptr = 0;
// Decide which stats should be printed according to the stats mask
if ((stats_mask & (uint8_t) 1) == (uint8_t) 1) {
print_ifc_stats = TRUE;
}
if ((stats_mask & (uint8_t) 2) == (uint8_t) 2) {
print_cpu_stats = TRUE;
}
if ((stats_mask & (uint8_t) 4) == (uint8_t) 4) {
print_memory_stats = TRUE;
}
if (print_ifc_stats == TRUE) {
for (x = 0; x < loaded_modules_cnt; x++) {
if (running_modules[x].module_status == TRUE && running_modules[x].module_service_ifc_isconnected == TRUE) {
if (running_modules[x].in_ifces_data != NULL) {
for (y = 0; y < running_modules[x].total_in_ifces_cnt; y++) {
ptr += sprintf(buffer + ptr, "%s,in,%c,%s,%"PRIu64",%"PRIu64"\n", running_modules[x].module_name,
running_modules[x].in_ifces_data[y].ifc_type,
(running_modules[x].in_ifces_data[y].ifc_id != NULL ? running_modules[x].in_ifces_data[y].ifc_id : "none"),
running_modules[x].in_ifces_data[y].recv_msg_cnt,
running_modules[x].in_ifces_data[y].recv_buffer_cnt);
if (strlen(buffer) >= (3 * size_of_buffer) / 5) {
size_of_buffer += size_of_buffer / 2;
buffer = (char *) realloc (buffer, size_of_buffer * sizeof(char));
memset(buffer + ptr, 0, size_of_buffer - ptr);
}
}
}
if (running_modules[x].out_ifces_data != NULL) {
for (y = 0; y < running_modules[x].total_out_ifces_cnt; y++) {
ptr += sprintf(buffer + ptr, "%s,out,%c,%s,%"PRIu64",%"PRIu64",%"PRIu64",%"PRIu64"\n", running_modules[x].module_name,
running_modules[x].out_ifces_data[y].ifc_type,
(running_modules[x].out_ifces_data[y].ifc_id != NULL ? running_modules[x].out_ifces_data[y].ifc_id : "none"),
running_modules[x].out_ifces_data[y].sent_msg_cnt,
running_modules[x].out_ifces_data[y].dropped_msg_cnt,
running_modules[x].out_ifces_data[y].sent_buffer_cnt,
running_modules[x].out_ifces_data[y].autoflush_cnt);
if (strlen(buffer) >= (3 * size_of_buffer) / 5) {
size_of_buffer += size_of_buffer / 2;
buffer = (char *) realloc (buffer, size_of_buffer * sizeof(char));
memset(buffer + ptr, 0, size_of_buffer - ptr);
}
}
}
}
}
}
if (print_cpu_stats == TRUE) {
for (x=0; x<loaded_modules_cnt; x++) {
if (running_modules[x].module_status == TRUE) {
ptr += sprintf(buffer + ptr, "%s,cpu,%lu,%lu\n", running_modules[x].module_name,
running_modules[x].last_period_percent_cpu_usage_kernel_mode,
running_modules[x].last_period_percent_cpu_usage_user_mode);
if (strlen(buffer) >= (3*size_of_buffer)/5) {
size_of_buffer += size_of_buffer/2;
buffer = (char *) realloc (buffer, size_of_buffer * sizeof(char));
memset(buffer + ptr, 0, size_of_buffer - ptr);
}
}
}
}
if (print_memory_stats == TRUE) {
for (x=0; x<loaded_modules_cnt; x++) {
if (running_modules[x].module_status == TRUE) {
ptr += sprintf(buffer + ptr, "%s,mem,%lu\n", running_modules[x].module_name,
running_modules[x].virtual_memory_size / (1024*1024)); // to convert B to MB, divide by 1024*1024
if (strlen(buffer) >= (3*size_of_buffer)/5) {
size_of_buffer += size_of_buffer/2;
buffer = (char *) realloc (buffer, size_of_buffer * sizeof(char));
memset(buffer + ptr, 0, size_of_buffer - ptr);
}
}
}
}
return buffer;
}
int find_loaded_module(char *name)
{
unsigned int x;
for (x=0; x<loaded_modules_cnt; x++) {
if (strcmp(running_modules[x].module_name, name) == 0) {
return x;
}
}
return -1;
}
void generate_backup_config_file()
{
FILE *backup_file_fd = NULL;
char *backup_file_name = NULL;
modules_profile_t * ptr = first_profile_ptr;
unsigned int x, y;
char buffer[20];
const char *templ = "<?xml version=\"1.0\"?><nemea-supervisor xmlns=\"urn:cesnet:tmc:nemea:1.0\"></nemea-supervisor>";
xmlDocPtr document_ptr = NULL;
xmlNodePtr root_elem = NULL, modules = NULL, module = NULL, trapinterfaces = NULL, interface = NULL;
document_ptr = xmlParseMemory(templ, strlen(templ));
if (document_ptr == NULL) {
return;
}
root_elem = xmlDocGetRootElement(document_ptr);
xmlNewProp (root_elem, BAD_CAST "lock", NULL);
if (daemon_flag) {
xmlNewProp (root_elem, BAD_CAST "daemon", BAD_CAST "true");
xmlNewProp (root_elem, BAD_CAST "socket_path", BAD_CAST socket_path);
} else {
xmlNewProp (root_elem, BAD_CAST "daemon", BAD_CAST "false");
xmlNewProp (root_elem, BAD_CAST "socket_path", BAD_CAST NULL);
}
// backup modules with profile name
while (ptr != NULL) {