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