forked from openPMD/openPMD-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJSONIOHandlerImpl.cpp
1775 lines (1637 loc) · 52.2 KB
/
JSONIOHandlerImpl.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
*
* 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/DatatypeHelpers.hpp"
#include "openPMD/Error.hpp"
#include "openPMD/IO/AbstractIOHandler.hpp"
#include "openPMD/IO/AbstractIOHandlerImpl.hpp"
#include "openPMD/auxiliary/Filesystem.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/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
{
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
static constexpr char const *errorMsg = "JSON default value";
};
/*
* 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;
}
} // namespace
JSONIOHandlerImpl::JSONIOHandlerImpl(
AbstractIOHandler *handler,
// NOLINTNEXTLINE(performance-unnecessary-value-param)
[[maybe_unused]] openPMD::json::TracingJSON config,
FileFormat format,
std::string originalExtension)
: AbstractIOHandlerImpl(handler)
, m_fileFormat{format}
, m_originalExtension{std::move(originalExtension)}
{}
#if openPMD_HAVE_MPI
JSONIOHandlerImpl::JSONIOHandlerImpl(
AbstractIOHandler *handler,
MPI_Comm comm,
// NOLINTNEXTLINE(performance-unnecessary-value-param)
[[maybe_unused]] openPMD::json::TracingJSON config,
FileFormat format,
std::string originalExtension)
: AbstractIOHandlerImpl(handler)
, m_communicator{comm}
, m_fileFormat{format}
, m_originalExtension{std::move(originalExtension)}
{}
#endif
JSONIOHandlerImpl::~JSONIOHandlerImpl() = default;
std::future<void> JSONIOHandlerImpl::flush()
{
AbstractIOHandlerImpl::flush();
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.");
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 (m_handler->m_backendAccess != Access::APPEND ||
!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");
}
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"] = datatypeToString(parameter.dtype);
auto extent = parameter.extent;
switch (parameter.dtype)
{
case Datatype::CFLOAT:
case Datatype::CDOUBLE:
case Datatype::CLONG_DOUBLE: {
extent.push_back(2);
break;
}
default:
break;
}
// TOML does not support nulls, so initialize with zero
dset["data"] = initializeNDArray(
extent,
m_fileFormat == FileFormat::Json ? std::optional<Datatype>()
: parameter.dtype);
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.")
setAndGetFilePosition(writable);
refreshFileFromParent(writable);
auto &j = obtainJsonContents(writable);
try
{
auto datasetExtent = 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");
}
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;
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;
}
/*
* Check whether two chunks can be merged to form a large one
* and optionally return that larger chunk
*/
std::optional<WrittenChunkInfo>
mergeChunks(WrittenChunkInfo const &chunk1, WrittenChunkInfo const &chunk2)
{
/*
* Idea:
* If two chunks can be merged into one, they agree on offsets and
* extents in all but exactly one dimension dim.
* At dimension dim, the offset of chunk 2 is equal to the offset
* of chunk 1 plus its extent -- or vice versa.
*/
unsigned dimensionality = chunk1.extent.size();
for (unsigned dim = 0; dim < dimensionality; ++dim)
{
WrittenChunkInfo const *c1(&chunk1), *c2(&chunk2);
// check if one chunk is the extension of the other at
// dimension dim
// first, let's put things in order
if (c1->offset[dim] > c2->offset[dim])
{
std::swap(c1, c2);
}
// now, c1 begins at the lower of both offsets
// next check, that both chunks border one another exactly
if (c2->offset[dim] != c1->offset[dim] + c1->extent[dim])
{
continue;
}
// we've got a candidate
// verify that all other dimensions have equal values
auto equalValues = [dimensionality, dim, c1, c2]() {
for (unsigned j = 0; j < dimensionality; ++j)
{
if (j == dim)
{
continue;
}
if (c1->offset[j] != c2->offset[j] ||
c1->extent[j] != c2->extent[j])
{
return false;
}
}
return true;
};
if (!equalValues())
{
continue;
}
// we can merge the chunks
Offset offset(c1->offset);
Extent extent(c1->extent);
extent[dim] += c2->extent[dim];
return std::make_optional(WrittenChunkInfo(offset, extent));
}
return std::optional<WrittenChunkInfo>();
}
/*
* Merge chunks in the chunktable until no chunks are left that can be
* merged.
*/
void mergeChunks(ChunkTable &table)
{
bool stillChanging;
do
{
stillChanging = false;
auto innerLoops = [&table]() {
/*
* Iterate over pairs of chunks in the table.
* When a pair that can be merged is found, merge it,
* delete the original two chunks from the table,
* put the new one in and return.
*/
for (auto i = table.begin(); i < table.end(); ++i)
{
for (auto j = i + 1; j < table.end(); ++j)
{
std::optional<WrittenChunkInfo> merged =
mergeChunks(*i, *j);
if (merged)
{
// erase order is important due to iterator
// invalidation
table.erase(j);
table.erase(i);
table.emplace_back(std::move(merged.value()));
return true;
}
}
}
return false;
};
stillChanging = innerLoops();
} while (stillChanging);
}
} // 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);
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);
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();
}
std::remove(fullPath(filename).c_str());
writable->written = false;
}
void JSONIOHandlerImpl::deletePath(
Writable *writable, Parameter<Operation::DELETE_PATH> const ¶meters)
{
VERIFY_ALWAYS(
access::write(m_handler->m_backendAccess),
"[JSON] Cannot delete paths in read-only mode")
if (!writable->written)
{
return;
}
VERIFY_ALWAYS(
!auxiliary::starts_with(parameters.path, '/'),
"[JSON] Paths passed for deletion should be relative, the given path "
"is absolute (starts with '/')")
auto file = refreshFileFromParent(writable);
auto filepos = setAndGetFilePosition(writable, false);
auto path = removeSlashes(parameters.path);
VERIFY(!path.empty(), "[JSON] No path passed for deletion.")
nlohmann::json *j;
if (path == ".")
{
auto s = filepos->id.to_string();
if (s == "/")
{
throw std::runtime_error("[JSON] Cannot delete the root group");
}
auto i = s.rfind('/');
path = s;
path.replace(0, i + 1, "");
// path should now be equal to the name of the current group
// go up one group
// go to parent directory
// parent exists since we have verified that the current
// directory is != root
parentDir(s);
j = &(*obtainJsonContents(file))[nlohmann::json::json_pointer(s)];
}
else
{
if (auxiliary::starts_with(path, "./"))
{
path = auxiliary::replace_first(path, "./", "");
}
j = &obtainJsonContents(writable);
}
nlohmann::json *lastPointer = j;
bool needToDelete = true;
auto splitPath = auxiliary::split(path, "/");
// be careful not to create the group by accident
// the loop will execute at least once
for (auto const &folder : splitPath)
{
auto it = j->find(folder);
if (it == j->end())
{
needToDelete = false;
break;
}
else
{
lastPointer = j;
j = &it.value();
}
}
if (needToDelete)
{
lastPointer->erase(splitPath[splitPath.size() - 1]);
}
putJsonContents(file);
writable->abstractFilePosition.reset();
writable->written = false;
}
void JSONIOHandlerImpl::deleteDataset(
Writable *writable, Parameter<Operation::DELETE_DATASET> const ¶meters)
{
VERIFY_ALWAYS(
access::write(m_handler->m_backendAccess),
"[JSON] Cannot delete datasets in read-only mode")
if (!writable->written)
{
return;
}
auto filepos = setAndGetFilePosition(writable, false);
auto file = refreshFileFromParent(writable);
auto dataset = removeSlashes(parameters.name);
nlohmann::json *parent;
if (dataset == ".")
{
auto s = filepos->id.to_string();
if (s.empty())
{
throw std::runtime_error(
"[JSON] Invalid position for a dataset in the JSON file.");
}
dataset = s;
auto i = dataset.rfind('/');
dataset.replace(0, i + 1, "");
parentDir(s);
parent = &(*obtainJsonContents(file))[nlohmann::json::json_pointer(s)];
}
else
{
parent = &obtainJsonContents(writable);
}
parent->erase(dataset);
putJsonContents(file);
writable->written = false;
writable->abstractFilePosition.reset();
}
void JSONIOHandlerImpl::deleteAttribute(
Writable *writable, Parameter<Operation::DELETE_ATT> const ¶meters)
{
VERIFY_ALWAYS(
access::write(m_handler->m_backendAccess),
"[JSON] Cannot delete attributes in read-only mode")
if (!writable->written)
{
return;
}
setAndGetFilePosition(writable);
auto file = refreshFileFromParent(writable);
auto &j = obtainJsonContents(writable);
j.erase(parameters.name);
putJsonContents(file);
}
void JSONIOHandlerImpl::writeDataset(
Writable *writable, Parameter<Operation::WRITE_DATASET> ¶meters)
{
VERIFY_ALWAYS(
access::write(m_handler->m_backendAccess),
"[JSON] Cannot write data in read-only mode.");
auto pos = setAndGetFilePosition(writable);
auto file = refreshFileFromParent(writable);
auto &j = obtainJsonContents(writable);
verifyDataset(parameters, j);
switchType<DatasetWriter>(parameters.dtype, j, parameters);
writable->written = true;
putJsonContents(file);
}
void JSONIOHandlerImpl::writeAttribute(
Writable *writable, Parameter<Operation::WRITE_ATT> const ¶meter)
{
if (parameter.changesOverSteps ==
Parameter<Operation::WRITE_ATT>::ChangesOverSteps::Yes)
{
// cannot do this
return;
}
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.");
}
/* Sanitize name */
std::string name = removeSlashes(parameter.name);
auto file = refreshFileFromParent(writable);
auto jsonVal = obtainJsonContents(file);
auto filePosition = setAndGetFilePosition(writable);
if ((*jsonVal)[filePosition->id]["attributes"].empty())
{
(*jsonVal)[filePosition->id]["attributes"] = nlohmann::json::object();
}
nlohmann::json value;
switchType<AttributeWriter>(parameter.dtype, value, parameter.resource);
(*jsonVal)[filePosition->id]["attributes"][parameter.name] = {
{"datatype", datatypeToString(parameter.dtype)}, {"value", value}};
writable->written = true;
m_dirty.emplace(file);
}
void JSONIOHandlerImpl::readDataset(
Writable *writable, Parameter<Operation::READ_DATASET> ¶meters)
{
refreshFileFromParent(writable);
setAndGetFilePosition(writable);
auto &j = obtainJsonContents(writable);
verifyDataset(parameters, j);
try
{
switchType<DatasetReader>(parameters.dtype, j["data"], parameters);
}
catch (json::basic_json::type_error &)
{
throw std::runtime_error(
"[JSON] The given path does not contain a valid dataset.");
}
}
void JSONIOHandlerImpl::readAttribute(
Writable *writable, Parameter<Operation::READ_ATT> ¶meters)
{
VERIFY_ALWAYS(
writable->written,
"[JSON] Attributes have to be written before reading.")
refreshFileFromParent(writable);
auto name = removeSlashes(parameters.name);
auto const &jsonContents = obtainJsonContents(writable);
auto const &jsonLoc = jsonContents["attributes"];
setAndGetFilePosition(writable);
std::string error_msg("[JSON] No such attribute '");
if (!hasKey(jsonLoc, name))
{
throw error::ReadError(
error::AffectedObject::Attribute,
error::Reason::NotFound,
"JSON",
"Tried looking up attribute '" + name +
"' in object: " + jsonLoc.dump());
}
auto &j = jsonLoc[name];
try
{
*parameters.dtype =
Datatype(stringToDatatype(j["datatype"].get<std::string>()));
switchType<AttributeReader>(*parameters.dtype, j["value"], parameters);
}
catch (json::type_error &)
{
throw error::ReadError(
error::AffectedObject::Attribute,
error::Reason::UnexpectedContent,
"JSON",
"No properly formatted attribute with name '" + name +
"' found in object: " + jsonLoc.dump());
}
}
void JSONIOHandlerImpl::listPaths(
Writable *writable, Parameter<Operation::LIST_PATHS> ¶meters)
{
VERIFY_ALWAYS(
writable->written,
"[JSON] Values have to be written before reading a directory");
auto &j = obtainJsonContents(writable);
setAndGetFilePosition(writable);
refreshFileFromParent(writable);
parameters.paths->clear();
for (auto it = j.begin(); it != j.end(); it++)
{
if (isGroup(it))
{
parameters.paths->push_back(it.key());
}
}
}
void JSONIOHandlerImpl::listDatasets(
Writable *writable, Parameter<Operation::LIST_DATASETS> ¶meters)