License update
[srvx.git] / src / saxdb.c
1 /* saxdb.c - srvx database manager
2  * Copyright 2002-2004 srvx Development Team
3  *
4  * This file is part of srvx.
5  *
6  * srvx is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with srvx; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
19  */
20
21 #include "conf.h"
22 #include "hash.h"
23 #include "modcmd.h"
24 #include "saxdb.h"
25 #include "timeq.h"
26
27 DECLARE_LIST(int_list, int);
28 DEFINE_LIST(int_list, int);
29
30 struct saxdb {
31     char *name;
32     char *filename;
33     char *mondo_section;
34     saxdb_reader_func_t *reader;
35     saxdb_writer_func_t *writer;
36     unsigned int write_interval;
37     time_t last_write;
38     unsigned int last_write_duration;
39     struct saxdb *prev;
40 };
41
42 struct saxdb_context {
43     FILE *output;
44     unsigned int indent;
45     struct int_list complex;
46     jmp_buf jbuf;
47     /* XXX: If jbuf is ever used, places that use saxdb_open_context() and
48      * saxdb_close_context() must be modified to fill it in */
49 };
50
51 #define COMPLEX(CTX) ((CTX)->complex.used ? ((CTX)->complex.list[(CTX)->complex.used-1]) : 1)
52
53 static struct saxdb *last_db;
54 static struct dict *saxdbs; /* -> struct saxdb */
55 static struct dict *mondo_db;
56 static struct module *saxdb_module;
57
58 static SAXDB_WRITER(saxdb_mondo_writer);
59 static void saxdb_timed_write(void *data);
60
61 static void
62 saxdb_read_db(struct saxdb *db) {
63     struct dict *data;
64
65     assert(db);
66     assert(db->filename);
67     data = parse_database(db->filename);
68     if (!data) return;
69     if (db->writer == saxdb_mondo_writer) {
70         mondo_db = data;
71     } else {
72         db->reader(data);
73         free_database(data);
74     }
75 }
76
77 struct saxdb *
78 saxdb_register(const char *name, saxdb_reader_func_t *reader, saxdb_writer_func_t *writer) {
79     struct saxdb *db;
80     struct dict *conf;
81     int ii;
82     const char *filename = NULL, *str;
83     char conf_path[MAXLEN];
84
85     db = calloc(1, sizeof(*db));
86     db->name = strdup(name);
87     db->reader = reader;
88     db->writer = writer;
89     /* Look up configuration */
90     sprintf(conf_path, "dbs/%s", name);
91     if ((conf = conf_get_data(conf_path, RECDB_OBJECT))) {
92         if ((str = database_get_data(conf, "mondo_section", RECDB_QSTRING))) {
93             db->mondo_section = strdup(str);
94         }
95         str = database_get_data(conf, "frequency", RECDB_QSTRING);
96         db->write_interval = str ? ParseInterval(str) : 1800;
97         filename = database_get_data(conf, "filename", RECDB_QSTRING);
98     } else {
99         db->write_interval = 1800;
100     }
101     /* Schedule database writes */
102     if (db->write_interval && !db->mondo_section) {
103         timeq_add(now + db->write_interval, saxdb_timed_write, db);
104     }
105     /* Insert filename */
106     if (filename) {
107         db->filename = strdup(filename);
108     } else {
109         db->filename = malloc(strlen(db->name)+4);
110         for (ii=0; db->name[ii]; ++ii) db->filename[ii] = tolower(db->name[ii]);
111         strcpy(db->filename+ii, ".db");
112     }
113     /* Read from disk (or mondo DB) */
114     if (db->mondo_section) {
115         if (mondo_db && (conf = database_get_data(mondo_db, db->mondo_section, RECDB_OBJECT))) {
116             db->reader(conf);
117         }
118     } else {
119         saxdb_read_db(db);
120     }
121     /* Remember the database */
122     dict_insert(saxdbs, db->name, db);
123     db->prev = last_db;
124     last_db = db;
125     return db;
126 }
127
128 static int
129 saxdb_write_db(struct saxdb *db) {
130     struct saxdb_context ctx;
131     char tmp_fname[MAXLEN];
132     int res, res2;
133     time_t start, finish;
134
135     assert(db->filename);
136     sprintf(tmp_fname, "%s.new", db->filename);
137     memset(&ctx, 0, sizeof(ctx));
138     ctx.output = fopen(tmp_fname, "w+");
139     int_list_init(&ctx.complex);
140     if (!ctx.output) {
141         log_module(MAIN_LOG, LOG_ERROR, "Unable to write to %s: %s", tmp_fname, strerror(errno));
142         int_list_clean(&ctx.complex);
143         return 1;
144     }
145     start = time(NULL);
146     if ((res = setjmp(ctx.jbuf)) || (res2 = db->writer(&ctx))) {
147         if (res) {
148             log_module(MAIN_LOG, LOG_ERROR, "Exception %d caught while writing to %s", res, tmp_fname);
149         } else {
150             log_module(MAIN_LOG, LOG_ERROR, "Internal error %d while writing to %s", res2, tmp_fname);
151         }
152         int_list_clean(&ctx.complex);
153         fclose(ctx.output);
154         remove(tmp_fname);
155         return 2;
156     }
157     finish = time(NULL);
158     assert(ctx.complex.used == 0);
159     int_list_clean(&ctx.complex);
160     fclose(ctx.output);
161     if (rename(tmp_fname, db->filename) < 0) {
162         log_module(MAIN_LOG, LOG_ERROR, "Unable to rename %s to %s: %s", tmp_fname, db->filename, strerror(errno));
163     }
164     db->last_write = now;
165     db->last_write_duration = finish - start;
166     log_module(MAIN_LOG, LOG_INFO, "Wrote %s database to disk.", db->name);
167     return 0;
168 }
169
170 static void
171 saxdb_timed_write(void *data) {
172     struct saxdb *db = data;
173     saxdb_write_db(db);
174     timeq_add(now + db->write_interval, saxdb_timed_write, db);
175 }
176
177 void
178 saxdb_write(const char *db_name) {
179     struct saxdb *db;
180     db = dict_find(saxdbs, db_name, NULL);
181     if (db) saxdb_write_db(db);
182 }
183
184 void
185 saxdb_write_all(void) {
186     dict_iterator_t it;
187     struct saxdb *db;
188
189     for (it = dict_first(saxdbs); it; it = iter_next(it)) {
190         db = iter_data(it);
191         if (!db->mondo_section) saxdb_write_db(db);
192     }
193 }
194
195 #define saxdb_put_char(DEST, CH)   fputc(CH, (DEST)->output)
196 #define saxdb_put_string(DEST, CH) fputs(CH, (DEST)->output)
197
198 static inline void
199 saxdb_put_nchars(struct saxdb_context *dest, const char *name, int len) {
200     while (len--) {
201         fputc(*name++, dest->output);
202     }
203 }
204
205 static void
206 saxdb_put_qstring(struct saxdb_context *dest, const char *str) {
207     const char *esc;
208
209     assert(str);
210     saxdb_put_char(dest, '"');
211     while ((esc = strpbrk(str, "\\\a\b\t\n\v\f\r\""))) {
212         if (esc != str) saxdb_put_nchars(dest, str, esc-str);
213         saxdb_put_char(dest, '\\');
214         switch (*esc) {
215         case '\a': saxdb_put_char(dest, 'a'); break;
216         case '\b': saxdb_put_char(dest, 'b'); break;
217         case '\t': saxdb_put_char(dest, 't'); break;
218         case '\n': saxdb_put_char(dest, 'n'); break;
219         case '\v': saxdb_put_char(dest, 'v'); break;
220         case '\f': saxdb_put_char(dest, 'f'); break;
221         case '\r': saxdb_put_char(dest, 'r'); break;
222         case '\\': saxdb_put_char(dest, '\\'); break;
223         case '"': saxdb_put_char(dest, '"'); break;
224         }
225         str = esc + 1;
226     }
227     saxdb_put_string(dest, str);
228     saxdb_put_char(dest, '"');
229 }
230
231 #ifndef NDEBUG
232 static void
233 saxdb_pre_object(struct saxdb_context *dest) {
234     unsigned int ii;
235     if (COMPLEX(dest)) {
236         for (ii=0; ii<dest->indent; ++ii) saxdb_put_char(dest, '\t');
237     }
238 }
239 #else
240 #define saxdb_pre_object(DEST) 
241 #endif
242
243 static inline void
244 saxdb_post_object(struct saxdb_context *dest) {
245     saxdb_put_char(dest, ';');
246     saxdb_put_char(dest, COMPLEX(dest) ? '\n' : ' ');
247 }
248
249 void
250 saxdb_start_record(struct saxdb_context *dest, const char *name, int complex) {
251     saxdb_pre_object(dest);
252     saxdb_put_qstring(dest, name);
253     saxdb_put_string(dest, " { ");
254     int_list_append(&dest->complex, complex);
255     if (complex) {
256         dest->indent++;
257         saxdb_put_char(dest, '\n');
258     }
259 }
260
261 void
262 saxdb_end_record(struct saxdb_context *dest) {
263     assert(dest->complex.used > 0);
264     if (COMPLEX(dest)) dest->indent--;
265     saxdb_pre_object(dest);
266     dest->complex.used--;
267     saxdb_put_char(dest, '}');
268     saxdb_post_object(dest);
269 }
270
271 void
272 saxdb_write_string_list(struct saxdb_context *dest, const char *name, struct string_list *list) {
273     unsigned int ii;
274
275     saxdb_pre_object(dest);
276     saxdb_put_qstring(dest, name);
277     saxdb_put_string(dest, " (");
278     if (list->used) {
279         for (ii=0; ii<list->used-1; ++ii) {
280             saxdb_put_qstring(dest, list->list[ii]);
281             saxdb_put_string(dest, ", ");
282         }
283         saxdb_put_qstring(dest, list->list[list->used-1]);
284     }
285     saxdb_put_string(dest, ")");
286     saxdb_post_object(dest);
287 }
288
289 void
290 saxdb_write_string(struct saxdb_context *dest, const char *name, const char *value) {
291     saxdb_pre_object(dest);
292     saxdb_put_qstring(dest, name);
293     saxdb_put_char(dest, ' ');
294     saxdb_put_qstring(dest, value);
295     saxdb_post_object(dest);
296 }
297
298 void
299 saxdb_write_int(struct saxdb_context *dest, const char *name, unsigned long value) {
300     unsigned char buf[16];
301     /* we could optimize this to take advantage of the fact that buf will never need escapes */
302     snprintf(buf, sizeof(buf), "%lu", value);
303     saxdb_write_string(dest, name, buf);
304 }
305
306 static void
307 saxdb_free(void *data) {
308     struct saxdb *db = data;
309     free(db->name);
310     free(db->filename);
311     free(db->mondo_section);
312     free(db);
313 }
314
315 static int
316 saxdb_mondo_read(struct dict *db, struct saxdb *saxdb) {
317     int res;
318     struct dict *subdb;
319
320     if (saxdb->prev && (res = saxdb_mondo_read(db, saxdb->prev))) return res;
321     if (saxdb->mondo_section
322         && (subdb = database_get_data(db, saxdb->mondo_section, RECDB_OBJECT))
323         && (res = saxdb->reader(subdb))) {
324         log_module(MAIN_LOG, LOG_INFO, " mondo section read for %s failed: %d", saxdb->mondo_section, res);
325         return res;
326     }
327     return 0;
328 }
329
330 static SAXDB_READER(saxdb_mondo_reader) {
331     return saxdb_mondo_read(db, last_db);
332 }
333
334 static int
335 saxdb_mondo_write(struct saxdb_context *ctx, struct saxdb *saxdb) {
336     int res;
337     if (saxdb->prev && (res = saxdb_mondo_write(ctx, saxdb->prev))) return res;
338     if (saxdb->mondo_section) {
339         saxdb_start_record(ctx, saxdb->mondo_section, 1);
340         if ((res = saxdb->writer(ctx))) {
341             log_module(MAIN_LOG, LOG_INFO, " mondo section write for %s failed: %d", saxdb->mondo_section, res);
342             return res;
343         }
344         saxdb_end_record(ctx);
345         /* cheat a little here to put a newline between mondo sections */
346         saxdb_put_char(ctx, '\n');
347     }
348     return 0;
349 }
350
351 static SAXDB_WRITER(saxdb_mondo_writer) {
352     return saxdb_mondo_write(ctx, last_db);
353 }
354
355 static MODCMD_FUNC(cmd_write) {
356     struct timeval start, stop;
357     unsigned int ii, written;
358     struct saxdb *db;
359
360     assert(argc >= 2);
361     written = 0;
362     for (ii=1; ii<argc; ++ii) {
363         if (!(db = dict_find(saxdbs, argv[ii], NULL))) {
364             reply("MSG_DB_UNKNOWN", argv[ii]);
365             continue;
366         }
367         if (db->mondo_section) {
368             reply("MSG_DB_IS_MONDO", db->name);
369             continue;
370         }
371         gettimeofday(&start, NULL);
372         if (saxdb_write_db(db)) {
373             reply("MSG_DB_WRITE_ERROR", db->name);
374         } else {
375             gettimeofday(&stop, NULL);
376             stop.tv_sec -= start.tv_sec;
377             stop.tv_usec -= start.tv_usec;
378             if (stop.tv_usec < 0) {
379                 stop.tv_sec -= 1;
380                 stop.tv_usec += 1000000;
381             }
382             reply("MSG_DB_WROTE_DB", db->name, stop.tv_sec, stop.tv_usec);
383             written++;
384         }
385     }
386     return written;
387 }
388
389 static MODCMD_FUNC(cmd_writeall) {
390     struct timeval start, stop;
391
392     gettimeofday(&start, NULL);
393     saxdb_write_all();
394     gettimeofday(&stop, NULL);
395     stop.tv_sec -= start.tv_sec;
396     stop.tv_usec -= start.tv_usec;
397     if (stop.tv_usec < 0) {
398         stop.tv_sec -= 1;
399         stop.tv_usec += 1000000;
400     }
401     reply("MSG_DB_WROTE_ALL", stop.tv_sec, stop.tv_usec);
402     return 1;
403 }
404
405 static MODCMD_FUNC(cmd_stats_databases) {
406     struct helpfile_table tbl;
407     dict_iterator_t it;
408     unsigned int ii;
409
410     tbl.length = dict_size(saxdbs) + 1;
411     tbl.width = 5;
412     tbl.flags = TABLE_NO_FREE;
413     tbl.contents = calloc(tbl.length, sizeof(tbl.contents[0]));
414     tbl.contents[0] = calloc(tbl.width, sizeof(tbl.contents[0][0]));
415     tbl.contents[0][0] = "Database";
416     tbl.contents[0][1] = "Filename/Section";
417     tbl.contents[0][2] = "Interval";
418     tbl.contents[0][3] = "Last Written";
419     tbl.contents[0][4] = "Last Duration";
420     for (ii=1, it=dict_first(saxdbs); it; it=iter_next(it), ++ii) {
421         struct saxdb *db = iter_data(it);
422         char *buf = malloc(INTERVALLEN*3);
423         tbl.contents[ii] = calloc(tbl.width, sizeof(tbl.contents[ii][0]));
424         tbl.contents[ii][0] = db->name;
425         tbl.contents[ii][1] = db->mondo_section ? db->mondo_section : db->filename;
426         if (db->write_interval) {
427             intervalString(buf, db->write_interval);
428         } else {
429             strcpy(buf, "Never");
430         }
431         tbl.contents[ii][2] = buf;
432         if (db->last_write) {
433             intervalString(buf+INTERVALLEN, now - db->last_write);
434             intervalString(buf+INTERVALLEN*2, db->last_write_duration);
435         } else {
436             strcpy(buf+INTERVALLEN, "Never");
437             strcpy(buf+INTERVALLEN*2, "Never");
438         }
439         tbl.contents[ii][3] = buf+INTERVALLEN;
440         tbl.contents[ii][4] = buf+INTERVALLEN*2;
441     }
442     table_send(cmd->parent->bot, user->nick, 0, 0, tbl);
443     free(tbl.contents[0]);
444     for (ii=1; ii<tbl.length; ++ii) {
445         free((char*)tbl.contents[ii][2]);
446         free(tbl.contents[ii]);
447     }
448     free(tbl.contents);
449     return 0;
450 }
451
452 static void
453 saxdb_cleanup(void) {
454     dict_delete(saxdbs);
455 }
456
457 static struct helpfile_expansion
458 saxdb_expand_help(const char *variable) {
459     struct helpfile_expansion exp;
460     if (!strcasecmp(variable, "dblist")) {
461         dict_iterator_t it;
462         struct string_buffer sbuf;
463         struct saxdb *db;
464
465         exp.type = HF_STRING;
466         string_buffer_init(&sbuf);
467         for (it = dict_first(saxdbs); it; it = iter_next(it)) {
468             db = iter_data(it);
469             if (db->mondo_section) continue;
470             if (sbuf.used) string_buffer_append_string(&sbuf, ", ");
471             string_buffer_append_string(&sbuf, iter_key(it));
472         }
473         exp.value.str = sbuf.list;
474     } else {
475         exp.type = HF_STRING;
476         exp.value.str = NULL;
477     }
478     return exp;
479 }
480
481 void
482 saxdb_init(void) {
483     reg_exit_func(saxdb_cleanup);
484     saxdbs = dict_new();
485     dict_set_free_data(saxdbs, saxdb_free);
486     saxdb_register("mondo", saxdb_mondo_reader, saxdb_mondo_writer);
487     saxdb_module = module_register("saxdb", MAIN_LOG, "saxdb.help", saxdb_expand_help);
488     modcmd_register(saxdb_module, "write", cmd_write, 2, MODCMD_REQUIRE_AUTHED, "level", "800", NULL);
489     modcmd_register(saxdb_module, "writeall", cmd_writeall, 0, MODCMD_REQUIRE_AUTHED, "level", "800", NULL);
490     modcmd_register(saxdb_module, "stats databases", cmd_stats_databases, 0, 0, NULL);
491 }
492
493 void
494 saxdb_finalize(void) {
495     free_database(mondo_db);
496 }
497
498 static void
499 write_database_helper(struct saxdb_context *ctx, struct dict *db) {
500     dict_iterator_t it;
501     struct record_data *rd;
502
503     for (it = dict_first(db); it; it = iter_next(it)) {
504         rd = iter_data(it);
505         switch (rd->type) {
506         case RECDB_INVALID: break;
507         case RECDB_QSTRING: saxdb_write_string(ctx, iter_key(it), rd->d.qstring); break;
508         case RECDB_STRING_LIST: saxdb_write_string_list(ctx, iter_key(it), rd->d.slist); break;
509         case RECDB_OBJECT:
510             saxdb_start_record(ctx, iter_key(it), 1);
511             write_database_helper(ctx, rd->d.object);
512             saxdb_end_record(ctx);
513             break;
514         }
515     }
516 }
517
518 int
519 write_database(FILE *out, struct dict *db) {
520     struct saxdb_context ctx;
521     int res;
522
523     ctx.output = out;
524     ctx.indent = 0;
525     int_list_init(&ctx.complex);
526     if (!(res = setjmp(ctx.jbuf))) {
527         write_database_helper(&ctx, db);
528     } else {
529         log_module(MAIN_LOG, LOG_ERROR, "Exception %d caught while writing to stream", res);
530         int_list_clean(&ctx.complex);
531         return 1;
532     }
533     assert(ctx.complex.used == 0);
534     int_list_clean(&ctx.complex);
535     return 0;
536 }
537
538 struct saxdb_context *
539 saxdb_open_context(FILE *file) {
540     struct saxdb_context *ctx;
541
542     assert(file);
543     ctx = calloc(1, sizeof(*ctx));
544     ctx->output = file;
545     int_list_init(&ctx->complex);
546
547     return ctx;
548 }
549
550 void
551 saxdb_close_context(struct saxdb_context *ctx) {
552     assert(ctx->complex.used == 0);
553     int_list_clean(&ctx->complex);
554     free(ctx);
555 }