Apply suggestions from code review
[collectd.git] / src / utils / format_graphite / format_graphite.c
1 /**
2  * collectd - src/utils_format_graphite.c
3  * Copyright (C) 2012  Thomas Meson
4  * Copyright (C) 2012  Florian octo Forster
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  *   Thomas Meson <zllak at hycik.org>
21  *   Florian octo Forster <octo at collectd.org>
22  **/
23
24 #include "collectd.h"
25
26 #include "plugin.h"
27 #include "utils/common/common.h"
28
29 #include "utils/format_graphite/format_graphite.h"
30 #include "utils_cache.h"
31
32 #define GRAPHITE_FORBIDDEN " \t\"\\:!/()\n\r"
33
34 /* Utils functions to format data sets in graphite format.
35  * Largely taken from write_graphite.c as it remains the same formatting */
36
37 /* helper function for reverse_hostname */
38 void reverse_string(char *r_host, int len) {
39   char t;
40   for (int i = 0, j = len - 1; i < j; i++, j--) {
41     t = r_host[i];
42     r_host[i] = r_host[j];
43     r_host[j] = t;
44   }
45 }
46
47 void reverse_hostname(char *r_host, char const *orig_host) {
48   int len_host = strlen(orig_host);
49
50   /* put reversed hostname into working copy */
51   for (int i = 0; i < len_host; i++)
52     r_host[i] = orig_host[len_host - 1 - i];
53   r_host[len_host] = '\0';
54
55   /* reverse labels (except last) */
56   int p = 0;
57   for (int i = 0; i < len_host; i++)
58     if (r_host[i] == '.') {
59       reverse_string(&r_host[p], i - p);
60       p = i + 1;
61     }
62
63   /* reverse last label */
64   reverse_string(&r_host[p], len_host - p);
65 }
66
67 static int gr_format_values(char *ret, size_t ret_len, int ds_num,
68                             const data_set_t *ds, const value_list_t *vl,
69                             gauge_t const *rates) {
70   size_t offset = 0;
71   int status;
72
73   assert(0 == strcmp(ds->type, vl->type));
74
75   memset(ret, 0, ret_len);
76
77 #define BUFFER_ADD(...)                                                        \
78   do {                                                                         \
79     status = snprintf(ret + offset, ret_len - offset, __VA_ARGS__);            \
80     if (status < 1) {                                                          \
81       return -1;                                                               \
82     } else if (((size_t)status) >= (ret_len - offset)) {                       \
83       return -1;                                                               \
84     } else                                                                     \
85       offset += ((size_t)status);                                              \
86   } while (0)
87
88   if (ds->ds[ds_num].type == DS_TYPE_GAUGE)
89     BUFFER_ADD(GAUGE_FORMAT, vl->values[ds_num].gauge);
90   else if (rates != NULL)
91     BUFFER_ADD("%f", rates[ds_num]);
92   else if (ds->ds[ds_num].type == DS_TYPE_COUNTER)
93     BUFFER_ADD("%" PRIu64, (uint64_t)vl->values[ds_num].counter);
94   else if (ds->ds[ds_num].type == DS_TYPE_DERIVE)
95     BUFFER_ADD("%" PRIi64, vl->values[ds_num].derive);
96   else if (ds->ds[ds_num].type == DS_TYPE_ABSOLUTE)
97     BUFFER_ADD("%" PRIu64, vl->values[ds_num].absolute);
98   else {
99     P_ERROR("gr_format_values: Unknown data source type: %i",
100             ds->ds[ds_num].type);
101     return -1;
102   }
103
104 #undef BUFFER_ADD
105
106   return 0;
107 }
108
109 static void gr_copy_escape_part(char *dst, const char *src, size_t dst_len,
110                                 char escape_char, bool preserve_separator) {
111   memset(dst, 0, dst_len);
112
113   if (src == NULL)
114     return;
115
116   for (size_t i = 0; i < dst_len; i++) {
117     if (src[i] == 0) {
118       dst[i] = 0;
119       break;
120     }
121
122     if ((!preserve_separator && (src[i] == '.')) || isspace((int)src[i]) ||
123         iscntrl((int)src[i]))
124       dst[i] = escape_char;
125     else
126       dst[i] = src[i];
127   }
128 }
129
130 static int gr_format_name_tagged(char *ret, int ret_len, value_list_t const *vl,
131                                  char const *ds_name, char const *prefix,
132                                  char const *postfix, char const escape_char,
133                                  unsigned int flags) {
134   char n_host[DATA_MAX_NAME_LEN];
135   char n_plugin[DATA_MAX_NAME_LEN];
136   char n_plugin_instance[DATA_MAX_NAME_LEN];
137   char n_type[DATA_MAX_NAME_LEN];
138   char n_type_instance[DATA_MAX_NAME_LEN];
139
140   char tmp_plugin[DATA_MAX_NAME_LEN + 8];
141   char tmp_plugin_instance[DATA_MAX_NAME_LEN + 17];
142   char tmp_type[DATA_MAX_NAME_LEN + 6];
143   char tmp_type_instance[DATA_MAX_NAME_LEN + 15];
144   char tmp_metric[3 * DATA_MAX_NAME_LEN + 2];
145   char tmp_ds_name[DATA_MAX_NAME_LEN + 9];
146
147   if (prefix == NULL)
148     prefix = "";
149
150   if (postfix == NULL)
151     postfix = "";
152
153   if (flags & GRAPHITE_REVERSE_HOST) {
154     char r_host[DATA_MAX_NAME_LEN];
155     reverse_hostname(r_host, vl->host);
156     gr_copy_escape_part(n_host, r_host, sizeof(n_host), escape_char, 1);
157   } else {
158     gr_copy_escape_part(n_host, vl->host, sizeof(n_host), escape_char, 1);
159   }
160   gr_copy_escape_part(n_plugin, vl->plugin, sizeof(n_plugin), escape_char, 1);
161   gr_copy_escape_part(n_plugin_instance, vl->plugin_instance,
162                       sizeof(n_plugin_instance), escape_char, 1);
163   gr_copy_escape_part(n_type, vl->type, sizeof(n_type), escape_char, 1);
164   gr_copy_escape_part(n_type_instance, vl->type_instance,
165                       sizeof(n_type_instance), escape_char, 1);
166
167   snprintf(tmp_plugin, sizeof(tmp_plugin), ";plugin=%s", n_plugin);
168
169   if (n_plugin_instance[0] != '\0')
170     snprintf(tmp_plugin_instance, sizeof(tmp_plugin_instance),
171              ";plugin_instance=%s", n_plugin_instance);
172   else
173     tmp_plugin_instance[0] = '\0';
174
175   if (!(flags & GRAPHITE_DROP_DUPE_FIELDS) || strcmp(n_plugin, n_type) != 0)
176     snprintf(tmp_type, sizeof(tmp_type), ";type=%s", n_type);
177   else
178     tmp_type[0] = '\0';
179
180   if (n_type_instance[0] != '\0') {
181     if (!(flags & GRAPHITE_DROP_DUPE_FIELDS) ||
182         strcmp(n_plugin_instance, n_type_instance) != 0)
183       snprintf(tmp_type_instance, sizeof(tmp_type_instance),
184                ";type_instance=%s", n_type_instance);
185     else
186       tmp_type_instance[0] = '\0';
187   } else
188     tmp_type_instance[0] = '\0';
189
190   /* Assert always_append_ds -> ds_name */
191   assert(!(flags & GRAPHITE_ALWAYS_APPEND_DS) || (ds_name != NULL));
192   if (ds_name != NULL) {
193     snprintf(tmp_ds_name, sizeof(tmp_ds_name), ";ds_name=%s", ds_name);
194
195     if ((flags & GRAPHITE_DROP_DUPE_FIELDS) && strcmp(n_plugin, n_type) == 0)
196       snprintf(tmp_metric, sizeof(tmp_metric), "%s.%s", n_plugin, ds_name);
197     else
198       snprintf(tmp_metric, sizeof(tmp_metric), "%s.%s.%s", n_plugin, n_type,
199                ds_name);
200   } else {
201     tmp_ds_name[0] = '\0';
202
203     if ((flags & GRAPHITE_DROP_DUPE_FIELDS) && strcmp(n_plugin, n_type) == 0)
204       snprintf(tmp_metric, sizeof(tmp_metric), "%s", n_plugin);
205     else
206       snprintf(tmp_metric, sizeof(tmp_metric), "%s.%s", n_plugin, n_type);
207   }
208
209   snprintf(ret, ret_len, "%s%s%s;host=%s%s%s%s%s%s", prefix, tmp_metric,
210            postfix, n_host, tmp_plugin, tmp_plugin_instance, tmp_type,
211            tmp_type_instance, tmp_ds_name);
212
213   return 0;
214 }
215
216 static int gr_format_name(char *ret, int ret_len, value_list_t const *vl,
217                           char const *ds_name, char const *prefix,
218                           char const *postfix, char const escape_char,
219                           unsigned int flags) {
220   char n_host[DATA_MAX_NAME_LEN];
221   char n_plugin[DATA_MAX_NAME_LEN];
222   char n_plugin_instance[DATA_MAX_NAME_LEN];
223   char n_type[DATA_MAX_NAME_LEN];
224   char n_type_instance[DATA_MAX_NAME_LEN];
225
226   char tmp_plugin[2 * DATA_MAX_NAME_LEN + 1];
227   char tmp_type[2 * DATA_MAX_NAME_LEN + 1];
228
229   if (prefix == NULL)
230     prefix = "";
231
232   if (postfix == NULL)
233     postfix = "";
234
235   bool preserve_separator = (flags & GRAPHITE_PRESERVE_SEPARATOR);
236
237   if (flags & GRAPHITE_REVERSE_HOST) {
238     char r_host[DATA_MAX_NAME_LEN];
239     reverse_hostname(r_host, vl->host);
240     gr_copy_escape_part(n_host, r_host, sizeof(n_host), escape_char,
241                         preserve_separator);
242   } else {
243     gr_copy_escape_part(n_host, vl->host, sizeof(n_host), escape_char,
244                         preserve_separator);
245   }
246   gr_copy_escape_part(n_plugin, vl->plugin, sizeof(n_plugin), escape_char,
247                       preserve_separator);
248   gr_copy_escape_part(n_plugin_instance, vl->plugin_instance,
249                       sizeof(n_plugin_instance), escape_char,
250                       preserve_separator);
251   gr_copy_escape_part(n_type, vl->type, sizeof(n_type), escape_char,
252                       preserve_separator);
253   gr_copy_escape_part(n_type_instance, vl->type_instance,
254                       sizeof(n_type_instance), escape_char, preserve_separator);
255
256   if (n_plugin_instance[0] != '\0')
257     snprintf(tmp_plugin, sizeof(tmp_plugin), "%s%c%s", n_plugin,
258              (flags & GRAPHITE_SEPARATE_INSTANCES) ? '.' : '-',
259              n_plugin_instance);
260   else
261     sstrncpy(tmp_plugin, n_plugin, sizeof(tmp_plugin));
262
263   if (n_type_instance[0] != '\0') {
264     if ((flags & GRAPHITE_DROP_DUPE_FIELDS) && strcmp(n_plugin, n_type) == 0)
265       sstrncpy(tmp_type, n_type_instance, sizeof(tmp_type));
266     else
267       snprintf(tmp_type, sizeof(tmp_type), "%s%c%s", n_type,
268                (flags & GRAPHITE_SEPARATE_INSTANCES) ? '.' : '-',
269                n_type_instance);
270   } else
271     sstrncpy(tmp_type, n_type, sizeof(tmp_type));
272
273   /* Assert always_append_ds -> ds_name */
274   assert(!(flags & GRAPHITE_ALWAYS_APPEND_DS) || (ds_name != NULL));
275   if (ds_name != NULL) {
276     if ((flags & GRAPHITE_DROP_DUPE_FIELDS) &&
277         strcmp(tmp_plugin, tmp_type) == 0)
278       snprintf(ret, ret_len, "%s%s%s.%s.%s", prefix, n_host, postfix,
279                tmp_plugin, ds_name);
280     else
281       snprintf(ret, ret_len, "%s%s%s.%s.%s.%s", prefix, n_host, postfix,
282                tmp_plugin, tmp_type, ds_name);
283   } else
284     snprintf(ret, ret_len, "%s%s%s.%s.%s", prefix, n_host, postfix, tmp_plugin,
285              tmp_type);
286
287   return 0;
288 }
289
290 static void escape_graphite_string(char *buffer, char escape_char) {
291   assert(strchr(GRAPHITE_FORBIDDEN, escape_char) == NULL);
292
293   for (char *head = buffer + strcspn(buffer, GRAPHITE_FORBIDDEN); *head != '\0';
294        head += strcspn(head, GRAPHITE_FORBIDDEN))
295     *head = escape_char;
296 }
297
298 int format_graphite(char *buffer, size_t buffer_size, data_set_t const *ds,
299                     value_list_t const *vl, char const *prefix,
300                     char const *postfix, char const escape_char,
301                     unsigned int flags) {
302   int status = 0;
303   int buffer_pos = 0;
304
305   gauge_t *rates = NULL;
306   if (flags & GRAPHITE_STORE_RATES) {
307     rates = uc_get_rate(ds, vl);
308     if (rates == NULL) {
309       P_ERROR("format_graphite: error with uc_get_rate");
310       return -1;
311     }
312   }
313
314   for (size_t i = 0; i < ds->ds_num; i++) {
315     char const *ds_name = NULL;
316     char key[10 * DATA_MAX_NAME_LEN];
317     char values[512];
318     size_t message_len;
319     char message[1024];
320
321     if ((flags & GRAPHITE_ALWAYS_APPEND_DS) || (ds->ds_num > 1))
322       ds_name = ds->ds[i].name;
323
324     /* Copy the identifier to `key' and escape it. */
325     if (flags & GRAPHITE_USE_TAGS) {
326       status = gr_format_name_tagged(key, sizeof(key), vl, ds_name, prefix,
327                                      postfix, escape_char, flags);
328       if (status != 0) {
329         P_ERROR("format_graphite: error with gr_format_name_tagged");
330         sfree(rates);
331         return status;
332       }
333     } else {
334       status = gr_format_name(key, sizeof(key), vl, ds_name, prefix, postfix,
335                               escape_char, flags);
336       if (status != 0) {
337         P_ERROR("format_graphite: error with gr_format_name");
338         sfree(rates);
339         return status;
340       }
341     }
342
343     escape_graphite_string(key, escape_char);
344
345     /* Convert the values to an ASCII representation and put that into
346      * `values'. */
347     status = gr_format_values(values, sizeof(values), i, ds, vl, rates);
348     if (status != 0) {
349       P_ERROR("format_graphite: error with gr_format_values");
350       sfree(rates);
351       return status;
352     }
353
354     /* Compute the graphite command */
355     message_len =
356         (size_t)snprintf(message, sizeof(message), "%s %s %u\r\n", key, values,
357                          (unsigned int)CDTIME_T_TO_TIME_T(vl->time));
358     if (message_len >= sizeof(message)) {
359       P_ERROR("format_graphite: message buffer too small: "
360               "Need %" PRIsz " bytes.",
361               message_len + 1);
362       sfree(rates);
363       return -ENOMEM;
364     }
365
366     /* Append it in case we got multiple data set */
367     if ((buffer_pos + message_len) >= buffer_size) {
368       P_ERROR("format_graphite: target buffer too small");
369       sfree(rates);
370       return -ENOMEM;
371     }
372     memcpy((void *)(buffer + buffer_pos), message, message_len);
373     buffer_pos += message_len;
374     buffer[buffer_pos] = '\0';
375   }
376   sfree(rates);
377   return status;
378 } /* int format_graphite */