Repository navigation
Expand file tree
/
Copy pathStream.cpp
More file actions
488 lines (421 loc) · 20.1 KB
/
Copy pathStream.cpp
File metadata and controls
488 lines (421 loc) · 20.1 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
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
/* Copyright (c) 2022-2026. The SWAT Team. All rights reserved. */
/* This program is free software; you can redistribute it and/or modify it
* under the terms of the license (GNU LGPL) which comes with this package. */
#include <array>
#include <boost/algorithm/string/replace.hpp>
#include <chrono>
#include <fstream>
#include "dtlmod/CompressionReductionMethod.hpp"
#include "dtlmod/DTL.hpp"
#include "dtlmod/DTLException.hpp"
#include "dtlmod/DecimationReductionMethod.hpp"
#include "dtlmod/FileEngine.hpp"
#include "dtlmod/ReductionMethod.hpp"
#include "dtlmod/StagingEngine.hpp"
#include "dtlmod/Stream.hpp"
#include "dtlmod/Variable.hpp"
XBT_LOG_NEW_DEFAULT_SUBCATEGORY(dtlmod_stream, dtlmod, "DTL logging about Streams");
namespace dtlmod {
// Constexpr lookup table for Engine::Type to string conversion
constexpr std::array<std::pair<Engine::Type, const char*>, 3> engine_type_strings{{
{Engine::Type::File, "Engine::Type::File"},
{Engine::Type::Staging, "Engine::Type::Staging"},
{Engine::Type::Undefined, "Engine::Type::Undefined"},
}};
// Constexpr lookup table for Transport::Method to string conversion
constexpr std::array<std::pair<Transport::Method, const char*>, 4> transport_method_strings{{
{Transport::Method::File, "Transport::Method::File"},
{Transport::Method::Mailbox, "Transport::Method::Mailbox"},
{Transport::Method::MQ, "Transport::Method::MQ"},
{Transport::Method::Undefined, "Transport::Method::Undefined"},
}};
// Constexpr validators for compile-time checking
namespace {
constexpr bool is_valid_engine_type(Engine::Type type) noexcept
{
return type == Engine::Type::File || type == Engine::Type::Staging;
}
constexpr bool is_valid_transport_method(Transport::Method method) noexcept
{
return method == Transport::Method::File || method == Transport::Method::Mailbox || method == Transport::Method::MQ;
}
constexpr bool is_valid_mode(Stream::Mode mode) noexcept
{
return mode == Stream::Mode::Publish || mode == Stream::Mode::Subscribe;
}
} // namespace
std::optional<const char*> Stream::get_engine_type_str() const noexcept
{
for (const auto& [type, str] : engine_type_strings) {
if (type == engine_type_)
return str;
}
return std::nullopt; // LCOV_EXCL_LINE
}
Stream& Stream::set_engine_type(const Engine::Type& engine_type)
{
if (engine_type_ == engine_type) // No modification, just return
return *this;
// Check if this engine type is known
if (!is_valid_engine_type(engine_type))
throw UnknownEngineTypeException(XBT_THROW_POINT, "");
// Check is one tries to redefine the engine type
if (engine_type_ != Engine::Type::Undefined)
throw MultipleEngineTypeException(XBT_THROW_POINT, "");
// This is the first definition of the engine type.
// Check for unauthorized combinations first.
if (transport_method_ == Transport::Method::File && engine_type != Engine::Type::File)
throw InvalidEngineAndTransportCombinationException(
XBT_THROW_POINT, ": The Transport::Method::File transport method can only be used with Engine::File.");
if ((transport_method_ == Transport::Method::Mailbox || transport_method_ == Transport::Method::MQ) &&
engine_type != Engine::Type::Staging)
throw InvalidEngineAndTransportCombinationException(
XBT_THROW_POINT, ": The Transport::Method::Mailbox and Transport::Method::MQ transport methods "
"can only be used with Engine::Staging.");
// set the engine type
engine_type_ = engine_type;
return *this;
}
std::optional<const char*> Stream::get_transport_method_str() const noexcept
{
for (const auto& [method, str] : transport_method_strings) {
if (method == transport_method_)
return str;
}
return std::nullopt; // LCOV_EXCL_LINE
}
std::optional<std::shared_ptr<ReductionMethod>> Stream::get_reduction_method(std::string_view name) const noexcept
{
auto it = reduction_methods_.find(std::string(name));
if (it == reduction_methods_.end())
return std::nullopt;
return it->second;
}
Stream& Stream::set_transport_method(const Transport::Method& transport_method)
{
if (transport_method_ == transport_method) // No modification, just return
return *this;
// Check if this transport method is known
if (!is_valid_transport_method(transport_method))
throw UnknownTransportMethodException(XBT_THROW_POINT, "");
// Check is one tries to redefine the transport method
if (transport_method_ != Transport::Method::Undefined)
throw MultipleTransportMethodException(XBT_THROW_POINT, "");
// This is the first definition of the transport method.
// Check for unauthorized combinations first.
if (engine_type_ == Engine::Type::File && transport_method != Transport::Method::File)
throw InvalidEngineAndTransportCombinationException(
XBT_THROW_POINT, "An Engine::File only accepts Transport::Method::File as a transport method.");
if (engine_type_ == Engine::Type::Staging &&
not(transport_method == Transport::Method::Mailbox || transport_method == Transport::Method::MQ))
throw InvalidEngineAndTransportCombinationException(
XBT_THROW_POINT, "An Engine::Staging only accepts Transport::Method::Mailbox or Transport::Method::MQ as a "
"transport method.");
// Set the transport method
transport_method_ = transport_method;
return *this;
}
Stream& Stream::set_metadata_export() noexcept
{
metadata_export_ = true;
return *this;
}
Stream& Stream::unset_metadata_export() noexcept
{
metadata_export_ = false;
return *this;
}
Stream& Stream::set_simulate_memory_copy(bool value) noexcept
{
simulate_memory_copy_ = value;
return *this;
}
Stream& Stream::set_open_overhead(double seconds)
{
if (seconds < 0)
throw InvalidOpenOverheadException(XBT_THROW_POINT, std::to_string(seconds));
open_overhead_ = seconds;
return *this;
}
void Stream::export_metadata_to_file()
{
metadata_exported_ = true;
if (metadata_export_) {
std::ofstream export_stream(metadata_file_, std::ofstream::out);
for (const auto& [name, v] : variables_) {
auto it = var_prog_file_paths_.find(name);
std::string prog = (it != var_prog_file_paths_.end()) ? it->second : "";
v->get_metadata()->export_to_file(export_stream, prog);
}
export_stream.close();
// Remove per-variable prog files now that the final file is written
for (const auto& [name, path] : var_prog_file_paths_)
std::remove(path.c_str());
var_prog_file_paths_.clear();
}
}
void Stream::flush_and_evict_transaction(unsigned int tx_id)
{
if (metadata_exported_) {
// Sequential scenario or post-export: the metadata file is already complete; just free memory
for (const auto& [name, v] : variables_)
v->get_metadata()->evict_transaction(tx_id);
return;
}
if (metadata_export_) {
for (const auto& [name, v] : variables_) {
if (!var_prog_file_paths_.count(name))
var_prog_file_paths_[name] = metadata_file_ + "." + name + ".prog";
std::ofstream out(var_prog_file_paths_.at(name), std::ofstream::app);
v->get_metadata()->write_transaction_to_stream(tx_id, out);
// write_transaction_to_stream also increments flushed_count_ and evicts from transaction_infos_
}
} else {
for (const auto& [name, v] : variables_)
v->get_metadata()->evict_transaction(tx_id);
}
}
std::shared_ptr<ReductionMethod> Stream::define_reduction_method(const std::string& name)
{
if (auto it = reduction_methods_.find(name); it != reduction_methods_.end())
return it->second;
std::shared_ptr<ReductionMethod> reduction_method;
if (name == "decimation")
reduction_method = std::make_shared<DecimationReductionMethod>(name);
else if (name == "compression")
reduction_method = std::make_shared<CompressionReductionMethod>(name);
else
throw UnknownReductionMethodException(XBT_THROW_POINT, name);
reduction_methods_.try_emplace(name, reduction_method);
return reduction_method;
}
/****** Engine Factory ******/
/// Validate that all required parameters are set before opening a Stream.
void Stream::validate_open_parameters(std::string_view name, Mode mode) const
{
if (engine_type_ == Engine::Type::Undefined)
throw UndefinedEngineTypeException(XBT_THROW_POINT, std::string(name));
if (transport_method_ == Transport::Method::Undefined)
throw UndefinedTransportMethodException(XBT_THROW_POINT, std::string(name));
if (!is_valid_mode(mode))
throw UnknownOpenModeException(XBT_THROW_POINT, mode_to_str(mode));
}
/// Create the Engine if this is the first actor opening the Stream.
/// Executed in a critical section to ensure only one Engine is created.
std::shared_ptr<Engine> Stream::create_engine_if_needed(std::string_view name, Mode mode)
{
std::scoped_lock lock(*dtl_->mutex_);
if (not engine_) {
std::shared_ptr<Engine> temp_engine;
if (engine_type_ == Engine::Type::Staging) {
temp_engine = std::make_shared<StagingEngine>(name, shared_from_this());
temp_engine->create_transport(transport_method_);
} else if (engine_type_ == Engine::Type::File) {
temp_engine = std::make_shared<FileEngine>(name, shared_from_this());
temp_engine->create_transport(transport_method_);
}
// Only commit if fully initialized
engine_ = std::move(temp_engine);
access_mode_ = mode;
if (metadata_export_)
metadata_file_ = boost::replace_all_copy(engine_->get_name(), "/", "#") + "#md." +
std::to_string(std::chrono::system_clock::now().time_since_epoch().count());
}
// Return the Engine while still holding the lock: releasing it is a scheduling point at which the last actor closing
// the Engine on the other side can reset engine_.
return engine_;
}
/// Register the current actor as a publisher or subscriber with the Engine.
void Stream::register_actor_with_engine(const std::shared_ptr<Engine>& engine, Mode mode) const
{
if (mode == Mode::Publish)
engine->add_publisher(sg4::Actor::self());
else
engine->add_subscriber(sg4::Actor::self());
}
/// When multiple actors open the same Stream, only the first one to call this function is in charge of creating an
/// Engine object for that Stream. The Engine creation is thus in a critical section. Each actor calling the open()
/// function is considered as a subscriber to the created Engine.
///
/// Both Engine::Type and Transport::Method have to be specified before opening a Stream.
///
/// If an open overhead was set with set_open_overhead(), the calling actor then sleeps for that duration.
///
/// For the FileEngine engine type, name corresponds to a fullpath to where to write data. This fullpath is
/// structured as follows: netzone_name:file_system_name:/path/to/file_name.
std::shared_ptr<Engine> Stream::open(std::string_view name, Mode mode)
{
validate_open_parameters(name, mode);
// Keep a handle on the Engine: engine_ can be reset at any scheduling point by the last actor closing the Engine on
// the other side.
auto engine = create_engine_if_needed(name, mode);
register_actor_with_engine(engine, mode);
// Simulate the setup cost of the middleware. Done outside of the critical section of create_engine_if_needed() so
// that actors opening this Stream concurrently pay this overhead in parallel.
if (open_overhead_ > 0)
sg4::this_actor::sleep_for(open_overhead_);
XBT_DEBUG("Stream '%s' uses engine '%s' and transport '%s' (%zu Pub. / %zu Sub.)", get_cname(),
get_engine_type_str().value_or("Unknown"), get_transport_method_str().value_or("Unknown"),
engine->get_publishers().count(), engine->get_subscribers().count());
return engine;
} // LCOV_EXCL_LINE
/****** Variable Factory ******/
/// This function creates a new scalar Variable and the corresponding entry in the internal directory of the Stream that
/// stores all the known variables. This definition does not refer to the data carried by the Variable but provides
/// information about its shape (here a scalar) and element type.
std::shared_ptr<Variable> Stream::define_variable(std::string_view name, size_t element_size)
{
return define_variable(name, {1}, {0}, {1}, element_size);
}
/// Validate variable parameters for shape, start, count, and element_size.
/// Checks for empty vectors, size mismatches, zero dimensions, and wrapped negative numbers.
void Stream::validate_variable_parameters(const std::vector<size_t>& shape, const std::vector<size_t>& start,
const std::vector<size_t>& count, size_t element_size)
{
// Check for empty vectors
if (shape.empty())
throw InconsistentVariableDefinitionException(XBT_THROW_POINT, "Shape vector cannot be empty");
// Vectors should have the same size
if (shape.size() != start.size() || shape.size() != count.size())
throw InconsistentVariableDefinitionException(
XBT_THROW_POINT, std::string("Shape, Start, and Count vectors must have the same size. Shape: ") +
std::to_string(shape.size()) + ", Start: " + std::to_string(start.size()) +
", Count: " + std::to_string(count.size()));
// Check for zero dimensions and detect wrapped negative numbers
// size_t is unsigned, so negative values wrap to very large numbers (> SIZE_MAX/2)
constexpr size_t max_reasonable_dim = std::numeric_limits<size_t>::max() / 2;
for (unsigned int i = 0; i < shape.size(); i++) {
if (shape[i] == 0)
throw InconsistentVariableDefinitionException(XBT_THROW_POINT, std::string("Shape dimension ") +
std::to_string(i) + " cannot be zero");
if (shape[i] > max_reasonable_dim)
throw InconsistentVariableDefinitionException(
XBT_THROW_POINT,
std::string("Shape dimension ") + std::to_string(i) +
" has suspiciously large value (possible wrapped negative): " + std::to_string(shape[i]));
if (start[i] > max_reasonable_dim)
throw InconsistentVariableDefinitionException(
XBT_THROW_POINT,
std::string("Start dimension ") + std::to_string(i) +
" has suspiciously large value (possible wrapped negative): " + std::to_string(start[i]));
if (count[i] == 0)
throw InconsistentVariableDefinitionException(XBT_THROW_POINT, std::string("Count dimension ") +
std::to_string(i) + " cannot be zero");
if (count[i] > max_reasonable_dim)
throw InconsistentVariableDefinitionException(
XBT_THROW_POINT,
std::string("Count dimension ") + std::to_string(i) +
" has suspiciously large value (possible wrapped negative): " + std::to_string(count[i]));
}
// Check element_size
if (element_size == 0)
throw InconsistentVariableDefinitionException(XBT_THROW_POINT, "Element size cannot be zero");
if (element_size > max_reasonable_dim)
throw InconsistentVariableDefinitionException(
XBT_THROW_POINT, std::string("Element size has suspiciously large value (possible wrapped negative): ") +
std::to_string(element_size));
// The local size of the variable (start + count) cannot exceed the global size (shape) of the Variable
// Check written to avoid overflow: count[i] > (shape[i] - start[i])
for (unsigned int i = 0; i < shape.size(); i++) {
if (start[i] > shape[i] || count[i] > shape[i] - start[i])
throw InconsistentVariableDefinitionException(
XBT_THROW_POINT, std::string("start + count exceeds shape in dimension ") + std::to_string(i) +
" (start: " + std::to_string(start[i]) + ", count: " + std::to_string(count[i]) +
", shape: " + std::to_string(shape[i]) + ")");
}
}
/// This function creates a new Variable and the corresponding entry in the internal directory of the Stream that
/// stores all the known variables. This definition does not refer to the data carried by the Variable but provides
/// information about its shape (here a multi-dimensional array) and element type.
std::shared_ptr<Variable> Stream::define_variable(std::string_view name, const std::vector<size_t>& shape,
const std::vector<size_t>& start, const std::vector<size_t>& count,
size_t element_size)
{
// Validate parameters
validate_variable_parameters(shape, start, count, element_size);
std::unique_lock lock(*mutex_);
auto publisher = sg4::Actor::self();
std::string name_str(name);
auto var = variables_.find(name_str);
if (var != variables_.end()) {
if (var->second->get_shape().size() != shape.size() || var->second->get_element_size() != element_size)
throw MultipleVariableDefinitionException(XBT_THROW_POINT, name_str + " already exists in Stream " + get_name());
else {
var->second->set_local_start_and_count(publisher, std::make_pair(start, count));
return var->second;
}
} else {
auto new_var = std::make_shared<Variable>(name_str, element_size, shape, shared_from_this());
new_var->set_local_start_and_count(publisher, std::make_pair(start, count));
new_var->create_metadata();
variables_.try_emplace(name_str, new_var);
// Wake up the subscribers that may be waiting for this Variable in inquire_variable()
if (nb_variable_waiters_ > 0)
variable_defined_->notify_all();
return new_var;
}
}
std::vector<std::string> Stream::get_all_variables() const
{
std::vector<std::string> variable_names;
variable_names.reserve(variables_.size());
for (const auto& [name, var] : variables_)
variable_names.push_back(name);
return variable_names;
} // LCOV_EXCL_LINE
std::shared_ptr<Variable> Stream::inquire_variable(std::string_view name, double timeout) const
{
std::string name_str(name);
auto var = variables_.find(name_str);
// A subscriber may inquire a Variable before a publisher defines it. Depending on timeout, wait for the
// definition (signaled by define_variable()) for a bounded or unbounded amount of time, or not at all.
// The lock is only taken when waiting: actors are scheduled cooperatively, so the lookup above cannot interleave
// with a define_variable(), and locking there would add a scheduling point that changes the simulated behavior.
if (var == variables_.end() && timeout != 0) {
std::unique_lock lock(*mutex_);
if (not variable_defined_)
variable_defined_ = sg4::ConditionVariable::create();
const double deadline = sg4::Engine::get_clock() + timeout;
nb_variable_waiters_++;
while ((var = variables_.find(name_str)) == variables_.end()) {
if (timeout < 0)
variable_defined_->wait(lock);
else if (variable_defined_->wait_until(lock, deadline) == std::cv_status::timeout) {
var = variables_.find(name_str);
break;
}
}
nb_variable_waiters_--;
}
if (var == variables_.end())
throw UnknownVariableException(XBT_THROW_POINT, name_str);
auto actor = sg4::Actor::self();
if (not engine_ || engine_->get_publishers().contains(actor))
return var->second;
else {
auto new_var = std::make_shared<Variable>(name_str, var->second->get_element_size(), var->second->get_shape(),
shared_from_this());
new_var->set_local_start_and_count(actor, std::make_pair(std::vector<size_t>(var->second->get_shape().size(), 0),
std::vector<size_t>(var->second->get_shape().size(), 0)));
new_var->set_metadata(var->second->get_metadata());
// Propagate reduction state so subscribers can detect publisher-side reduction
if (var->second->is_reduced()) {
new_var->is_reduced_with_ = var->second->get_reduction_method();
new_var->reduction_origin_ = var->second->reduction_origin_;
// Register the subscriber's variable in the reduction method's map so that
// Engine::get() can compute costs, and subscribers can query reduced sizes.
new_var->is_reduced_with_->propagate_for_subscriber(*var->second, *new_var);
}
return new_var;
}
}
void Stream::remove_variable(std::string_view name)
{
std::string name_str(name);
auto var = variables_.find(name_str);
if (var != variables_.end())
variables_.erase(var);
else
throw UnknownVariableException(XBT_THROW_POINT, name_str);
}
} // namespace dtlmod