-
Notifications
You must be signed in to change notification settings - Fork 494
Expand file tree
/
Copy pathDispatcher.cxx
More file actions
267 lines (223 loc) · 10.2 KB
/
Dispatcher.cxx
File metadata and controls
267 lines (223 loc) · 10.2 KB
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
// Copyright CERN and copyright holders of ALICE O2. This software is
// distributed under the terms of the GNU General Public License v3 (GPL
// Version 3), copied verbatim in the file "COPYING".
//
// See http://alice-o2.web.cern.ch/license for full licensing information.
//
// In applying this license CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
/// \file Dispatcher.cxx
/// \brief Implementation of Dispatcher for O2 Data Sampling
///
/// \author Piotr Konopka, piotr.jan.konopka@cern.ch
#include "DataSampling/Dispatcher.h"
#include "Framework/RawDeviceService.h"
#include "DataSampling/DataSamplingPolicy.h"
#include "DataSampling/DataSamplingHeader.h"
#include "Framework/DataProcessingHeader.h"
#include "Framework/DataSpecUtils.h"
#include "Framework/Logger.h"
#include "Framework/ConfigParamRegistry.h"
#include "Framework/InputRecordWalker.h"
#include "Framework/Monitoring.h"
#include <Configuration/ConfigurationInterface.h>
#include <Configuration/ConfigurationFactory.h>
#include <fairmq/FairMQDevice.h>
using namespace o2::configuration;
using namespace o2::monitoring;
using namespace o2::framework;
namespace o2::utilities
{
Dispatcher::Dispatcher(std::string name, const std::string reconfigurationSource)
: mName(name), mReconfigurationSource(reconfigurationSource)
{
}
Dispatcher::~Dispatcher() = default;
void Dispatcher::init(InitContext& ctx)
{
LOG(DEBUG) << "Reading Data Sampling Policies...";
boost::property_tree::ptree policiesTree;
if (mReconfigurationSource.empty() == false) {
std::unique_ptr<ConfigurationInterface> cfg = ConfigurationFactory::getConfiguration(mReconfigurationSource);
policiesTree = cfg->getRecursive("dataSamplingPolicies");
mPolicies.clear();
} else if (ctx.options().isSet("sampling-config-ptree")) {
policiesTree = ctx.options().get<boost::property_tree::ptree>("sampling-config-ptree");
mPolicies.clear();
} else {
; // we use policies declared during workflow init.
}
for (auto&& policyConfig : policiesTree) {
// we don't want the Dispatcher to exit due to one faulty Policy
try {
mPolicies.emplace_back(std::make_shared<DataSamplingPolicy>(DataSamplingPolicy::fromConfiguration(policyConfig.second)));
} catch (std::exception& ex) {
LOG(WARN) << "Could not load the Data Sampling Policy '"
<< policyConfig.second.get_optional<std::string>("id").value_or("") << "', because: " << ex.what();
} catch (...) {
LOG(WARN) << "Could not load the Data Sampling Policy '"
<< policyConfig.second.get_optional<std::string>("id").value_or("") << "'";
}
}
}
void Dispatcher::run(ProcessingContext& ctx)
{
for (const auto& input : InputRecordWalker(ctx.inputs())) {
const auto* inputHeader = header::get<header::DataHeader*>(input.header);
ConcreteDataMatcher inputMatcher{inputHeader->dataOrigin, inputHeader->dataDescription, inputHeader->subSpecification};
for (auto& policy : mPolicies) {
// todo: consider getting the outputSpec in match to improve performance
// todo: consider matching (and deciding) in completion policy to save some time
if (policy->match(inputMatcher) && policy->decide(input)) {
// We copy every header which is not DataHeader or DataProcessingHeader,
// so that custom data-dependent headers are passed forward,
// and we add a DataSamplingHeader.
header::Stack headerStack{
std::move(extractAdditionalHeaders(input.header)),
std::move(prepareDataSamplingHeader(*policy.get(), ctx.services().get<const DeviceSpec>()))};
if (!policy->getFairMQOutputChannel().empty()) {
sendFairMQ(ctx.services().get<RawDeviceService>().device(), input, policy->getFairMQOutputChannelName(),
std::move(headerStack));
} else {
Output output = policy->prepareOutput(inputMatcher, input.spec->lifetime);
output.metaHeader = std::move(header::Stack{std::move(output.metaHeader), std::move(headerStack)});
send(ctx.outputs(), input, std::move(output));
}
}
}
}
if (ctx.inputs().isValid("timer-stats")) {
reportStats(ctx.services().get<Monitoring>());
}
}
void Dispatcher::reportStats(Monitoring& monitoring) const
{
uint64_t dispatcherTotalEvaluatedMessages = 0;
uint64_t dispatcherTotalAcceptedMessages = 0;
for (const auto& policy : mPolicies) {
dispatcherTotalEvaluatedMessages += policy->getTotalEvaluatedMessages();
dispatcherTotalAcceptedMessages += policy->getTotalAcceptedMessages();
}
monitoring.send({dispatcherTotalEvaluatedMessages, "Dispatcher_messages_evaluated"});
monitoring.send({dispatcherTotalAcceptedMessages, "Dispatcher_messages_passed"});
}
DataSamplingHeader Dispatcher::prepareDataSamplingHeader(const DataSamplingPolicy& policy, const DeviceSpec& spec)
{
uint64_t sampleTime = static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count());
DataSamplingHeader::DeviceIDType id;
id.runtimeInit(spec.id.substr(0, DataSamplingHeader::deviceIDTypeSize).c_str());
return {
sampleTime,
policy.getTotalAcceptedMessages(),
policy.getTotalEvaluatedMessages(),
id};
}
header::Stack Dispatcher::extractAdditionalHeaders(const char* inputHeaderStack) const
{
header::Stack headerStack;
const auto* first = header::BaseHeader::get(reinterpret_cast<const std::byte*>(inputHeaderStack));
for (const auto* current = first; current != nullptr; current = current->next()) {
if (current->description != header::DataHeader::sHeaderType &&
current->description != DataProcessingHeader::sHeaderType) {
headerStack = std::move(header::Stack{std::move(headerStack), *current});
}
}
return headerStack;
}
void Dispatcher::send(DataAllocator& dataAllocator, const DataRef& inputData, Output&& output) const
{
const auto* inputHeader = header::get<header::DataHeader*>(inputData.header);
dataAllocator.snapshot(output, inputData.payload, inputHeader->payloadSize, inputHeader->payloadSerializationMethod);
}
// ideally this should be in a separate proxy device or use Lifetime::External
void Dispatcher::sendFairMQ(FairMQDevice* device, const DataRef& inputData, const std::string& fairMQChannel,
header::Stack&& stack) const
{
const auto* dh = header::get<header::DataHeader*>(inputData.header);
assert(dh);
const auto* dph = header::get<DataProcessingHeader*>(inputData.header);
assert(dph);
header::DataHeader dhout{dh->dataDescription, dh->dataOrigin, dh->subSpecification, dh->payloadSize};
dhout.payloadSerializationMethod = dh->payloadSerializationMethod;
DataProcessingHeader dphout{dph->startTime, dph->duration};
o2::header::Stack headerStack{dhout, dphout, stack};
auto channelAlloc = o2::pmr::getTransportAllocator(device->Transport());
FairMQMessagePtr msgHeaderStack = o2::pmr::getMessage(std::move(headerStack), channelAlloc);
char* payloadCopy = new char[dh->payloadSize];
memcpy(payloadCopy, inputData.payload, dh->payloadSize);
auto cleanupFcn = [](void* data, void*) { delete[] reinterpret_cast<char*>(data); };
FairMQMessagePtr msgPayload(device->NewMessage(payloadCopy, dh->payloadSize, cleanupFcn, payloadCopy));
FairMQParts message;
message.AddPart(move(msgHeaderStack));
message.AddPart(move(msgPayload));
int64_t bytesSent = device->Send(message, fairMQChannel);
}
void Dispatcher::registerPolicy(std::unique_ptr<DataSamplingPolicy>&& policy)
{
mPolicies.emplace_back(std::move(policy));
}
const std::string& Dispatcher::getName()
{
return mName;
}
Inputs Dispatcher::getInputSpecs()
{
Inputs declaredInputs;
// Add data inputs. Avoid duplicates and inputs which include others (e.g. "TST/DATA" includes "TST/DATA/1".
for (const auto& policy : mPolicies) {
for (const auto& path : policy->getPathMap()) {
auto& potentiallyNewInput = path.first;
// The idea is that we remove all existing inputs which are covered by the potentially new input.
// If there are none which are broader than the new one, then we add it.
auto newInputIsBroader = [&potentiallyNewInput](const InputSpec& other) {
return DataSpecUtils::includes(potentiallyNewInput, other);
};
declaredInputs.erase(std::remove_if(declaredInputs.begin(), declaredInputs.end(), newInputIsBroader), declaredInputs.end());
auto declaredInputIsBroader = [&potentiallyNewInput](const InputSpec& other) {
return DataSpecUtils::includes(other, potentiallyNewInput);
};
if (std::none_of(declaredInputs.begin(), declaredInputs.end(), declaredInputIsBroader)) {
declaredInputs.push_back(potentiallyNewInput);
}
}
}
// add timer input
header::DataDescription timerDescription;
timerDescription.runtimeInit(("TIMER-" + mName).substr(0, 16).c_str());
declaredInputs.emplace_back(InputSpec{"timer-stats", "DS", timerDescription, 0, Lifetime::Timer});
return declaredInputs;
}
Outputs Dispatcher::getOutputSpecs()
{
Outputs declaredOutputs;
for (const auto& policy : mPolicies) {
for (const auto& [_policyInput, policyOutput] : policy->getPathMap()) {
(void)_policyInput;
// In principle Data Sampling Policies should have different outputs.
// We may add a check to be very gentle with users.
declaredOutputs.push_back(policyOutput);
}
}
return declaredOutputs;
}
framework::Options Dispatcher::getOptions()
{
o2::framework::Options options;
for (const auto& policy : mPolicies) {
if (!policy->getFairMQOutputChannel().empty()) {
if (!options.empty()) {
throw std::runtime_error("Maximum one policy with raw FairMQ channel is allowed, more have been declared.");
}
options.push_back({"channel-config", VariantType::String, policy->getFairMQOutputChannel().c_str(), {"Out-of-band channel config"}});
LOG(DEBUG) << " - registering output FairMQ channel '" << policy->getFairMQOutputChannel() << "'";
}
}
options.push_back({"period-timer-stats", framework::VariantType::Int, 10 * 1000000, {"Dispatcher's stats timer period"}});
return options;
}
size_t Dispatcher::numberOfPolicies()
{
return mPolicies.size();
}
} // namespace o2::utilities