Line data Source code
1 : pub(crate) mod split_state;
2 : use std::collections::HashMap;
3 : use std::str::FromStr;
4 : use std::sync::Arc;
5 : use std::time::Duration;
6 : use std::time::Instant;
7 :
8 : use self::split_state::SplitState;
9 : use diesel::prelude::*;
10 : use diesel_async::async_connection_wrapper::AsyncConnectionWrapper;
11 : use diesel_async::pooled_connection::bb8::Pool;
12 : use diesel_async::pooled_connection::AsyncDieselConnectionManager;
13 : use diesel_async::pooled_connection::ManagerConfig;
14 : use diesel_async::AsyncPgConnection;
15 : use diesel_async::RunQueryDsl;
16 : use futures::future::BoxFuture;
17 : use futures::FutureExt;
18 : use itertools::Itertools;
19 : use pageserver_api::controller_api::AvailabilityZone;
20 : use pageserver_api::controller_api::MetadataHealthRecord;
21 : use pageserver_api::controller_api::SafekeeperDescribeResponse;
22 : use pageserver_api::controller_api::ShardSchedulingPolicy;
23 : use pageserver_api::controller_api::SkSchedulingPolicy;
24 : use pageserver_api::controller_api::{NodeSchedulingPolicy, PlacementPolicy};
25 : use pageserver_api::models::TenantConfig;
26 : use pageserver_api::shard::ShardConfigError;
27 : use pageserver_api::shard::ShardIdentity;
28 : use pageserver_api::shard::ShardStripeSize;
29 : use pageserver_api::shard::{ShardCount, ShardNumber, TenantShardId};
30 : use rustls::client::danger::{ServerCertVerified, ServerCertVerifier};
31 : use rustls::client::WebPkiServerVerifier;
32 : use rustls::crypto::ring;
33 : use scoped_futures::ScopedBoxFuture;
34 : use serde::{Deserialize, Serialize};
35 : use utils::generation::Generation;
36 : use utils::id::{NodeId, TenantId};
37 :
38 : use crate::metrics::{
39 : DatabaseQueryErrorLabelGroup, DatabaseQueryLatencyLabelGroup, METRICS_REGISTRY,
40 : };
41 : use crate::node::Node;
42 :
43 : use diesel_migrations::{embed_migrations, EmbeddedMigrations};
44 : const MIGRATIONS: EmbeddedMigrations = embed_migrations!("./migrations");
45 :
46 : /// ## What do we store?
47 : ///
48 : /// The storage controller service does not store most of its state durably.
49 : ///
50 : /// The essential things to store durably are:
51 : /// - generation numbers, as these must always advance monotonically to ensure data safety.
52 : /// - Tenant's PlacementPolicy and TenantConfig, as the source of truth for these is something external.
53 : /// - Node's scheduling policies, as the source of truth for these is something external.
54 : ///
55 : /// Other things we store durably as an implementation detail:
56 : /// - Node's host/port: this could be avoided it we made nodes emit a self-registering heartbeat,
57 : /// but it is operationally simpler to make this service the authority for which nodes
58 : /// it talks to.
59 : ///
60 : /// ## Performance/efficiency
61 : ///
62 : /// The storage controller service does not go via the database for most things: there are
63 : /// a couple of places where we must, and where efficiency matters:
64 : /// - Incrementing generation numbers: the Reconciler has to wait for this to complete
65 : /// before it can attach a tenant, so this acts as a bound on how fast things like
66 : /// failover can happen.
67 : /// - Pageserver re-attach: we will increment many shards' generations when this happens,
68 : /// so it is important to avoid e.g. issuing O(N) queries.
69 : ///
70 : /// Database calls relating to nodes have low performance requirements, as they are very rarely
71 : /// updated, and reads of nodes are always from memory, not the database. We only require that
72 : /// we can UPDATE a node's scheduling mode reasonably quickly to mark a bad node offline.
73 : pub struct Persistence {
74 : connection_pool: Pool<AsyncPgConnection>,
75 : }
76 :
77 : /// Legacy format, for use in JSON compat objects in test environment
78 0 : #[derive(Serialize, Deserialize)]
79 : struct JsonPersistence {
80 : tenants: HashMap<TenantShardId, TenantShardPersistence>,
81 : }
82 :
83 : #[derive(thiserror::Error, Debug)]
84 : pub(crate) enum DatabaseError {
85 : #[error(transparent)]
86 : Query(#[from] diesel::result::Error),
87 : #[error(transparent)]
88 : Connection(#[from] diesel::result::ConnectionError),
89 : #[error(transparent)]
90 : ConnectionPool(#[from] diesel_async::pooled_connection::bb8::RunError),
91 : #[error("Logical error: {0}")]
92 : Logical(String),
93 : #[error("Migration error: {0}")]
94 : Migration(String),
95 : }
96 :
97 : #[derive(measured::FixedCardinalityLabel, Copy, Clone)]
98 : pub(crate) enum DatabaseOperation {
99 : InsertNode,
100 : UpdateNode,
101 : DeleteNode,
102 : ListNodes,
103 : BeginShardSplit,
104 : CompleteShardSplit,
105 : AbortShardSplit,
106 : Detach,
107 : ReAttach,
108 : IncrementGeneration,
109 : TenantGenerations,
110 : ShardGenerations,
111 : ListTenantShards,
112 : LoadTenant,
113 : InsertTenantShards,
114 : UpdateTenantShard,
115 : DeleteTenant,
116 : UpdateTenantConfig,
117 : UpdateMetadataHealth,
118 : ListMetadataHealth,
119 : ListMetadataHealthUnhealthy,
120 : ListMetadataHealthOutdated,
121 : ListSafekeepers,
122 : GetLeader,
123 : UpdateLeader,
124 : SetPreferredAzs,
125 : }
126 :
127 : #[must_use]
128 : pub(crate) enum AbortShardSplitStatus {
129 : /// We aborted the split in the database by reverting to the parent shards
130 : Aborted,
131 : /// The split had already been persisted.
132 : Complete,
133 : }
134 :
135 : pub(crate) type DatabaseResult<T> = Result<T, DatabaseError>;
136 :
137 : /// Some methods can operate on either a whole tenant or a single shard
138 : #[derive(Clone)]
139 : pub(crate) enum TenantFilter {
140 : Tenant(TenantId),
141 : Shard(TenantShardId),
142 : }
143 :
144 : /// Represents the results of looking up generation+pageserver for the shards of a tenant
145 : pub(crate) struct ShardGenerationState {
146 : pub(crate) tenant_shard_id: TenantShardId,
147 : pub(crate) generation: Option<Generation>,
148 : pub(crate) generation_pageserver: Option<NodeId>,
149 : }
150 :
151 : // A generous allowance for how many times we may retry serializable transactions
152 : // before giving up. This is not expected to be hit: it is a defensive measure in case we
153 : // somehow engineer a situation where duelling transactions might otherwise live-lock.
154 : const MAX_RETRIES: usize = 128;
155 :
156 : impl Persistence {
157 : // The default postgres connection limit is 100. We use up to 99, to leave one free for a human admin under
158 : // normal circumstances. This assumes we have exclusive use of the database cluster to which we connect.
159 : pub const MAX_CONNECTIONS: u32 = 99;
160 :
161 : // We don't want to keep a lot of connections alive: close them down promptly if they aren't being used.
162 : const IDLE_CONNECTION_TIMEOUT: Duration = Duration::from_secs(10);
163 : const MAX_CONNECTION_LIFETIME: Duration = Duration::from_secs(60);
164 :
165 0 : pub async fn new(database_url: String) -> Self {
166 0 : let mut mgr_config = ManagerConfig::default();
167 0 : mgr_config.custom_setup = Box::new(establish_connection_rustls);
168 0 :
169 0 : let manager = AsyncDieselConnectionManager::<AsyncPgConnection>::new_with_config(
170 0 : database_url,
171 0 : mgr_config,
172 0 : );
173 :
174 : // We will use a connection pool: this is primarily to _limit_ our connection count, rather than to optimize time
175 : // to execute queries (database queries are not generally on latency-sensitive paths).
176 0 : let connection_pool = Pool::builder()
177 0 : .max_size(Self::MAX_CONNECTIONS)
178 0 : .max_lifetime(Some(Self::MAX_CONNECTION_LIFETIME))
179 0 : .idle_timeout(Some(Self::IDLE_CONNECTION_TIMEOUT))
180 0 : // Always keep at least one connection ready to go
181 0 : .min_idle(Some(1))
182 0 : .test_on_check_out(true)
183 0 : .build(manager)
184 0 : .await
185 0 : .expect("Could not build connection pool");
186 0 :
187 0 : Self { connection_pool }
188 0 : }
189 :
190 : /// A helper for use during startup, where we would like to tolerate concurrent restarts of the
191 : /// database and the storage controller, therefore the database might not be available right away
192 0 : pub async fn await_connection(
193 0 : database_url: &str,
194 0 : timeout: Duration,
195 0 : ) -> Result<(), diesel::ConnectionError> {
196 0 : let started_at = Instant::now();
197 0 : log_postgres_connstr_info(database_url)
198 0 : .map_err(|e| diesel::ConnectionError::InvalidConnectionUrl(e.to_string()))?;
199 : loop {
200 0 : match establish_connection_rustls(database_url).await {
201 : Ok(_) => {
202 0 : tracing::info!("Connected to database.");
203 0 : return Ok(());
204 : }
205 0 : Err(e) => {
206 0 : if started_at.elapsed() > timeout {
207 0 : return Err(e);
208 : } else {
209 0 : tracing::info!("Database not yet available, waiting... ({e})");
210 0 : tokio::time::sleep(Duration::from_millis(100)).await;
211 : }
212 : }
213 : }
214 : }
215 0 : }
216 :
217 : /// Execute the diesel migrations that are built into this binary
218 0 : pub(crate) async fn migration_run(&self) -> DatabaseResult<()> {
219 : use diesel_migrations::{HarnessWithOutput, MigrationHarness};
220 :
221 : // Can't use self.with_conn here as we do spawn_blocking which requires static.
222 0 : let conn = self
223 0 : .connection_pool
224 0 : .dedicated_connection()
225 0 : .await
226 0 : .map_err(|e| DatabaseError::Migration(e.to_string()))?;
227 0 : let mut async_wrapper: AsyncConnectionWrapper<AsyncPgConnection> =
228 0 : AsyncConnectionWrapper::from(conn);
229 0 : tokio::task::spawn_blocking(move || {
230 0 : let mut retry_count = 0;
231 0 : loop {
232 0 : let result = HarnessWithOutput::write_to_stdout(&mut async_wrapper)
233 0 : .run_pending_migrations(MIGRATIONS)
234 0 : .map(|_| ())
235 0 : .map_err(|e| DatabaseError::Migration(e.to_string()));
236 0 : match result {
237 0 : Ok(r) => break Ok(r),
238 : Err(
239 0 : err @ DatabaseError::Query(diesel::result::Error::DatabaseError(
240 0 : diesel::result::DatabaseErrorKind::SerializationFailure,
241 0 : _,
242 0 : )),
243 0 : ) => {
244 0 : retry_count += 1;
245 0 : if retry_count > MAX_RETRIES {
246 0 : tracing::error!(
247 0 : "Exceeded max retries on SerializationFailure errors: {err:?}"
248 : );
249 0 : break Err(err);
250 : } else {
251 : // Retry on serialization errors: these are expected, because even though our
252 : // transactions don't fight for the same rows, they will occasionally collide
253 : // on index pages (e.g. increment_generation for unrelated shards can collide)
254 0 : tracing::debug!(
255 0 : "Retrying transaction on serialization failure {err:?}"
256 : );
257 0 : continue;
258 : }
259 : }
260 0 : Err(e) => break Err(e),
261 : }
262 : }
263 0 : })
264 0 : .await
265 0 : .map_err(|e| DatabaseError::Migration(e.to_string()))??;
266 0 : Ok(())
267 0 : }
268 :
269 : /// Wraps `with_conn` in order to collect latency and error metrics
270 0 : async fn with_measured_conn<'a, 'b, F, R>(
271 0 : &self,
272 0 : op: DatabaseOperation,
273 0 : func: F,
274 0 : ) -> DatabaseResult<R>
275 0 : where
276 0 : F: for<'r> Fn(&'r mut AsyncPgConnection) -> ScopedBoxFuture<'b, 'r, DatabaseResult<R>>
277 0 : + Send
278 0 : + std::marker::Sync
279 0 : + 'a,
280 0 : R: Send + 'b,
281 0 : {
282 0 : let latency = &METRICS_REGISTRY
283 0 : .metrics_group
284 0 : .storage_controller_database_query_latency;
285 0 : let _timer = latency.start_timer(DatabaseQueryLatencyLabelGroup { operation: op });
286 :
287 0 : let res = self.with_conn(func).await;
288 :
289 0 : if let Err(err) = &res {
290 0 : let error_counter = &METRICS_REGISTRY
291 0 : .metrics_group
292 0 : .storage_controller_database_query_error;
293 0 : error_counter.inc(DatabaseQueryErrorLabelGroup {
294 0 : error_type: err.error_label(),
295 0 : operation: op,
296 0 : })
297 0 : }
298 :
299 0 : res
300 0 : }
301 :
302 : /// Call the provided function with a Diesel database connection in a retry loop
303 0 : async fn with_conn<'a, 'b, F, R>(&self, func: F) -> DatabaseResult<R>
304 0 : where
305 0 : F: for<'r> Fn(&'r mut AsyncPgConnection) -> ScopedBoxFuture<'b, 'r, DatabaseResult<R>>
306 0 : + Send
307 0 : + std::marker::Sync
308 0 : + 'a,
309 0 : R: Send + 'b,
310 0 : {
311 0 : let mut retry_count = 0;
312 : loop {
313 0 : let mut conn = self.connection_pool.get().await?;
314 0 : match conn
315 0 : .build_transaction()
316 0 : .serializable()
317 0 : .run(|c| func(c))
318 0 : .await
319 : {
320 0 : Ok(r) => break Ok(r),
321 : Err(
322 0 : err @ DatabaseError::Query(diesel::result::Error::DatabaseError(
323 0 : diesel::result::DatabaseErrorKind::SerializationFailure,
324 0 : _,
325 0 : )),
326 0 : ) => {
327 0 : retry_count += 1;
328 0 : if retry_count > MAX_RETRIES {
329 0 : tracing::error!(
330 0 : "Exceeded max retries on SerializationFailure errors: {err:?}"
331 : );
332 0 : break Err(err);
333 : } else {
334 : // Retry on serialization errors: these are expected, because even though our
335 : // transactions don't fight for the same rows, they will occasionally collide
336 : // on index pages (e.g. increment_generation for unrelated shards can collide)
337 0 : tracing::debug!("Retrying transaction on serialization failure {err:?}");
338 0 : continue;
339 : }
340 : }
341 0 : Err(e) => break Err(e),
342 : }
343 : }
344 0 : }
345 :
346 : /// When a node is first registered, persist it before using it for anything
347 0 : pub(crate) async fn insert_node(&self, node: &Node) -> DatabaseResult<()> {
348 0 : let np = &node.to_persistent();
349 0 : self.with_measured_conn(DatabaseOperation::InsertNode, move |conn| {
350 0 : Box::pin(async move {
351 0 : diesel::insert_into(crate::schema::nodes::table)
352 0 : .values(np)
353 0 : .execute(conn)
354 0 : .await?;
355 0 : Ok(())
356 0 : })
357 0 : })
358 0 : .await
359 0 : }
360 :
361 : /// At startup, populate the list of nodes which our shards may be placed on
362 0 : pub(crate) async fn list_nodes(&self) -> DatabaseResult<Vec<NodePersistence>> {
363 0 : let nodes: Vec<NodePersistence> = self
364 0 : .with_measured_conn(DatabaseOperation::ListNodes, move |conn| {
365 0 : Box::pin(async move {
366 0 : Ok(crate::schema::nodes::table
367 0 : .load::<NodePersistence>(conn)
368 0 : .await?)
369 0 : })
370 0 : })
371 0 : .await?;
372 :
373 0 : tracing::info!("list_nodes: loaded {} nodes", nodes.len());
374 :
375 0 : Ok(nodes)
376 0 : }
377 :
378 0 : pub(crate) async fn update_node<V>(
379 0 : &self,
380 0 : input_node_id: NodeId,
381 0 : values: V,
382 0 : ) -> DatabaseResult<()>
383 0 : where
384 0 : V: diesel::AsChangeset<Target = crate::schema::nodes::table> + Clone + Send + Sync,
385 0 : V::Changeset: diesel::query_builder::QueryFragment<diesel::pg::Pg> + Send, // valid Postgres SQL
386 0 : {
387 : use crate::schema::nodes::dsl::*;
388 0 : let updated = self
389 0 : .with_measured_conn(DatabaseOperation::UpdateNode, move |conn| {
390 0 : let values = values.clone();
391 0 : Box::pin(async move {
392 0 : let updated = diesel::update(nodes)
393 0 : .filter(node_id.eq(input_node_id.0 as i64))
394 0 : .set(values)
395 0 : .execute(conn)
396 0 : .await?;
397 0 : Ok(updated)
398 0 : })
399 0 : })
400 0 : .await?;
401 :
402 0 : if updated != 1 {
403 0 : Err(DatabaseError::Logical(format!(
404 0 : "Node {node_id:?} not found for update",
405 0 : )))
406 : } else {
407 0 : Ok(())
408 : }
409 0 : }
410 :
411 0 : pub(crate) async fn update_node_scheduling_policy(
412 0 : &self,
413 0 : input_node_id: NodeId,
414 0 : input_scheduling: NodeSchedulingPolicy,
415 0 : ) -> DatabaseResult<()> {
416 : use crate::schema::nodes::dsl::*;
417 0 : self.update_node(
418 0 : input_node_id,
419 0 : scheduling_policy.eq(String::from(input_scheduling)),
420 0 : )
421 0 : .await
422 0 : }
423 :
424 0 : pub(crate) async fn update_node_on_registration(
425 0 : &self,
426 0 : input_node_id: NodeId,
427 0 : input_https_port: Option<u16>,
428 0 : ) -> DatabaseResult<()> {
429 : use crate::schema::nodes::dsl::*;
430 0 : self.update_node(
431 0 : input_node_id,
432 0 : listen_https_port.eq(input_https_port.map(|x| x as i32)),
433 0 : )
434 0 : .await
435 0 : }
436 :
437 : /// At startup, load the high level state for shards, such as their config + policy. This will
438 : /// be enriched at runtime with state discovered on pageservers.
439 : ///
440 : /// We exclude shards configured to be detached. During startup, if we see any attached locations
441 : /// for such shards, they will automatically be detached as 'orphans'.
442 0 : pub(crate) async fn load_active_tenant_shards(
443 0 : &self,
444 0 : ) -> DatabaseResult<Vec<TenantShardPersistence>> {
445 : use crate::schema::tenant_shards::dsl::*;
446 0 : self.with_measured_conn(DatabaseOperation::ListTenantShards, move |conn| {
447 0 : Box::pin(async move {
448 0 : let query = tenant_shards.filter(
449 0 : placement_policy.ne(serde_json::to_string(&PlacementPolicy::Detached).unwrap()),
450 0 : );
451 0 : let result = query.load::<TenantShardPersistence>(conn).await?;
452 :
453 0 : Ok(result)
454 0 : })
455 0 : })
456 0 : .await
457 0 : }
458 :
459 : /// When restoring a previously detached tenant into memory, load it from the database
460 0 : pub(crate) async fn load_tenant(
461 0 : &self,
462 0 : filter_tenant_id: TenantId,
463 0 : ) -> DatabaseResult<Vec<TenantShardPersistence>> {
464 : use crate::schema::tenant_shards::dsl::*;
465 0 : self.with_measured_conn(DatabaseOperation::LoadTenant, move |conn| {
466 0 : Box::pin(async move {
467 0 : let query = tenant_shards.filter(tenant_id.eq(filter_tenant_id.to_string()));
468 0 : let result = query.load::<TenantShardPersistence>(conn).await?;
469 :
470 0 : Ok(result)
471 0 : })
472 0 : })
473 0 : .await
474 0 : }
475 :
476 : /// Tenants must be persisted before we schedule them for the first time. This enables us
477 : /// to correctly retain generation monotonicity, and the externally provided placement policy & config.
478 0 : pub(crate) async fn insert_tenant_shards(
479 0 : &self,
480 0 : shards: Vec<TenantShardPersistence>,
481 0 : ) -> DatabaseResult<()> {
482 : use crate::schema::metadata_health;
483 : use crate::schema::tenant_shards;
484 :
485 0 : let now = chrono::Utc::now();
486 0 :
487 0 : let metadata_health_records = shards
488 0 : .iter()
489 0 : .map(|t| MetadataHealthPersistence {
490 0 : tenant_id: t.tenant_id.clone(),
491 0 : shard_number: t.shard_number,
492 0 : shard_count: t.shard_count,
493 0 : healthy: true,
494 0 : last_scrubbed_at: now,
495 0 : })
496 0 : .collect::<Vec<_>>();
497 0 :
498 0 : let shards = &shards;
499 0 : let metadata_health_records = &metadata_health_records;
500 0 : self.with_measured_conn(DatabaseOperation::InsertTenantShards, move |conn| {
501 0 : Box::pin(async move {
502 0 : diesel::insert_into(tenant_shards::table)
503 0 : .values(shards)
504 0 : .execute(conn)
505 0 : .await?;
506 :
507 0 : diesel::insert_into(metadata_health::table)
508 0 : .values(metadata_health_records)
509 0 : .execute(conn)
510 0 : .await?;
511 0 : Ok(())
512 0 : })
513 0 : })
514 0 : .await
515 0 : }
516 :
517 : /// Ordering: call this _after_ deleting the tenant on pageservers, but _before_ dropping state for
518 : /// the tenant from memory on this server.
519 0 : pub(crate) async fn delete_tenant(&self, del_tenant_id: TenantId) -> DatabaseResult<()> {
520 : use crate::schema::tenant_shards::dsl::*;
521 0 : self.with_measured_conn(DatabaseOperation::DeleteTenant, move |conn| {
522 0 : Box::pin(async move {
523 0 : // `metadata_health` status (if exists) is also deleted based on the cascade behavior.
524 0 : diesel::delete(tenant_shards)
525 0 : .filter(tenant_id.eq(del_tenant_id.to_string()))
526 0 : .execute(conn)
527 0 : .await?;
528 0 : Ok(())
529 0 : })
530 0 : })
531 0 : .await
532 0 : }
533 :
534 0 : pub(crate) async fn delete_node(&self, del_node_id: NodeId) -> DatabaseResult<()> {
535 : use crate::schema::nodes::dsl::*;
536 0 : self.with_measured_conn(DatabaseOperation::DeleteNode, move |conn| {
537 0 : Box::pin(async move {
538 0 : diesel::delete(nodes)
539 0 : .filter(node_id.eq(del_node_id.0 as i64))
540 0 : .execute(conn)
541 0 : .await?;
542 :
543 0 : Ok(())
544 0 : })
545 0 : })
546 0 : .await
547 0 : }
548 :
549 : /// When a tenant invokes the /re-attach API, this function is responsible for doing an efficient
550 : /// batched increment of the generations of all tenants whose generation_pageserver is equal to
551 : /// the node that called /re-attach.
552 : #[tracing::instrument(skip_all, fields(node_id))]
553 : pub(crate) async fn re_attach(
554 : &self,
555 : input_node_id: NodeId,
556 : ) -> DatabaseResult<HashMap<TenantShardId, Generation>> {
557 : use crate::schema::nodes::dsl::scheduling_policy;
558 : use crate::schema::nodes::dsl::*;
559 : use crate::schema::tenant_shards::dsl::*;
560 : let updated = self
561 0 : .with_measured_conn(DatabaseOperation::ReAttach, move |conn| {
562 0 : Box::pin(async move {
563 0 : let rows_updated = diesel::update(tenant_shards)
564 0 : .filter(generation_pageserver.eq(input_node_id.0 as i64))
565 0 : .set(generation.eq(generation + 1))
566 0 : .execute(conn)
567 0 : .await?;
568 :
569 0 : tracing::info!("Incremented {} tenants' generations", rows_updated);
570 :
571 : // TODO: UPDATE+SELECT in one query
572 :
573 0 : let updated = tenant_shards
574 0 : .filter(generation_pageserver.eq(input_node_id.0 as i64))
575 0 : .select(TenantShardPersistence::as_select())
576 0 : .load(conn)
577 0 : .await?;
578 :
579 : // If the node went through a drain and restart phase before re-attaching,
580 : // then reset it's node scheduling policy to active.
581 0 : diesel::update(nodes)
582 0 : .filter(node_id.eq(input_node_id.0 as i64))
583 0 : .filter(
584 0 : scheduling_policy
585 0 : .eq(String::from(NodeSchedulingPolicy::PauseForRestart))
586 0 : .or(scheduling_policy
587 0 : .eq(String::from(NodeSchedulingPolicy::Draining)))
588 0 : .or(scheduling_policy
589 0 : .eq(String::from(NodeSchedulingPolicy::Filling))),
590 0 : )
591 0 : .set(scheduling_policy.eq(String::from(NodeSchedulingPolicy::Active)))
592 0 : .execute(conn)
593 0 : .await?;
594 :
595 0 : Ok(updated)
596 0 : })
597 0 : })
598 : .await?;
599 :
600 : let mut result = HashMap::new();
601 : for tsp in updated {
602 : let tenant_shard_id = TenantShardId {
603 : tenant_id: TenantId::from_str(tsp.tenant_id.as_str())
604 0 : .map_err(|e| DatabaseError::Logical(format!("Malformed tenant id: {e}")))?,
605 : shard_number: ShardNumber(tsp.shard_number as u8),
606 : shard_count: ShardCount::new(tsp.shard_count as u8),
607 : };
608 :
609 : let Some(g) = tsp.generation else {
610 : // If the generation_pageserver column was non-NULL, then the generation column should also be non-NULL:
611 : // we only set generation_pageserver when setting generation.
612 : return Err(DatabaseError::Logical(
613 : "Generation should always be set after incrementing".to_string(),
614 : ));
615 : };
616 : result.insert(tenant_shard_id, Generation::new(g as u32));
617 : }
618 :
619 : Ok(result)
620 : }
621 :
622 : /// Reconciler calls this immediately before attaching to a new pageserver, to acquire a unique, monotonically
623 : /// advancing generation number. We also store the NodeId for which the generation was issued, so that in
624 : /// [`Self::re_attach`] we can do a bulk UPDATE on the generations for that node.
625 0 : pub(crate) async fn increment_generation(
626 0 : &self,
627 0 : tenant_shard_id: TenantShardId,
628 0 : node_id: NodeId,
629 0 : ) -> anyhow::Result<Generation> {
630 : use crate::schema::tenant_shards::dsl::*;
631 0 : let updated = self
632 0 : .with_measured_conn(DatabaseOperation::IncrementGeneration, move |conn| {
633 0 : Box::pin(async move {
634 0 : let updated = diesel::update(tenant_shards)
635 0 : .filter(tenant_id.eq(tenant_shard_id.tenant_id.to_string()))
636 0 : .filter(shard_number.eq(tenant_shard_id.shard_number.0 as i32))
637 0 : .filter(shard_count.eq(tenant_shard_id.shard_count.literal() as i32))
638 0 : .set((
639 0 : generation.eq(generation + 1),
640 0 : generation_pageserver.eq(node_id.0 as i64),
641 0 : ))
642 0 : // TODO: only returning() the generation column
643 0 : .returning(TenantShardPersistence::as_returning())
644 0 : .get_result(conn)
645 0 : .await?;
646 :
647 0 : Ok(updated)
648 0 : })
649 0 : })
650 0 : .await?;
651 :
652 : // Generation is always non-null in the rseult: if the generation column had been NULL, then we
653 : // should have experienced an SQL Confilict error while executing a query that tries to increment it.
654 0 : debug_assert!(updated.generation.is_some());
655 0 : let Some(g) = updated.generation else {
656 0 : return Err(DatabaseError::Logical(
657 0 : "Generation should always be set after incrementing".to_string(),
658 0 : )
659 0 : .into());
660 : };
661 :
662 0 : Ok(Generation::new(g as u32))
663 0 : }
664 :
665 : /// When we want to call out to the running shards for a tenant, e.g. during timeline CRUD operations,
666 : /// we need to know where the shard is attached, _and_ the generation, so that we can re-check the generation
667 : /// afterwards to confirm that our timeline CRUD operation is truly persistent (it must have happened in the
668 : /// latest generation)
669 : ///
670 : /// If the tenant doesn't exist, an empty vector is returned.
671 : ///
672 : /// Output is sorted by shard number
673 0 : pub(crate) async fn tenant_generations(
674 0 : &self,
675 0 : filter_tenant_id: TenantId,
676 0 : ) -> Result<Vec<ShardGenerationState>, DatabaseError> {
677 : use crate::schema::tenant_shards::dsl::*;
678 0 : let rows = self
679 0 : .with_measured_conn(DatabaseOperation::TenantGenerations, move |conn| {
680 0 : Box::pin(async move {
681 0 : let result = tenant_shards
682 0 : .filter(tenant_id.eq(filter_tenant_id.to_string()))
683 0 : .select(TenantShardPersistence::as_select())
684 0 : .order(shard_number)
685 0 : .load(conn)
686 0 : .await?;
687 0 : Ok(result)
688 0 : })
689 0 : })
690 0 : .await?;
691 :
692 0 : Ok(rows
693 0 : .into_iter()
694 0 : .map(|p| ShardGenerationState {
695 0 : tenant_shard_id: p
696 0 : .get_tenant_shard_id()
697 0 : .expect("Corrupt tenant shard id in database"),
698 0 : generation: p.generation.map(|g| Generation::new(g as u32)),
699 0 : generation_pageserver: p.generation_pageserver.map(|n| NodeId(n as u64)),
700 0 : })
701 0 : .collect())
702 0 : }
703 :
704 : /// Read the generation number of specific tenant shards
705 : ///
706 : /// Output is unsorted. Output may not include values for all inputs, if they are missing in the database.
707 0 : pub(crate) async fn shard_generations(
708 0 : &self,
709 0 : mut tenant_shard_ids: impl Iterator<Item = &TenantShardId>,
710 0 : ) -> Result<Vec<(TenantShardId, Option<Generation>)>, DatabaseError> {
711 0 : let mut rows = Vec::with_capacity(tenant_shard_ids.size_hint().0);
712 :
713 : // We will chunk our input to avoid composing arbitrarily long `IN` clauses. Typically we are
714 : // called with a single digit number of IDs, but in principle we could be called with tens
715 : // of thousands (all the shards on one pageserver) from the generation validation API.
716 0 : loop {
717 0 : // A modest hardcoded chunk size to handle typical cases in a single query but never generate particularly
718 0 : // large query strings.
719 0 : let chunk_ids = tenant_shard_ids.by_ref().take(32);
720 0 :
721 0 : // Compose a comma separated list of tuples for matching on (tenant_id, shard_number, shard_count)
722 0 : let in_clause = chunk_ids
723 0 : .map(|tsid| {
724 0 : format!(
725 0 : "('{}', {}, {})",
726 0 : tsid.tenant_id, tsid.shard_number.0, tsid.shard_count.0
727 0 : )
728 0 : })
729 0 : .join(",");
730 0 :
731 0 : // We are done when our iterator gives us nothing to filter on
732 0 : if in_clause.is_empty() {
733 0 : break;
734 0 : }
735 0 :
736 0 : let in_clause = &in_clause;
737 0 : let chunk_rows = self
738 0 : .with_measured_conn(DatabaseOperation::ShardGenerations, move |conn| {
739 0 : Box::pin(async move {
740 : // diesel doesn't support multi-column IN queries, so we compose raw SQL. No escaping is required because
741 : // the inputs are strongly typed and cannot carry any user-supplied raw string content.
742 0 : let result : Vec<TenantShardPersistence> = diesel::sql_query(
743 0 : format!("SELECT * from tenant_shards where (tenant_id, shard_number, shard_count) in ({in_clause});").as_str()
744 0 : ).load(conn).await?;
745 :
746 0 : Ok(result)
747 0 : })
748 0 : })
749 0 : .await?;
750 0 : rows.extend(chunk_rows.into_iter())
751 : }
752 :
753 0 : Ok(rows
754 0 : .into_iter()
755 0 : .map(|tsp| {
756 0 : (
757 0 : tsp.get_tenant_shard_id()
758 0 : .expect("Bad tenant ID in database"),
759 0 : tsp.generation.map(|g| Generation::new(g as u32)),
760 0 : )
761 0 : })
762 0 : .collect())
763 0 : }
764 :
765 : #[allow(non_local_definitions)]
766 : /// For use when updating a persistent property of a tenant, such as its config or placement_policy.
767 : ///
768 : /// Do not use this for settting generation, unless in the special onboarding code path (/location_config)
769 : /// API: use [`Self::increment_generation`] instead. Setting the generation via this route is a one-time thing
770 : /// that we only do the first time a tenant is set to an attached policy via /location_config.
771 0 : pub(crate) async fn update_tenant_shard(
772 0 : &self,
773 0 : tenant: TenantFilter,
774 0 : input_placement_policy: Option<PlacementPolicy>,
775 0 : input_config: Option<TenantConfig>,
776 0 : input_generation: Option<Generation>,
777 0 : input_scheduling_policy: Option<ShardSchedulingPolicy>,
778 0 : ) -> DatabaseResult<()> {
779 : use crate::schema::tenant_shards::dsl::*;
780 :
781 0 : let tenant = &tenant;
782 0 : let input_placement_policy = &input_placement_policy;
783 0 : let input_config = &input_config;
784 0 : let input_generation = &input_generation;
785 0 : let input_scheduling_policy = &input_scheduling_policy;
786 0 : self.with_measured_conn(DatabaseOperation::UpdateTenantShard, move |conn| {
787 0 : Box::pin(async move {
788 0 : let query = match tenant {
789 0 : TenantFilter::Shard(tenant_shard_id) => diesel::update(tenant_shards)
790 0 : .filter(tenant_id.eq(tenant_shard_id.tenant_id.to_string()))
791 0 : .filter(shard_number.eq(tenant_shard_id.shard_number.0 as i32))
792 0 : .filter(shard_count.eq(tenant_shard_id.shard_count.literal() as i32))
793 0 : .into_boxed(),
794 0 : TenantFilter::Tenant(input_tenant_id) => diesel::update(tenant_shards)
795 0 : .filter(tenant_id.eq(input_tenant_id.to_string()))
796 0 : .into_boxed(),
797 : };
798 :
799 : // Clear generation_pageserver if we are moving into a state where we won't have
800 : // any attached pageservers.
801 0 : let input_generation_pageserver = match input_placement_policy {
802 0 : None | Some(PlacementPolicy::Attached(_)) => None,
803 0 : Some(PlacementPolicy::Detached | PlacementPolicy::Secondary) => Some(None),
804 : };
805 :
806 0 : #[derive(AsChangeset)]
807 : #[diesel(table_name = crate::schema::tenant_shards)]
808 : struct ShardUpdate {
809 : generation: Option<i32>,
810 : placement_policy: Option<String>,
811 : config: Option<String>,
812 : scheduling_policy: Option<String>,
813 : generation_pageserver: Option<Option<i64>>,
814 : }
815 :
816 0 : let update = ShardUpdate {
817 0 : generation: input_generation.map(|g| g.into().unwrap() as i32),
818 0 : placement_policy: input_placement_policy
819 0 : .as_ref()
820 0 : .map(|p| serde_json::to_string(&p).unwrap()),
821 0 : config: input_config
822 0 : .as_ref()
823 0 : .map(|c| serde_json::to_string(&c).unwrap()),
824 0 : scheduling_policy: input_scheduling_policy
825 0 : .map(|p| serde_json::to_string(&p).unwrap()),
826 0 : generation_pageserver: input_generation_pageserver,
827 0 : };
828 0 :
829 0 : query.set(update).execute(conn).await?;
830 :
831 0 : Ok(())
832 0 : })
833 0 : })
834 0 : .await?;
835 :
836 0 : Ok(())
837 0 : }
838 :
839 : /// Note that passing None for a shard clears the preferred AZ (rather than leaving it unmodified)
840 0 : pub(crate) async fn set_tenant_shard_preferred_azs(
841 0 : &self,
842 0 : preferred_azs: Vec<(TenantShardId, Option<AvailabilityZone>)>,
843 0 : ) -> DatabaseResult<Vec<(TenantShardId, Option<AvailabilityZone>)>> {
844 : use crate::schema::tenant_shards::dsl::*;
845 :
846 0 : let preferred_azs = preferred_azs.as_slice();
847 0 : self.with_measured_conn(DatabaseOperation::SetPreferredAzs, move |conn| {
848 0 : Box::pin(async move {
849 0 : let mut shards_updated = Vec::default();
850 :
851 0 : for (tenant_shard_id, preferred_az) in preferred_azs.iter() {
852 0 : let updated = diesel::update(tenant_shards)
853 0 : .filter(tenant_id.eq(tenant_shard_id.tenant_id.to_string()))
854 0 : .filter(shard_number.eq(tenant_shard_id.shard_number.0 as i32))
855 0 : .filter(shard_count.eq(tenant_shard_id.shard_count.literal() as i32))
856 0 : .set(preferred_az_id.eq(preferred_az.as_ref().map(|az| az.0.clone())))
857 0 : .execute(conn)
858 0 : .await?;
859 :
860 0 : if updated == 1 {
861 0 : shards_updated.push((*tenant_shard_id, preferred_az.clone()));
862 0 : }
863 : }
864 :
865 0 : Ok(shards_updated)
866 0 : })
867 0 : })
868 0 : .await
869 0 : }
870 :
871 0 : pub(crate) async fn detach(&self, tenant_shard_id: TenantShardId) -> anyhow::Result<()> {
872 : use crate::schema::tenant_shards::dsl::*;
873 0 : self.with_measured_conn(DatabaseOperation::Detach, move |conn| {
874 0 : Box::pin(async move {
875 0 : let updated = diesel::update(tenant_shards)
876 0 : .filter(tenant_id.eq(tenant_shard_id.tenant_id.to_string()))
877 0 : .filter(shard_number.eq(tenant_shard_id.shard_number.0 as i32))
878 0 : .filter(shard_count.eq(tenant_shard_id.shard_count.literal() as i32))
879 0 : .set((
880 0 : generation_pageserver.eq(Option::<i64>::None),
881 0 : placement_policy
882 0 : .eq(serde_json::to_string(&PlacementPolicy::Detached).unwrap()),
883 0 : ))
884 0 : .execute(conn)
885 0 : .await?;
886 :
887 0 : Ok(updated)
888 0 : })
889 0 : })
890 0 : .await?;
891 :
892 0 : Ok(())
893 0 : }
894 :
895 : // When we start shard splitting, we must durably mark the tenant so that
896 : // on restart, we know that we must go through recovery.
897 : //
898 : // We create the child shards here, so that they will be available for increment_generation calls
899 : // if some pageserver holding a child shard needs to restart before the overall tenant split is complete.
900 0 : pub(crate) async fn begin_shard_split(
901 0 : &self,
902 0 : old_shard_count: ShardCount,
903 0 : split_tenant_id: TenantId,
904 0 : parent_to_children: Vec<(TenantShardId, Vec<TenantShardPersistence>)>,
905 0 : ) -> DatabaseResult<()> {
906 : use crate::schema::tenant_shards::dsl::*;
907 0 : let parent_to_children = parent_to_children.as_slice();
908 0 : self.with_measured_conn(DatabaseOperation::BeginShardSplit, move |conn| {
909 0 : Box::pin(async move {
910 : // Mark parent shards as splitting
911 :
912 0 : let updated = diesel::update(tenant_shards)
913 0 : .filter(tenant_id.eq(split_tenant_id.to_string()))
914 0 : .filter(shard_count.eq(old_shard_count.literal() as i32))
915 0 : .set((splitting.eq(1),))
916 0 : .execute(conn).await?;
917 0 : if u8::try_from(updated)
918 0 : .map_err(|_| DatabaseError::Logical(
919 0 : format!("Overflow existing shard count {} while splitting", updated))
920 0 : )? != old_shard_count.count() {
921 : // Perhaps a deletion or another split raced with this attempt to split, mutating
922 : // the parent shards that we intend to split. In this case the split request should fail.
923 0 : return Err(DatabaseError::Logical(
924 0 : format!("Unexpected existing shard count {updated} when preparing tenant for split (expected {})", old_shard_count.count())
925 0 : ));
926 0 : }
927 0 :
928 0 : // FIXME: spurious clone to sidestep closure move rules
929 0 : let parent_to_children = parent_to_children.to_vec();
930 :
931 : // Insert child shards
932 0 : for (parent_shard_id, children) in parent_to_children {
933 0 : let mut parent = crate::schema::tenant_shards::table
934 0 : .filter(tenant_id.eq(parent_shard_id.tenant_id.to_string()))
935 0 : .filter(shard_number.eq(parent_shard_id.shard_number.0 as i32))
936 0 : .filter(shard_count.eq(parent_shard_id.shard_count.literal() as i32))
937 0 : .load::<TenantShardPersistence>(conn).await?;
938 0 : let parent = if parent.len() != 1 {
939 0 : return Err(DatabaseError::Logical(format!(
940 0 : "Parent shard {parent_shard_id} not found"
941 0 : )));
942 : } else {
943 0 : parent.pop().unwrap()
944 : };
945 0 : for mut shard in children {
946 : // Carry the parent's generation into the child
947 0 : shard.generation = parent.generation;
948 0 :
949 0 : debug_assert!(shard.splitting == SplitState::Splitting);
950 0 : diesel::insert_into(tenant_shards)
951 0 : .values(shard)
952 0 : .execute(conn).await?;
953 : }
954 : }
955 :
956 0 : Ok(())
957 0 : })
958 0 : })
959 0 : .await
960 0 : }
961 :
962 : // When we finish shard splitting, we must atomically clean up the old shards
963 : // and insert the new shards, and clear the splitting marker.
964 0 : pub(crate) async fn complete_shard_split(
965 0 : &self,
966 0 : split_tenant_id: TenantId,
967 0 : old_shard_count: ShardCount,
968 0 : ) -> DatabaseResult<()> {
969 : use crate::schema::tenant_shards::dsl::*;
970 0 : self.with_measured_conn(DatabaseOperation::CompleteShardSplit, move |conn| {
971 0 : Box::pin(async move {
972 0 : // Drop parent shards
973 0 : diesel::delete(tenant_shards)
974 0 : .filter(tenant_id.eq(split_tenant_id.to_string()))
975 0 : .filter(shard_count.eq(old_shard_count.literal() as i32))
976 0 : .execute(conn)
977 0 : .await?;
978 :
979 : // Clear sharding flag
980 0 : let updated = diesel::update(tenant_shards)
981 0 : .filter(tenant_id.eq(split_tenant_id.to_string()))
982 0 : .set((splitting.eq(0),))
983 0 : .execute(conn)
984 0 : .await?;
985 0 : debug_assert!(updated > 0);
986 :
987 0 : Ok(())
988 0 : })
989 0 : })
990 0 : .await
991 0 : }
992 :
993 : /// Used when the remote part of a shard split failed: we will revert the database state to have only
994 : /// the parent shards, with SplitState::Idle.
995 0 : pub(crate) async fn abort_shard_split(
996 0 : &self,
997 0 : split_tenant_id: TenantId,
998 0 : new_shard_count: ShardCount,
999 0 : ) -> DatabaseResult<AbortShardSplitStatus> {
1000 : use crate::schema::tenant_shards::dsl::*;
1001 0 : self.with_measured_conn(DatabaseOperation::AbortShardSplit, move |conn| {
1002 0 : Box::pin(async move {
1003 : // Clear the splitting state on parent shards
1004 0 : let updated = diesel::update(tenant_shards)
1005 0 : .filter(tenant_id.eq(split_tenant_id.to_string()))
1006 0 : .filter(shard_count.ne(new_shard_count.literal() as i32))
1007 0 : .set((splitting.eq(0),))
1008 0 : .execute(conn)
1009 0 : .await?;
1010 :
1011 : // Parent shards are already gone: we cannot abort.
1012 0 : if updated == 0 {
1013 0 : return Ok(AbortShardSplitStatus::Complete);
1014 0 : }
1015 0 :
1016 0 : // Sanity check: if parent shards were present, their cardinality should
1017 0 : // be less than the number of child shards.
1018 0 : if updated >= new_shard_count.count() as usize {
1019 0 : return Err(DatabaseError::Logical(format!(
1020 0 : "Unexpected parent shard count {updated} while aborting split to \
1021 0 : count {new_shard_count:?} on tenant {split_tenant_id}"
1022 0 : )));
1023 0 : }
1024 0 :
1025 0 : // Erase child shards
1026 0 : diesel::delete(tenant_shards)
1027 0 : .filter(tenant_id.eq(split_tenant_id.to_string()))
1028 0 : .filter(shard_count.eq(new_shard_count.literal() as i32))
1029 0 : .execute(conn)
1030 0 : .await?;
1031 :
1032 0 : Ok(AbortShardSplitStatus::Aborted)
1033 0 : })
1034 0 : })
1035 0 : .await
1036 0 : }
1037 :
1038 : /// Stores all the latest metadata health updates durably. Updates existing entry on conflict.
1039 : ///
1040 : /// **Correctness:** `metadata_health_updates` should all belong the tenant shards managed by the storage controller.
1041 : #[allow(dead_code)]
1042 0 : pub(crate) async fn update_metadata_health_records(
1043 0 : &self,
1044 0 : healthy_records: Vec<MetadataHealthPersistence>,
1045 0 : unhealthy_records: Vec<MetadataHealthPersistence>,
1046 0 : now: chrono::DateTime<chrono::Utc>,
1047 0 : ) -> DatabaseResult<()> {
1048 : use crate::schema::metadata_health::dsl::*;
1049 :
1050 0 : let healthy_records = healthy_records.as_slice();
1051 0 : let unhealthy_records = unhealthy_records.as_slice();
1052 0 : self.with_measured_conn(DatabaseOperation::UpdateMetadataHealth, move |conn| {
1053 0 : Box::pin(async move {
1054 0 : diesel::insert_into(metadata_health)
1055 0 : .values(healthy_records)
1056 0 : .on_conflict((tenant_id, shard_number, shard_count))
1057 0 : .do_update()
1058 0 : .set((healthy.eq(true), last_scrubbed_at.eq(now)))
1059 0 : .execute(conn)
1060 0 : .await?;
1061 :
1062 0 : diesel::insert_into(metadata_health)
1063 0 : .values(unhealthy_records)
1064 0 : .on_conflict((tenant_id, shard_number, shard_count))
1065 0 : .do_update()
1066 0 : .set((healthy.eq(false), last_scrubbed_at.eq(now)))
1067 0 : .execute(conn)
1068 0 : .await?;
1069 0 : Ok(())
1070 0 : })
1071 0 : })
1072 0 : .await
1073 0 : }
1074 :
1075 : /// Lists all the metadata health records.
1076 : #[allow(dead_code)]
1077 0 : pub(crate) async fn list_metadata_health_records(
1078 0 : &self,
1079 0 : ) -> DatabaseResult<Vec<MetadataHealthPersistence>> {
1080 0 : self.with_measured_conn(DatabaseOperation::ListMetadataHealth, move |conn| {
1081 0 : Box::pin(async {
1082 0 : Ok(crate::schema::metadata_health::table
1083 0 : .load::<MetadataHealthPersistence>(conn)
1084 0 : .await?)
1085 0 : })
1086 0 : })
1087 0 : .await
1088 0 : }
1089 :
1090 : /// Lists all the metadata health records that is unhealthy.
1091 : #[allow(dead_code)]
1092 0 : pub(crate) async fn list_unhealthy_metadata_health_records(
1093 0 : &self,
1094 0 : ) -> DatabaseResult<Vec<MetadataHealthPersistence>> {
1095 : use crate::schema::metadata_health::dsl::*;
1096 0 : self.with_measured_conn(
1097 0 : DatabaseOperation::ListMetadataHealthUnhealthy,
1098 0 : move |conn| {
1099 0 : Box::pin(async {
1100 0 : DatabaseResult::Ok(
1101 0 : crate::schema::metadata_health::table
1102 0 : .filter(healthy.eq(false))
1103 0 : .load::<MetadataHealthPersistence>(conn)
1104 0 : .await?,
1105 : )
1106 0 : })
1107 0 : },
1108 0 : )
1109 0 : .await
1110 0 : }
1111 :
1112 : /// Lists all the metadata health records that have not been updated since an `earlier` time.
1113 : #[allow(dead_code)]
1114 0 : pub(crate) async fn list_outdated_metadata_health_records(
1115 0 : &self,
1116 0 : earlier: chrono::DateTime<chrono::Utc>,
1117 0 : ) -> DatabaseResult<Vec<MetadataHealthPersistence>> {
1118 : use crate::schema::metadata_health::dsl::*;
1119 :
1120 0 : self.with_measured_conn(DatabaseOperation::ListMetadataHealthOutdated, move |conn| {
1121 0 : Box::pin(async move {
1122 0 : let query = metadata_health.filter(last_scrubbed_at.lt(earlier));
1123 0 : let res = query.load::<MetadataHealthPersistence>(conn).await?;
1124 :
1125 0 : Ok(res)
1126 0 : })
1127 0 : })
1128 0 : .await
1129 0 : }
1130 :
1131 : /// Get the current entry from the `leader` table if one exists.
1132 : /// It is an error for the table to contain more than one entry.
1133 0 : pub(crate) async fn get_leader(&self) -> DatabaseResult<Option<ControllerPersistence>> {
1134 0 : let mut leader: Vec<ControllerPersistence> = self
1135 0 : .with_measured_conn(DatabaseOperation::GetLeader, move |conn| {
1136 0 : Box::pin(async move {
1137 0 : Ok(crate::schema::controllers::table
1138 0 : .load::<ControllerPersistence>(conn)
1139 0 : .await?)
1140 0 : })
1141 0 : })
1142 0 : .await?;
1143 :
1144 0 : if leader.len() > 1 {
1145 0 : return Err(DatabaseError::Logical(format!(
1146 0 : "More than one entry present in the leader table: {leader:?}"
1147 0 : )));
1148 0 : }
1149 0 :
1150 0 : Ok(leader.pop())
1151 0 : }
1152 :
1153 : /// Update the new leader with compare-exchange semantics. If `prev` does not
1154 : /// match the current leader entry, then the update is treated as a failure.
1155 : /// When `prev` is not specified, the update is forced.
1156 0 : pub(crate) async fn update_leader(
1157 0 : &self,
1158 0 : prev: Option<ControllerPersistence>,
1159 0 : new: ControllerPersistence,
1160 0 : ) -> DatabaseResult<()> {
1161 : use crate::schema::controllers::dsl::*;
1162 :
1163 0 : let updated = self
1164 0 : .with_measured_conn(DatabaseOperation::UpdateLeader, move |conn| {
1165 0 : let prev = prev.clone();
1166 0 : let new = new.clone();
1167 0 : Box::pin(async move {
1168 0 : let updated = match &prev {
1169 0 : Some(prev) => {
1170 0 : diesel::update(controllers)
1171 0 : .filter(address.eq(prev.address.clone()))
1172 0 : .filter(started_at.eq(prev.started_at))
1173 0 : .set((
1174 0 : address.eq(new.address.clone()),
1175 0 : started_at.eq(new.started_at),
1176 0 : ))
1177 0 : .execute(conn)
1178 0 : .await?
1179 : }
1180 : None => {
1181 0 : diesel::insert_into(controllers)
1182 0 : .values(new.clone())
1183 0 : .execute(conn)
1184 0 : .await?
1185 : }
1186 : };
1187 :
1188 0 : Ok(updated)
1189 0 : })
1190 0 : })
1191 0 : .await?;
1192 :
1193 0 : if updated == 0 {
1194 0 : return Err(DatabaseError::Logical(
1195 0 : "Leader table update failed".to_string(),
1196 0 : ));
1197 0 : }
1198 0 :
1199 0 : Ok(())
1200 0 : }
1201 :
1202 : /// At startup, populate the list of nodes which our shards may be placed on
1203 0 : pub(crate) async fn list_safekeepers(&self) -> DatabaseResult<Vec<SafekeeperPersistence>> {
1204 0 : let safekeepers: Vec<SafekeeperPersistence> = self
1205 0 : .with_measured_conn(DatabaseOperation::ListNodes, move |conn| {
1206 0 : Box::pin(async move {
1207 0 : Ok(crate::schema::safekeepers::table
1208 0 : .load::<SafekeeperPersistence>(conn)
1209 0 : .await?)
1210 0 : })
1211 0 : })
1212 0 : .await?;
1213 :
1214 0 : tracing::info!("list_safekeepers: loaded {} nodes", safekeepers.len());
1215 :
1216 0 : Ok(safekeepers)
1217 0 : }
1218 :
1219 0 : pub(crate) async fn safekeeper_upsert(
1220 0 : &self,
1221 0 : record: SafekeeperUpsert,
1222 0 : ) -> Result<(), DatabaseError> {
1223 : use crate::schema::safekeepers::dsl::*;
1224 :
1225 0 : self.with_conn(move |conn| {
1226 0 : let record = record.clone();
1227 0 : Box::pin(async move {
1228 0 : let bind = record
1229 0 : .as_insert_or_update()
1230 0 : .map_err(|e| DatabaseError::Logical(format!("{e}")))?;
1231 :
1232 0 : let inserted_updated = diesel::insert_into(safekeepers)
1233 0 : .values(&bind)
1234 0 : .on_conflict(id)
1235 0 : .do_update()
1236 0 : .set(&bind)
1237 0 : .execute(conn)
1238 0 : .await?;
1239 :
1240 0 : if inserted_updated != 1 {
1241 0 : return Err(DatabaseError::Logical(format!(
1242 0 : "unexpected number of rows ({})",
1243 0 : inserted_updated
1244 0 : )));
1245 0 : }
1246 0 :
1247 0 : Ok(())
1248 0 : })
1249 0 : })
1250 0 : .await
1251 0 : }
1252 :
1253 0 : pub(crate) async fn set_safekeeper_scheduling_policy(
1254 0 : &self,
1255 0 : id_: i64,
1256 0 : scheduling_policy_: SkSchedulingPolicy,
1257 0 : ) -> Result<(), DatabaseError> {
1258 : use crate::schema::safekeepers::dsl::*;
1259 :
1260 0 : self.with_conn(move |conn| {
1261 0 : Box::pin(async move {
1262 0 : #[derive(Insertable, AsChangeset)]
1263 : #[diesel(table_name = crate::schema::safekeepers)]
1264 : struct UpdateSkSchedulingPolicy<'a> {
1265 : id: i64,
1266 : scheduling_policy: &'a str,
1267 : }
1268 0 : let scheduling_policy_ = String::from(scheduling_policy_);
1269 :
1270 0 : let rows_affected = diesel::update(safekeepers.filter(id.eq(id_)))
1271 0 : .set(scheduling_policy.eq(scheduling_policy_))
1272 0 : .execute(conn)
1273 0 : .await?;
1274 :
1275 0 : if rows_affected != 1 {
1276 0 : return Err(DatabaseError::Logical(format!(
1277 0 : "unexpected number of rows ({rows_affected})",
1278 0 : )));
1279 0 : }
1280 0 :
1281 0 : Ok(())
1282 0 : })
1283 0 : })
1284 0 : .await
1285 0 : }
1286 : }
1287 :
1288 0 : pub(crate) fn load_certs() -> anyhow::Result<Arc<rustls::RootCertStore>> {
1289 0 : let der_certs = rustls_native_certs::load_native_certs();
1290 0 :
1291 0 : if !der_certs.errors.is_empty() {
1292 0 : anyhow::bail!("could not parse certificates: {:?}", der_certs.errors);
1293 0 : }
1294 0 :
1295 0 : let mut store = rustls::RootCertStore::empty();
1296 0 : store.add_parsable_certificates(der_certs.certs);
1297 0 : Ok(Arc::new(store))
1298 0 : }
1299 :
1300 : #[derive(Debug)]
1301 : /// A verifier that accepts all certificates (but logs an error still)
1302 : struct AcceptAll(Arc<WebPkiServerVerifier>);
1303 : impl ServerCertVerifier for AcceptAll {
1304 0 : fn verify_server_cert(
1305 0 : &self,
1306 0 : end_entity: &rustls::pki_types::CertificateDer<'_>,
1307 0 : intermediates: &[rustls::pki_types::CertificateDer<'_>],
1308 0 : server_name: &rustls::pki_types::ServerName<'_>,
1309 0 : ocsp_response: &[u8],
1310 0 : now: rustls::pki_types::UnixTime,
1311 0 : ) -> Result<ServerCertVerified, rustls::Error> {
1312 0 : let r =
1313 0 : self.0
1314 0 : .verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now);
1315 0 : if let Err(err) = r {
1316 0 : tracing::info!(
1317 : ?server_name,
1318 0 : "ignoring db connection TLS validation error: {err:?}"
1319 : );
1320 0 : return Ok(ServerCertVerified::assertion());
1321 0 : }
1322 0 : r
1323 0 : }
1324 0 : fn verify_tls12_signature(
1325 0 : &self,
1326 0 : message: &[u8],
1327 0 : cert: &rustls::pki_types::CertificateDer<'_>,
1328 0 : dss: &rustls::DigitallySignedStruct,
1329 0 : ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
1330 0 : self.0.verify_tls12_signature(message, cert, dss)
1331 0 : }
1332 0 : fn verify_tls13_signature(
1333 0 : &self,
1334 0 : message: &[u8],
1335 0 : cert: &rustls::pki_types::CertificateDer<'_>,
1336 0 : dss: &rustls::DigitallySignedStruct,
1337 0 : ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
1338 0 : self.0.verify_tls13_signature(message, cert, dss)
1339 0 : }
1340 0 : fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
1341 0 : self.0.supported_verify_schemes()
1342 0 : }
1343 : }
1344 :
1345 : /// Loads the root certificates and constructs a client config suitable for connecting.
1346 : /// This function is blocking.
1347 0 : fn client_config_with_root_certs() -> anyhow::Result<rustls::ClientConfig> {
1348 0 : let client_config =
1349 0 : rustls::ClientConfig::builder_with_provider(Arc::new(ring::default_provider()))
1350 0 : .with_safe_default_protocol_versions()
1351 0 : .expect("ring should support the default protocol versions");
1352 : static DO_CERT_CHECKS: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1353 0 : let do_cert_checks =
1354 0 : DO_CERT_CHECKS.get_or_init(|| std::env::var("STORCON_DB_CERT_CHECKS").is_ok());
1355 0 : Ok(if *do_cert_checks {
1356 0 : client_config
1357 0 : .with_root_certificates(load_certs()?)
1358 0 : .with_no_client_auth()
1359 : } else {
1360 0 : let verifier = AcceptAll(
1361 : WebPkiServerVerifier::builder_with_provider(
1362 0 : load_certs()?,
1363 0 : Arc::new(ring::default_provider()),
1364 0 : )
1365 0 : .build()?,
1366 : );
1367 0 : client_config
1368 0 : .dangerous()
1369 0 : .with_custom_certificate_verifier(Arc::new(verifier))
1370 0 : .with_no_client_auth()
1371 : })
1372 0 : }
1373 :
1374 0 : fn establish_connection_rustls(config: &str) -> BoxFuture<ConnectionResult<AsyncPgConnection>> {
1375 0 : let fut = async {
1376 : // We first set up the way we want rustls to work.
1377 0 : let rustls_config = client_config_with_root_certs()
1378 0 : .map_err(|err| ConnectionError::BadConnection(format!("{err:?}")))?;
1379 0 : let tls = tokio_postgres_rustls::MakeRustlsConnect::new(rustls_config);
1380 0 : let (client, conn) = tokio_postgres::connect(config, tls)
1381 0 : .await
1382 0 : .map_err(|e| ConnectionError::BadConnection(e.to_string()))?;
1383 :
1384 0 : AsyncPgConnection::try_from_client_and_connection(client, conn).await
1385 0 : };
1386 0 : fut.boxed()
1387 0 : }
1388 :
1389 : #[cfg_attr(test, test)]
1390 1 : fn test_config_debug_censors_password() {
1391 1 : let has_pw =
1392 1 : "host=/var/lib/postgresql,localhost port=1234 user=specialuser password='NOT ALLOWED TAG'";
1393 1 : let has_pw_cfg = has_pw.parse::<tokio_postgres::Config>().unwrap();
1394 1 : assert!(format!("{has_pw_cfg:?}").contains("specialuser"));
1395 : // Ensure that the password is not leaked by the debug impl
1396 1 : assert!(!format!("{has_pw_cfg:?}").contains("NOT ALLOWED TAG"));
1397 1 : }
1398 :
1399 0 : fn log_postgres_connstr_info(config_str: &str) -> anyhow::Result<()> {
1400 0 : let config = config_str
1401 0 : .parse::<tokio_postgres::Config>()
1402 0 : .map_err(|_e| anyhow::anyhow!("Couldn't parse config str"))?;
1403 : // We use debug formatting here, and use a unit test to ensure that we don't leak the password.
1404 : // To make extra sure the test gets ran, run it every time the function is called
1405 : // (this is rather cold code, we can afford it).
1406 : #[cfg(not(test))]
1407 0 : test_config_debug_censors_password();
1408 0 : tracing::info!("database connection config: {config:?}");
1409 0 : Ok(())
1410 0 : }
1411 :
1412 : /// Parts of [`crate::tenant_shard::TenantShard`] that are stored durably
1413 : #[derive(
1414 0 : QueryableByName, Queryable, Selectable, Insertable, Serialize, Deserialize, Clone, Eq, PartialEq,
1415 : )]
1416 : #[diesel(table_name = crate::schema::tenant_shards)]
1417 : pub(crate) struct TenantShardPersistence {
1418 : #[serde(default)]
1419 : pub(crate) tenant_id: String,
1420 : #[serde(default)]
1421 : pub(crate) shard_number: i32,
1422 : #[serde(default)]
1423 : pub(crate) shard_count: i32,
1424 : #[serde(default)]
1425 : pub(crate) shard_stripe_size: i32,
1426 :
1427 : // Latest generation number: next time we attach, increment this
1428 : // and use the incremented number when attaching.
1429 : //
1430 : // Generation is only None when first onboarding a tenant, where it may
1431 : // be in PlacementPolicy::Secondary and therefore have no valid generation state.
1432 : pub(crate) generation: Option<i32>,
1433 :
1434 : // Currently attached pageserver
1435 : #[serde(rename = "pageserver")]
1436 : pub(crate) generation_pageserver: Option<i64>,
1437 :
1438 : #[serde(default)]
1439 : pub(crate) placement_policy: String,
1440 : #[serde(default)]
1441 : pub(crate) splitting: SplitState,
1442 : #[serde(default)]
1443 : pub(crate) config: String,
1444 : #[serde(default)]
1445 : pub(crate) scheduling_policy: String,
1446 :
1447 : // Hint that we should attempt to schedule this tenant shard the given
1448 : // availability zone in order to minimise the chances of cross-AZ communication
1449 : // with compute.
1450 : pub(crate) preferred_az_id: Option<String>,
1451 : }
1452 :
1453 : impl TenantShardPersistence {
1454 0 : pub(crate) fn get_shard_identity(&self) -> Result<ShardIdentity, ShardConfigError> {
1455 0 : if self.shard_count == 0 {
1456 0 : Ok(ShardIdentity::unsharded())
1457 : } else {
1458 0 : Ok(ShardIdentity::new(
1459 0 : ShardNumber(self.shard_number as u8),
1460 0 : ShardCount::new(self.shard_count as u8),
1461 0 : ShardStripeSize(self.shard_stripe_size as u32),
1462 0 : )?)
1463 : }
1464 0 : }
1465 :
1466 0 : pub(crate) fn get_tenant_shard_id(&self) -> Result<TenantShardId, hex::FromHexError> {
1467 0 : Ok(TenantShardId {
1468 0 : tenant_id: TenantId::from_str(self.tenant_id.as_str())?,
1469 0 : shard_number: ShardNumber(self.shard_number as u8),
1470 0 : shard_count: ShardCount::new(self.shard_count as u8),
1471 : })
1472 0 : }
1473 : }
1474 :
1475 : /// Parts of [`crate::node::Node`] that are stored durably
1476 0 : #[derive(Serialize, Deserialize, Queryable, Selectable, Insertable, Eq, PartialEq)]
1477 : #[diesel(table_name = crate::schema::nodes)]
1478 : pub(crate) struct NodePersistence {
1479 : pub(crate) node_id: i64,
1480 : pub(crate) scheduling_policy: String,
1481 : pub(crate) listen_http_addr: String,
1482 : pub(crate) listen_http_port: i32,
1483 : pub(crate) listen_pg_addr: String,
1484 : pub(crate) listen_pg_port: i32,
1485 : pub(crate) availability_zone_id: String,
1486 : pub(crate) listen_https_port: Option<i32>,
1487 : }
1488 :
1489 : /// Tenant metadata health status that are stored durably.
1490 0 : #[derive(Queryable, Selectable, Insertable, Serialize, Deserialize, Clone, Eq, PartialEq)]
1491 : #[diesel(table_name = crate::schema::metadata_health)]
1492 : pub(crate) struct MetadataHealthPersistence {
1493 : #[serde(default)]
1494 : pub(crate) tenant_id: String,
1495 : #[serde(default)]
1496 : pub(crate) shard_number: i32,
1497 : #[serde(default)]
1498 : pub(crate) shard_count: i32,
1499 :
1500 : pub(crate) healthy: bool,
1501 : pub(crate) last_scrubbed_at: chrono::DateTime<chrono::Utc>,
1502 : }
1503 :
1504 : impl MetadataHealthPersistence {
1505 0 : pub fn new(
1506 0 : tenant_shard_id: TenantShardId,
1507 0 : healthy: bool,
1508 0 : last_scrubbed_at: chrono::DateTime<chrono::Utc>,
1509 0 : ) -> Self {
1510 0 : let tenant_id = tenant_shard_id.tenant_id.to_string();
1511 0 : let shard_number = tenant_shard_id.shard_number.0 as i32;
1512 0 : let shard_count = tenant_shard_id.shard_count.literal() as i32;
1513 0 :
1514 0 : MetadataHealthPersistence {
1515 0 : tenant_id,
1516 0 : shard_number,
1517 0 : shard_count,
1518 0 : healthy,
1519 0 : last_scrubbed_at,
1520 0 : }
1521 0 : }
1522 :
1523 : #[allow(dead_code)]
1524 0 : pub(crate) fn get_tenant_shard_id(&self) -> Result<TenantShardId, hex::FromHexError> {
1525 0 : Ok(TenantShardId {
1526 0 : tenant_id: TenantId::from_str(self.tenant_id.as_str())?,
1527 0 : shard_number: ShardNumber(self.shard_number as u8),
1528 0 : shard_count: ShardCount::new(self.shard_count as u8),
1529 : })
1530 0 : }
1531 : }
1532 :
1533 : impl From<MetadataHealthPersistence> for MetadataHealthRecord {
1534 0 : fn from(value: MetadataHealthPersistence) -> Self {
1535 0 : MetadataHealthRecord {
1536 0 : tenant_shard_id: value
1537 0 : .get_tenant_shard_id()
1538 0 : .expect("stored tenant id should be valid"),
1539 0 : healthy: value.healthy,
1540 0 : last_scrubbed_at: value.last_scrubbed_at,
1541 0 : }
1542 0 : }
1543 : }
1544 :
1545 : #[derive(
1546 0 : Serialize, Deserialize, Queryable, Selectable, Insertable, Eq, PartialEq, Debug, Clone,
1547 : )]
1548 : #[diesel(table_name = crate::schema::controllers)]
1549 : pub(crate) struct ControllerPersistence {
1550 : pub(crate) address: String,
1551 : pub(crate) started_at: chrono::DateTime<chrono::Utc>,
1552 : }
1553 :
1554 : // What we store in the database
1555 0 : #[derive(Serialize, Deserialize, Queryable, Selectable, Eq, PartialEq, Debug, Clone)]
1556 : #[diesel(table_name = crate::schema::safekeepers)]
1557 : pub(crate) struct SafekeeperPersistence {
1558 : pub(crate) id: i64,
1559 : pub(crate) region_id: String,
1560 : /// 1 is special, it means just created (not currently posted to storcon).
1561 : /// Zero or negative is not really expected.
1562 : /// Otherwise the number from `release-$(number_of_commits_on_branch)` tag.
1563 : pub(crate) version: i64,
1564 : pub(crate) host: String,
1565 : pub(crate) port: i32,
1566 : pub(crate) http_port: i32,
1567 : pub(crate) availability_zone_id: String,
1568 : pub(crate) scheduling_policy: String,
1569 : }
1570 :
1571 : impl SafekeeperPersistence {
1572 0 : pub(crate) fn from_upsert(
1573 0 : upsert: SafekeeperUpsert,
1574 0 : scheduling_policy: SkSchedulingPolicy,
1575 0 : ) -> Self {
1576 0 : crate::persistence::SafekeeperPersistence {
1577 0 : id: upsert.id,
1578 0 : region_id: upsert.region_id,
1579 0 : version: upsert.version,
1580 0 : host: upsert.host,
1581 0 : port: upsert.port,
1582 0 : http_port: upsert.http_port,
1583 0 : availability_zone_id: upsert.availability_zone_id,
1584 0 : scheduling_policy: String::from(scheduling_policy),
1585 0 : }
1586 0 : }
1587 0 : pub(crate) fn as_describe_response(&self) -> Result<SafekeeperDescribeResponse, DatabaseError> {
1588 0 : let scheduling_policy =
1589 0 : SkSchedulingPolicy::from_str(&self.scheduling_policy).map_err(|e| {
1590 0 : DatabaseError::Logical(format!("can't construct SkSchedulingPolicy: {e:?}"))
1591 0 : })?;
1592 0 : Ok(SafekeeperDescribeResponse {
1593 0 : id: NodeId(self.id as u64),
1594 0 : region_id: self.region_id.clone(),
1595 0 : version: self.version,
1596 0 : host: self.host.clone(),
1597 0 : port: self.port,
1598 0 : http_port: self.http_port,
1599 0 : availability_zone_id: self.availability_zone_id.clone(),
1600 0 : scheduling_policy,
1601 0 : })
1602 0 : }
1603 : }
1604 :
1605 : /// What we expect from the upsert http api
1606 0 : #[derive(Serialize, Deserialize, Eq, PartialEq, Debug, Clone)]
1607 : pub(crate) struct SafekeeperUpsert {
1608 : pub(crate) id: i64,
1609 : pub(crate) region_id: String,
1610 : /// 1 is special, it means just created (not currently posted to storcon).
1611 : /// Zero or negative is not really expected.
1612 : /// Otherwise the number from `release-$(number_of_commits_on_branch)` tag.
1613 : pub(crate) version: i64,
1614 : pub(crate) host: String,
1615 : pub(crate) port: i32,
1616 : /// The active flag will not be stored in the database and will be ignored.
1617 : pub(crate) active: Option<bool>,
1618 : pub(crate) http_port: i32,
1619 : pub(crate) availability_zone_id: String,
1620 : }
1621 :
1622 : impl SafekeeperUpsert {
1623 0 : fn as_insert_or_update(&self) -> anyhow::Result<InsertUpdateSafekeeper<'_>> {
1624 0 : if self.version < 0 {
1625 0 : anyhow::bail!("negative version: {}", self.version);
1626 0 : }
1627 0 : Ok(InsertUpdateSafekeeper {
1628 0 : id: self.id,
1629 0 : region_id: &self.region_id,
1630 0 : version: self.version,
1631 0 : host: &self.host,
1632 0 : port: self.port,
1633 0 : http_port: self.http_port,
1634 0 : availability_zone_id: &self.availability_zone_id,
1635 0 : // None means a wish to not update this column. We expose abilities to update it via other means.
1636 0 : scheduling_policy: None,
1637 0 : })
1638 0 : }
1639 : }
1640 :
1641 0 : #[derive(Insertable, AsChangeset)]
1642 : #[diesel(table_name = crate::schema::safekeepers)]
1643 : struct InsertUpdateSafekeeper<'a> {
1644 : id: i64,
1645 : region_id: &'a str,
1646 : version: i64,
1647 : host: &'a str,
1648 : port: i32,
1649 : http_port: i32,
1650 : availability_zone_id: &'a str,
1651 : scheduling_policy: Option<&'a str>,
1652 : }
|