1
// Copyright (C) Moondance Labs Ltd.
2
// This file is part of Tanssi.
3

            
4
// Tanssi is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Tanssi is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

            
14
// You should have received a copy of the GNU General Public License
15
// along with Tanssi.  If not, see <http://www.gnu.org/licenses/>.
16

            
17
//! Container Chain Spawner
18
//!
19
//! Controls the starting and stopping of container chains.
20
//!
21
//! For more information about when the database is deleted, check the
22
//! [Keep db flowchart](https://raw.githubusercontent.com/moondance-labs/tanssi/master/docs/keep_db_flowchart.png)
23

            
24
use {
25
    crate::{
26
        cli::ContainerChainCli,
27
        monitor::{SpawnedContainer, SpawnedContainersMonitor},
28
        rpc::generate_rpc_builder::GenerateRpcBuilder,
29
        service::{
30
            start_node_impl_container, ContainerChainClient, MinimalContainerRuntimeApi,
31
            ParachainClient,
32
        },
33
    },
34
    cumulus_primitives_core::ParaId,
35
    cumulus_relay_chain_interface::RelayChainInterface,
36
    dancebox_runtime::{opaque::Block as OpaqueBlock, Block},
37
    dc_orchestrator_chain_interface::{OrchestratorChainInterface, PHash},
38
    frame_support::{CloneNoBound, DefaultNoBound},
39
    fs2::FileExt,
40
    futures::FutureExt,
41
    node_common::command::generate_genesis_block,
42
    pallet_author_noting_runtime_api::AuthorNotingApi,
43
    polkadot_primitives::CollatorPair,
44
    sc_cli::{Database, SyncMode},
45
    sc_network::config::MultiaddrWithPeerId,
46
    sc_service::SpawnTaskHandle,
47
    sc_transaction_pool::TransactionPoolHandle,
48
    sp_api::ProvideRuntimeApi,
49
    sp_core::H256,
50
    sp_keystore::KeystorePtr,
51
    sp_runtime::traits::Block as BlockT,
52
    std::{
53
        any::Any,
54
        collections::{HashMap, HashSet},
55
        marker::PhantomData,
56
        path::{Path, PathBuf},
57
        sync::{Arc, Mutex},
58
        time::Instant,
59
    },
60
    tokio::{
61
        sync::{mpsc, oneshot},
62
        time::{sleep, Duration},
63
    },
64
    tokio_util::sync::CancellationToken,
65
};
66

            
67
/// Timeout to wait for the database to close before starting it again, used in `wait_for_paritydb_lock`.
68
/// This is the max timeout, if the db is closed in 1 second then that function will only wait 1 second.
69
const MAX_DB_RESTART_TIMEOUT: Duration = Duration::from_secs(60);
70

            
71
/// Block diff threshold above which we decide it will be faster to delete the database and
72
/// use warp sync, rather than using full sync to download a large number of blocks.
73
/// This is only needed because warp sync does not support syncing from a state that is not
74
/// genesis, it falls back to full sync in that case.
75
/// 30_000 blocks = 50 hours at 6s/block.
76
/// Assuming a syncing speed of 100 blocks per second, this will take 5 minutes to sync.
77
const MAX_BLOCK_DIFF_FOR_FULL_SYNC: u32 = 30_000;
78

            
79
/// Task that handles spawning a stopping container chains based on assignment.
80
/// The main loop is [rx_loop](ContainerChainSpawner::rx_loop).
81
pub struct ContainerChainSpawner<
82
    RuntimeApi: MinimalContainerRuntimeApi,
83
    TGenerateRpcBuilder: GenerateRpcBuilder<RuntimeApi>,
84
> {
85
    /// Start container chain params
86
    pub params: ContainerChainSpawnParams<RuntimeApi, TGenerateRpcBuilder>,
87

            
88
    /// State
89
    pub state: Arc<Mutex<ContainerChainSpawnerState>>,
90

            
91
    /// Before the first assignment, there is a db cleanup process that removes folders of container
92
    /// chains that we are no longer assigned to.
93
    pub db_folder_cleanup_done: bool,
94

            
95
    /// Async callback that enables collation on the orchestrator chain
96
    pub collate_on_tanssi:
97
        Arc<dyn Fn() -> (CancellationToken, futures::channel::oneshot::Receiver<()>) + Send + Sync>,
98
    /// Stores the cancellation token used to stop the orchestrator chain collator process.
99
    /// When this is None, the orchestrator collator is not running.
100
    pub collation_cancellation_constructs:
101
        Option<(CancellationToken, futures::channel::oneshot::Receiver<()>)>,
102
}
103

            
104
/// Struct with all the params needed to start a container chain node given the CLI arguments,
105
/// and creating the ChainSpec from on-chain data from the orchestrator chain.
106
/// These params must be the same for all container chains, params that change such as the
107
/// `container_chain_para_id` should be passed as separate arguments to the [try_spawn] function.
108
///
109
/// This struct MUST NOT contain types (outside of `Option<CollationParams>`) obtained through
110
/// running an embeded orchestrator node, as this will prevent spawning a container chain in a node
111
/// connected to an orchestrator node through WebSocket.
112
#[derive(CloneNoBound)]
113
pub struct ContainerChainSpawnParams<
114
    RuntimeApi: MinimalContainerRuntimeApi,
115
    TGenerateRpcBuilder: GenerateRpcBuilder<RuntimeApi>,
116
> {
117
    pub orchestrator_chain_interface: Arc<dyn OrchestratorChainInterface>,
118
    pub container_chain_cli: ContainerChainCli,
119
    pub tokio_handle: tokio::runtime::Handle,
120
    pub chain_type: sc_chain_spec::ChainType,
121
    pub relay_chain: String,
122
    pub relay_chain_interface: Arc<dyn RelayChainInterface>,
123
    pub sync_keystore: KeystorePtr,
124
    pub spawn_handle: SpawnTaskHandle,
125
    pub collation_params: Option<CollationParams>,
126
    pub data_preserver: bool,
127
    pub generate_rpc_builder: TGenerateRpcBuilder,
128
    pub override_sync_mode: Option<SyncMode>,
129

            
130
    pub phantom: PhantomData<RuntimeApi>,
131
}
132

            
133
/// Params specific to collation. This struct can contain types obtained through running an
134
/// embeded orchestrator node.
135
#[derive(Clone)]
136
pub struct CollationParams {
137
    pub collator_key: CollatorPair,
138
    pub orchestrator_tx_pool: Option<Arc<TransactionPoolHandle<OpaqueBlock, ParachainClient>>>,
139
    pub orchestrator_client: Option<Arc<ParachainClient>>,
140
    pub orchestrator_para_id: ParaId,
141
    /// If this is `false`, then `orchestrator_tx_pool` and `orchestrator_client` must be `Some`.
142
    pub solochain: bool,
143
}
144

            
145
/// Mutable state for container chain spawner. Keeps track of running chains.
146
#[derive(DefaultNoBound)]
147
pub struct ContainerChainSpawnerState {
148
    spawned_container_chains: HashMap<ParaId, ContainerChainState>,
149
    assigned_para_id: Option<ParaId>,
150
    next_assigned_para_id: Option<ParaId>,
151
    failed_para_ids: HashSet<ParaId>,
152
    // For debugging and detecting errors
153
    pub spawned_containers_monitor: SpawnedContainersMonitor,
154
}
155

            
156
pub struct ContainerChainState {
157
    /// Handle that can be used to stop the container chain
158
    stop_handle: StopContainerChain,
159
    /// Database path
160
    db_path: PathBuf,
161
}
162

            
163
/// Stops a container chain when signal is sent. The bool means `keep_db`, whether to keep the
164
/// container chain database (true) or remove it (false).
165
pub struct StopContainerChain {
166
    signal: oneshot::Sender<bool>,
167
    id: usize,
168
}
169

            
170
/// Messages used to control the `ContainerChainSpawner`. This is needed because one of the fields
171
/// of `ContainerChainSpawner` is not `Sync`, so we cannot simply pass an
172
/// `Arc<ContainerChainSpawner>` to other threads.
173
#[derive(Debug)]
174
pub enum CcSpawnMsg {
175
    /// Update container chain assignment
176
    UpdateAssignment {
177
        current: Option<ParaId>,
178
        next: Option<ParaId>,
179
    },
180
}
181

            
182
// Separate function to allow using `?` to return a result, and also to avoid using `self` in an
183
// async function. Mutable state should be written by locking `state`.
184
// TODO: `state` should be an async mutex
185
async fn try_spawn<
186
    RuntimeApi: MinimalContainerRuntimeApi,
187
    TGenerateRpcBuilder: GenerateRpcBuilder<RuntimeApi>,
