Merge branch 'collectd-5.7'
[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 = ssnprintf(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 = ssnprintf(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 =
76           ssnprintf(buffer + offset, buffer_len - offset, ",%lf", rates[i]);
77     } else if (ds->ds[i].type == DS_TYPE_COUNTER) {
78       status = ssnprintf(buffer + offset, buffer_len - offset, ",%llu",
79                          vl->values[i].counter);
80     } else if (ds->ds[i].type == DS_TYPE_DERIVE) {
81       status = ssnprintf(buffer + offset, buffer_len - offset, ",%" PRIi64,
82                          vl->values[i].derive);
83     } else if (ds->ds[i].type == DS_TYPE_ABSOLUTE) {
84       status = ssnprintf(buffer + offset, buffer_len - offset, ",%" PRIu64,
85                          vl->values[i].absolute);
86     }
87
88     if ((status < 1) || (status >= (buffer_len - offset))) {
89       sfree(rates);
90       return -1;
91     }
92
93     offset += status;
94   } /* for ds->ds_num */
95
96   sfree(rates);
97   return 0;
98 } /* int value_list_to_string */
99
100 static int value_list_to_filename(char *buffer, size_t buffer_size,
101                                   value_list_t const *vl) {
102   int status;
103
104   char *ptr = buffer;
105   size_t ptr_size = buffer_size;
106   time_t now;
107   struct tm struct_tm;
108
109   if (datadir != NULL) {
110     size_t len = strlen(datadir) + 1;
111
112     if (len >= ptr_size)
113       return ENOBUFS;
114
115     memcpy(ptr, datadir, len);
116     ptr[len - 1] = '/';
117     ptr_size -= len;
118     ptr += len;
119   }
120
121   status = FORMAT_VL(ptr, ptr_size, vl);
122   if (status != 0)
123     return status;
124
125   /* Skip all the time formatting stuff when printing to STDOUT or
126    * STDERR. */
127   if (use_stdio)
128     return 0;
129
130   ptr_size -= strlen(ptr);
131   ptr += strlen(ptr);
132
133   /* "-2013-07-12" => 11 bytes */
134   if (ptr_size < 12) {
135     ERROR("csv plugin: Buffer too small.");
136     return ENOMEM;
137   }
138
139   /* TODO: Find a way to minimize the calls to `localtime_r',
140    * since they are pretty expensive.. */
141   now = time(NULL);
142   if (localtime_r(&now, &struct_tm) == NULL) {
143     ERROR("csv plugin: localtime_r failed");
144     return -1;
145   }
146
147   status = strftime(ptr, ptr_size, "-%Y-%m-%d", &struct_tm);
148   if (status == 0) /* yep, it returns zero on error. */
149   {
150     ERROR("csv plugin: strftime failed");
151     return -1;
152   }
153
154   return 0;
155 } /* int value_list_to_filename */
156
157 static int csv_create_file(const char *filename, const data_set_t *ds) {
158   FILE *csv;
159
160   if (check_create_dir(filename))
161     return -1;
162
163   csv = fopen(filename, "w");
164   if (csv == NULL) {
165     char errbuf[1024];
166     ERROR("csv plugin: fopen (%s) failed: %s", filename,
167           sstrerror(errno, errbuf, sizeof(errbuf)));
168     return -1;
169   }
170
171   fprintf(csv, "epoch");
172   for (size_t i = 0; i < ds->ds_num; i++)
173     fprintf(csv, ",%s", ds->ds[i].name);
174
175   fprintf(csv, "\n");
176   fclose(csv);
177
178   return 0;
179 } /* int csv_create_file */
180
181 static int csv_config(const char *key, const char *value) {
182   if (strcasecmp("DataDir", key) == 0) {
183     if (datadir != NULL) {
184       free(datadir);
185       datadir = NULL;
186     }
187     if (strcasecmp("stdout", value) == 0) {
188       use_stdio = 1;
189       return 0;
190     } else if (strcasecmp("stderr", value) == 0) {
191       use_stdio = 2;
192       return 0;
193     }
194     datadir = strdup(value);
195     if (datadir != NULL) {
196       int len = strlen(datadir);
197       while ((len > 0) && (datadir[len - 1] == '/')) {
198         len--;
199         datadir[len] = '\0';
200       }
201       if (len <= 0) {
202         free(datadir);
203         datadir = NULL;
204       }
205     }
206   } else if (strcasecmp("StoreRates", key) == 0) {
207     if (IS_TRUE(value))
208       store_rates = 1;
209     else
210       store_rates = 0;
211   } else {
212     return -1;
213   }
214   return 0;
215 } /* int csv_config */
216
217 static int csv_write(const data_set_t *ds, const value_list_t *vl,
218                      user_data_t __attribute__((unused)) * user_data) {
219   struct stat statbuf;
220   char filename[512];
221   char values[4096];
222   FILE *csv;
223   int csv_fd;
224   struct flock fl = {0};
225   int status;
226
227   if (0 != strcmp(ds->type, vl->type)) {
228     ERROR("csv plugin: DS type does not match value list type");
229     return -1;
230   }
231
232   status = value_list_to_filename(filename, sizeof(filename), vl);
233   if (status != 0)
234     return -1;
235
236   DEBUG("csv plugin: csv_write: filename = %s;", filename);
237
238   if (value_list_to_string(values, sizeof(values), ds, vl) != 0)
239     return -1;
240
241   if (use_stdio) {
242     escape_string(filename, sizeof(filename));
243
244     /* Replace commas by colons for PUTVAL compatible output. */
245     for (size_t i = 0; i < sizeof(values); i++) {
246       if (values[i] == 0)
247         break;
248       else if (values[i] == ',')
249         values[i] = ':';
250     }
251
252     fprintf(use_stdio == 1 ? stdout : stderr, "PUTVAL %s interval=%.3f %s\n",
253             filename, CDTIME_T_TO_DOUBLE(vl->interval), values);
254     return 0;
255   }
256
257   if (stat(filename, &statbuf) == -1) {
258     if (errno == ENOENT) {
259       if (csv_create_file(filename, ds))
260         return -1;
261     } else {
262       char errbuf[1024];
263       ERROR("stat(%s) failed: %s", filename,
264             sstrerror(errno, errbuf, sizeof(errbuf)));
265       return -1;
266     }
267   } else if (!S_ISREG(statbuf.st_mode)) {
268     ERROR("stat(%s): Not a regular file!", filename);
269     return -1;
270   }
271
272   csv = fopen(filename, "a");
273   if (csv == NULL) {
274     char errbuf[1024];
275     ERROR("csv plugin: fopen (%s) failed: %s", filename,
276           sstrerror(errno, errbuf, sizeof(errbuf)));
277     return -1;
278   }
279   csv_fd = fileno(csv);
280
281   fl.l_pid = getpid();
282   fl.l_type = F_WRLCK;
283   fl.l_whence = SEEK_SET;
284
285   status = fcntl(csv_fd, F_SETLK, &fl);
286   if (status != 0) {
287     char errbuf[1024];
288     ERROR("csv plugin: flock (%s) failed: %s", filename,
289           sstrerror(errno, errbuf, sizeof(errbuf)));
290     fclose(csv);
291     return -1;
292   }
293
294   fprintf(csv, "%s\n", values);
295
296   /* The lock is implicitely released. I we don't release it explicitely
297    * because the `FILE *' may need to flush a cache first */
298   fclose(csv);
299
300   return 0;
301 } /* int csv_write */
302
303 void module_register(void) {
304   plugin_register_config("csv", csv_config, config_keys, config_keys_num);
305   plugin_register_write("csv", csv_write, /* user_data = */ NULL);
306 } /* void module_register */