Debian Codegraph @

c/examples/broker.c

raw
1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 #include "thread.h"
21
22 #include <proton/engine.h>
23 #include <proton/listener.h>
24 #include <proton/netaddr.h>
25 #include <proton/proactor.h>
26 #include <proton/sasl.h>
27 #include <proton/ssl.h>
28 #include <proton/transport.h>
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33
34 /* The ssl-certs subdir must be in the current directory for an ssl-enabled broker */
35 #define SSL_FILE(NAME) "ssl-certs/" NAME
36 #define SSL_PW "tserverpw"
37 /* Windows vs. OpenSSL certificates */
38 #if defined(_WIN32)
39 # define CERTIFICATE(NAME) SSL_FILE(NAME "-certificate.p12")
40 # define SET_CREDENTIALS(DOMAIN, NAME) \
41 pn_ssl_domain_set_credentials(DOMAIN, SSL_FILE(NAME "-full.p12"), "", SSL_PW)
42 #else
43 # define CERTIFICATE(NAME) SSL_FILE(NAME "-certificate.pem")
44 # define SET_CREDENTIALS(DOMAIN, NAME) \
45 pn_ssl_domain_set_credentials(DOMAIN, CERTIFICATE(NAME), SSL_FILE(NAME "-private-key.pem"), SSL_PW)
46 #endif
47
48 /* Simple re-sizable vector that acts as a queue */
49 #define VEC(T) struct { T* data; size_t len, cap; }
50
51 #define VEC_INIT(V) \
52 do { \
53 void **vp = (void**)&V.data; \
54 V.len = 0; \
55 V.cap = 16; \
56 *vp = malloc(V.cap * sizeof(*V.data)); \
57 } while(0)
58
59 #define VEC_FINAL(V) free(V.data)
60
61 #define VEC_PUSH(V, X) \
62 do { \
63 if (V.len == V.cap) { \
64 void **vp = (void**)&V.data; \
65 V.cap *= 2; \
66 *vp = realloc(V.data, V.cap * sizeof(*V.data)); \
67 } \
68 V.data[V.len++] = X; \
69 } while(0) \
70
71 #define VEC_POP(V) \
72 do { \
73 if (V.len > 0) \
74 memmove(V.data, V.data+1, (--V.len)*sizeof(*V.data)); \
75 } while(0)
76
77 /* Simple thread-safe queue implementation */
78 typedef struct queue_t {
79 pthread_mutex_t lock;
80 char *name;
81 VEC(pn_rwbytes_t) messages; /* Messages on the queue_t */
82 VEC(pn_connection_t*) waiting; /* Connections waiting to send messages from this queue */
83 struct queue_t *next; /* Next queue in chain */
84 size_t sent; /* Count of messages sent, used as delivery tag */
85 } queue_t;
86
87 static void queue_init(queue_t *q, const char* name, queue_t *next) {
88 pthread_mutex_init(&q->lock, NULL);
89 q->name = (char*)malloc(strlen(name)+1);
90 memcpy(q->name, name, strlen(name)+1);
91 VEC_INIT(q->messages);
92 VEC_INIT(q->waiting);
93 q->next = next;
94 q->sent = 0;
95 }
96
97 static void queue_destroy(queue_t *q) {
98 size_t i;
99 pthread_mutex_destroy(&q->lock);
100 for (i = 0; i < q->messages.len; ++i)
101 free(q->messages.data[i].start);
102 VEC_FINAL(q->messages);
103 for (i = 0; i < q->waiting.len; ++i)
104 pn_decref(q->waiting.data[i]);
105 VEC_FINAL(q->waiting);
106 free(q->name);
107 }
108
109 /* Send a message on s, or record s as waiting if there are no messages to send.
110 Called in s dispatch loop, assumes s has credit.
111 */
112 static void queue_send(queue_t *q, pn_link_t *s) {
113 pn_rwbytes_t m = { 0 };
114 size_t tag = 0;
115 pthread_mutex_lock(&q->lock);
116 if (q->messages.len == 0) { /* Empty, record connection as waiting */
117 /* Record connection for wake-up if not already on the list. */
118 pn_connection_t *c = pn_session_connection(pn_link_session(s));
119 size_t i = 0;
120 for (; i < q->waiting.len && q->waiting.data[i] != c; ++i)
121 ;
122 if (i == q->waiting.len) {
123 VEC_PUSH(q->waiting, c);
124 }
125 } else {
126 m = q->messages.data[0];
127 VEC_POP(q->messages);
128 tag = ++q->sent;
129 }
130 pthread_mutex_unlock(&q->lock);
131 if (m.start) {
132 pn_delivery_t *d = pn_delivery(s, pn_dtag((char*)&tag, sizeof(tag)));
133 pn_link_send(s, m.start, m.size);
134 pn_link_advance(s);
135 pn_delivery_settle(d); /* Pre-settled: unreliable, there will be no ack/ */
136 free(m.start);
137 }
138 }
139
140 /* Use the connection context pointer as a boolean flag to indicate we need to check queues */
141 void set_check_queues(pn_connection_t *c, bool check) {
142 pn_connection_set_context(c, (void*)check);
143 }
144
145 bool get_check_queues(pn_connection_t *c) {
146 return (bool)pn_connection_get_context(c);
147 }
148
149 /* Use a buffer per link to accumulate message data - message can arrive in multiple deliveries,
150 and the broker can receive messages on many concurrently. */
151 pn_rwbytes_t *message_buffer(pn_link_t *l) {
152 if (!pn_link_get_context(l)) {
153 pn_link_set_context(l, calloc(1, sizeof(pn_rwbytes_t)));
154 }
155 return (pn_rwbytes_t*)pn_link_get_context(l);
156 }
157
158 /* Put a message on the queue, called in receiver dispatch loop.
159 If the queue was previously empty, notify waiting senders.
160 */
161 static void queue_receive(pn_proactor_t *d, queue_t *q, pn_rwbytes_t m) {
162 pthread_mutex_lock(&q->lock);
163 VEC_PUSH(q->messages, m);
164 if (q->messages.len == 1) { /* Was empty, notify waiting connections */
165 size_t i;
166 for (i = 0; i < q->waiting.len; ++i) {
167 pn_connection_t *c = q->waiting.data[i];
168 set_check_queues(c, true);
169 pn_connection_wake(c); /* Wake the connection */
170 }
171 q->waiting.len = 0;
172 }
173 pthread_mutex_unlock(&q->lock);
174 }
175
176 /* Thread safe set of queues */
177 typedef struct queues_t {
178 pthread_mutex_t lock;
179 queue_t *queues;
180 size_t sent;
181 } queues_t;
182
183 void queues_init(queues_t *qs) {
184 pthread_mutex_init(&qs->lock, NULL);
185 qs->queues = NULL;
186 }
187
188 void queues_destroy(queues_t *qs) {
189 while (qs->queues) {
190 queue_t *q = qs->queues;
191 qs->queues = qs->queues->next;
192 queue_destroy(q);
193 free(q);
194 }
195 pthread_mutex_destroy(&qs->lock);
196 }
197
198 /** Get or create the named queue. */
199 queue_t* queues_get(queues_t *qs, const char* name) {
200 queue_t *q;
201 pthread_mutex_lock(&qs->lock);
202 for (q = qs->queues; q && strcmp(q->name, name) != 0; q = q->next)
203 ;
204 if (!q) {
205 q = (queue_t*)malloc(sizeof(queue_t));
206 queue_init(q, name, qs->queues);
207 qs->queues = q;
208 }
209 pthread_mutex_unlock(&qs->lock);
210 return q;
211 }
212
213 /* The broker implementation */
214 typedef struct broker_t {
215 pn_proactor_t *proactor;
216 size_t threads;
217 const char *container_id; /* AMQP container-id */
218 queues_t queues;
219 pn_ssl_domain_t *ssl_domain;
220 } broker_t;
221
222 void broker_stop(broker_t *b) {
223 /* Interrupt the proactor to stop the working threads. */
224 pn_proactor_interrupt(b->proactor);
225 }
226
227 /* Try to send if link is sender and has credit */
228 static void link_send(broker_t *b, pn_link_t *s) {
229 if (pn_link_is_sender(s) && pn_link_credit(s) > 0) {
230 const char *qname = pn_terminus_get_address(pn_link_source(s));
231 queue_t *q = queues_get(&b->queues, qname);
232 queue_send(q, s);
233 }
234 }
235
236 static void queue_unsub(queue_t *q, pn_connection_t *c) {
237 size_t i;
238 pthread_mutex_lock(&q->lock);
239 for (i = 0; i < q->waiting.len; ++i) {
240 if (q->waiting.data[i] == c){
241 q->waiting.data[i] = q->waiting.data[0]; /* save old [0] */
242 VEC_POP(q->waiting);
243 break;
244 }
245 }
246 pthread_mutex_unlock(&q->lock);
247 }
248
249 /* Unsubscribe from the queue of interest to this link. */
250 static void link_unsub(broker_t *b, pn_link_t *s) {
251 if (pn_link_is_sender(s)) {
252 const char *qname = pn_terminus_get_address(pn_link_source(s));
253 if (qname) {
254 queue_t *q = queues_get(&b->queues, qname);
255 queue_unsub(q, pn_session_connection(pn_link_session(s)));
256 }
257 }
258 }
259
260 /* Called in connection's event loop when a connection is woken for messages.*/
261 static void connection_unsub(broker_t *b, pn_connection_t *c) {
262 pn_link_t *l;
263 for (l = pn_link_head(c, 0); l != NULL; l = pn_link_next(l, 0))
264 link_unsub(b, l);
265 }
266
267 static void session_unsub(broker_t *b, pn_session_t *ssn) {
268 pn_connection_t *c = pn_session_connection(ssn);
269 pn_link_t *l;
270 for (l = pn_link_head(c, 0); l != NULL; l = pn_link_next(l, 0)) {
271 if (pn_link_session(l) == ssn)
272 link_unsub(b, l);
273 }
274 }
275
276 static void check_condition(pn_event_t *e, pn_condition_t *cond) {
277 if (pn_condition_is_set(cond)) {
278 printf("%s: %s: %s\n", pn_event_type_name(pn_event_type(e)),
279 pn_condition_get_name(cond), pn_condition_get_description(cond));
280 }
281 }
282
283 const int WINDOW=5; /* Very small incoming credit window, to show flow control in action */
284
285 static bool handle(broker_t* b, pn_event_t* e) {
286 pn_connection_t *c = pn_event_connection(e);
287
288 switch (pn_event_type(e)) {
289
290 case PN_LISTENER_OPEN: {
291 char port[PN_MAX_ADDR]; /* Get the listening port */
292 pn_netaddr_host_port(pn_listener_addr(pn_event_listener(e)), NULL, 0, port, sizeof(port));
293 printf("listening on %s\n", port);
294 fflush(stdout);
295 break;
296 }
297 case PN_LISTENER_ACCEPT: {
298 /* Configure a transport to allow SSL and SASL connections. See ssl_domain setup in main() */
299 pn_transport_t *t = pn_transport();
300 pn_transport_set_server(t); /* Must call before pn_sasl() */
301 pn_sasl_allowed_mechs(pn_sasl(t), "ANONYMOUS");
302 if (b->ssl_domain) {
303 pn_ssl_init(pn_ssl(t), b->ssl_domain, NULL);
304 pn_transport_require_encryption(t, false); /* Must call this after pn_ssl_init */
305 }
306 pn_listener_accept2(pn_event_listener(e), NULL, t);
307 break;
308 }
309 case PN_CONNECTION_INIT:
310 pn_connection_set_container(c, b->container_id);
311 break;
312
313 case PN_CONNECTION_REMOTE_OPEN: {
314 pn_connection_open(pn_event_connection(e)); /* Complete the open */
315 break;
316 }
317 case PN_CONNECTION_WAKE: {
318 if (get_check_queues(c)) {
319 int flags = PN_LOCAL_ACTIVE&PN_REMOTE_ACTIVE;
320 pn_link_t *l;
321 set_check_queues(c, false);
322 for (l = pn_link_head(c, flags); l != NULL; l = pn_link_next(l, flags))
323 link_send(b, l);
324 }
325 break;
326 }
327 case PN_SESSION_REMOTE_OPEN: {
328 pn_session_open(pn_event_session(e));
329 break;
330 }
331 case PN_LINK_REMOTE_OPEN: {
332 pn_link_t *l = pn_event_link(e);
333 if (pn_link_is_sender(l)) {
334 const char *source = pn_terminus_get_address(pn_link_remote_source(l));
335 pn_terminus_set_address(pn_link_source(l), source);
336 } else {
337 const char* target = pn_terminus_get_address(pn_link_remote_target(l));
338 pn_terminus_set_address(pn_link_target(l), target);
339 pn_link_flow(l, WINDOW);
340 }
341 pn_link_open(l);
342 break;
343 }
344 case PN_LINK_FLOW: {
345 link_send(b, pn_event_link(e));
346 break;
347 }
348 case PN_LINK_FINAL: {
349 pn_rwbytes_t *buf = (pn_rwbytes_t*)pn_link_get_context(pn_event_link(e));
350 if (buf) {
351 free(buf->start);
352 free(buf);
353 }
354 break;
355 }
356 case PN_DELIVERY: { /* Incoming message data */
357 pn_delivery_t *d = pn_event_delivery(e);
358 if (pn_delivery_readable(d)) {
359 pn_link_t *l = pn_delivery_link(d);
360 size_t size = pn_delivery_pending(d);
361 pn_rwbytes_t* m = message_buffer(l); /* Append data to incoming message buffer */
362 ssize_t recv;
363 m->size += size;
364 m->start = (char*)realloc(m->start, m->size);
365 recv = pn_link_recv(l, m->start, m->size);
366 if (recv == PN_ABORTED) { /* */
367 printf("Message aborted\n");
368 fflush(stdout);
369 m->size = 0; /* Forget the data we accumulated */
370 pn_delivery_settle(d); /* Free the delivery so we can receive the next message */
371 pn_link_flow(l, WINDOW - pn_link_credit(l)); /* Replace credit for the aborted message */
372 } else if (recv < 0 && recv != PN_EOS) { /* Unexpected error */
373 pn_condition_format(pn_link_condition(l), "broker", "PN_DELIVERY error: %s", pn_code((int)recv));
374 pn_link_close(l); /* Unexpected error, close the link */
375 } else if (!pn_delivery_partial(d)) { /* Message is complete */
376 const char *qname = pn_terminus_get_address(pn_link_target(l));
377 queue_receive(b->proactor, queues_get(&b->queues, qname), *m);
378 *m = pn_rwbytes_null; /* Reset the buffer for the next message*/
379 pn_delivery_update(d, PN_ACCEPTED);
380 pn_delivery_settle(d);
381 pn_link_flow(l, WINDOW - pn_link_credit(l));
382 }
383 }
384 break;
385 }
386
387 case PN_TRANSPORT_CLOSED:
388 check_condition(e, pn_transport_condition(pn_event_transport(e)));
389 connection_unsub(b, pn_event_connection(e));
390 break;
391
392 case PN_CONNECTION_REMOTE_CLOSE:
393 check_condition(e, pn_connection_remote_condition(pn_event_connection(e)));
394 pn_connection_close(pn_event_connection(e));
395 break;
396
397 case PN_SESSION_REMOTE_CLOSE:
398 check_condition(e, pn_session_remote_condition(pn_event_session(e)));
399 session_unsub(b, pn_event_session(e));
400 pn_session_close(pn_event_session(e));
401 pn_session_free(pn_event_session(e));
402 break;
403
404 case PN_LINK_REMOTE_CLOSE:
405 check_condition(e, pn_link_remote_condition(pn_event_link(e)));
406 link_unsub(b, pn_event_link(e));
407 pn_link_close(pn_event_link(e));
408 pn_link_free(pn_event_link(e));
409 break;
410
411 case PN_LISTENER_CLOSE:
412 check_condition(e, pn_listener_condition(pn_event_listener(e)));
413 broker_stop(b);
414 break;
415
416 case PN_PROACTOR_INACTIVE: /* listener and all connections closed */
417 broker_stop(b);
418 break;
419
420 case PN_PROACTOR_INTERRUPT:
421 pn_proactor_interrupt(b->proactor); /* Pass along the interrupt to the other threads */
422 return false;
423
424 default:
425 break;
426 }
427 return true;
428 }
429
430 static void* broker_thread(void *void_broker) {
431 broker_t *b = (broker_t*)void_broker;
432 bool finished = false;
433 do {
434 pn_event_batch_t *events = pn_proactor_wait(b->proactor);
435 pn_event_t *e;
436 while ((e = pn_event_batch_next(events))) {
437 if (!handle(b, e)) finished = true;
438 }
439 pn_proactor_done(b->proactor, events);
440 } while(!finished);
441 return NULL;
442 }
443
444 int main(int argc, char **argv) {
445 const char *host = (argc > 1) ? argv[1] : "";
446 const char *port = (argc > 2) ? argv[2] : "amqp";
447 int err;
448
449 broker_t b = {0};
450 b.proactor = pn_proactor();
451 queues_init(&b.queues);
452 b.container_id = argv[0];
453 b.threads = 4;
454 b.ssl_domain = pn_ssl_domain(PN_SSL_MODE_SERVER);
455 err = SET_CREDENTIALS(b.ssl_domain, "tserver");
456 if (err) {
457 printf("Failed to set up server certificate: %s, private key: %s\n", CERTIFICATE("tserver"), SSL_FILE("tserver-private-key.pem"));
458 }
459 {
460 /* Listen on addr */
461 char addr[PN_MAX_ADDR];
462 pn_proactor_addr(addr, sizeof(addr), host, port);
463 pn_proactor_listen(b.proactor, pn_listener(), addr, 16);
464 }
465
466 {
467 /* Start n-1 threads */
468 pthread_t* threads = (pthread_t*)calloc(sizeof(pthread_t), b.threads);
469 size_t i;
470 for (i = 0; i < b.threads-1; ++i) {
471 pthread_create(&threads[i], NULL, broker_thread, &b);
472 }
473 broker_thread(&b); /* Use the main thread too. */
474 /* Join the other threads */
475 for (i = 0; i < b.threads-1; ++i) {
476 pthread_join(threads[i], NULL);
477 }
478 pn_proactor_free(b.proactor);
479 free(threads);
480 pn_ssl_domain_free(b.ssl_domain);
481 return 0;
482 }
483 }