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