-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmonitor.cpp
1295 lines (1138 loc) · 31.1 KB
/
monitor.cpp
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
#include "debug.hpp"
#include "monitor.hpp"
#include "utility.hpp"
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/inotify.h>
#include <unistd.h>
#include <fcntl.h>
#include <pcre.h>
#include <libgen.h>
#define MAX_OVCOUNT 256
#define TRASH_HOLD_SIZE 2048
#define MAX_LOG_ITEM_SIZE 4096
#define MAX_EVENTS_PER_TURN 100
#define EVENT_SIZE (sizeof (struct inotify_event))
#define EVENT_BUF_LEN (1024 * (EVENT_SIZE + 16))
void *LNActionPreprocessor::m_pcre = NULL;
std::map<int , std::string> ineMap;
//----------------------------------------------------------------------------
LNEventQueue::~LNEventQueue() {
while(!empty()) {
pop();
}
}
LNFreq::LNFreq() {
this->m_count = 0;
this->m_time = 1;
}
LNFreq::LNFreq(const std::string &freq) {
this->SetFromString(freq);
}
LNFreq::LNFreq(const std::string &count, const std::string &time) {
this->setCount(count);
this->setTimePeriod(time);
}
LNFreq::LNFreq(unsigned long count, unsigned long time) {
this->setCount(count);
this->setTimePeriod(time);
}
void LNFreq::setCount(const std::string &count) {
this->m_count = atoi(count.c_str());
}
void LNFreq::setTimePeriod(const std::string &time) {
this->m_time = atoi(time.c_str());
}
std::string LNFreq::ToString() const {
return LNUtility::formatString("%d/%d", m_count, m_time);
}
bool LNFreq::SetFromString(const std::string &freq) {
std::vector<std::string> params;
LNUtility::explodeString(params, freq, "/");
if(params.size() < 2) {
LNLog::logWarning("Invalid log frequency format.");
return false;
}
m_count = atoi(params[0].c_str());
m_time = atoi(params[1].c_str());
return true;
}
void LNFreq::pushEvent(unsigned int crc) {
time_t currTime = time(NULL);
std::map<unsigned int, LNEventQueue*>::iterator i =
m_events.find(crc);
LNEventQueue *pQueue = (i != m_events.end())?i->second:NULL;
if(!pQueue) {
pQueue = new LNEventQueue();
if(!pQueue) {
LNLog::logError("No enough memory. [ line: %d file: %s ]",
__LINE__, __FILE__);
return;
}
m_events[crc] = pQueue;
}
// check hard limit (to prevent high memory usage in case of frequent events)
unsigned long hard_limit = m_count + 10;
if(pQueue->size() > hard_limit) {
hard_limit = pQueue->size() - hard_limit;
for(unsigned long i=0; i < hard_limit; i++) {
pQueue->pop();
}
}
pQueue->push(currTime);
}
void LNFreq::removeDeprecated(time_t currTime) {
time_t deprTime = currTime - m_time;
LNEventQueue *pQueue = NULL;
std::map<unsigned int, LNEventQueue*>::iterator i, prev;
for (prev = i = m_events.begin(); i != m_events.end(); i++) {
pQueue = i->second;
while ((pQueue->size() > 0) && (pQueue->front() < deprTime)) {
pQueue->pop();
}
if (! (pQueue->size()) ) {
delete pQueue;
m_events.erase(i);
if(i != prev) {
i = m_events.begin();
}
}
prev = i;
}
}
unsigned long LNFreq::getMessuringCount(unsigned int crc) const {
unsigned long c = 0;
LNEventQueue *pQueue = NULL;
if (!crc) {
std::map<unsigned int, LNEventQueue*>::const_iterator i;
for (i = m_events.begin(); i != m_events.end(); i++) {
c += i->second->size();
}
} else {
pQueue = m_events.find(crc)->second;
if(!pQueue) {
return 0;
}
c = pQueue->size();
}
return c;
}
void LNFreq::resetMessuring(unsigned int crc) {
LNEventQueue *pQueue = NULL;
if (crc) {
pQueue = m_events.find(crc)->second;
if (!pQueue) {
return;
}
while (!(pQueue->empty())) {
pQueue->pop();
}
} else {
std::map<unsigned int, LNEventQueue*>::const_iterator i;
for (i = m_events.begin(); i != m_events.end(); i++) {
pQueue = i->second;
while (!(pQueue->empty())) {
pQueue->pop();
}
}
}
}
//----------------------------------------------------------------------------
LNLogItem::LNLogItem(
const std::string &name,
const std::string ®ex,
const std::string &up_bound_action,
const std::string &down_bound_action,
const std::string &sizeAction,
const LNFreq &up_bound,
const LNFreq &down_bound,
size_t size,
bool usecrc
) {
this->m_name = name;
this->m_regex = regex;
this->m_upbaction = up_bound_action;
this->m_downbaction = down_bound_action;
this->m_sizeAction = sizeAction;
this->m_upfreq = up_bound;
this->m_downfreq = down_bound;
this->m_usecrc = usecrc;
this->m_size = size;
m_quotient = 0;
// compile PCRE
const char *errmsg = "No error.";
const char *errmsgfmt =
"Failed to compile PCRE expression at offset %d. %s [line: %ld file: %s]";
int erroffset = 0;
LNLog::logDebug("LogItem: %s | RegEx: %s", name.c_str(), regex.c_str());
this->m_pcre = (void*)pcre_compile(regex.c_str(), PCRE_NEWLINE_ANYCRLF, &errmsg, &erroffset, NULL);
if (!m_pcre) {
LNLog::logFatal(errmsgfmt, erroffset, errmsg, __LINE__, __FILE__);
}
}
LNLogItem::~LNLogItem() {
LNMutexLocker lock(*this);
// Release memory used for the compiled patterns
pcre_free((pcre*)m_pcre);
}
std::string LNLogItem::getName() {
LNMutexLocker lock(*this);
return this->m_name;
}
std::string LNLogItem::getRegEx() {
LNMutexLocker lock(*this);
return this->m_regex;
}
std::string LNLogItem::getUpBoundAction() {
LNMutexLocker lock(*this);
return this->m_upbaction;
}
std::string LNLogItem::getDownBoundAction() {
LNMutexLocker lock(*this);
return this->m_downbaction;
}
const LNFreq &LNLogItem::getUpBoundFreq() {
LNMutexLocker lock(*this);
return m_upfreq;
}
const LNFreq &LNLogItem::getDownBoundFreq() {
LNMutexLocker lock(*this);
return m_downfreq;
}
size_t LNLogItem::getSize() {
LNMutexLocker lock(*this);
return m_size;
}
std::string LNLogItem::getSizeAction() {
LNMutexLocker lock(*this);
return m_sizeAction;
}
int LNLogItem::Match(const std::string &log, std::vector<std::string> &matches) {
LNMutexLocker lock(*this);
int ovector[MAX_OVCOUNT], pcre_result = 0;
matches.clear();
pcre_result = pcre_exec((const pcre*)m_pcre, NULL, log.c_str(),
log.length(), 0, 0, ovector, MAX_OVCOUNT);
if(pcre_result >= 0) {
for(int m = 0, mc = 0; mc < pcre_result; m+=2, mc++) {
matches.push_back(
log.substr(ovector[m], ovector[m+1] - ovector[m]) );
}
unsigned int crc = 0;
if(m_usecrc) {
crc = LNUtility::crci(matches[0]);
}
m_upfreq.pushEvent(crc);
m_downfreq.pushEvent(0);
} else if (pcre_result != PCRE_ERROR_NOMATCH) {
LNLog::logWarning("Log match error (%d). LogRule: %s.",
pcre_result, m_name.c_str());
}
return pcre_result;
}
bool LNLogItem::upBoundFreqExcess(const std::string &match) {
LNMutexLocker lock(*this);
unsigned int crc = m_usecrc?LNUtility::crci(match):0;
return (m_upfreq.getMessuringCount(crc) > m_upfreq.getCount());
}
bool LNLogItem::downBoundFreqExcess() {
LNMutexLocker lock(*this);
return (m_downfreq.getMessuringCount(0) < m_downfreq.getCount());
}
size_t LNLogItem::getSizeQuotient() {
LNMutexLocker lock(*this);
return m_quotient;
}
void LNLogItem::setSizeQuotient(size_t q) {
LNMutexLocker lock(*this);
m_quotient = q;
}
bool LNLogItem::sizeExcess(size_t size) {
LNMutexLocker lock(*this);
if (!m_size) {
return false;
}
size_t cur_q = size/m_size;
if (cur_q > m_quotient) {
m_quotient = cur_q;
return true;
}
m_quotient = cur_q;
return false;
}
//----------------------------------------------------------------------------------------
std::string LNActionPreprocessor::run(const std::string &action, const std::string &line,
const std::vector<std::string> &matches) {
std::string result = action;
// is regular expression compiled already?
if(!m_pcre) {
const char *errmsg = "No error.";
const char *errmsgfmt =
"Failed to compile PCRE expression at offset %d."
" %s [line: %ld file: %s]";
int erroffset = 0;
m_pcre = (void*)pcre_compile("[^\\\\](\\$[0-9@]+)", PCRE_NEWLINE_ANYCRLF,
&errmsg, &erroffset, NULL);
if (!m_pcre) {
LNLog::logFatal(errmsgfmt, erroffset, errmsg, __LINE__, __FILE__);
}
}
int ovector[MAX_OVCOUNT], pcre_result = 0;
memset(ovector, 0, sizeof(ovector));
pcre_result = pcre_exec((const pcre*)m_pcre, NULL, result.c_str(),
result.length(), 0, PCRE_NEWLINE_ANYCRLF,
ovector, MAX_OVCOUNT);
std::string smi;
while(pcre_result > 1) {
for(int m = 2, mc = 1; mc < pcre_result; m+=2, mc++) {
std::string mstr = result.substr(ovector[m],
ovector[m+1] -
ovector[m]).c_str();
smi = result.substr(ovector[m]+1, ovector[m+1] - (ovector[m]+1));
size_t mi = 0;
if(smi != "@") {
mi = atoi(smi.c_str());
} else {
result = LNUtility::replaceString(mstr, line,
result);
continue;
}
if(!(mi >= matches.size())) {
result = LNUtility::replaceString(mstr, matches[mi],
result);
} else {
result = LNUtility::replaceString(
result.substr(ovector[m],
ovector[m+1] - ovector[m]),
" ", result);
}
}
memset(ovector, 0, sizeof(ovector));
pcre_result = pcre_exec((const pcre*)m_pcre, NULL, result.c_str(),
result.length(), 0, PCRE_NEWLINE_ANYCRLF, ovector,
MAX_OVCOUNT);
}
if (pcre_result < 0 && pcre_result != PCRE_ERROR_NOMATCH) {
LNLog::logWarning("RegEx match error (%d). LogRule: Action preprocessor.",
pcre_result);
}
return LNUtility::replaceString("\\$", "$", result);
}
//---------------------------------------------------------------------------------------
LNLogItems::LNLogItems() {
// position at beginning of initial empty position in case
// someone tries to iterate
m_i = m_by_name.begin();
}
LNLogItems::~LNLogItems() {
this->removeAll();
}
bool LNLogItems::add(LNLogItem *pli) {
LNMutexLocker lock(*this);
if(pli) {
m_by_name[pli->getName()] = pli;
}
return false;
}
LNLogItem* LNLogItems::add(
const std::string &name,
const std::string ®ex,
const std::string &up_bound_action,
const std::string &down_bound_action,
const std::string &sizeAction,
const LNFreq &up_bound,
const LNFreq &down_bound,
const size_t size,
bool usecrc
) {
LNMutexLocker lock(*this);
LNLogItem *pli = new LNLogItem(
name,
regex,
up_bound_action,
down_bound_action,
sizeAction,
up_bound,
down_bound,
size,
usecrc
);
if(!pli) {
LNLog::logError("No enough memory. [line: %ld file: %s]", __LINE__, __FILE__);
}
return pli;
}
LNLogItem *LNLogItems::find(const std::string &name) {
LNMutexLocker lock(*this);
std::map<std::string, LNLogItem *>::iterator res = m_by_name.find(name);
if(res != m_by_name.end()) {
return res->second;
}
return NULL;
}
LNLogItem * LNLogItems::remove(const std::string &name) {
LNMutexLocker lock(*this);
LNLogItem *pli;
std::map<std::string, LNLogItem *>::iterator res = m_by_name.find(name);
if(res != m_by_name.end()) {
pli = res->second;
m_by_name.erase(res);
return pli;
}
return NULL;
}
bool LNLogItems::removeAndDelete(const std::string &name) {
LNMutexLocker lock(*this);
LNLogItem *pli;
std::map<std::string, LNLogItem *>::iterator res = m_by_name.find(name);
if(res != m_by_name.end()) {
pli = res->second;
m_by_name.erase(res);
delete pli;
return true;
}
return false;
}
bool LNLogItems::removeAll() {
LNMutexLocker lock(*this);
LNLogItem *pli = NULL;
for(m_i = m_by_name.begin(); m_i != m_by_name.end(); ) {
pli = m_i->second;
m_by_name.erase(m_i);
m_i = m_by_name.begin();
}
return true;
}
bool LNLogItems::removeAndDeleteAll() {
LNMutexLocker lock(*this);
LNLogItem *pli = NULL;
for(m_i = m_by_name.begin(); m_i != m_by_name.end(); ) {
pli = m_i->second;
m_by_name.erase(m_i);
m_i = m_by_name.begin();
delete pli;
}
return true;
}
void LNLogItems::reset() {
LNMutexLocker lock(*this);
m_i = m_by_name.begin();
}
LNLogItem *LNLogItems::getNext() {
LNMutexLocker lock(*this);
LNLogItem *res = NULL;
if(m_i != m_by_name.end() ) {
res = m_i->second;
m_i++;
}
return res;
}
//----------------------------------------------------------------------------
LNLogFile::LNLogFile() {
// initialize file descriptor to none
m_fd = 0;
m_curPos = 0;
// Avoid frequent memory reallocation most of logs are less
// then 512 bytes
m_trash_hold.reserve(TRASH_HOLD_SIZE);
};
LNLogFile::LNLogFile(const std::string &filep, LNLogFile::Type type,
const std::string &sep) {
std::vector<std::string>::iterator scic, scip;
std::string _sep;
this->m_fd = 0;
// Avoid frequent memory reallocation most of logs are less
// then 512 bytes
m_trash_hold.reserve(TRASH_HOLD_SIZE);
this->open(filep, type, sep);
}
LNLogFile::~LNLogFile() {
this->close();
}
bool LNLogFile::isOpen() {
LNMutexLocker lock(*this);
return (m_fd != 0?true:false);
}
int LNLogFile::getFileDescriptor() {
LNMutexLocker lock(*this);
return m_fd;
}
bool LNLogFile::open(const std::string &path, LNLogFile::Type type, const std::string &sep,
bool seekEnd) {
LNMutexLocker lock(*this);
bool open = false;
int retc = 0, fd = 0;
struct stat finfo;
if(m_fd) {
this->close();
}
if(type == USOCK) {
LNLog::logError("Unix socket are not supported yet.");
return false;
}
// check if file exist
retc = ::stat( path.c_str(), &finfo );
retc = ( retc?errno:0 );
if(retc && retc == ENOENT) {
// create file
switch(type) {
case FIFO:
retc = ( (::mkfifo(path.c_str(), 0600))?errno:0 );
if(retc && retc != EEXIST) {
LNLog::logError("Failed to create FIFO '%s'. "
"%s [line: %ld file: %s]",
path.c_str(), strerror(errno),
__LINE__, __FILE__ );
return false;
}
open = true;
LNLog::logInfo("Created FIFO file '%s'", path.c_str());
break;
case FILE:
LNLog::logError("Specified log file '%s' dose not exist.",
path.c_str());
return false;
break;
case USOCK:
break;
default:
LNLog::logFatal("Unknown file type! '%s' [line: %ld file: %s]",
path.c_str(), strerror(errno), __LINE__, __FILE__);
break;
}
} else if(retc) {
// its some problem, report error and return
LNLog::logError("Access to log file failed '%s'. %s [line: %ld file: %s]",
path.c_str(), strerror(errno), __LINE__, __FILE__ );
return false;
}
if(open || type == FILE || type == FIFO) {
fd = ::open(path.c_str(), O_RDONLY | O_NONBLOCK);
retc = (fd != -1?0:errno);
if(retc) {
LNLog::logError("Failed to access file '%s'. %s [line: %ld file: %s]",
path.c_str(), strerror(errno), __LINE__, __FILE__ );
return false;
}
if(type == FILE && seekEnd) {
m_curPos = lseek(fd, 0, SEEK_END);
} else {
m_curPos = 0;
}
}
// get file name and directory
m_fpath = path;
char *pathBuff = new char[m_fpath.size()+1];
if(!pathBuff) {
LNLog::logFatal("No enough memory. [ file: %s line: %ld ]",
__FILE__, __LINE__);
}
strcpy(pathBuff, m_fpath.c_str());
m_fdir = dirname(pathBuff);
strcpy(pathBuff, m_fpath.c_str());
m_fname = basename(pathBuff);
delete[] pathBuff;
m_fd = fd;
m_type = type;
m_sep = LNUtility::replaceString("\\n", "\n", sep);
m_sep = LNUtility::replaceString("\\r", "\r", m_sep);
LNLog::logInfo("File '%s' is opened.", m_fname.c_str());
return true;
}
bool LNLogFile::reopen(bool seekEnd) {
LNMutexLocker lock(*this);
off_t oldPos = 0;
if (!m_fpath.size()) {
LNLog::logError("Can't reopen file was never open before.");
return false;
}
oldPos = m_curPos;
if (open(m_fpath, m_type, m_sep, seekEnd)) {
fstat(m_fd, &m_fstats);
// check if file truncated
if ( !(oldPos > m_fstats.st_size) ) {
// continue from last position
m_curPos = lseek(m_fd, oldPos, SEEK_SET);
} else {
// cleanup last partial read it's not valid anymore
m_trash_hold = "";
}
return true;
}
return false;
}
bool LNLogFile::close() {
LNMutexLocker lock(*this);
int retc;
if(m_fd) {
retc = ((::close(m_fd))?errno:0);
m_fd = 0;
if(retc) {
LNLog::logError("Failed to close file '%s'. %s [line: %ld file: %s]",
m_fpath.c_str(), strerror(errno), __LINE__, __FILE__ );
return false;
}
}
return true;
}
bool LNLogFile::fetchNextLog(std::string &item) {
LNMutexLocker lock(*this);
char *trash = NULL;
ssize_t bytes_read = 0;
bool item_extracted = false;
if(!m_fd) {
LNLog::logError("Log file is not opened. [line: %ld file: %s]",
__LINE__, __FILE__ );
return false;
}
// first check previous trash hold
if(m_trash_hold.length() &&
( trash = strstr((char*)m_trash_hold.c_str(), m_sep.c_str()) ) ) {
memset(trash, 0, m_sep.size()*sizeof(char));
trash += m_sep.size()*sizeof(char);
item = m_trash_hold;
m_trash_hold = trash;
return true; // item extracted
}
do {
if(this->m_trash_hold.length() > TRASH_HOLD_SIZE) {
LNLog::logWarning("Extracted log item seems to long. "
"Check your separator settings.");
}
if(this->m_trash_hold.length() > MAX_LOG_ITEM_SIZE) {
LNLog::logError("Log item exceeded length limit. "
"Check your separator settings.");
this->m_trash_hold = "";
return false;
}
memset(m_read_buf, 0, sizeof(m_read_buf));
do {
LNLog::logDebug("-- Read file %s", this->m_fpath.c_str());
bytes_read = read(m_fd, m_read_buf,
sizeof(m_read_buf) - sizeof(char));
LNLog::logDebug("-- Bytes read %ld (%s) from %s", bytes_read,
(bytes_read==EAGAIN?"THERE IS MORE":"NO MORE"),
this->m_fpath.c_str());
} while(errno == EAGAIN && bytes_read == 0);
// update current position
m_curPos = lseek(m_fd, 0, SEEK_CUR);
if(bytes_read <= 0) {
break; // end of file;
} else if(bytes_read < 0 && errno != EAGAIN) {
LNLog::logError("Failed to fetch log item. '%s' %s "
"[%d] [line: %ld file: %s]",
m_fpath.c_str(), strerror(errno), errno,
__LINE__, __FILE__);
return false;
}
if( (trash = strstr(m_read_buf, m_sep.c_str()) ) ) {
memset(trash, 0, m_sep.size()*sizeof(char));
trash += m_sep.size()*sizeof(char);
item = m_trash_hold + m_read_buf;
m_trash_hold = trash;
item_extracted = true;
break;
} else if (!(*m_read_buf)) {
// empty log, zeros written to file
item = m_trash_hold + m_read_buf;
trash = m_read_buf;
m_trash_hold = trash;
item_extracted = true;
break;
} else {
m_trash_hold += m_read_buf;
}
} while(!item_extracted);
return item_extracted;
}
size_t LNLogFile::getPosition() {
LNMutexLocker lock(*this);
if(m_fd) {
return m_curPos;
}
return 0;
}
void LNLogFile::handleIfTruncated() {
LNMutexLocker lock(*this);
if(!m_fd) {
return;
}
fstat(m_fd, &m_fstats);
if(m_curPos > m_fstats.st_size) {
// REPOSITION AT END OF FILE
m_curPos = lseek(m_fd, 0, SEEK_END);
LNLog::logInfo("File '%s' was truncated to %d bytes. "
"logNOT repositioned.", m_fname.c_str(), m_fstats.st_size);
}
}
std::string LNLogFile::getFilePath() {
LNMutexLocker lock(*this);
return m_fpath;
}
std::string LNLogFile::getFileName() {
LNMutexLocker lock(*this);
return m_fname;
}
std::string LNLogFile::getDirectoryPath() {
LNMutexLocker lock(*this);
return m_fdir;
}
LNLogItems & LNLogFile::getAttachedItems() {
LNMutexLocker lock(*this);
return this->m_items;
}
bool LNLogFile::exist(const std::string &path) {
return !(::access(path.c_str(), F_OK));
}
//----------------------------------------------------------------------------
LNLogFiles::LNLogFiles() {
m_curPos = this->m_byDesc.begin();
}
LNLogFiles::~LNLogFiles() {
this->closeAll();
}
LNLogFile *LNLogFiles::open(const std::string &path, LNLogFile::Type type, const std::string &sep) {
LNMutexLocker lock(*this);
LNLogFile *pResult = NULL;
int fd = 0;
if(m_byPath.count(path)) {
return m_byPath[path];
}
pResult = new LNLogFile();
if(!pResult) {
LNLog::logError("No enough memory. [line: %d file: %s]", __FILE__, __LINE__);
return NULL;
}
if(!pResult->open(path, type, sep)) {
delete pResult; // free failed file from memory
return NULL;
}
fd = pResult->getFileDescriptor();
// map opened file by file descriptor and path
m_byDesc[fd] = pResult;
m_byPath[path] = pResult;
return pResult;
}
bool LNLogFiles::close(int fd) {
LNMutexLocker lock(*this);
bool res=false;
std::map<int , LNLogFile*>::iterator item = m_byDesc.find(fd);
if(item != m_byDesc.end()) {
LNLogFile *pf = item->second;
m_byPath.erase(pf->getFilePath());
m_byDesc.erase(item);
delete pf;
res = true;
}
LNLog::logWarning("Required to close non existing file by descriptor %d.", fd);
return res;
}
bool LNLogFiles::close(const std::string &path) {
LNMutexLocker lock(*this);
bool res=false;
std::map<std::string , LNLogFile*>::iterator item = m_byPath.find(path);
if(item != m_byPath.end()) {
LNLogFile *pf = item->second;
m_byDesc.erase(pf->getFileDescriptor());
m_byPath.erase(item);
delete pf;
res = true;
}
LNLog::logWarning("Required to close non existing file by path '%s'.",
path.c_str());
return res;
}
bool LNLogFiles::closeAll() {
LNMutexLocker lock(*this);
bool res = true;
for(std::map<int, LNLogFile*>::iterator i = m_byDesc.begin(); i != m_byDesc.end(); ) {
m_byPath.erase(i->second->getFilePath());
m_byDesc.erase(i);
delete i->second;
i = m_byDesc.begin();
}
return res;
}
LNLogFile *LNLogFiles::find(int fd) {
LNMutexLocker lock(*this);
LNLogFile *pRes = NULL;
std::map<int , LNLogFile*>::iterator res = m_byDesc.find(fd);
if(res != m_byDesc.end()) {
pRes = res->second;
}
return pRes;
}
LNLogFile *LNLogFiles::find(const std::string &path) {
LNMutexLocker lovk(*this);
LNLogFile *pRes = NULL;
std::map<std::string , LNLogFile*>::iterator res = m_byPath.find(path);
if(res != m_byPath.end()) {
pRes = res->second;
}
return pRes;
}
void LNLogFiles::reset() {
LNMutexLocker lock(*this);
m_curPos = this->m_byDesc.begin();
}
LNLogFile *LNLogFiles::getNext() {
LNMutexLocker lock(*this);
LNLogFile *res = NULL;
if(m_curPos != this->m_byDesc.end() && this->m_byDesc.size() > 0) {
res = m_curPos->second;
m_curPos++;
}
return res;
}
size_t LNLogFiles::count() {
LNMutexLocker lock(*this);
return m_byDesc.size();
}
//----------------------------------------------------------------------------
// LNLogEvents
LNLogEvents::LNLogEvents() {
m_cpos = m_files.begin();
}
LNLogEvents::~LNLogEvents() {
this->clear();
}
void LNLogEvents::clear() {
LNMutexLocker lock(*this);
m_files.clear();
}
void LNLogEvents::append(LNLogFile *lf) {
LNMutexLocker lock(*this);
m_files.push_back(lf);
}
void LNLogEvents::reset() {
LNMutexLocker lock(*this);
m_cpos = m_files.begin();
}
LNLogFile* LNLogEvents::getNext() {
LNMutexLocker lock(*this);
LNLogFile *res = NULL;
if(m_cpos != m_files.end() && m_files.size() > 0) {
res = *m_cpos;
m_cpos++;
}
return res;
}
//--------------------------------------------------------------------------------------------------
// LNInotify
LNInotify::LNInotify() {
m_eventsBuffer = new char[EVENT_BUF_LEN];
if (!m_eventsBuffer) {
LNLog::logFatal("No enough memory. [ file: %s line: %s ]", __FILE__, __LINE__);
}
memset(m_eventsBuffer, 0, EVENT_BUF_LEN*sizeof(char));
m_fd = inotify_init();
if (m_fd == -1) {
LNLog::logFatal("Failed to initialize file system monitoring. (%s)",
strerror(errno));
}
}
LNInotify::~LNInotify() {
if (-1 == close(m_fd)) {
LNLog::logError("Failed to close inotify fd. (%s)", strerror(errno));
}
delete [] m_eventsBuffer;
}
bool LNInotify::addWatch(LNLogFile *pFile, bool watchDir) {
const char * pathToWatch =
watchDir?pFile->getDirectoryPath().c_str()\
:pFile->getFilePath().c_str();
int wd = inotify_add_watch(m_fd, pathToWatch, //IN_ALL_EVENTS);
IN_MODIFY | IN_DELETE | IN_MOVE | IN_ATTRIB | IN_MOVE_SELF);
if (wd == -1) {
LNLog::logError("Failed to monitor file '%s'.", pFile->getFilePath().c_str());
LNLog::logError("%s", strerror(errno));
return false;
}
m_watchMap[wd] = pFile;
return true;
}
bool LNInotify::rmWatch(LNLogFile *pFile, bool watchDir) {
const char * pathToWatch =
watchDir?pFile->getDirectoryPath().c_str()\
:pFile->getFilePath().c_str();
int wd = inotify_add_watch(m_fd, pathToWatch, 0);
if (wd == -1 && errno != ENOENT) {
LNLog::logError("%s [ errno: %d ]", strerror(errno), errno);
return false;
}
int rc = inotify_rm_watch(m_fd, wd);
if (rc == -1) {
LNLog::logError("Failed to stop monitoring on file '%s'.",
pFile->getFilePath().c_str());
LNLog::logError("%s", strerror(errno));
return false;
}
m_watchMap.erase(wd);
return true;
}
bool LNInotify::rmWatch(int wd) {
int rc = inotify_rm_watch(m_fd, wd);
if (rc == -1) {
LNLog::logError("Failed to stop monitoring on file's wd '%d'.", wd);
LNLog::logError("%s", strerror(errno));