aboutsummaryrefslogtreecommitdiffstats
path: root/vnfs/VESreporting_vFW5.0_DANOS/evel/evel-library/code/evel_library/evel_event_mgr.c
blob: cc676a6fc475b5b5d85f6fffd62474f9f9777cf0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
/*************************************************************************//**
 *
 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
 *
 * Unless otherwise specified, all software contained herein is
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 ****************************************************************************/

/**************************************************************************//**
 * @file
 * Event Manager
 *
 * Simple event manager that is responsible for taking events (Heartbeats,
 * Faults and Measurements) from the ring-buffer and posting them to the API.
 *
 ****************************************************************************/

#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <pthread.h>

#include <curl/curl.h>

#include "evel.h"
#include "evel_internal.h"
#include "ring_buffer.h"
#include "evel_throttle.h"

/**************************************************************************//**
 * How long we're prepared to wait for the API service to respond in
 * seconds.
 *****************************************************************************/
static const int EVEL_API_TIMEOUT = 5;

/**************************************************************************//**
 * Wait time if both the collectors are not responding
 *****************************************************************************/
static const int EVEL_COLLECTOR_RECONNECTION_WAIT_TIME = 120;

/*****************************************************************************/
/* Prototypes of locally scoped functions.                                   */
/*****************************************************************************/
static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *userp);
static void * event_handler(void *arg);
static bool evel_handle_response_tokens(const MEMORY_CHUNK * const chunk,
                                        const jsmntok_t * const json_tokens,
                                        const int num_tokens,
                                        MEMORY_CHUNK * const post);
static bool evel_tokens_match_command_list(const MEMORY_CHUNK * const chunk,
                                           const jsmntok_t * const json_token,
                                           const int num_tokens);
static bool evel_token_equals_string(const MEMORY_CHUNK * const chunk,
                                     const jsmntok_t * const json_token,
                                     const char * check_string);
static EVEL_ERR_CODES evel_setup_curl();
static EVEL_ERR_CODES evel_send_to_another_collector(const EVEL_EVENT_DOMAINS evel_domain, char * json_body, size_t json_size);

/**************************************************************************//**
 * Buffers for error strings from libcurl.
 *****************************************************************************/
static char curl_err_string[CURL_ERROR_SIZE] = "<NULL>";

/**************************************************************************//**
 * Handle for the API into libcurl.
 *****************************************************************************/
static CURL * curl_handle = NULL;
int curr_global_handles = 0;

/**************************************************************************//**
 * Special headers that we send.
 *****************************************************************************/
static struct curl_slist * hdr_chunk = NULL;

/**************************************************************************//**
 * Message queue for sending events to the API.
 *****************************************************************************/
static ring_buffer event_buffer;

/**************************************************************************//**
 * Single pending priority post, which can be generated as a result of a
 * response to an event.  Currently only used to respond to a commandList.
 *****************************************************************************/
static MEMORY_CHUNK priority_post;

/**************************************************************************//**
 * The thread which is responsible for handling events off of the ring-buffer
 * and posting them to the Event Handler API.
 *****************************************************************************/
static pthread_t evt_handler_thread;

/**************************************************************************//**
 * Variable to convey to the event handler thread what the foreground wants it
 * to do.
 *****************************************************************************/
static EVT_HANDLER_STATE evt_handler_state = EVT_HANDLER_UNINITIALIZED;

/**************************************************************************//**
 * The configured API URL for event and throttling.
 *****************************************************************************/
static char * evel_event_api_url;
static char * evel_throt_api_url;
static char * evel_batch_api_url;

static char * evel_bevent_api_url;
static char * evel_bthrot_api_url;
static char * evel_bbatch_api_url;

/**************************************************************************//**
 * Storage for other CURL related parameters
 *****************************************************************************/
int evel_secure = -1;
int evel_verbosity = -1;

long evel_verify_peer = 0;
long evel_verify_host = 0;

static char * evel_source_ip = NULL;
static char * evel_source_ip_bakup = NULL;
static char * evel_cert_file_path = NULL;
static char * evel_key_file_path = NULL;
static char * evel_ca_info = NULL;
static char * evel_ca_file_path = NULL;
static char * evel_username = NULL;
static char * evel_password = NULL;
static char * evel_username2 = NULL;
static char * evel_password2 = NULL;

static long http_response_code = 0;
static int evel_collector_id = 1;
/**************************************************************************//**
 * Initialize the event handler.
 *
 * Primarily responsible for getting CURL ready for use.
 *
 * @param[in] event_api_url
 *                      The URL where the Vendor Event Listener API is expected
 *                      to be.
 * @param[in] throt_api_url
 *                      The URL where the Throttling API is expected to be.
 * @param[in] source_ip  Source IP of VES Agent
 * @param[in] ring_buf_size     Initial size of ring buffer
 * @param[in] secure     Whether Using http or https
 * @param[in] cert_file_path  Path to Client Certificate file
 * @param[in] key_file_path   Path to Client key file
 * @param[in] ca_info         Path to CA info file
 * @param[in] ca_file_path    Path to CA file 
 * @param[in] verify_peer     Using peer verification or not 0 or 1
 * @param[in] verify_host     Using host verification or not 0 or 1
 * @param[in] username  The username for the Basic Authentication of requests.
 * @param[in] password  The password for the Basic Authentication of requests.
 * @param     verbosity 0 for normal operation, positive values for chattier
 *                        logs.
 *****************************************************************************/
