summaryrefslogtreecommitdiffstats
path: root/fluent-bit/plugins/out_loki/loki.c
blob: d93a3f9aad62b5d30daf4a3c0d01f7f5cbbfb0a5 (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
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*  Fluent Bit
 *  ==========
 *  Copyright (C) 2015-2022 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 <fluent-bit/flb_output_plugin.h>
#include <fluent-bit/flb_version.h>
#include <fluent-bit/flb_pack.h>
#include <fluent-bit/flb_utils.h>
#include <fluent-bit/flb_time.h>
#include <fluent-bit/flb_http_client.h>
#include <fluent-bit/flb_ra_key.h>
#include <fluent-bit/flb_thread_storage.h>
#include <fluent-bit/record_accessor/flb_ra_parser.h>
#include <fluent-bit/flb_mp.h>
#include <fluent-bit/flb_log_event_decoder.h>
#include <fluent-bit/flb_gzip.h>

#include <ctype.h>
#include <sys/stat.h>

#include "loki.h"

struct flb_loki_dynamic_tenant_id_entry {
    flb_sds_t value;
    struct cfl_list _head;
};

pthread_once_t initialization_guard = PTHREAD_ONCE_INIT;

FLB_TLS_DEFINE(struct flb_loki_dynamic_tenant_id_entry,
               thread_local_tenant_id);

void initialize_thread_local_storage()
{
    FLB_TLS_INIT(thread_local_tenant_id);
}

static struct flb_loki_dynamic_tenant_id_entry *dynamic_tenant_id_create() {
    struct flb_loki_dynamic_tenant_id_entry *entry;

    entry = (struct flb_loki_dynamic_tenant_id_entry *) \
        flb_calloc(1, sizeof(struct flb_loki_dynamic_tenant_id_entry));

    if (entry != NULL) {
        entry->value = NULL;

        cfl_list_entry_init(&entry->_head);
    }

    return entry;
}

static void dynamic_tenant_id_destroy(struct flb_loki_dynamic_tenant_id_entry *entry) {
    if (entry != NULL) {
        if (entry->value != NULL) {
            flb_sds_destroy(entry->value);

            entry->value = NULL;
        }

        if (!cfl_list_entry_is_orphan(&entry->_head)) {
            cfl_list_del(&entry->_head);
        }

        flb_free(entry);
    }
}

static void flb_loki_kv_init(struct mk_list *list)
{
    mk_list_init(list);
}

static inline void safe_sds_cat(flb_sds_t *buf, const char *str, int len)
{
    flb_sds_t tmp;

    tmp = flb_sds_cat(*buf, str, len);
    if (tmp) {
        *buf = tmp;
    }
}

static inline void normalize_cat(struct flb_ra_parser *rp, flb_sds_t *name)
{
    int sub;
    int len;
    char tmp[64];
    struct mk_list *s_head;
    struct flb_ra_key *key;
    struct flb_ra_subentry *entry;

    /* Iterate record accessor keys */
    key = rp->key;
    if (rp->type == FLB_RA_PARSER_STRING) {
        safe_sds_cat(name, key->name, flb_sds_len(key->name));
    }
    else if (rp->type == FLB_RA_PARSER_KEYMAP) {
        safe_sds_cat(name, key->name, flb_sds_len(key->name));
        if (mk_list_size(key->subkeys) > 0) {
            safe_sds_cat(name, "_", 1);
        }

        sub = 0;
        mk_list_foreach(s_head, key->subkeys) {
            entry = mk_list_entry(s_head, struct flb_ra_subentry, _head);

            if (sub > 0) {
                safe_sds_cat(name, "_", 1);
            }
            if (entry->type == FLB_RA_PARSER_STRING) {
                safe_sds_cat(name, entry->str, flb_sds_len(entry->str));
            }
            else if (entry->type == FLB_RA_PARSER_ARRAY_ID) {
                len = snprintf(tmp, sizeof(tmp) -1, "%d",
                               entry->array_id);
                safe_sds_cat(name, tmp, len);
            }
            sub++;
        }
    }
}

static flb_sds_t normalize_ra_key_name(struct flb_loki *ctx,
                                       struct flb_record_accessor *ra)
{
    int c = 0;
    flb_sds_t name;
    struct mk_list *head;
    struct flb_ra_parser *rp;

    name = flb_sds_create_size(128);
    if (!name) {
        return NULL;
    }

    mk_list_foreach(head, &ra->list) {
        rp = mk_list_entry(head, struct flb_ra_parser, _head);
        if (c > 0) {
            flb_sds_cat(name, "_", 1);
        }
        normalize_cat(rp, &name);
        c++;
    }

    return name;
}

void flb_loki_kv_destroy(struct flb_loki_kv *kv)
{
    /* destroy key and value */
    flb_sds_destroy(kv->key);
    if (kv->val_type == FLB_LOKI_KV_STR) {
        flb_sds_destroy(kv->str_val);
    }
    else if (kv->val_type == FLB_LOKI_KV_RA) {
        flb_ra_destroy(kv->ra_val);
    }

    if (kv->ra_key) {
        flb_ra_destroy(kv->ra_key);
    }

    if (kv->key_normalized) {
        flb_sds_destroy(kv->key_normalized);
    }

    flb_free(kv);
}

int flb_loki_kv_append(struct flb_loki *ctx, char *key, char *val)
{
    int ra_count = 0;
    int k_len;
    int ret;
    struct flb_loki_kv *kv;

    if (!key) {
        return -1;
    }

    if (!val && key[0] != '$') {
        return -1;
    }

    kv = flb_calloc(1, sizeof(struct flb_loki_kv));
    if (!kv) {
        flb_errno();
        return -1;
    }

    k_len = strlen(key);
    if (key[0] == '$' && k_len >= 2 && isdigit(key[1])) {
        flb_plg_error(ctx->ins,
                      "key name for record accessor cannot start with a number: %s",
                      key);
        flb_free(kv);
        return -1;
    }

    kv->key = flb_sds_create(key);
    if (!kv->key) {
        flb_free(kv);
        return -1;
    }

    /*
     * If the key starts with a '$', it means its a record accessor pattern and
     * the key value pair will be formed using the key name and it proper value.
     */
    if (key[0] == '$' && val == NULL) {
        kv->ra_key = flb_ra_create(key, FLB_TRUE);
        if (!kv->ra_key) {
            flb_plg_error(ctx->ins,
                          "invalid key record accessor pattern for key '%s'",
                          key);
            flb_loki_kv_destroy(kv);
            return -1;
        }

        /* Normalize 'key name' using record accessor pattern */
        kv->key_normalized = normalize_ra_key_name(ctx, kv->ra_key);
        if (!kv->key_normalized) {
            flb_plg_error(ctx->ins,
                          "could not normalize key pattern name '%s'\n",
                          kv->ra_key->pattern);
            flb_loki_kv_destroy(kv);
            return -1;
        }
        /* remove record keys placed as stream labels via 'labels' and 'label_keys' */
        ret = flb_slist_add(&ctx->remove_keys_derived, key);
        if (ret < 0) {
            flb_loki_kv_destroy(kv);
            return -1;
        }
        ra_count++;
    }
    else if (val[0] == '$') {
        /* create a record accessor context */
        kv->val_type = FLB_LOKI_KV_RA;
        kv->ra_val = flb_ra_create(val, FLB_TRUE);
        if (!kv->ra_val) {
            flb_plg_error(ctx->ins,
                          "invalid record accessor pattern for key '%s': %s",
                          key, val);
            flb_loki_kv_destroy(kv);
            return -1;
        }
        ret = flb_slist_add(&ctx->remove_keys_derived, val);
        if (ret < 0) {
            flb_loki_kv_destroy(kv);
            return -1;
        }
        ra_count++;
    }
    else {
        kv->val_type = FLB_LOKI_KV_STR;
        kv->str_val = flb_sds_create(val);
        if (!kv->str_val) {
            flb_loki_kv_destroy(kv);
            return -1;
        }
    }
    mk_list_add(&kv->_head, &ctx->labels_list);

    /* return the number of record accessor values */
    return ra_count;
}

static void flb_loki_kv_exit(struct flb_loki *ctx)
{
    struct mk_list *tmp;
    struct mk_list *head;
    struct flb_loki_kv *kv;

    mk_list_foreach_safe(head, tmp, &ctx->labels_list) {
        kv = mk_list_entry(head, struct flb_loki_kv, _head);

        /* unlink and destroy */
        mk_list_del(&kv->_head);
        flb_loki_kv_destroy(kv);
    }
}

/* Pack a label key, it also perform sanitization of the characters */
static int pack_label_key(msgpack_packer *mp_pck, char *key, int key_len)
{
    int i;
    int k_len = key_len;
    int is_digit = FLB_FALSE;
    char *p;
    size_t prev_size;

    /* Normalize key name using the packed value */
    if (isdigit(*key)) {
        is_digit = FLB_TRUE;
        k_len++;
    }

    /* key: pack the length */
    msgpack_pack_str(mp_pck, k_len);
    if (is_digit) {
        msgpack_pack_str_body(mp_pck, "_", 1);
    }

    /* save the current offset */
    prev_size = ((msgpack_sbuffer *) mp_pck->data)->size;

    /* Pack the key name */
    msgpack_pack_str_body(mp_pck, key, key_len);

    /* 'p' will point to where the key was written */
    p = (char *) (((msgpack_sbuffer*) mp_pck->data)->data + prev_size);

    /* and sanitize the key characters */
    for (i = 0; i < key_len; i++) {
        if (!isalnum(p[i]) && p[i] != '_') {
            p[i] = '_';
        }
    }

    return 0;
}

static flb_sds_t pack_labels(struct flb_loki *ctx,
                             msgpack_packer *mp_pck,
                             char *tag, int tag_len,
                             msgpack_object *map)
{
    int i;
    flb_sds_t ra_val;
    struct mk_list *head;
    struct flb_ra_value *rval = NULL;
    struct flb_loki_kv *kv;
    msgpack_object k;
    msgpack_object v;
    struct flb_mp_map_header mh;


    /* Initialize dynamic map header */
    flb_mp_map_header_init(&mh, mp_pck);

    mk_list_foreach(head, &ctx->labels_list) {
        kv = mk_list_entry(head, struct flb_loki_kv, _head);

        /* record accessor key/value pair */
        if (kv->ra_key != NULL && kv->ra_val == NULL) {
            ra_val = flb_ra_translate(kv->ra_key, tag, tag_len, *(map), NULL);
            if (!ra_val || flb_sds_len(ra_val) == 0) {
                /* if no value is retruned or if it's empty, just skip it */
                flb_plg_warn(ctx->ins,
                             "empty record accessor key translation for pattern: %s",
                             kv->ra_key->pattern);
            }
            else {
                /* Pack the key and value */
                flb_mp_map_header_append(&mh);

                /* We skip the first '$' character since it won't be valid in Loki */
                pack_label_key(mp_pck, kv->key_normalized,
                               flb_sds_len(kv->key_normalized));

                msgpack_pack_str(mp_pck, flb_sds_len(ra_val));
                msgpack_pack_str_body(mp_pck, ra_val, flb_sds_len(ra_val));
            }

            if (ra_val) {
                flb_sds_destroy(ra_val);
            }
            continue;
        }

        /*
         * The code is a bit duplicated to be able to manage the exception of an
         * invalid or empty value, on that case the k/v is skipped.
         */
        if (kv->val_type == FLB_LOKI_KV_STR) {
            flb_mp_map_header_append(&mh);
            msgpack_pack_str(mp_pck, flb_sds_len(kv->key));
            msgpack_pack_str_body(mp_pck, kv->key, flb_sds_len(kv->key));
            msgpack_pack_str(mp_pck, flb_sds_len(kv->str_val));
            msgpack_pack_str_body(mp_pck, kv->str_val, flb_sds_len(kv->str_val));
        }
        else if (kv->val_type == FLB_LOKI_KV_RA) {
            /* record accessor type */
            ra_val = flb_ra_translate(kv->ra_val, tag, tag_len, *(map), NULL);
            if (!ra_val || flb_sds_len(ra_val) == 0) {
                flb_plg_debug(ctx->ins, "could not translate record accessor");
            }
            else {
                flb_mp_map_header_append(&mh);
                msgpack_pack_str(mp_pck, flb_sds_len(kv->key));
                msgpack_pack_str_body(mp_pck, kv->key, flb_sds_len(kv->key));
                msgpack_pack_str(mp_pck, flb_sds_len(ra_val));
                msgpack_pack_str_body(mp_pck, ra_val, flb_sds_len(ra_val));
            }

            if (ra_val) {
                flb_sds_destroy(ra_val);
            }
        }
    }

    if (ctx->auto_kubernetes_labels == FLB_TRUE) {
        rval = flb_ra_get_value_object(ctx->ra_k8s, *map);
        if (rval && rval->o.type == MSGPACK_OBJECT_MAP) {
            for (i = 0; i < rval->o.via.map.size; i++) {
                k = rval->o.via.map.ptr[i].key;
                v = rval->o.via.map.ptr[i].val;

                if (k.type != MSGPACK_OBJECT_STR || v.type != MSGPACK_OBJECT_STR) {
                    continue;
                }

                /* append the key/value pair */
                flb_mp_map_header_append(&mh);

                /* Pack key */
                pack_label_key(mp_pck, (char *) k.via.str.ptr, k.via.str.size);

                /* Pack the value */
                msgpack_pack_str(mp_pck, v.via.str.size);
                msgpack_pack_str_body(mp_pck, v.via.str.ptr,  v.via.str.size);
            }
        }

        if (rval) {
            flb_ra_key_value_destroy(rval);
        }
    }

    /* Check if we added any label, if no one has been set, set the defaul 'job' */
    if (mh.entries == 0) {
        /* pack the default entry */
        flb_mp_map_header_append(&mh);
        msgpack_pack_str(mp_pck, 3);
        msgpack_pack_str_body(mp_pck, "job", 3);
        msgpack_pack_str(mp_pck, 10);
        msgpack_pack_str_body(mp_pck, "fluent-bit", 10);
    }
    flb_mp_map_header_end(&mh);
    return 0;
}

static int create_label_map_entry(struct flb_loki *ctx,
                                  struct flb_sds_list *list, msgpack_object *val, int *ra_used)
{
    msgpack_object key;
    flb_sds_t label_key;
    flb_sds_t val_str;
    int i;
    int len;
    int ret;

    if (ctx == NULL || list == NULL || val == NULL || ra_used == NULL) {
        return -1;
    }

    switch (val->type) {
    case MSGPACK_OBJECT_STR:
        label_key = flb_sds_create_len(val->via.str.ptr, val->via.str.size);
        if (label_key == NULL) {
            flb_errno();
            return -1;
        }

        val_str = flb_ra_create_str_from_list(list);
        if (val_str == NULL) {
            flb_plg_error(ctx->ins, "[%s] flb_ra_create_from_list failed", __FUNCTION__);
            flb_sds_destroy(label_key);
            return -1;
        }

        /* for debugging
          printf("label_key=%s val_str=%s\n", label_key, val_str);
         */

        ret = flb_loki_kv_append(ctx, label_key, val_str);
        flb_sds_destroy(label_key);
        flb_sds_destroy(val_str);
        if (ret == -1) {
            return -1;
        }
        *ra_used = *ra_used + 1;

        break;
    case MSGPACK_OBJECT_MAP:
        len = val->via.map.size;
        for (i=0; i<len; i++) {
            key = val->via.map.ptr[i].key;
            if (key.type != MSGPACK_OBJECT_STR) {
                flb_plg_error(ctx->ins, "[%s] key is not string", __FUNCTION__);
                return -1;
            }
            ret = flb_sds_list_add(list, (char*)key.via.str.ptr, key.via.str.size);
            if (ret < 0) {
                flb_plg_error(ctx->ins, "[%s] flb_sds_list_add failed", __FUNCTION__);
                return -1;
            }

            ret = create_label_map_entry(ctx, list, &val->via.map.ptr[i].val, ra_used);
            if (ret < 0) {
                return -1;
            }

            ret = flb_sds_list_del_last_entry(list);
            if (ret < 0) {
                flb_plg_error(ctx->ins, "[%s] flb_sds_list_del_last_entry failed", __FUNCTION__);
                return -1;
            }
        }

        break;
    default:
        flb_plg_error(ctx->ins, "[%s] value type is not str or map. type=%d", __FUNCTION__, val->type);
        return -1;
    }
    return 0;
}

static int create_label_map_entries(struct flb_loki *ctx,
                                    char *msgpack_buf, size_t msgpack_size, int *ra_used)
{
    struct flb_sds_list *list = NULL;
    msgpack_unpacked result;
    size_t off = 0;
    int i;
    int len;
    int ret;
    msgpack_object key;

    if (ctx == NULL || msgpack_buf == NULL || ra_used == NULL) {
        return -1;
    }

    msgpack_unpacked_init(&result);
    while(msgpack_unpack_next(&result, msgpack_buf, msgpack_size, &off) == MSGPACK_UNPACK_SUCCESS) {
        if (result.data.type != MSGPACK_OBJECT_MAP) {
            flb_plg_error(ctx->ins, "[%s] data type is not map", __FUNCTION__);
            msgpack_unpacked_destroy(&result);
            return -1;
        }

        len = result.data.via.map.size;
        for (i=0; i<len; i++) {
            list = flb_sds_list_create();
            if (list == NULL) {
                flb_plg_error(ctx->ins, "[%s] flb_sds_list_create failed", __FUNCTION__);
                msgpack_unpacked_destroy(&result);
                return -1;
            }
            key = result.data.via.map.ptr[i].key;
            if (key.type != MSGPACK_OBJECT_STR) {
                flb_plg_error(ctx->ins, "[%s] key is not string", __FUNCTION__);
                flb_sds_list_destroy(list);
                msgpack_unpacked_destroy(&result);
                return -1;
            }

            ret = flb_sds_list_add(list, (char*)key.via.str.ptr, key.via.str.size);
            if (ret < 0) {
                flb_plg_error(ctx->ins, "[%s] flb_sds_list_add failed", __FUNCTION__);
                flb_sds_list_destroy(list);
                msgpack_unpacked_destroy(&result);
                return -1;
            }

            ret = create_label_map_entry(ctx, list, &result.data.via.map.ptr[i].val, ra_used);
            if (ret < 0) {
                flb_plg_error(ctx->ins, "[%s] create_label_map_entry failed", __FUNCTION__);
                flb_sds_list_destroy(list);
                msgpack_unpacked_destroy(&result);
                return -1;
            }

            flb_sds_list_destroy(list);
            list = NULL;
        }
    }

    msgpack_unpacked_destroy(&result);

    return 0;
}

static int read_label_map_path_file(struct flb_output_instance *ins, flb_sds_t path,
                                    char **out_buf, size_t *out_size)
{
    int ret;
    int root_type;
    char *buf = NULL;
    char *msgp_buf = NULL;
    FILE *fp = NULL;
    struct stat st;
    size_t file_size;
    size_t ret_size;

    ret = access(path, R_OK);
    if (ret < 0) {
        flb_errno();
        flb_plg_error(ins, "can't access %s", path);
        return -1;
    }

    ret = stat(path, &st);
    if (ret < 0) {
        flb_errno();
        flb_plg_error(ins, "stat failed %s", path);
        return -1;
    }
    file_size = st.st_size;

    fp = fopen(path, "r");
    if (fp == NULL) {
        flb_plg_error(ins, "can't open %s", path);
        return -1;
    }

    buf = flb_malloc(file_size);
    if (buf == NULL) {
        flb_plg_error(ins, "malloc failed");
        fclose(fp);
        return -1;
    }

    ret_size = fread(buf, 1, file_size, fp);
    if (ret_size < file_size && feof(fp) != 0) {
        flb_plg_error(ins, "fread failed");
        fclose(fp);
        flb_free(buf);
        return -1;
    }

    ret = flb_pack_json(buf, file_size, &msgp_buf, &ret_size, &root_type, NULL);
    if (ret < 0) {
        flb_plg_error(ins, "flb_pack_json failed");
        fclose(fp);
        flb_free(buf);
        return -1;
    }

    *out_buf = msgp_buf;
    *out_size = ret_size;

    fclose(fp);
    flb_free(buf);
    return 0;
}

static int load_label_map_path(struct flb_loki *ctx, flb_sds_t path, int *ra_used)
{
    int ret;
    char *msgpack_buf = NULL;
    size_t msgpack_size;

    ret = read_label_map_path_file(ctx->ins, path, &msgpack_buf, &msgpack_size);
    if (ret < 0) {
        return -1;
    }

    ret = create_label_map_entries(ctx, msgpack_buf, msgpack_size, ra_used);
    if (ret < 0) {
        flb_free(msgpack_buf);
        return -1;
    }

    if (msgpack_buf != NULL) {
        flb_free(msgpack_buf);
    }

    return 0;
}

static int parse_labels(struct flb_loki *ctx)
{
    int ret;
    int ra_used = 0;
    char *p;
    flb_sds_t key;
    flb_sds_t val;
    struct mk_list *head;
    struct flb_slist_entry *entry;

    flb_loki_kv_init(&ctx->labels_list);

    if (ctx->labels) {
        mk_list_foreach(head, ctx->labels) {
            entry = mk_list_entry(head, struct flb_slist_entry, _head);

            /* record accessor label key ? */
            if (entry->str[0] == '$') {
                ret = flb_loki_kv_append(ctx, entry->str, NULL);
                if (ret == -1) {
                    return -1;
                }
                else if (ret > 0) {
                    ra_used++;
                }
                continue;
            }

            p = strchr(entry->str, '=');
            if (!p) {
                flb_plg_error(ctx->ins, "invalid key value pair on '%s'",
                              entry->str);
                return -1;
            }

            key = flb_sds_create_size((p - entry->str) + 1);
            flb_sds_cat(key, entry->str, p - entry->str);
            val = flb_sds_create(p + 1);
            if (!key) {
                flb_plg_error(ctx->ins,
                              "invalid key value pair on '%s'",
                              entry->str);
                return -1;
            }
            if (!val || flb_sds_len(val) == 0) {
                flb_plg_error(ctx->ins,
                              "invalid key value pair on '%s'",
                              entry->str);
                flb_sds_destroy(key);
                return -1;
            }

            ret = flb_loki_kv_append(ctx, key, val);
            flb_sds_destroy(key);
            flb_sds_destroy(val);

            if (ret == -1) {
                return -1;
            }
            else if (ret > 0) {
                ra_used++;
            }
        }
    }

    /* Append label keys set in the configuration */
    if (ctx->label_keys) {
        mk_list_foreach(head, ctx->label_keys) {
            entry = mk_list_entry(head, struct flb_slist_entry, _head);
            if (entry->str[0] != '$') {
                flb_plg_error(ctx->ins,
                              "invalid label key, the name must start with '$'");
                return -1;
            }

            ret = flb_loki_kv_append(ctx, entry->str, NULL);
            if (ret == -1) {
                return -1;
            }
            else if (ret > 0) {
                ra_used++;
            }
        }
    }

    /* label_map_path */
    if (ctx->label_map_path) {
        ret = load_label_map_path(ctx, ctx->label_map_path, &ra_used);
        if (ret != 0) {
            flb_plg_error(ctx->ins, "failed to load label_map_path");
        }
    }

    if (ctx->auto_kubernetes_labels == FLB_TRUE) {
        ctx->ra_k8s = flb_ra_create("$kubernetes['labels']", FLB_TRUE);
        if (!ctx->ra_k8s) {
            flb_plg_error(ctx->ins,
                          "could not create record accessor for Kubernetes labels");
            return -1;
        }
    }

    /*
     * If the variable 'ra_used' is greater than zero, means that record accessor is
     * being used to compose the stream labels.
     */
    ctx->ra_used = ra_used;
    return 0;
}

static int key_is_duplicated(struct mk_list *list, char *str, int len)
{
    struct mk_list *head;
    struct flb_slist_entry *entry;

    mk_list_foreach(head, list) {
        entry = mk_list_entry(head, struct flb_slist_entry, _head);
        if (flb_sds_len(entry->str) == len &&
            strncmp(entry->str, str, len) == 0) {
            return FLB_TRUE;
        }
    }

    return FLB_FALSE;
}

static int prepare_remove_keys(struct flb_loki *ctx)
{
    int ret;
    int len;
    int size;
    char *tmp;
    struct mk_list *head;
    struct flb_slist_entry *entry;
    struct mk_list *patterns;

    patterns = &ctx->remove_keys_derived;

    /* Add remove keys set in the configuration */
    if (ctx->remove_keys) {
        mk_list_foreach(head, ctx->remove_keys) {
            entry = mk_list_entry(head, struct flb_slist_entry, _head);

            if (entry->str[0] != '$') {
                tmp = flb_malloc(flb_sds_len(entry->str) + 2);
                if (!tmp) {
                    flb_errno();
                    continue;
                }
                else {
                    tmp[0] = '$';
                    len = flb_sds_len(entry->str);
                    memcpy(tmp + 1, entry->str, len);
                    tmp[len + 1] = '\0';
                    len++;
                }
            }
            else {
                tmp = entry->str;
                len = flb_sds_len(entry->str);
            }

            ret = key_is_duplicated(patterns, tmp, len);
            if (ret == FLB_TRUE) {
                if (entry->str != tmp) {
                    flb_free(tmp);
                }
                continue;
            }

            ret = flb_slist_add_n(patterns, tmp, len);
            if (entry->str != tmp) {
                flb_free(tmp);
            }
            if (ret < 0) {
                return -1;
            }
        }
        size = mk_list_size(patterns);
        flb_plg_debug(ctx->ins, "remove_mpa size: %d", size);
        if (size > 0) {
            ctx->remove_mpa = flb_mp_accessor_create(patterns);
            if (ctx->remove_mpa == NULL) {
                return -1;
            }
        }
    }

    return 0;
}

static void loki_config_destroy(struct flb_loki *ctx)
{
    if (ctx->u) {
        flb_upstream_destroy(ctx->u);
    }

    if (ctx->ra_k8s) {
        flb_ra_destroy(ctx->ra_k8s);
    }
    if (ctx->ra_tenant_id_key) {
        flb_ra_destroy(ctx->ra_tenant_id_key);
    }

    if (ctx->remove_mpa) {
        flb_mp_accessor_destroy(ctx->remove_mpa);
    }
    flb_slist_destroy(&ctx->remove_keys_derived);

    flb_loki_kv_exit(ctx);
    flb_free(ctx);
}

static struct flb_loki *loki_config_create(struct flb_output_instance *ins,
                                           struct flb_config *config)
{
    int ret;
    int io_flags = 0;
    struct flb_loki *ctx;
    struct flb_upstream *upstream;
    char *compress;

    /* Create context */
    ctx = flb_calloc(1, sizeof(struct flb_loki));
    if (!ctx) {
        flb_errno();
        return NULL;
    }
    ctx->ins = ins;
    flb_loki_kv_init(&ctx->labels_list);

    /* Register context with plugin instance */
    flb_output_set_context(ins, ctx);

    /* Set networking defaults */
    flb_output_net_default(FLB_LOKI_HOST, FLB_LOKI_PORT, ins);

    /* Load config map */
    ret = flb_output_config_map_set(ins, (void *) ctx);
    if (ret == -1) {
        return NULL;
    }

    /* Initialize final remove_keys list */
    flb_slist_create(&ctx->remove_keys_derived);

    /* Parse labels */
    ret = parse_labels(ctx);
    if (ret == -1) {
        return NULL;
    }

    /* Load remove keys */
    ret = prepare_remove_keys(ctx);
    if (ret == -1) {
        return NULL;
    }

    /* tenant_id_key */
    if (ctx->tenant_id_key_config) {
        ctx->ra_tenant_id_key = flb_ra_create(ctx->tenant_id_key_config, FLB_FALSE);
        if (!ctx->ra_tenant_id_key) {
            flb_plg_error(ctx->ins,
                          "could not create record accessor for Tenant ID");
        }
    }

    /* Compress (gzip) */
    compress = (char *) flb_output_get_property("compress", ins);
    ctx->compress_gzip = FLB_FALSE;
    if (compress) {
        if (strcasecmp(compress, "gzip") == 0) {
            ctx->compress_gzip = FLB_TRUE;
        }
    }

    /* Line Format */
    if (strcasecmp(ctx->line_format, "json") == 0) {
        ctx->out_line_format = FLB_LOKI_FMT_JSON;
    }
    else if (strcasecmp(ctx->line_format, "key_value") == 0) {
        ctx->out_line_format = FLB_LOKI_FMT_KV;
    }
    else {
        flb_plg_error(ctx->ins, "invalid 'line_format' value: %s",
                      ctx->line_format);
        return NULL;
    }

    /* use TLS ? */
    if (ins->use_tls == FLB_TRUE) {
        io_flags = FLB_IO_TLS;
    }
    else {
        io_flags = FLB_IO_TCP;
    }

    if (ins->host.ipv6 == FLB_TRUE) {
        io_flags |= FLB_IO_IPV6;
    }

    /* Create Upstream connection context */
    upstream = flb_upstream_create(config,
                                   ins->host.name,
                                   ins->host.port,
                                   io_flags,
                                   ins->tls);
    if (!upstream) {
        return NULL;
    }
    ctx->u = upstream;
    flb_output_upstream_set(ctx->u, ins);
    ctx->tcp_port = ins->host.port;
    ctx->tcp_host = ins->host.name;

    return ctx;
}

/*
 * Convert struct flb_tm timestamp value to nanoseconds and then it pack it as
 * a string.
 */
static void pack_timestamp(msgpack_packer *mp_pck, struct flb_time *tms)
{
    int len;
    char buf[64];
    uint64_t nanosecs;

    /* convert to nanoseconds */
    nanosecs = flb_time_to_nanosec(tms);

    /* format as a string */
    len = snprintf(buf, sizeof(buf) - 1, "%" PRIu64, nanosecs);

    /* pack the value */
    msgpack_pack_str(mp_pck, len);
    msgpack_pack_str_body(mp_pck, buf, len);
}


static void pack_format_line_value(flb_sds_t *buf, msgpack_object *val)
{
    int i;
    int len;
    char temp[512];
    msgpack_object k;
    msgpack_object v;

    if (val->type == MSGPACK_OBJECT_STR) {
        safe_sds_cat(buf, "\"", 1);
        safe_sds_cat(buf, val->via.str.ptr, val->via.str.size);
        safe_sds_cat(buf, "\"", 1);
    }
    else if (val->type == MSGPACK_OBJECT_NIL) {
        safe_sds_cat(buf, "null", 4);
    }
    else if (val->type == MSGPACK_OBJECT_BOOLEAN) {
        if (val->via.boolean) {
            safe_sds_cat(buf, "true", 4);
        }
        else {
            safe_sds_cat(buf, "false", 5);
        }
    }
    else if (val->type == MSGPACK_OBJECT_POSITIVE_INTEGER) {
        len = snprintf(temp, sizeof(temp)-1, "%"PRIu64, val->via.u64);
        safe_sds_cat(buf, temp, len);
    }
    else if (val->type == MSGPACK_OBJECT_NEGATIVE_INTEGER) {
        len = snprintf(temp, sizeof(temp)-1, "%"PRId64, val->via.i64);
        safe_sds_cat(buf, temp, len);
    }
    else if (val->type == MSGPACK_OBJECT_FLOAT32 ||
             val->type == MSGPACK_OBJECT_FLOAT64) {
        if (val->via.f64 == (double)(long long int) val->via.f64) {
            len = snprintf(temp, sizeof(temp)-1, "%.1f", val->via.f64);
        }
        else {
            len = snprintf(temp, sizeof(temp)-1, "%.16g", val->via.f64);
        }
        safe_sds_cat(buf, temp, len);
    }
    else if (val->type == MSGPACK_OBJECT_ARRAY) {
        safe_sds_cat(buf, "\"[", 2);
        for (i = 0; i < val->via.array.size; i++) {
            v = val->via.array.ptr[i];
            if (i > 0) {
                safe_sds_cat(buf, " ", 1);
            }
            pack_format_line_value(buf, &v);
        }
        safe_sds_cat(buf, "]\"", 2);
    }
    else if (val->type == MSGPACK_OBJECT_MAP) {
        safe_sds_cat(buf, "\"map[", 5);

        for (i = 0; i < val->via.map.size; i++) {
            k = val->via.map.ptr[i].key;
            v = val->via.map.ptr[i].val;

            if (k.type != MSGPACK_OBJECT_STR) {
                continue;
            }

            if (i > 0) {
                safe_sds_cat(buf, " ", 1);
            }

            safe_sds_cat(buf, k.via.str.ptr, k.via.str.size);
            safe_sds_cat(buf, ":", 1);
            pack_format_line_value(buf, &v);
        }
        safe_sds_cat(buf, "]\"", 2);
    }
    else {

        return;
    }
}

// seek tenant id from map and set it to dynamic_tenant_id
static int get_tenant_id_from_record(struct flb_loki *ctx, msgpack_object *map,
                                     flb_sds_t *dynamic_tenant_id)
{
    struct flb_ra_value *rval = NULL;
    flb_sds_t tmp_str;
    int cmp_len;

    rval = flb_ra_get_value_object(ctx->ra_tenant_id_key, *map);

    if (rval == NULL) {
        flb_plg_warn(ctx->ins, "the value of %s is missing",
                     ctx->tenant_id_key_config);
        return -1;
    }
    else if (rval->o.type != MSGPACK_OBJECT_STR) {
        flb_plg_warn(ctx->ins, "the value of %s is not string",
                     ctx->tenant_id_key_config);
        flb_ra_key_value_destroy(rval);
        return -1;
    }

    tmp_str = flb_sds_create_len(rval->o.via.str.ptr,
                                 rval->o.via.str.size);
    if (tmp_str == NULL) {
        flb_plg_warn(ctx->ins, "cannot create tenant ID string from record");
        flb_ra_key_value_destroy(rval);
        return -1;
    }

    // check if already dynamic_tenant_id is set.
    if (*dynamic_tenant_id != NULL) {
        cmp_len = flb_sds_len(*dynamic_tenant_id);

        if ((rval->o.via.str.size == cmp_len) &&
            flb_sds_cmp(tmp_str, *dynamic_tenant_id, cmp_len) == 0) {
            // tenant_id is same. nothing to do.
            flb_ra_key_value_destroy(rval);
            flb_sds_destroy(tmp_str);

            return 0;
        }

        flb_plg_warn(ctx->ins, "Tenant ID is overwritten %s -> %s",
                     *dynamic_tenant_id, tmp_str);

        flb_sds_destroy(*dynamic_tenant_id);
    }

    // this sds will be released after setting http header.
    *dynamic_tenant_id = tmp_str;
    flb_plg_debug(ctx->ins, "Tenant ID is %s", *dynamic_tenant_id);

    flb_ra_key_value_destroy(rval);
    return 0;
}

static int pack_record(struct flb_loki *ctx,
                       msgpack_packer *mp_pck, msgpack_object *rec,
                       flb_sds_t *dynamic_tenant_id)
{
    int i;
    int skip = 0;
    int len;
    int ret;
    int size_hint = 1024;
    char *line;
    flb_sds_t buf;
    msgpack_object key;
    msgpack_object val;
    char *tmp_sbuf_data = NULL;
    size_t tmp_sbuf_size;
    msgpack_unpacked mp_buffer;
    size_t off = 0;

    /*
     * Get tenant id from record before removing keys.
     * https://github.com/fluent/fluent-bit/issues/6207
     */
    if (ctx->ra_tenant_id_key && rec->type == MSGPACK_OBJECT_MAP) {
        get_tenant_id_from_record(ctx, rec, dynamic_tenant_id);
    }

    /* Remove keys in remove_keys */
    msgpack_unpacked_init(&mp_buffer);
    if (ctx->remove_mpa) {
        ret = flb_mp_accessor_keys_remove(ctx->remove_mpa, rec,
                                          (void *) &tmp_sbuf_data, &tmp_sbuf_size);
        if (ret == FLB_TRUE) {
            ret = msgpack_unpack_next(&mp_buffer, tmp_sbuf_data, tmp_sbuf_size, &off);
            if (ret != MSGPACK_UNPACK_SUCCESS) {
                flb_free(tmp_sbuf_data);
                msgpack_unpacked_destroy(&mp_buffer);
                return -1;
            }
            rec = &mp_buffer.data;
        }
    }

    /* Drop single key */
    if (ctx->drop_single_key == FLB_TRUE && rec->type == MSGPACK_OBJECT_MAP && rec->via.map.size == 1) {
        if (ctx->out_line_format == FLB_LOKI_FMT_JSON) {
            rec = &rec->via.map.ptr[0].val;
        } else if (ctx->out_line_format == FLB_LOKI_FMT_KV) {
            val = rec->via.map.ptr[0].val;

            if (val.type == MSGPACK_OBJECT_STR) {
                msgpack_pack_str(mp_pck, val.via.str.size);
                msgpack_pack_str_body(mp_pck, val.via.str.ptr, val.via.str.size);
            } else {
                buf = flb_sds_create_size(size_hint);
                if (!buf) {
                    msgpack_unpacked_destroy(&mp_buffer);
                    if (tmp_sbuf_data) {
                        flb_free(tmp_sbuf_data);
                    }
                    return -1;
                }
                pack_format_line_value(&buf, &val);
                msgpack_pack_str(mp_pck, flb_sds_len(buf));
                msgpack_pack_str_body(mp_pck, buf, flb_sds_len(buf));
                flb_sds_destroy(buf);
            }

            msgpack_unpacked_destroy(&mp_buffer);
            if (tmp_sbuf_data) {
                flb_free(tmp_sbuf_data);
            }

            return 0;
        }
    }

    if (ctx->out_line_format == FLB_LOKI_FMT_JSON) {
        line = flb_msgpack_to_json_str(size_hint, rec);
        if (!line) {
            if (tmp_sbuf_data) {
                flb_free(tmp_sbuf_data);
            }
            msgpack_unpacked_destroy(&mp_buffer);
            return -1;
        }
        len = strlen(line);
        msgpack_pack_str(mp_pck, len);
        msgpack_pack_str_body(mp_pck, line, len);
        flb_free(line);
    }
    else if (ctx->out_line_format == FLB_LOKI_FMT_KV) {
        if (rec->type != MSGPACK_OBJECT_MAP) {
            msgpack_unpacked_destroy(&mp_buffer);
            if (tmp_sbuf_data) {
                flb_free(tmp_sbuf_data);
            }
            return -1;
        }

        buf = flb_sds_create_size(size_hint);
        if (!buf) {
            msgpack_unpacked_destroy(&mp_buffer);
            if (tmp_sbuf_data) {
                flb_free(tmp_sbuf_data);
            }
            return -1;
        }

        for (i = 0; i < rec->via.map.size; i++) {
            key = rec->via.map.ptr[i].key;
            val = rec->via.map.ptr[i].val;

            if (key.type != MSGPACK_OBJECT_STR) {
                skip++;
                continue;
            }

            if (i > skip) {
                safe_sds_cat(&buf, " ", 1);
            }

            safe_sds_cat(&buf, key.via.str.ptr, key.via.str.size);
            safe_sds_cat(&buf, "=", 1);
            pack_format_line_value(&buf, &val);
        }

        msgpack_pack_str(mp_pck, flb_sds_len(buf));
        msgpack_pack_str_body(mp_pck, buf, flb_sds_len(buf));
        flb_sds_destroy(buf);
    }

    msgpack_unpacked_destroy(&mp_buffer);
    if (tmp_sbuf_data) {
        flb_free(tmp_sbuf_data);
    }

    return 0;
}

/* Initialization callback */
static int cb_loki_init(struct flb_output_instance *ins,
                        struct flb_config *config, void *data)
{
    int              result;
    struct flb_loki *ctx;

    /* Create plugin context */
    ctx = loki_config_create(ins, config);
    if (!ctx) {
        flb_plg_error(ins, "cannot initialize configuration");
        return -1;
    }

    result = pthread_mutex_init(&ctx->dynamic_tenant_list_lock, NULL);

    if (result != 0) {
        flb_errno();

        flb_plg_error(ins, "cannot initialize dynamic tenant id list lock");

        loki_config_destroy(ctx);

        return -1;
    }

    result = pthread_once(&initialization_guard,
                          initialize_thread_local_storage);

    if (result != 0) {
        flb_errno();

        flb_plg_error(ins, "cannot initialize thread local storage");

        loki_config_destroy(ctx);

        return -1;
    }

    cfl_list_init(&ctx->dynamic_tenant_list);

    /*
     * This plugin instance uses the HTTP client interface, let's register
     * it debugging callbacks.
     */
    flb_output_set_http_debug_callbacks(ins);

    flb_plg_info(ins,
                 "configured, hostname=%s:%i",
                 ctx->tcp_host, ctx->tcp_port);
    return 0;
}

static flb_sds_t loki_compose_payload(struct flb_loki *ctx,
                                      int total_records,
                                      char *tag, int tag_len,
                                      const void *data, size_t bytes,
                                      flb_sds_t *dynamic_tenant_id)
{
    // int mp_ok = MSGPACK_UNPACK_SUCCESS;
    // size_t off = 0;
    flb_sds_t json;
    // struct flb_time tms;
    // msgpack_unpacked result;
    msgpack_packer mp_pck;
    msgpack_sbuffer mp_sbuf;
    // msgpack_object *obj;
    struct flb_log_event_decoder log_decoder;
    struct flb_log_event log_event;
    int ret;

    /*
     * Fluent Bit uses Loki API v1 to push records in JSON format, this
     * is the expected structure:
     *
     * {
     *   "streams": [
     *     {
     *       "stream": {
     *         "label": "value"
     *       },
     *       "values": [
     *         [ "<unix epoch in nanoseconds>", "<log line>" ],
     *         [ "<unix epoch in nanoseconds>", "<log line>" ]
     *       ]
     *     }
     *   ]
     * }
     */

    ret = flb_log_event_decoder_init(&log_decoder, (char *) data, bytes);

    if (ret != FLB_EVENT_DECODER_SUCCESS) {
        flb_plg_error(ctx->ins,
                      "Log event decoder initialization error : %d", ret);

        return NULL;
    }

    /* Initialize msgpack buffers */
    msgpack_sbuffer_init(&mp_sbuf);
    msgpack_packer_init(&mp_pck, &mp_sbuf, msgpack_sbuffer_write);

    /* Main map */
    msgpack_pack_map(&mp_pck, 1);

    /* streams */
    msgpack_pack_str(&mp_pck, 7);
    msgpack_pack_str_body(&mp_pck, "streams", 7);

    if (ctx->ra_used == 0 && ctx->auto_kubernetes_labels == FLB_FALSE) {
        /*
         * If labels are cached, there is no record accessor or custom
         * keys, so it's safe to put one main stream and attach all the
         * values.
         */
        msgpack_pack_array(&mp_pck, 1);

        /* map content: streams['stream'] & streams['values'] */
        msgpack_pack_map(&mp_pck, 2);

        /* streams['stream'] */
        msgpack_pack_str(&mp_pck, 6);
        msgpack_pack_str_body(&mp_pck, "stream", 6);

        /* Pack stream labels */
        pack_labels(ctx, &mp_pck, tag, tag_len, NULL);

        /* streams['values'] */
        msgpack_pack_str(&mp_pck, 6);
        msgpack_pack_str_body(&mp_pck, "values", 6);
        msgpack_pack_array(&mp_pck, total_records);

        while ((ret = flb_log_event_decoder_next(
                        &log_decoder,
                        &log_event)) == FLB_EVENT_DECODER_SUCCESS) {
            msgpack_pack_array(&mp_pck, 2);

            /* Append the timestamp */
            pack_timestamp(&mp_pck, &log_event.timestamp);
            pack_record(ctx, &mp_pck, log_event.body, dynamic_tenant_id);
        }
    }
    else {
        /*
         * Here there are no cached labels and the labels are composed by
         * each record content. To simplify the operation just create
         * one stream per record.
         */
        msgpack_pack_array(&mp_pck, total_records);

        while ((ret = flb_log_event_decoder_next(
                        &log_decoder,
                        &log_event)) == FLB_EVENT_DECODER_SUCCESS) {
            /* map content: streams['stream'] & streams['values'] */
            msgpack_pack_map(&mp_pck, 2);

            /* streams['stream'] */
            msgpack_pack_str(&mp_pck, 6);
            msgpack_pack_str_body(&mp_pck, "stream", 6);

            /* Pack stream labels */
            pack_labels(ctx, &mp_pck, tag, tag_len, log_event.body);

            /* streams['values'] */
            msgpack_pack_str(&mp_pck, 6);
            msgpack_pack_str_body(&mp_pck, "values", 6);
            msgpack_pack_array(&mp_pck, 1);

            msgpack_pack_array(&mp_pck, 2);

            /* Append the timestamp */
            pack_timestamp(&mp_pck, &log_event.timestamp);
            pack_record(ctx, &mp_pck, log_event.body, dynamic_tenant_id);
        }
    }

    flb_log_event_decoder_destroy(&log_decoder);

    json = flb_msgpack_raw_to_json_sds(mp_sbuf.data, mp_sbuf.size);

    msgpack_sbuffer_destroy(&mp_sbuf);

    return json;
}

static void payload_release(void *payload, int compressed)
{
    if (compressed) {
        flb_free(payload);
    }
    else {
        flb_sds_destroy(payload);
    }
}

static void cb_loki_flush(struct flb_event_chunk *event_chunk,
                          struct flb_output_flush *out_flush,
                          struct flb_input_instance *i_ins,
                          void *out_context,
                          struct flb_config *config)
{
    int ret;
    int out_ret = FLB_OK;
    size_t b_sent;
    flb_sds_t payload = NULL;
    flb_sds_t out_buf = NULL;
    size_t out_size;
    int compressed = FLB_FALSE;
    struct flb_loki *ctx = out_context;
    struct flb_connection *u_conn;
    struct flb_http_client *c;
    struct flb_loki_dynamic_tenant_id_entry *dynamic_tenant_id;

    dynamic_tenant_id = FLB_TLS_GET(thread_local_tenant_id);

    if (dynamic_tenant_id == NULL) {
        dynamic_tenant_id = dynamic_tenant_id_create();

        if (dynamic_tenant_id == NULL) {
            flb_errno();
            flb_plg_error(ctx->ins, "cannot allocate dynamic tenant id");

            FLB_OUTPUT_RETURN(FLB_RETRY);
        }

        FLB_TLS_SET(thread_local_tenant_id, dynamic_tenant_id);

        pthread_mutex_lock(&ctx->dynamic_tenant_list_lock);

        cfl_list_add(&dynamic_tenant_id->_head, &ctx->dynamic_tenant_list);

        pthread_mutex_unlock(&ctx->dynamic_tenant_list_lock);
    }

    /* Format the data to the expected Newrelic Payload */
    payload = loki_compose_payload(ctx,
                                   event_chunk->total_events,
                                   (char *) event_chunk->tag,
                                   flb_sds_len(event_chunk->tag),
                                   event_chunk->data, event_chunk->size,
                                   &dynamic_tenant_id->value);

    if (!payload) {
        flb_plg_error(ctx->ins, "cannot compose request payload");

        FLB_OUTPUT_RETURN(FLB_RETRY);
    }

    /* Map buffer */
    out_buf = payload;
    out_size = flb_sds_len(payload);

    if (ctx->compress_gzip == FLB_TRUE) {
        ret = flb_gzip_compress((void *) payload, flb_sds_len(payload), (void **) &out_buf, &out_size);
        if (ret == -1) {
            flb_plg_error(ctx->ins,
                          "cannot gzip payload, disabling compression");
        } else {
            compressed = FLB_TRUE;
            /* payload is not longer needed */
            flb_sds_destroy(payload);
        }
    }

    /* Lookup an available connection context */
    u_conn = flb_upstream_conn_get(ctx->u);
    if (!u_conn) {
        flb_plg_error(ctx->ins, "no upstream connections available");

        payload_release(out_buf, compressed);

        FLB_OUTPUT_RETURN(FLB_RETRY);
    }

    /* Create HTTP client context */
    c = flb_http_client(u_conn, FLB_HTTP_POST, FLB_LOKI_URI,
                        out_buf, out_size,
                        ctx->tcp_host, ctx->tcp_port,
                        NULL, 0);
    if (!c) {
        flb_plg_error(ctx->ins, "cannot create HTTP client context");

        payload_release(out_buf, compressed);
        flb_upstream_conn_release(u_conn);

        FLB_OUTPUT_RETURN(FLB_RETRY);
    }

    /* Set callback context to the HTTP client context */
    flb_http_set_callback_context(c, ctx->ins->callback);

    /* User Agent */
    flb_http_add_header(c, "User-Agent", 10, "Fluent-Bit", 10);

    /* Auth headers */
    if (ctx->http_user && ctx->http_passwd) { /* Basic */
        flb_http_basic_auth(c, ctx->http_user, ctx->http_passwd);
    } else if (ctx->bearer_token) { /* Bearer token */
        flb_http_bearer_auth(c, ctx->bearer_token);
    }

    /* Add Content-Type header */
    flb_http_add_header(c,
                        FLB_LOKI_CT, sizeof(FLB_LOKI_CT) - 1,
                        FLB_LOKI_CT_JSON, sizeof(FLB_LOKI_CT_JSON) - 1);

    if (compressed == FLB_TRUE) {
        flb_http_set_content_encoding_gzip(c);
    }

    /* Add X-Scope-OrgID header */
    if (dynamic_tenant_id->value != NULL) {
        flb_http_add_header(c,
                            FLB_LOKI_HEADER_SCOPE, sizeof(FLB_LOKI_HEADER_SCOPE) - 1,
                            dynamic_tenant_id->value,
                            flb_sds_len(dynamic_tenant_id->value));
    }
    else if (ctx->tenant_id) {
        flb_http_add_header(c,
                            FLB_LOKI_HEADER_SCOPE, sizeof(FLB_LOKI_HEADER_SCOPE) - 1,
                            ctx->tenant_id, flb_sds_len(ctx->tenant_id));
    }

    /* Send HTTP request */
    ret = flb_http_do(c, &b_sent);
    payload_release(out_buf, compressed);

    /* Validate HTTP client return status */
    if (ret == 0) {
        /*
         * Only allow the following HTTP status:
         *
         * - 200: OK
         * - 201: Created
         * - 202: Accepted
         * - 203: no authorative resp
         * - 204: No Content
         * - 205: Reset content
         *
         */
        if (c->resp.status == 400) {
            /*
             * Loki will return 400 if incoming data is out of order.
             * We should not retry such data.
             */
            flb_plg_error(ctx->ins, "%s:%i, HTTP status=%i Not retrying.\n%s",
                          ctx->tcp_host, ctx->tcp_port, c->resp.status,
                          c->resp.payload);
            out_ret = FLB_ERROR;
        }
        else if (c->resp.status < 200 || c->resp.status > 205) {
            if (c->resp.payload) {
                flb_plg_error(ctx->ins, "%s:%i, HTTP status=%i\n%s",
                              ctx->tcp_host, ctx->tcp_port, c->resp.status,
                              c->resp.payload);
            }
            else {
                flb_plg_error(ctx->ins, "%s:%i, HTTP status=%i",
                              ctx->tcp_host, ctx->tcp_port, c->resp.status);
            }
            out_ret = FLB_RETRY;
        }
        else {
            if (c->resp.payload) {
                flb_plg_debug(ctx->ins, "%s:%i, HTTP status=%i\n%s",
                              ctx->tcp_host, ctx->tcp_port,
                              c->resp.status, c->resp.payload);
            }
            else {
                flb_plg_debug(ctx->ins, "%s:%i, HTTP status=%i",
                              ctx->tcp_host, ctx->tcp_port,
                              c->resp.status);
            }
        }
    }
    else {
        flb_plg_error(ctx->ins, "could not flush records to %s:%i (http_do=%i)",
                      ctx->tcp_host, ctx->tcp_port, ret);
        out_ret = FLB_RETRY;
    }

    flb_http_client_destroy(c);
    flb_upstream_conn_release(u_conn);

    FLB_OUTPUT_RETURN(out_ret);
}

static void release_dynamic_tenant_ids(struct cfl_list *dynamic_tenant_list)
{
    struct cfl_list                         *iterator;
    struct cfl_list                         *backup;
    struct flb_loki_dynamic_tenant_id_entry *entry;

    cfl_list_foreach_safe(iterator, backup, dynamic_tenant_list) {
        entry = cfl_list_entry(iterator,
                               struct flb_loki_dynamic_tenant_id_entry,
                               _head);

        dynamic_tenant_id_destroy(entry);
    }
}

static int cb_loki_exit(void *data, struct flb_config *config)
{
    struct flb_loki *ctx = data;

    if (!ctx) {
        return 0;
    }

    pthread_mutex_lock(&ctx->dynamic_tenant_list_lock);

    release_dynamic_tenant_ids(&ctx->dynamic_tenant_list);

    pthread_mutex_unlock(&ctx->dynamic_tenant_list_lock);

    loki_config_destroy(ctx);

    return 0;
}

/* Configuration properties map */
static struct flb_config_map config_map[] = {
    {
     FLB_CONFIG_MAP_STR, "tenant_id", NULL,
     0, FLB_TRUE, offsetof(struct flb_loki, tenant_id),
     "Tenant ID used by default to push logs to Loki. If omitted or empty "
     "it assumes Loki is running in single-tenant mode and no X-Scope-OrgID "
     "header is sent."
    },
    {
     FLB_CONFIG_MAP_STR, "tenant_id_key", NULL,
     0, FLB_TRUE, offsetof(struct flb_loki, tenant_id_key_config),
     "If set, X-Scope-OrgID will be the value of the key from incoming record. "
     "It is useful to set X-Scode-OrgID dynamically."
    },

    {
     FLB_CONFIG_MAP_CLIST, "labels", NULL,
     0, FLB_TRUE, offsetof(struct flb_loki, labels),
     "labels for API requests. If no value is set, the default label is 'job=fluent-bit'"
    },

    {
     FLB_CONFIG_MAP_BOOL, "auto_kubernetes_labels", "false",
     0, FLB_TRUE, offsetof(struct flb_loki, auto_kubernetes_labels),
     "If set to true, it will add all Kubernetes labels to Loki labels.",
    },

    {
     FLB_CONFIG_MAP_BOOL, "drop_single_key", "false",
     0, FLB_TRUE, offsetof(struct flb_loki, drop_single_key),
     "If set to true and only a single key remains, the log line sent to Loki "
     "will be the value of that key.",
    },

    {
     FLB_CONFIG_MAP_CLIST, "label_keys", NULL,
     0, FLB_TRUE, offsetof(struct flb_loki, label_keys),
     "Comma separated list of keys to use as stream labels."
    },

    {
     FLB_CONFIG_MAP_CLIST, "remove_keys", NULL,
     0, FLB_TRUE, offsetof(struct flb_loki, remove_keys),
     "Comma separated list of keys to remove."
    },

    {
     FLB_CONFIG_MAP_STR, "line_format", "json",
     0, FLB_TRUE, offsetof(struct flb_loki, line_format),
     "Format to use when flattening the record to a log line. Valid values are "
     "'json' or 'key_value'. If set to 'json' the log line sent to Loki will be "
     "the Fluent Bit record dumped as json. If set to 'key_value', the log line "
     "will be each item in the record concatenated together (separated by a "
     "single space) in the format '='."
    },

    {
     FLB_CONFIG_MAP_STR, "label_map_path", NULL,
     0, FLB_TRUE, offsetof(struct flb_loki, label_map_path),
     "A label map file path"
    },

    {
     FLB_CONFIG_MAP_STR, "http_user", NULL,
     0, FLB_TRUE, offsetof(struct flb_loki, http_user),
     "Set HTTP auth user"
    },

    {
     FLB_CONFIG_MAP_STR, "http_passwd", "",
     0, FLB_TRUE, offsetof(struct flb_loki, http_passwd),
     "Set HTTP auth password"
    },

    {
     FLB_CONFIG_MAP_STR, "bearer_token", NULL,
     0, FLB_TRUE, offsetof(struct flb_loki, bearer_token),
     "Set bearer token auth"
    },

    {
     FLB_CONFIG_MAP_STR, "compress", NULL,
     0, FLB_FALSE, 0,
     "Set payload compression in network transfer. Option available is 'gzip'"
    },

    /* EOF */
    {0}
};

/* for testing */
static int cb_loki_format_test(struct flb_config *config,
                               struct flb_input_instance *ins,
                               void *plugin_context,
                               void *flush_ctx,
                               int event_type,
                               const char *tag, int tag_len,
                               const void *data, size_t bytes,
                               void **out_data, size_t *out_size)
{
    int total_records;
    flb_sds_t payload = NULL;
    flb_sds_t dynamic_tenant_id;
    struct flb_loki *ctx = plugin_context;

    dynamic_tenant_id = NULL;

    /* Count number of records */
    total_records = flb_mp_count(data, bytes);

    payload = loki_compose_payload(ctx, total_records,
                                   (char *) tag, tag_len, data, bytes,
                                   &dynamic_tenant_id);
    if (payload == NULL) {
        if (dynamic_tenant_id != NULL) {
            flb_sds_destroy(dynamic_tenant_id);
        }

        return -1;
    }

    *out_data = payload;
    *out_size = flb_sds_len(payload);

    return 0;
}

/* Plugin reference */
struct flb_output_plugin out_loki_plugin = {
    .name        = "loki",
    .description = "Loki",
    .cb_init     = cb_loki_init,
    .cb_flush    = cb_loki_flush,
    .cb_exit     = cb_loki_exit,
    .config_map  = config_map,

    /* for testing */
    .test_formatter.callback = cb_loki_format_test,

    .flags       = FLB_OUTPUT_NET | FLB_IO_OPT_TLS,
};