sui_indexer/restorer/
formal_snapshot.rs

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
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::collections::BTreeMap;
use std::num::NonZeroUsize;
use std::path::PathBuf;
use std::sync::Arc;

use futures::future::{AbortHandle, AbortRegistration, Abortable};
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use object_store::path::Path;
use tokio::sync::{Mutex, Semaphore};
use tokio::task;
use tracing::info;

use sui_config::object_storage_config::{ObjectStoreConfig, ObjectStoreType};
use sui_core::authority::authority_store_tables::LiveObject;
use sui_snapshot::reader::{download_bytes, LiveObjectIter, StateSnapshotReaderV1};
use sui_snapshot::FileMetadata;
use sui_storage::object_store::util::get;
use sui_storage::object_store::ObjectStoreGetExt;
use sui_types::accumulator::Accumulator;

use crate::config::RestoreConfig;
use crate::errors::IndexerError;
use crate::handlers::TransactionObjectChangesToCommit;
use crate::restorer::archives::{read_restore_checkpoint_info, RestoreCheckpointInfo};
use crate::store::{indexer_store::IndexerStore, PgIndexerStore};
use crate::types::{IndexedCheckpoint, IndexedObject};

pub type DigestByBucketAndPartition = BTreeMap<u32, BTreeMap<u32, [u8; 32]>>;
pub type SnapshotChecksums = (DigestByBucketAndPartition, Accumulator);
pub type Sha3DigestType = Arc<Mutex<BTreeMap<u32, BTreeMap<u32, [u8; 32]>>>>;

pub struct IndexerFormalSnapshotRestorer {
    store: PgIndexerStore,
    reader: StateSnapshotReaderV1,
    restore_config: RestoreConfig,
}

impl IndexerFormalSnapshotRestorer {
    pub async fn new(
        store: PgIndexerStore,
        restore_config: RestoreConfig,
    ) -> Result<Self, IndexerError> {
        let remote_store_config = ObjectStoreConfig {
            object_store: Some(ObjectStoreType::S3),
            aws_endpoint: Some(restore_config.snapshot_endpoint.clone()),
            aws_virtual_hosted_style_request: true,
            object_store_connection_limit: restore_config.object_store_concurrent_limit,
            no_sign_request: true,
            ..Default::default()
        };

        let base_path = PathBuf::from(restore_config.snapshot_download_dir.clone());
        let snapshot_dir = base_path.join("snapshot");
        let local_store_config = ObjectStoreConfig {
            object_store: Some(ObjectStoreType::File),
            directory: Some(snapshot_dir.clone().to_path_buf()),
            ..Default::default()
        };

        let m = MultiProgress::new();
        let reader = StateSnapshotReaderV1::new(
            restore_config.start_epoch,
            &remote_store_config,
            &local_store_config,
            NonZeroUsize::new(restore_config.object_store_concurrent_limit).unwrap(),
            m.clone(),
            true, // skip_reset_local_store
        )
        .await
        .unwrap_or_else(|err| panic!("Failed to create reader: {}", err));
        info!(
            "Initialized formal snapshot reader at epoch {}",
            restore_config.start_epoch
        );

        Ok(Self {
            store,
            reader,
            restore_config: restore_config.clone(),
        })
    }

    pub async fn restore(&mut self) -> Result<(), IndexerError> {
        let (sha3_digests, num_part_files) = self.reader.compute_checksum().await?;
        let (_abort_handle, abort_registration) = AbortHandle::new_pair();
        let (input_files, epoch_dir, remote_object_store, _concurrency) =
            self.reader.export_metadata().await?;
        let owned_input_files: Vec<(u32, (u32, FileMetadata))> = input_files
            .into_iter()
            .map(|(bucket, (part_num, metadata))| (*bucket, (part_num, metadata.clone())))
            .collect();
        self.restore_move_objects(
            abort_registration,
            owned_input_files,
            epoch_dir,
            remote_object_store,
            sha3_digests,
            num_part_files,
        )
        .await?;
        info!("Finished restoring move objects");
        self.restore_display_table().await?;
        info!("Finished restoring display table");
        self.restore_cp_watermark_and_chain_id().await?;
        info!("Finished restoring checkpoint info");
        Ok(())
    }

