messaging.c (2658B)
1 /*
2 * Copyright (c) 2015 Joris Vink <joris@coders.se>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
16
17 #include <kore/kore.h>
18 #include <kore/http.h>
19
20 /*
21 * This example demonstrates how to use the messaging framework
22 * in Kore. This framework allows you to send messages between
23 * your workers with custom callbacks defined per message ID.
24 */
25
26 /* Your code shouldn't use IDs <= KORE_MSG_APP_BASE. */
27 #define MY_MESSAGE_ID KORE_MSG_APP_BASE + 1
28
29 int init(int);
30 int page(struct http_request *);
31 int page_shutdown(struct http_request *req);
32 void received_message(struct kore_msg *, const void *);
33
34 /* Initialization callback. */
35 int
36 init(int state)
37 {
38 if (state == KORE_MODULE_UNLOAD)
39 return (KORE_RESULT_OK);
40
41 /*
42 * Register our message callback when the module is initialized.
43 * kore_msg_register() fails if the message ID already exists,
44 * but in our case that is OK.
45 */
46 (void)kore_msg_register(MY_MESSAGE_ID, received_message);
47
48 return (KORE_RESULT_OK);
49 }
50
51 /*
52 * Callback for receiving a message MY_MESSAGE_ID.
53 */
54 void
55 received_message(struct kore_msg *msg, const void *data)
56 {
57 kore_log(LOG_INFO, "got message from %u (%zu bytes): %.*s", msg->src,
58 msg->length, (int)msg->length, (const char *)data);
59 }
60
61 /*
62 * Page request which will send a message to all other workers
63 * with the ID set to MY_MESSAGE_ID and a payload of "hello".
64 */
65 int
66 page(struct http_request *req)
67 {
68 /* Send to all workers first. */
69 kore_msg_send(KORE_MSG_WORKER_ALL, MY_MESSAGE_ID, "hello", 5);
70
71 /* Now send something to worker number #2 only. */
72 kore_msg_send(2, MY_MESSAGE_ID, "hello number 2", 14);
73
74 http_response(req, 200, NULL, 0);
75 return (KORE_RESULT_OK);
76 }
77
78 /*
79 * Page request which will send a message to the parent
80 * requesting process shutdown.
81 */
82 int
83 page_shutdown(struct http_request *req)
84 {
85 /* Send shutdown request to parent. */
86 kore_msg_send(KORE_MSG_PARENT, KORE_MSG_SHUTDOWN, "1", 1);
87
88 http_response(req, 200, NULL, 0);
89 return (KORE_RESULT_OK);
90 }