EVEL_ERR_CODES event_handler_initialize(const char * const event_api_url,
                                        const char * const bakup_api_url,
                                        const char * const throt_api_url,
                                        const char * const source_ip,
                                        const char * const source_ip_bakup,
                                        int ring_buf_size,
                                        int secure,
                                        const char * const cert_file_path,
                                        const char * const key_file_path,
                                        const char * const ca_info,
                                        const char * const ca_file_path,
                                        long verify_peer,
                                        long verify_host,
                                        const char * const username,
                                        const char * const password,
                                        const char * const username2,
                                        const char * const password2,
                                        int verbosity)
{
  int rc = EVEL_SUCCESS;
  char batch_api_url[EVEL_MAX_URL_LEN + 1] = {0};

  EVEL_ENTER();

  /***************************************************************************/
  /* Check assumptions.                                                      */
  /***************************************************************************/
  assert(event_api_url != NULL);
  assert(throt_api_url != NULL);
  assert(username != NULL);
  assert(password != NULL);
  if( bakup_api_url != NULL )
  {
    assert(username2 != NULL);
    assert(password2 != NULL);
  }

  /***************************************************************************/
  /* Store the API URLs.                                                     */
  /***************************************************************************/
  evel_event_api_url = strdup(event_api_url);
  assert(evel_event_api_url != NULL);
  sprintf(batch_api_url,"%s/eventBatch",event_api_url);
  evel_batch_api_url = strdup(batch_api_url);
  assert(evel_batch_api_url != NULL);
  evel_throt_api_url = strdup(throt_api_url);
  assert(evel_throt_api_url != NULL);

  curr_global_handles = 1;

  if( bakup_api_url != NULL )
  {
    evel_bevent_api_url = strdup(bakup_api_url);
    assert(evel_bevent_api_url != NULL);
    sprintf(batch_api_url,"%s/eventBatch",bakup_api_url);
    evel_bbatch_api_url = strdup(batch_api_url);
    assert(evel_bbatch_api_url != NULL);
    evel_bthrot_api_url = strdup(throt_api_url);
    assert(evel_bthrot_api_url != NULL);
    curr_global_handles = 2;
  }

  /***************************************************************************/
  /* Store other parameters                                                  */
  /***************************************************************************/
  evel_secure = secure;
  evel_verbosity = verbosity;

  evel_verify_peer = verify_peer;
  evel_verify_host = verify_host;

  evel_source_ip = NULL;
  if (source_ip != NULL)
  {
    evel_source_ip = strdup(source_ip);
    assert(evel_source_ip != NULL);
  }

  evel_source_ip_bakup = NULL;
  if (source_ip_bakup != NULL)
  {
    evel_source_ip_bakup = strdup(source_ip_bakup);
    assert(evel_source_ip_bakup != NULL);
  }

  evel_cert_file_path = NULL;
  if (cert_file_path != NULL)
  {
    evel_cert_file_path = strdup(cert_file_path);
    assert(evel_cert_file_path != NULL);
  }

  evel_key_file_path = NULL;
  if (key_file_path != NULL)
  {
    evel_key_file_path = strdup(key_file_path);
    assert(evel_key_file_path != NULL);
  }

  evel_ca_info = NULL;
  if (ca_info != NULL)
  {
    evel_ca_info = strdup(ca_info);
    assert(evel_ca_info != NULL);
  }

  evel_ca_file_path = NULL;
  if (ca_file_path != NULL)
  {
    evel_ca_file_path = strdup(ca_file_path);
    assert(evel_ca_file_path != NULL);
  }

  evel_username = NULL;
  if (username != NULL)
  {
    evel_username = strdup(username);
    assert(evel_username != NULL);
  }

  evel_password = NULL;
  if (password != NULL)
  {
    evel_password = strdup(password);
    assert(evel_password != NULL);
  }

  evel_username2 = NULL;
  if (username2 != NULL)
  {
    evel_username2 = strdup(username2);
    assert(evel_username2 != NULL);
  }

  evel_password2 = NULL;
  if (password2 != NULL)
  {
    evel_password2 = strdup(password2);
    assert(evel_password2 != NULL);
  }

  curl_version_info_data *d = curl_version_info(CURLVERSION_NOW);
  /* compare with the 24 bit hex number in 8 bit fields */
  if(d->version_num >= 0x072100) {
     /* this is libcurl 7.33.0 or later */
     EVEL_INFO("7.33 or later Curl version %x.",d->version_num);
  }
  else {
     EVEL_INFO("Old Curl version.");
  }

  /***************************************************************************/
  /* Initialize a message ring-buffer to be used between the foreground and  */
  /* the thread which sends the messages.  This can't fail.                  */
  /***************************************************************************/
  if( ring_buf_size < EVEL_EVENT_BUFFER_DEPTH )
  {
    log_error_state("Warning: Failed to initialize Ring buffer size to %d. ",
                    ring_buf_size);
    goto exit_label;
  }
  ring_buffer_initialize(&event_buffer, EVEL_EVENT_BUFFER_DEPTH);

exit_label:

  EVEL_EXIT();

  return rc;

}
/**************************************************************************//**
 * Setup the curl connection to collector
 *
 * Primarily responsible for getting CURL ready to send message. Also it would
 * be used to swithch over to other collector 
 *****************************************************************************/
