src/rrd_flush.c: Add the `flush' command to the `rrdtool' application.
[rrdtool.git] / src / rrd_tool.c
1 /*****************************************************************************
2  * RRDtool 1.3.0  Copyright by Tobi Oetiker, 1997-2008
3  *****************************************************************************
4  * rrd_tool.c  Startup wrapper
5  *****************************************************************************/
6
7 #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__CYGWIN32__) && !defined(HAVE_CONFIG_H)
8 #include "../win32/config.h"
9 #else
10 #ifdef HAVE_CONFIG_H
11 #include "../rrd_config.h"
12 #endif
13 #endif
14
15 #include "rrd_tool.h"
16 #include "rrd_xport.h"
17 #include "rrd_i18n.h"
18
19 #ifdef HAVE_LOCALE_H
20 #include <locale.h>
21 #endif
22
23 void      PrintUsage(
24     char *cmd);
25 int       CountArgs(
26     char *aLine);
27 int       CreateArgs(
28     char *,
29     char *,
30     int,
31     char **);
32 int       HandleInputLine(
33     int,
34     char **,
35     FILE *);
36 int       RemoteMode = 0;
37 int       ChangeRoot = 0;
38
39 #define TRUE            1
40 #define FALSE           0
41 #define MAX_LENGTH      10000
42
43
44 void PrintUsage(
45     char *cmd)
46 {
47
48     const char *help_main =
49         N_("RRDtool %s"
50            "  Copyright 1997-2008 by Tobias Oetiker <tobi@oetiker.ch>\n"
51            "               Compiled %s %s\n\n"
52            "Usage: rrdtool [options] command command_options\n\n");
53
54     const char *help_list =
55         N_
56         ("Valid commands: create, update, updatev, graph, graphv,  dump, restore,\n"
57          "\t\tlast, lastupdate, first, info, fetch, tune,\n"
58          "\t\tresize, xport, flush\n\n");
59
60     const char *help_listremote =
61         N_("Valid remote commands: quit, ls, cd, mkdir, pwd\n\n");
62
63
64     const char *help_create =
65         N_("* create - create a new RRD\n\n"
66            "\trrdtool create filename [--start|-b start time]\n"
67            "\t\t[--step|-s step]\n"
68            "\t\t[DS:ds-name:DST:dst arguments]\n"
69            "\t\t[RRA:CF:cf arguments]\n\n");
70
71     const char *help_dump =
72         N_("* dump - dump an RRD to XML\n\n"
73            "\trrdtool dump filename.rrd >filename.xml\n\n");
74
75     const char *help_info =
76         N_("* info - returns the configuration and status of the RRD\n\n"
77            "\trrdtool info filename.rrd\n\n");
78
79     const char *help_restore =
80         N_("* restore - restore an RRD file from its XML form\n\n"
81            "\trrdtool restore [--range-check|-r] [--force-overwrite|-f] filename.xml filename.rrd\n\n");
82
83     const char *help_last =
84         N_("* last - show last update time for RRD\n\n"
85            "\trrdtool last filename.rrd\n\n");
86
87     const char *help_lastupdate =
88         N_("* lastupdate - returns the most recent datum stored for\n"
89            "  each DS in an RRD\n\n" "\trrdtool lastupdate filename.rrd\n\n");
90
91     const char *help_first =
92         N_("* first - show first update time for RRA within an RRD\n\n"
93            "\trrdtool first filename.rrd [--rraindex number]\n\n");
94
95     const char *help_update =
96         N_("* update - update an RRD\n\n"
97            "\trrdtool update filename\n"
98            "\t\t[--template|-t ds-name:ds-name:...]\n"
99            "\t\t[--daemon <address>]\n"
100            "\t\ttime|N:value[:value...]\n\n"
101            "\t\tat-time@value[:value...]\n\n"
102            "\t\t[ time:value[:value...] ..]\n\n");
103
104     const char *help_updatev =
105         N_("* updatev - a verbose version of update\n"
106            "\treturns information about values, RRAs, and datasources updated\n\n"
107            "\trrdtool updatev filename\n"
108            "\t\t[--template|-t ds-name:ds-name:...]\n"
109            "\t\ttime|N:value[:value...]\n\n"
110            "\t\tat-time@value[:value...]\n\n"
111            "\t\t[ time:value[:value...] ..]\n\n");
112
113     const char *help_fetch =
114         N_("* fetch - fetch data out of an RRD\n\n"
115            "\trrdtool fetch filename.rrd CF\n"
116            "\t\t[-r|--resolution resolution]\n"
117            "\t\t[-s|--start start] [-e|--end end]\n"
118            "\t\t[--daemon <address>]\n\n");
119
120     const char *help_flush =
121         N_("* flush - flush cached data out to an RRD file\n\n"
122            "\trrdtool flush filename.rrd\n"
123            "\t\t[--daemon <address>]\n\n");
124
125 /* break up very large strings (help_graph, help_tune) for ISO C89 compliance*/
126
127     const char *help_graph0 =
128         N_("* graph - generate a graph from one or several RRD\n\n"
129            "\trrdtool graph filename [-s|--start seconds] [-e|--end seconds]\n");
130     const char *help_graphv0 =
131         N_("* graphv - generate a graph from one or several RRD\n"
132            "           with meta data printed before the graph\n\n"
133            "\trrdtool graphv filename [-s|--start seconds] [-e|--end seconds]\n");
134     const char *help_graph1 =
135         N_("\t\t[-x|--x-grid x-axis grid and label]\n"
136            "\t\t[-Y|--alt-y-grid]\n"
137            "\t\t[-y|--y-grid y-axis grid and label]\n"
138            "\t\t[-v|--vertical-label string] [-w|--width pixels]\n"
139            "\t\t[-h|--height pixels] [-o|--logarithmic]\n"
140            "\t\t[-u|--upper-limit value] [-z|--lazy]\n"
141            "\t\t[-l|--lower-limit value] [-r|--rigid]\n"
142            "\t\t[-g|--no-legend] [--daemon <address>]\n"
143            "\t\t[-F|--force-rules-legend]\n" "\t\t[-j|--only-graph]\n");
144     const char *help_graph2 =
145         N_("\t\t[-n|--font FONTTAG:size:font]\n"
146            "\t\t[-m|--zoom factor]\n"
147            "\t\t[-A|--alt-autoscale]\n"
148            "\t\t[-M|--alt-autoscale-max]\n"
149            "\t\t[-R|--font-render-mode {normal,light,mono}]\n"
150            "\t\t[-B|--font-smoothing-threshold size]\n"
151            "\t\t[-T|--tabwidth width]\n"
152            "\t\t[-E|--slope-mode]\n"
153            "\t\t[-N|--no-gridfit]\n"
154            "\t\t[-X|--units-exponent value]\n"
155            "\t\t[-L|--units-length value]\n"
156            "\t\t[-S|--step seconds]\n"
157            "\t\t[-f|--imginfo printfstr]\n"
158            "\t\t[-a|--imgformat PNG]\n"
159            "\t\t[-c|--color COLORTAG#rrggbb[aa]] [-t|--title string]\n"
160            "\t\t[-W|--watermark string]\n"
161            "\t\t[DEF:vname=rrd:ds-name:CF]\n");
162     const char *help_graph3 =
163         N_("\t\t[CDEF:vname=rpn-expression]\n"
164            "\t\t[VDEF:vdefname=rpn-expression]\n"
165            "\t\t[PRINT:vdefname:format]\n"
166            "\t\t[GPRINT:vdefname:format]\n" "\t\t[COMMENT:text]\n"
167            "\t\t[SHIFT:vname:offset]\n"
168            "\t\t[TICK:vname#rrggbb[aa][:[fraction][:legend]]]\n"
169            "\t\t[HRULE:value#rrggbb[aa][:legend]]\n"
170            "\t\t[VRULE:value#rrggbb[aa][:legend]]\n"
171            "\t\t[LINE[width]:vname[#rrggbb[aa][:[legend][:STACK]]]]\n"
172            "\t\t[AREA:vname[#rrggbb[aa][:[legend][:STACK]]]]\n"
173            "\t\t[PRINT:vname:CF:format] (deprecated)\n"
174            "\t\t[GPRINT:vname:CF:format] (deprecated)\n"
175            "\t\t[STACK:vname[#rrggbb[aa][:legend]]] (deprecated)\n\n");
176     const char *help_tune1 =
177         N_(" * tune -  Modify some basic properties of an RRD\n\n"
178            "\trrdtool tune filename\n"
179            "\t\t[--heartbeat|-h ds-name:heartbeat]\n"
180            "\t\t[--data-source-type|-d ds-name:DST]\n"
181            "\t\t[--data-source-rename|-r old-name:new-name]\n"
182            "\t\t[--minimum|-i ds-name:min] [--maximum|-a ds-name:max]\n"
183            "\t\t[--deltapos scale-value] [--deltaneg scale-value]\n"
184            "\t\t[--failure-threshold integer]\n"
185            "\t\t[--window-length integer]\n"
186            "\t\t[--alpha adaptation-parameter]\n");
187     const char *help_tune2 =
188         N_(" * tune -  Modify some basic properties of an RRD\n\n"
189            "\t\t[--beta adaptation-parameter]\n"
190            "\t\t[--gamma adaptation-parameter]\n"
191            "\t\t[--gamma-deviation adaptation-parameter]\n"
192            "\t\t[--aberrant-reset ds-name]\n\n");
193     const char *help_resize =
194         N_
195         (" * resize - alter the length of one of the RRAs in an RRD\n\n"
196          "\trrdtool resize filename rranum GROW|SHRINK rows\n\n");
197     const char *help_xport =
198         N_("* xport - generate XML dump from one or several RRD\n\n"
199            "\trrdtool xport [-s|--start seconds] [-e|--end seconds]\n"
200            "\t\t[-m|--maxrows rows]\n" "\t\t[--step seconds]\n"
201            "\t\t[--enumds]\n" "\t\t[DEF:vname=rrd:ds-name:CF]\n"
202            "\t\t[CDEF:vname=rpn-expression]\n"
203            "\t\t[XPORT:vname:legend]\n\n");
204     const char *help_quit =
205         N_(" * quit - closing a session in remote mode\n\n"
206            "\trrdtool quit\n\n");
207     const char *help_ls =
208         N_(" * ls - lists all *.rrd files in current directory\n\n"
209            "\trrdtool ls\n\n");
210     const char *help_cd =
211         N_(" * cd - changes the current directory\n\n"
212            "\trrdtool cd new directory\n\n");
213     const char *help_mkdir =
214         N_(" * mkdir - creates a new directory\n\n"
215            "\trrdtool mkdir newdirectoryname\n\n");
216     const char *help_pwd =
217         N_(" * pwd - returns the current working directory\n\n"
218            "\trrdtool pwd\n\n");
219     const char *help_lic =
220         N_("RRDtool is distributed under the Terms of the GNU General\n"
221            "Public License Version 2. (www.gnu.org/copyleft/gpl.html)\n\n"
222            "For more information read the RRD manpages\n\n");
223     enum { C_NONE, C_CREATE, C_DUMP, C_INFO, C_RESTORE, C_LAST,
224         C_LASTUPDATE, C_FIRST, C_UPDATE, C_FETCH, C_GRAPH, C_GRAPHV,
225         C_TUNE,
226         C_RESIZE, C_XPORT, C_QUIT, C_LS, C_CD, C_MKDIR, C_PWD,
227         C_UPDATEV, C_FLUSH
228     };
229     int       help_cmd = C_NONE;
230
231     if (cmd) {
232         if (!strcmp(cmd, "create"))
233             help_cmd = C_CREATE;
234         else if (!strcmp(cmd, "dump"))
235             help_cmd = C_DUMP;
236         else if (!strcmp(cmd, "info"))
237             help_cmd = C_INFO;
238         else if (!strcmp(cmd, "restore"))
239             help_cmd = C_RESTORE;
240         else if (!strcmp(cmd, "last"))
241             help_cmd = C_LAST;
242         else if (!strcmp(cmd, "lastupdate"))
243             help_cmd = C_LASTUPDATE;
244         else if (!strcmp(cmd, "first"))
245             help_cmd = C_FIRST;
246         else if (!strcmp(cmd, "update"))
247             help_cmd = C_UPDATE;
248         else if (!strcmp(cmd, "updatev"))
249             help_cmd = C_UPDATEV;
250         else if (!strcmp(cmd, "fetch"))
251             help_cmd = C_FETCH;
252         else if (!strcmp(cmd, "flush"))
253             help_cmd = C_FLUSH;
254         else if (!strcmp(cmd, "graph"))
255             help_cmd = C_GRAPH;
256         else if (!strcmp(cmd, "graphv"))
257             help_cmd = C_GRAPHV;
258         else if (!strcmp(cmd, "tune"))
259             help_cmd = C_TUNE;
260         else if (!strcmp(cmd, "resize"))
261             help_cmd = C_RESIZE;
262         else if (!strcmp(cmd, "xport"))
263             help_cmd = C_XPORT;
264         else if (!strcmp(cmd, "quit"))
265             help_cmd = C_QUIT;
266         else if (!strcmp(cmd, "ls"))
267             help_cmd = C_LS;
268         else if (!strcmp(cmd, "cd"))
269             help_cmd = C_CD;
270         else if (!strcmp(cmd, "mkdir"))
271             help_cmd = C_MKDIR;
272         else if (!strcmp(cmd, "pwd"))
273             help_cmd = C_PWD;
274     }
275     fprintf(stdout, _(help_main), PACKAGE_VERSION, __DATE__, __TIME__);
276     fflush(stdout);
277     switch (help_cmd) {
278     case C_NONE:
279         fputs(_(help_list), stdout);
280         if (RemoteMode) {
281             fputs(_(help_listremote), stdout);
282         }
283         break;
284     case C_CREATE:
285         fputs(_(help_create), stdout);
286         break;
287     case C_DUMP:
288         fputs(_(help_dump), stdout);
289         break;
290     case C_INFO:
291         fputs(_(help_info), stdout);
292         break;
293     case C_RESTORE:
294         fputs(_(help_restore), stdout);
295         break;
296     case C_LAST:
297         fputs(_(help_last), stdout);
298         break;
299     case C_LASTUPDATE:
300         fputs(_(help_lastupdate), stdout);
301         break;
302     case C_FIRST:
303         fputs(_(help_first), stdout);
304         break;
305     case C_UPDATE:
306         fputs(_(help_update), stdout);
307         break;
308     case C_UPDATEV:
309         fputs(_(help_updatev), stdout);
310         break;
311     case C_FETCH:
312         fputs(_(help_fetch), stdout);
313         break;
314     case C_FLUSH:
315         fputs(_(help_flush), stdout);
316         break;
317     case C_GRAPH:
318         fputs(_(help_graph0), stdout);
319         fputs(_(help_graph1), stdout);
320         fputs(_(help_graph2), stdout);
321         fputs(_(help_graph3), stdout);
322         break;
323     case C_GRAPHV:
324         fputs(_(help_graphv0), stdout);
325         fputs(_(help_graph1), stdout);
326         fputs(_(help_graph2), stdout);
327         fputs(_(help_graph3), stdout);
328         break;
329     case C_TUNE:
330         fputs(_(help_tune1), stdout);
331         fputs(_(help_tune2), stdout);
332         break;
333     case C_RESIZE:
334         fputs(_(help_resize), stdout);
335         break;
336     case C_XPORT:
337         fputs(_(help_xport), stdout);
338         break;
339     case C_QUIT:
340         fputs(_(help_quit), stdout);
341         break;
342     case C_LS:
343         fputs(_(help_ls), stdout);
344         break;
345     case C_CD:
346         fputs(_(help_cd), stdout);
347         break;
348     case C_MKDIR:
349         fputs(_(help_mkdir), stdout);
350         break;
351     case C_PWD:
352         fputs(_(help_pwd), stdout);
353         break;
354     }
355     fputs(_(help_lic), stdout);
356 }
357
358 static char *fgetslong(
359     char **aLinePtr,
360     FILE * stream)
361 {
362     char     *linebuf;
363     size_t    bufsize = MAX_LENGTH;
364     int       eolpos = 0;
365
366     if (feof(stream))
367         return *aLinePtr = 0;
368     if (!(linebuf = malloc(bufsize))) {
369         perror("fgetslong: malloc");
370         exit(1);
371     }
372     linebuf[0] = '\0';
373     while (fgets(linebuf + eolpos, MAX_LENGTH, stream)) {
374         eolpos += strlen(linebuf + eolpos);
375         if (linebuf[eolpos - 1] == '\n')
376             return *aLinePtr = linebuf;
377         bufsize += MAX_LENGTH;
378         if (!(linebuf = realloc(linebuf, bufsize))) {
379             perror("fgetslong: realloc");
380             exit(1);
381         }
382     }
383     return *aLinePtr = linebuf[0] ? linebuf : 0;
384 }
385
386 int main(
387     int argc,
388     char *argv[])
389 {
390     char    **myargv;
391     char     *aLine;
392     char     *firstdir = "";
393
394 #ifdef MUST_DISABLE_SIGFPE
395     signal(SIGFPE, SIG_IGN);
396 #endif
397 #ifdef MUST_DISABLE_FPMASK
398     fpsetmask(0);
399 #endif
400 #ifdef HAVE_LOCALE_H
401     setlocale(LC_ALL, "");
402 #endif
403
404 #if defined(HAVE_LIBINTL_H) && defined(BUILD_LIBINTL)
405     bindtextdomain(GETTEXT_PACKAGE, LOCALEDIR);
406     bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
407     textdomain(GETTEXT_PACKAGE);
408 #endif
409     if (argc == 1) {
410         PrintUsage("");
411         return 0;
412     }
413
414     if (((argc == 2) || (argc == 3)) && !strcmp("-", argv[1])) {
415 #if HAVE_GETRUSAGE
416         struct rusage myusage;
417         struct timeval starttime;
418         struct timeval currenttime;
419
420         gettimeofday(&starttime, NULL);
421 #endif
422         RemoteMode = 1;
423         if ((argc == 3) && strcmp("", argv[2])) {
424
425             if (
426 #ifdef HAVE_GETUID
427                    getuid()
428 #else
429                    1
430 #endif
431                    == 0) {
432
433 #ifdef HAVE_CHROOT
434                 chroot(argv[2]);
435                 if (errno != 0) {
436                     fprintf(stderr,
437                             "ERROR: can't change root to '%s' errno=%d\n",
438                             argv[2], errno);
439                     exit(errno);
440                 }
441                 ChangeRoot = 1;
442                 firstdir = "/";
443 #else
444                 fprintf(stderr,
445                         "ERROR: change root is not supported by your OS "
446                         "or at least by this copy of rrdtool\n");
447                 exit(1);
448 #endif
449             } else {
450                 firstdir = argv[2];
451             }
452         }
453         if (strcmp(firstdir, "")) {
454             chdir(firstdir);
455             if (errno != 0) {
456                 fprintf(stderr, "ERROR: %s\n", rrd_strerror(errno));
457                 exit(errno);
458             }
459         }
460
461         while (fgetslong(&aLine, stdin)) {
462             if ((argc = CountArgs(aLine)) == 0) {
463                 printf("ERROR: not enough arguments\n");
464             }
465             if ((myargv = (char **) malloc((argc + 1) *
466                                            sizeof(char *))) == NULL) {
467                 perror("malloc");
468                 exit(1);
469             }
470             if ((argc = CreateArgs(argv[0], aLine, argc, myargv)) < 0) {
471                 printf("ERROR: creating arguments\n");
472             } else {
473                 int       ret = HandleInputLine(argc, myargv, stdout);
474
475                 free(myargv);
476                 if (ret == 0) {
477 #if HAVE_GETRUSAGE
478                     getrusage(RUSAGE_SELF, &myusage);
479                     gettimeofday(&currenttime, NULL);
480                     printf("OK u:%1.2f s:%1.2f r:%1.2f\n",
481                            (double) myusage.ru_utime.tv_sec +
482                            (double) myusage.ru_utime.tv_usec / 1000000.0,
483                            (double) myusage.ru_stime.tv_sec +
484                            (double) myusage.ru_stime.tv_usec / 1000000.0,
485                            (double) (currenttime.tv_sec - starttime.tv_sec)
486                            + (double) (currenttime.tv_usec -
487                                        starttime.tv_usec)
488                            / 1000000.0);
489 #else
490                     printf("OK\n");
491 #endif
492                 }
493             }
494             fflush(stdout); /* this is important for pipes to work */
495             free(aLine);
496         }
497     } else if (argc == 2) {
498         PrintUsage(argv[1]);
499         exit(0);
500     } else if (argc == 3 && !strcmp(argv[1], "help")) {
501         PrintUsage(argv[2]);
502         exit(0);
503     } else {
504         exit(HandleInputLine(argc, argv, stderr));
505     }
506     return 0;
507 }
508
509 /* HandleInputLine is NOT thread safe - due to readdir issues,
510    resolving them portably is not really simple. */
511 int HandleInputLine(
512     int argc,
513     char **argv,
514     FILE * out)
515 {
516 #if defined(HAVE_OPENDIR) && defined (HAVE_READDIR)
517     DIR      *curdir;   /* to read current dir with ls */
518     struct dirent *dent;
519 #endif
520 #if defined(HAVE_SYS_STAT_H)
521     struct stat st;
522 #endif
523     char     *cwd;      /* To hold current working dir on call to pwd */
524
525     /* Reset errno to 0 before we start.
526      */
527     errno = 0;
528     if (RemoteMode) {
529         if (argc > 1 && strcmp("quit", argv[1]) == 0) {
530             if (argc > 2) {
531                 printf("ERROR: invalid parameter count for quit\n");
532                 return (1);
533             }
534             exit(0);
535         }
536 #if defined(HAVE_OPENDIR) && defined(HAVE_READDIR) && defined(HAVE_CHDIR)
537         if (argc > 1 && strcmp("cd", argv[1]) == 0) {
538             if (argc > 3) {
539                 printf("ERROR: invalid parameter count for cd\n");
540                 return (1);
541             }
542 #if ! defined(HAVE_CHROOT) || ! defined(HAVE_GETUID)
543             if (getuid() == 0 && !ChangeRoot) {
544                 printf
545                     ("ERROR: chdir security problem - rrdtool is running as "
546                      "root but not chroot!\n");
547                 return (1);
548             }
549 #endif
550             chdir(argv[2]);
551             if (errno != 0) {
552                 printf("ERROR: %s\n", rrd_strerror(errno));
553                 return (1);
554             }
555             return (0);
556         }
557         if (argc > 1 && strcmp("pwd", argv[1]) == 0) {
558             if (argc > 2) {
559                 printf("ERROR: invalid parameter count for pwd\n");
560                 return (1);
561             }
562             cwd = getcwd(NULL, MAXPATH);
563             if (cwd == NULL) {
564                 printf("ERROR: %s\n", rrd_strerror(errno));
565                 return (1);
566             }
567             printf("%s\n", cwd);
568             free(cwd);
569             return (0);
570         }
571         if (argc > 1 && strcmp("mkdir", argv[1]) == 0) {
572             if (argc > 3) {
573                 printf("ERROR: invalid parameter count for mkdir\n");
574                 return (1);
575             }
576 #if ! defined(HAVE_CHROOT) || ! defined(HAVE_GETUID)
577             if (getuid() == 0 && !ChangeRoot) {
578                 printf
579                     ("ERROR: mkdir security problem - rrdtool is running as "
580                      "root but not chroot!\n");
581                 return (1);
582             }
583 #endif
584             mkdir(argv[2], 0777);
585             if (errno != 0) {
586                 printf("ERROR: %s\n", rrd_strerror(errno));
587                 return (1);
588             }
589             return (0);
590         }
591         if (argc > 1 && strcmp("ls", argv[1]) == 0) {
592             if (argc > 2) {
593                 printf("ERROR: invalid parameter count for ls\n");
594                 return (1);
595             }
596             if ((curdir = opendir(".")) != NULL) {
597                 while ((dent = readdir(curdir)) != NULL) {
598                     if (!stat(dent->d_name, &st)) {
599                         if (S_ISDIR(st.st_mode)) {
600                             printf("d %s\n", dent->d_name);
601                         }
602                         if (strlen(dent->d_name) > 4 && S_ISREG(st.st_mode)) {
603                             if (!strcmp
604                                 (dent->d_name + NAMLEN(dent) - 4, ".rrd")
605                                 || !strcmp(dent->d_name + NAMLEN(dent) - 4,
606                                            ".RRD")) {
607                                 printf("- %s\n", dent->d_name);
608                             }
609                         }
610                     }
611                 }
612                 closedir(curdir);
613             } else {
614                 printf("ERROR: %s\n", rrd_strerror(errno));
615                 return (errno);
616             }
617             return (0);
618         }
619 #endif                          /* opendir and readdir */
620
621     }
622     if (argc < 3
623         || strcmp("help", argv[1]) == 0
624         || strcmp("--help", argv[1]) == 0
625         || strcmp("-help", argv[1]) == 0
626         || strcmp("-?", argv[1]) == 0 || strcmp("-h", argv[1]) == 0) {
627         PrintUsage("");
628         return 0;
629     }
630
631     if (strcmp("create", argv[1]) == 0)
632         rrd_create(argc - 1, &argv[1]);
633     else if (strcmp("dump", argv[1]) == 0)
634         rrd_dump(argc - 1, &argv[1]);
635     else if (strcmp("info", argv[1]) == 0 || strcmp("updatev", argv[1]) == 0) {
636         rrd_info_t *data;
637
638         if (strcmp("info", argv[1]) == 0)
639
640             data = rrd_info(argc - 1, &argv[1]);
641         else
642             data = rrd_update_v(argc - 1, &argv[1]);
643         rrd_info_print(data);
644         rrd_info_free(data);
645     }
646
647     else if (strcmp("--version", argv[1]) == 0 ||
648              strcmp("version", argv[1]) == 0 ||
649              strcmp("v", argv[1]) == 0 ||
650              strcmp("-v", argv[1]) == 0 || strcmp("-version", argv[1]) == 0)
651         printf("RRDtool " PACKAGE_VERSION
652                "  Copyright by Tobi Oetiker, 1997-2008 (%f)\n",
653                rrd_version());
654     else if (strcmp("restore", argv[1]) == 0)
655         rrd_restore(argc - 1, &argv[1]);
656     else if (strcmp("resize", argv[1]) == 0)
657         rrd_resize(argc - 1, &argv[1]);
658     else if (strcmp("last", argv[1]) == 0)
659         printf("%ld\n", rrd_last(argc - 1, &argv[1]));
660     else if (strcmp("lastupdate", argv[1]) == 0) {
661         rrd_lastupdate(argc - 1, &argv[1]);
662     } else if (strcmp("first", argv[1]) == 0)
663         printf("%ld\n", rrd_first(argc - 1, &argv[1]));
664     else if (strcmp("update", argv[1]) == 0)
665         rrd_update(argc - 1, &argv[1]);
666     else if (strcmp("fetch", argv[1]) == 0) {
667         time_t    start, end, ti;
668         unsigned long step, ds_cnt, i, ii;
669         rrd_value_t *data, *datai;
670         char    **ds_namv;
671
672         if (rrd_fetch
673             (argc - 1, &argv[1], &start, &end, &step, &ds_cnt, &ds_namv,
674              &data) != -1) {
675             datai = data;
676             printf("           ");
677             for (i = 0; i < ds_cnt; i++)
678                 printf("%20s", ds_namv[i]);
679             printf("\n\n");
680             for (ti = start + step; ti <= end; ti += step) {
681                 printf("%10lu:", ti);
682                 for (ii = 0; ii < ds_cnt; ii++)
683                     printf(" %0.10e", *(datai++));
684                 printf("\n");
685             }
686             for (i = 0; i < ds_cnt; i++)
687                 free(ds_namv[i]);
688             free(ds_namv);
689             free(data);
690         }
691     } else if (strcmp("xport", argv[1]) == 0) {
692         int       xxsize;
693         unsigned long int j = 0;
694         time_t    start, end, ti;
695         unsigned long step, col_cnt, row_cnt;
696         rrd_value_t *data, *ptr;
697         char    **legend_v;
698         int       enumds = 0;
699         int       i;
700         size_t    vtag_s = strlen(COL_DATA_TAG) + 10;
701         char     *vtag = malloc(vtag_s);
702
703         for (i = 2; i < argc; i++) {
704             if (strcmp("--enumds", argv[i]) == 0)
705                 enumds = 1;
706         }
707
708         if (rrd_xport
709             (argc - 1, &argv[1], &xxsize, &start, &end, &step, &col_cnt,
710              &legend_v, &data) != -1) {
711             row_cnt = (end - start) / step;
712             ptr = data;
713             printf("<?xml version=\"1.0\" encoding=\"%s\"?>\n\n",
714                    XML_ENCODING);
715             printf("<%s>\n", ROOT_TAG);
716             printf("  <%s>\n", META_TAG);
717             printf("    <%s>%lu</%s>\n", META_START_TAG,
718                    (unsigned long) start + step, META_START_TAG);
719             printf("    <%s>%lu</%s>\n", META_STEP_TAG, step, META_STEP_TAG);
720             printf("    <%s>%lu</%s>\n", META_END_TAG, (unsigned long) end,
721                    META_END_TAG);
722             printf("    <%s>%lu</%s>\n", META_ROWS_TAG, row_cnt,
723                    META_ROWS_TAG);
724             printf("    <%s>%lu</%s>\n", META_COLS_TAG, col_cnt,
725                    META_COLS_TAG);
726             printf("    <%s>\n", LEGEND_TAG);
727             for (j = 0; j < col_cnt; j++) {
728                 char     *entry = NULL;
729
730                 entry = legend_v[j];
731                 printf("      <%s>%s</%s>\n", LEGEND_ENTRY_TAG, entry,
732                        LEGEND_ENTRY_TAG);
733                 free(entry);
734             }
735             free(legend_v);
736             printf("    </%s>\n", LEGEND_TAG);
737             printf("  </%s>\n", META_TAG);
738             printf("  <%s>\n", DATA_TAG);
739             for (ti = start + step; ti <= end; ti += step) {
740                 printf("    <%s>", DATA_ROW_TAG);
741                 printf("<%s>%lu</%s>", COL_TIME_TAG, ti, COL_TIME_TAG);
742                 for (j = 0; j < col_cnt; j++) {
743                     rrd_value_t newval = DNAN;
744
745                     if (enumds == 1)
746
747                         snprintf(vtag, vtag_s, "%s%lu", COL_DATA_TAG, j);
748                     else
749                         snprintf(vtag, vtag_s, "%s", COL_DATA_TAG);
750                     newval = *ptr;
751                     if (isnan(newval)) {
752                         printf("<%s>NaN</%s>", vtag, vtag);
753                     } else {
754                         printf("<%s>%0.10e</%s>", vtag, newval, vtag);
755                     };
756                     ptr++;
757                 }
758                 printf("</%s>\n", DATA_ROW_TAG);
759             }
760             free(data);
761             printf("  </%s>\n", DATA_TAG);
762             printf("</%s>\n", ROOT_TAG);
763         }
764         free(vtag);
765     } else if (strcmp("graph", argv[1]) == 0) {
766         char    **calcpr;
767
768 #ifdef notused /*XXX*/
769         const char *imgfile = argv[2];  /* rrd_graph changes argv pointer */
770 #endif
771         int       xsize, ysize;
772         double    ymin, ymax;
773         int       i;
774         int       tostdout = (strcmp(argv[2], "-") == 0);
775         int       imginfo = 0;
776
777         for (i = 2; i < argc; i++) {
778             if (strcmp(argv[i], "--imginfo") == 0
779                 || strcmp(argv[i], "-f") == 0) {
780                 imginfo = 1;
781                 break;
782             }
783         }
784         if (rrd_graph
785             (argc - 1, &argv[1], &calcpr, &xsize, &ysize, NULL, &ymin,
786              &ymax) != -1) {
787             if (!tostdout && !imginfo)
788                 printf("%dx%d\n", xsize, ysize);
789             if (calcpr) {
790                 for (i = 0; calcpr[i]; i++) {
791                     if (!tostdout)
792                         printf("%s\n", calcpr[i]);
793                     free(calcpr[i]);
794                 }
795                 free(calcpr);
796             }
797         }
798
799     } else if (strcmp("graphv", argv[1]) == 0) {
800         rrd_info_t *grinfo = NULL;  /* 1 to distinguish it from the NULL that rrd_graph sends in */
801
802         grinfo = rrd_graph_v(argc - 1, &argv[1]);
803         if (grinfo) {
804             rrd_info_print(grinfo);
805             rrd_info_free(grinfo);
806         }
807
808     } else if (strcmp("tune", argv[1]) == 0)
809         rrd_tune(argc - 1, &argv[1]);
810     else if (strcmp("flush", argv[1]) == 0)
811         rrd_cmd_flush(argc - 1, &argv[1]);
812     else {
813         rrd_set_error("unknown function '%s'", argv[1]);
814     }
815     if (rrd_test_error()) {
816         fprintf(out, "ERROR: %s\n", rrd_get_error());
817         rrd_clear_error();
818         return 1;
819     }
820     return (0);
821 }
822
823 int CountArgs(
824     char *aLine)
825 {
826     int       i = 0;
827     int       aCount = 0;
828     int       inarg = 0;
829
830     while (aLine[i] == ' ')
831         i++;
832     while (aLine[i] != 0) {
833         if ((aLine[i] == ' ') && inarg) {
834             inarg = 0;
835         }
836         if ((aLine[i] != ' ') && !inarg) {
837             inarg = 1;
838             aCount++;
839         }
840         i++;
841     }
842     return aCount;
843 }
844
845 /*
846  * CreateArgs - take a string (aLine) and tokenize
847  */
848 int CreateArgs(
849     char *pName,
850     char *aLine,
851     int argc,
852     char **argv)
853 {
854     char     *getP, *putP;
855     char    **pargv = argv;
856     char      Quote = 0;
857     int       inArg = 0;
858     int       len;
859
860     len = strlen(aLine);
861     /* remove trailing space and newlines */
862     while (len && aLine[len] <= ' ') {
863         aLine[len] = 0;
864         len--;
865     }
866     /* sikp leading blanks */
867     while (*aLine && *aLine <= ' ')
868         aLine++;
869     pargv[0] = pName;
870     argc = 1;
871     getP = aLine;
872     putP = aLine;
873     while (*getP) {
874         switch (*getP) {
875         case ' ':
876             if (Quote) {
877                 *(putP++) = *getP;
878             } else if (inArg) {
879                 *(putP++) = 0;
880                 inArg = 0;
881             }
882             break;
883         case '"':
884         case '\'':
885             if (Quote != 0) {
886                 if (Quote == *getP)
887                     Quote = 0;
888                 else {
889                     *(putP++) = *getP;
890                 }
891             } else {
892                 if (!inArg) {
893                     pargv[argc++] = putP;
894                     inArg = 1;
895                 }
896                 Quote = *getP;
897             }
898             break;
899         default:
900             if (!inArg) {
901                 pargv[argc++] = putP;
902                 inArg = 1;
903             }
904             *(putP++) = *getP;
905             break;
906         }
907         getP++;
908     }
909
910     *putP = '\0';
911     if (Quote)
912         return -1;
913     else
914         return argc;
915 }