-
Notifications
You must be signed in to change notification settings - Fork 51
/
ADIOS2IOHandler.cpp
3818 lines (3567 loc) · 129 KB
/
ADIOS2IOHandler.cpp
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/ADIOS2IOHandler.hpp"
#include "openPMD/Datatype.hpp"
#include "openPMD/Error.hpp"
#include "openPMD/IO/ADIOS/ADIOS2FilePosition.hpp"
#include "openPMD/IO/ADIOS/ADIOS2IOHandler.hpp"
#include "openPMD/auxiliary/Environment.hpp"
#include "openPMD/auxiliary/Filesystem.hpp"
#include "openPMD/auxiliary/Mpi.hpp"
#include "openPMD/auxiliary/StringManip.hpp"
#include "openPMD/auxiliary/TypeTraits.hpp"
#include <algorithm>
#include <cctype> // std::tolower
#include <iostream>
#include <iterator>
#include <memory>
#include <set>
#include <string>
#include <type_traits>
namespace openPMD
{
#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
#define HAS_ADIOS_2_8 (ADIOS2_VERSION_MAJOR * 100 + ADIOS2_VERSION_MINOR >= 208)
#if openPMD_HAVE_MPI
ADIOS2IOHandlerImpl::ADIOS2IOHandlerImpl(
AbstractIOHandler *handler,
MPI_Comm communicator,
json::TracingJSON cfg,
std::string engineType,
std::string specifiedExtension)
: AbstractIOHandlerImplCommon(handler)
, m_ADIOS{communicator}
, m_communicator{communicator}
, m_engineType(std::move(engineType))
, m_userSpecifiedExtension{std::move(specifiedExtension)}
{
init(std::move(cfg));
}
#endif // openPMD_HAVE_MPI
ADIOS2IOHandlerImpl::ADIOS2IOHandlerImpl(
AbstractIOHandler *handler,
json::TracingJSON cfg,
std::string engineType,
std::string specifiedExtension)
: AbstractIOHandlerImplCommon(handler)
, m_ADIOS{}
, m_engineType(std::move(engineType))
, m_userSpecifiedExtension(std::move(specifiedExtension))
{
init(std::move(cfg));
}
ADIOS2IOHandlerImpl::~ADIOS2IOHandlerImpl()
{
/*
* m_fileData is an unordered_map indexed by pointer addresses
* to the fileState member of InvalidatableFile.
* This means that destruction order is nondeterministic.
* Let's determinize it (necessary if computing in parallel).
*/
using file_t = std::unique_ptr<detail::BufferedActions>;
std::vector<file_t> sorted;
sorted.reserve(m_fileData.size());
for (auto &pair : m_fileData)
{
sorted.push_back(std::move(pair.second));
}
m_fileData.clear();
/*
* Technically, std::sort() is sufficient here, since file names are unique.
* Use std::stable_sort() for two reasons:
* 1) On some systems (clang 13.0.1, libc++ 13.0.1), std::sort() leads to
* weird inconsistent segfaults here.
* 2) Robustness against future changes. stable_sort() might become needed
* in future, and debugging this can be hard.
* 3) It does not really matter, this is just the destructor, so we can take
* the extra time.
*/
std::stable_sort(
sorted.begin(), sorted.end(), [](auto const &left, auto const &right) {
return left->m_file <= right->m_file;
});
// run the destructors
for (auto &file : sorted)
{
// std::unique_ptr interface
file.reset();
}
}
void ADIOS2IOHandlerImpl::init(json::TracingJSON cfg)
{
// allow overriding through environment variable
m_engineType =
auxiliary::getEnvString("OPENPMD_ADIOS2_ENGINE", m_engineType);
std::transform(
m_engineType.begin(),
m_engineType.end(),
m_engineType.begin(),
[](unsigned char c) { return std::tolower(c); });
// environment-variable based configuration
if (int schemaViaEnv = auxiliary::getEnvNum("OPENPMD2_ADIOS2_SCHEMA", -1);
schemaViaEnv != -1)
{
m_schema = schemaViaEnv;
}
if (cfg.json().contains("adios2"))
{
m_config = cfg["adios2"];
if (m_config.json().contains("schema"))
{
m_schema = m_config["schema"].json().get<ADIOS2Schema::schema_t>();
}
if (m_config.json().contains("use_span_based_put"))
{
m_useSpanBasedPutByDefault =
m_config["use_span_based_put"].json().get<bool>() ? UseSpan::Yes
: UseSpan::No;
}
auto engineConfig = config(ADIOS2Defaults::str_engine);
if (!engineConfig.json().is_null())
{
auto engineTypeConfig =
config(ADIOS2Defaults::str_type, engineConfig).json();
if (!engineTypeConfig.is_null())
{
// convert to string
auto maybeEngine =
json::asLowerCaseStringDynamic(engineTypeConfig);
if (maybeEngine.has_value())
{
// override engine type by JSON/TOML configuration
m_engineType = std::move(maybeEngine.value());
}
else
{
throw error::BackendConfigSchema(
{"adios2", "engine", "type"},
"Must be convertible to string type.");
}
}
}
auto operators = getOperators();
if (operators)
{
defaultOperators = std::move(operators.value());
}
}
}
std::optional<std::vector<ADIOS2IOHandlerImpl::ParameterizedOperator>>
ADIOS2IOHandlerImpl::getOperators(json::TracingJSON cfg)
{
using ret_t = std::optional<std::vector<ParameterizedOperator>>;
std::vector<ParameterizedOperator> res;
if (!cfg.json().contains("dataset"))
{
return ret_t();
}
auto datasetConfig = cfg["dataset"];
if (!datasetConfig.json().contains("operators"))
{
return ret_t();
}
auto _operators = datasetConfig["operators"];
nlohmann::json const &operators = _operators.json();
for (auto operatorIterator = operators.begin();
operatorIterator != operators.end();
++operatorIterator)
{
nlohmann::json const &op = operatorIterator.value();
std::string const &type = op["type"];
adios2::Params adiosParams;
if (op.contains("parameters"))
{
nlohmann::json const ¶ms = op["parameters"];
for (auto paramIterator = params.begin();
paramIterator != params.end();
++paramIterator)
{
auto maybeString = json::asStringDynamic(paramIterator.value());
if (maybeString.has_value())
{
adiosParams[paramIterator.key()] =
std::move(maybeString.value());
}
else
{
throw error::BackendConfigSchema(
{"adios2", "dataset", "operators", paramIterator.key()},
"Must be convertible to string type.");
}
}
}
std::optional<adios2::Operator> adiosOperator =
getCompressionOperator(type);
if (adiosOperator)
{
res.emplace_back(ParameterizedOperator{
adiosOperator.value(), std::move(adiosParams)});
}
}
_operators.declareFullyRead();
return std::make_optional(std::move(res));
}
std::optional<std::vector<ADIOS2IOHandlerImpl::ParameterizedOperator>>
ADIOS2IOHandlerImpl::getOperators()
{
return getOperators(m_config);
}
using AcceptedEndingsForEngine = std::map<std::string, std::string>;
std::string ADIOS2IOHandlerImpl::fileSuffix(bool verbose) const
{
// SST engine adds its suffix unconditionally
// so we don't add it
static std::map<std::string, AcceptedEndingsForEngine> const endings{
{"sst", {{"", ""}, {".sst", ""}}},
{"staging", {{"", ""}, {".sst", ""}}},
{"filestream", {{".bp", ".bp"}, {".bp4", ".bp4"}, {".bp5", ".bp5"}}},
{"bp4", {{".bp4", ".bp4"}, {".bp", ".bp"}}},
{"bp5", {{".bp5", ".bp5"}, {".bp", ".bp"}}},
{"bp3", {{".bp", ".bp"}}},
{"file", {{".bp", ".bp"}, {".bp4", ".bp4"}, {".bp5", ".bp5"}}},
{"hdf5", {{".h5", ".h5"}}},
{"nullcore", {{".nullcore", ".nullcore"}, {".bp", ".bp"}}},
{"ssc", {{".ssc", ".ssc"}}}};
if (auto engine = endings.find(m_engineType); engine != endings.end())
{
auto const &acceptedEndings = engine->second;
if (auto ending = acceptedEndings.find(m_userSpecifiedExtension);
ending != acceptedEndings.end())
{
if (verbose &&
(m_engineType == "file" || m_engineType == "filestream") &&
(m_userSpecifiedExtension == ".bp3" ||
m_userSpecifiedExtension == ".bp4" ||
m_userSpecifiedExtension == ".bp5"))
{
std::cerr
<< "[ADIOS2] Explicit ending '" << m_userSpecifiedExtension
<< "' was specified in combination with generic file "
"engine '"
<< m_engineType
<< "'. ADIOS2 will pick a default file ending "
"independent of specified suffix. (E.g. 'simData.bp5' "
"might actually be written as a BP4 dataset.)"
<< std::endl;
}
return ending->second;
}
else if (m_userSpecifiedExtension.empty())
{
std::cerr << "[ADIOS2] No file ending specified. Will not add one."
<< std::endl;
if (verbose && m_engineType == "bp3")
{
std::cerr
<< "Note that the ADIOS2 BP3 engine will add its "
"ending '.bp' if not specified (e.g. 'simData.bp3' "
"will appear on disk as 'simData.bp3.bp')."
<< std::endl;
}
return "";
}
else
{
if (verbose)
{
std::cerr << "[ADIOS2] Specified ending '"
<< m_userSpecifiedExtension
<< "' does not match the selected engine '"
<< m_engineType
<< "'. Will use the specified ending anyway."
<< std::endl;
if (m_engineType == "bp3")
{
std::cerr
<< "Note that the ADIOS2 BP3 engine will add its "
"ending '.bp' if not specified (e.g. 'simData.bp3' "
"will appear on disk as 'simData.bp3.bp')."
<< std::endl;
}
}
return m_userSpecifiedExtension;
}
}
else
{
throw error::WrongAPIUsage(
"[ADIOS2] Specified engine '" + m_engineType +
"' is not supported by ADIOS2 backend.");
}
}
using FlushTarget = ADIOS2IOHandlerImpl::FlushTarget;
static FlushTarget flushTargetFromString(std::string const &str)
{
if (str == "buffer")
{
return FlushTarget::Buffer;
}
else if (str == "disk")
{
return FlushTarget::Disk;
}
else if (str == "buffer_override")
{
return FlushTarget::Buffer_Override;
}
else if (str == "disk_override")
{
return FlushTarget::Disk_Override;
}
else
{
throw error::BackendConfigSchema(
{"adios2", "engine", ADIOS2Defaults::str_flushtarget},
"Flush target must be either 'disk' or 'buffer', but "
"was " +
str + ".");
}
}
static FlushTarget &
overrideFlushTarget(FlushTarget &inplace, FlushTarget new_val)
{
auto allowsOverride = [](FlushTarget ft) {
switch (ft)
{
case FlushTarget::Buffer:
case FlushTarget::Disk:
return true;
case FlushTarget::Buffer_Override:
case FlushTarget::Disk_Override:
return false;
}
return true;
};
if (allowsOverride(inplace))
{
inplace = new_val;
}
else
{
if (!allowsOverride(new_val))
{
inplace = new_val;
}
// else { keep the old value, no-op }
}
return inplace;
}
std::future<void>
ADIOS2IOHandlerImpl::flush(internal::ParsedFlushParams &flushParams)
{
auto res = AbstractIOHandlerImpl::flush();
detail::BufferedActions::ADIOS2FlushParams adios2FlushParams{
flushParams.flushLevel, m_flushTarget};
if (flushParams.backendConfig.json().contains("adios2"))
{
auto adios2Config = flushParams.backendConfig["adios2"];
if (adios2Config.json().contains("engine"))
{
auto engineConfig = adios2Config["engine"];
if (engineConfig.json().contains(ADIOS2Defaults::str_flushtarget))
{
auto target = json::asLowerCaseStringDynamic(
engineConfig[ADIOS2Defaults::str_flushtarget].json());
if (!target.has_value())
{
throw error::BackendConfigSchema(
{"adios2", "engine", ADIOS2Defaults::str_flushtarget},
"Flush target must be either 'disk' or 'buffer', but "
"was non-literal type.");
}
overrideFlushTarget(
adios2FlushParams.flushTarget,
flushTargetFromString(target.value()));
}
}
if (auto shadow = adios2Config.invertShadow(); shadow.size() > 0)
{
switch (adios2Config.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"
<< asToml << std::endl;
break;
}
}
}
}
for (auto &p : m_fileData)
{
if (m_dirty.find(p.first) != m_dirty.end())
{
p.second->flush(adios2FlushParams, /* writeLatePuts = */ false);
}
else
{
p.second->drop();
}
}
return res;
}
void ADIOS2IOHandlerImpl::createFile(
Writable *writable, Parameter<Operation::CREATE_FILE> const ¶meters)
{
VERIFY_ALWAYS(
access::write(m_handler->m_backendAccess),
"[ADIOS2] Creating a file in read-only mode is not possible.");
if (!writable->written)
{
std::string name = parameters.name + fileSuffix();
auto res_pair = getPossiblyExisting(name);
InvalidatableFile shared_name = InvalidatableFile(name);
VERIFY_ALWAYS(
!(m_handler->m_backendAccess == Access::READ_WRITE &&
(!std::get<PE_NewlyCreated>(res_pair) ||
auxiliary::file_exists(
fullPath(std::get<PE_InvalidatableFile>(res_pair))))),
"[ADIOS2] Can only overwrite existing file in CREATE mode.");
if (!std::get<PE_NewlyCreated>(res_pair))
{
auto file = std::get<PE_InvalidatableFile>(res_pair);
m_dirty.erase(file);
dropFileData(file);
file.invalidate();
}
std::string const dir(m_handler->directory);
if (!auxiliary::directory_exists(dir))
{
auto success = auxiliary::create_directories(dir);
VERIFY(success, "[ADIOS2] Could not create directory.");
}
m_iterationEncoding = parameters.encoding;
associateWithFile(writable, shared_name);
this->m_dirty.emplace(shared_name);
writable->written = true;
writable->abstractFilePosition = std::make_shared<ADIOS2FilePosition>();
// enforce opening the file
// lazy opening is deathly in parallel situations
getFileData(shared_name, IfFileNotOpen::OpenImplicitly);
}
}
void ADIOS2IOHandlerImpl::checkFile(
Writable *, Parameter<Operation::CHECK_FILE> ¶meters)
{
std::string name =
fullPath(parameters.name + fileSuffix(/* verbose = */ false));
using FileExists = Parameter<Operation::CHECK_FILE>::FileExists;
*parameters.fileExists = checkFile(name) ? FileExists::Yes : FileExists::No;
}
bool ADIOS2IOHandlerImpl::checkFile(std::string fullFilePath) const
{
if (m_engineType == "bp3")
{
if (!auxiliary::ends_with(fullFilePath, ".bp"))
{
/*
* BP3 will add this ending if not specified
*/
fullFilePath += ".bp";
}
}
else if (m_engineType == "sst")
{
/*
* SST will add this ending indiscriminately
*/
fullFilePath += ".sst";
}
bool fileExists = auxiliary::directory_exists(fullFilePath) ||
auxiliary::file_exists(fullFilePath);
#if openPMD_HAVE_MPI
if (m_communicator.has_value())
{
bool fileExistsRes = false;
int status = MPI_Allreduce(
&fileExists,
&fileExistsRes,
1,
MPI_C_BOOL,
MPI_LOR, // logical or
m_communicator.value());
if (status != 0)
{
throw std::runtime_error("MPI Reduction failed!");
}
fileExists = fileExistsRes;
}
#endif
return fileExists;
}
void ADIOS2IOHandlerImpl::createPath(
Writable *writable, const Parameter<Operation::CREATE_PATH> ¶meters)
{
std::string path;
refreshFileFromParent(writable, /* preferParentFile = */ true);
/* Sanitize path */
if (!auxiliary::starts_with(parameters.path, '/'))
{
path = filePositionToString(setAndGetFilePosition(writable)) + "/" +
auxiliary::removeSlashes(parameters.path);
}
else
{
path = "/" + auxiliary::removeSlashes(parameters.path);
}
/* ADIOS has no concept for explicitly creating paths.
* They are implicitly created with the paths of variables/attributes. */
writable->written = true;
writable->abstractFilePosition = std::make_shared<ADIOS2FilePosition>(
path, ADIOS2FilePosition::GD::GROUP);
}
void ADIOS2IOHandlerImpl::createDataset(
Writable *writable, const Parameter<Operation::CREATE_DATASET> ¶meters)
{
if (access::readOnly(m_handler->m_backendAccess))
{
throw std::runtime_error(
"[ADIOS2] Creating a dataset in a file opened as read "
"only is not possible.");
}
if (!writable->written)
{
/* Sanitize name */
std::string name = auxiliary::removeSlashes(parameters.name);
auto const file =
refreshFileFromParent(writable, /* preferParentFile = */ true);
auto filePos = setAndGetFilePosition(writable, name);
filePos->gd = ADIOS2FilePosition::GD::DATASET;
auto const varName = nameOfVariable(writable);
std::vector<ParameterizedOperator> operators;
json::TracingJSON options =
json::parseOptions(parameters.options, /* considerFiles = */ false);
if (options.json().contains("adios2"))
{
json::TracingJSON datasetConfig(options["adios2"]);
auto datasetOperators = getOperators(datasetConfig);
operators = datasetOperators ? std::move(datasetOperators.value())
: defaultOperators;
}
else
{
operators = defaultOperators;
}
parameters.warnUnusedParameters(
options,
"adios2",
"Warning: parts of the backend configuration for ADIOS2 dataset '" +
varName + "' remain unused:\n");
// cast from openPMD::Extent to adios2::Dims
adios2::Dims const shape(
parameters.extent.begin(), parameters.extent.end());
auto &fileData = getFileData(file, IfFileNotOpen::ThrowError);
#define HAS_BP5_BLOSC2_BUG \
(ADIOS2_VERSION_MAJOR * 100 + ADIOS2_VERSION_MINOR == 209 && \
ADIOS2_VERSION_PATCH <= 1)
#if HAS_BP5_BLOSC2_BUG
std::string engineType = fileData.getEngine().Type();
std::transform(
engineType.begin(),
engineType.end(),
engineType.begin(),
[](unsigned char c) { return std::tolower(c); });
if (!printedWarningsAlready.blosc2bp5 && engineType == "bp5writer")
{
for (auto const &op : operators)
{
std::string operatorType = op.op.Type();
std::transform(
operatorType.begin(),
operatorType.end(),
operatorType.begin(),
[](unsigned char c) { return std::tolower(c); });
if (operatorType == "blosc")
{
std::cerr << &R"(
[Warning] Use BP5+Blosc with care in ADIOS2 v2.9.0 and v2.9.1.
Unreadable data might be created, to mitigate either deactivate Blosc or use BP4+Blosc.
For further details see
https://github.com/ornladios/ADIOS2/issues/3504.
)"[1] << std::endl;
printedWarningsAlready.blosc2bp5 = true;
}
}
}
#endif
#undef HAS_BP5_BLOSC2_BUG
switchAdios2VariableType<detail::VariableDefiner>(
parameters.dtype, fileData.m_IO, varName, operators, shape);
fileData.invalidateVariablesMap();
writable->written = true;
m_dirty.emplace(file);
}
}
namespace detail
{
struct DatasetExtender
{
template <typename T, typename... Args>
static void call(
adios2::IO &IO, std::string const &variable, Extent const &newShape)
{
auto var = IO.InquireVariable<T>(variable);
if (!var)
{
throw std::runtime_error(
"[ADIOS2] Unable to retrieve variable for resizing: '" +
variable + "'.");
}
adios2::Dims dims;
dims.reserve(newShape.size());
for (auto ext : newShape)
{
dims.push_back(ext);
}
var.SetShape(dims);
}
static constexpr char const *errorMsg = "ADIOS2: extendDataset()";
};
} // namespace detail
void ADIOS2IOHandlerImpl::extendDataset(
Writable *writable, const Parameter<Operation::EXTEND_DATASET> ¶meters)
{
VERIFY_ALWAYS(
access::write(m_handler->m_backendAccess),
"[ADIOS2] Cannot extend datasets in read-only mode.");
setAndGetFilePosition(writable);
auto file = refreshFileFromParent(writable, /* preferParentFile = */ false);
std::string name = nameOfVariable(writable);
auto &filedata = getFileData(file, IfFileNotOpen::ThrowError);
Datatype dt = detail::fromADIOS2Type(filedata.m_IO.VariableType(name));
switchAdios2VariableType<detail::DatasetExtender>(
dt, filedata.m_IO, name, parameters.extent);
}
void ADIOS2IOHandlerImpl::openFile(
Writable *writable, Parameter<Operation::OPEN_FILE> ¶meters)
{
if (!auxiliary::directory_exists(m_handler->directory))
{
throw error::ReadError(
error::AffectedObject::File,
error::Reason::Inaccessible,
"ADIOS2",
"Supplied directory is not valid: " + m_handler->directory);
}
std::string name = parameters.name + fileSuffix();
auto file = std::get<PE_InvalidatableFile>(getPossiblyExisting(name));
associateWithFile(writable, file);
writable->written = true;
writable->abstractFilePosition = std::make_shared<ADIOS2FilePosition>();
m_iterationEncoding = parameters.encoding;
// enforce opening the file
// lazy opening is deathly in parallel situations
auto &fileData = getFileData(file, IfFileNotOpen::OpenImplicitly);
*parameters.out_parsePreference = fileData.parsePreference;
}
void ADIOS2IOHandlerImpl::closeFile(
Writable *writable, Parameter<Operation::CLOSE_FILE> const &)
{
auto fileIterator = m_files.find(writable);
if (fileIterator != m_files.end())
{
// do not invalidate the file
// it still exists, it is just not open
auto it = m_fileData.find(fileIterator->second);
if (it != m_fileData.end())
{
/*
* No need to finalize unconditionally, destructor will take care
* of it.
*/
it->second->flush(
FlushLevel::UserFlush,
[](detail::BufferedActions &ba, adios2::Engine &) {
ba.finalize();
},
/* writeLatePuts = */ true,
/* flushUnconditionally = */ false);
m_fileData.erase(it);
}
m_dirty.erase(fileIterator->second);
m_files.erase(fileIterator);
}
}
void ADIOS2IOHandlerImpl::openPath(
Writable *writable, const Parameter<Operation::OPEN_PATH> ¶meters)
{
/* Sanitize path */
refreshFileFromParent(writable, /* preferParentFile = */ true);
std::string prefix =
filePositionToString(setAndGetFilePosition(writable->parent));
std::string suffix = auxiliary::removeSlashes(parameters.path);
std::string infix =
suffix.empty() || auxiliary::ends_with(prefix, '/') ? "" : "/";
/* ADIOS has no concept for explicitly creating paths.
* They are implicitly created with the paths of variables/attributes. */
writable->abstractFilePosition = std::make_shared<ADIOS2FilePosition>(
prefix + infix + suffix, ADIOS2FilePosition::GD::GROUP);
writable->written = true;
}
void ADIOS2IOHandlerImpl::openDataset(
Writable *writable, Parameter<Operation::OPEN_DATASET> ¶meters)
{
auto name = auxiliary::removeSlashes(parameters.name);
writable->abstractFilePosition.reset();
auto pos = setAndGetFilePosition(writable, name);
pos->gd = ADIOS2FilePosition::GD::DATASET;
auto file = refreshFileFromParent(writable, /* preferParentFile = */ true);
auto varName = nameOfVariable(writable);
*parameters.dtype =
detail::fromADIOS2Type(getFileData(file, IfFileNotOpen::ThrowError)
.m_IO.VariableType(varName));
switchAdios2VariableType<detail::DatasetOpener>(
*parameters.dtype, this, file, varName, parameters);
writable->written = true;
}
void ADIOS2IOHandlerImpl::deleteFile(
Writable *, const Parameter<Operation::DELETE_FILE> &)
{
throw std::runtime_error("[ADIOS2] Backend does not support deletion.");
}
void ADIOS2IOHandlerImpl::deletePath(
Writable *, const Parameter<Operation::DELETE_PATH> &)
{
throw std::runtime_error("[ADIOS2] Backend does not support deletion.");
}
void ADIOS2IOHandlerImpl::deleteDataset(
Writable *, const Parameter<Operation::DELETE_DATASET> &)
{
// call filedata.invalidateVariablesMap
throw std::runtime_error("[ADIOS2] Backend does not support deletion.");
}
void ADIOS2IOHandlerImpl::deleteAttribute(
Writable *, const Parameter<Operation::DELETE_ATT> &)
{
// call filedata.invalidateAttributesMap
throw std::runtime_error("[ADIOS2] Backend does not support deletion.");
}
void ADIOS2IOHandlerImpl::writeDataset(
Writable *writable, Parameter<Operation::WRITE_DATASET> ¶meters)
{
VERIFY_ALWAYS(
access::write(m_handler->m_backendAccess),
"[ADIOS2] Cannot write data in read-only mode.");
setAndGetFilePosition(writable);
auto file = refreshFileFromParent(writable, /* preferParentFile = */ false);
detail::BufferedActions &ba = getFileData(file, IfFileNotOpen::ThrowError);
detail::BufferedPut bp;
bp.name = nameOfVariable(writable);
bp.param = std::move(parameters);
ba.enqueue(std::move(bp));
m_dirty.emplace(std::move(file));
writable->written = true; // TODO erst nach dem Schreiben?
}
void ADIOS2IOHandlerImpl::writeAttribute(
Writable *writable, const Parameter<Operation::WRITE_ATT> ¶meters)
{
switch (attributeLayout())
{
case AttributeLayout::ByAdiosAttributes:
if (parameters.changesOverSteps)
{
// cannot do this
return;
}
switchType<detail::OldAttributeWriter>(
parameters.dtype, this, writable, parameters);
break;
case AttributeLayout::ByAdiosVariables: {
VERIFY_ALWAYS(
access::write(m_handler->m_backendAccess),
"[ADIOS2] Cannot write attribute in read-only mode.");
auto pos = setAndGetFilePosition(writable);
auto file =
refreshFileFromParent(writable, /* preferParentFile = */ false);
auto fullName = nameOfAttribute(writable, parameters.name);
auto prefix = filePositionToString(pos);
auto &filedata = getFileData(file, IfFileNotOpen::ThrowError);
if (parameters.changesOverSteps &&
filedata.streamStatus ==
detail::BufferedActions::StreamStatus::NoStream)
{
// cannot do this
return;
}
filedata.requireActiveStep();
filedata.invalidateAttributesMap();
m_dirty.emplace(std::move(file));
// this intentionally overwrites previous writes
auto &bufferedWrite = filedata.m_attributeWrites[fullName];
bufferedWrite.name = fullName;
bufferedWrite.dtype = parameters.dtype;
bufferedWrite.resource = parameters.resource;
break;
}
default:
throw std::runtime_error("Unreachable!");
}
}
void ADIOS2IOHandlerImpl::readDataset(
Writable *writable, Parameter<Operation::READ_DATASET> ¶meters)
{
setAndGetFilePosition(writable);
auto file = refreshFileFromParent(writable, /* preferParentFile = */ false);
detail::BufferedActions &ba = getFileData(file, IfFileNotOpen::ThrowError);
detail::BufferedGet bg;
bg.name = nameOfVariable(writable);
bg.param = parameters;
ba.enqueue(std::move(bg));
m_dirty.emplace(std::move(file));
}
namespace detail
{
struct GetSpan
{
template <typename T, typename... Args>
static void call(
ADIOS2IOHandlerImpl *impl,
Parameter<Operation::GET_BUFFER_VIEW> ¶ms,
detail::BufferedActions &ba,
std::string const &varName)
{
auto &IO = ba.m_IO;
auto &engine = ba.getEngine();
adios2::Variable<T> variable = impl->verifyDataset<T>(
params.offset, params.extent, IO, varName);
adios2::Dims offset(params.offset.begin(), params.offset.end());
adios2::Dims extent(params.extent.begin(), params.extent.end());
variable.SetSelection({std::move(offset), std::move(extent)});
typename adios2::Variable<T>::Span span = engine.Put(variable);
params.out->backendManagedBuffer = true;
/*
* SIC!
* Do not emplace span.data() yet.
* Only call span.data() as soon as the user needs the pointer
* (will always be propagated to the backend with parameters.update
* = true).
* This avoids repeated resizing of ADIOS2 internal buffers if
* calling multiple spans.
*/
// params.out->ptr = span.data();
unsigned nextIndex;
if (ba.m_updateSpans.empty())
{
nextIndex = 0;
}
else
{
nextIndex = ba.m_updateSpans.rbegin()->first + 1;
}
params.out->viewIndex = nextIndex;
std::unique_ptr<I_UpdateSpan> updateSpan{
new UpdateSpan<T>{std::move(span)}};
ba.m_updateSpans.emplace_hint(
ba.m_updateSpans.end(), nextIndex, std::move(updateSpan));
}
static constexpr char const *errorMsg = "ADIOS2: getBufferView()";
};
struct HasOperators
{
template <typename T>
static bool call(std::string const &name, adios2::IO &IO)
{
adios2::Variable<T> variable = IO.InquireVariable<T>(name);
if (!variable)
{
return false;
}
return !variable.Operations().empty();
}
static constexpr char const *errorMsg = "ADIOS2: getBufferView()";
};
} // namespace detail
void ADIOS2IOHandlerImpl::getBufferView(
Writable *writable, Parameter<Operation::GET_BUFFER_VIEW> ¶meters)
{