summaryrefslogtreecommitdiffstats
path: root/src/fluent-bit/plugins/in_calyptia_fleet/in_calyptia_fleet.c
blob: 3175b5645c1e1058f0c88587de104c4d9be3df75 (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
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*  Fluent Bit
 *  ==========
 *  Copyright (C) 2015-2023 The Fluent Bit Authors
 *
 *  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.
 */

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <signal.h>
#include <sys/stat.h>

#include <msgpack.h>
#include <fluent-bit/flb_input.h>
#include <fluent-bit/flb_input_plugin.h>
#include <fluent-bit/flb_config.h>
#include <fluent-bit/flb_config_map.h>
#include <fluent-bit/flb_error.h>
#include <fluent-bit/flb_time.h>
#include <fluent-bit/flb_pack.h>
#include <fluent-bit/flb_strptime.h>
#include <fluent-bit/flb_reload.h>
#include <fluent-bit/flb_lib.h>
#include <fluent-bit/config_format/flb_cf_fluentbit.h>
#include <fluent-bit/flb_base64.h>


#define CALYPTIA_H_PROJECT       "X-Project-Token"
#define CALYPTIA_H_CTYPE         "Content-Type"
#define CALYPTIA_H_CTYPE_JSON    "application/json"

#define DEFAULT_INTERVAL_SEC  "15"
#define DEFAULT_INTERVAL_NSEC "0"

#define CALYPTIA_HOST "cloud-api.calyptia.com"
#define CALYPTIA_PORT "443"

#ifndef _WIN32
#define PATH_SEPARATOR "/"
#define DEFAULT_CONFIG_DIR "/tmp/calyptia-fleet"
#else
#define DEFAULT_CONFIG_DIR NULL
#define PATH_SEPARATOR "\\"
#endif

struct flb_in_calyptia_fleet_config {
    /* Time interval check */
    int interval_sec;
    int interval_nsec;

    /* Grabbed from the cfg_path, used to check if configuration has
     * has been updated.
     */
    long config_timestamp;

    flb_sds_t api_key;
    flb_sds_t fleet_id;
    flb_sds_t fleet_name;
    flb_sds_t machine_id;
    flb_sds_t config_dir;
    flb_sds_t cloud_host;
    flb_sds_t cloud_port;

    flb_sds_t fleet_url;

    struct flb_input_instance *ins;       /* plugin instance */
    struct flb_config *config;            /* Fluent Bit context */

    /* Networking */
    struct flb_upstream *u;

    int event_fd;

    int collect_fd;
};

static char *find_case_header(struct flb_http_client *cli, const char *header)
{
    char *ptr;
    char *headstart;


    headstart = strstr(cli->resp.data, "\r\n");

    if (headstart == NULL) {
        return NULL;
    }

    /* Lookup the beginning of the header */
    for (ptr = headstart; ptr != NULL && ptr+2 < cli->resp.payload; ptr = strstr(ptr, "\r\n")) {

        if (ptr + 4 < cli->resp.payload && strcmp(ptr, "\r\n\r\n") == 0) {
            return NULL;
        }

        ptr+=2;

        /* no space left for header */
        if (ptr + strlen(header)+2 >= cli->resp.payload) {
            return NULL;
        }

        /* matched header and the delimiter */
        if (strncasecmp(ptr, header, strlen(header)) == 0) {

            if (ptr[strlen(header)] == ':' && ptr[strlen(header)+1] == ' ') {
                return ptr;                
            }
        }
    }

    return NULL;
}

/* Try to find a header value in the buffer. Copied from flb_http_client.c. */
static int case_header_lookup(struct flb_http_client *cli,
                         const char *header, int header_len,
                         const char **out_val, int *out_len)
{
    char *ptr;
    char *crlf;
    char *end;

    if (!cli->resp.data) {
        return -1;
    }

    ptr = find_case_header(cli, header);
    end = strstr(cli->resp.data, "\r\n\r\n");

    if (!ptr) {

        if (end) {
            /* The headers are complete but the header is not there */
            return -1;
        }

        /* We need more data */
        return -1;
    }

    /* Exclude matches in the body */
    if (end && ptr > end) {
        return -1;
    }

    /* Lookup CRLF (end of line \r\n) */
    crlf = strstr(ptr, "\r\n");

    if (!crlf) {
        return -1;
    }

    /* sanity check that the header_len does not exceed the headers. */
    if (ptr + header_len + 2 > end) {
        return -1;
    }

    ptr += header_len + 2;

    *out_val = ptr;
    *out_len = (crlf - ptr);

    return 0;
}

struct reload_ctx {
    flb_ctx_t *flb;
    flb_sds_t cfg_path;
};

static flb_sds_t fleet_config_filename(struct flb_in_calyptia_fleet_config *ctx, char *fname)
{
    flb_sds_t cfgname;

    cfgname = flb_sds_create_size(4096);

    if (ctx->fleet_name != NULL) {
        flb_sds_printf(&cfgname,
                       "%s" PATH_SEPARATOR "%s" PATH_SEPARATOR "%s" PATH_SEPARATOR "%s.ini",
                       ctx->config_dir, ctx->machine_id, ctx->fleet_name, fname);
    }
    else {
        flb_sds_printf(&cfgname,
                       "%s" PATH_SEPARATOR "%s" PATH_SEPARATOR "%s" PATH_SEPARATOR "%s.ini",
                       ctx->config_dir, ctx->machine_id, ctx->fleet_id, fname);
    }

    return cfgname;
}

static flb_sds_t new_fleet_config_filename(struct flb_in_calyptia_fleet_config *ctx)
{
    return fleet_config_filename(ctx, "new");
}

static flb_sds_t cur_fleet_config_filename(struct flb_in_calyptia_fleet_config *ctx)
{
    return fleet_config_filename(ctx, "cur");
}

static flb_sds_t old_fleet_config_filename(struct flb_in_calyptia_fleet_config *ctx)
{
    return fleet_config_filename(ctx, "old");
}

static flb_sds_t time_fleet_config_filename(struct flb_in_calyptia_fleet_config *ctx, time_t t)
{
    char s_last_modified[32];

    snprintf(s_last_modified, sizeof(s_last_modified)-1, "%d", (int)t);
    return fleet_config_filename(ctx, s_last_modified);
}

static int is_new_fleet_config(struct flb_in_calyptia_fleet_config *ctx, struct flb_config *cfg)
{
    flb_sds_t cfgnewname;
    int ret = FLB_FALSE;


    if (cfg->conf_path_file == NULL) {
        return FLB_FALSE;
    }

    cfgnewname = new_fleet_config_filename(ctx);

    if (strcmp(cfgnewname, cfg->conf_path_file) == 0) {
        ret = FLB_TRUE;
    }

    flb_sds_destroy(cfgnewname);

    return ret;
}

static int is_cur_fleet_config(struct flb_in_calyptia_fleet_config *ctx, struct flb_config *cfg)
{
    flb_sds_t cfgcurname;
    int ret = FLB_FALSE;


    if (cfg->conf_path_file == NULL) {
        return FLB_FALSE;
    }

    cfgcurname = cur_fleet_config_filename(ctx);

    if (strcmp(cfgcurname, cfg->conf_path_file) == 0) {
        ret = FLB_TRUE;
    }

    flb_sds_destroy(cfgcurname);

    return ret;
}

static int is_timestamped_fleet_config(struct flb_in_calyptia_fleet_config *ctx, struct flb_config *cfg)
{
    char *fname;
    char *end;
    long val;

    if (cfg->conf_path_file == NULL) {
        return FLB_FALSE;
    }

    fname = strrchr(cfg->conf_path_file, PATH_SEPARATOR[0]);

    if (fname == NULL) {
        return FLB_FALSE;
    }

    fname++;

    errno = 0;
    val = strtol(fname, &end, 10);

    if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) ||
         (errno != 0 && val == 0)) {
        flb_errno();
        return FLB_FALSE;
    }

    if (strcmp(end, ".ini") == 0) {
        return FLB_TRUE;
    }

    return FLB_FALSE;
}

