-
Notifications
You must be signed in to change notification settings - Fork 0
/
dispatcher.c
1963 lines (1598 loc) · 54.6 KB
/
dispatcher.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
#include "dispatcher.h"
#include "global.h"
/* TODO: portable printf format for pid_t (now %d) */
int main(int argc, char *argv[])
{
uint32_t dispatched_counter = 0; /* number of dispatched tasks */
time_t sense_timestamp = 0; /* timestamp for sense display */
time_t terminate_timestamp = 0; /* timestamp for termination sense display */
time_t pause_timestamp = 0; /* timestamp for pause sense display */
MYSQL *db = NULL;
int option;
const char *usage =
"Usage: "PACKAGE_NAME" [OPTIONS...]\n"
" -h\t\tPrint this help information\n"
" -V\t\tShow version information\n"
" -f <file>\tOverride configuration file location\n"
" -n <size>\tMaximum number of children";
/* process command line parameters */
while ((option = getopt(argc, argv, "n:f:hV")) != -1)
switch (option) {
case 'n':
if (sscanf(optarg, "%"SCNu8, &child_limit) < 1) {
fprintf(stderr, "Invalid parameter value\n");
return EXIT_FAILURE;
}
break;
case 'f':
cfg_location = optarg;
break;
case 'h':
fprintf(stdout, "%s\n", usage);
return EXIT_SUCCESS;
case 'V':
fprintf(stdout, PACKAGE_NAME", version "PACKAGE_VERSION"\n");
return EXIT_SUCCESS;
case '?':
fprintf(stdout, "%s\n", usage);
return EXIT_FAILURE;
}
/* initialize buffers */
query = dp_buffer_new(BUFFER_QUERY);
/* initialize signal and status processing */
if (!dp_config_init() ||
!dp_status_init() ||
!dp_signal_init())
return EXIT_FAILURE;
/* specify that we are initialized */
initialized = true;
/* initialize logger */
dp_logger_init(cfg.log.dispatcher);
/* global MySQL initialize */
my_init();
/* initialize MySQL structure */
if (!dp_mysql_init(&db))
return EXIT_FAILURE;
/* connect to MySQL server */
if (!dp_mysql_connect(db)) {
mysql_close(db);
return EXIT_FAILURE;
}
/* main loop */
while (true) {
time_t timestamp;
bool is_job = false;
dp_task task;
pid_t pid;
/* get timestamp for current iteration */
timestamp = time(NULL);
/* Check if we should reload configuration */
if (reload_flag) {
dp_logger(LOG_WARNING, "Reloading configuration...");
/* reload configuration and log files (possible changes)
* NOTE: this function automatically merges configuration and
* handles errors
* NOTE: openlog does not allocate identifier!
*/
if (dp_config_init())
dp_logger_init(cfg.log.dispatcher);
reload_flag = false;
}
/* Check if we should print status */
if (status_flag) {
dp_logger(LOG_NOTICE, "Logging status...");
for (size_t i = 0; i < child_limit; ++i) {
if (child_status[i].null)
continue;
/* print status of the single worker */
/* id, method, priority, stamp to timeout */
dp_logger(LOG_NOTICE, "%3zu: %-10d %-30.30s %-4d %-6.0lf",
i,
child_status[i].task.id,
child_status[i].task.type,
child_status[i].task.priority,
difftime(timestamp,
child_status[i].task.run_after));
}
status_flag = false;
}
/* check if we should terminate */
if (terminate_flag) {
/* if we start countdown then we should print some information
* to syslog and terminal
*/
if (terminate_timestamp == 0) {
dp_logger(LOG_WARNING, "Terminating... Waiting for children");
terminate_timestamp = timestamp + cfg.sense.terminated;
}
if (terminate_flag >= FORCE_TERMINATE_COUNT) {
dp_logger(LOG_WARNING, "Forced instant termination");
/* kill all child processes */
for (size_t i = 0; i < child_limit; ++i)
if (!child_status[i].null)
kill(child_status[i].pid, SIGTERM);
break;
}
/* Check if we should print sense information during terminate */
if (cfg.sense.terminated &&
terminate_timestamp < timestamp) {
dp_logger(LOG_WARNING, "(%d/%d) Terminating...", child_counter, child_limit);
terminate_timestamp = timestamp + cfg.sense.terminated;
}
/* Check if all children are done
* NOTE: we break main loop here
*/
if (child_counter <= 0) {
dp_logger(LOG_WARNING, "Terminated");
break;
}
sleep(cfg.sleep_loop);
/* update status of workers and get number of workers */
dp_status_timeout(timestamp - cfg.task.timeout_delay);
dp_status_update();
continue;
}
/* check if we are paused */
if (pause_flag) {
/* update sense timestamp when paused */
sense_timestamp = timestamp + cfg.sense.loop;
/* Check if we should print sense information during pause */
if (cfg.sense.paused && pause_timestamp < timestamp) {
dp_logger(LOG_NOTICE, "Sleeping (%"PRIi32"/%"PRIi32")",
child_counter, child_limit);
pause_timestamp = timestamp + cfg.sense.paused;
}
sleep(cfg.sleep_loop);
/* update status of workers and get number of workers */
dp_status_timeout(timestamp - cfg.task.timeout_delay);
dp_status_update();
continue;
} else
pause_timestamp = timestamp + cfg.sense.paused;
/* log sense */
if (cfg.sense.loop && sense_timestamp < timestamp) {
dp_logger(LOG_NOTICE, "Dispatching (%"PRIu32") (%"PRIi32"/%"PRIi32")",
dispatched_counter,
child_counter, child_limit);
sense_timestamp = timestamp + cfg.sense.loop;
dispatched_counter = 0;
}
/* If we are already at maximum fork capacity, we shouldn't
* grab another task, we should just sleep for a bit.
* NOTE: this prevents automatic update of task in database, even
* when there is no space in queue
*/
if (child_counter >= child_limit) {
sleep(cfg.sleep_loop);
/* update status of workers and get number of workers */
dp_status_timeout(timestamp - cfg.task.timeout_delay);
dp_status_update();
continue;
}
/* START fake loop for query "exceptions" */
do {
MYSQL_RES *result;
/* make double sure that there is space in queue for task,
* we don't want to make it 'working' and do nothing later
*/
if (child_counter >= child_limit)
break;
/* setup optional ORDER BY */
const char *order_by = (cfg.task.priority) ?
"ORDER BY priority DESC" : "";
/* get pending task, check specific environment */
if (cfg.task.environment != NULL) {
dp_buffer_printf(query,
"SELECT * FROM %s "
"WHERE status IN ('new','working') AND run_after < %ld "
"AND type LIKE '%%:%s:%%' "
"%s LIMIT 1",
cfg.mysql.table,
timestamp,
cfg.task.environment,
order_by);
} else {
dp_buffer_printf(query,
"SELECT * FROM %s "
"WHERE status IN ('new','working') AND run_after < %ld "
"%s LIMIT 1",
cfg.mysql.table,
timestamp,
order_by);
}
/* execute query */
if (!dp_mysql_query(db, query->str, false))
break;
/* extract task */
result = mysql_store_result(db);
is_job = dp_mysql_get_task(&task, result);
mysql_free_result(result);
/* check if we have job */
if (!is_job)
break;
/* try to update status */
dp_buffer_printf(query,
"UPDATE %s "
"SET status = 'working', run_after = '%ld' "
"WHERE id = %d",
cfg.mysql.table,
timestamp + cfg.task.timeout_delay,
task.id);
if (!dp_mysql_query(db, query->str, false))
continue;
result = mysql_store_result(db);
mysql_free_result(result);
/* check if update was successful */
/* NOTE: job may be taken already by another dispatcher */
if (mysql_affected_rows(db) == 0)
continue;
/* END fake loop for query "exceptions" */
} while (false);
/* START fake loop for dispatching "exceptions" */
do {
dp_child *worker;
/* check if we have free spots
* NOTE: currently if there is job we get here only if there is
* free spot in queue, but check of queue size anyway
*/
if (!is_job || child_counter >= child_limit)
break;
/* find first empty entry */
if ((worker = dp_child_null()) == NULL) {
dp_logger(LOG_ERR,
"Internal job error (%d): No more free workers",
task.id);
/* insert task back to queue */
dp_buffer_printf(query,
"UPDATE %s SET status = 'new' WHERE id = %d",
cfg.mysql.table,
worker->task.id);
dp_mysql_query(db, query->str, false);
/* stop processing */
break;
}
/* initialize worker data */
worker->task = task;
worker->stamp = timestamp;
worker->null = false;
/* update dispatched marker for sense */
dispatched_counter += 1;
/* fork worker */
if ((pid = fork()) == 0)
/* executed in fork only */
return dp_fork_exec(worker);
/* detect fork error */
/* fork failed */
if (pid < 0) {
dp_logger(LOG_ERR, "Fork failed!");
/* insert task back to queue */
dp_buffer_printf(query,
"UPDATE %s SET status = 'new' WHERE id = %d",
cfg.mysql.table,
worker->task.id);
dp_mysql_query(db, query->str, false);
/* fork successful */
} else {
/* update worker status */
worker->pid = pid;
/* increase task count */
child_counter += 1;
}
/* END fake loop for dispatching "exceptions" */
} while (false);
/* wait for next iteration
* NOTE: sleep terminates when we receive signal
* NOTE: sleep only when no task are waiting or we have full queue
*/
if (!is_job || (is_job && child_counter >= child_limit))
sleep(cfg.sleep_loop);
/* update status of workers and get number of running workers */
dp_status_timeout(timestamp - cfg.task.timeout_delay);
dp_status_update();
}
/* close mysql connection */
mysql_close(db);
/* free configuration resources */
dp_buffer_free(query);
dp_config_free(&cfg);
dp_status_free();
return EXIT_SUCCESS;
}
int dp_fork_exec(dp_child *worker)
{
gearman_client_st *client = NULL; /* gearman client */
gearman_return_t error; /* gearman error */
void *worker_result = NULL; /* gearman worker result */
size_t worker_result_size; /* gearman worker result size */
time_t timestamp; /* fork execution timestamp */
MYSQL *db = NULL;
/* data extracted from worker result */
dp_task_result result;
dp_buffer *description;
/* initialize signal processing */
if (!dp_fork_signal_init())
return EXIT_FAILURE;
/* initialize logger */
dp_logger_init(cfg.log.worker);
dp_logger(LOG_DEBUG, "Worker forked (%d/%d) job (%d)",
child_counter + 1, child_limit, worker->task.id);
/* gearman initialize */
if (!dp_gearman_init(&client))
return EXIT_FAILURE;
description = dp_yaml_task_description(&worker->task);
if (description == NULL)
return EXIT_FAILURE;
/* process job */
worker_result = gearman_client_do(client,
worker->task.type,
NULL,
description->str,
description->size,
&worker_result_size,
&error);
/* entering critical section, blocking terminate signal */
/* NOTE: we block SIGTERM till the end */
dp_signal_block(SIGTERM);
/* get result timestamp */
timestamp = time(NULL);
/* NOTE: we initialize mysql only after gearman finished work.
* This prevents timeouts from mysql connection when task execution
* takes more time.
*/
/* initialize mysql for worker */
my_init();
/* initialize connection data */
if (!dp_mysql_init(&db) ||
!dp_mysql_connect(db))
return EXIT_FAILURE;
/* error executing work, retry */
if (error) {
dp_logger(LOG_ERR, "Worker job (%d) FAILED (%d): %s",
worker->task.id, error, gearman_client_error(client));
/* escape work details */
char *type = dp_strescape(worker->task.type);
char *description = dp_strescape(worker->task.description);
/* specify run delay */
time_t run_after = timestamp + cfg.task.failed_delay;
/* insert task one more time */
dp_buffer_printf(query,
"INSERT INTO %s "
"(type, description, status, priority, run_after) "
"VALUES ('%s', '%s', 'new', '%d', '%ld')",
cfg.mysql.table,
type, description,
worker->task.priority, run_after);
if (!dp_mysql_query(db, query->str, true))
return EXIT_FAILURE;
/* update task to describe error */
dp_buffer_printf(query,
"UPDATE %s "
"SET status = 'failed', result = '%s', "
"result_timestamp = '%ld' "
"WHERE id = %d",
cfg.mysql.table,
RESULT_ERROR_GEARMAN,
timestamp,
worker->task.id);
if (!dp_mysql_query(db, query->str, true))
return EXIT_FAILURE;
/* free temporary buffers */
free(description);
free(type);
return error;
}
/* process reply from gearman */
dp_gearman_get_result(&result, worker_result, worker_result_size);
/* prepare query to database */
if (result.status) {
/* update task entry to indicate that it is done */
dp_buffer_printf(query,
"UPDATE %s "
"SET status = 'done', result = '', "
"result_timestamp = '%ld', time_elapsed = '%.5lf' "
"WHERE id = %d",
cfg.mysql.table,
timestamp, result.time_elapsed,
worker->task.id);
if (!dp_mysql_query(db, query->str, true))
return EXIT_FAILURE;
} else {
/* update task entry to indicate that it failed */
/* NOTE: we update task status and insert new one */
dp_logger(LOG_ERR, "Worker job (%d) FAILED",
worker->task.id);
/* escape work details */
char *type = dp_strescape(worker->task.type);
char *description = dp_strescape(worker->task.description);
char *value = dp_struescape(worker_result, worker_result_size);
/* specify run delay */
time_t run_after = timestamp + cfg.task.failed_delay;
/* insert task to rerun */
dp_buffer_printf(query,
"INSERT INTO %s "
"(type, description, status, priority, run_after) "
"VALUES ('%s', '%s', 'new', '%d', '%ld')",
cfg.mysql.table,
type, description,
worker->task.priority, run_after);
if (!dp_mysql_query(db, query->str, true))
return EXIT_FAILURE;
/* update status of the task */
dp_buffer_printf(query,
"UPDATE %s "
"SET status = 'failed', result = '%s', "
"result_timestamp = '%ld', time_elapsed = '%.5lf' "
"WHERE id = %d",
cfg.mysql.table,
value, timestamp, result.time_elapsed,
worker->task.id);
if (!dp_mysql_query(db, query->str, true))
return EXIT_FAILURE;
/* free temporary buffers */
free(description);
free(type);
free(value);
}
/* close gearman connection */
gearman_client_free(client);
/* close mysql connection */
mysql_close(db);
dp_logger(LOG_DEBUG, "Worker finished");
return EXIT_SUCCESS;
}
/* Load dispatcher configuration file, can be called multiple times.
* When configuration file is invalid then function return false;
* NOTE: we log in syslog configuration related issues only after
* initialization is complete, i.e. on reload
*/
bool dp_config_init()
{
FILE *fconfig;
char buffer[BUFFER_SIZE_MAX];
char value[BUFFER_SIZE_MAX];
char name[BUFFER_SIZE_MAX];
dp_config_val field;
uint32_t line;
bool is_eof = false, is_error = false;
dp_config config;
/* initialize new config */
memset(&config, 0, sizeof(dp_config));
/* extract config location */
const char *config_location = (cfg_location == NULL) ?
DP_CONFIG"/dispatcher.conf" :
cfg_location;
/* open configuration file */
fconfig = fopen(config_location, "r");
if (fconfig == NULL) {
if (initialized)
dp_logger(LOG_ERR, "Unable to find configuration file: '%s'", config_location);
else
fprintf(stderr, "Unable to find configuration file: '%s'\n", config_location);
return false;
}
/* read each line separately */
for (line = 1; fgets(buffer, BUFFER_SIZE_MAX, fconfig); ++line) {
/* omit comments, empty lines */
if (*buffer == '#' || *buffer == '\n')
continue;
/* read configuration directive */
/* NOTE: we don't care about overruns here
* all buffer are with same length
*/
sscanf(buffer, "%s = %s", name, value);
/* extract field id */
field = dp_config_field(name);
/* try to set configuration variable */
if (!dp_config_set(&config, field, value, true)) {
is_error = true;
break;
}
}
/* finalize read */
is_eof = feof(fconfig);
fclose(fconfig);
/* check for errors */
if (is_eof && !is_error) {
/* reload configuration if parse was successful */
dp_config_free(&cfg);
cfg = config;
} else {
dp_config_free(&config);
if (initialized)
dp_logger(LOG_ERR, "Invalid configuration directive at line (%"PRIu32")", line);
else
fprintf(stderr, "Invalid configuration directive at line (%"PRIu32")\n", line);
return false;
}
return true;
}
bool dp_signal_init()
{
/* setup signals */
struct sigaction action;
sigset_t block, no_block;
sigemptyset(&block);
sigemptyset(&no_block);
/* queue multiple SIGCHLD signals, used to prevent zombie children */
sigaddset(&block, SIGCHLD);
/* queue multiple SIGUSR1 signals, used to pause and resume dispatching */
sigaddset(&block, SIGUSR1);
/* setup action for SIGCHLD */
action.sa_handler = dp_sigchld;
action.sa_mask = block;
action.sa_flags = 0;
/* install signal handler */
sigaction(SIGCHLD, &action, NULL);
/* setup action for SIGHUP */
action.sa_handler = dp_sighup;
action.sa_mask = no_block;
action.sa_flags = 0;
/* install signal handler */
sigaction(SIGHUP, &action, NULL);
/* setup action for SIGTERM and SIGINT */
action.sa_handler = dp_sigtermint;
action.sa_mask = no_block;
action.sa_flags = 0;
/* install signal handler */
sigaction(SIGTERM, &action, NULL);
sigaction(SIGINT, &action, NULL);
/* setup action for SIGUSR1 */
action.sa_handler = dp_sigusr1;
action.sa_mask = block;
action.sa_flags = 0;
/* install signal handler */
sigaction(SIGUSR1, &action, NULL);
/* setup action for SIGUSR2 */
action.sa_handler = dp_sigusr2;
action.sa_mask = no_block;
action.sa_flags = 0;
/* install signal handler */
sigaction(SIGUSR2, &action, NULL);
return true;
}
bool dp_fork_signal_init()
{
/* setup signals */
struct sigaction action;
sigset_t empty;
sigemptyset(&empty);
/* set default handler */
action.sa_handler = SIG_DFL;
action.sa_mask = empty;
action.sa_flags = 0;
/* install default signal handlers */
sigaction(SIGCHLD, &action, NULL);
sigaction(SIGHUP, &action, NULL);
sigaction(SIGTERM, &action, NULL);
sigaction(SIGUSR1, &action, NULL);
sigaction(SIGUSR2, &action, NULL);
/* set ignore handler */
action.sa_handler = SIG_IGN;
action.sa_mask = empty;
action.sa_flags = 0;
/* ignore following signals */
sigaction(SIGINT, &action, NULL);
return true;
}
bool dp_signal_block(int signum)
{
sigset_t mask;
/* specify sigset_t */
sigemptyset(&mask);
sigaddset(&mask, signum);
/* block signal */
sigprocmask(SIG_BLOCK, &mask, NULL);
return true;
}
bool dp_signal_unblock(int signum)
{
sigset_t mask;
/* specify sigset_t */
sigemptyset(&mask);
sigaddset(&mask, signum);
/* unblock signal */
sigprocmask(SIG_UNBLOCK , &mask, NULL);
return true;
}
dp_config_val dp_config_field(const char *name)
{
dp_enum *match;
if (name == NULL)
return DP_CONFIG_UNKNOWN;
/* extract matching enum */
match = dp_enum_name(dp_config_value, name);
if (match == NULL)
return DP_CONFIG_UNKNOWN;
return match->value;
}
bool dp_config_set(dp_config *config, dp_config_val field, char *value, bool if_dup)
{
dp_enum *enumeration;
switch (field) {
case DP_CONFIG_UNKNOWN:
return false;
case DP_CONFIG_MYSQL_HOST:
if (config->mysql.host) free(config->mysql.host);
if (!if_dup) config->mysql.host = value;
else config->mysql.host = dp_strdup(value);
break;
case DP_CONFIG_MYSQL_DB:
if (config->mysql.db) free(config->mysql.db);
if (!if_dup) config->mysql.db = value;
else config->mysql.db = dp_strdup(value);
break;
case DP_CONFIG_MYSQL_USER:
if (config->mysql.user) free(config->mysql.user);
if (!if_dup) config->mysql.user = value;
else config->mysql.user = dp_strdup(value);
break;
case DP_CONFIG_MYSQL_PASSWD:
if (config->mysql.passwd) free(config->mysql.passwd);
if (!if_dup) config->mysql.passwd = value;
else config->mysql.passwd = dp_strdup(value);
break;
case DP_CONFIG_MYSQL_TABLE:
if (config->mysql.table) free(config->mysql.table);
if (!if_dup) config->mysql.table = value;
else config->mysql.table = dp_strdup(value);
break;
case DP_CONFIG_MYSQL_PORT:
if (sscanf(value, "%d", &config->mysql.port) != 1)
return false;
break;
case DP_CONFIG_GEARMAN_HOST:
if (config->gearman.host) free(config->gearman.host);
if (!if_dup) config->gearman.host = value;
else config->gearman.host = dp_strdup(value);
break;
case DP_CONFIG_GEARMAN_PORT:
if (sscanf(value, "%d", &config->gearman.port) != 1)
return false;
break;
case DP_CONFIG_TASK_FAILED_DELAY:
if (sscanf(value, "%" SCNu16, &config->task.failed_delay) != 1)
return false;
break;
case DP_CONFIG_TASK_TIMEOUT_DELAY:
if (sscanf(value, "%" SCNu16, &config->task.timeout_delay) != 1)
return false;
break;
case DP_CONFIG_TASK_ENVIRONMENT:
if (config->task.environment) free(config->task.environment);
/* handle processing of the environment */
if (!strcmp(value, "any")) {
/* free value if we should take ownership */
if (!if_dup) free(value);
config->task.environment = NULL;
} else {
if (!if_dup) config->task.environment = value;
else config->task.environment = dp_strdup(value);
}
break;
case DP_CONFIG_TASK_PRIORITY:
if (!strcmp(value, "true") || !strcmp(value, "1"))
config->task.priority = true;
else if (!strcmp(value, "false") || !strcmp(value, "0"))
config->task.priority = false;
else
return false;
break;
case DP_CONFIG_LOG_DISPATCHER:
if (config->log.dispatcher) free(config->log.dispatcher);
if (!if_dup) config->log.dispatcher = value;
else config->log.dispatcher = dp_strdup(value);
break;
case DP_CONFIG_LOG_WORKER:
if (config->log.worker) free(config->log.worker);
if (!if_dup) config->log.worker = value;
else config->log.worker = dp_strdup(value);
break;
case DP_CONFIG_LOG_LEVEL:
if ((enumeration = dp_enum_name(dp_log_level, value)) == NULL)
return false;
config->log.level = enumeration->value;
break;
case DP_CONFIG_LOG_FACILITY:
if ((enumeration = dp_enum_name(dp_log_facility, value)) == NULL)
return false;
config->log.facility = enumeration->value;
break;
case DP_CONFIG_SENSE_LOOP:
if (sscanf(value, "%" SCNu16, &config->sense.loop) != 1)
return false;
break;
case DP_CONFIG_SENSE_TERMINATED:
if (sscanf(value, "%" SCNu16, &config->sense.terminated) != 1)
return false;
break;
case DP_CONFIG_SENSE_PAUSED:
if (sscanf(value, "%" SCNu16, &config->sense.paused) != 1)
return false;
break;
case DP_CONFIG_SLEEP_LOOP:
if (sscanf(value, "%" SCNu16, &config->sleep_loop) != 1)
return false;
break;
}
return true;
}
void dp_config_free(dp_config *config)
{
if (config != NULL) {
free(config->mysql.host);
free(config->mysql.db);
free(config->mysql.user);
free(config->mysql.passwd);
free(config->mysql.table);
free(config->gearman.host);
free(config->task.environment);
free(config->log.dispatcher);
free(config->log.worker);
}
}
dp_buffer *dp_buffer_new(size_t pool)
{
dp_buffer *buf;
/* allocate buffer */
buf = malloc(sizeof(dp_buffer));
if (buf == NULL)
return NULL;
/* allocate buffer pool */
if (dp_buffer_init(buf, pool) == NULL) {
free(buf);
return NULL;
}
return buf;
}
dp_buffer *dp_buffer_init(dp_buffer *buf, size_t pool)
{
/* handle empty buffer request */
if (pool == 0) {
buf->str = NULL;
buf->size = 0;
buf->pool = 0;
} else {
/* allocate pool */
buf->str = malloc(pool);
if (buf->str == NULL)
return NULL;
/* initialize buffer */
buf->str[0] = '\0';
buf->size = 0;
buf->pool = pool;
}
return buf;
}
void dp_buffer_free(dp_buffer *buf)
{
if (buf != NULL) {
free(buf->str);
free(buf);
}
}
dp_buffer *dp_buffer_printf(dp_buffer *buf, const char *format, ...)
{
va_list arg;
size_t len;
/* insert format string */
va_start(arg, format);
len = vsnprintf(buf->str, buf->pool, format, arg);
va_end(arg);
/* check if everything was inserted */
if (len >= buf->pool) {
/* allocate bigger buffer */
char *str = malloc(len + 1);
if (str == NULL)
goto enomem_error;
/* retry insert format string */
va_start(arg, format);
vsnprintf(str, len + 1, format, arg);
va_end(arg);
/* adjust buffer */
free(buf->str);
buf->str = str;
buf->size = len;
buf->pool = len + 1;
} else
/* adjust buffer */
buf->size = len;
return buf;
enomem_error:
/* failback buffer */
buf->size = 0;
buf->str[0] = '\0';
/* log our problem */
dp_logger(LOG_ERR, "Memory exhaustion!");
return NULL;
}
dp_buffer *dp_buffer_append(dp_buffer *buf,
const dp_buffer *append)
{
if (buf->pool < buf->size + append->size + 1) {
/* allocate updated buffer */
char *str = malloc(buf->size + append->size + 1);
if (str == NULL) {
/* log our problem */
dp_logger(LOG_ERR, "Memory exhaustion!");
return NULL;
}
/* copy previous contents */
if (buf->str != NULL)
memcpy(str, buf->str, buf->size);
/* free previous contents */
free(buf->str);
/* initialize updated buffer */
buf->pool = buf->size + append->size + 1;
buf->str = str;
}
/* insert string into updated buffer */
memcpy(buf->str + buf->size, append->str, append->size);