summaryrefslogtreecommitdiff
path: root/res/res_statsd.c
blob: aee0bcd5a00a97df4525d20a8c25cd1a09f4e7ed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
/*
 * Asterisk -- An open source telephony toolkit.
 *
 * Copyright (C) 2013, Digium, Inc.
 *
 * David M. Lee, II <dlee@digium.com>
 *
 * See http://www.asterisk.org for more information about
 * the Asterisk project. Please do not directly contact
 * any of the maintainers of this project for assistance;
 * the project provides a web site, mailing lists and IRC
 * channels for your use.
 *
 * This program is free software, distributed under the terms of
 * the GNU General Public License Version 2. See the LICENSE file
 * at the top of the source tree.
 */

/*!
 * \brief Support for publishing to a statsd server.
 *
 * \author David M. Lee, II <dlee@digium.com>
 * \since 12
 */

/*** MODULEINFO
	<support_level>extended</support_level>
 ***/

/*** DOCUMENTATION
	<configInfo name="res_statsd" language="en_US">
		<synopsis>Statsd client.</synopsis>
		<configFile name="statsd.conf">
			<configObject name="global">
				<synopsis>Global configuration settings</synopsis>
				<configOption name="enabled">
					<synopsis>Enable/disable the statsd module</synopsis>
				</configOption>
				<configOption name="server">
					<synopsis>Address of the statsd server</synopsis>
				</configOption>
				<configOption name="prefix">
					<synopsis>Prefix to prepend to every metric</synopsis>
				</configOption>
				<configOption name="add_newline">
					<synopsis>Append a newline to every event. This is useful if you want to fake out a server using netcat (nc -lu 8125)</synopsis>
				</configOption>
			</configObject>
		</configFile>
	</configInfo>
***/

#include "asterisk.h"

#include "asterisk/config_options.h"
#include "asterisk/module.h"
#include "asterisk/netsock2.h"

#define AST_API_MODULE
#include "asterisk/statsd.h"

#define DEFAULT_STATSD_PORT 8125

#define MAX_PREFIX 40

/*! Socket for sending statd messages */
static int socket_fd = -1;

/*! \brief Global configuration options for statsd client. */
struct conf_global_options {
	/*! Enabled by default, disabled if false. */
	int enabled;
	/*! Disabled by default, appends newlines to all messages when enabled. */
	int add_newline;
	/*! Statsd server address[:port]. */
	struct ast_sockaddr statsd_server;
	/*! Prefix to put on every stat. */
	char prefix[MAX_PREFIX + 1];
};

/*! \brief All configuration options for statsd client. */
struct conf {
	/*! The general section configuration options. */
	struct conf_global_options *global;
};

/*! \brief Locking container for safe configuration access. */
static AO2_GLOBAL_OBJ_STATIC(confs);

static void conf_server(const struct conf *cfg, struct ast_sockaddr *addr)
{
	*addr = cfg->global->statsd_server;
	if (ast_sockaddr_port(addr) == 0) {
		ast_sockaddr_set_port(addr, DEFAULT_STATSD_PORT);
	}
}

void AST_OPTIONAL_API_NAME(ast_statsd_log_string)(const char *metric_name,
	const char *metric_type, const char *value, double sample_rate)
{
	struct conf *cfg;
	struct ast_str *msg;
	size_t len;
	struct ast_sockaddr statsd_server;

	if (socket_fd == -1) {
		return;
	}

	/* Rates <= 0.0 never get logged.
	 * Rates >= 1.0 always get logged.
	 * All others leave it to chance.
	 */
	if (sample_rate <= 0.0 ||
		(sample_rate < 1.0 && sample_rate < ast_random_double())) {
		return;
	}

	cfg = ao2_global_obj_ref(confs);
	conf_server(cfg, &statsd_server);

	msg = ast_str_create(40);
	if (!msg) {
		ao2_cleanup(cfg);
		return;
	}

	if (!ast_strlen_zero(cfg->global->prefix)) {
		ast_str_append(&msg, 0, "%s.", cfg->global->prefix);
	}

	ast_str_append(&msg, 0, "%s:%s|%s", metric_name, value, metric_type);

	if (sample_rate < 1.0) {
		ast_str_append(&msg, 0, "|@%.2f", sample_rate);
	}

	if (cfg->global->add_newline) {
		ast_str_append(&msg, 0, "\n");
	}

	len = ast_str_strlen(msg);

	ast_debug(6, "Sending statistic %s to StatsD server\n", ast_str_buffer(msg));
	ast_sendto(socket_fd, ast_str_buffer(msg), len, 0, &statsd_server);

	ao2_cleanup(cfg);
	ast_free(msg);
}