static int is_fleet_config(struct flb_in_calyptia_fleet_config *ctx, struct flb_config *cfg)
{
    if (cfg->conf_path_file == NULL) {
        return FLB_FALSE;
    }

    return is_new_fleet_config(ctx, cfg) ||
           is_cur_fleet_config(ctx, cfg) ||
           is_timestamped_fleet_config(ctx, cfg);
}

static int exists_new_fleet_config(struct flb_in_calyptia_fleet_config *ctx)
{
    flb_sds_t cfgnewname;
    int ret = FLB_FALSE;


    cfgnewname = new_fleet_config_filename(ctx);
    ret = access(cfgnewname, F_OK) == 0 ? FLB_TRUE : FLB_FALSE;

    flb_sds_destroy(cfgnewname);
    return ret;
}

static int exists_cur_fleet_config(struct flb_in_calyptia_fleet_config *ctx)
{
    flb_sds_t cfgcurname;
    int ret = FLB_FALSE;


    cfgcurname = cur_fleet_config_filename(ctx);
    ret = access(cfgcurname, F_OK) == 0 ? FLB_TRUE : FLB_FALSE;

    flb_sds_destroy(cfgcurname);
    return ret;
}

static void *do_reload(void *data)
{
    struct reload_ctx *reload = (struct reload_ctx *)data;

    /* avoid reloading the current configuration... just use our new one! */
    flb_context_set(reload->flb);
    reload->flb->config->enable_hot_reload = FLB_TRUE;
    reload->flb->config->conf_path_file = reload->cfg_path;

    sleep(5);
#ifndef FLB_SYSTEM_WINDOWS
    kill(getpid(), SIGHUP);
#else
	GenerateConsoleCtrlEvent(1 /* CTRL_BREAK_EVENT_1 */, 0);
#endif
    return NULL;
}

