Line data Source code
1 : pub(crate) mod split_state;
2 : use std::collections::HashMap;
3 : use std::str::FromStr;
4 : use std::time::Duration;
5 : use std::time::Instant;
6 :
7 : use self::split_state::SplitState;
8 : use diesel::pg::PgConnection;
9 : use diesel::prelude::*;
10 : use diesel::Connection;
11 : use pageserver_api::controller_api::MetadataHealthRecord;
12 : use pageserver_api::controller_api::ShardSchedulingPolicy;
13 : use pageserver_api::controller_api::{NodeSchedulingPolicy, PlacementPolicy};
14 : use pageserver_api::models::TenantConfig;
15 : use pageserver_api::shard::ShardConfigError;
16 : use pageserver_api::shard::ShardIdentity;
17 : use pageserver_api::shard::ShardStripeSize;
18 : use pageserver_api::shard::{ShardCount, ShardNumber, TenantShardId};
19 : use serde::{Deserialize, Serialize};
20 : use utils::generation::Generation;
21 : use utils::id::{NodeId, TenantId};
22 :
23 : use crate::metrics::{
24 : DatabaseQueryErrorLabelGroup, DatabaseQueryLatencyLabelGroup, METRICS_REGISTRY,
25 : };
26 : use crate::node::Node;
27 :
28 : use diesel_migrations::{embed_migrations, EmbeddedMigrations};
29 : const MIGRATIONS: EmbeddedMigrations = embed_migrations!("./migrations");
30 :
31 : /// ## What do we store?
32 : ///
33 : /// The storage controller service does not store most of its state durably.
34 : ///
35 : /// The essential things to store durably are:
36 : /// - generation numbers, as these must always advance monotonically to ensure data safety.
37 : /// - Tenant's PlacementPolicy and TenantConfig, as the source of truth for these is something external.
38 : /// - Node's scheduling policies, as the source of truth for these is something external.
39 : ///
40 : /// Other things we store durably as an implementation detail:
41 : /// - Node's host/port: this could be avoided it we made nodes emit a self-registering heartbeat,
42 : /// but it is operationally simpler to make this service the authority for which nodes
43 : /// it talks to.
44 : ///
45 : /// ## Performance/efficiency
46 : ///
47 : /// The storage controller service does not go via the database for most things: there are
48 : /// a couple of places where we must, and where efficiency matters:
49 : /// - Incrementing generation numbers: the Reconciler has to wait for this to complete
50 : /// before it can attach a tenant, so this acts as a bound on how fast things like
51 : /// failover can happen.
52 : /// - Pageserver re-attach: we will increment many shards' generations when this happens,
53 : /// so it is important to avoid e.g. issuing O(N) queries.
54 : ///
55 : /// Database calls relating to nodes have low performance requirements, as they are very rarely
56 : /// updated, and reads of nodes are always from memory, not the database. We only require that
57 : /// we can UPDATE a node's scheduling mode reasonably quickly to mark a bad node offline.
58 : pub struct Persistence {
59 : connection_pool: diesel::r2d2::Pool<diesel::r2d2::ConnectionManager<PgConnection>>,
60 : }
61 :
62 : /// Legacy format, for use in JSON compat objects in test environment
63 0 : #[derive(Serialize, Deserialize)]
64 : struct JsonPersistence {
65 : tenants: HashMap<TenantShardId, TenantShardPersistence>,
66 : }
67 :
68 0 : #[derive(thiserror::Error, Debug)]
69 : pub(crate) enum DatabaseError {
70 : #[error(transparent)]
71 : Query(#[from] diesel::result::Error),
72 : #[error(transparent)]
73 : Connection(#[from] diesel::result::ConnectionError),
74 : #[error(transparent)]
75 : ConnectionPool(#[from] r2d2::Error),
76 : #[error("Logical error: {0}")]
77 : Logical(String),
78 : #[error("Migration error: {0}")]
79 : Migration(String),
80 : }
81 :
82 : #[derive(measured::FixedCardinalityLabel, Copy, Clone)]
83 : pub(crate) enum DatabaseOperation {
84 : InsertNode,
85 : UpdateNode,
86 : DeleteNode,
87 : ListNodes,
88 : BeginShardSplit,
89 : CompleteShardSplit,
90 : AbortShardSplit,
91 : Detach,
92 : ReAttach,
93 : IncrementGeneration,
94 : PeekGenerations,
95 : ListTenantShards,
96 : InsertTenantShards,
97 : UpdateTenantShard,
98 : DeleteTenant,
99 : UpdateTenantConfig,
100 : UpdateMetadataHealth,
101 : ListMetadataHealth,
102 : ListMetadataHealthUnhealthy,
103 : ListMetadataHealthOutdated,
104 : GetLeader,
105 : UpdateLeader,
106 : SetNodeAzId,
107 : }
108 :
109 : #[must_use]
110 : pub(crate) enum AbortShardSplitStatus {
111 : /// We aborted the split in the database by reverting to the parent shards
112 : Aborted,
113 : /// The split had already been persisted.
114 : Complete,
115 : }
116 :
117 : pub(crate) type DatabaseResult<T> = Result<T, DatabaseError>;
118 :
119 : /// Some methods can operate on either a whole tenant or a single shard
120 : pub(crate) enum TenantFilter {
121 : Tenant(TenantId),
122 : Shard(TenantShardId),
123 : }
124 :
125 : impl Persistence {
126 : // The default postgres connection limit is 100. We use up to 99, to leave one free for a human admin under
127 : // normal circumstances. This assumes we have exclusive use of the database cluster to which we connect.
128 : pub const MAX_CONNECTIONS: u32 = 99;
129 :
130 : // We don't want to keep a lot of connections alive: close them down promptly if they aren't being used.
131 : const IDLE_CONNECTION_TIMEOUT: Duration = Duration::from_secs(10);
132 : const MAX_CONNECTION_LIFETIME: Duration = Duration::from_secs(60);
133 :
134 0 : pub fn new(database_url: String) -> Self {
135 0 : let manager = diesel::r2d2::ConnectionManager::<PgConnection>::new(database_url);
136 0 :
137 0 : // We will use a connection pool: this is primarily to _limit_ our connection count, rather than to optimize time
138 0 : // to execute queries (database queries are not generally on latency-sensitive paths).
139 0 : let connection_pool = diesel::r2d2::Pool::builder()
140 0 : .max_size(Self::MAX_CONNECTIONS)
141 0 : .max_lifetime(Some(Self::MAX_CONNECTION_LIFETIME))
142 0 : .idle_timeout(Some(Self::IDLE_CONNECTION_TIMEOUT))
143 0 : // Always keep at least one connection ready to go
144 0 : .min_idle(Some(1))
145 0 : .test_on_check_out(true)
146 0 : .build(manager)
147 0 : .expect("Could not build connection pool");
148 0 :
149 0 : Self { connection_pool }
150 0 : }
151 :
152 : /// A helper for use during startup, where we would like to tolerate concurrent restarts of the
153 : /// database and the storage controller, therefore the database might not be available right away
154 0 : pub async fn await_connection(
155 0 : database_url: &str,
156 0 : timeout: Duration,
157 0 : ) -> Result<(), diesel::ConnectionError> {
158 0 : let started_at = Instant::now();
159 0 : loop {
160 0 : match PgConnection::establish(database_url) {
161 : Ok(_) => {
162 0 : tracing::info!("Connected to database.");
163 0 : return Ok(());
164 : }
165 0 : Err(e) => {
166 0 : if started_at.elapsed() > timeout {
167 0 : return Err(e);
168 : } else {
169 0 : tracing::info!("Database not yet available, waiting... ({e})");
170 0 : tokio::time::sleep(Duration::from_millis(100)).await;
171 : }
172 : }
173 : }
174 : }
175 0 : }
176 :
177 : /// Execute the diesel migrations that are built into this binary
178 0 : pub(crate) async fn migration_run(&self) -> DatabaseResult<()> {
179 0 : use diesel_migrations::{HarnessWithOutput, MigrationHarness};
180 0 :
181 0 : self.with_conn(move |conn| -> DatabaseResult<()> {
182 0 : HarnessWithOutput::write_to_stdout(conn)
183 0 : .run_pending_migrations(MIGRATIONS)
184 0 : .map(|_| ())
185 0 : .map_err(|e| DatabaseError::Migration(e.to_string()))
186 0 : })
187 0 : .await
188 0 : }
189 :
190 : /// Wraps `with_conn` in order to collect latency and error metrics
191 0 : async fn with_measured_conn<F, R>(&self, op: DatabaseOperation, func: F) -> DatabaseResult<R>
192 0 : where
193 0 : F: Fn(&mut PgConnection) -> DatabaseResult<R> + Send + 'static,
194 0 : R: Send + 'static,
195 0 : {
196 0 : let latency = &METRICS_REGISTRY
197 0 : .metrics_group
198 0 : .storage_controller_database_query_latency;
199 0 : let _timer = latency.start_timer(DatabaseQueryLatencyLabelGroup { operation: op });
200 :
201 0 : let res = self.with_conn(func).await;
202 :
203 0 : if let Err(err) = &res {
204 0 : let error_counter = &METRICS_REGISTRY
205 0 : .metrics_group
206 0 : .storage_controller_database_query_error;
207 0 : error_counter.inc(DatabaseQueryErrorLabelGroup {
208 0 : error_type: err.error_label(),
209 0 : operation: op,
210 0 : })
211 0 : }
212 :
213 0 : res
214 0 : }
215 :
216 : /// Call the provided function in a tokio blocking thread, with a Diesel database connection.
217 0 : async fn with_conn<F, R>(&self, func: F) -> DatabaseResult<R>
218 0 : where
219 0 : F: Fn(&mut PgConnection) -> DatabaseResult<R> + Send + 'static,
220 0 : R: Send + 'static,
221 0 : {
222 : // A generous allowance for how many times we may retry serializable transactions
223 : // before giving up. This is not expected to be hit: it is a defensive measure in case we
224 : // somehow engineer a situation where duelling transactions might otherwise live-lock.
225 : const MAX_RETRIES: usize = 128;
226 :
227 0 : let mut conn = self.connection_pool.get()?;
228 0 : tokio::task::spawn_blocking(move || -> DatabaseResult<R> {
229 0 : let mut retry_count = 0;
230 : loop {
231 0 : match conn.build_transaction().serializable().run(|c| func(c)) {
232 0 : Ok(r) => break Ok(r),
233 : Err(
234 0 : err @ DatabaseError::Query(diesel::result::Error::DatabaseError(
235 0 : diesel::result::DatabaseErrorKind::SerializationFailure,
236 0 : _,
237 0 : )),
238 0 : ) => {
239 0 : retry_count += 1;
240 0 : if retry_count > MAX_RETRIES {
241 0 : tracing::error!(
242 0 : "Exceeded max retries on SerializationFailure errors: {err:?}"
243 : );
244 0 : break Err(err);
245 : } else {
246 : // Retry on serialization errors: these are expected, because even though our
247 : // transactions don't fight for the same rows, they will occasionally collide
248 : // on index pages (e.g. increment_generation for unrelated shards can collide)
249 0 : tracing::debug!(
250 0 : "Retrying transaction on serialization failure {err:?}"
251 : );
252 0 : continue;
253 : }
254 : }
255 0 : Err(e) => break Err(e),
256 : }
257 : }
258 0 : })
259 0 : .await
260 0 : .expect("Task panic")
261 0 : }
262 :
263 : /// When a node is first registered, persist it before using it for anything
264 0 : pub(crate) async fn insert_node(&self, node: &Node) -> DatabaseResult<()> {
265 0 : let np = node.to_persistent();
266 0 : self.with_measured_conn(
267 0 : DatabaseOperation::InsertNode,
268 0 : move |conn| -> DatabaseResult<()> {
269 0 : diesel::insert_into(crate::schema::nodes::table)
270 0 : .values(&np)
271 0 : .execute(conn)?;
272 0 : Ok(())
273 0 : },
274 0 : )
275 0 : .await
276 0 : }
277 :
278 : /// At startup, populate the list of nodes which our shards may be placed on
279 0 : pub(crate) async fn list_nodes(&self) -> DatabaseResult<Vec<NodePersistence>> {
280 0 : let nodes: Vec<NodePersistence> = self
281 0 : .with_measured_conn(
282 0 : DatabaseOperation::ListNodes,
283 0 : move |conn| -> DatabaseResult<_> {
284 0 : Ok(crate::schema::nodes::table.load::<NodePersistence>(conn)?)
285 0 : },
286 0 : )
287 0 : .await?;
288 :
289 0 : tracing::info!("list_nodes: loaded {} nodes", nodes.len());
290 :
291 0 : Ok(nodes)
292 0 : }
293 :
294 0 : pub(crate) async fn update_node(
295 0 : &self,
296 0 : input_node_id: NodeId,
297 0 : input_scheduling: NodeSchedulingPolicy,
298 0 : ) -> DatabaseResult<()> {
299 : use crate::schema::nodes::dsl::*;
300 0 : let updated = self
301 0 : .with_measured_conn(DatabaseOperation::UpdateNode, move |conn| {
302 0 : let updated = diesel::update(nodes)
303 0 : .filter(node_id.eq(input_node_id.0 as i64))
304 0 : .set((scheduling_policy.eq(String::from(input_scheduling)),))
305 0 : .execute(conn)?;
306 0 : Ok(updated)
307 0 : })
308 0 : .await?;
309 :
310 0 : if updated != 1 {
311 0 : Err(DatabaseError::Logical(format!(
312 0 : "Node {node_id:?} not found for update",
313 0 : )))
314 : } else {
315 0 : Ok(())
316 : }
317 0 : }
318 :
319 0 : pub(crate) async fn set_node_availability_zone_id(
320 0 : &self,
321 0 : input_node_id: NodeId,
322 0 : input_az_id: String,
323 0 : ) -> DatabaseResult<()> {
324 : use crate::schema::nodes::dsl::*;
325 0 : let updated = self
326 0 : .with_measured_conn(DatabaseOperation::SetNodeAzId, move |conn| {
327 0 : let updated = diesel::update(nodes)
328 0 : .filter(node_id.eq(input_node_id.0 as i64))
329 0 : .set((availability_zone_id.eq(input_az_id.clone()),))
330 0 : .execute(conn)?;
331 0 : Ok(updated)
332 0 : })
333 0 : .await?;
334 :
335 0 : if updated != 1 {
336 0 : Err(DatabaseError::Logical(format!(
337 0 : "Node {node_id:?} not found for setting az id",
338 0 : )))
339 : } else {
340 0 : Ok(())
341 : }
342 0 : }
343 :
344 : /// At startup, load the high level state for shards, such as their config + policy. This will
345 : /// be enriched at runtime with state discovered on pageservers.
346 0 : pub(crate) async fn list_tenant_shards(&self) -> DatabaseResult<Vec<TenantShardPersistence>> {
347 0 : self.with_measured_conn(
348 0 : DatabaseOperation::ListTenantShards,
349 0 : move |conn| -> DatabaseResult<_> {
350 0 : Ok(crate::schema::tenant_shards::table.load::<TenantShardPersistence>(conn)?)
351 0 : },
352 0 : )
353 0 : .await
354 0 : }
355 :
356 : /// Tenants must be persisted before we schedule them for the first time. This enables us
357 : /// to correctly retain generation monotonicity, and the externally provided placement policy & config.
358 0 : pub(crate) async fn insert_tenant_shards(
359 0 : &self,
360 0 : shards: Vec<TenantShardPersistence>,
361 0 : ) -> DatabaseResult<()> {
362 0 : use crate::schema::metadata_health;
363 0 : use crate::schema::tenant_shards;
364 0 :
365 0 : let now = chrono::Utc::now();
366 0 :
367 0 : let metadata_health_records = shards
368 0 : .iter()
369 0 : .map(|t| MetadataHealthPersistence {
370 0 : tenant_id: t.tenant_id.clone(),
371 0 : shard_number: t.shard_number,
372 0 : shard_count: t.shard_count,
373 0 : healthy: true,
374 0 : last_scrubbed_at: now,
375 0 : })
376 0 : .collect::<Vec<_>>();
377 0 :
378 0 : self.with_measured_conn(
379 0 : DatabaseOperation::InsertTenantShards,
380 0 : move |conn| -> DatabaseResult<()> {
381 0 : diesel::insert_into(tenant_shards::table)
382 0 : .values(&shards)
383 0 : .execute(conn)?;
384 :
385 0 : diesel::insert_into(metadata_health::table)
386 0 : .values(&metadata_health_records)
387 0 : .execute(conn)?;
388 0 : Ok(())
389 0 : },
390 0 : )
391 0 : .await
392 0 : }
393 :
394 : /// Ordering: call this _after_ deleting the tenant on pageservers, but _before_ dropping state for
395 : /// the tenant from memory on this server.
396 0 : pub(crate) async fn delete_tenant(&self, del_tenant_id: TenantId) -> DatabaseResult<()> {
397 0 : use crate::schema::tenant_shards::dsl::*;
398 0 : self.with_measured_conn(
399 0 : DatabaseOperation::DeleteTenant,
400 0 : move |conn| -> DatabaseResult<()> {
401 0 : // `metadata_health` status (if exists) is also deleted based on the cascade behavior.
402 0 : diesel::delete(tenant_shards)
403 0 : .filter(tenant_id.eq(del_tenant_id.to_string()))
404 0 : .execute(conn)?;
405 0 : Ok(())
406 0 : },
407 0 : )
408 0 : .await
409 0 : }
410 :
411 0 : pub(crate) async fn delete_node(&self, del_node_id: NodeId) -> DatabaseResult<()> {
412 0 : use crate::schema::nodes::dsl::*;
413 0 : self.with_measured_conn(
414 0 : DatabaseOperation::DeleteNode,
415 0 : move |conn| -> DatabaseResult<()> {
416 0 : diesel::delete(nodes)
417 0 : .filter(node_id.eq(del_node_id.0 as i64))
418 0 : .execute(conn)?;
419 :
420 0 : Ok(())
421 0 : },
422 0 : )
423 0 : .await
424 0 : }
425 :
426 : /// When a tenant invokes the /re-attach API, this function is responsible for doing an efficient
427 : /// batched increment of the generations of all tenants whose generation_pageserver is equal to
428 : /// the node that called /re-attach.
429 0 : #[tracing::instrument(skip_all, fields(node_id))]
430 : pub(crate) async fn re_attach(
431 : &self,
432 : input_node_id: NodeId,
433 : ) -> DatabaseResult<HashMap<TenantShardId, Generation>> {
434 : use crate::schema::nodes::dsl::scheduling_policy;
435 : use crate::schema::nodes::dsl::*;
436 : use crate::schema::tenant_shards::dsl::*;
437 : let updated = self
438 0 : .with_measured_conn(DatabaseOperation::ReAttach, move |conn| {
439 0 : let rows_updated = diesel::update(tenant_shards)
440 0 : .filter(generation_pageserver.eq(input_node_id.0 as i64))
441 0 : .set(generation.eq(generation + 1))
442 0 : .execute(conn)?;
443 :
444 0 : tracing::info!("Incremented {} tenants' generations", rows_updated);
445 :
446 : // TODO: UPDATE+SELECT in one query
447 :
448 0 : let updated = tenant_shards
449 0 : .filter(generation_pageserver.eq(input_node_id.0 as i64))
450 0 : .select(TenantShardPersistence::as_select())
451 0 : .load(conn)?;
452 :
453 : // If the node went through a drain and restart phase before re-attaching,
454 : // then reset it's node scheduling policy to active.
455 0 : diesel::update(nodes)
456 0 : .filter(node_id.eq(input_node_id.0 as i64))
457 0 : .filter(
458 0 : scheduling_policy
459 0 : .eq(String::from(NodeSchedulingPolicy::PauseForRestart))
460 0 : .or(scheduling_policy.eq(String::from(NodeSchedulingPolicy::Draining)))
461 0 : .or(scheduling_policy.eq(String::from(NodeSchedulingPolicy::Filling))),
462 0 : )
463 0 : .set(scheduling_policy.eq(String::from(NodeSchedulingPolicy::Active)))
464 0 : .execute(conn)?;
465 :
466 0 : Ok(updated)
467 0 : })
468 : .await?;
469 :
470 : let mut result = HashMap::new();
471 : for tsp in updated {
472 : let tenant_shard_id = TenantShardId {
473 : tenant_id: TenantId::from_str(tsp.tenant_id.as_str())
474 0 : .map_err(|e| DatabaseError::Logical(format!("Malformed tenant id: {e}")))?,
475 : shard_number: ShardNumber(tsp.shard_number as u8),
476 : shard_count: ShardCount::new(tsp.shard_count as u8),
477 : };
478 :
479 : let Some(g) = tsp.generation else {
480 : // If the generation_pageserver column was non-NULL, then the generation column should also be non-NULL:
481 : // we only set generation_pageserver when setting generation.
482 : return Err(DatabaseError::Logical(
483 : "Generation should always be set after incrementing".to_string(),
484 : ));
485 : };
486 : result.insert(tenant_shard_id, Generation::new(g as u32));
487 : }
488 :
489 : Ok(result)
490 : }
491 :
492 : /// Reconciler calls this immediately before attaching to a new pageserver, to acquire a unique, monotonically
493 : /// advancing generation number. We also store the NodeId for which the generation was issued, so that in
494 : /// [`Self::re_attach`] we can do a bulk UPDATE on the generations for that node.
495 0 : pub(crate) async fn increment_generation(
496 0 : &self,
497 0 : tenant_shard_id: TenantShardId,
498 0 : node_id: NodeId,
499 0 : ) -> anyhow::Result<Generation> {
500 : use crate::schema::tenant_shards::dsl::*;
501 0 : let updated = self
502 0 : .with_measured_conn(DatabaseOperation::IncrementGeneration, move |conn| {
503 0 : let updated = diesel::update(tenant_shards)
504 0 : .filter(tenant_id.eq(tenant_shard_id.tenant_id.to_string()))
505 0 : .filter(shard_number.eq(tenant_shard_id.shard_number.0 as i32))
506 0 : .filter(shard_count.eq(tenant_shard_id.shard_count.literal() as i32))
507 0 : .set((
508 0 : generation.eq(generation + 1),
509 0 : generation_pageserver.eq(node_id.0 as i64),
510 0 : ))
511 0 : // TODO: only returning() the generation column
512 0 : .returning(TenantShardPersistence::as_returning())
513 0 : .get_result(conn)?;
514 :
515 0 : Ok(updated)
516 0 : })
517 0 : .await?;
518 :
519 : // Generation is always non-null in the rseult: if the generation column had been NULL, then we
520 : // should have experienced an SQL Confilict error while executing a query that tries to increment it.
521 0 : debug_assert!(updated.generation.is_some());
522 0 : let Some(g) = updated.generation else {
523 0 : return Err(DatabaseError::Logical(
524 0 : "Generation should always be set after incrementing".to_string(),
525 0 : )
526 0 : .into());
527 : };
528 :
529 0 : Ok(Generation::new(g as u32))
530 0 : }
531 :
532 : /// When we want to call out to the running shards for a tenant, e.g. during timeline CRUD operations,
533 : /// we need to know where the shard is attached, _and_ the generation, so that we can re-check the generation
534 : /// afterwards to confirm that our timeline CRUD operation is truly persistent (it must have happened in the
535 : /// latest generation)
536 : ///
537 : /// If the tenant doesn't exist, an empty vector is returned.
538 : ///
539 : /// Output is sorted by shard number
540 0 : pub(crate) async fn peek_generations(
541 0 : &self,
542 0 : filter_tenant_id: TenantId,
543 0 : ) -> Result<Vec<(TenantShardId, Option<Generation>, Option<NodeId>)>, DatabaseError> {
544 : use crate::schema::tenant_shards::dsl::*;
545 0 : let rows = self
546 0 : .with_measured_conn(DatabaseOperation::PeekGenerations, move |conn| {
547 0 : let result = tenant_shards
548 0 : .filter(tenant_id.eq(filter_tenant_id.to_string()))
549 0 : .select(TenantShardPersistence::as_select())
550 0 : .order(shard_number)
551 0 : .load(conn)?;
552 0 : Ok(result)
553 0 : })
554 0 : .await?;
555 :
556 0 : Ok(rows
557 0 : .into_iter()
558 0 : .map(|p| {
559 0 : (
560 0 : p.get_tenant_shard_id()
561 0 : .expect("Corrupt tenant shard id in database"),
562 0 : p.generation.map(|g| Generation::new(g as u32)),
563 0 : p.generation_pageserver.map(|n| NodeId(n as u64)),
564 0 : )
565 0 : })
566 0 : .collect())
567 0 : }
568 :
569 : #[allow(non_local_definitions)]
570 : /// For use when updating a persistent property of a tenant, such as its config or placement_policy.
571 : ///
572 : /// Do not use this for settting generation, unless in the special onboarding code path (/location_config)
573 : /// API: use [`Self::increment_generation`] instead. Setting the generation via this route is a one-time thing
574 : /// that we only do the first time a tenant is set to an attached policy via /location_config.
575 0 : pub(crate) async fn update_tenant_shard(
576 0 : &self,
577 0 : tenant: TenantFilter,
578 0 : input_placement_policy: Option<PlacementPolicy>,
579 0 : input_config: Option<TenantConfig>,
580 0 : input_generation: Option<Generation>,
581 0 : input_scheduling_policy: Option<ShardSchedulingPolicy>,
582 0 : ) -> DatabaseResult<()> {
583 0 : use crate::schema::tenant_shards::dsl::*;
584 0 :
585 0 : self.with_measured_conn(DatabaseOperation::UpdateTenantShard, move |conn| {
586 0 : let query = match tenant {
587 0 : TenantFilter::Shard(tenant_shard_id) => diesel::update(tenant_shards)
588 0 : .filter(tenant_id.eq(tenant_shard_id.tenant_id.to_string()))
589 0 : .filter(shard_number.eq(tenant_shard_id.shard_number.0 as i32))
590 0 : .filter(shard_count.eq(tenant_shard_id.shard_count.literal() as i32))
591 0 : .into_boxed(),
592 0 : TenantFilter::Tenant(input_tenant_id) => diesel::update(tenant_shards)
593 0 : .filter(tenant_id.eq(input_tenant_id.to_string()))
594 0 : .into_boxed(),
595 : };
596 :
597 0 : #[derive(AsChangeset)]
598 : #[diesel(table_name = crate::schema::tenant_shards)]
599 : struct ShardUpdate {
600 : generation: Option<i32>,
601 : placement_policy: Option<String>,
602 : config: Option<String>,
603 : scheduling_policy: Option<String>,
604 : }
605 :
606 0 : let update = ShardUpdate {
607 0 : generation: input_generation.map(|g| g.into().unwrap() as i32),
608 0 : placement_policy: input_placement_policy
609 0 : .as_ref()
610 0 : .map(|p| serde_json::to_string(&p).unwrap()),
611 0 : config: input_config
612 0 : .as_ref()
613 0 : .map(|c| serde_json::to_string(&c).unwrap()),
614 0 : scheduling_policy: input_scheduling_policy
615 0 : .map(|p| serde_json::to_string(&p).unwrap()),
616 0 : };
617 0 :
618 0 : query.set(update).execute(conn)?;
619 :
620 0 : Ok(())
621 0 : })
622 0 : .await?;
623 :
624 0 : Ok(())
625 0 : }
626 :
627 0 : pub(crate) async fn detach(&self, tenant_shard_id: TenantShardId) -> anyhow::Result<()> {
628 0 : use crate::schema::tenant_shards::dsl::*;
629 0 : self.with_measured_conn(DatabaseOperation::Detach, move |conn| {
630 0 : let updated = diesel::update(tenant_shards)
631 0 : .filter(tenant_id.eq(tenant_shard_id.tenant_id.to_string()))
632 0 : .filter(shard_number.eq(tenant_shard_id.shard_number.0 as i32))
633 0 : .filter(shard_count.eq(tenant_shard_id.shard_count.literal() as i32))
634 0 : .set((
635 0 : generation_pageserver.eq(Option::<i64>::None),
636 0 : placement_policy.eq(serde_json::to_string(&PlacementPolicy::Detached).unwrap()),
637 0 : ))
638 0 : .execute(conn)?;
639 :
640 0 : Ok(updated)
641 0 : })
642 0 : .await?;
643 :
644 0 : Ok(())
645 0 : }
646 :
647 : // When we start shard splitting, we must durably mark the tenant so that
648 : // on restart, we know that we must go through recovery.
649 : //
650 : // We create the child shards here, so that they will be available for increment_generation calls
651 : // if some pageserver holding a child shard needs to restart before the overall tenant split is complete.
652 0 : pub(crate) async fn begin_shard_split(
653 0 : &self,
654 0 : old_shard_count: ShardCount,
655 0 : split_tenant_id: TenantId,
656 0 : parent_to_children: Vec<(TenantShardId, Vec<TenantShardPersistence>)>,
657 0 : ) -> DatabaseResult<()> {
658 0 : use crate::schema::tenant_shards::dsl::*;
659 0 : self.with_measured_conn(DatabaseOperation::BeginShardSplit, move |conn| -> DatabaseResult<()> {
660 : // Mark parent shards as splitting
661 :
662 0 : let updated = diesel::update(tenant_shards)
663 0 : .filter(tenant_id.eq(split_tenant_id.to_string()))
664 0 : .filter(shard_count.eq(old_shard_count.literal() as i32))
665 0 : .set((splitting.eq(1),))
666 0 : .execute(conn)?;
667 0 : if u8::try_from(updated)
668 0 : .map_err(|_| DatabaseError::Logical(
669 0 : format!("Overflow existing shard count {} while splitting", updated))
670 0 : )? != old_shard_count.count() {
671 : // Perhaps a deletion or another split raced with this attempt to split, mutating
672 : // the parent shards that we intend to split. In this case the split request should fail.
673 0 : return Err(DatabaseError::Logical(
674 0 : format!("Unexpected existing shard count {updated} when preparing tenant for split (expected {})", old_shard_count.count())
675 0 : ));
676 0 : }
677 0 :
678 0 : // FIXME: spurious clone to sidestep closure move rules
679 0 : let parent_to_children = parent_to_children.clone();
680 :
681 : // Insert child shards
682 0 : for (parent_shard_id, children) in parent_to_children {
683 0 : let mut parent = crate::schema::tenant_shards::table
684 0 : .filter(tenant_id.eq(parent_shard_id.tenant_id.to_string()))
685 0 : .filter(shard_number.eq(parent_shard_id.shard_number.0 as i32))
686 0 : .filter(shard_count.eq(parent_shard_id.shard_count.literal() as i32))
687 0 : .load::<TenantShardPersistence>(conn)?;
688 0 : let parent = if parent.len() != 1 {
689 0 : return Err(DatabaseError::Logical(format!(
690 0 : "Parent shard {parent_shard_id} not found"
691 0 : )));
692 : } else {
693 0 : parent.pop().unwrap()
694 : };
695 0 : for mut shard in children {
696 : // Carry the parent's generation into the child
697 0 : shard.generation = parent.generation;
698 0 :
699 0 : debug_assert!(shard.splitting == SplitState::Splitting);
700 0 : diesel::insert_into(tenant_shards)
701 0 : .values(shard)
702 0 : .execute(conn)?;
703 : }
704 : }
705 :
706 0 : Ok(())
707 0 : })
708 0 : .await
709 0 : }
710 :
711 : // When we finish shard splitting, we must atomically clean up the old shards
712 : // and insert the new shards, and clear the splitting marker.
713 0 : pub(crate) async fn complete_shard_split(
714 0 : &self,
715 0 : split_tenant_id: TenantId,
716 0 : old_shard_count: ShardCount,
717 0 : ) -> DatabaseResult<()> {
718 0 : use crate::schema::tenant_shards::dsl::*;
719 0 : self.with_measured_conn(
720 0 : DatabaseOperation::CompleteShardSplit,
721 0 : move |conn| -> DatabaseResult<()> {
722 0 : // Drop parent shards
723 0 : diesel::delete(tenant_shards)
724 0 : .filter(tenant_id.eq(split_tenant_id.to_string()))
725 0 : .filter(shard_count.eq(old_shard_count.literal() as i32))
726 0 : .execute(conn)?;
727 :
728 : // Clear sharding flag
729 0 : let updated = diesel::update(tenant_shards)
730 0 : .filter(tenant_id.eq(split_tenant_id.to_string()))
731 0 : .set((splitting.eq(0),))
732 0 : .execute(conn)?;
733 0 : debug_assert!(updated > 0);
734 :
735 0 : Ok(())
736 0 : },
737 0 : )
738 0 : .await
739 0 : }
740 :
741 : /// Used when the remote part of a shard split failed: we will revert the database state to have only
742 : /// the parent shards, with SplitState::Idle.
743 0 : pub(crate) async fn abort_shard_split(
744 0 : &self,
745 0 : split_tenant_id: TenantId,
746 0 : new_shard_count: ShardCount,
747 0 : ) -> DatabaseResult<AbortShardSplitStatus> {
748 0 : use crate::schema::tenant_shards::dsl::*;
749 0 : self.with_measured_conn(
750 0 : DatabaseOperation::AbortShardSplit,
751 0 : move |conn| -> DatabaseResult<AbortShardSplitStatus> {
752 : // Clear the splitting state on parent shards
753 0 : let updated = diesel::update(tenant_shards)
754 0 : .filter(tenant_id.eq(split_tenant_id.to_string()))
755 0 : .filter(shard_count.ne(new_shard_count.literal() as i32))
756 0 : .set((splitting.eq(0),))
757 0 : .execute(conn)?;
758 :
759 : // Parent shards are already gone: we cannot abort.
760 0 : if updated == 0 {
761 0 : return Ok(AbortShardSplitStatus::Complete);
762 0 : }
763 0 :
764 0 : // Sanity check: if parent shards were present, their cardinality should
765 0 : // be less than the number of child shards.
766 0 : if updated >= new_shard_count.count() as usize {
767 0 : return Err(DatabaseError::Logical(format!(
768 0 : "Unexpected parent shard count {updated} while aborting split to \
769 0 : count {new_shard_count:?} on tenant {split_tenant_id}"
770 0 : )));
771 0 : }
772 0 :
773 0 : // Erase child shards
774 0 : diesel::delete(tenant_shards)
775 0 : .filter(tenant_id.eq(split_tenant_id.to_string()))
776 0 : .filter(shard_count.eq(new_shard_count.literal() as i32))
777 0 : .execute(conn)?;
778 :
779 0 : Ok(AbortShardSplitStatus::Aborted)
780 0 : },
781 0 : )
782 0 : .await
783 0 : }
784 :
785 : /// Stores all the latest metadata health updates durably. Updates existing entry on conflict.
786 : ///
787 : /// **Correctness:** `metadata_health_updates` should all belong the tenant shards managed by the storage controller.
788 : #[allow(dead_code)]
789 0 : pub(crate) async fn update_metadata_health_records(
790 0 : &self,
791 0 : healthy_records: Vec<MetadataHealthPersistence>,
792 0 : unhealthy_records: Vec<MetadataHealthPersistence>,
793 0 : now: chrono::DateTime<chrono::Utc>,
794 0 : ) -> DatabaseResult<()> {
795 0 : use crate::schema::metadata_health::dsl::*;
796 0 :
797 0 : self.with_measured_conn(
798 0 : DatabaseOperation::UpdateMetadataHealth,
799 0 : move |conn| -> DatabaseResult<_> {
800 0 : diesel::insert_into(metadata_health)
801 0 : .values(&healthy_records)
802 0 : .on_conflict((tenant_id, shard_number, shard_count))
803 0 : .do_update()
804 0 : .set((healthy.eq(true), last_scrubbed_at.eq(now)))
805 0 : .execute(conn)?;
806 :
807 0 : diesel::insert_into(metadata_health)
808 0 : .values(&unhealthy_records)
809 0 : .on_conflict((tenant_id, shard_number, shard_count))
810 0 : .do_update()
811 0 : .set((healthy.eq(false), last_scrubbed_at.eq(now)))
812 0 : .execute(conn)?;
813 0 : Ok(())
814 0 : },
815 0 : )
816 0 : .await
817 0 : }
818 :
819 : /// Lists all the metadata health records.
820 : #[allow(dead_code)]
821 0 : pub(crate) async fn list_metadata_health_records(
822 0 : &self,
823 0 : ) -> DatabaseResult<Vec<MetadataHealthPersistence>> {
824 0 : self.with_measured_conn(
825 0 : DatabaseOperation::ListMetadataHealth,
826 0 : move |conn| -> DatabaseResult<_> {
827 0 : Ok(
828 0 : crate::schema::metadata_health::table
829 0 : .load::<MetadataHealthPersistence>(conn)?,
830 : )
831 0 : },
832 0 : )
833 0 : .await
834 0 : }
835 :
836 : /// Lists all the metadata health records that is unhealthy.
837 : #[allow(dead_code)]
838 0 : pub(crate) async fn list_unhealthy_metadata_health_records(
839 0 : &self,
840 0 : ) -> DatabaseResult<Vec<MetadataHealthPersistence>> {
841 0 : use crate::schema::metadata_health::dsl::*;
842 0 : self.with_measured_conn(
843 0 : DatabaseOperation::ListMetadataHealthUnhealthy,
844 0 : move |conn| -> DatabaseResult<_> {
845 0 : Ok(crate::schema::metadata_health::table
846 0 : .filter(healthy.eq(false))
847 0 : .load::<MetadataHealthPersistence>(conn)?)
848 0 : },
849 0 : )
850 0 : .await
851 0 : }
852 :
853 : /// Lists all the metadata health records that have not been updated since an `earlier` time.
854 : #[allow(dead_code)]
855 0 : pub(crate) async fn list_outdated_metadata_health_records(
856 0 : &self,
857 0 : earlier: chrono::DateTime<chrono::Utc>,
858 0 : ) -> DatabaseResult<Vec<MetadataHealthPersistence>> {
859 0 : use crate::schema::metadata_health::dsl::*;
860 0 :
861 0 : self.with_measured_conn(
862 0 : DatabaseOperation::ListMetadataHealthOutdated,
863 0 : move |conn| -> DatabaseResult<_> {
864 0 : let query = metadata_health.filter(last_scrubbed_at.lt(earlier));
865 0 : let res = query.load::<MetadataHealthPersistence>(conn)?;
866 :
867 0 : Ok(res)
868 0 : },
869 0 : )
870 0 : .await
871 0 : }
872 :
873 : /// Get the current entry from the `leader` table if one exists.
874 : /// It is an error for the table to contain more than one entry.
875 0 : pub(crate) async fn get_leader(&self) -> DatabaseResult<Option<ControllerPersistence>> {
876 0 : let mut leader: Vec<ControllerPersistence> = self
877 0 : .with_measured_conn(
878 0 : DatabaseOperation::GetLeader,
879 0 : move |conn| -> DatabaseResult<_> {
880 0 : Ok(crate::schema::controllers::table.load::<ControllerPersistence>(conn)?)
881 0 : },
882 0 : )
883 0 : .await?;
884 :
885 0 : if leader.len() > 1 {
886 0 : return Err(DatabaseError::Logical(format!(
887 0 : "More than one entry present in the leader table: {leader:?}"
888 0 : )));
889 0 : }
890 0 :
891 0 : Ok(leader.pop())
892 0 : }
893 :
894 : /// Update the new leader with compare-exchange semantics. If `prev` does not
895 : /// match the current leader entry, then the update is treated as a failure.
896 : /// When `prev` is not specified, the update is forced.
897 0 : pub(crate) async fn update_leader(
898 0 : &self,
899 0 : prev: Option<ControllerPersistence>,
900 0 : new: ControllerPersistence,
901 0 : ) -> DatabaseResult<()> {
902 : use crate::schema::controllers::dsl::*;
903 :
904 0 : let updated = self
905 0 : .with_measured_conn(
906 0 : DatabaseOperation::UpdateLeader,
907 0 : move |conn| -> DatabaseResult<usize> {
908 0 : let updated = match &prev {
909 0 : Some(prev) => diesel::update(controllers)
910 0 : .filter(address.eq(prev.address.clone()))
911 0 : .filter(started_at.eq(prev.started_at))
912 0 : .set((
913 0 : address.eq(new.address.clone()),
914 0 : started_at.eq(new.started_at),
915 0 : ))
916 0 : .execute(conn)?,
917 0 : None => diesel::insert_into(controllers)
918 0 : .values(new.clone())
919 0 : .execute(conn)?,
920 : };
921 :
922 0 : Ok(updated)
923 0 : },
924 0 : )
925 0 : .await?;
926 :
927 0 : if updated == 0 {
928 0 : return Err(DatabaseError::Logical(
929 0 : "Leader table update failed".to_string(),
930 0 : ));
931 0 : }
932 0 :
933 0 : Ok(())
934 0 : }
935 : }
936 :
937 : /// Parts of [`crate::tenant_shard::TenantShard`] that are stored durably
938 0 : #[derive(Queryable, Selectable, Insertable, Serialize, Deserialize, Clone, Eq, PartialEq)]
939 : #[diesel(table_name = crate::schema::tenant_shards)]
940 : pub(crate) struct TenantShardPersistence {
941 : #[serde(default)]
942 : pub(crate) tenant_id: String,
943 : #[serde(default)]
944 : pub(crate) shard_number: i32,
945 : #[serde(default)]
946 : pub(crate) shard_count: i32,
947 : #[serde(default)]
948 : pub(crate) shard_stripe_size: i32,
949 :
950 : // Latest generation number: next time we attach, increment this
951 : // and use the incremented number when attaching.
952 : //
953 : // Generation is only None when first onboarding a tenant, where it may
954 : // be in PlacementPolicy::Secondary and therefore have no valid generation state.
955 : pub(crate) generation: Option<i32>,
956 :
957 : // Currently attached pageserver
958 : #[serde(rename = "pageserver")]
959 : pub(crate) generation_pageserver: Option<i64>,
960 :
961 : #[serde(default)]
962 : pub(crate) placement_policy: String,
963 : #[serde(default)]
964 : pub(crate) splitting: SplitState,
965 : #[serde(default)]
966 : pub(crate) config: String,
967 : #[serde(default)]
968 : pub(crate) scheduling_policy: String,
969 : }
970 :
971 : impl TenantShardPersistence {
972 0 : pub(crate) fn get_shard_identity(&self) -> Result<ShardIdentity, ShardConfigError> {
973 0 : if self.shard_count == 0 {
974 0 : Ok(ShardIdentity::unsharded())
975 : } else {
976 0 : Ok(ShardIdentity::new(
977 0 : ShardNumber(self.shard_number as u8),
978 0 : ShardCount::new(self.shard_count as u8),
979 0 : ShardStripeSize(self.shard_stripe_size as u32),
980 0 : )?)
981 : }
982 0 : }
983 :
984 0 : pub(crate) fn get_tenant_shard_id(&self) -> Result<TenantShardId, hex::FromHexError> {
985 0 : Ok(TenantShardId {
986 0 : tenant_id: TenantId::from_str(self.tenant_id.as_str())?,
987 0 : shard_number: ShardNumber(self.shard_number as u8),
988 0 : shard_count: ShardCount::new(self.shard_count as u8),
989 : })
990 0 : }
991 : }
992 :
993 : /// Parts of [`crate::node::Node`] that are stored durably
994 0 : #[derive(Serialize, Deserialize, Queryable, Selectable, Insertable, Eq, PartialEq)]
995 : #[diesel(table_name = crate::schema::nodes)]
996 : pub(crate) struct NodePersistence {
997 : pub(crate) node_id: i64,
998 : pub(crate) scheduling_policy: String,
999 : pub(crate) listen_http_addr: String,
1000 : pub(crate) listen_http_port: i32,
1001 : pub(crate) listen_pg_addr: String,
1002 : pub(crate) listen_pg_port: i32,
1003 : pub(crate) availability_zone_id: Option<String>,
1004 : }
1005 :
1006 : /// Tenant metadata health status that are stored durably.
1007 0 : #[derive(Queryable, Selectable, Insertable, Serialize, Deserialize, Clone, Eq, PartialEq)]
1008 : #[diesel(table_name = crate::schema::metadata_health)]
1009 : pub(crate) struct MetadataHealthPersistence {
1010 : #[serde(default)]
1011 : pub(crate) tenant_id: String,
1012 : #[serde(default)]
1013 : pub(crate) shard_number: i32,
1014 : #[serde(default)]
1015 : pub(crate) shard_count: i32,
1016 :
1017 : pub(crate) healthy: bool,
1018 : pub(crate) last_scrubbed_at: chrono::DateTime<chrono::Utc>,
1019 : }
1020 :
1021 : impl MetadataHealthPersistence {
1022 0 : pub fn new(
1023 0 : tenant_shard_id: TenantShardId,
1024 0 : healthy: bool,
1025 0 : last_scrubbed_at: chrono::DateTime<chrono::Utc>,
1026 0 : ) -> Self {
1027 0 : let tenant_id = tenant_shard_id.tenant_id.to_string();
1028 0 : let shard_number = tenant_shard_id.shard_number.0 as i32;
1029 0 : let shard_count = tenant_shard_id.shard_count.literal() as i32;
1030 0 :
1031 0 : MetadataHealthPersistence {
1032 0 : tenant_id,
1033 0 : shard_number,
1034 0 : shard_count,
1035 0 : healthy,
1036 0 : last_scrubbed_at,
1037 0 : }
1038 0 : }
1039 :
1040 : #[allow(dead_code)]
1041 0 : pub(crate) fn get_tenant_shard_id(&self) -> Result<TenantShardId, hex::FromHexError> {
1042 0 : Ok(TenantShardId {
1043 0 : tenant_id: TenantId::from_str(self.tenant_id.as_str())?,
1044 0 : shard_number: ShardNumber(self.shard_number as u8),
1045 0 : shard_count: ShardCount::new(self.shard_count as u8),
1046 : })
1047 0 : }
1048 : }
1049 :
1050 : impl From<MetadataHealthPersistence> for MetadataHealthRecord {
1051 0 : fn from(value: MetadataHealthPersistence) -> Self {
1052 0 : MetadataHealthRecord {
1053 0 : tenant_shard_id: value
1054 0 : .get_tenant_shard_id()
1055 0 : .expect("stored tenant id should be valid"),
1056 0 : healthy: value.healthy,
1057 0 : last_scrubbed_at: value.last_scrubbed_at,
1058 0 : }
1059 0 : }
1060 : }
1061 :
1062 : #[derive(
1063 0 : Serialize, Deserialize, Queryable, Selectable, Insertable, Eq, PartialEq, Debug, Clone,
1064 : )]
1065 : #[diesel(table_name = crate::schema::controllers)]
1066 : pub(crate) struct ControllerPersistence {
1067 : pub(crate) address: String,
1068 : pub(crate) started_at: chrono::DateTime<chrono::Utc>,
1069 : }
|