static EVEL_ERR_CODES evel_setup_curl()
{
  int rc = EVEL_SUCCESS;
  CURLcode curl_rc = CURLE_OK;
  char local_address[64];
  char * api_url = NULL;
  char * username = NULL;
  char * password = NULL;
  char * source_ip = NULL;

  EVEL_ENTER();

  if (evel_collector_id > 2)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Wrong evel_collector- value > 2");
    goto exit_label;
  }

  /***************************************************************************/
  /* Initialize the local variable with proper global variables that are     */
  /* required to setup the connection                                        */
  /***************************************************************************/
  if (evel_collector_id == 1)
  {
     api_url = evel_event_api_url;
     source_ip = evel_source_ip;
     username = evel_username;
     password = evel_password;
  }
  else if (evel_collector_id == 2)
  {
     api_url = evel_bevent_api_url;
     source_ip = evel_source_ip_bakup;
     username = evel_username2;
     password = evel_password2;
  }
  /***************************************************************************/
  /* Clean-up the cURL library.                                              */
  /***************************************************************************/
  if (curl_handle != NULL)
  {
    curl_easy_cleanup(curl_handle);
    curl_handle = NULL;
  }
  if (hdr_chunk != NULL)
  {
    curl_slist_free_all(hdr_chunk);
    hdr_chunk = NULL;
  }

  /***************************************************************************/
  /* Start the CURL library. Note that this initialization is not threadsafe */
  /* which imposes a constraint that the EVEL library is initialized before  */
  /* any threads are started.                                                */
  /***************************************************************************/
  curl_rc = curl_global_init(CURL_GLOBAL_SSL);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL. Error code=%d", curl_rc);
    goto exit_label;
  }

  /***************************************************************************/
  /* Get a curl handle which we'll use for all of our output.                */
  /***************************************************************************/
  curl_handle = curl_easy_init();
  if (curl_handle == NULL)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to get libCURL handle");
    goto exit_label;
  }

  /***************************************************************************/
  /* Prime the library to give friendly error codes.                         */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(curl_handle,
                             CURLOPT_ERRORBUFFER,
                             curl_err_string);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL to provide friendly errors. "
                    "Error code=%d", curl_rc);
    goto exit_label;
  }

  /***************************************************************************/
  /* If running in verbose mode generate more output.                        */
  /***************************************************************************/
  if (evel_verbosity > 0)
  {
    curl_rc = curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1L);
    if (curl_rc != CURLE_OK)
    {
      rc = EVEL_CURL_LIBRARY_FAIL;
      log_error_state("Failed to initialize libCURL to be verbose. "
                      "Error code=%d", curl_rc);
      goto exit_label;
    }
  }

  /***************************************************************************/
  /* Set the URL for the API.                                                */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(curl_handle, CURLOPT_URL, api_url);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL with the API URL. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }
  EVEL_INFO("Initializing CURL to send events to: %s", api_url);

  /***************************************************************************/
  /* send all data to this function.                                         */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(curl_handle,
                             CURLOPT_WRITEFUNCTION,
                             evel_write_callback);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL with the write callback. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }

  /***************************************************************************/
  /* configure local ip address if provided */
  /* Default ip if NULL */
  /***************************************************************************/
  if( source_ip != NULL )
  {
    snprintf(local_address,sizeof(local_address),source_ip);
    if( local_address[0] != '\0' )
    {
      curl_rc = curl_easy_setopt(curl_handle,
                             CURLOPT_INTERFACE,
                             local_address);
      if (curl_rc != CURLE_OK)
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize libCURL with the local address. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
        goto exit_label;
      }
    }
  }

  /***************************************************************************/
  /* configure SSL options for HTTPS transfers */
  /***************************************************************************/
  if( evel_secure )
  {
    if( evel_cert_file_path != NULL )
    {
      curl_rc = curl_easy_setopt(curl_handle,
                             CURLOPT_SSLCERT,
                             evel_cert_file_path);
      if (curl_rc != CURLE_OK)
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize libCURL with the client cert. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
        goto exit_label;
      }
    }

    if( evel_key_file_path != NULL )
    {
      curl_rc = curl_easy_setopt(curl_handle,
                             CURLOPT_SSLKEY,
                             evel_key_file_path);
      if (curl_rc != CURLE_OK)
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize libCURL with the client key. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
        goto exit_label;
      }
    }

    if( evel_ca_info != NULL )
    {
      curl_rc = curl_easy_setopt(curl_handle,
                             CURLOPT_CAINFO,
                             evel_ca_info);
      if (curl_rc != CURLE_OK)
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize libCURL with the CA cert file. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
        goto exit_label;
      }
    }

    if( evel_ca_file_path != NULL )
    {
      curl_rc = curl_easy_setopt(curl_handle,
                             CURLOPT_CAPATH,
                             evel_ca_file_path);
      if (curl_rc != CURLE_OK)
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize libCURL with the CA cert path. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
        goto exit_label;
      }
    }

      curl_rc = curl_easy_setopt(curl_handle,
                             CURLOPT_SSL_VERIFYPEER,
                             evel_verify_peer);
      if (curl_rc != CURLE_OK)
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize libCURL with SSL Server verification. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
        goto exit_label;
      }
      curl_rc = curl_easy_setopt(curl_handle,
                             CURLOPT_SSL_VERIFYHOST,
                             evel_verify_host);
      if (curl_rc != CURLE_OK)
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize libCURL with Client host verification. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
        goto exit_label;
      }

  }



  /***************************************************************************/
  /* some servers don't like requests that are made without a user-agent     */
  /* field, so we provide one.                                               */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(curl_handle,
                             CURLOPT_USERAGENT,
                             "libcurl-agent/1.0");
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL to upload. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }

  /***************************************************************************/
  /* Specify that we are going to POST data.                                 */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(curl_handle, CURLOPT_POST, 1L);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL to upload. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }

  /***************************************************************************/
  /* we want to use our own read function.                                   */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(curl_handle, CURLOPT_READFUNCTION, read_callback);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL to upload using read "
                    "function. Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }

  /***************************************************************************/
  /* All of our events are JSON encoded.  We also suppress the               */
  /* Expect: 100-continue   header that we would otherwise get since it      */
  /* confuses some servers.                                                  */
  /*                                                                         */
  /* @TODO: do AT&T want this behavior?                                      */
  /***************************************************************************/
  hdr_chunk = curl_slist_append(hdr_chunk, "Content-type: application/json");
  hdr_chunk = curl_slist_append(hdr_chunk, "Expect:");

  /***************************************************************************/
  /* set our custom set of headers.                                         */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, hdr_chunk);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL to use custom headers. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }

  /***************************************************************************/
  /* Set the timeout for the operation.                                      */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(curl_handle,
                             CURLOPT_TIMEOUT,
                             EVEL_API_TIMEOUT);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL for API timeout. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }

  /***************************************************************************/
  /* Set that we want Basic authentication with username:password Base-64    */
  /* encoded for the operation.                                              */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(curl_handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL for Basic Authentication. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }
  curl_rc = curl_easy_setopt(curl_handle, CURLOPT_USERNAME, username);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL with username. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }
  curl_rc = curl_easy_setopt(curl_handle, CURLOPT_PASSWORD, password);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL with password. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }

  /***************************************************************************/
  /* Initialize the priority post buffer to empty.                           */
  /***************************************************************************/
  priority_post.memory = NULL;

exit_label:
  EVEL_EXIT();

  return(rc);
}

/**************************************************************************//**
 * Run the event handler.
 *
 * Spawns the thread responsible for handling events and sending them to the
 * API.
 *
 *  @return Status code.
 *  @retval ::EVEL_SUCCESS if everything OK.
 *  @retval One of ::EVEL_ERR_CODES if there was a problem.
 *****************************************************************************/