static int test_config_is_valid(flb_sds_t cfgpath)
{
    struct flb_config *config;
    struct flb_cf *conf;
    int ret = FLB_FALSE;


    config = flb_config_init();

    if (config == NULL) {
        goto config_init_error;
    }

    conf = flb_cf_create();

    if (conf == NULL) {
        goto cf_create_error;
    } 

    conf = flb_cf_create_from_file(conf, cfgpath);

    if (conf == NULL) {
        goto cf_create_from_file_error;
    } 

    if (flb_config_load_config_format(config, conf)) {
        goto cf_load_config_format_error;
    }

    if (flb_reload_property_check_all(config)) {
       goto cf_property_check_error;
    }

    ret = FLB_TRUE;

cf_property_check_error:
cf_load_config_format_error:
cf_create_from_file_error:
    flb_cf_destroy(conf);
cf_create_error:
    flb_config_exit(config);
config_init_error:
    return ret;
}

static int execute_reload(struct flb_in_calyptia_fleet_config *ctx, flb_sds_t cfgpath)
{
    struct reload_ctx *reload;
    pthread_t pth;
    pthread_attr_t ptha;
    flb_ctx_t *flb = flb_context_get();

    if (ctx->collect_fd > 0) {
        flb_input_collector_pause(ctx->collect_fd, ctx->ins);
    }

    if (flb == NULL) {
        flb_plg_error(ctx->ins, "unable to get fluent-bit context.");

        if (ctx->collect_fd > 0) {
            flb_input_collector_resume(ctx->collect_fd, ctx->ins);
        }

        return FLB_FALSE;
    }

    /* fix execution in valgrind...
     * otherwise flb_reload errors out with:
     *    [error] [reload] given flb context is NULL
     */
    flb_plg_info(ctx->ins, "loading configuration from %s.", cfgpath);

    if (test_config_is_valid(cfgpath) == FLB_FALSE) {
        flb_plg_error(ctx->ins, "unable to load configuration.");

        if (ctx->collect_fd > 0) {
            flb_input_collector_resume(ctx->collect_fd, ctx->ins);
        }

        return FLB_FALSE;
    }

    reload = flb_calloc(1, sizeof(struct reload_ctx));
    reload->flb = flb;
    reload->cfg_path = cfgpath;

    pthread_attr_init(&ptha);
    pthread_attr_setdetachstate(&ptha, PTHREAD_CREATE_DETACHED);
    pthread_create(&pth, &ptha, do_reload, reload);

    return FLB_TRUE;
}

static char *tls_setting_string(int use_tls)
{
    if (use_tls) {
        return "On";
    }

    return "Off";
}

static flb_sds_t parse_api_key_json(struct flb_in_calyptia_fleet_config *ctx,
                                    char *payload, size_t size)
{
    int ret;
    int out_size;
    char *pack;
    struct flb_pack_state pack_state;
    size_t off = 0;
    msgpack_unpacked result;
    msgpack_object_kv *cur;
    msgpack_object_str *key;
    flb_sds_t project_id;
    int idx = 0;

    /* Initialize packer */
    flb_pack_state_init(&pack_state);

    /* Pack JSON as msgpack */
    ret = flb_pack_json_state(payload, size,
                              &pack, &out_size, &pack_state);
    flb_pack_state_reset(&pack_state);

    /* Handle exceptions */
    if (ret == FLB_ERR_JSON_PART) {
        flb_plg_warn(ctx->ins, "JSON data is incomplete, skipping");
        return NULL;
    }
    else if (ret == FLB_ERR_JSON_INVAL) {
        flb_plg_warn(ctx->ins, "invalid JSON message, skipping");
        return NULL;
    }
    else if (ret == -1) {
        return NULL;
    }

    msgpack_unpacked_init(&result);
    while (msgpack_unpack_next(&result, pack, out_size, &off) == MSGPACK_UNPACK_SUCCESS) {

        if (result.data.type == MSGPACK_OBJECT_MAP) {
            for (idx = 0; idx < result.data.via.map.size; idx++) {
                cur = &result.data.via.map.ptr[idx];
                key = &cur->key.via.str;

                if (strncmp(key->ptr, "ProjectID", key->size) == 0) {

                    if (cur->val.type != MSGPACK_OBJECT_STR) {
                        flb_plg_error(ctx->ins, "unable to find fleet by name");
                        msgpack_unpacked_destroy(&result);
                        return NULL;
                    }

                    project_id = flb_sds_create_len(cur->val.via.str.ptr, 
                                                    cur->val.via.str.size);
                    msgpack_unpacked_destroy(&result);
                    flb_free(pack);

                    return project_id;
                }
            }
        }
    }

    msgpack_unpacked_destroy(&result);
    flb_free(pack);

    return NULL;
}

