Belle II Software development
storagerecord.cc
1/**************************************************************************
2 * basf2 (Belle II Analysis Software Framework) *
3 * Author: The Belle II Collaboration *
4 * *
5 * See git log for contributors and copyright holders. *
6 * This file is licensed under LGPL-3.0, see LICENSE.md. *
7 **************************************************************************/
8#include <unistd.h>
9#include <cstdlib>
10#include <sys/stat.h>
11#include <fcntl.h>
12
13#include <framework/logging/Logger.h>
14#include <framework/pcore/EvtMessage.h>
15
16#include <daq/storage/SharedEventBuffer.h>
17
18#include <daq/slc/psql/PostgreSQLInterface.h>
19
20#include <daq/slc/database/DBHandlerException.h>
21
22#include <daq/slc/readout/RunInfoBuffer.h>
23
24#include <daq/slc/base/ConfigFile.h>
25#include <daq/slc/base/Date.h>
26#include <daq/slc/base/StringUtil.h>
27
28#include <cstdio>
29#include <cstring>
30#include <fstream>
31#include <iostream>
32#include <signal.h>
33#include <sys/statvfs.h>
34#include <zlib.h>
35
36using namespace Belle2;
37
38const unsigned long long GB = 1000 * 1024 * 1024;
39const unsigned long long MAX_FILE_SIZE = 8 * GB;
40const char* g_table = "datafiles";
41unsigned int g_streamersize = 0;
42char* g_streamerinfo = new char[1000000];
43int g_diskid = 0;
44std::string g_file_diskid;
45int g_runno = 0;
46int g_expno = 0;
47bool g_is_arich = false;
48
49class FileHandler {
50
51public:
52 FileHandler(DBInterface* db, const std::string& runtype,
53 const char* host, const char* dbtmp)
54 : m_db(db), m_runtype(runtype), m_host(host), m_dbtmp(dbtmp)
55 {
56 m_file = -1;
57 m_id = -1;
58 m_filesize = 0;
59 m_fileid = 0;
60 m_diskid = 1;
61 m_expno = -1;
62 m_runno = -1;
63 m_nevents = 0;
64 m_chksum = 0;
65 }
66 ~FileHandler() throw()
67 {
68 }
69
70public:
71 int getDiskId() { return m_diskid; }
72 int getFileId() { return m_fileid; }
73
74public:
75 int open(const std::string& dir, int ndisks, int expno, int runno, int fileid)
76 {
77 m_filesize = 0;
78 m_fileid = 0;
79 m_diskid = 1;
80 m_chksum = 1;
81 m_nevents = 0;
82 m_filesize = 0;
83 m_expno = (g_expno > 0) ? g_expno : expno;
84 m_runno = (g_runno > 0) ? g_runno : runno;
85 m_fileid = fileid;
86 bool available = false;
87 char filename[1024];
88 struct statvfs statfs;
89 if (g_diskid > 0) {
90 m_diskid = g_diskid;
91 available = true;
92 } else {
93 {
94 int diskid = 1;
95 std::ifstream fin(g_file_diskid.c_str());
96 fin >> diskid;
97 m_diskid = diskid;
98 }
99 for (int i = 0; i < ndisks; i++) {
100 sprintf(filename, "%s%02d", dir.c_str(), m_diskid);
101 statvfs(filename, &statfs);
102 float usage = 1 - ((float)statfs.f_bfree / statfs.f_blocks);
103 sprintf(filename, "%s%02d/storage/full_flag", dir.c_str(), m_diskid);
104 std::ifstream fin(filename);
105 int flag = 0;
106 fin >> flag;
107 fin.close();
108 /*
109 if (usage < 0.1) {
110 fin.close();
111 //::unlink(filename);
112 if (flag == 1) {
113 std::cout << "[DEBUG] disk : " << m_diskid << " is available again (full_flag removed)" << std::endl;
114 }
115 available = true;
116 std::cout << "[DEBUG] disk : " << m_diskid << " is available" << std::endl;
117 break;
118 } else
119 */
120 if (usage < 0.7) {
121 if (flag != 1) {
122 available = true;
123 std::cout << "[DEBUG] disk : " << m_diskid << " is available" << std::endl;
124 break;
125 }
126 std::cout << "[DEBUG] disk : " << m_diskid << " is with full_flag" << std::endl;
127 } else {
128 std::ofstream fout(filename);
129 fout << 1;
130 fout.close();
131 B2WARNING("disk-" << m_diskid << " is full " << usage);
132 }
133 m_diskid++;
134 if (m_diskid > ndisks) m_diskid = 1;
135 }
136 }
137 if (!available) {
138 B2FATAL("No disk available for writing " << __FILE__ << ":" << __LINE__);
139 exit(1);
140 }
141 std::string filedir = dir + StringUtil::form("%02d/storage/%4.4d/%5.5d/", m_diskid, expno, runno);
142 system(("mkdir -p " + filedir).c_str());
143 m_filename = StringUtil::form("%s.%4.4d.%5.5d.%s.f%5.5d.sroot",
144 m_runtype.c_str(), expno, runno, m_host.c_str(), m_fileid);
145 m_path = filedir + m_filename;
146 m_file = ::open(m_path.c_str(), O_WRONLY | O_CREAT | O_EXCL, 0664);
147 g_diskid = m_diskid;
148 std::ofstream fout(g_file_diskid.c_str());
149 fout << g_diskid;
150 if (m_file < 0) {
151 B2FATAL("Failed to open file : " << m_path);
152 exit(1);
153 }
154 try {
155 m_db->connect();
156 m_db->execute("insert into %s (name, path, host, label, expno, runno, fileno, nevents, chksum, size) "
157 "values ('%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0);",
158 g_table, m_filename.c_str(), m_path.c_str(), m_host.c_str(),
159 m_runtype.c_str(), m_expno, m_runno, m_fileid);
160 } catch (const DBHandlerException& e) {
161 B2WARNING(e.what());
162 }
163 write(g_streamerinfo, g_streamersize, true);
164 B2INFO("New file " << m_path << " is opened");
165
166 return m_id;
167 }
168
169 void close()
170 {
171 if (m_file > 0) {
172 std::cout << "[DEBUG] File closed" << std::endl;
173 ::close(m_file);
174 try {
175 struct stat st;
176 stat(m_path.c_str(), &st);
177 std::string d = Date(st.st_mtime).toString();
178 m_db->connect();
179 m_db->execute("update %s set time_close = '%s', chksum = %lu, nevents = %lu, "
180 "size = %lu where name = '%s' and host = '%s';",
181 g_table, d.c_str(), m_chksum, m_nevents, m_filesize,
182 m_filename.c_str(), m_host.c_str());
183 } catch (const DBHandlerException& e) {
184 B2WARNING(e.what());
185 }
186 m_db->close();
187 }
188 }
189
190 int write(char* evtbuf, int nbyte, bool isstreamer = false)
191 {
192 m_chksum = adler32(m_chksum, reinterpret_cast<unsigned char*>(evtbuf), nbyte);
193 int ret = ::write(m_file, evtbuf, nbyte);
194 m_filesize += nbyte;
195 if (!isstreamer) {
196 m_nevents++;
197 }
198 return ret;
199 }
200
201 operator bool()
202 {
203 return m_file > 0;
204 }
205
206private:
207 DBInterface* m_db;
208 std::string m_runtype;
209 std::string m_host;
210 std::string m_dbtmp;
211 int m_id;
212 std::string m_filename;
213 std::string m_path;
214 int m_diskid;
215 int m_fileid;
216 int m_file;
217 int m_expno;
218 int m_runno;
219 unsigned long long m_filesize;
220 unsigned long long m_chksum;
221 unsigned long long m_nevents;
222};
223
224FileHandler* g_file = NULL;
225
226void signalHandler(int)
227{
228 if (g_file) g_file->close();
229 exit(1);
230}
231
232int main(int argc, char** argv)
233{
234 if (argc < 8) {
235 printf("%s : <ibufname> <ibufsize> <hostname> <runtype> <path> <ndisk> "
236 "<filepath_dbtmp> [<obufname> <obufsize> nodename, nodeid]\n", argv[0]);
237 return 1;
238 }
239 const unsigned interval = 1;
240 const char* ibufname = argv[1];
241 const int ibufsize = atoi(argv[2]);
242 const char* hostname = argv[3];
243 const char* runtype = argv[4];
244 const bool not_record = std::string(runtype).find(std::string("null")) != std::string::npos;
245 const char* path = argv[5];
246 const int ndisks = atoi(argv[6]);
247 const char* file_dbtmp = argv[7];
248 const int obufsize = (argc > 8) ? atoi(argv[9]) : -1;
249 const char* nodename = (argc > 9) ? argv[10] : "";
250 g_is_arich = StringUtil::find(runtype, "arich");
251 const int nodeid = (argc > 10) ? atoi(argv[11]) : -1;
252 const unsigned int ninput = (argc > 11) ? atoi(argv[12]) : 1;
253 g_file_diskid = StringUtil::form("/tmp/%s_diskid", nodename);
254
255 RunInfoBuffer info;
256 const bool use_info = nodeid >= 0;
257 if (use_info) {
258 info.open(nodename, nodeid);
259 }
260 SharedEventBuffer ibuf[10];
261 for (unsigned int ib = 0; ib < ninput; ib++) {
262 ibuf[ib].open(StringUtil::form("%s_%d", ibufname, ib), ibufsize * 1000000);//, true);
263 }
264 signal(SIGINT, signalHandler);
265 signal(SIGKILL, signalHandler);
266 ConfigFile config("slowcontrol");
267 PostgreSQLInterface* db = new PostgreSQLInterface(config.get("database.host"),
268 config.get("database.dbname"),
269 config.get("database.user"),
270 config.get("database.password"),
271 config.getInt("database.port"));
273 if (obufsize > 0) obuf.open(argv[8], obufsize * 1000000);//, true);
274 if (use_info) info.reportReady();
275 B2DEBUG(1, "started recording.");
276 unsigned long long nbyte_out = 0;
277 unsigned int count_out = 0;
278 unsigned int expno = 0;
279 unsigned int runno = 0;
280 unsigned int subno = 0;
281 int* evtbuf = new int[10000000];
282 g_file = new FileHandler(db, runtype, hostname, file_dbtmp);
283 FileHandler& file(*g_file);
284 int ecount = 0;
285 bool newrun = false;
286 unsigned int fileid = 0;
287 struct dataheader {
288 // int nword; // unused
289 int type;
290 unsigned int expno;
291 unsigned int runno;
292 } hd;
293 g_streamersize = 0;
294 while (true) {
295 if (use_info) info.reportRunning();
296 if (g_is_arich) {
297 if (g_runno == 0) {
298 while ((g_runno = info.getRunNumber()) <= 0) {
299 usleep(500);
300 }
301 g_expno = info.getExpNumber();
302 std::cout << "[DEBUG] expno = " << g_expno << ", runno =" << g_runno << std::endl;
303 }
304 }
305 for (unsigned int ib = 0; ib < ninput; ib++) {
306 ibuf[ib].lock();
307 ibuf[ib].read(reinterpret_cast<int*>(&hd), true, true);
308 ibuf[ib].read(evtbuf, true, true);
309 ibuf[ib].unlock();
310 int nbyte = evtbuf[0];
311 int nword = (nbyte - 1) / 4 + 1;
312 bool isnew = false;
313 if (hd.type == MSG_STREAMERINFO) {
314 memcpy(g_streamerinfo, evtbuf, nbyte);
315 g_streamersize = nbyte;
316 }
317 if (expno > hd.expno || runno > hd.runno) {
318 B2WARNING("The old run was detected => discard event exp = " << hd.expno <<
319 " (" << expno << "), runno" << hd.runno << "(" << runno << ")");
320 continue;
321 }
322 if (!newrun || expno < hd.expno || runno < hd.runno) {
323 newrun = true;
324 isnew = true;
325 expno = hd.expno;
326 runno = hd.runno;
327 fileid = 0;
328 if (use_info) {
329 info.setExpNumber(expno);
330 info.setRunNumber(runno);
331 info.setSubNumber(subno);
332 info.setInputCount(0);
333 info.setInputNBytes(0);
334 info.setOutputCount(0);
335 info.setOutputNBytes(0);
336 nbyte_out = 0;
337 count_out = 0;
338 }
339 obuf.lock();
340 SharedEventBuffer::Header* oheader = obuf.getHeader();
341 oheader->expno = expno;
342 oheader->runno = runno;
343 obuf.unlock();
344 if (!not_record) {
345 if (file) {
346 file.close();
347 }
348 std::string filename = StringUtil::form("%s%02d", path, g_diskid);
349 struct statvfs statfs;
350 statvfs(filename.c_str(), &statfs);
351 float usage = 1 - ((float)statfs.f_bfree / statfs.f_blocks);
352 if (usage > 0.9) g_diskid = 0;
353 file.open(path, ndisks, expno, runno, fileid);
354 ecount = 0;
355 nbyte_out += nbyte;
356 fileid++;
357 }
358 continue;
359 }
360 if (use_info) {
361 info.addInputCount(1);
362 info.addInputNBytes(nbyte);
363 }
364 if (hd.type == MSG_STREAMERINFO) {
365 continue;
366 }
367 if (file) {
368 if (nbyte_out > MAX_FILE_SIZE) {
369 file.close();
370 nbyte_out = 0;
371 if (g_diskid > 0) {
372 std::string filename = StringUtil::form("%s%02d", path, g_diskid);
373 struct statvfs statfs;
374 statvfs(filename.c_str(), &statfs);
375 float usage = 1 - ((float)statfs.f_bfree / statfs.f_blocks);
376 if (usage > 0.9) {
377 B2WARNING("disk-" << g_diskid << " is already full. Stopping Run#" << runno);
378 std::cout << "[STOP=RUNCONTROL]" << std::endl;
379 continue;
380 }
381 }
382 file.open(path, ndisks, expno, runno, fileid);
383 ecount = 0;
384 fileid++;
385 }
386 file.write(reinterpret_cast<char*>(evtbuf), nbyte);
387 nbyte_out += nbyte;
388 if (use_info) {
389 info.addOutputCount(1);
390 info.addOutputNBytes(nbyte);
391 info.get()->reserved[0] = file.getFileId();
392 info.get()->reserved[1] = file.getDiskId();
393 info.get()->reserved_f[0] = (float)info.getOutputNBytes() / 1024. / 1024.;
394 }
395 } else {
396 if (!ecount) {
397 B2WARNING("no run was initialzed for recording : " << hd.expno << "." << hd.runno);
398 }
399 ecount = 1;
400 }
401 // Dump data into output buffer
402 // cppcheck-suppress moduloofone ; interval is a tuning knob
403 // cppcheck-suppress knownConditionTrueFalse ; interval is a tuning knob
404 if (!isnew && obufsize > 0 && count_out % interval == 0 && obuf.isWritable(nword)) {
405 obuf.write(evtbuf, nword, true);
406 }
407 count_out++;
408 }
409 }
410 return 0;
411}
412
Abstract base class for different kinds of events.