188
>(
189
    try_spawn_params: ContainerChainSpawnParams<RuntimeApi, TGenerateRpcBuilder>,
190
    state: Arc<Mutex<ContainerChainSpawnerState>>,
191
    container_chain_para_id: ParaId,
192
    start_collation: bool,
193
) -> sc_service::error::Result<()> {
194
    let ContainerChainSpawnParams {
195
        orchestrator_chain_interface,
196
        mut container_chain_cli,
197
        tokio_handle,
198
        chain_type,
199
        relay_chain,
200
        relay_chain_interface,
201
        sync_keystore,
202
        spawn_handle,
203
        mut collation_params,
204
        data_preserver,
205
        generate_rpc_builder,
206
        override_sync_mode,
207
        ..
208
    } = try_spawn_params;
209
    // Preload genesis data from orchestrator chain storage.
210

            
211
    // TODO: the orchestrator chain node may not be fully synced yet,
212
    // in that case we will be reading an old state.
213
    let orchestrator_block_hash = orchestrator_chain_interface
214
        .finalized_block_hash()
215
        .await
216
        .map_err(|e| format!("Failed to get latest block hash: {e}"))?;
217

            
218
    log::info!(
219
        "Detected assignment for container chain {}",
220
        container_chain_para_id
221
    );
222

            
223
    let genesis_data = orchestrator_chain_interface
224
        .genesis_data(orchestrator_block_hash, container_chain_para_id)
225
        .await
226
        .map_err(|e| format!("Failed to call genesis_data runtime api: {}", e))?
227
        .ok_or_else(|| {
228
            format!(
229
                "No genesis data registered for container chain id {}",
230
                container_chain_para_id
231
            )
232
        })?;
233

            
234
    let boot_nodes_raw = orchestrator_chain_interface
235
        .boot_nodes(orchestrator_block_hash, container_chain_para_id)
236
        .await
237
        .map_err(|e| format!("Failed to call boot_nodes runtime api: {}", e))?;
238

            
239
    if boot_nodes_raw.is_empty() {
240
        log::warn!(
241
            "No boot nodes registered on-chain for container chain {}",
242
            container_chain_para_id
243
        );
244
    }
245
    let boot_nodes = parse_boot_nodes_ignore_invalid(boot_nodes_raw, container_chain_para_id);
246
    if boot_nodes.is_empty() {
247
        log::warn!(
248
            "No valid boot nodes for container chain {}",
249
            container_chain_para_id
250
        );
251
    }
252

            
253
    container_chain_cli
254
        .preload_chain_spec_from_genesis_data(
255
            container_chain_para_id.into(),
256
            genesis_data,
257
            chain_type.clone(),
258
            relay_chain.clone(),
259
            boot_nodes,
260
        )
261
        .map_err(|e| {
262
            format!(
263
                "failed to create container chain chain spec from on chain genesis data: {}",
264
                e
265
            )
266
        })?;
267

            
268
    log::info!(
269
        "Loaded chain spec for container chain {}",
270
        container_chain_para_id
271
    );
272

            
273
    if !data_preserver && !start_collation {
274
        log::info!("This is a syncing container chain, using random ports");
275

            
276
        collation_params = None;
277

            
278
        // Use random ports to avoid conflicts with the other running container chain
279
        let random_ports = [23456, 23457, 23458];
280

            
281
        container_chain_cli
282
            .base
283
            .base
284
            .prometheus_params
285
            .prometheus_port = Some(random_ports[0]);
286
        container_chain_cli.base.base.network_params.port = Some(random_ports[1]);
287
        container_chain_cli.base.base.rpc_params.rpc_port = Some(random_ports[2]);
288

            
289
        // Use a different network key for syncing the chain. This is to avoid full nodes banning collators
290
        // by mistake, with error:
291
        // Reason: Unsupported protocol. Banned, disconnecting.
292
        //
293
        // Store this new key in a new path to not conflict with the real network key.
294
        // The same key is used for all container chains, that doesn't seem to cause problems.
295

            
296
        // Collator-01/data/containers
297
        let mut syncing_network_key_path = container_chain_cli
298
            .base
299
            .base
300
            .shared_params
301
            .base_path
302
            .clone()
303
            .expect("base path always set");
304
        // Collator-01/data/containers/keystore/network_syncing/secret_ed25519
305
        syncing_network_key_path.push("keystore/network_syncing/secret_ed25519");
306

            
307
        // Clear network key_params. These will be used by the collating process, but not by the syncing process.
308
        container_chain_cli
309
            .base
310
            .base
311
            .network_params
312
            .node_key_params
313
            .node_key = None;
314
        container_chain_cli
315
            .base
316
            .base
317
            .network_params
318
            .node_key_params
319
            .node_key_file = Some(syncing_network_key_path);
320
        // Generate a new network key if it has not been generated already.
321
        // This is safe to enable if your node is not an authority. We use it only for syncing the network.
322
        container_chain_cli
323
            .base
324
            .base
325
            .network_params
326
            .node_key_params
327
            .unsafe_force_node_key_generation = true;
328
    }
329

            
330
    let validator = collation_params.is_some();
331

            
332
    // Update CLI params
333
    container_chain_cli.base.para_id = Some(container_chain_para_id.into());
334
    container_chain_cli
335
        .base
336
        .base
337
        .import_params
338
        .database_params
339
        .database = Some(Database::ParityDb);
340

            
341
    let keep_db = container_chain_cli.base.keep_db;
342

            
343
    // Get a closure that checks if db_path exists.Need this to know when to use full sync instead of warp sync.
344
    let check_db_exists = {
345
        // Get db_path from config
346
        let mut container_chain_cli_config = sc_cli::SubstrateCli::create_configuration(
347
            &container_chain_cli,
348
            &container_chain_cli,
349
            tokio_handle.clone(),
350
        )
351
        .map_err(|err| format!("Container chain argument error: {}", err))?;
352

            
353
        // Change database path to make it depend on container chain para id
354
        // So instead of the usual "db/full" we have "db/full-container-2000"
355
        let mut db_path = container_chain_cli_config
356
            .database
357
            .path()
358
            .ok_or_else(|| "Failed to get database path".to_string())?
359
            .to_owned();
360
        db_path.set_file_name(format!("full-container-{}", container_chain_para_id));
361
        container_chain_cli_config.database.set_path(&db_path);
362

            
363
        // Return a closure because we may need to check if the db exists multiple times
364
        move || db_path.exists()
365
    };
366

            
367
    // Start container chain node. After starting, check if the database is good or needs to
368
    // be removed. If the db needs to be removed, this function will handle the node restart, and
369
    // return the components of a running container chain node.
370
    // This should be a separate function, but it has so many arguments that I prefer to have it as a closure for now
371
    let start_node_impl_container_with_restart = || async move {
372
        // Loop will run at most 2 times: 1 time if the db is good and 2 times if the db needs to be removed
373
        for _ in 0..2 {
374
            let db_existed_before = check_db_exists();
375

            
376
            if let Some(sync) = override_sync_mode {
377
                container_chain_cli.base.base.network_params.sync = sync;
378
            }
379
            log::info!(
380
                "Container chain sync mode: {:?}",
381
                container_chain_cli.base.base.network_params.sync
382
            );
383

            
384
            let mut container_chain_cli_config = sc_cli::SubstrateCli::create_configuration(
385
                &container_chain_cli,
386
                &container_chain_cli,
387
                tokio_handle.clone(),
388
            )
389
            .map_err(|err| format!("Container chain argument error: {}", err))?;
390

            
391
            // Change database path to make it depend on container chain para id
392
            // So instead of the usual "db/full" we have "db/full-container-2000"
393
            let mut db_path = container_chain_cli_config
394
                .database
395
                .path()
396
                .ok_or_else(|| "Failed to get database path".to_string())?
397
                .to_owned();
398
            db_path.set_file_name(format!("full-container-{}", container_chain_para_id));
399
            container_chain_cli_config.database.set_path(&db_path);
400

            
401
            let (container_chain_task_manager, container_chain_client, container_chain_db) =
402
                match container_chain_cli_config
403
                    .network
404
                    .network_backend
405
                    .unwrap_or(sc_network::config::NetworkBackendType::Libp2p)
406
                {
407
                    sc_network::config::NetworkBackendType::Libp2p => {
408
                        start_node_impl_container::<_, _, sc_network::NetworkWorker<_, _>>(
409
                            container_chain_cli_config,
410
                            relay_chain_interface.clone(),
411
                            orchestrator_chain_interface.clone(),
412
                            sync_keystore.clone(),
413
                            container_chain_para_id,
414
                            collation_params.clone(),
415
                            generate_rpc_builder.clone(),
416
                            &container_chain_cli,
417
                            data_preserver,
418
                        )
419
                        .await?
420
                    }
421
                    sc_network::config::NetworkBackendType::Litep2p => {
422
                        start_node_impl_container::<_, _, sc_network::Litep2pNetworkBackend>(
423
                            container_chain_cli_config,
424
                            relay_chain_interface.clone(),
425
                            orchestrator_chain_interface.clone(),
426
                            sync_keystore.clone(),
427
                            container_chain_para_id,
428
                            collation_params.clone(),
429
                            generate_rpc_builder.clone(),
430
                            &container_chain_cli,
431
                            data_preserver,
432
                        )
433
                        .await?
434
                    }
435
                };
436

            
437
            // Keep all node parts in one variable to make them easier to drop
438
            let node_parts = (
439
                container_chain_task_manager,
440
                container_chain_client,
441
                container_chain_db,
442
                db_path,
443
            );
444

            
445
            if db_existed_before {
446
                // If the database already existed before, check if it can be used or it needs to be removed.
447
                // To remove the database, we restart the node, wait for the db to close to avoid a
448
                // "shutdown error" log, and then remove it.
449
                if let Some(db_removal_reason) = db_needs_removal(
450
                    &node_parts.1,
451
                    &orchestrator_chain_interface,
452
                    orchestrator_block_hash,
453
                    container_chain_para_id,
454
                    &container_chain_cli,
455
                    container_chain_cli.base.keep_db,
456
                )
457
                .await?
458
                {
459
                    let db_path = node_parts.3.clone();
460
                    // Important, drop `node_parts` before trying to `wait_for_paritydb_lock`
461
                    drop(node_parts);
462
                    // Wait here to for the database created in the previous loop iteration to close.
463
                    // Dropping is not enough because there is some background process that keeps the database open,
464
                    // so we check the paritydb lock file directly.
465
                    log::info!(
466
                        "Restarting container chain {} after db deletion. Reason: {:?}",
467
                        container_chain_para_id,
468
                        db_removal_reason,
469
                    );
470
                    wait_for_paritydb_lock(&db_path, MAX_DB_RESTART_TIMEOUT)
471
                        .await
472
                        .map_err(|e| {
473
                            log::warn!(
474
                                "Error waiting for chain {} to release db lock: {:?}",
475
                                container_chain_para_id,
476
                                e
477
                            );
478

            
479
                            e
480
                        })?;
481
                    delete_container_chain_db(&db_path);
482

            
483
                    // Recursion, will only happen once because `db_existed_before` will be false after
484
                    // removing the db. Apparently closures cannot be recursive so fake recursion by
485
                    // using a loop + continue
486
                    continue;
487
                }
488
            }
489

            
490
            // If using full sync, print a warning if the local db is at block 0 and the chain has thousands of blocks
491
            if container_chain_cli.base.base.network_params.sync == SyncMode::Full {
492
                let last_container_block_temp = node_parts.1.chain_info().best_number;
493
                let cc_block_num = get_latest_container_block_number_from_orchestrator(
494
                    &orchestrator_chain_interface,
495
                    orchestrator_block_hash,
496
                    container_chain_para_id,
497
                )
498
                .await
499
                .unwrap_or(0);
500
                if last_container_block_temp == 0 && cc_block_num > MAX_BLOCK_DIFF_FOR_FULL_SYNC {
501
                    let db_folder = format!("full-container-{}", container_chain_para_id);
502
                    log::error!("\
503
                        Existing database for container chain {} is at block 0, assuming that warp sync failed.\n\
504
                        The node will now use full sync, which has to download {} blocks.\n\
505
                        If running as collator, it may not finish syncing on time and miss block rewards.\n\
506
                        To force using warp sync, stop tanssi-node and manually remove the db folder: {:?}\n\
507
                        ", container_chain_para_id, cc_block_num, db_folder)
508
                }
509
            }
510

            
511
            return sc_service::error::Result::Ok(node_parts);
512
        }
513

            
514
        unreachable!("Above loop can run at most 2 times, and in the second iteration it is guaranteed to return")
515
    };
516

            
517
    let (mut container_chain_task_manager, container_chain_client, container_chain_db, db_path) =
518
        start_node_impl_container_with_restart().await?;
519

            
520
    // Signal that allows to gracefully stop a container chain
521
    let (signal, on_exit) = oneshot::channel::<bool>();
522

            
523
    let monitor_id;
524
    {
525
        let mut state = state.lock().expect("poison error");
526
        let container_chain_client = container_chain_client as Arc<dyn Any + Sync + Send>;
527

            
528
        monitor_id = state.spawned_containers_monitor.push(SpawnedContainer {
529
            id: 0,
530
            para_id: container_chain_para_id,
531
            start_time: Instant::now(),
532
            stop_signal_time: None,
533
            stop_task_manager_time: None,
534
            stop_refcount_time: Default::default(),
535
            backend: Arc::downgrade(&container_chain_db),
536
            client: Arc::downgrade(&container_chain_client),
537
        });
538

            
539
        if state
540
            .spawned_container_chains
541
            .contains_key(&container_chain_para_id)
542
        {
543
            return Err(format!("Tried to spawn a container chain when another container chain with the same para id was already running: {:?}", container_chain_para_id).into());
544
        }
545
        state.spawned_container_chains.insert(
546
            container_chain_para_id,
547
            ContainerChainState {
548
                stop_handle: StopContainerChain {
549
                    signal,
550
                    id: monitor_id,
551
                },
552
                db_path: db_path.clone(),
553
            },
554
        );
555
    }
556

            
557
    // Add the container chain task manager as a child task to the parent task manager.
558
    // We want to stop the node if this task manager stops, but we also want to allow a
559
    // graceful shutdown using the `on_exit` future.
560
    let name = "container-chain-task-manager";
561
    spawn_handle.spawn(name, None, async move {
562
        let mut container_chain_task_manager_future =
563
            container_chain_task_manager.future().fuse();
564
        let mut on_exit_future = on_exit.fuse();
565

            
566
        futures::select! {
567
            res1 = container_chain_task_manager_future => {
568
                // An essential task failed or the task manager was stopped unexpectedly
569
                // using `.terminate()`. This should stop the container chain but not the node.
570
                if res1.is_err() {
571
                    log::error!("Essential task failed in container chain {} task manager. Shutting down container chain service", container_chain_para_id);
572
                } else {
573
                    log::error!("Unexpected shutdown in container chain {} task manager. Shutting down container chain service", container_chain_para_id);
574
                }
575
                // Mark this container chain as "failed to stop" to avoid warning in `self.stop()`
576
                let mut state = state.lock().expect("poison error");
577
                state.failed_para_ids.insert(container_chain_para_id);
578
                // Never delete db in this case because it is not a graceful shutdown
579
            }
580
            stop_unassigned = on_exit_future => {
581
                // Graceful shutdown.
582
                // `stop_unassigned` will be `Ok(keep_db)` if `.stop()` has been called, which means that the
583
                // container chain has been unassigned, and will be `Err` if the handle has been dropped,
584
                // which means that the node is stopping.
585
                // Delete existing database if running as collator
586
                if validator && stop_unassigned == Ok(false) && !keep_db {
587
                    // If this breaks after a code change, make sure that all the variables that
588
                    // may keep the chain alive are dropped before the call to `wait_for_paritydb_lock`.
589
                    drop(container_chain_task_manager_future);
590
                    drop(container_chain_task_manager);
591
                    let db_closed = wait_for_paritydb_lock(&db_path, MAX_DB_RESTART_TIMEOUT)
592
                        .await
593
                        .map_err(|e| {
594
                            log::warn!(
595
                                "Error waiting for chain {} to release db lock: {:?}",
596
                                container_chain_para_id,
597
                                e
598
                            );
599
                        }).is_ok();
600
                    // If db has not closed in 60 seconds we do not delete it.
601
                    if db_closed {
602
                        delete_container_chain_db(&db_path);
603
                    }
604
                }
605
            }
606
        }
607

            
608
        let mut state = state.lock().expect("poison error");
609
        state
610
            .spawned_containers_monitor
611
            .set_stop_task_manager_time(monitor_id, Instant::now());
612
    });
613

            
614
    Ok(())
615
}
616

            
617
/// Interface for spawning and stopping container chain embeded nodes.
618
pub trait Spawner {
619
    /// Access to the Orchestrator Chain Interface
620
    fn orchestrator_chain_interface(&self) -> Arc<dyn OrchestratorChainInterface>;
621

            
622
    /// Try to start a new container chain. In case of an error, this does not stop the node, and
623
    /// the container chain will be attempted to spawn again when the collator is reassigned to it.
624
    ///
625
    /// It is possible that we try to spawn-stop-spawn the same chain, and the second spawn fails
626
    /// because the chain has not stopped yet, because `stop` does not wait for the chain to stop,
627
    /// so before calling `spawn` make sure to call `wait_for_paritydb_lock` before, like we do in
628
    /// `handle_update_assignment`.
629
    fn spawn(
630
        &self,
631
        container_chain_para_id: ParaId,
632
        start_collation: bool,
633
    ) -> impl std::future::Future<Output = ()> + Send;
634

            
635
    /// Stop a container chain. Prints a warning if the container chain was not running.
636
    /// Returns the database path for the container chain, can be used with `wait_for_paritydb_lock`
637
    /// to ensure that the container chain has fully stopped. The database path can be `None` if the
638
    /// chain was not running.
639
    fn stop(&self, container_chain_para_id: ParaId, keep_db: bool) -> Option<PathBuf>;
640
}
641

            
642
impl<
643
        RuntimeApi: MinimalContainerRuntimeApi,
644
        TGenerateRpcBuilder: GenerateRpcBuilder<RuntimeApi>,
645
    > Spawner for ContainerChainSpawner<RuntimeApi, TGenerateRpcBuilder>
646
{
647
    /// Access to the Orchestrator Chain Interface
648
    fn orchestrator_chain_interface(&self) -> Arc<dyn OrchestratorChainInterface> {
649
        self.params.orchestrator_chain_interface.clone()
650
    }
651

            
652
    /// Try to start a new container chain. In case of an error, this does not stop the node, and
653
    /// the container chain will be attempted to spawn again when the collator is reassigned to it.
654
    ///
655
    /// It is possible that we try to spawn-stop-spawn the same chain, and the second spawn fails
656
    /// because the chain has not stopped yet, because `stop` does not wait for the chain to stop,
657
    /// so before calling `spawn` make sure to call `wait_for_paritydb_lock` before, like we do in
658
    /// `handle_update_assignment`.
659
    async fn spawn(&self, container_chain_para_id: ParaId, start_collation: bool) {
660
        let try_spawn_params = self.params.clone();
661
        let state = self.state.clone();
662
        let state2 = state.clone();
663

            
664
        match try_spawn(
665
            try_spawn_params,
666
            state,
667
            container_chain_para_id,
668
            start_collation,
669
        )
670
        .await
671
        {
672
            Ok(()) => {}
673
            Err(e) => {
674
                log::error!(
675
                    "Failed to start container chain {}: {}",
676
                    container_chain_para_id,
677
                    e
678
                );
679
                // Mark this container chain as "failed to start"
680
                let mut state = state2.lock().expect("poison error");
681
                state.failed_para_ids.insert(container_chain_para_id);
682
            }
683
        }
684
    }
685

            
686
    /// Stop a container chain. Prints a warning if the container chain was not running.
687
    /// Returns the database path for the container chain, can be used with `wait_for_paritydb_lock`
688
    /// to ensure that the container chain has fully stopped. The database path can be `None` if the
689
    /// chain was not running.
690
    fn stop(&self, container_chain_para_id: ParaId, keep_db: bool) -> Option<PathBuf> {
691
        let mut state = self.state.lock().expect("poison error");
692
        let stop_handle = state
693
            .spawned_container_chains
694
            .remove(&container_chain_para_id);
695

            
696
        match stop_handle {
697
            Some(stop_handle) => {
698
                log::info!("Stopping container chain {}", container_chain_para_id);
699

            
700
                let id = stop_handle.stop_handle.id;
701
                state
702
                    .spawned_containers_monitor
703
                    .set_stop_signal_time(id, Instant::now());
704

            
705
                // Send signal to perform graceful shutdown, which will delete the db if needed
706
                let _ = stop_handle.stop_handle.signal.send(keep_db);
707

            
708
                Some(stop_handle.db_path)
709
            }
710
            None => {
711
                // Do not print the warning message if this is a container chain that has failed to
712
                // start, because in that case it will not be running
713
                if !state.failed_para_ids.remove(&container_chain_para_id) {
714
                    log::warn!(
715
                        "Tried to stop a container chain that is not running: {}",
716
                        container_chain_para_id
717
                    );
718
                }
719

            
720
                None
721
            }
722
        }
723
    }
724
}
725

            
726
impl<
727
        RuntimeApi: MinimalContainerRuntimeApi,
728
        TGenerateRpcBuilder: GenerateRpcBuilder<RuntimeApi>,
729
    > ContainerChainSpawner<RuntimeApi, TGenerateRpcBuilder>
730
{
731
    /// Receive and process `CcSpawnMsg`s indefinitely
732
    pub async fn rx_loop(
733
        mut self,
734
        mut rx: mpsc::UnboundedReceiver<CcSpawnMsg>,
735
        validator: bool,
736
        solochain: bool,
737
    ) {
738
        let orchestrator_para_id = self
739
            .params
740
            .collation_params
741
            .as_ref()
742
            .expect("assignment update should only occur in a collating node")
743
            .orchestrator_para_id;
744

            
745
        // The node always starts as an orchestrator chain collator.
746
        // This is because the assignment is detected after importing a new block, so if all
747
        // collators stop at the same time, when they start again nobody will produce the new block.
748
        // So all nodes start as orchestrator chain collators, until the first block is imported,
749
        // then the real assignment is used.
750
        // Except in solochain mode, then the initial assignment is None.
751
        if validator && !solochain {
752
            self.handle_update_assignment(Some(orchestrator_para_id), None)
753
                .await;
754
        }
755

            
756
        while let Some(msg) = rx.recv().await {
757
            match msg {
758
                CcSpawnMsg::UpdateAssignment { current, next } => {
759
                    self.handle_update_assignment(current, next).await;
760
                }
761
            }
762
        }
763

            
764
        // The while loop can end if all the senders get dropped, but since this is an
765
        // essential task we don't want it to stop. So await a future that never completes.
766
        // This should only happen when starting a full node.
767
        if !validator {
768
            let () = std::future::pending().await;
769
        }
770
    }
771

            
772
    /// Handle `CcSpawnMsg::UpdateAssignment`
773
    async fn handle_update_assignment(&mut self, current: Option<ParaId>, next: Option<ParaId>) {
774
        if !self.db_folder_cleanup_done {
775
            self.db_folder_cleanup_done = true;
776

            
777
            // Disabled when running with --keep-db
778
            let keep_db = self.params.container_chain_cli.base.keep_db;
779
            if !keep_db {
780
                let mut chains_to_keep = HashSet::new();
781
                chains_to_keep.extend(current);
782
                chains_to_keep.extend(next);
783
                self.db_folder_cleanup(&chains_to_keep);
784
            }
785
        }
786

            
787
        let orchestrator_para_id = self
788
            .params
789
            .collation_params
790
            .as_ref()
791
            .expect("assignment update should only occur in a collating node")
792
            .orchestrator_para_id;
793

            
794
        let HandleUpdateAssignmentResult {
795
            chains_to_stop,
796
            chains_to_start,
797
            need_to_restart: _,
798
        } = handle_update_assignment_state_change(
799
            &mut self.state.lock().expect("poison error"),
800
            orchestrator_para_id,
801
            current,
802
            next,
803
        );
804

            
805
        if current != Some(orchestrator_para_id) {
806
            // If not assigned to orchestrator chain anymore, we need to stop the collator process
807
            let maybe_exit_notification_receiver = self
808
                .collation_cancellation_constructs
809
                .take()
810
                .map(|(cancellation_token, exit_notification_receiver)| {
811
                    cancellation_token.cancel();
812
                    exit_notification_receiver
813
                });
814

            
815
            if let Some(exit_notification_receiver) = maybe_exit_notification_receiver {
816
                let _ = exit_notification_receiver.await;
817
            }
818
        } else if self.collation_cancellation_constructs.is_none() {
819
            // If assigned to orchestrator chain but the collator process is not running, start it
820
            self.collation_cancellation_constructs = Some((self.collate_on_tanssi)());
821
        }
822

            
823
        // Stop all container chains that are no longer needed
824
        let mut db_paths_restart = vec![];
825
        for para_id in chains_to_stop {
826
            // Keep db if we are currently assigned to this chain
827
            let keep_db = Some(para_id) == current;
828
            let maybe_db_path = self.stop(para_id, keep_db);
829
            // If we are restarting this chain, save its db_path to check when it actually stopped
830
            if let Some(db_path) = maybe_db_path {
831
                if chains_to_start.contains(&para_id) {
832
                    db_paths_restart.push((para_id, db_path));
833
                }
834
            }
835
        }
836

            
837
        if !db_paths_restart.is_empty() {
838
            // Ensure the chains we stopped actually stopped by checking if their database is unlocked.
839
            // Using `join_all` because in one edge case we may be restarting 2 chains,
840
            // but almost always this will be only one future.
841
            let futs = db_paths_restart
842
                .into_iter()
843
                .map(|(para_id, db_path)| async move {
844
                    wait_for_paritydb_lock(&db_path, MAX_DB_RESTART_TIMEOUT)
845
                        .await
846
                        .map_err(|e| {
847
                            log::warn!(
848
                                "Error waiting for chain {} to release db lock: {:?}",
849
                                para_id,
850
                                e
851
                            );
852
                        })
853
                });
854
            futures::future::join_all(futs).await;
855
        }
856

            
857
        // Start all new container chains (usually 1)
858
        for para_id in chains_to_start {
859
            // Edge case: when starting the node it may be assigned to a container chain, so we need to
860
            // start a container chain already collating.
861
            // TODO: another edge case: if current == None, and running_chains == 0,
862
            // and chains_to_start == 1, we can start this chain as collating, and we won't need
863
            // to restart it on the next session. We need to add some extra state somewhere to
864
            // implement this properly.
865
            let start_collation = Some(para_id) == current;
866
            self.spawn(para_id, start_collation).await;
867
        }
868
    }
869

            
870
    fn db_folder_cleanup(&self, chains_to_keep: &HashSet<ParaId>) {
871
        // "containers" folder
872
        let mut base_path = self
873
            .params
874
            .container_chain_cli
875
            .base
876
            .base
877
            .shared_params
878
            .base_path
879
            .as_ref()
880
            .expect("base_path is always set")
881
            .to_owned();
882

            
883
        // "containers/chains"
884
        base_path.push("chains");
885

            
886
        // Inside chains folder we have container folders such as
887
        // containers/chains/simple_container_2000/
888
        // containers/chains/frontier_container_2001/
889
        // But this is not the para id, it's the chain id which we have set to include the para id, but that's not mandatory.
890
        // To get the para id we need to look for the paritydb folder:
891
        // containers/chains/frontier_container_2001/paritydb/full-container-2001/
892
        let mut chain_folders = sort_container_folders_by_para_id(&base_path);
893

            
894
        // Keep chains that we are assigned to
895
        for para_id in chains_to_keep {
896
            chain_folders.remove(&Some(*para_id));
897
        }
898

            
899
        // Print nice log message when removing folders
900
        if !chain_folders.is_empty() {
901
            let chain_folders_fmt = chain_folders
902
                .iter()
903
                .flat_map(|(para_id, vec_paths)| {
904
                    let para_id_fmt = if let Some(para_id) = para_id {
905
                        para_id.to_string()
906
                    } else {
907
                        "None".to_string()
908
                    };
909
                    vec_paths
910
                        .iter()
911
                        .map(move |path| format!("\n{}: {}", para_id_fmt, path.display()))
912
                })
913
                .collect::<String>();
914
            log::info!(
915
                "db_folder_cleanup: removing container folders: (para_id, path):{}",
916
                chain_folders_fmt
917
            );
918
        }
919

            
920
        // Remove, ignoring errors
921
        for (_para_id, folders) in chain_folders {
922
            for folder in folders {
923
                let _ = std::fs::remove_dir_all(&folder);
924
            }
925
        }
926
    }
927
}
928

            
929
struct HandleUpdateAssignmentResult {
930
    chains_to_stop: Vec<ParaId>,
931
    chains_to_start: Vec<ParaId>,
932
    #[allow(dead_code)] // no longer used except in tests
933
    need_to_restart: bool,
934
}
935

            
936
// This is a separate function to allow testing
937
35
fn handle_update_assignment_state_change(
938
35
    state: &mut ContainerChainSpawnerState,
939
35
    orchestrator_para_id: ParaId,
940
35
    current: Option<ParaId>,
941
35
    next: Option<ParaId>,
942
35
) -> HandleUpdateAssignmentResult {
943
35
    if (state.assigned_para_id, state.next_assigned_para_id) == (current, next) {
944
        // If nothing changed there is nothing to update
945
        return HandleUpdateAssignmentResult {
946
            chains_to_stop: Default::default(),
947
            chains_to_start: Default::default(),
948
            need_to_restart: false,
949
        };
950
35
    }
951
35

            
952
35
    // Create a set with the container chains that were running before, and the container
953
35
    // chains that should be running after the updated assignment. This is used to calculate
954
35
    // the difference, and stop and start the required container chains.
955
35
    let mut running_chains_before = HashSet::new();
956
35
    let mut running_chains_after = HashSet::new();
957
35

            
958
35
    running_chains_before.extend(state.assigned_para_id);
959
35
    running_chains_before.extend(state.next_assigned_para_id);
960
35
    // Ignore orchestrator_para_id because it is handled in a special way, as it does not need to
961
35
    // start one session before in order to sync.
962
35
    running_chains_before.remove(&orchestrator_para_id);
963
35

            
964
35
    running_chains_after.extend(current);
965
35
    running_chains_after.extend(next);
966
35
    running_chains_after.remove(&orchestrator_para_id);
967
35
    let mut need_to_restart_current = false;
968
35
    let mut need_to_restart_next = false;
969
35

            
970
35
    if state.assigned_para_id != current {
971
24
        if let Some(para_id) = current {
972
            // If the assigned container chain has changed, we may need to
973
            // restart it in collation mode, unless it is the orchestrator chain.
974
16
            if para_id != orchestrator_para_id {
975
13
                need_to_restart_current = true;
976
13
            }
977
8
        }
978

            
979
24
        if let Some(para_id) = state.assigned_para_id {
980
18
            if para_id != orchestrator_para_id && Some(para_id) == next {
981
2
                need_to_restart_next = true;
982
16
            }
983
6
        }
984
11
    }
985

            
986
35
    state.assigned_para_id = current;
987
35
    state.next_assigned_para_id = next;
988
35

            
989
35
    let mut chains_to_stop: Vec<_> = running_chains_before
990
35
        .difference(&running_chains_after)
991
35
        .copied()
992
35
        .collect();
993
35
    let mut chains_to_start: Vec<_> = running_chains_after
994
35
        .difference(&running_chains_before)
995
35
        .copied()
996
35
        .collect();
997
35

            
998
35
    if need_to_restart_current {
999
        // Force restart of new assigned container chain: if it was running before it was in "syncing mode",
        // which doesn't use the correct ports, so start it in "collation mode".
13
        let id = current.unwrap();
13
        if running_chains_before.contains(&id) && !chains_to_stop.contains(&id) {
6
            chains_to_stop.push(id);
7
        }
13
        if !chains_to_start.contains(&id) {
6
            chains_to_start.push(id);
7
        }
22
    }
35
    if need_to_restart_next {
        // Handle edge case of going from (2000, 2001) to (2001, 2000). In that case we must restart both chains,
        // because previously 2000 was collating and now 2000 will only be syncing.
2
        let id = next.unwrap();
2
        if running_chains_before.contains(&id) && !chains_to_stop.contains(&id) {
2
            chains_to_stop.push(id);
2
        }
2
        if !chains_to_start.contains(&id) {
2
            chains_to_start.push(id);
2
        }
33
    }
    HandleUpdateAssignmentResult {
35
        chains_to_stop,
35
        chains_to_start,
35
        need_to_restart: need_to_restart_current || need_to_restart_next,
    }
35
}
/// Select [SyncMode] to use for a container chain.
/// We want to use warp sync unless the db still exists, or the container chain is
/// still at genesis block (because of a warp sync bug in that case).
///
/// Remember that warp sync doesn't work if a partially synced database already exists, it falls
/// back to full sync instead. The only exception is if the previous instance of the database was
/// interrupted before it finished downloading the state, in that case the node will use warp sync.
/// If it was interrupted during the block history download, the node will use full sync but also
/// finish the block history download in the background, even if sync mode is set to full sync.
pub fn select_sync_mode_using_client(
    db_exists: bool,
    orchestrator_client: &Arc<ParachainClient>,
    container_chain_para_id: ParaId,
) -> sc_service::error::Result<SyncMode> {
    if db_exists {
        // If the user wants to use warp sync, they should have already removed the database
        return Ok(SyncMode::Full);
    }
    // The following check is only needed because of this bug:
    // https://github.com/paritytech/polkadot-sdk/issues/1930
    let orchestrator_runtime_api = orchestrator_client.runtime_api();
    let orchestrator_chain_info = orchestrator_client.chain_info();
    // If the container chain is still at genesis block, use full sync because warp sync is broken
    let full_sync_needed = orchestrator_runtime_api
        .latest_author(orchestrator_chain_info.best_hash, container_chain_para_id)
        .map_err(|e| format!("Failed to read latest author: {}", e))?
        .is_none();
    if full_sync_needed {
        Ok(SyncMode::Full)
    } else {
        Ok(SyncMode::Warp)
    }
}
async fn get_latest_container_block_number_from_orchestrator(
    orchestrator_chain_interface: &Arc<dyn OrchestratorChainInterface>,
    orchestrator_block_hash: PHash,
    container_chain_para_id: ParaId,
) -> Option<u32> {
    // Get the container chain's latest block from orchestrator chain and compare with client's one
    orchestrator_chain_interface
        .latest_block_number(orchestrator_block_hash, container_chain_para_id)
        .await
        .unwrap_or_default()
}
#[derive(Debug)]
#[allow(dead_code)]
enum DbRemovalReason {
    HighBlockDiff {
        best_block_number_db: u32,
        best_block_number_onchain: u32,
    },
    GenesisHashMismatch {
        container_client_genesis_hash: H256,
        chain_spec_genesis_hash_v0: H256,
        chain_spec_genesis_hash_v1: H256,
    },
}
/// Given a container chain client, check if the database is valid. If not, returns `Some` with the
/// reason for db removal.
/// Reasons may be:
/// * High block diff: when the local db is outdated and it would take a long time to sync using full sync, we remove it to be able to use warp sync.
/// * Genesis hash mismatch, when the chain was deregistered and a different chain with the same para id was registered.
async fn db_needs_removal<RuntimeApi: MinimalContainerRuntimeApi>(
    container_chain_client: &Arc<ContainerChainClient<RuntimeApi>>,
    orchestrator_chain_interface: &Arc<dyn OrchestratorChainInterface>,
    orchestrator_block_hash: PHash,
    container_chain_para_id: ParaId,
    container_chain_cli: &ContainerChainCli,
    keep_db: bool,
) -> sc_service::error::Result<Option<DbRemovalReason>> {
    // Check block diff, only needed if keep-db is false
    if !keep_db {
        // Get latest block number from the container chain client
        let last_container_block_temp = container_chain_client.chain_info().best_number;
        if last_container_block_temp == 0 {
            // Don't remove an empty database, as it may be in the process of a warp sync
        } else if get_latest_container_block_number_from_orchestrator(
            orchestrator_chain_interface,
            orchestrator_block_hash,
            container_chain_para_id,
        )
        .await
        .unwrap_or(0)
        .abs_diff(last_container_block_temp)
            > MAX_BLOCK_DIFF_FOR_FULL_SYNC
        {
            // if the diff is big, delete db and restart using warp sync
            return Ok(Some(DbRemovalReason::HighBlockDiff {
                best_block_number_db: last_container_block_temp,
                best_block_number_onchain: last_container_block_temp,
            }));
        }
    }
    // Generate genesis hash to compare against container client's genesis hash
    let container_preloaded_genesis = container_chain_cli.preloaded_chain_spec.as_ref().unwrap();
    // Check with both state versions, but first v1 which is the latest
    let block_v1: Block =
        generate_genesis_block(&**container_preloaded_genesis, sp_runtime::StateVersion::V1)
            .map_err(|e| format!("{:?}", e))?;
    let chain_spec_genesis_hash_v1 = block_v1.header().hash();
    let container_client_genesis_hash = container_chain_client.chain_info().genesis_hash;
    if container_client_genesis_hash != chain_spec_genesis_hash_v1 {
        let block_v0: Block =
            generate_genesis_block(&**container_preloaded_genesis, sp_runtime::StateVersion::V0)
                .map_err(|e| format!("{:?}", e))?;
        let chain_spec_genesis_hash_v0 = block_v0.header().hash();
        if container_client_genesis_hash != chain_spec_genesis_hash_v0 {
            log::info!("Container genesis V0: {:?}", chain_spec_genesis_hash_v0);
            log::info!("Container genesis V1: {:?}", chain_spec_genesis_hash_v1);
            log::info!(
                "Chain spec genesis {:?} did not match with any container genesis - Restarting...",
                container_client_genesis_hash
            );
            return Ok(Some(DbRemovalReason::GenesisHashMismatch {
                container_client_genesis_hash,
                chain_spec_genesis_hash_v0,
                chain_spec_genesis_hash_v1,
            }));
        }
    }
    Ok(None)
}
/// Remove the container chain database folder. This is called with db_path:
///     `Collator2002-01/data/containers/chains/simple_container_2002/paritydb/full-container-2002`
/// but we want to delete everything under
///     `Collator2002-01/data/containers/chains/simple_container_2002`
/// So we use `delete_empty_folders_recursive` to try to remove the parent folders as well, but only
/// if they are empty. This is to avoid removing any secret keys or other important data.
fn delete_container_chain_db(db_path: &Path) {
    // Remove folder `full-container-2002`
    let _ = std::fs::remove_dir_all(db_path);
    // Remove all the empty folders inside `simple_container_2002`, including self
    if let Some(parent) = db_path.ancestors().nth(2) {
        delete_empty_folders_recursive(parent);
    }
}
/// Removes all empty folders in `path`, recursively. Then, if `path` is empty, it removes it as well.
/// Ignores any IO errors.
fn delete_empty_folders_recursive(path: &Path) {
    let entry_iter = std::fs::read_dir(path);
    let entry_iter = match entry_iter {
        Ok(x) => x,
        Err(_e) => return,
    };
    for entry in entry_iter {
        let entry = match entry {
            Ok(x) => x,
            Err(_e) => continue,
        };
        let path = entry.path();
        if path.is_dir() {
            delete_empty_folders_recursive(&path);
        }
    }
    // Try to remove dir. Returns an error if the directory is not empty, but we ignore it.
    let _ = std::fs::remove_dir(path);
}
/// Parse a list of boot nodes in `Vec<u8>` format. Invalid boot nodes are filtered out.
3
fn parse_boot_nodes_ignore_invalid(
3
    boot_nodes_raw: Vec<Vec<u8>>,
3
    container_chain_para_id: ParaId,
3
) -> Vec<MultiaddrWithPeerId> {
3
    boot_nodes_raw
3
        .into_iter()
3
        .filter_map(|x| {
3
            let x = String::from_utf8(x)
3
                .map_err(|e| {
1
                    log::debug!(
                        "Invalid boot node in container chain {}: {}",
                        container_chain_para_id,
                        e
                    );
3
                })
3
                .ok()?;
2
            x.parse::<MultiaddrWithPeerId>()
2
                .map_err(|e| {
1
                    log::debug!(
                        "Invalid boot node in container chain {}: {}",
                        container_chain_para_id,
                        e
                    )
2
                })
2
                .ok()
3
        })
3
        .collect()
3
}
pub async fn wait_for_paritydb_lock(db_path: &Path, max_timeout: Duration) -> Result<(), String> {
    let now = Instant::now();
    while now.elapsed() < max_timeout {
        let lock_held = check_paritydb_lock_held(db_path)
            .map_err(|e| format!("Failed to check if lock file is held: {}", e))?;
        if !lock_held {
            return Ok(());
        }
        sleep(Duration::from_secs(1)).await;
    }
    Err("Timeout when waiting for paritydb lock".to_string())
}
/// Given a path to a paritydb database, check if its lock file is held. This indicates that a
/// background process is still using the database, so we should wait before trying to open it.
///
/// This should be kept up to date with the way paritydb handles the lock file:
/// <https://github.com/paritytech/parity-db/blob/2b6820e310a08678d4540c044f41a93d87343ac8/src/db.rs#L215>
fn check_paritydb_lock_held(db_path: &Path) -> Result<bool, std::io::Error> {
    if !db_path.is_dir() {
        // Lock file does not exist, so it is not held
        return Ok(false);
    }
    let mut lock_path: std::path::PathBuf = db_path.to_owned();
    lock_path.push("lock");
    let lock_file = std::fs::OpenOptions::new()
        .create(true)
        .read(true)
        .write(true)
        .truncate(true)
        .open(lock_path.as_path())?;
    // Check if the lock file is busy by trying to lock it.
    // Returns err if failed to adquire the lock.
    let lock_held = lock_file.try_lock_exclusive().is_err();
    Ok(lock_held)
}
fn sort_container_folders_by_para_id(
    chains_folder_path: &Path,
) -> HashMap<Option<ParaId>, Vec<PathBuf>> {
    let mut h = HashMap::new();
    let entry_iter = std::fs::read_dir(chains_folder_path);
    let entry_iter = match entry_iter {
        Ok(x) => x,
        Err(_e) => return h,
    };
    for entry in entry_iter {
        let entry = match entry {
            Ok(x) => x,
            Err(_e) => continue,
        };
        let path = entry.path();
        if path.is_dir() {
            if let Ok(para_id) = process_container_folder_get_para_id(path.clone()) {
                h.entry(para_id).or_default().push(path);
            }
        }
    }
    h
}
fn process_container_folder_get_para_id(path: PathBuf) -> std::io::Result<Option<ParaId>> {
    // Build the path to the paritydb directory
    let paritydb_path = path.join("paritydb");
    // Check if the paritydb directory exists and is a directory
    if !paritydb_path.is_dir() {
        // If not, associate the path with `None` in the hashmap
        return Ok(None);
    }
    // Read the entries in the paritydb directory
    let entry_iter = std::fs::read_dir(&paritydb_path)?;
    let mut para_id: Option<ParaId> = None;
    // Iterate over each entry in the paritydb directory
    for entry in entry_iter {
        let entry = entry?;
        let sub_path = entry.path();
        // Only consider directories
        if !sub_path.is_dir() {
            continue;
        }
        let sub_path_file_name = match sub_path.file_name().and_then(|s| s.to_str()) {
            Some(x) => x,
            None => {
                continue;
            }
        };
        // That follow this pattern
        if !sub_path_file_name.starts_with("full-container-") {
            continue;
        }
        if let Some(id) = parse_para_id_from_folder_name(sub_path_file_name) {
            if para_id.is_some() {
                // If there is more than one folder with a para id, assume this folder is
                // corrupted and ignore it, keep it for manual deletion
                return Err(std::io::Error::new(std::io::ErrorKind::Other, ""));
            }
            para_id = Some(id);
        }
    }
    Ok(para_id)
}
// Input:
// full-container-2000
// Output:
// Some(2000)
5
fn parse_para_id_from_folder_name(folder_name: &str) -> Option<ParaId> {
    // Find last '-' in string
5
    let idx = folder_name.rfind('-')?;
    // +1 to skip the '-'
3
    let id_str = &folder_name[idx + 1..];
    // Try to parse as u32, in case of error return None
3
    let id = id_str.parse::<u32>().ok()?;
1
    Some(id.into())
5
}
#[cfg(test)]
mod tests {
    use {super::*, std::path::PathBuf};
    // Copy of ContainerChainSpawner with extra assertions for tests, and mocked spawn function.
    struct MockContainerChainSpawner {
        state: Arc<Mutex<ContainerChainSpawnerState>>,
        orchestrator_para_id: ParaId,
        collate_on_tanssi: Arc<
            dyn Fn() -> (CancellationToken, futures::channel::oneshot::Receiver<()>) + Send + Sync,
        >,
        collation_cancellation_constructs: Option<()>,
        // Keep track of the last CollateOn message, for tests
        currently_collating_on: Arc<Mutex<Option<ParaId>>>,
    }
    impl MockContainerChainSpawner {
10
        fn new() -> Self {
10
            let orchestrator_para_id = 1000.into();
10
            // The node always starts as an orchestrator chain collator
10
            let currently_collating_on = Arc::new(Mutex::new(Some(orchestrator_para_id)));
10
            let currently_collating_on2 = currently_collating_on.clone();
10
            let collate_closure = move || {
3
                let mut cco = currently_collating_on2.lock().unwrap();
3
                assert_ne!(
3
                    *cco,
3
                    Some(orchestrator_para_id),
                    "Received CollateOn message when we were already collating on this chain: {}",
                    orchestrator_para_id
                );
3
                *cco = Some(orchestrator_para_id);
3
                let (_, receiver) = futures::channel::oneshot::channel();
3
                (CancellationToken::new(), receiver)
3
            };
10
            let collate_on_tanssi: Arc<
10
                dyn Fn() -> (CancellationToken, futures::channel::oneshot::Receiver<()>)
10
                    + Send
10
                    + Sync,
10
            > = Arc::new(collate_closure);
10

            
10
            Self {
10
                state: Arc::new(Mutex::new(ContainerChainSpawnerState {
10
                    spawned_container_chains: Default::default(),
10
                    assigned_para_id: Some(orchestrator_para_id),
10
                    next_assigned_para_id: None,
10
                    failed_para_ids: Default::default(),
10
                    spawned_containers_monitor: Default::default(),
10
                })),
10
                orchestrator_para_id,
10
                collate_on_tanssi,
10
                // Some if collator starts on orchestrator chain
10
                collation_cancellation_constructs: Some(()),
10
                currently_collating_on,
10
            }
10
        }
21
        fn spawn(&self, container_chain_para_id: ParaId, start_collation: bool) {
21
            let (signal, _on_exit) = oneshot::channel();
21
            let currently_collating_on2 = self.currently_collating_on.clone();
21
            let collate_closure = move || {
13
                let mut cco = currently_collating_on2.lock().unwrap();
13
                assert_ne!(
13
                    *cco,
13
                    Some(container_chain_para_id),
                    "Received CollateOn message when we were already collating on this chain: {}",
                    container_chain_para_id
                );
13
                *cco = Some(container_chain_para_id);
13
                let (_, receiver) = futures::channel::oneshot::channel();
13
                (CancellationToken::new(), receiver)
13
            };
21
            let collate_on: Arc<
21
                dyn Fn() -> (CancellationToken, futures::channel::oneshot::Receiver<()>)
21
                    + Send
21
                    + Sync,
21
            > = Arc::new(collate_closure);
21
            // Dummy db_path for tests, is not actually used
21
            let db_path = PathBuf::from(format!("/tmp/container-{}/db", container_chain_para_id));
21

            
21
            let old = self
21
                .state
21
                .lock()
21
                .expect("poison error")
21
                .spawned_container_chains
21
                .insert(
21
                    container_chain_para_id,
21
                    ContainerChainState {
21
                        stop_handle: StopContainerChain { signal, id: 0 },
21
                        db_path,
21
                    },
21
                );
21

            
21
            assert!(
21
                old.is_none(),
                "tried to spawn a container chain that was already running: {}",
                container_chain_para_id
            );
21
            if start_collation {
13
                let (_cancellation_token, _exit_receiver) = collate_on();
13
            }
21
        }
15
        fn stop(&self, container_chain_para_id: ParaId) {
15
            let stop_handle = self
15
                .state
15
                .lock()
15
                .expect("poison error")
15
                .spawned_container_chains
15
                .remove(&container_chain_para_id);
15

            
15
            match stop_handle {
15
                Some(_stop_handle) => {
15
                    log::info!("Stopping container chain {}", container_chain_para_id);
                }
                None => {
                    panic!(
                        "Tried to stop a container chain that is not running: {}",
                        container_chain_para_id
                    );
                }
            }
            // Update currently_collating_on, if we stopped the chain we are no longer collating there
15
            let mut lco = self.currently_collating_on.lock().unwrap();
15
            if *lco == Some(container_chain_para_id) {
7
                *lco = None;
8
            }
15
        }
35
        fn handle_update_assignment(&mut self, current: Option<ParaId>, next: Option<ParaId>) {
35
            let HandleUpdateAssignmentResult {
35
                chains_to_stop,
35
                chains_to_start,
35
                need_to_restart,
35
            } = handle_update_assignment_state_change(
35
                &mut self.state.lock().unwrap(),
35
                self.orchestrator_para_id,
35
                current,
35
                next,
35
            );
35

            
35
            if current != Some(self.orchestrator_para_id) {
                // If not assigned to orchestrator chain anymore, we need to stop the collator process
27
                let mut cco = self.currently_collating_on.lock().unwrap();
27
                if *cco == Some(self.orchestrator_para_id) {
10
                    *cco = None;
17
                }
27
                self.collation_cancellation_constructs = None;
8
            } else if self.collation_cancellation_constructs.is_none() {
3
                let (_cancellation_token, _exit_notification_receiver) = (self.collate_on_tanssi)();
3
                self.collation_cancellation_constructs = Some(());
5
            }
            // Assert we never start and stop the same container chain
56
            for para_id in &chains_to_start {
21
                if !need_to_restart {
4
                    assert!(
4
                        !chains_to_stop.contains(para_id),
                        "Tried to start and stop same container chain: {}",
                        para_id
                    );
                } else {
                    // Will try to start and stop container chain with id "current" or "next", so ignore that
17
                    if Some(*para_id) != current && Some(*para_id) != next {
                        assert!(
                            !chains_to_stop.contains(para_id),
                            "Tried to start and stop same container chain: {}",
                            para_id
                        );
17
                    }
                }
            }
            // Assert we never start or stop the orchestrator chain
35
            assert!(!chains_to_start.contains(&self.orchestrator_para_id));
35
            assert!(!chains_to_stop.contains(&self.orchestrator_para_id));
            // Stop all container chains that are no longer needed
50
            for para_id in chains_to_stop {
15
                self.stop(para_id);
15
            }
            // Start all new container chains (usually 1)
56
            for para_id in chains_to_start {
21
                // Edge case: when starting the node it may be assigned to a container chain, so we need to
21
                // start a container chain already collating.
21
                let start_collation = Some(para_id) == current;
21
                self.spawn(para_id, start_collation);
21
            }
            // Assert that if we are currently assigned to a container chain, we are collating there
35
            if let Some(para_id) = current {
24
                self.assert_collating_on(Some(para_id));
24
            } else {
11
                self.assert_collating_on(None);
11
            }
35
        }
        #[track_caller]
71
        fn assert_collating_on(&self, para_id: Option<ParaId>) {
71
            let currently_collating_on = *self.currently_collating_on.lock().unwrap();
71
            assert_eq!(currently_collating_on, para_id);
71
        }
        #[track_caller]
36
        fn assert_running_chains(&self, para_ids: &[ParaId]) {
36
            let mut actually_running: Vec<ParaId> = self
36
                .state
36
                .lock()
36
                .unwrap()
36
                .spawned_container_chains
36
                .keys()
36
                .cloned()
36
                .collect();
36
            actually_running.sort();
36
            let mut should_be_running = para_ids.to_vec();
36
            should_be_running.sort();
36
            assert_eq!(actually_running, should_be_running);
36
        }
    }
    #[test]
1
    fn starts_collating_on_tanssi() {
1
        let mut m = MockContainerChainSpawner::new();
1
        m.assert_collating_on(Some(1000.into()));
1
        m.assert_running_chains(&[]);
1

            
1
        m.handle_update_assignment(None, None);
1
        m.assert_collating_on(None);
1
        m.assert_running_chains(&[]);
1
    }
    #[test]
1
    fn assigned_to_orchestrator_chain() {
1
        let mut m = MockContainerChainSpawner::new();
1

            
1
        m.handle_update_assignment(Some(1000.into()), Some(1000.into()));
1
        m.assert_collating_on(Some(1000.into()));
1
        m.assert_running_chains(&[]);
1

            
1
        m.handle_update_assignment(Some(1000.into()), None);
1
        m.assert_collating_on(Some(1000.into()));
1
        m.assert_running_chains(&[]);
1

            
1
        m.handle_update_assignment(None, None);
1
        m.assert_collating_on(None);
1
        m.assert_running_chains(&[]);
1

            
1
        m.handle_update_assignment(None, Some(1000.into()));
1
        m.assert_collating_on(None);
1
        m.assert_running_chains(&[]);
1

            
1
        m.handle_update_assignment(Some(1000.into()), Some(1000.into()));
1
        m.assert_collating_on(Some(1000.into()));
1
        m.assert_running_chains(&[]);
1
    }
    #[test]
1
    fn assigned_to_container_chain() {
1
        let mut m = MockContainerChainSpawner::new();
1

            
1
        m.handle_update_assignment(Some(2000.into()), Some(2000.into()));
1
        m.assert_collating_on(Some(2000.into()));
1
        m.assert_running_chains(&[2000.into()]);
1

            
1
        m.handle_update_assignment(Some(2000.into()), None);
1
        m.assert_collating_on(Some(2000.into()));
1
        m.assert_running_chains(&[2000.into()]);
1

            
1
        m.handle_update_assignment(None, None);
1
        m.assert_collating_on(None);
1
        m.assert_running_chains(&[]);
1

            
1
        m.handle_update_assignment(None, Some(2000.into()));
1
        m.assert_collating_on(None);
1
        m.assert_running_chains(&[2000.into()]);
1

            
1
        m.handle_update_assignment(Some(2000.into()), Some(2000.into()));
1
        m.assert_collating_on(Some(2000.into()));
1
        m.assert_running_chains(&[2000.into()]);
1
    }
    #[test]
1
    fn spawn_container_chains() {
1
        let mut m = MockContainerChainSpawner::new();
1

            
1
        m.handle_update_assignment(Some(1000.into()), Some(2000.into()));
1
        m.assert_collating_on(Some(1000.into()));
1
        m.assert_running_chains(&[2000.into()]);
1

            
1
        m.handle_update_assignment(Some(2000.into()), Some(2000.into()));
1
        m.assert_collating_on(Some(2000.into()));
1
        m.assert_running_chains(&[2000.into()]);
1

            
1
        m.handle_update_assignment(Some(2000.into()), Some(2001.into()));
1
        m.assert_collating_on(Some(2000.into()));
1
        m.assert_running_chains(&[2000.into(), 2001.into()]);
1

            
1
        m.handle_update_assignment(Some(2001.into()), Some(2001.into()));
1
        m.assert_collating_on(Some(2001.into()));
1
        m.assert_running_chains(&[2001.into()]);
1

            
1
        m.handle_update_assignment(Some(2001.into()), Some(1000.into()));
1
        m.assert_collating_on(Some(2001.into()));
1
        m.assert_running_chains(&[2001.into()]);
1

            
1
        m.handle_update_assignment(Some(1000.into()), Some(1000.into()));
1
        m.assert_collating_on(Some(1000.into()));
1
        m.assert_running_chains(&[]);
1
    }
    #[test]
1
    fn swap_current_next() {
1
        // Going from (2000, 2001) to (2001, 2000) shouldn't start or stop any container chains
1
        let mut m: MockContainerChainSpawner = MockContainerChainSpawner::new();
1

            
1
        m.handle_update_assignment(Some(2000.into()), Some(2001.into()));
1
        m.assert_collating_on(Some(2000.into()));
1
        m.assert_running_chains(&[2000.into(), 2001.into()]);
1

            
1
        m.handle_update_assignment(Some(2001.into()), Some(2000.into()));
1
        m.assert_collating_on(Some(2001.into()));
1
        m.assert_running_chains(&[2000.into(), 2001.into()]);
1
    }
    #[test]
1
    fn stop_collating_orchestrator() {
1
        let mut m: MockContainerChainSpawner = MockContainerChainSpawner::new();
1

            
1
        m.handle_update_assignment(Some(1000.into()), Some(1000.into()));
1
        m.assert_collating_on(Some(1000.into()));
1
        m.assert_running_chains(&[]);
1

            
1
        m.handle_update_assignment(Some(1000.into()), None);
1
        m.assert_collating_on(Some(1000.into()));
1
        m.assert_running_chains(&[]);
1

            
1
        m.handle_update_assignment(None, None);
1
        m.assert_collating_on(None);
1
        m.assert_running_chains(&[]);
1

            
1
        m.handle_update_assignment(Some(1000.into()), None);
1
        m.assert_collating_on(Some(1000.into()));
1
        m.assert_running_chains(&[]);
1
    }
    #[test]
1
    fn stop_collating_container() {
1
        let mut m: MockContainerChainSpawner = MockContainerChainSpawner::new();
1

            
1
        m.handle_update_assignment(Some(2000.into()), None);
1
        m.assert_collating_on(Some(2000.into()));
1
        m.assert_running_chains(&[2000.into()]);
1

            
1
        m.handle_update_assignment(None, None);
1
        m.assert_collating_on(None);
1
        m.assert_running_chains(&[]);
1

            
1
        m.handle_update_assignment(None, Some(2000.into()));
1
        m.assert_collating_on(None);
1
        m.assert_running_chains(&[2000.into()]);
1

            
1
        // This will send a CollateOn message to the same chain as the last CollateOn,
1
        // but this is needed because that chain has been stopped
1
        m.handle_update_assignment(Some(2000.into()), Some(2000.into()));
1
        m.assert_collating_on(Some(2000.into()));
1
        m.assert_running_chains(&[2000.into()]);
1
    }
    #[test]
1
    fn stop_collating_container_start_immediately() {
1
        let mut m: MockContainerChainSpawner = MockContainerChainSpawner::new();
1

            
1
        m.handle_update_assignment(Some(2000.into()), None);
1
        m.assert_collating_on(Some(2000.into()));
1
        m.assert_running_chains(&[2000.into()]);
1

            
1
        m.handle_update_assignment(None, None);
1
        m.assert_collating_on(None);
1
        m.assert_running_chains(&[]);
1

            
1
        // This will start the chain already collating
1
        m.handle_update_assignment(Some(2000.into()), Some(2000.into()));
1
        m.assert_collating_on(Some(2000.into()));
1
        m.assert_running_chains(&[2000.into()]);
1
    }
    #[test]
1
    fn stop_all_chains() {
1
        let mut m: MockContainerChainSpawner = MockContainerChainSpawner::new();
1

            
1
        m.handle_update_assignment(Some(2000.into()), Some(2001.into()));
1
        m.assert_collating_on(Some(2000.into()));
1
        m.assert_running_chains(&[2000.into(), 2001.into()]);
1

            
1
        m.handle_update_assignment(None, None);
1
        m.assert_collating_on(None);
1
        m.assert_running_chains(&[]);
1
    }
    #[test]
1
    fn keep_collating_on_container() {
1
        let mut m: MockContainerChainSpawner = MockContainerChainSpawner::new();
1

            
1
        m.handle_update_assignment(Some(2000.into()), None);
1
        m.assert_collating_on(Some(2000.into()));
1
        m.assert_running_chains(&[2000.into()]);
1

            
1
        m.handle_update_assignment(None, Some(2000.into()));
1
        m.assert_collating_on(None);
1
        m.assert_running_chains(&[2000.into()]);
1

            
1
        m.handle_update_assignment(Some(2000.into()), Some(2000.into()));
1
        m.assert_collating_on(Some(2000.into()));
1
        m.assert_running_chains(&[2000.into()]);
1
    }
    #[test]
1
    fn invalid_boot_nodes_are_ignored() {
1
        let para_id = 100.into();
1
        let bootnode1 =
1
            b"/ip4/127.0.0.1/tcp/33049/ws/p2p/12D3KooWHVMhQDHBpj9vQmssgyfspYecgV6e3hH1dQVDUkUbCYC9"
1
                .to_vec();
1
        assert_eq!(
1
            parse_boot_nodes_ignore_invalid(vec![b"A".to_vec()], para_id),
1
            vec![]
1
        );
1
        assert_eq!(
1
            parse_boot_nodes_ignore_invalid(vec![b"\xff".to_vec()], para_id),
1
            vec![]
1
        );
        // Valid boot nodes are not ignored
1
        assert_eq!(
1
            parse_boot_nodes_ignore_invalid(vec![bootnode1], para_id).len(),
1
            1
1
        );
1
    }
    #[test]
1
    fn path_ancestors() {
1
        // Test the implementation of `delete_container_chain_db`
1
        let db_path = PathBuf::from("/tmp/zombienet/Collator2002-01/data/containers/chains/simple_container_2002/paritydb/full-container-2002");
1
        let parent = db_path.ancestors().nth(2).unwrap();
1

            
1
        assert_eq!(
1
            parent,
1
            PathBuf::from(
1
                "/tmp/zombienet/Collator2002-01/data/containers/chains/simple_container_2002"
1
            )
1
        )
1
    }
    #[test]
1
    fn para_id_from_folder_name() {
1
        assert_eq!(parse_para_id_from_folder_name(""), None,);
1
        assert_eq!(parse_para_id_from_folder_name("full"), None,);
1
        assert_eq!(parse_para_id_from_folder_name("full-container"), None,);
1
        assert_eq!(parse_para_id_from_folder_name("full-container-"), None,);
1
        assert_eq!(
1
            parse_para_id_from_folder_name("full-container-2000"),
1
            Some(ParaId::from(2000)),
1
        );
1
    }
}