static ssize_t parse_fleet_search_json(struct flb_in_calyptia_fleet_config *ctx,
                                       char *payload, size_t size)
{
    int ret;
    int out_size;
    char *pack;
    struct flb_pack_state pack_state;
    size_t off = 0;
    msgpack_unpacked result;
    msgpack_object_array *results;
    msgpack_object_kv *cur;
    msgpack_object_str *key;
    int idx = 0;

    /* Initialize packer */
    flb_pack_state_init(&pack_state);

    /* Pack JSON as msgpack */
    ret = flb_pack_json_state(payload, size,
                              &pack, &out_size, &pack_state);
    flb_pack_state_reset(&pack_state);

    /* Handle exceptions */
    if (ret == FLB_ERR_JSON_PART) {
        flb_plg_warn(ctx->ins, "JSON data is incomplete, skipping");
        return -1;
    }
    else if (ret == FLB_ERR_JSON_INVAL) {
        flb_plg_warn(ctx->ins, "invalid JSON message, skipping");
        return -1;
    }
    else if (ret == -1) {
        return -1;
    }

    msgpack_unpacked_init(&result);
    while (msgpack_unpack_next(&result, pack, out_size, &off) == MSGPACK_UNPACK_SUCCESS) {

        if (result.data.type == MSGPACK_OBJECT_ARRAY) {
            results = &result.data.via.array;

            if (results->ptr[0].type == MSGPACK_OBJECT_MAP) {

                for (idx = 0; idx < results->ptr[0].via.map.size; idx++) {
                    cur = &results->ptr[0].via.map.ptr[idx];
                    key = &cur->key.via.str;

                    if (strncasecmp(key->ptr, "id", key->size) == 0) {

                        if (cur->val.type != MSGPACK_OBJECT_STR) {
                            flb_plg_error(ctx->ins, "unable to find fleet by name");
                            msgpack_unpacked_destroy(&result);
                            return -1;
                        }

                        ctx->fleet_id = flb_sds_create_len(cur->val.via.str.ptr,
                                                           cur->val.via.str.size);
                        break;
                    }
                    break;
                }
                break;
            }
        }
    }

    msgpack_unpacked_destroy(&result);
    flb_free(pack);

    if (ctx->fleet_id == NULL) {
        return -1;
    }

    return 0;
}

static int get_calyptia_fleet_id_by_name(struct flb_in_calyptia_fleet_config *ctx,
                                         struct flb_connection *u_conn,
                                         struct flb_config *config)
{
    struct flb_http_client *client;
    flb_sds_t url;
    flb_sds_t project_id;
    unsigned char token[512] = {0};
    unsigned char encoded[256];
    size_t elen;
    size_t tlen;
    char *api_token_sep;
    size_t b_sent;
    int ret;

    api_token_sep = strchr(ctx->api_key, '.');

    if (api_token_sep == NULL) {
        return -1;
    }

    elen = api_token_sep-ctx->api_key;
    elen = elen + (4 - (elen % 4));

    if (elen > sizeof(encoded)) {
        flb_plg_error(ctx->ins, "API Token is too large");
        return -1;
    }

    memset(encoded, '=', sizeof(encoded));
    memcpy(encoded, ctx->api_key, api_token_sep-ctx->api_key);

    ret = flb_base64_decode(token, sizeof(token)-1, &tlen,
                            encoded, elen); 

    if (ret != 0) {
        return ret;
    }

    project_id = parse_api_key_json(ctx, (char *)token, tlen);

    if (project_id == NULL) {
        return -1;
    }

    url = flb_sds_create_size(4096);
    flb_sds_printf(&url, "/v1/search?project_id=%s&resource=fleet&term=%s", 
                   project_id, ctx->fleet_name);

    client = flb_http_client(u_conn, FLB_HTTP_GET, url, NULL, 0,
                             ctx->ins->host.name, ctx->ins->host.port, NULL, 0);

    if (!client) {
        flb_plg_error(ctx->ins, "unable to create http client");
        return -1;
    }

    flb_http_buffer_size(client, 8192);

    flb_http_add_header(client,
                        CALYPTIA_H_PROJECT, sizeof(CALYPTIA_H_PROJECT) - 1,
                        ctx->api_key, flb_sds_len(ctx->api_key));

    ret = flb_http_do(client, &b_sent);

    if (ret != 0) {
        flb_plg_error(ctx->ins, "http do error");
        return -1;
    }

    if (client->resp.status != 200) {
        flb_plg_error(ctx->ins, "search http status code error: %d", client->resp.status);
        return -1;
    }

    if (client->resp.payload_size <= 0) {
        flb_plg_error(ctx->ins, "empty response");
        return -1;
    }