EVEL_ERR_CODES event_handler_run()
{
  EVEL_ERR_CODES rc = EVEL_SUCCESS;
  int pthread_rc = 0;

  EVEL_ENTER();

  /***************************************************************************/
  /* Start the event handler thread.                                         */
  /***************************************************************************/
  evt_handler_state = EVT_HANDLER_INACTIVE;
  pthread_rc = pthread_create(&evt_handler_thread, NULL, event_handler, NULL);
  if (pthread_rc != 0)
  {
    rc = EVEL_PTHREAD_LIBRARY_FAIL;
    log_error_state("Failed to start event handler thread. "
                    "Error code=%d", pthread_rc);
  }

  EVEL_EXIT()
  return rc;
}

/**************************************************************************//**
 * Terminate the event handler.
 *
 * Shuts down the event handler thread in as clean a way as possible. Sets the
 * global exit flag and then signals the thread to interrupt it since it's
 * most likely waiting on the ring-buffer.
 *
 * Having achieved an orderly shutdown of the event handler thread, clean up
 * the cURL library's resources cleanly.
 *
 *  @return Status code.
 *  @retval ::EVEL_SUCCESS if everything OK.
 *  @retval One of ::EVEL_ERR_CODES if there was a problem.
 *****************************************************************************/
EVEL_ERR_CODES event_handler_terminate()
{
  EVEL_ERR_CODES rc = EVEL_SUCCESS;

  EVEL_ENTER();
  EVENT_INTERNAL *event = NULL;

  /***************************************************************************/
  /* Make sure that we were initialized before trying to terminate the       */
  /* event handler thread.                                                   */
  /***************************************************************************/
  if (evt_handler_state != EVT_HANDLER_UNINITIALIZED)
  {
    /*************************************************************************/
    /* Make sure that the event handler knows it's time to die.              */
    /*************************************************************************/
    event = evel_new_internal_event(EVT_CMD_TERMINATE,"EVELinternal","EVELid");
    if (event == NULL)
    {
      /***********************************************************************/
      /* We failed to get an event, but we don't bail out - we will just     */
      /* clean up what we can and continue on our way, since we're exiting   */
      /* anyway.                                                             */
      /***********************************************************************/
      EVEL_ERROR("Failed to get internal event - perform dirty exit instead!");
    }
    else
    {
      /***********************************************************************/
      /* Post the event then wait for the Event Handler to exit.  Set the    */
      /* global command, too, in case the ring-buffer is full.               */
      /***********************************************************************/
      EVEL_DEBUG("Sending event to Event Hander to request it to exit.");
      evt_handler_state = EVT_HANDLER_REQUEST_TERMINATE;
      evel_post_event((EVENT_HEADER *) event);
      pthread_join(evt_handler_thread, NULL);
      EVEL_DEBUG("Event Handler thread has exited.");
    }
  }
  else
  {
    EVEL_DEBUG("Event handler was not initialized, so no need to kill it");
  }

  /***************************************************************************/
  /* Clean-up the cURL library.                                              */
  /***************************************************************************/
  if (curl_handle != NULL)
  {
    curl_easy_cleanup(curl_handle);
    curl_handle = NULL;
  }
  if (hdr_chunk != NULL)
  {
    curl_slist_free_all(hdr_chunk);
    hdr_chunk = NULL;
  }

  /***************************************************************************/
  /* Free off the stored API URL strings.                                    */
  /***************************************************************************/
  if (evel_event_api_url != NULL)
  {
    free(evel_event_api_url);
    evel_event_api_url = NULL;
  }
  if (evel_batch_api_url != NULL)
  {
    free(evel_batch_api_url);
    evel_batch_api_url = NULL;
  }
  if (evel_throt_api_url != NULL)
  {
    free(evel_throt_api_url);
    evel_throt_api_url = NULL;
  }

  EVEL_EXIT();
  return rc;
}

/**************************************************************************//**
 * Post an event.
 *
 * @note  So far as the caller is concerned, successfully posting the event
 * relinquishes all responsibility for the event - the library will take care
 * of freeing the event in due course.

 * @param event   The event to be posted.
 *
 * @returns Status code
 * @retval  EVEL_SUCCESS On success
 * @retval  "One of ::EVEL_ERR_CODES" On failure.
 *****************************************************************************/
EVEL_ERR_CODES evel_post_event(EVENT_HEADER * event)
{
  int rc = EVEL_SUCCESS;

  EVEL_ENTER();

  /***************************************************************************/
  /* Check preconditions.                                                    */
  /***************************************************************************/
  assert(event != NULL);

  /***************************************************************************/
  /* We need to make sure that we are either initializing or running         */
  /* normally before writing the event into the buffer so that we can        */
  /* guarantee that the ring-buffer empties  properly on exit.               */
  /***************************************************************************/
  if ((evt_handler_state == EVT_HANDLER_ACTIVE) ||
      (evt_handler_state == EVT_HANDLER_INACTIVE) ||
      (evt_handler_state == EVT_HANDLER_REQUEST_TERMINATE))
  {
    if (ring_buffer_write(&event_buffer, event) == 0)
    {
      log_error_state("Failed to write event to buffer - event dropped!");
      rc = EVEL_EVENT_BUFFER_FULL;
      evel_free_event(event);
    }
  }
  else
  {
    /*************************************************************************/
    /* System is not in active operation, so reject the event.               */
    /*************************************************************************/
    log_error_state("Event Handler system not active - event dropped!");
    rc = EVEL_EVENT_HANDLER_INACTIVE;
    evel_free_event(event);
  }

  EVEL_EXIT();
  return (rc);
}

/**************************************************************************//**
 * Post an event to the Vendor Event Listener API.
 *
 * @returns Status code
 * @retval  EVEL_SUCCESS On success
 * @retval  "One of ::EVEL_ERR_CODES" On failure.
 *****************************************************************************/
