forked from aristanetworks/quicktrace-public
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuickTrace.cpp
1355 lines (1195 loc) · 43 KB
/
QuickTrace.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
// Copyright (c) 2011, Arista Networks, Inc.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Arista Networks nor the names of its contributors may
// be used to endorse or promote products derived from this software without
// specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL ARISTA NETWORKS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
#include <QuickTrace/QuickTrace.h>
#include <QuickTrace/Registration.h>
#include <stdlib.h>
#include <sys/sendfile.h>
#include <cassert>
#include <climits>
#include <string.h>
#include <stdio.h>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <ctype.h>
#include <cstring>
#include <errno.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <sys/time.h>
#include <unistd.h>
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <dlfcn.h>
#include <fstream>
#include <unordered_set>
#ifdef QT_USE_ATFORK_LIB
#include <AtFork/AtFork.h>
#else
#include <pthread.h>
#endif
// A QuickTrace file has the following format:
// --------------------------------
// - TraceFileHeader (starts with file version)
// - 512 MsgCounters by default (can be configured via initialize)
// - 10 circular RingBufs for the different trace levels
// - The QuickTraceDict, variable size, containing a sequence of MsgDescs.
// Each one looks like this:
// "<timestamp> __FILE__ __LINE__ " (ascii)
// "<message-id> " (when file version >= 3)
// 4 byte length of message string
// null-terminated format string like this:
// "This is the message my int param is %d my other params are %s and %s"
// byte length of key string
// deserialization key, of the form "ddd" for a message with 3 integer params
namespace QuickTrace {
TraceHandle * defaultQuickTraceHandle;
static std::mutex traceHandleMutex = {};
static std::unordered_map< std::string, QuickTrace::TraceHandle * > traceHandleMap;
thread_local char QtString::formatBuf_[ QtString::formatBufSize ] = {};
thread_local std::vector< uint64_t > threadSubFuncStack = { 0 };
static constexpr uint32_t DEFAULT_MAX_SIZE = 32 * 1024;
#ifndef SMALL_MEMORY_MAX_SIZE
// Limit total ring-buffers to 512KB max on small-memory systems
static constexpr uint32_t SMALL_MEMORY_MAX_SIZE = 512;
#endif
#ifndef SMALL_SYSTEM_MEM_SIZE
// Small systems have at most 4G RAM, specify this in KB.
static constexpr uint64_t SMALL_SYSTEM_MEM_SIZE = 0x100000000ULL / 1024;
#endif
// Touch every page in some file by writing one byte of zero to it and
// return errno if we failed, 0 otherwise.
int
touchEveryPage( int fd, int sz ) noexcept {
int data = 0;
const int pagesize = 4 * 1024;
for( int i = 0; i < sz; i += pagesize ) {
lseek( fd, i, SEEK_SET );
int err = write( fd, &data, 1 );
if( err <= 0 ) return errno;
}
lseek( fd, sz-1, SEEK_SET );
int err = write( fd, &data, 1 );
return (err <= 0) ? errno : 0;
}
static int getfile( char const * filename, int sz ) noexcept {
int fd = open( filename, O_RDWR|O_CREAT, 0666 );
if( fd < 0 ) {
std::cerr << "open " << filename << ": "
<< errno << " " << strerror( errno ) << std::endl;
return -1;
}
// We leave a little buffer between the end of the last Ring Buffer
// and the start of the first message descriptor ftruncate to 0
// first gives me clean pages, so if there's some Ring Buffer I'm
// not using then it's backed by holes in the file that are not
// actually allocated. I think.
int err = ftruncate( fd, 0 );
if( err < 0 ) {
std::cerr << "Failed to truncate quicktrace file " << filename << " " << errno
<< ":" << strerror( errno ) << std::endl;
}
int realSize = sz+TraceFile::FileTrailerSize;
err = ftruncate( fd, realSize );
if( err < 0 ) {
std::cerr << "Failed to truncate quicktrace file " << filename << " " << errno
<< ":" << strerror( errno ) << std::endl;
}
// If the filesystem is full, then touchEveryPage will fail.
// Touching every page up front ensures that we don't get a sigbus
// later when we attempt to allocate memory for the page.
err = touchEveryPage( fd, realSize );
if( err ) {
std::cerr << "Filesystem full touchEveryPage failed" << std::endl;
int rc = ::close( fd );
assert( rc == 0 );
unlink( filename );
return -1;
}
lseek( fd, realSize, SEEK_SET );
return fd;
}
void MsgFormatString::put( char const * ss ) noexcept {
if( ptr_ != key_ ) { *ptr_++ = ','; }
ptr_ = (char*)memccpy( ptr_, ss, 0, key_ + keySize - ptr_ );
ptr_--;
}
MsgDesc::MsgDesc( TraceFile * tf, MsgId *msgIdPtr,
char const * file, int line ) noexcept
: tf_( tf ),
buf_( tf->msgDescBuf_ ),
ptr_( tf->msgDescBuf_ ),
end_( tf->msgDescBuf_ + MsgDesc::bufSize ),
formatString_( tf->msgFormatStringKey_ ) {
// Message IDs are shared across threads so another thread may have
// already allocated one for this message.
if( 0 == *msgIdPtr ) {
tf->traceHandle_->allocateMsgId( msgIdPtr );
}
id_ = *msgIdPtr;
// Store the message Id, timestamp, file, and line
int n = sprintf( ptr_, "%" PRId64 " %s %d %d ", rdtsc(), file, line, id_ );
ptr_ += n;
// save room to store the length
pstr_ = (PStringL*)ptr_;
ptr_ = pstr_->data;
}
void
MsgDesc::finish() noexcept {
// null-terminate the message string
*ptr_++ = '\0';
// backfill the length pointer so the message string is prepended
// by a 4 byte length value. The length includes the null terminator
// (maybe it should not)
pstr_->len = ptr_ - pstr_->data;
PStringL * p = (PStringL*)ptr_;
ptr_ = p->data;
ptr_ = (char*)memccpy( ptr_, formatString_.key(), 0, end_-ptr_);
assert( ptr_ ); // include null terminator on format
p->len = ptr_ - p->data;
// Write it all into the file
int fd = tf_->fd();
int n = write( fd, buf_, ptr_ - buf_ );
// int where = lseek( fd, 0, SEEK_CUR );
if( n <= 0 ) {
static bool once;
if( !once ) {
std::cerr << "QuickTrace failed to create message(" << errno << "): "
<< strerror( errno ) << std::endl;
once = 1;
}
}
tf_->msgIdInitializedIs( id_ );
}
MsgDesc &
MsgDesc::operator<<( const std::string_view & x ) noexcept {
assert( ( x.size() < static_cast< size_t >( end_ - ptr_ ) ) &&
"format string too long" );
auto lenToCopy = x.size();
ptr_ = ( char * )memcpy( ptr_, x.data(), lenToCopy );
ptr_ += lenToCopy;
return *this;
}
MsgDesc &
MsgDesc::operator<<( char const * x ) noexcept {
ptr_ = (char*) memccpy( ptr_, x, 0, end_ - ptr_ );
ptr_--;
return *this;
}
MsgDesc &
MsgDesc::operator<<( Varg x ) noexcept {
ptr_[0] = '%';
ptr_[1] = 's';
ptr_+=2;
return *this;
}
MsgDesc &
MsgDesc::operator<<( HexVarg x ) noexcept {
ptr_[0] = '%';
ptr_[1] = 'x';
ptr_+=2;
return *this;
}
static double monotime() noexcept {
struct timespec ts;
clock_gettime( CLOCK_MONOTONIC, &ts );
return (double)ts.tv_sec + ts.tv_nsec / (double)1000000000;
}
static double utc() noexcept {
struct timeval tv;
gettimeofday( &tv, 0 );
// in reality, gettimeofday never fails, so I'm not checking the
// error code.
return tv.tv_sec + 0.000001 * tv.tv_usec;
}
int qtMaxStringLen = 24;
static SizeSpec defaultTraceFileSizes = { 8,8,8,8,8,8,8,8,8,8 }; // in Kilobytes
void saveOldFiles( char const * path ) noexcept {
char old[256];
char oldest[256];
int old_len = snprintf( old, sizeof(old), "%s.1.gz", path );
int oldest_len = snprintf( oldest, sizeof(oldest), "%s.2.gz", path );
bool old_is_gz = access( old, F_OK ) == 0; // Is the old file (.1) compressed ?
// Remove .gz extension
if( !old_is_gz ) {
old[ old_len - 3 ] = '\0';
}
if( access( oldest, F_OK ) == -1 ) {
// The oldest file (.2) is not compressed
oldest[ oldest_len - 3 ] = '\0';
if( access( oldest, F_OK ) == -1 ) {
// The oldest file (.2) does not exist
if( old_is_gz ) {
oldest[ oldest_len - 3 ] = '.';
}
// We rename the old (.1) to the oldest (.2) only if the last doesn't exist
// to keep the first log file if the agent restarts many times.
// (Please refer to the README, Section 2.5: Turning QuickTrace on)
rename( old, oldest ); // may get ENOENT, but we don't care
}
}
if( old_is_gz ) {
// Remove the old compressed file (.1.gz)
unlink( old ); // may get ENOENT, but we don't care
old[ old_len - 3 ] = '\0';
}
rename( path, old ); // may get ENOENT, but we don't care
}
void
TraceFile::maybeBackupBuffer() noexcept {
if( !traceHandle_->foreverLog() ) {
return;
}
const std::string &foreverLogPath = traceHandle_->foreverLogPath();
if( foreverLogPath.empty() ) {
return;
}
if( foreverLogPath.find( "null" ) != std::string::npos ) {
std::cerr << "EventMon Buffer Full. Backups Disabled. Rolling Over";
return;
}
std::cerr << "BACKING UP BUFFER to " << foreverLogPath << " " <<
traceHandle_->foreverLogIndex() << std::endl;
char newPath[256];
snprintf( newPath, sizeof( newPath ), "%s.%d", foreverLogPath.c_str(),
traceHandle_->foreverLogIndex() );
// copy the file to new location
errno = 0;
int srcFd = open( fileName_.c_str(), O_RDONLY, 0 );
if ( srcFd == -1 ) {
// failed to open file - log error and continue
std::cerr << __PRETTY_FUNCTION__ << "open failed for " <<
fileName_.c_str() << " error " << strerror( errno ) << std::endl;
return;
}
// determine size of source file
struct stat statSrc;
if ( fstat( srcFd, &statSrc ) == -1 ) {
// failed to determine file status - clean up, log error, and continue
::close( srcFd );
std::cerr << __PRETTY_FUNCTION__ << "fstat failed for " << fileName_.c_str() <<
" error " << strerror( errno ) << std::endl;
return;
}
// get file descriptor for destination file - create if doesn't exist, open as
// write-only
int destFd = open( newPath, O_WRONLY | O_CREAT, 0644 );
if ( destFd == -1 ) {
// failed to open file - clean up, log error, and continue
::close( srcFd );
std::cerr << __PRETTY_FUNCTION__ << "open failed for " <<
newPath << " error " << strerror( errno ) << std::endl;
return;
}
// copy source to destination
if ( sendfile( destFd, srcFd, 0, statSrc.st_size ) == -1 ) {
// failed to copy file - throw exception
::close( srcFd );
::close( destFd );
// log error and give up
std::cerr << __PRETTY_FUNCTION__ << " sendfile failed for " <<
fileName_.c_str() << " error " << strerror( errno ) << std::endl;
return;
}
::close( srcFd );
::close( destFd );
traceHandle_->foreverLogIndexInc( 1 );
}
bool
initialize( char const * filename, SizeSpec * sizesInKilobytes,
char const *foreverLogPath, int foreverLogIndex,
int maxStringLen, MultiThreading multiThreading,
bool rotateLogFile, uint32_t numMsgCounters ) noexcept {
if( !filename || filename[0] == '\0' ) return false;
// We don't expect the filename to be just .qt in single thread case
// In multi-threaded scenario the qt file name comes from the thread name
if ( multiThreading != MultiThreading::enabled ) {
assert( "Filename cannot be .qt" && strcmp( filename, ".qt" ) );
}
// The maximum length of a string in the dynamic portion of QuickTrace.
// Longer strings will be truncated to fit this limit. 80 was picked as the
// limit because it struck a balance between avoiding the max buffer size of
// 256 while allowing longer strings (i.e. pathnames) to be stored.
if( maxStringLen > 80 ) {
qtMaxStringLen = 80;
} else {
qtMaxStringLen = maxStringLen;
}
// Even if trace file is already created, we should update the
// forever log parameters
if( NULL != defaultQuickTraceHandle ) {
if( defaultQuickTraceHandle->fileNameFormat() != filename ) {
std::cerr << "Tracing has already been enabled to " <<
defaultQuickTraceHandle->fileNameFormat() << std::endl;
return false;
}
} else {
defaultQuickTraceHandle = new TraceHandle( filename,
sizesInKilobytes,
foreverLogPath,
foreverLogIndex,
multiThreading,
rotateLogFile,
numMsgCounters,
true );
if( !defaultQuickTraceHandle->isInitialized() ) {
close();
return false;
}
}
return true;
}
void
close() noexcept {
delete defaultQuickTraceHandle;
// The TraceHandle desctructor sets the defaultQuickTraceHandle
// pointer to NULL
assert( NULL == defaultQuickTraceHandle );
}
TraceHandle *initialize_handle( char const *filename, SizeSpec *sizesInKilobytes,
char const *foreverLogPath, int foreverLogIndex,
MultiThreading multiThreading ) noexcept {
TraceHandle *th = new TraceHandle( filename, sizesInKilobytes, foreverLogPath,
foreverLogIndex, multiThreading );
// We could check if isInitialized() is false and delete the
// TraceHandle returning NULL but there are QuickTrace users
// (PolicyMap...) that assume they always get back a non-NULL
// handle.
return th;
}
bool enableContextSwitchTracking();
uint32_t addAndLimitSizes( SizeSpec * sizeSpec, bool limit ) noexcept {
uint32_t sz = 0;
for( int i = 0; i < 10; ++i ) {
uint32_t szi = sizeSpec->sz[i];
if( szi > 16384 && limit ) {
szi = 16384;
} else if( szi == 0 ) {
szi = 1;
}
sz += szi;
sizeSpec->sz[i] = szi;
}
return sz;
}
uint32_t addLevelSizes( SizeSpec * sizeSpec, int end ) noexcept {
uint32_t sum = 0;
for( int i = 0; i < end; i++ ) {
sum += sizeSpec->sz[i];
}
return sum;
}
uint32_t scaleDownSizes( SizeSpec * sizeSpec, float factor ) noexcept {
// Trims each trace level by the same percentage
// Except if the resulting size is < 1. Instead 1 is assigned.
uint32_t sum = 0;
for( int i = 0; i < 10; i++ ) {
uint32_t newSize = sizeSpec->sz[i] * factor;
// Zero size levels are not supported
// This could cause the total file size to be a few KB over the maximum,
// But it shouldn't be an issue.
sizeSpec->sz[i] = newSize < 1 ? 1 : newSize;
sum += sizeSpec->sz[i];
}
return sum;
}
TraceHandle *
traceHandle( const std::string & traceFilename ) noexcept {
std::lock_guard< std::mutex > lock( traceHandleMutex );
auto iter = traceHandleMap.find( traceFilename );
if ( iter == traceHandleMap.end() ) {
return nullptr;
}
return iter->second;
}
#ifndef __i386__
static size_t
getPhysicalMemorySize() noexcept {
FILE * fp = fopen( "/proc/meminfo", "r" );
assert( fp != nullptr );
char labelStr[ 32 ];
char unitsStr[ 32 ];
size_t memTotal;
int rc = fscanf( fp, "%s %zu %s", labelStr, &memTotal, unitsStr );
assert( rc == 3 );
rc = fclose( fp );
assert( rc == 0 );
// make sure we're reading the right thing
assert( strcmp( labelStr, "MemTotal:" ) == 0 );
assert( memTotal != 0 );
assert( memTotal != SIZE_MAX );
return memTotal;
}
#endif
void
TraceHandle::adjustSizeSpec( bool limit ) noexcept{
uint32_t sz = addAndLimitSizes( &sizeSpec_, limit );
uint32_t maxSize = DEFAULT_MAX_SIZE;
#ifndef __i386__
// On 64-bit small memory systems (e.g. 4GB RAM), automatically scale down
// the maximum total QT ring-buffer size to SMALL_MEMORY_MAX_SIZE
static size_t memorySize = getPhysicalMemorySize();
if ( memorySize <= SMALL_SYSTEM_MEM_SIZE ) {
maxSize = SMALL_MEMORY_MAX_SIZE;
}
#endif
if ( limit && sz > maxSize ) {
sz = scaleDownSizes( &sizeSpec_, ( maxSize * 1.0 ) / sz );
}
sz = sz * 1024 + sizeof( TraceFileHeader ) +
( numMsgCounters_ * sizeof( MsgCounter ) );
mappedTraceFileSize_ = sz;
}
bool
TraceHandle::resize( const SizeSpec &newSizeSpecInKilobytes ) noexcept{
// make sure resize is called only on a single threaded process
if( multiThreading_ == MultiThreading::enabled ) {
std::cerr << "Resizing multi-thread quicktrace not supported" << std::endl;
return false;
}
// check that sizespec to resize to is not the same as old sizespec
if( sizeSpec_ == newSizeSpecInKilobytes ){
std::cerr << "QuickTrace resize not required, identical SizeSpec" << std::endl;
return false;
}
bool deleteAndCreate = ( nonMtTraceFile_ != nullptr );
if ( deleteAndCreate ) {
// delete existing traceFile(s) - only one for single thread
close();
}
// change sizeSpec
sizeSpec_ = newSizeSpecInKilobytes;
adjustSizeSpec( false );
if ( deleteAndCreate ) {
// create new file and rotate old one
bool logRotate = true;
nonMtTraceFile_ = newTraceFile( logRotate, numMsgCounters_ );
// set other parts correctly
initialized_ = true;
traceFilesClosed_ = false;
}
return true;
}
TraceFile::TraceFile( TraceHandle * traceHandle, bool rotateLogFile,
uint32_t numMsgCounters ) noexcept
: traceHandle_( traceHandle ),
numMsgCounters_( numMsgCounters ),
buf_( 0 ),
initialized_( false ) {
multiThreading_ = traceHandle_->multiThreading_;
fileName_ = traceHandle_->qtdir();
if( fileName_ != "" ) {
fileName_ += "/";
}
if( traceHandle_->multiThreading_ == MultiThreading::enabled ) {
// Obtain the thread name that must have been previously been
// set through pthread_setname_np() to construct a unique
// thread-specific trace filename.
char threadName[ 100 ];
pthread_t myTid = pthread_self();
int ret = pthread_getname_np( myTid, threadName, sizeof( threadName ) );
assert( ret == 0 );
fileName_ += threadName;
}
fileName_ += traceHandle_->fileNameSuffix();
for( auto iter = traceHandle_->traceFiles_.cbegin();
iter != traceHandle_->traceFiles_.cend(); ++iter ) {
TraceFile * otherTraceFile = *iter;
assert( fileName_ != otherTraceFile->fileName_ );
}
// Rename the old .qt file.
if( rotateLogFile ) {
saveOldFiles( fileName_.c_str() );
}
// Open file and memory map
uint32_t mappedSize = traceHandle_->mappedTraceFileSize();
fd_ = getfile( fileName_.c_str(), mappedSize );
if( fd_ < 0 ) return;
void * m = mmap( 0, mappedSize, PROT_WRITE, MAP_SHARED, fd_, 0 );
if( m == MAP_FAILED ) {
std::cerr << "mmap " << fileName_ << ": "
<< errno << " " << strerror( errno ) << std::endl;
closeIfNeeded();
return;
}
int r = madvise( m, mappedSize, MADV_DONTDUMP ); // Don't include qt files in core
assert( r == 0 && "madvise() MADV_DONTDUMP failed" );
memset( m, 0, mappedSize ); // is this necessary?
buf_ = m;
TraceFileHeader* sfh = (TraceFileHeader*) m;
sfh->version = 5;
sfh->fileSize = mappedSize;
sfh->fileHeaderSize =
sizeof( TraceFileHeader ) + ( numMsgCounters_ * sizeof( MsgCounter ) );
sfh->fileTrailerSize = FileTrailerSize;
sfh->firstMsgOffset = sizeof( TraceFileHeader );
sfh->logCount = NumTraceLevels;
SizeSpec sizeSpec = traceHandle_->sizeSpec();
sfh->logSizes = sizeSpec;
MsgCounter * msgCounters = ( MsgCounter * )( sfh + 1 );
char * logStart = ( ( char * )m ) + sizeof( TraceFileHeader ) +
( numMsgCounters_ * sizeof( MsgCounter ) );
for( int i=0; i<NumTraceLevels; ++i ) {
int levelOffset = addLevelSizes( &sizeSpec, i ) * 1024;
log_[i].bufIs( logStart + levelOffset, sizeSpec.sz[ i ] * 1024 );
log_[i].qtFileIs( this );
log_[i].msgCounterIs( msgCounters );
log_[i].numMsgCountersIs( numMsgCounters_ );
}
// Insert TraceFile into the set maintained by the TraceHandle
traceHandle_->traceFiles_.insert( this );
initialized_ = true;
sfh->tsc0 = rdtsc();
sfh->monotime0 = monotime();
do {
takeTimestamp();
} while( sfh->monotime1 - sfh->monotime0 < 0.1 );
}
TraceFile::~TraceFile() noexcept {
if( buf_ ){
munmap( buf_, traceHandle_->mappedTraceFileSize() );
}
// Close the associated file descriptor
closeIfNeeded();
// Remove TraceFile from the set maintained by the TraceHandle
traceHandle_->traceFiles_.erase( this );
}
void TraceFile::closeIfNeeded() noexcept {
if( fd_ < 0 ) return;
int rc = ::close( fd_ );
assert( rc == 0 );
fd_ = -1;
}
void
TraceFile::sync() noexcept {
msync( buf_, traceHandle_->mappedTraceFileSize(), MS_SYNC );
}
void
TraceFile::takeTimestamp() noexcept {
TraceFileHeader* sfh = (TraceFileHeader*) buf_;
uint64_t tsc = rdtsc();
// Only take a new timestamp every 1 million cycles It's pointless
// to go much faster and this way we guarantee that we don't spend
// a lot of time monotime() and in gettimeofday(), which each take
// around a microsecond.
if( tsc - sfh->tsc1 > 1000000 ) {
sfh->tsc1 = tsc;
sfh->monotime1 = monotime();
sfh->utc1 = utc();
}
}
void
TraceFile::msgIdInitializedIs( MsgId msgId ) noexcept {
// Record that the necessary message descriptor information for
// this ID has been added to the trace file.
if( msgIdInitialized_.size() <= ( size_t )msgId ) {
msgIdInitialized_.resize( ( size_t )msgId + 32 );
}
msgIdInitialized_[ msgId ] = true;
}
// The wall-clock timestamp returned by gettimeofday
struct timeval
TraceFile::wallClockTimestamp() const noexcept {
struct timeval tv;
gettimeofday( &tv, 0 );
return tv;
}
struct RingBufHeader {
uint32_t tailPtr;
};
inline void
RingBuf::maybeWrap( TraceFile *tf ) noexcept {
if( unlikely(ptr_ >= bufEnd_) ) {
doWrap();
qtFile_->maybeBackupBuffer();
}
}
void
RingBuf::bufIs( void * buf, int bufSize ) noexcept {
buf_ = (char*)buf;
bufEnd_ = buf_ + bufSize - TrailerSize;
// initialize trailer to 0xff's to help qttail synchronize with messages
// that spill over into the trailer
memset( bufEnd_, -1, TrailerSize );
ptr_ = buf_;
doWrap();
// mark the buffer as empty by writing a zero tsc
memset( ptr_, 0, sizeof( uint64_t ) );
}
RingBuf::RingBuf() noexcept {
memset( this, 0, sizeof( *this ));
}
void
RingBuf::doWrap() noexcept {
memset( ptr_, -1, sizeof( uint64_t ) ); // restore the trailer's 0xff's
RingBufHeader * hdr = (RingBufHeader*) buf_;
hdr->tailPtr = ptr_ - buf_; // distance to byte after end of last message
ptr_ = (char*)(hdr+1);
if( qtFile_ )
qtFile_->takeTimestamp();
}
void
RingBuf::qtFileIs( TraceFile * f ) noexcept { qtFile_ = f; }
#ifndef SUPERFAST
uint64_t
RingBuf::startMsg( TraceFile *tf, MsgId id ) noexcept {
MsgCounter * mc = msgCounter( id );
__builtin_prefetch( mc, 1, 1 ); // This seems to make a small difference
maybeWrap(tf);
uint64_t tsc;
tsc = rdtsc();
// Don't touch the message if the 'off' bit is set
uint32_t off = mc->lastTsc & 0x80000000;
if( off ) {
msgStart_ = 0;
} else {
msgStart_ = ptr_;
memcpy( ptr_, &tsc, sizeof( tsc ) );
ptr_ += sizeof( uint64_t );
memcpy( ptr_, &id, sizeof( id ) );
ptr_ += sizeof( id );
}
// Update the hit counters. The high 4 bits of TSC take more
// than 8.5 years to become non-zero on a processor whose TSC
// advances at 2**32 ticks/second. So we'll not worry about the
// case where the last-use timer is more than 8 years ago.
// We make sure the 32nd bit is never set by masking it unless we set it manually.
// With a high enough tsc value, the 32nd bit can end up being true,
// and we don't want to disable the qt message when that becomes true.
mc->lastTsc = ( ( tsc >> 28 ) & 0x7FFFFFFF ) | off;
mc->count++;
return tsc;
}
void
RingBuf::endMsg() noexcept {
if ( enabled() ) {
*ptr_ = (char) (ptr_-msgStart_);
ptr_++;
memset( ptr_, 0, sizeof( uint64_t ) );
}
}
#endif
BlockTimer::~BlockTimer() noexcept {
if( likely( qtFile_ != 0 ) ) {
uint64_t now = rdtsc();
uint64_t delta = now - tsc_;
MsgCounter * mc = qtFile_->msgCounter( msgId_ );
mc->tscCount += delta;
mc->count++;
}
}
BlockTimerMsg::~BlockTimerMsg() noexcept {
if( likely( qtFile_ != 0 ) ) {
uint64_t now = rdtsc();
uint64_t delta = now - tsc_;
MsgCounter * mc = qtFile_->msgCounter( msgId_ );
mc->tscCount += delta;
}
}
BlockTimerSelf::BlockTimerSelf( TraceFile * sf, MsgId mid ) noexcept :
qtFile_( sf ), msgId_( mid ), tsc_( rdtsc() ) {
if ( qtFile_ != 0 ) {
threadSubFuncStack.push_back( 0 );
}
}
BlockTimerSelf::~BlockTimerSelf() noexcept {
if( likely( qtFile_ != 0 ) ) {
uint64_t now = rdtsc();
uint64_t delta = now - tsc_;
MsgCounter * mc = qtFile_->msgCounter( msgId_ );
mc->lastTsc = ( now >> 28 ) | ( mc->lastTsc & 0x80000000 );
mc->tscCount += delta;
mc->count++;
mc->tscSelfCount += delta;
mc->tscSelfCount -= threadSubFuncStack.back();
threadSubFuncStack.pop_back();
threadSubFuncStack.back() += delta;
}
}
BlockTimerSelfMsg::BlockTimerSelfMsg( TraceFile * sf, MsgId mid,
uint64_t now ) noexcept :
qtFile_( sf ), msgId_( mid ), tsc_( now ) {
if( qtFile_ != 0 ) {
threadSubFuncStack.push_back( 0 );
}
}
BlockTimerSelfMsg::~BlockTimerSelfMsg() noexcept {
if( likely( qtFile_ != 0 ) ) {
uint64_t now = rdtsc();
uint64_t delta = now - tsc_;
MsgCounter * mc = qtFile_->msgCounter( msgId_ );
mc->tscCount += delta;
mc->tscSelfCount += delta;
mc->tscSelfCount -= threadSubFuncStack.back();
threadSubFuncStack.pop_back();
threadSubFuncStack.back() += delta;
}
}
void put( RingBuf * log,
char const * x ) noexcept __attribute__ ( ( optimize( 3 ) ) );
void
put( RingBuf * log, char const * x ) noexcept {
// pascal-style string: len byte followed by data
char * ptr = ((char*) log->ptr());
char * ptr1 = ptr + 1;
int i;
for( i = 0 ; i < qtMaxStringLen ; ++i ) {
if( !x[i] ) { break; }
ptr1[i] = x[i];
}
*ptr = i;
log->ptrIs( ptr1 + i );
}
// Invoked when a thread is destroyed and the pthread TLS is being
// cleaned up.
static void
deleteTraceFile( void * tf ) noexcept {
// Deleting the TraceFile will modify the TraceHandle as we will be
// removing the TraceFile from the traceFiles_ set maintained in
// the TraceHandle.
std::lock_guard< std::mutex > lock( traceHandleMutex );
delete ( TraceFile * )tf;
}
// Controls whether we simply close the TraceHandles on fork or if we
// actually delete them. Default is to just close to support existing
// users that attempt to use the TraceHandle in the child process.
static bool deleteTraceHandlesOnFork;
void
setDeleteTraceHandlesOnFork() noexcept {
deleteTraceHandlesOnFork = true;
}
static void
processForkPrepare() noexcept {
// Block TraceHandle or TraceFile creation while we are forking
traceHandleMutex.lock();
}
static void
processForkParent() noexcept {
// Release the lock acquired in processForkPrepare()
traceHandleMutex.unlock();
}
static void
processForkChild() noexcept {
// The old mutex was locked by the parent process and we cannot
// release the lock as we have a different thread-id. Re-initalize
// the mutex by destroying the old mutex and constructing a new one
// in its place.
traceHandleMutex.~mutex();
new ( &traceHandleMutex ) std::mutex();
// At this point we are the only thread in the new child process.
if( deleteTraceHandlesOnFork ) {
while ( !traceHandleMap.empty() ) {
TraceHandle * th = traceHandleMap.begin()->second;
delete th;
}
} else {
// Closing the TraceHandle means that anyone holding onto a
// pointer can still access it. Tracing will be prevented as the
// user will get a NULL TraceFile when they attempt to issue a
// trace message. The NULL TraceFile is handled by the
// QuickTrace macros.
for ( auto iter = traceHandleMap.begin(); iter != traceHandleMap.end();
++iter ) {
TraceHandle * th = iter->second;
th->close();
}
}
}
static void
registerPostForkCleanup() noexcept {
static bool initialized;
if( initialized ) {
return;
}
initialized = true;
// Register handlers to safely handle a fork and to cleanup
// quicktrace on the child process after a fork.
// We shouldn't be holding any other custom locks inside quicktrace so pick
// a large priority value
#ifdef QT_USE_ATFORK_LIB
registerAtForkHandler( processForkPrepare, processForkParent, processForkChild,
100 );
#else
pthread_atfork( processForkPrepare, processForkParent, processForkChild );
#endif
}
TraceHandle::TraceHandle( char const * fileNameFormat,
SizeSpec * sizeSpec,
char const * foreverLogPath,
int foreverLogIndex,
MultiThreading multiThreading,
bool rotateLogFile,
uint32_t numMsgCounters,
bool defaultHandle ) noexcept
: multiThreading_( multiThreading ),
traceFilesClosed_( false ),
numMsgCounters_( numMsgCounters ),
nonMtTraceFile_( NULL ),
traceFileThreadLocalKey_( invalidPthreadKey ),
foreverLogIndex_( foreverLogIndex ),
foreverLog_( false ),
initialized_( false ) {
std::lock_guard< std::mutex > lock( traceHandleMutex );
registerPostForkCleanup();
if( foreverLogPath ) {
// Support for backup of thread specific files and management of
// the index has not been added.
assert( multiThreading_ == MultiThreading::disabled );
foreverLogPath_ = foreverLogPath;
foreverLog_ = true;
}
nextMsgId_ = 1;
assert( NULL != fileNameFormat );
assert( ( multiThreading_ == MultiThreading::enabled ) ||
fileNameFormat[ 0 ] );
// format the PID.
fileNameFormat_ = fileNameFormat;
char fnPid[ 256 ];
snprintf( fnPid, sizeof( fnPid ), fileNameFormat, getpid() );
fileNameSuffix_ = fnPid;
auto qtd = getQtDir( multiThreading_, fileNameFormat_ );
if ( !qtd.has_value() ) {