    if (parse_fleet_search_json(ctx, client->resp.payload, client->resp.payload_size) == -1) {
        flb_plg_error(ctx->ins, "unable to find fleet: %s", ctx->fleet_name);
        return -1;
    }

    if (ctx->fleet_id == NULL) {
        return -1;
    }
    return 0;
}

#ifdef FLB_SYSTEM_WINDOWS
#define link(a, b) CreateHardLinkA(b, a, 0)

ssize_t readlink(const char *path, char *realpath, size_t srealpath) {
    HANDLE hFile;
    DWORD ret;

    hFile = CreateFile(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 
                       FILE_ATTRIBUTE_NORMAL, NULL);

    if (hFile == INVALID_HANDLE_VALUE) {
        return -1;
    }

    ret = GetFinalPathNameByHandleA(hFile, realpath, srealpath, VOLUME_NAME_NT);

    if (ret < srealpath) {
        CloseHandle(hFile);
        return -1;
    }

    CloseHandle(hFile);
    return ret;
}

#endif

/* cb_collect callback */
static int in_calyptia_fleet_collect(struct flb_input_instance *ins,
                                     struct flb_config *config, 
                                     void *in_context)
{
    struct flb_in_calyptia_fleet_config *ctx = in_context;
    struct flb_connection *u_conn;
    struct flb_http_client *client;
    flb_sds_t cfgname;
    flb_sds_t cfgnewname;
    flb_sds_t cfgoldname;
    flb_sds_t cfgcurname;
    flb_sds_t header;
    flb_sds_t hdr;
    FILE *cfgfp;
    const char *fbit_last_modified;
    int fbit_last_modified_len;
    struct flb_tm tm_last_modified = { 0 };
    time_t time_last_modified;
    char *data;
    size_t b_sent;
    int ret = -1;
#ifdef FLB_SYSTEM_WINDOWS
    DWORD err;
    LPSTR lpMsg;
#endif

    u_conn = flb_upstream_conn_get(ctx->u);

    if (!u_conn) {
        flb_plg_error(ctx->ins, "could not get an upstream connection to %s:%u",
                      ctx->ins->host.name, ctx->ins->host.port);
        goto conn_error;
    }

    if (ctx->fleet_id == NULL) {

        if (get_calyptia_fleet_id_by_name(ctx, u_conn, config) == -1) {
            flb_plg_error(ctx->ins, "unable to find fleet: %s", ctx->fleet_name);
            goto conn_error;
        }
    }

    if (ctx->fleet_url == NULL) {
        ctx->fleet_url = flb_sds_create_size(4096);
        flb_sds_printf(&ctx->fleet_url, "/v1/fleets/%s/config?format=ini", ctx->fleet_id);
    }

    client = flb_http_client(u_conn, FLB_HTTP_GET, ctx->fleet_url,
                             NULL, 0, 
                             ctx->ins->host.name, ctx->ins->host.port, NULL, 0);

    if (!client) {
        flb_plg_error(ins, "unable to create http client");
        goto client_error;
    }

    flb_http_buffer_size(client, 8192);

    flb_http_add_header(client,
                        CALYPTIA_H_PROJECT, sizeof(CALYPTIA_H_PROJECT) - 1,
                        ctx->api_key, flb_sds_len(ctx->api_key));

    ret = flb_http_do(client, &b_sent);

    if (ret != 0) {
        flb_plg_error(ins, "http do error");
        goto http_error;
    }

    if (client->resp.status != 200) {
        flb_plg_error(ins, "http status code error: %d", client->resp.status);
        goto http_error;
    }

    if (client->resp.payload_size <= 0) {
        flb_plg_error(ins, "empty response");
        goto http_error;
    }

    /* copy and NULL terminate the payload */
    data = flb_sds_create_size(client->resp.payload_size + 1);

    if (!data) {
        goto http_error;
    }
    memcpy(data, client->resp.payload, client->resp.payload_size);
    data[client->resp.payload_size] = '\0';

    ret = case_header_lookup(client, "Last-modified", strlen("Last-modified"),
                        &fbit_last_modified, &fbit_last_modified_len);

    if (ret == -1) {
        flb_plg_error(ctx->ins, "unable to get last-modified header");
        goto http_error;
    }

    flb_strptime(fbit_last_modified, "%a, %d %B %Y %H:%M:%S GMT", &tm_last_modified);
    time_last_modified = mktime(&tm_last_modified.tm);

    cfgname = time_fleet_config_filename(ctx, time_last_modified);

    if (access(cfgname, F_OK) == -1 && errno == ENOENT) {
        cfgfp = fopen(cfgname, "w+");

        if (cfgfp == NULL) {
            flb_plg_error(ctx->ins, "unable to open configuration file: %s", cfgname);
            goto http_error;
        }

        header = flb_sds_create_size(4096);

        if (ctx->fleet_name == NULL) {
            hdr = flb_sds_printf(&header,
                        "[CUSTOM]\n"
                        "    Name             calyptia\n"
                        "    api_key          %s\n"
                        "    fleet_id         %s\n"
                        "    add_label        fleet_id %s\n"
                        "    fleet.config_dir %s\n"
                        "    calyptia_host    %s\n"
                        "    calyptia_port    %d\n"
                        "    calyptia_tls     %s\n",
                        ctx->api_key,
                        ctx->fleet_id,
                        ctx->fleet_id,
                        ctx->config_dir,
                        ctx->ins->host.name,
                        ctx->ins->host.port,
                        tls_setting_string(ctx->ins->use_tls)
            );
        }
        else {
            hdr = flb_sds_printf(&header,
                        "[CUSTOM]\n"
                        "    Name          calyptia\n"
                        "    api_key       %s\n"
                        "    fleet_name    %s\n"
                        "    fleet_id      %s\n"
                        "    add_label     fleet_id %s\n"
                        "    fleet.config_dir    %s\n"
                        "    calyptia_host %s\n"
                        "    calyptia_port %d\n"
                        "    calyptia_tls  %s\n",
                        ctx->api_key,
                        ctx->fleet_name,
                        ctx->fleet_id,
                        ctx->fleet_id,
                        ctx->config_dir,
                        ctx->ins->host.name,
                        ctx->ins->host.port,
                        tls_setting_string(ctx->ins->use_tls)
            );
        }
        if (hdr == NULL) {
            fclose(cfgfp);
            goto http_error;
        }
        if (ctx->machine_id) {
            hdr = flb_sds_printf(&header, "    machine_id %s\n", ctx->machine_id);
            if (hdr == NULL) {
                fclose(cfgfp);
                goto http_error;
            }
        }
        fwrite(header, strlen(header), 1, cfgfp);
        flb_sds_destroy(header);
        fwrite(data, client->resp.payload_size, 1, cfgfp);
        fclose(cfgfp);

        cfgnewname = new_fleet_config_filename(ctx);

        if (exists_new_fleet_config(ctx) == FLB_TRUE) {
            cfgoldname = old_fleet_config_filename(ctx);
            rename(cfgnewname, cfgoldname);
            unlink(cfgnewname);
            flb_sds_destroy(cfgoldname);
        }

        if (!link(cfgname, cfgnewname)) {
#ifdef FLB_SYSTEM_WINDOWS
            err = GetLastError();
            FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
                          NULL, err, 0, &lpMsg, 0, NULL);
            flb_plg_error(ctx->ins, "unable to create hard link: %s", lpMsg);
#else
            flb_errno();
#endif
        }
    }

    if (ctx->config_timestamp < time_last_modified) {
        flb_plg_debug(ctx->ins, "new configuration is newer than current: %ld < %ld",
                      ctx->config_timestamp, time_last_modified);
        flb_plg_info(ctx->ins, "force the reloading of the configuration file=%d.", ctx->event_fd);
        flb_sds_destroy(data);

        if (execute_reload(ctx, cfgname) == FLB_FALSE) {
            cfgoldname = old_fleet_config_filename(ctx);
            cfgcurname = cur_fleet_config_filename(ctx);
            rename(cfgoldname, cfgcurname);
            flb_sds_destroy(cfgcurname);
            flb_sds_destroy(cfgoldname);
            goto reload_error;
        }
        else {
            FLB_INPUT_RETURN(0);
        }
    }

    ret = 0;

