-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
EventProcessor.cc
2241 lines (2008 loc) · 87.6 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/Framework/interface/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/MessageReceiverForSource.h"
#include "FWCore/Framework/interface/ModuleChanger.h"
#include "FWCore/Framework/interface/OccurrenceTraits.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/SubProcess.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/src/Breakpoints.h"
#include "FWCore/Framework/src/EPStates.h"
#include "FWCore/Framework/src/EventSetupsController.h"
#include "FWCore/Framework/src/InputSourceFactory.h"
#include "FWCore/Framework/src/SharedResourcesRegistry.h"
#include "FWCore/Framework/src/streamTransitionAsync.h"
#include "FWCore/Framework/src/globalTransitionAsync.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/PythonParameterSet/interface/PythonProcessDesc.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/WaitingTaskHolder.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 "MessageForSource.h"
#include "MessageForParent.h"
#include "boost/thread/xtime.hpp"
#include "boost/range/adaptor/reversed.hpp"
#include <exception>
#include <iomanip>
#include <iostream>
#include <utility>
#include <sstream>
#include <sys/ipc.h>
#include <sys/msg.h>
#include "tbb/task.h"
//Used for forking
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <sys/fcntl.h>
#include <unistd.h>
//Used for CPU affinity
#ifndef __APPLE__
#include <sched.h>
#endif
namespace {
//Sentry class to only send a signal if an
// exception occurs. An exception is identified
// by the destructor being called without first
// calling completedSuccessfully().
class SendSourceTerminationSignalIfException {
public:
SendSourceTerminationSignalIfException(edm::ActivityRegistry* iReg):
reg_(iReg) {}
~SendSourceTerminationSignalIfException() {
if(reg_) {
reg_->preSourceEarlyTerminationSignal_(edm::TerminationOrigin::ExceptionFromThisContext);
}
}
void completedSuccessfully() {
reg_ = nullptr;
}
private:
edm::ActivityRegistry* reg_; // We do not use propagate_const because the registry itself is mutable.
};
}
namespace edm {
// ---------------------------------------------------------------
std::unique_ptr<InputSource>
makeInput(ParameterSet& params,
CommonParams const& common,
std::shared_ptr<ProductRegistry> preg,
std::shared_ptr<BranchIDListHelper> branchIDListHelper,
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 == 0) {
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());
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(),
ModuleDescription::getUniqueID());
InputSourceDescription isdesc(md, preg, branchIDListHelper, 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::shared_ptr<EDLooperBase> vLooper;
std::vector<std::string> loopers = params.getParameter<std::vector<std::string> >("@all_loopers");
if(loopers.size() == 0) {
return vLooper;
}
assert(1 == loopers.size());
for(std::vector<std::string>::iterator itName = loopers.begin(), itNameEnd = loopers.end();
itName != itNameEnd;
++itName) {
ParameterSet* providerPSet = params.getPSetForUpdate(*itName);
providerPSet->registerIt();
vLooper = eventsetup::LooperFactory::get()->addTo(esController,
cp,
*providerPSet);
}
return vLooper;
}
// ---------------------------------------------------------------
EventProcessor::EventProcessor(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_(),
espController_(new eventsetup::EventSetupsController),
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),
stateMachineWasInErrorState_(false),
fileMode_(),
emptyRunLumiMode_(),
exceptionMessageFiles_(),
exceptionMessageRuns_(),
exceptionMessageLumis_(),
alreadyHandlingException_(false),
forceLooperToEnd_(false),
looperBeginJobRun_(false),
forceESCacheClearOnNewRun_(false),
numberOfForkedChildren_(0),
numberOfSequentialEventsPerChild_(1),
setCpuAffinity_(false),
eventSetupDataToExcludeFromPrefetching_() {
std::shared_ptr<ParameterSet> parameterSet = PythonProcessDesc(config).parameterSet();
auto processDesc = std::make_shared<ProcessDesc>(parameterSet);
processDesc->addServices(defaultServices, forcedServices);
init(processDesc, iToken, iLegacy);
}
EventProcessor::EventProcessor(std::string const& config,
std::vector<std::string> const& defaultServices,
std::vector<std::string> const& forcedServices) :
actReg_(),
preg_(),
branchIDListHelper_(),
serviceToken_(),
input_(),
espController_(new eventsetup::EventSetupsController),
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),
stateMachineWasInErrorState_(false),
fileMode_(),
emptyRunLumiMode_(),
exceptionMessageFiles_(),
exceptionMessageRuns_(),
exceptionMessageLumis_(),
alreadyHandlingException_(false),
forceLooperToEnd_(false),
looperBeginJobRun_(false),
forceESCacheClearOnNewRun_(false),
numberOfForkedChildren_(0),
numberOfSequentialEventsPerChild_(1),
setCpuAffinity_(false),
asyncStopRequestedWhileProcessingEvents_(false),
nextItemTypeFromProcessingEvents_(InputSource::IsEvent),
eventSetupDataToExcludeFromPrefetching_()
{
std::shared_ptr<ParameterSet> parameterSet = PythonProcessDesc(config).parameterSet();
auto processDesc = std::make_shared<ProcessDesc>(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_(),
espController_(new eventsetup::EventSetupsController),
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),
stateMachineWasInErrorState_(false),
fileMode_(),
emptyRunLumiMode_(),
exceptionMessageFiles_(),
exceptionMessageRuns_(),
exceptionMessageLumis_(),
alreadyHandlingException_(false),
forceLooperToEnd_(false),
looperBeginJobRun_(false),
forceESCacheClearOnNewRun_(false),
numberOfForkedChildren_(0),
numberOfSequentialEventsPerChild_(1),
setCpuAffinity_(false),
asyncStopRequestedWhileProcessingEvents_(false),
nextItemTypeFromProcessingEvents_(InputSource::IsEvent),
eventSetupDataToExcludeFromPrefetching_()
{
init(processDesc, token, legacy);
}
EventProcessor::EventProcessor(std::string const& config, bool isPython):
actReg_(),
preg_(),
branchIDListHelper_(),
serviceToken_(),
input_(),
espController_(new eventsetup::EventSetupsController),
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),
stateMachineWasInErrorState_(false),
fileMode_(),
emptyRunLumiMode_(),
exceptionMessageFiles_(),
exceptionMessageRuns_(),
exceptionMessageLumis_(),
alreadyHandlingException_(false),
forceLooperToEnd_(false),
looperBeginJobRun_(false),
forceESCacheClearOnNewRun_(false),
numberOfForkedChildren_(0),
numberOfSequentialEventsPerChild_(1),
setCpuAffinity_(false),
asyncStopRequestedWhileProcessingEvents_(false),
nextItemTypeFromProcessingEvents_(InputSource::IsEvent),
eventSetupDataToExcludeFromPrefetching_()
{
if(isPython) {
std::shared_ptr<ParameterSet> parameterSet = PythonProcessDesc(config).parameterSet();
auto processDesc = std::make_shared<ProcessDesc>(parameterSet);
init(processDesc, ServiceToken(), serviceregistry::kOverlapIsError);
}
else {
auto processDesc = std::make_shared<ProcessDesc>(config);
init(processDesc, ServiceToken(), serviceregistry::kOverlapIsError);
}
}
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();
// Now set some parameters specific to the main process.
ParameterSet const& optionsPset(parameterSet->getUntrackedParameterSet("options", ParameterSet()));
fileMode_ = optionsPset.getUntrackedParameter<std::string>("fileMode", "");
emptyRunLumiMode_ = optionsPset.getUntrackedParameter<std::string>("emptyRunLumiMode", "");
forceESCacheClearOnNewRun_ = optionsPset.getUntrackedParameter<bool>("forceEventSetupCacheClearOnNewRun", false);
//threading
unsigned int nThreads=1;
if(optionsPset.existsAs<unsigned int>("numberOfThreads",false)) {
nThreads = optionsPset.getUntrackedParameter<unsigned int>("numberOfThreads");
if(nThreads == 0) {
nThreads = 1;
}
}
/* TODO: when we support having each stream run in a different thread use this default
unsigned int nStreams =nThreads;
*/
unsigned int nStreams =1;
if(optionsPset.existsAs<unsigned int>("numberOfStreams",false)) {
nStreams = optionsPset.getUntrackedParameter<unsigned int>("numberOfStreams");
if(nStreams==0) {
nStreams = nThreads;
}
// PG: Log the number of streams
edm::LogInfo("StreamSetup") <<"setting # streams "<<nStreams;
}
/*
bool nRunsSet = false;
*/
unsigned int nConcurrentRuns =1;
/*
if(nRunsSet = optionsPset.existsAs<unsigned int>("numberOfConcurrentRuns",false)) {
nConcurrentRuns = optionsPset.getUntrackedParameter<unsigned int>("numberOfConcurrentRuns");
}
*/
unsigned int nConcurrentLumis =1;
/*
if(optionsPset.existsAs<unsigned int>("numberOfConcurrentLuminosityBlocks",false)) {
nConcurrentLumis = optionsPset.getUntrackedParameter<unsigned int>("numberOfConcurrentLuminosityBlocks");
} else {
nConcurrentLumis = nConcurrentRuns;
}
*/
//Check that relationships between threading parameters makes sense
/*
if(nThreads<nStreams) {
//bad
}
if(nConcurrentRuns>nStreams) {
//bad
}
if(nConcurrentRuns>nConcurrentLumis) {
//bad
}
*/
//forking
ParameterSet const& forking = optionsPset.getUntrackedParameterSet("multiProcesses", ParameterSet());
numberOfForkedChildren_ = forking.getUntrackedParameter<int>("maxChildProcesses", 0);
numberOfSequentialEventsPerChild_ = forking.getUntrackedParameter<unsigned int>("maxSequentialEventsPerChild", 1);
setCpuAffinity_ = forking.getUntrackedParameter<bool>("setCpuAffinity", false);
continueAfterChildFailure_ = forking.getUntrackedParameter<bool>("continueAfterChildFailure",false);
std::vector<ParameterSet> const& excluded = forking.getUntrackedParameterSetVector("eventSetupDataToExcludeFromPrefetching", std::vector<ParameterSet>());
for(auto const& ps : excluded) {
eventSetupDataToExcludeFromPrefetching_[ps.getUntrackedParameter<std::string>("record")].emplace(ps.getUntrackedParameter<std::string>("type", "*"),
ps.getUntrackedParameter<std::string>("label", ""));
}
IllegalParameters::setThrowAnException(optionsPset.getUntrackedParameter<bool>("throwIfIllegalParameter", true));
printDependencies_ = optionsPset.getUntrackedParameter("printDependencies", false);
// 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_);
if(nStreams>1) {
edm::Service<RootHandlers> handler;
handler->willBeUsingThreads();
}
// intialize miscellaneous items
std::shared_ptr<CommonParams> common(items.initMisc(*parameterSet));
// intialize the event setup provider
esp_ = espController_->makeProvider(*parameterSet);
// initialize the looper, if any
looper_ = fillLooper(*espController_, *esp_, *parameterSet);
if(looper_) {
looper_->setActionTable(items.act_table_.get());
looper_->attachTo(*items.actReg_);
//For now loopers make us run only 1 transition at a time
nStreams=1;
nConcurrentLumis=1;
nConcurrentRuns=1;
}
preallocations_ = PreallocationConfiguration{nThreads,nStreams,nConcurrentLumis,nConcurrentRuns};
// initialize the input source
input_ = makeInput(*parameterSet,
*common,
items.preg(),
items.branchIDListHelper(),
items.thinnedAssociationsHelper(),
items.actReg_,
items.processConfiguration(),
preallocations_);
// intialize the Schedule
schedule_ = items.initSchedule(*parameterSet,hasSubProcesses,preallocations_,&processContext_);
// set the data members
act_table_ = std::move(items.act_table_);
actReg_ = items.actReg_;
preg_ = items.preg();
branchIDListHelper_ = items.branchIDListHelper();
thinnedAssociationsHelper_ = items.thinnedAssociationsHelper();
processConfiguration_ = items.processConfiguration();
processContext_.setProcessConfiguration(processConfiguration_.get());
principalCache_.setProcessHistoryRegistry(input_->processHistoryRegistry());
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);
principalCache_.insert(ep);
}
// fill the subprocesses, if there are any
subProcesses_.reserve(subProcessVParameterSet.size());
for(auto& subProcessPSet : subProcessVParameterSet) {
subProcesses_.emplace_back(subProcessPSet,
*parameterSet,
preg(),
branchIDListHelper(),
*thinnedAssociationsHelper_,
SubProcessParentageHelper(),
*espController_,
*actReg_,
token,
serviceregistry::kConfigurationOverrides,
preallocations_,
&processContext_);
}
}
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::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);
pathsAndConsumesOfModules_.initialize(schedule_.get(), preg());
//NOTE: this may throw
checkForModuleDependencyCorrectness(pathsAndConsumesOfModules_, printDependencies_);
actReg_->preBeginJobSignal_(pathsAndConsumesOfModules_, processContext_);
//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);
//}
try {
convertException::wrap([&]() {
input_->doBeginJob();
});
}
catch(cms::Exception& ex) {
ex.addContext("Calling beginJob for the source");
throw;
}
schedule_->beginJob(*preg_);
// toerror.succeeded(); // should we add this?
for_all(subProcesses_, [](auto& subProcess){ subProcess.doBeginJob(); });
actReg_->postBeginJobSignal_();
for(unsigned int i=0; i<preallocations_.numberOfStreams();++i) {
schedule_->beginStream(i);
for_all(subProcesses_, [i](auto& subProcess){ subProcess.doBeginStream(i); });
}
}
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_);
//NOTE: this really should go elsewhere in the future
for(unsigned int i=0; i<preallocations_.numberOfStreams();++i) {
c.call([this,i](){this->schedule_->endStream(i);});
for(auto& subProcess : subProcesses_) {
c.call([&subProcess,i](){ subProcess.doEndStream(i); } );
}
}
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_;
}
//Setup signal handler to listen for when forked children stop
namespace {
//These are volatile since the compiler can not be allowed to optimize them
// since they can be modified in the signaller handler
volatile bool child_failed = false;
volatile unsigned int num_children_done = 0;
volatile int child_fail_exit_status = 0;
volatile int child_fail_signal = 0;
//NOTE: We setup the signal handler to run in the main thread which
// is also the same thread that then reads the above values
extern "C" {
void ep_sigchld(int, siginfo_t*, void*) {
//printf("in sigchld\n");
//FDEBUG(1) << "in sigchld handler\n";
int stat_loc;
pid_t p = waitpid(-1, &stat_loc, WNOHANG);
while(0<p) {
//printf(" looping\n");
if(WIFEXITED(stat_loc)) {
++num_children_done;
if(0 != WEXITSTATUS(stat_loc)) {
child_fail_exit_status = WEXITSTATUS(stat_loc);
child_failed = true;
}
}
if(WIFSIGNALED(stat_loc)) {
++num_children_done;
child_fail_signal = WTERMSIG(stat_loc);
child_failed = true;
}
p = waitpid(-1, &stat_loc, WNOHANG);
}
}
}
}
enum {
kChildSucceed,
kChildExitBadly,
kChildSegv,
kMaxChildAction
};
namespace {
unsigned int numberOfDigitsInChildIndex(unsigned int numberOfChildren) {
unsigned int n = 0;
while(numberOfChildren != 0) {
++n;
numberOfChildren /= 10;
}
if(n == 0) {
n = 3; // Protect against zero numberOfChildren
}
return n;
}
/*This class embodied the thread which is used to listen to the forked children and
then tell them which events they should process */
class MessageSenderToSource {
public:
MessageSenderToSource(std::vector<int> const& childrenSockets, std::vector<int> const& childrenPipes, long iNEventsToProcess);
void operator()();
private:
const std::vector<int>& m_childrenPipes;
long const m_nEventsToProcess;
fd_set m_socketSet;
unsigned int m_aliveChildren;
int m_maxFd;
};
MessageSenderToSource::MessageSenderToSource(std::vector<int> const& childrenSockets,
std::vector<int> const& childrenPipes,
long iNEventsToProcess):
m_childrenPipes(childrenPipes),
m_nEventsToProcess(iNEventsToProcess),
m_aliveChildren(childrenSockets.size()),
m_maxFd(0)
{
FD_ZERO(&m_socketSet);
for (auto const socket : childrenSockets) {
FD_SET(socket, &m_socketSet);
if (socket > m_maxFd) {
m_maxFd = socket;
}
}
for (auto const pipe : childrenPipes) {
FD_SET(pipe, &m_socketSet);
if (pipe > m_maxFd) {
m_maxFd = pipe;
}
}
m_maxFd++; // select reads [0,m_maxFd).
}
/* This function is the heart of the communication between parent and child.
* When ready for more data, the child (see MessageReceiverForSource) requests
* data through a AF_UNIX socket message. The parent will then assign the next
* chunk of data by sending a message back.
*
* Additionally, this function also monitors the read-side of the pipe fd from the child.
* If the child dies unexpectedly, the pipe will be selected as ready for read and
* will return EPIPE when read from. Further, if the child thinks the parent has died
* (defined as waiting more than 1s for a response), it will write a single byte to
* the pipe. If the parent has died, the child will get a EPIPE and throw an exception.
* If still alive, the parent will read the byte and ignore it.
*
* Note this function is complemented by the SIGCHLD handler above as currently only the SIGCHLD
* handler can distinguish between success and failure cases.
*/
void
MessageSenderToSource::operator()() {
multicore::MessageForParent childMsg;
LogInfo("ForkingController") << "I am controller";
//this is the master and therefore the controller
multicore::MessageForSource sndmsg;
sndmsg.startIndex = 0;
sndmsg.nIndices = m_nEventsToProcess;
do {
fd_set readSockets, errorSockets;
// Wait for a request from a child for events.
memcpy(&readSockets, &m_socketSet, sizeof(m_socketSet));
memcpy(&errorSockets, &m_socketSet, sizeof(m_socketSet));
// Note that we don't timeout; may be reconsidered in the future.
ssize_t rc;
while (((rc = select(m_maxFd, &readSockets, NULL, &errorSockets, NULL)) < 0) && (errno == EINTR)) {}
if (rc < 0) {
std::cerr << "select failed; should be impossible due to preconditions.\n";
abort();
break;
}
// Read the message from the child.
for (int idx=0; idx<m_maxFd; idx++) {
// Handle errors
if (FD_ISSET(idx, &errorSockets)) {
LogInfo("ForkingController") << "Error on socket " << idx;
FD_CLR(idx, &m_socketSet);
close(idx);
// See if it was the watchdog pipe that died.
for (std::vector<int>::const_iterator it = m_childrenPipes.begin(); it != m_childrenPipes.end(); it++) {
if (*it == idx) {
m_aliveChildren--;
}
}
continue;
}
if (!FD_ISSET(idx, &readSockets)) {
continue;
}
// See if this FD is a child watchdog pipe. If so, read from it to prevent
// writes from blocking.
bool is_pipe = false;
for (std::vector<int>::const_iterator it = m_childrenPipes.begin(), itEnd = m_childrenPipes.end(); it != itEnd; it++) {
if (*it == idx) {
is_pipe = true;
char buf;
while (((rc = read(idx, &buf, 1)) < 0) && (errno == EINTR)) {}
if (rc <= 0) {
m_aliveChildren--;
FD_CLR(idx, &m_socketSet);
close(idx);
}
}
}
// Only execute this block if the FD is a socket for sending the child work.
if (!is_pipe) {
while (((rc = recv(idx, reinterpret_cast<char*>(&childMsg),childMsg.sizeForBuffer() , 0)) < 0) && (errno == EINTR)) {}
if (rc < 0) {
FD_CLR(idx, &m_socketSet);
close(idx);
continue;
}
// Tell the child what events to process.
// If 'send' fails, then the child process has failed (any other possibilities are
// eliminated because we are using fixed-size messages with Unix datagram sockets).
// Thus, the SIGCHLD handler will fire and set child_fail = true.
while (((rc = send(idx, (char *)(&sndmsg), multicore::MessageForSource::sizeForBuffer(), 0)) < 0) && (errno == EINTR)) {}
if (rc < 0) {
FD_CLR(idx, &m_socketSet);
close(idx);
continue;
}
//std::cout << "Sent chunk starting at " << sndmsg.startIndex << " to child, length " << sndmsg.nIndices << std::endl;
sndmsg.startIndex += sndmsg.nIndices;
}
}
} while (m_aliveChildren > 0);
return;
}
}
void EventProcessor::possiblyContinueAfterForkChildFailure() {
if(child_failed && continueAfterChildFailure_) {
if (child_fail_signal) {
LogSystem("ForkedChildFailed") << "child process ended abnormally with signal " << child_fail_signal;
child_fail_signal=0;
} else if (child_fail_exit_status) {
LogSystem("ForkedChildFailed") << "child process ended abnormally with exit code " << child_fail_exit_status;
child_fail_exit_status=0;
} else {
LogSystem("ForkedChildFailed") << "child process ended abnormally for unknown reason";
}
child_failed =false;
}
}
bool
EventProcessor::forkProcess(std::string const& jobReportFile) {
if(0 == numberOfForkedChildren_) {return true;}
assert(0<numberOfForkedChildren_);
//do what we want done in common
{
beginJob(); //make sure this was run
// make the services available
ServiceRegistry::Operate operate(serviceToken_);
InputSource::ItemType itemType;
itemType = input_->nextItemType();
assert(itemType == InputSource::IsFile);
{
readFile();
}
itemType = input_->nextItemType();
assert(itemType == InputSource::IsRun);
LogSystem("ForkingEventSetupPreFetching") << " prefetching for run " << input_->runAuxiliary()->run();
IOVSyncValue ts(EventID(input_->runAuxiliary()->run(), 0, 0),
input_->runAuxiliary()->beginTime());
espController_->eventSetupForInstance(ts);
EventSetup const& es = esp_->eventSetup();
//now get all the data available in the EventSetup
std::vector<eventsetup::EventSetupRecordKey> recordKeys;
es.fillAvailableRecordKeys(recordKeys);
std::vector<eventsetup::DataKey> dataKeys;
for(std::vector<eventsetup::EventSetupRecordKey>::const_iterator itKey = recordKeys.begin(), itEnd = recordKeys.end();
itKey != itEnd;
++itKey) {
eventsetup::EventSetupRecord const* recordPtr = es.find(*itKey);
//see if this is on our exclusion list
ExcludedDataMap::const_iterator itExcludeRec = eventSetupDataToExcludeFromPrefetching_.find(itKey->type().name());
ExcludedData const* excludedData(nullptr);
if(itExcludeRec != eventSetupDataToExcludeFromPrefetching_.end()) {
excludedData = &(itExcludeRec->second);
if(excludedData->size() == 0 || excludedData->begin()->first == "*") {
//skip all items in this record
continue;
}
}
if(0 != recordPtr) {
dataKeys.clear();
recordPtr->fillRegisteredDataKeys(dataKeys);
for(std::vector<eventsetup::DataKey>::const_iterator itDataKey = dataKeys.begin(), itDataKeyEnd = dataKeys.end();
itDataKey != itDataKeyEnd;
++itDataKey) {
//std::cout << " " << itDataKey->type().name() << " " << itDataKey->name().value() << std::endl;
if(0 != excludedData && excludedData->find(std::make_pair(itDataKey->type().name(), itDataKey->name().value())) != excludedData->end()) {
LogInfo("ForkingEventSetupPreFetching") << " excluding:" << itDataKey->type().name() << " " << itDataKey->name().value() << std::endl;
continue;
}
try {
recordPtr->doGet(*itDataKey);
} catch(cms::Exception& e) {
LogWarning("ForkingEventSetupPreFetching") << e.what();
}
}
}
}
}
LogSystem("ForkingEventSetupPreFetching") <<" done prefetching";
{
// make the services available
ServiceRegistry::Operate operate(serviceToken_);
Service<JobReport> jobReport;
jobReport->parentBeforeFork(jobReportFile, numberOfForkedChildren_);
//Now actually do the forking
actReg_->preForkReleaseResourcesSignal_();
input_->doPreForkReleaseResources();
schedule_->preForkReleaseResources();
}
installCustomHandler(SIGCHLD, ep_sigchld);
unsigned int childIndex = 0;
unsigned int const kMaxChildren = numberOfForkedChildren_;
unsigned int const numberOfDigitsInIndex = numberOfDigitsInChildIndex(kMaxChildren);
std::vector<pid_t> childrenIds;