Arcane  4.2.1.0
Developer documentation
Loading...
Searching...
No Matches
BasicWriter.cc
1// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*-
2//-----------------------------------------------------------------------------
3// Copyright 2000-2026 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com)
4// See the top-level COPYRIGHT file for details.
5// SPDX-License-Identifier: Apache-2.0
6//-----------------------------------------------------------------------------
7/*---------------------------------------------------------------------------*/
8/* BasicWriter.cc (C) 2000-2026 */
9/* */
10/* Simple writing for checkpoints/restorations. */
11/*---------------------------------------------------------------------------*/
12/*---------------------------------------------------------------------------*/
13
14#include "arcane/std/internal/BasicWriter.h"
15
16#include "arcane/utils/FatalErrorException.h"
17#include "arcane/utils/StringBuilder.h"
18#include "arcane/utils/PlatformUtils.h"
19#include "arcane/utils/JSONWriter.h"
20#include "arcane/utils/IDataCompressor.h"
21#include "arcane/utils/MemoryView.h"
22#include "arcane/utils/Ref.h"
23#include "arcane/utils/IHashAlgorithm.h"
24
25#include "arcane/core/IParallelMng.h"
26#include "arcane/core/ItemGroup.h"
27#include "arcane/core/IVariable.h"
28#include "arcane/core/IItemFamily.h"
29#include "arcane/core/IData.h"
30#include "arcane/core/internal/IVariableInternal.h"
31
32#include "arcane/std/internal/ParallelDataWriter.h"
33
34#include <fstream>
35
36/*---------------------------------------------------------------------------*/
37/*---------------------------------------------------------------------------*/
38
39namespace Arcane::impl
40{
41
42/*---------------------------------------------------------------------------*/
43/*---------------------------------------------------------------------------*/
44
45BasicWriter::
46BasicWriter(IApplication* app, IParallelMng* pm, const String& path,
47 eOpenMode open_mode, Int32 version, bool want_parallel)
48: BasicReaderWriterCommon(app, pm, path, open_mode)
49, m_want_parallel(want_parallel)
50, m_version(version)
51{
52}
53
54/*---------------------------------------------------------------------------*/
55/*---------------------------------------------------------------------------*/
56
57void BasicWriter::
58initialize()
59{
60 _checkNoInit();
61
62 Int32 rank = m_parallel_mng->commRank();
63 if (m_open_mode == OpenModeTruncate && m_parallel_mng->isMasterIO())
64 platform::recursiveCreateDirectory(m_path);
65 m_parallel_mng->barrier();
66 String filename = _getBasicVariableFile(m_version, m_path, rank);
67 m_text_writer = makeRef(new KeyValueTextWriter(traceMng(), filename, m_version));
68 m_text_writer->setDataCompressor(m_data_compressor);
69 m_text_writer->setHashAlgorithm(m_hash_algorithm);
70
71 // Allows overriding the compression service used by an environment variable
72 // if none is set
73 if (!m_data_compressor.get()) {
74 String data_compressor_name = platform::getEnvironmentVariable("ARCANE_DEFLATER");
75 if (!data_compressor_name.null()) {
76 data_compressor_name = data_compressor_name + "DataCompressor";
77 auto bc = _createDeflater(m_application, data_compressor_name);
78 info() << "Use data_compressor from environment variable ARCANE_DEFLATER name=" << data_compressor_name;
79 m_data_compressor = bc;
80 m_text_writer->setDataCompressor(bc);
81 }
82 }
83
84 // Same for the hash calculation service
85 if (!m_hash_algorithm.get()) {
86 String hash_algorithm_name = platform::getEnvironmentVariable("ARCANE_HASHALGORITHM");
87 if (hash_algorithm_name.null())
88 hash_algorithm_name = "SHA3_256";
89 else
90 info() << "Use hash algorithm from environment variable ARCANE_HASHALGORITHM name=" << hash_algorithm_name;
91 hash_algorithm_name = hash_algorithm_name + "HashAlgorithm";
92 auto v = _createHashAlgorithm(m_application, hash_algorithm_name);
93 m_hash_algorithm = v;
94 m_text_writer->setHashAlgorithm(v);
95 }
96
97 // For testing, allows specifying a service for global hash calculation.
98 if (!m_compare_hash_algorithm.get()) {
99 String algo_name = platform::getEnvironmentVariable("ARCANE_COMPAREHASHALGORITHM");
100 if (!algo_name.empty()) {
101 info() << "Use global hash algorithm from environment variable ARCANE_COMPAREHASHALGORITHM name=" << algo_name;
102 algo_name = algo_name + "HashAlgorithm";
103 auto v = _createHashAlgorithm(m_application, algo_name);
104 m_compare_hash_algorithm = v;
105 }
106 }
107
108 m_global_writer = new BasicGenericWriter(m_application, m_version, m_text_writer);
109 if (m_verbose_level > 0)
110 info() << "** OPEN MODE = " << m_open_mode;
111}
112
113/*---------------------------------------------------------------------------*/
114/*---------------------------------------------------------------------------*/
115
116void BasicWriter::
117_checkNoInit()
118{
119 if (m_is_init)
120 ARCANE_FATAL("initialize() has already been called");
121}
122
123/*---------------------------------------------------------------------------*/
124/*---------------------------------------------------------------------------*/
125
126Ref<ParallelDataWriter> BasicWriter::
127_getWriter(IVariable* var)
128{
129 return m_parallel_data_writers.getOrCreateWriter(var->itemGroup());
130}
131
132/*---------------------------------------------------------------------------*/
133/*---------------------------------------------------------------------------*/
134
135void BasicWriter::
136_directWriteVal(IVariable* var, IData* data)
137{
138 info(4) << "DIRECT WRITE VAL v=" << var->fullName();
139
140 IData* write_data = data;
141 Int64ConstArrayView written_unique_ids;
142 Int64UniqueArray wanted_unique_ids;
143 Int64UniqueArray sequential_written_unique_ids;
144
145 Ref<IData> allocated_write_data;
146 const bool is_mesh_variable = (var->itemKind() != IK_Unknown);
147 if (is_mesh_variable) {
148 ItemGroup group = var->itemGroup();
149 if (m_want_parallel) {
150 Ref<ParallelDataWriter> writer = _getWriter(var);
151 written_unique_ids = writer->sortedUniqueIds();
152 allocated_write_data = writer->getSortedValues(data);
153 write_data = allocated_write_data.get();
154 }
155 else {
156 // TODO check that uniqueId() are sorted.
157 // Normally it is always the case.
158 _fillUniqueIds(group, sequential_written_unique_ids);
159 written_unique_ids = sequential_written_unique_ids.view();
160 }
161 // Writes the group information if this is the first time accessing this group.
162 if (m_written_groups.find(group) == m_written_groups.end()) {
163 info(5) << "WRITE GROUP " << group.name();
164 const IItemFamily* item_family = group.itemFamily();
165 const String& gname = group.name();
166 String group_full_name = item_family->fullName() + "_" + gname;
167 _fillUniqueIds(group, wanted_unique_ids);
168 if (m_is_save_values)
169 m_global_writer->writeItemGroup(group_full_name, written_unique_ids, wanted_unique_ids.view());
170 m_written_groups.insert(group);
171 }
172 }
173
174 Ref<ISerializedData> sdata(write_data->createSerializedDataRef(false));
175 String compare_hash;
176 if (is_mesh_variable) {
177 compare_hash = _computeCompareHash(var, write_data);
178 }
179 m_global_writer->writeData(var->fullName(), sdata.get(), compare_hash, m_is_save_values);
180}
181
182/*---------------------------------------------------------------------------*/
183/*---------------------------------------------------------------------------*/
195String BasicWriter::
196_computeCompareHash(IVariable* var, IData* write_data)
197{
198 IHashAlgorithm* hash_algo = m_compare_hash_algorithm.get();
199 if (!hash_algo)
200 return {};
201 return var->_internalApi()->computeComparisonHashCollective(hash_algo, write_data);
202}
203
204/*---------------------------------------------------------------------------*/
205/*---------------------------------------------------------------------------*/
206
207void BasicWriter::
208write(IVariable* var, IData* data)
209{
210 if (var->isPartial()) {
211 info() << "** WARNING: partial variable not implemented in BasicWriter";
212 return;
213 }
214 _directWriteVal(var, data);
215}
216
217/*---------------------------------------------------------------------------*/
218/*---------------------------------------------------------------------------*/
219
220void BasicWriter::
221setMetaData(const String& meta_data)
222{
223 // In version 3, checkpoint metadata is in the database.
224 if (m_version >= 3) {
225 Span<const Byte> bytes = meta_data.utf8();
226 Int64 length = bytes.length();
227 String key_name = "Global:CheckpointMetadata";
228 m_text_writer->setExtents(key_name, Int64ConstArrayView(1, &length));
229 m_text_writer->write(key_name, asBytes(bytes));
230 }
231 else {
232 Int32 my_rank = m_parallel_mng->commRank();
233 String filename = _getMetaDataFileName(my_rank);
234 std::ofstream ofile(filename.localstr(), ios::binary);
235 meta_data.writeBytes(ofile);
236 }
237}
238
239/*---------------------------------------------------------------------------*/
240/*---------------------------------------------------------------------------*/
241
242void BasicWriter::
243beginWrite(const VariableCollection& vars)
244{
245 ARCANE_UNUSED(vars);
246 Int32 my_rank = m_parallel_mng->commRank();
247 m_global_writer->initialize(m_path, my_rank);
248}
249
250/*---------------------------------------------------------------------------*/
251/*---------------------------------------------------------------------------*/
252
253void BasicWriter::
254_endWriteV3()
255{
256 const Int64 nb_part = m_parallel_mng->commSize();
257
258 // Saves the information in JSON format
259 JSONWriter jsw;
260
261 {
262 JSONWriter::Object main_object(jsw);
263 jsw.writeKey(_getArcaneDBTag());
264 {
265 JSONWriter::Object db_object(jsw);
266 jsw.write("Version", (Int64)m_version);
267 jsw.write("NbPart", nb_part);
268 jsw.write("HasValues", m_is_save_values);
269
270 String data_compressor_name;
271 Int64 data_compressor_min_size = 0;
272 if (m_data_compressor.get()) {
273 data_compressor_name = m_data_compressor->name();
274 data_compressor_min_size = m_data_compressor->minCompressSize();
275 }
276 jsw.write("DataCompressor", data_compressor_name);
277 jsw.write("DataCompressorMinSize", String::fromNumber(data_compressor_min_size));
278
279 // Saves the hash algorithm name
280 {
281 String name;
282 if (m_hash_algorithm.get())
283 name = m_hash_algorithm->name();
284 jsw.write("HashAlgorithm", name);
285 }
286
287 // Saves the hash algorithm name for comparisons
288 {
289 String name;
290 if (m_compare_hash_algorithm.get())
291 name = m_compare_hash_algorithm->name();
292 jsw.write("ComparisonHashAlgorithm", name);
293 }
294 }
295 }
296
297 StringBuilder filename = m_path;
298 filename += "/arcane_acr_db.json";
299 String fn = filename.toString();
300 std::ofstream ofile(fn.localstr());
301 ofile << jsw.getBuffer();
302}
303
304/*---------------------------------------------------------------------------*/
305/*---------------------------------------------------------------------------*/
306
307void BasicWriter::
308endWrite()
309{
310 const IParallelMng* pm = m_parallel_mng;
311 if (pm->isMasterIO()) {
312 if (m_version >= 3) {
313 _endWriteV3();
314 }
315 else {
316 Int64 nb_part = pm->commSize();
317 StringBuilder filename = m_path;
318 filename += "/infos.txt";
319 String fn = filename.toString();
320 std::ofstream ofile(fn.localstr());
321 ofile << nb_part << '\n';
322 }
323 }
324 m_global_writer->endWrite();
325}
326
327/*---------------------------------------------------------------------------*/
328/*---------------------------------------------------------------------------*/
329
330} // namespace Arcane::impl
331
332/*---------------------------------------------------------------------------*/
333/*---------------------------------------------------------------------------*/
#define ARCANE_FATAL(...)
Macro throwing a FatalErrorException.
Interface of a data item.
Definition IData.h:34
Interface of a hashing algorithm.
virtual String computeComparisonHashCollective(IHashAlgorithm *hash_algo, IData *sorted_data)=0
Calculates the comparison hash for the variable.
Interface of a variable.
Definition IVariable.h:40
virtual bool isPartial() const =0
Indicates if the variable is partial.
virtual IVariableInternal * _internalApi()=0
Internal Arcane API.
View of an array of elements of type T.
Definition Span.h:633
void writeBytes(std::ostream &o) const
Writes the string in UTF-8 format to the stream o.
Definition String.cc:1247
const char * localstr() const
Returns the conversion of the instance into UTF-8 encoding.
Definition String.cc:229
ByteConstArrayView utf8() const
Returns the conversion of the instance into UTF-8 encoding.
Definition String.cc:277
TraceMessage info() const
Flow for an information message.
UniqueArray< Int64 > Int64UniqueArray
Dynamic 1D array of 64-bit integers.
Definition UtilsTypes.h:333
std::int64_t Int64
Signed integer type of 64 bits.
ConstArrayView< Int64 > Int64ConstArrayView
C equivalent of a 1D array of 64-bit integers.
Definition UtilsTypes.h:474
Impl::SpanTypeFromSize< conststd::byte, SizeType >::SpanType asBytes(const SpanImpl< DataType, SizeType, Extent > &s)
Converts the view into an array of non-modifiable bytes.
Definition Span.h:1030
auto makeRef(InstanceType *t) -> Ref< InstanceType >
Creates a reference on a pointer.
std::int32_t Int32
Signed integer type of 32 bits.