* this preserves principle of least surprise when dealing with files that
[rrdtool.git] / src / rrd_client.c
1 /**
2  * RRDTool - src/rrd_client.c
3  * Copyright (C) 2008 Florian octo Forster
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Authors:
19  *   Florian octo Forster <octo at verplant.org>
20  **/
21
22 #include "rrd.h"
23 #include "rrd_client.h"
24 #include "rrd_tool.h"
25
26 #include <stdlib.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <assert.h>
30 #include <pthread.h>
31 #include <sys/types.h>
32 #include <sys/socket.h>
33 #include <sys/un.h>
34 #include <netdb.h>
35
36 #ifndef ENODATA
37 #define ENODATA ENOENT
38 #endif
39
40 struct rrdc_response_s
41 {
42   int status;
43   char *message;
44   char **lines;
45   size_t lines_num;
46 };
47 typedef struct rrdc_response_s rrdc_response_t;
48
49 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
50 static int sd = -1;
51 static FILE *sh = NULL;
52 static char *sd_path = NULL; /* cache the path for sd */
53
54 /* One must hold `lock' when calling `close_connection'. */
55 static void close_connection (void) /* {{{ */
56 {
57   if (sh != NULL)
58   {
59     fclose (sh);
60     sh = NULL;
61     sd = -1;
62   }
63   else if (sd >= 0)
64   {
65     close (sd);
66     sd = -1;
67   }
68
69   if (sd_path != NULL)
70     free (sd_path);
71   sd_path = NULL;
72 } /* }}} void close_connection */
73
74 static int buffer_add_string (const char *str, /* {{{ */
75     char **buffer_ret, size_t *buffer_size_ret)
76 {
77   char *buffer;
78   size_t buffer_size;
79   size_t buffer_pos;
80   size_t i;
81   int status;
82
83   buffer = *buffer_ret;
84   buffer_size = *buffer_size_ret;
85   buffer_pos = 0;
86
87   i = 0;
88   status = -1;
89   while (buffer_pos < buffer_size)
90   {
91     if (str[i] == 0)
92     {
93       buffer[buffer_pos] = ' ';
94       buffer_pos++;
95       status = 0;
96       break;
97     }
98     else if ((str[i] == ' ') || (str[i] == '\\'))
99     {
100       if (buffer_pos >= (buffer_size - 1))
101         break;
102       buffer[buffer_pos] = '\\';
103       buffer_pos++;
104       buffer[buffer_pos] = str[i];
105       buffer_pos++;
106     }
107     else
108     {
109       buffer[buffer_pos] = str[i];
110       buffer_pos++;
111     }
112     i++;
113   } /* while (buffer_pos < buffer_size) */
114
115   if (status != 0)
116     return (-1);
117
118   *buffer_ret = buffer + buffer_pos;
119   *buffer_size_ret = buffer_size - buffer_pos;
120
121   return (0);
122 } /* }}} int buffer_add_string */
123
124 static int buffer_add_value (const char *value, /* {{{ */
125     char **buffer_ret, size_t *buffer_size_ret)
126 {
127   char temp[4096];
128
129   if (strncmp (value, "N:", 2) == 0)
130     snprintf (temp, sizeof (temp), "%lu:%s",
131         (unsigned long) time (NULL), value + 2);
132   else
133     strncpy (temp, value, sizeof (temp));
134   temp[sizeof (temp) - 1] = 0;
135
136   return (buffer_add_string (temp, buffer_ret, buffer_size_ret));
137 } /* }}} int buffer_add_value */
138
139 /* Remove trailing newline (NL) and carriage return (CR) characters. Similar to
140  * the Perl function `chomp'. Returns the number of characters that have been
141  * removed. */
142 static int chomp (char *str) /* {{{ */
143 {
144   size_t len;
145   int removed;
146
147   if (str == NULL)
148     return (-1);
149
150   len = strlen (str);
151   removed = 0;
152   while ((len > 0) && ((str[len - 1] == '\n') || (str[len - 1] == '\r')))
153   {
154     str[len - 1] = 0;
155     len--;
156     removed++;
157   }
158
159   return (removed);
160 } /* }}} int chomp */
161
162 static void response_free (rrdc_response_t *res) /* {{{ */
163 {
164   if (res == NULL)
165     return;
166
167   if (res->lines != NULL)
168   {
169     size_t i;
170
171     for (i = 0; i < res->lines_num; i++)
172       if (res->lines[i] != NULL)
173         free (res->lines[i]);
174     free (res->lines);
175   }
176
177   free (res);
178 } /* }}} void response_free */
179
180 static int response_read (rrdc_response_t **ret_response) /* {{{ */
181 {
182   rrdc_response_t *ret;
183
184   char buffer[4096];
185   char *buffer_ptr;
186
187   size_t i;
188
189   if (sh == NULL)
190     return (-1);
191
192   ret = (rrdc_response_t *) malloc (sizeof (rrdc_response_t));
193   if (ret == NULL)
194     return (-2);
195   memset (ret, 0, sizeof (*ret));
196   ret->lines = NULL;
197   ret->lines_num = 0;
198
199   buffer_ptr = fgets (buffer, sizeof (buffer), sh);
200   if (buffer_ptr == NULL)
201     return (-3);
202   chomp (buffer);
203
204   ret->status = strtol (buffer, &ret->message, 0);
205   if (buffer == ret->message)
206   {
207     response_free (ret);
208     return (-4);
209   }
210   /* Skip leading whitespace of the status message */
211   ret->message += strspn (ret->message, " \t");
212
213   if (ret->status <= 0)
214   {
215     if (ret->status < 0)
216       rrd_set_error("rrdcached: %s", ret->message);
217     *ret_response = ret;
218     return (0);
219   }
220
221   ret->lines = (char **) malloc (sizeof (char *) * ret->status);
222   if (ret->lines == NULL)
223   {
224     response_free (ret);
225     return (-5);
226   }
227   memset (ret->lines, 0, sizeof (char *) * ret->status);
228   ret->lines_num = (size_t) ret->status;
229
230   for (i = 0; i < ret->lines_num; i++)
231   {
232     buffer_ptr = fgets (buffer, sizeof (buffer), sh);
233     if (buffer_ptr == NULL)
234     {
235       response_free (ret);
236       return (-6);
237     }
238     chomp (buffer);
239
240     ret->lines[i] = strdup (buffer);
241     if (ret->lines[i] == NULL)
242     {
243       response_free (ret);
244       return (-7);
245     }
246   }
247
248   *ret_response = ret;
249   return (0);
250 } /* }}} rrdc_response_t *response_read */
251
252 static int request (const char *buffer, size_t buffer_size, /* {{{ */
253     rrdc_response_t **ret_response)
254 {
255   int status;
256   rrdc_response_t *res;
257
258   pthread_mutex_lock (&lock);
259
260   if (sh == NULL)
261   {
262     pthread_mutex_unlock (&lock);
263     return (ENOTCONN);
264   }
265
266   status = (int) fwrite (buffer, buffer_size, /* nmemb = */ 1, sh);
267   if (status != 1)
268   {
269     close_connection ();
270     pthread_mutex_unlock (&lock);
271     rrd_set_error("request: socket error (%d) while talking to rrdcached",
272                   status);
273     return (-1);
274   }
275   fflush (sh);
276
277   res = NULL;
278   status = response_read (&res);
279
280   pthread_mutex_unlock (&lock);
281
282   if (status != 0)
283   {
284     if (status < 0)
285       rrd_set_error("request: internal error while talking to rrdcached");
286     return (status);
287   }
288
289   *ret_response = res;
290   return (0);
291 } /* }}} int request */
292
293 /* determine whether we are connected to the specified daemon_addr if
294  * NULL, return whether we are connected at all
295  */
296 int rrdc_is_connected(const char *daemon_addr) /* {{{ */
297 {
298   if (sd < 0)
299     return 0;
300   else if (daemon_addr == NULL)
301   {
302     /* here we have to handle the case i.e.
303      *   UPDATE --daemon ...; UPDATEV (no --daemon) ...
304      * In other words: we have a cached connection,
305      * but it is not specified in the current command.
306      * Daemon is only implied in this case if set in ENV
307      */
308     if (getenv(ENV_RRDCACHED_ADDRESS) != NULL)
309       return 1;
310     else
311       return 0;
312   }
313   else if (strcmp(daemon_addr, sd_path) == 0)
314     return 1;
315   else
316     return 0;
317
318 } /* }}} int rrdc_is_connected */
319
320 static int rrdc_connect_unix (const char *path) /* {{{ */
321 {
322   struct sockaddr_un sa;
323   int status;
324
325   assert (path != NULL);
326   assert (sd == -1);
327
328   sd = socket (PF_UNIX, SOCK_STREAM, /* protocol = */ 0);
329   if (sd < 0)
330   {
331     status = errno;
332     return (status);
333   }
334
335   memset (&sa, 0, sizeof (sa));
336   sa.sun_family = AF_UNIX;
337   strncpy (sa.sun_path, path, sizeof (sa.sun_path) - 1);
338
339   status = connect (sd, (struct sockaddr *) &sa, sizeof (sa));
340   if (status != 0)
341   {
342     status = errno;
343     close_connection ();
344     return (status);
345   }
346
347   sh = fdopen (sd, "r+");
348   if (sh == NULL)
349   {
350     status = errno;
351     close_connection ();
352     return (status);
353   }
354
355   return (0);
356 } /* }}} int rrdc_connect_unix */
357
358 static int rrdc_connect_network (const char *addr_orig) /* {{{ */
359 {
360   struct addrinfo ai_hints;
361   struct addrinfo *ai_res;
362   struct addrinfo *ai_ptr;
363   char addr_copy[NI_MAXHOST];
364   char *addr;
365   char *port;
366
367   assert (addr_orig != NULL);
368   assert (sd == -1);
369
370   strncpy(addr_copy, addr_orig, sizeof(addr_copy));
371   addr_copy[sizeof(addr_copy) - 1] = '\0';
372   addr = addr_copy;
373
374   int status;
375   memset (&ai_hints, 0, sizeof (ai_hints));
376   ai_hints.ai_flags = 0;
377 #ifdef AI_ADDRCONFIG
378   ai_hints.ai_flags |= AI_ADDRCONFIG;
379 #endif
380   ai_hints.ai_family = AF_UNSPEC;
381   ai_hints.ai_socktype = SOCK_STREAM;
382
383   port = NULL;
384   if (*addr == '[') /* IPv6+port format */
385   {
386     /* `addr' is something like "[2001:780:104:2:211:24ff:feab:26f8]:12345" */
387     addr++;
388
389     port = strchr (addr, ']');
390     if (port == NULL)
391     {
392       rrd_set_error("malformed address: %s", addr_orig);
393       return (-1);
394     }
395     *port = 0;
396     port++;
397
398     if (*port == ':')
399       port++;
400     else if (*port == 0)
401       port = NULL;
402     else
403     {
404       rrd_set_error("garbage after address: %s", port);
405       return (-1);
406     }
407   } /* if (*addr = ']') */
408   else if (strchr (addr, '.') != NULL) /* Hostname or IPv4 */
409   {
410     port = rindex(addr, ':');
411     if (port != NULL)
412     {
413       *port = 0;
414       port++;
415     }
416   }
417
418   ai_res = NULL;
419   status = getaddrinfo (addr,
420                         port == NULL ? RRDCACHED_DEFAULT_PORT : port,
421                         &ai_hints, &ai_res);
422   if (status != 0)
423     return (status);
424
425   for (ai_ptr = ai_res; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
426   {
427     sd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
428     if (sd < 0)
429     {
430       status = errno;
431       sd = -1;
432       continue;
433     }
434
435     status = connect (sd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
436     if (status != 0)
437     {
438       status = errno;
439       close_connection();
440       continue;
441     }
442
443     sh = fdopen (sd, "r+");
444     if (sh == NULL)
445     {
446       status = errno;
447       close_connection ();
448       continue;
449     }
450
451     assert (status == 0);
452     break;
453   } /* for (ai_ptr) */
454
455   return (status);
456 } /* }}} int rrdc_connect_network */
457
458 int rrdc_connect (const char *addr) /* {{{ */
459 {
460   int status = 0;
461
462   if (addr == NULL)
463     addr = getenv (ENV_RRDCACHED_ADDRESS);
464
465   if (addr == NULL)
466     return 0;
467
468   pthread_mutex_lock(&lock);
469
470   if (sd >= 0 && sd_path != NULL && strcmp(addr, sd_path) == 0)
471   {
472     /* connection to the same daemon; use cached connection */
473     pthread_mutex_unlock (&lock);
474     return (0);
475   }
476   else
477   {
478     close_connection();
479   }
480
481   if (strncmp ("unix:", addr, strlen ("unix:")) == 0)
482     status = rrdc_connect_unix (addr + strlen ("unix:"));
483   else if (addr[0] == '/')
484     status = rrdc_connect_unix (addr);
485   else
486     status = rrdc_connect_network(addr);
487
488   if (status == 0 && sd >= 0)
489     sd_path = strdup(addr);
490   else
491     rrd_set_error("Unable to connect to rrdcached: %s",
492                   (status < 0)
493                   ? "Internal error"
494                   : rrd_strerror (status));
495
496   pthread_mutex_unlock (&lock);
497   return (status);
498 } /* }}} int rrdc_connect */
499
500 int rrdc_disconnect (void) /* {{{ */
501 {
502   pthread_mutex_lock (&lock);
503
504   close_connection();
505
506   pthread_mutex_unlock (&lock);
507
508   return (0);
509 } /* }}} int rrdc_disconnect */
510
511 int rrdc_update (const char *filename, int values_num, /* {{{ */
512                 const char * const *values)
513 {
514   char buffer[4096];
515   char *buffer_ptr;
516   size_t buffer_free;
517   size_t buffer_size;
518   rrdc_response_t *res;
519   int status;
520   int i;
521   char file_path[PATH_MAX];
522
523   memset (buffer, 0, sizeof (buffer));
524   buffer_ptr = &buffer[0];
525   buffer_free = sizeof (buffer);
526
527   status = buffer_add_string ("update", &buffer_ptr, &buffer_free);
528   if (status != 0)
529     return (ENOBUFS);
530
531   /* change to absolute path for rrdcached */
532   if (*filename != '/' && realpath(filename, file_path) != NULL)
533       filename = file_path;
534
535   status = buffer_add_string (filename, &buffer_ptr, &buffer_free);
536   if (status != 0)
537     return (ENOBUFS);
538
539   for (i = 0; i < values_num; i++)
540   {
541     status = buffer_add_value (values[i], &buffer_ptr, &buffer_free);
542     if (status != 0)
543       return (ENOBUFS);
544   }
545
546   assert (buffer_free < sizeof (buffer));
547   buffer_size = sizeof (buffer) - buffer_free;
548   assert (buffer[buffer_size - 1] == ' ');
549   buffer[buffer_size - 1] = '\n';
550
551   res = NULL;
552   status = request (buffer, buffer_size, &res);
553   if (status != 0)
554     return (status);
555
556   status = res->status;
557   response_free (res);
558
559   return (status);
560 } /* }}} int rrdc_update */
561
562 int rrdc_flush (const char *filename) /* {{{ */
563 {
564   char buffer[4096];
565   char *buffer_ptr;
566   size_t buffer_free;
567   size_t buffer_size;
568   rrdc_response_t *res;
569   int status;
570   char file_path[PATH_MAX];
571
572   if (filename == NULL)
573     return (-1);
574
575   memset (buffer, 0, sizeof (buffer));
576   buffer_ptr = &buffer[0];
577   buffer_free = sizeof (buffer);
578
579   status = buffer_add_string ("flush", &buffer_ptr, &buffer_free);
580   if (status != 0)
581     return (ENOBUFS);
582
583   /* change to absolute path for rrdcached */
584   if (*filename != '/' && realpath(filename, file_path) != NULL)
585       filename = file_path;
586
587   status = buffer_add_string (filename, &buffer_ptr, &buffer_free);
588   if (status != 0)
589     return (ENOBUFS);
590
591   assert (buffer_free < sizeof (buffer));
592   buffer_size = sizeof (buffer) - buffer_free;
593   assert (buffer[buffer_size - 1] == ' ');
594   buffer[buffer_size - 1] = '\n';
595
596   res = NULL;
597   status = request (buffer, buffer_size, &res);
598   if (status != 0)
599     return (status);
600
601   status = res->status;
602   response_free (res);
603
604   return (status);
605 } /* }}} int rrdc_flush */
606
607
608 /* convenience function; if there is a daemon specified, or if we can
609  * detect one from the environment, then flush the file.  Otherwise, no-op
610  */
611 int rrdc_flush_if_daemon (const char *opt_daemon, const char *filename) /* {{{ */
612 {
613   int status = 0;
614
615   rrdc_connect(opt_daemon);
616
617   if (rrdc_is_connected(opt_daemon))
618   {
619     status = rrdc_flush (filename);
620     if (status != 0)
621     {
622       rrd_set_error ("rrdc_flush (%s) failed with status %i.",
623                      filename, status);
624     }
625   } /* if (rrdc_is_connected(..)) */
626
627   return status;
628 } /* }}} int rrdc_flush_if_daemon */
629
630
631 int rrdc_stats_get (rrdc_stats_t **ret_stats) /* {{{ */
632 {
633   rrdc_stats_t *head;
634   rrdc_stats_t *tail;
635
636   rrdc_response_t *res;
637
638   int status;
639   size_t i;
640
641   /* Protocol example: {{{
642    * ->  STATS
643    * <-  5 Statistics follow
644    * <-  QueueLength: 0
645    * <-  UpdatesWritten: 0
646    * <-  DataSetsWritten: 0
647    * <-  TreeNodesNumber: 0
648    * <-  TreeDepth: 0
649    * }}} */
650
651   res = NULL;
652   status = request ("STATS\n", strlen ("STATS\n"), &res);
653   if (status != 0)
654     return (status);
655
656   if (res->status <= 0)
657   {
658     response_free (res);
659     return (EIO);
660   }
661
662   head = NULL;
663   tail = NULL;
664   for (i = 0; i < res->lines_num; i++)
665   {
666     char *key;
667     char *value;
668     char *endptr;
669     rrdc_stats_t *s;
670
671     key = res->lines[i];
672     value = strchr (key, ':');
673     if (value == NULL)
674       continue;
675     *value = 0;
676     value++;
677
678     while ((value[0] == ' ') || (value[0] == '\t'))
679       value++;
680
681     s = (rrdc_stats_t *) malloc (sizeof (rrdc_stats_t));
682     if (s == NULL)
683       continue;
684     memset (s, 0, sizeof (*s));
685
686     s->name = strdup (key);
687
688     endptr = NULL;
689     if ((strcmp ("QueueLength", key) == 0)
690         || (strcmp ("TreeDepth", key) == 0)
691         || (strcmp ("TreeNodesNumber", key) == 0))
692     {
693       s->type = RRDC_STATS_TYPE_GAUGE;
694       s->value.gauge = strtod (value, &endptr);
695     }
696     else if ((strcmp ("DataSetsWritten", key) == 0)
697         || (strcmp ("FlushesReceived", key) == 0)
698         || (strcmp ("JournalBytes", key) == 0)
699         || (strcmp ("JournalRotate", key) == 0)
700         || (strcmp ("UpdatesReceived", key) == 0)
701         || (strcmp ("UpdatesWritten", key) == 0))
702     {
703       s->type = RRDC_STATS_TYPE_COUNTER;
704       s->value.counter = (uint64_t) strtoll (value, &endptr, /* base = */ 0);
705     }
706     else
707     {
708       free (s);
709       continue;
710     }
711
712     /* Conversion failed */
713     if (endptr == value)
714     {
715       free (s);
716       continue;
717     }
718
719     if (head == NULL)
720     {
721       head = s;
722       tail = s;
723       s->next = NULL;
724     }
725     else
726     {
727       tail->next = s;
728       tail = s;
729     }
730   } /* for (i = 0; i < res->lines_num; i++) */
731
732   response_free (res);
733
734   if (head == NULL)
735     return (EPROTO);
736
737   *ret_stats = head;
738   return (0);
739 } /* }}} int rrdc_stats_get */
740
741 void rrdc_stats_free (rrdc_stats_t *ret_stats) /* {{{ */
742 {
743   rrdc_stats_t *this;
744
745   this = ret_stats;
746   while (this != NULL)
747   {
748     rrdc_stats_t *next;
749
750     next = this->next;
751
752     if (this->name != NULL)
753     {
754       free ((char *)this->name);
755       this->name = NULL;
756     }
757     free (this);
758
759     this = next;
760   } /* while (this != NULL) */
761 } /* }}} void rrdc_stats_free */
762
763 /*
764  * vim: set sw=2 sts=2 ts=8 et fdm=marker :
765  */