Implement batching of VES events
[demo.git] / vnfs / VES5.0 / evel / evel-library / code / evel_library / evel_event_mgr.c
1 /*************************************************************************//**
2  *
3  * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
4  *
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
10  *
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  ****************************************************************************/
18
19 /**************************************************************************//**
20  * @file
21  * Event Manager
22  *
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.
25  *
26  ****************************************************************************/
27
28 #include <string.h>
29 #include <assert.h>
30 #include <stdlib.h>
31 #include <pthread.h>
32
33 #include <curl/curl.h>
34
35 #include "evel.h"
36 #include "evel_internal.h"
37 #include "ring_buffer.h"
38 #include "evel_throttle.h"
39
40 /**************************************************************************//**
41  * How long we're prepared to wait for the API service to respond in
42  * seconds.
43  *****************************************************************************/
44 static const int EVEL_API_TIMEOUT = 5;
45
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,
53                                         const int num_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);
61
62 /**************************************************************************//**
63  * Buffers for error strings from libcurl.
64  *****************************************************************************/
65 static char curl_err_string[CURL_ERROR_SIZE] = "<NULL>";
66
67 /**************************************************************************//**
68  * Handle for the API into libcurl.
69  *****************************************************************************/
70 static CURL * curl_handle = NULL;
71
72 /**************************************************************************//**
73  * Special headers that we send.
74  *****************************************************************************/
75 static struct curl_slist * hdr_chunk = NULL;
76
77 /**************************************************************************//**
78  * Message queue for sending events to the API.
79  *****************************************************************************/
80 static ring_buffer event_buffer;
81
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;
87
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;
93
94 /**************************************************************************//**
95  * Variable to convey to the event handler thread what the foreground wants it
96  * to do.
97  *****************************************************************************/
98 static EVT_HANDLER_STATE evt_handler_state = EVT_HANDLER_UNINITIALIZED;
99
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;
106
107 /**************************************************************************//**
108  * Initialize the event handler.
109  *
110  * Primarily responsible for getting CURL ready for use.
111  *
112  * @param[in] event_api_url
113  *                      The URL where the Vendor Event Listener API is expected
114  *                      to be.
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
120  *                        logs.
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,
126                                         int verbosity)
127 {
128   int rc = EVEL_SUCCESS;
129   CURLcode curl_rc = CURLE_OK;
130   char batch_api_url[EVEL_MAX_URL_LEN + 1] = {0};
131
132   EVEL_ENTER();
133
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);
141
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);
152
153
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);
159   }
160   else {
161      EVEL_INFO("Old Curl version.");
162   }
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)
170   {
171     rc = EVEL_CURL_LIBRARY_FAIL;
172     log_error_state("Failed to initialize libCURL. Error code=%d", curl_rc);
173     goto exit_label;
174   }
175
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)
181   {
182     rc = EVEL_CURL_LIBRARY_FAIL;
183     log_error_state("Failed to get libCURL handle");
184     goto exit_label;
185   }
186
187   /***************************************************************************/
188   /* Prime the library to give friendly error codes.                         */
189   /***************************************************************************/
190   curl_rc = curl_easy_setopt(curl_handle,
191                              CURLOPT_ERRORBUFFER,
192                              curl_err_string);
193   if (curl_rc != CURLE_OK)
194   {
195     rc = EVEL_CURL_LIBRARY_FAIL;
196     log_error_state("Failed to initialize libCURL to provide friendly errors. "
197                     "Error code=%d", curl_rc);
198     goto exit_label;
199   }
200
201   /***************************************************************************/
202   /* If running in verbose mode generate more output.                        */
203   /***************************************************************************/
204   if (verbosity > 0)
205   {
206     curl_rc = curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1L);
207     if (curl_rc != CURLE_OK)
208     {
209       rc = EVEL_CURL_LIBRARY_FAIL;
210       log_error_state("Failed to initialize libCURL to be verbose. "
211                       "Error code=%d", curl_rc);
212       goto exit_label;
213     }
214   }
215
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)
221   {
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);
225     goto exit_label;
226   }
227   EVEL_INFO("Initializing CURL to send events to: %s", event_api_url);
228
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)
236   {
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);
240     goto exit_label;
241   }
242
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,
248                              CURLOPT_USERAGENT,
249                              "libcurl-agent/1.0");
250   if (curl_rc != CURLE_OK)
251   {
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);
255     goto exit_label;
256   }
257
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)
263   {
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);
267     goto exit_label;
268   }
269
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)
275   {
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);
279     goto exit_label;
280   }
281
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.                                                  */
286   /*                                                                         */
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:");
291
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)
297   {
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);
301     goto exit_label;
302   }
303
304   /***************************************************************************/
305   /* Set the timeout for the operation.                                      */
306   /***************************************************************************/
307   curl_rc = curl_easy_setopt(curl_handle,
308                              CURLOPT_TIMEOUT,
309                              EVEL_API_TIMEOUT);
310   if (curl_rc != CURLE_OK)
311   {
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);
315     goto exit_label;
316   }
317
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)
324   {
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);
328     goto exit_label;
329   }
330   curl_rc = curl_easy_setopt(curl_handle, CURLOPT_USERNAME, username);
331   if (curl_rc != CURLE_OK)
332   {
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);
336     goto exit_label;
337   }
338   curl_rc = curl_easy_setopt(curl_handle, CURLOPT_PASSWORD, password);
339   if (curl_rc != CURLE_OK)
340   {
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);
344     goto exit_label;
345   }
346
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);
352
353   /***************************************************************************/
354   /* Initialize the priority post buffer to empty.                           */
355   /***************************************************************************/
356   priority_post.memory = NULL;
357
358 exit_label:
359   EVEL_EXIT();
360
361   return(rc);
362 }
363
364 /**************************************************************************//**
365  * Run the event handler.
366  *
367  * Spawns the thread responsible for handling events and sending them to the
368  * API.
369  *
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()
375 {
376   EVEL_ERR_CODES rc = EVEL_SUCCESS;
377   int pthread_rc = 0;
378
379   EVEL_ENTER();
380
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);
386   if (pthread_rc != 0)
387   {
388     rc = EVEL_PTHREAD_LIBRARY_FAIL;
389     log_error_state("Failed to start event handler thread. "
390                     "Error code=%d", pthread_rc);
391   }
392
393   EVEL_EXIT()
394   return rc;
395 }
396
397 /**************************************************************************//**
398  * Terminate the event handler.
399  *
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.
403  *
404  * Having achieved an orderly shutdown of the event handler thread, clean up
405  * the cURL library's resources cleanly.
406  *
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()
412 {
413   EVEL_ERR_CODES rc = EVEL_SUCCESS;
414
415   EVEL_ENTER();
416   EVENT_INTERNAL *event = NULL;
417
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)
423   {
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");
428     if (event == NULL)
429     {
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   */
433       /* anyway.                                                             */
434       /***********************************************************************/
435       EVEL_ERROR("Failed to get internal event - perform dirty exit instead!");
436     }
437     else
438     {
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.");
448     }
449   }
450   else
451   {
452     EVEL_DEBUG("Event handler was not initialized, so no need to kill it");
453   }
454
455   /***************************************************************************/
456   /* Clean-up the cURL library.                                              */
457   /***************************************************************************/
458   if (curl_handle != NULL)
459   {
460     curl_easy_cleanup(curl_handle);
461     curl_handle = NULL;
462   }
463   if (hdr_chunk != NULL)
464   {
465     curl_slist_free_all(hdr_chunk);
466     hdr_chunk = NULL;
467   }
468
469   /***************************************************************************/
470   /* Free off the stored API URL strings.                                    */
471   /***************************************************************************/
472   if (evel_event_api_url != NULL)
473   {
474     free(evel_event_api_url);
475     evel_event_api_url = NULL;
476   }
477   if (evel_throt_api_url != NULL)
478   {
479     free(evel_throt_api_url);
480     evel_throt_api_url = NULL;
481   }
482
483   EVEL_EXIT();
484   return rc;
485 }
486
487 /**************************************************************************//**
488  * Post an event.
489  *
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.
493
494  * @param event   The event to be posted.
495  *
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)
501 {
502   int rc = EVEL_SUCCESS;
503
504   EVEL_ENTER();
505
506   /***************************************************************************/
507   /* Check preconditions.                                                    */
508   /***************************************************************************/
509   assert(event != NULL);
510
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))
519   {
520     if (ring_buffer_write(&event_buffer, event) == 0)
521     {
522       log_error_state("Failed to write event to buffer - event dropped!");
523       rc = EVEL_EVENT_BUFFER_FULL;
524       evel_free_event(event);
525     }
526   }
527   else
528   {
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);
535   }
536
537   EVEL_EXIT();
538   return (rc);
539 }
540
541 /**************************************************************************//**
542  * Post an event to the Vendor Event Listener API.
543  *
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)
549 {
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;
555
556   EVEL_ENTER();
557
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);
564   rx_chunk.size = 0;
565
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);
572
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)
578   {
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);
582     goto exit_label;
583   }
584   EVEL_DEBUG("Initialized data to receive");
585
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)
591   {
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);
595     goto exit_label;
596   }
597   EVEL_DEBUG("Initialized data to send");
598
599   /***************************************************************************/
600   /* Size of the data to transmit.                                           */
601   /***************************************************************************/
602   curl_rc = curl_easy_setopt(curl_handle,
603                              CURLOPT_POSTFIELDSIZE,
604                              tx_chunk.size);
605   if (curl_rc != CURLE_OK)
606   {
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);
610     goto exit_label;
611   }
612   EVEL_DEBUG("Initialized length of data to send");
613
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)
619   {
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);
624     goto exit_label;
625   }
626
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)
633   {
634     /*************************************************************************/
635     /* If the server responded with data it may be interesting but not a     */
636     /* problem.                                                              */
637     /*************************************************************************/
638     if ((rx_chunk.size > 0) && (rx_chunk.memory != NULL))
639     {
640       EVEL_DEBUG("Server returned data = %d (%s)",
641                  rx_chunk.size,
642                  rx_chunk.memory);
643
644       /***********************************************************************/
645       /* If this is a response to priority post, then we're not interested.  */
646       /***********************************************************************/
647       if (priority_post.memory != NULL)
648       {
649         EVEL_ERROR("Ignoring priority post response");
650       }
651       else
652       {
653         evel_handle_event_response(&rx_chunk, &priority_post);
654       }
655     }
656   }
657   else
658   {
659     EVEL_ERROR("Unexpected HTTP response code: %d with data size %d (%s)",
660                 http_response_code,
661                 rx_chunk.size,
662                 rx_chunk.size > 0 ? rx_chunk.memory : "NONE");
663     EVEL_ERROR("Potentially dropped event: %s", msg);
664   }
665
666 exit_label:
667   free(rx_chunk.memory);
668   EVEL_EXIT();
669   return(rc);
670 }
671
672 /**************************************************************************//**
673  * Callback function to provide data to send.
674  *
675  * Copy data into the supplied buffer, read_callback::ptr, checking size
676  * limits.
677  *
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)
681 {
682   size_t rtn = 0;
683   size_t bytes_to_write = 0;
684   MEMORY_CHUNK *tx_chunk = (MEMORY_CHUNK *)userp;
685
686   EVEL_ENTER();
687
688   bytes_to_write = min(size*nmemb, tx_chunk->size);
689
690   if (bytes_to_write > 0)
691   {
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;
697   }
698   else
699   {
700     EVEL_DEBUG("Reached EOF");
701   }
702
703   EVEL_EXIT();
704   return rtn;
705 }
706
707 /**************************************************************************//**
708  * Callback function to provide returned data.
709  *
710  * Copy data into the supplied buffer, write_callback::ptr, checking size
711  * limits.
712  *
713  * @returns   Number of bytes placed into write_callback::ptr. 0 for EOF.
714  *****************************************************************************/
715 size_t evel_write_callback(void *contents,
716                              size_t size,
717                              size_t nmemb,
718                              void *userp)
719 {
720   size_t realsize = size * nmemb;
721   MEMORY_CHUNK * rx_chunk = (MEMORY_CHUNK *)userp;
722
723   EVEL_ENTER();
724
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);
727
728   rx_chunk->memory = realloc(rx_chunk->memory, rx_chunk->size + realsize + 1);
729   if(rx_chunk->memory == NULL) {
730     /* out of memory! */
731     printf("not enough memory (realloc returned NULL)\n");
732     return 0;
733   }
734
735   memcpy(&(rx_chunk->memory[rx_chunk->size]), contents, realsize);
736   rx_chunk->size += realsize;
737   rx_chunk->memory[rx_chunk->size] = 0;
738
739   EVEL_DEBUG("Rx data: %s", rx_chunk->memory);
740   EVEL_DEBUG("Returning: %d", realsize);
741
742   EVEL_EXIT();
743   return realsize;
744 }
745
746 /**************************************************************************//**
747  * Event Handler.
748  *
749  * Watch for messages coming on the internal queue and send them to the
750  * listener.
751  *
752  * param[in]  arg  Argument - unused.
753  *****************************************************************************/
754 static void * event_handler(void * arg __attribute__ ((unused)))
755 {
756   int old_type = 0;
757   EVENT_HEADER * msg = NULL;
758   EVENT_INTERNAL * internal_msg = NULL;
759   int json_size = 0;
760   char json_body[EVEL_MAX_JSON_BODY];
761   int rc = EVEL_SUCCESS;
762   CURLcode curl_rc;
763
764   EVEL_INFO("Event handler thread started");
765
766   /***************************************************************************/
767   /* Set this thread to be cancellable immediately.                          */
768   /***************************************************************************/
769   pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &old_type);
770
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)
777   {
778     evt_handler_state = EVT_HANDLER_ACTIVE;
779   }
780   else
781   {
782     EVEL_ERROR("Event Handler State was not INACTIVE at start-up - "
783                "Handler will exit immediately!");
784   }
785
786   while (evt_handler_state == EVT_HANDLER_ACTIVE)
787   {
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);
793
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 )
799     {
800       EVEL_DEBUG("Batch event received");
801
802       /***********************************************************************/
803       /* Encode the event in JSON.                                           */
804       /***********************************************************************/
805       json_size = evel_json_encode_batch_event(json_body, EVEL_MAX_JSON_BODY, msg);
806
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)
812       {
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);
816       }
817
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)
824       {
825         EVEL_ERROR("Failed to transfer the data. Error code=%d", rc);
826       }
827     }
828     else if (msg->event_domain != EVEL_DOMAIN_INTERNAL )
829     {
830       EVEL_DEBUG("External event received");
831
832       /***********************************************************************/
833       /* Encode the event in JSON.                                           */
834       /***********************************************************************/
835       json_size = evel_json_encode_event(json_body, EVEL_MAX_JSON_BODY, msg);
836
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)
842       {
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);
846       }
847
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)
854       {
855         EVEL_ERROR("Failed to transfer the data. Error code=%d", rc);
856       }
857     }
858     else
859     {
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;
864     }
865
866     /*************************************************************************/
867     /* We are responsible for freeing the memory.                            */
868     /*************************************************************************/
869     evel_free_event(msg);
870     msg = NULL;
871
872     /*************************************************************************/
873     /* There may be a single priority post to be sent.                       */
874     /*************************************************************************/
875     if (priority_post.memory != NULL)
876     {
877       EVEL_DEBUG("Priority Post");
878
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)
884       {
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);
890       }
891       else
892       {
893         rc = evel_post_api(priority_post.memory, priority_post.size);
894         if (rc != EVEL_SUCCESS)
895         {
896           EVEL_ERROR("Failed to transfer priority post. Error code=%d", rc);
897         }
898       }
899
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)
905       {
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);
911       }
912
913       /***********************************************************************/
914       /* We are responsible for freeing the memory.                          */
915       /***********************************************************************/
916       free(priority_post.memory);
917       priority_post.memory = NULL;
918     }
919   }
920
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))
929   {
930     EVEL_DEBUG("Reading event from buffer");
931     msg = ring_buffer_read(&event_buffer);
932     evel_free_event(msg);
933   }
934   evt_handler_state = EVT_HANDLER_TERMINATED;
935   EVEL_INFO("Event handler thread stopped");
936
937   return (NULL);
938 }
939
940 /**************************************************************************//**
941  * Handle a JSON response from the listener, contained in a ::MEMORY_CHUNK.
942  *
943  * Tokenize the response, and decode any tokens found.
944  *
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)
950 {
951   jsmn_parser json_parser;
952   jsmntok_t json_tokens[EVEL_MAX_RESPONSE_TOKENS];
953   int num_tokens = 0;
954
955   EVEL_ENTER();
956
957   /***************************************************************************/
958   /* Check preconditions.                                                    */
959   /***************************************************************************/
960   assert(chunk != NULL);
961   assert(priority_post.memory == NULL);
962
963   EVEL_DEBUG("Response size = %d", chunk->size);
964   EVEL_DEBUG("Response = %s", chunk->memory);
965
966   /***************************************************************************/
967   /* Initialize the parser and tokenize the response.                        */
968   /***************************************************************************/
969   jsmn_init(&json_parser);
970   num_tokens = jsmn_parse(&json_parser,
971                           chunk->memory,
972                           chunk->size,
973                           json_tokens,
974                           EVEL_MAX_RESPONSE_TOKENS);
975
976   if (num_tokens < 0)
977   {
978     EVEL_ERROR("Failed to parse JSON response.  "
979                "Error code=%d", num_tokens);
980   }
981   else if (num_tokens == 0)
982   {
983     EVEL_DEBUG("No tokens found in JSON response");
984   }
985   else
986   {
987     EVEL_DEBUG("Decode JSON response tokens");
988     if (!evel_handle_response_tokens(chunk, json_tokens, num_tokens, post))
989     {
990       EVEL_ERROR("Failed to handle JSON response.");
991     }
992   }
993
994   EVEL_EXIT();
995 }
996
997 /**************************************************************************//**
998  * Handle a JSON response from the listener, as a list of tokens from JSMN.
999  *
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)
1010 {
1011   bool json_ok = false;
1012
1013   EVEL_ENTER();
1014
1015   /***************************************************************************/
1016   /* Check preconditions.                                                    */
1017   /***************************************************************************/
1018   assert(chunk != NULL);
1019   assert(json_tokens != NULL);
1020   assert(num_tokens < EVEL_MAX_RESPONSE_TOKENS);
1021
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    */
1025   /* point.                                                                  */
1026   /***************************************************************************/
1027   if (evel_tokens_match_command_list(chunk, json_tokens, num_tokens))
1028   {
1029     json_ok = evel_handle_command_list(chunk, json_tokens, num_tokens, post);
1030   }
1031
1032   EVEL_EXIT();
1033
1034   return json_ok;
1035 }
1036
1037 /**************************************************************************//**
1038  * Determine whether a list of tokens looks like a "commandList" response.
1039  *
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)
1048 {
1049   bool result = false;
1050
1051   EVEL_ENTER();
1052
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")))
1061   {
1062     result = true;
1063   }
1064
1065   EVEL_EXIT();
1066
1067   return result;
1068 }
1069
1070 /**************************************************************************//**
1071  * Check that a string token matches a given input string.
1072  *
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)
1081 {
1082   bool result = false;
1083
1084   EVEL_ENTER();
1085
1086   const int token_length = json_token->end - json_token->start;
1087   const char * const token_string = chunk->memory + json_token->start;
1088
1089   if (token_length == (int)strlen(check_string))
1090   {
1091     result = (strncmp(token_string, check_string, token_length) == 0);
1092   }
1093
1094   EVEL_EXIT();
1095
1096   return result;
1097 }