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(
379 0 : &self,
380 0 : input_node_id: NodeId,
381 0 : input_scheduling: NodeSchedulingPolicy,
382 0 : ) -> DatabaseResult<()> {
383 : use crate::schema::nodes::dsl::*;
384 0 : let updated = self
385 0 : .with_measured_conn(DatabaseOperation::UpdateNode, move |conn| {
386 0 : Box::pin(async move {
387 0 : let updated = diesel::update(nodes)
388 0 : .filter(node_id.eq(input_node_id.0 as i64))
389 0 : .set((scheduling_policy.eq(String::from(input_scheduling)),))
390 0 : .execute(conn)
391 0 : .await?;
392 0 : Ok(updated)
393 0 : })
394 0 : })
395 0 : .await?;
396 :
397 0 : if updated != 1 {
398 0 : Err(DatabaseError::Logical(format!(
399 0 : "Node {node_id:?} not found for update",
400 0 : )))
401 : } else {
402 0 : Ok(())
403 : }
404 0 : }
405 :
406 : /// At startup, load the high level state for shards, such as their config + policy. This will
407 : /// be enriched at runtime with state discovered on pageservers.
408 : ///
409 : /// We exclude shards configured to be detached. During startup, if we see any attached locations
410 : /// for such shards, they will automatically be detached as 'orphans'.
411 0 : pub(crate) async fn load_active_tenant_shards(
412 0 : &self,
413 0 : ) -> DatabaseResult<Vec<TenantShardPersistence>> {
414 : use crate::schema::tenant_shards::dsl::*;
415 0 : self.with_measured_conn(DatabaseOperation::ListTenantShards, move |conn| {
416 0 : Box::pin(async move {
417 0 : let query = tenant_shards.filter(
418 0 : placement_policy.ne(serde_json::to_string(&PlacementPolicy::Detached).unwrap()),
419 0 : );
420 0 : let result = query.load::<TenantShardPersistence>(conn).await?;
421 :
422 0 : Ok(result)
423 0 : })
424 0 : })
425 0 : .await
426 0 : }
427 :
428 : /// When restoring a previously detached tenant into memory, load it from the database
429 0 : pub(crate) async fn load_tenant(
430 0 : &self,
431 0 : filter_tenant_id: TenantId,
432 0 : ) -> DatabaseResult<Vec<TenantShardPersistence>> {
433 : use crate::schema::tenant_shards::dsl::*;
434 0 : self.with_measured_conn(DatabaseOperation::LoadTenant, move |conn| {
435 0 : Box::pin(async move {
436 0 : let query = tenant_shards.filter(tenant_id.eq(filter_tenant_id.to_string()));
437 0 : let result = query.load::<TenantShardPersistence>(conn).await?;
438 :
439 0 : Ok(result)
440 0 : })
441 0 : })
442 0 : .await
443 0 : }
444 :
445 : /// Tenants must be persisted before we schedule them for the first time. This enables us
446 : /// to correctly retain generation monotonicity, and the externally provided placement policy & config.
447 0 : pub(crate) async fn insert_tenant_shards(
448 0 : &self,
449 0 : shards: Vec<TenantShardPersistence>,
450 0 : ) -> DatabaseResult<()> {
451 : use crate::schema::metadata_health;
452 : use crate::schema::tenant_shards;
453 :
454 0 : let now = chrono::Utc::now();
455 0 :
456 0 : let metadata_health_records = shards
457 0 : .iter()
458 0 : .map(|t| MetadataHealthPersistence {
459 0 : tenant_id: t.tenant_id.clone(),
460 0 : shard_number: t.shard_number,
461 0 : shard_count: t.shard_count,
462 0 : healthy: true,
463 0 : last_scrubbed_at: now,
464 0 : })
465 0 : .collect::<Vec<_>>();
466 0 :
467 0 : let shards = &shards;
468 0 : let metadata_health_records = &metadata_health_records;
469 0 : self.with_measured_conn(DatabaseOperation::InsertTenantShards, move |conn| {
470 0 : Box::pin(async move {
471 0 : diesel::insert_into(tenant_shards::table)
472 0 : .values(shards)
473 0 : .execute(conn)
474 0 : .await?;
475 :
476 0 : diesel::insert_into(metadata_health::table)
477 0 : .values(metadata_health_records)
478 0 : .execute(conn)
479 0 : .await?;
480 0 : Ok(())
481 0 : })
482 0 : })
483 0 : .await
484 0 : }
485 :
486 : /// Ordering: call this _after_ deleting the tenant on pageservers, but _before_ dropping state for
487 : /// the tenant from memory on this server.
488 0 : pub(crate) async fn delete_tenant(&self, del_tenant_id: TenantId) -> DatabaseResult<()> {
489 : use crate::schema::tenant_shards::dsl::*;
490 0 : self.with_measured_conn(DatabaseOperation::DeleteTenant, move |conn| {
491 0 : Box::pin(async move {
492 0 : // `metadata_health` status (if exists) is also deleted based on the cascade behavior.
493 0 : diesel::delete(tenant_shards)
494 0 : .filter(tenant_id.eq(del_tenant_id.to_string()))
495 0 : .execute(conn)
496 0 : .await?;
497 0 : Ok(())
498 0 : })
499 0 : })
500 0 : .await
501 0 : }
502 :
503 0 : pub(crate) async fn delete_node(&self, del_node_id: NodeId) -> DatabaseResult<()> {
504 : use crate::schema::nodes::dsl::*;
505 0 : self.with_measured_conn(DatabaseOperation::DeleteNode, move |conn| {
506 0 : Box::pin(async move {
507 0 : diesel::delete(nodes)
508 0 : .filter(node_id.eq(del_node_id.0 as i64))
509 0 : .execute(conn)
510 0 : .await?;
511 :
512 0 : Ok(())
513 0 : })
514 0 : })
515 0 : .await
516 0 : }
517 :
518 : /// When a tenant invokes the /re-attach API, this function is responsible for doing an efficient
519 : /// batched increment of the generations of all tenants whose generation_pageserver is equal to
520 : /// the node that called /re-attach.
521 : #[tracing::instrument(skip_all, fields(node_id))]
522 : pub(crate) async fn re_attach(
523 : &self,
524 : input_node_id: NodeId,
525 : ) -> DatabaseResult<HashMap<TenantShardId, Generation>> {
526 : use crate::schema::nodes::dsl::scheduling_policy;
527 : use crate::schema::nodes::dsl::*;
528 : use crate::schema::tenant_shards::dsl::*;
529 : let updated = self
530 0 : .with_measured_conn(DatabaseOperation::ReAttach, move |conn| {
531 0 : Box::pin(async move {
532 0 : let rows_updated = diesel::update(tenant_shards)
533 0 : .filter(generation_pageserver.eq(input_node_id.0 as i64))
534 0 : .set(generation.eq(generation + 1))
535 0 : .execute(conn)
536 0 : .await?;
537 :
538 0 : tracing::info!("Incremented {} tenants' generations", rows_updated);
539 :
540 : // TODO: UPDATE+SELECT in one query
541 :
542 0 : let updated = tenant_shards
543 0 : .filter(generation_pageserver.eq(input_node_id.0 as i64))
544 0 : .select(TenantShardPersistence::as_select())
545 0 : .load(conn)
546 0 : .await?;
547 :
548 : // If the node went through a drain and restart phase before re-attaching,
549 : // then reset it's node scheduling policy to active.
550 0 : diesel::update(nodes)
551 0 : .filter(node_id.eq(input_node_id.0 as i64))
552 0 : .filter(
553 0 : scheduling_policy
554 0 : .eq(String::from(NodeSchedulingPolicy::PauseForRestart))
555 0 : .or(scheduling_policy
556 0 : .eq(String::from(NodeSchedulingPolicy::Draining)))
557 0 : .or(scheduling_policy
558 0 : .eq(String::from(NodeSchedulingPolicy::Filling))),
559 0 : )
560 0 : .set(scheduling_policy.eq(String::from(NodeSchedulingPolicy::Active)))
561 0 : .execute(conn)
562 0 : .await?;
563 :
564 0 : Ok(updated)
565 0 : })
566 0 : })
567 : .await?;
568 :
569 : let mut result = HashMap::new();
570 : for tsp in updated {
571 : let tenant_shard_id = TenantShardId {
572 : tenant_id: TenantId::from_str(tsp.tenant_id.as_str())
573 0 : .map_err(|e| DatabaseError::Logical(format!("Malformed tenant id: {e}")))?,
574 : shard_number: ShardNumber(tsp.shard_number as u8),
575 : shard_count: ShardCount::new(tsp.shard_count as u8),
576 : };
577 :
578 : let Some(g) = tsp.generation else {
579 : // If the generation_pageserver column was non-NULL, then the generation column should also be non-NULL:
580 : // we only set generation_pageserver when setting generation.
581 : return Err(DatabaseError::Logical(
582 : "Generation should always be set after incrementing".to_string(),
583 : ));
584 : };
585 : result.insert(tenant_shard_id, Generation::new(g as u32));
586 : }
587 :
588 : Ok(result)
589 : }
590 :
591 : /// Reconciler calls this immediately before attaching to a new pageserver, to acquire a unique, monotonically
592 : /// advancing generation number. We also store the NodeId for which the generation was issued, so that in
593 : /// [`Self::re_attach`] we can do a bulk UPDATE on the generations for that node.
594 0 : pub(crate) async fn increment_generation(
595 0 : &self,
596 0 : tenant_shard_id: TenantShardId,
597 0 : node_id: NodeId,
598 0 : ) -> anyhow::Result<Generation> {
599 : use crate::schema::tenant_shards::dsl::*;
600 0 : let updated = self
601 0 : .with_measured_conn(DatabaseOperation::IncrementGeneration, move |conn| {
602 0 : Box::pin(async move {
603 0 : let updated = diesel::update(tenant_shards)
604 0 : .filter(tenant_id.eq(tenant_shard_id.tenant_id.to_string()))
605 0 : .filter(shard_number.eq(tenant_shard_id.shard_number.0 as i32))
606 0 : .filter(shard_count.eq(tenant_shard_id.shard_count.literal() as i32))
607 0 : .set((
608 0 : generation.eq(generation + 1),
609 0 : generation_pageserver.eq(node_id.0 as i64),
610 0 : ))
611 0 : // TODO: only returning() the generation column
612 0 : .returning(TenantShardPersistence::as_returning())
613 0 : .get_result(conn)
614 0 : .await?;
615 :
616 0 : Ok(updated)
617 0 : })
618 0 : })
619 0 : .await?;
620 :
621 : // Generation is always non-null in the rseult: if the generation column had been NULL, then we
622 : // should have experienced an SQL Confilict error while executing a query that tries to increment it.
623 0 : debug_assert!(updated.generation.is_some());
624 0 : let Some(g) = updated.generation else {
625 0 : return Err(DatabaseError::Logical(
626 0 : "Generation should always be set after incrementing".to_string(),
627 0 : )
628 0 : .into());
629 : };
630 :
631 0 : Ok(Generation::new(g as u32))
632 0 : }
633 :
634 : /// When we want to call out to the running shards for a tenant, e.g. during timeline CRUD operations,
635 : /// we need to know where the shard is attached, _and_ the generation, so that we can re-check the generation
636 : /// afterwards to confirm that our timeline CRUD operation is truly persistent (it must have happened in the
637 : /// latest generation)
638 : ///
639 : /// If the tenant doesn't exist, an empty vector is returned.
640 : ///
641 : /// Output is sorted by shard number
642 0 : pub(crate) async fn tenant_generations(
643 0 : &self,
644 0 : filter_tenant_id: TenantId,
645 0 : ) -> Result<Vec<ShardGenerationState>, DatabaseError> {
646 : use crate::schema::tenant_shards::dsl::*;
647 0 : let rows = self
648 0 : .with_measured_conn(DatabaseOperation::TenantGenerations, move |conn| {
649 0 : Box::pin(async move {
650 0 : let result = tenant_shards
651 0 : .filter(tenant_id.eq(filter_tenant_id.to_string()))
652 0 : .select(TenantShardPersistence::as_select())
653 0 : .order(shard_number)
654 0 : .load(conn)
655 0 : .await?;
656 0 : Ok(result)
657 0 : })
658 0 : })
659 0 : .await?;
660 :
661 0 : Ok(rows
662 0 : .into_iter()
663 0 : .map(|p| ShardGenerationState {
664 0 : tenant_shard_id: p
665 0 : .get_tenant_shard_id()
666 0 : .expect("Corrupt tenant shard id in database"),
667 0 : generation: p.generation.map(|g| Generation::new(g as u32)),
668 0 : generation_pageserver: p.generation_pageserver.map(|n| NodeId(n as u64)),
669 0 : })
670 0 : .collect())
671 0 : }
672 :
673 : /// Read the generation number of specific tenant shards
674 : ///
675 : /// Output is unsorted. Output may not include values for all inputs, if they are missing in the database.
676 0 : pub(crate) async fn shard_generations(
677 0 : &self,
678 0 : mut tenant_shard_ids: impl Iterator<Item = &TenantShardId>,
679 0 : ) -> Result<Vec<(TenantShardId, Option<Generation>)>, DatabaseError> {
680 0 : let mut rows = Vec::with_capacity(tenant_shard_ids.size_hint().0);
681 :
682 : // We will chunk our input to avoid composing arbitrarily long `IN` clauses. Typically we are
683 : // called with a single digit number of IDs, but in principle we could be called with tens
684 : // of thousands (all the shards on one pageserver) from the generation validation API.
685 0 : loop {
686 0 : // A modest hardcoded chunk size to handle typical cases in a single query but never generate particularly
687 0 : // large query strings.
688 0 : let chunk_ids = tenant_shard_ids.by_ref().take(32);
689 0 :
690 0 : // Compose a comma separated list of tuples for matching on (tenant_id, shard_number, shard_count)
691 0 : let in_clause = chunk_ids
692 0 : .map(|tsid| {
693 0 : format!(
694 0 : "('{}', {}, {})",
695 0 : tsid.tenant_id, tsid.shard_number.0, tsid.shard_count.0
696 0 : )
697 0 : })
698 0 : .join(",");
699 0 :
700 0 : // We are done when our iterator gives us nothing to filter on
701 0 : if in_clause.is_empty() {
702 0 : break;
703 0 : }
704 0 :
705 0 : let in_clause = &in_clause;
706 0 : let chunk_rows = self
707 0 : .with_measured_conn(DatabaseOperation::ShardGenerations, move |conn| {
708 0 : Box::pin(async move {
709 : // diesel doesn't support multi-column IN queries, so we compose raw SQL. No escaping is required because
710 : // the inputs are strongly typed and cannot carry any user-supplied raw string content.
711 0 : let result : Vec<TenantShardPersistence> = diesel::sql_query(
712 0 : format!("SELECT * from tenant_shards where (tenant_id, shard_number, shard_count) in ({in_clause});").as_str()
713 0 : ).load(conn).await?;
714 :
715 0 : Ok(result)
716 0 : })
717 0 : })
718 0 : .await?;
719 0 : rows.extend(chunk_rows.into_iter())
720 : }
721 :
722 0 : Ok(rows
723 0 : .into_iter()
724 0 : .map(|tsp| {
725 0 : (
726 0 : tsp.get_tenant_shard_id()
727 0 : .expect("Bad tenant ID in database"),
728 0 : tsp.generation.map(|g| Generation::new(g as u32)),
729 0 : )
730 0 : })
731 0 : .collect())
732 0 : }
733 :
734 : #[allow(non_local_definitions)]
735 : /// For use when updating a persistent property of a tenant, such as its config or placement_policy.
736 : ///
737 : /// Do not use this for settting generation, unless in the special onboarding code path (/location_config)
738 : /// API: use [`Self::increment_generation`] instead. Setting the generation via this route is a one-time thing
739 : /// that we only do the first time a tenant is set to an attached policy via /location_config.
740 0 : pub(crate) async fn update_tenant_shard(
741 0 : &self,
742 0 : tenant: TenantFilter,
743 0 : input_placement_policy: Option<PlacementPolicy>,
744 0 : input_config: Option<TenantConfig>,
745 0 : input_generation: Option<Generation>,
746 0 : input_scheduling_policy: Option<ShardSchedulingPolicy>,
747 0 : ) -> DatabaseResult<()> {
748 : use crate::schema::tenant_shards::dsl::*;
749 :
750 0 : let tenant = &tenant;
751 0 : let input_placement_policy = &input_placement_policy;
752 0 : let input_config = &input_config;
753 0 : let input_generation = &input_generation;
754 0 : let input_scheduling_policy = &input_scheduling_policy;
755 0 : self.with_measured_conn(DatabaseOperation::UpdateTenantShard, move |conn| {
756 0 : Box::pin(async move {
757 0 : let query = match tenant {
758 0 : TenantFilter::Shard(tenant_shard_id) => diesel::update(tenant_shards)
759 0 : .filter(tenant_id.eq(tenant_shard_id.tenant_id.to_string()))
760 0 : .filter(shard_number.eq(tenant_shard_id.shard_number.0 as i32))
761 0 : .filter(shard_count.eq(tenant_shard_id.shard_count.literal() as i32))
762 0 : .into_boxed(),
763 0 : TenantFilter::Tenant(input_tenant_id) => diesel::update(tenant_shards)
764 0 : .filter(tenant_id.eq(input_tenant_id.to_string()))
765 0 : .into_boxed(),
766 : };
767 :
768 : // Clear generation_pageserver if we are moving into a state where we won't have
769 : // any attached pageservers.
770 0 : let input_generation_pageserver = match input_placement_policy {
771 0 : None | Some(PlacementPolicy::Attached(_)) => None,
772 0 : Some(PlacementPolicy::Detached | PlacementPolicy::Secondary) => Some(None),
773 : };
774 :
775 0 : #[derive(AsChangeset)]
776 : #[diesel(table_name = crate::schema::tenant_shards)]
777 : struct ShardUpdate {
778 : generation: Option<i32>,
779 : placement_policy: Option<String>,
780 : config: Option<String>,
781 : scheduling_policy: Option<String>,
782 : generation_pageserver: Option<Option<i64>>,
783 : }
784 :
785 0 : let update = ShardUpdate {
786 0 : generation: input_generation.map(|g| g.into().unwrap() as i32),
787 0 : placement_policy: input_placement_policy
788 0 : .as_ref()
789 0 : .map(|p| serde_json::to_string(&p).unwrap()),
790 0 : config: input_config
791 0 : .as_ref()
792 0 : .map(|c| serde_json::to_string(&c).unwrap()),
793 0 : scheduling_policy: input_scheduling_policy
794 0 : .map(|p| serde_json::to_string(&p).unwrap()),
795 0 : generation_pageserver: input_generation_pageserver,
796 0 : };
797 0 :
798 0 : query.set(update).execute(conn).await?;
799 :
800 0 : Ok(())
801 0 : })
802 0 : })
803 0 : .await?;
804 :
805 0 : Ok(())
806 0 : }
807 :
808 : /// Note that passing None for a shard clears the preferred AZ (rather than leaving it unmodified)
809 0 : pub(crate) async fn set_tenant_shard_preferred_azs(
810 0 : &self,
811 0 : preferred_azs: Vec<(TenantShardId, Option<AvailabilityZone>)>,
812 0 : ) -> DatabaseResult<Vec<(TenantShardId, Option<AvailabilityZone>)>> {
813 : use crate::schema::tenant_shards::dsl::*;
814 :
815 0 : let preferred_azs = preferred_azs.as_slice();
816 0 : self.with_measured_conn(DatabaseOperation::SetPreferredAzs, move |conn| {
817 0 : Box::pin(async move {
818 0 : let mut shards_updated = Vec::default();
819 :
820 0 : for (tenant_shard_id, preferred_az) in preferred_azs.iter() {
821 0 : let updated = diesel::update(tenant_shards)
822 0 : .filter(tenant_id.eq(tenant_shard_id.tenant_id.to_string()))
823 0 : .filter(shard_number.eq(tenant_shard_id.shard_number.0 as i32))
824 0 : .filter(shard_count.eq(tenant_shard_id.shard_count.literal() as i32))
825 0 : .set(preferred_az_id.eq(preferred_az.as_ref().map(|az| az.0.clone())))
826 0 : .execute(conn)
827 0 : .await?;
828 :
829 0 : if updated == 1 {
830 0 : shards_updated.push((*tenant_shard_id, preferred_az.clone()));
831 0 : }
832 : }
833 :
834 0 : Ok(shards_updated)
835 0 : })
836 0 : })
837 0 : .await
838 0 : }
839 :
840 0 : pub(crate) async fn detach(&self, tenant_shard_id: TenantShardId) -> anyhow::Result<()> {
841 : use crate::schema::tenant_shards::dsl::*;
842 0 : self.with_measured_conn(DatabaseOperation::Detach, move |conn| {
843 0 : Box::pin(async move {
844 0 : let updated = diesel::update(tenant_shards)
845 0 : .filter(tenant_id.eq(tenant_shard_id.tenant_id.to_string()))
846 0 : .filter(shard_number.eq(tenant_shard_id.shard_number.0 as i32))
847 0 : .filter(shard_count.eq(tenant_shard_id.shard_count.literal() as i32))
848 0 : .set((
849 0 : generation_pageserver.eq(Option::<i64>::None),
850 0 : placement_policy
851 0 : .eq(serde_json::to_string(&PlacementPolicy::Detached).unwrap()),
852 0 : ))
853 0 : .execute(conn)
854 0 : .await?;
855 :
856 0 : Ok(updated)
857 0 : })
858 0 : })
859 0 : .await?;
860 :
861 0 : Ok(())
862 0 : }
863 :
864 : // When we start shard splitting, we must durably mark the tenant so that
865 : // on restart, we know that we must go through recovery.
866 : //
867 : // We create the child shards here, so that they will be available for increment_generation calls
868 : // if some pageserver holding a child shard needs to restart before the overall tenant split is complete.
869 0 : pub(crate) async fn begin_shard_split(
870 0 : &self,
871 0 : old_shard_count: ShardCount,
872 0 : split_tenant_id: TenantId,
873 0 : parent_to_children: Vec<(TenantShardId, Vec<TenantShardPersistence>)>,
874 0 : ) -> DatabaseResult<()> {
875 : use crate::schema::tenant_shards::dsl::*;
876 0 : let parent_to_children = parent_to_children.as_slice();
877 0 : self.with_measured_conn(DatabaseOperation::BeginShardSplit, move |conn| {
878 0 : Box::pin(async move {
879 : // Mark parent shards as splitting
880 :
881 0 : let updated = diesel::update(tenant_shards)
882 0 : .filter(tenant_id.eq(split_tenant_id.to_string()))
883 0 : .filter(shard_count.eq(old_shard_count.literal() as i32))
884 0 : .set((splitting.eq(1),))
885 0 : .execute(conn).await?;
886 0 : if u8::try_from(updated)
887 0 : .map_err(|_| DatabaseError::Logical(
888 0 : format!("Overflow existing shard count {} while splitting", updated))
889 0 : )? != old_shard_count.count() {
890 : // Perhaps a deletion or another split raced with this attempt to split, mutating
891 : // the parent shards that we intend to split. In this case the split request should fail.
892 0 : return Err(DatabaseError::Logical(
893 0 : format!("Unexpected existing shard count {updated} when preparing tenant for split (expected {})", old_shard_count.count())
894 0 : ));
895 0 : }
896 0 :
897 0 : // FIXME: spurious clone to sidestep closure move rules
898 0 : let parent_to_children = parent_to_children.to_vec();
899 :
900 : // Insert child shards
901 0 : for (parent_shard_id, children) in parent_to_children {
902 0 : let mut parent = crate::schema::tenant_shards::table
903 0 : .filter(tenant_id.eq(parent_shard_id.tenant_id.to_string()))
904 0 : .filter(shard_number.eq(parent_shard_id.shard_number.0 as i32))
905 0 : .filter(shard_count.eq(parent_shard_id.shard_count.literal() as i32))
906 0 : .load::<TenantShardPersistence>(conn).await?;
907 0 : let parent = if parent.len() != 1 {
908 0 : return Err(DatabaseError::Logical(format!(
909 0 : "Parent shard {parent_shard_id} not found"
910 0 : )));
911 : } else {
912 0 : parent.pop().unwrap()
913 : };
914 0 : for mut shard in children {
915 : // Carry the parent's generation into the child
916 0 : shard.generation = parent.generation;
917 0 :
918 0 : debug_assert!(shard.splitting == SplitState::Splitting);
919 0 : diesel::insert_into(tenant_shards)
920 0 : .values(shard)
921 0 : .execute(conn).await?;
922 : }
923 : }
924 :
925 0 : Ok(())
926 0 : })
927 0 : })
928 0 : .await
929 0 : }
930 :
931 : // When we finish shard splitting, we must atomically clean up the old shards
932 : // and insert the new shards, and clear the splitting marker.
933 0 : pub(crate) async fn complete_shard_split(
934 0 : &self,
935 0 : split_tenant_id: TenantId,
936 0 : old_shard_count: ShardCount,
937 0 : ) -> DatabaseResult<()> {
938 : use crate::schema::tenant_shards::dsl::*;
939 0 : self.with_measured_conn(DatabaseOperation::CompleteShardSplit, move |conn| {
940 0 : Box::pin(async move {
941 0 : // Drop parent shards
942 0 : diesel::delete(tenant_shards)
943 0 : .filter(tenant_id.eq(split_tenant_id.to_string()))
944 0 : .filter(shard_count.eq(old_shard_count.literal() as i32))
945 0 : .execute(conn)
946 0 : .await?;
947 :
948 : // Clear sharding flag
949 0 : let updated = diesel::update(tenant_shards)
950 0 : .filter(tenant_id.eq(split_tenant_id.to_string()))
951 0 : .set((splitting.eq(0),))
952 0 : .execute(conn)
953 0 : .await?;
954 0 : debug_assert!(updated > 0);
955 :
956 0 : Ok(())
957 0 : })
958 0 : })
959 0 : .await
960 0 : }
961 :
962 : /// Used when the remote part of a shard split failed: we will revert the database state to have only
963 : /// the parent shards, with SplitState::Idle.
964 0 : pub(crate) async fn abort_shard_split(
965 0 : &self,
966 0 : split_tenant_id: TenantId,
967 0 : new_shard_count: ShardCount,
968 0 : ) -> DatabaseResult<AbortShardSplitStatus> {
969 : use crate::schema::tenant_shards::dsl::*;
970 0 : self.with_measured_conn(DatabaseOperation::AbortShardSplit, move |conn| {
971 0 : Box::pin(async move {
972 : // Clear the splitting state on parent shards
973 0 : let updated = diesel::update(tenant_shards)
974 0 : .filter(tenant_id.eq(split_tenant_id.to_string()))
975 0 : .filter(shard_count.ne(new_shard_count.literal() as i32))
976 0 : .set((splitting.eq(0),))
977 0 : .execute(conn)
978 0 : .await?;
979 :
980 : // Parent shards are already gone: we cannot abort.
981 0 : if updated == 0 {
982 0 : return Ok(AbortShardSplitStatus::Complete);
983 0 : }
984 0 :
985 0 : // Sanity check: if parent shards were present, their cardinality should
986 0 : // be less than the number of child shards.
987 0 : if updated >= new_shard_count.count() as usize {
988 0 : return Err(DatabaseError::Logical(format!(
989 0 : "Unexpected parent shard count {updated} while aborting split to \
990 0 : count {new_shard_count:?} on tenant {split_tenant_id}"
991 0 : )));
992 0 : }
993 0 :
994 0 : // Erase child shards
995 0 : diesel::delete(tenant_shards)
996 0 : .filter(tenant_id.eq(split_tenant_id.to_string()))
997 0 : .filter(shard_count.eq(new_shard_count.literal() as i32))
998 0 : .execute(conn)
999 0 : .await?;
1000 :
1001 0 : Ok(AbortShardSplitStatus::Aborted)
1002 0 : })
1003 0 : })
1004 0 : .await
1005 0 : }
1006 :
1007 : /// Stores all the latest metadata health updates durably. Updates existing entry on conflict.
1008 : ///
1009 : /// **Correctness:** `metadata_health_updates` should all belong the tenant shards managed by the storage controller.
1010 : #[allow(dead_code)]
1011 0 : pub(crate) async fn update_metadata_health_records(
1012 0 : &self,
1013 0 : healthy_records: Vec<MetadataHealthPersistence>,
1014 0 : unhealthy_records: Vec<MetadataHealthPersistence>,
1015 0 : now: chrono::DateTime<chrono::Utc>,
1016 0 : ) -> DatabaseResult<()> {
1017 : use crate::schema::metadata_health::dsl::*;
1018 :
1019 0 : let healthy_records = healthy_records.as_slice();
1020 0 : let unhealthy_records = unhealthy_records.as_slice();
1021 0 : self.with_measured_conn(DatabaseOperation::UpdateMetadataHealth, move |conn| {
1022 0 : Box::pin(async move {
1023 0 : diesel::insert_into(metadata_health)
1024 0 : .values(healthy_records)
1025 0 : .on_conflict((tenant_id, shard_number, shard_count))
1026 0 : .do_update()
1027 0 : .set((healthy.eq(true), last_scrubbed_at.eq(now)))
1028 0 : .execute(conn)
1029 0 : .await?;
1030 :
1031 0 : diesel::insert_into(metadata_health)
1032 0 : .values(unhealthy_records)
1033 0 : .on_conflict((tenant_id, shard_number, shard_count))
1034 0 : .do_update()
1035 0 : .set((healthy.eq(false), last_scrubbed_at.eq(now)))
1036 0 : .execute(conn)
1037 0 : .await?;
1038 0 : Ok(())
1039 0 : })
1040 0 : })
1041 0 : .await
1042 0 : }
1043 :
1044 : /// Lists all the metadata health records.
1045 : #[allow(dead_code)]
1046 0 : pub(crate) async fn list_metadata_health_records(
1047 0 : &self,
1048 0 : ) -> DatabaseResult<Vec<MetadataHealthPersistence>> {
1049 0 : self.with_measured_conn(DatabaseOperation::ListMetadataHealth, move |conn| {
1050 0 : Box::pin(async {
1051 0 : Ok(crate::schema::metadata_health::table
1052 0 : .load::<MetadataHealthPersistence>(conn)
1053 0 : .await?)
1054 0 : })
1055 0 : })
1056 0 : .await
1057 0 : }
1058 :
1059 : /// Lists all the metadata health records that is unhealthy.
1060 : #[allow(dead_code)]
1061 0 : pub(crate) async fn list_unhealthy_metadata_health_records(
1062 0 : &self,
1063 0 : ) -> DatabaseResult<Vec<MetadataHealthPersistence>> {
1064 : use crate::schema::metadata_health::dsl::*;
1065 0 : self.with_measured_conn(
1066 0 : DatabaseOperation::ListMetadataHealthUnhealthy,
1067 0 : move |conn| {
1068 0 : Box::pin(async {
1069 0 : DatabaseResult::Ok(
1070 0 : crate::schema::metadata_health::table
1071 0 : .filter(healthy.eq(false))
1072 0 : .load::<MetadataHealthPersistence>(conn)
1073 0 : .await?,
1074 : )
1075 0 : })
1076 0 : },
1077 0 : )
1078 0 : .await
1079 0 : }
1080 :
1081 : /// Lists all the metadata health records that have not been updated since an `earlier` time.
1082 : #[allow(dead_code)]
1083 0 : pub(crate) async fn list_outdated_metadata_health_records(
1084 0 : &self,
1085 0 : earlier: chrono::DateTime<chrono::Utc>,
1086 0 : ) -> DatabaseResult<Vec<MetadataHealthPersistence>> {
1087 : use crate::schema::metadata_health::dsl::*;
1088 :
1089 0 : self.with_measured_conn(DatabaseOperation::ListMetadataHealthOutdated, move |conn| {
1090 0 : Box::pin(async move {
1091 0 : let query = metadata_health.filter(last_scrubbed_at.lt(earlier));
1092 0 : let res = query.load::<MetadataHealthPersistence>(conn).await?;
1093 :
1094 0 : Ok(res)
1095 0 : })
1096 0 : })
1097 0 : .await
1098 0 : }
1099 :
1100 : /// Get the current entry from the `leader` table if one exists.
1101 : /// It is an error for the table to contain more than one entry.
1102 0 : pub(crate) async fn get_leader(&self) -> DatabaseResult<Option<ControllerPersistence>> {
1103 0 : let mut leader: Vec<ControllerPersistence> = self
1104 0 : .with_measured_conn(DatabaseOperation::GetLeader, move |conn| {
1105 0 : Box::pin(async move {
1106 0 : Ok(crate::schema::controllers::table
1107 0 : .load::<ControllerPersistence>(conn)
1108 0 : .await?)
1109 0 : })
1110 0 : })
1111 0 : .await?;
1112 :
1113 0 : if leader.len() > 1 {
1114 0 : return Err(DatabaseError::Logical(format!(
1115 0 : "More than one entry present in the leader table: {leader:?}"
1116 0 : )));
1117 0 : }
1118 0 :
1119 0 : Ok(leader.pop())
1120 0 : }
1121 :
1122 : /// Update the new leader with compare-exchange semantics. If `prev` does not
1123 : /// match the current leader entry, then the update is treated as a failure.
1124 : /// When `prev` is not specified, the update is forced.
1125 0 : pub(crate) async fn update_leader(
1126 0 : &self,
1127 0 : prev: Option<ControllerPersistence>,
1128 0 : new: ControllerPersistence,
1129 0 : ) -> DatabaseResult<()> {
1130 : use crate::schema::controllers::dsl::*;
1131 :
1132 0 : let updated = self
1133 0 : .with_measured_conn(DatabaseOperation::UpdateLeader, move |conn| {
1134 0 : let prev = prev.clone();
1135 0 : let new = new.clone();
1136 0 : Box::pin(async move {
1137 0 : let updated = match &prev {
1138 0 : Some(prev) => {
1139 0 : diesel::update(controllers)
1140 0 : .filter(address.eq(prev.address.clone()))
1141 0 : .filter(started_at.eq(prev.started_at))
1142 0 : .set((
1143 0 : address.eq(new.address.clone()),
1144 0 : started_at.eq(new.started_at),
1145 0 : ))
1146 0 : .execute(conn)
1147 0 : .await?
1148 : }
1149 : None => {
1150 0 : diesel::insert_into(controllers)
1151 0 : .values(new.clone())
1152 0 : .execute(conn)
1153 0 : .await?
1154 : }
1155 : };
1156 :
1157 0 : Ok(updated)
1158 0 : })
1159 0 : })
1160 0 : .await?;
1161 :
1162 0 : if updated == 0 {
1163 0 : return Err(DatabaseError::Logical(
1164 0 : "Leader table update failed".to_string(),
1165 0 : ));
1166 0 : }
1167 0 :
1168 0 : Ok(())
1169 0 : }
1170 :
1171 : /// At startup, populate the list of nodes which our shards may be placed on
1172 0 : pub(crate) async fn list_safekeepers(&self) -> DatabaseResult<Vec<SafekeeperPersistence>> {
1173 0 : let safekeepers: Vec<SafekeeperPersistence> = self
1174 0 : .with_measured_conn(DatabaseOperation::ListNodes, move |conn| {
1175 0 : Box::pin(async move {
1176 0 : Ok(crate::schema::safekeepers::table
1177 0 : .load::<SafekeeperPersistence>(conn)
1178 0 : .await?)
1179 0 : })
1180 0 : })
1181 0 : .await?;
1182 :
1183 0 : tracing::info!("list_safekeepers: loaded {} nodes", safekeepers.len());
1184 :
1185 0 : Ok(safekeepers)
1186 0 : }
1187 :
1188 0 : pub(crate) async fn safekeeper_upsert(
1189 0 : &self,
1190 0 : record: SafekeeperUpsert,
1191 0 : ) -> Result<(), DatabaseError> {
1192 : use crate::schema::safekeepers::dsl::*;
1193 :
1194 0 : self.with_conn(move |conn| {
1195 0 : let record = record.clone();
1196 0 : Box::pin(async move {
1197 0 : let bind = record
1198 0 : .as_insert_or_update()
1199 0 : .map_err(|e| DatabaseError::Logical(format!("{e}")))?;
1200 :
1201 0 : let inserted_updated = diesel::insert_into(safekeepers)
1202 0 : .values(&bind)
1203 0 : .on_conflict(id)
1204 0 : .do_update()
1205 0 : .set(&bind)
1206 0 : .execute(conn)
1207 0 : .await?;
1208 :
1209 0 : if inserted_updated != 1 {
1210 0 : return Err(DatabaseError::Logical(format!(
1211 0 : "unexpected number of rows ({})",
1212 0 : inserted_updated
1213 0 : )));
1214 0 : }
1215 0 :
1216 0 : Ok(())
1217 0 : })
1218 0 : })
1219 0 : .await
1220 0 : }
1221 :
1222 0 : pub(crate) async fn set_safekeeper_scheduling_policy(
1223 0 : &self,
1224 0 : id_: i64,
1225 0 : scheduling_policy_: SkSchedulingPolicy,
1226 0 : ) -> Result<(), DatabaseError> {
1227 : use crate::schema::safekeepers::dsl::*;
1228 :
1229 0 : self.with_conn(move |conn| {
1230 0 : Box::pin(async move {
1231 0 : #[derive(Insertable, AsChangeset)]
1232 : #[diesel(table_name = crate::schema::safekeepers)]
1233 : struct UpdateSkSchedulingPolicy<'a> {
1234 : id: i64,
1235 : scheduling_policy: &'a str,
1236 : }
1237 0 : let scheduling_policy_ = String::from(scheduling_policy_);
1238 :
1239 0 : let rows_affected = diesel::update(safekeepers.filter(id.eq(id_)))
1240 0 : .set(scheduling_policy.eq(scheduling_policy_))
1241 0 : .execute(conn)
1242 0 : .await?;
1243 :
1244 0 : if rows_affected != 1 {
1245 0 : return Err(DatabaseError::Logical(format!(
1246 0 : "unexpected number of rows ({rows_affected})",
1247 0 : )));
1248 0 : }
1249 0 :
1250 0 : Ok(())
1251 0 : })
1252 0 : })
1253 0 : .await
1254 0 : }
1255 : }
1256 :
1257 0 : pub(crate) fn load_certs() -> anyhow::Result<Arc<rustls::RootCertStore>> {
1258 0 : let der_certs = rustls_native_certs::load_native_certs();
1259 0 :
1260 0 : if !der_certs.errors.is_empty() {
1261 0 : anyhow::bail!("could not parse certificates: {:?}", der_certs.errors);
1262 0 : }
1263 0 :
1264 0 : let mut store = rustls::RootCertStore::empty();
1265 0 : store.add_parsable_certificates(der_certs.certs);
1266 0 : Ok(Arc::new(store))
1267 0 : }
1268 :
1269 : #[derive(Debug)]
1270 : /// A verifier that accepts all certificates (but logs an error still)
1271 : struct AcceptAll(Arc<WebPkiServerVerifier>);
1272 : impl ServerCertVerifier for AcceptAll {
1273 0 : fn verify_server_cert(
1274 0 : &self,
1275 0 : end_entity: &rustls::pki_types::CertificateDer<'_>,
1276 0 : intermediates: &[rustls::pki_types::CertificateDer<'_>],
1277 0 : server_name: &rustls::pki_types::ServerName<'_>,
1278 0 : ocsp_response: &[u8],
1279 0 : now: rustls::pki_types::UnixTime,
1280 0 : ) -> Result<ServerCertVerified, rustls::Error> {
1281 0 : let r =
1282 0 : self.0
1283 0 : .verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now);
1284 0 : if let Err(err) = r {
1285 0 : tracing::info!(
1286 : ?server_name,
1287 0 : "ignoring db connection TLS validation error: {err:?}"
1288 : );
1289 0 : return Ok(ServerCertVerified::assertion());
1290 0 : }
1291 0 : r
1292 0 : }
1293 0 : fn verify_tls12_signature(
1294 0 : &self,
1295 0 : message: &[u8],
1296 0 : cert: &rustls::pki_types::CertificateDer<'_>,
1297 0 : dss: &rustls::DigitallySignedStruct,
1298 0 : ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
1299 0 : self.0.verify_tls12_signature(message, cert, dss)
1300 0 : }
1301 0 : fn verify_tls13_signature(
1302 0 : &self,
1303 0 : message: &[u8],
1304 0 : cert: &rustls::pki_types::CertificateDer<'_>,
1305 0 : dss: &rustls::DigitallySignedStruct,
1306 0 : ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
1307 0 : self.0.verify_tls13_signature(message, cert, dss)
1308 0 : }
1309 0 : fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
1310 0 : self.0.supported_verify_schemes()
1311 0 : }
1312 : }
1313 :
1314 : /// Loads the root certificates and constructs a client config suitable for connecting.
1315 : /// This function is blocking.
1316 0 : fn client_config_with_root_certs() -> anyhow::Result<rustls::ClientConfig> {
1317 0 : let client_config =
1318 0 : rustls::ClientConfig::builder_with_provider(Arc::new(ring::default_provider()))
1319 0 : .with_safe_default_protocol_versions()
1320 0 : .expect("ring should support the default protocol versions");
1321 : static DO_CERT_CHECKS: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1322 0 : let do_cert_checks =
1323 0 : DO_CERT_CHECKS.get_or_init(|| std::env::var("STORCON_DB_CERT_CHECKS").is_ok());
1324 0 : Ok(if *do_cert_checks {
1325 0 : client_config
1326 0 : .with_root_certificates(load_certs()?)
1327 0 : .with_no_client_auth()
1328 : } else {
1329 0 : let verifier = AcceptAll(
1330 : WebPkiServerVerifier::builder_with_provider(
1331 0 : load_certs()?,
1332 0 : Arc::new(ring::default_provider()),
1333 0 : )
1334 0 : .build()?,
1335 : );
1336 0 : client_config
1337 0 : .dangerous()
1338 0 : .with_custom_certificate_verifier(Arc::new(verifier))
1339 0 : .with_no_client_auth()
1340 : })
1341 0 : }
1342 :
1343 0 : fn establish_connection_rustls(config: &str) -> BoxFuture<ConnectionResult<AsyncPgConnection>> {
1344 0 : let fut = async {
1345 : // We first set up the way we want rustls to work.
1346 0 : let rustls_config = client_config_with_root_certs()
1347 0 : .map_err(|err| ConnectionError::BadConnection(format!("{err:?}")))?;
1348 0 : let tls = tokio_postgres_rustls::MakeRustlsConnect::new(rustls_config);
1349 0 : let (client, conn) = tokio_postgres::connect(config, tls)
1350 0 : .await
1351 0 : .map_err(|e| ConnectionError::BadConnection(e.to_string()))?;
1352 :
1353 0 : AsyncPgConnection::try_from_client_and_connection(client, conn).await
1354 0 : };
1355 0 : fut.boxed()
1356 0 : }
1357 :
1358 : #[cfg_attr(test, test)]
1359 1 : fn test_config_debug_censors_password() {
1360 1 : let has_pw =
1361 1 : "host=/var/lib/postgresql,localhost port=1234 user=specialuser password='NOT ALLOWED TAG'";
1362 1 : let has_pw_cfg = has_pw.parse::<tokio_postgres::Config>().unwrap();
1363 1 : assert!(format!("{has_pw_cfg:?}").contains("specialuser"));
1364 : // Ensure that the password is not leaked by the debug impl
1365 1 : assert!(!format!("{has_pw_cfg:?}").contains("NOT ALLOWED TAG"));
1366 1 : }
1367 :
1368 0 : fn log_postgres_connstr_info(config_str: &str) -> anyhow::Result<()> {
1369 0 : let config = config_str
1370 0 : .parse::<tokio_postgres::Config>()
1371 0 : .map_err(|_e| anyhow::anyhow!("Couldn't parse config str"))?;
1372 : // We use debug formatting here, and use a unit test to ensure that we don't leak the password.
1373 : // To make extra sure the test gets ran, run it every time the function is called
1374 : // (this is rather cold code, we can afford it).
1375 : #[cfg(not(test))]
1376 0 : test_config_debug_censors_password();
1377 0 : tracing::info!("database connection config: {config:?}");
1378 0 : Ok(())
1379 0 : }
1380 :
1381 : /// Parts of [`crate::tenant_shard::TenantShard`] that are stored durably
1382 : #[derive(
1383 0 : QueryableByName, Queryable, Selectable, Insertable, Serialize, Deserialize, Clone, Eq, PartialEq,
1384 : )]
1385 : #[diesel(table_name = crate::schema::tenant_shards)]
1386 : pub(crate) struct TenantShardPersistence {
1387 : #[serde(default)]
1388 : pub(crate) tenant_id: String,
1389 : #[serde(default)]
1390 : pub(crate) shard_number: i32,
1391 : #[serde(default)]
1392 : pub(crate) shard_count: i32,
1393 : #[serde(default)]
1394 : pub(crate) shard_stripe_size: i32,
1395 :
1396 : // Latest generation number: next time we attach, increment this
1397 : // and use the incremented number when attaching.
1398 : //
1399 : // Generation is only None when first onboarding a tenant, where it may
1400 : // be in PlacementPolicy::Secondary and therefore have no valid generation state.
1401 : pub(crate) generation: Option<i32>,
1402 :
1403 : // Currently attached pageserver
1404 : #[serde(rename = "pageserver")]
1405 : pub(crate) generation_pageserver: Option<i64>,
1406 :
1407 : #[serde(default)]
1408 : pub(crate) placement_policy: String,
1409 : #[serde(default)]
1410 : pub(crate) splitting: SplitState,
1411 : #[serde(default)]
1412 : pub(crate) config: String,
1413 : #[serde(default)]
1414 : pub(crate) scheduling_policy: String,
1415 :
1416 : // Hint that we should attempt to schedule this tenant shard the given
1417 : // availability zone in order to minimise the chances of cross-AZ communication
1418 : // with compute.
1419 : pub(crate) preferred_az_id: Option<String>,
1420 : }
1421 :
1422 : impl TenantShardPersistence {
1423 0 : pub(crate) fn get_shard_identity(&self) -> Result<ShardIdentity, ShardConfigError> {
1424 0 : if self.shard_count == 0 {
1425 0 : Ok(ShardIdentity::unsharded())
1426 : } else {
1427 0 : Ok(ShardIdentity::new(
1428 0 : ShardNumber(self.shard_number as u8),
1429 0 : ShardCount::new(self.shard_count as u8),
1430 0 : ShardStripeSize(self.shard_stripe_size as u32),
1431 0 : )?)
1432 : }
1433 0 : }
1434 :
1435 0 : pub(crate) fn get_tenant_shard_id(&self) -> Result<TenantShardId, hex::FromHexError> {
1436 0 : Ok(TenantShardId {
1437 0 : tenant_id: TenantId::from_str(self.tenant_id.as_str())?,
1438 0 : shard_number: ShardNumber(self.shard_number as u8),
1439 0 : shard_count: ShardCount::new(self.shard_count as u8),
1440 : })
1441 0 : }
1442 : }
1443 :
1444 : /// Parts of [`crate::node::Node`] that are stored durably
1445 0 : #[derive(Serialize, Deserialize, Queryable, Selectable, Insertable, Eq, PartialEq)]
1446 : #[diesel(table_name = crate::schema::nodes)]
1447 : pub(crate) struct NodePersistence {
1448 : pub(crate) node_id: i64,
1449 : pub(crate) scheduling_policy: String,
1450 : pub(crate) listen_http_addr: String,
1451 : pub(crate) listen_http_port: i32,
1452 : pub(crate) listen_pg_addr: String,
1453 : pub(crate) listen_pg_port: i32,
1454 : pub(crate) availability_zone_id: String,
1455 : }
1456 :
1457 : /// Tenant metadata health status that are stored durably.
1458 0 : #[derive(Queryable, Selectable, Insertable, Serialize, Deserialize, Clone, Eq, PartialEq)]
1459 : #[diesel(table_name = crate::schema::metadata_health)]
1460 : pub(crate) struct MetadataHealthPersistence {
1461 : #[serde(default)]
1462 : pub(crate) tenant_id: String,
1463 : #[serde(default)]
1464 : pub(crate) shard_number: i32,
1465 : #[serde(default)]
1466 : pub(crate) shard_count: i32,
1467 :
1468 : pub(crate) healthy: bool,
1469 : pub(crate) last_scrubbed_at: chrono::DateTime<chrono::Utc>,
1470 : }
1471 :
1472 : impl MetadataHealthPersistence {
1473 0 : pub fn new(
1474 0 : tenant_shard_id: TenantShardId,
1475 0 : healthy: bool,
1476 0 : last_scrubbed_at: chrono::DateTime<chrono::Utc>,
1477 0 : ) -> Self {
1478 0 : let tenant_id = tenant_shard_id.tenant_id.to_string();
1479 0 : let shard_number = tenant_shard_id.shard_number.0 as i32;
1480 0 : let shard_count = tenant_shard_id.shard_count.literal() as i32;
1481 0 :
1482 0 : MetadataHealthPersistence {
1483 0 : tenant_id,
1484 0 : shard_number,
1485 0 : shard_count,
1486 0 : healthy,
1487 0 : last_scrubbed_at,
1488 0 : }
1489 0 : }
1490 :
1491 : #[allow(dead_code)]
1492 0 : pub(crate) fn get_tenant_shard_id(&self) -> Result<TenantShardId, hex::FromHexError> {
1493 0 : Ok(TenantShardId {
1494 0 : tenant_id: TenantId::from_str(self.tenant_id.as_str())?,
1495 0 : shard_number: ShardNumber(self.shard_number as u8),
1496 0 : shard_count: ShardCount::new(self.shard_count as u8),
1497 : })
1498 0 : }
1499 : }
1500 :
1501 : impl From<MetadataHealthPersistence> for MetadataHealthRecord {
1502 0 : fn from(value: MetadataHealthPersistence) -> Self {
1503 0 : MetadataHealthRecord {
1504 0 : tenant_shard_id: value
1505 0 : .get_tenant_shard_id()
1506 0 : .expect("stored tenant id should be valid"),
1507 0 : healthy: value.healthy,
1508 0 : last_scrubbed_at: value.last_scrubbed_at,
1509 0 : }
1510 0 : }
1511 : }
1512 :
1513 : #[derive(
1514 0 : Serialize, Deserialize, Queryable, Selectable, Insertable, Eq, PartialEq, Debug, Clone,
1515 : )]
1516 : #[diesel(table_name = crate::schema::controllers)]
1517 : pub(crate) struct ControllerPersistence {
1518 : pub(crate) address: String,
1519 : pub(crate) started_at: chrono::DateTime<chrono::Utc>,
1520 : }
1521 :
1522 : // What we store in the database
1523 0 : #[derive(Serialize, Deserialize, Queryable, Selectable, Eq, PartialEq, Debug, Clone)]
1524 : #[diesel(table_name = crate::schema::safekeepers)]
1525 : pub(crate) struct SafekeeperPersistence {
1526 : pub(crate) id: i64,
1527 : pub(crate) region_id: String,
1528 : /// 1 is special, it means just created (not currently posted to storcon).
1529 : /// Zero or negative is not really expected.
1530 : /// Otherwise the number from `release-$(number_of_commits_on_branch)` tag.
1531 : pub(crate) version: i64,
1532 : pub(crate) host: String,
1533 : pub(crate) port: i32,
1534 : pub(crate) http_port: i32,
1535 : pub(crate) availability_zone_id: String,
1536 : pub(crate) scheduling_policy: String,
1537 : }
1538 :
1539 : impl SafekeeperPersistence {
1540 0 : pub(crate) fn from_upsert(
1541 0 : upsert: SafekeeperUpsert,
1542 0 : scheduling_policy: SkSchedulingPolicy,
1543 0 : ) -> Self {
1544 0 : crate::persistence::SafekeeperPersistence {
1545 0 : id: upsert.id,
1546 0 : region_id: upsert.region_id,
1547 0 : version: upsert.version,
1548 0 : host: upsert.host,
1549 0 : port: upsert.port,
1550 0 : http_port: upsert.http_port,
1551 0 : availability_zone_id: upsert.availability_zone_id,
1552 0 : scheduling_policy: String::from(scheduling_policy),
1553 0 : }
1554 0 : }
1555 0 : pub(crate) fn as_describe_response(&self) -> Result<SafekeeperDescribeResponse, DatabaseError> {
1556 0 : let scheduling_policy =
1557 0 : SkSchedulingPolicy::from_str(&self.scheduling_policy).map_err(|e| {
1558 0 : DatabaseError::Logical(format!("can't construct SkSchedulingPolicy: {e:?}"))
1559 0 : })?;
1560 0 : Ok(SafekeeperDescribeResponse {
1561 0 : id: NodeId(self.id as u64),
1562 0 : region_id: self.region_id.clone(),
1563 0 : version: self.version,
1564 0 : host: self.host.clone(),
1565 0 : port: self.port,
1566 0 : http_port: self.http_port,
1567 0 : availability_zone_id: self.availability_zone_id.clone(),
1568 0 : scheduling_policy,
1569 0 : })
1570 0 : }
1571 : }
1572 :
1573 : /// What we expect from the upsert http api
1574 0 : #[derive(Serialize, Deserialize, Eq, PartialEq, Debug, Clone)]
1575 : pub(crate) struct SafekeeperUpsert {
1576 : pub(crate) id: i64,
1577 : pub(crate) region_id: String,
1578 : /// 1 is special, it means just created (not currently posted to storcon).
1579 : /// Zero or negative is not really expected.
1580 : /// Otherwise the number from `release-$(number_of_commits_on_branch)` tag.
1581 : pub(crate) version: i64,
1582 : pub(crate) host: String,
1583 : pub(crate) port: i32,
1584 : /// The active flag will not be stored in the database and will be ignored.
1585 : pub(crate) active: Option<bool>,
1586 : pub(crate) http_port: i32,
1587 : pub(crate) availability_zone_id: String,
1588 : }
1589 :
1590 : impl SafekeeperUpsert {
1591 0 : fn as_insert_or_update(&self) -> anyhow::Result<InsertUpdateSafekeeper<'_>> {
1592 0 : if self.version < 0 {
1593 0 : anyhow::bail!("negative version: {}", self.version);
1594 0 : }
1595 0 : Ok(InsertUpdateSafekeeper {
1596 0 : id: self.id,
1597 0 : region_id: &self.region_id,
1598 0 : version: self.version,
1599 0 : host: &self.host,
1600 0 : port: self.port,
1601 0 : http_port: self.http_port,
1602 0 : availability_zone_id: &self.availability_zone_id,
1603 0 : // None means a wish to not update this column. We expose abilities to update it via other means.
1604 0 : scheduling_policy: None,
1605 0 : })
1606 0 : }
1607 : }
1608 :
1609 0 : #[derive(Insertable, AsChangeset)]
1610 : #[diesel(table_name = crate::schema::safekeepers)]
1611 : struct InsertUpdateSafekeeper<'a> {
1612 : id: i64,
1613 : region_id: &'a str,
1614 : version: i64,
1615 : host: &'a str,
1616 : port: i32,
1617 : http_port: i32,
1618 : availability_zone_id: &'a str,
1619 : scheduling_policy: Option<&'a str>,
1620 : }
|