Merge branch 'collectd-5.8'
[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     ERROR("csv plugin: fopen (%s) failed: %s", filename, STRERRNO);
165     return -1;
166   }
167
168   fprintf(csv, "epoch");
169   for (size_t i = 0; i < ds->ds_num; i++)
170     fprintf(csv, ",%s", ds->ds[i].name);
171
172   fprintf(csv, "\n");
173   fclose(csv);
174
175   return 0;
176 } /* int csv_create_file */
177
178 static int csv_config(const char *key, const char *value) {
179   if (strcasecmp("DataDir", key) == 0) {
180     if (datadir != NULL) {
181       free(datadir);
182       datadir = NULL;
183     }
184     if (strcasecmp("stdout", value) == 0) {
185       use_stdio = 1;
186       return 0;
187     } else if (strcasecmp("stderr", value) == 0) {
188       use_stdio = 2;
189       return 0;
190     }
191     datadir = strdup(value);
192     if (datadir != NULL) {
193       int len = strlen(datadir);
194       while ((len > 0) && (datadir[len - 1] == '/')) {
195         len--;
196         datadir[len] = '\0';
197       }
198       if (len <= 0) {
199         free(datadir);
200         datadir = NULL;
201       }
202     }
203   } else if (strcasecmp("StoreRates", key) == 0) {
204     if (IS_TRUE(value))
205       store_rates = 1;
206     else
207       store_rates = 0;
208   } else {
209     return -1;
210   }
211   return 0;
212 } /* int csv_config */
213
214 static int csv_write(const data_set_t *ds, const value_list_t *vl,
215                      user_data_t __attribute__((unused)) * user_data) {
216   struct stat statbuf;
217   char filename[512];
218   char values[4096];
219   FILE *csv;
220   int csv_fd;
221   struct flock fl = {0};
222   int status;
223
224   if (0 != strcmp(ds->type, vl->type)) {
225     ERROR("csv plugin: DS type does not match value list type");
226     return -1;
227   }
228
229   status = value_list_to_filename(filename, sizeof(filename), vl);
230   if (status != 0)
231     return -1;
232
233   DEBUG("csv plugin: csv_write: filename = %s;", filename);
234
235   if (value_list_to_string(values, sizeof(values), ds, vl) != 0)
236     return -1;
237
238   if (use_stdio) {
239     escape_string(filename, sizeof(filename));
240
241     /* Replace commas by colons for PUTVAL compatible output. */
242     for (size_t i = 0; i < sizeof(values); i++) {
243       if (values[i] == 0)
244         break;
245       else if (values[i] == ',')
246         values[i] = ':';
247     }
248
249     fprintf(use_stdio == 1 ? stdout : stderr, "PUTVAL %s interval=%.3f %s\n",
250             filename, CDTIME_T_TO_DOUBLE(vl->interval), values);
251     return 0;
252   }
253
254   if (stat(filename, &statbuf) == -1) {
255     if (errno == ENOENT) {
256       if (csv_create_file(filename, ds))
257         return -1;
258     } else {
259       ERROR("stat(%s) failed: %s", filename, STRERRNO);
260       return -1;
261     }
262   } else if (!S_ISREG(statbuf.st_mode)) {
263     ERROR("stat(%s): Not a regular file!", filename);
264     return -1;
265   }
266
267   csv = fopen(filename, "a");
268   if (csv == NULL) {
269     ERROR("csv plugin: fopen (%s) failed: %s", filename, STRERRNO);
270     return -1;
271   }
272   csv_fd = fileno(csv);
273
274   fl.l_pid = getpid();
275   fl.l_type = F_WRLCK;
276   fl.l_whence = SEEK_SET;
277
278   status = fcntl(csv_fd, F_SETLK, &fl);
279   if (status != 0) {
280     ERROR("csv plugin: flock (%s) failed: %s", filename, STRERRNO);
281     fclose(csv);
282     return -1;
283   }
284
285   fprintf(csv, "%s\n", values);
286
287   /* The lock is implicitely released. I we don't release it explicitely
288    * because the `FILE *' may need to flush a cache first */
289   fclose(csv);
290
291   return 0;
292 } /* int csv_write */
293
294 void module_register(void) {
295   plugin_register_config("csv", csv_config, config_keys, config_keys_num);
296   plugin_register_write("csv", csv_write, /* user_data = */ NULL);
297 } /* void module_register */