    async fn restore_move_objects(
        &self,
        abort_registration: AbortRegistration,
        input_files: Vec<(u32, (u32, FileMetadata))>,
        epoch_dir: Path,
        remote_object_store: Arc<dyn ObjectStoreGetExt>,
        sha3_digests: Arc<Mutex<DigestByBucketAndPartition>>,
        num_part_files: usize,
    ) -> std::result::Result<(), anyhow::Error> {
        let move_object_progress_bar = Arc::new(self.reader.get_multi_progress().add(
            ProgressBar::new(num_part_files as u64).with_style(
                ProgressStyle::with_template(
                    "[{elapsed_precise}] {wide_bar} {pos} out of {len} move object files restored ({msg})",
                )
                .unwrap(),
            ),
        ));

        Abortable::new(
            async move {
                let sema_limit = Arc::new(Semaphore::new(
                    self.restore_config.object_store_concurrent_limit,
                ));
                let mut restore_tasks = vec![];

                for (bucket, (part_num, file_metadata)) in input_files.into_iter() {
                    let sema_limit_clone = sema_limit.clone();
                    let epoch_dir_clone = epoch_dir.clone();
                    let remote_object_store_clone = remote_object_store.clone();
                    let sha3_digests_clone = sha3_digests.clone();
                    let store_clone = self.store.clone();
                    let bar_clone = move_object_progress_bar.clone();
                    let restore_config = self.restore_config.clone();

                    let restore_task = task::spawn(async move {
                        let _permit = sema_limit_clone.acquire().await.unwrap();
                        let object_file_path = file_metadata.file_path(&epoch_dir_clone);
                        let (bytes, _) = download_bytes(
                            remote_object_store_clone,
                            &file_metadata,
                            epoch_dir_clone,
                            sha3_digests_clone,
                            &&bucket,
                            &part_num,
                            Some(restore_config.object_store_max_timeout_secs),
                        )
                        .await;
                        info!(
                            "Finished downloading move object file {:?}",
                            object_file_path
                        );
                        let mut move_objects = vec![];
                        let _result: Result<(), anyhow::Error> =
                            LiveObjectIter::new(&file_metadata, bytes.clone()).map(|obj_iter| {
                                for object in obj_iter {
                                    match object {
                                        LiveObject::Normal(obj) => {
                                            // TODO: placeholder values for df_info and checkpoint_seq_num,
                                            // will clean it up when the column cleanup is done.
                                            let indexed_object =
                                                IndexedObject::from_object(0, obj, None);
                                            move_objects.push(indexed_object);
                                        }
                                        LiveObject::Wrapped(_) => {}
                                    }
                                }
                            });

                        let live_obj_cnt = move_objects.len();
                        let object_changes = TransactionObjectChangesToCommit {
                            changed_objects: move_objects.clone(),
                            deleted_objects: vec![],
                        };
                        info!(
                            "Start persisting {} objects to objects table from {}",
                            live_obj_cnt, object_file_path
                        );
                        store_clone
                            .persist_objects(vec![object_changes])
                            .await
                            .expect("Failed to persist to objects from restore");
                        info!(
                            "Finished persisting {} objects to objects table from {}",
                            live_obj_cnt, object_file_path
                        );

                        let objects_snapshot_changes = TransactionObjectChangesToCommit {
                            changed_objects: move_objects,
                            deleted_objects: vec![],
                        };
                        store_clone
                            .persist_objects_snapshot(vec![objects_snapshot_changes])
                            .await
                            .expect("Failed to persist objects snapshot");

                        bar_clone.inc(1);
                        bar_clone.set_message(format!(
                            "Restored {} live move objects from {}",
                            live_obj_cnt, object_file_path
                        ));
                        Ok::<(), anyhow::Error>(())
                    });
                    restore_tasks.push(restore_task);
                }

                let restore_task_results = futures::future::join_all(restore_tasks).await;
                for restore_task_result in restore_task_results {
                    restore_task_result??;
                }
                Ok(())
            },
            abort_registration,
        )
        .await?
    }

    async fn restore_display_table(&self) -> std::result::Result<(), anyhow::Error> {
        let bucket = self.restore_config.gcs_display_bucket.clone();
        let start_epoch = self.restore_config.start_epoch;

        let remote_store_config = ObjectStoreConfig {
            object_store: Some(ObjectStoreType::GCS),
            bucket: Some(bucket),
            object_store_connection_limit: 200,
            no_sign_request: false,
            ..Default::default()
        };
        let remote_store = remote_store_config.make().map_err(|e| {
            IndexerError::GcsError(format!("Failed to make GCS remote store: {}", e))
        })?;
        let path = Path::from(format!("display_{}.csv", start_epoch).as_str());
        let bytes: bytes::Bytes = get(&remote_store, &path).await?;
        self.store.restore_display(bytes).await?;
        Ok(())
    }

    async fn restore_cp_watermark_and_chain_id(&self) -> Result<(), IndexerError> {
        let restore_checkpoint_info = read_restore_checkpoint_info(
            Some(self.restore_config.gcs_archive_bucket.clone()),
            self.restore_config.start_epoch,
        )
        .await?;
        let RestoreCheckpointInfo {
            next_checkpoint_after_epoch,
            chain_identifier,
        } = restore_checkpoint_info;
        self.store
            .persist_chain_identifier(chain_identifier.into_inner().to_vec())
            .await?;
        assert!(next_checkpoint_after_epoch > 0);
        // FIXME: This is a temporary hack to add a checkpoint watermark.
        // Once we have proper watermark tables, we should remove the following code.
        let last_cp = IndexedCheckpoint {
            sequence_number: next_checkpoint_after_epoch - 1,
            ..Default::default()
        };
        self.store.persist_checkpoints(vec![last_cp]).await?;
        Ok(())
    }
}