-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
EventProcessor.cc
2496 lines (2222 loc) · 111 KB
/
EventProcessor.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
#include "FWCore/Framework/interface/EventProcessor.h"
#include "DataFormats/Provenance/interface/BranchIDListHelper.h"
#include "DataFormats/Provenance/interface/ModuleDescription.h"
#include "DataFormats/Provenance/interface/ParameterSetID.h"
#include "DataFormats/Provenance/interface/ParentageRegistry.h"
#include "DataFormats/Provenance/interface/ProcessHistoryRegistry.h"
#include "DataFormats/Provenance/interface/SubProcessParentageHelper.h"
#include "FWCore/Common/interface/ProcessBlockHelper.h"
#include "FWCore/Framework/src/CommonParams.h"
#include "FWCore/Framework/interface/EDLooperBase.h"
#include "FWCore/Framework/interface/EventPrincipal.h"
#include "FWCore/Framework/interface/EventSetupProvider.h"
#include "FWCore/Framework/interface/EventSetupRecord.h"
#include "FWCore/Framework/interface/FileBlock.h"
#include "FWCore/Framework/interface/HistoryAppender.h"
#include "FWCore/Framework/interface/InputSourceDescription.h"
#include "FWCore/Framework/interface/IOVSyncValue.h"
#include "FWCore/Framework/interface/LooperFactory.h"
#include "FWCore/Framework/interface/LuminosityBlock.h"
#include "FWCore/Framework/interface/LuminosityBlockPrincipal.h"
#include "FWCore/Framework/interface/MergeableRunProductMetadata.h"
#include "FWCore/Framework/interface/ModuleChanger.h"
#include "FWCore/Framework/interface/makeModuleTypeResolverMaker.h"
#include "FWCore/Framework/interface/OccurrenceTraits.h"
#include "FWCore/Framework/interface/ProcessBlockPrincipal.h"
#include "FWCore/Framework/interface/ProcessingController.h"
#include "FWCore/Framework/interface/RunPrincipal.h"
#include "FWCore/Framework/interface/Schedule.h"
#include "FWCore/Framework/interface/ScheduleInfo.h"
#include "FWCore/Framework/interface/ScheduleItems.h"
#include "FWCore/Framework/interface/SubProcess.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/ESRecordsToProductResolverIndices.h"
#include "FWCore/Framework/src/Breakpoints.h"
#include "FWCore/Framework/interface/EventSetupsController.h"
#include "FWCore/Framework/interface/maker/InputSourceFactory.h"
#include "FWCore/Framework/interface/SharedResourcesRegistry.h"
#include "FWCore/Framework/interface/streamTransitionAsync.h"
#include "FWCore/Framework/interface/TransitionInfoTypes.h"
#include "FWCore/Framework/interface/ensureAvailableAccelerators.h"
#include "FWCore/Framework/interface/globalTransitionAsync.h"
#include "FWCore/Framework/interface/TriggerNamesService.h"
#include "FWCore/Framework/src/SendSourceTerminationSignalIfException.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h"
#include "FWCore/ParameterSet/interface/IllegalParameters.h"
#include "FWCore/ParameterSet/interface/ParameterSetDescriptionFillerBase.h"
#include "FWCore/ParameterSet/interface/ParameterSetDescriptionFillerPluginFactory.h"
#include "FWCore/ParameterSet/interface/ProcessDesc.h"
#include "FWCore/ParameterSet/interface/Registry.h"
#include "FWCore/ParameterSet/interface/validateTopLevelParameterSets.h"
#include "FWCore/ServiceRegistry/interface/ServiceRegistry.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "FWCore/ServiceRegistry/interface/StreamContext.h"
#include "FWCore/ServiceRegistry/interface/SystemBounds.h"
#include "FWCore/Concurrency/interface/WaitingTask.h"
#include "FWCore/Concurrency/interface/FinalWaitingTask.h"
#include "FWCore/Concurrency/interface/WaitingTaskHolder.h"
#include "FWCore/Concurrency/interface/chain_first.h"
#include "FWCore/Utilities/interface/Algorithms.h"
#include "FWCore/Utilities/interface/DebugMacros.h"
#include "FWCore/Utilities/interface/EDMException.h"
#include "FWCore/Utilities/interface/Exception.h"
#include "FWCore/Utilities/interface/ConvertException.h"
#include "FWCore/Utilities/interface/RandomNumberGenerator.h"
#include "FWCore/Utilities/interface/UnixSignalHandlers.h"
#include "FWCore/Utilities/interface/ExceptionCollector.h"
#include "FWCore/Utilities/interface/StreamID.h"
#include "FWCore/Utilities/interface/RootHandlers.h"
#include "FWCore/Utilities/interface/propagate_const.h"
#include "FWCore/Utilities/interface/thread_safety_macros.h"
#include "MessageForSource.h"
#include "MessageForParent.h"
#include "LuminosityBlockProcessingStatus.h"
#include "RunProcessingStatus.h"
#include "boost/range/adaptor/reversed.hpp"
#include <cassert>
#include <exception>
#include <iomanip>
#include <iostream>
#include <utility>
#include <sstream>
#include <sys/ipc.h>
#include <sys/msg.h>
#include "oneapi/tbb/task.h"
//Used for CPU affinity
#ifndef __APPLE__
#include <sched.h>
#endif
namespace {
class PauseQueueSentry {
public:
PauseQueueSentry(edm::SerialTaskQueue& queue) : queue_(queue) { queue_.pause(); }
~PauseQueueSentry() { queue_.resume(); }
private:
edm::SerialTaskQueue& queue_;
};
} // namespace
namespace edm {
namespace chain = waiting_task::chain;
// ---------------------------------------------------------------
std::unique_ptr<InputSource> makeInput(unsigned int moduleIndex,
ParameterSet& params,
CommonParams const& common,
std::shared_ptr<ProductRegistry> preg,
std::shared_ptr<BranchIDListHelper> branchIDListHelper,
std::shared_ptr<ProcessBlockHelper> const& processBlockHelper,
std::shared_ptr<ThinnedAssociationsHelper> thinnedAssociationsHelper,
std::shared_ptr<ActivityRegistry> areg,
std::shared_ptr<ProcessConfiguration const> processConfiguration,
PreallocationConfiguration const& allocations) {
ParameterSet* main_input = params.getPSetForUpdate("@main_input");
if (main_input == nullptr) {
throw Exception(errors::Configuration)
<< "There must be exactly one source in the configuration.\n"
<< "It is missing (or there are sufficient syntax errors such that it is not recognized as the source)\n";
}
std::string modtype(main_input->getParameter<std::string>("@module_type"));
std::unique_ptr<ParameterSetDescriptionFillerBase> filler(
ParameterSetDescriptionFillerPluginFactory::get()->create(modtype));
ConfigurationDescriptions descriptions(filler->baseType(), modtype);
filler->fill(descriptions);
try {
convertException::wrap([&]() { descriptions.validate(*main_input, std::string("source")); });
} catch (cms::Exception& iException) {
std::ostringstream ost;
ost << "Validating configuration of input source of type " << modtype;
iException.addContext(ost.str());
throw;
}
main_input->registerIt();
// Fill in "ModuleDescription", in case the input source produces
// any EDProducts, which would be registered in the ProductRegistry.
// Also fill in the process history item for this process.
// There is no module label for the unnamed input source, so
// just use "source".
// Only the tracked parameters belong in the process configuration.
ModuleDescription md(main_input->id(),
main_input->getParameter<std::string>("@module_type"),
"source",
processConfiguration.get(),
moduleIndex);
InputSourceDescription isdesc(md,
preg,
branchIDListHelper,
processBlockHelper,
thinnedAssociationsHelper,
areg,
common.maxEventsInput_,
common.maxLumisInput_,
common.maxSecondsUntilRampdown_,
allocations);
areg->preSourceConstructionSignal_(md);
std::unique_ptr<InputSource> input;
try {
//even if we have an exception, send the signal
std::shared_ptr<int> sentry(nullptr, [areg, &md](void*) { areg->postSourceConstructionSignal_(md); });
convertException::wrap([&]() {
input = std::unique_ptr<InputSource>(InputSourceFactory::get()->makeInputSource(*main_input, isdesc).release());
input->preEventReadFromSourceSignal_.connect(std::cref(areg->preEventReadFromSourceSignal_));
input->postEventReadFromSourceSignal_.connect(std::cref(areg->postEventReadFromSourceSignal_));
});
} catch (cms::Exception& iException) {
std::ostringstream ost;
ost << "Constructing input source of type " << modtype;
iException.addContext(ost.str());
throw;
}
return input;
}
// ---------------------------------------------------------------
std::shared_ptr<EDLooperBase> fillLooper(eventsetup::EventSetupsController& esController,
eventsetup::EventSetupProvider& cp,
ParameterSet& params,
std::vector<std::string> const& loopers) {
std::shared_ptr<EDLooperBase> vLooper;
assert(1 == loopers.size());
for (auto const& looperName : loopers) {
ParameterSet* providerPSet = params.getPSetForUpdate(looperName);
// Unlikely we would ever need the ModuleTypeResolver in Looper
vLooper = eventsetup::LooperFactory::get()->addTo(esController, cp, *providerPSet, nullptr);
}
return vLooper;
}
// ---------------------------------------------------------------
EventProcessor::EventProcessor(std::unique_ptr<ParameterSet> parameterSet, //std::string const& config,
ServiceToken const& iToken,
serviceregistry::ServiceLegacy iLegacy,
std::vector<std::string> const& defaultServices,
std::vector<std::string> const& forcedServices)
: actReg_(),
preg_(),
branchIDListHelper_(),
serviceToken_(),
input_(),
moduleTypeResolverMaker_(makeModuleTypeResolverMaker(*parameterSet)),
espController_(std::make_unique<eventsetup::EventSetupsController>(moduleTypeResolverMaker_.get())),
esp_(),
act_table_(),
processConfiguration_(),
schedule_(),
subProcesses_(),
historyAppender_(new HistoryAppender),
fb_(),
looper_(),
deferredExceptionPtrIsSet_(false),
sourceResourcesAcquirer_(SharedResourcesRegistry::instance()->createAcquirerForSourceDelayedReader().first),
sourceMutex_(SharedResourcesRegistry::instance()->createAcquirerForSourceDelayedReader().second),
principalCache_(),
beginJobCalled_(false),
shouldWeStop_(false),
fileModeNoMerge_(false),
exceptionMessageFiles_(),
exceptionMessageRuns_(false),
exceptionMessageLumis_(false),
forceLooperToEnd_(false),
looperBeginJobRun_(false),
forceESCacheClearOnNewRun_(false),
eventSetupDataToExcludeFromPrefetching_() {
auto processDesc = std::make_shared<ProcessDesc>(std::move(parameterSet));
processDesc->addServices(defaultServices, forcedServices);
init(processDesc, iToken, iLegacy);
}
EventProcessor::EventProcessor(std::unique_ptr<ParameterSet> parameterSet, //std::string const& config,
std::vector<std::string> const& defaultServices,
std::vector<std::string> const& forcedServices)
: actReg_(),
preg_(),
branchIDListHelper_(),
serviceToken_(),
input_(),
moduleTypeResolverMaker_(makeModuleTypeResolverMaker(*parameterSet)),
espController_(std::make_unique<eventsetup::EventSetupsController>(moduleTypeResolverMaker_.get())),
esp_(),
act_table_(),
processConfiguration_(),
schedule_(),
subProcesses_(),
historyAppender_(new HistoryAppender),
fb_(),
looper_(),
deferredExceptionPtrIsSet_(false),
sourceResourcesAcquirer_(SharedResourcesRegistry::instance()->createAcquirerForSourceDelayedReader().first),
sourceMutex_(SharedResourcesRegistry::instance()->createAcquirerForSourceDelayedReader().second),
principalCache_(),
beginJobCalled_(false),
shouldWeStop_(false),
fileModeNoMerge_(false),
exceptionMessageFiles_(),
exceptionMessageRuns_(false),
exceptionMessageLumis_(false),
forceLooperToEnd_(false),
looperBeginJobRun_(false),
forceESCacheClearOnNewRun_(false),
eventSetupDataToExcludeFromPrefetching_() {
auto processDesc = std::make_shared<ProcessDesc>(std::move(parameterSet));
processDesc->addServices(defaultServices, forcedServices);
init(processDesc, ServiceToken(), serviceregistry::kOverlapIsError);
}
EventProcessor::EventProcessor(std::shared_ptr<ProcessDesc> processDesc,
ServiceToken const& token,
serviceregistry::ServiceLegacy legacy)
: actReg_(),
preg_(),
branchIDListHelper_(),
serviceToken_(),
input_(),
moduleTypeResolverMaker_(makeModuleTypeResolverMaker(*processDesc->getProcessPSet())),
espController_(std::make_unique<eventsetup::EventSetupsController>(moduleTypeResolverMaker_.get())),
esp_(),
act_table_(),
processConfiguration_(),
schedule_(),
subProcesses_(),
historyAppender_(new HistoryAppender),
fb_(),
looper_(),
deferredExceptionPtrIsSet_(false),
sourceResourcesAcquirer_(SharedResourcesRegistry::instance()->createAcquirerForSourceDelayedReader().first),
sourceMutex_(SharedResourcesRegistry::instance()->createAcquirerForSourceDelayedReader().second),
principalCache_(),
beginJobCalled_(false),
shouldWeStop_(false),
fileModeNoMerge_(false),
exceptionMessageFiles_(),
exceptionMessageRuns_(false),
exceptionMessageLumis_(false),
forceLooperToEnd_(false),
looperBeginJobRun_(false),
forceESCacheClearOnNewRun_(false),
eventSetupDataToExcludeFromPrefetching_() {
init(processDesc, token, legacy);
}
void EventProcessor::init(std::shared_ptr<ProcessDesc>& processDesc,
ServiceToken const& iToken,
serviceregistry::ServiceLegacy iLegacy) {
//std::cerr << processDesc->dump() << std::endl;
// register the empty parentage vector , once and for all
ParentageRegistry::instance()->insertMapped(Parentage());
// register the empty parameter set, once and for all.
ParameterSet().registerIt();
std::shared_ptr<ParameterSet> parameterSet = processDesc->getProcessPSet();
// If there are subprocesses, pop the subprocess parameter sets out of the process parameter set
auto subProcessVParameterSet = popSubProcessVParameterSet(*parameterSet);
bool const hasSubProcesses = !subProcessVParameterSet.empty();
// Validates the parameters in the 'options', 'maxEvents', 'maxLuminosityBlocks',
// and 'maxSecondsUntilRampdown' top level parameter sets. Default values are also
// set in here if the parameters were not explicitly set.
validateTopLevelParameterSets(parameterSet.get());
// Now set some parameters specific to the main process.
ParameterSet const& optionsPset(parameterSet->getUntrackedParameterSet("options"));
auto const& fileMode = optionsPset.getUntrackedParameter<std::string>("fileMode");
if (fileMode != "NOMERGE" and fileMode != "FULLMERGE") {
throw Exception(errors::Configuration, "Illegal fileMode parameter value: ")
<< fileMode << ".\n"
<< "Legal values are 'NOMERGE' and 'FULLMERGE'.\n";
} else {
fileModeNoMerge_ = (fileMode == "NOMERGE");
}
forceESCacheClearOnNewRun_ = optionsPset.getUntrackedParameter<bool>("forceEventSetupCacheClearOnNewRun");
ensureAvailableAccelerators(*parameterSet);
//threading
unsigned int nThreads = optionsPset.getUntrackedParameter<unsigned int>("numberOfThreads");
// Even if numberOfThreads was set to zero in the Python configuration, the code
// in cmsRun.cpp should have reset it to something else.
assert(nThreads != 0);
unsigned int nStreams = optionsPset.getUntrackedParameter<unsigned int>("numberOfStreams");
if (nStreams == 0) {
nStreams = nThreads;
}
unsigned int nConcurrentLumis =
optionsPset.getUntrackedParameter<unsigned int>("numberOfConcurrentLuminosityBlocks");
if (nConcurrentLumis == 0) {
nConcurrentLumis = 2;
}
if (nConcurrentLumis > nStreams) {
nConcurrentLumis = nStreams;
}
unsigned int nConcurrentRuns = optionsPset.getUntrackedParameter<unsigned int>("numberOfConcurrentRuns");
if (nConcurrentRuns == 0 || nConcurrentRuns > nConcurrentLumis) {
nConcurrentRuns = nConcurrentLumis;
}
std::vector<std::string> loopers = parameterSet->getParameter<std::vector<std::string>>("@all_loopers");
if (!loopers.empty()) {
//For now loopers make us run only 1 transition at a time
if (nStreams != 1 || nConcurrentLumis != 1 || nConcurrentRuns != 1) {
edm::LogWarning("ThreadStreamSetup") << "There is a looper, so the number of streams, the number "
"of concurrent runs, and the number of concurrent lumis "
"are all being reset to 1. Loopers cannot currently support "
"values greater than 1.";
nStreams = 1;
nConcurrentLumis = 1;
nConcurrentRuns = 1;
}
}
bool dumpOptions = optionsPset.getUntrackedParameter<bool>("dumpOptions");
if (dumpOptions) {
dumpOptionsToLogFile(nThreads, nStreams, nConcurrentLumis, nConcurrentRuns);
} else {
if (nThreads > 1 or nStreams > 1) {
edm::LogInfo("ThreadStreamSetup") << "setting # threads " << nThreads << "\nsetting # streams " << nStreams;
}
}
// The number of concurrent IOVs is configured individually for each record in
// the class NumberOfConcurrentIOVs to values less than or equal to this.
// This maximum simplifies to being equal nConcurrentLumis if nConcurrentRuns is 1.
// Considering endRun, beginRun, and beginLumi we might need 3 concurrent IOVs per
// concurrent run past the first in use cases where IOVs change within a run.
unsigned int maxConcurrentIOVs =
3 * nConcurrentRuns - 2 + ((nConcurrentLumis > nConcurrentRuns) ? (nConcurrentLumis - nConcurrentRuns) : 0);
IllegalParameters::setThrowAnException(optionsPset.getUntrackedParameter<bool>("throwIfIllegalParameter"));
printDependencies_ = optionsPset.getUntrackedParameter<bool>("printDependencies");
deleteNonConsumedUnscheduledModules_ =
optionsPset.getUntrackedParameter<bool>("deleteNonConsumedUnscheduledModules");
//for now, if have a subProcess, don't allow early delete
// In the future we should use the SubProcess's 'keep list' to decide what can be kept
if (not hasSubProcesses) {
branchesToDeleteEarly_ = optionsPset.getUntrackedParameter<std::vector<std::string>>("canDeleteEarly");
}
if (not branchesToDeleteEarly_.empty()) {
auto referencePSets =
optionsPset.getUntrackedParameter<std::vector<edm::ParameterSet>>("holdsReferencesToDeleteEarly");
for (auto const& pset : referencePSets) {
auto product = pset.getParameter<std::string>("product");
auto references = pset.getParameter<std::vector<std::string>>("references");
for (auto const& ref : references) {
referencesToBranches_.emplace(product, ref);
}
}
modulesToIgnoreForDeleteEarly_ =
optionsPset.getUntrackedParameter<std::vector<std::string>>("modulesToIgnoreForDeleteEarly");
}
// Now do general initialization
ScheduleItems items;
//initialize the services
auto& serviceSets = processDesc->getServicesPSets();
ServiceToken token = items.initServices(serviceSets, *parameterSet, iToken, iLegacy, true);
serviceToken_ = items.addCPRandTNS(*parameterSet, token);
//make the services available
ServiceRegistry::Operate operate(serviceToken_);
CMS_SA_ALLOW try {
if (nThreads > 1) {
edm::Service<RootHandlers> handler;
handler->willBeUsingThreads();
}
// intialize miscellaneous items
std::shared_ptr<CommonParams> common(items.initMisc(*parameterSet));
// intialize the event setup provider
ParameterSet const& eventSetupPset(optionsPset.getUntrackedParameterSet("eventSetup"));
esp_ = espController_->makeProvider(
*parameterSet, items.actReg_.get(), &eventSetupPset, maxConcurrentIOVs, dumpOptions);
// initialize the looper, if any
if (!loopers.empty()) {
looper_ = fillLooper(*espController_, *esp_, *parameterSet, loopers);
looper_->setActionTable(items.act_table_.get());
looper_->attachTo(*items.actReg_);
// in presence of looper do not delete modules
deleteNonConsumedUnscheduledModules_ = false;
}
preallocations_ = PreallocationConfiguration{nThreads, nStreams, nConcurrentLumis, nConcurrentRuns};
runQueue_ = std::make_unique<LimitedTaskQueue>(nConcurrentRuns);
lumiQueue_ = std::make_unique<LimitedTaskQueue>(nConcurrentLumis);
streamQueues_.resize(nStreams);
streamRunStatus_.resize(nStreams);
streamLumiStatus_.resize(nStreams);
processBlockHelper_ = std::make_shared<ProcessBlockHelper>();
{
std::optional<ScheduleItems::MadeModules> madeModules;
//setup input and modules concurrently
tbb::task_group group;
// initialize the input source
auto tempReg = std::make_shared<ProductRegistry>();
auto sourceID = ModuleDescription::getUniqueID();
group.run([&, this]() {
// initialize the Schedule
ServiceRegistry::Operate operate(serviceToken_);
auto const& tns = ServiceRegistry::instance().get<service::TriggerNamesService>();
madeModules =
items.initModules(*parameterSet, tns, preallocations_, &processContext_, moduleTypeResolverMaker_.get());
});
group.run([&, this, tempReg]() {
ServiceRegistry::Operate operate(serviceToken_);
input_ = makeInput(sourceID,
*parameterSet,
*common,
/*items.preg(),*/ tempReg,
items.branchIDListHelper(),
get_underlying_safe(processBlockHelper_),
items.thinnedAssociationsHelper(),
items.actReg_,
items.processConfiguration(),
preallocations_);
});
group.wait();
items.preg()->addFromInput(*tempReg);
input_->switchTo(items.preg());
{
auto const& tns = ServiceRegistry::instance().get<service::TriggerNamesService>();
schedule_ = items.finishSchedule(std::move(*madeModules),
*parameterSet,
tns,
hasSubProcesses,
preallocations_,
&processContext_,
*processBlockHelper_);
}
}
// set the data members
act_table_ = std::move(items.act_table_);
actReg_ = items.actReg_;
preg_ = items.preg();
mergeableRunProductProcesses_.setProcessesWithMergeableRunProducts(*preg_);
branchIDListHelper_ = items.branchIDListHelper();
thinnedAssociationsHelper_ = items.thinnedAssociationsHelper();
processConfiguration_ = items.processConfiguration();
processContext_.setProcessConfiguration(processConfiguration_.get());
FDEBUG(2) << parameterSet << std::endl;
principalCache_.setNumberOfConcurrentPrincipals(preallocations_);
for (unsigned int index = 0; index < preallocations_.numberOfStreams(); ++index) {
// Reusable event principal
auto ep = std::make_shared<EventPrincipal>(preg(),
branchIDListHelper(),
thinnedAssociationsHelper(),
*processConfiguration_,
historyAppender_.get(),
index,
true /*primary process*/,
&*processBlockHelper_);
principalCache_.insert(std::move(ep));
}
for (unsigned int index = 0; index < preallocations_.numberOfRuns(); ++index) {
auto rp = std::make_unique<RunPrincipal>(
preg(), *processConfiguration_, historyAppender_.get(), index, true, &mergeableRunProductProcesses_);
principalCache_.insert(std::move(rp));
}
for (unsigned int index = 0; index < preallocations_.numberOfLuminosityBlocks(); ++index) {
auto lp =
std::make_unique<LuminosityBlockPrincipal>(preg(), *processConfiguration_, historyAppender_.get(), index);
principalCache_.insert(std::move(lp));
}
{
auto pb = std::make_unique<ProcessBlockPrincipal>(preg(), *processConfiguration_);
principalCache_.insert(std::move(pb));
auto pbForInput = std::make_unique<ProcessBlockPrincipal>(preg(), *processConfiguration_);
principalCache_.insertForInput(std::move(pbForInput));
}
// fill the subprocesses, if there are any
subProcesses_.reserve(subProcessVParameterSet.size());
for (auto& subProcessPSet : subProcessVParameterSet) {
subProcesses_.emplace_back(subProcessPSet,
*parameterSet,
preg(),
branchIDListHelper(),
*processBlockHelper_,
*thinnedAssociationsHelper_,
SubProcessParentageHelper(),
*espController_,
*actReg_,
token,
serviceregistry::kConfigurationOverrides,
preallocations_,
&processContext_,
moduleTypeResolverMaker_);
}
} catch (...) {
//in case of an exception, make sure Services are available
// during the following destructors
espController_ = nullptr;
esp_ = nullptr;
schedule_ = nullptr;
input_ = nullptr;
looper_ = nullptr;
actReg_ = nullptr;
throw;
}
}
EventProcessor::~EventProcessor() {
// Make the services available while everything is being deleted.
ServiceToken token = getToken();
ServiceRegistry::Operate op(token);
// manually destroy all these thing that may need the services around
// propagate_const<T> has no reset() function
espController_ = nullptr;
esp_ = nullptr;
schedule_ = nullptr;
input_ = nullptr;
looper_ = nullptr;
actReg_ = nullptr;
pset::Registry::instance()->clear();
ParentageRegistry::instance()->clear();
}
void EventProcessor::taskCleanup() {
edm::FinalWaitingTask task{taskGroup_};
espController_->endIOVsAsync(edm::WaitingTaskHolder{taskGroup_, &task});
task.waitNoThrow();
assert(task.done());
}
void EventProcessor::beginJob() {
if (beginJobCalled_)
return;
beginJobCalled_ = true;
bk::beginJob();
// StateSentry toerror(this); // should we add this ?
//make the services available
ServiceRegistry::Operate operate(serviceToken_);
service::SystemBounds bounds(preallocations_.numberOfStreams(),
preallocations_.numberOfLuminosityBlocks(),
preallocations_.numberOfRuns(),
preallocations_.numberOfThreads());
actReg_->preallocateSignal_(bounds);
schedule_->convertCurrentProcessAlias(processConfiguration_->processName());
pathsAndConsumesOfModules_.initialize(schedule_.get(), preg());
std::vector<ModuleProcessName> consumedBySubProcesses;
for_all(subProcesses_,
[&consumedBySubProcesses, deleteModules = deleteNonConsumedUnscheduledModules_](auto& subProcess) {
auto c = subProcess.keepOnlyConsumedUnscheduledModules(deleteModules);
if (consumedBySubProcesses.empty()) {
consumedBySubProcesses = std::move(c);
} else if (not c.empty()) {
std::vector<ModuleProcessName> tmp;
tmp.reserve(consumedBySubProcesses.size() + c.size());
std::merge(consumedBySubProcesses.begin(),
consumedBySubProcesses.end(),
c.begin(),
c.end(),
std::back_inserter(tmp));
std::swap(consumedBySubProcesses, tmp);
}
});
// Note: all these may throw
checkForModuleDependencyCorrectness(pathsAndConsumesOfModules_, printDependencies_);
if (deleteNonConsumedUnscheduledModules_) {
if (auto const unusedModules = nonConsumedUnscheduledModules(pathsAndConsumesOfModules_, consumedBySubProcesses);
not unusedModules.empty()) {
pathsAndConsumesOfModules_.removeModules(unusedModules);
edm::LogInfo("DeleteModules").log([&unusedModules](auto& l) {
l << "Following modules are not in any Path or EndPath, nor is their output consumed by any other module, "
"and "
"therefore they are deleted before beginJob transition.";
for (auto const& description : unusedModules) {
l << "\n " << description->moduleLabel();
}
});
for (auto const& description : unusedModules) {
schedule_->deleteModule(description->moduleLabel(), actReg_.get());
}
}
}
// Initialize after the deletion of non-consumed unscheduled
// modules to avoid non-consumed non-run modules to keep the
// products unnecessarily alive
if (not branchesToDeleteEarly_.empty()) {
auto modulesToSkip = std::move(modulesToIgnoreForDeleteEarly_);
auto branchesToDeleteEarly = std::move(branchesToDeleteEarly_);
auto referencesToBranches = std::move(referencesToBranches_);
schedule_->initializeEarlyDelete(branchesToDeleteEarly, referencesToBranches, modulesToSkip, *preg_);
}
if (preallocations_.numberOfLuminosityBlocks() > 1) {
throwAboutModulesRequiringLuminosityBlockSynchronization();
}
if (preallocations_.numberOfRuns() > 1) {
warnAboutModulesRequiringRunSynchronization();
}
//NOTE: This implementation assumes 'Job' means one call
// the EventProcessor::run
// If it really means once per 'application' then this code will
// have to be changed.
// Also have to deal with case where have 'run' then new Module
// added and do 'run'
// again. In that case the newly added Module needs its 'beginJob'
// to be called.
//NOTE: in future we should have a beginOfJob for looper that takes no arguments
// For now we delay calling beginOfJob until first beginOfRun
//if(looper_) {
// looper_->beginOfJob(es);
//}
espController_->finishConfiguration();
actReg_->eventSetupConfigurationSignal_(esp_->recordsToResolverIndices(), processContext_);
actReg_->preBeginJobSignal_(pathsAndConsumesOfModules_, processContext_);
try {
convertException::wrap([&]() { input_->doBeginJob(); });
} catch (cms::Exception& ex) {
ex.addContext("Calling beginJob for the source");
throw;
}
schedule_->beginJob(*preg_, esp_->recordsToResolverIndices(), *processBlockHelper_);
if (looper_) {
constexpr bool mustPrefetchMayGet = true;
auto const processBlockLookup = preg_->productLookup(InProcess);
auto const runLookup = preg_->productLookup(InRun);
auto const lumiLookup = preg_->productLookup(InLumi);
auto const eventLookup = preg_->productLookup(InEvent);
looper_->updateLookup(InProcess, *processBlockLookup, mustPrefetchMayGet);
looper_->updateLookup(InRun, *runLookup, mustPrefetchMayGet);
looper_->updateLookup(InLumi, *lumiLookup, mustPrefetchMayGet);
looper_->updateLookup(InEvent, *eventLookup, mustPrefetchMayGet);
looper_->updateLookup(esp_->recordsToResolverIndices());
}
// toerror.succeeded(); // should we add this?
for_all(subProcesses_, [](auto& subProcess) { subProcess.doBeginJob(); });
actReg_->postBeginJobSignal_();
oneapi::tbb::task_group group;
FinalWaitingTask last{group};
using namespace edm::waiting_task::chain;
first([this](auto nextTask) {
for (unsigned int i = 0; i < preallocations_.numberOfStreams(); ++i) {
first([i, this](auto nextTask) {
ServiceRegistry::Operate operate(serviceToken_);
schedule_->beginStream(i);
}) | ifThen(not subProcesses_.empty(), [this, i](auto nextTask) {
ServiceRegistry::Operate operate(serviceToken_);
for_all(subProcesses_, [i](auto& subProcess) { subProcess.doBeginStream(i); });
}) | lastTask(nextTask);
}
}) | runLast(WaitingTaskHolder(group, &last));
last.wait();
}
void EventProcessor::endJob() {
// Collects exceptions, so we don't throw before all operations are performed.
ExceptionCollector c(
"Multiple exceptions were thrown while executing endJob. An exception message follows for each.\n");
//make the services available
ServiceRegistry::Operate operate(serviceToken_);
using namespace edm::waiting_task::chain;
oneapi::tbb::task_group group;
edm::FinalWaitingTask waitTask{group};
{
//handle endStream transitions
edm::WaitingTaskHolder taskHolder(group, &waitTask);
std::mutex collectorMutex;
for (unsigned int i = 0; i < preallocations_.numberOfStreams(); ++i) {
first([this, i, &c, &collectorMutex](auto nextTask) {
std::exception_ptr ep;
try {
ServiceRegistry::Operate operate(serviceToken_);
this->schedule_->endStream(i);
} catch (...) {
ep = std::current_exception();
}
if (ep) {
std::lock_guard<std::mutex> l(collectorMutex);
c.call([&ep]() { std::rethrow_exception(ep); });
}
}) | then([this, i, &c, &collectorMutex](auto nextTask) {
for (auto& subProcess : subProcesses_) {
first([this, i, &c, &collectorMutex, &subProcess](auto nextTask) {
std::exception_ptr ep;
try {
ServiceRegistry::Operate operate(serviceToken_);
subProcess.doEndStream(i);
} catch (...) {
ep = std::current_exception();
}
if (ep) {
std::lock_guard<std::mutex> l(collectorMutex);
c.call([&ep]() { std::rethrow_exception(ep); });
}
}) | lastTask(nextTask);
}
}) | lastTask(taskHolder);
}
}
waitTask.waitNoThrow();
auto actReg = actReg_.get();
c.call([actReg]() { actReg->preEndJobSignal_(); });
schedule_->endJob(c);
for (auto& subProcess : subProcesses_) {
c.call(std::bind(&SubProcess::doEndJob, &subProcess));
}
c.call(std::bind(&InputSource::doEndJob, input_.get()));
if (looper_) {
c.call(std::bind(&EDLooperBase::endOfJob, looper()));
}
c.call([actReg]() { actReg->postEndJobSignal_(); });
if (c.hasThrown()) {
c.rethrow();
}
}
ServiceToken EventProcessor::getToken() { return serviceToken_; }
std::vector<ModuleDescription const*> EventProcessor::getAllModuleDescriptions() const {
return schedule_->getAllModuleDescriptions();
}
int EventProcessor::totalEvents() const { return schedule_->totalEvents(); }
int EventProcessor::totalEventsPassed() const { return schedule_->totalEventsPassed(); }
int EventProcessor::totalEventsFailed() const { return schedule_->totalEventsFailed(); }
void EventProcessor::clearCounters() { schedule_->clearCounters(); }
namespace {
#include "TransitionProcessors.icc"
}
bool EventProcessor::checkForAsyncStopRequest(StatusCode& returnCode) {
bool returnValue = false;
// Look for a shutdown signal
if (shutdown_flag.load(std::memory_order_acquire)) {
returnValue = true;
edm::LogSystem("ShutdownSignal") << "an external signal was sent to shutdown the job early.";
edm::Service<edm::JobReport> jr;
jr->reportShutdownSignal();
returnCode = epSignal;
}
return returnValue;
}
namespace {
struct SourceNextGuard {
SourceNextGuard(edm::ActivityRegistry& iReg) : act_(iReg) { iReg.preSourceNextTransitionSignal_.emit(); }
~SourceNextGuard() { act_.postSourceNextTransitionSignal_.emit(); }
edm::ActivityRegistry& act_;
};
} // namespace
InputSource::ItemTypeInfo EventProcessor::nextTransitionType() {
SendSourceTerminationSignalIfException sentry(actReg_.get());
InputSource::ItemTypeInfo itemTypeInfo;
{
SourceNextGuard guard(*actReg_.get());
//For now, do nothing with InputSource::IsSynchronize
do {
itemTypeInfo = input_->nextItemType();
} while (itemTypeInfo == InputSource::ItemType::IsSynchronize);
}
lastSourceTransition_ = itemTypeInfo;
sentry.completedSuccessfully();
StatusCode returnCode = epSuccess;
if (checkForAsyncStopRequest(returnCode)) {
actReg_->preSourceEarlyTerminationSignal_(TerminationOrigin::ExternalSignal);
lastSourceTransition_ = InputSource::ItemType::IsStop;
}
return lastSourceTransition_;
}
void EventProcessor::nextTransitionTypeAsync(std::shared_ptr<RunProcessingStatus> iRunStatus,
WaitingTaskHolder nextTask) {
auto group = nextTask.group();
sourceResourcesAcquirer_.serialQueueChain().push(
*group, [this, runStatus = std::move(iRunStatus), nextHolder = std::move(nextTask)]() mutable {
CMS_SA_ALLOW try {
ServiceRegistry::Operate operate(serviceToken_);
std::lock_guard<std::recursive_mutex> guard(*(sourceMutex_.get()));
nextTransitionType();
if (lastTransitionType() == InputSource::ItemType::IsRun &&
runStatus->runPrincipal()->run() == input_->run() &&
runStatus->runPrincipal()->reducedProcessHistoryID() == input_->reducedProcessHistoryID()) {
throw Exception(errors::LogicError)
<< "InputSource claimed previous Run Entry was last to be merged in this file,\n"
<< "but the next entry has the same run number and reduced ProcessHistoryID.\n"
<< "This is probably a bug in the InputSource. Please report to the Core group.\n";
}
} catch (...) {
nextHolder.doneWaiting(std::current_exception());
}
});
}
EventProcessor::StatusCode EventProcessor::runToCompletion() {
beginJob(); //make sure this was called
// make the services available
ServiceRegistry::Operate operate(serviceToken_);
actReg_->beginProcessingSignal_();
auto endSignal = [](ActivityRegistry* iReg) { iReg->endProcessingSignal_(); };
std::unique_ptr<ActivityRegistry, decltype(endSignal)> guard(actReg_.get(), endSignal);
try {
FilesProcessor fp(fileModeNoMerge_);
convertException::wrap([&]() {
bool firstTime = true;
do {
if (not firstTime) {
prepareForNextLoop();
rewindInput();
} else {
firstTime = false;
}
startingNewLoop();
auto trans = fp.processFiles(*this);
fp.normalEnd();
if (deferredExceptionPtrIsSet_.load()) {
std::rethrow_exception(deferredExceptionPtr_);
}
if (trans != InputSource::ItemType::IsStop) {
//problem with the source
doErrorStuff();
throw cms::Exception("BadTransition") << "Unexpected transition change " << static_cast<int>(trans);
}
} while (not endOfLoop());
}); // convertException::wrap
} // Try block
catch (cms::Exception& e) {
if (exceptionMessageLumis_) {
std::string message(
"Another exception was caught while trying to clean up lumis after the primary fatal exception.");
e.addAdditionalInfo(message);
if (e.alreadyPrinted()) {
LogAbsolute("Additional Exceptions") << message;
}
}
if (exceptionMessageRuns_) {
std::string message(
"Another exception was caught while trying to clean up runs after the primary fatal exception.");
e.addAdditionalInfo(message);
if (e.alreadyPrinted()) {
LogAbsolute("Additional Exceptions") << message;
}
}
if (!exceptionMessageFiles_.empty()) {
e.addAdditionalInfo(exceptionMessageFiles_);
if (e.alreadyPrinted()) {
LogAbsolute("Additional Exceptions") << exceptionMessageFiles_;
}
}
throw;
}
return epSuccess;
}
void EventProcessor::readFile() {
FDEBUG(1) << " \treadFile\n";
size_t size = preg_->size();
SendSourceTerminationSignalIfException sentry(actReg_.get());
if (streamRunActive_ > 0) {
streamRunStatus_[0]->runPrincipal()->preReadFile();
streamRunStatus_[0]->runPrincipal()->adjustIndexesAfterProductRegistryAddition();
}
if (streamLumiActive_ > 0) {
streamLumiStatus_[0]->lumiPrincipal()->adjustIndexesAfterProductRegistryAddition();
}
fb_ = input_->readFile();
if (size < preg_->size()) {
principalCache_.adjustIndexesAfterProductRegistryAddition();
}