static EVEL_ERR_CODES evel_post_api(char * msg, size_t size)
{
  int rc = EVEL_SUCCESS;
  CURLcode curl_rc = CURLE_OK;
  MEMORY_CHUNK rx_chunk;
  MEMORY_CHUNK tx_chunk;

  EVEL_ENTER();

  /***************************************************************************/
  /* Create the memory chunk to be used for the response to the post.  The   */
  /* will be realloced.                                                      */
  /***************************************************************************/
  rx_chunk.memory = malloc(1);
  assert(rx_chunk.memory != NULL);
  rx_chunk.size = 0;

  /***************************************************************************/
  /* Create the memory chunk to be sent as the body of the post.             */
  /***************************************************************************/
  tx_chunk.memory = msg;
  tx_chunk.size = size;
  EVEL_DEBUG("Sending chunk of size %d", tx_chunk.size);

  /***************************************************************************/
  /* Point to the data to be received.                                       */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, &rx_chunk);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to initialize libCURL to upload. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }
  EVEL_DEBUG("Initialized data to receive");

  /***************************************************************************/
  /* Pointer to pass to our read function                                    */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(curl_handle, CURLOPT_READDATA, &tx_chunk);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to set upload data for libCURL to upload. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }
  EVEL_DEBUG("Initialized data to send");

  /***************************************************************************/
  /* Size of the data to transmit.                                           */
  /***************************************************************************/
  curl_rc = curl_easy_setopt(curl_handle,
                             CURLOPT_POSTFIELDSIZE,
                             tx_chunk.size);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to set length of upload data for libCURL to "
                    "upload.  Error code=%d (%s)", curl_rc, curl_err_string);
    goto exit_label;
  }
  EVEL_DEBUG("Initialized length of data to send");

  /***************************************************************************/
  /* Now run off and do what you've been told!                               */
  /***************************************************************************/
  http_response_code = 0;

  curl_rc = curl_easy_perform(curl_handle);
  if (curl_rc != CURLE_OK)
  {
    rc = EVEL_CURL_LIBRARY_FAIL;
    log_error_state("Failed to transfer an event to Vendor Event Listener! "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
    EVEL_ERROR("Dropped event: %s", msg);
    goto exit_label;
  }

  /***************************************************************************/
  /* See what response we got - any 2XX response is good.                    */
  /***************************************************************************/
  curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &http_response_code);
  EVEL_DEBUG("HTTP response code: %d", http_response_code);
  if ((http_response_code / 100) == 2)
  {
    /*************************************************************************/
    /* If the server responded with data it may be interesting but not a     */
    /* problem.                                                              */
    /*************************************************************************/
    if ((rx_chunk.size > 0) && (rx_chunk.memory != NULL))
    {
      EVEL_DEBUG("Server returned data = %d (%s)",
                 rx_chunk.size,
                 rx_chunk.memory);

      /***********************************************************************/
      /* If this is a response to priority post, then we're not interested.  */
      /***********************************************************************/
      if (priority_post.memory != NULL)
      {
        EVEL_ERROR("Ignoring priority post response");
      }
      else
      {
        evel_handle_event_response(&rx_chunk, &priority_post);
      }
    }
  }
  else
  {
    EVEL_ERROR("Unexpected HTTP response code: %d with data size %d (%s)",
                http_response_code,
                rx_chunk.size,
                rx_chunk.size > 0 ? rx_chunk.memory : "NONE");
    EVEL_ERROR("Potentially dropped event: %s", msg);
  }

exit_label:
  free(rx_chunk.memory);
  EVEL_EXIT();
  return(rc);
}

/**************************************************************************//**
 * Send event to another collector
 *
 * Identify the next collector and try sending the event to that collector
 ****************************************************************************/
static EVEL_ERR_CODES evel_send_to_another_collector(
                        const EVEL_EVENT_DOMAINS evel_domain, 
                        char * json_body, 
                        size_t json_size)
{
  int rc = EVEL_SUCCESS;
  CURLcode curl_rc;

  EVEL_ENTER();

  if ((evel_collector_id == 1) && (curr_global_handles == 2))
  {
     evel_collector_id =2;
  }
  else if (evel_collector_id == 2)
  {
     evel_collector_id =1;
  }

  rc = evel_setup_curl();

  if ( rc == EVEL_SUCCESS)
  {
     if (evel_collector_id == 1)
     {
        if (evel_domain == EVEL_DOMAIN_BATCH)
           curl_rc = curl_easy_setopt(curl_handle, CURLOPT_URL, evel_batch_api_url);
        else
           curl_rc = curl_easy_setopt(curl_handle, CURLOPT_URL, evel_event_api_url);
     }
     else if (evel_collector_id == 2)
     {
        if (evel_domain == EVEL_DOMAIN_BATCH)
           curl_rc = curl_easy_setopt(curl_handle, CURLOPT_URL, evel_bbatch_api_url);
        else
           curl_rc = curl_easy_setopt(curl_handle, CURLOPT_URL, evel_bevent_api_url);
     }

     rc = evel_post_api(json_body, json_size);
  }

  EVEL_EXIT();

  return rc;
}

/**************************************************************************//**
 * Callback function to provide data to send.
 *
 * Copy data into the supplied buffer, read_callback::ptr, checking size
 * limits.
 *
 * @returns   Number of bytes placed into read_callback::ptr. 0 for EOF.
 *****************************************************************************/
static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *userp)
{
  size_t rtn = 0;
  size_t bytes_to_write = 0;
  MEMORY_CHUNK *tx_chunk = (MEMORY_CHUNK *)userp;

  EVEL_ENTER();

  bytes_to_write = min(size*nmemb, tx_chunk->size);

  if (bytes_to_write > 0)
  {
    EVEL_DEBUG("Going to try to write %d bytes", bytes_to_write);
    strncpy((char *)ptr, tx_chunk->memory, bytes_to_write);
    tx_chunk->memory += bytes_to_write;
    tx_chunk->size -= bytes_to_write;
    rtn = bytes_to_write;
  }
  else
  {
    EVEL_DEBUG("Reached EOF");
  }

  EVEL_EXIT();
  return rtn;
}

/**************************************************************************//**
 * Callback function to provide returned data.
 *
 * Copy data into the supplied buffer, write_callback::ptr, checking size
 * limits.
 *
 * @returns   Number of bytes placed into write_callback::ptr. 0 for EOF.
 *****************************************************************************/
