debe095327ecf57458ddf9aee59bc48e2f8094ff
[collectd.git] / src / csv.c
1 /**
2  * collectd - src/csv.c
3  * Copyright (C) 2007-2009  Florian octo Forster
4  * Copyright (C) 2009       Doug MacEachern
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the
8  * Free Software Foundation; only version 2 of the License is applicable.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
18  *
19  * Authors:
20  *   Florian octo Forster <octo at collectd.org>
21  *   Doug MacEachern <dougm@hyperic.com>
22  **/
23
24 #include "collectd.h"
25
26 #include "common.h"
27 #include "plugin.h"
28 #include "utils_cache.h"
29
30 /*
31  * Private variables
32  */
33 static const char *config_keys[] = {"DataDir", "StoreRates"};
34 static int config_keys_num = STATIC_ARRAY_SIZE(config_keys);
35
36 static char *datadir = NULL;
37 static int store_rates = 0;
38 static int use_stdio = 0;
39
40 static int value_list_to_string(char *buffer, int buffer_len,
41                                 const data_set_t *ds, const value_list_t *vl) {
42   int offset;
43   int status;
44   gauge_t *rates = NULL;
45
46   assert(0 == strcmp(ds->type, vl->type));
47
48   memset(buffer, '\0', buffer_len);
49
50   status = snprintf(buffer, buffer_len, "%.3f", CDTIME_T_TO_DOUBLE(vl->time));
51   if ((status < 1) || (status >= buffer_len))
52     return -1;
53   offset = status;
54
55   for (size_t i = 0; i < ds->ds_num; i++) {
56     if ((ds->ds[i].type != DS_TYPE_COUNTER) &&
57         (ds->ds[i].type != DS_TYPE_GAUGE) &&
58         (ds->ds[i].type != DS_TYPE_DERIVE) &&
59         (ds->ds[i].type != DS_TYPE_ABSOLUTE)) {
60       sfree(rates);
61       return -1;
62     }
63
64     if (ds->ds[i].type == DS_TYPE_GAUGE) {
65       status = snprintf(buffer + offset, buffer_len - offset, ",%lf",
66                         vl->values[i].gauge);
67     } else if (store_rates != 0) {
68       if (rates == NULL)
69         rates = uc_get_rate(ds, vl);
70       if (rates == NULL) {
71         WARNING("csv plugin: "
72                 "uc_get_rate failed.");
73         return -1;
74       }
75       status = snprintf(buffer + offset, buffer_len - offset, ",%lf", rates[i]);
76     } else if (ds->ds[i].type == DS_TYPE_COUNTER) {
77       status = snprintf(buffer + offset, buffer_len - offset, ",%llu",
78                         vl->values[i].counter);
79     } else if (ds->ds[i].type == DS_TYPE_DERIVE) {
80       status = snprintf(buffer + offset, buffer_len - offset, ",%" PRIi64,
81                         vl->values[i].derive);
82     } else if (ds->ds[i].type == DS_TYPE_ABSOLUTE) {
83       status = snprintf(buffer + offset, buffer_len - offset, ",%" PRIu64,
84                         vl->values[i].absolute);
85     }
86
87     if ((status < 1) || (status >= (buffer_len - offset))) {
88       sfree(rates);
89       return -1;
90     }
91
92     offset += status;
93   } /* for ds->ds_num */
94
95   sfree(rates);
96   return 0;
97 } /* int value_list_to_string */
98
99 static int value_list_to_filename(char *buffer, size_t buffer_size,
100                                   value_list_t const *vl) {
101   int status;
102
103   char *ptr = buffer;
104   size_t ptr_size = buffer_size;
105   time_t now;
106   struct tm struct_tm;
107
108   if (datadir != NULL) {
109     size_t len = strlen(datadir) + 1;
110
111     if (len >= ptr_size)
112       return ENOBUFS;
113
114     memcpy(ptr, datadir, len);
115     ptr[len - 1] = '/';
116     ptr_size -= len;
117     ptr += len;
118   }
119
120   status = FORMAT_VL(ptr, ptr_size, vl);
121   if (status != 0)
122     return status;
123
124   /* Skip all the time formatting stuff when printing to STDOUT or
125    * STDERR. */
126   if (use_stdio)
127     return 0;
128
129   ptr_size -= strlen(ptr);
130   ptr += strlen(ptr);
131
132   /* "-2013-07-12" => 11 bytes */
133   if (ptr_size < 12) {
134     ERROR("csv plugin: Buffer too small.");
135     return ENOMEM;
136   }
137
138   /* TODO: Find a way to minimize the calls to `localtime_r',
139    * since they are pretty expensive.. */
140   now = time(NULL);
141   if (localtime_r(&now, &struct_tm) == NULL) {
142     ERROR("csv plugin: localtime_r failed");
143     return -1;
144   }
145
146   status = strftime(ptr, ptr_size, "-%Y-%m-%d", &struct_tm);
147   if (status == 0) /* yep, it returns zero on error. */
148   {
149     ERROR("csv plugin: strftime failed");
150     return -1;
151   }
152
153   return 0;
154 } /* int value_list_to_filename */
155
156 static int csv_create_file(const char *filename, const data_set_t *ds) {
157   FILE *csv;
158
159   if (check_create_dir(filename))
160     return -1;
161
162   csv = fopen(filename, "w");
163   if (csv == NULL) {
164     char errbuf[1024];
165     ERROR("csv plugin: fopen (%s) failed: %s", filename,
166           sstrerror(errno, errbuf, sizeof(errbuf)));
167     return -1;
168   }
169
170   fprintf(csv, "epoch");
171   for (size_t i = 0; i < ds->ds_num; i++)
172     fprintf(csv, ",%s", ds->ds[i].name);
173
174   fprintf(csv, "\n");
175   fclose(csv);
176
177   return 0;
178 } /* int csv_create_file */
179
180 static int csv_config(const char *key, const char *value) {
181   if (strcasecmp("DataDir", key) == 0) {
182     if (datadir != NULL) {
183       free(datadir);
184       datadir = NULL;
185     }
186     if (strcasecmp("stdout", value) == 0) {
187       use_stdio = 1;
188       return 0;
189     } else if (strcasecmp("stderr", value) == 0) {
190       use_stdio = 2;
191       return 0;
192     }
193     datadir = strdup(value);
194     if (datadir != NULL) {
195       int len = strlen(datadir);
196       while ((len > 0) && (datadir[len - 1] == '/')) {
197         len--;
198         datadir[len] = '\0';
199       }
200       if (len <= 0) {
201         free(datadir);
202         datadir = NULL;
203       }
204     }
205   } else if (strcasecmp("StoreRates", key) == 0) {
206     if (IS_TRUE(value))
207       store_rates = 1;
208     else
209       store_rates = 0;
210   } else {
211     return -1;
212   }
213   return 0;
214 } /* int csv_config */
215
216 static int csv_write(const data_set_t *ds, const value_list_t *vl,
217                      user_data_t __attribute__((unused)) * user_data) {
218   struct stat statbuf;
219   char filename[512];
220   char values[4096];
221   FILE *csv;
222   int csv_fd;
223   struct flock fl = {0};
224   int status;
225
226   if (0 != strcmp(ds->type, vl->type)) {
227     ERROR("csv plugin: DS type does not match value list type");
228     return -1;
229   }
230
231   status = value_list_to_filename(filename, sizeof(filename), vl);
232   if (status != 0)
233     return -1;
234
235   DEBUG("csv plugin: csv_write: filename = %s;", filename);
236
237   if (value_list_to_string(values, sizeof(values), ds, vl) != 0)
238     return -1;
239
240   if (use_stdio) {
241     escape_string(filename, sizeof(filename));
242
243     /* Replace commas by colons for PUTVAL compatible output. */
244     for (size_t i = 0; i < sizeof(values); i++) {
245       if (values[i] == 0)
246         break;
247       else if (values[i] == ',')
248         values[i] = ':';
249     }
250
251     fprintf(use_stdio == 1 ? stdout : stderr, "PUTVAL %s interval=%.3f %s\n",
252             filename, CDTIME_T_TO_DOUBLE(vl->interval), values);
253     return 0;
254   }
255
256   if (stat(filename, &statbuf) == -1) {
257     if (errno == ENOENT) {
258       if (csv_create_file(filename, ds))
259         return -1;
260     } else {
261       char errbuf[1024];
262       ERROR("stat(%s) failed: %s", filename,
263             sstrerror(errno, errbuf, sizeof(errbuf)));
264       return -1;
265     }
266   } else if (!S_ISREG(statbuf.st_mode)) {
267     ERROR("stat(%s): Not a regular file!", filename);
268     return -1;
269   }
270
271   csv = fopen(filename, "a");
272   if (csv == NULL) {
273     char errbuf[1024];
274     ERROR("csv plugin: fopen (%s) failed: %s", filename,
275           sstrerror(errno, errbuf, sizeof(errbuf)));
276     return -1;
277   }
278   csv_fd = fileno(csv);
279
280   fl.l_pid = getpid();
281   fl.l_type = F_WRLCK;
282   fl.l_whence = SEEK_SET;
283
284   status = fcntl(csv_fd, F_SETLK, &fl);
285   if (status != 0) {
286     char errbuf[1024];
287     ERROR("csv plugin: flock (%s) failed: %s", filename,
288           sstrerror(errno, errbuf, sizeof(errbuf)));
289     fclose(csv);
290     return -1;
291   }
292
293   fprintf(csv, "%s\n", values);
294
295   /* The lock is implicitely released. I we don't release it explicitely
296    * because the `FILE *' may need to flush a cache first */
297   fclose(csv);
298
299   return 0;
300 } /* int csv_write */
301
302 void module_register(void) {
303   plugin_register_config("csv", csv_config, config_keys, config_keys_num);
304   plugin_register_write("csv", csv_write, /* user_data = */ NULL);
305 } /* void module_register */