void AST_OPTIONAL_API_NAME(ast_statsd_log_full)(const char *metric_name,
	const char *metric_type, intmax_t value, double sample_rate)
{
	char char_value[30];
	snprintf(char_value, sizeof(char_value), "%jd", value);

	ast_statsd_log_string(metric_name, metric_type, char_value, sample_rate);

}

AST_THREADSTORAGE(statsd_buf);

void AST_OPTIONAL_API_NAME(ast_statsd_log_string_va)(const char *metric_name,
	const char *metric_type, const char *value, double sample_rate, ...)
{
	struct ast_str *buf;
	va_list ap;
	int res;

	buf = ast_str_thread_get(&statsd_buf, 128);
	if (!buf) {
		return;
	}

	va_start(ap, sample_rate);
	res = ast_str_set_va(&buf, 0, metric_name, ap);
	va_end(ap);

	if (res == AST_DYNSTR_BUILD_FAILED) {
		return;
	}

	ast_statsd_log_string(ast_str_buffer(buf), metric_type, value, sample_rate);
}

void AST_OPTIONAL_API_NAME(ast_statsd_log_full_va)(const char *metric_name,
	const char *metric_type, intmax_t value, double sample_rate, ...)
{
	struct ast_str *buf;
	va_list ap;
	int res;

	buf = ast_str_thread_get(&statsd_buf, 128);
	if (!buf) {
		return;
	}

	va_start(ap, sample_rate);
	res = ast_str_set_va(&buf, 0, metric_name, ap);
	va_end(ap);

	if (res == AST_DYNSTR_BUILD_FAILED) {
		return;
	}

	ast_statsd_log_full(ast_str_buffer(buf), metric_type, value, sample_rate);
}

void AST_OPTIONAL_API_NAME(ast_statsd_log)(const char *metric_name,
	const char *metric_type, intmax_t value)
{
	char char_value[30];
	snprintf(char_value, sizeof(char_value), "%jd", value);

	ast_statsd_log_string(metric_name, metric_type, char_value, 1.0);
}

void AST_OPTIONAL_API_NAME(ast_statsd_log_sample)(const char *metric_name,
	intmax_t value, double sample_rate)
{
	char char_value[30];
	snprintf(char_value, sizeof(char_value), "%jd", value);

	ast_statsd_log_string(metric_name, AST_STATSD_COUNTER, char_value,
		sample_rate);
}

/*! \brief Mapping of the statsd conf struct's globals to the
 *         general context in the config file. */
static struct aco_type global_option = {
	.type = ACO_GLOBAL,
	.name = "global",
	.item_offset = offsetof(struct conf, global),
	.category = "^general$",
	.category_match = ACO_WHITELIST
};

static struct aco_type *global_options[] = ACO_TYPES(&global_option);

/*! \brief Disposes of the statsd conf object */
static void conf_destructor(void *obj)
{
    struct conf *cfg = obj;
    ao2_cleanup(cfg->global);
}

/*! \brief Creates the statis http conf object. */
static void *conf_alloc(void)
{
    struct conf *cfg;

    if (!(cfg = ao2_alloc(sizeof(*cfg), conf_destructor))) {
        return NULL;
    }

    if (!(cfg->global = ao2_alloc(sizeof(*cfg->global), NULL))) {
        ao2_ref(cfg, -1);
        return NULL;
    }
    return cfg;
}