reload_error:
http_error:
    flb_http_client_destroy(client);
client_error:
    flb_upstream_conn_release(u_conn);
conn_error:
    FLB_INPUT_RETURN(ret);
}

#ifdef FLB_SYSTEM_WINDOWS
#define _mkdir(a, b) mkdir(a)
#else
#define _mkdir(a, b) mkdir(a, b)
#endif

/* recursively create directories, based on:
 *   https://stackoverflow.com/a/2336245
 * who found it at:
 *   http://nion.modprobe.de/blog/archives/357-Recursive-directory-creation.html
 */
static int __mkdir(const char *dir, int perms) {
    char tmp[255];
    char *ptr = NULL;
    size_t len;
    int ret;

    ret = snprintf(tmp, sizeof(tmp),"%s",dir);
    if (ret > sizeof(tmp)) {
        return -1;
    }

    len = strlen(tmp);
    if (tmp[len - 1] == '/') {
        tmp[len - 1] = 0;
    }

    for (ptr = tmp + 1; *ptr; ptr++) {
        if (*ptr == '/') {
            *ptr = 0;
            if (access(tmp, F_OK) != 0) {
                ret = _mkdir(tmp, perms);
                if (ret != 0) {
                    return ret;
                }
            }
            *ptr = '/';
        }
    }
    return _mkdir(tmp, perms);
}

