-
Notifications
You must be signed in to change notification settings - Fork 481
/
Copy pathpcm-sensor-server.cpp
4084 lines (3707 loc) · 165 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
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2016-2022, Intel Corporation
// Use port allocated for PCM in prometheus:
// https://github.com/prometheus/prometheus/wiki/Default-port-allocations
constexpr unsigned int DEFAULT_HTTP_PORT = 9738;
#if defined (USE_SSL)
constexpr unsigned int DEFAULT_HTTPS_PORT = DEFAULT_HTTP_PORT;
#endif
#include "pcm-accel-common.h"
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include<string>
#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 &) = delete;
~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::fill(timeBuffer, timeBuffer + 64, 0);
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::fill(timeBuffer, timeBuffer + 64, 0);
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;
}
/* Not used right now
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];
std::fill(buf, buf + 2049, 0);
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;
sigemptyset(&sa.sa_mask);
sa.sa_handler = SIG_IGN;
sa.sa_flags = 0;
sigaction( signum, &sa, 0 );
}
void installHandler( void (*handler)(int), int signum ) {
struct sigaction sa;
sigemptyset(&sa.sa_mask);
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* cu) override {
printCounter( "Object", "ClientUncore" );
SocketCounterState before = getSocketCounter( aggPair_.first, cu->socketID() );
SocketCounterState after = getSocketCounter( aggPair_.second, cu->socketID() );
printUncoreCounterState( before, after );
}
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 );
// For backward compatibility we use socketUniqueCoreID to create a unique number inside the socket for a core
// and introduce HW Core ID as the physical core id inside a module, keep in mind this core id is not unique inside a socket
printCounter( "Core ID", c->socketUniqueCoreID() );
printCounter( "HW Core ID", c->coreID() );
printCounter( "Module ID", c->moduleID() );
printCounter( "Tile ID", c->tileID() );
printCounter( "Die ID", c->dieID() );
printCounter( "Die Group ID", c->dieGroupID() );
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 );
PCM * pcm = PCM::getInstance();
if (pcm->getAccel()!=ACCEL_NOCONFIG){
startObject ("Accelerators",BEGIN_OBJECT);
printAccelCounterState(before,after);
endObject( JSONPrinter::LineEndAction::DelimiterAndNewLine, END_OBJECT );
}
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 ) );
printCounter( "Core Frequency", getActiveAverageFrequency ( before, after ) );
printCounter( "Frontend Bound", int(100. * getFrontendBound(before, after)) );
printCounter( "Bad Speculation", int(100. * getBadSpeculation(before, after)) );
printCounter( "Backend Bound", int(100. * getBackendBound(before, after)) );
printCounter( "Retiring", int(100. * getRetiring(before, after)) );
printCounter( "Fetch Latency Bound", int(100. * getFetchLatencyBound(before, after)) );
printCounter( "Fetch Bandwidth Bound", int(100. * getFetchBandwidthBound(before, after)) );
printCounter( "Branch Misprediction Bound", int(100. * getBranchMispredictionBound(before, after)) );
printCounter( "Machine Clears Bound", int(100. * getMachineClearsBound(before, after)) );
printCounter( "Memory Bound", int(100. * getMemoryBound(before, after)) );
printCounter( "Core Bound", int(100. * getCoreBound(before, after)) );
printCounter( "Heavy Operations Bound", int(100. * getHeavyOperationsBound(before, after)) );
printCounter( "Light Operations Bound", int(100. * getLightOperationsBound(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 );
PCM* pcm = PCM::getInstance();
printCounter( "DRAM Writes", getBytesWrittenToMC ( before, after ) );
printCounter( "DRAM Reads", getBytesReadFromMC ( before, after ) );
if(pcm->nearMemoryMetricsAvailable()){
printCounter( "NM HitRate", getNMHitRate ( before, after ) );
printCounter( "NM Hits", getNMHits ( before, after ) );
printCounter( "NM Misses", getNMMisses ( before, after ) );
printCounter( "NM Miss Bw", getNMMissBW ( 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 IA Requests", getIARequestBytesFromMC( before, after ) );
printCounter( "Memory Controller GT Requests", getGTRequestBytesFromMC( before, after ) );
printCounter( "Memory Controller IO Requests", getIORequestBytesFromMC( before, after ) );
printCounter( "Package Joules Consumed", getConsumedJoules ( before, after ) );
printCounter( "PP0 Joules Consumed", getConsumedJoules ( 0, before, after ) );
printCounter( "PP1 Joules Consumed", getConsumedJoules ( 1, before, after ) );
printCounter( "DRAM Joules Consumed", getDRAMConsumedJoules ( before, after ) );
auto uncoreFrequencies = getUncoreFrequencies( before, after );
for (size_t i = 0; i < uncoreFrequencies.size(); ++i)
{
printCounter( std::string("Uncore Frequency Die ") + std::to_string(i), uncoreFrequencies[i]);
}
const auto localRatio = int(100.* getLocalMemoryRequestRatio(before, after));
printCounter( "Local Memory Request Ratio", int(100.* getLocalMemoryRequestRatio(before, after)) );
printCounter( "Remote Memory Request Ratio", 100 - localRatio);
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 printAccelCounterState( SystemCounterState const& before, SystemCounterState const& after ) {
AcceleratorCounterState* accs_ = AcceleratorCounterState::getInstance();
uint32 devs = accs_->getNumOfAccelDevs();
for ( uint32 i=0; i < devs; ++i ) {
startObject( std::string( accs_->getAccelCounterName() + " Counters Device " ) + std::to_string( i ), BEGIN_OBJECT );
for(int j=0;j<accs_->getNumberOfCounters();j++){
printCounter( accs_->getAccelIndexCounterName(j), accs_->getAccelIndexCounter(i, before, after,j) );
}
// debug prints
//for(uint32 j=0;j<accs_->getNumberOfCounters();j++){
// std::cout<<accs_->getAccelIndexCounterName(j) << " "<<accs_->getAccelIndexCounter(i, before, after,j)<<std::endl;
// }
// std::cout <<i << " Influxdb "<<accs_->getAccelIndexCounterName()<< accs_->getAccelInboundBW (i, before, after ) << " "<< accs_->getAccelOutboundBW (i, before, after ) << " "<<accs_->getAccelShareWQ_ReqNb (i, before, after ) << " "<<accs_->getAccelDedicateWQ_ReqNb (i, before, after ) << std::endl;
endObject( JSONPrinter::DelimiterAndNewLine, 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 );
printCounter( std::string( "CXL Write Cache" ), getCXLWriteCacheBytes (i, before, after ) );
printCounter( std::string( "CXL Write Mem" ), getCXLWriteMemBytes (i, before, after ) );
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* cu) override {
printComment( std::string( "Uncore Counters Socket " ) + std::to_string( cu->socketID() ) );
SocketCounterState before = getSocketCounter( aggPair_.first, cu->socketID() );
SocketCounterState after = getSocketCounter( aggPair_.second, cu->socketID() );
printUncoreCounterState( before, after );
}
virtual void dispatch( Core* c ) override {
addToHierarchy( std::string( "core=\"" ) + std::to_string( c->socketUniqueCoreID() ) + "\"" );
auto vec = c->threads();
iterateVectorAndCallAccept( vec );
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->getAccel()!=ACCEL_NOCONFIG){
printComment( "Accelerator Counters" );
printAccelCounterState(before,after);
}
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 ) );
#if 0
// disabling this metric for a moment due to https://github.com/intel/pcm/issues/789
printCounter( "Core Frequency", getActiveAverageFrequency ( before, after ) );
#endif
//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 ) {
PCM* pcm = PCM::getInstance();
addToHierarchy( "source=\"uncore\"" );
printCounter( "DRAM Writes", getBytesWrittenToMC ( before, after ) );
printCounter( "DRAM Reads", getBytesReadFromMC ( before, after ) );
if(pcm->nearMemoryMetricsAvailable()){
printCounter( "NM Hits", getNMHits ( before, after ) );
printCounter( "NM Misses", getNMMisses ( before, after ) );
printCounter( "NM Miss Bw", getNMMissBW ( before, after ) );
printCounter( "NM HitRate", getNMHitRate ( 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 IA Requests", getIARequestBytesFromMC( before, after ) );
printCounter( "Memory Controller GT Requests", getGTRequestBytesFromMC( before, after ) );
printCounter( "Memory Controller IO Requests", getIORequestBytesFromMC( before, after ) );
printCounter( "Package Joules Consumed", getConsumedJoules ( before, after ) );
printCounter( "PP0 Joules Consumed", getConsumedJoules ( 0, before, after ) );
printCounter( "PP1 Joules Consumed", getConsumedJoules ( 1, before, after ) );
printCounter( "DRAM Joules Consumed", getDRAMConsumedJoules ( before, after ) );
#if 0
// disabling these metrics for a moment due to https://github.com/intel/pcm/issues/789
auto uncoreFrequencies = getUncoreFrequencies( before, after );
for (size_t i = 0; i < uncoreFrequencies.size(); ++i)
{
printCounter( std::string("Uncore Frequency Die ") + std::to_string(i), uncoreFrequencies[i]);
}
#endif
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 printAccelCounterState( SystemCounterState const& before, SystemCounterState const& after )
{
addToHierarchy( "source=\"accel\"" );
AcceleratorCounterState* accs_ = AcceleratorCounterState::getInstance();
uint32 devs = accs_->getNumOfAccelDevs();
for ( uint32 i=0; i < devs; ++i )
{
addToHierarchy( std::string( accs_->getAccelCounterName() + "device=\"" ) + std::to_string( i ) + "\"" );
for(int j=0;j<accs_->getNumberOfCounters();j++)
{
printCounter( accs_->remove_string_inside_use(accs_->getAccelIndexCounterName(j)), accs_->getAccelIndexCounter(i, before, after,j) );
}
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 ) + "\"" );
printCounter( std::string( "CXL Write Cache" ), getCXLWriteCacheBytes (i, before, after ) );
printCounter( std::string( "CXL Write Mem" ), getCXLWriteMemBytes (i, before, after ) );
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 );
}
};
#if defined (USE_SSL)
void closeSSLConnectionAndFD( int fd, SSL* ssl ) {
int ret;
if ( (ret = SSL_shutdown( ssl )) == 0 ) {
DBG( 3, "first shutdown returned: ", ret );
// Call it again when it returns 0, it has sent the notification but not received it back yet
if ( (ret = SSL_shutdown( ssl )) != 1 )
// Big trouble but we did all we could.
DBG( 3, "Could not shutdown the SSL connection the second time... ret: ", ret );
}
ERR_clear_error();
SSL_free( ssl ); // Free the SSL structure to prevent memory leaks
// cppcheck-suppress uselessAssignmentPtrArg
ssl = nullptr;
DBG( 3, "close fd" );
::close( fd );
}
#endif
template <std::size_t SIZE = 256, class CharT = char, class Traits = std::char_traits<CharT>>
class basic_socketbuf : public std::basic_streambuf<CharT> {
public:
basic_socketbuf(const basic_socketbuf&) = delete;
basic_socketbuf & operator = (const basic_socketbuf&) = delete;
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( std::string dbg_ = std::string("Server: ") ): socketFD_(0), dbg(dbg_) {
// 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)
// I guess one could say that the instantiation of the ptr in this object will always be 0, i just want this to be explicit for now
// cppcheck-suppress uselessAssignmentPtrArg
ssl_ = nullptr;
#endif
}
virtual ~basic_socketbuf() {
close();
DBG( 3, dbg, "socketbuf destructor finished" );
}
int socket() {
return socketFD_;
}
void setSocket( int socketFD ) {
socketFD_ = socketFD;
if( 0 == socketFD ) // avoid work with 0 socket after closure socket and set value to 0
return;
// When receiving the socket descriptor, set the timeout
const auto res = setsockopt( socketFD_, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout_, sizeof(struct timeval) );
if (res != 0)
{
std::cerr << "setsockopt failed while setting timeout value, " << strerror( errno ) << "\n";
}
}
void setTimeout( struct timeval t ) {
timeout_ = t;
const auto res = setsockopt( socketFD_, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout_, sizeof(struct timeval) );
if (res != 0)
{
std::cerr << "setsockopt failed while setting timeout value, " << strerror( errno ) << "\n";
}
}
#if defined (USE_SSL)
SSL* ssl() {
return ssl_;
}
void setSSL( SSL* ssl ) {
if ( nullptr != ssl_ )
throw std::runtime_error( "BUG: You can set the SSL pointer only once" );
if ( nullptr == ssl )
throw std::runtime_error( "BUG: Trying to set a nullptr as ssl" );
ssl_ = ssl;
}
#endif
void close() {
basic_socketbuf::sync();
#if defined (USE_SSL)
if ( nullptr != ssl_ ) {
SSL_shutdown( ssl_ );
ERR_clear_error();
SSL_free( ssl_ );
ssl_ = nullptr;
}
#endif
if ( 0 != socketFD_ ) {
DBG( 3, dbg, "close clientsocketFD" );
::close( socketFD_ );
}
}
protected:
int_type writeToSocket() {
size_t bytesToSend;
ssize_t bytesSent;
bytesToSend = (char*)Base::pptr() - (char*)Base::pbase();
DBG( 3, dbg, "wts: Bytes to send: ", bytesToSend );
#if defined (USE_SSL)
if ( nullptr == ssl_ ) {
#endif