/*! \brief The conf file that's processed for the module. */
static struct aco_file conf_file = {
	/*! The config file name. */
	.filename = "statsd.conf",
	/*! The mapping object types to be processed. */
	.types = ACO_TYPES(&global_option),
};

CONFIG_INFO_STANDARD(cfg_info, confs, conf_alloc,
		     .files = ACO_FILES(&conf_file));

/*! \brief Helper function to check if module is enabled. */
static char is_enabled(void)
{
	RAII_VAR(struct conf *, cfg, ao2_global_obj_ref(confs), ao2_cleanup);
	return cfg->global->enabled;
}

static int statsd_init(void)
{
	RAII_VAR(struct conf *, cfg, ao2_global_obj_ref(confs), ao2_cleanup);
	char *server;
	struct ast_sockaddr statsd_server;

	ast_assert(is_enabled());

	ast_debug(3, "Configuring statsd client.\n");

	if (socket_fd == -1) {
		ast_debug(3, "Creating statsd socket.\n");
		socket_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
		if (socket_fd == -1) {
			perror("Error creating statsd socket");
			return -1;
		}
	}

	conf_server(cfg, &statsd_server);
	server = ast_sockaddr_stringify_fmt(&statsd_server,
		AST_SOCKADDR_STR_DEFAULT);
	ast_debug(3, "  statsd server = %s.\n", server);
	ast_debug(3, "  add newline = %s\n", AST_YESNO(cfg->global->add_newline));
	ast_debug(3, "  prefix = %s\n", cfg->global->prefix);

	return 0;
}

static void statsd_shutdown(void)
{
	ast_debug(3, "Shutting down statsd client.\n");
	if (socket_fd != -1) {
		close(socket_fd);
		socket_fd = -1;
	}
}

static int load_module(void)
{
	if (aco_info_init(&cfg_info)) {
		aco_info_destroy(&cfg_info);
		return AST_MODULE_LOAD_DECLINE;
	}

	aco_option_register(&cfg_info, "enabled", ACO_EXACT, global_options,
		"no", OPT_BOOL_T, 1,
		FLDSET(struct conf_global_options, enabled));

	aco_option_register(&cfg_info, "add_newline", ACO_EXACT, global_options,
		"no", OPT_BOOL_T, 1,
		FLDSET(struct conf_global_options, add_newline));

	aco_option_register(&cfg_info, "server", ACO_EXACT, global_options,
		"127.0.0.1", OPT_SOCKADDR_T, 0,
		FLDSET(struct conf_global_options, statsd_server));

	aco_option_register(&cfg_info, "prefix", ACO_EXACT, global_options,
		"", OPT_CHAR_ARRAY_T, 0,
		CHARFLDSET(struct conf_global_options, prefix));

	if (aco_process_config(&cfg_info, 0)) {
		aco_info_destroy(&cfg_info);
		return AST_MODULE_LOAD_DECLINE;
	}

	if (!is_enabled()) {
		return AST_MODULE_LOAD_SUCCESS;
	}

	if (statsd_init() != 0) {
		aco_info_destroy(&cfg_info);
		return AST_MODULE_LOAD_DECLINE;
	}

	/* For Optional API. */
	ast_module_shutdown_ref(AST_MODULE_SELF);

	return AST_MODULE_LOAD_SUCCESS;
}

static int unload_module(void)
{
	statsd_shutdown();
	aco_info_destroy(&cfg_info);
	ao2_global_obj_release(confs);
	return 0;
}

static int reload_module(void)
{
	if (aco_process_config(&cfg_info, 1)) {
		return AST_MODULE_LOAD_DECLINE;
	}

	if (is_enabled()) {
		return statsd_init();
	} else {
		statsd_shutdown();
		return AST_MODULE_LOAD_SUCCESS;
	}
}

/* The priority of this module is set to be as low as possible, since it could
 * be used by any other sort of module.
 */
AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Statsd client support",
	.support_level = AST_MODULE_SUPPORT_EXTENDED,
	.load = load_module,
	.unload = unload_module,
	.reload = reload_module,
	.load_pri = 0,
);