CbmRoot
Loading...
Searching...
No Matches
CbmMQTsaSampler.cxx
Go to the documentation of this file.
1/* Copyright (C) 2017-2019 GSI Helmholtzzentrum fuer Schwerionenforschung, Darmstadt
2 SPDX-License-Identifier: GPL-3.0-only
3 Authors: Florian Uhlig [committer] */
4
11
12
13#include "CbmMQTsaSampler.h"
14
15#include "CbmMQDefs.h"
16
17#include "TimesliceInputArchive.hpp"
18#include "TimesliceSubscriber.hpp"
19
20#include "FairMQLogger.h"
21#include "FairMQProgOptions.h" // device->fConfig
22
23#include <boost/algorithm/string.hpp>
24#include <boost/archive/binary_oarchive.hpp>
25#include <boost/filesystem.hpp>
26#include <boost/regex.hpp>
27
28namespace filesys = boost::filesystem;
29
30#include <algorithm>
31#include <chrono>
32#include <cstdio>
33#include <ctime>
34#include <string>
35#include <thread> // this_thread::sleep_for
36
37using namespace std;
38
39#include <stdexcept>
40
41struct InitTaskError : std::runtime_error {
42 using std::runtime_error::runtime_error;
43};
44
46 : FairMQDevice()
48 , fFileName("")
49 , fDirName("")
51 , fFileCounter(0)
52 , fHost("")
53 , fPort(0)
54 , fTSNumber(0)
55 , fTSCounter(0)
57 , fSource(nullptr)
58 , fTime()
59{
60}
61
63try {
64 // Get the values from the command line options (via fConfig)
65 fFileName = fConfig->GetValue<string>("filename");
66 fDirName = fConfig->GetValue<string>("dirname");
67 fHost = fConfig->GetValue<string>("flib-host");
68 fPort = fConfig->GetValue<uint64_t>("flib-port");
69 fMaxTimeslices = fConfig->GetValue<uint64_t>("max-timeslices");
70
71 // Check which input is defined
72 // Posibilities
73 // filename && ! dirname : single file
74 // filename with wildcards && diranme : all files with filename regex in the directory
75 // host && port : connect to the flim server
76
77 bool isGoodInputCombi {false};
78 if (0 != fFileName.size() && 0 == fDirName.size() && 0 == fHost.size() && 0 == fPort) {
79 isGoodInputCombi = true;
80 // Create a Path object from given path string
81 filesys::path pathObj(fFileName);
82 if (!filesys::is_regular_file(pathObj)) { throw InitTaskError("Passed file name is no valid file"); }
83 fInputFileList.push_back(fFileName);
84 LOG(info) << "Filename: " << fFileName;
85 }
86 else if (0 != fFileName.size() && 0 != fDirName.size() && 0 == fHost.size() && 0 == fPort) {
87 isGoodInputCombi = true;
88 filesys::path pathObj = fDirName;
89 if (!filesys::is_directory(pathObj)) { throw InitTaskError("Passed directory name is no valid directory"); }
90 if (fFileName.find("*") == std::string::npos) {
91 // Normal file without wildcards
92 pathObj += fFileName;
93 if (!filesys::is_regular_file(pathObj)) { throw InitTaskError("Passed file name is no valid file"); }
94 fInputFileList.push_back(pathObj.string());
95 LOG(info) << "Filename: " << fInputFileList[0];
96 }
97 else {
98 std::vector<filesys::path> v;
99
100 // escape "." which have a special meaning in regex
101 // change "*" to ".*" to find any number
102 // e.g. tofget4_hd2018.*.tsa => tofget4_hd2018\..*\.tsa
103 boost::replace_all(fFileName, ".", "\\.");
104 boost::replace_all(fFileName, "*", ".*");
105
106 // create regex
107 const boost::regex my_filter(fFileName);
108
109 // loop over all files in input directory
110 for (auto&& x : filesys::directory_iterator(pathObj)) {
111 // Skip if not a file
112 if (!boost::filesystem::is_regular_file(x)) continue;
113
114 // Skip if no match
115 // x.path().leaf().string() means get from directory iterator the
116 // current entry as filesys::path, from this extract the leaf
117 // filename or directory name and convert it to a string to be
118 // used in the regex:match
119 boost::smatch what;
120 if (!boost::regex_match(x.path().string(), what, my_filter)) continue;
121
122 v.push_back(x.path());
123 }
124
125 // sort the files which match the regex in increasing order
126 // (hopefully)
127 std::sort(v.begin(), v.end());
128
129 for (auto&& x : v)
130 fInputFileList.push_back(x.string());
131
132 LOG(info) << "The following files will be used in this order.";
133 for (auto&& x : v)
134 LOG(info) << " " << x;
135 }
136 }
137 else if (0 == fFileName.size() && 0 == fDirName.size() && 0 != fHost.size() && 0 != fPort) {
138 isGoodInputCombi = true;
139 LOG(info) << "Host: " << fHost;
140 LOG(info) << "Port: " << fPort;
141 }
142 else {
143 isGoodInputCombi = false;
144 }
145
146 if (!isGoodInputCombi) {
147 throw InitTaskError("Wrong combination of inputs. Either file or wildcard file + directory "
148 "or host + port are allowed combination.");
149 }
150
151
152 LOG(info) << "MaxTimeslices: " << fMaxTimeslices;
153
154 // Get the information about created channels from the device
155 // Check if the defined channels from the topology (by name)
156 // are in the list of channels which are possible/allowed
157 // for the device
158 // The idea is to check at initilization if the devices are
159 // properly connected. For the time beeing this is done with a
160 // nameing convention. It is not avoided that someone sends other
161 // data on this channel.
162 int noChannel = fChannels.size();
163 LOG(info) << "Number of defined output channels: " << noChannel;
164 for (auto const& entry : fChannels) {
165 LOG(info) << "Channel name: " << entry.first;
166 if (!IsChannelNameAllowed(entry.first)) throw InitTaskError("Channel name does not match.");
167 }
168
169 for (auto const& value : fComponentsToSend) {
170 LOG(info) << "Value : " << value;
171 if (value > 1) {
172 throw InitTaskError("Sending same data to more than one output channel "
173 "not implemented yet.");
174 }
175 }
176
177 if (0 == fFileName.size() && 0 != fHost.size()) {
178 std::string connector = "tcp://" + fHost + ":" + std::to_string(fPort);
179 LOG(info) << "Open TSPublisher at " << connector;
180 fSource = new fles::TimesliceSubscriber(connector, 1);
181 if (!fSource) { throw InitTaskError("Could not connect to publisher."); }
182 }
183 else {
184 if (false == OpenNextFile()) {
185 throw InitTaskError("Could not open the first input file in the list, Doing nothing!");
186 }
187 }
188
189 fTime = std::chrono::steady_clock::now();
190}
191catch (InitTaskError& e) {
192 LOG(error) << e.what();
193 // Wrapper defined in CbmMQDefs.h to support different FairMQ versions
195}
196
198{
199 // First Close and delete existing source
200 if (nullptr != fSource) delete fSource;
201
202 if (fInputFileList.size() > 0) {
204 fInputFileList.erase(fInputFileList.begin());
205 LOG(info) << "Open the Flib input file " << fFileName;
206 filesys::path pathObj(fFileName);
207 if (!filesys::is_regular_file(pathObj)) {
208 LOG(error) << "Input file " << fFileName << " doesn't exist.";
209 return false;
210 }
211 fSource = new fles::TimesliceInputArchive(fFileName);
212 if (!fSource) {
213 LOG(error) << "Could not open input file.";
214 return false;
215 }
216 }
217 else {
218 LOG(info) << "End of files list reached.";
219 return false;
220 }
221 return true;
222}
223
224bool CbmMQTsaSampler::IsChannelNameAllowed(std::string channelName)
225{
226
227 for (auto const& entry : fAllowedChannels) {
228 std::size_t pos1 = channelName.find(entry);
229 if (pos1 != std::string::npos) {
230 const vector<std::string>::const_iterator pos =
231 std::find(fAllowedChannels.begin(), fAllowedChannels.end(), entry);
232 const vector<std::string>::size_type idx = pos - fAllowedChannels.begin();
233 LOG(info) << "Found " << entry << " in " << channelName;
234 LOG(info) << "Channel name " << channelName << " found in list of allowed channel names at position " << idx;
235 fComponentsToSend[idx]++;
236 fChannelsToSend[idx].push_back(channelName);
237 return true;
238 }
239 }
240 LOG(info) << "Channel name " << channelName << " not found in list of allowed channel names.";
241 LOG(error) << "Stop device.";
242 return false;
243}
244
246{
247
248
249 auto timeslice = fSource->get();
250 if (timeslice) {
252 fTSCounter++;
253 if (fTSCounter % 10000 == 0) LOG(info) << "Analyse Event " << fTSCounter;
254
255
256 const fles::Timeslice& ts = *timeslice;
257 // auto tsIndex = ts.index();
258
259
260 LOG(info) << "Found " << ts.num_components() << " different components in timeslice";
261
262
263 CheckTimeslice(ts);
264
265 for (unsigned int nrComp = 0; nrComp < ts.num_components(); ++nrComp) {
266 CreateAndSendComponent(ts, nrComp);
267 }
268 return true;
269 }
270 else {
271 if (false == OpenNextFile()) {
272 CalcRuntime();
273 return false;
274 }
275 else {
276 return true;
277 }
278 }
279 }
280 else {
281 if (false == OpenNextFile()) {
282 CalcRuntime();
283 return false;
284 }
285 else {
286 return true;
287 }
288 }
289}
290
291bool CbmMQTsaSampler::CreateAndSendComponent(const fles::Timeslice& ts, int nrComp)
292{
293
294 // Check if component has to be send. If the corresponding channel
295 // is connected create the new timeslice and send it to the
296 // correct channel
297
298 LOG(info) << "SysID: " << static_cast<int>(ts.descriptor(nrComp, 0).sys_id);
299 const vector<int>::const_iterator pos =
300 std::find(fSysId.begin(), fSysId.end(), static_cast<int>(ts.descriptor(nrComp, 0).sys_id));
301 if (pos != fSysId.end()) {
302 const vector<std::string>::size_type idx = pos - fSysId.begin();
303 if (fComponentsToSend[idx] > 0) {
304 LOG(info) << "Create timeslice component for link " << nrComp;
305
306 fles::StorableTimeslice component {static_cast<uint32_t>(ts.num_core_microslices()), ts.index()};
307 component.append_component(ts.num_microslices(0));
308
309 for (size_t m = 0; m < ts.num_microslices(nrComp); ++m) {
310 component.append_microslice(0, m, ts.descriptor(nrComp, m), ts.content(nrComp, m));
311 }
312 if (!SendData(component, idx)) return false;
313 return true;
314 }
315 }
316 return true;
317}
318
319bool CbmMQTsaSampler::SendData(const fles::StorableTimeslice& component, int idx)
320{
321 // serialize the timeslice and create the message
322 std::stringstream oss;
323 boost::archive::binary_oarchive oa(oss);
324 oa << component;
325 std::string* strMsg = new std::string(oss.str());
326
327 FairMQMessagePtr msg(NewMessage(
328 const_cast<char*>(strMsg->c_str()), // data
329 strMsg->length(), // size
330 [](void* /*data*/, void* object) { delete static_cast<std::string*>(object); },
331 strMsg)); // object that manages the data
332
333 // TODO: Implement sending same data to more than one channel
334 // Need to create new message (copy message??)
335 if (fComponentsToSend[idx] > 1) { LOG(info) << "Need to copy FairMessage"; }
336
337 // in case of error or transfer interruption,
338 // return false to go to IDLE state
339 // successfull transfer will return number of bytes
340 // transfered (can be 0 if sending an empty message).
341
342 LOG(info) << "Send data to channel " << fChannelsToSend[idx][0];
343 if (Send(msg, fChannelsToSend[idx][0]) < 0) {
344 LOG(error) << "Problem sending data";
345 return false;
346 }
347
349 LOG(info) << "Send message " << fMessageCounter << " with a size of " << msg->GetSize();
350
351 return true;
352}
353
354
356
358{
359 std::chrono::duration<double> run_time = std::chrono::steady_clock::now() - fTime;
360
361 LOG(info) << "Runtime: " << run_time.count();
362 LOG(info) << "No more input data";
363}
364
365
366void CbmMQTsaSampler::PrintMicroSliceDescriptor(const fles::MicrosliceDescriptor& mdsc)
367{
368 LOG(info) << "Header ID: Ox" << std::hex << static_cast<int>(mdsc.hdr_id) << std::dec;
369 LOG(info) << "Header version: Ox" << std::hex << static_cast<int>(mdsc.hdr_ver) << std::dec;
370 LOG(info) << "Equipement ID: " << mdsc.eq_id;
371 LOG(info) << "Flags: " << mdsc.flags;
372 LOG(info) << "Sys ID: Ox" << std::hex << static_cast<int>(mdsc.sys_id) << std::dec;
373 LOG(info) << "Sys version: Ox" << std::hex << static_cast<int>(mdsc.sys_ver) << std::dec;
374 LOG(info) << "Microslice Idx: " << mdsc.idx;
375 LOG(info) << "Checksum: " << mdsc.crc;
376 LOG(info) << "Size: " << mdsc.size;
377 LOG(info) << "Offset: " << mdsc.offset;
378}
379
380bool CbmMQTsaSampler::CheckTimeslice(const fles::Timeslice& ts)
381{
382 if (0 == ts.num_components()) {
383 LOG(error) << "No Component in TS " << ts.index();
384 return 1;
385 }
386 LOG(info) << "Found " << ts.num_components() << " different components in timeslice";
387
388 for (size_t c = 0; c < ts.num_components(); ++c) {
389 LOG(info) << "Found " << ts.num_microslices(c) << " microslices in component " << c;
390 LOG(info) << "Component " << c << " has a size of " << ts.size_component(c) << " bytes";
391 LOG(info) << "Component " << c << " has the system id 0x" << std::hex
392 << static_cast<int>(ts.descriptor(c, 0).sys_id) << std::dec;
393 LOG(info) << "Component " << c << " has the system id 0x" << static_cast<int>(ts.descriptor(c, 0).sys_id);
394
395 /*
396 for (size_t m = 0; m < ts.num_microslices(c); ++m) {
397 PrintMicroSliceDescriptor(ts.descriptor(c,m));
398 }
399*/
400 }
401
402 return true;
403}
fscal v[fmask::Size]
Definition KfSimdPseudo.h:4
uint64_t fMaxTimeslices
bool CreateAndSendComponent(const fles::Timeslice &, int)
bool SendData(const fles::StorableTimeslice &component)
fles::TimesliceSource * fSource
std::chrono::steady_clock::time_point fTime
uint64_t fMessageCounter
virtual void InitTask()
std::vector< std::vector< std::string > > fChannelsToSend
bool CheckTimeslice(const fles::Timeslice &ts)
std::string fHost
std::vector< std::string > fAllowedChannels
std::string fFileName
void PrintMicroSliceDescriptor(const fles::MicrosliceDescriptor &mdsc)
std::string fDirName
std::vector< std::string > fInputFileList
List of input files.
bool IsChannelNameAllowed(std::string)
std::vector< int > fComponentsToSend
virtual bool ConditionalRun()
std::vector< int > fSysId
void ChangeState(FairMQDevice *device, cbm::mq::Transition transition)
Definition CbmMQDefs.h:26
Hash for CbmL1LinkKey.