Merge pull request #1557 from rpv-tomsk/master
[collectd.git] / src / daemon / common.h
1 /**
2  * collectd - src/common.h
3  * Copyright (C) 2005-2014  Florian octo Forster
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *   Florian octo Forster <octo at collectd.org>
25  *   Niki W. Waibel <niki.waibel@gmx.net>
26 **/
27
28 #ifndef COMMON_H
29 #define COMMON_H
30
31 #include "collectd.h"
32 #include "plugin.h"
33
34 #if HAVE_PWD_H
35 # include <pwd.h>
36 #endif
37
38 #define sfree(ptr) \
39         do { \
40                 free(ptr); \
41                 (ptr) = NULL; \
42         } while (0)
43
44 #define STATIC_ARRAY_SIZE(a) (sizeof (a) / sizeof (*(a)))
45
46 #define IS_TRUE(s) ((strcasecmp ("true", (s)) == 0) \
47                 || (strcasecmp ("yes", (s)) == 0) \
48                 || (strcasecmp ("on", (s)) == 0))
49 #define IS_FALSE(s) ((strcasecmp ("false", (s)) == 0) \
50                 || (strcasecmp ("no", (s)) == 0) \
51                 || (strcasecmp ("off", (s)) == 0))
52
53 struct rate_to_value_state_s
54 {
55   value_t last_value;
56   cdtime_t last_time;
57   gauge_t residual;
58 };
59 typedef struct rate_to_value_state_s rate_to_value_state_t;
60
61 struct value_to_rate_state_s
62 {
63   value_t last_value;
64   cdtime_t last_time;
65 };
66 typedef struct value_to_rate_state_s value_to_rate_state_t;
67
68 char *sstrncpy (char *dest, const char *src, size_t n);
69
70 __attribute__ ((format(printf,3,4)))
71 int ssnprintf (char *dest, size_t n, const char *format, ...);
72
73 __attribute__ ((format(printf,1,2)))
74 char *ssnprintf_alloc (char const *format, ...);
75
76 char *sstrdup(const char *s);
77 void *smalloc(size_t size);
78 char *sstrerror (int errnum, char *buf, size_t buflen);
79
80 /*
81  * NAME
82  *   sread
83  *
84  * DESCRIPTION
85  *   Reads exactly `n' bytes or fails. Syntax and other behavior is analogous
86  *   to `read(2)'. If EOF is received the file descriptor is closed and an
87  *   error is returned.
88  *
89  * PARAMETERS
90  *   `fd'          File descriptor to write to.
91  *   `buf'         Buffer that is to be written.
92  *   `count'       Number of bytes in the buffer.
93  *
94  * RETURN VALUE
95  *   Zero upon success or non-zero if an error occurred. `errno' is set in this
96  *   case.
97  */
98 ssize_t sread (int fd, void *buf, size_t count);
99
100 /*
101  * NAME
102  *   swrite
103  *
104  * DESCRIPTION
105  *   Writes exactly `n' bytes or fails. Syntax and other behavior is analogous
106  *   to `write(2)'.
107  *
108  * PARAMETERS
109  *   `fd'          File descriptor to write to.
110  *   `buf'         Buffer that is to be written.
111  *   `count'       Number of bytes in the buffer.
112  *
113  * RETURN VALUE
114  *   Zero upon success or non-zero if an error occurred. `errno' is set in this
115  *   case.
116  */
117 ssize_t swrite (int fd, const void *buf, size_t count);
118
119 /*
120  * NAME
121  *   strsplit
122  *
123  * DESCRIPTION
124  *   Splits a string into parts and stores pointers to the parts in `fields'.
125  *   The characters split at are: " ", "\t", "\r", and "\n".
126  *
127  * PARAMETERS
128  *   `string'      String to split. This string will be modified. `fields' will
129  *                 contain pointers to parts of this string, so free'ing it
130  *                 will destroy `fields' as well.
131  *   `fields'      Array of strings where pointers to the parts will be stored.
132  *   `size'        Number of elements in the array. No more than `size'
133  *                 pointers will be stored in `fields'.
134  *
135  * RETURN VALUE
136  *    Returns the number of parts stored in `fields'.
137  */
138 int strsplit (char *string, char **fields, size_t size);
139
140 /*
141  * NAME
142  *   strjoin
143  *
144  * DESCRIPTION
145  *   Joins together several parts of a string using `sep' as a separator. This
146  *   is equivalent to the Perl built-in `join'.
147  *
148  * PARAMETERS
149  *   `dst'         Buffer where the result is stored.
150  *   `dst_len'     Length of the destination buffer. No more than this many
151  *                 bytes will be written to the memory pointed to by `dst',
152  *                 including the trailing null-byte.
153  *   `fields'      Array of strings to be joined.
154  *   `fields_num'  Number of elements in the `fields' array.
155  *   `sep'         String to be inserted between any two elements of `fields'.
156  *                 This string is neither prepended nor appended to the result.
157  *                 Instead of passing "" (empty string) one can pass NULL.
158  *
159  * RETURN VALUE
160  *   Returns the number of characters in `dst', NOT including the trailing
161  *   null-byte. If an error occurred (empty array or `dst' too small) a value
162  *   smaller than zero will be returned.
163  */
164 int strjoin (char *dst, size_t dst_len, char **fields, size_t fields_num, const char *sep);
165
166 /*
167  * NAME
168  *   escape_slashes
169  *
170  * DESCRIPTION
171  *   Removes slashes ("/") from "buffer". If buffer contains a single slash,
172  *   the result will be "root". Leading slashes are removed. All other slashes
173  *   are replaced with underscores ("_").
174  *   This function is used by plugin_dispatch_values() to escape all parts of
175  *   the identifier.
176  *
177  * PARAMETERS
178  *   `buffer'         String to be escaped.
179  *   `buffer_size'    Size of the buffer. No more then this many bytes will be
180  *                    written to `buffer', including the trailing null-byte.
181  *
182  * RETURN VALUE
183  *   Returns zero upon success and a value smaller than zero upon failure.
184  */
185 int escape_slashes (char *buffer, size_t buffer_size);
186
187 /**
188  * NAME
189  *   escape_string
190  *
191  * DESCRIPTION
192  *   escape_string quotes and escapes a string to be usable with collectd's
193  *   plain text protocol. "simple" strings are left as they are, for example if
194  *   buffer is 'simple' before the call, it will remain 'simple'. However, if
195  *   buffer contains 'more "complex"' before the call, the returned buffer will
196  *   contain '"more \"complex\""'.
197  *
198  *   If the buffer is too small to contain the escaped string, the string will
199  *   be truncated. However, leading and trailing double quotes, as well as an
200  *   ending null byte are guaranteed.
201  *
202  * RETURN VALUE
203  *   Returns zero on success, even if the string was truncated. Non-zero on
204  *   failure.
205  */
206 int escape_string (char *buffer, size_t buffer_size);
207
208 /*
209  * NAME
210  *   replace_special
211  *
212  * DESCRIPTION
213  *   Replaces any special characters (anything that's not alpha-numeric or a
214  *   dash) with an underscore.
215  *
216  *   E.g. "foo$bar&" would become "foo_bar_".
217  *
218  * PARAMETERS
219  *   `buffer'      String to be handled.
220  *   `buffer_size' Length of the string. The function returns after
221  *                 encountering a null-byte or reading this many bytes.
222  */
223 void replace_special (char *buffer, size_t buffer_size);
224
225 /*
226  * NAME
227  *   strunescape
228  *
229  * DESCRIPTION
230  *   Replaces any escaped characters in a string with the appropriate special
231  *   characters. The following escaped characters are recognized:
232  *
233  *     \t -> <tab>
234  *     \n -> <newline>
235  *     \r -> <carriage return>
236  *
237  *   For all other escacped characters only the backslash will be removed.
238  *
239  * PARAMETERS
240  *   `buf'         String to be unescaped.
241  *   `buf_len'     Length of the string, including the terminating null-byte.
242  *
243  * RETURN VALUE
244  *   Returns zero upon success, a value less than zero else.
245  */
246 int strunescape (char *buf, size_t buf_len);
247
248 /**
249  * Removed trailing newline characters (CR and LF) from buffer, which must be
250  * null terminated. Returns the length of the resulting string.
251  */
252 __attribute__((nonnull (1)))
253 size_t strstripnewline (char *buffer);
254
255 /*
256  * NAME
257  *   timeval_cmp
258  *
259  * DESCRIPTION
260  *   Compare the two time values `tv0' and `tv1' and store the absolut value
261  *   of the difference in the time value pointed to by `delta' if it does not
262  *   equal NULL.
263  *
264  * RETURN VALUE
265  *   Returns an integer less than, equal to, or greater than zero if `tv0' is
266  *   less than, equal to, or greater than `tv1' respectively.
267  */
268 int timeval_cmp (struct timeval tv0, struct timeval tv1, struct timeval *delta);
269
270 /* make sure tv_usec stores less than a second */
271 #define NORMALIZE_TIMEVAL(tv) \
272         do { \
273                 (tv).tv_sec += (tv).tv_usec / 1000000; \
274                 (tv).tv_usec = (tv).tv_usec % 1000000; \
275         } while (0)
276
277 /* make sure tv_sec stores less than a second */
278 #define NORMALIZE_TIMESPEC(tv) \
279         do { \
280                 (tv).tv_sec += (tv).tv_nsec / 1000000000; \
281                 (tv).tv_nsec = (tv).tv_nsec % 1000000000; \
282         } while (0)
283
284 int check_create_dir (const char *file_orig);
285
286 #ifdef HAVE_LIBKSTAT
287 int get_kstat (kstat_t **ksp_ptr, char *module, int instance, char *name);
288 long long get_kstat_value (kstat_t *ksp, char *name);
289 #endif
290
291 #ifndef HAVE_HTONLL
292 unsigned long long ntohll (unsigned long long n);
293 unsigned long long htonll (unsigned long long n);
294 #endif
295
296 #if FP_LAYOUT_NEED_NOTHING
297 # define ntohd(d) (d)
298 # define htond(d) (d)
299 #elif FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP
300 double ntohd (double d);
301 double htond (double d);
302 #else
303 # error "Don't know how to convert between host and network representation of doubles."
304 #endif
305
306 int format_name (char *ret, int ret_len,
307                 const char *hostname,
308                 const char *plugin, const char *plugin_instance,
309                 const char *type, const char *type_instance);
310 #define FORMAT_VL(ret, ret_len, vl) \
311         format_name (ret, ret_len, (vl)->host, (vl)->plugin, (vl)->plugin_instance, \
312                         (vl)->type, (vl)->type_instance)
313 int format_values (char *ret, size_t ret_len,
314                 const data_set_t *ds, const value_list_t *vl,
315                 _Bool store_rates);
316
317 int parse_identifier (char *str, char **ret_host,
318                 char **ret_plugin, char **ret_plugin_instance,
319                 char **ret_type, char **ret_type_instance);
320 int parse_identifier_vl (const char *str, value_list_t *vl);
321 int parse_value (const char *value, value_t *ret_value, int ds_type);
322 int parse_values (char *buffer, value_list_t *vl, const data_set_t *ds);
323
324 #if !HAVE_GETPWNAM_R
325 int getpwnam_r (const char *name, struct passwd *pwbuf, char *buf,
326                 size_t buflen, struct passwd **pwbufp);
327 #endif
328
329 int notification_init (notification_t *n, int severity, const char *message,
330                 const char *host,
331                 const char *plugin, const char *plugin_instance,
332                 const char *type, const char *type_instance);
333 #define NOTIFICATION_INIT_VL(n, vl) \
334         notification_init (n, NOTIF_FAILURE, NULL, \
335                         (vl)->host, (vl)->plugin, (vl)->plugin_instance, \
336                         (vl)->type, (vl)->type_instance)
337
338 typedef int (*dirwalk_callback_f)(const char *dirname, const char *filename,
339                 void *user_data);
340 int walk_directory (const char *dir, dirwalk_callback_f callback,
341                 void *user_data, int hidden);
342 /* Returns the number of bytes read or negative on error. */
343 ssize_t read_file_contents (char const *filename, char *buf, size_t bufsize);
344
345 counter_t counter_diff (counter_t old_value, counter_t new_value);
346
347 /* Convert a rate back to a value_t. When converting to a derive_t, counter_t
348  * or absoltue_t, take fractional residuals into account. This is important
349  * when scaling counters, for example.
350  * Returns zero on success. Returns EAGAIN when called for the first time; in
351  * this case the value_t is invalid and the next call should succeed. Other
352  * return values indicate an error. */
353 int rate_to_value (value_t *ret_value, gauge_t rate,
354                 rate_to_value_state_t *state, int ds_type, cdtime_t t);
355
356 int value_to_rate (gauge_t *ret_rate, value_t value, int ds_type, cdtime_t t,
357                 value_to_rate_state_t *state);
358
359 /* Converts a service name (a string) to a port number
360  * (in the range [1-65535]). Returns less than zero on error. */
361 int service_name_to_port_number (const char *service_name);
362
363 /** Parse a string to a derive_t value. Returns zero on success or non-zero on
364  * failure. If failure is returned, ret_value is not touched. */
365 int strtoderive (const char *string, derive_t *ret_value);
366
367 /** Parse a string to a gauge_t value. Returns zero on success or non-zero on
368  * failure. If failure is returned, ret_value is not touched. */
369 int strtogauge (const char *string, gauge_t *ret_value);
370
371 int strarray_add (char ***ret_array, size_t *ret_array_len, char const *str);
372 void strarray_free (char **array, size_t array_len);
373
374 #endif /* COMMON_H */