-
Notifications
You must be signed in to change notification settings - Fork 17
/
traffic_profile_manager.cc
1723 lines (1508 loc) · 60.4 KB
/
traffic_profile_manager.cc
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-Clear
*
* Copyright (c) 2015 ARM Limited
* All rights reserved
* Created on: Sep 30, 2015
* Author: Matteo Andreozzi
*/
#include <google/protobuf/text_format.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include "proto/tp_packet.pb.h"
#include "event.hh"
#include <algorithm>
#include <stdexcept>
#include <limits>
#include <queue>
#include "traffic_profile_manager.hh"
#include "traffic_profile_master.hh"
#include "traffic_profile_checker.hh"
#include "traffic_profile_slave.hh"
#include "traffic_profile_delay.hh"
#include "utilities.hh"
using namespace google::protobuf::io;
using namespace google::protobuf;
namespace TrafficProfiles {
const Configuration::TimeUnit TrafficProfileManager::defaultTimeResolution = Configuration::PS;
const uint64_t TrafficProfileManager::defaultFrequency = 1e9;
TrafficProfileManager::TrafficProfileManager() :
initialized(false), profilesAsMasters(false),
trackerLatency(false), kronosEnabled(false),
kronosBucketsWidth(0), kronosCalendarLength(0),
kronosConfigurationValid(false),
time(0), timeResolution(defaultTimeResolution),
forwardDeclaredProfiles(0),
tracer(this), streamCacheValid(false), kronos(this) {
}
TrafficProfileManager::~TrafficProfileManager() {
for (auto& p : profiles) {
delete p;
}
}
void TrafficProfileManager::signalReset(const uint64_t pId) {
try {
nonTerminatedProfiles[profiles.at(pId)->getMasterId()]++;
} catch (out_of_range& oor){
ERROR("TrafficProfileManager::signalReset unknown profile id", pId);
}
}
TrafficProfileManager::PacketType
TrafficProfileManager::packetType (const Command cmd) {
PacketType ret = NO_TYPE;
switch(cmd) {
case Command::READ_REQ:
case Command::WRITE_REQ:
ret = REQUEST;
break;
case Command::READ_RESP:
case Command::WRITE_RESP:
ret = RESPONSE;
break;
default:
break;
}
return ret;
}
bool TrafficProfileManager::isTerminated(const string& m) {
bool terminated = true;
try {
const uint64_t mId = masterId(m);
terminated = (nonTerminatedProfiles.at(mId) == 0);
} catch (const out_of_range& oor) {
ERROR("TrafficProfileManager::isTerminated unknown master requested",
m);
}
LOG("TrafficProfileManager::isTerminated master", m,
(terminated ? "is" : "is not"), "terminated");
return terminated;
}
bool TrafficProfileManager::load(const string& fileName) {
// input stream used to acquire traffic profile specifications
ifstream stream(fileName.c_str());
bool ok = false;
if (stream.is_open()) {
LOG("TrafficProfileManager::init loading Manager object from file",
fileName);
// zero copy input stream from istream
IstreamInputStream zeroCopyStream(&stream);
// allocate google protocol buffer configuration object
Configuration c;
// Allocate a parser object
TextFormat::Parser parser;
// configure the parser to be case insensitive
parser.AllowCaseInsensitiveField(true);
// TextFormat acquires from plain text Google Protocol Buffer specifications
if (parser.Parse(&zeroCopyStream, &c)) {
// load the configuration object into the Traffic Profiles descriptors
loadConfiguration(c);
} else {
ERROR("TrafficProfileManager::load errors parsing file", fileName);
}
// close istream
stream.close();
// mark TPM as initialized
initialized = true;
// return ok
ok = true;
} else {
WARN("TrafficProfileManager::init unable to access file ", fileName);
}
return ok;
}
void TrafficProfileManager::configure(const Configuration& from) {
LOG("TrafficProfileManager::configure new Configuration object loaded in TPM");
// mark as initialized and then populate the Traffic Profile descriptors
initialized = true;
loadConfiguration(from);
}
uint64_t TrafficProfileManager::getOrGeneratePid(const string& name) {
try {
return profileMap.at(name);
} catch (const out_of_range& oor) {
// allocate a new ID to the forward declared profile
uint64_t id = profiles.size();
profileMap[name] = id;
profiles.push_back(nullptr);
LOG("TrafficProfileManager::",__func__,"forward declaration of "
"profile",name,"detected, assigning id",id);
forwardDeclaredProfiles++;
return id;
}
}
uint64_t TrafficProfileManager::profileId(const string& name) {
uint64_t ret { InvalidId<uint64_t>() };
try {
ret = profileMap.at(name);
} catch (const out_of_range& oor) {
ERROR("TrafficProfileManager::profileId",name,"does not exist");
}
return ret;
}
uint64_t TrafficProfileManager::getOrGenerateMid(const string& name) {
try {
return masterMap.at(name);
} catch (const out_of_range& oor) {
// allocate a new ID to the forward declared master
uint64_t id = masters.size();
masterMap[name] = id;
masters.push_back(name);
LOG("TrafficProfileManager::",__func__,"Master",name,
"registered with ID",id);
return id;
}
}
uint64_t TrafficProfileManager::masterId(const string& name) const {
uint64_t ret { InvalidId<uint64_t>() };
try {
ret = masterMap.at(name);
} catch (const out_of_range& oor) {
ERROR("TrafficProfileManager::",__func__,name,"does not exist");
}
return ret;
}
const string&
TrafficProfileManager::masterName(const uint64_t mId) const {
try {
return masters.at(mId);
} catch (out_of_range& oor) {
ERROR("TrafficProfileManager::masterName out-of-range master ID", mId);
return masters[mId];
}
}
const unordered_set<string>
TrafficProfileManager::getMasters() const {
unordered_set<string> ret (masters.begin(),
masters.end());
return ret;
}
const Stats TrafficProfileManager::getMasterStats(const string& m) {
Stats ret;
bool terminated = isTerminated(m);
LOG("TrafficProfileManager::getMasterStats master",m,"terminated",
terminated?"Y":"N");
ret.timeScale = toFrequency(timeResolution);
const uint64_t mId = masterId(m);
auto it = masterProfiles.find(mId);
if (it != masterProfiles.end()) {
for (auto& p : it->second) {
if (!terminated) {
profiles.at(p)->setStatsTime(time);
}
ret += profiles.at(p)->getStats();
}
} else {
ERROR("TrafficProfileManager::getMasterStats Unknown master requested",
m);
}
return ret;
}
TrafficProfileDescriptor* TrafficProfileManager::getProfile(
const uint64_t index) const {
TrafficProfileDescriptor* ret(nullptr);
try {
ret = profiles.at(index);
} catch (out_of_range& oor) {
ERROR("TrafficProfileManager::getProfile unable to find profile id",
index, "in", oor.what());
}
return ret;
}
const Stats TrafficProfileManager::getProfileStats(const string& p) {
Stats ret;
try {
const auto id = profileMap.at(p);
ret = profiles.at(id)->getStats();
} catch (out_of_range& oor) {
ERROR(
"TrafficProfileManager::getProfileStats Unknown profile requested",
p);
}
return ret;
}
uint64_t TrafficProfileManager::toFrequency(const Configuration::TimeUnit t) {
uint64_t ret = 1;
switch (t) {
case Configuration::PS:
ret = 1e+12;
break;
case Configuration::NS:
ret = 1e+9;
break;
case Configuration::US:
ret = 1e+6;
break;
case Configuration::MS:
ret = 1e+3;
break;
case Configuration::S: //intentional fall-trough
case Configuration::CYCLES: //intentional fall-trough
default:
break;
}
return ret;
}
void TrafficProfileManager::loadTaggerConfiguration(const Configuration& c) {
// configure the packet tagger with Packet ID boundaries from configuration
// file. In case TPM was already initialized, the configuration can only extend
// the existing range
if (c.has_lowid()) {
tagger.low_id =
(!initialized) ?
c.lowid() : min(tagger.low_id, c.lowid());
}
if (c.has_highid()) {
tagger.high_id =
(!initialized) ?
c.highid() : max(tagger.high_id, c.highid());
}
LOG("TrafficProfileManager::loadPacketIDConfiguration",
(initialized ? "Initialising" : "Extending"),
"packet ID boundaries to", tagger.low_id, tagger.high_id);
}
void TrafficProfileManager::loadTracerConfiguration(const Configuration& c) {
if (c.has_tracing() && c.tracing()) {
// enable tracing
tracer.enable();
if (c.has_trace_dir()) {
// set traces output directory
tracer.setOutDir(c.trace_dir());
}
LOG("TrafficProfileManager::loadTracerConfiguration tracer enabled",
(c.has_trace_dir()?"output directory "+c.trace_dir():""));
}
}
void TrafficProfileManager::enableTracer(const string& out) {
tracer.enable();
tracer.setOutDir(out);
LOG("TrafficProfileManager::enableTracer enabled "
"packet tracer with output dir",out);
}
pair<uint64_t, uint64_t> TrafficProfileManager::loadTimeConfiguration(
const Configuration& c) {
// Print ATP time resolution
LOG("TrafficProfileManager::loadTimeConfiguration ATP time resolution is set to",
Configuration::TimeUnit_Name(timeResolution));
// time scaling factor expressed as ratio (scale/period)
uint64_t scale = 1;
uint64_t period = 1;
// time factors expressed in number of units per second (frequency)
uint64_t frequencyFromConfig = 1;
// set period
uint64_t periodFromConfig = (c.has_period() ? c.period() : 1);
uint64_t currentFrequency = toFrequency(timeResolution);
// by default convert CYCLES to US if the frequency has been configured as well
if (c.timeunit() == Configuration::CYCLES) {
if (c.has_frequency()) {
// use configured time unit to
// compute the appropriate scale factor
frequencyFromConfig = c.frequency();
} else {
WARN("TrafficProfileManager::loadTimeConfiguration: CYCLES configured with no\n"
"associated frequency value. Cycle measurements will be inaccurate as\n"
"dependent on host platform configuration, ATP Engine frequency will be set\n"
"to default", defaultFrequency);
frequencyFromConfig = defaultFrequency;
}
} else {
frequencyFromConfig = toFrequency(c.timeunit());
}
if (frequencyFromConfig > currentFrequency) {
scale = frequencyFromConfig / currentFrequency;
} else {
period = currentFrequency / frequencyFromConfig;
}
// take configured period into account now
period *= periodFromConfig;
LOG("TrafficProfileManager::loadTimeConfiguration",
Configuration::TimeUnit_Name(c.timeunit()),
"configuration detected, time scale factor to",
Configuration::TimeUnit_Name(timeResolution), "is [scale]", scale,
"over [period]", period);
return pair<uint64_t, uint64_t>(scale, period);
}
pair<uint64_t, uint64_t> TrafficProfileManager::getTimeScaleFactors(
const uint64_t id) const {
pair<uint64_t, uint64_t> ret;
try {
ret = timeScaleFactor.at(id);
} catch (out_of_range& oo) {
ERROR(
"TrafficProfileManager::getTimeScaleFactor unable to find profile ID",
id);
}
return ret;
}
void TrafficProfileManager::createProfile(
const uint64_t id, const Profile& from, const uint64_t clone_num,
const uint64_t master_id) {
TrafficProfileDescriptor* temp = nullptr;
if (isValid(master_id) && master_id >= masters.size())
ERROR("TrafficProfileManager::",__func__,
"Unknown Master ID", master_id);
if (id >= profiles.size()){
ERROR("TrafficProfileManager::",__func__,
"profile descriptor ID",id,"not found");
}
bool slave = false;
// a packet descriptor means this is a master profile
if (from.has_pattern()) {
temp = new TrafficProfileMaster(this, id, &from, clone_num);
} else if (from.has_slave()) {
temp = new TrafficProfileSlave(this, id, &from, clone_num);
LOG("TrafficProfileManager::createProfile slave detected - enabling Kronos");
kronosEnabled = true;
// parsing a slave profile
slave = true;
} else if (from.has_delay()) {
temp = new TrafficProfileDelay(this, id, &from, clone_num);
} else if (from.check_size() > 0) {
temp = new TrafficProfileChecker(this, id, &from, clone_num);
//register this profile as a checker
checkers.insert(id);
// if this profile is a checker, register its checked profile.
for (int i = 0; i < from.check_size(); ++i) {
string toCheck { from.check(i) };
if (clone_num)
toCheck.append(TrafficProfileDescriptor::Name::CloneSuffix)
.append(to_string(clone_num - 1));
checkedByMap.emplace(make_pair(getOrGeneratePid(toCheck), temp));
LOG("TrafficProfileManager::createProfile registered profile",
temp->getName(), "as checker for profile", toCheck);
}
} else {
ERROR("TrafficProfileManager::createProfile "
"- unable to determine profile type");
}
if (!slave) {
const string &mName {
profilesAsMasters ? temp->getName() :
isValid(master_id) ? masterName(master_id) :
from.master_id()
};
// register masterId (string)
const uint64_t mId = getOrGenerateMid(mName);
masterProfiles[mId].insert(id);
// add the Traffic Profile to the master
temp->addToMaster(mId, mName);
// update active profiles count
nonTerminatedProfiles[mId]++;
} else {
slaves.insert(id);
}
// finally push the newly created profile
profiles[id] = temp;
}
void TrafficProfileManager::configureProfile(const Profile& from,
const pair<uint64_t, uint64_t> ts,
bool overwrite, const uint64_t clone_num, const uint64_t master_id) {
if (isValid(master_id) && master_id >= masters.size())
ERROR("TrafficProfileManager::",__func__,
"Unknown Master ID",master_id);
uint64_t id = 0;
string profName { from.name() };
if (clone_num) {
profName.append(TrafficProfileDescriptor::Name::CloneSuffix)
.append(to_string(clone_num - 1));
}
auto it = profileMap.find(profName);
// duplicated profile names are not allowed
if (it == profileMap.end()) {
// build new descriptor and insert with profile in the activeList
id = profiles.size();
// create space for a new profile descriptor
profiles.push_back(nullptr);
// register in name to id map
profileMap[profName] = id;
} else {
id = it->second;
if (profiles.at(id) == nullptr) {
// this profile name was forward-declared earlier,
// complete the creation process
LOG("TrafficProfileManager::configureProfile completed creation of "
"forward-declared profile", profName);
forwardDeclaredProfiles--;
} else if (!overwrite) {
ERROR("TrafficProfileManager::configureProfile duplicate"
" profile name detected:", profName);
} else {
LOG("TrafficProfileManager::configureProfile overwriting profile",
profName);
// deallocate previously allocated profile
delete profiles[id];
}
}
// insert the time scale factor into the map
// needed before profile creation
timeScaleFactor[id] = (ts);
// create the profile
createProfile(id, from, clone_num, master_id);
// enable TPM
initialized = true;
}
void TrafficProfileManager::loadConfiguration(const Configuration& toLoad) {
// store configuration object
config.push_back(toLoad);
// get a reference to it
auto& c = config.back();
// Configure the Time Unit and eventually the cycles to time
// conversion factor from the loaded configuration object
auto ts = loadTimeConfiguration(c);
stats.timeScale = toFrequency(timeResolution);
// Configure the packet tagger
loadTaggerConfiguration(c);
// Configure the tracer
loadTracerConfiguration(c);
// Traffic Profile Manager successfully populated
// Load Traffic Profile descriptors from data contained
// in the configuration object
for (int i = 0; i < c.profile_size(); i++) {
const Profile &from { c.profile(i) };
for (const auto &v : { from.master_id(), from.name() })
if (v.find(TrafficProfileDescriptor::Name::Reserved)
!= string::npos)
ERROR("TrafficProfileManager::",__func__,"Reserved char",
TrafficProfileDescriptor::Name::Reserved,"found in",v);
if (!from.has_name())
c.mutable_profile(i)->set_name(
TrafficProfileDescriptor::Name::Default + to_string(
TrafficProfileDescriptor::Name::AnonymousCount++));
configureProfile(from, ts);
}
// register checkers to checked profiles
for (auto c = begin(checkedByMap); c != end(checkedByMap); ++c) {
profiles.at(c->first)->registerChecker(c->second->getId());
LOG("TrafficProfileManager::loadConfiguration registered checker",
profiles.at(c->first)->getName(), "to profile",
c->second->getName());
}
// refresh the stream cache
streamCacheUpdate();
LOG("TrafficProfileManager::loadConfiguration active list initialised with",
profiles.size(), "traffic profiles", masters.size(), "masters");
}
void TrafficProfileManager::flush() {
LOG("TrafficProfileManager::flush requested", stats.dump());
// clear the configuration
config.clear();
// reset the TPM
reset();
}
void TrafficProfileManager::reset() {
LOG("TrafficProfileManager::reset requested", stats.dump());
// clear cycles to time conversion factors
timeScaleFactor.clear();
// deallocate profiles
for (auto& p : profiles) {
delete p;
}
// clear current configured Traffic Profiles
profiles.clear();
profileMap.clear();
checkers.clear();
checkedByMap.clear();
masters.clear();
masterMap.clear();
masterProfiles.clear();
masterSlaveMap.clear();
streamCache.clear();
streamLeavesCache.clear();
clonedStreams.clear();
streamCloneToOrigin.clear();
streamCacheValid = false;
nonTerminatedProfiles.clear();
activeList.clear();
waitedResponseUidMap.clear();
// reset all waited for requests
waitedRequestUidMap.clear();
// reset all waited for events
waitEventMap.clear();
// clear next transmission times
nextTimes = NextTimesPq();
// backup current configuration
auto temp = config;
// clear current configuration
config.clear();
for (auto &c : temp) {
// reload current configuration
loadConfiguration(c);
}
// reset all counters
stats.reset();
// reset time
time=0;
}
bool TrafficProfileManager::print(string& output) {
// clear passed string
output.clear();
// TextFormat prints plain text Google Protocol Buffer specifications
string temp;
for (auto& c : config) {
if (TextFormat::PrintToString(c, &temp)) {
output += temp;
} else
return false;
}
return true;
}
void TrafficProfileManager::updateCheckers(const uint64_t profile,
Packet* packet, const double delay) {
LOG("TrafficProfileManager::updateCheckers master", packet->master_id(),
"address", Utilities::toHex(packet->addr()));
// Initialise request flags
bool checkerLocked = false;
uint64_t nextCheckerTime = 0;
// select checkers for this profile
auto range = checkedByMap.equal_range(profile);
for (auto it = range.first, et = range.second; it != et; ++it) {
bool ok = false;
LOG("TrafficProfileManager::updateCheckers", "registering",
Command_Name(packet->cmd()), "to checker",
it->second->getName());
// select action based on packet command
switch (packet->cmd()) {
case Command::READ_REQ: //intentional fallthrough
case Command::WRITE_REQ:
// update checkers if available
ok = it->second->send(checkerLocked, packet, nextCheckerTime);
break;
case Command::READ_RESP: //intentional fallthrough
case Command::WRITE_RESP:
// update checker
ok = it->second->receive(nextCheckerTime, packet,
delay);
break;
default:
ERROR("TrafficProfileManager::updateCheckers unexpected"
"packet command");
}
if (!ok) {
ERROR("TrafficProfileManager::updateCheckers time", time,
"checker", it->second->getName(), "rejected",
Command_Name(packet->cmd()));
}
}
}
bool
TrafficProfileManager::send(Packet*& pkt, bool& locked,
const uint64_t pId) {
pkt = nullptr;
// reset next time hint
uint64_t next = 0;
locked = false;
bool sent = false;
if (initialized) {
// skip checkers - they do not send packets
if (!isChecker(pId)) {
// attempts to send all available packets from a traffic profile
auto& p = profiles.at(pId);
if (p->send(locked, pkt, next)) {
LOG("TrafficProfileManager::send time", time,
"got packet from profile", p->getName(),
"timestamp", pkt->time());
// update data sent statistics
stats.send(time, pkt->size());
// update checkers
updateCheckers(pId, pkt);
// signal transmission OK
sent = true;
}
if (next > time) {
LOG("TrafficProfileManager::send time ", time,
"profile", p->getName(), "next send time is",
next);
nextTimes.push(next);
}
if (locked) {
LOG("TrafficProfileManager::send time ", time,
"profile", p->getName(), "was found locked");
}
}
}
return sent;
}
void TrafficProfileManager::streamCacheUpdate() {
LOG("TrafficProfileManager::streamCacheUpdate started");
for (auto& root: activeList) {
if (profiles.at(root)->getRole()!=TrafficProfileDescriptor::SLAVE) {
// cache the stream hierarchy for this profile
getStream(root);
}
}
}
multimap<string, Packet*> TrafficProfileManager::send(bool& locked,
uint64_t& nextTransmission, const uint64_t packetTime) {
multimap<string, Packet*> ret;
// reset next time hint
nextTransmission = 0;
locked = false;
// clean next transmission times
nextTimes = NextTimesPq();
// parse all active Profiles and query them for the next packet to be transmitted
if (initialized) {
// check if all forward-declared profiles have been instantiated
if (forwardDeclaredProfiles>0) {
ERROR("TrafficProfileManager::loadConfiguration inconsistent "
"naming of waited for profiles detected. Please check the ATP configuration file.");
}
// reset the forward-declared profiles counter guard
forwardDeclaredProfiles = 0;
if (packetTime >= time) {
if (!streamCacheValid) {
// cache streams at TPM boot time
streamCacheUpdate();
streamCacheValid = true;
}
LOG("TrafficProfileManager::send request received at time",
packetTime);
// update current time
time = packetTime;
Packet * pkt = nullptr;
// next packet times
vector<uint64_t> nextPackets;
// total underruns/overruns
uint64_t underruns = 0, overruns = 0;
// handles event concurrency by repeating loop until time advances or TPM locks
// handle Kronos events if needed
if (kronos.isInitialized()) {
list<Event> events;
// get all Kronos events
kronos.get(events);
// parsing events will free ATP slaves response slots
for (auto&e : events) {
handle(e);
}
}
// cycle through the active list
for (auto it = begin(activeList); it != end(activeList); ++it) {
auto& p = profiles.at(*it);
const uint64_t& pId = p->getId();
bool profileLocked = false, sent = false;
// attempts to send all available packets from a traffic profile
do {
sent = send(pkt, profileLocked, pId);
if (sent) {
bool waitedFor = false;
double reqTime = 0.;
uint64_t destId = 0;
// trace the packet
tracer.trace(pkt);
waitedFor = getDestinationProfile(reqTime, destId, pkt);
if (waitedFor) {
if (!isValid(destId)) {
// packet to be discarded
delete pkt;
pkt = nullptr;
LOG("TrafficProfileManager::send packet "
"to invalid ID discarded");
} else {
LOG("TrafficProfileManager::send internal routing");
// 1) master going to internal slave
// 2) slave going to internal master
// if none of the above applies, emplace into ret
// store packet
bool routed = route(pkt, &pId, &destId);
if (!routed) {
LOG("TrafficProfileManager::send in internal routing"
" between",pId,"and",destId,"delayed");
}
}
} else {
ret.emplace(make_pair(p->getMasterName(), pkt));
}
}
} while (sent);
// OR locked status.
locked |= profileLocked;
// update FIFO statistics
underruns += p->getStats().underruns;
overruns += p->getStats().overruns;
}
// refresh total overruns/underruns
stats.underruns = underruns;
stats.overruns = overruns;
// compute overall nextTransmission send time
if (!nextTimes.empty()) {
nextTransmission = nextTimes.top();
}
LOG("TrafficProfileManager::send time", packetTime, "sending",
ret.size(), "packets. Underruns", underruns, "Overruns",
overruns,"next transmission time", nextTransmission);
} else {
ERROR("TrafficProfileManager::send - received event from the past:",
packetTime, "current time was", time);
}
} else {
ERROR("TrafficProfileManager::send - TPM not initialised!");
}
return ret;
}
bool TrafficProfileManager::getDestinationProfile(double& rTime,
uint64_t& dest, const Packet* pkt) const {
dest = 0;
bool found = false;
auto& wMap = (packetType(pkt->cmd())==RESPONSE ?
waitedResponseUidMap: waitedRequestUidMap);
if (wMap.count(pkt->uid()) > 0) {
tie(dest, rTime) = wMap.at(pkt->uid());
found = true;
}
// check against internal slaves
if (!found) {
found = toInternalSlave(dest,pkt);
}
return found;
}
bool TrafficProfileManager::receive(const uint64_t packetTime, Packet* packet) {
bool received = false, waitedFor = false;
if (initialized) {
if (packetTime >= time) {
double requestTime = time;
uint64_t pid = 0, next = 0;
// advance clock
time = packetTime;
waitedFor = getDestinationProfile(requestTime, pid, packet);
if (!waitedFor) {
WARN("TrafficProfileManager::receive unexpected packet "
"for master", packet->master_id(),
"UID", packet->uid(),
"address", packet->addr());
} else {
if (!isValid(pid)) {
// packet to be discarded
delete packet;
packet = nullptr;
LOG("TrafficProfileManager::receive packet "
"to invalid ID discarded");
} else {
double delay = packetTime - requestTime;
if (delay < 0) {
ERROR("TrafficProfileManager::receive response type",
Command_Name(packet->cmd()),
"detected negative request to response delay:",
delay);
}
LOG("TrafficProfileManager::receive response type",
Command_Name(packet->cmd()),
"UID",packet->uid(),
"response time",
packetTime, "request time", requestTime,
"for address",
Utilities::toHex(packet->addr()),
"request to response delay:", delay,
"destination resolved to",
profiles[pid]->getName());
if (isChecker(pid)) {
ERROR("TrafficProfileManager::receive received "
"a packet for checker profile",
profiles[pid]->getName());
}
// packet was expected - trace it
tracer.trace(packet);
if (profiles[pid]->receive(next, packet,
delay)) {
// update received packets counter and time
stats.receive(packetTime, packet->size(), delay);
received = true;
// update checkers if available
updateCheckers(pid, packet, delay);
// delete response packet here
delete packet;
} else if (kronosEnabled &&
isInternalMaster(packet->master_id())) {
// Kronos init check
if (!kronos.isInitialized()) {
initKronos();
}
// requests coming from external masters
// need to be handled in the adaptor, hence
// the following code is triggered only
// for internal masters' requests
// only slaves can reject a packet receive,
// therefore schedule a pending request event
LOG("TrafficProfileManager::receive failed, UID",
packet->uid(), "scheduling receive "
"in Kronos at", next);
// create a packet receive Kronos event
Event receive(Event::PACKET_REQUEST_RETRY, Event::TRIGGERED,
packet->uid(), next);
// store packet
buffer[packet->uid()] = packet;
kronos.schedule(receive);
}
if (next >= time) {
LOG("TrafficProfileManager::receive time ", time, "profile",
profiles.at(pid)->getName(), "next receive time is",
next);
nextTimes.push(next);
}
}
}
} else {
ERROR(
"TrafficProfileManager::receive - received event from the past:",
packetTime, "current time was", time);
}
} else {
ERROR("TrafficProfileManager::receive TPM is uninitialized");
}
return received;
}
void TrafficProfileManager::subscribe(const uint64_t profile, const Event& ev) {
if (ev.action == Event::TRIGGERED) {
ERROR(
"TrafficProfileManager::subscribe attempted subscription to a trigger",
ev);
}
// special handling for ACTIVATION events: if a profile is explicitly waiting to be activated
// it will be placed in the activeList to enable reporting the profile is locked
if (ev.type == Event::ACTIVATION) {
activeList.push_back(profile);
}
// add the profile id to the set of profiles waiting for event <ev>
LOG("TrafficProfileManager::subscribe event", ev, "profile", profile);
waitEventMap[ev.id][ev].insert(profile);
}
void TrafficProfileManager::event(const Event& ev) {
if (ev.action == Event::AWAITED) {
ERROR("TrafficProfileManager::event "
"attempted trigger of a subscription event", ev);
}
// // special handling in case of ACTIVATION events
if (ev.type==Event::ACTIVATION) {
activeList.push_back(ev.id);
LOG("TrafficProfileManager::event profile id",ev.id,
"added to active list");
}
// special handling in case of TERMINATION events
if (ev.type == Event::TERMINATION) {
const string mName = profiles.at(ev.id)->getMasterName();
const uint64_t mId = profiles.at(ev.id)->getMasterId();
if (0 == nonTerminatedProfiles[mId]--) {
ERROR("TrafficProfileManager::event duplicated termination event"