static int create_fleet_directory(struct flb_in_calyptia_fleet_config *ctx)
{
    flb_sds_t myfleetdir;

    if (access(ctx->config_dir, F_OK) != 0) {
        if (__mkdir(ctx->config_dir, 0700) != 0) {
            return -1;
        }
    }

    myfleetdir = flb_sds_create_size(256);

    if (ctx->fleet_name != NULL) {
        flb_sds_printf(&myfleetdir, "%s" PATH_SEPARATOR "%s" PATH_SEPARATOR "%s",
                       ctx->config_dir, ctx->machine_id, ctx->fleet_name);
    }
    else {
        flb_sds_printf(&myfleetdir, "%s" PATH_SEPARATOR "%s" PATH_SEPARATOR "%s",
                       ctx->config_dir, ctx->machine_id, ctx->fleet_id);
    }

    if (access(myfleetdir, F_OK) != 0) {
        if (__mkdir(myfleetdir, 0700) !=0) {
            return -1;
        }
    }

    flb_sds_destroy(myfleetdir);
    return 0;
}

static int load_fleet_config(struct flb_in_calyptia_fleet_config *ctx)
{
    flb_ctx_t *flb_ctx = flb_context_get();
    char *fname;
    char *ext;
    long timestamp;
    char realname[4096];
    ssize_t len;

    if (create_fleet_directory(ctx) != 0) {
        return -1;
    }

    /* check if we are already using the fleet configuration file. */
    if (is_fleet_config(ctx, flb_ctx->config) == FLB_FALSE) {
        /* check which one and load it */
        if (exists_cur_fleet_config(ctx) == FLB_TRUE) {
            return execute_reload(ctx, cur_fleet_config_filename(ctx));
        }
        else if (exists_new_fleet_config(ctx) == FLB_TRUE) {
            return execute_reload(ctx, new_fleet_config_filename(ctx));
        }
    }
    else {
        if (is_new_fleet_config(ctx, flb_ctx->config) || is_cur_fleet_config(ctx, flb_ctx->config)) {
            len = readlink(flb_ctx->config->conf_path_file, realname, sizeof(realname));

            if (len > sizeof(realname)) {
                return FLB_FALSE;
            }

            fname = basename(realname);
        }
        else {
            fname = basename(flb_ctx->config->conf_path_file);
        }

        if (fname == NULL) {
            return FLB_FALSE;
        }

        errno = 0;
        timestamp = strtol(fname, &ext, 10);

        if ((errno == ERANGE && (timestamp == LONG_MAX || timestamp == LONG_MIN)) ||
             (errno != 0 && timestamp == 0)) {
            flb_errno();
            return FLB_FALSE;
        }

        /* unable to parse the timstamp */
        if (errno == ERANGE) {
            return FLB_FALSE;
        }

        ctx->config_timestamp = timestamp;
    }

    return FLB_FALSE;
}

static int in_calyptia_fleet_init(struct flb_input_instance *in,
                          struct flb_config *config, void *data)
{
    int ret;
    int upstream_flags;
    struct flb_in_calyptia_fleet_config *ctx;
    (void) data;

#ifdef _WIN32
    char *tmpdir;
#endif

    flb_plg_info(in, "initializing calyptia fleet input.");

    if (in->host.name == NULL) {
        flb_plg_error(in, "no input 'Host' provided");
        return -1;
    }

    /* Allocate space for the configuration */
    ctx = flb_calloc(1, sizeof(struct flb_in_calyptia_fleet_config));

    if (!ctx) {
        flb_errno();
        return -1;
    }
    ctx->ins = in;
    ctx->collect_fd = -1;


    /* Load the config map */
    ret = flb_input_config_map_set(in, (void *)ctx);

    if (ret == -1) {
        flb_free(ctx);
        flb_plg_error(in, "unable to load configuration");
        return -1;
    }

#ifdef _WIN32
    if (ctx->config_dir == NULL) {
        tmpdir = getenv("TEMP");

        if (tmpdir == NULL) {
            flb_plg_error(in, "unable to find temporary directory (%%TEMP%%).");
            return -1;
        }

        ctx->config_dir = flb_sds_create_size(4096);

        if (ctx->config_dir == NULL) {
            flb_plg_error(in, "unable to allocate config-dir.");
            return -1;
        }
        flb_sds_printf(&ctx->config_dir, "%s" PATH_SEPARATOR "%s", tmpdir, "calyptia-fleet");
    }
#endif

    upstream_flags = FLB_IO_TCP;

    if (in->use_tls) {
        upstream_flags |= FLB_IO_TLS;
    }

    ctx->u = flb_upstream_create(config, in->host.name, in->host.port,
                                 upstream_flags, in->tls);

    if (!ctx->u) {
        flb_plg_error(ctx->ins, "could not initialize upstream");
        flb_free(ctx);
        return -1;
    }

