-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathADIOS2File.cpp
More file actions
1426 lines (1343 loc) · 47.3 KB
/
ADIOS2File.cpp
File metadata and controls
1426 lines (1343 loc) · 47.3 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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright 2017-2021 Franz Poeschel, Fabian Koller and Axel Huebl
*
* This file is part of openPMD-api.
*
* openPMD-api is free software: you can redistribute it and/or modify
* it under the terms of of either the GNU General Public License or
* the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* openPMD-api is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License and the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License
* and the GNU Lesser General Public License along with openPMD-api.
* If not, see <http://www.gnu.org/licenses/>.
*/
#include "openPMD/IO/ADIOS/ADIOS2File.hpp"
#include "openPMD/Error.hpp"
#include "openPMD/IO/ADIOS/ADIOS2Auxiliary.hpp"
#include "openPMD/IO/ADIOS/ADIOS2IOHandler.hpp"
#include "openPMD/IO/AbstractIOHandler.hpp"
#include "openPMD/IterationEncoding.hpp"
#include "openPMD/auxiliary/Environment.hpp"
#include "openPMD/auxiliary/StringManip.hpp"
#include <optional>
#include <stdexcept>
#if openPMD_USE_VERIFY
#define VERIFY(CONDITION, TEXT) \
{ \
if (!(CONDITION)) \
throw std::runtime_error((TEXT)); \
}
#else
#define VERIFY(CONDITION, TEXT) \
do \
{ \
(void)sizeof(CONDITION); \
} while (0);
#endif
#define VERIFY_ALWAYS(CONDITION, TEXT) \
{ \
if (!(CONDITION)) \
throw std::runtime_error((TEXT)); \
}
#if openPMD_HAVE_ADIOS2
namespace openPMD::detail
{
template <typename T>
void DatasetReader::call(
ADIOS2IOHandlerImpl *impl,
detail::BufferedGet &bp,
adios2::IO &IO,
adios2::Engine &engine,
std::string const &fileName,
std::optional<size_t> stepSelection,
detail::AdiosVariables const &av)
{
adios2::Variable<T> var = impl->verifyDataset<T>(
bp.param.offset,
bp.param.extent,
IO,
engine,
bp.name,
stepSelection,
av);
if (!var)
{
throw std::runtime_error(
"[ADIOS2] Failed retrieving ADIOS2 Variable with name '" + bp.name +
"' from file " + fileName + ".");
}
auto ptr = std::static_pointer_cast<T>(bp.param.data).get();
engine.Get(var, ptr);
}
template <class>
inline constexpr bool always_false_v = false;
template <typename T>
void WriteDataset::call(ADIOS2File &ba, detail::BufferedPut &bp)
{
VERIFY_ALWAYS(
access::write(ba.m_impl->m_handler->m_backendAccess),
"[ADIOS2] Cannot write data in read-only mode.");
std::visit(
[&](auto &&arg) {
using ptr_type = std::decay_t<decltype(arg)>;
if constexpr (std::is_same_v<ptr_type, std::shared_ptr<void const>>)
{
auto ptr = static_cast<T const *>(arg.get());
auto &engine = ba.getEngine();
adios2::Variable<T> var = ba.m_impl->verifyDataset<T>(
bp.param.offset,
bp.param.extent,
ba.m_IO,
engine,
bp.name,
std::nullopt,
ba.variables());
auto do_defer =
ba.m_is_bp5 ? adios2::Mode::Sync : adios2::Mode::Deferred;
engine.Put(var, ptr, do_defer);
}
else if constexpr (std::is_same_v<
ptr_type,
UniquePtrWithLambda<void>>)
{
BufferedUniquePtrPut bput;
bput.name = std::move(bp.name);
bput.offset = std::move(bp.param.offset);
bput.extent = std::move(bp.param.extent);
/*
* Note: Moving is required here since it's a unique_ptr.
* std::forward<>() would theoretically work, but it
* requires the type parameter and we don't have that
* inside the lambda.
* (ptr_type does not work for this case).
*/
// clang-format off
bput.data = std::move(arg); // NOLINT(bugprone-move-forwarding-reference)
// clang-format on
bput.dtype = bp.param.dtype;
ba.m_uniquePtrPuts.push_back(std::move(bput));
}
else
{
static_assert(
always_false_v<ptr_type>, "Unhandled std::variant branch");
}
},
bp.param.data.m_buffer);
}
template <int n, typename... Params>
void WriteDataset::call(Params &&...)
{
throw std::runtime_error("[ADIOS2] WRITE_DATASET: Invalid datatype.");
}
void BufferedGet::run(ADIOS2File &ba)
{
switchAdios2VariableType<detail::DatasetReader>(
param.dtype,
ba.m_impl,
*this,
ba.m_IO,
ba.getEngine(),
ba.m_file,
this->stepSelection,
ba.variables());
}
void BufferedPut::run(ADIOS2File &ba)
{
switchAdios2VariableType<detail::WriteDataset>(param.dtype, ba, *this);
}
struct RunUniquePtrPut
{
template <typename T>
static void call(BufferedUniquePtrPut &bufferedPut, ADIOS2File &ba)
{
auto ptr = static_cast<T const *>(bufferedPut.data.get());
auto &engine = ba.getEngine();
adios2::Variable<T> var = ba.m_impl->verifyDataset<T>(
bufferedPut.offset,
bufferedPut.extent,
ba.m_IO,
engine,
bufferedPut.name,
std::nullopt,
ba.variables());
auto do_defer =
ba.m_is_bp5 ? adios2::Mode::Sync : adios2::Mode::Deferred;
engine.Put(var, ptr, do_defer);
}
static constexpr char const *errorMsg = "RunUniquePtrPut";
};
void BufferedUniquePtrPut::run(ADIOS2File &ba)
{
switchAdios2VariableType<RunUniquePtrPut>(dtype, *this, ba);
}
ADIOS2File::ADIOS2File(
ADIOS2IOHandlerImpl &impl,
InvalidatableFile file,
adios_defs::OpenFileAs openFileAs)
: m_file(impl.fullPath(std::move(file)))
, m_ADIOS(impl.m_ADIOS)
, m_impl(&impl)
{
// Declaring these members in the constructor body to avoid
// initialization order hazards. Need the IO_ prefix since in some
// situation there seems to be trouble with number-only IO names
m_mode = impl.adios2AccessMode(m_file, openFileAs);
create_IO();
if (!m_IO)
{
throw std::runtime_error(
"[ADIOS2] Internal error: Failed declaring ADIOS2 IO object "
"for file " +
m_file);
}
else
{
configure_IO();
}
}
auto ADIOS2File::useGroupTable() const -> UseGroupTable
{
return m_impl->useGroupTable();
}
void ADIOS2File::create_IO()
{
m_IOName = std::to_string(m_impl->nameCounter++);
m_IO = m_impl->m_ADIOS.DeclareIO("IO_" + m_IOName);
}
ADIOS2File::~ADIOS2File()
{
finalize();
}
void ADIOS2File::finalize()
{
if (finalized)
{
return;
}
// if write accessing, ensure that the engine is opened
// and that all datasets are written
// (attributes and unique_ptr datasets are written upon closing a step
// or a file which users might never do)
bool needToWrite = !m_uniquePtrPuts.empty();
if ((needToWrite || !m_engine) && writeOnly(m_mode))
{
getEngine();
for (auto &entry : m_uniquePtrPuts)
{
entry.run(*this);
}
}
if (m_engine)
{
auto &engine = m_engine.value();
// might have been closed previously
if (engine)
{
if (streamStatus == StreamStatus::DuringStep)
{
engine.EndStep();
}
engine.Close();
m_ADIOS.RemoveIO(m_IOName);
}
}
m_uniquePtrPuts.clear();
finalized = true;
}
namespace
{
constexpr char const *alwaysSupportsUpfrontParsing[] = {"bp3", "hdf5"};
constexpr char const *supportsUpfrontParsingInRandomAccessMode[] = {
"bp4", "bp5", "file", "filestream"};
constexpr char const *nonPersistentEngines[] = {
"sst", "insitumpi", "inline", "staging", "nullcore", "ssc"};
bool supportedEngine(std::string const &engineType)
{
auto is_in_list = [&engineType](auto &list) {
for (auto const &e : list)
{
if (engineType == e)
{
return true;
}
}
return false;
};
return is_in_list(alwaysSupportsUpfrontParsing) ||
is_in_list(supportsUpfrontParsingInRandomAccessMode) ||
is_in_list(nonPersistentEngines);
}
bool supportsUpfrontParsing(Access access, std::string const &engineType)
{
for (auto const &e : alwaysSupportsUpfrontParsing)
{
if (e == engineType)
{
return true;
}
}
if (access != Access::READ_LINEAR)
{
for (auto const &e : supportsUpfrontParsingInRandomAccessMode)
{
if (e == engineType)
{
return true;
}
}
}
return false;
}
enum class PerstepParsing
{
Supported,
Unsupported,
Required
};
PerstepParsing
supportsPerstepParsing(Access access, std::string const &engineType)
{
// required in all streaming engines
for (auto const &e : nonPersistentEngines)
{
if (engineType == e)
{
return PerstepParsing::Required;
}
}
// supported in file engines in READ_LINEAR mode
if (access != Access::READ_RANDOM_ACCESS)
{
return PerstepParsing::Supported;
}
return PerstepParsing::Unsupported;
}
bool nonpersistentEngine(std::string const &engineType)
{
for (auto &e : nonPersistentEngines)
{
if (e == engineType)
{
return true;
}
}
return false;
}
} // namespace
size_t ADIOS2File::currentStep()
{
if (auto step_selection = stepSelection(); step_selection.has_value())
{
return *step_selection;
}
else if (m_mode == adios2::Mode::ReadRandomAccess)
{
return 0;
}
else
{
return getEngine().CurrentStep();
}
}
void ADIOS2File::setStepSelection(std::optional<size_t> step)
{
if (streamStatus != StreamStatus::ReadWithoutStream)
{
throw error::Internal(
"ADIOS2 backend: Cannot only use random-access step selections "
"when reading without streaming mode.");
}
m_stepSelection = step;
}
std::optional<size_t> const &ADIOS2File::stepSelection() const
{
return m_stepSelection;
}
void ADIOS2File::configure_IO_Read()
{
bool upfrontParsing = supportsUpfrontParsing(
m_impl->m_handler->m_backendAccess, m_impl->m_engineType);
PerstepParsing perstepParsing = supportsPerstepParsing(
m_impl->m_handler->m_backendAccess, m_impl->m_engineType);
switch (m_impl->m_handler->m_backendAccess)
{
case Access::READ_LINEAR:
switch (perstepParsing)
{
case PerstepParsing::Supported:
case PerstepParsing::Required:
// all is fine, we can go forward with READ_LINEAR mode
/*
* We don't know yet if per-step parsing will be fine since the
* engine is not opened yet.
* In non-persistent (streaming) engines, per-step parsing is
* always fine and always required.
*/
streamStatus = nonpersistentEngine(m_impl->m_engineType)
? StreamStatus::OutsideOfStep
: StreamStatus::Undecided;
parsePreference = ParsePreference::PerStep;
m_IO.SetParameter("StreamReader", "On");
break;
case PerstepParsing::Unsupported:
throw error::Internal(
"Internal control flow error: Per-Step parsing cannot be "
"unsupported when access type is READ_LINEAR");
break;
}
break;
case Access::READ_ONLY:
case Access::READ_WRITE:
/*
* Prefer up-front parsing, but try to fallback to per-step parsing
* if possible.
*/
if (upfrontParsing == nonpersistentEngine(m_impl->m_engineType))
{
throw error::Internal(
"Internal control flow error: With access types "
"READ_ONLY/READ_WRITE, support for upfront parsing is "
"equivalent to the chosen engine being file-based.");
}
if (upfrontParsing)
{
streamStatus = StreamStatus::ReadWithoutStream;
parsePreference = ParsePreference::UpFront;
}
else
{
/*
* Scenario: A step-only workflow was used (i.e. a streaming
* engine), but Access::READ_ONLY was specified.
* Fall back to streaming read mode.
*/
m_mode = adios2::Mode::Read;
parsePreference = ParsePreference::PerStep;
streamStatus = StreamStatus::OutsideOfStep;
}
break;
default:
VERIFY_ALWAYS(
access::writeOnly(m_impl->m_handler->m_backendAccess),
"Internal control flow error: Must set parse preference for "
"any read mode.");
}
}
void ADIOS2File::configure_IO_Write()
{
optimizeAttributesStreaming =
// Also, it should only be done when truly streaming, not
// when using a disk-based engine that behaves like a
// streaming engine (otherwise attributes might vanish)
nonpersistentEngine(m_impl->m_engineType);
streamStatus = StreamStatus::OutsideOfStep;
}
void ADIOS2File::configure_IO()
{
// step/variable-based iteration encoding requires use of group tables
// but the group table feature is available only in ADIOS2 >= v2.9
// use old layout to support at least one single iteration otherwise
// these properties are inferred from the opened dataset in read mode
if (writeOnly(m_mode))
{
if (!m_impl->m_useGroupTable.has_value())
{
switch (m_impl->m_handler->m_encoding)
{
case IterationEncoding::variableBased:
case IterationEncoding::groupBased:
m_impl->m_useGroupTable = UseGroupTable::Yes;
break;
case IterationEncoding::fileBased:
m_impl->m_useGroupTable = UseGroupTable::No;
break;
}
}
if (m_impl->m_modifiableAttributes ==
ADIOS2IOHandlerImpl::ModifiableAttributes::Unspecified)
{
m_impl->m_modifiableAttributes = m_impl->m_handler->m_encoding ==
IterationEncoding::variableBased
? ADIOS2IOHandlerImpl::ModifiableAttributes::Yes
: ADIOS2IOHandlerImpl::ModifiableAttributes::No;
}
m_IO.DefineAttribute<bool_representation>(
adios_defaults::str_useModifiableAttributes,
m_impl->m_modifiableAttributes ==
ADIOS2IOHandlerImpl::ModifiableAttributes::No
? 0
: 1);
}
// set engine type
{
m_IO.SetEngine(m_impl->realEngineType());
}
if (!supportedEngine(m_impl->m_engineType))
{
std::stringstream sstream;
sstream << "User-selected ADIOS2 engine '" << m_impl->m_engineType
<< "' is not recognized by the openPMD-api. Select one of: '";
bool first_entry = true;
auto add_entries = [&first_entry, &sstream](auto &list) {
for (auto const &e : list)
{
if (first_entry)
{
sstream << e;
first_entry = false;
}
else
{
sstream << ", " << e;
}
}
};
add_entries(alwaysSupportsUpfrontParsing);
add_entries(supportsUpfrontParsingInRandomAccessMode);
add_entries(nonPersistentEngines);
sstream << "'." << std::endl;
throw error::WrongAPIUsage(sstream.str());
}
// set engine parameters
std::set<std::string> alreadyConfigured;
bool wasTheFlushTargetSpecifiedViaJSON = false;
auto engineConfig = m_impl->config(adios_defaults::str_engine);
if (!engineConfig.json().is_null())
{
auto params = m_impl->config(adios_defaults::str_params, engineConfig);
params.declareFullyRead();
if (params.json().is_object())
{
for (auto it = params.json().begin(); it != params.json().end();
it++)
{
auto maybeString = json::asStringDynamic(it.value());
if (maybeString.has_value())
{
m_IO.SetParameter(it.key(), std::move(maybeString.value()));
}
else
{
throw error::BackendConfigSchema(
{"adios2", "engine", "parameters", it.key()},
"Must be convertible to string type.");
}
alreadyConfigured.emplace(
auxiliary::lowerCase(std::string(it.key())));
}
}
auto _useAdiosSteps =
m_impl->config(adios_defaults::str_usesteps, engineConfig);
if (!_useAdiosSteps.json().is_null() && writeOnly(m_mode))
{
std::cerr << "[ADIOS2 backend] WARNING: Parameter "
"`adios2.engine.usesteps` is deprecated since use "
"of steps is now always enabled."
<< std::endl;
}
if (engineConfig.json().contains(adios_defaults::str_flushtarget))
{
auto target = json::asLowerCaseStringDynamic(
engineConfig[adios_defaults::str_flushtarget].json());
if (!target.has_value())
{
throw error::BackendConfigSchema(
{"adios2", "engine", adios_defaults::str_flushtarget},
"Flush target must be either 'disk' or 'buffer', but "
"was non-literal type.");
}
m_impl->m_flushTarget =
adios_defs::flushTargetFromString(target.value());
wasTheFlushTargetSpecifiedViaJSON = true;
}
}
auto shadow = m_impl->m_config.invertShadow();
if (shadow.size() > 0)
{
switch (m_impl->m_config.originallySpecifiedAs)
{
case json::SupportedLanguages::JSON:
std::cerr << "Warning: parts of the backend configuration for "
"ADIOS2 remain unused:\n"
<< shadow << std::endl;
break;
case json::SupportedLanguages::TOML: {
auto asToml = json::jsonToToml(shadow);
std::cerr << "Warning: parts of the backend configuration for "
"ADIOS2 remain unused:\n"
<< json::format_toml(asToml) << std::endl;
break;
}
}
}
switch (m_impl->m_handler->m_backendAccess)
{
case Access::READ_LINEAR:
case Access::READ_ONLY:
configure_IO_Read();
break;
case Access::READ_WRITE:
if (readOnly(m_mode))
{
configure_IO_Read();
}
else
{
configure_IO_Write();
}
break;
case Access::APPEND_RANDOM_ACCESS:
case Access::APPEND_LINEAR:
case Access::CREATE_RANDOM_ACCESS:
case Access::CREATE_LINEAR:
configure_IO_Write();
break;
}
auto notYetConfigured = [&alreadyConfigured](std::string const ¶m) {
auto it =
alreadyConfigured.find(auxiliary::lowerCase(std::string(param)));
return it == alreadyConfigured.end();
};
// read parameters from environment
if (notYetConfigured("CollectiveMetadata"))
{
if (1 == auxiliary::getEnvNum("OPENPMD_ADIOS2_HAVE_METADATA_FILE", 1))
{
m_IO.SetParameter("CollectiveMetadata", "On");
}
else
{
m_IO.SetParameter("CollectiveMetadata", "Off");
}
}
if (notYetConfigured("Profile"))
{
if (1 == auxiliary::getEnvNum("OPENPMD_ADIOS2_HAVE_PROFILING", 1) &&
notYetConfigured("Profile"))
{
m_IO.SetParameter("Profile", "On");
}
else
{
m_IO.SetParameter("Profile", "Off");
}
}
if (notYetConfigured("AsyncWrite"))
{
if (1 == auxiliary::getEnvNum("OPENPMD_ADIOS2_ASYNC_WRITE", 0) &&
notYetConfigured("AsyncWrite"))
{
m_IO.SetParameter("AsyncWrite", "On");
if (!wasTheFlushTargetSpecifiedViaJSON)
{
m_impl->m_flushTarget = FlushTarget::Buffer;
}
}
else
{
m_IO.SetParameter("AsyncWrite", "Off");
}
}
#if openPMD_HAVE_MPI
{
auto num_substreams =
auxiliary::getEnvNum("OPENPMD_ADIOS2_NUM_SUBSTREAMS", 0);
if (notYetConfigured("SubStreams") && 0 != num_substreams)
{
m_IO.SetParameter("SubStreams", std::to_string(num_substreams));
}
// BP5 parameters
auto numAgg = auxiliary::getEnvNum("OPENPMD_ADIOS2_BP5_NumAgg", 0);
auto numSubFiles =
auxiliary::getEnvNum("OPENPMD_ADIOS2_BP5_NumSubFiles", 0);
auto AggTypeStr =
auxiliary::getEnvString("OPENPMD_ADIOS2_BP5_TypeAgg", "");
auto MaxShmMB = auxiliary::getEnvNum("OPENPMD_ADIOS2_BP5_MaxShmMB", 0);
auto BufferChunkMB =
auxiliary::getEnvNum("OPENPMD_ADIOS2_BP5_BufferChunkMB", 0);
if (notYetConfigured("NumAggregators") && (numAgg > 0))
m_IO.SetParameter("NumAggregators", std::to_string(numAgg));
if (notYetConfigured("NumSubFiles") && (numSubFiles > 0))
m_IO.SetParameter("NumSubFiles", std::to_string(numSubFiles));
if (notYetConfigured("AggregationType") && (AggTypeStr.size() > 0))
m_IO.SetParameter("AggregationType", AggTypeStr);
if (notYetConfigured("BufferChunkSize") && (BufferChunkMB > 0))
m_IO.SetParameter(
"BufferChunkSize",
std::to_string((uint64_t)BufferChunkMB * (uint64_t)1048576));
if (notYetConfigured("MaxShmSize") && (MaxShmMB > 0))
m_IO.SetParameter(
"MaxShmSize",
std::to_string((uint64_t)MaxShmMB * (uint64_t)1048576));
}
#endif
if (notYetConfigured("StatsLevel"))
{
/*
* Switch those off by default since they are expensive to compute
* and to enable it, set the JSON option "StatsLevel" or the
* environment variable "OPENPMD_ADIOS2_STATS_LEVEL" be positive.
* The ADIOS2 default was "1" (on).
*/
auto stats_level =
auxiliary::getEnvNum("OPENPMD_ADIOS2_STATS_LEVEL", 0);
m_IO.SetParameter("StatsLevel", std::to_string(stats_level));
}
if (m_impl->realEngineType() == "sst" && notYetConfigured("QueueLimit"))
{
/*
* By default, the SST engine of ADIOS2 does not set a limit on its
* internal queue length.
* If the reading end is slower than the writing end, this will
* lead to a congestion in the queue and hence an increasing
* memory usage while the writing code goes forward.
* We could set a default queue limit of 1, thus forcing the
* two codes to proceed entirely in lock-step.
* We prefer a default queue limit of 2, which is still lower than
* the default infinity, but allows writer and reader to process
* data asynchronously as long as neither code fails to keep up the
* rhythm. The writer can produce the next iteration while the
* reader still deals with the old one.
* Thus, a limit of 2 is a good balance between 1 and infinity,
* keeping pipeline parallelism a default without running the risk
* of using unbound memory.
*/
m_IO.SetParameter("QueueLimit", "2");
}
// We need to open the engine now already to inquire configuration
// options stored in there
getEngine();
}
auto ADIOS2File::detectGroupTable() -> UseGroupTable
{
return m_attributes.withAvailableAttributes(
currentStep(), m_IO, [&](auto const &attributes) {
auto lower_bound =
attributes.lower_bound(adios_defaults::str_activeTablePrefix);
if (lower_bound != attributes.end() &&
auxiliary::starts_with(
lower_bound->first, adios_defaults::str_activeTablePrefix))
{
return UseGroupTable::Yes;
}
else
{
return UseGroupTable::No;
}
});
}
adios2::Engine &ADIOS2File::getEngine()
{
if (!m_engine)
{
auto tempMode = m_mode;
switch (m_mode)
{
case adios2::Mode::Append:
#ifdef _WIN32
/*
* On Windows, ADIOS2 v2.8. Append mode only works with existing
* files. So, we first check for file existence and switch to
* create mode if it does not exist.
*
* See issue: https://github.com/ornladios/ADIOS2/issues/3358
*/
tempMode = m_impl->checkFile(m_file) ? adios2::Mode::Append
: adios2::Mode::Write;
[[fallthrough]];
#endif
case adios2::Mode::Write: {
// usesSteps attribute only written upon ::advance()
// this makes sure that the attribute is only put in case
// the streaming API was used.
m_engine =
std::make_optional(adios2::Engine(m_IO.Open(m_file, tempMode)));
m_engine->BeginStep();
streamStatus = StreamStatus::DuringStep;
break;
}
case adios2::Mode::ReadRandomAccess:
case adios2::Mode::Read: {
m_engine =
std::make_optional(adios2::Engine(m_IO.Open(m_file, m_mode)));
/*
* First round: detect use of group table
*/
bool openedANewStep = false;
{
if (!supportsUpfrontParsing(
m_impl->m_handler->m_backendAccess,
m_impl->m_engineType))
{
/*
* In BP5 with Linear read mode, we now need to
* tentatively open the first IO step.
* Otherwise we don't see the group table attributes.
* This branch is also taken by Streaming engines.
*/
if (m_engine->BeginStep() != adios2::StepStatus::OK)
{
throw std::runtime_error(
"[ADIOS2] Unexpected step status when "
"opening file/stream.");
}
openedANewStep = true;
}
if (m_impl->m_useGroupTable.has_value())
{
switch (m_impl->m_useGroupTable.value())
{
case UseGroupTable::Yes: {
auto detectedGroupTable = detectGroupTable();
if (detectedGroupTable == UseGroupTable::No)
{
std::cerr
<< "[Warning] User requested use of group "
"table when reading from ADIOS2 "
"dataset, but no group table has been "
"found. Will ignore."
<< std::endl;
m_impl->m_useGroupTable = UseGroupTable::No;
}
}
case UseGroupTable::No:
break;
}
}
else
{
m_impl->m_useGroupTable = detectGroupTable();
}
};
/*
* Second round: Decide the streamStatus.
*/
switch (streamStatus)
{
case StreamStatus::Undecided: {
auto attr = m_IO.InquireAttribute<bool_representation>(
adios_defaults::str_usesstepsAttribute);
if (attr && attr.Data()[0] == 1)
{
if (parsePreference == ParsePreference::UpFront)
{
if (openedANewStep)
{
throw error::Internal(
"Logic error in ADIOS2 backend! No need to "
"indiscriminately open a step before doing "
"anything in an engine that supports "
"up-front parsing.");
}
streamStatus = StreamStatus::ReadWithoutStream;
}
else
{
// If the iteration encoding is group-based and
// no group table is used, we're now at a dead-end.
// Step-by-Step parsing is unreliable in that mode
// since groups might be reported that are not
// there.
// But we were only able to find this out by opening
// the ADIOS2 file with an access mode that was
// possibly wrong, so we would have to close and
// reopen here.
// Since group-based encoding is a bag of trouble in
// ADIOS2 anyway, we just don't support this
// particular use case.
// This failure will only arise when the following
// conditions are met:
//
// 1) group-based encoding
// 2) no group table (i.e. old "ADIOS2 schema")
// 3) LINEAR access mode
//
// This is a relatively lenient restriction compared
// to forbidding group-based encoding in ADIOS2
// altogether.
if (m_impl->m_useGroupTable.value() ==
UseGroupTable::No &&
m_IO.InquireAttribute<std::string>(
adios_defaults::str_groupBasedWarning))
{
throw error::OperationUnsupportedInBackend(
"ADIOS2",
"Trying to open a group-based ADIOS2 file "
"that does not have a group table with "
"LINEAR access type. That combination is "
"very buggy, so please use "
"READ_ONLY/READ_RANDOM_ACCESS instead.");
}
if (!openedANewStep &&
m_engine.value().BeginStep() !=
adios2::StepStatus::OK)
{
throw std::runtime_error(
"[ADIOS2] Unexpected step status when "
"opening file/stream.");
}
streamStatus = StreamStatus::DuringStep;
}
}
else
{
/*
* If openedANewStep is true, then the file consists
* of one large step, we just leave it open.
*/
streamStatus = StreamStatus::ReadWithoutStream;
}
break;
}
case StreamStatus::ReadWithoutStream:
// using random-access mode
break;
case StreamStatus::DuringStep:
throw error::Internal(
"[ADIOS2] Control flow error: stream status cannot be "
"DuringStep before opening the engine.");
case StreamStatus::OutsideOfStep:
if (openedANewStep)
{
streamStatus = StreamStatus::DuringStep;
}
else
{
throw error::Internal(
"Control flow error: Step should have been opened "
"before this point.");
}
break;
default:
throw std::runtime_error("[ADIOS2] Control flow error!");
}
break;
}
default:
throw std::runtime_error("[ADIOS2] Invalid ADIOS access mode");
}
if (!m_engine.value())
{
throw std::runtime_error("[ADIOS2] Failed opening Engine.");
}
m_is_bp5 = m_impl->realEngineType() == "bp5" ||
/* this second check should be sufficient, but we leave the
first check in as a safeguard against renamings in
ADIOS2. Also do a lowerCase transform since the docstring
of `Engine::Type()` claims that the return value is in
lowercase, but for BP5 this does not seem true. */
auxiliary::lowerCase(m_engine->Type()) == "bp5writer";
}
return m_engine.value();
}
void ADIOS2File::flush_impl(
ADIOS2FlushParams flushParams,
std::function<void(ADIOS2File &, adios2::Engine &)> const &performPutGets,
bool writeLatePuts,