forked from intel/pcm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pcm-sensor-server.cpp
3332 lines (3001 loc) · 130 KB
/
pcm-sensor-server.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
/*
BSD 3-Clause License
Copyright (c) 2016-2020, Intel Corporation
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 the copyright holder 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.
*/
// Use port allocated for PCM in prometheus:
// https://github.com/prometheus/prometheus/wiki/Default-port-allocations
constexpr unsigned int DEFAULT_HTTP_PORT = 9738;
constexpr unsigned int DEFAULT_HTTPS_PORT = DEFAULT_HTTP_PORT;
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sched.h>
#include <cstring>
#include <fstream>
#include <ctime>
#include <vector>
#include <unordered_map>
#include "cpucounters.h"
#include "debug.h"
#include "topology.h"
#include "dashboard.h"
#define PCMWebServerVersion "0.1"
#if defined (USE_SSL)
# include <openssl/ssl.h>
# include <openssl/err.h>
# define CERT_FILE_NAME "./server.pem"
# define KEY_FILE_NAME "./server.pem"
#endif // USE_SSL
#include <chrono>
#include <algorithm>
#include "threadpool.h"
using namespace pcm;
std::string const HTTP_EOL( "\r\n" );
std::string const PROM_EOL( "\n" );
class Indent {
public:
explicit Indent( std::string const & is = std::string(" ") ) : indstr_(is), indent_(""), len_(0), indstrlen_(is.length())
{
}
Indent() = delete;
Indent(Indent const &) = default;
Indent & operator = (Indent const &) = default;
~Indent() = default;
friend std::stringstream& operator <<( std::stringstream& stream, Indent in );
void printIndentationString(std::stringstream& s) {
s << indent_;
}
// We only need post inc und pre dec
Indent& operator--() {
if ( len_ > 0 )
--len_;
else
throw std::runtime_error("Indent: Decremented len_ too often!");
indent_.erase( len_ * indstrlen_ );
return *this;
}
Indent operator++(int) {
Indent copy( *this );
++len_;
indent_ += indstr_; // add one more indstr_
return copy;
}
private:
std::string indstr_;
std::string indent_;
size_t len_;
size_t const indstrlen_;
};
std::stringstream& operator <<( std::stringstream& stream, Indent in ) {
in.printIndentationString( stream );
return stream;
}
class datetime {
public:
datetime() {
std::time_t t = std::time( nullptr );
const auto gt = std::gmtime( &t );
if (gt == nullptr)
throw std::runtime_error("std::gmtime returned nullptr");
now = *gt;
}
datetime( std::tm t ) : now( t ) {}
~datetime() = default;
datetime( datetime const& ) = default;
datetime & operator = ( datetime const& ) = default;
public:
void printDateTimeString( std::ostream& os ) const {
std::stringstream str("");
char timeBuffer[64];
std::memset( timeBuffer, 0, 64 );
str.imbue( std::locale::classic() );
if ( strftime( timeBuffer, 63, "%a, %d %b %Y %T GMT", &now ) )
str << timeBuffer;
else
throw std::runtime_error("Error writing to timeBuffer, too small?");
os << str.str();
}
std::string toString() const {
std::stringstream str("");
char timeBuffer[64];
std::memset( timeBuffer, 0, 64 );
str.imbue( std::locale::classic() );
if ( strftime( timeBuffer, 63, "%a, %d %b %Y %T GMT", &now ) )
str << timeBuffer;
else
throw std::runtime_error("Error writing to timeBuffer, too small?");
return str.str();
}
private:
std::tm now;
};
std::ostream& operator<<( std::ostream& os, datetime const & dt ) {
dt.printDateTimeString(os);
return os;
}
class date {
public:
date() {
now = std::time(nullptr);
}
~date() = default;
date( date const& ) = default;
date & operator = ( date const& ) = default;
public:
void printDate( std::ostream& os ) const {
char buf[64];
const auto t = std::localtime(&now);
assert(t);
std::strftime( buf, 64, "%F", t);
os << buf;
}
private:
std::time_t now;
};
std::ostream& operator<<( std::ostream& os, date const & d ) {
d.printDate(os);
return os;
}
std::string read_ndctl_info( std::ofstream& logfile ) {
int pipes[2];
if ( pipe( pipes ) == -1 ) {
logfile << date() << ": ERROR Cannot create pipe, errno = " << errno << ", strerror: " << strerror(errno) << ". Exit 50.\n";
exit(50);
}
std::stringstream ndctl;
if ( fork() == 0 ) {
// child, writes to pipe, close read-end
close( pipes[0] );
dup2( pipes[1], fileno(stdout) );
execl( "/usr/bin/ndctl", "ndctl", "list", (char*)NULL );
} else {
// parent, reads from pipe, close write-end
close( pipes[1] );
char buf[2049];
memset( buf, 0, 2049 );
ssize_t len = 0;
while( (len = read( pipes[0], buf, 2048 )) > 0 ) {
buf[len] = '\0';
ndctl << buf;
}
close( pipes[0] );
if ( len < 0 ) {
logfile << ": ERROR Read from ndctl pipe failed. errno = " << errno << ". strerror(errno) = " << strerror(errno) << ". Exit 52.\n";
exit(52);
}
logfile << datetime() << ": INFO Read JSON from ndctl pipe: " << ndctl.str() << ".\n";
}
return ndctl.str();
}
class HTTPServer;
class SignalHandler {
public:
static SignalHandler* getInstance() {
static SignalHandler instance;
return &instance;
}
static void handleSignal( int signum );
void setSocket( int s ) {
networkSocket_ = s;
}
void setHTTPServer( HTTPServer* hs ) {
httpServer_ = hs;
}
void ignoreSignal( int signum ) {
struct sigaction sa;
sa.sa_handler = SIG_IGN;
sa.sa_flags = 0;
sigaction( signum, &sa, 0 );
}
void installHandler( void (*handler)(int), int signum ) {
struct sigaction sa;
sa.sa_handler = handler;
sa.sa_flags = 0;
sigaction( signum, &sa, 0 );
}
SignalHandler( SignalHandler const & ) = delete;
void operator=( SignalHandler const & ) = delete;
~SignalHandler() = default;
private:
SignalHandler() = default;
private:
static int networkSocket_;
static HTTPServer* httpServer_;
};
int SignalHandler::networkSocket_ = 0;
HTTPServer* SignalHandler::httpServer_ = nullptr;
class JSONPrinter : Visitor
{
public:
enum LineEndAction {
NewLineOnly = 0,
DelimiterOnly,
DelimiterAndNewLine,
LineEndAction_Spare = 255
};
JSONPrinter( std::pair<std::shared_ptr<Aggregator>,std::shared_ptr<Aggregator>> aggregatorPair ) : indentation(" "), aggPair_( aggregatorPair ) {
if ( nullptr == aggPair_.second.get() )
throw std::runtime_error("BUG: second Aggregator == nullptr!");
DBG(2, "Constructor: before=", std::hex, aggPair_.first.get(), ", after=", std::hex, aggPair_.second.get() );
}
JSONPrinter( JSONPrinter const & ) = delete;
JSONPrinter & operator = ( JSONPrinter const & ) = delete;
JSONPrinter() = delete;
CoreCounterState const getCoreCounter( std::shared_ptr<Aggregator> ag, uint32 tid ) const {
CoreCounterState ccs;
if ( nullptr == ag.get() )
return ccs;
return std::move( ag->coreCounterStates()[tid] );
}
SocketCounterState const getSocketCounter( std::shared_ptr<Aggregator> ag, uint32 sid ) const {
SocketCounterState socs;
if ( nullptr == ag.get() )
return socs;
return std::move( ag->socketCounterStates()[sid] );
}
SystemCounterState getSystemCounter( std::shared_ptr<Aggregator> ag ) const {
SystemCounterState sycs;
if ( nullptr == ag.get() )
return sycs;
return std::move( ag->systemCounterState() );
}
virtual void dispatch( HyperThread* ht ) override {
printCounter( "Object", "HyperThread" );
printCounter( "Thread ID", ht->threadID() );
printCounter( "OS ID", ht->osID() );
CoreCounterState before = getCoreCounter( aggPair_.first, ht->osID() );
CoreCounterState after = getCoreCounter( aggPair_.second, ht->osID() );
printBasicCounterState( before, after );
}
virtual void dispatch( ServerUncore* su ) override {
printCounter( "Object", "ServerUncore" );
SocketCounterState before = getSocketCounter( aggPair_.first, su->socketID() );
SocketCounterState after = getSocketCounter( aggPair_.second, su->socketID() );
printUncoreCounterState( before, after );
}
virtual void dispatch( ClientUncore* ) override {
printCounter( "Object", "ClientUncore" );
}
virtual void dispatch( Core* c ) override {
printCounter( "Object", "Core" );
auto vec = c->threads();
printCounter( "Number of threads", vec.size() );
startObject( "Threads", BEGIN_LIST );
iterateVectorAndCallAccept( vec );
endObject( JSONPrinter::LineEndAction::DelimiterAndNewLine, END_LIST );
printCounter( "Tile ID", c->tileID() );
printCounter( "Core ID", c->coreID() );
printCounter( "Socket ID", c->socketID() );
}
virtual void dispatch( SystemRoot const & s ) override {
using namespace std::chrono;
auto interval = duration_cast<microseconds>( aggPair_.second->dispatchedAt() - aggPair_.first->dispatchedAt() ).count();
startObject( "", BEGIN_OBJECT );
printCounter( "Interval us", interval );
printCounter( "Object", "SystemRoot" );
auto vec = s.sockets();
printCounter( "Number of sockets", vec.size() );
startObject( "Sockets", BEGIN_LIST );
iterateVectorAndCallAccept( vec );
endObject( JSONPrinter::LineEndAction::DelimiterAndNewLine, END_LIST );
SystemCounterState before = getSystemCounter( aggPair_.first );
SystemCounterState after = getSystemCounter( aggPair_.second );
startObject( "QPI/UPI Links", BEGIN_OBJECT );
printSystemCounterState( before, after );
endObject( JSONPrinter::LineEndAction::DelimiterAndNewLine, END_OBJECT );
startObject( "Core Aggregate", BEGIN_OBJECT );
printBasicCounterState( before, after );
endObject( JSONPrinter::LineEndAction::DelimiterAndNewLine, END_OBJECT );
startObject( "Uncore Aggregate", BEGIN_OBJECT );
printUncoreCounterState( before, after );
endObject( JSONPrinter::LineEndAction::NewLineOnly, END_OBJECT );
endObject( JSONPrinter::LineEndAction::NewLineOnly, END_OBJECT );
}
virtual void dispatch( Socket* s ) override {
printCounter( "Object", "Socket" );
printCounter( "Socket ID", s->socketID() );
auto vec = s->cores();
printCounter( "Number of cores", vec.size() );
startObject( "Cores", BEGIN_LIST );
iterateVectorAndCallAccept( vec );
endObject( JSONPrinter::LineEndAction::DelimiterAndNewLine, END_LIST );
startObject( "Uncore", BEGIN_OBJECT );
s->uncore()->accept( *this );
endObject( JSONPrinter::LineEndAction::DelimiterAndNewLine, END_OBJECT );
startObject( "Core Aggregate", BEGIN_OBJECT );
SocketCounterState before = getSocketCounter( aggPair_.first, s->socketID() );
SocketCounterState after = getSocketCounter( aggPair_.second, s->socketID() );
printBasicCounterState( before, after );
endObject( JSONPrinter::LineEndAction::NewLineOnly, END_OBJECT );
}
std::string str( void ) {
return ss.str();
}
private:
void printBasicCounterState( BasicCounterState const& before, BasicCounterState const& after ) {
startObject( "Core Counters", BEGIN_OBJECT );
printCounter( "Instructions Retired Any", getInstructionsRetired( before, after ) );
printCounter( "Clock Unhalted Thread", getCycles ( before, after ) );
printCounter( "Clock Unhalted Ref", getRefCycles ( before, after ) );
printCounter( "L3 Cache Misses", getL3CacheMisses ( before, after ) );
printCounter( "L3 Cache Hits", getL3CacheHits ( before, after ) );
printCounter( "L2 Cache Misses", getL2CacheMisses ( before, after ) );
printCounter( "L2 Cache Hits", getL2CacheHits ( before, after ) );
printCounter( "L3 Cache Occupancy", getL3CacheOccupancy ( after ) );
printCounter( "Invariant TSC", getInvariantTSC ( before, after ) );
printCounter( "SMI Count", getSMICount ( before, after ) );
endObject( JSONPrinter::DelimiterAndNewLine, END_OBJECT );
//DBG( 2, "Invariant TSC before=", before.InvariantTSC, ", after=", after.InvariantTSC, ", difference=", after.InvariantTSC-before.InvariantTSC );
startObject( "Energy Counters", BEGIN_OBJECT );
printCounter( "Thermal Headroom", after.getThermalHeadroom() );
uint32 i = 0;
for ( ; i < ( PCM::MAX_C_STATE ); ++i ) {
std::stringstream s;
s << "CStateResidency[" << i << "]";
printCounter( s.str(), getCoreCStateResidency( i, before, after ) );
}
// Here i == PCM::MAX_STATE so no need to type so many characters ;-)
std::stringstream s;
s << "CStateResidency[" << i << "]";
printCounter( s.str(), getCoreCStateResidency( i, before, after ) );
endObject( JSONPrinter::DelimiterAndNewLine, END_OBJECT );
startObject( "Core Memory Bandwidth Counters", BEGIN_OBJECT );
printCounter( "Local Memory Bandwidth", getLocalMemoryBW( before, after ) );
printCounter( "Remote Memory Bandwidth", getRemoteMemoryBW( before, after ) );
endObject( JSONPrinter::NewLineOnly, END_OBJECT );
}
void printUncoreCounterState( SocketCounterState const& before, SocketCounterState const& after ) {
startObject( "Uncore Counters", BEGIN_OBJECT );
printCounter( "DRAM Writes", getBytesWrittenToMC ( before, after ) );
printCounter( "DRAM Reads", getBytesReadFromMC ( before, after ) );
printCounter( "Persistent Memory Writes", getBytesWrittenToPMM ( before, after ) );
printCounter( "Persistent Memory Reads", getBytesReadFromPMM ( before, after ) );
printCounter( "Embedded DRAM Writes", getBytesWrittenToEDC ( before, after ) );
printCounter( "Embedded DRAM Reads", getBytesReadFromEDC ( before, after ) );
printCounter( "Memory Controller IO Requests", getIORequestBytesFromMC( before, after ) );
printCounter( "Package Joules Consumed", getConsumedJoules ( before, after ) );
printCounter( "DRAM Joules Consumed", getDRAMConsumedJoules ( before, after ) );
uint32 i = 0;
for ( ; i < ( PCM::MAX_C_STATE ); ++i ) {
std::stringstream s;
s << "CStateResidency[" << i << "]";
printCounter( s.str(), getPackageCStateResidency( i, before, after ) );
}
// Here i == PCM::MAX_STATE so no need to type so many characters ;-)
std::stringstream s;
s << "CStateResidency[" << i << "]";
printCounter( s.str(), getPackageCStateResidency( i, before, after ) );
endObject( JSONPrinter::NewLineOnly, END_OBJECT );
}
void printSystemCounterState( SystemCounterState const& before, SystemCounterState const& after ) {
PCM* pcm = PCM::getInstance();
uint32 sockets = pcm->getNumSockets();
uint32 links = pcm->getQPILinksPerSocket();
for ( uint32 i=0; i < sockets; ++i ) {
startObject( std::string( "QPI Counters Socket " ) + std::to_string( i ), BEGIN_OBJECT );
for ( uint32 j=0; j < links; ++j ) {
printCounter( std::string( "Incoming Data Traffic On Link " ) + std::to_string( j ), getIncomingQPILinkBytes ( i, j, before, after ) );
printCounter( std::string( "Outgoing Data And Non-Data Traffic On Link " ) + std::to_string( j ), getOutgoingQPILinkBytes ( i, j, before, after ) );
printCounter( std::string( "Utilization Incoming Data Traffic On Link " ) + std::to_string( j ), getIncomingQPILinkUtilization( i, j, before, after ) );
printCounter( std::string( "Utilization Outgoing Data And Non-Data Traffic On Link " ) + std::to_string( j ), getOutgoingQPILinkUtilization( i, j, before, after ) );
}
endObject( JSONPrinter::DelimiterAndNewLine, END_OBJECT );
}
}
template <typename Counter>
void printCounter( std::string const & name, Counter c );
template <typename Vector>
void iterateVectorAndCallAccept( Vector const& v );
void startObject(std::string const& s, char const ch ) {
std::string name;
if ( s.size() != 0 )
name = "\"" + s + "\" : ";
ss << (indentation++) << name << ch << HTTP_EOL;
}
void endObject( enum JSONPrinter::LineEndAction lea, char const ch ) {
// look 3 chars back, if it is a ',' then delete it.
// make read same as write position - 3
std::stringstream::pos_type oldReadPos = ss.tellg();
ss.seekg( -3, std::ios_base::end );
if ( ss.peek() == ',' ) {
ss.seekp( ss.tellg() ); // Make write same as read position
ss << HTTP_EOL;
}
ss.seekg( oldReadPos );// Just making sure the readpointer is set back to where it was
ss << (--indentation) << ch;
if ( lea == LineEndAction::NewLineOnly )
ss << HTTP_EOL;
else if ( lea == LineEndAction::DelimiterAndNewLine )
ss << "," << HTTP_EOL;
else if ( lea == LineEndAction::DelimiterOnly )
ss << ",";
else
throw std::runtime_error( "Unknown LineEndAction enum" );
}
void insertListDelimiter() {
ss << "," << HTTP_EOL;
}
private:
Indent indentation;
std::pair<std::shared_ptr<Aggregator>,std::shared_ptr<Aggregator>> aggPair_;
const char BEGIN_OBJECT = '{';
const char END_OBJECT = '}';
const char BEGIN_LIST = '[';
const char END_LIST = ']';
};
template <typename Counter>
void JSONPrinter::printCounter( std::string const & name, Counter c ) {
if ( std::is_same<Counter, std::string>::value || std::is_same<Counter, char const*>::value )
ss << indentation << "\"" << name << "\" : \"" << c << "\"," << HTTP_EOL;
else
ss << indentation << "\"" << name << "\" : " << c << "," << HTTP_EOL;
}
template <typename Vector>
void JSONPrinter::iterateVectorAndCallAccept(Vector const& v) {
for ( auto* vecElem: v ) {
// Inside a list objects are not named
startObject( "", BEGIN_OBJECT );
vecElem->accept( *this );
endObject( JSONPrinter::DelimiterAndNewLine, END_OBJECT );
}
};
class PrometheusPrinter : Visitor
{
public:
PrometheusPrinter( std::pair<std::shared_ptr<Aggregator>,std::shared_ptr<Aggregator>> aggregatorPair ) : aggPair_( aggregatorPair ) {
if ( nullptr == aggPair_.second.get() )
throw std::runtime_error("BUG: second Aggregator == nullptr!");
DBG(2, "Constructor: before=", std::hex, aggPair_.first.get(), ", after=", std::hex, aggPair_.second.get() );
}
PrometheusPrinter( PrometheusPrinter const & ) = delete;
PrometheusPrinter & operator = ( PrometheusPrinter const & ) = delete;
PrometheusPrinter() = delete;
CoreCounterState const getCoreCounter( std::shared_ptr<Aggregator> ag, uint32 tid ) const {
CoreCounterState ccs;
if ( nullptr == ag.get() )
return ccs;
return std::move( ag->coreCounterStates()[tid] );
}
SocketCounterState const getSocketCounter( std::shared_ptr<Aggregator> ag, uint32 sid ) const {
SocketCounterState socs;
if ( nullptr == ag.get() )
return socs;
return std::move( ag->socketCounterStates()[sid] );
}
SystemCounterState getSystemCounter( std::shared_ptr<Aggregator> ag ) const {
SystemCounterState sycs;
if ( nullptr == ag.get() )
return sycs;
return std::move( ag->systemCounterState() );
}
virtual void dispatch( HyperThread* ht ) override {
addToHierarchy( "thread=\"" + std::to_string( ht->threadID() ) + "\"" );
printCounter( "OS ID", ht->osID() );
CoreCounterState before = getCoreCounter( aggPair_.first, ht->osID() );
CoreCounterState after = getCoreCounter( aggPair_.second, ht->osID() );
printBasicCounterState( before, after );
removeFromHierarchy();
}
virtual void dispatch( ServerUncore* su ) override {
printComment( std::string( "Uncore Counters Socket " ) + std::to_string( su->socketID() ) );
SocketCounterState before = getSocketCounter( aggPair_.first, su->socketID() );
SocketCounterState after = getSocketCounter( aggPair_.second, su->socketID() );
printUncoreCounterState( before, after );
}
virtual void dispatch( ClientUncore* ) override {
}
virtual void dispatch( Core* c ) override {
addToHierarchy( std::string( "core=\"" ) + std::to_string( c->coreID() ) + "\"" );
auto vec = c->threads();
iterateVectorAndCallAccept( vec );
// Useless?
//printCounter( "Tile ID", c->tileID() );
//printCounter( "Core ID", c->coreID() );
//printCounter( "Socket ID", c->socketID() );
removeFromHierarchy();
}
virtual void dispatch( SystemRoot const & s ) override {
using namespace std::chrono;
auto interval = duration_cast<microseconds>( aggPair_.second->dispatchedAt() - aggPair_.first->dispatchedAt() ).count();
printCounter( "Measurement Interval in us", interval );
auto vec = s.sockets();
printCounter( "Number of sockets", vec.size() );
iterateVectorAndCallAccept( vec );
SystemCounterState before = getSystemCounter( aggPair_.first );
SystemCounterState after = getSystemCounter( aggPair_.second );
addToHierarchy( "aggregate=\"system\"" );
PCM* pcm = PCM::getInstance();
if ( pcm->isServerCPU() && pcm->getNumSockets() >= 2 ) {
printComment( "UPI/QPI Counters" );
printSystemCounterState( before, after );
}
printComment( "Core Counters Aggregate System" );
printBasicCounterState ( before, after );
printComment( "Uncore Counters Aggregate System" );
printUncoreCounterState( before, after );
removeFromHierarchy(); // aggregate=system
}
virtual void dispatch( Socket* s ) override {
addToHierarchy( std::string( "socket=\"" ) + std::to_string( s->socketID() ) + "\"" );
printComment( std::string( "Core Counters Socket " ) + std::to_string( s->socketID() ) );
auto vec = s->cores();
iterateVectorAndCallAccept( vec );
// Uncore writes the comment for the socket uncore counters
s->uncore()->accept( *this );
addToHierarchy( "aggregate=\"socket\"" );
printComment( std::string( "Core Counters Aggregate Socket " ) + std::to_string( s->socketID() ) );
SocketCounterState before = getSocketCounter( aggPair_.first, s->socketID() );
SocketCounterState after = getSocketCounter( aggPair_.second, s->socketID() );
printBasicCounterState( before, after );
removeFromHierarchy(); // aggregate=socket
removeFromHierarchy(); // socket=x
}
std::string str( void ) {
return ss.str();
}
private:
void printBasicCounterState( BasicCounterState const& before, BasicCounterState const& after ) {
addToHierarchy( "source=\"core\"" );
printCounter( "Instructions Retired Any", getInstructionsRetired( before, after ) );
printCounter( "Clock Unhalted Thread", getCycles ( before, after ) );
printCounter( "Clock Unhalted Ref", getRefCycles ( before, after ) );
printCounter( "L3 Cache Misses", getL3CacheMisses ( before, after ) );
printCounter( "L3 Cache Hits", getL3CacheHits ( before, after ) );
printCounter( "L2 Cache Misses", getL2CacheMisses ( before, after ) );
printCounter( "L2 Cache Hits", getL2CacheHits ( before, after ) );
printCounter( "L3 Cache Occupancy", getL3CacheOccupancy ( after ) );
printCounter( "Invariant TSC", getInvariantTSC ( before, after ) );
printCounter( "SMI Count", getSMICount ( before, after ) );
//DBG( 2, "Invariant TSC before=", before.InvariantTSC, ", after=", after.InvariantTSC, ", difference=", after.InvariantTSC-before.InvariantTSC );
printCounter( "Thermal Headroom", after.getThermalHeadroom() );
uint32 i = 0;
for ( ; i <= ( PCM::MAX_C_STATE ); ++i ) {
std::stringstream s;
s << "index=\"" << i << "\"";
addToHierarchy( s.str() );
printCounter( "CStateResidency", getCoreCStateResidency( i, before, after ) );
// need a raw CStateResidency metric because the precision is lost to unacceptable levels when trying
// to compute CStateResidency for the last second using the existing CStateResidency metric
printCounter( "RawCStateResidency", getCoreCStateResidency( i, after ) );
removeFromHierarchy();
}
printCounter( "Local Memory Bandwidth", getLocalMemoryBW( before, after ) );
printCounter( "Remote Memory Bandwidth", getRemoteMemoryBW( before, after ) );
removeFromHierarchy();
}
void printUncoreCounterState( SocketCounterState const& before, SocketCounterState const& after ) {
addToHierarchy( "source=\"uncore\"" );
printCounter( "DRAM Writes", getBytesWrittenToMC ( before, after ) );
printCounter( "DRAM Reads", getBytesReadFromMC ( before, after ) );
printCounter( "Persistent Memory Writes", getBytesWrittenToPMM ( before, after ) );
printCounter( "Persistent Memory Reads", getBytesReadFromPMM ( before, after ) );
printCounter( "Embedded DRAM Writes", getBytesWrittenToEDC ( before, after ) );
printCounter( "Embedded DRAM Reads", getBytesReadFromEDC ( before, after ) );
printCounter( "Memory Controller IO Requests", getIORequestBytesFromMC( before, after ) );
printCounter( "Package Joules Consumed", getConsumedJoules ( before, after ) );
printCounter( "DRAM Joules Consumed", getDRAMConsumedJoules ( before, after ) );
uint32 i = 0;
for ( ; i <= ( PCM::MAX_C_STATE ); ++i ) {
std::stringstream s;
s << "index=\"" << i << "\"";
addToHierarchy( s.str() );
printCounter( "CStateResidency", getPackageCStateResidency( i, before, after ) );
// need a CStateResidency raw metric because the precision is lost to unacceptable levels when trying
// to compute CStateResidency for the last second using the existing CStateResidency metric
printCounter( "RawCStateResidency", getPackageCStateResidency( i, after ) );
removeFromHierarchy();
}
removeFromHierarchy();
}
void printSystemCounterState( SystemCounterState const& before, SystemCounterState const& after ) {
addToHierarchy( "source=\"uncore\"" );
PCM* pcm = PCM::getInstance();
uint32 sockets = pcm->getNumSockets();
uint32 links = pcm->getQPILinksPerSocket();
for ( uint32 i=0; i < sockets; ++i ) {
addToHierarchy( std::string( "socket=\"" ) + std::to_string( i ) + "\"" );
for ( uint32 j=0; j < links; ++j ) {
printCounter( std::string( "Incoming Data Traffic On Link " ) + std::to_string( j ), getIncomingQPILinkBytes ( i, j, before, after ) );
printCounter( std::string( "Outgoing Data And Non-Data Traffic On Link " ) + std::to_string( j ), getOutgoingQPILinkBytes ( i, j, before, after ) );
printCounter( std::string( "Utilization Incoming Data Traffic On Link " ) + std::to_string( j ), getIncomingQPILinkUtilization( i, j, before, after ) );
printCounter( std::string( "Utilization Outgoing Data And Non-Data Traffic On Link " ) + std::to_string( j ), getOutgoingQPILinkUtilization( i, j, before, after ) );
}
removeFromHierarchy();
}
removeFromHierarchy();
}
std::string replaceIllegalCharsWithUnderbar( std::string const& s ) {
size_t pos = 0;
std::string str(s);
while ( ( pos = str.find( '-', pos ) ) != std::string::npos ) {
str.replace( pos, 1, "_" );
}
pos = 0;
while ( ( pos = str.find( ' ', pos ) ) != std::string::npos ) {
str.replace( pos, 1, "_" );
}
return str;
}
void addToHierarchy( std::string const& s ) {
hierarchy_.push_back( s );
}
void removeFromHierarchy() {
hierarchy_.pop_back();
}
std::string printHierarchy() {
std::string s(" ");
if (hierarchy_.size() == 0 )
return s;
s = "{";
for(const auto & level : hierarchy_ ) {
s += level + ',';
}
s.pop_back();
s += "} ";
return s;
}
template <typename Counter>
void printCounter( std::string const & name, Counter c );
void printComment( std::string const &comment ) {
ss << "# " << comment << PROM_EOL;
}
template <typename Vector>
void iterateVectorAndCallAccept( Vector const& v );
private:
std::pair<std::shared_ptr<Aggregator>,std::shared_ptr<Aggregator>> aggPair_;
std::vector<std::string> hierarchy_;
};
template <typename Counter>
void PrometheusPrinter::printCounter( std::string const & name, Counter c ) {
ss << replaceIllegalCharsWithUnderbar(name) << printHierarchy() << c << PROM_EOL;
}
template <typename Vector>
void PrometheusPrinter::iterateVectorAndCallAccept(Vector const& v) {
for ( auto* vecElem: v ) {
vecElem->accept( *this );
}
};
template <std::size_t SIZE = 256, class CharT = char, class Traits = std::char_traits<CharT>>
class basic_socketbuf : public std::basic_streambuf<CharT> {
public:
using Base = std::basic_streambuf<CharT>;
using char_type = typename Base::char_type;
using int_type = typename Base::int_type;
using traits_type = typename Base::traits_type;
basic_socketbuf(): socketFD_(0) {
// According to http://en.cppreference.com/w/cpp/io/basic_streambuf
// epptr and egptr point beyond the buffer, so start + SIZE
Base::setp( outputBuffer_, outputBuffer_ + SIZE );
Base::setg( inputBuffer_, inputBuffer_, inputBuffer_ );
// Default timeout of 10 seconds and 0 microseconds
timeout_ = { 10, 0 };
#if defined (USE_SSL)
ssl_ = nullptr;
#endif
}
virtual ~basic_socketbuf() {
basic_socketbuf::sync();
#if defined (USE_SSL)
if ( nullptr != ssl_ ) {
SSL_free( ssl_ );
}
#endif
if ( 0 != socketFD_ )
::close( socketFD_ );
}
int socket() {
return socketFD_;
}
void setSocket( int socketFD ) {
socketFD_ = socketFD;
// When receiving the socket descriptor, set the timeout
setsockopt( socketFD_, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout_, sizeof(struct timeval) );
}
void setTimeout( struct timeval t ) {
timeout_ = t;
setsockopt( socketFD_, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout_, sizeof(struct timeval) );
}
#if defined (USE_SSL)
SSL* ssl() {
return ssl_;
}
void setSSL( SSL* ssl ) {
if ( nullptr != ssl_ )
throw std::runtime_error( "You can set the SSL pointer only once" );
if ( nullptr == ssl )
throw std::runtime_error( "Trying to set a nullptr as ssl" );
ssl_ = ssl;
}
#endif
protected:
int_type writeToSocket() {
size_t bytesToSend;
ssize_t bytesSent;
bytesToSend = (char*)Base::pptr() - (char*)Base::pbase();
#if defined (USE_SSL)
if ( nullptr == ssl_ ) {
#endif
bytesSent= ::send( socketFD_, (void*)outputBuffer_, bytesToSend, MSG_NOSIGNAL );
if ( -1 == bytesSent ) {
std::cerr << strerror( errno ) << "\n";
return traits_type::eof();
}
#if defined (USE_SSL)
}
else {
while( 1 ) {
// openSSL has no support for setting the MSG_NOSIGNAL during send
// but we ignore sigpipe so we should be fine
bytesSent = SSL_write( ssl_, (void*)outputBuffer_, bytesToSend );
if ( 0 >= bytesSent ) {
int sslError = SSL_get_error( ssl_, bytesSent );
switch ( sslError ) {
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
// retry
continue; // Should continue in the while loop and attempt to write again
// break;
case SSL_ERROR_ZERO_RETURN:
case SSL_ERROR_SYSCALL:
case SSL_ERROR_SSL:
default:
return traits_type::eof();
}
} else {
// Valid write
break; // out of the while loop
}
}
}
#endif
Base::pbump( -bytesSent );
return bytesSent;
}
int sync() override {
int_type ret = writeToSocket();
if ( traits_type::eof() == ret )
return -1;
return 0;
}
virtual int_type overflow( int_type ch ) {
// send data in buffer and reset it
if ( traits_type::eof() != ch ) {
*Base::pptr() = ch;
Base::pbump(1);
}
int_type bytesWritten = 0;
if ( traits_type::eof() == (bytesWritten = writeToSocket()) ) {
return traits_type::eof();
}
return bytesWritten; // Anything but traits_type::eof() to signal ok.
}
virtual int_type underflow() {
memset( inputBuffer_, 0, SIZE * sizeof( char_type ) );
ssize_t bytesReceived;
#if defined (USE_SSL)
if ( nullptr == ssl_ ) {
#endif
DBG( 3, "Socketbuf: Read from socket:" );
bytesReceived = ::read( socketFD_, static_cast<char*>(inputBuffer_), SIZE * sizeof( char_type ) );
if ( 0 == bytesReceived ) {
// Client closed the socket normally, we will do the same
::close( socketFD_ );
return traits_type::eof();
}
if ( -1 == bytesReceived ) {
if ( errno )
DBG( 3, "Errno: ", errno, ", (", strerror( errno ) , ")" );
::close( socketFD_ );
Base::setg( nullptr, nullptr, nullptr );
return traits_type::eof();
}
DBG( 3, "Bytes received: ", bytesReceived );
debug::dyn_hex_table_output( 3, std::cout, bytesReceived, inputBuffer_ );
DBG( 3, "End", std::dec );
#if defined (USE_SSL)
}
else {
while (1) {
bytesReceived = SSL_read( ssl_, static_cast<void*>(inputBuffer_), SIZE * sizeof( char_type ) );
if ( 0 >= bytesReceived ) {
int sslError = SSL_get_error( ssl_, bytesReceived );
switch ( sslError ) {
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
// retry
continue; // Should continue in the while loop and attempt to read again
break;
case SSL_ERROR_ZERO_RETURN:
case SSL_ERROR_SYSCALL:
case SSL_ERROR_SSL:
default:
Base::setg( nullptr, nullptr, nullptr );
return traits_type::eof();
}
} else {
// Valid read
break; // out of the while loop
}
}
}
#endif
// In case the number of bytes read is not the size of the buffer, we have to set
// egptr to start plus the number of bytes received
Base::setg( inputBuffer_, inputBuffer_, inputBuffer_ + bytesReceived );
return *inputBuffer_;
}
protected:
CharT outputBuffer_[SIZE];
CharT inputBuffer_[SIZE];
int socketFD_;
struct timeval timeout_;
#if defined (USE_SSL)
SSL* ssl_;
#endif
};
template <class CharT, class Traits = std::char_traits<CharT>>
class basic_socketstream : public std::basic_iostream<CharT, Traits> {
public:
using Base = std::basic_iostream<CharT, Traits>;
using stream_type = typename std::basic_iostream<CharT, Traits>;
using buf_type = basic_socketbuf<16385, CharT, Traits>;
using traits_type = typename Base::traits_type;
public:
basic_socketstream() : stream_type( &socketBuffer_ ) {}
#if defined (USE_SSL)
basic_socketstream( int socketFD, SSL* ssl ) : stream_type( &socketBuffer_ ) {
#else
basic_socketstream( int socketFD ) : stream_type( &socketBuffer_ ) {
#endif
socketBuffer_.setSocket( socketFD );
#if defined (USE_SSL)
if ( nullptr != ssl )
socketBuffer_.setSSL( ssl );
else