-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathflb_pack.c
More file actions
1763 lines (1527 loc) · 50.9 KB
/
flb_pack.c
File metadata and controls
1763 lines (1527 loc) · 50.9 KB
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
/*-*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* Fluent Bit
* ==========
* Copyright (C) 2015-2026 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 <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <limits.h>
#include <fluent-bit/flb_info.h>
#include <fluent-bit/flb_mem.h>
#include <fluent-bit/flb_sds.h>
#include <fluent-bit/flb_error.h>
#include <fluent-bit/flb_utils.h>
#include <fluent-bit/flb_sds.h>
#include <fluent-bit/flb_time.h>
#include <fluent-bit/flb_pack.h>
#include <fluent-bit/flb_pack_json.h>
#include <fluent-bit/flb_unescape.h>
#include <fluent-bit/flb_simd.h>
#include <fluent-bit/flb_log_event_encoder.h>
#include <fluent-bit/flb_log_event_decoder.h>
/* cmetrics */
#include <cmetrics/cmetrics.h>
#include <cmetrics/cmt_decode_msgpack.h>
#include <cmetrics/cmt_encode_text.h>
#include <msgpack.h>
#include <math.h>
#include <jsmn/jsmn.h>
#include <yyjson.h>
#define try_to_write_str flb_utils_write_str
static int convert_nan_to_null = FLB_FALSE;
static int flb_pack_set_null_as_nan(int b) {
if (b == FLB_TRUE || b == FLB_FALSE) {
convert_nan_to_null = b;
}
return convert_nan_to_null;
}
/* -----------------------------------------------------------------------------
* SIMD helpers
* -----------------------------------------------------------------------------
*
* json_find_escapable_simd:
* Returns a pointer to the first byte in s[0..n) that requires JSON string
* escaping (any of '"' or '\' or control chars < 0x20). If none, returns NULL.
*
* Fast-path skips whole vector-width blocks when there is no match. On hit,
* it falls back to a short scalar check within the block to find the exact
* offending index. Works with SSE2 / NEON / RVV through flb_simd.h.
*/
static inline const char *json_find_escapable_simd(const char *s, size_t n)
{
const char *p = s;
uint8_t c;
#ifdef FLB_HAVE_SIMD
const size_t vlen = FLB_SIMD_VEC8_INST_LEN;
flb_vector8 dq = flb_vector8_broadcast((uint8_t)'"');
flb_vector8 bs = flb_vector8_broadcast((uint8_t)'\\');
size_t i;
while (n >= vlen) {
flb_vector8 v;
flb_vector8_load(&v, (const uint8_t*)p);
/* If neither '"' nor '\' appears in this block, it is very likely
* safe; control chars are rare, handle them in the fallback check. */
bool has_dq = flb_vector8_is_highbit_set(flb_vector8_eq(v, dq));
bool has_bs = flb_vector8_is_highbit_set(flb_vector8_eq(v, bs));
if (has_dq || has_bs) {
/* Narrow down to the exact position in this block */
for (i = 0; i < vlen; i++) {
c = (uint8_t)p[i];
if (c == '"' || c == '\\' || c < 0x20) {
return p + i;
}
}
}
p += vlen;
n -= vlen;
}
#endif
/* Scalar tail / generic fallback, also checks control chars */
while (n--) {
c = (uint8_t)*p;
if (c == '"' || c == '\\' || c < 0x20) {
return p;
}
p++;
}
return NULL;
}
int flb_json_tokenise(const char *js, size_t len,
struct flb_pack_state *state)
{
int ret;
int new_tokens = 256;
size_t old_size;
size_t new_size;
void *tmp;
ret = jsmn_parse(&state->parser, js, len,
state->tokens, state->tokens_size);
while (ret == JSMN_ERROR_NOMEM) {
/* Get current size of the array in bytes */
old_size = state->tokens_size * sizeof(jsmntok_t);
/* New size: add capacity for new 256 entries */
new_size = old_size + (sizeof(jsmntok_t) * new_tokens);
tmp = flb_realloc(state->tokens, new_size);
if (!tmp) {
flb_errno();
return -1;
}
state->tokens = tmp;
state->tokens_size += new_tokens;
ret = jsmn_parse(&state->parser, js, len,
state->tokens, state->tokens_size);
}
if (ret == JSMN_ERROR_INVAL) {
return FLB_ERR_JSON_INVAL;
}
if (ret == JSMN_ERROR_PART) {
/* This is a partial JSON message, just stop */
flb_trace("[json tokenise] incomplete");
return FLB_ERR_JSON_PART;
}
/* always use jsmn_parser.toknext to count tokens */
state->tokens_count = state->parser.toknext;
return 0;
}
static inline int is_float(const char *buf, int len)
{
const char *end = buf + len;
const char *p = buf;
#ifdef FLB_HAVE_SIMD
{
const size_t vlen = FLB_SIMD_VEC8_INST_LEN;
flb_vector8 vdot = flb_vector8_broadcast((uint8_t)'.');
flb_vector8 ve = flb_vector8_broadcast((uint8_t)'e');
flb_vector8 vE = flb_vector8_broadcast((uint8_t)'E');
flb_vector8 v;
char c;
const char *q;
size_t i;
while ((size_t)(end - p) >= vlen) {
flb_vector8_load(&v, (const uint8_t *)p);
/* If the block contains '.', it's definitely a float */
if (flb_vector8_is_highbit_set(flb_vector8_eq(v, vdot))) {
return 1;
}
/* If the block contains 'e' or 'E', check the immediate next char. */
if (flb_vector8_is_highbit_set(flb_vector8_eq(v, ve)) ||
flb_vector8_is_highbit_set(flb_vector8_eq(v, vE))) {
/* Narrow inside this vector to the first e/E and verify next char */
for (i = 0; i < vlen; i++) {
c = p[i];
if (c == 'e' || c == 'E') {
q = p + i + 1;
if (q < end) {
char next = *q;
if (next == '+' || next == '-' ||
(unsigned)(next - '0') <= 9) {
return 1;
}
}
/* Not signed exponent here; fall through to precise check below.
Set p at the e/E position so the scalar loop sees it. */
p += i;
goto scalar_check;
}
}
/* Should not reach (we had a mask), but continue safely */
}
/* No candidates in this block; skip it entirely */
p += vlen;
}
}
#endif
scalar_check:
/* Precise scalar check for the remaining tail (and for cases we broke early). */
while (p < end) {
if (*p == '.') {
return 1;
}
if ((*p == 'e' || *p == 'E') && (p + 1) < end) {
char next = p[1];
if (next == '-' || next == '+' ||
(unsigned)(next - '0') <= 9) {
return 1;
}
}
p++;
}
return 0;
}
static inline void pack_numeric_token(msgpack_packer *pck, const char *p, int flen)
{
long long val;
unsigned long long u_val;
if (is_float(p, flen)) {
msgpack_pack_double(pck, strtod(p, NULL));
return;
}
errno = 0;
if (*p == '-') {
val = strtoll(p, NULL, 10);
if (errno == ERANGE) {
msgpack_pack_double(pck, strtod(p, NULL));
}
else {
msgpack_pack_int64(pck, val);
}
}
else {
u_val = strtoull(p, NULL, 10);
if (errno == ERANGE) {
msgpack_pack_double(pck, strtod(p, NULL));
}
else if (u_val <= LLONG_MAX) {
msgpack_pack_int64(pck, (long long)u_val);
}
else {
msgpack_pack_uint64(pck, u_val);
}
}
}
/* Sanitize incoming JSON string */
static inline int pack_string_token(struct flb_pack_state *state,
const char *str, int len,
msgpack_packer *pck)
{
int s;
int out_len;
char *tmp;
char *out_buf;
/* Fast path: if the JSON string does not contain '"' or '\' or any control
* chars (<0x20), we can pack it as-is without unescaping. */
const char *bad = json_find_escapable_simd(str, (size_t)len);
if (bad == NULL) {
msgpack_pack_str(pck, len);
msgpack_pack_str_body(pck, str, len);
return len;
}
/* Slow path: unescape into a temporary buffer as before. */
if (state->buf_size < len + 1) {
s = len + 1;
tmp = flb_realloc(state->buf_data, s);
if (!tmp) {
flb_errno();
return -1;
}
state->buf_data = tmp;
state->buf_size = s;
}
out_buf = state->buf_data;
/* Always decode UTF-8 escape sequences and specials when needed */
out_len = flb_unescape_string_utf8(str, len, out_buf);
/* Pack the decoded text */
msgpack_pack_str(pck, out_len);
msgpack_pack_str_body(pck, out_buf, out_len);
return out_len;
}
/* Convert a yyjson value to msgpack */
static void yyjson_val_to_msgpack(yyjson_val *val, msgpack_packer *pck)
{
size_t idx, max;
yyjson_val *key;
yyjson_val *tmp;
const char *k;
size_t klen;
switch (yyjson_get_type(val)) {
case YYJSON_TYPE_OBJ:
msgpack_pack_map(pck, yyjson_obj_size(val));
yyjson_obj_foreach(val, idx, max, key, tmp) {
k = yyjson_get_str(key);
klen = yyjson_get_len(key);
msgpack_pack_str(pck, klen);
msgpack_pack_str_body(pck, k, klen);
yyjson_val_to_msgpack(tmp, pck);
}
break;
case YYJSON_TYPE_ARR:
msgpack_pack_array(pck, yyjson_arr_size(val));
yyjson_arr_foreach(val, idx, max, tmp) {
yyjson_val_to_msgpack(tmp, pck);
}
break;
case YYJSON_TYPE_STR:
msgpack_pack_str(pck, yyjson_get_len(val));
msgpack_pack_str_body(pck, yyjson_get_str(val), yyjson_get_len(val));
break;
case YYJSON_TYPE_BOOL:
if (yyjson_get_bool(val)) {
msgpack_pack_true(pck);
}
else {
msgpack_pack_false(pck);
}
break;
case YYJSON_TYPE_NULL:
msgpack_pack_nil(pck);
break;
case YYJSON_TYPE_NUM:
if (yyjson_is_int(val)) {
if (yyjson_is_sint(val)) {
msgpack_pack_int64(pck, yyjson_get_sint(val));
}
else {
msgpack_pack_uint64(pck, yyjson_get_uint(val));
}
}
else {
msgpack_pack_double(pck, yyjson_get_real(val));
}
break;
default:
msgpack_pack_nil(pck);
}
}
static inline int yyjson_root_type(yyjson_val *val)
{
switch (yyjson_get_type(val)) {
case YYJSON_TYPE_OBJ:
return JSMN_OBJECT;
case YYJSON_TYPE_ARR:
return JSMN_ARRAY;
case YYJSON_TYPE_STR:
return JSMN_STRING;
default:
return JSMN_PRIMITIVE;
}
}
static int pack_json_to_msgpack_yyjson(const char *js, size_t len, char **buffer,
size_t *size, int *root_type, int *records,
size_t *consumed)
{
int count_records = 0;
size_t read_bytes;
yyjson_read_err err;
yyjson_doc *doc = NULL;
yyjson_val *root;
msgpack_sbuffer sbuf;
msgpack_packer pck;
char *start, *end, *insitu_buf;
if (!js || !buffer || !size) {
return -1;
}
/*
* This is the tricky part, if we want to take advantage of SIMD we need to add
* padding to the buffer (INSITU), otherwise trusting the caller it's a bit risky.
*
* An extra optimization would be to provide a specific API for callers who are aware about
* padding and buffer states, or use a pool allocator. While this is a good optimization,
* it's not a priority for now, we are already gaining around 50% perf improvement with this
* implementation compared to the previous one.
*/
insitu_buf = flb_malloc(len + YYJSON_PADDING_SIZE);
if (!insitu_buf) {
flb_errno();
return -1;
}
memcpy(insitu_buf, js, len);
memset(insitu_buf + len, 0, YYJSON_PADDING_SIZE);
start = insitu_buf;
end = insitu_buf + len;
msgpack_sbuffer_init(&sbuf);
msgpack_packer_init(&pck, &sbuf, msgpack_sbuffer_write);
while (start < end) {
/* Skip leading whitespace/newlines between JSON values */
while (start < end && (*start == ' ' || *start == '\t' ||
*start == '\n' || *start == '\r')) {
start++;
}
if (start >= end) {
/* only whitespace remains */
break;
}
doc = yyjson_read_opts(start, (size_t)(end - start),
YYJSON_READ_STOP_WHEN_DONE | YYJSON_READ_INSITU |
YYJSON_READ_ALLOW_INVALID_UNICODE | YYJSON_READ_REPLACE_INVALID_UNICODE,
NULL, &err);
if (!doc) {
/* If we already parsed something, treat trailing junk/whitespace as done */
if (count_records > 0) {
break;
}
flb_debug("[yyjson->msgpack] read error code=%d msg=%s pos=%zu",
err.code, err.msg, err.pos);
msgpack_sbuffer_clear(&sbuf);
msgpack_sbuffer_destroy(&sbuf);
flb_free(insitu_buf);
return -1;
}
read_bytes = yyjson_doc_get_read_size(doc);
if (read_bytes == 0) {
yyjson_doc_free(doc);
doc = NULL;
/* No progress; if nothing parsed yet, error; else stop */
if (count_records == 0) {
msgpack_sbuffer_clear(&sbuf);
msgpack_sbuffer_destroy(&sbuf);
flb_free(insitu_buf);
return -1;
}
break;
}
root = yyjson_doc_get_root(doc);
if (!root) {
yyjson_doc_free(doc);
doc = NULL;
msgpack_sbuffer_clear(&sbuf);
msgpack_sbuffer_destroy(&sbuf);
flb_free(insitu_buf);
return -1;
}
yyjson_val_to_msgpack(root, &pck);
if (root_type && count_records == 0) {
*root_type = yyjson_root_type(root);
}
yyjson_doc_free(doc);
doc = NULL;
count_records++;
/* Move to the next value in the stream */
start += read_bytes;
}
if (records) {
*records = count_records;
}
if (consumed) {
*consumed = (size_t) (start - insitu_buf);
}
/* caller owns and must free with the same allocator */
*buffer = sbuf.data;
*size = sbuf.size;
flb_free(insitu_buf);
return 0;
}
/* Receive a tokenized JSON message and convert it to MsgPack */
static char *tokens_to_msgpack(struct flb_pack_state *state,
const char *js,
int *out_size, int *last_byte,
int *out_records)
{
int i;
int flen;
int arr_size;
int records = 0;
const char *p;
char *buf = NULL;
const jsmntok_t *t;
msgpack_packer pck;
msgpack_sbuffer sbuf;
jsmntok_t *tokens;
tokens = state->tokens;
arr_size = state->tokens_count;
if (arr_size == 0) {
return NULL;
}
/* initialize buffers */
msgpack_sbuffer_init(&sbuf);
msgpack_packer_init(&pck, &sbuf, msgpack_sbuffer_write);
for (i = 0; i < arr_size ; i++) {
t = &tokens[i];
if (t->start < 0 || t->end <= 0) {
msgpack_sbuffer_destroy(&sbuf);
return NULL;
}
if (t->parent == -1) {
*last_byte = t->end;
records++;
}
flen = (t->end - t->start);
switch (t->type) {
case JSMN_OBJECT:
msgpack_pack_map(&pck, t->size);
break;
case JSMN_ARRAY:
msgpack_pack_array(&pck, t->size);
break;
case JSMN_STRING:
if (pack_string_token(state, js + t->start, flen, &pck) < 0) {
msgpack_sbuffer_destroy(&sbuf);
return NULL;
}
break;
case JSMN_PRIMITIVE:
p = js + t->start;
if (*p == 'f') {
msgpack_pack_false(&pck);
}
else if (*p == 't') {
msgpack_pack_true(&pck);
}
else if (*p == 'n') {
msgpack_pack_nil(&pck);
}
else {
pack_numeric_token(&pck, p, flen);
}
break;
case JSMN_UNDEFINED:
msgpack_sbuffer_destroy(&sbuf);
return NULL;
}
}
*out_size = sbuf.size;
*out_records = records;
buf = sbuf.data;
return buf;
}
/*
* It parse a JSON string and convert it to MessagePack format, this packer is
* useful when a complete JSON message exists, otherwise it will fail until
* the message is complete.
*
* This routine do not keep a state in the parser, do not use it for big
* JSON messages.
*/
static int pack_json_to_msgpack(const char *js, size_t len, char **buffer,
size_t *size, int *root_type, int *records,
size_t *consumed)
{
int ret = -1;
int n_records;
int out;
int last;
char *buf = NULL;
struct flb_pack_state state;
ret = flb_pack_state_init(&state);
if (ret != 0) {
return -1;
}
ret = flb_json_tokenise(js, len, &state);
if (ret != 0) {
ret = -1;
goto flb_pack_json_end;
}
if (state.tokens_count == 0) {
ret = -1;
goto flb_pack_json_end;
}
buf = tokens_to_msgpack(&state, js, &out, &last, &n_records);
if (!buf) {
ret = -1;
goto flb_pack_json_end;
}
*root_type = state.tokens[0].type;
*size = out;
*buffer = buf;
*records = n_records;
if (consumed != NULL) {
*consumed = last;
}
ret = 0;
flb_pack_json_end:
if (ret != 0 && buf) {
flb_free(buf);
}
flb_pack_state_reset(&state);
return ret;
}
int flb_pack_json_legacy(const char *js, size_t len, char **buffer, size_t *size,
int *root_type, size_t *consumed)
{
int records;
return pack_json_to_msgpack(js, len, buffer, size, root_type,
&records, consumed);
}
int flb_pack_json_recs_legacy(const char *js, size_t len, char **buffer, size_t *size,
int *root_type, int *out_records, size_t *consumed)
{
return pack_json_to_msgpack(js, len, buffer, size, root_type,
out_records, consumed);
}
/* Pack unlimited serialized JSON messages into msgpack */
int flb_pack_json(const char *js, size_t len, char **buffer, size_t *size,
int *root_type, size_t *consumed)
{
int records;
#ifdef FLB_HAVE_SIMD
/*
* When SIMD support is compiled in, route the default JSON pack API through
* the extensible frontend so callers inherit the YYJSON backend
* selection.
* However, all of the defaulting to use YYSJON is dangerous on
* coroutine.
* So, we only enabled it for normal thread.
* Still, we use legacy backend on using coroutine.
* Explicit backend-specific entry points remain available for forced JSMN
* or YYJSON behavior.
*/
if (flb_coro_get() != NULL) {
return flb_pack_json_legacy(js, len, buffer, size, root_type, consumed);
}
else {
return flb_pack_json_recs_ext(js, len, buffer, size, root_type,
&records, consumed, NULL);
}
#endif
return flb_pack_json_legacy(js, len, buffer, size, root_type, consumed);
}
/*
* Pack unlimited serialized JSON messages into msgpack, finally it writes on
* 'out_records' the number of messages.
*/
int flb_pack_json_recs(const char *js, size_t len, char **buffer, size_t *size,
int *root_type, int *out_records, size_t *consumed)
{
#ifdef FLB_HAVE_SIMD
return flb_pack_json_recs_ext(js, len, buffer, size, root_type,
out_records, consumed, NULL);
#endif
return flb_pack_json_recs_legacy(js, len, buffer, size, root_type,
out_records, consumed);
}
/* Pack a JSON message using yyjson */
int flb_pack_json_yyjson(const char *js, size_t len, char **buffer, size_t *size,
int *root_type, size_t *consumed)
{
int records;
return pack_json_to_msgpack_yyjson(js, len, buffer, size, root_type, &records, consumed);
}
int flb_pack_json_recs_yyjson(const char *js, size_t len, char **buffer, size_t *size,
int *root_type, int *out_records, size_t *consumed)
{
return pack_json_to_msgpack_yyjson(js, len, buffer, size, root_type, out_records, consumed);
}
/* Initialize a JSON packer state */
int flb_pack_state_init(struct flb_pack_state *s)
{
int tokens = 256;
size_t size = 256;
jsmn_init(&s->parser);
size = sizeof(jsmntok_t) * tokens;
s->tokens = flb_malloc(size);
if (!s->tokens) {
flb_errno();
return -1;
}
s->tokens_size = tokens;
s->tokens_count = 0;
s->last_byte = 0;
s->multiple = FLB_FALSE;
s->buf_data = flb_malloc(size);
if (!s->buf_data) {
flb_errno();
flb_free(s->tokens);
s->tokens = NULL;
return -1;
}
s->buf_size = size;
s->buf_len = 0;
return 0;
}
void flb_pack_state_reset(struct flb_pack_state *s)
{
flb_free(s->tokens);
s->tokens = NULL;
s->tokens_size = 0;
s->tokens_count = 0;
s->last_byte = 0;
s->buf_size = 0;
flb_free(s->buf_data);
s->buf_data = NULL;
}
/*
* It parse a JSON string and convert it to MessagePack format. The main
* difference of this function and the previous flb_pack_json() is that it
* keeps a parser and tokens state, allowing to process big messages and
* resume the parsing process instead of start from zero.
*/
int flb_pack_json_state(const char *js, size_t len,
char **buffer, int *size,
struct flb_pack_state *state)
{
int ret;
int out;
int delim = 0;
int last = 0;
int records;
char *buf;
jsmntok_t *t;
ret = flb_json_tokenise(js, len, state);
state->multiple = FLB_TRUE;
if (ret == FLB_ERR_JSON_PART && state->multiple == FLB_TRUE) {
/*
* If the caller enabled 'multiple' flag, it means that the incoming
* JSON message may have multiple messages concatenated and likely
* the last one is only incomplete.
*
* The following routine aims to determinate how many JSON messages
* are OK in the array of tokens, if any, process them and adjust
* the JSMN context/buffers.
*/
/*
* jsmn_parse updates jsmn_parser members. (state->parser)
* A member 'toknext' points next incomplete object token.
* We use toknext - 1 as an index of last member of complete JSON.
*/
int i;
int found = 0;
if (state->parser.toknext == 0) {
return ret;
}
for (i = (int)state->parser.toknext - 1; i >= 1; i--) {
t = &state->tokens[i];
if (t->parent == -1 && (t->end != 0)) {
found++;
delim = i;
break;
}
}
if (found == 0) {
return ret; /* FLB_ERR_JSON_PART */
}
state->tokens_count += delim;
}
else if (ret != 0) {
return ret;
}
if (state->tokens_count == 0 || state->tokens == NULL) {
state->last_byte = last;
return FLB_ERR_JSON_INVAL;
}
buf = tokens_to_msgpack(state, js, &out, &last, &records);
if (!buf) {
return -1;
}
*size = out;
*buffer = buf;
state->last_byte = last;
return 0;
}
int flb_metadata_pop_from_msgpack(msgpack_object **metadata, msgpack_unpacked *upk,
msgpack_object **map)
{
if (metadata == NULL || upk == NULL) {
return -1;
}
if (upk->data.type != MSGPACK_OBJECT_ARRAY) {
return -1;
}
*metadata = &upk->data.via.array.ptr[0].via.array.ptr[1];
*map = &upk->data.via.array.ptr[1];
return 0;
}
static int pack_print_fluent_record(size_t cnt, msgpack_unpacked result)
{
msgpack_object *metadata;
msgpack_object root;
msgpack_object *obj;
struct flb_time tms;
msgpack_object o;
root = result.data;
if (root.type != MSGPACK_OBJECT_ARRAY) {
return -1;
}
o = root.via.array.ptr[0];
if (o.type != MSGPACK_OBJECT_ARRAY) {
return -1;
}
/* decode expected timestamp only (integer, float or ext) */
o = o.via.array.ptr[0];
if (o.type != MSGPACK_OBJECT_POSITIVE_INTEGER &&
o.type != MSGPACK_OBJECT_FLOAT &&
o.type != MSGPACK_OBJECT_EXT) {
return -1;
}
/* This is a Fluent Bit record, just do the proper unpacking/printing */
flb_time_pop_from_msgpack(&tms, &result, &obj);
flb_metadata_pop_from_msgpack(&metadata, &result, &obj);
fprintf(stdout, "[%zd] [[%"PRId32".%09lu, ", cnt, (int32_t) tms.tm.tv_sec, tms.tm.tv_nsec);
msgpack_object_print(stdout, *metadata);
fprintf(stdout, "], ");
msgpack_object_print(stdout, *obj);
fprintf(stdout, "]\n");
return 0;
}
void flb_pack_print(const char *data, size_t bytes)
{
int ret;
msgpack_unpacked result;
size_t off = 0, cnt = 0;
msgpack_unpacked_init(&result);
while (msgpack_unpack_next(&result, data, bytes, &off) == MSGPACK_UNPACK_SUCCESS) {
/* Check if we are processing an internal Fluent Bit record */
ret = pack_print_fluent_record(cnt, result);
if (ret == 0) {
continue;
}
printf("[%zd] ", cnt++);
msgpack_object_print(stdout, result.data);
printf("\n");
}
msgpack_unpacked_destroy(&result);
}
void flb_pack_print_metrics(const char *data, size_t bytes)
{
int ret;
size_t off = 0;
cfl_sds_t text;
struct cmt *cmt = NULL;
/* get cmetrics context */
ret = cmt_decode_msgpack_create(&cmt, (char *) data, bytes, &off);
if (ret != 0) {
flb_error("could not process metrics payload");
return;
}
/* convert to text representation */
text = cmt_encode_text_create(cmt);
/* destroy cmt context */
cmt_destroy(cmt);
printf("%s", text);
fflush(stdout);
cmt_encode_text_destroy(text);
}
static inline int try_to_write(char *buf, int *off, size_t left,
const char *str, size_t str_len)
{
if (str_len <= 0){
str_len = strlen(str);
}
if (left <= *off+str_len) {
return FLB_FALSE;
}
memcpy(buf+*off, str, str_len);
*off += str_len;
return FLB_TRUE;
}
/*
* Check if a key exists in the map using the 'offset' as an index to define
* which element needs to start looking from
*/
static inline int key_exists_in_map(msgpack_object key, msgpack_object map, int offset)
{
int i;
msgpack_object p;
if (key.type != MSGPACK_OBJECT_STR) {
return FLB_FALSE;
}
for (i = offset; i < map.via.map.size; i++) {
p = map.via.map.ptr[i].key;
if (p.type != MSGPACK_OBJECT_STR) {
continue;
}
if (key.via.str.size != p.via.str.size) {
continue;
}
if (memcmp(key.via.str.ptr, p.via.str.ptr, p.via.str.size) == 0) {
return FLB_TRUE;
}
}
return FLB_FALSE;