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