Skip to main content

risingwave_meta/barrier/
mod.rs

1// Copyright 2022 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::{HashMap, HashSet};
16
17use anyhow::anyhow;
18use risingwave_common::catalog::{DatabaseId, TableId};
19use risingwave_meta_model::WorkerId;
20use risingwave_pb::catalog::Database;
21use risingwave_pb::common::WorkerNode;
22use risingwave_pb::hummock::HummockVersionStats;
23use risingwave_pb::meta::PbRecoveryStatus;
24use tokio::sync::oneshot::Sender;
25
26use crate::barrier::info::BarrierInfo;
27use crate::manager::ActiveStreamingWorkerNodes;
28use crate::model::{ActorId, BackfillUpstreamType, FragmentId, StreamActor, SubscriptionId};
29use crate::notification::Notifier;
30use crate::{MetaError, MetaResult};
31
32mod backfill_order_control;
33pub mod cdc_progress;
34mod checkpoint;
35mod command;
36pub use command::RescheduleContext;
37mod complete_task;
38pub(super) mod context;
39mod edge_builder;
40mod info;
41mod manager;
42mod partial_graph;
43mod progress;
44mod rpc;
45mod schedule;
46#[cfg(test)]
47mod tests;
48mod trace;
49mod utils;
50mod worker;
51
52pub use backfill_order_control::{BackfillNode, BackfillOrderState};
53use risingwave_common::id::JobId;
54use risingwave_pb::ddl_service::PbBackfillType;
55
56pub use self::checkpoint::snapshot_backfill_max_pending_barrier_num;
57pub use self::command::{
58    BarrierKind, Command, CreateStreamingJobCommandInfo, CreateStreamingJobType,
59    IcebergPkIndexCompactionOverwrite, IndependentStreamingJobType, ReplaceStreamJobPlan,
60    Reschedule, ReschedulePlan, ResumeBackfillTarget, SinceEpochInfo, SnapshotBackfillInfo,
61};
62pub(crate) use self::info::{SharedActorInfos, SharedFragmentInfo};
63pub use self::manager::{BarrierManagerRef, GlobalBarrierManager};
64pub(crate) use self::rpc::to_partial_graph_id;
65pub use self::schedule::BarrierScheduler;
66pub use self::trace::TracedEpoch;
67use crate::barrier::cdc_progress::CdcProgress;
68use crate::barrier::context::recovery::LoadedRecoveryContext;
69use crate::controller::fragment::InflightFragmentInfo;
70use crate::stream::cdc::CdcTableSnapshotSplits;
71
72/// The reason why the cluster is recovering.
73enum RecoveryReason {
74    /// After bootstrap.
75    Bootstrap(Sender<HashMap<WorkerId, WorkerNode>>),
76    /// After failure.
77    Failover(MetaError),
78    /// Manually triggered
79    Adhoc,
80}
81
82/// Recovery state exposed by the barrier manager, without completion notifiers.
83enum RecoveryStatus {
84    Bootstrap,
85    Failover(MetaError),
86    Adhoc,
87}
88
89impl From<&RecoveryReason> for RecoveryStatus {
90    fn from(reason: &RecoveryReason) -> Self {
91        match reason {
92            RecoveryReason::Bootstrap(_) => Self::Bootstrap,
93            RecoveryReason::Failover(err) => Self::Failover(err.clone()),
94            RecoveryReason::Adhoc => Self::Adhoc,
95        }
96    }
97}
98
99/// Status of barrier manager.
100enum BarrierManagerStatus {
101    /// Barrier manager is starting.
102    Starting,
103    /// Barrier manager is under recovery.
104    Recovering(RecoveryStatus),
105    /// Barrier manager is running.
106    Running,
107}
108
109/// Scheduled command with its notifier.
110struct Scheduled {
111    database_id: DatabaseId,
112    command: Command,
113    notifier: Notifier,
114    span: tracing::Span,
115}
116
117impl From<&BarrierManagerStatus> for PbRecoveryStatus {
118    fn from(status: &BarrierManagerStatus) -> Self {
119        match status {
120            BarrierManagerStatus::Starting => Self::StatusStarting,
121            BarrierManagerStatus::Recovering(reason) => match reason {
122                RecoveryStatus::Bootstrap => Self::StatusStarting,
123                RecoveryStatus::Failover(_) | RecoveryStatus::Adhoc => Self::StatusRecovering,
124            },
125            BarrierManagerStatus::Running => Self::StatusRunning,
126        }
127    }
128}
129
130pub(crate) struct BackfillProgress {
131    pub(crate) progress: String,
132    pub(crate) backfill_type: PbBackfillType,
133}
134
135#[derive(Debug, Clone, Copy)]
136pub(crate) struct FragmentBackfillProgress {
137    pub(crate) job_id: JobId,
138    pub(crate) fragment_id: FragmentId,
139    pub(crate) consumed_rows: u64,
140    pub(crate) done: bool,
141    pub(crate) upstream_type: BackfillUpstreamType,
142}
143
144pub(crate) struct UpdateDatabaseBarrierRequest {
145    pub database_id: DatabaseId,
146    pub barrier_interval_ms: Option<u32>,
147    pub checkpoint_frequency: Option<u64>,
148    pub sender: Sender<()>,
149}
150
151pub(crate) enum BarrierManagerRequest {
152    GetBackfillProgress(Sender<MetaResult<HashMap<JobId, BackfillProgress>>>),
153    GetFragmentBackfillProgress(Sender<MetaResult<Vec<FragmentBackfillProgress>>>),
154    GetCdcProgress(Sender<MetaResult<HashMap<JobId, CdcProgress>>>),
155    AdhocRecovery(Sender<()>),
156    UpdateDatabaseBarrier(UpdateDatabaseBarrierRequest),
157}
158
159#[derive(Debug)]
160struct BarrierWorkerRuntimeInfoSnapshot {
161    active_streaming_nodes: ActiveStreamingWorkerNodes,
162    recovery_context: LoadedRecoveryContext,
163    state_table_committed_epochs: HashMap<TableId, u64>,
164    /// `table_id` -> (`Vec<non-checkpoint epoch>`, checkpoint epoch)
165    state_table_log_epochs: HashMap<TableId, Vec<(Vec<u64>, u64)>>,
166    mv_depended_subscriptions: HashMap<TableId, HashSet<SubscriptionId>>,
167    creating_jobs: HashSet<JobId>,
168    hummock_version_stats: HummockVersionStats,
169    database_infos: Vec<Database>,
170    cdc_table_snapshot_splits: HashMap<JobId, CdcTableSnapshotSplits>,
171}
172
173impl BarrierWorkerRuntimeInfoSnapshot {
174    fn validate_database_info(
175        database_id: DatabaseId,
176        database_jobs: &HashMap<JobId, HashMap<FragmentId, InflightFragmentInfo>>,
177        active_streaming_nodes: &ActiveStreamingWorkerNodes,
178        stream_actors: &HashMap<ActorId, StreamActor>,
179        state_table_committed_epochs: &HashMap<TableId, u64>,
180    ) -> MetaResult<()> {
181        {
182            for fragment in database_jobs.values().flat_map(|job| job.values()) {
183                for (actor_id, actor) in &fragment.actors {
184                    if !active_streaming_nodes
185                        .current()
186                        .contains_key(&actor.worker_id)
187                    {
188                        return Err(anyhow!(
189                            "worker_id {} for actor {} does not exist",
190                            actor.worker_id,
191                            actor_id
192                        )
193                        .into());
194                    }
195                    if !stream_actors.contains_key(actor_id) {
196                        return Err(anyhow!("cannot find StreamActor of actor {}", actor_id).into());
197                    }
198                }
199                for state_table_id in &fragment.state_table_ids {
200                    if !state_table_committed_epochs.contains_key(state_table_id) {
201                        return Err(anyhow!(
202                            "state table {} is not registered to hummock",
203                            state_table_id
204                        )
205                        .into());
206                    }
207                }
208            }
209            for (job_id, fragments) in database_jobs {
210                let mut committed_epochs =
211                    InflightFragmentInfo::existing_table_ids(fragments.values()).map(|table_id| {
212                        (
213                            table_id,
214                            *state_table_committed_epochs
215                                .get(&table_id)
216                                .expect("checked exist"),
217                        )
218                    });
219                let (first_table, first_epoch) = committed_epochs.next().ok_or_else(|| {
220                    anyhow!(
221                        "job {} in database {} has no state table after recovery",
222                        job_id,
223                        database_id
224                    )
225                })?;
226                for (table_id, epoch) in committed_epochs {
227                    if epoch != first_epoch {
228                        return Err(anyhow!(
229                            "job {} in database {} has tables with different table ids. {}:{}, {}:{}",
230                            job_id,
231                            database_id,
232                            first_table,
233                            first_epoch,
234                            table_id,
235                            epoch
236                        )
237                        .into());
238                    }
239                }
240            }
241        }
242        Ok(())
243    }
244}
245
246#[derive(Debug)]
247struct DatabaseRuntimeInfoSnapshot {
248    recovery_context: LoadedRecoveryContext,
249    state_table_committed_epochs: HashMap<TableId, u64>,
250    /// `table_id` -> (`Vec<non-checkpoint epoch>`, checkpoint epoch)
251    state_table_log_epochs: HashMap<TableId, Vec<(Vec<u64>, u64)>>,
252    mv_depended_subscriptions: HashMap<TableId, HashSet<SubscriptionId>>,
253    creating_jobs: HashSet<JobId>,
254    cdc_table_snapshot_splits: HashMap<JobId, CdcTableSnapshotSplits>,
255}