size_t evel_write_callback(void *contents,
                             size_t size,
                             size_t nmemb,
                             void *userp)
{
  size_t realsize = size * nmemb;
  MEMORY_CHUNK * rx_chunk = (MEMORY_CHUNK *)userp;

  EVEL_ENTER();

  EVEL_DEBUG("Called with %d chunks of %d size = %d", nmemb, size, realsize);
  EVEL_DEBUG("rx chunk size is %d", rx_chunk->size);

  rx_chunk->memory = realloc(rx_chunk->memory, rx_chunk->size + realsize + 1);
  if(rx_chunk->memory == NULL) {
    /* out of memory! */
    printf("not enough memory (realloc returned NULL)\n");
    return 0;
  }

  memcpy(&(rx_chunk->memory[rx_chunk->size]), contents, realsize);
  rx_chunk->size += realsize;
  rx_chunk->memory[rx_chunk->size] = 0;

  EVEL_DEBUG("Rx data: %s", rx_chunk->memory);
  EVEL_DEBUG("Returning: %d", realsize);

  EVEL_EXIT();
  return realsize;
}

/**************************************************************************//**
 * Event Handler.
 *
 * Watch for messages coming on the internal queue and send them to the
 * listener.
 *
 * param[in]  arg  Argument - unused.
 *****************************************************************************/
