forked from openPMD/openPMD-api
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathJSONIOHandlerImpl.cpp
More file actions
2499 lines (2330 loc) · 77.1 KB
/
JSONIOHandlerImpl.cpp
File metadata and controls
2499 lines (2330 loc) · 77.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
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-2025 Franz Poeschel, Axel Huebl, Junmin Gu, Luca Fedeli
*
* 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/JSON/JSONIOHandlerImpl.hpp"
#include "openPMD/Datatype.hpp"
#include "openPMD/Error.hpp"
#include "openPMD/IO/AbstractIOHandler.hpp"
#include "openPMD/IO/AbstractIOHandlerImpl.hpp"
#include "openPMD/ThrowError.hpp"
#include "openPMD/auxiliary/Filesystem.hpp"
#include "openPMD/auxiliary/JSONMatcher.hpp"
#include "openPMD/auxiliary/JSON_internal.hpp"
#include "openPMD/auxiliary/Memory.hpp"
#include "openPMD/auxiliary/StringManip.hpp"
#include "openPMD/auxiliary/TypeTraits.hpp"
#include "openPMD/backend/Attribute.hpp"
#include "openPMD/backend/Writable.hpp"
#include <iomanip>
#include <sstream>
#include <toml.hpp>
#include <algorithm>
#include <exception>
#include <iostream>
#include <optional>
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)); \
}
namespace JSONDefaults
{
using const_str = char const *const;
constexpr const_str openpmd_internal = "__openPMD_internal";
constexpr const_str DatasetMode = "dataset_mode";
constexpr const_str AttributeMode = "attribute_mode";
} // namespace JSONDefaults
namespace
{
struct DefaultValue
{
template <typename T>
static nlohmann::json call()
{
if constexpr (auxiliary::IsComplex_v<T>)
{
return typename T::value_type{};
}
else
{
return T{};
}
#if defined(__INTEL_COMPILER)
/*
* ICPC has trouble with if constexpr, thinking that return statements are
* missing afterwards. Deactivate the warning.
* Note that putting a statement here will not help to fix this since it will
* then complain about unreachable code.
* https://community.intel.com/t5/Intel-C-Compiler/quot-if-constexpr-quot-and-quot-missing-return-statement-quot-in/td-p/1154551
*/
#pragma warning(disable : 1011)
}
#pragma warning(default : 1011)
#else
}
#endif
template <int>
static nlohmann::json call()
{
return 0;
}
};
/*
* If initializeWithDefaultValue contains a datatype, then the dataset ought
* to be initialized with the zero value of that dataset.
* Otherwise with null.
*/
nlohmann::json initializeNDArray(
Extent const &extent,
std::optional<Datatype> initializeWithDefaultValue)
{
// idea: begin from the innermost shale and copy the result into the
// outer shales
nlohmann::json accum = initializeWithDefaultValue.has_value()
? switchNonVectorType<DefaultValue>(
initializeWithDefaultValue.value())
: nlohmann::json();
nlohmann::json old;
auto *accum_ptr = &accum;
auto *old_ptr = &old;
for (auto it = extent.rbegin(); it != extent.rend(); it++)
{
std::swap(old_ptr, accum_ptr);
*accum_ptr = nlohmann::json::array();
for (Extent::value_type i = 0; i < *it; i++)
{
(*accum_ptr)[i] = *old_ptr; // copy boi
}
}
return *accum_ptr;
}
void warnUnusedJson(openPMD::json::TracingJSON const &jsonConfig)
{
auto shadow = jsonConfig.invertShadow();
if (shadow.size() > 0)
{
switch (jsonConfig.originallySpecifiedAs)
{
case openPMD::json::SupportedLanguages::JSON:
std::cerr << "Warning: parts of the backend configuration for "
"JSON/TOML backend remain unused:\n"
<< shadow << '\n';
break;
case openPMD::json::SupportedLanguages::TOML: {
auto asToml = openPMD::json::jsonToToml(shadow);
std::cerr << "Warning: parts of the backend configuration for "
"JSON/TOML backend remain unused:\n"
<< json::format_toml(asToml) << '\n';
break;
}
}
}
}
// Does the same as datatypeToString(), but this makes sure that we don't
// accidentally change the JSON schema by modifying datatypeToString()
std::string jsonDatatypeToString(Datatype dt)
{
switch (dt)
{
using DT = Datatype;
case DT::CHAR:
return "CHAR";
case DT::UCHAR:
return "UCHAR";
case DT::SCHAR:
return "SCHAR";
case DT::SHORT:
return "SHORT";
case DT::INT:
return "INT";
case DT::LONG:
return "LONG";
case DT::LONGLONG:
return "LONGLONG";
case DT::USHORT:
return "USHORT";
case DT::UINT:
return "UINT";
case DT::ULONG:
return "ULONG";
case DT::ULONGLONG:
return "ULONGLONG";
case DT::FLOAT:
return "FLOAT";
case DT::DOUBLE:
return "DOUBLE";
case DT::LONG_DOUBLE:
return "LONG_DOUBLE";
case DT::CFLOAT:
return "CFLOAT";
case DT::CDOUBLE:
return "CDOUBLE";
case DT::CLONG_DOUBLE:
return "CLONG_DOUBLE";
case DT::STRING:
return "STRING";
case DT::VEC_CHAR:
return "VEC_CHAR";
case DT::VEC_SHORT:
return "VEC_SHORT";
case DT::VEC_INT:
return "VEC_INT";
case DT::VEC_LONG:
return "VEC_LONG";
case DT::VEC_LONGLONG:
return "VEC_LONGLONG";
case DT::VEC_UCHAR:
return "VEC_UCHAR";
case DT::VEC_USHORT:
return "VEC_USHORT";
case DT::VEC_UINT:
return "VEC_UINT";
case DT::VEC_ULONG:
return "VEC_ULONG";
case DT::VEC_ULONGLONG:
return "VEC_ULONGLONG";
case DT::VEC_FLOAT:
return "VEC_FLOAT";
case DT::VEC_DOUBLE:
return "VEC_DOUBLE";
case DT::VEC_LONG_DOUBLE:
return "VEC_LONG_DOUBLE";
case DT::VEC_CFLOAT:
return "VEC_CFLOAT";
case DT::VEC_CDOUBLE:
return "VEC_CDOUBLE";
case DT::VEC_CLONG_DOUBLE:
return "VEC_CLONG_DOUBLE";
case DT::VEC_SCHAR:
return "VEC_SCHAR";
case DT::VEC_STRING:
return "VEC_STRING";
case DT::ARR_DBL_7:
return "ARR_DBL_7";
case DT::BOOL:
return "BOOL";
case DT::UNDEFINED:
return "UNDEFINED";
}
return "Unreachable!";
}
} // namespace
auto JSONIOHandlerImpl::retrieveDatasetMode(
openPMD::json::TracingJSON &config) const -> DatasetMode_s
{
// start with / copy from current config
auto res = m_datasetMode;
DatasetMode &ioMode = res.m_mode;
SpecificationVia &specificationVia = res.m_specificationVia;
bool &skipWarnings = res.m_skipWarnings;
if (auto [configLocation, maybeConfig] = getBackendConfig(config);
maybeConfig.has_value())
{
auto jsonConfig = maybeConfig.value();
if (jsonConfig.json().contains("dataset"))
{
auto datasetConfig = jsonConfig["dataset"];
if (datasetConfig.json().contains("mode"))
{
auto modeOption = openPMD::json::asLowerCaseStringDynamic(
datasetConfig["mode"].json());
if (!modeOption.has_value())
{
throw error::BackendConfigSchema(
{configLocation, "mode"},
"Invalid value of non-string type (accepted values are "
"'dataset' and 'template'.");
}
auto mode = modeOption.value();
if (mode == "dataset")
{
ioMode = DatasetMode::Dataset;
specificationVia = SpecificationVia::Manually;
}
else if (mode == "template")
{
ioMode = DatasetMode::Template;
specificationVia = SpecificationVia::Manually;
}
else if (mode == "template_no_warn")
{
ioMode = DatasetMode::Template;
specificationVia = SpecificationVia::Manually;
skipWarnings = true;
}
else
{
throw error::BackendConfigSchema(
{configLocation, "dataset", "mode"},
"Invalid value: '" + mode +
"' (accepted values are 'dataset' and 'template'.");
}
}
}
}
return res;
}
auto JSONIOHandlerImpl::retrieveAttributeMode(
openPMD::json::TracingJSON &config) const -> AttributeMode_s
{
// start with / copy from current config
auto res = m_attributeMode;
AttributeMode &mode = res.m_mode;
SpecificationVia &specificationVia = res.m_specificationVia;
if (auto [configLocation, maybeConfig] = getBackendConfig(config);
maybeConfig.has_value())
{
auto jsonConfig = maybeConfig.value();
if (jsonConfig.json().contains("attribute"))
{
auto attributeConfig = jsonConfig["attribute"];
if (attributeConfig.json().contains("mode"))
{
auto modeOption = openPMD::json::asLowerCaseStringDynamic(
attributeConfig["mode"].json());
if (!modeOption.has_value())
{
throw error::BackendConfigSchema(
{configLocation, "mode"},
"Invalid value of non-string type (accepted values are "
"'dataset' and 'template'.");
}
auto modeCfg = modeOption.value();
if (modeCfg == "short")
{
mode = AttributeMode::Short;
specificationVia = SpecificationVia::Manually;
}
else if (modeCfg == "long")
{
mode = AttributeMode::Long;
specificationVia = SpecificationVia::Manually;
}
else
{
throw error::BackendConfigSchema(
{configLocation, "attribute", "mode"},
"Invalid value: '" + modeCfg +
"' (accepted values are 'short' and 'long'.");
}
}
}
}
return res;
}
std::string JSONIOHandlerImpl::backendConfigKey() const
{
switch (m_fileFormat)
{
case FileFormat::Json:
return "json";
case FileFormat::Toml:
return "toml";
}
throw std::runtime_error("Unreachable!");
}
std::pair<std::string, std::optional<openPMD::json::TracingJSON>>
JSONIOHandlerImpl::getBackendConfig(openPMD::json::TracingJSON &config) const
{
std::string configLocation = backendConfigKey();
if (config.json().contains(configLocation))
{
return std::make_pair(
std::move(configLocation), config[configLocation]);
}
else
{
return std::make_pair(std::move(configLocation), std::nullopt);
}
}
JSONIOHandlerImpl::JSONIOHandlerImpl(
AbstractIOHandler *handler,
FileFormat format,
std::string originalExtension)
: AbstractIOHandlerImpl(handler)
, m_fileFormat{format}
, m_originalExtension{std::move(originalExtension)}
{
init(handler->jsonMatcher->getDefault(backendConfigKey()));
}
#if openPMD_HAVE_MPI
JSONIOHandlerImpl::JSONIOHandlerImpl(
AbstractIOHandler *handler,
MPI_Comm comm,
FileFormat format,
std::string originalExtension)
: AbstractIOHandlerImpl(handler)
, m_communicator{comm}
, m_fileFormat{format}
, m_originalExtension{std::move(originalExtension)}
{
init(handler->jsonMatcher->getDefault(backendConfigKey()));
}
#endif
void JSONIOHandlerImpl::init(openPMD::json::TracingJSON config)
{
// set the defaults
switch (m_fileFormat)
{
case FileFormat::Json:
// Set the attribute mode to Long for now, needs to be evaluated
// again when creating a new file, since the openPMD version might
// be specified via Series::setOpenPMD() after initialization of the
// JSON backend.
m_attributeMode.m_mode = AttributeMode::Long;
m_datasetMode.m_mode = DatasetMode::Dataset;
break;
case FileFormat::Toml:
m_attributeMode.m_mode = AttributeMode::Short;
m_datasetMode.m_mode = DatasetMode::Dataset;
break;
}
// now modify according to config
m_datasetMode = retrieveDatasetMode(config);
m_attributeMode = retrieveAttributeMode(config);
if (auto [_, backendConfig] = getBackendConfig(config);
backendConfig.has_value())
{
(void)_;
warnUnusedJson(backendConfig.value());
}
}
JSONIOHandlerImpl::~JSONIOHandlerImpl() = default;
std::future<void> JSONIOHandlerImpl::flush()
{
AbstractIOHandlerImpl::flush();
if (access::readOnly(m_handler->m_backendAccess) && !m_dirty.empty())
{
throw error::Internal(
"JSON backend: Cannot have dirty files in read-only modes.");
}
for (auto const &file : m_dirty)
{
putJsonContents(file, false);
}
m_dirty.clear();
return std::future<void>();
}
void JSONIOHandlerImpl::createFile(
Writable *writable, Parameter<Operation::CREATE_FILE> const ¶meters)
{
VERIFY_ALWAYS(
access::write(m_handler->m_backendAccess),
"[JSON] Creating a file in read-only mode is not possible.");
/*
* Need to resolve this later than init() since the openPMD version might be
* specified after the creation of the IOHandler.
*/
if (m_attributeMode.m_specificationVia == SpecificationVia::DefaultValue)
{
switch (m_fileFormat)
{
case FileFormat::Json:
m_attributeMode.m_mode =
m_handler->m_standard >= OpenpmdStandard::v_2_0_0
? AttributeMode::Short
: AttributeMode::Long;
break;
default:
break;
}
}
if (!writable->written)
{
std::string name = parameters.name + m_originalExtension;
auto res_pair = getPossiblyExisting(name);
auto fullPathToFile = fullPath(std::get<0>(res_pair));
File shared_name = File(name);
VERIFY_ALWAYS(
!(m_handler->m_backendAccess == Access::READ_WRITE &&
(!std::get<2>(res_pair) ||
auxiliary::file_exists(fullPathToFile))),
"[JSON] Can only overwrite existing file in CREATE mode.");
if (!std::get<2>(res_pair))
{
auto file = std::get<0>(res_pair);
m_dirty.erase(file);
m_jsonVals.erase(file);
file.invalidate();
}
std::string const &dir(m_handler->directory);
if (!auxiliary::directory_exists(dir))
{
auto success = auxiliary::create_directories(dir);
VERIFY(success, "[JSON] Could not create directory.");
}
associateWithFile(writable, shared_name);
this->m_dirty.emplace(shared_name);
if (!access::append(m_handler->m_backendAccess) ||
!auxiliary::file_exists(fullPathToFile))
{
// if in create mode: make sure to overwrite
// if in append mode and the file does not exist: create an empty
// dataset
this->m_jsonVals[shared_name] = std::make_shared<nlohmann::json>();
}
// else: the JSON value is not available in m_jsonVals and will be
// read from the file later on before overwriting
writable->written = true;
writable->abstractFilePosition = std::make_shared<JSONFilePosition>();
}
}
void JSONIOHandlerImpl::checkFile(
Writable *, Parameter<Operation::CHECK_FILE> ¶meters)
{
std::string name = parameters.name;
if (!auxiliary::ends_with(name, ".json"))
{
name += ".json";
}
name = fullPath(name);
using FileExists = Parameter<Operation::CHECK_FILE>::FileExists;
*parameters.fileExists =
(auxiliary::file_exists(name) || auxiliary::directory_exists(name))
? FileExists::Yes
: FileExists::No;
}
void JSONIOHandlerImpl::createPath(
Writable *writable, Parameter<Operation::CREATE_PATH> const ¶meter)
{
std::string path = parameter.path;
/* Sanitize:
* The JSON API does not like to have slashes in the end.
*/
if (auxiliary::ends_with(path, "/"))
{
path = auxiliary::replace_last(path, "/", "");
}
auto file = refreshFileFromParent(writable);
auto *jsonVal = &*obtainJsonContents(file);
if (!auxiliary::starts_with(path, "/"))
{ // path is relative
auto filepos = setAndGetFilePosition(writable, false);
jsonVal = &(*jsonVal)[filepos->id];
ensurePath(jsonVal, path);
path = filepos->id.to_string() + "/" + path;
}
else
{
ensurePath(jsonVal, path);
}
m_dirty.emplace(file);
writable->written = true;
writable->abstractFilePosition =
std::make_shared<JSONFilePosition>(nlohmann::json::json_pointer(path));
}
void JSONIOHandlerImpl::createDataset(
Writable *writable, Parameter<Operation::CREATE_DATASET> const ¶meter)
{
if (access::readOnly(m_handler->m_backendAccess))
{
throw std::runtime_error(
"[JSON] Creating a dataset in a file opened as read only is not "
"possible.");
}
if (parameter.joinedDimension.has_value())
{
error::throwOperationUnsupportedInBackend(
"JSON", "Joined Arrays currently only supported in ADIOS2");
}
openPMD::json::TracingJSON config = openPMD::json::parseOptions(
parameter.options, /* considerFiles = */ false);
// Retrieves mode from dataset-specific configuration, falls back to global
// value if not defined
auto [localMode, _, skipWarnings] = retrieveDatasetMode(config);
(void)_;
// No use in introducing logic to skip warnings only for one particular
// dataset. If warnings are skipped, then they are skipped consistently.
// Use |= since `false` is the default value and we don't wish to reset
// the flag.
m_datasetMode.m_skipWarnings |= skipWarnings;
parameter.warnUnusedParameters(
config,
backendConfigKey(),
"Warning: parts of the dataset-specific backend configuration for "
"JSON/TOML backend remain unused");
if (!writable->written)
{
/* Sanitize name */
std::string name = removeSlashes(parameter.name);
auto file = refreshFileFromParent(writable);
writable->abstractFilePosition.reset();
setAndGetFilePosition(writable);
auto &jsonVal = obtainJsonContents(writable);
// be sure to have a JSON object, not a list
if (jsonVal.empty())
{
jsonVal = nlohmann::json::object();
}
setAndGetFilePosition(writable, name);
auto &dset = jsonVal[name];
dset["datatype"] = jsonDatatypeToString(parameter.dtype);
switch (localMode)
{
case DatasetMode::Dataset: {
auto extent = parameter.extent;
switch (parameter.dtype)
{
case Datatype::CFLOAT:
case Datatype::CDOUBLE:
case Datatype::CLONG_DOUBLE: {
extent.push_back(2);
break;
}
default:
break;
}
if (parameter.extent.size() != 1 ||
parameter.extent[0] != Dataset::UNDEFINED_EXTENT)
{
// TOML does not support nulls, so initialize with zero
dset["data"] = initializeNDArray(
extent,
m_fileFormat == FileFormat::Json ? std::optional<Datatype>{}
: parameter.dtype);
}
break;
}
case DatasetMode::Template:
if (parameter.extent != Extent{0} &&
parameter.extent[0] != Dataset::UNDEFINED_EXTENT)
{
dset["extent"] = parameter.extent;
}
else
{
// no-op
// If extent is empty or no datatype is defined, don't bother
// writing it.
// The datatype is written above anyway.
}
break;
}
writable->written = true;
m_dirty.emplace(file);
}
}
namespace
{
void mergeInto(nlohmann::json &into, nlohmann::json &from);
void mergeInto(nlohmann::json &into, nlohmann::json &from)
{
if (!from.is_array())
{
into = from; // copy
}
else
{
size_t size = from.size();
for (size_t i = 0; i < size; ++i)
{
if (!from[i].is_null())
{
mergeInto(into[i], from[i]);
}
}
}
}
} // namespace
void JSONIOHandlerImpl::extendDataset(
Writable *writable, Parameter<Operation::EXTEND_DATASET> const ¶meters)
{
VERIFY_ALWAYS(
access::write(m_handler->m_backendAccess),
"[JSON] Cannot extend a dataset in read-only mode.")
if (parameters.joinedDimension.has_value())
{
error::throwOperationUnsupportedInBackend(
"JSON", "Joined Arrays currently only supported in ADIOS2");
}
setAndGetFilePosition(writable);
refreshFileFromParent(writable);
auto &j = obtainJsonContents(writable);
DatasetMode localIOMode;
try
{
Extent datasetExtent;
std::tie(datasetExtent, localIOMode) = getExtent(j);
VERIFY_ALWAYS(
datasetExtent.size() == parameters.extent.size(),
"[JSON] Cannot change dimensionality of a dataset")
for (size_t currentdim = 0; currentdim < parameters.extent.size();
currentdim++)
{
VERIFY_ALWAYS(
datasetExtent[currentdim] <= parameters.extent[currentdim],
"[JSON] Cannot shrink the extent of a dataset")
}
}
catch (json::basic_json::type_error &)
{
throw std::runtime_error(
"[JSON] The specified location contains no valid dataset");
}
switch (localIOMode)
{
case DatasetMode::Dataset: {
auto extent = parameters.extent;
auto datatype = stringToDatatype(j["datatype"].get<std::string>());
switch (datatype)
{
case Datatype::CFLOAT:
case Datatype::CDOUBLE:
case Datatype::CLONG_DOUBLE: {
extent.push_back(2);
break;
}
default:
// nothing to do
break;
}
// TOML does not support nulls, so initialize with zero
nlohmann::json newData = initializeNDArray(
extent,
m_fileFormat == FileFormat::Json ? std::optional<Datatype>{}
: datatype);
nlohmann::json &oldData = j["data"];
mergeInto(newData, oldData);
j["data"] = newData;
}
break;
case DatasetMode::Template: {
j["extent"] = parameters.extent;
}
break;
}
writable->written = true;
}
namespace
{
// pre-declare since this one is recursive
ChunkTable chunksInJSON(nlohmann::json const &);
ChunkTable chunksInJSON(nlohmann::json const &j)
{
/*
* Idea:
* Iterate (n-1)-dimensional hyperslabs line by line and query
* their chunks recursively.
* If two or more successive (n-1)-dimensional slabs return the
* same chunktable, they can be merged as one chunk.
*
* Notice that this approach is simple, relatively easily
* implemented, but not ideal, since chunks that overlap in some
* dimensions may be ripped apart:
*
* 0123
* 0 ____
* 1 ____
* 2 **__
* 3 **__
* 4 **__
* 5 **__
* 6 **__
* 7 **_*
* 8 ___*
* 9 ___*
*
* Since both of the drawn chunks overlap on line 7, this approach
* will return 4 chunks:
* offset - extent
* (2,0) - (4,2)
* (7,0) - (1,2)
* (7,3) - (1,1)
* (8,3) - (2,1)
*
* Hence, in a second phase, the mergeChunks function below will
* merge things back up.
*/
if (!j.is_array())
{
return ChunkTable{WrittenChunkInfo(Offset{}, Extent{})};
}
ChunkTable res;
size_t it = 0;
size_t end = j.size();
while (it < end)
{
// skip empty slots
while (it < end && j[it].is_null())
{
++it;
}
if (it == end)
{
break;
}
// get chunking at current position
// and additionally, number of successive rows with the same
// recursive results
size_t const offset = it;
ChunkTable referenceTable = chunksInJSON(j[it]);
++it;
for (; it < end; ++it)
{
if (j[it].is_null())
{
break;
}
ChunkTable currentTable = chunksInJSON(j[it]);
if (currentTable != referenceTable)
{
break;
}
}
size_t const extent = it - offset; // sic! no -1
// now we know the number of successive rows with same rec.
// results, let's extend these results to include dimension 0
for (auto const &chunk : referenceTable)
{
Offset o = {offset};
Extent e = {extent};
for (auto entry : chunk.offset)
{
o.push_back(entry);
}
for (auto entry : chunk.extent)
{
e.push_back(entry);
}
res.emplace_back(std::move(o), std::move(e), chunk.sourceID);
}
}
return res;
}
} // namespace
void JSONIOHandlerImpl::availableChunks(
Writable *writable, Parameter<Operation::AVAILABLE_CHUNKS> ¶meters)
{
refreshFileFromParent(writable);
auto filePosition = setAndGetFilePosition(writable);
auto &j = obtainJsonContents(writable)["data"];
*parameters.chunks = chunksInJSON(j);
chunk_assignment::mergeChunks(*parameters.chunks);
}
void JSONIOHandlerImpl::openFile(
Writable *writable, Parameter<Operation::OPEN_FILE> ¶meter)
{
if (!auxiliary::directory_exists(m_handler->directory))
{
throw error::ReadError(
error::AffectedObject::File,
error::Reason::Inaccessible,
"JSON",
"Supplied directory is not valid: " + m_handler->directory);
}
std::string name = parameter.name + m_originalExtension;
auto file = std::get<0>(getPossiblyExisting(name));
associateWithFile(writable, file);
writable->written = true;
writable->abstractFilePosition = std::make_shared<JSONFilePosition>();
}
void JSONIOHandlerImpl::closeFile(
Writable *writable, Parameter<Operation::CLOSE_FILE> const &)
{
auto fileIterator = m_files.find(writable);
if (fileIterator != m_files.end())
{
auto it = putJsonContents(fileIterator->second);
if (it != m_jsonVals.end())
{
m_jsonVals.erase(it);
}
m_dirty.erase(fileIterator->second);
// do not invalidate the file
// it still exists, it is just not open
m_files.erase(fileIterator);
}
}
void JSONIOHandlerImpl::openPath(
Writable *writable, Parameter<Operation::OPEN_PATH> const ¶meters)
{
auto file = refreshFileFromParent(writable);
nlohmann::json *j = &obtainJsonContents(writable->parent);
auto path = removeSlashes(parameters.path);
path = path.empty() ? filepositionOf(writable->parent)
: filepositionOf(writable->parent) + "/" + path;
if (writable->abstractFilePosition)
{
*setAndGetFilePosition(writable, false) =
JSONFilePosition(json::json_pointer(path));
}
else
{
writable->abstractFilePosition =
std::make_shared<JSONFilePosition>(json::json_pointer(path));
}
ensurePath(j, removeSlashes(parameters.path));
writable->written = true;
}
void JSONIOHandlerImpl::openDataset(
Writable *writable, Parameter<Operation::OPEN_DATASET> ¶meters)
{
refreshFileFromParent(writable);
auto name = removeSlashes(parameters.name);
auto &datasetJson = obtainJsonContents(writable->parent)[name];
/*
* If the dataset has been opened previously, the path needs not be
* set again.
*/
if (!writable->abstractFilePosition)
{
setAndGetFilePosition(writable, name);
}
*parameters.dtype =
Datatype(stringToDatatype(datasetJson["datatype"].get<std::string>()));
*parameters.extent = getExtent(datasetJson).first;
writable->written = true;
}
void JSONIOHandlerImpl::deleteFile(
Writable *writable, Parameter<Operation::DELETE_FILE> const ¶meters)
{
VERIFY_ALWAYS(
access::write(m_handler->m_backendAccess),
"[JSON] Cannot delete files in read-only mode")
if (!writable->written)
{
return;
}
auto filename = auxiliary::ends_with(parameters.name, ".json")
? parameters.name
: parameters.name + ".json";
auto tuple = getPossiblyExisting(filename);
if (!std::get<2>(tuple))
{
// file is already in the system
auto file = std::get<0>(tuple);
m_dirty.erase(file);
m_jsonVals.erase(file);
file.invalidate();