18namespace fs = std::filesystem;
22 static constexpr auto snapshot_file_prefix =
"snapshot";
23 static constexpr auto snapshot_idx_delimiter =
"_";
24 static constexpr auto snapshot_committed_suffix =
".committed";
26 static bool is_snapshot_file(
const std::string& file_name)
28 return file_name.starts_with(snapshot_file_prefix);
31 static bool is_snapshot_file_committed(
const std::string& file_name)
33 return file_name.find(snapshot_committed_suffix) != std::string::npos;
36 static size_t read_idx(
const std::string& str)
39 auto end_ptr = str.data() + str.size();
41 auto res = std::from_chars(str.data(), end_ptr, idx);
42 if (res.ec != std::errc())
44 throw std::logic_error(
45 fmt::format(
"Could not read idx from string \"{}\": {}", str, res.ec));
47 else if (res.ptr != end_ptr)
49 throw std::logic_error(fmt::format(
50 "Trailing characters in \"{}\" cannot be converted to idx: \"{}\"",
52 std::string(res.ptr, end_ptr)));
57 static std::optional<size_t> get_evidence_commit_idx_from_file_name(
58 const std::string& file_name)
64 auto pos = file_name.find(snapshot_committed_suffix);
65 if (pos == std::string::npos)
67 throw std::logic_error(
68 fmt::format(
"Snapshot file \"{}\" is not committed", file_name));
71 pos = file_name.find(snapshot_idx_delimiter, pos);
72 if (pos == std::string::npos)
78 return read_idx(file_name.substr(pos + 1));
81 static size_t get_snapshot_idx_from_file_name(
const std::string& file_name)
83 if (!is_snapshot_file(file_name))
85 throw std::logic_error(
86 fmt::format(
"File \"{}\" is not a valid snapshot file", file_name));
89 auto idx_pos = file_name.find_first_of(snapshot_idx_delimiter);
90 if (idx_pos == std::string::npos)
92 throw std::logic_error(fmt::format(
93 "Snapshot file name {} does not contain snapshot seqno", file_name));
96 auto evidence_idx_pos =
97 file_name.find_first_of(snapshot_idx_delimiter, idx_pos + 1);
98 if (evidence_idx_pos == std::string::npos)
100 throw std::logic_error(fmt::format(
101 "Snapshot file \"{}\" does not contain evidence index", file_name));
105 file_name.substr(idx_pos + 1, evidence_idx_pos - idx_pos - 1));
108 static size_t get_snapshot_evidence_idx_from_file_name(
109 const std::string& file_name)
111 if (!is_snapshot_file(file_name))
113 throw std::logic_error(
114 fmt::format(
"File \"{}\" is not a valid snapshot file", file_name));
117 auto idx_pos = file_name.find_first_of(snapshot_idx_delimiter);
118 if (idx_pos == std::string::npos)
120 throw std::logic_error(
121 fmt::format(
"Snapshot file \"{}\" does not contain index", file_name));
124 auto evidence_idx_pos =
125 file_name.find_first_of(snapshot_idx_delimiter, idx_pos + 1);
126 if (evidence_idx_pos == std::string::npos)
128 throw std::logic_error(fmt::format(
129 "Snapshot file \"{}\" does not contain evidence index", file_name));
133 size_t end_str = std::string::npos;
134 auto commit_suffix_pos =
135 file_name.find_first_of(snapshot_committed_suffix, evidence_idx_pos + 1);
136 if (commit_suffix_pos != std::string::npos)
138 end_str = commit_suffix_pos - evidence_idx_pos - 1;
141 return read_idx(file_name.substr(evidence_idx_pos + 1, end_str));
145 const fs::path& directory,
size_t& latest_committed_snapshot_idx)
147 std::optional<fs::path> latest_committed_snapshot_file_name = std::nullopt;
149 for (
auto& f : fs::directory_iterator(directory))
151 auto file_name = f.path().filename();
152 if (!is_snapshot_file(file_name))
154 LOG_INFO_FMT(
"Ignoring non-snapshot file {}", file_name);
158 if (!is_snapshot_file_committed(file_name))
160 LOG_INFO_FMT(
"Ignoring non-committed snapshot file {}", file_name);
164 if (fs::exists(f.path()) && fs::is_empty(f.path()))
166 LOG_INFO_FMT(
"Ignoring empty snapshot file {}", file_name);
170 auto snapshot_idx = get_snapshot_idx_from_file_name(file_name);
171 if (snapshot_idx > latest_committed_snapshot_idx)
173 latest_committed_snapshot_file_name = file_name;
174 latest_committed_snapshot_idx = snapshot_idx;
178 return latest_committed_snapshot_file_name;
186 const fs::path snapshot_dir;
187 const std::optional<fs::path> read_snapshot_dir = std::nullopt;
189 struct PendingSnapshot
192 std::shared_ptr<std::vector<uint8_t>> snapshot;
194 std::map<size_t, PendingSnapshot> pending_snapshots;
198 const std::string& snapshot_dir_,
200 const std::optional<std::string>& read_snapshot_dir_ = std::nullopt) :
201 to_enclave(writer_factory.create_writer_to_inside()),
202 snapshot_dir(snapshot_dir_),
203 read_snapshot_dir(read_snapshot_dir_)
205 if (fs::is_directory(snapshot_dir))
208 "Snapshots will be stored in existing directory: {}", snapshot_dir);
210 else if (!fs::create_directory(snapshot_dir))
212 throw std::logic_error(
213 fmt::format(
"Could not create snapshot directory: {}", snapshot_dir));
217 read_snapshot_dir.has_value() &&
218 !fs::is_directory(read_snapshot_dir.value()))
220 throw std::logic_error(fmt::format(
221 "{} read-only snapshot is not a directory",
222 read_snapshot_dir.value()));
234 size_t requested_size)
236 auto snapshot = std::make_shared<std::vector<uint8_t>>(requested_size);
237 pending_snapshots.emplace(idx, PendingSnapshot{evidence_idx, snapshot});
240 "Added pending snapshot {} [{} bytes]", idx, requested_size);
245#define THROW_ON_ERROR(x, name) \
251 throw std::runtime_error(fmt::format( \
252 "Error ({}) writing snapshot {} in " #x, strerror(errno), name)); \
259 const std::filesystem::path
dir;
270#ifndef TEST_MODE_EXECUTE_SYNC_INLINE
277 fmt::format(
"Committing snapshot - fsync({})", data->tmp_file_name));
278 fsync(data->snapshot_fd);
281 close(data->snapshot_fd);
284 data->committed_file_name =
285 fmt::format(
"{}{}", data->tmp_file_name, snapshot_committed_suffix);
286 const auto full_committed_path = data->dir / data->committed_file_name;
288 const auto full_tmp_path = data->dir / data->tmp_file_name;
294 "Written snapshot to {} (size: {} bytes, sha256: {} )",
295 data->committed_file_name,
299#ifndef TEST_MODE_EXECUTE_SYNC_INLINE
309 "Renamed temporary snapshot {} to {}",
311 data->committed_file_name);
319 const uint8_t* receipt_data,
323 fmt::format(
"Committing snapshot - snapshot_idx={}", snapshot_idx));
327 for (
auto it = pending_snapshots.begin(); it != pending_snapshots.end();
330 if (snapshot_idx == it->first)
333 auto file_name = fmt::format(
335 snapshot_file_prefix,
336 snapshot_idx_delimiter,
338 snapshot_idx_delimiter,
339 it->second.evidence_idx);
340 auto full_snapshot_path = snapshot_dir / file_name;
342 int snapshot_fd = open(
343 full_snapshot_path.c_str(), O_CREAT | O_EXCL | O_WRONLY, 0664);
344 if (snapshot_fd == -1)
351 "Cannot write snapshot as file already exists: {}",
357 "Cannot write snapshot: error ({}) opening file {}",
364 const auto& snapshot = it->second.snapshot;
367 write(snapshot_fd, snapshot->data(), snapshot->size()),
370 write(snapshot_fd, receipt_data, receipt_size), file_name);
373 "New snapshot file written to {} [{} bytes] (unsynced)",
375 snapshot->size() + receipt_size);
379 uv_work_t* work_handle =
new uv_work_t;
384 .tmp_file_name = file_name,
385 .snapshot_fd = snapshot_fd};
387 work_handle->data = data;
390#ifdef TEST_MODE_EXECUTE_SYNC_INLINE
404 "Writing snapshot to {} (sha256: {})", full_snapshot_path, sha);
406 pending_snapshots.erase(it);
412 LOG_FAIL_FMT(
"Could not find snapshot to commit at {}", snapshot_idx);
414 catch (std::exception& e)
417 "Exception while attempting to commit snapshot at {}: {}",
424 std::optional<std::pair<fs::path, fs::path>>
428 size_t latest_idx = 0;
430 std::optional<fs::path> read_only_latest_committed_snapshot =
432 if (read_snapshot_dir.has_value())
434 read_only_latest_committed_snapshot =
436 read_snapshot_dir.value(), latest_idx);
439 auto main_latest_committed_snapshot =
442 if (main_latest_committed_snapshot.has_value())
444 return std::make_pair(
445 snapshot_dir, main_latest_committed_snapshot.value());
447 else if (read_only_latest_committed_snapshot.has_value())
449 return std::make_pair(
450 read_snapshot_dir.value(),
451 read_only_latest_committed_snapshot.value());
462 ::consensus::snapshot_allocate,
463 [
this](
const uint8_t* data,
size_t size) {
464 auto idx = serialized::read<::consensus::Index>(data, size);
465 auto evidence_idx = serialized::read<::consensus::Index>(data, size);
466 auto requested_size = serialized::read<size_t>(data, size);
467 auto generation_count = serialized::read<uint32_t>(data, size);
473 ::consensus::snapshot_allocated,
475 std::span<uint8_t>{snapshot->data(), snapshot->size()},
481 ::consensus::snapshot_commit,
482 [
this](
const uint8_t* data,
size_t size) {
483 auto snapshot_idx = serialized::read<::consensus::Index>(data, size);
Definition snapshots.h:182
static void on_snapshot_sync_and_rename_complete(uv_work_t *req, int status)
Definition snapshots.h:304
std::optional< std::pair< fs::path, fs::path > > find_latest_committed_snapshot()
Definition snapshots.h:425
SnapshotManager(const std::string &snapshot_dir_, ringbuffer::AbstractWriterFactory &writer_factory, const std::optional< std::string > &read_snapshot_dir_=std::nullopt)
Definition snapshots.h:197
void register_message_handlers(messaging::Dispatcher< ringbuffer::Message > &disp)
Definition snapshots.h:457
fs::path get_main_directory() const
Definition snapshots.h:226
static void on_snapshot_sync_and_rename(uv_work_t *req)
Definition snapshots.h:267
void commit_snapshot(::consensus::Index snapshot_idx, const uint8_t *receipt_data, size_t receipt_size)
Definition snapshots.h:317
std::shared_ptr< std::vector< uint8_t > > add_pending_snapshot(::consensus::Index idx, ::consensus::Index evidence_idx, size_t requested_size)
Definition snapshots.h:231
Definition sha256_hash.h:16
std::string hex_str() const
Definition sha256_hash.cpp:61
Definition messaging.h:38
Definition ring_buffer_types.h:153
#define LOG_INFO_FMT
Definition logger.h:395
#define LOG_DEBUG_FMT
Definition logger.h:380
#define LOG_FAIL_FMT
Definition logger.h:396
#define DISPATCHER_SET_MESSAGE_HANDLER(DISP, MSG,...)
Definition messaging.h:316
std::optional< fs::path > find_latest_committed_snapshot_in_directory(const fs::path &directory, size_t &latest_committed_snapshot_idx)
Definition snapshots.h:144
void openssl_sha256_init()
Definition hash.cpp:43
void openssl_sha256_shutdown()
Definition hash.cpp:69
uint64_t Index
Definition ledger_enclave_types.h:11
std::vector< uint8_t > slurp(const std::string &file, bool optional=false)
Tries to read a file as byte vector.
Definition files.h:43
void rename(const fs::path &src, const fs::path &dst)
Definition files.h:141
std::shared_ptr< AbstractWriter > WriterPtr
Definition ring_buffer_types.h:150
#define RINGBUFFER_WRITE_MESSAGE(MSG,...)
Definition ring_buffer_types.h:255
#define THROW_ON_ERROR(x, name)
Definition snapshots.h:245
Definition snapshots.h:257
std::string committed_file_name
Definition snapshots.h:264
const std::filesystem::path dir
Definition snapshots.h:259
const int snapshot_fd
Definition snapshots.h:261
const std::string tmp_file_name
Definition snapshots.h:260
Definition time_bound_logger.h:14