static void * event_handler(void * arg __attribute__ ((unused)))
{
  int old_type = 0;
  EVENT_HEADER * msg = NULL;
  EVENT_INTERNAL * internal_msg = NULL;
  int json_size = 0;
  char json_body[EVEL_MAX_JSON_BODY];
  int rc = EVEL_SUCCESS;
  CURLcode curl_rc;
  int collector_down_count = 0;
  int switch_coll = 0;

  EVEL_INFO("Event handler thread started");

  /***************************************************************************/
  /* Set this thread to be cancellable immediately.                          */
  /***************************************************************************/
  pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &old_type);

  /***************************************************************************/
  /* Set the handler as active, defending against weird situations like      */
  /* immediately shutting down after initializing the library so the         */
  /* handler never gets started up properly.                                 */
  /***************************************************************************/
  if (evt_handler_state == EVT_HANDLER_INACTIVE)
  {
    evt_handler_state = EVT_HANDLER_ACTIVE;
  }
  else
  {
    EVEL_ERROR("Event Handler State was not INACTIVE at start-up - "
               "Handler will exit immediately!");
  }
  /***************************************************************************/
  /* Set the connection to collector                                         */
  /***************************************************************************/
  while (true)
  {
     evel_collector_id = 1;
     rc = evel_setup_curl();

     if ( rc != EVEL_SUCCESS)
     {
        EVEL_ERROR("Failed to setup the first collector. Error code=%d", rc);
        if (curr_global_handles == 2)
        {
           EVEL_DEBUG("Switching to other collector");

           evel_collector_id = 2;

           rc = evel_setup_curl();
           if ( rc != EVEL_SUCCESS)
           {
              EVEL_ERROR("Failed to setup the connection to second collector also, Error code%d", rc);
              sleep(EVEL_COLLECTOR_RECONNECTION_WAIT_TIME);
              collector_down_count = collector_down_count + 1;
              EVEL_ERROR("Collectors setup issue- retry count=%d", collector_down_count);
           }
           else
           {
              collector_down_count = 0;
              break;
           }
        }
        else
        {
           sleep(EVEL_COLLECTOR_RECONNECTION_WAIT_TIME);
           collector_down_count = collector_down_count + 1;
           EVEL_ERROR("Collector setup issue-retry count=%d", collector_down_count);
         }
     }
     else
     {
        collector_down_count = 0;
        break;
     }
  }

  while (evt_handler_state == EVT_HANDLER_ACTIVE)
  {
    /*************************************************************************/
    /* Wait for a message to be received.                                    */
    /*************************************************************************/
    EVEL_DEBUG("Event handler getting any messages");
    msg = ring_buffer_read(&event_buffer);

    /*************************************************************************/
    /* Internal events get special treatment while regular events get posted */
    /* to the far side.                                                      */
    /*************************************************************************/
    if (msg->event_domain == EVEL_DOMAIN_BATCH )
    {
      EVEL_DEBUG("Batch event received");

      /***********************************************************************/
      /* Encode the event in JSON.                                           */
      /***********************************************************************/
      json_size = evel_json_encode_batch_event(json_body, EVEL_MAX_JSON_BODY, msg);

      /***************************************************************************/
      /* Set the URL for the API.                                                */
      /***************************************************************************/
      if (evel_collector_id == 1)
      {
         curl_rc = curl_easy_setopt(curl_handle, CURLOPT_URL, evel_batch_api_url);
      }
      else
      {
         curl_rc = curl_easy_setopt(curl_handle, CURLOPT_URL, evel_bbatch_api_url);
      }

      if (curl_rc != CURLE_OK)
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize libCURL with the Batch API URL. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
      }

      /***********************************************************************/
      /* Send the JSON across the API.                                       */
      /***********************************************************************/
      EVEL_DEBUG("Sending Batch JSON of size %d is: %s", json_size, json_body);
      rc = evel_post_api(json_body, json_size);

      switch_coll = 0;
      if ((rc == EVEL_SUCCESS) && ((http_response_code / 100) != 2))
      {
         switch_coll = 1;
         if (http_response_code == 400) // 400 - Bad JSON related return code
            switch_coll = 0;
      }

      if ((rc != EVEL_SUCCESS)  || (switch_coll == 1))
      {
        EVEL_ERROR("Failed to transfer the data. Error code=%d", rc);
        EVEL_DEBUG("Switching to other collector if any");

        while (true)
        {
           if (curr_global_handles == 2)
           {
              rc = evel_send_to_another_collector(msg->event_domain, json_body, json_size);

              switch_coll = 0;
              if ((rc == EVEL_SUCCESS) && ((http_response_code / 100) != 2))
              {
                 switch_coll = 1;
                 if (http_response_code == 400) // 400 - Bad JSON related return code
                    switch_coll = 0;
              }
              if ((rc != EVEL_SUCCESS)  || (switch_coll == 1))
              {
                 sleep(EVEL_COLLECTOR_RECONNECTION_WAIT_TIME);
                 collector_down_count = collector_down_count + 1;
                 EVEL_ERROR("Collector setup issue-retry count=%d", collector_down_count);
              }
              else
              {
                 break;
              }
           }
           else
           {
              sleep(EVEL_COLLECTOR_RECONNECTION_WAIT_TIME);
              collector_down_count = collector_down_count + 1;
              EVEL_ERROR("Collector setup issue-retry count=%d", collector_down_count);
           }

           rc = evel_send_to_another_collector(msg->event_domain, json_body, json_size);

           switch_coll = 0;
           if ((rc == EVEL_SUCCESS) && ((http_response_code / 100) != 2))
           {
              switch_coll = 1;
              if (http_response_code == 400) // 400 - Bad JSON related return code
                 switch_coll = 0;
           }
           if ((rc != EVEL_SUCCESS)  || (switch_coll == 1))
           {
              collector_down_count = collector_down_count + 1;
              EVEL_ERROR("Collector setup issue-retry count=%d", collector_down_count);
           }
           else
           {
              break;
           }
        }
      }
    }
    else if (msg->event_domain != EVEL_DOMAIN_INTERNAL )
    {
      EVEL_DEBUG("External event received");

      /***********************************************************************/
      /* Encode the event in JSON.                                           */
      /***********************************************************************/
      json_size = evel_json_encode_event(json_body, EVEL_MAX_JSON_BODY, msg);

      /***************************************************************************/
      /* Set the URL for the API.                                                */
      /***************************************************************************/
      if (evel_collector_id == 1)
         curl_rc = curl_easy_setopt(curl_handle, CURLOPT_URL, evel_event_api_url);
      else
         curl_rc = curl_easy_setopt(curl_handle, CURLOPT_URL, evel_bevent_api_url);
      if (curl_rc != CURLE_OK)
      {
        rc = EVEL_CURL_LIBRARY_FAIL;
        log_error_state("Failed to initialize libCURL with the API URL. "
                    "Error code=%d (%s)", curl_rc, curl_err_string);
      }

      /***********************************************************************/
      /* Send the JSON across the API.                                       */
      /***********************************************************************/
      EVEL_DEBUG("Sending JSON of size %d is: %s", json_size, json_body);
      rc = evel_post_api(json_body, json_size);

      switch_coll = 0;
      if ((rc == EVEL_SUCCESS) && ((http_response_code / 100) != 2))
      {
         switch_coll = 1;
         if (http_response_code == 400) // 400 - Bad JSON related return code
            switch_coll = 0;
      }

      if ((rc != EVEL_SUCCESS)  || (switch_coll == 1))
      {
        EVEL_ERROR("Failed to transfer the data. Error code=%d", rc);
        EVEL_DEBUG("Switching to other collector if any");

        while (true)
        {
           if (curr_global_handles == 2)
           {
              rc = evel_send_to_another_collector(msg->event_domain, json_body, json_size);

              switch_coll = 0;
              if ((rc == EVEL_SUCCESS) && ((http_response_code / 100) != 2))
              {
                 switch_coll = 1;
                 if (http_response_code == 400) // 400 - Bad JSON related return code
                    switch_coll = 0;
              }
              if ((rc != EVEL_SUCCESS)  || (switch_coll == 1))
              {
                 sleep(EVEL_COLLECTOR_RECONNECTION_WAIT_TIME);
                 collector_down_count = collector_down_count + 1;
                 EVEL_ERROR("Collector setup issue-retry count=%d", collector_down_count);
              }
              else
              {
                 break;
              }
           }
           else
           {
              sleep(EVEL_COLLECTOR_RECONNECTION_WAIT_TIME);
              collector_down_count = collector_down_count + 1;
              EVEL_ERROR("Collector setup issue-retry count=%d", collector_down_count);
           }

           rc = evel_send_to_another_collector(msg->event_domain, json_body, json_size);

           switch_coll = 0;
           if ((rc == EVEL_SUCCESS) && ((http_response_code / 100) != 2))
           {
              switch_coll = 1;
              if (http_response_code == 400) // 400 - Bad JSON related return code
                 switch_coll = 0;
           }
           if ((rc != EVEL_SUCCESS)  || (switch_coll == 1))
           {
              collector_down_count = collector_down_count + 1;
              EVEL_ERROR("Collector setup issue-retry count=%d", collector_down_count);
           }
           else
           {
              break;
           }
        }
      }
    }
    else
    {
      EVEL_DEBUG("Internal event received");
      internal_msg = (EVENT_INTERNAL *) msg;
      assert(internal_msg->command == EVT_CMD_TERMINATE);
      evt_handler_state = EVT_HANDLER_TERMINATING;
    }

    /*************************************************************************/
    /* We are responsible for freeing the memory.                            */
    /*************************************************************************/
    evel_free_event(msg);
    msg = NULL;

    /*************************************************************************/
    /* There may be a single priority post to be sent.                       */
    /*************************************************************************/
    if (priority_post.memory != NULL)
    {
      EVEL_DEBUG("Priority Post");

      /***********************************************************************/
      /* Set the URL for the throttling API.                                 */
      /***********************************************************************/
      curl_rc = curl_easy_setopt(curl_handle, CURLOPT_URL, evel_throt_api_url);
      if (curl_rc != CURLE_OK)
      {
        /*********************************************************************/
        /* This is only likely to happen with CURLE_OUT_OF_MEMORY, in which  */
        /* case we carry on regardless.                                      */
        /*********************************************************************/
        EVEL_ERROR("Failed to set throttling URL. Error code=%d", rc);
      }
      else
      {
        rc = evel_post_api(priority_post.memory, priority_post.size);
        if (rc != EVEL_SUCCESS)
        {
          EVEL_ERROR("Failed to transfer priority post. Error code=%d", rc);
        }
      }

      /***********************************************************************/
      /* Reinstate the URL for the event API.                                */
      /***********************************************************************/
      curl_rc = curl_easy_setopt(curl_handle, CURLOPT_URL, evel_event_api_url);
      if (curl_rc != CURLE_OK)
      {
        /*********************************************************************/
        /* This is only likely to happen with CURLE_OUT_OF_MEMORY, in which  */
        /* case we carry on regardless.                                      */
        /*********************************************************************/
        EVEL_ERROR("Failed to reinstate events URL. Error code=%d", rc);
      }

      /***********************************************************************/
      /* We are responsible for freeing the memory.                          */
      /***********************************************************************/
      free(priority_post.memory);
      priority_post.memory = NULL;
    }
  }

  /***************************************************************************/
  /* The event handler is now exiting. The ring-buffer could contain events  */
  /* which have not been processed, so deplete those.  Because we've been    */
  /* asked to exit we can be confident that the foreground will have stopped */
  /* sending events in so we know that this process will conclude!           */
  /***************************************************************************/
  evt_handler_state = EVT_HANDLER_TERMINATING;
  while (!ring_buffer_is_empty(&event_buffer))
  {
    EVEL_DEBUG("Reading event from buffer");
    msg = ring_buffer_read(&event_buffer);
    evel_free_event(msg);
  }
  evt_handler_state = EVT_HANDLER_TERMINATED;
  EVEL_INFO("Event handler thread stopped");

  return (NULL);
}

