]> git.itanic.dy.fi Git - rrdd/blob - rrdtool.c
onewire_parser.c: Fix compiler warnings about string lengths
[rrdd] / rrdtool.c
1 #include <time.h>
2
3 #include <sys/types.h>
4 #include <sys/stat.h>
5 #include <fcntl.h>
6 #include <unistd.h>
7 #include <string.h>
8
9 #include "rrdtool.h"
10 #include "process.h"
11 #include "parser.h"
12 #include "debug.h"
13 #include "string.h"
14 #include "utils.h"
15
16 #define MAX_ARGS        512
17 #define ARGSTR_LEN      32768
18
19 #define RRDTOOL_CMD "/usr/bin/rrdtool"
20
21 /*
22  * Add new argument to a argument list
23  *
24  * args         pointer list to arguments
25  * argcnt       argument counter
26  * argstr       array where the actual arguments are stored
27  * idx          index in the argstr where the new argument will be appended
28  */
29 #define add_arg(args, argcnt, argstr, idx, fmt, arg...) \
30         args[argcnt] = argstr + idx;                    \
31         idx += sprintf(argstr + idx, fmt, ##arg);       \
32         argcnt++;                                       \
33         args[argcnt] = 0;                               \
34         argstr[++idx] = 0
35
36 int rrdtool_draw_image(struct rrd_image *image)
37 {
38         char cmd[] = RRDTOOL_CMD;
39 //      char cmd[] = "echo";
40         char *args[512], argstr[ARGSTR_LEN];
41         int idx = 0, argcnt = 0, i,j;
42         char timestamp[256];
43         char tmp[sizeof(timestamp)];
44         char tmpfile[256];
45         time_t t = time(0);
46         const char *updatestr = "Last update %d.%m.%Y %T (%Z)";
47
48         pr_info("Drawing image %s\n", image->image_filename);
49
50         tmpfile[0] = 0;
51         tmp[0] = 0;
52         strncpy(tmpfile, image->image_filename, sizeof(tmpfile) - 1);
53         _strlcat(tmpfile, ".tmp", sizeof(tmpfile));
54
55         if (image->updatestr)
56                 updatestr = image->updatestr;
57
58         strftime(tmp, sizeof(tmp), updatestr, localtime(&t));
59         for (i = 0, j = 0; j < sizeof(tmp);) {
60                 if (tmp[i] == ':') {
61                         timestamp[j++] = '\\';
62                 }
63                 timestamp[j++] = tmp[i++];
64                 if (!tmp[i])
65                         break;
66         }
67         timestamp[j] = 0;
68
69
70         add_arg(args, argcnt, argstr, idx, RRDTOOL_CMD);
71         add_arg(args, argcnt, argstr, idx, "graph");
72         add_arg(args, argcnt, argstr, idx, "%s", tmpfile);
73
74         add_arg(args, argcnt, argstr, idx, "--start");
75         add_arg(args, argcnt, argstr, idx, "%s", image->timestart);
76         add_arg(args, argcnt, argstr, idx, "--end");
77         add_arg(args, argcnt, argstr, idx, "%s", image->timeend);
78         add_arg(args, argcnt, argstr, idx, "--width");
79         add_arg(args, argcnt, argstr, idx, "%d", image->width);
80         add_arg(args, argcnt, argstr, idx, "--height");
81         add_arg(args, argcnt, argstr, idx, "%d", image->height);
82         add_arg(args, argcnt, argstr, idx, "--imgformat");
83         add_arg(args, argcnt, argstr, idx, "%s", image->imageformat);
84
85         for (i = 0; image->options[i]; i++) {
86                 add_arg(args, argcnt, argstr, idx, "%s", image->options[i]);
87         }
88
89         for (i = 0; image->text[i]; i++) {
90                 args[argcnt++] = (char *)image->text[i];
91         }
92
93         add_arg(args, argcnt, argstr, idx, "COMMENT: %s\\c", timestamp);
94
95         run(cmd, args);
96
97         rename(tmpfile, image->image_filename);
98
99         return 0;
100 }
101
102 int rrdtool_draw_images(struct rrd_image **image)
103 {
104         int i;
105         for (i = 0; image[i]; i++)
106                 queue_work(WORK_PRIORITY_LOW, "rrdtool_draw_image",
107                         (work_fn_t *)rrdtool_draw_image, image[i]);
108
109         return 0;
110 }
111
112 static int sanitize_rrd_update_data(char *data)
113 {
114         char clean_data[RRD_DATA_MAX_LEN];
115         int entries = 0;
116         int minus;
117         char *src, *end, *cln;
118
119         data[RRD_DATA_MAX_LEN - 1] = 0;
120         src = data;
121         cln = clean_data;
122
123         /*
124          * Copy a legit floating point number to clean_data buffer
125          * starting from *src and ending to next ':'. If no legit
126          * number could be found, put a 'U' there instead to make
127          * rrdtool to understand this datapoint is undefined.
128          */
129
130         while (src < data + RRD_DATA_MAX_LEN && *src) {
131                 minus = 0;
132
133                 /* skip any non_numbers but not ':' */
134                 while (*src && !isdigit(*src) && *src != '-' && *src != ':')
135                         src++;
136
137                 if (*src == '-') {
138                         src++;
139                         minus = 1;
140                 }
141
142                 /* Now find the end of the number */
143                 end = skip_numbers(src);
144
145                 /* Floating point numberrs may have a dot with more numbers */
146                 if (*end == '.') {
147                         end++;
148                         end = skip_numbers(end);
149                 }
150
151                 /*
152                  * Now we have gone past the number, there should be a
153                  * colon or zero byte. If src == end, there was no
154                  * number and the entry is undefined instead.
155                  */
156                 if ((*end == ':' || !*end) && src != end) {
157                         if (minus) {
158                                 *cln = '-';
159                                 cln++;
160                         }
161
162                         /*
163                          * Copy the legit number and start copying the
164                          * next one
165                          */
166                         for (; src <= end; src++, cln++)
167                                 *cln = *src;
168
169                         goto next;
170                 }
171
172                 /* Skip over whatever junk there might be */
173                 while (*end != ':' && *end)
174                         end++;
175
176                 /* Mark the entry as undefined */
177                 *cln = 'U';
178                 cln++;
179                 *cln = ':';
180                 cln++;
181         next:
182                 end++;
183                 src = end;
184                 entries++;
185         }
186
187         /*
188          * If last entry was undefined, we need to remove the extra
189          * colon at the end
190          */
191         if (*(cln - 1) == ':')
192                 cln--;
193         *cln = '\0';
194
195         strncpy(data, clean_data, RRD_DATA_MAX_LEN);
196         return entries;
197 }
198
199 static int write_to_logfile(struct rrd_database *rrd, const char *data, time_t now)
200 {
201         int fd, ret;
202         int spacing, i;
203         char filename[1024];
204         char logstr[RRD_DATA_MAX_LEN * 2] = { 0 };
205         const char *time_stamp_fmt = "%Y.%m.%d %H:%M ";
206         char *str_ptr;
207
208         if (!rrd->logfile)
209                 return 0;
210
211         if (rrd->logfile_timestamp_fmt)
212                 time_stamp_fmt = rrd->logfile_timestamp_fmt;
213
214         strftime(filename, sizeof(filename), rrd->logfile, localtime(&now));
215
216         fd = open(filename, O_RDWR | O_APPEND | O_CREAT | O_CLOEXEC, 0644);
217         if (fd < 0) {
218                 pr_err("Failed to open file %s for logging: %m\n", filename);
219                 return -1;
220         }
221
222         strftime(logstr, sizeof(logstr), time_stamp_fmt, localtime(&now));
223
224         str_ptr = logstr + strlen(logstr);
225
226         /* Skip the "N: part */
227         while (*data != ':')
228                 data++;
229         data++;
230
231         spacing = 12;
232
233         while (*data && str_ptr - logstr < sizeof(logstr) - 1) {
234                 if (*data == ':') {
235                         *str_ptr++ = ' ';
236                         for (i = 0; i < spacing; i++)
237                                 *str_ptr++ = ' ';
238                         spacing = 12;
239                         data++;
240                         continue;
241                 }
242
243                 *str_ptr++ = *data++;
244                 spacing--;
245         }
246         *str_ptr++ = '\n';
247         *str_ptr++ = 0;
248
249         ret = write(fd, logstr, strlen(logstr));
250         if (ret < 0)
251                 pr_err("Failed to write to logfile %s: %m\n", filename);
252
253         close(fd);
254
255         return ret < 0 ? ret : 0;
256 }
257
258 static int run_post_draw_cmd(struct rrd_database *rrd)
259 {
260         pr_info("Running post draw command for %s\n", rrd->name);
261
262         if (rrd->post_draw_cmd && !strcmp(rrd->post_draw_cmd[0], "shell"))
263                 run(rrd->post_draw_cmd[1], &rrd->post_draw_cmd[1]);
264
265         return 0;
266 }
267
268 static int rrdtool_update_data_multi(struct rrd_database *rrd)
269 {
270         char **data = NULL;
271         int ret, i, d;
272         char cmd[] = RRDTOOL_CMD;
273         char *cmdline[512] = {
274                 RRDTOOL_CMD,
275                 "update",
276                 (char *const)rrd->filename,
277         };
278         int old_last_update = rrd->last_update;
279         time_t now = time(NULL);
280
281         ret = rrd->parser->parse_multi(&data, rrd->parser_data,
282                                 &rrd->parser_state, rrd->last_update);
283         if (ret < 0) {
284                 pr_err("Parser failure: %d\n", ret);
285                 goto out;
286         }
287
288         for (i = 3, d = 0; i < ARRAY_SIZE(cmdline) - 1; d++) {
289                 time_t then;
290
291                 if (!data[d])
292                         break;
293
294                 sanitize_rrd_update_data(data[d]);
295
296                 then = atoi(data[d]);
297                 if (then > now) {
298                         pr_err("Skipping bad data with timestamp in future: %ld > %ld\n",
299                                 then, now);
300                         continue;
301                 }
302                 write_to_logfile(rrd, data[d], then);
303                 cmdline[i] = data[d];
304                 pr_info("Data: %s\n", data[d]);
305
306                 rrd->last_update = then;
307                 i++;
308         }
309
310         cmdline[i] = 0;
311
312         if (ret)
313                 run(cmd, cmdline);
314
315 out:
316         if (data)
317                 for (d = 0; data[d]; d++)
318                         free(data[d]);
319         free(data);
320
321         if (old_last_update == rrd->last_update) {
322                 rrd->update_backoff = time(NULL) + 10;
323                 pr_info("Setting backoff\n");
324         } else
325                 rrd->update_backoff = 0;
326
327         /*
328          * Re-schedule job processing in case we are too far behind
329          * with updates on this database and can start parsing more
330          * data immediately.
331          */
332         notify_job_request();
333
334         return 0;
335 }
336
337 static int do_rrdtool_update_data(struct rrd_database *rrd)
338 {
339         char data[RRD_DATA_MAX_LEN + 12]; /* 12 == "%s:" + NULL termination */
340         char cmd[] = RRDTOOL_CMD;
341 //      char cmd[] = "echo";
342         char *const cmdline[] = {
343                 RRDTOOL_CMD,
344                 "update",
345                 (char *const)rrd->filename,
346                 data,
347                 0
348         };
349         int l;
350         time_t now = time(NULL);
351
352         bzero(data, sizeof(data));
353         l = sprintf(data, "%zd:", now);
354
355         if (rrd->parser && rrd->parser->parse_multi) {
356                 rrdtool_update_data_multi(rrd);
357         } else if (rrd->parser && rrd->parser->parse) {
358                 rrd->parser->parse(data + l, rrd->parser_data,
359                                 &rrd->parser_state);
360                 data[RRD_DATA_MAX_LEN + l] = '\0';
361
362                 pr_info("Data: %s\n", data);
363
364                 sanitize_rrd_update_data(data + l);
365                 write_to_logfile(rrd, data, now);
366
367                 run(cmd, cmdline);
368                 rrd->last_update = now;
369         } else
370                 rrd->last_update = now;
371
372         if (rrd->pre_draw_cmd && !strcmp(rrd->pre_draw_cmd[0], "shell")) {
373                 run(rrd->pre_draw_cmd[1], &rrd->pre_draw_cmd[1]);
374         }
375
376         if (rrd->images)
377                 rrdtool_draw_images(rrd->images);
378
379         /*
380          * We rely on the fact that rrdtool_draw_images queues image
381          * drawings into low priority queue and the post draw queue is
382          * placed on the queue after images. This ensures post draw
383          * command is not started before images are started.
384          *
385          * There is nothing that guarantees post_draw_cmd is executed
386          * after all images are completed though, but it's close..
387          */
388         if (rrd->post_draw_cmd)
389                 queue_work(WORK_PRIORITY_LOW, "rrdtool_post_draw_cmd",
390                         (work_fn_t *)run_post_draw_cmd, rrd);
391
392         rrd->update_active = 0;
393
394         return 0;
395 }
396
397 int rrdtool_update_data(struct rrd_database *rrd)
398 {
399         rrd->update_active = 1;
400
401         return queue_work(WORK_PRIORITY_HIGH, "rrdtool_update_data",
402                         (work_fn_t *)do_rrdtool_update_data, rrd);
403 }
404
405 /*
406  * Walk through the database list and return the first database which
407  * last update is too far in past
408  */
409 struct rrd_database *get_outdated_db(struct rrd_database **dblist)
410 {
411         int i;
412         time_t now = time(0), last;
413
414         for (i = 0; dblist[i]; i++) {
415                 last = max(ROUND_UP(dblist[i]->last_update, dblist[i]->interval),
416                         dblist[i]->update_backoff);
417                 if (!dblist[i]->update_active && last - now <= 0)
418                         return dblist[i];
419         }
420
421         /* Nothing to update this time, return null */
422         return NULL;
423 }
424
425 /*
426  * See how long we may sleep until next update interval window begins
427  */
428 int get_next_update(struct rrd_database **dblist, const char **name)
429 {
430         int i, sleeptime = -1, diff;
431         time_t now = time(0);
432
433         for (i = 0; dblist[i]; i++) {
434                 if (dblist[i]->update_active)
435                         continue;
436
437                 diff = ROUND_UP(dblist[i]->last_update, dblist[i]->interval) - now;
438                 diff = max(diff, dblist[i]->update_backoff - now);
439
440                 if (sleeptime == -1 || sleeptime > diff) {
441                         sleeptime = diff;
442                         *name = dblist[i]->name;
443                 }
444         }
445
446         return sleeptime;
447 }
448
449 static int database_exists(struct rrd_database *db)
450 {
451         struct stat s;
452
453         /* If the filename exists, stat will return zero */
454         if (db->filename)
455                 return !stat(db->filename, &s);
456
457         return 0;
458 }
459
460 static int get_last_update(struct rrd_database *db)
461 {
462         char cmd[] = RRDTOOL_CMD;
463         char *args[10], argstr[ARGSTR_LEN];
464         char buf[16];
465         int idx = 0, argcnt = 0;
466         int ofd, child;
467         int ret;
468
469         add_arg(args, argcnt, argstr, idx, RRDTOOL_CMD);
470         add_arg(args, argcnt, argstr, idx, "last");
471         add_arg(args, argcnt, argstr, idx, db->filename);
472
473         child = run_piped(cmd, args, NULL, &ofd, NULL);
474         ret = read(ofd, buf, sizeof(buf) - 1);
475         if (ret < 0) {
476                 pr_err("Error reading: %m\n");
477                 buf[0] = 0;
478         } else {
479                 buf[ret] = 0;
480         }
481
482         db->last_update = atoi(buf);
483         pr_info("Last update for %s is: %ld, %ld sec ago\n", db->name, db->last_update,
484                 time(NULL) - db->last_update);
485
486         close(ofd);
487         clear_zombie(child);
488
489         return 0;
490 }
491
492 static int create_database(struct rrd_database *db)
493 {
494         char cmd[] = RRDTOOL_CMD;
495 //      char cmd[] = "echo";
496         char *args[512], argstr[ARGSTR_LEN];
497         int idx = 0, argcnt = 0;
498         int i;
499
500         if (!db->filename) {
501                 pr_err("Database %s missing database filename\n", db->name);
502                 return -1;
503         }
504
505         if (!db->sources || !db->archives) {
506                 pr_err("Cannot create db \"%s\", insufficient source data\n",
507                         db->filename);
508                 return -1;
509         }
510
511         add_arg(args, argcnt, argstr, idx, RRDTOOL_CMD);
512         add_arg(args, argcnt, argstr, idx, "create");
513         add_arg(args, argcnt, argstr, idx, "%s", db->filename);
514         add_arg(args, argcnt, argstr, idx, "--step");
515         add_arg(args, argcnt, argstr, idx, "%d", db->interval);
516
517         for (i = 0; db->sources[i].type; i++) {
518                 add_arg(args, argcnt, argstr, idx, "DS:%s:%s:%d:%f:%f",
519                         db->sources[i].name,
520                         db->sources[i].type,
521                         db->sources[i].heartbeat,
522                         db->sources[i].min,
523                         db->sources[i].max);
524         }
525
526         for (i = 0; db->archives[i].type; i++) {
527                 add_arg(args, argcnt, argstr, idx, "RRA:%s:%f:%d:%d",
528                         db->archives[i].type,
529                         db->archives[i].xff,
530                         db->archives[i].steps,
531                         db->archives[i].rows);
532         }
533
534         run(cmd, args);
535
536         return 0;
537 }
538
539 int rrdtool_create_missing_databases(struct rrd_database *dbs[])
540 {
541         struct rrd_database *db;
542         int i, ret = 0;
543
544         for (i = 0, db = dbs[i]; db; i++, db = dbs[i]) {
545                 if (database_exists(db)) {
546                         pr_info("database %s found\n", db->filename);
547                         get_last_update(db);
548                         continue;
549                 }
550                 pr_info("Database %s missing, creating\n", db->filename);
551                 ret |= create_database(db);
552         }
553
554         return ret;
555 }