1 /*************************************************************************//**
3 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
5 * Unless otherwise specified, all software contained herein is
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
17 ****************************************************************************/
19 /**************************************************************************//**
23 * Simple event manager that is responsible for taking events (Heartbeats,
24 * Faults and Measurements) from the ring-buffer and posting them to the API.
26 ****************************************************************************/
33 #include <curl/curl.h>
36 #include "evel_internal.h"
37 #include "ring_buffer.h"
38 #include "evel_throttle.h"
40 /**************************************************************************//**
41 * How long we're prepared to wait for the API service to respond in
43 *****************************************************************************/
44 static const int EVEL_API_TIMEOUT = 5;
46 /*****************************************************************************/
47 /* Prototypes of locally scoped functions. */
48 /*****************************************************************************/
49 static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *userp);
50 static void * event_handler(void *arg);
51 static bool evel_handle_response_tokens(const MEMORY_CHUNK * const chunk,
52 const jsmntok_t * const json_tokens,
54 MEMORY_CHUNK * const post);
55 static bool evel_tokens_match_command_list(const MEMORY_CHUNK * const chunk,
56 const jsmntok_t * const json_token,
57 const int num_tokens);
58 static bool evel_token_equals_string(const MEMORY_CHUNK * const chunk,
59 const jsmntok_t * const json_token,
60 const char * check_string);
62 /**************************************************************************//**
63 * Buffers for error strings from libcurl.
64 *****************************************************************************/
65 static char curl_err_string[CURL_ERROR_SIZE] = "<NULL>";
67 /**************************************************************************//**
68 * Handle for the API into libcurl.
69 *****************************************************************************/
70 static CURL * curl_handle = NULL;
72 /**************************************************************************//**
73 * Special headers that we send.
74 *****************************************************************************/
75 static struct curl_slist * hdr_chunk = NULL;
77 /**************************************************************************//**
78 * Message queue for sending events to the API.
79 *****************************************************************************/
80 static ring_buffer event_buffer;
82 /**************************************************************************//**
83 * Single pending priority post, which can be generated as a result of a
84 * response to an event. Currently only used to respond to a commandList.
85 *****************************************************************************/
86 static MEMORY_CHUNK priority_post;
88 /**************************************************************************//**
89 * The thread which is responsible for handling events off of the ring-buffer
90 * and posting them to the Event Handler API.
91 *****************************************************************************/
92 static pthread_t evt_handler_thread;
94 /**************************************************************************//**
95 * Variable to convey to the event handler thread what the foreground wants it
97 *****************************************************************************/
98 static EVT_HANDLER_STATE evt_handler_state = EVT_HANDLER_UNINITIALIZED;
100 /**************************************************************************//**
101 * The configured API URL for event and throttling.
102 *****************************************************************************/
103 static char * evel_event_api_url;
104 static char * evel_throt_api_url;
105 static char * evel_batch_api_url;
107 /**************************************************************************//**
108 * Initialize the event handler.
110 * Primarily responsible for getting CURL ready for use.
112 * @param[in] event_api_url
113 * The URL where the Vendor Event Listener API is expected
115 * @param[in] throt_api_url
116 * The URL where the Throttling API is expected to be.
117 * @param[in] username The username for the Basic Authentication of requests.
118 * @param[in] password The password for the Basic Authentication of requests.
119 * @param verbosity 0 for normal operation, positive values for chattier
121 *****************************************************************************/
122 EVEL_ERR_CODES event_handler_initialize(const char * const event_api_url,
123 const char * const throt_api_url,
124 const char * const username,
125 const char * const password,
128 int rc = EVEL_SUCCESS;
129 CURLcode curl_rc = CURLE_OK;
130 char batch_api_url[EVEL_MAX_URL_LEN + 1] = {0};
134 /***************************************************************************/
135 /* Check assumptions. */
136 /***************************************************************************/
137 assert(event_api_url != NULL);
138 assert(throt_api_url != NULL);
139 assert(username != NULL);
140 assert(password != NULL);
142 /***************************************************************************/
143 /* Store the API URLs. */
144 /***************************************************************************/
145 evel_event_api_url = strdup(event_api_url);
146 assert(evel_event_api_url != NULL);
147 sprintf(batch_api_url,"%s/eventBatch",event_api_url);
148 evel_batch_api_url = strdup(batch_api_url);
149 assert(evel_batch_api_url != NULL);
150 evel_throt_api_url = strdup(throt_api_url);
151 assert(evel_throt_api_url != NULL);
154 curl_version_info_data *d = curl_version_info(CURLVERSION_NOW);
155 /* compare with the 24 bit hex number in 8 bit fields */
156 if(d->version_num >= 0x072100) {
157 /* this is libcurl 7.33.0 or later */
158 EVEL_INFO("7.33 or later Curl version %x.",d->version_num);
161 EVEL_INFO("Old Curl version.");
163 /***************************************************************************/
164 /* Start the CURL library. Note that this initialization is not threadsafe */
165 /* which imposes a constraint that the EVEL library is initialized before */
166 /* any threads are started. */
167 /***************************************************************************/
168 curl_rc = curl_global_init(CURL_GLOBAL_SSL);
169 if (curl_rc != CURLE_OK)
171 rc = EVEL_CURL_LIBRARY_FAIL;
172 log_error_state("Failed to initialize libCURL. Error code=%d", curl_rc);
176 /***************************************************************************/
177 /* Get a curl handle which we'll use for all of our output. */
178 /***************************************************************************/
179 curl_handle = curl_easy_init();
180 if (curl_handle == NULL)
182 rc = EVEL_CURL_LIBRARY_FAIL;
183 log_error_state("Failed to get libCURL handle");
187 /***************************************************************************/
188 /* Prime the library to give friendly error codes. */
189 /***************************************************************************/
190 curl_rc = curl_easy_setopt(curl_handle,
193 if (curl_rc != CURLE_OK)
195 rc = EVEL_CURL_LIBRARY_FAIL;
196 log_error_state("Failed to initialize libCURL to provide friendly errors. "
197 "Error code=%d", curl_rc);
201 /***************************************************************************/
202 /* If running in verbose mode generate more output. */
203 /***************************************************************************/
206 curl_rc = curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1L);
207 if (curl_rc != CURLE_OK)
209 rc = EVEL_CURL_LIBRARY_FAIL;
210 log_error_state("Failed to initialize libCURL to be verbose. "
211 "Error code=%d", curl_rc);
216 /***************************************************************************/
217 /* Set the URL for the API. */
218 /***************************************************************************/
219 curl_rc = curl_easy_setopt(curl_handle, CURLOPT_URL, event_api_url);
220 if (curl_rc != CURLE_OK)
222 rc = EVEL_CURL_LIBRARY_FAIL;
223 log_error_state("Failed to initialize libCURL with the API URL. "
224 "Error code=%d (%s)", curl_rc, curl_err_string);
227 EVEL_INFO("Initializing CURL to send events to: %s", event_api_url);
229 /***************************************************************************/
230 /* send all data to this function. */
231 /***************************************************************************/
232 curl_rc = curl_easy_setopt(curl_handle,
233 CURLOPT_WRITEFUNCTION,
234 evel_write_callback);
235 if (curl_rc != CURLE_OK)
237 rc = EVEL_CURL_LIBRARY_FAIL;
238 log_error_state("Failed to initialize libCURL with the write callback. "
239 "Error code=%d (%s)", curl_rc, curl_err_string);
243 /***************************************************************************/
244 /* some servers don't like requests that are made without a user-agent */
245 /* field, so we provide one. */
246 /***************************************************************************/
247 curl_rc = curl_easy_setopt(curl_handle,
249 "libcurl-agent/1.0");
250 if (curl_rc != CURLE_OK)
252 rc = EVEL_CURL_LIBRARY_FAIL;
253 log_error_state("Failed to initialize libCURL to upload. "
254 "Error code=%d (%s)", curl_rc, curl_err_string);
258 /***************************************************************************/
259 /* Specify that we are going to POST data. */
260 /***************************************************************************/
261 curl_rc = curl_easy_setopt(curl_handle, CURLOPT_POST, 1L);
262 if (curl_rc != CURLE_OK)
264 rc = EVEL_CURL_LIBRARY_FAIL;
265 log_error_state("Failed to initialize libCURL to upload. "
266 "Error code=%d (%s)", curl_rc, curl_err_string);
270 /***************************************************************************/
271 /* we want to use our own read function. */
272 /***************************************************************************/
273 curl_rc = curl_easy_setopt(curl_handle, CURLOPT_READFUNCTION, read_callback);
274 if (curl_rc != CURLE_OK)
276 rc = EVEL_CURL_LIBRARY_FAIL;
277 log_error_state("Failed to initialize libCURL to upload using read "
278 "function. Error code=%d (%s)", curl_rc, curl_err_string);
282 /***************************************************************************/
283 /* All of our events are JSON encoded. We also suppress the */
284 /* Expect: 100-continue header that we would otherwise get since it */
285 /* confuses some servers. */
287 /* @TODO: do AT&T want this behavior? */
288 /***************************************************************************/
289 hdr_chunk = curl_slist_append(hdr_chunk, "Content-type: application/json");
290 hdr_chunk = curl_slist_append(hdr_chunk, "Expect:");
292 /***************************************************************************/
293 /* set our custom set of headers. */
294 /***************************************************************************/
295 curl_rc = curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, hdr_chunk);
296 if (curl_rc != CURLE_OK)
298 rc = EVEL_CURL_LIBRARY_FAIL;
299 log_error_state("Failed to initialize libCURL to use custom headers. "
300 "Error code=%d (%s)", curl_rc, curl_err_string);
304 /***************************************************************************/
305 /* Set the timeout for the operation. */
306 /***************************************************************************/
307 curl_rc = curl_easy_setopt(curl_handle,
310 if (curl_rc != CURLE_OK)
312 rc = EVEL_CURL_LIBRARY_FAIL;
313 log_error_state("Failed to initialize libCURL for API timeout. "
314 "Error code=%d (%s)", curl_rc, curl_err_string);
318 /***************************************************************************/
319 /* Set that we want Basic authentication with username:password Base-64 */
320 /* encoded for the operation. */
321 /***************************************************************************/
322 curl_rc = curl_easy_setopt(curl_handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
323 if (curl_rc != CURLE_OK)
325 rc = EVEL_CURL_LIBRARY_FAIL;
326 log_error_state("Failed to initialize libCURL for Basic Authentication. "
327 "Error code=%d (%s)", curl_rc, curl_err_string);
330 curl_rc = curl_easy_setopt(curl_handle, CURLOPT_USERNAME, username);
331 if (curl_rc != CURLE_OK)
333 rc = EVEL_CURL_LIBRARY_FAIL;
334 log_error_state("Failed to initialize libCURL with username. "
335 "Error code=%d (%s)", curl_rc, curl_err_string);
338 curl_rc = curl_easy_setopt(curl_handle, CURLOPT_PASSWORD, password);
339 if (curl_rc != CURLE_OK)
341 rc = EVEL_CURL_LIBRARY_FAIL;
342 log_error_state("Failed to initialize libCURL with password. "
343 "Error code=%d (%s)", curl_rc, curl_err_string);
347 /***************************************************************************/
348 /* Initialize a message ring-buffer to be used between the foreground and */
349 /* the thread which sends the messages. This can't fail. */
350 /***************************************************************************/
351 ring_buffer_initialize(&event_buffer, EVEL_EVENT_BUFFER_DEPTH);
353 /***************************************************************************/
354 /* Initialize the priority post buffer to empty. */
355 /***************************************************************************/
356 priority_post.memory = NULL;
364 /**************************************************************************//**
365 * Run the event handler.
367 * Spawns the thread responsible for handling events and sending them to the
370 * @return Status code.
371 * @retval ::EVEL_SUCCESS if everything OK.
372 * @retval One of ::EVEL_ERR_CODES if there was a problem.
373 *****************************************************************************/
374 EVEL_ERR_CODES event_handler_run()
376 EVEL_ERR_CODES rc = EVEL_SUCCESS;
381 /***************************************************************************/
382 /* Start the event handler thread. */
383 /***************************************************************************/
384 evt_handler_state = EVT_HANDLER_INACTIVE;
385 pthread_rc = pthread_create(&evt_handler_thread, NULL, event_handler, NULL);
388 rc = EVEL_PTHREAD_LIBRARY_FAIL;
389 log_error_state("Failed to start event handler thread. "
390 "Error code=%d", pthread_rc);
397 /**************************************************************************//**
398 * Terminate the event handler.
400 * Shuts down the event handler thread in as clean a way as possible. Sets the
401 * global exit flag and then signals the thread to interrupt it since it's
402 * most likely waiting on the ring-buffer.
404 * Having achieved an orderly shutdown of the event handler thread, clean up
405 * the cURL library's resources cleanly.
407 * @return Status code.
408 * @retval ::EVEL_SUCCESS if everything OK.
409 * @retval One of ::EVEL_ERR_CODES if there was a problem.
410 *****************************************************************************/
411 EVEL_ERR_CODES event_handler_terminate()
413 EVEL_ERR_CODES rc = EVEL_SUCCESS;
416 EVENT_INTERNAL *event = NULL;
418 /***************************************************************************/
419 /* Make sure that we were initialized before trying to terminate the */
420 /* event handler thread. */
421 /***************************************************************************/
422 if (evt_handler_state != EVT_HANDLER_UNINITIALIZED)
424 /*************************************************************************/
425 /* Make sure that the event handler knows it's time to die. */
426 /*************************************************************************/
427 event = evel_new_internal_event(EVT_CMD_TERMINATE,"EVELinternal","EVELid");
430 /***********************************************************************/
431 /* We failed to get an event, but we don't bail out - we will just */
432 /* clean up what we can and continue on our way, since we're exiting */
434 /***********************************************************************/
435 EVEL_ERROR("Failed to get internal event - perform dirty exit instead!");
439 /***********************************************************************/
440 /* Post the event then wait for the Event Handler to exit. Set the */
441 /* global command, too, in case the ring-buffer is full. */
442 /***********************************************************************/
443 EVEL_DEBUG("Sending event to Event Hander to request it to exit.");
444 evt_handler_state = EVT_HANDLER_REQUEST_TERMINATE;
445 evel_post_event((EVENT_HEADER *) event);
446 pthread_join(evt_handler_thread, NULL);
447 EVEL_DEBUG("Event Handler thread has exited.");
452 EVEL_DEBUG("Event handler was not initialized, so no need to kill it");
455 /***************************************************************************/
456 /* Clean-up the cURL library. */
457 /***************************************************************************/
458 if (curl_handle != NULL)
460 curl_easy_cleanup(curl_handle);
463 if (hdr_chunk != NULL)
465 curl_slist_free_all(hdr_chunk);
469 /***************************************************************************/
470 /* Free off the stored API URL strings. */
471 /***************************************************************************/
472 if (evel_event_api_url != NULL)
474 free(evel_event_api_url);
475 evel_event_api_url = NULL;
477 if (evel_throt_api_url != NULL)
479 free(evel_throt_api_url);
480 evel_throt_api_url = NULL;
487 /**************************************************************************//**
490 * @note So far as the caller is concerned, successfully posting the event
491 * relinquishes all responsibility for the event - the library will take care
492 * of freeing the event in due course.
494 * @param event The event to be posted.
496 * @returns Status code
497 * @retval EVEL_SUCCESS On success
498 * @retval "One of ::EVEL_ERR_CODES" On failure.
499 *****************************************************************************/
500 EVEL_ERR_CODES evel_post_event(EVENT_HEADER * event)
502 int rc = EVEL_SUCCESS;
506 /***************************************************************************/
507 /* Check preconditions. */
508 /***************************************************************************/
509 assert(event != NULL);
511 /***************************************************************************/
512 /* We need to make sure that we are either initializing or running */
513 /* normally before writing the event into the buffer so that we can */
514 /* guarantee that the ring-buffer empties properly on exit. */
515 /***************************************************************************/
516 if ((evt_handler_state == EVT_HANDLER_ACTIVE) ||
517 (evt_handler_state == EVT_HANDLER_INACTIVE) ||
518 (evt_handler_state == EVT_HANDLER_REQUEST_TERMINATE))
520 if (ring_buffer_write(&event_buffer, event) == 0)
522 log_error_state("Failed to write event to buffer - event dropped!");
523 rc = EVEL_EVENT_BUFFER_FULL;
524 evel_free_event(event);
529 /*************************************************************************/
530 /* System is not in active operation, so reject the event. */
531 /*************************************************************************/
532 log_error_state("Event Handler system not active - event dropped!");
533 rc = EVEL_EVENT_HANDLER_INACTIVE;
534 evel_free_event(event);
541 /**************************************************************************//**
542 * Post an event to the Vendor Event Listener API.
544 * @returns Status code
545 * @retval EVEL_SUCCESS On success
546 * @retval "One of ::EVEL_ERR_CODES" On failure.
547 *****************************************************************************/
548 static EVEL_ERR_CODES evel_post_api(char * msg, size_t size)
550 int rc = EVEL_SUCCESS;
551 CURLcode curl_rc = CURLE_OK;
552 MEMORY_CHUNK rx_chunk;
553 MEMORY_CHUNK tx_chunk;
554 int http_response_code = 0;
558 /***************************************************************************/
559 /* Create the memory chunk to be used for the response to the post. The */
560 /* will be realloced. */
561 /***************************************************************************/
562 rx_chunk.memory = malloc(1);
563 assert(rx_chunk.memory != NULL);
566 /***************************************************************************/
567 /* Create the memory chunk to be sent as the body of the post. */
568 /***************************************************************************/
569 tx_chunk.memory = msg;
570 tx_chunk.size = size;
571 EVEL_DEBUG("Sending chunk of size %d", tx_chunk.size);
573 /***************************************************************************/
574 /* Point to the data to be received. */
575 /***************************************************************************/
576 curl_rc = curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, &rx_chunk);
577 if (curl_rc != CURLE_OK)
579 rc = EVEL_CURL_LIBRARY_FAIL;
580 log_error_state("Failed to initialize libCURL to upload. "
581 "Error code=%d (%s)", curl_rc, curl_err_string);
584 EVEL_DEBUG("Initialized data to receive");
586 /***************************************************************************/
587 /* Pointer to pass to our read function */
588 /***************************************************************************/
589 curl_rc = curl_easy_setopt(curl_handle, CURLOPT_READDATA, &tx_chunk);
590 if (curl_rc != CURLE_OK)
592 rc = EVEL_CURL_LIBRARY_FAIL;
593 log_error_state("Failed to set upload data for libCURL to upload. "
594 "Error code=%d (%s)", curl_rc, curl_err_string);
597 EVEL_DEBUG("Initialized data to send");
599 /***************************************************************************/
600 /* Size of the data to transmit. */
601 /***************************************************************************/
602 curl_rc = curl_easy_setopt(curl_handle,
603 CURLOPT_POSTFIELDSIZE,
605 if (curl_rc != CURLE_OK)
607 rc = EVEL_CURL_LIBRARY_FAIL;
608 log_error_state("Failed to set length of upload data for libCURL to "
609 "upload. Error code=%d (%s)", curl_rc, curl_err_string);
612 EVEL_DEBUG("Initialized length of data to send");
614 /***************************************************************************/
615 /* Now run off and do what you've been told! */
616 /***************************************************************************/
617 curl_rc = curl_easy_perform(curl_handle);
618 if (curl_rc != CURLE_OK)
620 rc = EVEL_CURL_LIBRARY_FAIL;
621 log_error_state("Failed to transfer an event to Vendor Event Listener! "
622 "Error code=%d (%s)", curl_rc, curl_err_string);
623 EVEL_ERROR("Dropped event: %s", msg);
627 /***************************************************************************/
628 /* See what response we got - any 2XX response is good. */
629 /***************************************************************************/
630 curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &http_response_code);
631 EVEL_DEBUG("HTTP response code: %d", http_response_code);
632 if ((http_response_code / 100) == 2)
634 /*************************************************************************/
635 /* If the server responded with data it may be interesting but not a */
637 /*************************************************************************/
638 if ((rx_chunk.size > 0) && (rx_chunk.memory != NULL))
640 EVEL_DEBUG("Server returned data = %d (%s)",
644 /***********************************************************************/
645 /* If this is a response to priority post, then we're not interested. */
646 /***********************************************************************/
647 if (priority_post.memory != NULL)
649 EVEL_ERROR("Ignoring priority post response");
653 evel_handle_event_response(&rx_chunk, &priority_post);
659 EVEL_ERROR("Unexpected HTTP response code: %d with data size %d (%s)",
662 rx_chunk.size > 0 ? rx_chunk.memory : "NONE");
663 EVEL_ERROR("Potentially dropped event: %s", msg);
667 free(rx_chunk.memory);
672 /**************************************************************************//**
673 * Callback function to provide data to send.
675 * Copy data into the supplied buffer, read_callback::ptr, checking size
678 * @returns Number of bytes placed into read_callback::ptr. 0 for EOF.
679 *****************************************************************************/
680 static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *userp)
683 size_t bytes_to_write = 0;
684 MEMORY_CHUNK *tx_chunk = (MEMORY_CHUNK *)userp;
688 bytes_to_write = min(size*nmemb, tx_chunk->size);
690 if (bytes_to_write > 0)
692 EVEL_DEBUG("Going to try to write %d bytes", bytes_to_write);
693 strncpy((char *)ptr, tx_chunk->memory, bytes_to_write);
694 tx_chunk->memory += bytes_to_write;
695 tx_chunk->size -= bytes_to_write;
696 rtn = bytes_to_write;
700 EVEL_DEBUG("Reached EOF");
707 /**************************************************************************//**
708 * Callback function to provide returned data.
710 * Copy data into the supplied buffer, write_callback::ptr, checking size
713 * @returns Number of bytes placed into write_callback::ptr. 0 for EOF.
714 *****************************************************************************/
715 size_t evel_write_callback(void *contents,
720 size_t realsize = size * nmemb;
721 MEMORY_CHUNK * rx_chunk = (MEMORY_CHUNK *)userp;
725 EVEL_DEBUG("Called with %d chunks of %d size = %d", nmemb, size, realsize);
726 EVEL_DEBUG("rx chunk size is %d", rx_chunk->size);
728 rx_chunk->memory = realloc(rx_chunk->memory, rx_chunk->size + realsize + 1);
729 if(rx_chunk->memory == NULL) {
731 printf("not enough memory (realloc returned NULL)\n");
735 memcpy(&(rx_chunk->memory[rx_chunk->size]), contents, realsize);
736 rx_chunk->size += realsize;
737 rx_chunk->memory[rx_chunk->size] = 0;
739 EVEL_DEBUG("Rx data: %s", rx_chunk->memory);
740 EVEL_DEBUG("Returning: %d", realsize);
746 /**************************************************************************//**
749 * Watch for messages coming on the internal queue and send them to the
752 * param[in] arg Argument - unused.
753 *****************************************************************************/
754 static void * event_handler(void * arg __attribute__ ((unused)))
757 EVENT_HEADER * msg = NULL;
758 EVENT_INTERNAL * internal_msg = NULL;
760 char json_body[EVEL_MAX_JSON_BODY];
761 int rc = EVEL_SUCCESS;
764 EVEL_INFO("Event handler thread started");
766 /***************************************************************************/
767 /* Set this thread to be cancellable immediately. */
768 /***************************************************************************/
769 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &old_type);
771 /***************************************************************************/
772 /* Set the handler as active, defending against weird situations like */
773 /* immediately shutting down after initializing the library so the */
774 /* handler never gets started up properly. */
775 /***************************************************************************/
776 if (evt_handler_state == EVT_HANDLER_INACTIVE)
778 evt_handler_state = EVT_HANDLER_ACTIVE;
782 EVEL_ERROR("Event Handler State was not INACTIVE at start-up - "
783 "Handler will exit immediately!");
786 while (evt_handler_state == EVT_HANDLER_ACTIVE)
788 /*************************************************************************/
789 /* Wait for a message to be received. */
790 /*************************************************************************/
791 EVEL_DEBUG("Event handler getting any messages");
792 msg = ring_buffer_read(&event_buffer);
794 /*************************************************************************/
795 /* Internal events get special treatment while regular events get posted */
796 /* to the far side. */
797 /*************************************************************************/
798 if (msg->event_domain == EVEL_DOMAIN_BATCH )
800 EVEL_DEBUG("Batch event received");
802 /***********************************************************************/
803 /* Encode the event in JSON. */
804 /***********************************************************************/
805 json_size = evel_json_encode_batch_event(json_body, EVEL_MAX_JSON_BODY, msg);
807 /***************************************************************************/
808 /* Set the URL for the API. */
809 /***************************************************************************/
810 curl_rc = curl_easy_setopt(curl_handle, CURLOPT_URL, evel_batch_api_url);
811 if (curl_rc != CURLE_OK)
813 rc = EVEL_CURL_LIBRARY_FAIL;
814 log_error_state("Failed to initialize libCURL with the Batch API URL. "
815 "Error code=%d (%s)", curl_rc, curl_err_string);
818 /***********************************************************************/
819 /* Send the JSON across the API. */
820 /***********************************************************************/
821 EVEL_DEBUG("Sending Batch JSON of size %d is: %s", json_size, json_body);
822 rc = evel_post_api(json_body, json_size);
823 if (rc != EVEL_SUCCESS)
825 EVEL_ERROR("Failed to transfer the data. Error code=%d", rc);
828 else if (msg->event_domain != EVEL_DOMAIN_INTERNAL )
830 EVEL_DEBUG("External event received");
832 /***********************************************************************/
833 /* Encode the event in JSON. */
834 /***********************************************************************/
835 json_size = evel_json_encode_event(json_body, EVEL_MAX_JSON_BODY, msg);
837 /***************************************************************************/
838 /* Set the URL for the API. */
839 /***************************************************************************/
840 curl_rc = curl_easy_setopt(curl_handle, CURLOPT_URL, evel_event_api_url);
841 if (curl_rc != CURLE_OK)
843 rc = EVEL_CURL_LIBRARY_FAIL;
844 log_error_state("Failed to initialize libCURL with the API URL. "
845 "Error code=%d (%s)", curl_rc, curl_err_string);
848 /***********************************************************************/
849 /* Send the JSON across the API. */
850 /***********************************************************************/
851 EVEL_DEBUG("Sending JSON of size %d is: %s", json_size, json_body);
852 rc = evel_post_api(json_body, json_size);
853 if (rc != EVEL_SUCCESS)
855 EVEL_ERROR("Failed to transfer the data. Error code=%d", rc);
860 EVEL_DEBUG("Internal event received");
861 internal_msg = (EVENT_INTERNAL *) msg;
862 assert(internal_msg->command == EVT_CMD_TERMINATE);
863 evt_handler_state = EVT_HANDLER_TERMINATING;
866 /*************************************************************************/
867 /* We are responsible for freeing the memory. */
868 /*************************************************************************/
869 evel_free_event(msg);
872 /*************************************************************************/
873 /* There may be a single priority post to be sent. */
874 /*************************************************************************/
875 if (priority_post.memory != NULL)
877 EVEL_DEBUG("Priority Post");
879 /***********************************************************************/
880 /* Set the URL for the throttling API. */
881 /***********************************************************************/
882 curl_rc = curl_easy_setopt(curl_handle, CURLOPT_URL, evel_throt_api_url);
883 if (curl_rc != CURLE_OK)
885 /*********************************************************************/
886 /* This is only likely to happen with CURLE_OUT_OF_MEMORY, in which */
887 /* case we carry on regardless. */
888 /*********************************************************************/
889 EVEL_ERROR("Failed to set throttling URL. Error code=%d", rc);
893 rc = evel_post_api(priority_post.memory, priority_post.size);
894 if (rc != EVEL_SUCCESS)
896 EVEL_ERROR("Failed to transfer priority post. Error code=%d", rc);
900 /***********************************************************************/
901 /* Reinstate the URL for the event API. */
902 /***********************************************************************/
903 curl_rc = curl_easy_setopt(curl_handle, CURLOPT_URL, evel_event_api_url);
904 if (curl_rc != CURLE_OK)
906 /*********************************************************************/
907 /* This is only likely to happen with CURLE_OUT_OF_MEMORY, in which */
908 /* case we carry on regardless. */
909 /*********************************************************************/
910 EVEL_ERROR("Failed to reinstate events URL. Error code=%d", rc);
913 /***********************************************************************/
914 /* We are responsible for freeing the memory. */
915 /***********************************************************************/
916 free(priority_post.memory);
917 priority_post.memory = NULL;
921 /***************************************************************************/
922 /* The event handler is now exiting. The ring-buffer could contain events */
923 /* which have not been processed, so deplete those. Because we've been */
924 /* asked to exit we can be confident that the foreground will have stopped */
925 /* sending events in so we know that this process will conclude! */
926 /***************************************************************************/
927 evt_handler_state = EVT_HANDLER_TERMINATING;
928 while (!ring_buffer_is_empty(&event_buffer))
930 EVEL_DEBUG("Reading event from buffer");
931 msg = ring_buffer_read(&event_buffer);
932 evel_free_event(msg);
934 evt_handler_state = EVT_HANDLER_TERMINATED;
935 EVEL_INFO("Event handler thread stopped");
940 /**************************************************************************//**
941 * Handle a JSON response from the listener, contained in a ::MEMORY_CHUNK.
943 * Tokenize the response, and decode any tokens found.
945 * @param chunk The memory chunk containing the response.
946 * @param post The memory chunk in which to place any resulting POST.
947 *****************************************************************************/
948 void evel_handle_event_response(const MEMORY_CHUNK * const chunk,
949 MEMORY_CHUNK * const post)
951 jsmn_parser json_parser;
952 jsmntok_t json_tokens[EVEL_MAX_RESPONSE_TOKENS];
957 /***************************************************************************/
958 /* Check preconditions. */
959 /***************************************************************************/
960 assert(chunk != NULL);
961 assert(priority_post.memory == NULL);
963 EVEL_DEBUG("Response size = %d", chunk->size);
964 EVEL_DEBUG("Response = %s", chunk->memory);
966 /***************************************************************************/
967 /* Initialize the parser and tokenize the response. */
968 /***************************************************************************/
969 jsmn_init(&json_parser);
970 num_tokens = jsmn_parse(&json_parser,
974 EVEL_MAX_RESPONSE_TOKENS);
978 EVEL_ERROR("Failed to parse JSON response. "
979 "Error code=%d", num_tokens);
981 else if (num_tokens == 0)
983 EVEL_DEBUG("No tokens found in JSON response");
987 EVEL_DEBUG("Decode JSON response tokens");
988 if (!evel_handle_response_tokens(chunk, json_tokens, num_tokens, post))
990 EVEL_ERROR("Failed to handle JSON response.");
997 /**************************************************************************//**
998 * Handle a JSON response from the listener, as a list of tokens from JSMN.
1000 * @param chunk Memory chunk containing the JSON buffer.
1001 * @param json_tokens Array of tokens to handle.
1002 * @param num_tokens The number of tokens to handle.
1003 * @param post The memory chunk in which to place any resulting POST.
1004 * @return true if we handled the response, false otherwise.
1005 *****************************************************************************/
1006 bool evel_handle_response_tokens(const MEMORY_CHUNK * const chunk,
1007 const jsmntok_t * const json_tokens,
1008 const int num_tokens,
1009 MEMORY_CHUNK * const post)
1011 bool json_ok = false;
1015 /***************************************************************************/
1016 /* Check preconditions. */
1017 /***************************************************************************/
1018 assert(chunk != NULL);
1019 assert(json_tokens != NULL);
1020 assert(num_tokens < EVEL_MAX_RESPONSE_TOKENS);
1022 /***************************************************************************/
1023 /* Peek at the tokens to decide what the response it, then call the */
1024 /* appropriate handler to handle it. There is only one handler at this */
1026 /***************************************************************************/
1027 if (evel_tokens_match_command_list(chunk, json_tokens, num_tokens))
1029 json_ok = evel_handle_command_list(chunk, json_tokens, num_tokens, post);
1037 /**************************************************************************//**
1038 * Determine whether a list of tokens looks like a "commandList" response.
1040 * @param chunk Memory chunk containing the JSON buffer.
1041 * @param json_tokens Token to check.
1042 * @param num_tokens The number of tokens to handle.
1043 * @return true if the tokens look like a "commandList" match, or false.
1044 *****************************************************************************/
1045 bool evel_tokens_match_command_list(const MEMORY_CHUNK * const chunk,
1046 const jsmntok_t * const json_tokens,
1047 const int num_tokens)
1049 bool result = false;
1053 /***************************************************************************/
1054 /* Make some checks on the basic layout of the commandList. */
1055 /***************************************************************************/
1056 if ((num_tokens > 3) &&
1057 (json_tokens[0].type == JSMN_OBJECT) &&
1058 (json_tokens[1].type == JSMN_STRING) &&
1059 (json_tokens[2].type == JSMN_ARRAY) &&
1060 (evel_token_equals_string(chunk, &json_tokens[1], "commandList")))
1070 /**************************************************************************//**
1071 * Check that a string token matches a given input string.
1073 * @param chunk Memory chunk containing the JSON buffer.
1074 * @param json_token Token to check.
1075 * @param check_string String to check it against.
1076 * @return true if the strings match, or false.
1077 *****************************************************************************/
1078 bool evel_token_equals_string(const MEMORY_CHUNK * const chunk,
1079 const jsmntok_t * json_token,
1080 const char * check_string)
1082 bool result = false;
1086 const int token_length = json_token->end - json_token->start;
1087 const char * const token_string = chunk->memory + json_token->start;
1089 if (token_length == (int)strlen(check_string))
1091 result = (strncmp(token_string, check_string, token_length) == 0);