1 /**
2  * collectd - src/amqp.c
3  * Copyright (C) 2009       Sebastien Pahl
4  * Copyright (C) 2010-2012  Florian Forster
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22  * DEALINGS IN THE SOFTWARE.
23  *
24  * Authors:
25  *   Sebastien Pahl <sebastien.pahl at dotcloud.com>
26  *   Florian Forster <octo at collectd.org>
27  **/
28 
29 #include "collectd.h"
30 
31 #include "plugin.h"
32 #include "utils/cmds/putval.h"
33 #include "utils/common/common.h"
34 #include "utils/format_graphite/format_graphite.h"
35 #include "utils/format_json/format_json.h"
36 #include "utils_random.h"
37 
38 #include <amqp.h>
39 #include <amqp_framing.h>
40 
41 #ifdef HAVE_AMQP_TCP_SOCKET_H
42 #include <amqp_ssl_socket.h>
43 #include <amqp_tcp_socket.h>
44 #endif
45 #ifdef HAVE_AMQP_SOCKET_H
46 #include <amqp_socket.h>
47 #endif
48 #ifdef HAVE_AMQP_TCP_SOCKET
49 #if defined HAVE_DECL_AMQP_SOCKET_CLOSE && !HAVE_DECL_AMQP_SOCKET_CLOSE
50 /* rabbitmq-c does not currently ship amqp_socket.h
51  * and, thus, does not define this function. */
52 int amqp_socket_close(amqp_socket_t *);
53 #endif
54 #endif
55 
56 /* Defines for the delivery mode. I have no idea why they're not defined by the
57  * library.. */
58 #define CAMQP_DM_VOLATILE 1
59 #define CAMQP_DM_PERSISTENT 2
60 
61 #define CAMQP_FORMAT_COMMAND 1
62 #define CAMQP_FORMAT_JSON 2
63 #define CAMQP_FORMAT_GRAPHITE 3
64 
65 #define CAMQP_CHANNEL 1
66 
67 /*
68  * Data types
69  */
70 struct camqp_config_s {
71   bool publish;
72   char *name;
73 
74   char **hosts;
75   size_t hosts_count;
76   int port;
77   char *vhost;
78   char *user;
79   char *password;
80 
81   bool tls_enabled;
82   bool tls_verify_peer;
83   bool tls_verify_hostname;
84   char *tls_cacert;
85   char *tls_client_cert;
86   char *tls_client_key;
87 
88   char *exchange;
89   char *routing_key;
90 
91   /* Number of seconds to wait before connection is retried */
92   int connection_retry_delay;
93 
94   /* publish only */
95   uint8_t delivery_mode;
96   bool store_rates;
97   int format;
98   /* publish & graphite format only */
99   char *prefix;
100   char *postfix;
101   char escape_char;
102   unsigned int graphite_flags;
103 
104   /* subscribe only */
105   char *exchange_type;
106   char *queue;
107   bool queue_durable;
108   bool queue_auto_delete;
109 
110   amqp_connection_state_t connection;
111   pthread_mutex_t lock;
112 };
113 typedef struct camqp_config_s camqp_config_t;
114 
115 /*
116  * Global variables
117  */
118 static const char *def_vhost = "/";
119 static const char *def_user = "guest";
120 static const char *def_password = "guest";
121 static const char *def_exchange = "amq.fanout";
122 
123 static pthread_t *subscriber_threads;
124 static size_t subscriber_threads_num;
125 static bool subscriber_threads_running = true;
126 
127 #define CONF(c, f) (((c)->f != NULL) ? (c)->f : def_##f)
128 
129 /*
130  * Functions
131  */
camqp_close_connection(camqp_config_t * conf)132 static void camqp_close_connection(camqp_config_t *conf) /* {{{ */
133 {
134   int sockfd;
135 
136   if ((conf == NULL) || (conf->connection == NULL))
137     return;
138 
139   sockfd = amqp_get_sockfd(conf->connection);
140   amqp_channel_close(conf->connection, CAMQP_CHANNEL, AMQP_REPLY_SUCCESS);
141   amqp_connection_close(conf->connection, AMQP_REPLY_SUCCESS);
142   amqp_destroy_connection(conf->connection);
143   close(sockfd);
144   conf->connection = NULL;
145 } /* }}} void camqp_close_connection */
146 
camqp_config_free(void * ptr)147 static void camqp_config_free(void *ptr) /* {{{ */
148 {
149   camqp_config_t *conf = ptr;
150 
151   if (conf == NULL)
152     return;
153 
154   camqp_close_connection(conf);
155 
156   sfree(conf->name);
157   strarray_free(conf->hosts, conf->hosts_count);
158   sfree(conf->vhost);
159   sfree(conf->user);
160   sfree(conf->password);
161   sfree(conf->tls_cacert);
162   sfree(conf->tls_client_cert);
163   sfree(conf->tls_client_key);
164   sfree(conf->exchange);
165   sfree(conf->exchange_type);
166   sfree(conf->queue);
167   sfree(conf->routing_key);
168   sfree(conf->prefix);
169   sfree(conf->postfix);
170 
171   sfree(conf);
172 } /* }}} void camqp_config_free */
173 
camqp_bytes_cstring(amqp_bytes_t * in)174 static char *camqp_bytes_cstring(amqp_bytes_t *in) /* {{{ */
175 {
176   char *ret;
177 
178   if ((in == NULL) || (in->bytes == NULL))
179     return NULL;
180 
181   ret = malloc(in->len + 1);
182   if (ret == NULL)
183     return NULL;
184 
185   memcpy(ret, in->bytes, in->len);
186   ret[in->len] = 0;
187 
188   return ret;
189 } /* }}} char *camqp_bytes_cstring */
190 
camqp_is_error(camqp_config_t * conf)191 static bool camqp_is_error(camqp_config_t *conf) /* {{{ */
192 {
193   amqp_rpc_reply_t r;
194 
195   r = amqp_get_rpc_reply(conf->connection);
196   if (r.reply_type == AMQP_RESPONSE_NORMAL)
197     return false;
198 
199   return true;
200 } /* }}} bool camqp_is_error */
201 
camqp_strerror(camqp_config_t * conf,char * buffer,size_t buffer_size)202 static char *camqp_strerror(camqp_config_t *conf, /* {{{ */
203                             char *buffer, size_t buffer_size) {
204   amqp_rpc_reply_t r;
205 
206   r = amqp_get_rpc_reply(conf->connection);
207   switch (r.reply_type) {
208   case AMQP_RESPONSE_NORMAL:
209     sstrncpy(buffer, "Success", buffer_size);
210     break;
211 
212   case AMQP_RESPONSE_NONE:
213     sstrncpy(buffer, "Missing RPC reply type", buffer_size);
214     break;
215 
216   case AMQP_RESPONSE_LIBRARY_EXCEPTION:
217 #if HAVE_AMQP_RPC_REPLY_T_LIBRARY_ERRNO
218     if (r.library_errno)
219       return sstrerror(r.library_errno, buffer, buffer_size);
220 #else
221     if (r.library_error)
222       return sstrerror(r.library_error, buffer, buffer_size);
223 #endif
224     else
225       sstrncpy(buffer, "End of stream", buffer_size);
226     break;
227 
228   case AMQP_RESPONSE_SERVER_EXCEPTION:
229     if (r.reply.id == AMQP_CONNECTION_CLOSE_METHOD) {
230       amqp_connection_close_t *m = r.reply.decoded;
231       char *tmp = camqp_bytes_cstring(&m->reply_text);
232       ssnprintf(buffer, buffer_size, "Server connection error %d: %s",
233                 m->reply_code, tmp);
234       sfree(tmp);
235     } else if (r.reply.id == AMQP_CHANNEL_CLOSE_METHOD) {
236       amqp_channel_close_t *m = r.reply.decoded;
237       char *tmp = camqp_bytes_cstring(&m->reply_text);
238       ssnprintf(buffer, buffer_size, "Server channel error %d: %s",
239                 m->reply_code, tmp);
240       sfree(tmp);
241     } else {
242       ssnprintf(buffer, buffer_size, "Server error method %#" PRIx32,
243                 r.reply.id);
244     }
245     break;
246 
247   default:
248     ssnprintf(buffer, buffer_size, "Unknown reply type %i", (int)r.reply_type);
249   }
250 
251   return buffer;
252 } /* }}} char *camqp_strerror */
253 
254 #if HAVE_AMQP_RPC_REPLY_T_LIBRARY_ERRNO
camqp_create_exchange(camqp_config_t * conf)255 static int camqp_create_exchange(camqp_config_t *conf) /* {{{ */
256 {
257   amqp_exchange_declare_ok_t *ed_ret;
258 
259   if (conf->exchange_type == NULL)
260     return 0;
261 
262   ed_ret = amqp_exchange_declare(
263       conf->connection,
264       /* channel     = */ CAMQP_CHANNEL,
265       /* exchange    = */ amqp_cstring_bytes(conf->exchange),
266       /* type        = */ amqp_cstring_bytes(conf->exchange_type),
267       /* passive     = */ 0,
268       /* durable     = */ 0,
269       /* auto_delete = */ 1,
270       /* arguments   = */ AMQP_EMPTY_TABLE);
271   if ((ed_ret == NULL) && camqp_is_error(conf)) {
272     char errbuf[1024];
273     ERROR("amqp plugin: amqp_exchange_declare failed: %s",
274           camqp_strerror(conf, errbuf, sizeof(errbuf)));
275     camqp_close_connection(conf);
276     return -1;
277   }
278 
279   INFO("amqp plugin: Successfully created exchange \"%s\" "
280        "with type \"%s\".",
281        conf->exchange, conf->exchange_type);
282 
283   return 0;
284 } /* }}} int camqp_create_exchange */
285 #else
camqp_create_exchange(camqp_config_t * conf)286 static int camqp_create_exchange(camqp_config_t *conf) /* {{{ */
287 {
288   amqp_exchange_declare_ok_t *ed_ret;
289   amqp_table_t argument_table;
290   struct amqp_table_entry_t_ argument_table_entries[1];
291 
292   if (conf->exchange_type == NULL)
293     return 0;
294 
295   /* Valid arguments: "auto_delete", "internal" */
296   argument_table.num_entries = STATIC_ARRAY_SIZE(argument_table_entries);
297   argument_table.entries = argument_table_entries;
298   argument_table_entries[0].key = amqp_cstring_bytes("auto_delete");
299   argument_table_entries[0].value.kind = AMQP_FIELD_KIND_BOOLEAN;
300   argument_table_entries[0].value.value.boolean = 1;
301 
302   ed_ret = amqp_exchange_declare(
303       conf->connection,
304       /* channel     = */ CAMQP_CHANNEL,
305       /* exchange    = */ amqp_cstring_bytes(conf->exchange),
306       /* type        = */ amqp_cstring_bytes(conf->exchange_type),
307       /* passive     = */ 0,
308       /* durable     = */ 0,
309 #if defined(AMQP_VERSION) && AMQP_VERSION >= 0x00060000
310       /* auto delete = */ 0,
311       /* internal    = */ 0,
312 #endif
313       /* arguments   = */ argument_table);
314   if ((ed_ret == NULL) && camqp_is_error(conf)) {
315     char errbuf[1024];
316     ERROR("amqp plugin: amqp_exchange_declare failed: %s",
317           camqp_strerror(conf, errbuf, sizeof(errbuf)));
318     camqp_close_connection(conf);
319     return -1;
320   }
321 
322   INFO("amqp plugin: Successfully created exchange \"%s\" "
323        "with type \"%s\".",
324        conf->exchange, conf->exchange_type);
325 
326   return 0;
327 } /* }}} int camqp_create_exchange */
328 #endif
329 
camqp_setup_queue(camqp_config_t * conf)330 static int camqp_setup_queue(camqp_config_t *conf) /* {{{ */
331 {
332   amqp_queue_declare_ok_t *qd_ret;
333   amqp_basic_consume_ok_t *cm_ret;
334 
335   qd_ret =
336       amqp_queue_declare(conf->connection,
337                          /* channel     = */ CAMQP_CHANNEL,
338                          /* queue       = */
339                          (conf->queue != NULL) ? amqp_cstring_bytes(conf->queue)
340                                                : AMQP_EMPTY_BYTES,
341                          /* passive     = */ 0,
342                          /* durable     = */ conf->queue_durable,
343                          /* exclusive   = */ 0,
344                          /* auto_delete = */ conf->queue_auto_delete,
345                          /* arguments   = */ AMQP_EMPTY_TABLE);
346   if (qd_ret == NULL) {
347     ERROR("amqp plugin: amqp_queue_declare failed.");
348     camqp_close_connection(conf);
349     return -1;
350   }
351 
352   if (conf->queue == NULL) {
353     conf->queue = camqp_bytes_cstring(&qd_ret->queue);
354     if (conf->queue == NULL) {
355       ERROR("amqp plugin: camqp_bytes_cstring failed.");
356       camqp_close_connection(conf);
357       return -1;
358     }
359 
360     INFO("amqp plugin: Created queue \"%s\".", conf->queue);
361   }
362   DEBUG("amqp plugin: Successfully created queue \"%s\".", conf->queue);
363 
364   /* bind to an exchange */
365   if (conf->exchange != NULL) {
366     amqp_queue_bind_ok_t *qb_ret;
367 
368     assert(conf->queue != NULL);
369     qb_ret = amqp_queue_bind(
370         conf->connection,
371         /* channel     = */ CAMQP_CHANNEL,
372         /* queue       = */ amqp_cstring_bytes(conf->queue),
373         /* exchange    = */ amqp_cstring_bytes(conf->exchange),
374         /* routing_key = */
375         (conf->routing_key != NULL) ? amqp_cstring_bytes(conf->routing_key)
376                                     : AMQP_EMPTY_BYTES,
377         /* arguments   = */ AMQP_EMPTY_TABLE);
378     if ((qb_ret == NULL) && camqp_is_error(conf)) {
379       char errbuf[1024];
380       ERROR("amqp plugin: amqp_queue_bind failed: %s",
381             camqp_strerror(conf, errbuf, sizeof(errbuf)));
382       camqp_close_connection(conf);
383       return -1;
384     }
385 
386     DEBUG("amqp plugin: Successfully bound queue \"%s\" to exchange \"%s\".",
387           conf->queue, conf->exchange);
388   } /* if (conf->exchange != NULL) */
389 
390   cm_ret =
391       amqp_basic_consume(conf->connection,
392                          /* channel      = */ CAMQP_CHANNEL,
393                          /* queue        = */ amqp_cstring_bytes(conf->queue),
394                          /* consumer_tag = */ AMQP_EMPTY_BYTES,
395                          /* no_local     = */ 0,
396                          /* no_ack       = */ 1,
397                          /* exclusive    = */ 0,
398                          /* arguments    = */ AMQP_EMPTY_TABLE);
399   if ((cm_ret == NULL) && camqp_is_error(conf)) {
400     char errbuf[1024];
401     ERROR("amqp plugin: amqp_basic_consume failed: %s",
402           camqp_strerror(conf, errbuf, sizeof(errbuf)));
403     camqp_close_connection(conf);
404     return -1;
405   }
406 
407   return 0;
408 } /* }}} int camqp_setup_queue */
409 
camqp_connect(camqp_config_t * conf)410 static int camqp_connect(camqp_config_t *conf) /* {{{ */
411 {
412   static time_t last_connect_time;
413 
414   amqp_rpc_reply_t reply;
415   int status;
416 #ifdef HAVE_AMQP_TCP_SOCKET
417   amqp_socket_t *socket;
418 #else
419   int sockfd;
420 #endif
421 
422   if (conf->connection != NULL)
423     return 0;
424 
425   time_t now = time(NULL);
426   if (now < (last_connect_time + conf->connection_retry_delay)) {
427     DEBUG("amqp plugin: skipping connection retry, "
428           "ConnectionRetryDelay: %d",
429           conf->connection_retry_delay);
430     return 1;
431   } else {
432     DEBUG("amqp plugin: retrying connection");
433     last_connect_time = now;
434   }
435 
436   conf->connection = amqp_new_connection();
437   if (conf->connection == NULL) {
438     ERROR("amqp plugin: amqp_new_connection failed.");
439     return ENOMEM;
440   }
441 
442   char *host = conf->hosts[cdrand_u() % conf->hosts_count];
443   INFO("amqp plugin: Connecting to %s", host);
444 
445 #ifdef HAVE_AMQP_TCP_SOCKET
446 #define CLOSE_SOCKET() /* amqp_destroy_connection() closes the socket for us   \
447                         */
448 
449   if (conf->tls_enabled) {
450     socket = amqp_ssl_socket_new(conf->connection);
451     if (!socket) {
452       ERROR("amqp plugin: amqp_ssl_socket_new failed.");
453       amqp_destroy_connection(conf->connection);
454       conf->connection = NULL;
455       return ENOMEM;
456     }
457 
458 #if AMQP_VERSION >= 0x00080000
459     amqp_ssl_socket_set_verify_peer(socket, conf->tls_verify_peer);
460     amqp_ssl_socket_set_verify_hostname(socket, conf->tls_verify_hostname);
461 #endif
462 
463     if (conf->tls_cacert) {
464       status = amqp_ssl_socket_set_cacert(socket, conf->tls_cacert);
465       if (status < 0) {
466         ERROR("amqp plugin: amqp_ssl_socket_set_cacert failed: %s",
467               amqp_error_string2(status));
468         amqp_destroy_connection(conf->connection);
469         conf->connection = NULL;
470         return status;
471       }
472     }
473     if (conf->tls_client_cert && conf->tls_client_key) {
474       status = amqp_ssl_socket_set_key(socket, conf->tls_client_cert,
475                                        conf->tls_client_key);
476       if (status < 0) {
477         ERROR("amqp plugin: amqp_ssl_socket_set_key failed: %s",
478               amqp_error_string2(status));
479         amqp_destroy_connection(conf->connection);
480         conf->connection = NULL;
481         return status;
482       }
483     }
484   } else {
485     socket = amqp_tcp_socket_new(conf->connection);
486     if (!socket) {
487       ERROR("amqp plugin: amqp_tcp_socket_new failed.");
488       amqp_destroy_connection(conf->connection);
489       conf->connection = NULL;
490       return ENOMEM;
491     }
492   }
493 
494   status = amqp_socket_open(socket, host, conf->port);
495   if (status < 0) {
496     ERROR("amqp plugin: amqp_socket_open failed: %s",
497           amqp_error_string2(status));
498     amqp_destroy_connection(conf->connection);
499     conf->connection = NULL;
500     return status;
501   }
502 #else /* HAVE_AMQP_TCP_SOCKET */
503 #define CLOSE_SOCKET() close(sockfd)
504   /* this interface is deprecated as of rabbitmq-c 0.4 */
505   sockfd = amqp_open_socket(host, conf->port);
506   if (sockfd < 0) {
507     status = (-1) * sockfd;
508     ERROR("amqp plugin: amqp_open_socket failed: %s", STRERROR(status));
509     amqp_destroy_connection(conf->connection);
510     conf->connection = NULL;
511     return status;
512   }
513   amqp_set_sockfd(conf->connection, sockfd);
514 #endif
515 
516   reply = amqp_login(conf->connection, CONF(conf, vhost),
517                      /* channel max = */ 0,
518                      /* frame max   = */ 131072,
519                      /* heartbeat   = */ 0,
520                      /* authentication = */ AMQP_SASL_METHOD_PLAIN,
521                      CONF(conf, user), CONF(conf, password));
522   if (reply.reply_type != AMQP_RESPONSE_NORMAL) {
523     ERROR("amqp plugin: amqp_login (vhost = %s, user = %s) failed.",
524           CONF(conf, vhost), CONF(conf, user));
525     amqp_destroy_connection(conf->connection);
526     CLOSE_SOCKET();
527     conf->connection = NULL;
528     return 1;
529   }
530 
531   amqp_channel_open(conf->connection, /* channel = */ 1);
532   /* FIXME: Is checking "reply.reply_type" really correct here? How does
533    * it get set? --octo */
534   if (reply.reply_type != AMQP_RESPONSE_NORMAL) {
535     ERROR("amqp plugin: amqp_channel_open failed.");
536     amqp_connection_close(conf->connection, AMQP_REPLY_SUCCESS);
537     amqp_destroy_connection(conf->connection);
538     CLOSE_SOCKET();
539     conf->connection = NULL;
540     return 1;
541   }
542 
543   INFO("amqp plugin: Successfully opened connection to vhost \"%s\" "
544        "on %s:%i.",
545        CONF(conf, vhost), host, conf->port);
546 
547   status = camqp_create_exchange(conf);
548   if (status != 0)
549     return status;
550 
551   if (!conf->publish)
552     return camqp_setup_queue(conf);
553   return 0;
554 } /* }}} int camqp_connect */
555 
camqp_shutdown(void)556 static int camqp_shutdown(void) /* {{{ */
557 {
558   DEBUG("amqp plugin: Shutting down %" PRIsz " subscriber threads.",
559         subscriber_threads_num);
560 
561   subscriber_threads_running = 0;
562   for (size_t i = 0; i < subscriber_threads_num; i++) {
563     /* FIXME: Sending a signal is not very elegant here. Maybe find out how
564      * to use a timeout in the thread and check for the variable in regular
565      * intervals. */
566     pthread_kill(subscriber_threads[i], SIGTERM);
567     pthread_join(subscriber_threads[i], /* retval = */ NULL);
568   }
569 
570   subscriber_threads_num = 0;
571   sfree(subscriber_threads);
572 
573   DEBUG("amqp plugin: All subscriber threads exited.");
574 
575   return 0;
576 } /* }}} int camqp_shutdown */
577 
578 /*
579  * Subscribing code
580  */
camqp_read_body(camqp_config_t * conf,size_t body_size,const char * content_type)581 static int camqp_read_body(camqp_config_t *conf, /* {{{ */
582                            size_t body_size, const char *content_type) {
583   char body[body_size + 1];
584   char *body_ptr;
585   size_t received;
586   amqp_frame_t frame;
587   int status;
588 
589   memset(body, 0, sizeof(body));
590   body_ptr = &body[0];
591   received = 0;
592 
593   while (received < body_size) {
594     status = amqp_simple_wait_frame(conf->connection, &frame);
595     if (status < 0) {
596       status = (-1) * status;
597       ERROR("amqp plugin: amqp_simple_wait_frame failed: %s", STRERROR(status));
598       camqp_close_connection(conf);
599       return status;
600     }
601 
602     if (frame.frame_type != AMQP_FRAME_BODY) {
603       NOTICE("amqp plugin: Unexpected frame type: %#" PRIx8, frame.frame_type);
604       return -1;
605     }
606 
607     if ((body_size - received) < frame.payload.body_fragment.len) {
608       WARNING("amqp plugin: Body is larger than indicated by header.");
609       return -1;
610     }
611 
612     memcpy(body_ptr, frame.payload.body_fragment.bytes,
613            frame.payload.body_fragment.len);
614     body_ptr += frame.payload.body_fragment.len;
615     received += frame.payload.body_fragment.len;
616   } /* while (received < body_size) */
617 
618   if (strcasecmp("text/collectd", content_type) == 0) {
619     status = cmd_handle_putval(stderr, body);
620     if (status != 0)
621       ERROR("amqp plugin: cmd_handle_putval failed with status %i.", status);
622     return status;
623   } else if (strcasecmp("application/json", content_type) == 0) {
624     ERROR("amqp plugin: camqp_read_body: Parsing JSON data has not "
625           "been implemented yet. FIXME!");
626     return 0;
627   } else {
628     ERROR("amqp plugin: camqp_read_body: Unknown content type \"%s\".",
629           content_type);
630     return EINVAL;
631   }
632 
633   /* not reached */
634   return 0;
635 } /* }}} int camqp_read_body */
636 
camqp_read_header(camqp_config_t * conf)637 static int camqp_read_header(camqp_config_t *conf) /* {{{ */
638 {
639   int status;
640   amqp_frame_t frame;
641   amqp_basic_properties_t *properties;
642   char *content_type;
643 
644   status = amqp_simple_wait_frame(conf->connection, &frame);
645   if (status < 0) {
646     status = (-1) * status;
647     ERROR("amqp plugin: amqp_simple_wait_frame failed: %s", STRERROR(status));
648     camqp_close_connection(conf);
649     return status;
650   }
651 
652   if (frame.frame_type != AMQP_FRAME_HEADER) {
653     NOTICE("amqp plugin: Unexpected frame type: %#" PRIx8, frame.frame_type);
654     return -1;
655   }
656 
657   properties = frame.payload.properties.decoded;
658   content_type = camqp_bytes_cstring(&properties->content_type);
659   if (content_type == NULL) {
660     ERROR("amqp plugin: Unable to determine content type.");
661     return -1;
662   }
663 
664   status = camqp_read_body(conf, (size_t)frame.payload.properties.body_size,
665                            content_type);
666 
667   sfree(content_type);
668   return status;
669 } /* }}} int camqp_read_header */
670 
camqp_subscribe_thread(void * user_data)671 static void *camqp_subscribe_thread(void *user_data) /* {{{ */
672 {
673   camqp_config_t *conf = user_data;
674   int status;
675 
676   cdtime_t interval = plugin_get_interval();
677 
678   while (subscriber_threads_running) {
679     amqp_frame_t frame;
680 
681     status = camqp_connect(conf);
682     if (status != 0) {
683       ERROR("amqp plugin: camqp_connect failed. "
684             "Will sleep for %.3f seconds.",
685             CDTIME_T_TO_DOUBLE(interval));
686       nanosleep(&CDTIME_T_TO_TIMESPEC(interval), /* remaining = */ NULL);
687       continue;
688     }
689 
690     status = amqp_simple_wait_frame(conf->connection, &frame);
691     if (status < 0) {
692       ERROR("amqp plugin: amqp_simple_wait_frame failed. "
693             "Will sleep for %.3f seconds.",
694             CDTIME_T_TO_DOUBLE(interval));
695       camqp_close_connection(conf);
696       nanosleep(&CDTIME_T_TO_TIMESPEC(interval), /* remaining = */ NULL);
697       continue;
698     }
699 
700     if (frame.frame_type != AMQP_FRAME_METHOD) {
701       DEBUG("amqp plugin: Unexpected frame type: %#" PRIx8, frame.frame_type);
702       continue;
703     }
704 
705     if (frame.payload.method.id != AMQP_BASIC_DELIVER_METHOD) {
706       DEBUG("amqp plugin: Unexpected method id: %#" PRIx32,
707             frame.payload.method.id);
708       continue;
709     }
710 
711     camqp_read_header(conf);
712 
713     amqp_maybe_release_buffers(conf->connection);
714   } /* while (subscriber_threads_running) */
715 
716   camqp_config_free(conf);
717   pthread_exit(NULL);
718   return NULL;
719 } /* }}} void *camqp_subscribe_thread */
720 
camqp_subscribe_init(camqp_config_t * conf)721 static int camqp_subscribe_init(camqp_config_t *conf) /* {{{ */
722 {
723   int status;
724   pthread_t *tmp;
725 
726   tmp = realloc(subscriber_threads,
727                 sizeof(*subscriber_threads) * (subscriber_threads_num + 1));
728   if (tmp == NULL) {
729     ERROR("amqp plugin: realloc failed.");
730     sfree(subscriber_threads);
731     return ENOMEM;
732   }
733   subscriber_threads = tmp;
734   tmp = subscriber_threads + subscriber_threads_num;
735   memset(tmp, 0, sizeof(*tmp));
736 
737   status =
738       plugin_thread_create(tmp, camqp_subscribe_thread, conf, "amqp subscribe");
739   if (status != 0) {
740     ERROR("amqp plugin: pthread_create failed: %s", STRERROR(status));
741     return status;
742   }
743 
744   subscriber_threads_num++;
745 
746   return 0;
747 } /* }}} int camqp_subscribe_init */
748 
749 /*
750  * Publishing code
751  */
752 /* XXX: You must hold "conf->lock" when calling this function! */
camqp_write_locked(camqp_config_t * conf,const char * buffer,const char * routing_key)753 static int camqp_write_locked(camqp_config_t *conf, /* {{{ */
754                               const char *buffer, const char *routing_key) {
755   int status;
756 
757   status = camqp_connect(conf);
758   if (status != 0)
759     return status;
760 
761   amqp_basic_properties_t props = {._flags = AMQP_BASIC_CONTENT_TYPE_FLAG |
762                                              AMQP_BASIC_DELIVERY_MODE_FLAG |
763                                              AMQP_BASIC_APP_ID_FLAG,
764                                    .delivery_mode = conf->delivery_mode,
765                                    .app_id = amqp_cstring_bytes("collectd")};
766 
767   if (conf->format == CAMQP_FORMAT_COMMAND)
768     props.content_type = amqp_cstring_bytes("text/collectd");
769   else if (conf->format == CAMQP_FORMAT_JSON)
770     props.content_type = amqp_cstring_bytes("application/json");
771   else if (conf->format == CAMQP_FORMAT_GRAPHITE)
772     props.content_type = amqp_cstring_bytes("text/graphite");
773   else
774     assert(23 == 42);
775 
776   status = amqp_basic_publish(
777       conf->connection,
778       /* channel = */ 1, amqp_cstring_bytes(CONF(conf, exchange)),
779       amqp_cstring_bytes(routing_key),
780       /* mandatory = */ 0,
781       /* immediate = */ 0, &props, amqp_cstring_bytes(buffer));
782   if (status != 0) {
783     ERROR("amqp plugin: amqp_basic_publish failed with status %i.", status);
784     camqp_close_connection(conf);
785   }
786 
787   return status;
788 } /* }}} int camqp_write_locked */
789 
camqp_write(const data_set_t * ds,const value_list_t * vl,user_data_t * user_data)790 static int camqp_write(const data_set_t *ds, const value_list_t *vl, /* {{{ */
791                        user_data_t *user_data) {
792   camqp_config_t *conf = user_data->data;
793   char routing_key[6 * DATA_MAX_NAME_LEN];
794   char buffer[8192];
795   int status;
796 
797   if ((ds == NULL) || (vl == NULL) || (conf == NULL))
798     return EINVAL;
799 
800   if (conf->routing_key != NULL) {
801     sstrncpy(routing_key, conf->routing_key, sizeof(routing_key));
802   } else {
803     ssnprintf(routing_key, sizeof(routing_key), "collectd/%s/%s/%s/%s/%s",
804               vl->host, vl->plugin, vl->plugin_instance, vl->type,
805               vl->type_instance);
806 
807     /* Switch slashes (the only character forbidden by collectd) and dots
808      * (the separation character used by AMQP). */
809     for (size_t i = 0; routing_key[i] != 0; i++) {
810       if (routing_key[i] == '.')
811         routing_key[i] = '/';
812       else if (routing_key[i] == '/')
813         routing_key[i] = '.';
814     }
815   }
816 
817   if (conf->format == CAMQP_FORMAT_COMMAND) {
818     status = cmd_create_putval(buffer, sizeof(buffer), ds, vl);
819     if (status != 0) {
820       ERROR("amqp plugin: cmd_create_putval failed with status %i.", status);
821       return status;
822     }
823   } else if (conf->format == CAMQP_FORMAT_JSON) {
824     size_t bfree = sizeof(buffer);
825     size_t bfill = 0;
826 
827     format_json_initialize(buffer, &bfill, &bfree);
828     format_json_value_list(buffer, &bfill, &bfree, ds, vl, conf->store_rates);
829     format_json_finalize(buffer, &bfill, &bfree);
830   } else if (conf->format == CAMQP_FORMAT_GRAPHITE) {
831     status =
832         format_graphite(buffer, sizeof(buffer), ds, vl, conf->prefix,
833                         conf->postfix, conf->escape_char, conf->graphite_flags);
834     if (status != 0) {
835       ERROR("amqp plugin: format_graphite failed with status %i.", status);
836       return status;
837     }
838   } else {
839     ERROR("amqp plugin: Invalid format (%i).", conf->format);
840     return -1;
841   }
842 
843   pthread_mutex_lock(&conf->lock);
844   status = camqp_write_locked(conf, buffer, routing_key);
845   pthread_mutex_unlock(&conf->lock);
846 
847   return status;
848 } /* }}} int camqp_write */
849 
850 /*
851  * Config handling
852  */
camqp_config_set_format(oconfig_item_t * ci,camqp_config_t * conf)853 static int camqp_config_set_format(oconfig_item_t *ci, /* {{{ */
854                                    camqp_config_t *conf) {
855   char *string;
856   int status;
857 
858   string = NULL;
859   status = cf_util_get_string(ci, &string);
860   if (status != 0)
861     return status;
862 
863   assert(string != NULL);
864   if (strcasecmp("Command", string) == 0)
865     conf->format = CAMQP_FORMAT_COMMAND;
866   else if (strcasecmp("JSON", string) == 0)
867     conf->format = CAMQP_FORMAT_JSON;
868   else if (strcasecmp("Graphite", string) == 0)
869     conf->format = CAMQP_FORMAT_GRAPHITE;
870   else {
871     WARNING("amqp plugin: Invalid format string: %s", string);
872   }
873 
874   free(string);
875 
876   return 0;
877 } /* }}} int config_set_string */
878 
camqp_config_connection(oconfig_item_t * ci,bool publish)879 static int camqp_config_connection(oconfig_item_t *ci, /* {{{ */
880                                    bool publish) {
881   camqp_config_t *conf;
882   int status;
883 
884   conf = calloc(1, sizeof(*conf));
885   if (conf == NULL) {
886     ERROR("amqp plugin: calloc failed.");
887     return ENOMEM;
888   }
889 
890   /* Initialize "conf" {{{ */
891   conf->publish = publish;
892   conf->name = NULL;
893   conf->format = CAMQP_FORMAT_COMMAND;
894   conf->hosts = NULL;
895   conf->hosts_count = 0;
896   conf->port = 5672;
897   conf->vhost = NULL;
898   conf->user = NULL;
899   conf->password = NULL;
900   conf->tls_enabled = false;
901   conf->tls_verify_peer = true;
902   conf->tls_verify_hostname = true;
903   conf->tls_cacert = NULL;
904   conf->tls_client_cert = NULL;
905   conf->tls_client_key = NULL;
906   conf->exchange = NULL;
907   conf->routing_key = NULL;
908   conf->connection_retry_delay = 0;
909 
910   /* publish only */
911   conf->delivery_mode = CAMQP_DM_VOLATILE;
912   conf->store_rates = false;
913   conf->graphite_flags = 0;
914   /* publish & graphite only */
915   conf->prefix = NULL;
916   conf->postfix = NULL;
917   conf->escape_char = '_';
918   /* subscribe only */
919   conf->exchange_type = NULL;
920   conf->queue = NULL;
921   conf->queue_durable = false;
922   conf->queue_auto_delete = true;
923   /* general */
924   conf->connection = NULL;
925   pthread_mutex_init(&conf->lock, /* attr = */ NULL);
926   /* }}} */
927 
928   status = cf_util_get_string(ci, &conf->name);
929   if (status != 0) {
930     sfree(conf);
931     return status;
932   }
933 
934   for (int i = 0; i < ci->children_num; i++) {
935     oconfig_item_t *child = ci->children + i;
936 
937     if (strcasecmp("Host", child->key) == 0) {
938       for (int j = 0; j < child->values_num; j++) {
939         if (child->values[j].type != OCONFIG_TYPE_STRING) {
940           status = EINVAL;
941           ERROR("amqp plugin: Host arguments must be strings");
942           break;
943         }
944 
945         status = strarray_add(&conf->hosts, &conf->hosts_count,
946                               child->values[j].value.string);
947         if (status) {
948           ERROR("amqp plugin: Host configuration failed: %d", status);
949           break;
950         }
951       }
952     } else if (strcasecmp("Port", child->key) == 0) {
953       status = cf_util_get_port_number(child);
954       if (status > 0) {
955         conf->port = status;
956         status = 0;
957       }
958     } else if (strcasecmp("VHost", child->key) == 0)
959       status = cf_util_get_string(child, &conf->vhost);
960     else if (strcasecmp("User", child->key) == 0)
961       status = cf_util_get_string(child, &conf->user);
962     else if (strcasecmp("Password", child->key) == 0)
963       status = cf_util_get_string(child, &conf->password);
964     else if (strcasecmp("TLSEnabled", child->key) == 0)
965       status = cf_util_get_boolean(child, &conf->tls_enabled);
966     else if (strcasecmp("TLSVerifyPeer", child->key) == 0)
967       status = cf_util_get_boolean(child, &conf->tls_verify_peer);
968     else if (strcasecmp("TLSVerifyHostName", child->key) == 0)
969       status = cf_util_get_boolean(child, &conf->tls_verify_hostname);
970     else if (strcasecmp("TLSCACert", child->key) == 0)
971       status = cf_util_get_string(child, &conf->tls_cacert);
972     else if (strcasecmp("TLSClientCert", child->key) == 0)
973       status = cf_util_get_string(child, &conf->tls_client_cert);
974     else if (strcasecmp("TLSClientKey", child->key) == 0)
975       status = cf_util_get_string(child, &conf->tls_client_key);
976     else if (strcasecmp("Exchange", child->key) == 0)
977       status = cf_util_get_string(child, &conf->exchange);
978     else if (strcasecmp("ExchangeType", child->key) == 0)
979       status = cf_util_get_string(child, &conf->exchange_type);
980     else if ((strcasecmp("Queue", child->key) == 0) && !publish)
981       status = cf_util_get_string(child, &conf->queue);
982     else if ((strcasecmp("QueueDurable", child->key) == 0) && !publish)
983       status = cf_util_get_boolean(child, &conf->queue_durable);
984     else if ((strcasecmp("QueueAutoDelete", child->key) == 0) && !publish)
985       status = cf_util_get_boolean(child, &conf->queue_auto_delete);
986     else if (strcasecmp("RoutingKey", child->key) == 0)
987       status = cf_util_get_string(child, &conf->routing_key);
988     else if ((strcasecmp("Persistent", child->key) == 0) && publish) {
989       bool tmp = 0;
990       status = cf_util_get_boolean(child, &tmp);
991       if (tmp)
992         conf->delivery_mode = CAMQP_DM_PERSISTENT;
993       else
994         conf->delivery_mode = CAMQP_DM_VOLATILE;
995     } else if ((strcasecmp("StoreRates", child->key) == 0) && publish) {
996       status = cf_util_get_boolean(child, &conf->store_rates);
997       (void)cf_util_get_flag(child, &conf->graphite_flags,
998                              GRAPHITE_STORE_RATES);
999     } else if ((strcasecmp("Format", child->key) == 0) && publish)
1000       status = camqp_config_set_format(child, conf);
1001     else if ((strcasecmp("GraphiteSeparateInstances", child->key) == 0) &&
1002              publish)
1003       status = cf_util_get_flag(child, &conf->graphite_flags,
1004                                 GRAPHITE_SEPARATE_INSTANCES);
1005     else if ((strcasecmp("GraphiteAlwaysAppendDS", child->key) == 0) && publish)
1006       status = cf_util_get_flag(child, &conf->graphite_flags,
1007                                 GRAPHITE_ALWAYS_APPEND_DS);
1008     else if ((strcasecmp("GraphitePreserveSeparator", child->key) == 0) &&
1009              publish)
1010       status = cf_util_get_flag(child, &conf->graphite_flags,
1011                                 GRAPHITE_PRESERVE_SEPARATOR);
1012     else if ((strcasecmp("GraphitePrefix", child->key) == 0) && publish)
1013       status = cf_util_get_string(child, &conf->prefix);
1014     else if ((strcasecmp("GraphitePostfix", child->key) == 0) && publish)
1015       status = cf_util_get_string(child, &conf->postfix);
1016     else if ((strcasecmp("GraphiteEscapeChar", child->key) == 0) && publish) {
1017       char *tmp_buff = NULL;
1018       status = cf_util_get_string(child, &tmp_buff);
1019       if (strlen(tmp_buff) > 1)
1020         WARNING("amqp plugin: The option \"GraphiteEscapeChar\" handles "
1021                 "only one character. Others will be ignored.");
1022       conf->escape_char = tmp_buff[0];
1023       sfree(tmp_buff);
1024     } else if (strcasecmp("ConnectionRetryDelay", child->key) == 0)
1025       status = cf_util_get_int(child, &conf->connection_retry_delay);
1026     else
1027       WARNING("amqp plugin: Ignoring unknown "
1028               "configuration option \"%s\".",
1029               child->key);
1030 
1031     if (status != 0)
1032       break;
1033   } /* for (i = 0; i < ci->children_num; i++) */
1034 
1035   if (status == 0 && conf->hosts_count == 0) {
1036     status = strarray_add(&conf->hosts, &conf->hosts_count, "localhost");
1037     if (status)
1038       ERROR("amqp plugin: Host configuration failed: %d", status);
1039   }
1040 
1041   if ((status == 0) && (conf->exchange == NULL)) {
1042     if (conf->exchange_type != NULL)
1043       WARNING("amqp plugin: The option \"ExchangeType\" was given "
1044               "without the \"Exchange\" option. It will be ignored.");
1045 
1046     if (!publish && (conf->routing_key != NULL))
1047       WARNING("amqp plugin: The option \"RoutingKey\" was given "
1048               "without the \"Exchange\" option. It will be ignored.");
1049   }
1050 
1051 #if !defined(AMQP_VERSION) || AMQP_VERSION < 0x00040000
1052   if (status == 0 && conf->tls_enabled) {
1053     ERROR("amqp plugin: TLSEnabled is set but not supported. "
1054           "rebuild collectd with rabbitmq-c >= 0.4");
1055     status = 1;
1056   }
1057 #endif
1058 #if !defined(AMQP_VERSION) || AMQP_VERSION < 0x00080000
1059   if (status == 0 && (!conf->tls_verify_peer || !conf->tls_verify_hostname)) {
1060     ERROR("amqp plugin: disabling TLSVerify* is not supported. "
1061           "rebuild collectd with rabbitmq-c >= 0.8");
1062     status = 1;
1063   }
1064 #endif
1065   if (status == 0 &&
1066       (conf->tls_client_cert != NULL || conf->tls_client_key != NULL)) {
1067     if (conf->tls_client_cert == NULL || conf->tls_client_key == NULL) {
1068       ERROR("amqp plugin: only one of TLSClientCert/TLSClientKey is "
1069             "configured. need both or neither.");
1070       status = 1;
1071     }
1072   }
1073 
1074   if (status != 0) {
1075     camqp_config_free(conf);
1076     return status;
1077   }
1078 
1079   if (conf->exchange != NULL) {
1080     DEBUG("amqp plugin: camqp_config_connection: exchange = %s;",
1081           conf->exchange);
1082   }
1083 
1084   if (publish) {
1085     char cbname[128];
1086     ssnprintf(cbname, sizeof(cbname), "amqp/%s", conf->name);
1087 
1088     status = plugin_register_write(cbname, camqp_write,
1089                                    &(user_data_t){
1090                                        .data = conf,
1091                                        .free_func = camqp_config_free,
1092                                    });
1093     if (status != 0) {
1094       camqp_config_free(conf);
1095       return status;
1096     }
1097   } else {
1098     status = camqp_subscribe_init(conf);
1099     if (status != 0) {
1100       camqp_config_free(conf);
1101       return status;
1102     }
1103   }
1104 
1105   return 0;
1106 } /* }}} int camqp_config_connection */
1107 
camqp_config(oconfig_item_t * ci)1108 static int camqp_config(oconfig_item_t *ci) /* {{{ */
1109 {
1110   for (int i = 0; i < ci->children_num; i++) {
1111     oconfig_item_t *child = ci->children + i;
1112 
1113     if (strcasecmp("Publish", child->key) == 0)
1114       camqp_config_connection(child, /* publish = */ true);
1115     else if (strcasecmp("Subscribe", child->key) == 0)
1116       camqp_config_connection(child, /* publish = */ false);
1117     else
1118       WARNING("amqp plugin: Ignoring unknown config option \"%s\".",
1119               child->key);
1120   } /* for (ci->children_num) */
1121 
1122   return 0;
1123 } /* }}} int camqp_config */
1124 
module_register(void)1125 void module_register(void) {
1126   plugin_register_complex_config("amqp", camqp_config);
1127   plugin_register_shutdown("amqp", camqp_shutdown);
1128 } /* void module_register */
1129