Line data Source code
1 : pub(crate) mod split_state;
2 : use std::collections::HashMap;
3 : use std::str::FromStr;
4 : use std::time::Duration;
5 :
6 : use self::split_state::SplitState;
7 : use camino::Utf8Path;
8 : use camino::Utf8PathBuf;
9 : use diesel::pg::PgConnection;
10 : use diesel::prelude::*;
11 : use diesel::Connection;
12 : use pageserver_api::controller_api::ShardSchedulingPolicy;
13 : use pageserver_api::controller_api::{NodeSchedulingPolicy, PlacementPolicy};
14 : use pageserver_api::models::TenantConfig;
15 : use pageserver_api::shard::ShardConfigError;
16 : use pageserver_api::shard::ShardIdentity;
17 : use pageserver_api::shard::ShardStripeSize;
18 : use pageserver_api::shard::{ShardCount, ShardNumber, TenantShardId};
19 : use serde::{Deserialize, Serialize};
20 : use utils::generation::Generation;
21 : use utils::id::{NodeId, TenantId};
22 :
23 : use crate::metrics::{
24 : DatabaseQueryErrorLabelGroup, DatabaseQueryLatencyLabelGroup, METRICS_REGISTRY,
25 : };
26 : use crate::node::Node;
27 :
28 : /// ## What do we store?
29 : ///
30 : /// The storage controller service does not store most of its state durably.
31 : ///
32 : /// The essential things to store durably are:
33 : /// - generation numbers, as these must always advance monotonically to ensure data safety.
34 : /// - Tenant's PlacementPolicy and TenantConfig, as the source of truth for these is something external.
35 : /// - Node's scheduling policies, as the source of truth for these is something external.
36 : ///
37 : /// Other things we store durably as an implementation detail:
38 : /// - Node's host/port: this could be avoided it we made nodes emit a self-registering heartbeat,
39 : /// but it is operationally simpler to make this service the authority for which nodes
40 : /// it talks to.
41 : ///
42 : /// ## Performance/efficiency
43 : ///
44 : /// The storage controller service does not go via the database for most things: there are
45 : /// a couple of places where we must, and where efficiency matters:
46 : /// - Incrementing generation numbers: the Reconciler has to wait for this to complete
47 : /// before it can attach a tenant, so this acts as a bound on how fast things like
48 : /// failover can happen.
49 : /// - Pageserver re-attach: we will increment many shards' generations when this happens,
50 : /// so it is important to avoid e.g. issuing O(N) queries.
51 : ///
52 : /// Database calls relating to nodes have low performance requirements, as they are very rarely
53 : /// updated, and reads of nodes are always from memory, not the database. We only require that
54 : /// we can UPDATE a node's scheduling mode reasonably quickly to mark a bad node offline.
55 : pub struct Persistence {
56 : connection_pool: diesel::r2d2::Pool<diesel::r2d2::ConnectionManager<PgConnection>>,
57 :
58 : // In test environments, we support loading+saving a JSON file. This is temporary, for the benefit of
59 : // test_compatibility.py, so that we don't have to commit to making the database contents fully backward/forward
60 : // compatible just yet.
61 : json_path: Option<Utf8PathBuf>,
62 : }
63 :
64 : /// Legacy format, for use in JSON compat objects in test environment
65 0 : #[derive(Serialize, Deserialize)]
66 : struct JsonPersistence {
67 : tenants: HashMap<TenantShardId, TenantShardPersistence>,
68 : }
69 :
70 0 : #[derive(thiserror::Error, Debug)]
71 : pub(crate) enum DatabaseError {
72 : #[error(transparent)]
73 : Query(#[from] diesel::result::Error),
74 : #[error(transparent)]
75 : Connection(#[from] diesel::result::ConnectionError),
76 : #[error(transparent)]
77 : ConnectionPool(#[from] r2d2::Error),
78 : #[error("Logical error: {0}")]
79 : Logical(String),
80 : }
81 :
82 : #[derive(measured::FixedCardinalityLabel, Copy, Clone)]
83 : pub(crate) enum DatabaseOperation {
84 : InsertNode,
85 : UpdateNode,
86 : DeleteNode,
87 : ListNodes,
88 : BeginShardSplit,
89 : CompleteShardSplit,
90 : AbortShardSplit,
91 : Detach,
92 : ReAttach,
93 : IncrementGeneration,
94 : ListTenantShards,
95 : InsertTenantShards,
96 : UpdateTenantShard,
97 : DeleteTenant,
98 : UpdateTenantConfig,
99 : }
100 :
101 : #[must_use]
102 : pub(crate) enum AbortShardSplitStatus {
103 : /// We aborted the split in the database by reverting to the parent shards
104 : Aborted,
105 : /// The split had already been persisted.
106 : Complete,
107 : }
108 :
109 : pub(crate) type DatabaseResult<T> = Result<T, DatabaseError>;
110 :
111 : /// Some methods can operate on either a whole tenant or a single shard
112 : pub(crate) enum TenantFilter {
113 : Tenant(TenantId),
114 : Shard(TenantShardId),
115 : }
116 :
117 : impl Persistence {
118 : // The default postgres connection limit is 100. We use up to 99, to leave one free for a human admin under
119 : // normal circumstances. This assumes we have exclusive use of the database cluster to which we connect.
120 : pub const MAX_CONNECTIONS: u32 = 99;
121 :
122 : // We don't want to keep a lot of connections alive: close them down promptly if they aren't being used.
123 : const IDLE_CONNECTION_TIMEOUT: Duration = Duration::from_secs(10);
124 : const MAX_CONNECTION_LIFETIME: Duration = Duration::from_secs(60);
125 :
126 0 : pub fn new(database_url: String, json_path: Option<Utf8PathBuf>) -> Self {
127 0 : let manager = diesel::r2d2::ConnectionManager::<PgConnection>::new(database_url);
128 0 :
129 0 : // We will use a connection pool: this is primarily to _limit_ our connection count, rather than to optimize time
130 0 : // to execute queries (database queries are not generally on latency-sensitive paths).
131 0 : let connection_pool = diesel::r2d2::Pool::builder()
132 0 : .max_size(Self::MAX_CONNECTIONS)
133 0 : .max_lifetime(Some(Self::MAX_CONNECTION_LIFETIME))
134 0 : .idle_timeout(Some(Self::IDLE_CONNECTION_TIMEOUT))
135 0 : // Always keep at least one connection ready to go
136 0 : .min_idle(Some(1))
137 0 : .test_on_check_out(true)
138 0 : .build(manager)
139 0 : .expect("Could not build connection pool");
140 0 :
141 0 : Self {
142 0 : connection_pool,
143 0 : json_path,
144 0 : }
145 0 : }
146 :
147 : /// Wraps `with_conn` in order to collect latency and error metrics
148 0 : async fn with_measured_conn<F, R>(&self, op: DatabaseOperation, func: F) -> DatabaseResult<R>
149 0 : where
150 0 : F: FnOnce(&mut PgConnection) -> DatabaseResult<R> + Send + 'static,
151 0 : R: Send + 'static,
152 0 : {
153 0 : let latency = &METRICS_REGISTRY
154 0 : .metrics_group
155 0 : .storage_controller_database_query_latency;
156 0 : let _timer = latency.start_timer(DatabaseQueryLatencyLabelGroup { operation: op });
157 :
158 0 : let res = self.with_conn(func).await;
159 :
160 0 : if let Err(err) = &res {
161 0 : let error_counter = &METRICS_REGISTRY
162 0 : .metrics_group
163 0 : .storage_controller_database_query_error;
164 0 : error_counter.inc(DatabaseQueryErrorLabelGroup {
165 0 : error_type: err.error_label(),
166 0 : operation: op,
167 0 : })
168 0 : }
169 :
170 0 : res
171 0 : }
172 :
173 : /// Call the provided function in a tokio blocking thread, with a Diesel database connection.
174 0 : async fn with_conn<F, R>(&self, func: F) -> DatabaseResult<R>
175 0 : where
176 0 : F: FnOnce(&mut PgConnection) -> DatabaseResult<R> + Send + 'static,
177 0 : R: Send + 'static,
178 0 : {
179 0 : let mut conn = self.connection_pool.get()?;
180 0 : tokio::task::spawn_blocking(move || -> DatabaseResult<R> { func(&mut conn) })
181 0 : .await
182 0 : .expect("Task panic")
183 0 : }
184 :
185 : /// When a node is first registered, persist it before using it for anything
186 0 : pub(crate) async fn insert_node(&self, node: &Node) -> DatabaseResult<()> {
187 0 : let np = node.to_persistent();
188 0 : self.with_measured_conn(
189 0 : DatabaseOperation::InsertNode,
190 0 : move |conn| -> DatabaseResult<()> {
191 0 : diesel::insert_into(crate::schema::nodes::table)
192 0 : .values(&np)
193 0 : .execute(conn)?;
194 0 : Ok(())
195 0 : },
196 0 : )
197 0 : .await
198 0 : }
199 :
200 : /// At startup, populate the list of nodes which our shards may be placed on
201 0 : pub(crate) async fn list_nodes(&self) -> DatabaseResult<Vec<NodePersistence>> {
202 0 : let nodes: Vec<NodePersistence> = self
203 0 : .with_measured_conn(
204 0 : DatabaseOperation::ListNodes,
205 0 : move |conn| -> DatabaseResult<_> {
206 0 : Ok(crate::schema::nodes::table.load::<NodePersistence>(conn)?)
207 0 : },
208 0 : )
209 0 : .await?;
210 :
211 0 : tracing::info!("list_nodes: loaded {} nodes", nodes.len());
212 :
213 0 : Ok(nodes)
214 0 : }
215 :
216 0 : pub(crate) async fn update_node(
217 0 : &self,
218 0 : input_node_id: NodeId,
219 0 : input_scheduling: NodeSchedulingPolicy,
220 0 : ) -> DatabaseResult<()> {
221 : use crate::schema::nodes::dsl::*;
222 0 : let updated = self
223 0 : .with_measured_conn(DatabaseOperation::UpdateNode, move |conn| {
224 0 : let updated = diesel::update(nodes)
225 0 : .filter(node_id.eq(input_node_id.0 as i64))
226 0 : .set((scheduling_policy.eq(String::from(input_scheduling)),))
227 0 : .execute(conn)?;
228 0 : Ok(updated)
229 0 : })
230 0 : .await?;
231 :
232 0 : if updated != 1 {
233 0 : Err(DatabaseError::Logical(format!(
234 0 : "Node {node_id:?} not found for update",
235 0 : )))
236 : } else {
237 0 : Ok(())
238 : }
239 0 : }
240 :
241 : /// At startup, load the high level state for shards, such as their config + policy. This will
242 : /// be enriched at runtime with state discovered on pageservers.
243 0 : pub(crate) async fn list_tenant_shards(&self) -> DatabaseResult<Vec<TenantShardPersistence>> {
244 0 : let loaded = self
245 0 : .with_measured_conn(
246 0 : DatabaseOperation::ListTenantShards,
247 0 : move |conn| -> DatabaseResult<_> {
248 0 : Ok(crate::schema::tenant_shards::table.load::<TenantShardPersistence>(conn)?)
249 0 : },
250 0 : )
251 0 : .await?;
252 :
253 0 : if loaded.is_empty() {
254 0 : if let Some(path) = &self.json_path {
255 0 : if tokio::fs::try_exists(path)
256 0 : .await
257 0 : .map_err(|e| DatabaseError::Logical(format!("Error stat'ing JSON file: {e}")))?
258 : {
259 0 : tracing::info!("Importing from legacy JSON format at {path}");
260 0 : return self.list_tenant_shards_json(path).await;
261 0 : }
262 0 : }
263 0 : }
264 0 : Ok(loaded)
265 0 : }
266 :
267 : /// Shim for automated compatibility tests: load tenants from a JSON file instead of database
268 0 : pub(crate) async fn list_tenant_shards_json(
269 0 : &self,
270 0 : path: &Utf8Path,
271 0 : ) -> DatabaseResult<Vec<TenantShardPersistence>> {
272 0 : let bytes = tokio::fs::read(path)
273 0 : .await
274 0 : .map_err(|e| DatabaseError::Logical(format!("Failed to load JSON: {e}")))?;
275 :
276 0 : let mut decoded = serde_json::from_slice::<JsonPersistence>(&bytes)
277 0 : .map_err(|e| DatabaseError::Logical(format!("Deserialization error: {e}")))?;
278 0 : for shard in decoded.tenants.values_mut() {
279 0 : if shard.placement_policy == "\"Single\"" {
280 0 : // Backward compat for test data after PR https://github.com/neondatabase/neon/pull/7165
281 0 : shard.placement_policy = "{\"Attached\":0}".to_string();
282 0 : }
283 :
284 0 : if shard.scheduling_policy.is_empty() {
285 0 : shard.scheduling_policy =
286 0 : serde_json::to_string(&ShardSchedulingPolicy::default()).unwrap();
287 0 : }
288 : }
289 :
290 0 : let tenants: Vec<TenantShardPersistence> = decoded.tenants.into_values().collect();
291 0 :
292 0 : // Synchronize database with what is in the JSON file
293 0 : self.insert_tenant_shards(tenants.clone()).await?;
294 :
295 0 : Ok(tenants)
296 0 : }
297 :
298 : /// For use in testing environments, where we dump out JSON on shutdown.
299 0 : pub async fn write_tenants_json(&self) -> anyhow::Result<()> {
300 0 : let Some(path) = &self.json_path else {
301 0 : anyhow::bail!("Cannot write JSON if path isn't set (test environment bug)");
302 : };
303 0 : tracing::info!("Writing state to {path}...");
304 0 : let tenants = self.list_tenant_shards().await?;
305 0 : let mut tenants_map = HashMap::new();
306 0 : for tsp in tenants {
307 0 : let tenant_shard_id = TenantShardId {
308 0 : tenant_id: TenantId::from_str(tsp.tenant_id.as_str())?,
309 0 : shard_number: ShardNumber(tsp.shard_number as u8),
310 0 : shard_count: ShardCount::new(tsp.shard_count as u8),
311 0 : };
312 0 :
313 0 : tenants_map.insert(tenant_shard_id, tsp);
314 : }
315 0 : let json = serde_json::to_string(&JsonPersistence {
316 0 : tenants: tenants_map,
317 0 : })?;
318 :
319 0 : tokio::fs::write(path, &json).await?;
320 0 : tracing::info!("Wrote {} bytes to {path}...", json.len());
321 :
322 0 : Ok(())
323 0 : }
324 :
325 : /// Tenants must be persisted before we schedule them for the first time. This enables us
326 : /// to correctly retain generation monotonicity, and the externally provided placement policy & config.
327 0 : pub(crate) async fn insert_tenant_shards(
328 0 : &self,
329 0 : shards: Vec<TenantShardPersistence>,
330 0 : ) -> DatabaseResult<()> {
331 0 : use crate::schema::tenant_shards::dsl::*;
332 0 : self.with_measured_conn(
333 0 : DatabaseOperation::InsertTenantShards,
334 0 : move |conn| -> DatabaseResult<()> {
335 0 : conn.transaction(|conn| -> QueryResult<()> {
336 0 : for tenant in &shards {
337 0 : diesel::insert_into(tenant_shards)
338 0 : .values(tenant)
339 0 : .execute(conn)?;
340 : }
341 0 : Ok(())
342 0 : })?;
343 0 : Ok(())
344 0 : },
345 0 : )
346 0 : .await
347 0 : }
348 :
349 : /// Ordering: call this _after_ deleting the tenant on pageservers, but _before_ dropping state for
350 : /// the tenant from memory on this server.
351 0 : pub(crate) async fn delete_tenant(&self, del_tenant_id: TenantId) -> DatabaseResult<()> {
352 0 : use crate::schema::tenant_shards::dsl::*;
353 0 : self.with_measured_conn(
354 0 : DatabaseOperation::DeleteTenant,
355 0 : move |conn| -> DatabaseResult<()> {
356 0 : diesel::delete(tenant_shards)
357 0 : .filter(tenant_id.eq(del_tenant_id.to_string()))
358 0 : .execute(conn)?;
359 :
360 0 : Ok(())
361 0 : },
362 0 : )
363 0 : .await
364 0 : }
365 :
366 0 : pub(crate) async fn delete_node(&self, del_node_id: NodeId) -> DatabaseResult<()> {
367 0 : use crate::schema::nodes::dsl::*;
368 0 : self.with_measured_conn(
369 0 : DatabaseOperation::DeleteNode,
370 0 : move |conn| -> DatabaseResult<()> {
371 0 : diesel::delete(nodes)
372 0 : .filter(node_id.eq(del_node_id.0 as i64))
373 0 : .execute(conn)?;
374 :
375 0 : Ok(())
376 0 : },
377 0 : )
378 0 : .await
379 0 : }
380 :
381 : /// When a tenant invokes the /re-attach API, this function is responsible for doing an efficient
382 : /// batched increment of the generations of all tenants whose generation_pageserver is equal to
383 : /// the node that called /re-attach.
384 0 : #[tracing::instrument(skip_all, fields(node_id))]
385 : pub(crate) async fn re_attach(
386 : &self,
387 : node_id: NodeId,
388 : ) -> DatabaseResult<HashMap<TenantShardId, Generation>> {
389 : use crate::schema::tenant_shards::dsl::*;
390 : let updated = self
391 0 : .with_measured_conn(DatabaseOperation::ReAttach, move |conn| {
392 0 : let rows_updated = diesel::update(tenant_shards)
393 0 : .filter(generation_pageserver.eq(node_id.0 as i64))
394 0 : .set(generation.eq(generation + 1))
395 0 : .execute(conn)?;
396 :
397 0 : tracing::info!("Incremented {} tenants' generations", rows_updated);
398 :
399 : // TODO: UPDATE+SELECT in one query
400 :
401 0 : let updated = tenant_shards
402 0 : .filter(generation_pageserver.eq(node_id.0 as i64))
403 0 : .select(TenantShardPersistence::as_select())
404 0 : .load(conn)?;
405 0 : Ok(updated)
406 0 : })
407 : .await?;
408 :
409 : let mut result = HashMap::new();
410 : for tsp in updated {
411 : let tenant_shard_id = TenantShardId {
412 : tenant_id: TenantId::from_str(tsp.tenant_id.as_str())
413 0 : .map_err(|e| DatabaseError::Logical(format!("Malformed tenant id: {e}")))?,
414 : shard_number: ShardNumber(tsp.shard_number as u8),
415 : shard_count: ShardCount::new(tsp.shard_count as u8),
416 : };
417 :
418 : let Some(g) = tsp.generation else {
419 : // If the generation_pageserver column was non-NULL, then the generation column should also be non-NULL:
420 : // we only set generation_pageserver when setting generation.
421 : return Err(DatabaseError::Logical(
422 : "Generation should always be set after incrementing".to_string(),
423 : ));
424 : };
425 : result.insert(tenant_shard_id, Generation::new(g as u32));
426 : }
427 :
428 : Ok(result)
429 : }
430 :
431 : /// Reconciler calls this immediately before attaching to a new pageserver, to acquire a unique, monotonically
432 : /// advancing generation number. We also store the NodeId for which the generation was issued, so that in
433 : /// [`Self::re_attach`] we can do a bulk UPDATE on the generations for that node.
434 0 : pub(crate) async fn increment_generation(
435 0 : &self,
436 0 : tenant_shard_id: TenantShardId,
437 0 : node_id: NodeId,
438 0 : ) -> anyhow::Result<Generation> {
439 : use crate::schema::tenant_shards::dsl::*;
440 0 : let updated = self
441 0 : .with_measured_conn(DatabaseOperation::IncrementGeneration, move |conn| {
442 0 : let updated = diesel::update(tenant_shards)
443 0 : .filter(tenant_id.eq(tenant_shard_id.tenant_id.to_string()))
444 0 : .filter(shard_number.eq(tenant_shard_id.shard_number.0 as i32))
445 0 : .filter(shard_count.eq(tenant_shard_id.shard_count.literal() as i32))
446 0 : .set((
447 0 : generation.eq(generation + 1),
448 0 : generation_pageserver.eq(node_id.0 as i64),
449 0 : ))
450 0 : // TODO: only returning() the generation column
451 0 : .returning(TenantShardPersistence::as_returning())
452 0 : .get_result(conn)?;
453 :
454 0 : Ok(updated)
455 0 : })
456 0 : .await?;
457 :
458 : // Generation is always non-null in the rseult: if the generation column had been NULL, then we
459 : // should have experienced an SQL Confilict error while executing a query that tries to increment it.
460 0 : debug_assert!(updated.generation.is_some());
461 0 : let Some(g) = updated.generation else {
462 0 : return Err(DatabaseError::Logical(
463 0 : "Generation should always be set after incrementing".to_string(),
464 0 : )
465 0 : .into());
466 : };
467 :
468 0 : Ok(Generation::new(g as u32))
469 0 : }
470 :
471 : /// For use when updating a persistent property of a tenant, such as its config or placement_policy.
472 : ///
473 : /// Do not use this for settting generation, unless in the special onboarding code path (/location_config)
474 : /// API: use [`Self::increment_generation`] instead. Setting the generation via this route is a one-time thing
475 : /// that we only do the first time a tenant is set to an attached policy via /location_config.
476 0 : pub(crate) async fn update_tenant_shard(
477 0 : &self,
478 0 : tenant: TenantFilter,
479 0 : input_placement_policy: Option<PlacementPolicy>,
480 0 : input_config: Option<TenantConfig>,
481 0 : input_generation: Option<Generation>,
482 0 : input_scheduling_policy: Option<ShardSchedulingPolicy>,
483 0 : ) -> DatabaseResult<()> {
484 0 : use crate::schema::tenant_shards::dsl::*;
485 0 :
486 0 : self.with_measured_conn(DatabaseOperation::UpdateTenantShard, move |conn| {
487 0 : let query = match tenant {
488 0 : TenantFilter::Shard(tenant_shard_id) => diesel::update(tenant_shards)
489 0 : .filter(tenant_id.eq(tenant_shard_id.tenant_id.to_string()))
490 0 : .filter(shard_number.eq(tenant_shard_id.shard_number.0 as i32))
491 0 : .filter(shard_count.eq(tenant_shard_id.shard_count.literal() as i32))
492 0 : .into_boxed(),
493 0 : TenantFilter::Tenant(input_tenant_id) => diesel::update(tenant_shards)
494 0 : .filter(tenant_id.eq(input_tenant_id.to_string()))
495 0 : .into_boxed(),
496 : };
497 :
498 0 : #[derive(AsChangeset)]
499 : #[diesel(table_name = crate::schema::tenant_shards)]
500 : struct ShardUpdate {
501 : generation: Option<i32>,
502 : placement_policy: Option<String>,
503 : config: Option<String>,
504 : scheduling_policy: Option<String>,
505 : }
506 :
507 0 : let update = ShardUpdate {
508 0 : generation: input_generation.map(|g| g.into().unwrap() as i32),
509 0 : placement_policy: input_placement_policy
510 0 : .map(|p| serde_json::to_string(&p).unwrap()),
511 0 : config: input_config.map(|c| serde_json::to_string(&c).unwrap()),
512 0 : scheduling_policy: input_scheduling_policy
513 0 : .map(|p| serde_json::to_string(&p).unwrap()),
514 0 : };
515 0 :
516 0 : query.set(update).execute(conn)?;
517 :
518 0 : Ok(())
519 0 : })
520 0 : .await?;
521 :
522 0 : Ok(())
523 0 : }
524 :
525 0 : pub(crate) async fn detach(&self, tenant_shard_id: TenantShardId) -> anyhow::Result<()> {
526 0 : use crate::schema::tenant_shards::dsl::*;
527 0 : self.with_measured_conn(DatabaseOperation::Detach, move |conn| {
528 0 : let updated = diesel::update(tenant_shards)
529 0 : .filter(tenant_id.eq(tenant_shard_id.tenant_id.to_string()))
530 0 : .filter(shard_number.eq(tenant_shard_id.shard_number.0 as i32))
531 0 : .filter(shard_count.eq(tenant_shard_id.shard_count.literal() as i32))
532 0 : .set((
533 0 : generation_pageserver.eq(Option::<i64>::None),
534 0 : placement_policy.eq(serde_json::to_string(&PlacementPolicy::Detached).unwrap()),
535 0 : ))
536 0 : .execute(conn)?;
537 :
538 0 : Ok(updated)
539 0 : })
540 0 : .await?;
541 :
542 0 : Ok(())
543 0 : }
544 :
545 : // When we start shard splitting, we must durably mark the tenant so that
546 : // on restart, we know that we must go through recovery.
547 : //
548 : // We create the child shards here, so that they will be available for increment_generation calls
549 : // if some pageserver holding a child shard needs to restart before the overall tenant split is complete.
550 0 : pub(crate) async fn begin_shard_split(
551 0 : &self,
552 0 : old_shard_count: ShardCount,
553 0 : split_tenant_id: TenantId,
554 0 : parent_to_children: Vec<(TenantShardId, Vec<TenantShardPersistence>)>,
555 0 : ) -> DatabaseResult<()> {
556 0 : use crate::schema::tenant_shards::dsl::*;
557 0 : self.with_measured_conn(DatabaseOperation::BeginShardSplit, move |conn| -> DatabaseResult<()> {
558 0 : conn.transaction(|conn| -> DatabaseResult<()> {
559 : // Mark parent shards as splitting
560 :
561 0 : let updated = diesel::update(tenant_shards)
562 0 : .filter(tenant_id.eq(split_tenant_id.to_string()))
563 0 : .filter(shard_count.eq(old_shard_count.literal() as i32))
564 0 : .set((splitting.eq(1),))
565 0 : .execute(conn)?;
566 0 : if u8::try_from(updated)
567 0 : .map_err(|_| DatabaseError::Logical(
568 0 : format!("Overflow existing shard count {} while splitting", updated))
569 0 : )? != old_shard_count.count() {
570 : // Perhaps a deletion or another split raced with this attempt to split, mutating
571 : // the parent shards that we intend to split. In this case the split request should fail.
572 0 : return Err(DatabaseError::Logical(
573 0 : format!("Unexpected existing shard count {updated} when preparing tenant for split (expected {})", old_shard_count.count())
574 0 : ));
575 0 : }
576 0 :
577 0 : // FIXME: spurious clone to sidestep closure move rules
578 0 : let parent_to_children = parent_to_children.clone();
579 :
580 : // Insert child shards
581 0 : for (parent_shard_id, children) in parent_to_children {
582 0 : let mut parent = crate::schema::tenant_shards::table
583 0 : .filter(tenant_id.eq(parent_shard_id.tenant_id.to_string()))
584 0 : .filter(shard_number.eq(parent_shard_id.shard_number.0 as i32))
585 0 : .filter(shard_count.eq(parent_shard_id.shard_count.literal() as i32))
586 0 : .load::<TenantShardPersistence>(conn)?;
587 0 : let parent = if parent.len() != 1 {
588 0 : return Err(DatabaseError::Logical(format!(
589 0 : "Parent shard {parent_shard_id} not found"
590 0 : )));
591 : } else {
592 0 : parent.pop().unwrap()
593 : };
594 0 : for mut shard in children {
595 : // Carry the parent's generation into the child
596 0 : shard.generation = parent.generation;
597 0 :
598 0 : debug_assert!(shard.splitting == SplitState::Splitting);
599 0 : diesel::insert_into(tenant_shards)
600 0 : .values(shard)
601 0 : .execute(conn)?;
602 : }
603 : }
604 :
605 0 : Ok(())
606 0 : })?;
607 :
608 0 : Ok(())
609 0 : })
610 0 : .await
611 0 : }
612 :
613 : // When we finish shard splitting, we must atomically clean up the old shards
614 : // and insert the new shards, and clear the splitting marker.
615 0 : pub(crate) async fn complete_shard_split(
616 0 : &self,
617 0 : split_tenant_id: TenantId,
618 0 : old_shard_count: ShardCount,
619 0 : ) -> DatabaseResult<()> {
620 0 : use crate::schema::tenant_shards::dsl::*;
621 0 : self.with_measured_conn(
622 0 : DatabaseOperation::CompleteShardSplit,
623 0 : move |conn| -> DatabaseResult<()> {
624 0 : conn.transaction(|conn| -> QueryResult<()> {
625 0 : // Drop parent shards
626 0 : diesel::delete(tenant_shards)
627 0 : .filter(tenant_id.eq(split_tenant_id.to_string()))
628 0 : .filter(shard_count.eq(old_shard_count.literal() as i32))
629 0 : .execute(conn)?;
630 :
631 : // Clear sharding flag
632 0 : let updated = diesel::update(tenant_shards)
633 0 : .filter(tenant_id.eq(split_tenant_id.to_string()))
634 0 : .set((splitting.eq(0),))
635 0 : .execute(conn)?;
636 0 : debug_assert!(updated > 0);
637 :
638 0 : Ok(())
639 0 : })?;
640 :
641 0 : Ok(())
642 0 : },
643 0 : )
644 0 : .await
645 0 : }
646 :
647 : /// Used when the remote part of a shard split failed: we will revert the database state to have only
648 : /// the parent shards, with SplitState::Idle.
649 0 : pub(crate) async fn abort_shard_split(
650 0 : &self,
651 0 : split_tenant_id: TenantId,
652 0 : new_shard_count: ShardCount,
653 0 : ) -> DatabaseResult<AbortShardSplitStatus> {
654 0 : use crate::schema::tenant_shards::dsl::*;
655 0 : self.with_measured_conn(
656 0 : DatabaseOperation::AbortShardSplit,
657 0 : move |conn| -> DatabaseResult<AbortShardSplitStatus> {
658 0 : let aborted =
659 0 : conn.transaction(|conn| -> DatabaseResult<AbortShardSplitStatus> {
660 : // Clear the splitting state on parent shards
661 0 : let updated = diesel::update(tenant_shards)
662 0 : .filter(tenant_id.eq(split_tenant_id.to_string()))
663 0 : .filter(shard_count.ne(new_shard_count.literal() as i32))
664 0 : .set((splitting.eq(0),))
665 0 : .execute(conn)?;
666 :
667 : // Parent shards are already gone: we cannot abort.
668 0 : if updated == 0 {
669 0 : return Ok(AbortShardSplitStatus::Complete);
670 0 : }
671 0 :
672 0 : // Sanity check: if parent shards were present, their cardinality should
673 0 : // be less than the number of child shards.
674 0 : if updated >= new_shard_count.count() as usize {
675 0 : return Err(DatabaseError::Logical(format!(
676 0 : "Unexpected parent shard count {updated} while aborting split to \
677 0 : count {new_shard_count:?} on tenant {split_tenant_id}"
678 0 : )));
679 0 : }
680 0 :
681 0 : // Erase child shards
682 0 : diesel::delete(tenant_shards)
683 0 : .filter(tenant_id.eq(split_tenant_id.to_string()))
684 0 : .filter(shard_count.eq(new_shard_count.literal() as i32))
685 0 : .execute(conn)?;
686 :
687 0 : Ok(AbortShardSplitStatus::Aborted)
688 0 : })?;
689 :
690 0 : Ok(aborted)
691 0 : },
692 0 : )
693 0 : .await
694 0 : }
695 : }
696 :
697 : /// Parts of [`crate::tenant_shard::TenantShard`] that are stored durably
698 0 : #[derive(Queryable, Selectable, Insertable, Serialize, Deserialize, Clone, Eq, PartialEq)]
699 : #[diesel(table_name = crate::schema::tenant_shards)]
700 : pub(crate) struct TenantShardPersistence {
701 : #[serde(default)]
702 : pub(crate) tenant_id: String,
703 : #[serde(default)]
704 : pub(crate) shard_number: i32,
705 : #[serde(default)]
706 : pub(crate) shard_count: i32,
707 : #[serde(default)]
708 : pub(crate) shard_stripe_size: i32,
709 :
710 : // Latest generation number: next time we attach, increment this
711 : // and use the incremented number when attaching.
712 : //
713 : // Generation is only None when first onboarding a tenant, where it may
714 : // be in PlacementPolicy::Secondary and therefore have no valid generation state.
715 : pub(crate) generation: Option<i32>,
716 :
717 : // Currently attached pageserver
718 : #[serde(rename = "pageserver")]
719 : pub(crate) generation_pageserver: Option<i64>,
720 :
721 : #[serde(default)]
722 : pub(crate) placement_policy: String,
723 : #[serde(default)]
724 : pub(crate) splitting: SplitState,
725 : #[serde(default)]
726 : pub(crate) config: String,
727 : #[serde(default)]
728 : pub(crate) scheduling_policy: String,
729 : }
730 :
731 : impl TenantShardPersistence {
732 0 : pub(crate) fn get_shard_identity(&self) -> Result<ShardIdentity, ShardConfigError> {
733 0 : if self.shard_count == 0 {
734 0 : Ok(ShardIdentity::unsharded())
735 : } else {
736 0 : Ok(ShardIdentity::new(
737 0 : ShardNumber(self.shard_number as u8),
738 0 : ShardCount::new(self.shard_count as u8),
739 0 : ShardStripeSize(self.shard_stripe_size as u32),
740 0 : )?)
741 : }
742 0 : }
743 :
744 0 : pub(crate) fn get_tenant_shard_id(&self) -> Result<TenantShardId, hex::FromHexError> {
745 0 : Ok(TenantShardId {
746 0 : tenant_id: TenantId::from_str(self.tenant_id.as_str())?,
747 0 : shard_number: ShardNumber(self.shard_number as u8),
748 0 : shard_count: ShardCount::new(self.shard_count as u8),
749 : })
750 0 : }
751 : }
752 :
753 : /// Parts of [`crate::node::Node`] that are stored durably
754 0 : #[derive(Serialize, Deserialize, Queryable, Selectable, Insertable, Eq, PartialEq)]
755 : #[diesel(table_name = crate::schema::nodes)]
756 : pub(crate) struct NodePersistence {
757 : pub(crate) node_id: i64,
758 : pub(crate) scheduling_policy: String,
759 : pub(crate) listen_http_addr: String,
760 : pub(crate) listen_http_port: i32,
761 : pub(crate) listen_pg_addr: String,
762 : pub(crate) listen_pg_port: i32,
763 : }
|