    if (ctx->interval_sec <= 0 && ctx->interval_nsec <= 0) {
        /* Illegal settings. Override them. */
        ctx->interval_sec = atoi(DEFAULT_INTERVAL_SEC);
        ctx->interval_nsec = atoi(DEFAULT_INTERVAL_NSEC);
    }

    if (ctx->interval_sec < atoi(DEFAULT_INTERVAL_SEC)) {
        ctx->interval_sec = atoi(DEFAULT_INTERVAL_SEC);
    }

    /* Set the context */
    flb_input_set_context(in, ctx);

    /* if we load a new configuration then we will be reloaded anyways */
    if (load_fleet_config(ctx) == FLB_TRUE) {
        return 0;
    }

    /* Set our collector based on time */
    ret = flb_input_set_collector_time(in,
                                       in_calyptia_fleet_collect,
                                       ctx->interval_sec,
                                       ctx->interval_nsec,
                                       config);

    if (ret == -1) {
        flb_plg_error(ctx->ins, "could not initialize collector for fleet input plugin");
        flb_free(ctx);
        return -1;
    }

    ctx->collect_fd = ret;

    return 0;
}

static void cb_in_calyptia_fleet_pause(void *data, struct flb_config *config)
{
    struct flb_in_calyptia_fleet_config *ctx = data;
    flb_input_collector_pause(ctx->collect_fd, ctx->ins);
}

static void cb_in_calyptia_fleet_resume(void *data, struct flb_config *config)
{
    struct flb_in_calyptia_fleet_config *ctx = data;
    flb_input_collector_resume(ctx->collect_fd, ctx->ins);
}

static int in_calyptia_fleet_exit(void *data, struct flb_config *config)
{
    (void) *config;
    struct flb_in_calyptia_fleet_config *ctx = (struct flb_in_calyptia_fleet_config *)data;

    flb_input_collector_delete(ctx->collect_fd, ctx->ins);
    flb_upstream_destroy(ctx->u);
    flb_free(ctx);

    return 0;
}

static struct flb_config_map config_map[] = {
    {
     FLB_CONFIG_MAP_STR, "api_key", NULL,
     0, FLB_TRUE, offsetof(struct flb_in_calyptia_fleet_config, api_key),
     "Calyptia Cloud API Key."
    },
    {
     FLB_CONFIG_MAP_STR, "config_dir", DEFAULT_CONFIG_DIR,
     0, FLB_TRUE, offsetof(struct flb_in_calyptia_fleet_config, config_dir),
     "Base path for the configuration directory."
    },
    {
     FLB_CONFIG_MAP_STR, "fleet_id", NULL,
     0, FLB_TRUE, offsetof(struct flb_in_calyptia_fleet_config, fleet_id),
     "Calyptia Fleet ID."
    },
    {
     FLB_CONFIG_MAP_STR, "fleet_name", NULL,
     0, FLB_TRUE, offsetof(struct flb_in_calyptia_fleet_config, fleet_name),
     "Calyptia Fleet Name (used to lookup the fleet ID via the cloud API)."
    },
    {
     FLB_CONFIG_MAP_STR, "machine_id", NULL,
     0, FLB_TRUE, offsetof(struct flb_in_calyptia_fleet_config, machine_id),
     "Agent Machine ID."
    },
    {
      FLB_CONFIG_MAP_INT, "event_fd", "-1",
      0, FLB_TRUE, offsetof(struct flb_in_calyptia_fleet_config, event_fd),
      "Used internally to set the event fd."
    },
    {
      FLB_CONFIG_MAP_INT, "interval_sec", DEFAULT_INTERVAL_SEC,
      0, FLB_TRUE, offsetof(struct flb_in_calyptia_fleet_config, interval_sec),
      "Set the collector interval"
    },
    {
      FLB_CONFIG_MAP_INT, "interval_nsec", DEFAULT_INTERVAL_NSEC,
      0, FLB_TRUE, offsetof(struct flb_in_calyptia_fleet_config, interval_nsec),
      "Set the collector interval (nanoseconds)"
    },
    /* EOF */
    {0}
};

/* Plugin reference */
struct flb_input_plugin in_calyptia_fleet_plugin = {
    .name         = "calyptia_fleet",
    .description  = "Calyptia Fleet Input",
    .cb_init      = in_calyptia_fleet_init,
    .cb_pre_run   = NULL,
    .cb_collect   = in_calyptia_fleet_collect,
    .cb_resume    = cb_in_calyptia_fleet_resume,
    .cb_pause     = cb_in_calyptia_fleet_pause,
    .cb_flush_buf = NULL,
    .cb_exit      = in_calyptia_fleet_exit,
    .config_map   = config_map,
    .flags        = FLB_INPUT_NET|FLB_INPUT_CORO|FLB_IO_OPT_TLS|FLB_INPUT_PRIVATE
};