Debian Codegraph @

packages/seacas/libraries/ioss/src/heartbeat/Iohb_DatabaseIO.C

raw
1 // Copyright(C) 1999-2024 National Technology & Engineering Solutions
2 // of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
3 // NTESS, the U.S. Government retains certain rights in this software.
4 //
5 // See packages/seacas/LICENSE for details
6
7 #include "Ioss_CodeTypes.h"
8 #include "heartbeat/Iohb_DatabaseIO.h"
9 #include "heartbeat/Iohb_Layout.h"
10 #include <cassert>
11 #include <cstddef>
12 #include <ctime>
13 #include <fmt/ostream.h>
14 #include <fstream>
15 #include <string>
16 #include <vector>
17
18 #include "Ioss_DBUsage.h"
19 #include "Ioss_DatabaseIO.h"
20 #include "Ioss_EntityType.h"
21 #include "Ioss_Field.h"
22 #include "Ioss_IOFactory.h"
23 #include "Ioss_ParallelUtils.h"
24 #include "Ioss_Property.h"
25 #include "Ioss_PropertyManager.h"
26 #include "Ioss_State.h"
27 #include "Ioss_Utils.h"
28
29 namespace {
30 std::string time_stamp(const std::string &format)
31 {
32 if (format.empty()) {
33 return {""};
34 }
35 const int length = 256;
36 static char time_string[length];
37
38 time_t calendar_time = time(nullptr);
39 struct tm *local_time = localtime(&calendar_time);
40
41 size_t error = strftime(time_string, length, format.c_str(), local_time);
42 if (error != 0) {
43 time_string[length - 1] = '\0';
44 return {time_string};
45 }
46 return {"[ERROR]"};
47 }
48
49 std::ostream *open_stream(const std::string &filename, bool *needs_delete, bool append_file)
50 {
51 // A little weirdness and ambiguity is possible here. We want to
52 // minimize the number of commands, but maximize the
53 // functionality. For example, we want to be able to specify output
54 // to existing streams (cout/stdout, cerr/stderr, outputP0), files,
55 // sockets, XML-RPC?, SOAP?. However, we want to be able to specify
56 // this with a single command.
57 // So..., we first check for some 'reserved' stream names. These
58 // are the 'cout, stdout, cerr, stderr, output, outputP0' type.
59 // Note that this means the user can't specify a file name of
60 // 'cerr', but that shouldn't be too much of a hardship. [If it is,
61 // we can devise a syntax as: 'FILE:cout' or do a './cout'
62
63 std::ostream *log_stream = nullptr;
64 *needs_delete = false;
65 if (filename == "cout" || filename == "stdout") {
66 log_stream = &std::cout;
67 }
68 else if (filename == "cerr" || filename == "stderr") {
69 log_stream = &std::cerr; // This is also default if nothing specified
70 }
71 else if (filename == "output" || filename == "outputP0") {
72 log_stream = &std::cout; // This should be sierra::Env::outputP0(), but not
73 // available during transition to stk...
74 }
75 else if (filename == "clog" || filename == "log") {
76 log_stream = &std::clog; // Same as cerr, but not flushed automatically.
77 }
78 else {
79 // Open the file (on processor 0 only) Might need to do
80 // something better here if we want to share streams among
81 // different heartbeats or logging mechanisms. Need perhaps a
82 // 'logger' class which handles sharing and destruction...
83 std::ofstream *tmp = nullptr;
84 if (append_file) {
85 tmp = new std::ofstream(filename, std::ios::out | std::ios::app);
86 }
87 else {
88 tmp = new std::ofstream(filename);
89 }
90 if (!tmp->is_open()) {
91 delete tmp;
92 }
93 else {
94 log_stream = tmp;
95 *needs_delete = true;
96 }
97 }
98 return log_stream;
99 }
100 } // namespace
101
102 namespace Iohb {
103
104 // ========================================================================
105 const IOFactory *IOFactory::factory()
106 {
107 static IOFactory registerThis;
108 return &registerThis;
109 }
110
111 IOFactory::IOFactory() : Ioss::IOFactory("heartbeat") {}
112
113 Ioss::DatabaseIO *IOFactory::make_IO(const std::string &filename, Ioss::DatabaseUsage db_usage,
114 Ioss_MPI_Comm communicator,
115 const Ioss::PropertyManager &props) const
116 {
117 return new DatabaseIO(nullptr, filename, db_usage, communicator, props);
118 }
119
120 // ========================================================================
121 DatabaseIO::DatabaseIO(Ioss::Region *region, const std::string &filename,
122 Ioss::DatabaseUsage db_usage, Ioss_MPI_Comm communicator,
123 const Ioss::PropertyManager &props)
124 : Ioss::DatabaseIO(region, filename, db_usage, communicator, props)
125 {
126 timeLastFlush_ = time(nullptr);
127 dbState = Ioss::STATE_UNKNOWN;
128 }
129
130 DatabaseIO::~DatabaseIO()
131 {
132 if (streamNeedsDelete && (logStream != nullptr)) {
133 delete logStream;
134 }
135 }
136
137 void DatabaseIO::initialize() const
138 {
139 if (!initialized_) {
140 auto *new_this = const_cast<DatabaseIO *>(this);
141
142 if (properties.exists("FILE_FORMAT")) {
143 std::string format = properties.get("FILE_FORMAT").get_string();
144 if (Ioss::Utils::str_equal(format, "spyhis")) {
145 new_this->fileFormat = Iohb::Format::SPYHIS;
146 }
147 else if (Ioss::Utils::str_equal(format, "csv")) {
148 new_this->fileFormat = Iohb::Format::CSV;
149 }
150 else if (Ioss::Utils::str_equal(format, "ts_csv")) {
151 new_this->fileFormat = Iohb::Format::TS_CSV;
152 }
153 else if (Ioss::Utils::str_equal(format, "text")) {
154 new_this->fileFormat = Iohb::Format::TEXT;
155 }
156 else if (Ioss::Utils::str_equal(format, "ts_text")) {
157 new_this->fileFormat = Iohb::Format::TS_TEXT;
158 }
159 }
160
161 bool append = open_create_behavior() == Ioss::DB_APPEND;
162
163 // Try to open file...
164 new_this->logStream = nullptr;
165 if (util().parallel_rank() == 0) {
166 new_this->logStream = open_stream(get_filename(), &(new_this->streamNeedsDelete), append);
167
168 if (new_this->logStream == nullptr) {
169 IOSS_ERROR(fmt::format("ERROR: Could not create heartbeat file '{}'\n", get_filename()));
170 }
171 }
172
173 // "Predefined" formats... (put first so can modify settings if wanted)
174 if (fileFormat == Iohb::Format::CSV) {
175 new_this->addTimeField = true;
176 new_this->showLegend = true;
177 new_this->showLabels = false;
178 new_this->separator_ = ", ";
179 }
180 else if (fileFormat == Iohb::Format::TS_CSV) {
181 new_this->addTimeField = true;
182 new_this->showLegend = true;
183 new_this->showLabels = false;
184 new_this->separator_ = ", ";
185 new_this->tsFormat = defaultTsFormat;
186 }
187 else if (fileFormat == Iohb::Format::TEXT) {
188 new_this->addTimeField = true;
189 new_this->showLegend = true;
190 new_this->showLabels = false;
191 new_this->separator_ = "\t";
192 }
193 else if (fileFormat == Iohb::Format::TS_TEXT) {
194 new_this->addTimeField = true;
195 new_this->showLegend = true;
196 new_this->showLabels = false;
197 new_this->separator_ = "\t";
198 new_this->tsFormat = defaultTsFormat;
199 }
200
201 // Pull variables from the regions property data...
202 if (properties.exists("FIELD_SEPARATOR")) {
203 new_this->separator_ = properties.get("FIELD_SEPARATOR").get_string();
204 }
205
206 if (properties.exists("FLUSH_INTERVAL")) {
207 new_this->flushInterval_ = properties.get("FLUSH_INTERVAL").get_int();
208 }
209
210 if (properties.exists("HEARTBEAT_FLUSH_INTERVAL")) {
211 new_this->flushInterval_ = properties.get("HEARTBEAT_FLUSH_INTERVAL").get_int();
212 }
213
214 if (properties.exists("TIME_STAMP_FORMAT")) {
215 new_this->tsFormat = properties.get("TIME_STAMP_FORMAT").get_string();
216 }
217
218 bool show_time_stamp = !new_this->tsFormat.empty();
219 Ioss::Utils::check_set_bool_property(properties, "SHOW_TIME_STAMP", show_time_stamp);
220 if (show_time_stamp) {
221 if (tsFormat.empty()) {
222 new_this->tsFormat = defaultTsFormat;
223 }
224 }
225 else {
226 new_this->tsFormat = "";
227 }
228
229 if (properties.exists("PRECISION")) {
230 new_this->precision_ = properties.get("PRECISION").get_int();
231 }
232
233 if (properties.exists("FIELD_WIDTH")) {
234 new_this->fieldWidth_ = properties.get("FIELD_WIDTH").get_int();
235 }
236 else {
237 // +1.xxxxxxe+00 The x count is the precision the "+1.e+00" is the 7
238 new_this->fieldWidth_ = precision_ + 7;
239 }
240
241 Ioss::Utils::check_set_bool_property(properties, "SHOW_LABELS", new_this->showLabels);
242
243 if (!new_this->appendOutput) {
244 Ioss::Utils::check_set_bool_property(properties, "SHOW_LEGEND", new_this->showLegend);
245 }
246
247 Ioss::Utils::check_set_bool_property(properties, "SHOW_TIME_FIELD", new_this->addTimeField);
248
249 if (properties.exists("FULL_PRECISION")) {
250 bool precision = true;
251 Ioss::Utils::check_set_bool_property(properties, "FULL_PRECISION", precision);
252 if (precision) {
253 new_this->precision_ = -1;
254 }
255 }
256
257 // SpyHis format is specific format, so don't override these settings:
258 if (fileFormat == Iohb::Format::SPYHIS) {
259 new_this->addTimeField = true;
260 new_this->showLegend = true;
261 new_this->showLabels = false;
262 new_this->tsFormat = "";
263 }
264
265 if (showLegend) {
266 new_this->legend_ = std::make_unique<Layout>(false, precision_, separator_, fieldWidth_);
267 if (!tsFormat.empty()) {
268 new_this->legend_->add_literal("+");
269 new_this->legend_->add_literal(time_stamp(tsFormat));
270 new_this->legend_->add_literal(" ");
271 }
272
273 if (addTimeField) {
274 if (fileFormat == Iohb::Format::SPYHIS) {
275 new_this->legend_->add_legend("TIME");
276 }
277 else {
278 new_this->legend_->add_legend("Time");
279 }
280 }
281 }
282
283 new_this->initialized_ = true;
284 }
285 }
286
287 bool DatabaseIO::begin_nl(Ioss::State /* state */) { return true; }
288
289 bool DatabaseIO::end_nl(Ioss::State /* state */) { return true; }
290
291 bool DatabaseIO::begin_state_nl(int /* state */, double time)
292 {
293 // If this is the first time, open the output stream and see if user wants a legend
294 initialize();
295
296 layout_ = std::make_unique<Layout>(showLabels, precision_, separator_, fieldWidth_);
297 if (!tsFormat.empty()) {
298 layout_->add_literal("+");
299 layout_->add_literal(time_stamp(tsFormat));
300 layout_->add_literal(" ");
301 }
302
303 if (addTimeField) {
304 layout_->add("TIME", time / timeScaleFactor);
305 }
306
307 return true;
308 }
309
310 void DatabaseIO::flush_database_nl() const
311 {
312 if (myProcessor == 0) {
313 logStream->flush();
314 }
315 }
316
317 bool DatabaseIO::end_state_nl(int /* state */, double /* time */)
318 {
319 if (legend_ != nullptr) {
320 if (fileFormat == Iohb::Format::SPYHIS) {
321 time_t calendar_time = time(nullptr);
322 // ctime include \n; the legend is output twice for SPYHIS.
323 fmt::print(*logStream, "% Sierra SPYHIS Output {}{}\n", ctime(&calendar_time),
324 legend_->layout()); // ctime includes \n
325 }
326
327 fmt::print(*logStream, "{}\n", legend_->layout());
328 legend_.reset();
329 }
330
331 fmt::print(*logStream, "{}\n", layout_->layout());
332 layout_.reset();
333
334 // Flush the buffer to disk...
335 // flush if there is more than 'flushInterval_' seconds since the last flush to avoid
336 // the flush eating up cpu time for small fast jobs...
337 // If want a flush every step for some reason, set `flushInterval_` to 0.0.
338
339 // This code is derived from code in finalize_write() in Ioex_DatabaseIO.C
340 // See other comments there...
341
342 time_t cur_time = time(nullptr);
343 if (cur_time - timeLastFlush_ >= flushInterval_) {
344 timeLastFlush_ = cur_time;
345 flush_database();
346 }
347
348 return true;
349 }
350
351 int64_t DatabaseIO::put_field_internal(const Ioss::Region * /* region */,
352 const Ioss::Field &field, void *data,
353 size_t data_size) const
354 {
355 initialize();
356 Ioss::Field::RoleType role = field.get_role();
357 int64_t num_to_get = field.verify(data_size);
358
359 if ((role == Ioss::Field::TRANSIENT || role == Ioss::Field::REDUCTION) && num_to_get == 1) {
360
361 int ncomp = field.get_component_count(Ioss::Field::InOut::OUTPUT);
362
363 if (legend_ != nullptr && layout_ != nullptr) {
364 if (ncomp == 1) {
365 legend_->add_legend(field.get_name());
366 }
367 else {
368 for (int i = 0; i < ncomp; i++) {
369 std::string var_name = get_component_name(field, Ioss::Field::InOut::OUTPUT, i + 1);
370 legend_->add_legend(var_name);
371 }
372 }
373 }
374
375 if (field.get_type() == Ioss::Field::STRING) {
376 // Assume that if layout_ is nullptr, then we want special one-line output.
377 if (layout_ == nullptr) {
378 Layout layout(false, 0, separator_, fieldWidth_);
379 layout.add_literal("-");
380 layout.add_literal(time_stamp(tsFormat));
381 layout.add_literal(" ");
382 layout.add_literal(*reinterpret_cast<std::string *>(data));
383 if (logStream != nullptr) {
384 fmt::print(*logStream, "{}\n", layout.layout());
385 }
386 }
387 else {
388 layout_->add(field.get_name(), *reinterpret_cast<std::string *>(data));
389 }
390 }
391 else {
392 if (layout_ == nullptr) {
393 IOSS_ERROR("INTERNAL ERROR: Unexpected nullptr layout.\n");
394 }
395 if (field.get_type() == Ioss::Field::INTEGER) {
396 assert(field.transformed_count() == 1);
397
398 int *i_data = reinterpret_cast<int *>(data);
399 std::vector<int> idata(ncomp);
400 for (int i = 0; i < ncomp; i++) {
401 idata[i] = i_data[i];
402 }
403 layout_->add(field.get_name(), idata);
404 }
405 else {
406 std::vector<double> rdata(ncomp);
407 auto *r_data = reinterpret_cast<double *>(data);
408 for (int i = 0; i < ncomp; i++) {
409 rdata[i] = r_data[i];
410 }
411 layout_->add(field.get_name(), rdata);
412 }
413 }
414 }
415 else {
416 IOSS_ERROR("ERROR: Can not handle non-TRANSIENT or non-REDUCTION fields on regions.\n");
417 }
418 return num_to_get;
419 }
420
421 unsigned DatabaseIO::entity_field_support() const { return Ioss::REGION; }
422 } // namespace Iohb