-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathsensors_analytics.c
1568 lines (1332 loc) · 40 KB
/
sensors_analytics.c
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
/*
* Copyright (C) 2015 SensorsData
* All rights reserved.
*/
#include <string.h>
#include <stdint.h>
#if defined(USE_POSIX)
#include <pthread.h>
#include <regex.h>
#include <sys/time.h>
#elif defined(_WIN32)
#include <windows.h>
#include <sys/timeb.h>
#include <share.h>
#include "pcre/pcre.h"
#elif defined(__linux__)
#include <sys/time.h>
#endif
#include "sensors_analytics.h"
#define SA_LIB_VERSION "0.2.1"
#define SA_LIB "C"
#define SA_LIB_METHOD "code"
#define KEY_WORD_PATTERN "(^distinct_id$|^original_id$|^time$|^properties$|^id$|^first_id$|^second_id$|^users$|^events$|^event$|^user_id$|^date$|^datetime$)"
#define NAME_PATTERN "^[a-zA-Z_$][a-zA-Z0-9_$]{0,99}$"
#if defined(__linux__)
#define LOCALTIME(seconds, now) localtime_r((seconds), (now))
#define FOPEN(file, filename, option) do { \
*(file) = fopen((filename), (option)); \
} while (0)
#elif defined(__APPLE__)
#define LOCALTIME(seconds, now) localtime_r((seconds), (now))
#define FOPEN(file, filename, option) do { \
*(file) = fopen((filename), (option)); \
} while (0)
#elif defined(_WIN32)
#define LOCALTIME(seconds, now) localtime_s((now), (seconds))
#define FOPEN(file, filename, option) do { \
*(file) = _fsopen((filename), (option), _SH_DENYNO); \
} while (0)
#endif
static void* _sa_safe_malloc(unsigned long n, unsigned long line) {
void* p = malloc(n);
if (!p) {
fprintf(stderr, "[%s:%lu]Out of memory(%lu bytes)\n", __FILE__, line, (unsigned long)n);
exit(SA_MALLOC_ERROR);
}
return p;
}
#define SA_SAFE_MALLOC(n) _sa_safe_malloc((n), __LINE__)
static char* _sa_strdup(const char *str) {
int len = strlen(str);
char *ret = (char*)SA_SAFE_MALLOC(len + 1);
memcpy(ret, str, len);
ret[len] = '\0';
return ret;
}
// String buffer --------------------------------------------------------------
typedef struct {
char *cur;
char *end;
char *start;
} SAStringBuffer;
static int _sa_sb_init(SAStringBuffer *sb) {
sb->start = (char*)SA_SAFE_MALLOC(17);
sb->cur = sb->start;
sb->end = sb->start + 16;
return SA_OK;
}
/* sb and need may be evaluated multiple times. */
#define _sa_sb_need(sb, need) do { \
int res = SA_OK; \
if ((sb)->end < (sb)->cur + (need)) \
if (SA_OK != (res = _sa_sb_grow(sb, need))) \
return res; \
} while (0)
static int _sa_sb_grow(SAStringBuffer *sb, unsigned long need) {
size_t length = sb->cur - sb->start;
size_t alloc = sb->end - sb->start;
do {
alloc *= 2;
} while (alloc < length + need);
sb->start = (char*) realloc(sb->start, alloc + 1);
if (sb->start == NULL) {
fprintf(stderr, "Out of memory.");
exit(SA_MALLOC_ERROR);
}
sb->cur = sb->start + length;
sb->end = sb->start + alloc;
return SA_OK;
}
static int _sa_sb_put(SAStringBuffer *sb, const char *string_, unsigned long length) {
_sa_sb_need(sb, length);
memcpy(sb->cur, string_, length);
sb->cur += length;
return SA_OK;
}
#define _sa_sb_putc(sb, c) do { \
int res = SA_OK; \
if ((sb)->cur >= (sb)->end) \
if (SA_OK != (res = _sa_sb_grow(sb, 1))) \
return res; \
*(sb)->cur++ = (c); \
} while (0)
static char *_sa_sb_finish(SAStringBuffer *sb, unsigned long* length) {
*sb->cur = 0;
*length = sb->cur - sb->start;
return sb->start;
}
static void _sa_sb_free(SAStringBuffer *sb) {
free(sb->start);
}
// SANode ---------------------------------------------------------------------
// 属性的数据类型.
enum SANodeTag {
SA_BOOL,
SA_NUMBER,
SA_INT,
SA_DATE,
SA_STRING,
SA_LIST,
SA_DICT
};
struct SAListNode;
typedef struct SANode {
// 引用计数,初始值为 1.
unsigned int ref_count;
// 属性的 key,以 \0 结尾.
char* key;
enum SANodeTag tag;
union {
int bool_;
double number_;
long long int_;
struct {
time_t seconds;
int microseconds;
} date_;
char* string_; // 字符串必须是 UTF-8 编码.
struct SAListNode* array_; // 数组的元素必须是 UTF-8 编码的字符串.
};
} SANode;
typedef struct SAListNode {
// 存储事件属性的单向链表.
struct SAListNode* next;
struct SANode* value;
} SAListNode;
static void _sa_free_node(struct SANode* node);
// 初始化事件属性或用户属性对象.
static struct SANode* _sa_malloc_node(enum SANodeTag tag, const char* key) {
struct SANode* node = (struct SANode*)SA_SAFE_MALLOC(sizeof(SANode));
memset(node, 0, sizeof(struct SANode));
node->ref_count = 1;
node->tag = tag;
if (NULL != key) {
node->key = _sa_strdup(key);
}
return node;
}
static struct SANode* _sa_init_bool_node(const char* key, int bool_) {
struct SANode* node = _sa_malloc_node(SA_BOOL, key);
if (NULL == node) {
return NULL;
}
node->bool_ = bool_;
return node;
}
static struct SANode* _sa_init_number_node(const char* key, double number_) {
struct SANode* node = _sa_malloc_node(SA_NUMBER, key);
if (NULL == node) {
return NULL;
}
node->number_ = number_;
return node;
}
static struct SANode* _sa_init_int_node(const char* key, long long int_) {
struct SANode* node = _sa_malloc_node(SA_INT, key);
if (NULL == node) {
return NULL;
}
node->int_ = int_;
return node;
}
static struct SANode* _sa_init_date_node(const char* key, time_t seconds, int microseconds) {
struct SANode* node = _sa_malloc_node(SA_DATE, key);
if (NULL == node) {
return NULL;
}
node->date_.seconds = seconds;
node->date_.microseconds = microseconds;
return node;
}
static struct SANode* _sa_init_string_node(const char* key, const char* str, unsigned int length) {
struct SANode* node = _sa_malloc_node(SA_STRING, key);
if (NULL == node) {
return NULL;
}
node->string_ = (char*)SA_SAFE_MALLOC(length + 1);
memcpy(node->string_, str, length);
node->string_[length] = 0;
return node;
}
static struct SANode* _sa_init_list_node(const char* key) {
return _sa_malloc_node(SA_LIST, key);
}
static struct SANode* _sa_init_dict_node(const char* key) {
return _sa_malloc_node(SA_DICT, key);
}
static struct SANode* _sa_get_child(const char* key, const struct SANode* parent) {
if (parent->tag != SA_DICT || NULL == key) {
return NULL;
}
struct SAListNode* curr = parent->array_;
while (NULL != curr) {
struct SAListNode* next = curr->next;
if (NULL != curr->value->key && 0 == strncmp(curr->value->key, key, 256)) {
return curr->value;
}
curr = next;
}
return NULL;
}
static void _sa_remove_child(const char* key, struct SANode* parent) {
if (parent->tag != SA_DICT && parent->tag != SA_LIST) {
return;
}
struct SAListNode* prev = NULL;
struct SAListNode* curr = parent->array_;
while (NULL != curr) {
struct SAListNode* next = curr->next;
if (NULL == key || (
(NULL != curr->value->key && 0 == strncmp(curr->value->key, key, 256)))) {
if (NULL != prev) {
prev->next = next;
} else {
parent->array_ = next;
}
_sa_free_node(curr->value);
// SAListNode 对象只在这里 free.
free(curr);
} else {
prev = curr;
}
curr = next;
}
}
static struct SAListNode* _sa_add_child(struct SANode* child, struct SANode* parent) {
if (SA_DICT != parent->tag && SA_LIST != parent->tag) {
return NULL;
}
if (SA_DICT == parent->tag) {
if (NULL == child->key) {
return NULL;
}
_sa_remove_child(child->key, parent);
}
// SAListNode 对象只在这里 malloc.
struct SAListNode* element = (struct SAListNode*)SA_SAFE_MALLOC(sizeof(struct SAListNode));
element->next = parent->array_;
parent->array_ = element;
element->value = child;
// 操作引用计数.
++element->value->ref_count;
return element;
}
// 释放事件属性或用户属性对象.
static void _sa_free_node(struct SANode* node) {
if ((--node->ref_count) == 0) {
if (NULL != node->key) {
free(node->key);
}
// 释放属性的值.
switch(node->tag) {
case SA_STRING:
free(node->string_);
break;
case SA_LIST:
case SA_DICT:
_sa_remove_child(NULL/* remove all child */, node);
break;
default:
// DO NOTHING
break;
}
free(node);
}
}
int _sa_dump_node(const struct SANode* node, SAStringBuffer* sb);
int _sa_dump_dict(const struct SANode* node, SAStringBuffer* sb) {
_sa_sb_putc(sb, '{');
struct SAListNode* child = node->array_;
while (NULL != child) {
_sa_sb_putc(sb, '"');
_sa_sb_put(sb, child->value->key, strlen(child->value->key));
_sa_sb_putc(sb, '"');
_sa_sb_putc(sb, ':');
_sa_dump_node(child->value, sb);
child = child->next;
if (child != NULL) {
_sa_sb_putc(sb, ',');
}
}
_sa_sb_putc(sb, '}');
return SA_OK;
}
int _sa_dump_list(const struct SANode* node, SAStringBuffer* sb) {
_sa_sb_putc(sb, '[');
struct SAListNode* child = node->array_;
while (NULL != child) {
_sa_dump_node(child->value, sb);
child = child->next;
if (child != NULL) {
_sa_sb_putc(sb, ',');
}
}
_sa_sb_putc(sb, ']');
return SA_OK;
}
/*
* Validate a single UTF-8 character starting at @s.
* The string must be null-terminated.
*
* If it's valid, return its length (1 thru 4).
* If it's invalid or clipped, return 0.
*
* This function implements the syntax given in RFC3629, which is
* the same as that given in The Unicode Standard, Version 6.0.
*
* It has the following properties:
*
* * All codepoints U+0000..U+10FFFF may be encoded,
* except for U+D800..U+DFFF, which are reserved
* for UTF-16 surrogate pair encoding.
* * UTF-8 byte sequences longer than 4 bytes are not permitted,
* as they exceed the range of Unicode.
* * The sixty-six Unicode "non-characters" are permitted
* (namely, U+FDD0..U+FDEF, U+xxFFFE, and U+xxFFFF).
*/
static int sa_utf8_validate_cz(const char *s) {
unsigned char c = *s++;
if (c <= 0x7F) { /* 00..7F */
return 1;
} else if (c <= 0xC1) { /* 80..C1 */
/* Disallow overlong 2-byte sequence. */
return 0;
} else if (c <= 0xDF) { /* C2..DF */
/* Make sure subsequent byte is in the range 0x80..0xBF. */
if (((unsigned char)*s++ & 0xC0) != 0x80) {
return 0;
}
return 2;
} else if (c <= 0xEF) { /* E0..EF */
/* Disallow overlong 3-byte sequence. */
if (c == 0xE0 && (unsigned char)*s < 0xA0) {
return 0;
}
/* Disallow U+D800..U+DFFF. */
if (c == 0xED && (unsigned char)*s > 0x9F) {
return 0;
}
/* Make sure subsequent bytes are in the range 0x80..0xBF. */
if (((unsigned char)*s++ & 0xC0) != 0x80) {
return 0;
}
if (((unsigned char)*s++ & 0xC0) != 0x80) {
return 0;
}
return 3;
} else if (c <= 0xF4) { /* F0..F4 */
/* Disallow overlong 4-byte sequence. */
if (c == 0xF0 && (unsigned char)*s < 0x90) {
return 0;
}
/* Disallow codepoints beyond U+10FFFF. */
if (c == 0xF4 && (unsigned char)*s > 0x8F) {
return 0;
}
/* Make sure subsequent bytes are in the range 0x80..0xBF. */
if (((unsigned char)*s++ & 0xC0) != 0x80) {
return 0;
}
if (((unsigned char)*s++ & 0xC0) != 0x80) {
return 0;
}
if (((unsigned char)*s++ & 0xC0) != 0x80) {
return 0;
}
return 4;
} else { /* F5..FF */
return 0;
}
}
/* Validate a null-terminated UTF-8 string. */
static SABool sa_utf8_validate(const char *s) {
int len;
for (; *s != 0; s += len) {
len = sa_utf8_validate_cz(s);
if (len == 0) {
return SA_FALSE;
}
}
return SA_TRUE;
}
/*
* Read a single UTF-8 character starting at @s,
* returning the length, in bytes, of the character read.
*
* This function assumes input is valid UTF-8,
* and that there are enough characters in front of @s.
*/
static int utf8_read_char(const char *s, unsigned int *out) {
const unsigned int *c = (const unsigned int*) s;
if (c[0] <= 0x7F) {
/* 00..7F */
*out = c[0];
return 1;
} else if (c[0] <= 0xDF) {
/* C2..DF (unless input is invalid) */
*out = ((unsigned int)c[0] & 0x1F) << 6 |
((unsigned int)c[1] & 0x3F);
return 2;
} else if (c[0] <= 0xEF) {
/* E0..EF */
*out = ((unsigned int)c[0] & 0xF) << 12 |
((unsigned int)c[1] & 0x3F) << 6 |
((unsigned int)c[2] & 0x3F);
return 3;
} else {
/* F0..F4 (unless input is invalid) */
*out = ((unsigned int)c[0] & 0x7) << 18 |
((unsigned int)c[1] & 0x3F) << 12 |
((unsigned int)c[2] & 0x3F) << 6 |
((unsigned int)c[3] & 0x3F);
return 4;
}
}
/*
* Encodes a 16-bit number into hexadecimal,
* writing exactly 4 hex chars.
*/
static int _sa_write_hex16(char *out, uint16_t val) {
const char *hex = "0123456789ABCDEF";
*out++ = hex[(val >> 12) & 0xF];
*out++ = hex[(val >> 8) & 0xF];
*out++ = hex[(val >> 4) & 0xF];
*out++ = hex[ val & 0xF];
return 4;
}
/*
* Construct a UTF-16 surrogate pair given a Unicode codepoint.
*
* @unicode must be U+10000..U+10FFFF.
*/
static void _sa_to_surrogate_pair(unsigned int unicode, uint16_t *uc, uint16_t *lc) {
unsigned int n = unicode - 0x10000;
*uc = ((n >> 10) & 0x3FF) | 0xD800;
*lc = (n & 0x3FF) | 0xDC00;
}
int _sa_dump_string(const struct SANode* node, SAStringBuffer* sb) {
SABool escape_unicode = SA_FALSE;
const char *s = node->string_;
char *b;
if (!sa_utf8_validate(s)) {
fprintf(stderr, "Invalid utf-8 string.");
return SA_INVALID_PARAMETER_ERROR;
}
/*
* 14 bytes is enough space to write up to two
* \uXXXX escapes and two quotation marks.
*/
_sa_sb_need(sb, 14);
b = sb->cur;
*b++ = '"';
while (*s != 0) {
unsigned char c = *s++;
/* Encode the next character, and write it to b. */
switch (c) {
case '"':
*b++ = '\\';
*b++ = '"';
break;
case '\\':
*b++ = '\\';
*b++ = '\\';
break;
case '\b':
*b++ = '\\';
*b++ = 'b';
break;
case '\f':
*b++ = '\\';
*b++ = 'f';
break;
case '\n':
*b++ = '\\';
*b++ = 'n';
break;
case '\r':
*b++ = '\\';
*b++ = 'r';
break;
case '\t':
*b++ = '\\';
*b++ = 't';
break;
default: {
int len;
s--;
len = sa_utf8_validate_cz(s);
if (len == 0) {
/*
* Handle invalid UTF-8 character gracefully in production
* by writing a replacement character (U+FFFD)
* and skipping a single byte.
*
* This should never happen when assertions are enabled
* due to the assertion at the beginning of this function.
*/
if (escape_unicode) {
memcpy(b, "\\uFFFD", 6);
b += 6;
} else {
*b++ = 0xEF;
*b++ = 0xBF;
*b++ = 0xBD;
}
s++;
} else if (c < 0x1F || (c >= 0x80 && escape_unicode)) {
/* Encode using \u.... */
unsigned int unicode;
s += utf8_read_char(s, &unicode);
if (unicode <= 0xFFFF) {
*b++ = '\\';
*b++ = 'u';
b += _sa_write_hex16(b, unicode);
} else {
/* Produce a surrogate pair. */
uint16_t uc, lc;
// assert(unicode <= 0x10FFFF);
_sa_to_surrogate_pair(unicode, &uc, &lc);
*b++ = '\\';
*b++ = 'u';
b += _sa_write_hex16(b, uc);
*b++ = '\\';
*b++ = 'u';
b += _sa_write_hex16(b, lc);
}
} else {
/* Write the character directly. */
while (len--)
*b++ = *s++;
}
break;
}
}
/*
* Update *sb to know about the new bytes,
* and set up b to write another encoded character.
*/
sb->cur = b;
_sa_sb_need(sb, 14);
b = sb->cur;
}
*b++ = '"';
sb->cur = b;
return SA_OK;
}
// 将 struct SANode JSON 序列化至文件.
int _sa_dump_node(const struct SANode* node, SAStringBuffer* sb) {
if (NULL == node || NULL == sb) {
return SA_INVALID_PARAMETER_ERROR;
}
char buf[64];
struct tm tm;
switch(node->tag) {
case SA_BOOL:
if (node->bool_) {
_sa_sb_put(sb, "true", strlen("true"));
} else {
_sa_sb_put(sb, "false", strlen("false"));
}
break;
case SA_NUMBER:
snprintf(buf, 64, "%.3f", node->number_);
_sa_sb_put(sb, buf, strlen(buf));
break;
case SA_INT:
snprintf(buf, 64, "%lld", node->int_);
_sa_sb_put(sb, buf, strlen(buf));
break;
case SA_DATE:
LOCALTIME(&node->date_.seconds, &tm);
snprintf(buf, 64, "\"%04d-%02d-%02d %02d:%02d:%02d.%03d\"",
tm.tm_year + 1900,
tm.tm_mon + 1,
tm.tm_mday,
tm.tm_hour,
tm.tm_min,
tm.tm_sec,
node->date_.microseconds);
_sa_sb_put(sb, buf, strlen(buf));
break;
case SA_STRING:
_sa_dump_string(node, sb);
break;
case SA_LIST:
_sa_dump_list(node, sb);
break;
case SA_DICT:
_sa_dump_dict(node, sb);
break;
default:
return SA_INVALID_PARAMETER_ERROR;
}
return SA_OK;
}
// Properites -----------------------------------------------------------------
SAProperties* sa_init_properties() {
return _sa_init_dict_node("properties");
}
void sa_free_properties(SAProperties* properties) {
_sa_free_node(properties);
}
int sa_add_bool(const char* key, SABool bool_, SAProperties* properties) {
if (NULL == properties) {
fprintf(stderr, "Parameter 'properties' is NULL.");
return SA_INVALID_PARAMETER_ERROR;
}
// TODO: check key
struct SANode* child = _sa_init_bool_node(key, bool_);
if (NULL == child) {
fprintf(stderr, "Out of memory.");
return SA_MALLOC_ERROR;
}
_sa_add_child(child, properties);
_sa_free_node(child);
return SA_OK;
}
int sa_add_number(const char* key, double number_, SAProperties* properties) {
if (NULL == properties) {
fprintf(stderr, "Parameter 'properties' is NULL.");
return SA_INVALID_PARAMETER_ERROR;
}
// TODO: check key
struct SANode* child = _sa_init_number_node(key, number_);
if (NULL == child) {
fprintf(stderr, "Out of memory.");
return SA_MALLOC_ERROR;
}
_sa_add_child(child, properties);
_sa_free_node(child);
return SA_OK;
}
int sa_add_int(const char* key, long long int_, SAProperties* properties) {
if (NULL == properties) {
fprintf(stderr, "Parameter 'properties' is NULL.");
return SA_INVALID_PARAMETER_ERROR;
}
// TODO: check key
struct SANode* child = _sa_init_int_node(key, int_);
if (NULL == child) {
fprintf(stderr, "Out of memory.");
return SA_MALLOC_ERROR;
}
_sa_add_child(child, properties);
_sa_free_node(child);
return SA_OK;
}
int sa_add_date(const char* key, time_t seconds, int microseconds, SAProperties* properties) {
if (NULL == properties) {
fprintf(stderr, "Parameter 'properties' is NULL.");
return SA_INVALID_PARAMETER_ERROR;
}
// TODO: check key
struct SANode* child = _sa_init_date_node(key, seconds, microseconds);
if (NULL == child) {
fprintf(stderr, "Out of memory.");
return SA_MALLOC_ERROR;
}
_sa_add_child(child, properties);
_sa_free_node(child);
return SA_OK;
}
int sa_add_string(const char* key, const char* string_, unsigned int length, SAProperties* properties) {
if (NULL == properties) {
fprintf(stderr, "Parameter 'properties' is NULL.");
return SA_INVALID_PARAMETER_ERROR;
}
// TODO: check key
struct SANode* child = _sa_init_string_node(key, string_, length);
if (NULL == child) {
fprintf(stderr, "Out of memory.");
return SA_MALLOC_ERROR;
}
_sa_add_child(child, properties);
_sa_free_node(child);
return SA_OK;
}
// 向事件属性或用户属性的 List 类型的属性中插入新对象,对象必须是 String 类型的.
int sa_append_list(const char* key, const char* string_, unsigned int length, SAProperties* properties) {
if (NULL == properties) {
fprintf(stderr, "Parameter 'properties' is NULL.");
return SA_INVALID_PARAMETER_ERROR;
}
// TODO: check key
// 向 properties 中添加 List 对象,若该对象已存在,则使用该对象.
struct SANode* list = _sa_get_child(key, properties);
if (NULL == list) {
list = _sa_init_list_node(key);
if (NULL == list) {
return SA_MALLOC_ERROR;
}
_sa_add_child(list, properties);
} else {
++list->ref_count;
}
// 向 List 对象中添加字符串属性.
struct SANode* str_child = _sa_init_string_node(NULL, string_, length);
if (NULL == str_child) {
return SA_MALLOC_ERROR;
}
_sa_add_child(str_child, list);
_sa_free_node(str_child);
_sa_free_node(list);
return SA_OK;
}
// Logging Consumer -----------------------------------------------------------
typedef struct {
char file_name[512];
char file_name_prefix[512];
// 日志文件日期,存为数字,20170101.
int date;
// 输出文件句柄.
FILE* file;
} SALoggingConsumerInter;
static int _sa_get_current_date() {
time_t t = time(NULL);
struct tm tm;
LOCALTIME(&t, &tm);
return tm.tm_year * 10000 + (tm.tm_mon + 1) * 100 + tm.tm_mday;
}
static int _sa_logging_consumer_flush(void* this_) {
SALoggingConsumerInter* inter = (SALoggingConsumerInter*)this_;
if (NULL != inter->file && 0 == fflush(inter->file)) {
return SA_OK;
}
return SA_IO_ERROR;
}
static int _sa_logging_consumer_close(void* this_) {
if (NULL == this_) {
return SA_INVALID_PARAMETER_ERROR;
}
SALoggingConsumerInter* inter = (SALoggingConsumerInter*)this_;
if (NULL != inter->file) {
fflush(inter->file);
fclose(inter->file);
inter->file = NULL;
}
return SA_OK;
}
static int _sa_logging_consumer_send(void* this_, const char* event, unsigned long length) {
if (NULL == this_ || NULL == event) {
return SA_INVALID_PARAMETER_ERROR;
}
SALoggingConsumerInter* inter = (SALoggingConsumerInter*)this_;
// 判断日志文件的日期是否为当日.
int date = _sa_get_current_date();
if (date != inter->date) {
_sa_logging_consumer_close(this_);
inter->date = date;
snprintf(inter->file_name, 512, "%s.log.%d", inter->file_name_prefix, date);
// Append 模式打开文件.
FOPEN(&inter->file, inter->file_name, "a");
if (NULL == inter->file) {
fprintf(stderr, "Failed to open file.");
return SA_IO_ERROR;
}
}
fwrite(event, length, 1, inter->file);
fwrite("\n", 1, 1, inter->file);
return SA_OK;
}
// 初始化 Logging Consumer.
int sa_init_logging_consumer(const char* file_name, SALoggingConsumer** sa) {
if (strlen(file_name) > 500) {
fprintf(stderr,"The file name length must not exceed 500.");
return SA_INVALID_PARAMETER_ERROR;
}
SALoggingConsumerInter* inter = (SALoggingConsumerInter*)SA_SAFE_MALLOC(sizeof(SALoggingConsumerInter));
memset(inter, 0, sizeof(SALoggingConsumerInter));
memcpy(inter->file_name_prefix, file_name, strlen(file_name));
*sa = (SALoggingConsumer*)SA_SAFE_MALLOC(sizeof(SALoggingConsumer));
(*sa)->this_ = (void*)inter;
(*sa)->op.send = &_sa_logging_consumer_send;
(*sa)->op.flush = &_sa_logging_consumer_flush;
(*sa)->op.close = &_sa_logging_consumer_close;
return SA_OK;
}
// Sensors Analytics ----------------------------------------------------------
typedef struct SensorsAnalytics {
// 存储事件公共属性.
SAProperties* super_properties;
#if defined(USE_POSIX)
// Mutex
pthread_mutex_t mutex;
// 检查事件、属性规范的正则表达式.
regex_t regex[2];
#elif defined(_WIN32)
CRITICAL_SECTION mutex;
pcre* regex[2];
#endif
struct SAConsumer* consumer;
} SensorsAnalytics;
int sa_init(struct SAConsumer* consumer, SensorsAnalytics** sa) {
*sa = (SensorsAnalytics*)SA_SAFE_MALLOC(sizeof(SensorsAnalytics));
(*sa)->super_properties = sa_init_properties();
if (NULL == (*sa)->super_properties) {
free(*sa);
return SA_MALLOC_ERROR;
}
#if defined(USE_POSIX)
if (pthread_mutex_init(&((*sa)->mutex), NULL) != 0) {
fprintf(stderr, "Initialize mutex error.");
return SA_MALLOC_ERROR;
}
if (0 != regcomp(&((*sa)->regex[0]), KEY_WORD_PATTERN, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
fprintf(stderr, "Compile regex error.");