-
Notifications
You must be signed in to change notification settings - Fork 1
/
logger.h
3107 lines (2767 loc) · 93.3 KB
/
logger.h
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
/*
* GreaseLogger.h
*
* Created on: Aug 27, 2014
* Author: ed
* (c) 2014, Framez Inc
*/
#ifndef GreaseLogger_H_
#define GreaseLogger_H_
#include <v8.h>
#include <node.h>
#include <uv.h>
#include <node_buffer.h>
#include "nan.h"
using namespace node;
using namespace v8;
#include <sys/types.h>
#include <sys/socket.h>
#include <linux/if.h>
#include <linux/if_tun.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <linux/fs.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <uv.h>
#include <time.h>
// Linux thing:
#include <sys/timeb.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/select.h>
#include <TW/tw_alloc.h>
#include <TW/tw_fifo.h>
#include <TW/tw_khash.h>
#include <TW/tw_circular.h>
#include "grease_client.h"
#include "error-common.h"
#include <gperftools/tcmalloc.h>
#define LMALLOC tc_malloc_skip_new_handler
#define LCALLOC tc_calloc
#define LREALLOC tc_realloc
#define LFREE tc_free
extern "C" char *local_strdup_safe(const char *s);
namespace Grease {
using namespace TWlib;
struct Alloc_LMALLOC {
static void *malloc (tw_size nbytes) { return LMALLOC((int) nbytes); }
static void *calloc (tw_size nelem, tw_size elemsize) { return LCALLOC((size_t) nelem,(size_t) elemsize); }
static void *realloc(void *d, tw_size s) { return LREALLOC(d,(size_t) s); }
static void free(void *p) { LFREE(p); }
static void sync(void *addr, tw_size len, int flags = 0) { } // does nothing - not shared memory
static void *memcpy(void *d, const void *s, size_t n) { return ::memcpy(d,s,n); };
static void *memmove(void *d, const void *s, size_t n) { return ::memmove(d,s,n); };
static int memcmp(void *l, void *r, size_t n) { return ::memcmp(l, r, n); }
static void *memset(void *d, int c, size_t n) { return ::memset(d,c,n); }
static const char *ALLOC_NOMEM_ERROR_MESSAGE;
};
typedef TWlib::Allocator<Alloc_LMALLOC> LoggerAlloc;
struct uint32_t_eqstrP {
inline int operator() (const uint32_t *l, const uint32_t *r) const
{
return (*l == *r);
}
};
struct TargetId_eqstrP {
inline int operator() (const TargetId *l, const TargetId *r) const
{
return (*l == *r);
}
};
struct uint64_t_eqstrP {
inline int operator() (const uint64_t *l, const uint64_t *r) const
{
return (*l == *r);
}
};
// http://broken.build/2012/11/10/magical-container_of-macro/
// http://www.kroah.com/log/linux/container_of.html
#ifndef offsetof
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#endif
#ifndef container_of
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
#endif
#if UV_VERSION_MAJOR < 1
#define ERROR_UV(msg, code, loop) do { \
uv_err_t __err = uv_last_error(loop); \
fprintf(stderr, "%s: [%s: %s]\n", msg, uv_err_name(__err), uv_strerror(__err)); \
} while(0)
#else
#define ERROR_UV(msg, code, loop) do { \
fprintf(stderr, "%s: [%s: %s]\n", msg, uv_err_name(code), uv_strerror(code)); \
} while(0)
#endif
// assert(0);
#define COMMAND_QUEUE_NODE_SIZE 200
#define INTERNAL_QUEUE_SIZE 200 // must be at least as big as PRIMARY_BUFFER_ENTRIES
#define V8_LOG_CALLBACK_QUEUE_SIZE 10
#define MAX_TARGET_CALLBACK_STACK 20
#define TARGET_CALLBACK_QUEUE_WAIT 2000000 // 2 seconds
#define MAX_ROTATED_FILES 10
#define DEFAULT_TARGET GREASE_DEFAULT_TARGET_ID
#define DEFAULT_ID 0
#define ALL_LEVELS 0xFFFFFFFF
#define GREASE_STDOUT 1
#define GREASE_STDERR 2
#define GREASE_BAD_FD -1
#define TTY_NORMAL 0
#define TTY_RAW 1
#define NOTREADABLE 0
#define READABLE 1
#define META_GET_LIST(m,n) ((FilterList *)m._cached_lists[n])
#define META_SET_LIST(m,n,p) do { m._cached_lists[n] = p; } while(0)
// use these to fix "NO BUFFERS" ... greaseLog will never block if it's IO can't keep up with logging
// and instead will drop log info
#define NUM_BANKS 4
#define LOGGER_DEFAULT_CHUNK_SIZE 1500
#define DEFAULT_BUFFER_SIZE 2000
#define PRIMARY_BUFFER_ENTRIES 100 // this is the amount of entries we hold in memory, which will be logged by the logger thread.
// each entry is DEFAULT_BUFFER_SIZE
// if a log message is > than DEFAULT_BUFFER_SIZE, it logged as an overflow.
#define PRIMARY_BUFFER_SIZE (PRIMARY_BUFFER_ENTRIES*DEFAULT_BUFFER_SIZE)
// Sink settings
#define SINK_BUFFER_SIZE (DEFAULT_BUFFER_SIZE*2)
#define BUFFERS_PER_SINK 4
// this number can be bigger, but why?
// anything larger than this will just be dropped. Prevents a buggy program
// from chewing up gobs of log memory.
#define MAX_LOG_MESSAGE_SIZE 65536
#define DEFAULT_MODE_FILE_TARGET (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)
#define DEFAULT_FLAGS_FILE_TARGET (O_APPEND | O_CREAT | O_WRONLY)
//#define LOGGER_HEAVY_DEBUG 1
#define MAX_IDENTICAL_FILTERS 16
#ifdef LOGGER_HEAVY_DEBUG
#pragma message "Build is Debug Heavy!!"
// confused? here: https://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html
#define HEAVY_DBG_OUT(s,...) fprintf(stderr, "**DEBUG2** " s "\n", ##__VA_ARGS__ )
#define IF_HEAVY_DBG( x ) { x }
#else
#define HEAVY_DBG_OUT(s,...) {}
#define IF_DBG( x ) {}
#endif
const int MAX_IF_NAME_LEN = 16;
class GreaseLogger : public Nan::ObjectWrap {
public:
typedef void (*actionCB)(GreaseLogger *, _errcmn::err_ev &err, void *data);
// struct start_info {
// Handle<Function> callback;
// start_info() : callback() {}
// };
class heapBuf final {
public:
class heapBufManager {
public:
virtual void returnBuffer(heapBuf *b) = 0;
};
heapBufManager *return_cb;
uv_buf_t handle;
int used;
// uv_buf_t getUvBuf() {
// return uv_buf_init(handle.base,handle.len);
// }
explicit heapBuf(int n) : return_cb(NULL), used(0) {
handle.len = n;
if(n > 0)
handle.base = (char *) LMALLOC(n);
else
handle.base = NULL;
}
void sprintf(const char *format, ... ) {
char buffer[512];
va_list args;
va_start (args, format);
RawLogLen len = (RawLogLen) vsnprintf (buffer,512,format, args);
va_end (args);
if(handle.base) LFREE(handle.base);
handle.len = len;
handle.base = (char *) LMALLOC(handle.len);
::memset((void *)handle.base,(int) 0,handle.len);
::memcpy(handle.base,buffer,len);
used = handle.len;
}
heapBuf(const char *d, int n) : return_cb(NULL), used(0) {
handle.len = n;
handle.base = (char *) LMALLOC(n);
::memcpy(handle.base,d,n);
}
heapBuf(heapBuf &&o) {
handle = o.handle;
used = o.used; o.used =0;
o.handle.base = NULL;
o.handle.len = 0;
return_cb = o.return_cb; o.return_cb = NULL;
}
void malloc(int n) {
if(handle.base) LFREE(handle.base);
handle.len = n;
handle.base = (char *) LMALLOC(handle.len);
used = 0;
}
int memcpy(const char *s, size_t l,const char *append_str=nullptr) {
if(handle.base) {
if(append_str) {
bool append = false;
int app_len = 0;
if(l > handle.len) {
app_len = strlen(append_str);
l = (int) handle.len-app_len;
append = true;
::memcpy((char*)handle.base+l,append_str,app_len);
}
::memcpy(handle.base,s,l);
used = l + app_len;
return l;
} else {
if(l > handle.len) l = (int) handle.len;
::memcpy(handle.base,s,l);
used = l;
return l;
}
} else
return 0;
}
heapBuf duplicate() {
heapBuf ret;
if(handle.base) {
ret.handle.base = (char *) LMALLOC(handle.len);
ret.handle.len = handle.len;
::memcpy(ret.handle.base,handle.base,handle.len);
ret.used = used;
}
ret.return_cb = return_cb;
return ret;
}
bool empty() {
if(handle.base != NULL) return false; else return true;
}
void returnBuf() {
if(return_cb) return_cb->returnBuffer(this);
}
explicit heapBuf() : return_cb(NULL) { handle.base = NULL; handle.len = 0; };
~heapBuf() {
// DBG_OUT(" debug FREE %x\n",handle.base);
if(handle.base) LFREE(handle.base);
}
// I find it too confusing to having multiple overloaded '=' operators - so we have this
void assign(heapBuf &o) {
returnBuf();
if(handle.base) LFREE(handle.base);
handle.base = NULL;
if(o.handle.base && o.handle.len > 0) {
handle.base = (char *) LMALLOC(o.handle.len);
handle.len = o.handle.len;
::memcpy(handle.base,o.handle.base,handle.len);
}
}
heapBuf& operator=(heapBuf&& o) {
used = o.used; o.used =0;
handle = o.handle;
o.handle.base = NULL;
o.handle.len = 0;
return_cb = o.return_cb; o.return_cb = NULL;
return *this;
}
};
class singleLog final {
private:
int _ref_cnt;
protected:
public:
extra_logMeta meta;
heapBuf buf;
static const int NOT_REFED = -2; // no reference counting
static const int INIT_REF = 1; // no reference counting
singleLog(const char *d, int l, const logMeta &_m) : _ref_cnt(NOT_REFED), meta(), buf(d,l) {
meta.m = _m;
}
singleLog(int len) : _ref_cnt(NOT_REFED), meta(), buf(len) {
ZERO_LOGMETA(meta.m);
}
singleLog() = delete;
static singleLog *heapSingleLog(int len) {
singleLog *ret = new singleLog(len);
ret->_ref_cnt = INIT_REF;
return ret;
}
static singleLog *heapSingleLog(const char *d, int l, const logMeta &_m) {
singleLog *ret = new singleLog(d,l,_m);
ret->_ref_cnt = INIT_REF;
return ret;
}
void clear() {
buf.used = 0;
_ref_cnt = 1;
ZERO_LOGMETA(meta.m);
}
void incRef() {
if(_ref_cnt != NOT_REFED) {
DBG_OUT("incRef: %p (%d)\n", this, _ref_cnt);
_ref_cnt++;
}
}
void decRef() {
if(_ref_cnt != NOT_REFED) {
DBG_OUT("decRef: %p (%d)\n", this, _ref_cnt);
_ref_cnt--;
if(_ref_cnt < 1) {
DBG_OUT("ref ... delete: %p (%d)\n", this, _ref_cnt);
delete this;
}
}
}
int getRef() {
return _ref_cnt;
}
};
static const int MAX_OVERFLOW_BUFFERS = 4;
class overflowWriteOut final {
public:
int N;
singleLog *bufs[MAX_OVERFLOW_BUFFERS];
protected:
void decRef() {
for(int n=0;n<MAX_OVERFLOW_BUFFERS;n++)
if(bufs[n]) bufs[n]->decRef();
}
public:
overflowWriteOut() : N(0) {
for(int n=0;n<MAX_OVERFLOW_BUFFERS;n++)
bufs[n] = NULL;
}
void addBuffer(singleLog *l) {
assert(N < MAX_OVERFLOW_BUFFERS);
bufs[N] = l;
N++;
}
int totalSize() {
int ret = 0;
for(int n=0;n<MAX_OVERFLOW_BUFFERS;n++)
if(bufs[n]) {
ret += bufs[n]->buf.handle.len;
}
return ret;
}
void copyAllTo(char *d) {
char *walk = d;
for(int n=0;n<MAX_OVERFLOW_BUFFERS;n++)
if(bufs[n]) {
memcpy(d,bufs[n]->buf.handle.base,bufs[n]->buf.handle.len);
walk += bufs[n]->buf.handle.len;
}
}
~overflowWriteOut() {
decRef();
}
};
class logLabel final {
public:
heapBuf buf;
logLabel(const char *s, const char *format = nullptr) : buf() {
if(format != nullptr)
buf.sprintf(format,s);
else
buf.sprintf("%s",s);
}
size_t length() {
return buf.handle.len;
}
logLabel() : buf() {}
bool empty() { return buf.empty(); }
void setUTF8(const char *s, int len) {
buf.malloc(len+1);
memset(buf.handle.base,0,(size_t) len+1);
buf.memcpy(s,(size_t) len);
}
logLabel& operator=(logLabel &o) {
buf.assign(o.buf);
return *this;
}
/**
* Creates a log label from a utf8 string with specific len. The normal cstor
* can be used to do this also, but this ensures the entire string is encoded (if there are bugs
* with your sprintf, etc for UTF8)
* @param s
* @param len
* @return
*/
static logLabel *fromUTF8(const char *s, int len) {
logLabel *l = new logLabel();
l->buf.malloc((size_t) len+1);
memset(l->buf.handle.base,0,(size_t) len+1);
l->buf.memcpy(s,len);
return l;
}
};
typedef TWlib::TW_KHash_32<uint32_t, logLabel *, TWlib::TW_Mutex, uint32_t_eqstrP, TWlib::Allocator<LoggerAlloc> > LabelTable;
class delim_data final {
public:
heapBuf delim;
heapBuf delim_output;
delim_data() : delim(), delim_output() {}
delim_data(delim_data&& o)
: delim(std::move(o.delim)),
delim_output(std::move(o.delim_output)) {}
void setDelim(char *s,int l) {
delim.malloc(l);
delim.memcpy(s,l);
}
void setOutputDelim(char *s,int l) {
delim_output.malloc(l);
delim_output.memcpy(s,l);
}
delim_data duplicate() {
delim_data d;
d.delim = delim.duplicate();
d.delim_output = delim_output.duplicate();
return d;
}
delim_data& operator=(delim_data&& o) {
this->delim = std::move(o.delim);
this->delim_output = std::move(o.delim_output);
return *this;
}
};
class target_start_info final {
public:
bool needsAsyncQueue; // if the callback must be called in the v8 thread
_errcmn::err_ev err; // used if above is true
actionCB cb;
// start_info *system_start_info;
Nan::Callback *targetStartCB;
TargetId targId;
target_start_info() : needsAsyncQueue(false), err(), cb(NULL), targetStartCB(NULL), targId(0) {}
target_start_info& operator=(target_start_info&& o) {
if(o.err.hasErr())
err = std::move(o.err);
cb = o.cb; o.cb = NULL;
targetStartCB = o.targetStartCB; o.targetStartCB = NULL;
targId = o.targId;
return *this;
}
};
struct Opts_t {
uv_mutex_t mutex;
bool show_errors;
bool callback_errors;
int bufferSize; // size of each buffer
int chunkSize;
uint32_t levelFilterOutMask;
bool defaultFilterOut;
Opts_t() : show_errors(false), callback_errors(false), levelFilterOutMask(0), defaultFilterOut(false) {
uv_mutex_init(&mutex);
}
void lock() {
uv_mutex_lock(&mutex);
}
void unlock() {
uv_mutex_unlock(&mutex);
}
};
Opts_t Opts;
protected:
static GreaseLogger *LOGGER; // this class is a Singleton
// these are the primary buffers for all log messages. Logs are put here before targets are found,
// or anything else happens (other than sift())
TWlib::tw_safeCircular<singleLog *, LoggerAlloc > masterBufferAvail; // <-- available buffers (starts out full)
uv_thread_t logThreadId;
uv_async_t asyncV8LogCallback; // used to wakeup v8 to call log callbacks (see v8LogCallbacks)
uv_async_t asyncTargetCallback; // used to wakeup v8 to call callbacks on target starts
uv_async_t asyncRefLogger; // used to signal whether the node/v8 thread can exit or not (used as V8 ref/unref keep-alive handle)
uv_async_t asyncUnrefLogger; // used to signal whether the node/v8 thread can exit or not
uv_mutex_t mutexRefLogger;
uint32_t needV8; // 0 means can exit, > 0 mean can't
uint32_t needGreaseThread;
// when understanding the uv_async stuff, it's important to read this note: https://nikhilm.github.io/uvbook/threads.html#inter-thread-communication
// and realize that multiple calls to async_send only guarantee at least _one_ call of the callback
void refGreaseInGrease() {
uv_mutex_lock(&mutexRefLogger);
DBG_OUT("[ask for ref] needGreaseThread=%d",needGreaseThread+1);
if(needGreaseThread == 0) {
uv_ref((uv_handle_t *)&flushTimer); // we use the flush timer to keep the grease thread up...
startFlushTimer();
}
needGreaseThread++;
uv_mutex_unlock(&mutexRefLogger);
}
void unrefGreaseInGrease() {
uv_mutex_lock(&mutexRefLogger);
assert(needGreaseThread > 0);
DBG_OUT("[unref] needGreaseThread=%d",needGreaseThread-1);
needGreaseThread--;
if(needGreaseThread < 1) {
uv_unref((uv_handle_t *)&flushTimer);
stopFlushTimer();
}
uv_mutex_unlock(&mutexRefLogger);
}
void refFromV8() {
uv_mutex_lock(&mutexRefLogger);
if(needV8 == 0) {
DBG_OUT("[ask for ref] needV8=%d",needV8);
uv_async_send(&asyncRefLogger);
}
needV8++;
uv_mutex_unlock(&mutexRefLogger);
}
// to be called from non-V8 thread
void unrefFromV8() {
uv_mutex_lock(&mutexRefLogger);
assert(needV8 > 0); // FIXME
needV8--;
if(needV8 < 1) {
uv_async_send(&asyncUnrefLogger);
}
uv_mutex_unlock(&mutexRefLogger);
}
// to be called from V8 thread
void unrefFromV8_inV8() {
uv_mutex_lock(&mutexRefLogger);
assert(needV8 > 0); // FIXME
needV8--;
DBG_OUT("[unref] needV8=%d",needV8);
if(needV8 == 0) {
uv_unref((uv_handle_t *)&asyncRefLogger);
}
int n = uv_loop_alive(uv_default_loop());
DBG_OUT("v8 loop_alive=%d\n",n);
uv_mutex_unlock(&mutexRefLogger);
}
#if UV_VERSION_MAJOR > 0
static void refCb_Logger(uv_async_t* handle) {
#else
static void refCb_Logger(uv_async_t* handle, int status) {
#endif
/* After closing the async handle, it will no longer keep the loop alive. */
// uv_mutex_lock(&LOGGER->mutexRefLogger);
uv_ref((uv_handle_t *)&LOGGER->asyncRefLogger);
// uv_mutex_unlock(&LOGGER->mutexRefLogger);
}
#if UV_VERSION_MAJOR > 0
static void unrefCb_Logger(uv_async_t* handle) {
#else
static void unrefCb_Logger(uv_async_t* handle, int status) {
#endif
// uv_mutex_lock(&LOGGER->mutexRefLogger);
uv_unref((uv_handle_t *)&LOGGER->asyncRefLogger);
// uv_mutex_unlock(&LOGGER->mutexRefLogger);
}
TWlib::tw_safeCircular<target_start_info *, LoggerAlloc > targetCallbackQueue;
_errcmn::err_ev err;
// Definitions:
// Target - a final place a log entry goes: TTY, file, etc.
// Filter - a condition, which if matching, will cause a log to go to a target
// FilterHash - a number used to point to one or more filters
// Log entry - the log entry (1) - synonymous with a single call to log() or logSync()
// Meta - the data in a log Entry beyond the message itself
// Default target - where stuff goes if no matching filter is found
//
//
// filter id -> { [N1:0 0:N2 N1:N2], [level mask], [target] }
// table:tag -> N1 --> [filter id list]
// table:origin -> N2 --> [filter id list]
// search N1:0 0:N2 N1:N2 --> [filter id list]
// filterMasterTable: uint64_t -> [ filter id list ]
// { tag: "mystuff", origin: "crazy.js", level" 0x02 }
uv_mutex_t nextIdMutex;
FilterId nextFilterId;
TargetId nextTargetId;
SinkId nextSinkId;
class Filter final {
public:
bool _disabled;
FilterId id;
LevelMask levelMask;
TargetId targetId;
logLabel preFormat;
logLabel postFormatPreMsg;
logLabel postFormat;
Filter() : preFormat(), postFormat() {
id = 0; // an ID of 0 means - empty Filter
levelMask = 0;
targetId = 0;
_disabled = false;
};
Filter(FilterId id, LevelMask mask, TargetId t) : _disabled(false), id(id), levelMask(mask), targetId(t), preFormat(), postFormatPreMsg(), postFormat() {}
// Filter(Filter &&o) : id(o.id), levelMask(o.mask), targetId(o.t) {};
Filter(Filter &o) : _disabled(false), id(o.id), levelMask(o.levelMask), targetId(o.targetId) {};
Filter& operator=(Filter& o) {
id = o.id;
levelMask = o.levelMask;
targetId = o.targetId;
preFormat = o.preFormat;
postFormatPreMsg = o.postFormatPreMsg;
postFormat = o.postFormat;
return *this;
}
};
class FilterList final {
public:
Filter list[MAX_IDENTICAL_FILTERS]; // a non-zero entry is valid. when encountering the first zero, the rest array elements are skipped
LevelMask bloom; // this is the bloom filter for the list. If this does not match, the list does not log this level
bool filterOut; // if true, then this entire list is filtered out - and will not be logged.
FilterList() : bloom(0), filterOut(false) {}
inline bool valid(LevelMask m) {
return (bloom & m);
}
inline bool add(Filter &filter) {
bool ret = false;
for(int n=0;n<MAX_IDENTICAL_FILTERS;n++) {
if(list[n].id == 0) {
bloom |= filter.levelMask;
list[n] = filter;
ret = true;
break;
}
}
return ret;
}
inline bool find(FilterId lookup_id, Filter *&filter) {
bool ret = false;
for(int n=0;n<MAX_IDENTICAL_FILTERS;n++) {
if(list[n].id == lookup_id) {
filter = &list[n];
ret = true;
break;
}
}
return ret;
}
};
class Sink {
protected:
Persistent<Function> onNewConnCB;
public:
Sink() : onNewConnCB() {}
static void parseAndLog() {
}
bool bind() {
return false;
}
void start() {
}
void shutdown() {
}
};
/**
* NOT COMPLETE
*/
class PipeSink final : public Sink, virtual public heapBuf::heapBufManager {
protected:
TWlib::tw_safeCircular<heapBuf *, LoggerAlloc > buffers;
struct PipeClient {
char temp[SINK_BUFFER_SIZE];
enum _state {
NEED_PREAMBLE,
IN_PREAMBLE,
IN_LOG_ENTRY // have log_entry_size
};
int temp_used;
int state_remain;
int log_entry_size;
_state state;
uv_pipe_t client;
PipeSink *self;
PipeClient() = delete;
PipeClient(PipeSink *_self) :
temp_used(0),
state_remain(GREASE_CLIENT_HEADER_SIZE), // the initial state requires preamble + size(uint32_t)
log_entry_size(0),
state(NEED_PREAMBLE), self(_self) {
uv_pipe_init(_self->loop, &client, 0);
client.data = this;
}
void resetState() {
state = NEED_PREAMBLE;
state_remain = GREASE_CLIENT_HEADER_SIZE;
temp_used = 0;
log_entry_size = 0;
}
void close() {
}
static void on_close(uv_handle_t *t) {
PipeClient *c = (PipeClient *) t->data;
delete c;
}
static void on_read(uv_stream_t* handle, ssize_t nread, uv_buf_t buf) {
PipeClient *c = (PipeClient *) handle->data;
if(nread == -1) {
// time to shutdown - client left...
uv_close((uv_handle_t *)&c->client, PipeClient::on_close);
DBG_OUT("PipeSink client disconnect.\n");
} else {
int walk = 0;
while(walk < buf.len) {
switch(c->state) {
case NEED_PREAMBLE:
if(buf.len >= GREASE_CLIENT_HEADER_SIZE) {
if(IS_SINK_PREAMBLE(buf.base)) {
c->state = IN_LOG_ENTRY;
GET_SIZE_FROM_PREAMBLE(buf.base,c->log_entry_size);
} else {
DBG_OUT("PipeClient: Bad state. resetting.\n");
c->resetState();
}
walk += GREASE_CLIENT_HEADER_SIZE;
} else {
c->state_remain = SIZEOF_SINK_LOG_PREAMBLE - buf.len;
memcpy(c->temp+c->temp_used, buf.base+walk,buf.len);
c->state = IN_PREAMBLE;
walk += buf.len;
}
break;
case IN_PREAMBLE:
{
int n = c->state_remain;
if(buf.len < n) n = buf.len;
memcpy(c->temp+c->temp_used,buf.base,n);
walk += n;
c->state_remain = c->state_remain - n;
if(c->state_remain == 0) {
if(IS_SINK_PREAMBLE(c->temp)) {
GET_SIZE_FROM_PREAMBLE(c->temp,c->log_entry_size);
c->temp_used = 0;
c->state = IN_LOG_ENTRY;
} else {
DBG_OUT("PipeClient: Bad state. resetting.\n");
c->resetState();
}
}
break;
}
case IN_LOG_ENTRY:
{
if(c->temp_used == 0) { // we aren't using the buffer,
if((buf.len - walk) >= GREASE_TOTAL_MSG_SIZE(c->log_entry_size)) { // let's see if we have everything already
int r;
if((r = c->self->owner->logFromRaw(buf.base,GREASE_TOTAL_MSG_SIZE(c->log_entry_size)))
!= GREASE_OK) {
ERROR_OUT("Grease logFromRaw failure: %d\n", r);
}
walk += c->log_entry_size;
c->resetState();
} else {
memcpy(c->temp,buf.base+walk,buf.len-walk);
c->temp_used = buf.len;
walk += buf.len; // end loop
}
} else {
int need = GREASE_TOTAL_MSG_SIZE(c->log_entry_size) - c->temp_used;
if(need <= buf.len-walk) {
memcpy(c->temp + c->temp_used,buf.base+walk,need);
walk += need;
c->temp_used += need;
int r;
if((r = c->self->owner->logFromRaw(c->temp,GREASE_TOTAL_MSG_SIZE(c->log_entry_size)))
!= GREASE_OK) {
ERROR_OUT("Grease logFromRaw failure (2): %d\n", r);
}
c->resetState();
} else {
memcpy(c->temp + c->temp_used,buf.base+walk,buf.len-walk);
walk += buf.len-walk;
c->temp_used += buf.len-walk;
}
}
break;
}
}
}
}
}
};
public:
uv_loop_t *loop;
GreaseLogger *owner;
char *path;
SinkId id;
uv_pipe_t pipe; // on Unix this is a AF_UNIX/SOCK_STREAM, on Windows its a Named Pipe
PipeSink() = delete;
PipeSink(GreaseLogger *o, char *_path, SinkId _id, uv_loop_t *l) :
buffers(BUFFERS_PER_SINK),
loop(l), owner(o), path(NULL), id(_id) {
uv_pipe_init(l,&pipe,0);
pipe.data = this;
if(_path)
path = local_strdup_safe(_path);
for (int n=0;n<BUFFERS_PER_SINK;n++) {
heapBuf *b = new heapBuf(SINK_BUFFER_SIZE);
buffers.add(b);
}
}
void returnBuffer(heapBuf *b) {
buffers.add(b);
}
bool bind() {
assert(path);
uv_pipe_bind(&pipe,path);
return true;
}
//uv_buf_t (*uv_alloc_cb)(uv_handle_t* handle, size_t suggested_size);
static uv_buf_t alloc_cb(uv_handle_t* handle, size_t suggested_size) {
uv_buf_t buf;
heapBuf *b = NULL;
PipeClient *client = (PipeClient *) handle->data;
if(client->self->buffers.remove(b)) { // grab an existing buffer
buf.base = b->handle.base;
buf.len = b->handle.len;
b->return_cb = (heapBuf::heapBufManager *) client->self; // assign class/callback
} else {
ERROR_OUT("PipeSink: alloc_cb failing. no sink buffers.\n");
buf.len = 0;
buf.base = NULL;
}
return buf;
}
static void on_new_conn(uv_stream_t* server, int status) {
PipeSink *sink = (PipeSink *) server->data;
if(status == 0 ) {
PipeClient *client = new PipeClient(sink);
int r;
#if UV_VERSION_MAJOR > 0
if((r = uv_accept(server, (uv_stream_t *)&client->client)) < 0) {
ERROR_OUT("PipeSink: Failed accept() %s\n", uv_strerror(r));
delete sink;
} else {
// if(uv_read_start((uv_stream_t *)&client->client,PipeSink::alloc_cb, PipeClient::on_read)) {
//
// }
}
#else
if((r = uv_accept(server, (uv_stream_t *)&client->client))==0) {
ERROR_OUT("PipeSink: Failed accept()\n", uv_strerror(uv_last_error(sink->loop)));
delete sink;
} else {
if(uv_read_start((uv_stream_t *)&client->client,PipeSink::alloc_cb, PipeClient::on_read)) {
}
}
#endif
} else {
ERROR_OUT("Sink: on_new_conn: Error on status: %d\n",status);
}
}
void start() {
pipe.data = this;
uv_listen((uv_stream_t*)&pipe,16,&on_new_conn);
}
void stop() {
}
~PipeSink() {
if(path) ::free(path);
heapBuf *b;
while(buffers.remove(b)) {
delete b;
}
}
};
/**
* The difference between using a uv_pipe (implemented by libuv as a unix socket,
* and a Unix datagram socket, is that message boundaries get preserved.
* This really simplifies things.
*
* Read more here:
* http://stackoverflow.com/questions/4669710/atomic-write-on-an-unix-socket
*/
class UnixDgramSink final : public Sink, virtual public heapBuf::heapBufManager {
protected:
// TWlib::tw_safeCircular<heapBuf *, LoggerAlloc > buffers;
// struct UnixDgramClient {
//// char temp[SINK_BUFFER_SIZE];
// enum _state {
// NEED_PREAMBLE,
// IN_PREAMBLE,
// IN_LOG_ENTRY // have log_entry_size
// };
// int temp_used;
// int state_remain;
// int log_entry_size;
// _state state;
// uv_pipe_t client;
// UnixDgramSink *self;
// UnixDgramClient() = delete;
// UnixDgramClient(UnixDgramSink *_self) :
// temp_used(0),
// state_remain(GREASE_CLIENT_HEADER_SIZE), // the initial state requires preamble + size(uint32_t)
// log_entry_size(0),
// state(NEED_PREAMBLE), self(_self) {
// uv_pipe_init(_self->loop, &client, 0);
// client.data = this;
// }
// void resetState() {