-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.c
2097 lines (1578 loc) · 49.2 KB
/
database.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
/*
* database.c
*
* Created on: 03.03.2016
* Author: jh
*/
/*
Database for the project and process data.
Provides information about all current projects, processes and statistics.
Copyright (C) 2015,2016 Jörg Habenicht (jh@mwerk.net)
This file is part of qgis-server-scheduler
qgis-server-scheduler is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
qgis-server-scheduler is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#define _GNU_SOURCE
#include "database.h"
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <sqlite3.h>
#include <pthread.h>
#include <assert.h>
#include <string.h>
#include <libgen.h>
#include <errno.h>
#include "logger.h"
#include "qgis_config.h"
#include "qgis_shutdown_queue.h"
#include "statistic.h"
#include "stringext.h"
#include "timer.h"
/* process data:
* process id, list state, process state, worker thread id, socket fd
*
* project data:
* project name, number of crashes during init phase
*/
#define DB_MAX_RETRIES 10
/* callback function for the common query function.
* First parameter is the data given by "callback_arg"
* from int db_select_parameter_callback(enum db_select_statement_id sid, sqlite3_callback callback, void *callback_arg, ...)
* Second parameter is the number of columns in the result.
* Third parameter is the data type of the result array, one entry for each result.
* Forth parameter is the array of results, which have to be converted. Do like this:
* switch (type[i])
* {
* case SQLITE_INTEGER:
* int value = results[i].integer;
* break;
* case SQLITE_FLOAT:
* double value = results[i].floating;
* break;
* case SQLITE_BLOB:
* const void *data = results[i].blob;
* break;
* case SQLITE_NULL:
* break;
* case SQLITE_TEXT:
* char *value = strdup(results[i].text);
* break;
* }
* Fifth parameter is the array of column names.
*/
union callback_result_t {
long long int integer;
double floating;
const unsigned char *text;
const void *blob;
};
typedef int (*db_callback)(void *data, int ncol, int *type, union callback_result_t *results, const char**cols);
static sqlite3 *dbhandler = NULL;
static pthread_mutex_t db_mutex_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t idle_process_condition = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t idle_process_mutex = PTHREAD_MUTEX_INITIALIZER;
/* This is a global flag where statements can set the default error behaviour
* Normally the error is printed on standard error channel or into the log file.
* By setting this variable != 0 the behavior changes and the application exits
* with an error message.
*
* CAUTION: This variable needs to be changed under the protection of
* "db_mutex_lock", i.e. inbetween db_global_lock() and db_global_unlock().
*/
static int db_exit_on_error = 0;
enum db_select_statement_id
{
DB_SELECT_ID_NULL = 0,
// from this id on we can use prepared statements
DB_SELECT_CREATE_PROJECT_TABLE,
DB_SELECT_CREATE_PROCESS_TABLE,
DB_SELECT_GET_NAMES_FROM_PROJECT,
DB_INSERT_PROJECT_DATA,
DB_DELETE_PROJECT_DATA,
DB_SELECT_CONFIGPATH_WITH_PROJECT,
DB_INSERT_PROCESS_DATA,
DB_UPDATE_PROCESS_STATE,
DB_GET_PROCESS_STATE,
DB_GET_STATE_PROCESS,
DB_GET_NUM_START_INIT_IDLE_PROCESS,
DB_GET_ALL_PROCESS,
DB_GET_PROCESS_FROM_LIST,
DB_GET_NUM_PROCESS_FROM_LIST,
DB_UPDATE_PROCESS_LISTS_WITH_NAME_AND_LIST,
DB_UPDATE_PROCESS_LIST_PID,
DB_UPDATE_PROCESS_LIST,
DB_UPDATE_PROCESS_SIGNAL_TIMER,
DB_SELECT_PROCESS_SIGNAL_TIMER,
DB_SELECT_PROCESS_MIN_SIGNAL_TIMER,
DB_DELETE_PROCESS_WITH_STATE,
DB_INC_PROJECT_STARTUP_FAILURE,
DB_SELECT_PROJECT_STARTUP_FAILURE,
DB_RESET_PROJECT_STARTUP_FAILURE,
DB_SELECT_PROJECT_WITH_PID,
DB_SELECT_PROCESS_WITH_NAME_LIST_AND_STATE,
DB_GET_LIST_FROM_PROCESS,
DB_GET_PROCESS_SOCKET_FROM_PROCESS,
DB_UPDATE_PROJECT_WITH_CONFIG_AND_WATCHD,
DB_GET_PROJECTS_FOR_WATCHES_AND_CONFIGS,
DB_GET_WATCHD_FROM_CONFIG,
DB_GET_WATCHD_FROM_PROJECT,
DB_GET_NUM_WATCHD_FROM_CONFIG,
DB_GET_NUM_WATCHD_FROM_WATCHD,
DB_DUMP_PROJECT,
DB_DUMP_PROCESS,
DB_SELECT_ID_MAX // last entry, do not use
};
static const char *db_select_statement[DB_SELECT_ID_MAX] =
{
// DB_SELECT_ID_NULL
"",
// DB_SELECT_CREATE_PROJECT_TABLE
"CREATE TABLE projects (name TEXT UNIQUE NOT NULL, configpath TEXT DEFAULT '', configbasename TEXT DEFAULT '', watchd INTEGER DEFAULT 0, nr_crashs INTEGER DEFAULT 0)",
// DB_SELECT_CREATE_PROCESS_TABLE
"CREATE TABLE processes (projectname TEXT REFERENCES projects (name), "
"list INTEGER NOT NULL, state INTEGER NOT NULL, "
"threadid INTEGER, pid INTEGER UNIQUE NOT NULL, "
"process_socket_fd INTEGER NOT NULL, client_socket_fd INTEGER DEFAULT -1, "
"starttime_sec INTEGER DEFAULT 0, starttime_nsec INTEGER DEFAULT 0, "
"signaltime_sec INTEGER DEFAULT 0, signaltime_nsec INTEGER DEFAULT 0 )",
// DB_SELECT_GET_NAMES_FROM_PROJECT
"SELECT name FROM projects",
// DB_INSERT_PROJECT_DATA
"INSERT INTO projects (name) VALUES (%s)",
// DB_DELETE_PROJECT_DATA
"DELETE FROM projects WHERE name = %s",
// DB_SELECT_CONFIGPATH_WITH_PROJECT
"SELECT configpath FROM projects WHERE name = %s",
// DB_INSERT_PROCESS_DATA
"INSERT INTO processes (projectname, list, state, pid, process_socket_fd) VALUES (%s,%i,%i,%i,%i)",
// DB_UPDATE_PROCESS_STATE
"UPDATE processes SET state = %i, threadid = %l WHERE pid = %i",
// DB_GET_PROCESS_STATE
"SELECT state FROM processes WHERE pid = %i",
// DB_GET_STATE_PROCESS
"SELECT pid FROM processes WHERE projectname = %s AND state = %i",
// DB_GET_NUM_START_INIT_IDLE_PROCESS
"SELECT count(pid) FROM processes WHERE projectname = %s AND ( state = 0 OR state = 1 OR state = 2 )",
// DB_GET_ALL_PROCESS
"SELECT pid FROM processes",
// DB_GET_PROCESS_FROM_LIST
"SELECT pid FROM processes WHERE list = %d",
// DB_GET_NUM_PROCESS_FROM_LIST
"SELECT count(pid) FROM processes WHERE list = %d",
// DB_UPDATE_PROCESS_LISTS_WITH_NAME_AND_LIST
"UPDATE processes SET list = %i WHERE projectname = %s AND list = %i",
// DB_UPDATE_PROCESS_LIST_PID
"UPDATE processes SET list = %i WHERE pid = %i",
// DB_UPDATE_PROCESS_LIST
"UPDATE processes SET list = %i",
// DB_UPDATE_PROCESS_SIGNAL_TIMER
"UPDATE processes SET signaltime_sec = %l, signaltime_nsec = %l WHERE pid = %i",
// DB_SELECT_PROCESS_SIGNAL_TIMER
"SELECT signaltime_sec,signaltime_nsec FROM processes WHERE pid = %i",
// DB_SELECT_PROCESS_MIN_SIGNAL_TIMER
"SELECT signaltime_sec,signaltime_nsec FROM processes WHERE signaltime_sec != 0 AND signaltime_nsec != 0 ORDER BY signaltime_sec ASC, signaltime_nsec ASC LIMIT 1",
// DB_DELETE_PROCESS_WITH_STATE
"DELETE FROM processes WHERE STATE = %i",
// DB_INC_PROJECT_STARTUP_FAILURE
"UPDATE projects SET nr_crashs = nr_crashs+1 WHERE name = %s",
// DB_SELECT_PROJECT_STARTUP_FAILURE
"SELECT nr_crashs FROM projects WHERE name = %s",
// DB_RESET_PROJECT_STARTUP_FAILURE
"UPDATE projects SET nr_crashs = 0 WHERE name = %s",
// DB_SELECT_PROJECT_WITH_PID
"SELECT projectname FROM processes WHERE pid = %i",
// DB_SELECT_PROCESS_WITH_NAME_LIST_AND_STATE
"SELECT pid FROM processes WHERE (projectname= %s AND list = %i AND state = %i) LIMIT 1",
// DB_GET_LIST_FROM_PROCESS
"SELECT list FROM processes WHERE pid = %d",
// DB_GET_PROCESS_SOCKET_FROM_PROCESS
"SELECT process_socket_fd FROM processes WHERE pid = %d",
// DB_UPDATE_PROJECT_WITH_CONFIG_AND_WATCHD
"UPDATE OR IGNORE projects SET configpath = %s, configbasename = %s, watchd = %i WHERE name = %s",
// DB_GET_PROJECTS_FOR_WATCHES_AND_CONFIGS
"SELECT name FROM projects WHERE watchd = %d AND configbasename = %s",
// DB_GET_WATCHD_FROM_CONFIG
"SELECT watchd FROM projects WHERE configpath = %s",
// DB_GET_WATCHD_FROM_PROJECT
"SELECT watchd FROM projects WHERE name = %s",
// DB_GET_NUM_WATCHD_FROM_CONFIG
"SELECT count(watchd) FROM projects WHERE watchd IN (SELECT watchd FROM projects WHERE configpath = %s)",
// DB_GET_NUM_WATCHD_FROM_WATCHD
"SELECT count(watchd) FROM projects WHERE watchd = %d",
// DB_DUMP_PROJECT
"SELECT * FROM projects ORDER BY name ASC",
// DB_DUMP_PROCESS
"SELECT * FROM processes ORDER BY projectname ASC, pid ASC",
};
static sqlite3_stmt *db_prepared_stmt[DB_SELECT_ID_MAX] = { 0 };
static void db_global_lock(void)
{
int retval = pthread_mutex_lock(&db_mutex_lock);
if (retval)
{
errno = retval;
logerror("ERROR: acquire db mutex lock");
qexit(EXIT_FAILURE);
}
}
static void db_global_unlock(void)
{
int retval = pthread_mutex_unlock(&db_mutex_lock);
if (retval)
{
errno = retval;
logerror("ERROR: unlock db mutex lock");
qexit(EXIT_FAILURE);
}
}
static sqlite3_stmt *db_statement_prepare(enum db_select_statement_id sid)
{
assert(sid < DB_SELECT_ID_MAX);
sqlite3_stmt *ppstmt;
const char *const sql = db_select_statement[sid];
const char *srcsql = sql;
/* exchange "%N" markers with '?' */
char * const copysql = strdup(sql);
char *destsql = copysql;
char c;
do
{
c = *srcsql++;
if ('%' == c)
{
switch(*srcsql++)
{
case 'p':
/* found pointer value "%p". */
// fall through
case 'f':
/* found double value "%f". */
// fall through
case 's':
/* found string value "%s". */
// fall through
case 'd':
/* found integer value "%i". */
// fall through
case 'i':
/* found integer value "%i". */
// fall through
case 'l':
/* found long long integer value "%l". */
/* exchange "%N" with '?' */
c = '?';
break;
case '%':
/* found double percent sign "%%". just go on */
/* exchange "%%" with '%' */
break;
case '\0':
/* percentage sign has been the last character in the string
* rewind the string, so the outer while() catches the end of
* the string.
*/
debug(1, "Huh? found '%%' at the end of the sql '%s'", sql);
srcsql--;
break;
default:
/* unknown character found. exit */
srcsql--;
printlog("ERROR: unknown character found in sql string '%s', position %ld: '%c'", db_select_statement[sid], (long int)(srcsql - db_select_statement[sid]), *srcsql);
qexit(EXIT_FAILURE);
}
}
*destsql++ = c;
} while ( c ); // moved while() down here to copy terminating '\0' to "destsql"
debug(1, "transferred sql from '%s' to '%s'", sql, copysql);
int retval = sqlite3_prepare(dbhandler, copysql, -1, &ppstmt, NULL);
if (SQLITE_OK != retval)
{
printlog("ERROR: preparing sql statement '%s': %s", sql, sqlite3_errstr(retval));
qexit(EXIT_FAILURE);
}
free(copysql);
return ppstmt;
}
static void db_statement_finalize(sqlite3_stmt *ppstmt)
{
int retval = sqlite3_finalize(ppstmt);
if (SQLITE_OK != retval)
{
printlog("ERROR: finalizing sql statement: %s", sqlite3_errstr(retval));
qexit(EXIT_FAILURE);
}
}
static int db_select_parameter_callback(enum db_select_statement_id sid, db_callback callback, void *callback_arg, ...)
{
/* The life-cycle of a prepared statement object usually goes like this:
*
* 1. Create the prepared statement object using sqlite3_prepare_v2().
* 2. Bind values to parameters using the sqlite3_bind_*() interfaces.
* 3. Run the SQL by calling sqlite3_step() one or more times.
* 4. Reset the prepared statement using sqlite3_reset() then go back to step 2. Do this zero or more times.
* 5. Destroy the object using sqlite3_finalize().
*/
int retval;
const int loglevel = config_get_debuglevel();
#define BUFFERSIZE 64
char debug_buffer[BUFFERSIZE] = {0,};
int debug_loglen = BUFFERSIZE;
char *debug_log = NULL;
if (1 <= loglevel)
{
debug_log = malloc(BUFFERSIZE);
if (NULL == debug_log)
{
logerror("ERROR: malloc");
qexit(EXIT_FAILURE);
}
*debug_log = '\0';
}
assert(dbhandler);
assert(sid < DB_SELECT_ID_MAX);
const char *sql = db_select_statement[sid];
sqlite3_stmt *ppstmt;
if ( !db_prepared_stmt[sid] )
db_prepared_stmt[sid] =
ppstmt = db_statement_prepare(sid);
else
ppstmt = db_prepared_stmt[sid];
/* evaluate the remaining arguments */
int col = 1; // column position index
va_list args;
va_start(args, callback_arg);
while (*sql)
{
if ('%' == *sql++)
{
switch(*sql++)
{
case 'p':
/* found pointer value "%p". The next argument is the
* type "void *" */
{
assert(0); // TODO need to extend "%p" to "%NNNp" with NNN being decimal number describing the size of 'p'
const void *v = va_arg(args, void *);
retval = sqlite3_bind_blob(ppstmt, col++, v, -1, SQLITE_STATIC);
if ( SQLITE_OK != retval )
{
printlog("ERROR: in sql '%s' bind column %d returned: %s", sql, col, sqlite3_errstr(retval));
qexit(EXIT_FAILURE);
}
if (1 <= loglevel)
{
snprintf(debug_buffer, BUFFERSIZE-1, ", %p", v);
strnbcat(&debug_log, &debug_loglen, debug_buffer);
}
break;
}
case 'f':
/* found double value "%f". The next argument is the
* type "double" */
{
double d = va_arg(args, double);
retval = sqlite3_bind_double(ppstmt, col++, d);
if ( SQLITE_OK != retval )
{
printlog("ERROR: in sql '%s' bind column %d returned: %s", sql, col, sqlite3_errstr(retval));
qexit(EXIT_FAILURE);
}
if (1 <= loglevel)
{
snprintf(debug_buffer, BUFFERSIZE-1, ", %f", d);
strnbcat(&debug_log, &debug_loglen, debug_buffer);
}
break;
}
case 's':
/* found string value "%s". The next argument is the
* type "const char *" */
{
const char *s = va_arg(args, char *);
retval = sqlite3_bind_text(ppstmt, col++, s, -1, SQLITE_STATIC);
if ( SQLITE_OK != retval )
{
printlog("ERROR: in sql '%s' bind column %d returned: %s", sql, col, sqlite3_errstr(retval));
qexit(EXIT_FAILURE);
}
if (1 <= loglevel)
{
snprintf(debug_buffer, BUFFERSIZE-1, ", %s", s);
strnbcat(&debug_log, &debug_loglen, debug_buffer);
}
break;
}
case 'd': // fall through
case 'i':
/* found integer value "%i". The next argument is the
* type "int" */
{
int i = va_arg(args, int);
retval = sqlite3_bind_int(ppstmt, col++, i);
if ( SQLITE_OK != retval )
{
printlog("ERROR: in sql '%s' bind column %d returned: %s", sql, col, sqlite3_errstr(retval));
qexit(EXIT_FAILURE);
}
if (1 <= loglevel)
{
snprintf(debug_buffer, BUFFERSIZE-1, ", %d", i);
strnbcat(&debug_log, &debug_loglen, debug_buffer);
}
break;
}
case 'l':
/* found 64bit integer value "%l". The next argument is the
* type "long long int" */
{
long long int l = va_arg(args, long long int);
retval = sqlite3_bind_int64(ppstmt, col++, l);
if ( SQLITE_OK != retval )
{
printlog("ERROR: in sql '%s' bind column %d returned: %s", sql, col, sqlite3_errstr(retval));
qexit(EXIT_FAILURE);
}
if (1 <= loglevel)
{
snprintf(debug_buffer, BUFFERSIZE-1, ", %lld", l);
strnbcat(&debug_log, &debug_loglen, debug_buffer);
}
break;
}
case '%':
/* found double percent sign "%%". just go on */
break;
case '\0':
/* percentage sign has been the last character in the string
* rewind the string, so the outer while() catches the end of
* the string.
*/
sql--;
break;
default:
/* unknown character found. exit */
printlog("ERROR: unknown character found in sql string '%s', position %ld: %c", db_select_statement[sid], (long int)(sql - db_select_statement[sid]), *sql);
qexit(EXIT_FAILURE);
}
}
}
va_end(args);
debug(1, "db selected %d: '%s%s'", sid, db_select_statement[sid], debug_log);
free(debug_log);
int try_num = 0;
do {
retval = sqlite3_step(ppstmt);
if (SQLITE_BUSY == retval)
try_num++;
else if (SQLITE_ROW == retval)
{
/* there is data available, fetch data and recall step() */
debug(1, "data available: sql '%s'", db_select_statement[sid]);
assert(callback);
if ( !callback )
{
printlog("ERROR: data available but no callback function defined for sql '%s'", db_select_statement[sid]);
/* go on with the loop until no more data is available */
}
else
{
/* prepare the callback data */
const int ncol_result = sqlite3_column_count(ppstmt);
int *type = calloc(ncol_result, sizeof(*type));
if ( !type )
{
printlog("ERROR: not enough memory");
qexit(EXIT_FAILURE);
}
union callback_result_t *results = calloc(ncol_result, sizeof(*results));
if ( !results )
{
printlog("ERROR: not enough memory");
qexit(EXIT_FAILURE);
}
const char **cols = calloc(ncol_result, sizeof(*cols));
if ( !cols )
{
printlog("ERROR: not enough memory");
qexit(EXIT_FAILURE);
}
int i;
for (i = 0; i<ncol_result; i++)
{
int mytype =
type[i] = sqlite3_column_type(ppstmt, i);
switch(mytype)
{
case SQLITE_INTEGER:
results[i].integer = sqlite3_column_int64(ppstmt, i);
break;
case SQLITE_FLOAT:
results[i].floating = sqlite3_column_double(ppstmt, i);
break;
case SQLITE_TEXT:
results[i].text = sqlite3_column_text(ppstmt, i);
break;
case SQLITE_BLOB:
results[i].blob = sqlite3_column_blob(ppstmt, i);
break;
case SQLITE_NULL:
break;
default:
printlog("ERROR: unknown type %d", mytype);
qexit(EXIT_FAILURE);
}
cols[i] = sqlite3_column_name(ppstmt, i);
}
retval = callback(callback_arg, ncol_result, type, results, cols);
//TODO: reuse arrays for the next row
free(type);
free(results);
free(cols);
if (retval)
{
retval = SQLITE_ABORT;
break;
}
}
}
else
break;
} while (try_num < DB_MAX_RETRIES);
switch(retval)
{
case SQLITE_BUSY:
printlog("ERROR: db busy! Exceeded max calls (%d) to fetch data", try_num);
break;
case SQLITE_ROW:
/* error: there has been data available,
* but the program broke out of the loop?
*/
assert(0);
break;
case SQLITE_ERROR:
/* there has been a data error. Print out and reset() the statement */
{
const char *sql = db_select_statement[sid];
printlog("ERROR: stepping sql statement '%s': %s", sql, sqlite3_errstr(retval));
if (db_exit_on_error)
{
printlog("exiting..");
qexit(EXIT_FAILURE);
}
else
{
retval = sqlite3_reset(ppstmt);
if (SQLITE_OK != retval)
{
printlog("ERROR: resetting sql statement '%s': %s", sql, sqlite3_errstr(retval));
}
}
}
break;
case SQLITE_MISUSE:
/* the statement has been incorrect */
printlog("ERROR: misuse of prepared sql statement '%s'", db_select_statement[sid]);
if (db_exit_on_error)
{
printlog("exiting..");
qexit(EXIT_FAILURE);
}
break;
case SQLITE_ABORT:
printlog("ERROR: abort in callback function during steps of sql '%s'", db_select_statement[sid]);
qexit(EXIT_FAILURE);
break;
case SQLITE_OK:
case SQLITE_DONE:
/* the statement has finished successfully */
retval = sqlite3_reset(ppstmt);
if (SQLITE_OK != retval)
{
const char *sql = db_select_statement[sid];
printlog("ERROR: resetting sql statement '%s': %s", sql, sqlite3_errstr(retval));
qexit(EXIT_FAILURE);
}
break;
}
// if ( !db_prepared_stmt[sid] )
// db_statement_finalize(ppstmt);
return 0;
}
#define db_select_parameter(sid, ...) \
db_select_parameter_callback(sid, NULL, NULL, ##__VA_ARGS__);
/* prepare database stements for use */
//static void db_statements_prepare(void)
//{
// enum db_select_statement_id i;
// for (i=DB_SELECT_GET_NAMES_FROM_PROJECT; i<DB_SELECT_ID_MAX; i++)
// {
// sqlite3_stmt *ppstmt = db_statement_prepare(i);
// db_prepared_stmt[i] = ppstmt;
// }
//}
static pid_t db_nolock__get_process(const char *projname, enum db_process_list_e list, enum db_process_state_e state)
{
assert(state < PROCESS_STATE_MAX);
assert(list < LIST_SELECTOR_MAX);
int get_process(void *data, int ncol, int *type, union callback_result_t *results, const char**cols)
{
int *proc = data;
assert(1 == ncol);
assert(SQLITE_INTEGER == type[0]);
*proc = results[0].integer;
return 0;
}
pid_t ret = -1;
int mylist = list;
int mystate = state;
db_select_parameter_callback(DB_SELECT_PROCESS_WITH_NAME_LIST_AND_STATE, get_process, &ret, projname, mylist, mystate);
debug(1, "returned %d", ret);
return ret;
}
static int db_nolock__process_set_state(pid_t pid, enum db_process_state_e state, pthread_t threadid)
{
int ret = 0;
if (0 > pid)
{
// do not execute DB update command with invalid pid
ret = -1;
}
else
{
// we need to type cast values to a "guaranteed" 64 bit value
// because the vararg parser assumes type "long long int" with "%l"
int mystate = state;
int mypid = pid;
long long int mythreadid = threadid;
db_select_parameter(DB_UPDATE_PROCESS_STATE, mystate, mythreadid, mypid);
}
return ret;
}
/* delete prepared statements */
static void db_statements_finalize(void)
{
enum db_select_statement_id i;
for (i=DB_SELECT_ID_NULL; i<DB_SELECT_ID_MAX; i++)
{
sqlite3_stmt *ppstmt = db_prepared_stmt[i];
db_statement_finalize(ppstmt);
db_prepared_stmt[i] = NULL;
}
}
/* called by sqlite3 function sqlite3_log()
*/
static void db_log(void *obsolete, int result, const char *msg)
{
(void)obsolete;
/* TODO documentation says we have to be thread save.
* is it sufficient to rely on printlog(...) ?
*/
debug(1, "SQlite3: retval %d, %s", result, msg);
}
void db_init(void)
{
int retval = sqlite3_config(SQLITE_CONFIG_SERIALIZED);
if (SQLITE_OK != retval)
{
printlog("ERROR: calling sqlite3_config(): %s\n"
"Can not set thread safe access mode\n"
"Did you compile sqlite3 with 'SQLITE_THREADSAFE=1'?", sqlite3_errstr(retval));
qexit(EXIT_FAILURE);
}
retval = sqlite3_config(SQLITE_CONFIG_LOG, db_log, NULL);
if (SQLITE_OK != retval)
{
printlog("ERROR: calling sqlite3_config(): %s\n"
"Can not set db log function", sqlite3_errstr(retval));
qexit(EXIT_FAILURE);
}
retval = sqlite3_initialize();
if (SQLITE_OK != retval)
{
printlog("ERROR: calling sqlite3_initialize(): %s", sqlite3_errstr(retval));
qexit(EXIT_FAILURE);
}
retval = sqlite3_open(":memory:", &dbhandler);
if (SQLITE_OK != retval)
{
printlog("ERROR: calling sqlite3_open(): %s", sqlite3_errstr(retval));
qexit(EXIT_FAILURE);
}
debug(1, "created memory db");
/* initialize the condition variable timeout clock attribute with the same
* value we use in the clock measurements. Else if we don't we have
* different timeout values (clock module <-> pthread condition timeout)
*/
pthread_condattr_t condattr;
retval = pthread_condattr_init(&condattr);
if (retval)
{
errno = retval;
logerror("ERROR: pthread_condattr_init");
qexit(EXIT_FAILURE);
}
retval = pthread_condattr_setclock(&condattr, get_valid_clock_id());
if (retval)
{
errno = retval;
logerror("ERROR: pthread_condattr_setclock() id %d", get_valid_clock_id());
qexit(EXIT_FAILURE);
}
retval = pthread_cond_init(&idle_process_condition, &condattr);
if (retval)
{
errno = retval;
logerror("ERROR: pthread_cond_init");
qexit(EXIT_FAILURE);
}
retval = pthread_condattr_destroy(&condattr);
if (retval)
{
errno = retval;
logerror("ERROR: pthread_condattr_destroy");
qexit(EXIT_FAILURE);
}
/* setup all tables */
db_select_parameter(DB_SELECT_CREATE_PROJECT_TABLE);
db_select_parameter(DB_SELECT_CREATE_PROCESS_TABLE);
/* prepare further statements */
// db_statements_prepare();
}
void db_delete(void)
{
/* remove the projects */
debug(1, "shutdown memory db");
db_statements_finalize();
int retval = sqlite3_close(dbhandler);
if (SQLITE_OK != retval)
{
printlog("ERROR: calling sqlite3_close(): %s", sqlite3_errstr(retval));
qexit(EXIT_FAILURE);
}
dbhandler = NULL;
retval = sqlite3_shutdown();
if (SQLITE_OK != retval)
{
printlog("ERROR: calling sqlite3_shutdown(): %s", sqlite3_errstr(retval));
qexit(EXIT_FAILURE);
}
}
void db_add_project(const char *projname)
{
assert(projname);
db_global_lock();
db_exit_on_error = 1; // exit on error
db_select_parameter(DB_INSERT_PROJECT_DATA, projname);
db_exit_on_error = 0; // reset exit flag
db_global_unlock();
}
int db_get_names_project(char ***projname, int *len)
{
assert(projname);
assert(len);
struct data_s
{
char **array;
int arraysize;
int num;
};
int get_names_list(void *data, int ncol, int *type, union callback_result_t *results, const char**cols)
{
struct data_s *mydata = data;
assert(1 == ncol);
assert(SQLITE_TEXT == type[0]);
char *str = strdup((const char *)results[0].text);
arraycat(&mydata->array, &mydata->arraysize, &mydata->num, &str, sizeof(str));
return 0;
}
struct data_s data = {0};
db_global_lock();
db_select_parameter_callback(DB_SELECT_GET_NAMES_FROM_PROJECT, get_names_list, &data);
db_global_unlock();
debug(1, "select found %d project names", data.num);
*projname = data.array;
*len = data.num;
return 0;
}
void db_free_names_project(char **projname, int len)
{
assert(projname);
assert(len >= 0);
int i;
for (i=0; i<len; i++)
{
free(projname[i]);
}
free(projname);
}
void db_remove_project(const char *projname)
{
assert(projname);
db_global_lock();
db_select_parameter(DB_DELETE_PROJECT_DATA, projname);
db_global_unlock();
}
char *db_get_configpath_from_project(const char *projname)
{
assert(projname);
int get_configpath_from_project(void *data, int ncol, int *type, union callback_result_t *results, const char**cols)
{
const char **path = data;
assert(1 == ncol);
assert(SQLITE_TEXT == type[0]);
*path = strdup((const char *)results[0].text);
return 0;
}
char *ret = NULL;
db_global_lock();
db_select_parameter_callback(DB_SELECT_CONFIGPATH_WITH_PROJECT, get_configpath_from_project, &ret, projname);
db_global_unlock();
debug(1, "returned %s", ret);
return ret;
}