/**************************************************************************//**
 * Handle a JSON response from the listener, contained in a ::MEMORY_CHUNK.
 *
 * Tokenize the response, and decode any tokens found.
 *
 * @param chunk         The memory chunk containing the response.
 * @param post          The memory chunk in which to place any resulting POST.
 *****************************************************************************/
void evel_handle_event_response(const MEMORY_CHUNK * const chunk,
                                MEMORY_CHUNK * const post)
{
  jsmn_parser json_parser;
  jsmntok_t json_tokens[EVEL_MAX_RESPONSE_TOKENS];
  int num_tokens = 0;

  EVEL_ENTER();

  /***************************************************************************/
  /* Check preconditions.                                                    */
  /***************************************************************************/
  assert(chunk != NULL);
  assert(priority_post.memory == NULL);

  EVEL_DEBUG("Response size = %d", chunk->size);
  EVEL_DEBUG("Response = %s", chunk->memory);

  /***************************************************************************/
  /* Initialize the parser and tokenize the response.                        */
  /***************************************************************************/
  jsmn_init(&json_parser);
  num_tokens = jsmn_parse(&json_parser,
                          chunk->memory,
                          chunk->size,
                          json_tokens,
                          EVEL_MAX_RESPONSE_TOKENS);

  if (num_tokens < 0)
  {
    EVEL_ERROR("Failed to parse JSON response.  "
               "Error code=%d", num_tokens);
  }
  else if (num_tokens == 0)
  {
    EVEL_DEBUG("No tokens found in JSON response");
  }
  else
  {
    EVEL_DEBUG("Decode JSON response tokens");
    if (!evel_handle_response_tokens(chunk, json_tokens, num_tokens, post))
    {
      EVEL_ERROR("Failed to handle JSON response.");
    }
  }

  EVEL_EXIT();
}

/**************************************************************************//**
 * Handle a JSON response from the listener, as a list of tokens from JSMN.
 *
 * @param chunk         Memory chunk containing the JSON buffer.
 * @param json_tokens   Array of tokens to handle.
 * @param num_tokens    The number of tokens to handle.
 * @param post          The memory chunk in which to place any resulting POST.
 * @return true if we handled the response, false otherwise.
 *****************************************************************************/
bool evel_handle_response_tokens(const MEMORY_CHUNK * const chunk,
                                 const jsmntok_t * const json_tokens,
                                 const int num_tokens,
                                 MEMORY_CHUNK * const post)
{
  bool json_ok = true;

  EVEL_ENTER();

  /***************************************************************************/
  /* Check preconditions.                                                    */
  /***************************************************************************/
  assert(chunk != NULL);
  assert(json_tokens != NULL);
  assert(num_tokens < EVEL_MAX_RESPONSE_TOKENS);

  /***************************************************************************/
  /* Peek at the tokens to decide what the response it, then call the        */
  /* appropriate handler to handle it.  There is only one handler at this    */
  /* point.                                                                  */
  /***************************************************************************/
  if (evel_tokens_match_command_list(chunk, json_tokens, num_tokens))
  {
    json_ok = evel_handle_command_list(chunk, json_tokens, num_tokens, post);
  }

  EVEL_EXIT();

  return json_ok;
}

/**************************************************************************//**
 * Determine whether a list of tokens looks like a "commandList" response.
 *
 * @param chunk         Memory chunk containing the JSON buffer.
 * @param json_tokens   Token to check.
 * @param num_tokens    The number of tokens to handle.
 * @return true if the tokens look like a "commandList" match, or false.
 *****************************************************************************/
bool evel_tokens_match_command_list(const MEMORY_CHUNK * const chunk,
                                    const jsmntok_t * const json_tokens,
                                    const int num_tokens)
{
  bool result = false;

  EVEL_ENTER();

  /***************************************************************************/
  /* Make some checks on the basic layout of the commandList.                */
  /***************************************************************************/
  if ((num_tokens > 3) &&
      (json_tokens[0].type == JSMN_OBJECT) &&
      (json_tokens[1].type == JSMN_STRING) &&
      (json_tokens[2].type == JSMN_ARRAY) &&
      (evel_token_equals_string(chunk, &json_tokens[1], "commandList")))
  {
    result = true;
  }

  EVEL_EXIT();

  return result;
}

/**************************************************************************//**
 * Check that a string token matches a given input string.
 *
 * @param chunk         Memory chunk containing the JSON buffer.
 * @param json_token    Token to check.
 * @param check_string  String to check it against.
 * @return true if the strings match, or false.
 *****************************************************************************/
bool evel_token_equals_string(const MEMORY_CHUNK * const chunk,
                              const jsmntok_t * json_token,
                              const char * check_string)
{
  bool result = false;

  EVEL_ENTER();

  const int token_length = json_token->end - json_token->start;
  const char * const token_string = chunk->memory + json_token->start;

  if (token_length == (int)strlen(check_string))
  {
    result = (strncmp(token_string, check_string, token_length) == 0);
  }

  EVEL_EXIT();

  return result;
}