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