LCOV - code coverage report
Current view: top level - storage_controller/src - persistence.rs (source / functions) Coverage Total Hit
Test: ccf45ed1c149555259baec52d6229a81013dcd6a.info Lines: 0.0 % 597 0
Test Date: 2024-08-21 17:32:46 Functions: 0.0 % 273 0

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

Generated by: LCOV version 2.1-beta