Line data Source code
1 : pub mod chaos_injector;
2 : mod context_iterator;
3 :
4 : use std::borrow::Cow;
5 : use std::cmp::Ordering;
6 : use std::collections::{BTreeMap, HashMap, HashSet};
7 : use std::error::Error;
8 : use std::num::NonZeroU32;
9 : use std::ops::Deref;
10 : use std::path::PathBuf;
11 : use std::str::FromStr;
12 : use std::sync::Arc;
13 : use std::time::{Duration, Instant};
14 :
15 : use anyhow::Context;
16 : use context_iterator::TenantShardContextIterator;
17 : use control_plane::storage_controller::{
18 : AttachHookRequest, AttachHookResponse, InspectRequest, InspectResponse,
19 : };
20 : use diesel::result::DatabaseErrorKind;
21 : use futures::StreamExt;
22 : use futures::stream::FuturesUnordered;
23 : use http_utils::error::ApiError;
24 : use hyper::Uri;
25 : use itertools::Itertools;
26 : use pageserver_api::controller_api::{
27 : AvailabilityZone, MetadataHealthRecord, MetadataHealthUpdateRequest, NodeAvailability,
28 : NodeRegisterRequest, NodeSchedulingPolicy, NodeShard, NodeShardResponse, PlacementPolicy,
29 : SafekeeperDescribeResponse, ShardSchedulingPolicy, ShardsPreferredAzsRequest,
30 : ShardsPreferredAzsResponse, SkSchedulingPolicy, TenantCreateRequest, TenantCreateResponse,
31 : TenantCreateResponseShard, TenantDescribeResponse, TenantDescribeResponseShard,
32 : TenantLocateResponse, TenantPolicyRequest, TenantShardMigrateRequest,
33 : TenantShardMigrateResponse,
34 : };
35 : use pageserver_api::models::{
36 : self, LocationConfig, LocationConfigListResponse, LocationConfigMode, PageserverUtilization,
37 : SecondaryProgress, ShardParameters, TenantConfig, TenantConfigPatchRequest,
38 : TenantConfigRequest, TenantLocationConfigRequest, TenantLocationConfigResponse,
39 : TenantShardLocation, TenantShardSplitRequest, TenantShardSplitResponse,
40 : TenantTimeTravelRequest, TimelineArchivalConfigRequest, TimelineCreateRequest, TimelineInfo,
41 : TopTenantShardsRequest,
42 : };
43 : use pageserver_api::shard::{
44 : ShardCount, ShardIdentity, ShardNumber, ShardStripeSize, TenantShardId,
45 : };
46 : use pageserver_api::upcall_api::{
47 : ReAttachRequest, ReAttachResponse, ReAttachResponseTenant, ValidateRequest, ValidateResponse,
48 : ValidateResponseTenant,
49 : };
50 : use pageserver_client::{BlockUnblock, mgmt_api};
51 : use reqwest::StatusCode;
52 : use safekeeper_api::models::SafekeeperUtilization;
53 : use tokio::sync::TryAcquireError;
54 : use tokio::sync::mpsc::error::TrySendError;
55 : use tokio_util::sync::CancellationToken;
56 : use tracing::{Instrument, instrument};
57 : use utils::completion::Barrier;
58 : use utils::generation::Generation;
59 : use utils::id::{NodeId, TenantId, TimelineId};
60 : use utils::sync::gate::Gate;
61 : use utils::{failpoint_support, pausable_failpoint};
62 :
63 : use crate::background_node_operations::{
64 : Drain, Fill, MAX_RECONCILES_PER_OPERATION, Operation, OperationError, OperationHandler,
65 : };
66 : use crate::compute_hook::{self, ComputeHook, NotifyError};
67 : use crate::drain_utils::{self, TenantShardDrain, TenantShardIterator};
68 : use crate::heartbeater::{Heartbeater, PageserverState, SafekeeperState};
69 : use crate::id_lock_map::{
70 : IdLockMap, TracingExclusiveGuard, trace_exclusive_lock, trace_shared_lock,
71 : };
72 : use crate::leadership::Leadership;
73 : use crate::metrics;
74 : use crate::node::{AvailabilityTransition, Node};
75 : use crate::pageserver_client::PageserverClient;
76 : use crate::peer_client::GlobalObservedState;
77 : use crate::persistence::split_state::SplitState;
78 : use crate::persistence::{
79 : AbortShardSplitStatus, ControllerPersistence, DatabaseError, DatabaseResult,
80 : MetadataHealthPersistence, Persistence, ShardGenerationState, TenantFilter,
81 : TenantShardPersistence,
82 : };
83 : use crate::reconciler::{
84 : ReconcileError, ReconcileUnits, ReconcilerConfig, ReconcilerConfigBuilder, ReconcilerPriority,
85 : attached_location_conf,
86 : };
87 : use crate::safekeeper::Safekeeper;
88 : use crate::scheduler::{MaySchedule, ScheduleContext, ScheduleError, ScheduleMode, Scheduler};
89 : use crate::tenant_shard::{
90 : IntentState, MigrateAttachment, ObservedState, ObservedStateDelta, ObservedStateLocation,
91 : ReconcileNeeded, ReconcileResult, ReconcileWaitError, ReconcilerStatus, ReconcilerWaiter,
92 : ScheduleOptimization, ScheduleOptimizationAction, TenantShard,
93 : };
94 :
95 : const WAITER_FILL_DRAIN_POLL_TIMEOUT: Duration = Duration::from_millis(500);
96 :
97 : // For operations that should be quick, like attaching a new tenant
98 : const SHORT_RECONCILE_TIMEOUT: Duration = Duration::from_secs(5);
99 :
100 : // For operations that might be slow, like migrating a tenant with
101 : // some data in it.
102 : pub const RECONCILE_TIMEOUT: Duration = Duration::from_secs(30);
103 :
104 : // If we receive a call using Secondary mode initially, it will omit generation. We will initialize
105 : // tenant shards into this generation, and as long as it remains in this generation, we will accept
106 : // input generation from future requests as authoritative.
107 : const INITIAL_GENERATION: Generation = Generation::new(0);
108 :
109 : /// How long [`Service::startup_reconcile`] is allowed to take before it should give
110 : /// up on unresponsive pageservers and proceed.
111 : pub(crate) const STARTUP_RECONCILE_TIMEOUT: Duration = Duration::from_secs(30);
112 :
113 : /// How long a node may be unresponsive to heartbeats before we declare it offline.
114 : /// This must be long enough to cover node restarts as well as normal operations: in future
115 : pub const MAX_OFFLINE_INTERVAL_DEFAULT: Duration = Duration::from_secs(30);
116 :
117 : /// How long a node may be unresponsive to heartbeats during start up before we declare it
118 : /// offline.
119 : ///
120 : /// This is much more lenient than [`MAX_OFFLINE_INTERVAL_DEFAULT`] since the pageserver's
121 : /// handling of the re-attach response may take a long time and blocks heartbeats from
122 : /// being handled on the pageserver side.
123 : pub const MAX_WARMING_UP_INTERVAL_DEFAULT: Duration = Duration::from_secs(300);
124 :
125 : /// How often to send heartbeats to registered nodes?
126 : pub const HEARTBEAT_INTERVAL_DEFAULT: Duration = Duration::from_secs(5);
127 :
128 : /// How long is too long for a reconciliation?
129 : pub const LONG_RECONCILE_THRESHOLD_DEFAULT: Duration = Duration::from_secs(120);
130 :
131 : #[derive(Clone, strum_macros::Display)]
132 : enum TenantOperations {
133 : Create,
134 : LocationConfig,
135 : ConfigSet,
136 : ConfigPatch,
137 : TimeTravelRemoteStorage,
138 : Delete,
139 : UpdatePolicy,
140 : ShardSplit,
141 : SecondaryDownload,
142 : TimelineCreate,
143 : TimelineDelete,
144 : AttachHook,
145 : TimelineArchivalConfig,
146 : TimelineDetachAncestor,
147 : TimelineGcBlockUnblock,
148 : DropDetached,
149 : DownloadHeatmapLayers,
150 : }
151 :
152 : #[derive(Clone, strum_macros::Display)]
153 : enum NodeOperations {
154 : Register,
155 : Configure,
156 : Delete,
157 : }
158 :
159 : /// The leadership status for the storage controller process.
160 : /// Allowed transitions are:
161 : /// 1. Leader -> SteppedDown
162 : /// 2. Candidate -> Leader
163 : #[derive(
164 : Eq,
165 : PartialEq,
166 : Copy,
167 : Clone,
168 : strum_macros::Display,
169 0 : strum_macros::EnumIter,
170 : measured::FixedCardinalityLabel,
171 : )]
172 : #[strum(serialize_all = "snake_case")]
173 : pub(crate) enum LeadershipStatus {
174 : /// This is the steady state where the storage controller can produce
175 : /// side effects in the cluster.
176 : Leader,
177 : /// We've been notified to step down by another candidate. No reconciliations
178 : /// take place in this state.
179 : SteppedDown,
180 : /// Initial state for a new storage controller instance. Will attempt to assume leadership.
181 : #[allow(unused)]
182 : Candidate,
183 : }
184 :
185 : pub const RECONCILER_CONCURRENCY_DEFAULT: usize = 128;
186 : pub const PRIORITY_RECONCILER_CONCURRENCY_DEFAULT: usize = 256;
187 :
188 : // Depth of the channel used to enqueue shards for reconciliation when they can't do it immediately.
189 : // This channel is finite-size to avoid using excessive memory if we get into a state where reconciles are finishing more slowly
190 : // than they're being pushed onto the queue.
191 : const MAX_DELAYED_RECONCILES: usize = 10000;
192 :
193 : // Top level state available to all HTTP handlers
194 : struct ServiceState {
195 : leadership_status: LeadershipStatus,
196 :
197 : tenants: BTreeMap<TenantShardId, TenantShard>,
198 :
199 : nodes: Arc<HashMap<NodeId, Node>>,
200 :
201 : safekeepers: Arc<HashMap<NodeId, Safekeeper>>,
202 :
203 : scheduler: Scheduler,
204 :
205 : /// Ongoing background operation on the cluster if any is running.
206 : /// Note that only one such operation may run at any given time,
207 : /// hence the type choice.
208 : ongoing_operation: Option<OperationHandler>,
209 :
210 : /// Queue of tenants who are waiting for concurrency limits to permit them to reconcile
211 : delayed_reconcile_rx: tokio::sync::mpsc::Receiver<TenantShardId>,
212 : }
213 :
214 : /// Transform an error from a pageserver into an error to return to callers of a storage
215 : /// controller API.
216 0 : fn passthrough_api_error(node: &Node, e: mgmt_api::Error) -> ApiError {
217 0 : match e {
218 0 : mgmt_api::Error::SendRequest(e) => {
219 0 : // Presume errors sending requests are connectivity/availability issues
220 0 : ApiError::ResourceUnavailable(format!("{node} error sending request: {e}").into())
221 : }
222 0 : mgmt_api::Error::ReceiveErrorBody(str) => {
223 0 : // Presume errors receiving body are connectivity/availability issues
224 0 : ApiError::ResourceUnavailable(
225 0 : format!("{node} error receiving error body: {str}").into(),
226 0 : )
227 : }
228 0 : mgmt_api::Error::ReceiveBody(err) if err.is_decode() => {
229 0 : // Return 500 for decoding errors.
230 0 : ApiError::InternalServerError(anyhow::Error::from(err).context("error decoding body"))
231 : }
232 0 : mgmt_api::Error::ReceiveBody(err) => {
233 0 : // Presume errors receiving body are connectivity/availability issues except for decoding errors
234 0 : let src_str = err.source().map(|e| e.to_string()).unwrap_or_default();
235 0 : ApiError::ResourceUnavailable(
236 0 : format!("{node} error receiving error body: {err} {}", src_str).into(),
237 0 : )
238 : }
239 0 : mgmt_api::Error::ApiError(StatusCode::NOT_FOUND, msg) => {
240 0 : ApiError::NotFound(anyhow::anyhow!(format!("{node}: {msg}")).into())
241 : }
242 0 : mgmt_api::Error::ApiError(StatusCode::SERVICE_UNAVAILABLE, msg) => {
243 0 : ApiError::ResourceUnavailable(format!("{node}: {msg}").into())
244 : }
245 0 : mgmt_api::Error::ApiError(status @ StatusCode::UNAUTHORIZED, msg)
246 0 : | mgmt_api::Error::ApiError(status @ StatusCode::FORBIDDEN, msg) => {
247 : // Auth errors talking to a pageserver are not auth errors for the caller: they are
248 : // internal server errors, showing that something is wrong with the pageserver or
249 : // storage controller's auth configuration.
250 0 : ApiError::InternalServerError(anyhow::anyhow!("{node} {status}: {msg}"))
251 : }
252 0 : mgmt_api::Error::ApiError(status @ StatusCode::TOO_MANY_REQUESTS, msg) => {
253 0 : // Pass through 429 errors: if pageserver is asking us to wait + retry, we in
254 0 : // turn ask our clients to wait + retry
255 0 : ApiError::Conflict(format!("{node} {status}: {status} {msg}"))
256 : }
257 0 : mgmt_api::Error::ApiError(status, msg) => {
258 0 : // Presume general case of pageserver API errors is that we tried to do something
259 0 : // that can't be done right now.
260 0 : ApiError::Conflict(format!("{node} {status}: {status} {msg}"))
261 : }
262 0 : mgmt_api::Error::Cancelled => ApiError::ShuttingDown,
263 : }
264 0 : }
265 :
266 : impl ServiceState {
267 0 : fn new(
268 0 : nodes: HashMap<NodeId, Node>,
269 0 : safekeepers: HashMap<NodeId, Safekeeper>,
270 0 : tenants: BTreeMap<TenantShardId, TenantShard>,
271 0 : scheduler: Scheduler,
272 0 : delayed_reconcile_rx: tokio::sync::mpsc::Receiver<TenantShardId>,
273 0 : initial_leadership_status: LeadershipStatus,
274 0 : ) -> Self {
275 0 : metrics::update_leadership_status(initial_leadership_status);
276 0 :
277 0 : Self {
278 0 : leadership_status: initial_leadership_status,
279 0 : tenants,
280 0 : nodes: Arc::new(nodes),
281 0 : safekeepers: Arc::new(safekeepers),
282 0 : scheduler,
283 0 : ongoing_operation: None,
284 0 : delayed_reconcile_rx,
285 0 : }
286 0 : }
287 :
288 0 : fn parts_mut(
289 0 : &mut self,
290 0 : ) -> (
291 0 : &mut Arc<HashMap<NodeId, Node>>,
292 0 : &mut BTreeMap<TenantShardId, TenantShard>,
293 0 : &mut Scheduler,
294 0 : ) {
295 0 : (&mut self.nodes, &mut self.tenants, &mut self.scheduler)
296 0 : }
297 :
298 : #[allow(clippy::type_complexity)]
299 0 : fn parts_mut_sk(
300 0 : &mut self,
301 0 : ) -> (
302 0 : &mut Arc<HashMap<NodeId, Node>>,
303 0 : &mut Arc<HashMap<NodeId, Safekeeper>>,
304 0 : &mut BTreeMap<TenantShardId, TenantShard>,
305 0 : &mut Scheduler,
306 0 : ) {
307 0 : (
308 0 : &mut self.nodes,
309 0 : &mut self.safekeepers,
310 0 : &mut self.tenants,
311 0 : &mut self.scheduler,
312 0 : )
313 0 : }
314 :
315 0 : fn get_leadership_status(&self) -> LeadershipStatus {
316 0 : self.leadership_status
317 0 : }
318 :
319 0 : fn step_down(&mut self) {
320 0 : self.leadership_status = LeadershipStatus::SteppedDown;
321 0 : metrics::update_leadership_status(self.leadership_status);
322 0 : }
323 :
324 0 : fn become_leader(&mut self) {
325 0 : self.leadership_status = LeadershipStatus::Leader;
326 0 : metrics::update_leadership_status(self.leadership_status);
327 0 : }
328 : }
329 :
330 : #[derive(Clone)]
331 : pub struct Config {
332 : // All pageservers managed by one instance of this service must have
333 : // the same public key. This JWT token will be used to authenticate
334 : // this service to the pageservers it manages.
335 : pub pageserver_jwt_token: Option<String>,
336 :
337 : // All safekeepers managed by one instance of this service must have
338 : // the same public key. This JWT token will be used to authenticate
339 : // this service to the safekeepers it manages.
340 : pub safekeeper_jwt_token: Option<String>,
341 :
342 : // This JWT token will be used to authenticate this service to the control plane.
343 : pub control_plane_jwt_token: Option<String>,
344 :
345 : // This JWT token will be used to authenticate with other storage controller instances
346 : pub peer_jwt_token: Option<String>,
347 :
348 : /// Where the compute hook should send notifications of pageserver attachment locations
349 : /// (this URL points to the control plane in prod). If this is None, the compute hook will
350 : /// assume it is running in a test environment and try to update neon_local.
351 : pub compute_hook_url: Option<String>,
352 :
353 : /// Grace period within which a pageserver does not respond to heartbeats, but is still
354 : /// considered active. Once the grace period elapses, the next heartbeat failure will
355 : /// mark the pagseserver offline.
356 : pub max_offline_interval: Duration,
357 :
358 : /// Extended grace period within which pageserver may not respond to heartbeats.
359 : /// This extended grace period kicks in after the node has been drained for restart
360 : /// and/or upon handling the re-attach request from a node.
361 : pub max_warming_up_interval: Duration,
362 :
363 : /// How many normal-priority Reconcilers may be spawned concurrently
364 : pub reconciler_concurrency: usize,
365 :
366 : /// How many high-priority Reconcilers may be spawned concurrently
367 : pub priority_reconciler_concurrency: usize,
368 :
369 : /// How many API requests per second to allow per tenant, across all
370 : /// tenant-scoped API endpoints. Further API requests queue until ready.
371 : pub tenant_rate_limit: NonZeroU32,
372 :
373 : /// How large must a shard grow in bytes before we split it?
374 : /// None disables auto-splitting.
375 : pub split_threshold: Option<u64>,
376 :
377 : // TODO: make this cfg(feature = "testing")
378 : pub neon_local_repo_dir: Option<PathBuf>,
379 :
380 : // Maximum acceptable download lag for the secondary location
381 : // while draining a node. If the secondary location is lagging
382 : // by more than the configured amount, then the secondary is not
383 : // upgraded to primary.
384 : pub max_secondary_lag_bytes: Option<u64>,
385 :
386 : pub heartbeat_interval: Duration,
387 :
388 : pub address_for_peers: Option<Uri>,
389 :
390 : pub start_as_candidate: bool,
391 :
392 : pub http_service_port: i32,
393 :
394 : pub long_reconcile_threshold: Duration,
395 :
396 : pub use_https_pageserver_api: bool,
397 :
398 : pub load_safekeepers: bool,
399 : }
400 :
401 : impl From<DatabaseError> for ApiError {
402 0 : fn from(err: DatabaseError) -> ApiError {
403 0 : match err {
404 0 : DatabaseError::Query(e) => ApiError::InternalServerError(e.into()),
405 : // FIXME: ApiError doesn't have an Unavailable variant, but ShuttingDown maps to 503.
406 : DatabaseError::Connection(_) | DatabaseError::ConnectionPool(_) => {
407 0 : ApiError::ShuttingDown
408 : }
409 0 : DatabaseError::Logical(reason) | DatabaseError::Migration(reason) => {
410 0 : ApiError::InternalServerError(anyhow::anyhow!(reason))
411 : }
412 : }
413 0 : }
414 : }
415 :
416 : enum InitialShardScheduleOutcome {
417 : Scheduled(TenantCreateResponseShard),
418 : NotScheduled,
419 : ShardScheduleError(ScheduleError),
420 : }
421 :
422 : pub struct Service {
423 : inner: Arc<std::sync::RwLock<ServiceState>>,
424 : config: Config,
425 : persistence: Arc<Persistence>,
426 : compute_hook: Arc<ComputeHook>,
427 : result_tx: tokio::sync::mpsc::UnboundedSender<ReconcileResultRequest>,
428 :
429 : heartbeater_ps: Heartbeater<Node, PageserverState>,
430 : heartbeater_sk: Heartbeater<Safekeeper, SafekeeperState>,
431 :
432 : // Channel for background cleanup from failed operations that require cleanup, such as shard split
433 : abort_tx: tokio::sync::mpsc::UnboundedSender<TenantShardSplitAbort>,
434 :
435 : // Locking on a tenant granularity (covers all shards in the tenant):
436 : // - Take exclusively for rare operations that mutate the tenant's persistent state (e.g. create/delete/split)
437 : // - Take in shared mode for operations that need the set of shards to stay the same to complete reliably (e.g. timeline CRUD)
438 : tenant_op_locks: IdLockMap<TenantId, TenantOperations>,
439 :
440 : // Locking for node-mutating operations: take exclusively for operations that modify the node's persistent state, or
441 : // that transition it to/from Active.
442 : node_op_locks: IdLockMap<NodeId, NodeOperations>,
443 :
444 : // Limit how many Reconcilers we will spawn concurrently for normal-priority tasks such as background reconciliations
445 : // and reconciliation on startup.
446 : reconciler_concurrency: Arc<tokio::sync::Semaphore>,
447 :
448 : // Limit how many Reconcilers we will spawn concurrently for high-priority tasks such as tenant/timeline CRUD, which
449 : // a human user might be waiting for.
450 : priority_reconciler_concurrency: Arc<tokio::sync::Semaphore>,
451 :
452 : /// Queue of tenants who are waiting for concurrency limits to permit them to reconcile
453 : /// Send into this queue to promptly attempt to reconcile this shard next time units are available.
454 : ///
455 : /// Note that this state logically lives inside ServiceState, but carrying Sender here makes the code simpler
456 : /// by avoiding needing a &mut ref to something inside the ServiceState. This could be optimized to
457 : /// use a VecDeque instead of a channel to reduce synchronization overhead, at the cost of some code complexity.
458 : delayed_reconcile_tx: tokio::sync::mpsc::Sender<TenantShardId>,
459 :
460 : // Process shutdown will fire this token
461 : cancel: CancellationToken,
462 :
463 : // Child token of [`Service::cancel`] used by reconcilers
464 : reconcilers_cancel: CancellationToken,
465 :
466 : // Background tasks will hold this gate
467 : gate: Gate,
468 :
469 : // Reconcilers background tasks will hold this gate
470 : reconcilers_gate: Gate,
471 :
472 : /// This waits for initial reconciliation with pageservers to complete. Until this barrier
473 : /// passes, it isn't safe to do any actions that mutate tenants.
474 : pub(crate) startup_complete: Barrier,
475 : }
476 :
477 : impl From<ReconcileWaitError> for ApiError {
478 0 : fn from(value: ReconcileWaitError) -> Self {
479 0 : match value {
480 0 : ReconcileWaitError::Shutdown => ApiError::ShuttingDown,
481 0 : e @ ReconcileWaitError::Timeout(_) => ApiError::Timeout(format!("{e}").into()),
482 0 : e @ ReconcileWaitError::Failed(..) => ApiError::InternalServerError(anyhow::anyhow!(e)),
483 : }
484 0 : }
485 : }
486 :
487 : impl From<OperationError> for ApiError {
488 0 : fn from(value: OperationError) -> Self {
489 0 : match value {
490 0 : OperationError::NodeStateChanged(err) | OperationError::FinalizeError(err) => {
491 0 : ApiError::InternalServerError(anyhow::anyhow!(err))
492 : }
493 0 : OperationError::Cancelled => ApiError::Conflict("Operation was cancelled".into()),
494 : }
495 0 : }
496 : }
497 :
498 : #[allow(clippy::large_enum_variant)]
499 : enum TenantCreateOrUpdate {
500 : Create(TenantCreateRequest),
501 : Update(Vec<ShardUpdate>),
502 : }
503 :
504 : struct ShardSplitParams {
505 : old_shard_count: ShardCount,
506 : new_shard_count: ShardCount,
507 : new_stripe_size: Option<ShardStripeSize>,
508 : targets: Vec<ShardSplitTarget>,
509 : policy: PlacementPolicy,
510 : config: TenantConfig,
511 : shard_ident: ShardIdentity,
512 : preferred_az_id: Option<AvailabilityZone>,
513 : }
514 :
515 : // When preparing for a shard split, we may either choose to proceed with the split,
516 : // or find that the work is already done and return NoOp.
517 : enum ShardSplitAction {
518 : Split(Box<ShardSplitParams>),
519 : NoOp(TenantShardSplitResponse),
520 : }
521 :
522 : // A parent shard which will be split
523 : struct ShardSplitTarget {
524 : parent_id: TenantShardId,
525 : node: Node,
526 : child_ids: Vec<TenantShardId>,
527 : }
528 :
529 : /// When we tenant shard split operation fails, we may not be able to clean up immediately, because nodes
530 : /// might not be available. We therefore use a queue of abort operations processed in the background.
531 : struct TenantShardSplitAbort {
532 : tenant_id: TenantId,
533 : /// The target values from the request that failed
534 : new_shard_count: ShardCount,
535 : new_stripe_size: Option<ShardStripeSize>,
536 : /// Until this abort op is complete, no other operations may be done on the tenant
537 : _tenant_lock: TracingExclusiveGuard<TenantOperations>,
538 : }
539 :
540 : #[derive(thiserror::Error, Debug)]
541 : enum TenantShardSplitAbortError {
542 : #[error(transparent)]
543 : Database(#[from] DatabaseError),
544 : #[error(transparent)]
545 : Remote(#[from] mgmt_api::Error),
546 : #[error("Unavailable")]
547 : Unavailable,
548 : }
549 :
550 : struct ShardUpdate {
551 : tenant_shard_id: TenantShardId,
552 : placement_policy: PlacementPolicy,
553 : tenant_config: TenantConfig,
554 :
555 : /// If this is None, generation is not updated.
556 : generation: Option<Generation>,
557 :
558 : /// If this is None, scheduling policy is not updated.
559 : scheduling_policy: Option<ShardSchedulingPolicy>,
560 : }
561 :
562 : enum StopReconciliationsReason {
563 : ShuttingDown,
564 : SteppingDown,
565 : }
566 :
567 : impl std::fmt::Display for StopReconciliationsReason {
568 0 : fn fmt(&self, writer: &mut std::fmt::Formatter) -> std::fmt::Result {
569 0 : let s = match self {
570 0 : Self::ShuttingDown => "Shutting down",
571 0 : Self::SteppingDown => "Stepping down",
572 : };
573 0 : write!(writer, "{}", s)
574 0 : }
575 : }
576 :
577 : pub(crate) enum ReconcileResultRequest {
578 : ReconcileResult(ReconcileResult),
579 : Stop,
580 : }
581 :
582 : #[derive(Clone)]
583 : struct MutationLocation {
584 : node: Node,
585 : generation: Generation,
586 : }
587 :
588 : #[derive(Clone)]
589 : struct ShardMutationLocations {
590 : latest: MutationLocation,
591 : other: Vec<MutationLocation>,
592 : }
593 :
594 : #[derive(Default, Clone)]
595 : struct TenantMutationLocations(BTreeMap<TenantShardId, ShardMutationLocations>);
596 :
597 : impl Service {
598 0 : pub fn get_config(&self) -> &Config {
599 0 : &self.config
600 0 : }
601 :
602 : /// Called once on startup, this function attempts to contact all pageservers to build an up-to-date
603 : /// view of the world, and determine which pageservers are responsive.
604 : #[instrument(skip_all)]
605 : async fn startup_reconcile(
606 : self: &Arc<Service>,
607 : current_leader: Option<ControllerPersistence>,
608 : leader_step_down_state: Option<GlobalObservedState>,
609 : bg_compute_notify_result_tx: tokio::sync::mpsc::Sender<
610 : Result<(), (TenantShardId, NotifyError)>,
611 : >,
612 : ) {
613 : // Startup reconciliation does I/O to other services: whether they
614 : // are responsive or not, we should aim to finish within our deadline, because:
615 : // - If we don't, a k8s readiness hook watching /ready will kill us.
616 : // - While we're waiting for startup reconciliation, we are not fully
617 : // available for end user operations like creating/deleting tenants and timelines.
618 : //
619 : // We set multiple deadlines to break up the time available between the phases of work: this is
620 : // arbitrary, but avoids a situation where the first phase could burn our entire timeout period.
621 : let start_at = Instant::now();
622 : let node_scan_deadline = start_at
623 : .checked_add(STARTUP_RECONCILE_TIMEOUT / 2)
624 : .expect("Reconcile timeout is a modest constant");
625 :
626 : let observed = if let Some(state) = leader_step_down_state {
627 : tracing::info!(
628 : "Using observed state received from leader at {}",
629 : current_leader.as_ref().unwrap().address
630 : );
631 :
632 : state
633 : } else {
634 : self.build_global_observed_state(node_scan_deadline).await
635 : };
636 :
637 : // Accumulate a list of any tenant locations that ought to be detached
638 : let mut cleanup = Vec::new();
639 :
640 : // Send initial heartbeat requests to all nodes loaded from the database
641 : let all_nodes = {
642 : let locked = self.inner.read().unwrap();
643 : locked.nodes.clone()
644 : };
645 : let (mut nodes_online, mut sks_online) =
646 : self.initial_heartbeat_round(all_nodes.keys()).await;
647 :
648 : // List of tenants for which we will attempt to notify compute of their location at startup
649 : let mut compute_notifications = Vec::new();
650 :
651 : // Populate intent and observed states for all tenants, based on reported state on pageservers
652 : tracing::info!("Populating tenant shards' states from initial pageserver scan...");
653 : let shard_count = {
654 : let mut locked = self.inner.write().unwrap();
655 : let (nodes, safekeepers, tenants, scheduler) = locked.parts_mut_sk();
656 :
657 : // Mark nodes online if they responded to us: nodes are offline by default after a restart.
658 : let mut new_nodes = (**nodes).clone();
659 : for (node_id, node) in new_nodes.iter_mut() {
660 : if let Some(utilization) = nodes_online.remove(node_id) {
661 : node.set_availability(NodeAvailability::Active(utilization));
662 : scheduler.node_upsert(node);
663 : }
664 : }
665 : *nodes = Arc::new(new_nodes);
666 :
667 : let mut new_sks = (**safekeepers).clone();
668 : for (node_id, node) in new_sks.iter_mut() {
669 : if let Some((utilization, last_seen_at)) = sks_online.remove(node_id) {
670 : node.set_availability(SafekeeperState::Available {
671 : utilization,
672 : last_seen_at,
673 : });
674 : }
675 : }
676 : *safekeepers = Arc::new(new_sks);
677 :
678 : for (tenant_shard_id, observed_state) in observed.0 {
679 : let Some(tenant_shard) = tenants.get_mut(&tenant_shard_id) else {
680 : for node_id in observed_state.locations.keys() {
681 : cleanup.push((tenant_shard_id, *node_id));
682 : }
683 :
684 : continue;
685 : };
686 :
687 : tenant_shard.observed = observed_state;
688 : }
689 :
690 : // Populate each tenant's intent state
691 : let mut schedule_context = ScheduleContext::default();
692 : for (tenant_shard_id, tenant_shard) in tenants.iter_mut() {
693 : if tenant_shard_id.shard_number == ShardNumber(0) {
694 : // Reset scheduling context each time we advance to the next Tenant
695 : schedule_context = ScheduleContext::default();
696 : }
697 :
698 : tenant_shard.intent_from_observed(scheduler);
699 : if let Err(e) = tenant_shard.schedule(scheduler, &mut schedule_context) {
700 : // Non-fatal error: we are unable to properly schedule the tenant, perhaps because
701 : // not enough pageservers are available. The tenant may well still be available
702 : // to clients.
703 : tracing::error!("Failed to schedule tenant {tenant_shard_id} at startup: {e}");
704 : } else {
705 : // If we're both intending and observed to be attached at a particular node, we will
706 : // emit a compute notification for this. In the case where our observed state does not
707 : // yet match our intent, we will eventually reconcile, and that will emit a compute notification.
708 : if let Some(attached_at) = tenant_shard.stably_attached() {
709 : compute_notifications.push(compute_hook::ShardUpdate {
710 : tenant_shard_id: *tenant_shard_id,
711 : node_id: attached_at,
712 : stripe_size: tenant_shard.shard.stripe_size,
713 : preferred_az: tenant_shard
714 : .preferred_az()
715 0 : .map(|az| Cow::Owned(az.clone())),
716 : });
717 : }
718 : }
719 : }
720 :
721 : tenants.len()
722 : };
723 :
724 : // Before making any obeservable changes to the cluster, persist self
725 : // as leader in database and memory.
726 : let leadership = Leadership::new(
727 : self.persistence.clone(),
728 : self.config.clone(),
729 : self.cancel.child_token(),
730 : );
731 :
732 : if let Err(e) = leadership.become_leader(current_leader).await {
733 : tracing::error!("Failed to persist self as leader: {e}. Aborting start-up ...");
734 : std::process::exit(1);
735 : }
736 :
737 : self.inner.write().unwrap().become_leader();
738 :
739 : // TODO: if any tenant's intent now differs from its loaded generation_pageserver, we should clear that
740 : // generation_pageserver in the database.
741 :
742 : // Emit compute hook notifications for all tenants which are already stably attached. Other tenants
743 : // will emit compute hook notifications when they reconcile.
744 : //
745 : // Ordering: our calls to notify_background synchronously establish a relative order for these notifications vs. any later
746 : // calls into the ComputeHook for the same tenant: we can leave these to run to completion in the background and any later
747 : // calls will be correctly ordered wrt these.
748 : //
749 : // Concurrency: we call notify_background for all tenants, which will create O(N) tokio tasks, but almost all of them
750 : // will just wait on the ComputeHook::API_CONCURRENCY semaphore immediately, so very cheap until they get that semaphore
751 : // unit and start doing I/O.
752 : tracing::info!(
753 : "Sending {} compute notifications",
754 : compute_notifications.len()
755 : );
756 : self.compute_hook.notify_background(
757 : compute_notifications,
758 : bg_compute_notify_result_tx.clone(),
759 : &self.cancel,
760 : );
761 :
762 : // Finally, now that the service is up and running, launch reconcile operations for any tenants
763 : // which require it: under normal circumstances this should only include tenants that were in some
764 : // transient state before we restarted, or any tenants whose compute hooks failed above.
765 : tracing::info!("Checking for shards in need of reconciliation...");
766 : let reconcile_tasks = self.reconcile_all();
767 : // We will not wait for these reconciliation tasks to run here: we're now done with startup and
768 : // normal operations may proceed.
769 :
770 : // Clean up any tenants that were found on pageservers but are not known to us. Do this in the
771 : // background because it does not need to complete in order to proceed with other work.
772 : if !cleanup.is_empty() {
773 : tracing::info!("Cleaning up {} locations in the background", cleanup.len());
774 : tokio::task::spawn({
775 : let cleanup_self = self.clone();
776 0 : async move { cleanup_self.cleanup_locations(cleanup).await }
777 : });
778 : }
779 :
780 : tracing::info!(
781 : "Startup complete, spawned {reconcile_tasks} reconciliation tasks ({shard_count} shards total)"
782 : );
783 : }
784 :
785 0 : async fn initial_heartbeat_round<'a>(
786 0 : &self,
787 0 : node_ids: impl Iterator<Item = &'a NodeId>,
788 0 : ) -> (
789 0 : HashMap<NodeId, PageserverUtilization>,
790 0 : HashMap<NodeId, (SafekeeperUtilization, Instant)>,
791 0 : ) {
792 0 : assert!(!self.startup_complete.is_ready());
793 :
794 0 : let all_nodes = {
795 0 : let locked = self.inner.read().unwrap();
796 0 : locked.nodes.clone()
797 0 : };
798 0 :
799 0 : let mut nodes_to_heartbeat = HashMap::new();
800 0 : for node_id in node_ids {
801 0 : match all_nodes.get(node_id) {
802 0 : Some(node) => {
803 0 : nodes_to_heartbeat.insert(*node_id, node.clone());
804 0 : }
805 : None => {
806 0 : tracing::warn!("Node {node_id} was removed during start-up");
807 : }
808 : }
809 : }
810 :
811 0 : let all_sks = {
812 0 : let locked = self.inner.read().unwrap();
813 0 : locked.safekeepers.clone()
814 0 : };
815 0 :
816 0 : tracing::info!("Sending initial heartbeats...");
817 : // Put a small, but reasonable timeout to get the initial heartbeats of the safekeepers to avoid a storage controller downtime
818 : const SK_TIMEOUT: Duration = Duration::from_secs(5);
819 0 : let (res_ps, res_sk) = tokio::join!(
820 0 : self.heartbeater_ps.heartbeat(Arc::new(nodes_to_heartbeat)),
821 0 : tokio::time::timeout(SK_TIMEOUT, self.heartbeater_sk.heartbeat(all_sks))
822 0 : );
823 :
824 0 : let mut online_nodes = HashMap::new();
825 0 : if let Ok(deltas) = res_ps {
826 0 : for (node_id, status) in deltas.0 {
827 0 : match status {
828 0 : PageserverState::Available { utilization, .. } => {
829 0 : online_nodes.insert(node_id, utilization);
830 0 : }
831 0 : PageserverState::Offline => {}
832 : PageserverState::WarmingUp { .. } => {
833 0 : unreachable!("Nodes are never marked warming-up during startup reconcile")
834 : }
835 : }
836 : }
837 0 : }
838 :
839 0 : let mut online_sks = HashMap::new();
840 0 : if let Ok(Ok(deltas)) = res_sk {
841 0 : for (node_id, status) in deltas.0 {
842 0 : match status {
843 : SafekeeperState::Available {
844 0 : utilization,
845 0 : last_seen_at,
846 0 : } => {
847 0 : online_sks.insert(node_id, (utilization, last_seen_at));
848 0 : }
849 0 : SafekeeperState::Offline => {}
850 : }
851 : }
852 0 : }
853 :
854 0 : (online_nodes, online_sks)
855 0 : }
856 :
857 : /// Used during [`Self::startup_reconcile`]: issue GETs to all nodes concurrently, with a deadline.
858 : ///
859 : /// The result includes only nodes which responded within the deadline
860 0 : async fn scan_node_locations(
861 0 : &self,
862 0 : deadline: Instant,
863 0 : ) -> HashMap<NodeId, LocationConfigListResponse> {
864 0 : let nodes = {
865 0 : let locked = self.inner.read().unwrap();
866 0 : locked.nodes.clone()
867 0 : };
868 0 :
869 0 : let mut node_results = HashMap::new();
870 0 :
871 0 : let mut node_list_futs = FuturesUnordered::new();
872 0 :
873 0 : tracing::info!("Scanning shards on {} nodes...", nodes.len());
874 0 : for node in nodes.values() {
875 0 : node_list_futs.push({
876 0 : async move {
877 0 : tracing::info!("Scanning shards on node {node}...");
878 0 : let timeout = Duration::from_secs(5);
879 0 : let response = node
880 0 : .with_client_retries(
881 0 : |client| async move { client.list_location_config().await },
882 0 : &self.config.pageserver_jwt_token,
883 0 : 1,
884 0 : 5,
885 0 : timeout,
886 0 : &self.cancel,
887 0 : )
888 0 : .await;
889 0 : (node.get_id(), response)
890 0 : }
891 0 : });
892 0 : }
893 :
894 : loop {
895 0 : let (node_id, result) = tokio::select! {
896 0 : next = node_list_futs.next() => {
897 0 : match next {
898 0 : Some(result) => result,
899 : None =>{
900 : // We got results for all our nodes
901 0 : break;
902 : }
903 :
904 : }
905 : },
906 0 : _ = tokio::time::sleep(deadline.duration_since(Instant::now())) => {
907 : // Give up waiting for anyone who hasn't responded: we will yield the results that we have
908 0 : tracing::info!("Reached deadline while waiting for nodes to respond to location listing requests");
909 0 : break;
910 : }
911 : };
912 :
913 0 : let Some(list_response) = result else {
914 0 : tracing::info!("Shutdown during startup_reconcile");
915 0 : break;
916 : };
917 :
918 0 : match list_response {
919 0 : Err(e) => {
920 0 : tracing::warn!("Could not scan node {} ({e})", node_id);
921 : }
922 0 : Ok(listing) => {
923 0 : node_results.insert(node_id, listing);
924 0 : }
925 : }
926 : }
927 :
928 0 : node_results
929 0 : }
930 :
931 0 : async fn build_global_observed_state(&self, deadline: Instant) -> GlobalObservedState {
932 0 : let node_listings = self.scan_node_locations(deadline).await;
933 0 : let mut observed = GlobalObservedState::default();
934 :
935 0 : for (node_id, location_confs) in node_listings {
936 0 : tracing::info!(
937 0 : "Received {} shard statuses from pageserver {}",
938 0 : location_confs.tenant_shards.len(),
939 : node_id
940 : );
941 :
942 0 : for (tid, location_conf) in location_confs.tenant_shards {
943 0 : let entry = observed.0.entry(tid).or_default();
944 0 : entry.locations.insert(
945 0 : node_id,
946 0 : ObservedStateLocation {
947 0 : conf: location_conf,
948 0 : },
949 0 : );
950 0 : }
951 : }
952 :
953 0 : observed
954 0 : }
955 :
956 : /// Used during [`Self::startup_reconcile`]: detach a list of unknown-to-us tenants from pageservers.
957 : ///
958 : /// This is safe to run in the background, because if we don't have this TenantShardId in our map of
959 : /// tenants, then it is probably something incompletely deleted before: we will not fight with any
960 : /// other task trying to attach it.
961 : #[instrument(skip_all)]
962 : async fn cleanup_locations(&self, cleanup: Vec<(TenantShardId, NodeId)>) {
963 : let nodes = self.inner.read().unwrap().nodes.clone();
964 :
965 : for (tenant_shard_id, node_id) in cleanup {
966 : // A node reported a tenant_shard_id which is unknown to us: detach it.
967 : let Some(node) = nodes.get(&node_id) else {
968 : // This is legitimate; we run in the background and [`Self::startup_reconcile`] might have identified
969 : // a location to clean up on a node that has since been removed.
970 : tracing::info!(
971 : "Not cleaning up location {node_id}/{tenant_shard_id}: node not found"
972 : );
973 : continue;
974 : };
975 :
976 : if self.cancel.is_cancelled() {
977 : break;
978 : }
979 :
980 : let client = PageserverClient::new(
981 : node.get_id(),
982 : node.base_url(),
983 : self.config.pageserver_jwt_token.as_deref(),
984 : );
985 : match client
986 : .location_config(
987 : tenant_shard_id,
988 : LocationConfig {
989 : mode: LocationConfigMode::Detached,
990 : generation: None,
991 : secondary_conf: None,
992 : shard_number: tenant_shard_id.shard_number.0,
993 : shard_count: tenant_shard_id.shard_count.literal(),
994 : shard_stripe_size: 0,
995 : tenant_conf: models::TenantConfig::default(),
996 : },
997 : None,
998 : false,
999 : )
1000 : .await
1001 : {
1002 : Ok(()) => {
1003 : tracing::info!(
1004 : "Detached unknown shard {tenant_shard_id} on pageserver {node_id}"
1005 : );
1006 : }
1007 : Err(e) => {
1008 : // Non-fatal error: leaving a tenant shard behind that we are not managing shouldn't
1009 : // break anything.
1010 : tracing::error!(
1011 : "Failed to detach unknkown shard {tenant_shard_id} on pageserver {node_id}: {e}"
1012 : );
1013 : }
1014 : }
1015 : }
1016 : }
1017 :
1018 : /// Long running background task that periodically wakes up and looks for shards that need
1019 : /// reconciliation. Reconciliation is fallible, so any reconciliation tasks that fail during
1020 : /// e.g. a tenant create/attach/migrate must eventually be retried: this task is responsible
1021 : /// for those retries.
1022 : #[instrument(skip_all)]
1023 : async fn background_reconcile(self: &Arc<Self>) {
1024 : self.startup_complete.clone().wait().await;
1025 :
1026 : const BACKGROUND_RECONCILE_PERIOD: Duration = Duration::from_secs(20);
1027 : let mut interval = tokio::time::interval(BACKGROUND_RECONCILE_PERIOD);
1028 : while !self.reconcilers_cancel.is_cancelled() {
1029 : tokio::select! {
1030 : _ = interval.tick() => {
1031 : let reconciles_spawned = self.reconcile_all();
1032 : if reconciles_spawned == 0 {
1033 : // Run optimizer only when we didn't find any other work to do
1034 : self.optimize_all().await;
1035 : }
1036 : // Always attempt autosplits. Sharding is crucial for bulk ingest performance, so we
1037 : // must be responsive when new projects begin ingesting and reach the threshold.
1038 : self.autosplit_tenants().await;
1039 : }
1040 : _ = self.reconcilers_cancel.cancelled() => return
1041 : }
1042 : }
1043 : }
1044 : #[instrument(skip_all)]
1045 : async fn spawn_heartbeat_driver(&self) {
1046 : self.startup_complete.clone().wait().await;
1047 :
1048 : let mut interval = tokio::time::interval(self.config.heartbeat_interval);
1049 : while !self.cancel.is_cancelled() {
1050 : tokio::select! {
1051 : _ = interval.tick() => { }
1052 : _ = self.cancel.cancelled() => return
1053 : };
1054 :
1055 : let nodes = {
1056 : let locked = self.inner.read().unwrap();
1057 : locked.nodes.clone()
1058 : };
1059 :
1060 : let safekeepers = {
1061 : let locked = self.inner.read().unwrap();
1062 : locked.safekeepers.clone()
1063 : };
1064 :
1065 : const SK_TIMEOUT: Duration = Duration::from_secs(3);
1066 : let (res_ps, res_sk) = tokio::join!(
1067 : self.heartbeater_ps.heartbeat(nodes),
1068 : tokio::time::timeout(SK_TIMEOUT, self.heartbeater_sk.heartbeat(safekeepers))
1069 : );
1070 :
1071 : if let Ok(deltas) = res_ps {
1072 : let mut to_handle = Vec::default();
1073 :
1074 : for (node_id, state) in deltas.0 {
1075 : let new_availability = match state {
1076 : PageserverState::Available { utilization, .. } => {
1077 : NodeAvailability::Active(utilization)
1078 : }
1079 : PageserverState::WarmingUp { started_at } => {
1080 : NodeAvailability::WarmingUp(started_at)
1081 : }
1082 : PageserverState::Offline => {
1083 : // The node might have been placed in the WarmingUp state
1084 : // while the heartbeat round was on-going. Hence, filter out
1085 : // offline transitions for WarmingUp nodes that are still within
1086 : // their grace period.
1087 : if let Ok(NodeAvailability::WarmingUp(started_at)) = self
1088 : .get_node(node_id)
1089 : .await
1090 : .as_ref()
1091 0 : .map(|n| n.get_availability())
1092 : {
1093 : let now = Instant::now();
1094 : if now - *started_at >= self.config.max_warming_up_interval {
1095 : NodeAvailability::Offline
1096 : } else {
1097 : NodeAvailability::WarmingUp(*started_at)
1098 : }
1099 : } else {
1100 : NodeAvailability::Offline
1101 : }
1102 : }
1103 : };
1104 :
1105 : let node_lock = trace_exclusive_lock(
1106 : &self.node_op_locks,
1107 : node_id,
1108 : NodeOperations::Configure,
1109 : )
1110 : .await;
1111 :
1112 : pausable_failpoint!("heartbeat-pre-node-state-configure");
1113 :
1114 : // This is the code path for geniune availability transitions (i.e node
1115 : // goes unavailable and/or comes back online).
1116 : let res = self
1117 : .node_state_configure(node_id, Some(new_availability), None, &node_lock)
1118 : .await;
1119 :
1120 : match res {
1121 : Ok(transition) => {
1122 : // Keep hold of the lock until the availability transitions
1123 : // have been handled in
1124 : // [`Service::handle_node_availability_transitions`] in order avoid
1125 : // racing with [`Service::external_node_configure`].
1126 : to_handle.push((node_id, node_lock, transition));
1127 : }
1128 : Err(ApiError::NotFound(_)) => {
1129 : // This should be rare, but legitimate since the heartbeats are done
1130 : // on a snapshot of the nodes.
1131 : tracing::info!("Node {} was not found after heartbeat round", node_id);
1132 : }
1133 : Err(ApiError::ShuttingDown) => {
1134 : // No-op: we're shutting down, no need to try and update any nodes' statuses
1135 : }
1136 : Err(err) => {
1137 : // Transition to active involves reconciling: if a node responds to a heartbeat then
1138 : // becomes unavailable again, we may get an error here.
1139 : tracing::error!(
1140 : "Failed to update node state {} after heartbeat round: {}",
1141 : node_id,
1142 : err
1143 : );
1144 : }
1145 : }
1146 : }
1147 :
1148 : // We collected all the transitions above and now we handle them.
1149 : let res = self.handle_node_availability_transitions(to_handle).await;
1150 : if let Err(errs) = res {
1151 : for (node_id, err) in errs {
1152 : match err {
1153 : ApiError::NotFound(_) => {
1154 : // This should be rare, but legitimate since the heartbeats are done
1155 : // on a snapshot of the nodes.
1156 : tracing::info!(
1157 : "Node {} was not found after heartbeat round",
1158 : node_id
1159 : );
1160 : }
1161 : err => {
1162 : tracing::error!(
1163 : "Failed to handle availability transition for {} after heartbeat round: {}",
1164 : node_id,
1165 : err
1166 : );
1167 : }
1168 : }
1169 : }
1170 : }
1171 : }
1172 : if let Ok(Ok(deltas)) = res_sk {
1173 : let mut locked = self.inner.write().unwrap();
1174 : let mut safekeepers = (*locked.safekeepers).clone();
1175 : for (id, state) in deltas.0 {
1176 : let Some(sk) = safekeepers.get_mut(&id) else {
1177 : tracing::info!(
1178 : "Couldn't update safekeeper safekeeper state for id {id} from heartbeat={state:?}"
1179 : );
1180 : continue;
1181 : };
1182 : sk.set_availability(state);
1183 : }
1184 : locked.safekeepers = Arc::new(safekeepers);
1185 : }
1186 : }
1187 : }
1188 :
1189 : /// Apply the contents of a [`ReconcileResult`] to our in-memory state: if the reconciliation
1190 : /// was successful and intent hasn't changed since the Reconciler was spawned, this will update
1191 : /// the observed state of the tenant such that subsequent calls to [`TenantShard::get_reconcile_needed`]
1192 : /// will indicate that reconciliation is not needed.
1193 : #[instrument(skip_all, fields(
1194 : seq=%result.sequence,
1195 : tenant_id=%result.tenant_shard_id.tenant_id,
1196 : shard_id=%result.tenant_shard_id.shard_slug(),
1197 : ))]
1198 : fn process_result(&self, result: ReconcileResult) {
1199 : let mut locked = self.inner.write().unwrap();
1200 : let (nodes, tenants, _scheduler) = locked.parts_mut();
1201 : let Some(tenant) = tenants.get_mut(&result.tenant_shard_id) else {
1202 : // A reconciliation result might race with removing a tenant: drop results for
1203 : // tenants that aren't in our map.
1204 : return;
1205 : };
1206 :
1207 : // Usually generation should only be updated via this path, so the max() isn't
1208 : // needed, but it is used to handle out-of-band updates via. e.g. test hook.
1209 : tenant.generation = std::cmp::max(tenant.generation, result.generation);
1210 :
1211 : // If the reconciler signals that it failed to notify compute, set this state on
1212 : // the shard so that a future [`TenantShard::maybe_reconcile`] will try again.
1213 : tenant.pending_compute_notification = result.pending_compute_notification;
1214 :
1215 : // Let the TenantShard know it is idle.
1216 : tenant.reconcile_complete(result.sequence);
1217 :
1218 : // In case a node was deleted while this reconcile is in flight, filter it out of the update we will
1219 : // make to the tenant
1220 0 : let deltas = result.observed_deltas.into_iter().flat_map(|delta| {
1221 : // In case a node was deleted while this reconcile is in flight, filter it out of the update we will
1222 : // make to the tenant
1223 0 : let node = nodes.get(delta.node_id())?;
1224 :
1225 0 : if node.is_available() {
1226 0 : return Some(delta);
1227 0 : }
1228 0 :
1229 0 : // In case a node became unavailable concurrently with the reconcile, observed
1230 0 : // locations on it are now uncertain. By convention, set them to None in order
1231 0 : // for them to get refreshed when the node comes back online.
1232 0 : Some(ObservedStateDelta::Upsert(Box::new((
1233 0 : node.get_id(),
1234 0 : ObservedStateLocation { conf: None },
1235 0 : ))))
1236 0 : });
1237 :
1238 : match result.result {
1239 : Ok(()) => {
1240 : tenant.apply_observed_deltas(deltas);
1241 : tenant.waiter.advance(result.sequence);
1242 : }
1243 : Err(e) => {
1244 : match e {
1245 : ReconcileError::Cancel => {
1246 : tracing::info!("Reconciler was cancelled");
1247 : }
1248 : ReconcileError::Remote(mgmt_api::Error::Cancelled) => {
1249 : // This might be due to the reconciler getting cancelled, or it might
1250 : // be due to the `Node` being marked offline.
1251 : tracing::info!("Reconciler cancelled during pageserver API call");
1252 : }
1253 : _ => {
1254 : tracing::warn!("Reconcile error: {}", e);
1255 : }
1256 : }
1257 :
1258 : // Ordering: populate last_error before advancing error_seq,
1259 : // so that waiters will see the correct error after waiting.
1260 : tenant.set_last_error(result.sequence, e);
1261 :
1262 : // Skip deletions on reconcile failures
1263 : let upsert_deltas =
1264 0 : deltas.filter(|delta| matches!(delta, ObservedStateDelta::Upsert(_)));
1265 : tenant.apply_observed_deltas(upsert_deltas);
1266 : }
1267 : }
1268 :
1269 : // If we just finished detaching all shards for a tenant, it might be time to drop it from memory.
1270 : if tenant.policy == PlacementPolicy::Detached {
1271 : // We may only drop a tenant from memory while holding the exclusive lock on the tenant ID: this protects us
1272 : // from concurrent execution wrt a request handler that might expect the tenant to remain in memory for the
1273 : // duration of the request.
1274 : let guard = self.tenant_op_locks.try_exclusive(
1275 : tenant.tenant_shard_id.tenant_id,
1276 : TenantOperations::DropDetached,
1277 : );
1278 : if let Some(guard) = guard {
1279 : self.maybe_drop_tenant(tenant.tenant_shard_id.tenant_id, &mut locked, &guard);
1280 : }
1281 : }
1282 :
1283 : // Maybe some other work can proceed now that this job finished.
1284 : //
1285 : // Only bother with this if we have some semaphore units available in the normal-priority semaphore (these
1286 : // reconciles are scheduled at `[ReconcilerPriority::Normal]`).
1287 : if self.reconciler_concurrency.available_permits() > 0 {
1288 : while let Ok(tenant_shard_id) = locked.delayed_reconcile_rx.try_recv() {
1289 : let (nodes, tenants, _scheduler) = locked.parts_mut();
1290 : if let Some(shard) = tenants.get_mut(&tenant_shard_id) {
1291 : shard.delayed_reconcile = false;
1292 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::Normal);
1293 : }
1294 :
1295 : if self.reconciler_concurrency.available_permits() == 0 {
1296 : break;
1297 : }
1298 : }
1299 : }
1300 : }
1301 :
1302 0 : async fn process_results(
1303 0 : &self,
1304 0 : mut result_rx: tokio::sync::mpsc::UnboundedReceiver<ReconcileResultRequest>,
1305 0 : mut bg_compute_hook_result_rx: tokio::sync::mpsc::Receiver<
1306 0 : Result<(), (TenantShardId, NotifyError)>,
1307 0 : >,
1308 0 : ) {
1309 : loop {
1310 : // Wait for the next result, or for cancellation
1311 0 : tokio::select! {
1312 0 : r = result_rx.recv() => {
1313 0 : match r {
1314 0 : Some(ReconcileResultRequest::ReconcileResult(result)) => {self.process_result(result);},
1315 0 : None | Some(ReconcileResultRequest::Stop) => {break;}
1316 : }
1317 : }
1318 0 : _ = async{
1319 0 : match bg_compute_hook_result_rx.recv().await {
1320 0 : Some(result) => {
1321 0 : if let Err((tenant_shard_id, notify_error)) = result {
1322 0 : tracing::warn!("Marking shard {tenant_shard_id} for notification retry, due to error {notify_error}");
1323 0 : let mut locked = self.inner.write().unwrap();
1324 0 : if let Some(shard) = locked.tenants.get_mut(&tenant_shard_id) {
1325 0 : shard.pending_compute_notification = true;
1326 0 : }
1327 :
1328 0 : }
1329 : },
1330 : None => {
1331 : // This channel is dead, but we don't want to terminate the outer loop{}: just wait for shutdown
1332 0 : self.cancel.cancelled().await;
1333 : }
1334 : }
1335 0 : } => {},
1336 0 : _ = self.cancel.cancelled() => {
1337 0 : break;
1338 : }
1339 : };
1340 : }
1341 0 : }
1342 :
1343 0 : async fn process_aborts(
1344 0 : &self,
1345 0 : mut abort_rx: tokio::sync::mpsc::UnboundedReceiver<TenantShardSplitAbort>,
1346 0 : ) {
1347 : loop {
1348 : // Wait for the next result, or for cancellation
1349 0 : let op = tokio::select! {
1350 0 : r = abort_rx.recv() => {
1351 0 : match r {
1352 0 : Some(op) => {op},
1353 0 : None => {break;}
1354 : }
1355 : }
1356 0 : _ = self.cancel.cancelled() => {
1357 0 : break;
1358 : }
1359 : };
1360 :
1361 : // Retry until shutdown: we must keep this request object alive until it is properly
1362 : // processed, as it holds a lock guard that prevents other operations trying to do things
1363 : // to the tenant while it is in a weird part-split state.
1364 0 : while !self.cancel.is_cancelled() {
1365 0 : match self.abort_tenant_shard_split(&op).await {
1366 0 : Ok(_) => break,
1367 0 : Err(e) => {
1368 0 : tracing::warn!(
1369 0 : "Failed to abort shard split on {}, will retry: {e}",
1370 : op.tenant_id
1371 : );
1372 :
1373 : // If a node is unavailable, we hope that it has been properly marked Offline
1374 : // when we retry, so that the abort op will succeed. If the abort op is failing
1375 : // for some other reason, we will keep retrying forever, or until a human notices
1376 : // and does something about it (either fixing a pageserver or restarting the controller).
1377 0 : tokio::time::timeout(Duration::from_secs(5), self.cancel.cancelled())
1378 0 : .await
1379 0 : .ok();
1380 : }
1381 : }
1382 : }
1383 : }
1384 0 : }
1385 :
1386 0 : pub async fn spawn(config: Config, persistence: Arc<Persistence>) -> anyhow::Result<Arc<Self>> {
1387 0 : let (result_tx, result_rx) = tokio::sync::mpsc::unbounded_channel();
1388 0 : let (abort_tx, abort_rx) = tokio::sync::mpsc::unbounded_channel();
1389 0 :
1390 0 : let leadership_cancel = CancellationToken::new();
1391 0 : let leadership = Leadership::new(persistence.clone(), config.clone(), leadership_cancel);
1392 0 : let (leader, leader_step_down_state) = leadership.step_down_current_leader().await?;
1393 :
1394 : // Apply the migrations **after** the current leader has stepped down
1395 : // (or we've given up waiting for it), but **before** reading from the
1396 : // database. The only exception is reading the current leader before
1397 : // migrating.
1398 0 : persistence.migration_run().await?;
1399 :
1400 0 : tracing::info!("Loading nodes from database...");
1401 0 : let nodes = persistence
1402 0 : .list_nodes()
1403 0 : .await?
1404 0 : .into_iter()
1405 0 : .map(|x| Node::from_persistent(x, config.use_https_pageserver_api))
1406 0 : .collect::<anyhow::Result<Vec<Node>>>()?;
1407 0 : let nodes: HashMap<NodeId, Node> = nodes.into_iter().map(|n| (n.get_id(), n)).collect();
1408 0 : tracing::info!("Loaded {} nodes from database.", nodes.len());
1409 0 : metrics::METRICS_REGISTRY
1410 0 : .metrics_group
1411 0 : .storage_controller_pageserver_nodes
1412 0 : .set(nodes.len() as i64);
1413 0 :
1414 0 : tracing::info!("Loading safekeepers from database...");
1415 0 : let safekeepers = if config.load_safekeepers {
1416 0 : persistence
1417 0 : .list_safekeepers()
1418 0 : .await?
1419 0 : .into_iter()
1420 0 : .map(|skp| Safekeeper::from_persistence(skp, CancellationToken::new()))
1421 0 : .collect::<Vec<_>>()
1422 : } else {
1423 0 : tracing::info!("Skipping safekeeper loading");
1424 0 : Default::default()
1425 : };
1426 :
1427 0 : let safekeepers: HashMap<NodeId, Safekeeper> =
1428 0 : safekeepers.into_iter().map(|n| (n.get_id(), n)).collect();
1429 0 :
1430 0 : tracing::info!("Loading shards from database...");
1431 0 : let mut tenant_shard_persistence = persistence.load_active_tenant_shards().await?;
1432 0 : tracing::info!(
1433 0 : "Loaded {} shards from database.",
1434 0 : tenant_shard_persistence.len()
1435 : );
1436 :
1437 : // If any shard splits were in progress, reset the database state to abort them
1438 0 : let mut tenant_shard_count_min_max: HashMap<TenantId, (ShardCount, ShardCount)> =
1439 0 : HashMap::new();
1440 0 : for tsp in &mut tenant_shard_persistence {
1441 0 : let shard = tsp.get_shard_identity()?;
1442 0 : let tenant_shard_id = tsp.get_tenant_shard_id()?;
1443 0 : let entry = tenant_shard_count_min_max
1444 0 : .entry(tenant_shard_id.tenant_id)
1445 0 : .or_insert_with(|| (shard.count, shard.count));
1446 0 : entry.0 = std::cmp::min(entry.0, shard.count);
1447 0 : entry.1 = std::cmp::max(entry.1, shard.count);
1448 0 : }
1449 :
1450 0 : for (tenant_id, (count_min, count_max)) in tenant_shard_count_min_max {
1451 0 : if count_min != count_max {
1452 : // Aborting the split in the database and dropping the child shards is sufficient: the reconciliation in
1453 : // [`Self::startup_reconcile`] will implicitly drop the child shards on remote pageservers, or they'll
1454 : // be dropped later in [`Self::node_activate_reconcile`] if it isn't available right now.
1455 0 : tracing::info!("Aborting shard split {tenant_id} {count_min:?} -> {count_max:?}");
1456 0 : let abort_status = persistence.abort_shard_split(tenant_id, count_max).await?;
1457 :
1458 : // We may never see the Complete status here: if the split was complete, we wouldn't have
1459 : // identified this tenant has having mismatching min/max counts.
1460 0 : assert!(matches!(abort_status, AbortShardSplitStatus::Aborted));
1461 :
1462 : // Clear the splitting status in-memory, to reflect that we just aborted in the database
1463 0 : tenant_shard_persistence.iter_mut().for_each(|tsp| {
1464 0 : // Set idle split state on those shards that we will retain.
1465 0 : let tsp_tenant_id = TenantId::from_str(tsp.tenant_id.as_str()).unwrap();
1466 0 : if tsp_tenant_id == tenant_id
1467 0 : && tsp.get_shard_identity().unwrap().count == count_min
1468 0 : {
1469 0 : tsp.splitting = SplitState::Idle;
1470 0 : } else if tsp_tenant_id == tenant_id {
1471 : // Leave the splitting state on the child shards: this will be used next to
1472 : // drop them.
1473 0 : tracing::info!(
1474 0 : "Shard {tsp_tenant_id} will be dropped after shard split abort",
1475 : );
1476 0 : }
1477 0 : });
1478 0 :
1479 0 : // Drop shards for this tenant which we didn't just mark idle (i.e. child shards of the aborted split)
1480 0 : tenant_shard_persistence.retain(|tsp| {
1481 0 : TenantId::from_str(tsp.tenant_id.as_str()).unwrap() != tenant_id
1482 0 : || tsp.splitting == SplitState::Idle
1483 0 : });
1484 0 : }
1485 : }
1486 :
1487 0 : let mut tenants = BTreeMap::new();
1488 0 :
1489 0 : let mut scheduler = Scheduler::new(nodes.values());
1490 :
1491 : #[cfg(feature = "testing")]
1492 : {
1493 : use pageserver_api::controller_api::AvailabilityZone;
1494 :
1495 : // Hack: insert scheduler state for all nodes referenced by shards, as compatibility
1496 : // tests only store the shards, not the nodes. The nodes will be loaded shortly
1497 : // after when pageservers start up and register.
1498 0 : let mut node_ids = HashSet::new();
1499 0 : for tsp in &tenant_shard_persistence {
1500 0 : if let Some(node_id) = tsp.generation_pageserver {
1501 0 : node_ids.insert(node_id);
1502 0 : }
1503 : }
1504 0 : for node_id in node_ids {
1505 0 : tracing::info!("Creating node {} in scheduler for tests", node_id);
1506 0 : let node = Node::new(
1507 0 : NodeId(node_id as u64),
1508 0 : "".to_string(),
1509 0 : 123,
1510 0 : None,
1511 0 : "".to_string(),
1512 0 : 123,
1513 0 : AvailabilityZone("test_az".to_string()),
1514 0 : false,
1515 0 : )
1516 0 : .unwrap();
1517 0 :
1518 0 : scheduler.node_upsert(&node);
1519 : }
1520 : }
1521 0 : for tsp in tenant_shard_persistence {
1522 0 : let tenant_shard_id = tsp.get_tenant_shard_id()?;
1523 :
1524 : // We will populate intent properly later in [`Self::startup_reconcile`], initially populate
1525 : // it with what we can infer: the node for which a generation was most recently issued.
1526 0 : let mut intent = IntentState::new(
1527 0 : tsp.preferred_az_id
1528 0 : .as_ref()
1529 0 : .map(|az| AvailabilityZone(az.clone())),
1530 0 : );
1531 0 : if let Some(generation_pageserver) = tsp.generation_pageserver.map(|n| NodeId(n as u64))
1532 : {
1533 0 : if nodes.contains_key(&generation_pageserver) {
1534 0 : intent.set_attached(&mut scheduler, Some(generation_pageserver));
1535 0 : } else {
1536 : // If a node was removed before being completely drained, it is legal for it to leave behind a `generation_pageserver` referring
1537 : // to a non-existent node, because node deletion doesn't block on completing the reconciliations that will issue new generations
1538 : // on different pageservers.
1539 0 : tracing::warn!(
1540 0 : "Tenant shard {tenant_shard_id} references non-existent node {generation_pageserver} in database, will be rescheduled"
1541 : );
1542 : }
1543 0 : }
1544 0 : let new_tenant = TenantShard::from_persistent(tsp, intent)?;
1545 :
1546 0 : tenants.insert(tenant_shard_id, new_tenant);
1547 : }
1548 :
1549 0 : let (startup_completion, startup_complete) = utils::completion::channel();
1550 0 :
1551 0 : // This channel is continuously consumed by process_results, so doesn't need to be very large.
1552 0 : let (bg_compute_notify_result_tx, bg_compute_notify_result_rx) =
1553 0 : tokio::sync::mpsc::channel(512);
1554 0 :
1555 0 : let (delayed_reconcile_tx, delayed_reconcile_rx) =
1556 0 : tokio::sync::mpsc::channel(MAX_DELAYED_RECONCILES);
1557 0 :
1558 0 : let cancel = CancellationToken::new();
1559 0 : let reconcilers_cancel = cancel.child_token();
1560 0 :
1561 0 : let heartbeater_ps = Heartbeater::new(
1562 0 : config.pageserver_jwt_token.clone(),
1563 0 : config.max_offline_interval,
1564 0 : config.max_warming_up_interval,
1565 0 : cancel.clone(),
1566 0 : );
1567 0 :
1568 0 : let heartbeater_sk = Heartbeater::new(
1569 0 : config.safekeeper_jwt_token.clone(),
1570 0 : config.max_offline_interval,
1571 0 : config.max_warming_up_interval,
1572 0 : cancel.clone(),
1573 0 : );
1574 :
1575 0 : let initial_leadership_status = if config.start_as_candidate {
1576 0 : LeadershipStatus::Candidate
1577 : } else {
1578 0 : LeadershipStatus::Leader
1579 : };
1580 :
1581 0 : let this = Arc::new(Self {
1582 0 : inner: Arc::new(std::sync::RwLock::new(ServiceState::new(
1583 0 : nodes,
1584 0 : safekeepers,
1585 0 : tenants,
1586 0 : scheduler,
1587 0 : delayed_reconcile_rx,
1588 0 : initial_leadership_status,
1589 0 : ))),
1590 0 : config: config.clone(),
1591 0 : persistence,
1592 0 : compute_hook: Arc::new(ComputeHook::new(config.clone())),
1593 0 : result_tx,
1594 0 : heartbeater_ps,
1595 0 : heartbeater_sk,
1596 0 : reconciler_concurrency: Arc::new(tokio::sync::Semaphore::new(
1597 0 : config.reconciler_concurrency,
1598 0 : )),
1599 0 : priority_reconciler_concurrency: Arc::new(tokio::sync::Semaphore::new(
1600 0 : config.priority_reconciler_concurrency,
1601 0 : )),
1602 0 : delayed_reconcile_tx,
1603 0 : abort_tx,
1604 0 : startup_complete: startup_complete.clone(),
1605 0 : cancel,
1606 0 : reconcilers_cancel,
1607 0 : gate: Gate::default(),
1608 0 : reconcilers_gate: Gate::default(),
1609 0 : tenant_op_locks: Default::default(),
1610 0 : node_op_locks: Default::default(),
1611 0 : });
1612 0 :
1613 0 : let result_task_this = this.clone();
1614 0 : tokio::task::spawn(async move {
1615 : // Block shutdown until we're done (we must respect self.cancel)
1616 0 : if let Ok(_gate) = result_task_this.gate.enter() {
1617 0 : result_task_this
1618 0 : .process_results(result_rx, bg_compute_notify_result_rx)
1619 0 : .await
1620 0 : }
1621 0 : });
1622 0 :
1623 0 : tokio::task::spawn({
1624 0 : let this = this.clone();
1625 0 : async move {
1626 : // Block shutdown until we're done (we must respect self.cancel)
1627 0 : if let Ok(_gate) = this.gate.enter() {
1628 0 : this.process_aborts(abort_rx).await
1629 0 : }
1630 0 : }
1631 0 : });
1632 0 :
1633 0 : tokio::task::spawn({
1634 0 : let this = this.clone();
1635 0 : async move {
1636 0 : if let Ok(_gate) = this.gate.enter() {
1637 : loop {
1638 0 : tokio::select! {
1639 0 : _ = this.cancel.cancelled() => {
1640 0 : break;
1641 : },
1642 0 : _ = tokio::time::sleep(Duration::from_secs(60)) => {}
1643 0 : };
1644 0 : this.tenant_op_locks.housekeeping();
1645 : }
1646 0 : }
1647 0 : }
1648 0 : });
1649 0 :
1650 0 : tokio::task::spawn({
1651 0 : let this = this.clone();
1652 0 : // We will block the [`Service::startup_complete`] barrier until [`Self::startup_reconcile`]
1653 0 : // is done.
1654 0 : let startup_completion = startup_completion.clone();
1655 0 : async move {
1656 : // Block shutdown until we're done (we must respect self.cancel)
1657 0 : let Ok(_gate) = this.gate.enter() else {
1658 0 : return;
1659 : };
1660 :
1661 0 : this.startup_reconcile(leader, leader_step_down_state, bg_compute_notify_result_tx)
1662 0 : .await;
1663 :
1664 0 : drop(startup_completion);
1665 0 : }
1666 0 : });
1667 0 :
1668 0 : tokio::task::spawn({
1669 0 : let this = this.clone();
1670 0 : let startup_complete = startup_complete.clone();
1671 0 : async move {
1672 0 : startup_complete.wait().await;
1673 0 : this.background_reconcile().await;
1674 0 : }
1675 0 : });
1676 0 :
1677 0 : tokio::task::spawn({
1678 0 : let this = this.clone();
1679 0 : let startup_complete = startup_complete.clone();
1680 0 : async move {
1681 0 : startup_complete.wait().await;
1682 0 : this.spawn_heartbeat_driver().await;
1683 0 : }
1684 0 : });
1685 0 :
1686 0 : Ok(this)
1687 0 : }
1688 :
1689 0 : pub(crate) async fn attach_hook(
1690 0 : &self,
1691 0 : attach_req: AttachHookRequest,
1692 0 : ) -> anyhow::Result<AttachHookResponse> {
1693 0 : let _tenant_lock = trace_exclusive_lock(
1694 0 : &self.tenant_op_locks,
1695 0 : attach_req.tenant_shard_id.tenant_id,
1696 0 : TenantOperations::AttachHook,
1697 0 : )
1698 0 : .await;
1699 :
1700 : // This is a test hook. To enable using it on tenants that were created directly with
1701 : // the pageserver API (not via this service), we will auto-create any missing tenant
1702 : // shards with default state.
1703 0 : let insert = {
1704 0 : match self
1705 0 : .maybe_load_tenant(attach_req.tenant_shard_id.tenant_id, &_tenant_lock)
1706 0 : .await
1707 : {
1708 0 : Ok(_) => false,
1709 0 : Err(ApiError::NotFound(_)) => true,
1710 0 : Err(e) => return Err(e.into()),
1711 : }
1712 : };
1713 :
1714 0 : if insert {
1715 0 : let tsp = TenantShardPersistence {
1716 0 : tenant_id: attach_req.tenant_shard_id.tenant_id.to_string(),
1717 0 : shard_number: attach_req.tenant_shard_id.shard_number.0 as i32,
1718 0 : shard_count: attach_req.tenant_shard_id.shard_count.literal() as i32,
1719 0 : shard_stripe_size: 0,
1720 0 : generation: attach_req.generation_override.or(Some(0)),
1721 0 : generation_pageserver: None,
1722 0 : placement_policy: serde_json::to_string(&PlacementPolicy::Attached(0)).unwrap(),
1723 0 : config: serde_json::to_string(&TenantConfig::default()).unwrap(),
1724 0 : splitting: SplitState::default(),
1725 0 : scheduling_policy: serde_json::to_string(&ShardSchedulingPolicy::default())
1726 0 : .unwrap(),
1727 0 : preferred_az_id: None,
1728 0 : };
1729 0 :
1730 0 : match self.persistence.insert_tenant_shards(vec![tsp]).await {
1731 0 : Err(e) => match e {
1732 : DatabaseError::Query(diesel::result::Error::DatabaseError(
1733 : DatabaseErrorKind::UniqueViolation,
1734 : _,
1735 : )) => {
1736 0 : tracing::info!(
1737 0 : "Raced with another request to insert tenant {}",
1738 : attach_req.tenant_shard_id
1739 : )
1740 : }
1741 0 : _ => return Err(e.into()),
1742 : },
1743 : Ok(()) => {
1744 0 : tracing::info!("Inserted shard {} in database", attach_req.tenant_shard_id);
1745 :
1746 0 : let mut locked = self.inner.write().unwrap();
1747 0 : locked.tenants.insert(
1748 0 : attach_req.tenant_shard_id,
1749 0 : TenantShard::new(
1750 0 : attach_req.tenant_shard_id,
1751 0 : ShardIdentity::unsharded(),
1752 0 : PlacementPolicy::Attached(0),
1753 0 : None,
1754 0 : ),
1755 0 : );
1756 0 : tracing::info!("Inserted shard {} in memory", attach_req.tenant_shard_id);
1757 : }
1758 : }
1759 0 : }
1760 :
1761 0 : let new_generation = if let Some(req_node_id) = attach_req.node_id {
1762 0 : let maybe_tenant_conf = {
1763 0 : let locked = self.inner.write().unwrap();
1764 0 : locked
1765 0 : .tenants
1766 0 : .get(&attach_req.tenant_shard_id)
1767 0 : .map(|t| t.config.clone())
1768 0 : };
1769 0 :
1770 0 : match maybe_tenant_conf {
1771 0 : Some(conf) => {
1772 0 : let new_generation = self
1773 0 : .persistence
1774 0 : .increment_generation(attach_req.tenant_shard_id, req_node_id)
1775 0 : .await?;
1776 :
1777 : // Persist the placement policy update. This is required
1778 : // when we reattaching a detached tenant.
1779 0 : self.persistence
1780 0 : .update_tenant_shard(
1781 0 : TenantFilter::Shard(attach_req.tenant_shard_id),
1782 0 : Some(PlacementPolicy::Attached(0)),
1783 0 : Some(conf),
1784 0 : None,
1785 0 : None,
1786 0 : )
1787 0 : .await?;
1788 0 : Some(new_generation)
1789 : }
1790 : None => {
1791 0 : anyhow::bail!("Attach hook handling raced with tenant removal")
1792 : }
1793 : }
1794 : } else {
1795 0 : self.persistence.detach(attach_req.tenant_shard_id).await?;
1796 0 : None
1797 : };
1798 :
1799 0 : let mut locked = self.inner.write().unwrap();
1800 0 : let (_nodes, tenants, scheduler) = locked.parts_mut();
1801 0 :
1802 0 : let tenant_shard = tenants
1803 0 : .get_mut(&attach_req.tenant_shard_id)
1804 0 : .expect("Checked for existence above");
1805 :
1806 0 : if let Some(new_generation) = new_generation {
1807 0 : tenant_shard.generation = Some(new_generation);
1808 0 : tenant_shard.policy = PlacementPolicy::Attached(0);
1809 0 : } else {
1810 : // This is a detach notification. We must update placement policy to avoid re-attaching
1811 : // during background scheduling/reconciliation, or during storage controller restart.
1812 0 : assert!(attach_req.node_id.is_none());
1813 0 : tenant_shard.policy = PlacementPolicy::Detached;
1814 : }
1815 :
1816 0 : if let Some(attaching_pageserver) = attach_req.node_id.as_ref() {
1817 0 : tracing::info!(
1818 : tenant_id = %attach_req.tenant_shard_id,
1819 : ps_id = %attaching_pageserver,
1820 : generation = ?tenant_shard.generation,
1821 0 : "issuing",
1822 : );
1823 0 : } else if let Some(ps_id) = tenant_shard.intent.get_attached() {
1824 0 : tracing::info!(
1825 : tenant_id = %attach_req.tenant_shard_id,
1826 : %ps_id,
1827 : generation = ?tenant_shard.generation,
1828 0 : "dropping",
1829 : );
1830 : } else {
1831 0 : tracing::info!(
1832 : tenant_id = %attach_req.tenant_shard_id,
1833 0 : "no-op: tenant already has no pageserver");
1834 : }
1835 0 : tenant_shard
1836 0 : .intent
1837 0 : .set_attached(scheduler, attach_req.node_id);
1838 0 :
1839 0 : tracing::info!(
1840 0 : "attach_hook: tenant {} set generation {:?}, pageserver {}",
1841 0 : attach_req.tenant_shard_id,
1842 0 : tenant_shard.generation,
1843 0 : // TODO: this is an odd number of 0xf's
1844 0 : attach_req.node_id.unwrap_or(utils::id::NodeId(0xfffffff))
1845 : );
1846 :
1847 : // Trick the reconciler into not doing anything for this tenant: this helps
1848 : // tests that manually configure a tenant on the pagesrever, and then call this
1849 : // attach hook: they don't want background reconciliation to modify what they
1850 : // did to the pageserver.
1851 : #[cfg(feature = "testing")]
1852 : {
1853 0 : if let Some(node_id) = attach_req.node_id {
1854 0 : tenant_shard.observed.locations = HashMap::from([(
1855 0 : node_id,
1856 0 : ObservedStateLocation {
1857 0 : conf: Some(attached_location_conf(
1858 0 : tenant_shard.generation.unwrap(),
1859 0 : &tenant_shard.shard,
1860 0 : &tenant_shard.config,
1861 0 : &PlacementPolicy::Attached(0),
1862 0 : )),
1863 0 : },
1864 0 : )]);
1865 0 : } else {
1866 0 : tenant_shard.observed.locations.clear();
1867 0 : }
1868 : }
1869 :
1870 0 : Ok(AttachHookResponse {
1871 0 : generation: attach_req
1872 0 : .node_id
1873 0 : .map(|_| tenant_shard.generation.expect("Test hook, not used on tenants that are mid-onboarding with a NULL generation").into().unwrap()),
1874 0 : })
1875 0 : }
1876 :
1877 0 : pub(crate) fn inspect(&self, inspect_req: InspectRequest) -> InspectResponse {
1878 0 : let locked = self.inner.read().unwrap();
1879 0 :
1880 0 : let tenant_shard = locked.tenants.get(&inspect_req.tenant_shard_id);
1881 0 :
1882 0 : InspectResponse {
1883 0 : attachment: tenant_shard.and_then(|s| {
1884 0 : s.intent
1885 0 : .get_attached()
1886 0 : .map(|ps| (s.generation.expect("Test hook, not used on tenants that are mid-onboarding with a NULL generation").into().unwrap(), ps))
1887 0 : }),
1888 0 : }
1889 0 : }
1890 :
1891 : // When the availability state of a node transitions to active, we must do a full reconciliation
1892 : // of LocationConfigs on that node. This is because while a node was offline:
1893 : // - we might have proceeded through startup_reconcile without checking for extraneous LocationConfigs on this node
1894 : // - aborting a tenant shard split might have left rogue child shards behind on this node.
1895 : //
1896 : // This function must complete _before_ setting a `Node` to Active: once it is set to Active, other
1897 : // Reconcilers might communicate with the node, and these must not overlap with the work we do in
1898 : // this function.
1899 : //
1900 : // The reconciliation logic in here is very similar to what [`Self::startup_reconcile`] does, but
1901 : // for written for a single node rather than as a batch job for all nodes.
1902 : #[tracing::instrument(skip_all, fields(node_id=%node.get_id()))]
1903 : async fn node_activate_reconcile(
1904 : &self,
1905 : mut node: Node,
1906 : _lock: &TracingExclusiveGuard<NodeOperations>,
1907 : ) -> Result<(), ApiError> {
1908 : // This Node is a mutable local copy: we will set it active so that we can use its
1909 : // API client to reconcile with the node. The Node in [`Self::nodes`] will get updated
1910 : // later.
1911 : node.set_availability(NodeAvailability::Active(PageserverUtilization::full()));
1912 :
1913 : let configs = match node
1914 : .with_client_retries(
1915 0 : |client| async move { client.list_location_config().await },
1916 : &self.config.pageserver_jwt_token,
1917 : 1,
1918 : 5,
1919 : SHORT_RECONCILE_TIMEOUT,
1920 : &self.cancel,
1921 : )
1922 : .await
1923 : {
1924 : None => {
1925 : // We're shutting down (the Node's cancellation token can't have fired, because
1926 : // we're the only scope that has a reference to it, and we didn't fire it).
1927 : return Err(ApiError::ShuttingDown);
1928 : }
1929 : Some(Err(e)) => {
1930 : // This node didn't succeed listing its locations: it may not proceed to active state
1931 : // as it is apparently unavailable.
1932 : return Err(ApiError::PreconditionFailed(
1933 : format!("Failed to query node location configs, cannot activate ({e})").into(),
1934 : ));
1935 : }
1936 : Some(Ok(configs)) => configs,
1937 : };
1938 : tracing::info!("Loaded {} LocationConfigs", configs.tenant_shards.len());
1939 :
1940 : let mut cleanup = Vec::new();
1941 : {
1942 : let mut locked = self.inner.write().unwrap();
1943 :
1944 : for (tenant_shard_id, observed_loc) in configs.tenant_shards {
1945 : let Some(tenant_shard) = locked.tenants.get_mut(&tenant_shard_id) else {
1946 : cleanup.push(tenant_shard_id);
1947 : continue;
1948 : };
1949 : tenant_shard
1950 : .observed
1951 : .locations
1952 : .insert(node.get_id(), ObservedStateLocation { conf: observed_loc });
1953 : }
1954 : }
1955 :
1956 : for tenant_shard_id in cleanup {
1957 : tracing::info!("Detaching {tenant_shard_id}");
1958 : match node
1959 : .with_client_retries(
1960 0 : |client| async move {
1961 0 : let config = LocationConfig {
1962 0 : mode: LocationConfigMode::Detached,
1963 0 : generation: None,
1964 0 : secondary_conf: None,
1965 0 : shard_number: tenant_shard_id.shard_number.0,
1966 0 : shard_count: tenant_shard_id.shard_count.literal(),
1967 0 : shard_stripe_size: 0,
1968 0 : tenant_conf: models::TenantConfig::default(),
1969 0 : };
1970 0 : client
1971 0 : .location_config(tenant_shard_id, config, None, false)
1972 0 : .await
1973 0 : },
1974 : &self.config.pageserver_jwt_token,
1975 : 1,
1976 : 5,
1977 : SHORT_RECONCILE_TIMEOUT,
1978 : &self.cancel,
1979 : )
1980 : .await
1981 : {
1982 : None => {
1983 : // We're shutting down (the Node's cancellation token can't have fired, because
1984 : // we're the only scope that has a reference to it, and we didn't fire it).
1985 : return Err(ApiError::ShuttingDown);
1986 : }
1987 : Some(Err(e)) => {
1988 : // Do not let the node proceed to Active state if it is not responsive to requests
1989 : // to detach. This could happen if e.g. a shutdown bug in the pageserver is preventing
1990 : // detach completing: we should not let this node back into the set of nodes considered
1991 : // okay for scheduling.
1992 : return Err(ApiError::Conflict(format!(
1993 : "Node {node} failed to detach {tenant_shard_id}: {e}"
1994 : )));
1995 : }
1996 : Some(Ok(_)) => {}
1997 : };
1998 : }
1999 :
2000 : Ok(())
2001 : }
2002 :
2003 0 : pub(crate) async fn re_attach(
2004 0 : &self,
2005 0 : reattach_req: ReAttachRequest,
2006 0 : ) -> Result<ReAttachResponse, ApiError> {
2007 0 : if let Some(register_req) = reattach_req.register {
2008 0 : self.node_register(register_req).await?;
2009 0 : }
2010 :
2011 : // Ordering: we must persist generation number updates before making them visible in the in-memory state
2012 0 : let incremented_generations = self.persistence.re_attach(reattach_req.node_id).await?;
2013 :
2014 0 : tracing::info!(
2015 : node_id=%reattach_req.node_id,
2016 0 : "Incremented {} tenant shards' generations",
2017 0 : incremented_generations.len()
2018 : );
2019 :
2020 : // Apply the updated generation to our in-memory state, and
2021 : // gather discover secondary locations.
2022 0 : let mut locked = self.inner.write().unwrap();
2023 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
2024 0 :
2025 0 : let mut response = ReAttachResponse {
2026 0 : tenants: Vec::new(),
2027 0 : };
2028 :
2029 : // TODO: cancel/restart any running reconciliation for this tenant, it might be trying
2030 : // to call location_conf API with an old generation. Wait for cancellation to complete
2031 : // before responding to this request. Requires well implemented CancellationToken logic
2032 : // all the way to where we call location_conf. Even then, there can still be a location_conf
2033 : // request in flight over the network: TODO handle that by making location_conf API refuse
2034 : // to go backward in generations.
2035 :
2036 : // Scan through all shards, applying updates for ones where we updated generation
2037 : // and identifying shards that intend to have a secondary location on this node.
2038 0 : for (tenant_shard_id, shard) in tenants {
2039 0 : if let Some(new_gen) = incremented_generations.get(tenant_shard_id) {
2040 0 : let new_gen = *new_gen;
2041 0 : response.tenants.push(ReAttachResponseTenant {
2042 0 : id: *tenant_shard_id,
2043 0 : r#gen: Some(new_gen.into().unwrap()),
2044 0 : // A tenant is only put into multi or stale modes in the middle of a [`Reconciler::live_migrate`]
2045 0 : // execution. If a pageserver is restarted during that process, then the reconcile pass will
2046 0 : // fail, and start from scratch, so it doesn't make sense for us to try and preserve
2047 0 : // the stale/multi states at this point.
2048 0 : mode: LocationConfigMode::AttachedSingle,
2049 0 : });
2050 0 :
2051 0 : shard.generation = std::cmp::max(shard.generation, Some(new_gen));
2052 0 : if let Some(observed) = shard.observed.locations.get_mut(&reattach_req.node_id) {
2053 : // Why can we update `observed` even though we're not sure our response will be received
2054 : // by the pageserver? Because the pageserver will not proceed with startup until
2055 : // it has processed response: if it loses it, we'll see another request and increment
2056 : // generation again, avoiding any uncertainty about dirtiness of tenant's state.
2057 0 : if let Some(conf) = observed.conf.as_mut() {
2058 0 : conf.generation = new_gen.into();
2059 0 : }
2060 0 : } else {
2061 0 : // This node has no observed state for the shard: perhaps it was offline
2062 0 : // when the pageserver restarted. Insert a None, so that the Reconciler
2063 0 : // will be prompted to learn the location's state before it makes changes.
2064 0 : shard
2065 0 : .observed
2066 0 : .locations
2067 0 : .insert(reattach_req.node_id, ObservedStateLocation { conf: None });
2068 0 : }
2069 0 : } else if shard.intent.get_secondary().contains(&reattach_req.node_id) {
2070 0 : // Ordering: pageserver will not accept /location_config requests until it has
2071 0 : // finished processing the response from re-attach. So we can update our in-memory state
2072 0 : // now, and be confident that we are not stamping on the result of some later location config.
2073 0 : // TODO: however, we are not strictly ordered wrt ReconcileResults queue,
2074 0 : // so we might update observed state here, and then get over-written by some racing
2075 0 : // ReconcileResult. The impact is low however, since we have set state on pageserver something
2076 0 : // that matches intent, so worst case if we race then we end up doing a spurious reconcile.
2077 0 :
2078 0 : response.tenants.push(ReAttachResponseTenant {
2079 0 : id: *tenant_shard_id,
2080 0 : r#gen: None,
2081 0 : mode: LocationConfigMode::Secondary,
2082 0 : });
2083 0 :
2084 0 : // We must not update observed, because we have no guarantee that our
2085 0 : // response will be received by the pageserver. This could leave it
2086 0 : // falsely dirty, but the resulting reconcile should be idempotent.
2087 0 : }
2088 : }
2089 :
2090 : // We consider a node Active once we have composed a re-attach response, but we
2091 : // do not call [`Self::node_activate_reconcile`]: the handling of the re-attach response
2092 : // implicitly synchronizes the LocationConfigs on the node.
2093 : //
2094 : // Setting a node active unblocks any Reconcilers that might write to the location config API,
2095 : // but those requests will not be accepted by the node until it has finished processing
2096 : // the re-attach response.
2097 : //
2098 : // Additionally, reset the nodes scheduling policy to match the conditional update done
2099 : // in [`Persistence::re_attach`].
2100 0 : if let Some(node) = nodes.get(&reattach_req.node_id) {
2101 0 : let reset_scheduling = matches!(
2102 0 : node.get_scheduling(),
2103 : NodeSchedulingPolicy::PauseForRestart
2104 : | NodeSchedulingPolicy::Draining
2105 : | NodeSchedulingPolicy::Filling
2106 : );
2107 :
2108 0 : let mut new_nodes = (**nodes).clone();
2109 0 : if let Some(node) = new_nodes.get_mut(&reattach_req.node_id) {
2110 0 : if reset_scheduling {
2111 0 : node.set_scheduling(NodeSchedulingPolicy::Active);
2112 0 : }
2113 :
2114 0 : tracing::info!("Marking {} warming-up on reattach", reattach_req.node_id);
2115 0 : node.set_availability(NodeAvailability::WarmingUp(std::time::Instant::now()));
2116 0 :
2117 0 : scheduler.node_upsert(node);
2118 0 : let new_nodes = Arc::new(new_nodes);
2119 0 : *nodes = new_nodes;
2120 : } else {
2121 0 : tracing::error!(
2122 0 : "Reattaching node {} was removed while processing the request",
2123 : reattach_req.node_id
2124 : );
2125 : }
2126 0 : }
2127 :
2128 0 : Ok(response)
2129 0 : }
2130 :
2131 0 : pub(crate) async fn validate(
2132 0 : &self,
2133 0 : validate_req: ValidateRequest,
2134 0 : ) -> Result<ValidateResponse, DatabaseError> {
2135 : // Fast in-memory check: we may reject validation on anything that doesn't match our
2136 : // in-memory generation for a shard
2137 0 : let in_memory_result = {
2138 0 : let mut in_memory_result = Vec::new();
2139 0 : let locked = self.inner.read().unwrap();
2140 0 : for req_tenant in validate_req.tenants {
2141 0 : if let Some(tenant_shard) = locked.tenants.get(&req_tenant.id) {
2142 0 : let valid = tenant_shard.generation == Some(Generation::new(req_tenant.r#gen));
2143 0 : tracing::info!(
2144 0 : "handle_validate: {}(gen {}): valid={valid} (latest {:?})",
2145 : req_tenant.id,
2146 : req_tenant.r#gen,
2147 : tenant_shard.generation
2148 : );
2149 :
2150 0 : in_memory_result.push((
2151 0 : req_tenant.id,
2152 0 : Generation::new(req_tenant.r#gen),
2153 0 : valid,
2154 0 : ));
2155 : } else {
2156 : // This is legal: for example during a shard split the pageserver may still
2157 : // have deletions in its queue from the old pre-split shard, or after deletion
2158 : // of a tenant that was busy with compaction/gc while being deleted.
2159 0 : tracing::info!(
2160 0 : "Refusing deletion validation for missing shard {}",
2161 : req_tenant.id
2162 : );
2163 : }
2164 : }
2165 :
2166 0 : in_memory_result
2167 : };
2168 :
2169 : // Database calls to confirm validity for anything that passed the in-memory check. We must do this
2170 : // in case of controller split-brain, where some other controller process might have incremented the generation.
2171 0 : let db_generations = self
2172 0 : .persistence
2173 0 : .shard_generations(
2174 0 : in_memory_result
2175 0 : .iter()
2176 0 : .filter_map(|i| if i.2 { Some(&i.0) } else { None }),
2177 0 : )
2178 0 : .await?;
2179 0 : let db_generations = db_generations.into_iter().collect::<HashMap<_, _>>();
2180 0 :
2181 0 : let mut response = ValidateResponse {
2182 0 : tenants: Vec::new(),
2183 0 : };
2184 0 : for (tenant_shard_id, validate_generation, valid) in in_memory_result.into_iter() {
2185 0 : let valid = if valid {
2186 0 : let db_generation = db_generations.get(&tenant_shard_id);
2187 0 : db_generation == Some(&Some(validate_generation))
2188 : } else {
2189 : // If in-memory state says it's invalid, trust that. It's always safe to fail a validation, at worst
2190 : // this prevents a pageserver from cleaning up an object in S3.
2191 0 : false
2192 : };
2193 :
2194 0 : response.tenants.push(ValidateResponseTenant {
2195 0 : id: tenant_shard_id,
2196 0 : valid,
2197 0 : })
2198 : }
2199 :
2200 0 : Ok(response)
2201 0 : }
2202 :
2203 0 : pub(crate) async fn tenant_create(
2204 0 : &self,
2205 0 : create_req: TenantCreateRequest,
2206 0 : ) -> Result<TenantCreateResponse, ApiError> {
2207 0 : let tenant_id = create_req.new_tenant_id.tenant_id;
2208 :
2209 : // Exclude any concurrent attempts to create/access the same tenant ID
2210 0 : let _tenant_lock = trace_exclusive_lock(
2211 0 : &self.tenant_op_locks,
2212 0 : create_req.new_tenant_id.tenant_id,
2213 0 : TenantOperations::Create,
2214 0 : )
2215 0 : .await;
2216 0 : let (response, waiters) = self.do_tenant_create(create_req).await?;
2217 :
2218 0 : if let Err(e) = self.await_waiters(waiters, RECONCILE_TIMEOUT).await {
2219 : // Avoid deadlock: reconcile may fail while notifying compute, if the cloud control plane refuses to
2220 : // accept compute notifications while it is in the process of creating. Reconciliation will
2221 : // be retried in the background.
2222 0 : tracing::warn!(%tenant_id, "Reconcile not done yet while creating tenant ({e})");
2223 0 : }
2224 0 : Ok(response)
2225 0 : }
2226 :
2227 0 : pub(crate) async fn do_tenant_create(
2228 0 : &self,
2229 0 : create_req: TenantCreateRequest,
2230 0 : ) -> Result<(TenantCreateResponse, Vec<ReconcilerWaiter>), ApiError> {
2231 0 : let placement_policy = create_req
2232 0 : .placement_policy
2233 0 : .clone()
2234 0 : // As a default, zero secondaries is convenient for tests that don't choose a policy.
2235 0 : .unwrap_or(PlacementPolicy::Attached(0));
2236 :
2237 : // This service expects to handle sharding itself: it is an error to try and directly create
2238 : // a particular shard here.
2239 0 : let tenant_id = if !create_req.new_tenant_id.is_unsharded() {
2240 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
2241 0 : "Attempted to create a specific shard, this API is for creating the whole tenant"
2242 0 : )));
2243 : } else {
2244 0 : create_req.new_tenant_id.tenant_id
2245 0 : };
2246 0 :
2247 0 : tracing::info!(
2248 0 : "Creating tenant {}, shard_count={:?}",
2249 : create_req.new_tenant_id,
2250 : create_req.shard_parameters.count,
2251 : );
2252 :
2253 0 : let create_ids = (0..create_req.shard_parameters.count.count())
2254 0 : .map(|i| TenantShardId {
2255 0 : tenant_id,
2256 0 : shard_number: ShardNumber(i),
2257 0 : shard_count: create_req.shard_parameters.count,
2258 0 : })
2259 0 : .collect::<Vec<_>>();
2260 :
2261 : // If the caller specifies a None generation, it means "start from default". This is different
2262 : // to [`Self::tenant_location_config`], where a None generation is used to represent
2263 : // an incompletely-onboarded tenant.
2264 0 : let initial_generation = if matches!(placement_policy, PlacementPolicy::Secondary) {
2265 0 : tracing::info!(
2266 0 : "tenant_create: secondary mode, generation is_some={}",
2267 0 : create_req.generation.is_some()
2268 : );
2269 0 : create_req.generation.map(Generation::new)
2270 : } else {
2271 0 : tracing::info!(
2272 0 : "tenant_create: not secondary mode, generation is_some={}",
2273 0 : create_req.generation.is_some()
2274 : );
2275 0 : Some(
2276 0 : create_req
2277 0 : .generation
2278 0 : .map(Generation::new)
2279 0 : .unwrap_or(INITIAL_GENERATION),
2280 0 : )
2281 : };
2282 :
2283 0 : let preferred_az_id = {
2284 0 : let locked = self.inner.read().unwrap();
2285 : // Idempotency: take the existing value if the tenant already exists
2286 0 : if let Some(shard) = locked.tenants.get(create_ids.first().unwrap()) {
2287 0 : shard.preferred_az().cloned()
2288 : } else {
2289 0 : locked.scheduler.get_az_for_new_tenant()
2290 : }
2291 : };
2292 :
2293 : // Ordering: we persist tenant shards before creating them on the pageserver. This enables a caller
2294 : // to clean up after themselves by issuing a tenant deletion if something goes wrong and we restart
2295 : // during the creation, rather than risking leaving orphan objects in S3.
2296 0 : let persist_tenant_shards = create_ids
2297 0 : .iter()
2298 0 : .map(|tenant_shard_id| TenantShardPersistence {
2299 0 : tenant_id: tenant_shard_id.tenant_id.to_string(),
2300 0 : shard_number: tenant_shard_id.shard_number.0 as i32,
2301 0 : shard_count: tenant_shard_id.shard_count.literal() as i32,
2302 0 : shard_stripe_size: create_req.shard_parameters.stripe_size.0 as i32,
2303 0 : generation: initial_generation.map(|g| g.into().unwrap() as i32),
2304 0 : // The pageserver is not known until scheduling happens: we will set this column when
2305 0 : // incrementing the generation the first time we attach to a pageserver.
2306 0 : generation_pageserver: None,
2307 0 : placement_policy: serde_json::to_string(&placement_policy).unwrap(),
2308 0 : config: serde_json::to_string(&create_req.config).unwrap(),
2309 0 : splitting: SplitState::default(),
2310 0 : scheduling_policy: serde_json::to_string(&ShardSchedulingPolicy::default())
2311 0 : .unwrap(),
2312 0 : preferred_az_id: preferred_az_id.as_ref().map(|az| az.to_string()),
2313 0 : })
2314 0 : .collect();
2315 0 :
2316 0 : match self
2317 0 : .persistence
2318 0 : .insert_tenant_shards(persist_tenant_shards)
2319 0 : .await
2320 : {
2321 0 : Ok(_) => {}
2322 : Err(DatabaseError::Query(diesel::result::Error::DatabaseError(
2323 : DatabaseErrorKind::UniqueViolation,
2324 : _,
2325 : ))) => {
2326 : // Unique key violation: this is probably a retry. Because the shard count is part of the unique key,
2327 : // if we see a unique key violation it means that the creation request's shard count matches the previous
2328 : // creation's shard count.
2329 0 : tracing::info!(
2330 0 : "Tenant shards already present in database, proceeding with idempotent creation..."
2331 : );
2332 : }
2333 : // Any other database error is unexpected and a bug.
2334 0 : Err(e) => return Err(ApiError::InternalServerError(anyhow::anyhow!(e))),
2335 : };
2336 :
2337 0 : let mut schedule_context = ScheduleContext::default();
2338 0 : let mut schedule_error = None;
2339 0 : let mut response_shards = Vec::new();
2340 0 : for tenant_shard_id in create_ids {
2341 0 : tracing::info!("Creating shard {tenant_shard_id}...");
2342 :
2343 0 : let outcome = self
2344 0 : .do_initial_shard_scheduling(
2345 0 : tenant_shard_id,
2346 0 : initial_generation,
2347 0 : &create_req.shard_parameters,
2348 0 : create_req.config.clone(),
2349 0 : placement_policy.clone(),
2350 0 : preferred_az_id.as_ref(),
2351 0 : &mut schedule_context,
2352 0 : )
2353 0 : .await;
2354 :
2355 0 : match outcome {
2356 0 : InitialShardScheduleOutcome::Scheduled(resp) => response_shards.push(resp),
2357 0 : InitialShardScheduleOutcome::NotScheduled => {}
2358 0 : InitialShardScheduleOutcome::ShardScheduleError(err) => {
2359 0 : schedule_error = Some(err);
2360 0 : }
2361 : }
2362 : }
2363 :
2364 : // If we failed to schedule shards, then they are still created in the controller,
2365 : // but we return an error to the requester to avoid a silent failure when someone
2366 : // tries to e.g. create a tenant whose placement policy requires more nodes than
2367 : // are present in the system. We do this here rather than in the above loop, to
2368 : // avoid situations where we only create a subset of shards in the tenant.
2369 0 : if let Some(e) = schedule_error {
2370 0 : return Err(ApiError::Conflict(format!(
2371 0 : "Failed to schedule shard(s): {e}"
2372 0 : )));
2373 0 : }
2374 0 :
2375 0 : let waiters = {
2376 0 : let mut locked = self.inner.write().unwrap();
2377 0 : let (nodes, tenants, _scheduler) = locked.parts_mut();
2378 0 : let config = ReconcilerConfigBuilder::new(ReconcilerPriority::High)
2379 0 : .tenant_creation_hint(true)
2380 0 : .build();
2381 0 : tenants
2382 0 : .range_mut(TenantShardId::tenant_range(tenant_id))
2383 0 : .filter_map(|(_shard_id, shard)| {
2384 0 : self.maybe_configured_reconcile_shard(shard, nodes, config)
2385 0 : })
2386 0 : .collect::<Vec<_>>()
2387 0 : };
2388 0 :
2389 0 : Ok((
2390 0 : TenantCreateResponse {
2391 0 : shards: response_shards,
2392 0 : },
2393 0 : waiters,
2394 0 : ))
2395 0 : }
2396 :
2397 : /// Helper for tenant creation that does the scheduling for an individual shard. Covers both the
2398 : /// case of a new tenant and a pre-existing one.
2399 : #[allow(clippy::too_many_arguments)]
2400 0 : async fn do_initial_shard_scheduling(
2401 0 : &self,
2402 0 : tenant_shard_id: TenantShardId,
2403 0 : initial_generation: Option<Generation>,
2404 0 : shard_params: &ShardParameters,
2405 0 : config: TenantConfig,
2406 0 : placement_policy: PlacementPolicy,
2407 0 : preferred_az_id: Option<&AvailabilityZone>,
2408 0 : schedule_context: &mut ScheduleContext,
2409 0 : ) -> InitialShardScheduleOutcome {
2410 0 : let mut locked = self.inner.write().unwrap();
2411 0 : let (_nodes, tenants, scheduler) = locked.parts_mut();
2412 :
2413 : use std::collections::btree_map::Entry;
2414 0 : match tenants.entry(tenant_shard_id) {
2415 0 : Entry::Occupied(mut entry) => {
2416 0 : tracing::info!("Tenant shard {tenant_shard_id} already exists while creating");
2417 :
2418 0 : if let Err(err) = entry.get_mut().schedule(scheduler, schedule_context) {
2419 0 : return InitialShardScheduleOutcome::ShardScheduleError(err);
2420 0 : }
2421 :
2422 0 : if let Some(node_id) = entry.get().intent.get_attached() {
2423 0 : let generation = entry
2424 0 : .get()
2425 0 : .generation
2426 0 : .expect("Generation is set when in attached mode");
2427 0 : InitialShardScheduleOutcome::Scheduled(TenantCreateResponseShard {
2428 0 : shard_id: tenant_shard_id,
2429 0 : node_id: *node_id,
2430 0 : generation: generation.into().unwrap(),
2431 0 : })
2432 : } else {
2433 0 : InitialShardScheduleOutcome::NotScheduled
2434 : }
2435 : }
2436 0 : Entry::Vacant(entry) => {
2437 0 : let state = entry.insert(TenantShard::new(
2438 0 : tenant_shard_id,
2439 0 : ShardIdentity::from_params(tenant_shard_id.shard_number, shard_params),
2440 0 : placement_policy,
2441 0 : preferred_az_id.cloned(),
2442 0 : ));
2443 0 :
2444 0 : state.generation = initial_generation;
2445 0 : state.config = config;
2446 0 : if let Err(e) = state.schedule(scheduler, schedule_context) {
2447 0 : return InitialShardScheduleOutcome::ShardScheduleError(e);
2448 0 : }
2449 :
2450 : // Only include shards in result if we are attaching: the purpose
2451 : // of the response is to tell the caller where the shards are attached.
2452 0 : if let Some(node_id) = state.intent.get_attached() {
2453 0 : let generation = state
2454 0 : .generation
2455 0 : .expect("Generation is set when in attached mode");
2456 0 : InitialShardScheduleOutcome::Scheduled(TenantCreateResponseShard {
2457 0 : shard_id: tenant_shard_id,
2458 0 : node_id: *node_id,
2459 0 : generation: generation.into().unwrap(),
2460 0 : })
2461 : } else {
2462 0 : InitialShardScheduleOutcome::NotScheduled
2463 : }
2464 : }
2465 : }
2466 0 : }
2467 :
2468 : /// Helper for functions that reconcile a number of shards, and would like to do a timeout-bounded
2469 : /// wait for reconciliation to complete before responding.
2470 0 : async fn await_waiters(
2471 0 : &self,
2472 0 : waiters: Vec<ReconcilerWaiter>,
2473 0 : timeout: Duration,
2474 0 : ) -> Result<(), ReconcileWaitError> {
2475 0 : let deadline = Instant::now().checked_add(timeout).unwrap();
2476 0 : for waiter in waiters {
2477 0 : let timeout = deadline.duration_since(Instant::now());
2478 0 : waiter.wait_timeout(timeout).await?;
2479 : }
2480 :
2481 0 : Ok(())
2482 0 : }
2483 :
2484 : /// Same as [`Service::await_waiters`], but returns the waiters which are still
2485 : /// in progress
2486 0 : async fn await_waiters_remainder(
2487 0 : &self,
2488 0 : waiters: Vec<ReconcilerWaiter>,
2489 0 : timeout: Duration,
2490 0 : ) -> Vec<ReconcilerWaiter> {
2491 0 : let deadline = Instant::now().checked_add(timeout).unwrap();
2492 0 : for waiter in waiters.iter() {
2493 0 : let timeout = deadline.duration_since(Instant::now());
2494 0 : let _ = waiter.wait_timeout(timeout).await;
2495 : }
2496 :
2497 0 : waiters
2498 0 : .into_iter()
2499 0 : .filter(|waiter| matches!(waiter.get_status(), ReconcilerStatus::InProgress))
2500 0 : .collect::<Vec<_>>()
2501 0 : }
2502 :
2503 : /// Part of [`Self::tenant_location_config`]: dissect an incoming location config request,
2504 : /// and transform it into either a tenant creation of a series of shard updates.
2505 : ///
2506 : /// If the incoming request makes no changes, a [`TenantCreateOrUpdate::Update`] result will
2507 : /// still be returned.
2508 0 : fn tenant_location_config_prepare(
2509 0 : &self,
2510 0 : tenant_id: TenantId,
2511 0 : req: TenantLocationConfigRequest,
2512 0 : ) -> TenantCreateOrUpdate {
2513 0 : let mut updates = Vec::new();
2514 0 : let mut locked = self.inner.write().unwrap();
2515 0 : let (nodes, tenants, _scheduler) = locked.parts_mut();
2516 0 : let tenant_shard_id = TenantShardId::unsharded(tenant_id);
2517 :
2518 : // Use location config mode as an indicator of policy.
2519 0 : let placement_policy = match req.config.mode {
2520 0 : LocationConfigMode::Detached => PlacementPolicy::Detached,
2521 0 : LocationConfigMode::Secondary => PlacementPolicy::Secondary,
2522 : LocationConfigMode::AttachedMulti
2523 : | LocationConfigMode::AttachedSingle
2524 : | LocationConfigMode::AttachedStale => {
2525 0 : if nodes.len() > 1 {
2526 0 : PlacementPolicy::Attached(1)
2527 : } else {
2528 : // Convenience for dev/test: if we just have one pageserver, import
2529 : // tenants into non-HA mode so that scheduling will succeed.
2530 0 : PlacementPolicy::Attached(0)
2531 : }
2532 : }
2533 : };
2534 :
2535 : // Ordinarily we do not update scheduling policy, but when making major changes
2536 : // like detaching or demoting to secondary-only, we need to force the scheduling
2537 : // mode to Active, or the caller's expected outcome (detach it) will not happen.
2538 0 : let scheduling_policy = match req.config.mode {
2539 : LocationConfigMode::Detached | LocationConfigMode::Secondary => {
2540 : // Special case: when making major changes like detaching or demoting to secondary-only,
2541 : // we need to force the scheduling mode to Active, or nothing will happen.
2542 0 : Some(ShardSchedulingPolicy::Active)
2543 : }
2544 : LocationConfigMode::AttachedMulti
2545 : | LocationConfigMode::AttachedSingle
2546 : | LocationConfigMode::AttachedStale => {
2547 : // While attached, continue to respect whatever the existing scheduling mode is.
2548 0 : None
2549 : }
2550 : };
2551 :
2552 0 : let mut create = true;
2553 0 : for (shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
2554 : // Saw an existing shard: this is not a creation
2555 0 : create = false;
2556 :
2557 : // Shards may have initially been created by a Secondary request, where we
2558 : // would have left generation as None.
2559 : //
2560 : // We only update generation the first time we see an attached-mode request,
2561 : // and if there is no existing generation set. The caller is responsible for
2562 : // ensuring that no non-storage-controller pageserver ever uses a higher
2563 : // generation than they passed in here.
2564 : use LocationConfigMode::*;
2565 0 : let set_generation = match req.config.mode {
2566 0 : AttachedMulti | AttachedSingle | AttachedStale if shard.generation.is_none() => {
2567 0 : req.config.generation.map(Generation::new)
2568 : }
2569 0 : _ => None,
2570 : };
2571 :
2572 0 : updates.push(ShardUpdate {
2573 0 : tenant_shard_id: *shard_id,
2574 0 : placement_policy: placement_policy.clone(),
2575 0 : tenant_config: req.config.tenant_conf.clone(),
2576 0 : generation: set_generation,
2577 0 : scheduling_policy,
2578 0 : });
2579 : }
2580 :
2581 0 : if create {
2582 : use LocationConfigMode::*;
2583 0 : let generation = match req.config.mode {
2584 0 : AttachedMulti | AttachedSingle | AttachedStale => req.config.generation,
2585 : // If a caller provided a generation in a non-attached request, ignore it
2586 : // and leave our generation as None: this enables a subsequent update to set
2587 : // the generation when setting an attached mode for the first time.
2588 0 : _ => None,
2589 : };
2590 :
2591 0 : TenantCreateOrUpdate::Create(
2592 0 : // Synthesize a creation request
2593 0 : TenantCreateRequest {
2594 0 : new_tenant_id: tenant_shard_id,
2595 0 : generation,
2596 0 : shard_parameters: ShardParameters {
2597 0 : count: tenant_shard_id.shard_count,
2598 0 : // We only import un-sharded or single-sharded tenants, so stripe
2599 0 : // size can be made up arbitrarily here.
2600 0 : stripe_size: ShardParameters::DEFAULT_STRIPE_SIZE,
2601 0 : },
2602 0 : placement_policy: Some(placement_policy),
2603 0 : config: req.config.tenant_conf,
2604 0 : },
2605 0 : )
2606 : } else {
2607 0 : assert!(!updates.is_empty());
2608 0 : TenantCreateOrUpdate::Update(updates)
2609 : }
2610 0 : }
2611 :
2612 : /// For APIs that might act on tenants with [`PlacementPolicy::Detached`], first check if
2613 : /// the tenant is present in memory. If not, load it from the database. If it is found
2614 : /// in neither location, return a NotFound error.
2615 : ///
2616 : /// Caller must demonstrate they hold a lock guard, as otherwise two callers might try and load
2617 : /// it at the same time, or we might race with [`Self::maybe_drop_tenant`]
2618 0 : async fn maybe_load_tenant(
2619 0 : &self,
2620 0 : tenant_id: TenantId,
2621 0 : _guard: &TracingExclusiveGuard<TenantOperations>,
2622 0 : ) -> Result<(), ApiError> {
2623 : // Check if the tenant is present in memory, and select an AZ to use when loading
2624 : // if we will load it.
2625 0 : let load_in_az = {
2626 0 : let locked = self.inner.read().unwrap();
2627 0 : let existing = locked
2628 0 : .tenants
2629 0 : .range(TenantShardId::tenant_range(tenant_id))
2630 0 : .next();
2631 0 :
2632 0 : // If the tenant is not present in memory, we expect to load it from database,
2633 0 : // so let's figure out what AZ to load it into while we have self.inner locked.
2634 0 : if existing.is_none() {
2635 0 : locked
2636 0 : .scheduler
2637 0 : .get_az_for_new_tenant()
2638 0 : .ok_or(ApiError::BadRequest(anyhow::anyhow!(
2639 0 : "No AZ with nodes found to load tenant"
2640 0 : )))?
2641 : } else {
2642 : // We already have this tenant in memory
2643 0 : return Ok(());
2644 : }
2645 : };
2646 :
2647 0 : let tenant_shards = self.persistence.load_tenant(tenant_id).await?;
2648 0 : if tenant_shards.is_empty() {
2649 0 : return Err(ApiError::NotFound(
2650 0 : anyhow::anyhow!("Tenant {} not found", tenant_id).into(),
2651 0 : ));
2652 0 : }
2653 0 :
2654 0 : // Update the persistent shards with the AZ that we are about to apply to in-memory state
2655 0 : self.persistence
2656 0 : .set_tenant_shard_preferred_azs(
2657 0 : tenant_shards
2658 0 : .iter()
2659 0 : .map(|t| {
2660 0 : (
2661 0 : t.get_tenant_shard_id().expect("Corrupt shard in database"),
2662 0 : Some(load_in_az.clone()),
2663 0 : )
2664 0 : })
2665 0 : .collect(),
2666 0 : )
2667 0 : .await?;
2668 :
2669 0 : let mut locked = self.inner.write().unwrap();
2670 0 : tracing::info!(
2671 0 : "Loaded {} shards for tenant {}",
2672 0 : tenant_shards.len(),
2673 : tenant_id
2674 : );
2675 :
2676 0 : locked.tenants.extend(tenant_shards.into_iter().map(|p| {
2677 0 : let intent = IntentState::new(Some(load_in_az.clone()));
2678 0 : let shard =
2679 0 : TenantShard::from_persistent(p, intent).expect("Corrupt shard row in database");
2680 0 :
2681 0 : // Sanity check: when loading on-demand, we should always be loaded something Detached
2682 0 : debug_assert!(shard.policy == PlacementPolicy::Detached);
2683 0 : if shard.policy != PlacementPolicy::Detached {
2684 0 : tracing::error!(
2685 0 : "Tenant shard {} loaded on-demand, but has non-Detached policy {:?}",
2686 : shard.tenant_shard_id,
2687 : shard.policy
2688 : );
2689 0 : }
2690 :
2691 0 : (shard.tenant_shard_id, shard)
2692 0 : }));
2693 0 :
2694 0 : Ok(())
2695 0 : }
2696 :
2697 : /// If all shards for a tenant are detached, and in a fully quiescent state (no observed locations on pageservers),
2698 : /// and have no reconciler running, then we can drop the tenant from memory. It will be reloaded on-demand
2699 : /// if we are asked to attach it again (see [`Self::maybe_load_tenant`]).
2700 : ///
2701 : /// Caller must demonstrate they hold a lock guard, as otherwise it is unsafe to drop a tenant from
2702 : /// memory while some other function might assume it continues to exist while not holding the lock on Self::inner.
2703 0 : fn maybe_drop_tenant(
2704 0 : &self,
2705 0 : tenant_id: TenantId,
2706 0 : locked: &mut std::sync::RwLockWriteGuard<ServiceState>,
2707 0 : _guard: &TracingExclusiveGuard<TenantOperations>,
2708 0 : ) {
2709 0 : let mut tenant_shards = locked.tenants.range(TenantShardId::tenant_range(tenant_id));
2710 0 : if tenant_shards.all(|(_id, shard)| {
2711 0 : shard.policy == PlacementPolicy::Detached
2712 0 : && shard.reconciler.is_none()
2713 0 : && shard.observed.is_empty()
2714 0 : }) {
2715 0 : let keys = locked
2716 0 : .tenants
2717 0 : .range(TenantShardId::tenant_range(tenant_id))
2718 0 : .map(|(id, _)| id)
2719 0 : .copied()
2720 0 : .collect::<Vec<_>>();
2721 0 : for key in keys {
2722 0 : tracing::info!("Dropping detached tenant shard {} from memory", key);
2723 0 : locked.tenants.remove(&key);
2724 : }
2725 0 : }
2726 0 : }
2727 :
2728 : /// This API is used by the cloud control plane to migrate unsharded tenants that it created
2729 : /// directly with pageservers into this service.
2730 : ///
2731 : /// Cloud control plane MUST NOT continue issuing GENERATION NUMBERS for this tenant once it
2732 : /// has attempted to call this API. Failure to oblige to this rule may lead to S3 corruption.
2733 : /// Think of the first attempt to call this API as a transfer of absolute authority over the
2734 : /// tenant's source of generation numbers.
2735 : ///
2736 : /// The mode in this request coarse-grained control of tenants:
2737 : /// - Call with mode Attached* to upsert the tenant.
2738 : /// - Call with mode Secondary to either onboard a tenant without attaching it, or
2739 : /// to set an existing tenant to PolicyMode::Secondary
2740 : /// - Call with mode Detached to switch to PolicyMode::Detached
2741 0 : pub(crate) async fn tenant_location_config(
2742 0 : &self,
2743 0 : tenant_shard_id: TenantShardId,
2744 0 : req: TenantLocationConfigRequest,
2745 0 : ) -> Result<TenantLocationConfigResponse, ApiError> {
2746 : // We require an exclusive lock, because we are updating both persistent and in-memory state
2747 0 : let _tenant_lock = trace_exclusive_lock(
2748 0 : &self.tenant_op_locks,
2749 0 : tenant_shard_id.tenant_id,
2750 0 : TenantOperations::LocationConfig,
2751 0 : )
2752 0 : .await;
2753 :
2754 0 : let tenant_id = if !tenant_shard_id.is_unsharded() {
2755 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
2756 0 : "This API is for importing single-sharded or unsharded tenants"
2757 0 : )));
2758 : } else {
2759 0 : tenant_shard_id.tenant_id
2760 0 : };
2761 0 :
2762 0 : // In case we are waking up a Detached tenant
2763 0 : match self.maybe_load_tenant(tenant_id, &_tenant_lock).await {
2764 0 : Ok(()) | Err(ApiError::NotFound(_)) => {
2765 0 : // This is a creation or an update
2766 0 : }
2767 0 : Err(e) => {
2768 0 : return Err(e);
2769 : }
2770 : };
2771 :
2772 : // First check if this is a creation or an update
2773 0 : let create_or_update = self.tenant_location_config_prepare(tenant_id, req);
2774 0 :
2775 0 : let mut result = TenantLocationConfigResponse {
2776 0 : shards: Vec::new(),
2777 0 : stripe_size: None,
2778 0 : };
2779 0 : let waiters = match create_or_update {
2780 0 : TenantCreateOrUpdate::Create(create_req) => {
2781 0 : let (create_resp, waiters) = self.do_tenant_create(create_req).await?;
2782 0 : result.shards = create_resp
2783 0 : .shards
2784 0 : .into_iter()
2785 0 : .map(|s| TenantShardLocation {
2786 0 : node_id: s.node_id,
2787 0 : shard_id: s.shard_id,
2788 0 : })
2789 0 : .collect();
2790 0 : waiters
2791 : }
2792 0 : TenantCreateOrUpdate::Update(updates) => {
2793 0 : // Persist updates
2794 0 : // Ordering: write to the database before applying changes in-memory, so that
2795 0 : // we will not appear time-travel backwards on a restart.
2796 0 :
2797 0 : let mut schedule_context = ScheduleContext::default();
2798 : for ShardUpdate {
2799 0 : tenant_shard_id,
2800 0 : placement_policy,
2801 0 : tenant_config,
2802 0 : generation,
2803 0 : scheduling_policy,
2804 0 : } in &updates
2805 : {
2806 0 : self.persistence
2807 0 : .update_tenant_shard(
2808 0 : TenantFilter::Shard(*tenant_shard_id),
2809 0 : Some(placement_policy.clone()),
2810 0 : Some(tenant_config.clone()),
2811 0 : *generation,
2812 0 : *scheduling_policy,
2813 0 : )
2814 0 : .await?;
2815 : }
2816 :
2817 : // Apply updates in-memory
2818 0 : let mut waiters = Vec::new();
2819 0 : {
2820 0 : let mut locked = self.inner.write().unwrap();
2821 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
2822 :
2823 : for ShardUpdate {
2824 0 : tenant_shard_id,
2825 0 : placement_policy,
2826 0 : tenant_config,
2827 0 : generation: update_generation,
2828 0 : scheduling_policy,
2829 0 : } in updates
2830 : {
2831 0 : let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
2832 0 : tracing::warn!("Shard {tenant_shard_id} removed while updating");
2833 0 : continue;
2834 : };
2835 :
2836 : // Update stripe size
2837 0 : if result.stripe_size.is_none() && shard.shard.count.count() > 1 {
2838 0 : result.stripe_size = Some(shard.shard.stripe_size);
2839 0 : }
2840 :
2841 0 : shard.policy = placement_policy;
2842 0 : shard.config = tenant_config;
2843 0 : if let Some(generation) = update_generation {
2844 0 : shard.generation = Some(generation);
2845 0 : }
2846 :
2847 0 : if let Some(scheduling_policy) = scheduling_policy {
2848 0 : shard.set_scheduling_policy(scheduling_policy);
2849 0 : }
2850 :
2851 0 : shard.schedule(scheduler, &mut schedule_context)?;
2852 :
2853 0 : let maybe_waiter =
2854 0 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High);
2855 0 : if let Some(waiter) = maybe_waiter {
2856 0 : waiters.push(waiter);
2857 0 : }
2858 :
2859 0 : if let Some(node_id) = shard.intent.get_attached() {
2860 0 : result.shards.push(TenantShardLocation {
2861 0 : shard_id: tenant_shard_id,
2862 0 : node_id: *node_id,
2863 0 : })
2864 0 : }
2865 : }
2866 : }
2867 0 : waiters
2868 : }
2869 : };
2870 :
2871 0 : if let Err(e) = self.await_waiters(waiters, SHORT_RECONCILE_TIMEOUT).await {
2872 : // Do not treat a reconcile error as fatal: we have already applied any requested
2873 : // Intent changes, and the reconcile can fail for external reasons like unavailable
2874 : // compute notification API. In these cases, it is important that we do not
2875 : // cause the cloud control plane to retry forever on this API.
2876 0 : tracing::warn!(
2877 0 : "Failed to reconcile after /location_config: {e}, returning success anyway"
2878 : );
2879 0 : }
2880 :
2881 : // Logging the full result is useful because it lets us cross-check what the cloud control
2882 : // plane's tenant_shards table should contain.
2883 0 : tracing::info!("Complete, returning {result:?}");
2884 :
2885 0 : Ok(result)
2886 0 : }
2887 :
2888 0 : pub(crate) async fn tenant_config_patch(
2889 0 : &self,
2890 0 : req: TenantConfigPatchRequest,
2891 0 : ) -> Result<(), ApiError> {
2892 0 : let _tenant_lock = trace_exclusive_lock(
2893 0 : &self.tenant_op_locks,
2894 0 : req.tenant_id,
2895 0 : TenantOperations::ConfigPatch,
2896 0 : )
2897 0 : .await;
2898 :
2899 0 : let tenant_id = req.tenant_id;
2900 0 : let patch = req.config;
2901 0 :
2902 0 : self.maybe_load_tenant(tenant_id, &_tenant_lock).await?;
2903 :
2904 0 : let base = {
2905 0 : let locked = self.inner.read().unwrap();
2906 0 : let shards = locked
2907 0 : .tenants
2908 0 : .range(TenantShardId::tenant_range(req.tenant_id));
2909 0 :
2910 0 : let mut configs = shards.map(|(_sid, shard)| &shard.config).peekable();
2911 :
2912 0 : let first = match configs.peek() {
2913 0 : Some(first) => (*first).clone(),
2914 : None => {
2915 0 : return Err(ApiError::NotFound(
2916 0 : anyhow::anyhow!("Tenant {} not found", req.tenant_id).into(),
2917 0 : ));
2918 : }
2919 : };
2920 :
2921 0 : if !configs.all_equal() {
2922 0 : tracing::error!("Tenant configs for {} are mismatched. ", req.tenant_id);
2923 : // This can't happen because we atomically update the database records
2924 : // of all shards to the new value in [`Self::set_tenant_config_and_reconcile`].
2925 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
2926 0 : "Tenant configs for {} are mismatched",
2927 0 : req.tenant_id
2928 0 : )));
2929 0 : }
2930 0 :
2931 0 : first
2932 : };
2933 :
2934 0 : let updated_config = base
2935 0 : .apply_patch(patch)
2936 0 : .map_err(|err| ApiError::BadRequest(anyhow::anyhow!(err)))?;
2937 0 : self.set_tenant_config_and_reconcile(tenant_id, updated_config)
2938 0 : .await
2939 0 : }
2940 :
2941 0 : pub(crate) async fn tenant_config_set(&self, req: TenantConfigRequest) -> Result<(), ApiError> {
2942 : // We require an exclusive lock, because we are updating persistent and in-memory state
2943 0 : let _tenant_lock = trace_exclusive_lock(
2944 0 : &self.tenant_op_locks,
2945 0 : req.tenant_id,
2946 0 : TenantOperations::ConfigSet,
2947 0 : )
2948 0 : .await;
2949 :
2950 0 : self.maybe_load_tenant(req.tenant_id, &_tenant_lock).await?;
2951 :
2952 0 : self.set_tenant_config_and_reconcile(req.tenant_id, req.config)
2953 0 : .await
2954 0 : }
2955 :
2956 0 : async fn set_tenant_config_and_reconcile(
2957 0 : &self,
2958 0 : tenant_id: TenantId,
2959 0 : config: TenantConfig,
2960 0 : ) -> Result<(), ApiError> {
2961 0 : self.persistence
2962 0 : .update_tenant_shard(
2963 0 : TenantFilter::Tenant(tenant_id),
2964 0 : None,
2965 0 : Some(config.clone()),
2966 0 : None,
2967 0 : None,
2968 0 : )
2969 0 : .await?;
2970 :
2971 0 : let waiters = {
2972 0 : let mut waiters = Vec::new();
2973 0 : let mut locked = self.inner.write().unwrap();
2974 0 : let (nodes, tenants, _scheduler) = locked.parts_mut();
2975 0 : for (_shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
2976 0 : shard.config = config.clone();
2977 0 : if let Some(waiter) =
2978 0 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High)
2979 0 : {
2980 0 : waiters.push(waiter);
2981 0 : }
2982 : }
2983 0 : waiters
2984 : };
2985 :
2986 0 : if let Err(e) = self.await_waiters(waiters, SHORT_RECONCILE_TIMEOUT).await {
2987 : // Treat this as success because we have stored the configuration. If e.g.
2988 : // a node was unavailable at this time, it should not stop us accepting a
2989 : // configuration change.
2990 0 : tracing::warn!(%tenant_id, "Accepted configuration update but reconciliation failed: {e}");
2991 0 : }
2992 :
2993 0 : Ok(())
2994 0 : }
2995 :
2996 0 : pub(crate) fn tenant_config_get(
2997 0 : &self,
2998 0 : tenant_id: TenantId,
2999 0 : ) -> Result<HashMap<&str, serde_json::Value>, ApiError> {
3000 0 : let config = {
3001 0 : let locked = self.inner.read().unwrap();
3002 0 :
3003 0 : match locked
3004 0 : .tenants
3005 0 : .range(TenantShardId::tenant_range(tenant_id))
3006 0 : .next()
3007 : {
3008 0 : Some((_tenant_shard_id, shard)) => shard.config.clone(),
3009 : None => {
3010 0 : return Err(ApiError::NotFound(
3011 0 : anyhow::anyhow!("Tenant not found").into(),
3012 0 : ));
3013 : }
3014 : }
3015 : };
3016 :
3017 : // Unlike the pageserver, we do not have a set of global defaults: the config is
3018 : // entirely per-tenant. Therefore the distinction between `tenant_specific_overrides`
3019 : // and `effective_config` in the response is meaningless, but we retain that syntax
3020 : // in order to remain compatible with the pageserver API.
3021 :
3022 0 : let response = HashMap::from([
3023 : (
3024 : "tenant_specific_overrides",
3025 0 : serde_json::to_value(&config)
3026 0 : .context("serializing tenant specific overrides")
3027 0 : .map_err(ApiError::InternalServerError)?,
3028 : ),
3029 : (
3030 0 : "effective_config",
3031 0 : serde_json::to_value(&config)
3032 0 : .context("serializing effective config")
3033 0 : .map_err(ApiError::InternalServerError)?,
3034 : ),
3035 : ]);
3036 :
3037 0 : Ok(response)
3038 0 : }
3039 :
3040 0 : pub(crate) async fn tenant_time_travel_remote_storage(
3041 0 : &self,
3042 0 : time_travel_req: &TenantTimeTravelRequest,
3043 0 : tenant_id: TenantId,
3044 0 : timestamp: Cow<'_, str>,
3045 0 : done_if_after: Cow<'_, str>,
3046 0 : ) -> Result<(), ApiError> {
3047 0 : let _tenant_lock = trace_exclusive_lock(
3048 0 : &self.tenant_op_locks,
3049 0 : tenant_id,
3050 0 : TenantOperations::TimeTravelRemoteStorage,
3051 0 : )
3052 0 : .await;
3053 :
3054 0 : let node = {
3055 0 : let mut locked = self.inner.write().unwrap();
3056 : // Just a sanity check to prevent misuse: the API expects that the tenant is fully
3057 : // detached everywhere, and nothing writes to S3 storage. Here, we verify that,
3058 : // but only at the start of the process, so it's really just to prevent operator
3059 : // mistakes.
3060 0 : for (shard_id, shard) in locked.tenants.range(TenantShardId::tenant_range(tenant_id)) {
3061 0 : if shard.intent.get_attached().is_some() || !shard.intent.get_secondary().is_empty()
3062 : {
3063 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
3064 0 : "We want tenant to be attached in shard with tenant_shard_id={shard_id}"
3065 0 : )));
3066 0 : }
3067 0 : let maybe_attached = shard
3068 0 : .observed
3069 0 : .locations
3070 0 : .iter()
3071 0 : .filter_map(|(node_id, observed_location)| {
3072 0 : observed_location
3073 0 : .conf
3074 0 : .as_ref()
3075 0 : .map(|loc| (node_id, observed_location, loc.mode))
3076 0 : })
3077 0 : .find(|(_, _, mode)| *mode != LocationConfigMode::Detached);
3078 0 : if let Some((node_id, _observed_location, mode)) = maybe_attached {
3079 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
3080 0 : "We observed attached={mode:?} tenant in node_id={node_id} shard with tenant_shard_id={shard_id}"
3081 0 : )));
3082 0 : }
3083 : }
3084 0 : let scheduler = &mut locked.scheduler;
3085 : // Right now we only perform the operation on a single node without parallelization
3086 : // TODO fan out the operation to multiple nodes for better performance
3087 0 : let node_id = scheduler.any_available_node()?;
3088 0 : let node = locked
3089 0 : .nodes
3090 0 : .get(&node_id)
3091 0 : .expect("Pageservers may not be deleted while lock is active");
3092 0 : node.clone()
3093 0 : };
3094 0 :
3095 0 : // The shard count is encoded in the remote storage's URL, so we need to handle all historically used shard counts
3096 0 : let mut counts = time_travel_req
3097 0 : .shard_counts
3098 0 : .iter()
3099 0 : .copied()
3100 0 : .collect::<HashSet<_>>()
3101 0 : .into_iter()
3102 0 : .collect::<Vec<_>>();
3103 0 : counts.sort_unstable();
3104 :
3105 0 : for count in counts {
3106 0 : let shard_ids = (0..count.count())
3107 0 : .map(|i| TenantShardId {
3108 0 : tenant_id,
3109 0 : shard_number: ShardNumber(i),
3110 0 : shard_count: count,
3111 0 : })
3112 0 : .collect::<Vec<_>>();
3113 0 : for tenant_shard_id in shard_ids {
3114 0 : let client = PageserverClient::new(
3115 0 : node.get_id(),
3116 0 : node.base_url(),
3117 0 : self.config.pageserver_jwt_token.as_deref(),
3118 0 : );
3119 0 :
3120 0 : tracing::info!("Doing time travel recovery for shard {tenant_shard_id}",);
3121 :
3122 0 : client
3123 0 : .tenant_time_travel_remote_storage(
3124 0 : tenant_shard_id,
3125 0 : ×tamp,
3126 0 : &done_if_after,
3127 0 : )
3128 0 : .await
3129 0 : .map_err(|e| {
3130 0 : ApiError::InternalServerError(anyhow::anyhow!(
3131 0 : "Error doing time travel recovery for shard {tenant_shard_id} on node {}: {e}",
3132 0 : node
3133 0 : ))
3134 0 : })?;
3135 : }
3136 : }
3137 0 : Ok(())
3138 0 : }
3139 :
3140 0 : pub(crate) async fn tenant_secondary_download(
3141 0 : &self,
3142 0 : tenant_id: TenantId,
3143 0 : wait: Option<Duration>,
3144 0 : ) -> Result<(StatusCode, SecondaryProgress), ApiError> {
3145 0 : let _tenant_lock = trace_shared_lock(
3146 0 : &self.tenant_op_locks,
3147 0 : tenant_id,
3148 0 : TenantOperations::SecondaryDownload,
3149 0 : )
3150 0 : .await;
3151 :
3152 : // Acquire lock and yield the collection of shard-node tuples which we will send requests onward to
3153 0 : let targets = {
3154 0 : let locked = self.inner.read().unwrap();
3155 0 : let mut targets = Vec::new();
3156 :
3157 0 : for (tenant_shard_id, shard) in
3158 0 : locked.tenants.range(TenantShardId::tenant_range(tenant_id))
3159 : {
3160 0 : for node_id in shard.intent.get_secondary() {
3161 0 : let node = locked
3162 0 : .nodes
3163 0 : .get(node_id)
3164 0 : .expect("Pageservers may not be deleted while referenced");
3165 0 :
3166 0 : targets.push((*tenant_shard_id, node.clone()));
3167 0 : }
3168 : }
3169 0 : targets
3170 0 : };
3171 0 :
3172 0 : // Issue concurrent requests to all shards' locations
3173 0 : let mut futs = FuturesUnordered::new();
3174 0 : for (tenant_shard_id, node) in targets {
3175 0 : let client = PageserverClient::new(
3176 0 : node.get_id(),
3177 0 : node.base_url(),
3178 0 : self.config.pageserver_jwt_token.as_deref(),
3179 0 : );
3180 0 : futs.push(async move {
3181 0 : let result = client
3182 0 : .tenant_secondary_download(tenant_shard_id, wait)
3183 0 : .await;
3184 0 : (result, node, tenant_shard_id)
3185 0 : })
3186 : }
3187 :
3188 : // Handle any errors returned by pageservers. This includes cases like this request racing with
3189 : // a scheduling operation, such that the tenant shard we're calling doesn't exist on that pageserver any more, as
3190 : // well as more general cases like 503s, 500s, or timeouts.
3191 0 : let mut aggregate_progress = SecondaryProgress::default();
3192 0 : let mut aggregate_status: Option<StatusCode> = None;
3193 0 : let mut error: Option<mgmt_api::Error> = None;
3194 0 : while let Some((result, node, tenant_shard_id)) = futs.next().await {
3195 0 : match result {
3196 0 : Err(e) => {
3197 0 : // Secondary downloads are always advisory: if something fails, we nevertheless report success, so that whoever
3198 0 : // is calling us will proceed with whatever migration they're doing, albeit with a slightly less warm cache
3199 0 : // than they had hoped for.
3200 0 : tracing::warn!("Secondary download error from pageserver {node}: {e}",);
3201 0 : error = Some(e)
3202 : }
3203 0 : Ok((status_code, progress)) => {
3204 0 : tracing::info!(%tenant_shard_id, "Shard status={status_code} progress: {progress:?}");
3205 0 : aggregate_progress.layers_downloaded += progress.layers_downloaded;
3206 0 : aggregate_progress.layers_total += progress.layers_total;
3207 0 : aggregate_progress.bytes_downloaded += progress.bytes_downloaded;
3208 0 : aggregate_progress.bytes_total += progress.bytes_total;
3209 0 : aggregate_progress.heatmap_mtime =
3210 0 : std::cmp::max(aggregate_progress.heatmap_mtime, progress.heatmap_mtime);
3211 0 : aggregate_status = match aggregate_status {
3212 0 : None => Some(status_code),
3213 0 : Some(StatusCode::OK) => Some(status_code),
3214 0 : Some(cur) => {
3215 0 : // Other status codes (e.g. 202) -- do not overwrite.
3216 0 : Some(cur)
3217 : }
3218 : };
3219 : }
3220 : }
3221 : }
3222 :
3223 : // If any of the shards return 202, indicate our result as 202.
3224 0 : match aggregate_status {
3225 : None => {
3226 0 : match error {
3227 0 : Some(e) => {
3228 0 : // No successes, and an error: surface it
3229 0 : Err(ApiError::Conflict(format!("Error from pageserver: {e}")))
3230 : }
3231 : None => {
3232 : // No shards found
3233 0 : Err(ApiError::NotFound(
3234 0 : anyhow::anyhow!("Tenant {} not found", tenant_id).into(),
3235 0 : ))
3236 : }
3237 : }
3238 : }
3239 0 : Some(aggregate_status) => Ok((aggregate_status, aggregate_progress)),
3240 : }
3241 0 : }
3242 :
3243 0 : pub(crate) async fn tenant_delete(&self, tenant_id: TenantId) -> Result<StatusCode, ApiError> {
3244 0 : let _tenant_lock =
3245 0 : trace_exclusive_lock(&self.tenant_op_locks, tenant_id, TenantOperations::Delete).await;
3246 :
3247 0 : self.maybe_load_tenant(tenant_id, &_tenant_lock).await?;
3248 :
3249 : // Detach all shards. This also deletes local pageserver shard data.
3250 0 : let (detach_waiters, node) = {
3251 0 : let mut detach_waiters = Vec::new();
3252 0 : let mut locked = self.inner.write().unwrap();
3253 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
3254 0 : for (_, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
3255 : // Update the tenant's intent to remove all attachments
3256 0 : shard.policy = PlacementPolicy::Detached;
3257 0 : shard
3258 0 : .schedule(scheduler, &mut ScheduleContext::default())
3259 0 : .expect("De-scheduling is infallible");
3260 0 : debug_assert!(shard.intent.get_attached().is_none());
3261 0 : debug_assert!(shard.intent.get_secondary().is_empty());
3262 :
3263 0 : if let Some(waiter) =
3264 0 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High)
3265 0 : {
3266 0 : detach_waiters.push(waiter);
3267 0 : }
3268 : }
3269 :
3270 : // Pick an arbitrary node to use for remote deletions (does not have to be where the tenant
3271 : // was attached, just has to be able to see the S3 content)
3272 0 : let node_id = scheduler.any_available_node()?;
3273 0 : let node = nodes
3274 0 : .get(&node_id)
3275 0 : .expect("Pageservers may not be deleted while lock is active");
3276 0 : (detach_waiters, node.clone())
3277 0 : };
3278 0 :
3279 0 : // This reconcile wait can fail in a few ways:
3280 0 : // A there is a very long queue for the reconciler semaphore
3281 0 : // B some pageserver is failing to handle a detach promptly
3282 0 : // C some pageserver goes offline right at the moment we send it a request.
3283 0 : //
3284 0 : // A and C are transient: the semaphore will eventually become available, and once a node is marked offline
3285 0 : // the next attempt to reconcile will silently skip detaches for an offline node and succeed. If B happens,
3286 0 : // it's a bug, and needs resolving at the pageserver level (we shouldn't just leave attachments behind while
3287 0 : // deleting the underlying data).
3288 0 : self.await_waiters(detach_waiters, RECONCILE_TIMEOUT)
3289 0 : .await?;
3290 :
3291 : // Delete the entire tenant (all shards) from remote storage via a random pageserver.
3292 : // Passing an unsharded tenant ID will cause the pageserver to remove all remote paths with
3293 : // the tenant ID prefix, including all shards (even possibly stale ones).
3294 0 : match node
3295 0 : .with_client_retries(
3296 0 : |client| async move {
3297 0 : client
3298 0 : .tenant_delete(TenantShardId::unsharded(tenant_id))
3299 0 : .await
3300 0 : },
3301 0 : &self.config.pageserver_jwt_token,
3302 0 : 1,
3303 0 : 3,
3304 0 : RECONCILE_TIMEOUT,
3305 0 : &self.cancel,
3306 0 : )
3307 0 : .await
3308 0 : .unwrap_or(Err(mgmt_api::Error::Cancelled))
3309 : {
3310 0 : Ok(_) => {}
3311 : Err(mgmt_api::Error::Cancelled) => {
3312 0 : return Err(ApiError::ShuttingDown);
3313 : }
3314 0 : Err(e) => {
3315 0 : // This is unexpected: remote deletion should be infallible, unless the object store
3316 0 : // at large is unavailable.
3317 0 : tracing::error!("Error deleting via node {node}: {e}");
3318 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(e)));
3319 : }
3320 : }
3321 :
3322 : // Fall through: deletion of the tenant on pageservers is complete, we may proceed to drop
3323 : // our in-memory state and database state.
3324 :
3325 : // Ordering: we delete persistent state first: if we then
3326 : // crash, we will drop the in-memory state.
3327 :
3328 : // Drop persistent state.
3329 0 : self.persistence.delete_tenant(tenant_id).await?;
3330 :
3331 : // Drop in-memory state
3332 : {
3333 0 : let mut locked = self.inner.write().unwrap();
3334 0 : let (_nodes, tenants, scheduler) = locked.parts_mut();
3335 :
3336 : // Dereference Scheduler from shards before dropping them
3337 0 : for (_tenant_shard_id, shard) in
3338 0 : tenants.range_mut(TenantShardId::tenant_range(tenant_id))
3339 0 : {
3340 0 : shard.intent.clear(scheduler);
3341 0 : }
3342 :
3343 0 : tenants.retain(|tenant_shard_id, _shard| tenant_shard_id.tenant_id != tenant_id);
3344 0 : tracing::info!(
3345 0 : "Deleted tenant {tenant_id}, now have {} tenants",
3346 0 : locked.tenants.len()
3347 : );
3348 : };
3349 :
3350 : // Success is represented as 404, to imitate the existing pageserver deletion API
3351 0 : Ok(StatusCode::NOT_FOUND)
3352 0 : }
3353 :
3354 : /// Naming: this configures the storage controller's policies for a tenant, whereas [`Self::tenant_config_set`] is "set the TenantConfig"
3355 : /// for a tenant. The TenantConfig is passed through to pageservers, whereas this function modifies
3356 : /// the tenant's policies (configuration) within the storage controller
3357 0 : pub(crate) async fn tenant_update_policy(
3358 0 : &self,
3359 0 : tenant_id: TenantId,
3360 0 : req: TenantPolicyRequest,
3361 0 : ) -> Result<(), ApiError> {
3362 : // We require an exclusive lock, because we are updating persistent and in-memory state
3363 0 : let _tenant_lock = trace_exclusive_lock(
3364 0 : &self.tenant_op_locks,
3365 0 : tenant_id,
3366 0 : TenantOperations::UpdatePolicy,
3367 0 : )
3368 0 : .await;
3369 :
3370 0 : self.maybe_load_tenant(tenant_id, &_tenant_lock).await?;
3371 :
3372 0 : failpoint_support::sleep_millis_async!("tenant-update-policy-exclusive-lock");
3373 :
3374 : let TenantPolicyRequest {
3375 0 : placement,
3376 0 : mut scheduling,
3377 0 : } = req;
3378 :
3379 0 : if let Some(PlacementPolicy::Detached | PlacementPolicy::Secondary) = placement {
3380 : // When someone configures a tenant to detach, we force the scheduling policy to enable
3381 : // this to take effect.
3382 0 : if scheduling.is_none() {
3383 0 : scheduling = Some(ShardSchedulingPolicy::Active);
3384 0 : }
3385 0 : }
3386 :
3387 0 : self.persistence
3388 0 : .update_tenant_shard(
3389 0 : TenantFilter::Tenant(tenant_id),
3390 0 : placement.clone(),
3391 0 : None,
3392 0 : None,
3393 0 : scheduling,
3394 0 : )
3395 0 : .await?;
3396 :
3397 0 : let mut schedule_context = ScheduleContext::default();
3398 0 : let mut locked = self.inner.write().unwrap();
3399 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
3400 0 : for (shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
3401 0 : if let Some(placement) = &placement {
3402 0 : shard.policy = placement.clone();
3403 0 :
3404 0 : tracing::info!(tenant_id=%shard_id.tenant_id, shard_id=%shard_id.shard_slug(),
3405 0 : "Updated placement policy to {placement:?}");
3406 0 : }
3407 :
3408 0 : if let Some(scheduling) = &scheduling {
3409 0 : shard.set_scheduling_policy(*scheduling);
3410 0 :
3411 0 : tracing::info!(tenant_id=%shard_id.tenant_id, shard_id=%shard_id.shard_slug(),
3412 0 : "Updated scheduling policy to {scheduling:?}");
3413 0 : }
3414 :
3415 : // In case scheduling is being switched back on, try it now.
3416 0 : shard.schedule(scheduler, &mut schedule_context).ok();
3417 0 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High);
3418 : }
3419 :
3420 0 : Ok(())
3421 0 : }
3422 :
3423 0 : pub(crate) async fn tenant_timeline_create(
3424 0 : &self,
3425 0 : tenant_id: TenantId,
3426 0 : mut create_req: TimelineCreateRequest,
3427 0 : ) -> Result<TimelineInfo, ApiError> {
3428 0 : tracing::info!(
3429 0 : "Creating timeline {}/{}",
3430 : tenant_id,
3431 : create_req.new_timeline_id,
3432 : );
3433 :
3434 0 : let _tenant_lock = trace_shared_lock(
3435 0 : &self.tenant_op_locks,
3436 0 : tenant_id,
3437 0 : TenantOperations::TimelineCreate,
3438 0 : )
3439 0 : .await;
3440 0 : failpoint_support::sleep_millis_async!("tenant-create-timeline-shared-lock");
3441 :
3442 0 : self.tenant_remote_mutation(tenant_id, move |mut targets| async move {
3443 0 : if targets.0.is_empty() {
3444 0 : return Err(ApiError::NotFound(
3445 0 : anyhow::anyhow!("Tenant not found").into(),
3446 0 : ));
3447 0 : };
3448 0 :
3449 0 : let (shard_zero_tid, shard_zero_locations) =
3450 0 : targets.0.pop_first().expect("Must have at least one shard");
3451 0 : assert!(shard_zero_tid.is_shard_zero());
3452 :
3453 0 : async fn create_one(
3454 0 : tenant_shard_id: TenantShardId,
3455 0 : locations: ShardMutationLocations,
3456 0 : jwt: Option<String>,
3457 0 : create_req: TimelineCreateRequest,
3458 0 : ) -> Result<TimelineInfo, ApiError> {
3459 0 : let latest = locations.latest.node;
3460 0 :
3461 0 : tracing::info!(
3462 0 : "Creating timeline on shard {}/{}, attached to node {latest} in generation {:?}",
3463 : tenant_shard_id,
3464 : create_req.new_timeline_id,
3465 : locations.latest.generation
3466 : );
3467 :
3468 0 : let client =
3469 0 : PageserverClient::new(latest.get_id(), latest.base_url(), jwt.as_deref());
3470 :
3471 0 : let timeline_info = client
3472 0 : .timeline_create(tenant_shard_id, &create_req)
3473 0 : .await
3474 0 : .map_err(|e| passthrough_api_error(&latest, e))?;
3475 :
3476 : // We propagate timeline creations to all attached locations such that a compute
3477 : // for the new timeline is able to start regardless of the current state of the
3478 : // tenant shard reconciliation.
3479 0 : for location in locations.other {
3480 0 : tracing::info!(
3481 0 : "Creating timeline on shard {}/{}, stale attached to node {} in generation {:?}",
3482 : tenant_shard_id,
3483 : create_req.new_timeline_id,
3484 : location.node,
3485 : location.generation
3486 : );
3487 :
3488 0 : let client = PageserverClient::new(
3489 0 : location.node.get_id(),
3490 0 : location.node.base_url(),
3491 0 : jwt.as_deref(),
3492 0 : );
3493 :
3494 0 : let res = client
3495 0 : .timeline_create(tenant_shard_id, &create_req)
3496 0 : .await;
3497 :
3498 0 : if let Err(e) = res {
3499 0 : match e {
3500 0 : mgmt_api::Error::ApiError(StatusCode::NOT_FOUND, _) => {
3501 0 : // Tenant might have been detached from the stale location,
3502 0 : // so ignore 404s.
3503 0 : },
3504 : _ => {
3505 0 : return Err(passthrough_api_error(&location.node, e));
3506 : }
3507 : }
3508 0 : }
3509 : }
3510 :
3511 0 : Ok(timeline_info)
3512 0 : }
3513 :
3514 : // Because the caller might not provide an explicit LSN, we must do the creation first on a single shard, and then
3515 : // use whatever LSN that shard picked when creating on subsequent shards. We arbitrarily use shard zero as the shard
3516 : // that will get the first creation request, and propagate the LSN to all the >0 shards.
3517 0 : let timeline_info = create_one(
3518 0 : shard_zero_tid,
3519 0 : shard_zero_locations,
3520 0 : self.config.pageserver_jwt_token.clone(),
3521 0 : create_req.clone(),
3522 0 : )
3523 0 : .await?;
3524 :
3525 : // Propagate the LSN that shard zero picked, if caller didn't provide one
3526 0 : match &mut create_req.mode {
3527 0 : models::TimelineCreateRequestMode::Branch { ancestor_start_lsn, .. } if ancestor_start_lsn.is_none() => {
3528 0 : *ancestor_start_lsn = timeline_info.ancestor_lsn;
3529 0 : },
3530 0 : _ => {}
3531 : }
3532 :
3533 : // Create timeline on remaining shards with number >0
3534 0 : if !targets.0.is_empty() {
3535 : // If we had multiple shards, issue requests for the remainder now.
3536 0 : let jwt = &self.config.pageserver_jwt_token;
3537 0 : self.tenant_for_shards(
3538 0 : targets
3539 0 : .0
3540 0 : .iter()
3541 0 : .map(|t| (*t.0, t.1.latest.node.clone()))
3542 0 : .collect(),
3543 0 : |tenant_shard_id: TenantShardId, _node: Node| {
3544 0 : let create_req = create_req.clone();
3545 0 : let mutation_locations = targets.0.remove(&tenant_shard_id).unwrap();
3546 0 : Box::pin(create_one(
3547 0 : tenant_shard_id,
3548 0 : mutation_locations,
3549 0 : jwt.clone(),
3550 0 : create_req,
3551 0 : ))
3552 0 : },
3553 0 : )
3554 0 : .await?;
3555 0 : }
3556 :
3557 0 : Ok(timeline_info)
3558 0 : })
3559 0 : .await?
3560 0 : }
3561 :
3562 0 : pub(crate) async fn tenant_timeline_archival_config(
3563 0 : &self,
3564 0 : tenant_id: TenantId,
3565 0 : timeline_id: TimelineId,
3566 0 : req: TimelineArchivalConfigRequest,
3567 0 : ) -> Result<(), ApiError> {
3568 0 : tracing::info!(
3569 0 : "Setting archival config of timeline {tenant_id}/{timeline_id} to '{:?}'",
3570 : req.state
3571 : );
3572 :
3573 0 : let _tenant_lock = trace_shared_lock(
3574 0 : &self.tenant_op_locks,
3575 0 : tenant_id,
3576 0 : TenantOperations::TimelineArchivalConfig,
3577 0 : )
3578 0 : .await;
3579 :
3580 0 : self.tenant_remote_mutation(tenant_id, move |targets| async move {
3581 0 : if targets.0.is_empty() {
3582 0 : return Err(ApiError::NotFound(
3583 0 : anyhow::anyhow!("Tenant not found").into(),
3584 0 : ));
3585 0 : }
3586 0 : async fn config_one(
3587 0 : tenant_shard_id: TenantShardId,
3588 0 : timeline_id: TimelineId,
3589 0 : node: Node,
3590 0 : jwt: Option<String>,
3591 0 : req: TimelineArchivalConfigRequest,
3592 0 : ) -> Result<(), ApiError> {
3593 0 : tracing::info!(
3594 0 : "Setting archival config of timeline on shard {tenant_shard_id}/{timeline_id}, attached to node {node}",
3595 : );
3596 :
3597 0 : let client = PageserverClient::new(node.get_id(), node.base_url(), jwt.as_deref());
3598 0 :
3599 0 : client
3600 0 : .timeline_archival_config(tenant_shard_id, timeline_id, &req)
3601 0 : .await
3602 0 : .map_err(|e| match e {
3603 0 : mgmt_api::Error::ApiError(StatusCode::PRECONDITION_FAILED, msg) => {
3604 0 : ApiError::PreconditionFailed(msg.into_boxed_str())
3605 : }
3606 0 : _ => passthrough_api_error(&node, e),
3607 0 : })
3608 0 : }
3609 :
3610 : // no shard needs to go first/last; the operation should be idempotent
3611 : // TODO: it would be great to ensure that all shards return the same error
3612 0 : let locations = targets.0.iter().map(|t| (*t.0, t.1.latest.node.clone())).collect();
3613 0 : let results = self
3614 0 : .tenant_for_shards(locations, |tenant_shard_id, node| {
3615 0 : futures::FutureExt::boxed(config_one(
3616 0 : tenant_shard_id,
3617 0 : timeline_id,
3618 0 : node,
3619 0 : self.config.pageserver_jwt_token.clone(),
3620 0 : req.clone(),
3621 0 : ))
3622 0 : })
3623 0 : .await?;
3624 0 : assert!(!results.is_empty(), "must have at least one result");
3625 :
3626 0 : Ok(())
3627 0 : }).await?
3628 0 : }
3629 :
3630 0 : pub(crate) async fn tenant_timeline_detach_ancestor(
3631 0 : &self,
3632 0 : tenant_id: TenantId,
3633 0 : timeline_id: TimelineId,
3634 0 : ) -> Result<models::detach_ancestor::AncestorDetached, ApiError> {
3635 0 : tracing::info!("Detaching timeline {tenant_id}/{timeline_id}",);
3636 :
3637 0 : let _tenant_lock = trace_shared_lock(
3638 0 : &self.tenant_op_locks,
3639 0 : tenant_id,
3640 0 : TenantOperations::TimelineDetachAncestor,
3641 0 : )
3642 0 : .await;
3643 :
3644 0 : self.tenant_remote_mutation(tenant_id, move |targets| async move {
3645 0 : if targets.0.is_empty() {
3646 0 : return Err(ApiError::NotFound(
3647 0 : anyhow::anyhow!("Tenant not found").into(),
3648 0 : ));
3649 0 : }
3650 :
3651 0 : async fn detach_one(
3652 0 : tenant_shard_id: TenantShardId,
3653 0 : timeline_id: TimelineId,
3654 0 : node: Node,
3655 0 : jwt: Option<String>,
3656 0 : ) -> Result<(ShardNumber, models::detach_ancestor::AncestorDetached), ApiError> {
3657 0 : tracing::info!(
3658 0 : "Detaching timeline on shard {tenant_shard_id}/{timeline_id}, attached to node {node}",
3659 : );
3660 :
3661 0 : let client = PageserverClient::new(node.get_id(), node.base_url(), jwt.as_deref());
3662 0 :
3663 0 : client
3664 0 : .timeline_detach_ancestor(tenant_shard_id, timeline_id)
3665 0 : .await
3666 0 : .map_err(|e| {
3667 : use mgmt_api::Error;
3668 :
3669 0 : match e {
3670 : // no ancestor (ever)
3671 0 : Error::ApiError(StatusCode::CONFLICT, msg) => ApiError::Conflict(format!(
3672 0 : "{node}: {}",
3673 0 : msg.strip_prefix("Conflict: ").unwrap_or(&msg)
3674 0 : )),
3675 : // too many ancestors
3676 0 : Error::ApiError(StatusCode::BAD_REQUEST, msg) => {
3677 0 : ApiError::BadRequest(anyhow::anyhow!("{node}: {msg}"))
3678 : }
3679 0 : Error::ApiError(StatusCode::INTERNAL_SERVER_ERROR, msg) => {
3680 0 : // avoid turning these into conflicts to remain compatible with
3681 0 : // pageservers, 500 errors are sadly retryable with timeline ancestor
3682 0 : // detach
3683 0 : ApiError::InternalServerError(anyhow::anyhow!("{node}: {msg}"))
3684 : }
3685 : // rest can be mapped as usual
3686 0 : other => passthrough_api_error(&node, other),
3687 : }
3688 0 : })
3689 0 : .map(|res| (tenant_shard_id.shard_number, res))
3690 0 : }
3691 :
3692 : // no shard needs to go first/last; the operation should be idempotent
3693 0 : let locations = targets.0.iter().map(|t| (*t.0, t.1.latest.node.clone())).collect();
3694 0 : let mut results = self
3695 0 : .tenant_for_shards(locations, |tenant_shard_id, node| {
3696 0 : futures::FutureExt::boxed(detach_one(
3697 0 : tenant_shard_id,
3698 0 : timeline_id,
3699 0 : node,
3700 0 : self.config.pageserver_jwt_token.clone(),
3701 0 : ))
3702 0 : })
3703 0 : .await?;
3704 :
3705 0 : let any = results.pop().expect("we must have at least one response");
3706 0 :
3707 0 : let mismatching = results
3708 0 : .iter()
3709 0 : .filter(|(_, res)| res != &any.1)
3710 0 : .collect::<Vec<_>>();
3711 0 : if !mismatching.is_empty() {
3712 : // this can be hit by races which should not happen because operation lock on cplane
3713 0 : let matching = results.len() - mismatching.len();
3714 0 : tracing::error!(
3715 : matching,
3716 : compared_against=?any,
3717 : ?mismatching,
3718 0 : "shards returned different results"
3719 : );
3720 :
3721 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!("pageservers returned mixed results for ancestor detach; manual intervention is required.")));
3722 0 : }
3723 0 :
3724 0 : Ok(any.1)
3725 0 : }).await?
3726 0 : }
3727 :
3728 0 : pub(crate) async fn tenant_timeline_block_unblock_gc(
3729 0 : &self,
3730 0 : tenant_id: TenantId,
3731 0 : timeline_id: TimelineId,
3732 0 : dir: BlockUnblock,
3733 0 : ) -> Result<(), ApiError> {
3734 0 : let _tenant_lock = trace_shared_lock(
3735 0 : &self.tenant_op_locks,
3736 0 : tenant_id,
3737 0 : TenantOperations::TimelineGcBlockUnblock,
3738 0 : )
3739 0 : .await;
3740 :
3741 0 : self.tenant_remote_mutation(tenant_id, move |targets| async move {
3742 0 : if targets.0.is_empty() {
3743 0 : return Err(ApiError::NotFound(
3744 0 : anyhow::anyhow!("Tenant not found").into(),
3745 0 : ));
3746 0 : }
3747 :
3748 0 : async fn do_one(
3749 0 : tenant_shard_id: TenantShardId,
3750 0 : timeline_id: TimelineId,
3751 0 : node: Node,
3752 0 : jwt: Option<String>,
3753 0 : dir: BlockUnblock,
3754 0 : ) -> Result<(), ApiError> {
3755 0 : let client = PageserverClient::new(node.get_id(), node.base_url(), jwt.as_deref());
3756 0 :
3757 0 : client
3758 0 : .timeline_block_unblock_gc(tenant_shard_id, timeline_id, dir)
3759 0 : .await
3760 0 : .map_err(|e| passthrough_api_error(&node, e))
3761 0 : }
3762 :
3763 : // no shard needs to go first/last; the operation should be idempotent
3764 0 : let locations = targets
3765 0 : .0
3766 0 : .iter()
3767 0 : .map(|t| (*t.0, t.1.latest.node.clone()))
3768 0 : .collect();
3769 0 : self.tenant_for_shards(locations, |tenant_shard_id, node| {
3770 0 : futures::FutureExt::boxed(do_one(
3771 0 : tenant_shard_id,
3772 0 : timeline_id,
3773 0 : node,
3774 0 : self.config.pageserver_jwt_token.clone(),
3775 0 : dir,
3776 0 : ))
3777 0 : })
3778 0 : .await
3779 0 : })
3780 0 : .await??;
3781 0 : Ok(())
3782 0 : }
3783 :
3784 0 : pub(crate) async fn tenant_timeline_download_heatmap_layers(
3785 0 : &self,
3786 0 : tenant_shard_id: TenantShardId,
3787 0 : timeline_id: TimelineId,
3788 0 : concurrency: Option<usize>,
3789 0 : recurse: bool,
3790 0 : ) -> Result<(), ApiError> {
3791 0 : let _tenant_lock = trace_shared_lock(
3792 0 : &self.tenant_op_locks,
3793 0 : tenant_shard_id.tenant_id,
3794 0 : TenantOperations::DownloadHeatmapLayers,
3795 0 : )
3796 0 : .await;
3797 :
3798 0 : let targets = {
3799 0 : let locked = self.inner.read().unwrap();
3800 0 : let mut targets = Vec::new();
3801 :
3802 : // If the request got an unsharded tenant id, then apply
3803 : // the operation to all shards. Otherwise, apply it to a specific shard.
3804 0 : let shards_range = if tenant_shard_id.is_unsharded() {
3805 0 : TenantShardId::tenant_range(tenant_shard_id.tenant_id)
3806 : } else {
3807 0 : tenant_shard_id.range()
3808 : };
3809 :
3810 0 : for (tenant_shard_id, shard) in locked.tenants.range(shards_range) {
3811 0 : if let Some(node_id) = shard.intent.get_attached() {
3812 0 : let node = locked
3813 0 : .nodes
3814 0 : .get(node_id)
3815 0 : .expect("Pageservers may not be deleted while referenced");
3816 0 :
3817 0 : targets.push((*tenant_shard_id, node.clone()));
3818 0 : }
3819 : }
3820 0 : targets
3821 0 : };
3822 0 :
3823 0 : self.tenant_for_shards_api(
3824 0 : targets,
3825 0 : |tenant_shard_id, client| async move {
3826 0 : client
3827 0 : .timeline_download_heatmap_layers(
3828 0 : tenant_shard_id,
3829 0 : timeline_id,
3830 0 : concurrency,
3831 0 : recurse,
3832 0 : )
3833 0 : .await
3834 0 : },
3835 0 : 1,
3836 0 : 1,
3837 0 : SHORT_RECONCILE_TIMEOUT,
3838 0 : &self.cancel,
3839 0 : )
3840 0 : .await;
3841 :
3842 0 : Ok(())
3843 0 : }
3844 :
3845 : /// Helper for concurrently calling a pageserver API on a number of shards, such as timeline creation.
3846 : ///
3847 : /// On success, the returned vector contains exactly the same number of elements as the input `locations`.
3848 0 : async fn tenant_for_shards<F, R>(
3849 0 : &self,
3850 0 : locations: Vec<(TenantShardId, Node)>,
3851 0 : mut req_fn: F,
3852 0 : ) -> Result<Vec<R>, ApiError>
3853 0 : where
3854 0 : F: FnMut(
3855 0 : TenantShardId,
3856 0 : Node,
3857 0 : )
3858 0 : -> std::pin::Pin<Box<dyn futures::Future<Output = Result<R, ApiError>> + Send>>,
3859 0 : {
3860 0 : let mut futs = FuturesUnordered::new();
3861 0 : let mut results = Vec::with_capacity(locations.len());
3862 :
3863 0 : for (tenant_shard_id, node) in locations {
3864 0 : futs.push(req_fn(tenant_shard_id, node));
3865 0 : }
3866 :
3867 0 : while let Some(r) = futs.next().await {
3868 0 : results.push(r?);
3869 : }
3870 :
3871 0 : Ok(results)
3872 0 : }
3873 :
3874 : /// Concurrently invoke a pageserver API call on many shards at once
3875 0 : pub(crate) async fn tenant_for_shards_api<T, O, F>(
3876 0 : &self,
3877 0 : locations: Vec<(TenantShardId, Node)>,
3878 0 : op: O,
3879 0 : warn_threshold: u32,
3880 0 : max_retries: u32,
3881 0 : timeout: Duration,
3882 0 : cancel: &CancellationToken,
3883 0 : ) -> Vec<mgmt_api::Result<T>>
3884 0 : where
3885 0 : O: Fn(TenantShardId, PageserverClient) -> F + Copy,
3886 0 : F: std::future::Future<Output = mgmt_api::Result<T>>,
3887 0 : {
3888 0 : let mut futs = FuturesUnordered::new();
3889 0 : let mut results = Vec::with_capacity(locations.len());
3890 :
3891 0 : for (tenant_shard_id, node) in locations {
3892 0 : futs.push(async move {
3893 0 : node.with_client_retries(
3894 0 : |client| op(tenant_shard_id, client),
3895 0 : &self.config.pageserver_jwt_token,
3896 0 : warn_threshold,
3897 0 : max_retries,
3898 0 : timeout,
3899 0 : cancel,
3900 0 : )
3901 0 : .await
3902 0 : });
3903 0 : }
3904 :
3905 0 : while let Some(r) = futs.next().await {
3906 0 : let r = r.unwrap_or(Err(mgmt_api::Error::Cancelled));
3907 0 : results.push(r);
3908 0 : }
3909 :
3910 0 : results
3911 0 : }
3912 :
3913 : /// Helper for safely working with the shards in a tenant remotely on pageservers, for example
3914 : /// when creating and deleting timelines:
3915 : /// - Makes sure shards are attached somewhere if they weren't already
3916 : /// - Looks up the shards and the nodes where they were most recently attached
3917 : /// - Guarantees that after the inner function returns, the shards' generations haven't moved on: this
3918 : /// ensures that the remote operation acted on the most recent generation, and is therefore durable.
3919 0 : async fn tenant_remote_mutation<R, O, F>(
3920 0 : &self,
3921 0 : tenant_id: TenantId,
3922 0 : op: O,
3923 0 : ) -> Result<R, ApiError>
3924 0 : where
3925 0 : O: FnOnce(TenantMutationLocations) -> F,
3926 0 : F: std::future::Future<Output = R>,
3927 0 : {
3928 0 : let mutation_locations = {
3929 0 : let mut locations = TenantMutationLocations::default();
3930 :
3931 : // Load the currently attached pageservers for the latest generation of each shard. This can
3932 : // run concurrently with reconciliations, and it is not guaranteed that the node we find here
3933 : // will still be the latest when we're done: we will check generations again at the end of
3934 : // this function to handle that.
3935 0 : let generations = self.persistence.tenant_generations(tenant_id).await?;
3936 :
3937 0 : if generations
3938 0 : .iter()
3939 0 : .any(|i| i.generation.is_none() || i.generation_pageserver.is_none())
3940 : {
3941 0 : let shard_generations = generations
3942 0 : .into_iter()
3943 0 : .map(|i| (i.tenant_shard_id, (i.generation, i.generation_pageserver)))
3944 0 : .collect::<HashMap<_, _>>();
3945 0 :
3946 0 : // One or more shards has not been attached to a pageserver. Check if this is because it's configured
3947 0 : // to be detached (409: caller should give up), or because it's meant to be attached but isn't yet (503: caller should retry)
3948 0 : let locked = self.inner.read().unwrap();
3949 0 : for (shard_id, shard) in
3950 0 : locked.tenants.range(TenantShardId::tenant_range(tenant_id))
3951 : {
3952 0 : match shard.policy {
3953 : PlacementPolicy::Attached(_) => {
3954 : // This shard is meant to be attached: the caller is not wrong to try and
3955 : // use this function, but we can't service the request right now.
3956 0 : let Some(generation) = shard_generations.get(shard_id) else {
3957 : // This can only happen if there is a split brain controller modifying the database. This should
3958 : // never happen when testing, and if it happens in production we can only log the issue.
3959 0 : debug_assert!(false);
3960 0 : tracing::error!(
3961 0 : "Shard {shard_id} not found in generation state! Is another rogue controller running?"
3962 : );
3963 0 : continue;
3964 : };
3965 0 : let (generation, generation_pageserver) = generation;
3966 0 : if let Some(generation) = generation {
3967 0 : if generation_pageserver.is_none() {
3968 : // This is legitimate only in a very narrow window where the shard was only just configured into
3969 : // Attached mode after being created in Secondary or Detached mode, and it has had its generation
3970 : // set but not yet had a Reconciler run (reconciler is the only thing that sets generation_pageserver).
3971 0 : tracing::warn!(
3972 0 : "Shard {shard_id} generation is set ({generation:?}) but generation_pageserver is None, reconciler not run yet?"
3973 : );
3974 0 : }
3975 : } else {
3976 : // This should never happen: a shard with no generation is only permitted when it was created in some state
3977 : // other than PlacementPolicy::Attached (and generation is always written to DB before setting Attached in memory)
3978 0 : debug_assert!(false);
3979 0 : tracing::error!(
3980 0 : "Shard {shard_id} generation is None, but it is in PlacementPolicy::Attached mode!"
3981 : );
3982 0 : continue;
3983 : }
3984 : }
3985 : PlacementPolicy::Secondary | PlacementPolicy::Detached => {
3986 0 : return Err(ApiError::Conflict(format!(
3987 0 : "Shard {shard_id} tenant has policy {:?}",
3988 0 : shard.policy
3989 0 : )));
3990 : }
3991 : }
3992 : }
3993 :
3994 0 : return Err(ApiError::ResourceUnavailable(
3995 0 : "One or more shards in tenant is not yet attached".into(),
3996 0 : ));
3997 0 : }
3998 0 :
3999 0 : let locked = self.inner.read().unwrap();
4000 : for ShardGenerationState {
4001 0 : tenant_shard_id,
4002 0 : generation,
4003 0 : generation_pageserver,
4004 0 : } in generations
4005 : {
4006 0 : let node_id = generation_pageserver.expect("We checked for None above");
4007 0 : let node = locked
4008 0 : .nodes
4009 0 : .get(&node_id)
4010 0 : .ok_or(ApiError::Conflict(format!(
4011 0 : "Raced with removal of node {node_id}"
4012 0 : )))?;
4013 0 : let generation = generation.expect("Checked above");
4014 0 :
4015 0 : let tenant = locked.tenants.get(&tenant_shard_id);
4016 :
4017 : // TODO(vlad): Abstract the logic that finds stale attached locations
4018 : // from observed state into a [`Service`] method.
4019 0 : let other_locations = match tenant {
4020 0 : Some(tenant) => {
4021 0 : let mut other = tenant.attached_locations();
4022 0 : let latest_location_index =
4023 0 : other.iter().position(|&l| l == (node.get_id(), generation));
4024 0 : if let Some(idx) = latest_location_index {
4025 0 : other.remove(idx);
4026 0 : }
4027 :
4028 0 : other
4029 : }
4030 0 : None => Vec::default(),
4031 : };
4032 :
4033 0 : let location = ShardMutationLocations {
4034 0 : latest: MutationLocation {
4035 0 : node: node.clone(),
4036 0 : generation,
4037 0 : },
4038 0 : other: other_locations
4039 0 : .into_iter()
4040 0 : .filter_map(|(node_id, generation)| {
4041 0 : let node = locked.nodes.get(&node_id)?;
4042 :
4043 0 : Some(MutationLocation {
4044 0 : node: node.clone(),
4045 0 : generation,
4046 0 : })
4047 0 : })
4048 0 : .collect(),
4049 0 : };
4050 0 : locations.0.insert(tenant_shard_id, location);
4051 0 : }
4052 :
4053 0 : locations
4054 : };
4055 :
4056 0 : let result = op(mutation_locations.clone()).await;
4057 :
4058 : // Post-check: are all the generations of all the shards the same as they were initially? This proves that
4059 : // our remote operation executed on the latest generation and is therefore persistent.
4060 : {
4061 0 : let latest_generations = self.persistence.tenant_generations(tenant_id).await?;
4062 0 : if latest_generations
4063 0 : .into_iter()
4064 0 : .map(
4065 0 : |ShardGenerationState {
4066 : tenant_shard_id,
4067 : generation,
4068 : generation_pageserver: _,
4069 0 : }| (tenant_shard_id, generation),
4070 0 : )
4071 0 : .collect::<Vec<_>>()
4072 0 : != mutation_locations
4073 0 : .0
4074 0 : .into_iter()
4075 0 : .map(|i| (i.0, Some(i.1.latest.generation)))
4076 0 : .collect::<Vec<_>>()
4077 : {
4078 : // We raced with something that incremented the generation, and therefore cannot be
4079 : // confident that our actions are persistent (they might have hit an old generation).
4080 : //
4081 : // This is safe but requires a retry: ask the client to do that by giving them a 503 response.
4082 0 : return Err(ApiError::ResourceUnavailable(
4083 0 : "Tenant attachment changed, please retry".into(),
4084 0 : ));
4085 0 : }
4086 0 : }
4087 0 :
4088 0 : Ok(result)
4089 0 : }
4090 :
4091 0 : pub(crate) async fn tenant_timeline_delete(
4092 0 : &self,
4093 0 : tenant_id: TenantId,
4094 0 : timeline_id: TimelineId,
4095 0 : ) -> Result<StatusCode, ApiError> {
4096 0 : tracing::info!("Deleting timeline {}/{}", tenant_id, timeline_id,);
4097 0 : let _tenant_lock = trace_shared_lock(
4098 0 : &self.tenant_op_locks,
4099 0 : tenant_id,
4100 0 : TenantOperations::TimelineDelete,
4101 0 : )
4102 0 : .await;
4103 :
4104 0 : self.tenant_remote_mutation(tenant_id, move |mut targets| async move {
4105 0 : if targets.0.is_empty() {
4106 0 : return Err(ApiError::NotFound(
4107 0 : anyhow::anyhow!("Tenant not found").into(),
4108 0 : ));
4109 0 : }
4110 0 :
4111 0 : let (shard_zero_tid, shard_zero_locations) = targets.0.pop_first().expect("Must have at least one shard");
4112 0 : assert!(shard_zero_tid.is_shard_zero());
4113 :
4114 0 : async fn delete_one(
4115 0 : tenant_shard_id: TenantShardId,
4116 0 : timeline_id: TimelineId,
4117 0 : node: Node,
4118 0 : jwt: Option<String>,
4119 0 : ) -> Result<StatusCode, ApiError> {
4120 0 : tracing::info!(
4121 0 : "Deleting timeline on shard {tenant_shard_id}/{timeline_id}, attached to node {node}",
4122 : );
4123 :
4124 0 : let client = PageserverClient::new(node.get_id(), node.base_url(), jwt.as_deref());
4125 0 : let res = client
4126 0 : .timeline_delete(tenant_shard_id, timeline_id)
4127 0 : .await;
4128 :
4129 0 : match res {
4130 0 : Ok(ok) => Ok(ok),
4131 0 : Err(mgmt_api::Error::ApiError(StatusCode::CONFLICT, _)) => Ok(StatusCode::CONFLICT),
4132 0 : Err(mgmt_api::Error::ApiError(StatusCode::SERVICE_UNAVAILABLE, msg)) => Err(ApiError::ResourceUnavailable(msg.into())),
4133 0 : Err(e) => {
4134 0 : Err(
4135 0 : ApiError::InternalServerError(anyhow::anyhow!(
4136 0 : "Error deleting timeline {timeline_id} on {tenant_shard_id} on node {node}: {e}",
4137 0 : ))
4138 0 : )
4139 : }
4140 : }
4141 0 : }
4142 :
4143 0 : let locations = targets.0.iter().map(|t| (*t.0, t.1.latest.node.clone())).collect();
4144 0 : let statuses = self
4145 0 : .tenant_for_shards(locations, |tenant_shard_id: TenantShardId, node: Node| {
4146 0 : Box::pin(delete_one(
4147 0 : tenant_shard_id,
4148 0 : timeline_id,
4149 0 : node,
4150 0 : self.config.pageserver_jwt_token.clone(),
4151 0 : ))
4152 0 : })
4153 0 : .await?;
4154 :
4155 : // If any shards >0 haven't finished deletion yet, don't start deletion on shard zero.
4156 : // We return 409 (Conflict) if deletion was already in progress on any of the shards
4157 : // and 202 (Accepted) if deletion was not already in progress on any of the shards.
4158 0 : if statuses.iter().any(|s| s == &StatusCode::CONFLICT) {
4159 0 : return Ok(StatusCode::CONFLICT);
4160 0 : }
4161 0 :
4162 0 : if statuses.iter().any(|s| s != &StatusCode::NOT_FOUND) {
4163 0 : return Ok(StatusCode::ACCEPTED);
4164 0 : }
4165 :
4166 : // Delete shard zero last: this is not strictly necessary, but since a caller's GET on a timeline will be routed
4167 : // to shard zero, it gives a more obvious behavior that a GET returns 404 once the deletion is done.
4168 0 : let shard_zero_status = delete_one(
4169 0 : shard_zero_tid,
4170 0 : timeline_id,
4171 0 : shard_zero_locations.latest.node,
4172 0 : self.config.pageserver_jwt_token.clone(),
4173 0 : )
4174 0 : .await?;
4175 0 : Ok(shard_zero_status)
4176 0 : }).await?
4177 0 : }
4178 :
4179 : /// When you know the TenantId but not a specific shard, and would like to get the node holding shard 0.
4180 0 : pub(crate) async fn tenant_shard0_node(
4181 0 : &self,
4182 0 : tenant_id: TenantId,
4183 0 : ) -> Result<(Node, TenantShardId), ApiError> {
4184 0 : let tenant_shard_id = {
4185 0 : let locked = self.inner.read().unwrap();
4186 0 : let Some((tenant_shard_id, _shard)) = locked
4187 0 : .tenants
4188 0 : .range(TenantShardId::tenant_range(tenant_id))
4189 0 : .next()
4190 : else {
4191 0 : return Err(ApiError::NotFound(
4192 0 : anyhow::anyhow!("Tenant {tenant_id} not found").into(),
4193 0 : ));
4194 : };
4195 :
4196 0 : *tenant_shard_id
4197 0 : };
4198 0 :
4199 0 : self.tenant_shard_node(tenant_shard_id)
4200 0 : .await
4201 0 : .map(|node| (node, tenant_shard_id))
4202 0 : }
4203 :
4204 : /// When you need to send an HTTP request to the pageserver that holds a shard of a tenant, this
4205 : /// function looks up and returns node. If the shard isn't found, returns Err(ApiError::NotFound)
4206 0 : pub(crate) async fn tenant_shard_node(
4207 0 : &self,
4208 0 : tenant_shard_id: TenantShardId,
4209 0 : ) -> Result<Node, ApiError> {
4210 0 : // Look up in-memory state and maybe use the node from there.
4211 0 : {
4212 0 : let locked = self.inner.read().unwrap();
4213 0 : let Some(shard) = locked.tenants.get(&tenant_shard_id) else {
4214 0 : return Err(ApiError::NotFound(
4215 0 : anyhow::anyhow!("Tenant shard {tenant_shard_id} not found").into(),
4216 0 : ));
4217 : };
4218 :
4219 0 : let Some(intent_node_id) = shard.intent.get_attached() else {
4220 0 : tracing::warn!(
4221 0 : tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(),
4222 0 : "Shard not scheduled (policy {:?}), cannot generate pass-through URL",
4223 : shard.policy
4224 : );
4225 0 : return Err(ApiError::Conflict(
4226 0 : "Cannot call timeline API on non-attached tenant".to_string(),
4227 0 : ));
4228 : };
4229 :
4230 0 : if shard.reconciler.is_none() {
4231 : // Optimization: while no reconcile is in flight, we may trust our in-memory state
4232 : // to tell us which pageserver to use. Otherwise we will fall through and hit the database
4233 0 : let Some(node) = locked.nodes.get(intent_node_id) else {
4234 : // This should never happen
4235 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
4236 0 : "Shard refers to nonexistent node"
4237 0 : )));
4238 : };
4239 0 : return Ok(node.clone());
4240 0 : }
4241 : };
4242 :
4243 : // Look up the latest attached pageserver location from the database
4244 : // generation state: this will reflect the progress of any ongoing migration.
4245 : // Note that it is not guaranteed to _stay_ here, our caller must still handle
4246 : // the case where they call through to the pageserver and get a 404.
4247 0 : let db_result = self
4248 0 : .persistence
4249 0 : .tenant_generations(tenant_shard_id.tenant_id)
4250 0 : .await?;
4251 : let Some(ShardGenerationState {
4252 : tenant_shard_id: _,
4253 : generation: _,
4254 0 : generation_pageserver: Some(node_id),
4255 0 : }) = db_result
4256 0 : .into_iter()
4257 0 : .find(|s| s.tenant_shard_id == tenant_shard_id)
4258 : else {
4259 : // This can happen if we raced with a tenant deletion or a shard split. On a retry
4260 : // the caller will either succeed (shard split case), get a proper 404 (deletion case),
4261 : // or a conflict response (case where tenant was detached in background)
4262 0 : return Err(ApiError::ResourceUnavailable(
4263 0 : format!("Shard {tenant_shard_id} not found in database, or is not attached").into(),
4264 0 : ));
4265 : };
4266 0 : let locked = self.inner.read().unwrap();
4267 0 : let Some(node) = locked.nodes.get(&node_id) else {
4268 : // This should never happen
4269 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
4270 0 : "Shard refers to nonexistent node"
4271 0 : )));
4272 : };
4273 :
4274 0 : Ok(node.clone())
4275 0 : }
4276 :
4277 0 : pub(crate) fn tenant_locate(
4278 0 : &self,
4279 0 : tenant_id: TenantId,
4280 0 : ) -> Result<TenantLocateResponse, ApiError> {
4281 0 : let locked = self.inner.read().unwrap();
4282 0 : tracing::info!("Locating shards for tenant {tenant_id}");
4283 :
4284 0 : let mut result = Vec::new();
4285 0 : let mut shard_params: Option<ShardParameters> = None;
4286 :
4287 0 : for (tenant_shard_id, shard) in locked.tenants.range(TenantShardId::tenant_range(tenant_id))
4288 : {
4289 0 : let node_id =
4290 0 : shard
4291 0 : .intent
4292 0 : .get_attached()
4293 0 : .ok_or(ApiError::BadRequest(anyhow::anyhow!(
4294 0 : "Cannot locate a tenant that is not attached"
4295 0 : )))?;
4296 :
4297 0 : let node = locked
4298 0 : .nodes
4299 0 : .get(&node_id)
4300 0 : .expect("Pageservers may not be deleted while referenced");
4301 0 :
4302 0 : result.push(node.shard_location(*tenant_shard_id));
4303 0 :
4304 0 : match &shard_params {
4305 0 : None => {
4306 0 : shard_params = Some(ShardParameters {
4307 0 : stripe_size: shard.shard.stripe_size,
4308 0 : count: shard.shard.count,
4309 0 : });
4310 0 : }
4311 0 : Some(params) => {
4312 0 : if params.stripe_size != shard.shard.stripe_size {
4313 : // This should never happen. We enforce at runtime because it's simpler than
4314 : // adding an extra per-tenant data structure to store the things that should be the same
4315 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
4316 0 : "Inconsistent shard stripe size parameters!"
4317 0 : )));
4318 0 : }
4319 : }
4320 : }
4321 : }
4322 :
4323 0 : if result.is_empty() {
4324 0 : return Err(ApiError::NotFound(
4325 0 : anyhow::anyhow!("No shards for this tenant ID found").into(),
4326 0 : ));
4327 0 : }
4328 0 : let shard_params = shard_params.expect("result is non-empty, therefore this is set");
4329 0 : tracing::info!(
4330 0 : "Located tenant {} with params {:?} on shards {}",
4331 0 : tenant_id,
4332 0 : shard_params,
4333 0 : result
4334 0 : .iter()
4335 0 : .map(|s| format!("{:?}", s))
4336 0 : .collect::<Vec<_>>()
4337 0 : .join(",")
4338 : );
4339 :
4340 0 : Ok(TenantLocateResponse {
4341 0 : shards: result,
4342 0 : shard_params,
4343 0 : })
4344 0 : }
4345 :
4346 : /// Returns None if the input iterator of shards does not include a shard with number=0
4347 0 : fn tenant_describe_impl<'a>(
4348 0 : &self,
4349 0 : shards: impl Iterator<Item = &'a TenantShard>,
4350 0 : ) -> Option<TenantDescribeResponse> {
4351 0 : let mut shard_zero = None;
4352 0 : let mut describe_shards = Vec::new();
4353 :
4354 0 : for shard in shards {
4355 0 : if shard.tenant_shard_id.is_shard_zero() {
4356 0 : shard_zero = Some(shard);
4357 0 : }
4358 :
4359 0 : describe_shards.push(TenantDescribeResponseShard {
4360 0 : tenant_shard_id: shard.tenant_shard_id,
4361 0 : node_attached: *shard.intent.get_attached(),
4362 0 : node_secondary: shard.intent.get_secondary().to_vec(),
4363 0 : last_error: shard
4364 0 : .last_error
4365 0 : .lock()
4366 0 : .unwrap()
4367 0 : .as_ref()
4368 0 : .map(|e| format!("{e}"))
4369 0 : .unwrap_or("".to_string())
4370 0 : .clone(),
4371 0 : is_reconciling: shard.reconciler.is_some(),
4372 0 : is_pending_compute_notification: shard.pending_compute_notification,
4373 0 : is_splitting: matches!(shard.splitting, SplitState::Splitting),
4374 0 : scheduling_policy: *shard.get_scheduling_policy(),
4375 0 : preferred_az_id: shard.preferred_az().map(ToString::to_string),
4376 : })
4377 : }
4378 :
4379 0 : let shard_zero = shard_zero?;
4380 :
4381 0 : Some(TenantDescribeResponse {
4382 0 : tenant_id: shard_zero.tenant_shard_id.tenant_id,
4383 0 : shards: describe_shards,
4384 0 : stripe_size: shard_zero.shard.stripe_size,
4385 0 : policy: shard_zero.policy.clone(),
4386 0 : config: shard_zero.config.clone(),
4387 0 : })
4388 0 : }
4389 :
4390 0 : pub(crate) fn tenant_describe(
4391 0 : &self,
4392 0 : tenant_id: TenantId,
4393 0 : ) -> Result<TenantDescribeResponse, ApiError> {
4394 0 : let locked = self.inner.read().unwrap();
4395 0 :
4396 0 : self.tenant_describe_impl(
4397 0 : locked
4398 0 : .tenants
4399 0 : .range(TenantShardId::tenant_range(tenant_id))
4400 0 : .map(|(_k, v)| v),
4401 0 : )
4402 0 : .ok_or_else(|| ApiError::NotFound(anyhow::anyhow!("Tenant {tenant_id} not found").into()))
4403 0 : }
4404 :
4405 : /// limit & offset are pagination parameters. Since we are walking an in-memory HashMap, `offset` does not
4406 : /// avoid traversing data, it just avoid returning it. This is suitable for our purposes, since our in memory
4407 : /// maps are small enough to traverse fast, our pagination is just to avoid serializing huge JSON responses
4408 : /// in our external API.
4409 0 : pub(crate) fn tenant_list(
4410 0 : &self,
4411 0 : limit: Option<usize>,
4412 0 : start_after: Option<TenantId>,
4413 0 : ) -> Vec<TenantDescribeResponse> {
4414 0 : let locked = self.inner.read().unwrap();
4415 :
4416 : // Apply start_from parameter
4417 0 : let shard_range = match start_after {
4418 0 : None => locked.tenants.range(..),
4419 0 : Some(tenant_id) => locked.tenants.range(
4420 0 : TenantShardId {
4421 0 : tenant_id,
4422 0 : shard_number: ShardNumber(u8::MAX),
4423 0 : shard_count: ShardCount(u8::MAX),
4424 0 : }..,
4425 0 : ),
4426 : };
4427 :
4428 0 : let mut result = Vec::new();
4429 0 : for (_tenant_id, tenant_shards) in &shard_range.group_by(|(id, _shard)| id.tenant_id) {
4430 0 : result.push(
4431 0 : self.tenant_describe_impl(tenant_shards.map(|(_k, v)| v))
4432 0 : .expect("Groups are always non-empty"),
4433 0 : );
4434 :
4435 : // Enforce `limit` parameter
4436 0 : if let Some(limit) = limit {
4437 0 : if result.len() >= limit {
4438 0 : break;
4439 0 : }
4440 0 : }
4441 : }
4442 :
4443 0 : result
4444 0 : }
4445 :
4446 : #[instrument(skip_all, fields(tenant_id=%op.tenant_id))]
4447 : async fn abort_tenant_shard_split(
4448 : &self,
4449 : op: &TenantShardSplitAbort,
4450 : ) -> Result<(), TenantShardSplitAbortError> {
4451 : // Cleaning up a split:
4452 : // - Parent shards are not destroyed during a split, just detached.
4453 : // - Failed pageserver split API calls can leave the remote node with just the parent attached,
4454 : // just the children attached, or both.
4455 : //
4456 : // Therefore our work to do is to:
4457 : // 1. Clean up storage controller's internal state to just refer to parents, no children
4458 : // 2. Call out to pageservers to ensure that children are detached
4459 : // 3. Call out to pageservers to ensure that parents are attached.
4460 : //
4461 : // Crash safety:
4462 : // - If the storage controller stops running during this cleanup *after* clearing the splitting state
4463 : // from our database, then [`Self::startup_reconcile`] will regard child attachments as garbage
4464 : // and detach them.
4465 : // - TODO: If the storage controller stops running during this cleanup *before* clearing the splitting state
4466 : // from our database, then we will re-enter this cleanup routine on startup.
4467 :
4468 : let TenantShardSplitAbort {
4469 : tenant_id,
4470 : new_shard_count,
4471 : new_stripe_size,
4472 : ..
4473 : } = op;
4474 :
4475 : // First abort persistent state, if any exists.
4476 : match self
4477 : .persistence
4478 : .abort_shard_split(*tenant_id, *new_shard_count)
4479 : .await?
4480 : {
4481 : AbortShardSplitStatus::Aborted => {
4482 : // Proceed to roll back any child shards created on pageservers
4483 : }
4484 : AbortShardSplitStatus::Complete => {
4485 : // The split completed (we might hit that path if e.g. our database transaction
4486 : // to write the completion landed in the database, but we dropped connection
4487 : // before seeing the result).
4488 : //
4489 : // We must update in-memory state to reflect the successful split.
4490 : self.tenant_shard_split_commit_inmem(
4491 : *tenant_id,
4492 : *new_shard_count,
4493 : *new_stripe_size,
4494 : );
4495 : return Ok(());
4496 : }
4497 : }
4498 :
4499 : // Clean up in-memory state, and accumulate the list of child locations that need detaching
4500 : let detach_locations: Vec<(Node, TenantShardId)> = {
4501 : let mut detach_locations = Vec::new();
4502 : let mut locked = self.inner.write().unwrap();
4503 : let (nodes, tenants, scheduler) = locked.parts_mut();
4504 :
4505 : for (tenant_shard_id, shard) in
4506 : tenants.range_mut(TenantShardId::tenant_range(op.tenant_id))
4507 : {
4508 : if shard.shard.count == op.new_shard_count {
4509 : // Surprising: the phase of [`Self::do_tenant_shard_split`] which inserts child shards in-memory
4510 : // is infallible, so if we got an error we shouldn't have got that far.
4511 : tracing::warn!(
4512 : "During split abort, child shard {tenant_shard_id} found in-memory"
4513 : );
4514 : continue;
4515 : }
4516 :
4517 : // Add the children of this shard to this list of things to detach
4518 : if let Some(node_id) = shard.intent.get_attached() {
4519 : for child_id in tenant_shard_id.split(*new_shard_count) {
4520 : detach_locations.push((
4521 : nodes
4522 : .get(node_id)
4523 : .expect("Intent references nonexistent node")
4524 : .clone(),
4525 : child_id,
4526 : ));
4527 : }
4528 : } else {
4529 : tracing::warn!(
4530 : "During split abort, shard {tenant_shard_id} has no attached location"
4531 : );
4532 : }
4533 :
4534 : tracing::info!("Restoring parent shard {tenant_shard_id}");
4535 :
4536 : // Drop any intents that refer to unavailable nodes, to enable this abort to proceed even
4537 : // if the original attachment location is offline.
4538 : if let Some(node_id) = shard.intent.get_attached() {
4539 : if !nodes.get(node_id).unwrap().is_available() {
4540 : tracing::info!(
4541 : "Demoting attached intent for {tenant_shard_id} on unavailable node {node_id}"
4542 : );
4543 : shard.intent.demote_attached(scheduler, *node_id);
4544 : }
4545 : }
4546 : for node_id in shard.intent.get_secondary().clone() {
4547 : if !nodes.get(&node_id).unwrap().is_available() {
4548 : tracing::info!(
4549 : "Dropping secondary intent for {tenant_shard_id} on unavailable node {node_id}"
4550 : );
4551 : shard.intent.remove_secondary(scheduler, node_id);
4552 : }
4553 : }
4554 :
4555 : shard.splitting = SplitState::Idle;
4556 : if let Err(e) = shard.schedule(scheduler, &mut ScheduleContext::default()) {
4557 : // If this shard can't be scheduled now (perhaps due to offline nodes or
4558 : // capacity issues), that must not prevent us rolling back a split. In this
4559 : // case it should be eventually scheduled in the background.
4560 : tracing::warn!("Failed to schedule {tenant_shard_id} during shard abort: {e}")
4561 : }
4562 :
4563 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High);
4564 : }
4565 :
4566 : // We don't expect any new_shard_count shards to exist here, but drop them just in case
4567 0 : tenants.retain(|_id, s| s.shard.count != *new_shard_count);
4568 :
4569 : detach_locations
4570 : };
4571 :
4572 : for (node, child_id) in detach_locations {
4573 : if !node.is_available() {
4574 : // An unavailable node cannot be cleaned up now: to avoid blocking forever, we will permit this, and
4575 : // rely on the reconciliation that happens when a node transitions to Active to clean up. Since we have
4576 : // removed child shards from our in-memory state and database, the reconciliation will implicitly remove
4577 : // them from the node.
4578 : tracing::warn!(
4579 : "Node {node} unavailable, can't clean up during split abort. It will be cleaned up when it is reactivated."
4580 : );
4581 : continue;
4582 : }
4583 :
4584 : // Detach the remote child. If the pageserver split API call is still in progress, this call will get
4585 : // a 503 and retry, up to our limit.
4586 : tracing::info!("Detaching {child_id} on {node}...");
4587 : match node
4588 : .with_client_retries(
4589 0 : |client| async move {
4590 0 : let config = LocationConfig {
4591 0 : mode: LocationConfigMode::Detached,
4592 0 : generation: None,
4593 0 : secondary_conf: None,
4594 0 : shard_number: child_id.shard_number.0,
4595 0 : shard_count: child_id.shard_count.literal(),
4596 0 : // Stripe size and tenant config don't matter when detaching
4597 0 : shard_stripe_size: 0,
4598 0 : tenant_conf: TenantConfig::default(),
4599 0 : };
4600 0 :
4601 0 : client.location_config(child_id, config, None, false).await
4602 0 : },
4603 : &self.config.pageserver_jwt_token,
4604 : 1,
4605 : 10,
4606 : Duration::from_secs(5),
4607 : &self.cancel,
4608 : )
4609 : .await
4610 : {
4611 : Some(Ok(_)) => {}
4612 : Some(Err(e)) => {
4613 : // We failed to communicate with the remote node. This is problematic: we may be
4614 : // leaving it with a rogue child shard.
4615 : tracing::warn!(
4616 : "Failed to detach child {child_id} from node {node} during abort"
4617 : );
4618 : return Err(e.into());
4619 : }
4620 : None => {
4621 : // Cancellation: we were shutdown or the node went offline. Shutdown is fine, we'll
4622 : // clean up on restart. The node going offline requires a retry.
4623 : return Err(TenantShardSplitAbortError::Unavailable);
4624 : }
4625 : };
4626 : }
4627 :
4628 : tracing::info!("Successfully aborted split");
4629 : Ok(())
4630 : }
4631 :
4632 : /// Infallible final stage of [`Self::tenant_shard_split`]: update the contents
4633 : /// of the tenant map to reflect the child shards that exist after the split.
4634 0 : fn tenant_shard_split_commit_inmem(
4635 0 : &self,
4636 0 : tenant_id: TenantId,
4637 0 : new_shard_count: ShardCount,
4638 0 : new_stripe_size: Option<ShardStripeSize>,
4639 0 : ) -> (
4640 0 : TenantShardSplitResponse,
4641 0 : Vec<(TenantShardId, NodeId, ShardStripeSize)>,
4642 0 : Vec<ReconcilerWaiter>,
4643 0 : ) {
4644 0 : let mut response = TenantShardSplitResponse {
4645 0 : new_shards: Vec::new(),
4646 0 : };
4647 0 : let mut child_locations = Vec::new();
4648 0 : let mut waiters = Vec::new();
4649 0 :
4650 0 : {
4651 0 : let mut locked = self.inner.write().unwrap();
4652 0 :
4653 0 : let parent_ids = locked
4654 0 : .tenants
4655 0 : .range(TenantShardId::tenant_range(tenant_id))
4656 0 : .map(|(shard_id, _)| *shard_id)
4657 0 : .collect::<Vec<_>>();
4658 0 :
4659 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
4660 0 : for parent_id in parent_ids {
4661 0 : let child_ids = parent_id.split(new_shard_count);
4662 :
4663 0 : let (pageserver, generation, policy, parent_ident, config, preferred_az) = {
4664 0 : let mut old_state = tenants
4665 0 : .remove(&parent_id)
4666 0 : .expect("It was present, we just split it");
4667 0 :
4668 0 : // A non-splitting state is impossible, because [`Self::tenant_shard_split`] holds
4669 0 : // a TenantId lock and passes it through to [`TenantShardSplitAbort`] in case of cleanup:
4670 0 : // nothing else can clear this.
4671 0 : assert!(matches!(old_state.splitting, SplitState::Splitting));
4672 :
4673 0 : let old_attached = old_state.intent.get_attached().unwrap();
4674 0 : old_state.intent.clear(scheduler);
4675 0 : let generation = old_state.generation.expect("Shard must have been attached");
4676 0 : (
4677 0 : old_attached,
4678 0 : generation,
4679 0 : old_state.policy.clone(),
4680 0 : old_state.shard,
4681 0 : old_state.config.clone(),
4682 0 : old_state.preferred_az().cloned(),
4683 0 : )
4684 0 : };
4685 0 :
4686 0 : let mut schedule_context = ScheduleContext::default();
4687 0 : for child in child_ids {
4688 0 : let mut child_shard = parent_ident;
4689 0 : child_shard.number = child.shard_number;
4690 0 : child_shard.count = child.shard_count;
4691 0 : if let Some(stripe_size) = new_stripe_size {
4692 0 : child_shard.stripe_size = stripe_size;
4693 0 : }
4694 :
4695 0 : let mut child_observed: HashMap<NodeId, ObservedStateLocation> = HashMap::new();
4696 0 : child_observed.insert(
4697 0 : pageserver,
4698 0 : ObservedStateLocation {
4699 0 : conf: Some(attached_location_conf(
4700 0 : generation,
4701 0 : &child_shard,
4702 0 : &config,
4703 0 : &policy,
4704 0 : )),
4705 0 : },
4706 0 : );
4707 0 :
4708 0 : let mut child_state =
4709 0 : TenantShard::new(child, child_shard, policy.clone(), preferred_az.clone());
4710 0 : child_state.intent =
4711 0 : IntentState::single(scheduler, Some(pageserver), preferred_az.clone());
4712 0 : child_state.observed = ObservedState {
4713 0 : locations: child_observed,
4714 0 : };
4715 0 : child_state.generation = Some(generation);
4716 0 : child_state.config = config.clone();
4717 0 :
4718 0 : // The child's TenantShard::splitting is intentionally left at the default value of Idle,
4719 0 : // as at this point in the split process we have succeeded and this part is infallible:
4720 0 : // we will never need to do any special recovery from this state.
4721 0 :
4722 0 : child_locations.push((child, pageserver, child_shard.stripe_size));
4723 :
4724 0 : if let Err(e) = child_state.schedule(scheduler, &mut schedule_context) {
4725 : // This is not fatal, because we've implicitly already got an attached
4726 : // location for the child shard. Failure here just means we couldn't
4727 : // find a secondary (e.g. because cluster is overloaded).
4728 0 : tracing::warn!("Failed to schedule child shard {child}: {e}");
4729 0 : }
4730 : // In the background, attach secondary locations for the new shards
4731 0 : if let Some(waiter) = self.maybe_reconcile_shard(
4732 0 : &mut child_state,
4733 0 : nodes,
4734 0 : ReconcilerPriority::High,
4735 0 : ) {
4736 0 : waiters.push(waiter);
4737 0 : }
4738 :
4739 0 : tenants.insert(child, child_state);
4740 0 : response.new_shards.push(child);
4741 : }
4742 : }
4743 0 : (response, child_locations, waiters)
4744 0 : }
4745 0 : }
4746 :
4747 0 : async fn tenant_shard_split_start_secondaries(
4748 0 : &self,
4749 0 : tenant_id: TenantId,
4750 0 : waiters: Vec<ReconcilerWaiter>,
4751 0 : ) {
4752 : // Wait for initial reconcile of child shards, this creates the secondary locations
4753 0 : if let Err(e) = self.await_waiters(waiters, RECONCILE_TIMEOUT).await {
4754 : // This is not a failure to split: it's some issue reconciling the new child shards, perhaps
4755 : // their secondaries couldn't be attached.
4756 0 : tracing::warn!("Failed to reconcile after split: {e}");
4757 0 : return;
4758 0 : }
4759 :
4760 : // Take the state lock to discover the attached & secondary intents for all shards
4761 0 : let (attached, secondary) = {
4762 0 : let locked = self.inner.read().unwrap();
4763 0 : let mut attached = Vec::new();
4764 0 : let mut secondary = Vec::new();
4765 :
4766 0 : for (tenant_shard_id, shard) in
4767 0 : locked.tenants.range(TenantShardId::tenant_range(tenant_id))
4768 : {
4769 0 : let Some(node_id) = shard.intent.get_attached() else {
4770 : // Unexpected. Race with a PlacementPolicy change?
4771 0 : tracing::warn!(
4772 0 : "No attached node on {tenant_shard_id} immediately after shard split!"
4773 : );
4774 0 : continue;
4775 : };
4776 :
4777 0 : let Some(secondary_node_id) = shard.intent.get_secondary().first() else {
4778 : // No secondary location. Nothing for us to do.
4779 0 : continue;
4780 : };
4781 :
4782 0 : let attached_node = locked
4783 0 : .nodes
4784 0 : .get(node_id)
4785 0 : .expect("Pageservers may not be deleted while referenced");
4786 0 :
4787 0 : let secondary_node = locked
4788 0 : .nodes
4789 0 : .get(secondary_node_id)
4790 0 : .expect("Pageservers may not be deleted while referenced");
4791 0 :
4792 0 : attached.push((*tenant_shard_id, attached_node.clone()));
4793 0 : secondary.push((*tenant_shard_id, secondary_node.clone()));
4794 : }
4795 0 : (attached, secondary)
4796 0 : };
4797 0 :
4798 0 : if secondary.is_empty() {
4799 : // No secondary locations; nothing for us to do
4800 0 : return;
4801 0 : }
4802 :
4803 0 : for result in self
4804 0 : .tenant_for_shards_api(
4805 0 : attached,
4806 0 : |tenant_shard_id, client| async move {
4807 0 : client.tenant_heatmap_upload(tenant_shard_id).await
4808 0 : },
4809 0 : 1,
4810 0 : 1,
4811 0 : SHORT_RECONCILE_TIMEOUT,
4812 0 : &self.cancel,
4813 0 : )
4814 0 : .await
4815 : {
4816 0 : if let Err(e) = result {
4817 0 : tracing::warn!("Error calling heatmap upload after shard split: {e}");
4818 0 : return;
4819 0 : }
4820 : }
4821 :
4822 0 : for result in self
4823 0 : .tenant_for_shards_api(
4824 0 : secondary,
4825 0 : |tenant_shard_id, client| async move {
4826 0 : client
4827 0 : .tenant_secondary_download(tenant_shard_id, Some(Duration::ZERO))
4828 0 : .await
4829 0 : },
4830 0 : 1,
4831 0 : 1,
4832 0 : SHORT_RECONCILE_TIMEOUT,
4833 0 : &self.cancel,
4834 0 : )
4835 0 : .await
4836 : {
4837 0 : if let Err(e) = result {
4838 0 : tracing::warn!("Error calling secondary download after shard split: {e}");
4839 0 : return;
4840 0 : }
4841 : }
4842 0 : }
4843 :
4844 0 : pub(crate) async fn tenant_shard_split(
4845 0 : &self,
4846 0 : tenant_id: TenantId,
4847 0 : split_req: TenantShardSplitRequest,
4848 0 : ) -> Result<TenantShardSplitResponse, ApiError> {
4849 : // TODO: return 503 if we get stuck waiting for this lock
4850 : // (issue https://github.com/neondatabase/neon/issues/7108)
4851 0 : let _tenant_lock = trace_exclusive_lock(
4852 0 : &self.tenant_op_locks,
4853 0 : tenant_id,
4854 0 : TenantOperations::ShardSplit,
4855 0 : )
4856 0 : .await;
4857 :
4858 0 : let new_shard_count = ShardCount::new(split_req.new_shard_count);
4859 0 : let new_stripe_size = split_req.new_stripe_size;
4860 :
4861 : // Validate the request and construct parameters. This phase is fallible, but does not require
4862 : // rollback on errors, as it does no I/O and mutates no state.
4863 0 : let shard_split_params = match self.prepare_tenant_shard_split(tenant_id, split_req)? {
4864 0 : ShardSplitAction::NoOp(resp) => return Ok(resp),
4865 0 : ShardSplitAction::Split(params) => params,
4866 : };
4867 :
4868 : // Execute this split: this phase mutates state and does remote I/O on pageservers. If it fails,
4869 : // we must roll back.
4870 0 : let r = self
4871 0 : .do_tenant_shard_split(tenant_id, shard_split_params)
4872 0 : .await;
4873 :
4874 0 : let (response, waiters) = match r {
4875 0 : Ok(r) => r,
4876 0 : Err(e) => {
4877 0 : // Split might be part-done, we must do work to abort it.
4878 0 : tracing::warn!("Enqueuing background abort of split on {tenant_id}");
4879 0 : self.abort_tx
4880 0 : .send(TenantShardSplitAbort {
4881 0 : tenant_id,
4882 0 : new_shard_count,
4883 0 : new_stripe_size,
4884 0 : _tenant_lock,
4885 0 : })
4886 0 : // Ignore error sending: that just means we're shutting down: aborts are ephemeral so it's fine to drop it.
4887 0 : .ok();
4888 0 : return Err(e);
4889 : }
4890 : };
4891 :
4892 : // The split is now complete. As an optimization, we will trigger all the child shards to upload
4893 : // a heatmap immediately, and all their secondary locations to start downloading: this avoids waiting
4894 : // for the background heatmap/download interval before secondaries get warm enough to migrate shards
4895 : // in [`Self::optimize_all`]
4896 0 : self.tenant_shard_split_start_secondaries(tenant_id, waiters)
4897 0 : .await;
4898 0 : Ok(response)
4899 0 : }
4900 :
4901 0 : fn prepare_tenant_shard_split(
4902 0 : &self,
4903 0 : tenant_id: TenantId,
4904 0 : split_req: TenantShardSplitRequest,
4905 0 : ) -> Result<ShardSplitAction, ApiError> {
4906 0 : fail::fail_point!("shard-split-validation", |_| Err(ApiError::BadRequest(
4907 0 : anyhow::anyhow!("failpoint")
4908 0 : )));
4909 :
4910 0 : let mut policy = None;
4911 0 : let mut config = None;
4912 0 : let mut shard_ident = None;
4913 0 : let mut preferred_az_id = None;
4914 : // Validate input, and calculate which shards we will create
4915 0 : let (old_shard_count, targets) =
4916 : {
4917 0 : let locked = self.inner.read().unwrap();
4918 0 :
4919 0 : let pageservers = locked.nodes.clone();
4920 0 :
4921 0 : let mut targets = Vec::new();
4922 0 :
4923 0 : // In case this is a retry, count how many already-split shards we found
4924 0 : let mut children_found = Vec::new();
4925 0 : let mut old_shard_count = None;
4926 :
4927 0 : for (tenant_shard_id, shard) in
4928 0 : locked.tenants.range(TenantShardId::tenant_range(tenant_id))
4929 : {
4930 0 : match shard.shard.count.count().cmp(&split_req.new_shard_count) {
4931 : Ordering::Equal => {
4932 : // Already split this
4933 0 : children_found.push(*tenant_shard_id);
4934 0 : continue;
4935 : }
4936 : Ordering::Greater => {
4937 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
4938 0 : "Requested count {} but already have shards at count {}",
4939 0 : split_req.new_shard_count,
4940 0 : shard.shard.count.count()
4941 0 : )));
4942 : }
4943 0 : Ordering::Less => {
4944 0 : // Fall through: this shard has lower count than requested,
4945 0 : // is a candidate for splitting.
4946 0 : }
4947 0 : }
4948 0 :
4949 0 : match old_shard_count {
4950 0 : None => old_shard_count = Some(shard.shard.count),
4951 0 : Some(old_shard_count) => {
4952 0 : if old_shard_count != shard.shard.count {
4953 : // We may hit this case if a caller asked for two splits to
4954 : // different sizes, before the first one is complete.
4955 : // e.g. 1->2, 2->4, where the 4 call comes while we have a mixture
4956 : // of shard_count=1 and shard_count=2 shards in the map.
4957 0 : return Err(ApiError::Conflict(
4958 0 : "Cannot split, currently mid-split".to_string(),
4959 0 : ));
4960 0 : }
4961 : }
4962 : }
4963 0 : if policy.is_none() {
4964 0 : policy = Some(shard.policy.clone());
4965 0 : }
4966 0 : if shard_ident.is_none() {
4967 0 : shard_ident = Some(shard.shard);
4968 0 : }
4969 0 : if config.is_none() {
4970 0 : config = Some(shard.config.clone());
4971 0 : }
4972 0 : if preferred_az_id.is_none() {
4973 0 : preferred_az_id = shard.preferred_az().cloned();
4974 0 : }
4975 :
4976 0 : if tenant_shard_id.shard_count.count() == split_req.new_shard_count {
4977 0 : tracing::info!(
4978 0 : "Tenant shard {} already has shard count {}",
4979 : tenant_shard_id,
4980 : split_req.new_shard_count
4981 : );
4982 0 : continue;
4983 0 : }
4984 :
4985 0 : let node_id = shard.intent.get_attached().ok_or(ApiError::BadRequest(
4986 0 : anyhow::anyhow!("Cannot split a tenant that is not attached"),
4987 0 : ))?;
4988 :
4989 0 : let node = pageservers
4990 0 : .get(&node_id)
4991 0 : .expect("Pageservers may not be deleted while referenced");
4992 0 :
4993 0 : targets.push(ShardSplitTarget {
4994 0 : parent_id: *tenant_shard_id,
4995 0 : node: node.clone(),
4996 0 : child_ids: tenant_shard_id
4997 0 : .split(ShardCount::new(split_req.new_shard_count)),
4998 0 : });
4999 : }
5000 :
5001 0 : if targets.is_empty() {
5002 0 : if children_found.len() == split_req.new_shard_count as usize {
5003 0 : return Ok(ShardSplitAction::NoOp(TenantShardSplitResponse {
5004 0 : new_shards: children_found,
5005 0 : }));
5006 : } else {
5007 : // No shards found to split, and no existing children found: the
5008 : // tenant doesn't exist at all.
5009 0 : return Err(ApiError::NotFound(
5010 0 : anyhow::anyhow!("Tenant {} not found", tenant_id).into(),
5011 0 : ));
5012 : }
5013 0 : }
5014 0 :
5015 0 : (old_shard_count, targets)
5016 0 : };
5017 0 :
5018 0 : // unwrap safety: we would have returned above if we didn't find at least one shard to split
5019 0 : let old_shard_count = old_shard_count.unwrap();
5020 0 : let shard_ident = if let Some(new_stripe_size) = split_req.new_stripe_size {
5021 : // This ShardIdentity will be used as the template for all children, so this implicitly
5022 : // applies the new stripe size to the children.
5023 0 : let mut shard_ident = shard_ident.unwrap();
5024 0 : if shard_ident.count.count() > 1 && shard_ident.stripe_size != new_stripe_size {
5025 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
5026 0 : "Attempted to change stripe size ({:?}->{new_stripe_size:?}) on a tenant with multiple shards",
5027 0 : shard_ident.stripe_size
5028 0 : )));
5029 0 : }
5030 0 :
5031 0 : shard_ident.stripe_size = new_stripe_size;
5032 0 : tracing::info!("applied stripe size {}", shard_ident.stripe_size.0);
5033 0 : shard_ident
5034 : } else {
5035 0 : shard_ident.unwrap()
5036 : };
5037 0 : let policy = policy.unwrap();
5038 0 : let config = config.unwrap();
5039 0 :
5040 0 : Ok(ShardSplitAction::Split(Box::new(ShardSplitParams {
5041 0 : old_shard_count,
5042 0 : new_shard_count: ShardCount::new(split_req.new_shard_count),
5043 0 : new_stripe_size: split_req.new_stripe_size,
5044 0 : targets,
5045 0 : policy,
5046 0 : config,
5047 0 : shard_ident,
5048 0 : preferred_az_id,
5049 0 : })))
5050 0 : }
5051 :
5052 0 : async fn do_tenant_shard_split(
5053 0 : &self,
5054 0 : tenant_id: TenantId,
5055 0 : params: Box<ShardSplitParams>,
5056 0 : ) -> Result<(TenantShardSplitResponse, Vec<ReconcilerWaiter>), ApiError> {
5057 0 : // FIXME: we have dropped self.inner lock, and not yet written anything to the database: another
5058 0 : // request could occur here, deleting or mutating the tenant. begin_shard_split checks that the
5059 0 : // parent shards exist as expected, but it would be neater to do the above pre-checks within the
5060 0 : // same database transaction rather than pre-check in-memory and then maybe-fail the database write.
5061 0 : // (https://github.com/neondatabase/neon/issues/6676)
5062 0 :
5063 0 : let ShardSplitParams {
5064 0 : old_shard_count,
5065 0 : new_shard_count,
5066 0 : new_stripe_size,
5067 0 : mut targets,
5068 0 : policy,
5069 0 : config,
5070 0 : shard_ident,
5071 0 : preferred_az_id,
5072 0 : } = *params;
5073 :
5074 : // Drop any secondary locations: pageservers do not support splitting these, and in any case the
5075 : // end-state for a split tenant will usually be to have secondary locations on different nodes.
5076 : // The reconciliation calls in this block also implicitly cancel+barrier wrt any ongoing reconciliation
5077 : // at the time of split.
5078 0 : let waiters = {
5079 0 : let mut locked = self.inner.write().unwrap();
5080 0 : let mut waiters = Vec::new();
5081 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
5082 0 : for target in &mut targets {
5083 0 : let Some(shard) = tenants.get_mut(&target.parent_id) else {
5084 : // Paranoia check: this shouldn't happen: we have the oplock for this tenant ID.
5085 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
5086 0 : "Shard {} not found",
5087 0 : target.parent_id
5088 0 : )));
5089 : };
5090 :
5091 0 : if shard.intent.get_attached() != &Some(target.node.get_id()) {
5092 : // Paranoia check: this shouldn't happen: we have the oplock for this tenant ID.
5093 0 : return Err(ApiError::Conflict(format!(
5094 0 : "Shard {} unexpectedly rescheduled during split",
5095 0 : target.parent_id
5096 0 : )));
5097 0 : }
5098 0 :
5099 0 : // Irrespective of PlacementPolicy, clear secondary locations from intent
5100 0 : shard.intent.clear_secondary(scheduler);
5101 :
5102 : // Run Reconciler to execute detach fo secondary locations.
5103 0 : if let Some(waiter) =
5104 0 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High)
5105 0 : {
5106 0 : waiters.push(waiter);
5107 0 : }
5108 : }
5109 0 : waiters
5110 0 : };
5111 0 : self.await_waiters(waiters, RECONCILE_TIMEOUT).await?;
5112 :
5113 : // Before creating any new child shards in memory or on the pageservers, persist them: this
5114 : // enables us to ensure that we will always be able to clean up if something goes wrong. This also
5115 : // acts as the protection against two concurrent attempts to split: one of them will get a database
5116 : // error trying to insert the child shards.
5117 0 : let mut child_tsps = Vec::new();
5118 0 : for target in &targets {
5119 0 : let mut this_child_tsps = Vec::new();
5120 0 : for child in &target.child_ids {
5121 0 : let mut child_shard = shard_ident;
5122 0 : child_shard.number = child.shard_number;
5123 0 : child_shard.count = child.shard_count;
5124 0 :
5125 0 : tracing::info!(
5126 0 : "Create child shard persistence with stripe size {}",
5127 : shard_ident.stripe_size.0
5128 : );
5129 :
5130 0 : this_child_tsps.push(TenantShardPersistence {
5131 0 : tenant_id: child.tenant_id.to_string(),
5132 0 : shard_number: child.shard_number.0 as i32,
5133 0 : shard_count: child.shard_count.literal() as i32,
5134 0 : shard_stripe_size: shard_ident.stripe_size.0 as i32,
5135 0 : // Note: this generation is a placeholder, [`Persistence::begin_shard_split`] will
5136 0 : // populate the correct generation as part of its transaction, to protect us
5137 0 : // against racing with changes in the state of the parent.
5138 0 : generation: None,
5139 0 : generation_pageserver: Some(target.node.get_id().0 as i64),
5140 0 : placement_policy: serde_json::to_string(&policy).unwrap(),
5141 0 : config: serde_json::to_string(&config).unwrap(),
5142 0 : splitting: SplitState::Splitting,
5143 0 :
5144 0 : // Scheduling policies and preferred AZ do not carry through to children
5145 0 : scheduling_policy: serde_json::to_string(&ShardSchedulingPolicy::default())
5146 0 : .unwrap(),
5147 0 : preferred_az_id: preferred_az_id.as_ref().map(|az| az.0.clone()),
5148 0 : });
5149 0 : }
5150 :
5151 0 : child_tsps.push((target.parent_id, this_child_tsps));
5152 : }
5153 :
5154 0 : if let Err(e) = self
5155 0 : .persistence
5156 0 : .begin_shard_split(old_shard_count, tenant_id, child_tsps)
5157 0 : .await
5158 : {
5159 0 : match e {
5160 : DatabaseError::Query(diesel::result::Error::DatabaseError(
5161 : DatabaseErrorKind::UniqueViolation,
5162 : _,
5163 : )) => {
5164 : // Inserting a child shard violated a unique constraint: we raced with another call to
5165 : // this function
5166 0 : tracing::warn!("Conflicting attempt to split {tenant_id}: {e}");
5167 0 : return Err(ApiError::Conflict("Tenant is already splitting".into()));
5168 : }
5169 0 : _ => return Err(ApiError::InternalServerError(e.into())),
5170 : }
5171 0 : }
5172 0 : fail::fail_point!("shard-split-post-begin", |_| Err(
5173 0 : ApiError::InternalServerError(anyhow::anyhow!("failpoint"))
5174 0 : ));
5175 :
5176 : // Now that I have persisted the splitting state, apply it in-memory. This is infallible, so
5177 : // callers may assume that if splitting is set in memory, then it was persisted, and if splitting
5178 : // is not set in memory, then it was not persisted.
5179 : {
5180 0 : let mut locked = self.inner.write().unwrap();
5181 0 : for target in &targets {
5182 0 : if let Some(parent_shard) = locked.tenants.get_mut(&target.parent_id) {
5183 0 : parent_shard.splitting = SplitState::Splitting;
5184 0 : // Put the observed state to None, to reflect that it is indeterminate once we start the
5185 0 : // split operation.
5186 0 : parent_shard
5187 0 : .observed
5188 0 : .locations
5189 0 : .insert(target.node.get_id(), ObservedStateLocation { conf: None });
5190 0 : }
5191 : }
5192 : }
5193 :
5194 : // TODO: issue split calls concurrently (this only matters once we're splitting
5195 : // N>1 shards into M shards -- initially we're usually splitting 1 shard into N).
5196 :
5197 0 : for target in &targets {
5198 : let ShardSplitTarget {
5199 0 : parent_id,
5200 0 : node,
5201 0 : child_ids,
5202 0 : } = target;
5203 0 : let client = PageserverClient::new(
5204 0 : node.get_id(),
5205 0 : node.base_url(),
5206 0 : self.config.pageserver_jwt_token.as_deref(),
5207 0 : );
5208 0 : let response = client
5209 0 : .tenant_shard_split(
5210 0 : *parent_id,
5211 0 : TenantShardSplitRequest {
5212 0 : new_shard_count: new_shard_count.literal(),
5213 0 : new_stripe_size,
5214 0 : },
5215 0 : )
5216 0 : .await
5217 0 : .map_err(|e| ApiError::Conflict(format!("Failed to split {}: {}", parent_id, e)))?;
5218 :
5219 0 : fail::fail_point!("shard-split-post-remote", |_| Err(ApiError::Conflict(
5220 0 : "failpoint".to_string()
5221 0 : )));
5222 :
5223 0 : failpoint_support::sleep_millis_async!("shard-split-post-remote-sleep", &self.cancel);
5224 :
5225 0 : tracing::info!(
5226 0 : "Split {} into {}",
5227 0 : parent_id,
5228 0 : response
5229 0 : .new_shards
5230 0 : .iter()
5231 0 : .map(|s| format!("{:?}", s))
5232 0 : .collect::<Vec<_>>()
5233 0 : .join(",")
5234 : );
5235 :
5236 0 : if &response.new_shards != child_ids {
5237 : // This should never happen: the pageserver should agree with us on how shard splits work.
5238 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
5239 0 : "Splitting shard {} resulted in unexpected IDs: {:?} (expected {:?})",
5240 0 : parent_id,
5241 0 : response.new_shards,
5242 0 : child_ids
5243 0 : )));
5244 0 : }
5245 : }
5246 :
5247 : // TODO: if the pageserver restarted concurrently with our split API call,
5248 : // the actual generation of the child shard might differ from the generation
5249 : // we expect it to have. In order for our in-database generation to end up
5250 : // correct, we should carry the child generation back in the response and apply it here
5251 : // in complete_shard_split (and apply the correct generation in memory)
5252 : // (or, we can carry generation in the request and reject the request if
5253 : // it doesn't match, but that requires more retry logic on this side)
5254 :
5255 0 : self.persistence
5256 0 : .complete_shard_split(tenant_id, old_shard_count)
5257 0 : .await?;
5258 :
5259 0 : fail::fail_point!("shard-split-post-complete", |_| Err(
5260 0 : ApiError::InternalServerError(anyhow::anyhow!("failpoint"))
5261 0 : ));
5262 :
5263 : // Replace all the shards we just split with their children: this phase is infallible.
5264 0 : let (response, child_locations, waiters) =
5265 0 : self.tenant_shard_split_commit_inmem(tenant_id, new_shard_count, new_stripe_size);
5266 0 :
5267 0 : // Send compute notifications for all the new shards
5268 0 : let mut failed_notifications = Vec::new();
5269 0 : for (child_id, child_ps, stripe_size) in child_locations {
5270 0 : if let Err(e) = self
5271 0 : .compute_hook
5272 0 : .notify(
5273 0 : compute_hook::ShardUpdate {
5274 0 : tenant_shard_id: child_id,
5275 0 : node_id: child_ps,
5276 0 : stripe_size,
5277 0 : preferred_az: preferred_az_id.as_ref().map(Cow::Borrowed),
5278 0 : },
5279 0 : &self.cancel,
5280 0 : )
5281 0 : .await
5282 : {
5283 0 : tracing::warn!(
5284 0 : "Failed to update compute of {}->{} during split, proceeding anyway to complete split ({e})",
5285 : child_id,
5286 : child_ps
5287 : );
5288 0 : failed_notifications.push(child_id);
5289 0 : }
5290 : }
5291 :
5292 : // If we failed any compute notifications, make a note to retry later.
5293 0 : if !failed_notifications.is_empty() {
5294 0 : let mut locked = self.inner.write().unwrap();
5295 0 : for failed in failed_notifications {
5296 0 : if let Some(shard) = locked.tenants.get_mut(&failed) {
5297 0 : shard.pending_compute_notification = true;
5298 0 : }
5299 : }
5300 0 : }
5301 :
5302 0 : Ok((response, waiters))
5303 0 : }
5304 :
5305 0 : pub(crate) async fn tenant_shard_migrate(
5306 0 : &self,
5307 0 : tenant_shard_id: TenantShardId,
5308 0 : migrate_req: TenantShardMigrateRequest,
5309 0 : ) -> Result<TenantShardMigrateResponse, ApiError> {
5310 0 : let waiter = {
5311 0 : let mut locked = self.inner.write().unwrap();
5312 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
5313 :
5314 0 : let Some(node) = nodes.get(&migrate_req.node_id) else {
5315 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
5316 0 : "Node {} not found",
5317 0 : migrate_req.node_id
5318 0 : )));
5319 : };
5320 :
5321 0 : if !node.is_available() {
5322 : // Warn but proceed: the caller may intend to manually adjust the placement of
5323 : // a shard even if the node is down, e.g. if intervening during an incident.
5324 0 : tracing::warn!("Migrating to unavailable node {node}");
5325 0 : }
5326 :
5327 0 : let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
5328 0 : return Err(ApiError::NotFound(
5329 0 : anyhow::anyhow!("Tenant shard not found").into(),
5330 0 : ));
5331 : };
5332 :
5333 0 : if shard.intent.get_attached() == &Some(migrate_req.node_id) {
5334 : // No-op case: we will still proceed to wait for reconciliation in case it is
5335 : // incomplete from an earlier update to the intent.
5336 0 : tracing::info!("Migrating: intent is unchanged {:?}", shard.intent);
5337 : } else {
5338 0 : let old_attached = *shard.intent.get_attached();
5339 0 :
5340 0 : match shard.policy {
5341 0 : PlacementPolicy::Attached(n) => {
5342 0 : // If our new attached node was a secondary, it no longer should be.
5343 0 : shard
5344 0 : .intent
5345 0 : .remove_secondary(scheduler, migrate_req.node_id);
5346 0 :
5347 0 : shard
5348 0 : .intent
5349 0 : .set_attached(scheduler, Some(migrate_req.node_id));
5350 :
5351 : // If we were already attached to something, demote that to a secondary
5352 0 : if let Some(old_attached) = old_attached {
5353 0 : if n > 0 {
5354 : // Remove other secondaries to make room for the location we'll demote
5355 0 : while shard.intent.get_secondary().len() >= n {
5356 0 : shard.intent.pop_secondary(scheduler);
5357 0 : }
5358 :
5359 0 : shard.intent.push_secondary(scheduler, old_attached);
5360 0 : }
5361 0 : }
5362 : }
5363 0 : PlacementPolicy::Secondary => {
5364 0 : shard.intent.clear(scheduler);
5365 0 : shard.intent.push_secondary(scheduler, migrate_req.node_id);
5366 0 : }
5367 : PlacementPolicy::Detached => {
5368 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
5369 0 : "Cannot migrate a tenant that is PlacementPolicy::Detached: configure it to an attached policy first"
5370 0 : )));
5371 : }
5372 : }
5373 :
5374 0 : tracing::info!("Migrating: new intent {:?}", shard.intent);
5375 0 : shard.sequence = shard.sequence.next();
5376 : }
5377 :
5378 0 : let reconciler_config = match migrate_req.migration_config {
5379 0 : Some(cfg) => (&cfg).into(),
5380 0 : None => ReconcilerConfig::new(ReconcilerPriority::High),
5381 : };
5382 :
5383 0 : self.maybe_configured_reconcile_shard(shard, nodes, reconciler_config)
5384 : };
5385 :
5386 0 : if let Some(waiter) = waiter {
5387 0 : waiter.wait_timeout(RECONCILE_TIMEOUT).await?;
5388 : } else {
5389 0 : tracing::info!("Migration is a no-op");
5390 : }
5391 :
5392 0 : Ok(TenantShardMigrateResponse {})
5393 0 : }
5394 :
5395 0 : pub(crate) async fn tenant_shard_migrate_secondary(
5396 0 : &self,
5397 0 : tenant_shard_id: TenantShardId,
5398 0 : migrate_req: TenantShardMigrateRequest,
5399 0 : ) -> Result<TenantShardMigrateResponse, ApiError> {
5400 0 : let waiter = {
5401 0 : let mut locked = self.inner.write().unwrap();
5402 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
5403 :
5404 0 : let Some(node) = nodes.get(&migrate_req.node_id) else {
5405 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
5406 0 : "Node {} not found",
5407 0 : migrate_req.node_id
5408 0 : )));
5409 : };
5410 :
5411 0 : if !node.is_available() {
5412 : // Warn but proceed: the caller may intend to manually adjust the placement of
5413 : // a shard even if the node is down, e.g. if intervening during an incident.
5414 0 : tracing::warn!("Migrating to unavailable node {node}");
5415 0 : }
5416 :
5417 0 : let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
5418 0 : return Err(ApiError::NotFound(
5419 0 : anyhow::anyhow!("Tenant shard not found").into(),
5420 0 : ));
5421 : };
5422 :
5423 0 : if shard.intent.get_secondary().len() == 1
5424 0 : && shard.intent.get_secondary()[0] == migrate_req.node_id
5425 : {
5426 0 : tracing::info!(
5427 0 : "Migrating secondary to {node}: intent is unchanged {:?}",
5428 : shard.intent
5429 : );
5430 0 : } else if shard.intent.get_attached() == &Some(migrate_req.node_id) {
5431 0 : tracing::info!(
5432 0 : "Migrating secondary to {node}: already attached where we were asked to create a secondary"
5433 : );
5434 : } else {
5435 0 : let old_secondaries = shard.intent.get_secondary().clone();
5436 0 : for secondary in old_secondaries {
5437 0 : shard.intent.remove_secondary(scheduler, secondary);
5438 0 : }
5439 :
5440 0 : shard.intent.push_secondary(scheduler, migrate_req.node_id);
5441 0 : shard.sequence = shard.sequence.next();
5442 0 : tracing::info!(
5443 0 : "Migrating secondary to {node}: new intent {:?}",
5444 : shard.intent
5445 : );
5446 : }
5447 :
5448 0 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High)
5449 : };
5450 :
5451 0 : if let Some(waiter) = waiter {
5452 0 : waiter.wait_timeout(RECONCILE_TIMEOUT).await?;
5453 : } else {
5454 0 : tracing::info!("Migration is a no-op");
5455 : }
5456 :
5457 0 : Ok(TenantShardMigrateResponse {})
5458 0 : }
5459 :
5460 : /// 'cancel' in this context means cancel any ongoing reconcile
5461 0 : pub(crate) async fn tenant_shard_cancel_reconcile(
5462 0 : &self,
5463 0 : tenant_shard_id: TenantShardId,
5464 0 : ) -> Result<(), ApiError> {
5465 : // Take state lock and fire the cancellation token, after which we drop lock and wait for any ongoing reconcile to complete
5466 0 : let waiter = {
5467 0 : let locked = self.inner.write().unwrap();
5468 0 : let Some(shard) = locked.tenants.get(&tenant_shard_id) else {
5469 0 : return Err(ApiError::NotFound(
5470 0 : anyhow::anyhow!("Tenant shard not found").into(),
5471 0 : ));
5472 : };
5473 :
5474 0 : let waiter = shard.get_waiter();
5475 0 : match waiter {
5476 : None => {
5477 0 : tracing::info!("Shard does not have an ongoing Reconciler");
5478 0 : return Ok(());
5479 : }
5480 0 : Some(waiter) => {
5481 0 : tracing::info!("Cancelling Reconciler");
5482 0 : shard.cancel_reconciler();
5483 0 : waiter
5484 0 : }
5485 0 : }
5486 0 : };
5487 0 :
5488 0 : // Cancellation should be prompt. If this fails we have still done our job of firing the
5489 0 : // cancellation token, but by returning an ApiError we will indicate to the caller that
5490 0 : // the Reconciler is misbehaving and not respecting the cancellation token
5491 0 : self.await_waiters(vec![waiter], SHORT_RECONCILE_TIMEOUT)
5492 0 : .await?;
5493 :
5494 0 : Ok(())
5495 0 : }
5496 :
5497 : /// This is for debug/support only: we simply drop all state for a tenant, without
5498 : /// detaching or deleting it on pageservers.
5499 0 : pub(crate) async fn tenant_drop(&self, tenant_id: TenantId) -> Result<(), ApiError> {
5500 0 : self.persistence.delete_tenant(tenant_id).await?;
5501 :
5502 0 : let mut locked = self.inner.write().unwrap();
5503 0 : let (_nodes, tenants, scheduler) = locked.parts_mut();
5504 0 : let mut shards = Vec::new();
5505 0 : for (tenant_shard_id, _) in tenants.range(TenantShardId::tenant_range(tenant_id)) {
5506 0 : shards.push(*tenant_shard_id);
5507 0 : }
5508 :
5509 0 : for shard_id in shards {
5510 0 : if let Some(mut shard) = tenants.remove(&shard_id) {
5511 0 : shard.intent.clear(scheduler);
5512 0 : }
5513 : }
5514 :
5515 0 : Ok(())
5516 0 : }
5517 :
5518 : /// This is for debug/support only: assuming tenant data is already present in S3, we "create" a
5519 : /// tenant with a very high generation number so that it will see the existing data.
5520 0 : pub(crate) async fn tenant_import(
5521 0 : &self,
5522 0 : tenant_id: TenantId,
5523 0 : ) -> Result<TenantCreateResponse, ApiError> {
5524 0 : // Pick an arbitrary available pageserver to use for scanning the tenant in remote storage
5525 0 : let maybe_node = {
5526 0 : self.inner
5527 0 : .read()
5528 0 : .unwrap()
5529 0 : .nodes
5530 0 : .values()
5531 0 : .find(|n| n.is_available())
5532 0 : .cloned()
5533 : };
5534 0 : let Some(node) = maybe_node else {
5535 0 : return Err(ApiError::BadRequest(anyhow::anyhow!("No nodes available")));
5536 : };
5537 :
5538 0 : let client = PageserverClient::new(
5539 0 : node.get_id(),
5540 0 : node.base_url(),
5541 0 : self.config.pageserver_jwt_token.as_deref(),
5542 0 : );
5543 :
5544 0 : let scan_result = client
5545 0 : .tenant_scan_remote_storage(tenant_id)
5546 0 : .await
5547 0 : .map_err(|e| passthrough_api_error(&node, e))?;
5548 :
5549 : // A post-split tenant may contain a mixture of shard counts in remote storage: pick the highest count.
5550 0 : let Some(shard_count) = scan_result
5551 0 : .shards
5552 0 : .iter()
5553 0 : .map(|s| s.tenant_shard_id.shard_count)
5554 0 : .max()
5555 : else {
5556 0 : return Err(ApiError::NotFound(
5557 0 : anyhow::anyhow!("No shards found").into(),
5558 0 : ));
5559 : };
5560 :
5561 : // Ideally we would set each newly imported shard's generation independently, but for correctness it is sufficient
5562 : // to
5563 0 : let generation = scan_result
5564 0 : .shards
5565 0 : .iter()
5566 0 : .map(|s| s.generation)
5567 0 : .max()
5568 0 : .expect("We already validated >0 shards");
5569 0 :
5570 0 : // FIXME: we have no way to recover the shard stripe size from contents of remote storage: this will
5571 0 : // only work if they were using the default stripe size.
5572 0 : let stripe_size = ShardParameters::DEFAULT_STRIPE_SIZE;
5573 :
5574 0 : let (response, waiters) = self
5575 0 : .do_tenant_create(TenantCreateRequest {
5576 0 : new_tenant_id: TenantShardId::unsharded(tenant_id),
5577 0 : generation,
5578 0 :
5579 0 : shard_parameters: ShardParameters {
5580 0 : count: shard_count,
5581 0 : stripe_size,
5582 0 : },
5583 0 : placement_policy: Some(PlacementPolicy::Attached(0)), // No secondaries, for convenient debug/hacking
5584 0 : config: TenantConfig::default(),
5585 0 : })
5586 0 : .await?;
5587 :
5588 0 : if let Err(e) = self.await_waiters(waiters, SHORT_RECONCILE_TIMEOUT).await {
5589 : // Since this is a debug/support operation, all kinds of weird issues are possible (e.g. this
5590 : // tenant doesn't exist in the control plane), so don't fail the request if it can't fully
5591 : // reconcile, as reconciliation includes notifying compute.
5592 0 : tracing::warn!(%tenant_id, "Reconcile not done yet while importing tenant ({e})");
5593 0 : }
5594 :
5595 0 : Ok(response)
5596 0 : }
5597 :
5598 : /// For debug/support: a full JSON dump of TenantShards. Returns a response so that
5599 : /// we don't have to make TenantShard clonable in the return path.
5600 0 : pub(crate) fn tenants_dump(&self) -> Result<hyper::Response<hyper::Body>, ApiError> {
5601 0 : let serialized = {
5602 0 : let locked = self.inner.read().unwrap();
5603 0 : let result = locked.tenants.values().collect::<Vec<_>>();
5604 0 : serde_json::to_string(&result).map_err(|e| ApiError::InternalServerError(e.into()))?
5605 : };
5606 :
5607 0 : hyper::Response::builder()
5608 0 : .status(hyper::StatusCode::OK)
5609 0 : .header(hyper::header::CONTENT_TYPE, "application/json")
5610 0 : .body(hyper::Body::from(serialized))
5611 0 : .map_err(|e| ApiError::InternalServerError(e.into()))
5612 0 : }
5613 :
5614 : /// Check the consistency of in-memory state vs. persistent state, and check that the
5615 : /// scheduler's statistics are up to date.
5616 : ///
5617 : /// These consistency checks expect an **idle** system. If changes are going on while
5618 : /// we run, then we can falsely indicate a consistency issue. This is sufficient for end-of-test
5619 : /// checks, but not suitable for running continuously in the background in the field.
5620 0 : pub(crate) async fn consistency_check(&self) -> Result<(), ApiError> {
5621 0 : let (mut expect_nodes, mut expect_shards) = {
5622 0 : let locked = self.inner.read().unwrap();
5623 0 :
5624 0 : locked
5625 0 : .scheduler
5626 0 : .consistency_check(locked.nodes.values(), locked.tenants.values())
5627 0 : .context("Scheduler checks")
5628 0 : .map_err(ApiError::InternalServerError)?;
5629 :
5630 0 : let expect_nodes = locked
5631 0 : .nodes
5632 0 : .values()
5633 0 : .map(|n| n.to_persistent())
5634 0 : .collect::<Vec<_>>();
5635 0 :
5636 0 : let expect_shards = locked
5637 0 : .tenants
5638 0 : .values()
5639 0 : .map(|t| t.to_persistent())
5640 0 : .collect::<Vec<_>>();
5641 :
5642 : // This method can only validate the state of an idle system: if a reconcile is in
5643 : // progress, fail out early to avoid giving false errors on state that won't match
5644 : // between database and memory under a ReconcileResult is processed.
5645 0 : for t in locked.tenants.values() {
5646 0 : if t.reconciler.is_some() {
5647 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
5648 0 : "Shard {} reconciliation in progress",
5649 0 : t.tenant_shard_id
5650 0 : )));
5651 0 : }
5652 : }
5653 :
5654 0 : (expect_nodes, expect_shards)
5655 : };
5656 :
5657 0 : let mut nodes = self.persistence.list_nodes().await?;
5658 0 : expect_nodes.sort_by_key(|n| n.node_id);
5659 0 : nodes.sort_by_key(|n| n.node_id);
5660 :
5661 : // Errors relating to nodes are deferred so that we don't skip the shard checks below if we have a node error
5662 0 : let node_result = if nodes != expect_nodes {
5663 0 : tracing::error!("Consistency check failed on nodes.");
5664 0 : tracing::error!(
5665 0 : "Nodes in memory: {}",
5666 0 : serde_json::to_string(&expect_nodes)
5667 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?
5668 : );
5669 0 : tracing::error!(
5670 0 : "Nodes in database: {}",
5671 0 : serde_json::to_string(&nodes)
5672 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?
5673 : );
5674 0 : Err(ApiError::InternalServerError(anyhow::anyhow!(
5675 0 : "Node consistency failure"
5676 0 : )))
5677 : } else {
5678 0 : Ok(())
5679 : };
5680 :
5681 0 : let mut persistent_shards = self.persistence.load_active_tenant_shards().await?;
5682 0 : persistent_shards
5683 0 : .sort_by_key(|tsp| (tsp.tenant_id.clone(), tsp.shard_number, tsp.shard_count));
5684 0 :
5685 0 : expect_shards.sort_by_key(|tsp| (tsp.tenant_id.clone(), tsp.shard_number, tsp.shard_count));
5686 :
5687 : // Because JSON contents of persistent tenants might disagree with the fields in current `TenantConfig`
5688 : // definition, we will do an encode/decode cycle to ensure any legacy fields are dropped and any new
5689 : // fields are added, before doing a comparison.
5690 0 : for tsp in &mut persistent_shards {
5691 0 : let config: TenantConfig = serde_json::from_str(&tsp.config)
5692 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?;
5693 0 : tsp.config = serde_json::to_string(&config).expect("Encoding config is infallible");
5694 : }
5695 :
5696 0 : if persistent_shards != expect_shards {
5697 0 : tracing::error!("Consistency check failed on shards.");
5698 :
5699 0 : tracing::error!(
5700 0 : "Shards in memory: {}",
5701 0 : serde_json::to_string(&expect_shards)
5702 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?
5703 : );
5704 0 : tracing::error!(
5705 0 : "Shards in database: {}",
5706 0 : serde_json::to_string(&persistent_shards)
5707 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?
5708 : );
5709 :
5710 : // The total dump log lines above are useful in testing but in the field grafana will
5711 : // usually just drop them because they're so large. So we also do some explicit logging
5712 : // of just the diffs.
5713 0 : let persistent_shards = persistent_shards
5714 0 : .into_iter()
5715 0 : .map(|tsp| (tsp.get_tenant_shard_id().unwrap(), tsp))
5716 0 : .collect::<HashMap<_, _>>();
5717 0 : let expect_shards = expect_shards
5718 0 : .into_iter()
5719 0 : .map(|tsp| (tsp.get_tenant_shard_id().unwrap(), tsp))
5720 0 : .collect::<HashMap<_, _>>();
5721 0 : for (tenant_shard_id, persistent_tsp) in &persistent_shards {
5722 0 : match expect_shards.get(tenant_shard_id) {
5723 : None => {
5724 0 : tracing::error!(
5725 0 : "Shard {} found in database but not in memory",
5726 : tenant_shard_id
5727 : );
5728 : }
5729 0 : Some(expect_tsp) => {
5730 0 : if expect_tsp != persistent_tsp {
5731 0 : tracing::error!(
5732 0 : "Shard {} is inconsistent. In memory: {}, database has: {}",
5733 0 : tenant_shard_id,
5734 0 : serde_json::to_string(expect_tsp).unwrap(),
5735 0 : serde_json::to_string(&persistent_tsp).unwrap()
5736 : );
5737 0 : }
5738 : }
5739 : }
5740 : }
5741 :
5742 : // Having already logged any differences, log any shards that simply aren't present in the database
5743 0 : for (tenant_shard_id, memory_tsp) in &expect_shards {
5744 0 : if !persistent_shards.contains_key(tenant_shard_id) {
5745 0 : tracing::error!(
5746 0 : "Shard {} found in memory but not in database: {}",
5747 0 : tenant_shard_id,
5748 0 : serde_json::to_string(memory_tsp)
5749 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?
5750 : );
5751 0 : }
5752 : }
5753 :
5754 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
5755 0 : "Shard consistency failure"
5756 0 : )));
5757 0 : }
5758 0 :
5759 0 : node_result
5760 0 : }
5761 :
5762 : /// For debug/support: a JSON dump of the [`Scheduler`]. Returns a response so that
5763 : /// we don't have to make TenantShard clonable in the return path.
5764 0 : pub(crate) fn scheduler_dump(&self) -> Result<hyper::Response<hyper::Body>, ApiError> {
5765 0 : let serialized = {
5766 0 : let locked = self.inner.read().unwrap();
5767 0 : serde_json::to_string(&locked.scheduler)
5768 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?
5769 : };
5770 :
5771 0 : hyper::Response::builder()
5772 0 : .status(hyper::StatusCode::OK)
5773 0 : .header(hyper::header::CONTENT_TYPE, "application/json")
5774 0 : .body(hyper::Body::from(serialized))
5775 0 : .map_err(|e| ApiError::InternalServerError(e.into()))
5776 0 : }
5777 :
5778 : /// This is for debug/support only: we simply drop all state for a tenant, without
5779 : /// detaching or deleting it on pageservers. We do not try and re-schedule any
5780 : /// tenants that were on this node.
5781 0 : pub(crate) async fn node_drop(&self, node_id: NodeId) -> Result<(), ApiError> {
5782 0 : self.persistence.delete_node(node_id).await?;
5783 :
5784 0 : let mut locked = self.inner.write().unwrap();
5785 :
5786 0 : for shard in locked.tenants.values_mut() {
5787 0 : shard.deref_node(node_id);
5788 0 : shard.observed.locations.remove(&node_id);
5789 0 : }
5790 :
5791 0 : let mut nodes = (*locked.nodes).clone();
5792 0 : nodes.remove(&node_id);
5793 0 : locked.nodes = Arc::new(nodes);
5794 0 : metrics::METRICS_REGISTRY
5795 0 : .metrics_group
5796 0 : .storage_controller_pageserver_nodes
5797 0 : .set(locked.nodes.len() as i64);
5798 0 :
5799 0 : locked.scheduler.node_remove(node_id);
5800 0 :
5801 0 : Ok(())
5802 0 : }
5803 :
5804 : /// If a node has any work on it, it will be rescheduled: this is "clean" in the sense
5805 : /// that we don't leave any bad state behind in the storage controller, but unclean
5806 : /// in the sense that we are not carefully draining the node.
5807 0 : pub(crate) async fn node_delete(&self, node_id: NodeId) -> Result<(), ApiError> {
5808 0 : let _node_lock =
5809 0 : trace_exclusive_lock(&self.node_op_locks, node_id, NodeOperations::Delete).await;
5810 :
5811 : // 1. Atomically update in-memory state:
5812 : // - set the scheduling state to Pause to make subsequent scheduling ops skip it
5813 : // - update shards' intents to exclude the node, and reschedule any shards whose intents we modified.
5814 : // - drop the node from the main nodes map, so that when running reconciles complete they do not
5815 : // re-insert references to this node into the ObservedState of shards
5816 : // - drop the node from the scheduler
5817 : {
5818 0 : let mut locked = self.inner.write().unwrap();
5819 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
5820 0 :
5821 0 : {
5822 0 : let mut nodes_mut = (*nodes).deref().clone();
5823 0 : match nodes_mut.get_mut(&node_id) {
5824 0 : Some(node) => {
5825 0 : // We do not bother setting this in the database, because we're about to delete the row anyway, and
5826 0 : // if we crash it would not be desirable to leave the node paused after a restart.
5827 0 : node.set_scheduling(NodeSchedulingPolicy::Pause);
5828 0 : }
5829 : None => {
5830 0 : tracing::info!(
5831 0 : "Node not found: presuming this is a retry and returning success"
5832 : );
5833 0 : return Ok(());
5834 : }
5835 : }
5836 :
5837 0 : *nodes = Arc::new(nodes_mut);
5838 : }
5839 :
5840 0 : for (_tenant_id, mut schedule_context, shards) in
5841 0 : TenantShardContextIterator::new(tenants, ScheduleMode::Normal)
5842 : {
5843 0 : for shard in shards {
5844 0 : if shard.deref_node(node_id) {
5845 0 : if let Err(e) = shard.schedule(scheduler, &mut schedule_context) {
5846 : // TODO: implement force flag to remove a node even if we can't reschedule
5847 : // a tenant
5848 0 : tracing::error!(
5849 0 : "Refusing to delete node, shard {} can't be rescheduled: {e}",
5850 : shard.tenant_shard_id
5851 : );
5852 0 : return Err(e.into());
5853 : } else {
5854 0 : tracing::info!(
5855 0 : "Rescheduled shard {} away from node during deletion",
5856 : shard.tenant_shard_id
5857 : )
5858 : }
5859 :
5860 0 : self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::Normal);
5861 0 : }
5862 :
5863 : // Here we remove an existing observed location for the node we're removing, and it will
5864 : // not be re-added by a reconciler's completion because we filter out removed nodes in
5865 : // process_result.
5866 : //
5867 : // Note that we update the shard's observed state _after_ calling maybe_reconcile_shard: that
5868 : // means any reconciles we spawned will know about the node we're deleting, enabling them
5869 : // to do live migrations if it's still online.
5870 0 : shard.observed.locations.remove(&node_id);
5871 : }
5872 : }
5873 :
5874 0 : scheduler.node_remove(node_id);
5875 0 :
5876 0 : {
5877 0 : let mut nodes_mut = (**nodes).clone();
5878 0 : if let Some(mut removed_node) = nodes_mut.remove(&node_id) {
5879 0 : // Ensure that any reconciler holding an Arc<> to this node will
5880 0 : // drop out when trying to RPC to it (setting Offline state sets the
5881 0 : // cancellation token on the Node object).
5882 0 : removed_node.set_availability(NodeAvailability::Offline);
5883 0 : }
5884 0 : *nodes = Arc::new(nodes_mut);
5885 0 : metrics::METRICS_REGISTRY
5886 0 : .metrics_group
5887 0 : .storage_controller_pageserver_nodes
5888 0 : .set(nodes.len() as i64);
5889 0 : }
5890 0 : }
5891 0 :
5892 0 : // Note: some `generation_pageserver` columns on tenant shards in the database may still refer to
5893 0 : // the removed node, as this column means "The pageserver to which this generation was issued", and
5894 0 : // their generations won't get updated until the reconcilers moving them away from this node complete.
5895 0 : // That is safe because in Service::spawn we only use generation_pageserver if it refers to a node
5896 0 : // that exists.
5897 0 :
5898 0 : // 2. Actually delete the node from the database and from in-memory state
5899 0 : tracing::info!("Deleting node from database");
5900 0 : self.persistence.delete_node(node_id).await?;
5901 :
5902 0 : Ok(())
5903 0 : }
5904 :
5905 0 : pub(crate) async fn node_list(&self) -> Result<Vec<Node>, ApiError> {
5906 0 : let nodes = {
5907 0 : self.inner
5908 0 : .read()
5909 0 : .unwrap()
5910 0 : .nodes
5911 0 : .values()
5912 0 : .cloned()
5913 0 : .collect::<Vec<_>>()
5914 0 : };
5915 0 :
5916 0 : Ok(nodes)
5917 0 : }
5918 :
5919 0 : pub(crate) async fn get_node(&self, node_id: NodeId) -> Result<Node, ApiError> {
5920 0 : self.inner
5921 0 : .read()
5922 0 : .unwrap()
5923 0 : .nodes
5924 0 : .get(&node_id)
5925 0 : .cloned()
5926 0 : .ok_or(ApiError::NotFound(
5927 0 : format!("Node {node_id} not registered").into(),
5928 0 : ))
5929 0 : }
5930 :
5931 0 : pub(crate) async fn get_node_shards(
5932 0 : &self,
5933 0 : node_id: NodeId,
5934 0 : ) -> Result<NodeShardResponse, ApiError> {
5935 0 : let locked = self.inner.read().unwrap();
5936 0 : let mut shards = Vec::new();
5937 0 : for (tid, tenant) in locked.tenants.iter() {
5938 0 : let is_intended_secondary = match (
5939 0 : tenant.intent.get_attached() == &Some(node_id),
5940 0 : tenant.intent.get_secondary().contains(&node_id),
5941 0 : ) {
5942 : (true, true) => {
5943 0 : return Err(ApiError::InternalServerError(anyhow::anyhow!(
5944 0 : "{} attached as primary+secondary on the same node",
5945 0 : tid
5946 0 : )));
5947 : }
5948 0 : (true, false) => Some(false),
5949 0 : (false, true) => Some(true),
5950 0 : (false, false) => None,
5951 : };
5952 0 : let is_observed_secondary = if let Some(ObservedStateLocation { conf: Some(conf) }) =
5953 0 : tenant.observed.locations.get(&node_id)
5954 : {
5955 0 : Some(conf.secondary_conf.is_some())
5956 : } else {
5957 0 : None
5958 : };
5959 0 : if is_intended_secondary.is_some() || is_observed_secondary.is_some() {
5960 0 : shards.push(NodeShard {
5961 0 : tenant_shard_id: *tid,
5962 0 : is_intended_secondary,
5963 0 : is_observed_secondary,
5964 0 : });
5965 0 : }
5966 : }
5967 0 : Ok(NodeShardResponse { node_id, shards })
5968 0 : }
5969 :
5970 0 : pub(crate) async fn get_leader(&self) -> DatabaseResult<Option<ControllerPersistence>> {
5971 0 : self.persistence.get_leader().await
5972 0 : }
5973 :
5974 0 : pub(crate) async fn node_register(
5975 0 : &self,
5976 0 : register_req: NodeRegisterRequest,
5977 0 : ) -> Result<(), ApiError> {
5978 0 : let _node_lock = trace_exclusive_lock(
5979 0 : &self.node_op_locks,
5980 0 : register_req.node_id,
5981 0 : NodeOperations::Register,
5982 0 : )
5983 0 : .await;
5984 :
5985 : #[derive(PartialEq)]
5986 : enum RegistrationStatus {
5987 : UpToDate,
5988 : NeedUpdate,
5989 : Mismatched,
5990 : New,
5991 : }
5992 :
5993 0 : let registration_status = {
5994 0 : let locked = self.inner.read().unwrap();
5995 0 : if let Some(node) = locked.nodes.get(®ister_req.node_id) {
5996 0 : if node.registration_match(®ister_req) {
5997 0 : if node.need_update(®ister_req) {
5998 0 : RegistrationStatus::NeedUpdate
5999 : } else {
6000 0 : RegistrationStatus::UpToDate
6001 : }
6002 : } else {
6003 0 : RegistrationStatus::Mismatched
6004 : }
6005 : } else {
6006 0 : RegistrationStatus::New
6007 : }
6008 : };
6009 :
6010 0 : match registration_status {
6011 : RegistrationStatus::UpToDate => {
6012 0 : tracing::info!(
6013 0 : "Node {} re-registered with matching address and is up to date",
6014 : register_req.node_id
6015 : );
6016 :
6017 0 : return Ok(());
6018 : }
6019 : RegistrationStatus::Mismatched => {
6020 : // TODO: decide if we want to allow modifying node addresses without removing and re-adding
6021 : // the node. Safest/simplest thing is to refuse it, and usually we deploy with
6022 : // a fixed address through the lifetime of a node.
6023 0 : tracing::warn!(
6024 0 : "Node {} tried to register with different address",
6025 : register_req.node_id
6026 : );
6027 0 : return Err(ApiError::Conflict(
6028 0 : "Node is already registered with different address".to_string(),
6029 0 : ));
6030 : }
6031 0 : RegistrationStatus::New | RegistrationStatus::NeedUpdate => {
6032 0 : // fallthrough
6033 0 : }
6034 0 : }
6035 0 :
6036 0 : // We do not require that a node is actually online when registered (it will start life
6037 0 : // with it's availability set to Offline), but we _do_ require that its DNS record exists. We're
6038 0 : // therefore not immune to asymmetric L3 connectivity issues, but we are protected against nodes
6039 0 : // that register themselves with a broken DNS config. We check only the HTTP hostname, because
6040 0 : // the postgres hostname might only be resolvable to clients (e.g. if we're on a different VPC than clients).
6041 0 : if tokio::net::lookup_host(format!(
6042 0 : "{}:{}",
6043 0 : register_req.listen_http_addr, register_req.listen_http_port
6044 0 : ))
6045 0 : .await
6046 0 : .is_err()
6047 : {
6048 : // If we have a transient DNS issue, it's up to the caller to retry their registration. Because
6049 : // we can't robustly distinguish between an intermittent issue and a totally bogus DNS situation,
6050 : // we return a soft 503 error, to encourage callers to retry past transient issues.
6051 0 : return Err(ApiError::ResourceUnavailable(
6052 0 : format!(
6053 0 : "Node {} tried to register with unknown DNS name '{}'",
6054 0 : register_req.node_id, register_req.listen_http_addr
6055 0 : )
6056 0 : .into(),
6057 0 : ));
6058 0 : }
6059 0 :
6060 0 : if self.config.use_https_pageserver_api && register_req.listen_https_port.is_none() {
6061 0 : return Err(ApiError::PreconditionFailed(
6062 0 : format!(
6063 0 : "Node {} has no https port, but use_https is enabled",
6064 0 : register_req.node_id
6065 0 : )
6066 0 : .into(),
6067 0 : ));
6068 0 : }
6069 0 :
6070 0 : // Ordering: we must persist the new node _before_ adding it to in-memory state.
6071 0 : // This ensures that before we use it for anything or expose it via any external
6072 0 : // API, it is guaranteed to be available after a restart.
6073 0 : let new_node = Node::new(
6074 0 : register_req.node_id,
6075 0 : register_req.listen_http_addr,
6076 0 : register_req.listen_http_port,
6077 0 : register_req.listen_https_port,
6078 0 : register_req.listen_pg_addr,
6079 0 : register_req.listen_pg_port,
6080 0 : register_req.availability_zone_id.clone(),
6081 0 : self.config.use_https_pageserver_api,
6082 0 : );
6083 0 : let new_node = match new_node {
6084 0 : Ok(new_node) => new_node,
6085 0 : Err(error) => return Err(ApiError::InternalServerError(error)),
6086 : };
6087 :
6088 0 : match registration_status {
6089 0 : RegistrationStatus::New => self.persistence.insert_node(&new_node).await?,
6090 : RegistrationStatus::NeedUpdate => {
6091 0 : self.persistence
6092 0 : .update_node_on_registration(
6093 0 : register_req.node_id,
6094 0 : register_req.listen_https_port,
6095 0 : )
6096 0 : .await?
6097 : }
6098 0 : _ => unreachable!("Other statuses have been processed earlier"),
6099 : }
6100 :
6101 0 : let mut locked = self.inner.write().unwrap();
6102 0 : let mut new_nodes = (*locked.nodes).clone();
6103 0 :
6104 0 : locked.scheduler.node_upsert(&new_node);
6105 0 : new_nodes.insert(register_req.node_id, new_node);
6106 0 :
6107 0 : locked.nodes = Arc::new(new_nodes);
6108 0 :
6109 0 : metrics::METRICS_REGISTRY
6110 0 : .metrics_group
6111 0 : .storage_controller_pageserver_nodes
6112 0 : .set(locked.nodes.len() as i64);
6113 0 :
6114 0 : match registration_status {
6115 : RegistrationStatus::New => {
6116 0 : tracing::info!(
6117 0 : "Registered pageserver {} ({}), now have {} pageservers",
6118 0 : register_req.node_id,
6119 0 : register_req.availability_zone_id,
6120 0 : locked.nodes.len()
6121 : );
6122 : }
6123 : RegistrationStatus::NeedUpdate => {
6124 0 : tracing::info!(
6125 0 : "Re-registered and updated node {} ({})",
6126 : register_req.node_id,
6127 : register_req.availability_zone_id,
6128 : );
6129 : }
6130 0 : _ => unreachable!("Other statuses have been processed earlier"),
6131 : }
6132 0 : Ok(())
6133 0 : }
6134 :
6135 : /// Configure in-memory and persistent state of a node as requested
6136 : ///
6137 : /// Note that this function does not trigger any immediate side effects in response
6138 : /// to the changes. That part is handled by [`Self::handle_node_availability_transition`].
6139 0 : async fn node_state_configure(
6140 0 : &self,
6141 0 : node_id: NodeId,
6142 0 : availability: Option<NodeAvailability>,
6143 0 : scheduling: Option<NodeSchedulingPolicy>,
6144 0 : node_lock: &TracingExclusiveGuard<NodeOperations>,
6145 0 : ) -> Result<AvailabilityTransition, ApiError> {
6146 0 : if let Some(scheduling) = scheduling {
6147 : // Scheduling is a persistent part of Node: we must write updates to the database before
6148 : // applying them in memory
6149 0 : self.persistence
6150 0 : .update_node_scheduling_policy(node_id, scheduling)
6151 0 : .await?;
6152 0 : }
6153 :
6154 : // If we're activating a node, then before setting it active we must reconcile any shard locations
6155 : // on that node, in case it is out of sync, e.g. due to being unavailable during controller startup,
6156 : // by calling [`Self::node_activate_reconcile`]
6157 : //
6158 : // The transition we calculate here remains valid later in the function because we hold the op lock on the node:
6159 : // nothing else can mutate its availability while we run.
6160 0 : let availability_transition = if let Some(input_availability) = availability.as_ref() {
6161 0 : let (activate_node, availability_transition) = {
6162 0 : let locked = self.inner.read().unwrap();
6163 0 : let Some(node) = locked.nodes.get(&node_id) else {
6164 0 : return Err(ApiError::NotFound(
6165 0 : anyhow::anyhow!("Node {} not registered", node_id).into(),
6166 0 : ));
6167 : };
6168 :
6169 0 : (
6170 0 : node.clone(),
6171 0 : node.get_availability_transition(input_availability),
6172 0 : )
6173 : };
6174 :
6175 0 : if matches!(availability_transition, AvailabilityTransition::ToActive) {
6176 0 : self.node_activate_reconcile(activate_node, node_lock)
6177 0 : .await?;
6178 0 : }
6179 0 : availability_transition
6180 : } else {
6181 0 : AvailabilityTransition::Unchanged
6182 : };
6183 :
6184 : // Apply changes from the request to our in-memory state for the Node
6185 0 : let mut locked = self.inner.write().unwrap();
6186 0 : let (nodes, _tenants, scheduler) = locked.parts_mut();
6187 0 :
6188 0 : let mut new_nodes = (**nodes).clone();
6189 :
6190 0 : let Some(node) = new_nodes.get_mut(&node_id) else {
6191 0 : return Err(ApiError::NotFound(
6192 0 : anyhow::anyhow!("Node not registered").into(),
6193 0 : ));
6194 : };
6195 :
6196 0 : if let Some(availability) = availability {
6197 0 : node.set_availability(availability);
6198 0 : }
6199 :
6200 0 : if let Some(scheduling) = scheduling {
6201 0 : node.set_scheduling(scheduling);
6202 0 : }
6203 :
6204 : // Update the scheduler, in case the elegibility of the node for new shards has changed
6205 0 : scheduler.node_upsert(node);
6206 0 :
6207 0 : let new_nodes = Arc::new(new_nodes);
6208 0 : locked.nodes = new_nodes;
6209 0 :
6210 0 : Ok(availability_transition)
6211 0 : }
6212 :
6213 : /// Handle availability transition of one node
6214 : ///
6215 : /// Note that you should first call [`Self::node_state_configure`] to update
6216 : /// the in-memory state referencing that node. If you need to handle more than one transition
6217 : /// consider using [`Self::handle_node_availability_transitions`].
6218 0 : async fn handle_node_availability_transition(
6219 0 : &self,
6220 0 : node_id: NodeId,
6221 0 : transition: AvailabilityTransition,
6222 0 : _node_lock: &TracingExclusiveGuard<NodeOperations>,
6223 0 : ) -> Result<(), ApiError> {
6224 0 : // Modify scheduling state for any Tenants that are affected by a change in the node's availability state.
6225 0 : match transition {
6226 : AvailabilityTransition::ToOffline => {
6227 0 : tracing::info!("Node {} transition to offline", node_id);
6228 :
6229 0 : let mut locked = self.inner.write().unwrap();
6230 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
6231 0 :
6232 0 : let mut tenants_affected: usize = 0;
6233 :
6234 0 : for (_tenant_id, mut schedule_context, shards) in
6235 0 : TenantShardContextIterator::new(tenants, ScheduleMode::Normal)
6236 : {
6237 0 : for tenant_shard in shards {
6238 0 : let tenant_shard_id = tenant_shard.tenant_shard_id;
6239 0 : if let Some(observed_loc) =
6240 0 : tenant_shard.observed.locations.get_mut(&node_id)
6241 0 : {
6242 0 : // When a node goes offline, we set its observed configuration to None, indicating unknown: we will
6243 0 : // not assume our knowledge of the node's configuration is accurate until it comes back online
6244 0 : observed_loc.conf = None;
6245 0 : }
6246 :
6247 0 : if nodes.len() == 1 {
6248 : // Special case for single-node cluster: there is no point trying to reschedule
6249 : // any tenant shards: avoid doing so, in order to avoid spewing warnings about
6250 : // failures to schedule them.
6251 0 : continue;
6252 0 : }
6253 0 :
6254 0 : if !nodes
6255 0 : .values()
6256 0 : .any(|n| matches!(n.may_schedule(), MaySchedule::Yes(_)))
6257 : {
6258 : // Special case for when all nodes are unavailable and/or unschedulable: there is no point
6259 : // trying to reschedule since there's nowhere else to go. Without this
6260 : // branch we incorrectly detach tenants in response to node unavailability.
6261 0 : continue;
6262 0 : }
6263 0 :
6264 0 : if tenant_shard.intent.demote_attached(scheduler, node_id) {
6265 0 : tenant_shard.sequence = tenant_shard.sequence.next();
6266 0 :
6267 0 : match tenant_shard.schedule(scheduler, &mut schedule_context) {
6268 0 : Err(e) => {
6269 0 : // It is possible that some tenants will become unschedulable when too many pageservers
6270 0 : // go offline: in this case there isn't much we can do other than make the issue observable.
6271 0 : // TODO: give TenantShard a scheduling error attribute to be queried later.
6272 0 : tracing::warn!(%tenant_shard_id, "Scheduling error when marking pageserver {} offline: {e}", node_id);
6273 : }
6274 : Ok(()) => {
6275 0 : if self
6276 0 : .maybe_reconcile_shard(
6277 0 : tenant_shard,
6278 0 : nodes,
6279 0 : ReconcilerPriority::Normal,
6280 0 : )
6281 0 : .is_some()
6282 0 : {
6283 0 : tenants_affected += 1;
6284 0 : };
6285 : }
6286 : }
6287 0 : }
6288 : }
6289 : }
6290 0 : tracing::info!(
6291 0 : "Launched {} reconciler tasks for tenants affected by node {} going offline",
6292 : tenants_affected,
6293 : node_id
6294 : )
6295 : }
6296 : AvailabilityTransition::ToActive => {
6297 0 : tracing::info!("Node {} transition to active", node_id);
6298 :
6299 0 : let mut locked = self.inner.write().unwrap();
6300 0 : let (nodes, tenants, _scheduler) = locked.parts_mut();
6301 :
6302 : // When a node comes back online, we must reconcile any tenant that has a None observed
6303 : // location on the node.
6304 0 : for tenant_shard in tenants.values_mut() {
6305 : // If a reconciliation is already in progress, rely on the previous scheduling
6306 : // decision and skip triggering a new reconciliation.
6307 0 : if tenant_shard.reconciler.is_some() {
6308 0 : continue;
6309 0 : }
6310 :
6311 0 : if let Some(observed_loc) = tenant_shard.observed.locations.get_mut(&node_id) {
6312 0 : if observed_loc.conf.is_none() {
6313 0 : self.maybe_reconcile_shard(
6314 0 : tenant_shard,
6315 0 : nodes,
6316 0 : ReconcilerPriority::Normal,
6317 0 : );
6318 0 : }
6319 0 : }
6320 : }
6321 :
6322 : // TODO: in the background, we should balance work back onto this pageserver
6323 : }
6324 : // No action required for the intermediate unavailable state.
6325 : // When we transition into active or offline from the unavailable state,
6326 : // the correct handling above will kick in.
6327 : AvailabilityTransition::ToWarmingUpFromActive => {
6328 0 : tracing::info!("Node {} transition to unavailable from active", node_id);
6329 : }
6330 : AvailabilityTransition::ToWarmingUpFromOffline => {
6331 0 : tracing::info!("Node {} transition to unavailable from offline", node_id);
6332 : }
6333 : AvailabilityTransition::Unchanged => {
6334 0 : tracing::debug!("Node {} no availability change during config", node_id);
6335 : }
6336 : }
6337 :
6338 0 : Ok(())
6339 0 : }
6340 :
6341 : /// Handle availability transition for multiple nodes
6342 : ///
6343 : /// Note that you should first call [`Self::node_state_configure`] for
6344 : /// all nodes being handled here for the handling to use fresh in-memory state.
6345 0 : async fn handle_node_availability_transitions(
6346 0 : &self,
6347 0 : transitions: Vec<(
6348 0 : NodeId,
6349 0 : TracingExclusiveGuard<NodeOperations>,
6350 0 : AvailabilityTransition,
6351 0 : )>,
6352 0 : ) -> Result<(), Vec<(NodeId, ApiError)>> {
6353 0 : let mut errors = Vec::default();
6354 0 : for (node_id, node_lock, transition) in transitions {
6355 0 : let res = self
6356 0 : .handle_node_availability_transition(node_id, transition, &node_lock)
6357 0 : .await;
6358 0 : if let Err(err) = res {
6359 0 : errors.push((node_id, err));
6360 0 : }
6361 : }
6362 :
6363 0 : if errors.is_empty() {
6364 0 : Ok(())
6365 : } else {
6366 0 : Err(errors)
6367 : }
6368 0 : }
6369 :
6370 0 : pub(crate) async fn node_configure(
6371 0 : &self,
6372 0 : node_id: NodeId,
6373 0 : availability: Option<NodeAvailability>,
6374 0 : scheduling: Option<NodeSchedulingPolicy>,
6375 0 : ) -> Result<(), ApiError> {
6376 0 : let node_lock =
6377 0 : trace_exclusive_lock(&self.node_op_locks, node_id, NodeOperations::Configure).await;
6378 :
6379 0 : let transition = self
6380 0 : .node_state_configure(node_id, availability, scheduling, &node_lock)
6381 0 : .await?;
6382 0 : self.handle_node_availability_transition(node_id, transition, &node_lock)
6383 0 : .await
6384 0 : }
6385 :
6386 : /// Wrapper around [`Self::node_configure`] which only allows changes while there is no ongoing
6387 : /// operation for HTTP api.
6388 0 : pub(crate) async fn external_node_configure(
6389 0 : &self,
6390 0 : node_id: NodeId,
6391 0 : availability: Option<NodeAvailability>,
6392 0 : scheduling: Option<NodeSchedulingPolicy>,
6393 0 : ) -> Result<(), ApiError> {
6394 0 : {
6395 0 : let locked = self.inner.read().unwrap();
6396 0 : if let Some(op) = locked.ongoing_operation.as_ref().map(|op| op.operation) {
6397 0 : return Err(ApiError::PreconditionFailed(
6398 0 : format!("Ongoing background operation forbids configuring: {op}").into(),
6399 0 : ));
6400 0 : }
6401 0 : }
6402 0 :
6403 0 : self.node_configure(node_id, availability, scheduling).await
6404 0 : }
6405 :
6406 0 : pub(crate) async fn start_node_drain(
6407 0 : self: &Arc<Self>,
6408 0 : node_id: NodeId,
6409 0 : ) -> Result<(), ApiError> {
6410 0 : let (ongoing_op, node_available, node_policy, schedulable_nodes_count) = {
6411 0 : let locked = self.inner.read().unwrap();
6412 0 : let nodes = &locked.nodes;
6413 0 : let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
6414 0 : anyhow::anyhow!("Node {} not registered", node_id).into(),
6415 0 : ))?;
6416 0 : let schedulable_nodes_count = nodes
6417 0 : .iter()
6418 0 : .filter(|(_, n)| matches!(n.may_schedule(), MaySchedule::Yes(_)))
6419 0 : .count();
6420 0 :
6421 0 : (
6422 0 : locked
6423 0 : .ongoing_operation
6424 0 : .as_ref()
6425 0 : .map(|ongoing| ongoing.operation),
6426 0 : node.is_available(),
6427 0 : node.get_scheduling(),
6428 0 : schedulable_nodes_count,
6429 0 : )
6430 0 : };
6431 :
6432 0 : if let Some(ongoing) = ongoing_op {
6433 0 : return Err(ApiError::PreconditionFailed(
6434 0 : format!("Background operation already ongoing for node: {}", ongoing).into(),
6435 0 : ));
6436 0 : }
6437 0 :
6438 0 : if !node_available {
6439 0 : return Err(ApiError::ResourceUnavailable(
6440 0 : format!("Node {node_id} is currently unavailable").into(),
6441 0 : ));
6442 0 : }
6443 0 :
6444 0 : if schedulable_nodes_count == 0 {
6445 0 : return Err(ApiError::PreconditionFailed(
6446 0 : "No other schedulable nodes to drain to".into(),
6447 0 : ));
6448 0 : }
6449 0 :
6450 0 : match node_policy {
6451 : NodeSchedulingPolicy::Active => {
6452 0 : self.node_configure(node_id, None, Some(NodeSchedulingPolicy::Draining))
6453 0 : .await?;
6454 :
6455 0 : let cancel = self.cancel.child_token();
6456 0 : let gate_guard = self.gate.enter().map_err(|_| ApiError::ShuttingDown)?;
6457 :
6458 0 : self.inner.write().unwrap().ongoing_operation = Some(OperationHandler {
6459 0 : operation: Operation::Drain(Drain { node_id }),
6460 0 : cancel: cancel.clone(),
6461 0 : });
6462 :
6463 0 : let span = tracing::info_span!(parent: None, "drain_node", %node_id);
6464 :
6465 0 : tokio::task::spawn({
6466 0 : let service = self.clone();
6467 0 : let cancel = cancel.clone();
6468 0 : async move {
6469 0 : let _gate_guard = gate_guard;
6470 0 :
6471 0 : scopeguard::defer! {
6472 0 : let prev = service.inner.write().unwrap().ongoing_operation.take();
6473 0 :
6474 0 : if let Some(Operation::Drain(removed_drain)) = prev.map(|h| h.operation) {
6475 0 : assert_eq!(removed_drain.node_id, node_id, "We always take the same operation");
6476 0 : } else {
6477 0 : panic!("We always remove the same operation")
6478 0 : }
6479 0 : }
6480 0 :
6481 0 : tracing::info!("Drain background operation starting");
6482 0 : let res = service.drain_node(node_id, cancel).await;
6483 0 : match res {
6484 : Ok(()) => {
6485 0 : tracing::info!("Drain background operation completed successfully");
6486 : }
6487 : Err(OperationError::Cancelled) => {
6488 0 : tracing::info!("Drain background operation was cancelled");
6489 : }
6490 0 : Err(err) => {
6491 0 : tracing::error!("Drain background operation encountered: {err}")
6492 : }
6493 : }
6494 0 : }
6495 0 : }.instrument(span));
6496 0 : }
6497 : NodeSchedulingPolicy::Draining => {
6498 0 : return Err(ApiError::Conflict(format!(
6499 0 : "Node {node_id} has drain in progress"
6500 0 : )));
6501 : }
6502 0 : policy => {
6503 0 : return Err(ApiError::PreconditionFailed(
6504 0 : format!("Node {node_id} cannot be drained due to {policy:?} policy").into(),
6505 0 : ));
6506 : }
6507 : }
6508 :
6509 0 : Ok(())
6510 0 : }
6511 :
6512 0 : pub(crate) async fn cancel_node_drain(&self, node_id: NodeId) -> Result<(), ApiError> {
6513 0 : let node_available = {
6514 0 : let locked = self.inner.read().unwrap();
6515 0 : let nodes = &locked.nodes;
6516 0 : let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
6517 0 : anyhow::anyhow!("Node {} not registered", node_id).into(),
6518 0 : ))?;
6519 :
6520 0 : node.is_available()
6521 0 : };
6522 0 :
6523 0 : if !node_available {
6524 0 : return Err(ApiError::ResourceUnavailable(
6525 0 : format!("Node {node_id} is currently unavailable").into(),
6526 0 : ));
6527 0 : }
6528 :
6529 0 : if let Some(op_handler) = self.inner.read().unwrap().ongoing_operation.as_ref() {
6530 0 : if let Operation::Drain(drain) = op_handler.operation {
6531 0 : if drain.node_id == node_id {
6532 0 : tracing::info!("Cancelling background drain operation for node {node_id}");
6533 0 : op_handler.cancel.cancel();
6534 0 : return Ok(());
6535 0 : }
6536 0 : }
6537 0 : }
6538 :
6539 0 : Err(ApiError::PreconditionFailed(
6540 0 : format!("Node {node_id} has no drain in progress").into(),
6541 0 : ))
6542 0 : }
6543 :
6544 0 : pub(crate) async fn start_node_fill(self: &Arc<Self>, node_id: NodeId) -> Result<(), ApiError> {
6545 0 : let (ongoing_op, node_available, node_policy, total_nodes_count) = {
6546 0 : let locked = self.inner.read().unwrap();
6547 0 : let nodes = &locked.nodes;
6548 0 : let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
6549 0 : anyhow::anyhow!("Node {} not registered", node_id).into(),
6550 0 : ))?;
6551 :
6552 0 : (
6553 0 : locked
6554 0 : .ongoing_operation
6555 0 : .as_ref()
6556 0 : .map(|ongoing| ongoing.operation),
6557 0 : node.is_available(),
6558 0 : node.get_scheduling(),
6559 0 : nodes.len(),
6560 0 : )
6561 0 : };
6562 :
6563 0 : if let Some(ongoing) = ongoing_op {
6564 0 : return Err(ApiError::PreconditionFailed(
6565 0 : format!("Background operation already ongoing for node: {}", ongoing).into(),
6566 0 : ));
6567 0 : }
6568 0 :
6569 0 : if !node_available {
6570 0 : return Err(ApiError::ResourceUnavailable(
6571 0 : format!("Node {node_id} is currently unavailable").into(),
6572 0 : ));
6573 0 : }
6574 0 :
6575 0 : if total_nodes_count <= 1 {
6576 0 : return Err(ApiError::PreconditionFailed(
6577 0 : "No other nodes to fill from".into(),
6578 0 : ));
6579 0 : }
6580 0 :
6581 0 : match node_policy {
6582 : NodeSchedulingPolicy::Active => {
6583 0 : self.node_configure(node_id, None, Some(NodeSchedulingPolicy::Filling))
6584 0 : .await?;
6585 :
6586 0 : let cancel = self.cancel.child_token();
6587 0 : let gate_guard = self.gate.enter().map_err(|_| ApiError::ShuttingDown)?;
6588 :
6589 0 : self.inner.write().unwrap().ongoing_operation = Some(OperationHandler {
6590 0 : operation: Operation::Fill(Fill { node_id }),
6591 0 : cancel: cancel.clone(),
6592 0 : });
6593 :
6594 0 : let span = tracing::info_span!(parent: None, "fill_node", %node_id);
6595 :
6596 0 : tokio::task::spawn({
6597 0 : let service = self.clone();
6598 0 : let cancel = cancel.clone();
6599 0 : async move {
6600 0 : let _gate_guard = gate_guard;
6601 0 :
6602 0 : scopeguard::defer! {
6603 0 : let prev = service.inner.write().unwrap().ongoing_operation.take();
6604 0 :
6605 0 : if let Some(Operation::Fill(removed_fill)) = prev.map(|h| h.operation) {
6606 0 : assert_eq!(removed_fill.node_id, node_id, "We always take the same operation");
6607 0 : } else {
6608 0 : panic!("We always remove the same operation")
6609 0 : }
6610 0 : }
6611 0 :
6612 0 : tracing::info!("Fill background operation starting");
6613 0 : let res = service.fill_node(node_id, cancel).await;
6614 0 : match res {
6615 : Ok(()) => {
6616 0 : tracing::info!("Fill background operation completed successfully");
6617 : }
6618 : Err(OperationError::Cancelled) => {
6619 0 : tracing::info!("Fill background operation was cancelled");
6620 : }
6621 0 : Err(err) => {
6622 0 : tracing::error!("Fill background operation encountered: {err}")
6623 : }
6624 : }
6625 0 : }
6626 0 : }.instrument(span));
6627 0 : }
6628 : NodeSchedulingPolicy::Filling => {
6629 0 : return Err(ApiError::Conflict(format!(
6630 0 : "Node {node_id} has fill in progress"
6631 0 : )));
6632 : }
6633 0 : policy => {
6634 0 : return Err(ApiError::PreconditionFailed(
6635 0 : format!("Node {node_id} cannot be filled due to {policy:?} policy").into(),
6636 0 : ));
6637 : }
6638 : }
6639 :
6640 0 : Ok(())
6641 0 : }
6642 :
6643 0 : pub(crate) async fn cancel_node_fill(&self, node_id: NodeId) -> Result<(), ApiError> {
6644 0 : let node_available = {
6645 0 : let locked = self.inner.read().unwrap();
6646 0 : let nodes = &locked.nodes;
6647 0 : let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
6648 0 : anyhow::anyhow!("Node {} not registered", node_id).into(),
6649 0 : ))?;
6650 :
6651 0 : node.is_available()
6652 0 : };
6653 0 :
6654 0 : if !node_available {
6655 0 : return Err(ApiError::ResourceUnavailable(
6656 0 : format!("Node {node_id} is currently unavailable").into(),
6657 0 : ));
6658 0 : }
6659 :
6660 0 : if let Some(op_handler) = self.inner.read().unwrap().ongoing_operation.as_ref() {
6661 0 : if let Operation::Fill(fill) = op_handler.operation {
6662 0 : if fill.node_id == node_id {
6663 0 : tracing::info!("Cancelling background drain operation for node {node_id}");
6664 0 : op_handler.cancel.cancel();
6665 0 : return Ok(());
6666 0 : }
6667 0 : }
6668 0 : }
6669 :
6670 0 : Err(ApiError::PreconditionFailed(
6671 0 : format!("Node {node_id} has no fill in progress").into(),
6672 0 : ))
6673 0 : }
6674 :
6675 : /// Like [`Self::maybe_configured_reconcile_shard`], but uses the default reconciler
6676 : /// configuration
6677 0 : fn maybe_reconcile_shard(
6678 0 : &self,
6679 0 : shard: &mut TenantShard,
6680 0 : nodes: &Arc<HashMap<NodeId, Node>>,
6681 0 : priority: ReconcilerPriority,
6682 0 : ) -> Option<ReconcilerWaiter> {
6683 0 : self.maybe_configured_reconcile_shard(shard, nodes, ReconcilerConfig::new(priority))
6684 0 : }
6685 :
6686 : /// Before constructing a Reconciler, acquire semaphore units from the appropriate concurrency limit (depends on priority)
6687 0 : fn get_reconciler_units(
6688 0 : &self,
6689 0 : priority: ReconcilerPriority,
6690 0 : ) -> Result<ReconcileUnits, TryAcquireError> {
6691 0 : let units = match priority {
6692 0 : ReconcilerPriority::Normal => self.reconciler_concurrency.clone().try_acquire_owned(),
6693 : ReconcilerPriority::High => {
6694 0 : match self
6695 0 : .priority_reconciler_concurrency
6696 0 : .clone()
6697 0 : .try_acquire_owned()
6698 : {
6699 0 : Ok(u) => Ok(u),
6700 : Err(TryAcquireError::NoPermits) => {
6701 : // If the high priority semaphore is exhausted, then high priority tasks may steal units from
6702 : // the normal priority semaphore.
6703 0 : self.reconciler_concurrency.clone().try_acquire_owned()
6704 : }
6705 0 : Err(e) => Err(e),
6706 : }
6707 : }
6708 : };
6709 :
6710 0 : units.map(ReconcileUnits::new)
6711 0 : }
6712 :
6713 : /// Wrap [`TenantShard`] reconciliation methods with acquisition of [`Gate`] and [`ReconcileUnits`],
6714 0 : fn maybe_configured_reconcile_shard(
6715 0 : &self,
6716 0 : shard: &mut TenantShard,
6717 0 : nodes: &Arc<HashMap<NodeId, Node>>,
6718 0 : reconciler_config: ReconcilerConfig,
6719 0 : ) -> Option<ReconcilerWaiter> {
6720 0 : let reconcile_needed = shard.get_reconcile_needed(nodes);
6721 :
6722 0 : let reconcile_reason = match reconcile_needed {
6723 0 : ReconcileNeeded::No => return None,
6724 0 : ReconcileNeeded::WaitExisting(waiter) => return Some(waiter),
6725 0 : ReconcileNeeded::Yes(reason) => {
6726 0 : // Fall through to try and acquire units for spawning reconciler
6727 0 : reason
6728 : }
6729 : };
6730 :
6731 0 : let units = match self.get_reconciler_units(reconciler_config.priority) {
6732 0 : Ok(u) => u,
6733 : Err(_) => {
6734 0 : tracing::info!(tenant_id=%shard.tenant_shard_id.tenant_id, shard_id=%shard.tenant_shard_id.shard_slug(),
6735 0 : "Concurrency limited: enqueued for reconcile later");
6736 0 : if !shard.delayed_reconcile {
6737 0 : match self.delayed_reconcile_tx.try_send(shard.tenant_shard_id) {
6738 0 : Err(TrySendError::Closed(_)) => {
6739 0 : // Weird mid-shutdown case?
6740 0 : }
6741 : Err(TrySendError::Full(_)) => {
6742 : // It is safe to skip sending our ID in the channel: we will eventually get retried by the background reconcile task.
6743 0 : tracing::warn!(
6744 0 : "Many shards are waiting to reconcile: delayed_reconcile queue is full"
6745 : );
6746 : }
6747 0 : Ok(()) => {
6748 0 : shard.delayed_reconcile = true;
6749 0 : }
6750 : }
6751 0 : }
6752 :
6753 : // We won't spawn a reconciler, but we will construct a waiter that waits for the shard's sequence
6754 : // number to advance. When this function is eventually called again and succeeds in getting units,
6755 : // it will spawn a reconciler that makes this waiter complete.
6756 0 : return Some(shard.future_reconcile_waiter());
6757 : }
6758 : };
6759 :
6760 0 : let Ok(gate_guard) = self.reconcilers_gate.enter() else {
6761 : // Gate closed: we're shutting down, drop out.
6762 0 : return None;
6763 : };
6764 :
6765 0 : shard.spawn_reconciler(
6766 0 : reconcile_reason,
6767 0 : &self.result_tx,
6768 0 : nodes,
6769 0 : &self.compute_hook,
6770 0 : reconciler_config,
6771 0 : &self.config,
6772 0 : &self.persistence,
6773 0 : units,
6774 0 : gate_guard,
6775 0 : &self.reconcilers_cancel,
6776 0 : )
6777 0 : }
6778 :
6779 : /// Check all tenants for pending reconciliation work, and reconcile those in need.
6780 : /// Additionally, reschedule tenants that require it.
6781 : ///
6782 : /// Returns how many reconciliation tasks were started, or `1` if no reconciles were
6783 : /// spawned but some _would_ have been spawned if `reconciler_concurrency` units where
6784 : /// available. A return value of 0 indicates that everything is fully reconciled already.
6785 0 : fn reconcile_all(&self) -> usize {
6786 0 : let mut locked = self.inner.write().unwrap();
6787 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
6788 0 : let pageservers = nodes.clone();
6789 0 :
6790 0 : // This function is an efficient place to update lazy statistics, since we are walking
6791 0 : // all tenants.
6792 0 : let mut pending_reconciles = 0;
6793 0 : let mut az_violations = 0;
6794 0 :
6795 0 : // If we find any tenants to drop from memory, stash them to offload after
6796 0 : // we're done traversing the map of tenants.
6797 0 : let mut drop_detached_tenants = Vec::new();
6798 0 :
6799 0 : let mut reconciles_spawned = 0;
6800 0 : for shard in tenants.values_mut() {
6801 : // Accumulate scheduling statistics
6802 0 : if let (Some(attached), Some(preferred)) =
6803 0 : (shard.intent.get_attached(), shard.preferred_az())
6804 : {
6805 0 : let node_az = nodes
6806 0 : .get(attached)
6807 0 : .expect("Nodes exist if referenced")
6808 0 : .get_availability_zone_id();
6809 0 : if node_az != preferred {
6810 0 : az_violations += 1;
6811 0 : }
6812 0 : }
6813 :
6814 : // Skip checking if this shard is already enqueued for reconciliation
6815 0 : if shard.delayed_reconcile && self.reconciler_concurrency.available_permits() == 0 {
6816 : // If there is something delayed, then return a nonzero count so that
6817 : // callers like reconcile_all_now do not incorrectly get the impression
6818 : // that the system is in a quiescent state.
6819 0 : reconciles_spawned = std::cmp::max(1, reconciles_spawned);
6820 0 : pending_reconciles += 1;
6821 0 : continue;
6822 0 : }
6823 0 :
6824 0 : // Eventual consistency: if an earlier reconcile job failed, and the shard is still
6825 0 : // dirty, spawn another rone
6826 0 : if self
6827 0 : .maybe_reconcile_shard(shard, &pageservers, ReconcilerPriority::Normal)
6828 0 : .is_some()
6829 0 : {
6830 0 : reconciles_spawned += 1;
6831 0 : } else if shard.delayed_reconcile {
6832 0 : // Shard wanted to reconcile but for some reason couldn't.
6833 0 : pending_reconciles += 1;
6834 0 : }
6835 :
6836 : // If this tenant is detached, try dropping it from memory. This is usually done
6837 : // proactively in [`Self::process_results`], but we do it here to handle the edge
6838 : // case where a reconcile completes while someone else is holding an op lock for the tenant.
6839 0 : if shard.tenant_shard_id.shard_number == ShardNumber(0)
6840 0 : && shard.policy == PlacementPolicy::Detached
6841 : {
6842 0 : if let Some(guard) = self.tenant_op_locks.try_exclusive(
6843 0 : shard.tenant_shard_id.tenant_id,
6844 0 : TenantOperations::DropDetached,
6845 0 : ) {
6846 0 : drop_detached_tenants.push((shard.tenant_shard_id.tenant_id, guard));
6847 0 : }
6848 0 : }
6849 : }
6850 :
6851 : // Some metrics are calculated from SchedulerNode state, update these periodically
6852 0 : scheduler.update_metrics();
6853 :
6854 : // Process any deferred tenant drops
6855 0 : for (tenant_id, guard) in drop_detached_tenants {
6856 0 : self.maybe_drop_tenant(tenant_id, &mut locked, &guard);
6857 0 : }
6858 :
6859 0 : metrics::METRICS_REGISTRY
6860 0 : .metrics_group
6861 0 : .storage_controller_schedule_az_violation
6862 0 : .set(az_violations as i64);
6863 0 :
6864 0 : metrics::METRICS_REGISTRY
6865 0 : .metrics_group
6866 0 : .storage_controller_pending_reconciles
6867 0 : .set(pending_reconciles as i64);
6868 0 :
6869 0 : reconciles_spawned
6870 0 : }
6871 :
6872 : /// `optimize` in this context means identifying shards which have valid scheduled locations, but
6873 : /// could be scheduled somewhere better:
6874 : /// - Cutting over to a secondary if the node with the secondary is more lightly loaded
6875 : /// * e.g. after a node fails then recovers, to move some work back to it
6876 : /// - Cutting over to a secondary if it improves the spread of shard attachments within a tenant
6877 : /// * e.g. after a shard split, the initial attached locations will all be on the node where
6878 : /// we did the split, but are probably better placed elsewhere.
6879 : /// - Creating new secondary locations if it improves the spreading of a sharded tenant
6880 : /// * e.g. after a shard split, some locations will be on the same node (where the split
6881 : /// happened), and will probably be better placed elsewhere.
6882 : ///
6883 : /// To put it more briefly: whereas the scheduler respects soft constraints in a ScheduleContext at
6884 : /// the time of scheduling, this function looks for cases where a better-scoring location is available
6885 : /// according to those same soft constraints.
6886 0 : async fn optimize_all(&self) -> usize {
6887 : // Limit on how many shards' optmizations each call to this function will execute. Combined
6888 : // with the frequency of background calls, this acts as an implicit rate limit that runs a small
6889 : // trickle of optimizations in the background, rather than executing a large number in parallel
6890 : // when a change occurs.
6891 : const MAX_OPTIMIZATIONS_EXEC_PER_PASS: usize = 16;
6892 :
6893 : // Synchronous prepare: scan shards for possible scheduling optimizations
6894 0 : let candidate_work = self.optimize_all_plan();
6895 0 : let candidate_work_len = candidate_work.len();
6896 :
6897 : // Asynchronous validate: I/O to pageservers to make sure shards are in a good state to apply validation
6898 0 : let validated_work = self.optimize_all_validate(candidate_work).await;
6899 :
6900 0 : let was_work_filtered = validated_work.len() != candidate_work_len;
6901 0 :
6902 0 : // Synchronous apply: update the shards' intent states according to validated optimisations
6903 0 : let mut reconciles_spawned = 0;
6904 0 : let mut optimizations_applied = 0;
6905 0 : let mut locked = self.inner.write().unwrap();
6906 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
6907 0 : for (tenant_shard_id, optimization) in validated_work {
6908 0 : let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
6909 : // Shard was dropped between planning and execution;
6910 0 : continue;
6911 : };
6912 0 : tracing::info!(tenant_shard_id=%tenant_shard_id, "Applying optimization: {optimization:?}");
6913 0 : if shard.apply_optimization(scheduler, optimization) {
6914 0 : optimizations_applied += 1;
6915 0 : if self
6916 0 : .maybe_reconcile_shard(shard, nodes, ReconcilerPriority::Normal)
6917 0 : .is_some()
6918 0 : {
6919 0 : reconciles_spawned += 1;
6920 0 : }
6921 0 : }
6922 :
6923 0 : if optimizations_applied >= MAX_OPTIMIZATIONS_EXEC_PER_PASS {
6924 0 : break;
6925 0 : }
6926 : }
6927 :
6928 0 : if was_work_filtered {
6929 0 : // If we filtered any work out during validation, ensure we return a nonzero value to indicate
6930 0 : // to callers that the system is not in a truly quiet state, it's going to do some work as soon
6931 0 : // as these validations start passing.
6932 0 : reconciles_spawned = std::cmp::max(reconciles_spawned, 1);
6933 0 : }
6934 :
6935 0 : reconciles_spawned
6936 0 : }
6937 :
6938 0 : fn optimize_all_plan(&self) -> Vec<(TenantShardId, ScheduleOptimization)> {
6939 : // How many candidate optimizations we will generate, before evaluating them for readniess: setting
6940 : // this higher than the execution limit gives us a chance to execute some work even if the first
6941 : // few optimizations we find are not ready.
6942 : const MAX_OPTIMIZATIONS_PLAN_PER_PASS: usize = 64;
6943 :
6944 0 : let mut work = Vec::new();
6945 0 : let mut locked = self.inner.write().unwrap();
6946 0 : let (_nodes, tenants, scheduler) = locked.parts_mut();
6947 :
6948 : // We are going to plan a bunch of optimisations before applying any of them, so the
6949 : // utilisation stats on nodes will be effectively stale for the >1st optimisation we
6950 : // generate. To avoid this causing unstable migrations/flapping, it's important that the
6951 : // code in TenantShard for finding optimisations uses [`NodeAttachmentSchedulingScore::disregard_utilization`]
6952 : // to ignore the utilisation component of the score.
6953 :
6954 0 : for (_tenant_id, schedule_context, shards) in
6955 0 : TenantShardContextIterator::new(tenants, ScheduleMode::Speculative)
6956 : {
6957 0 : for shard in shards {
6958 0 : if work.len() >= MAX_OPTIMIZATIONS_PLAN_PER_PASS {
6959 0 : break;
6960 0 : }
6961 0 : match shard.get_scheduling_policy() {
6962 0 : ShardSchedulingPolicy::Active => {
6963 0 : // Ok to do optimization
6964 0 : }
6965 : ShardSchedulingPolicy::Essential
6966 : | ShardSchedulingPolicy::Pause
6967 : | ShardSchedulingPolicy::Stop => {
6968 : // Policy prevents optimizing this shard.
6969 0 : continue;
6970 : }
6971 : }
6972 :
6973 0 : if !matches!(shard.splitting, SplitState::Idle)
6974 0 : || matches!(shard.policy, PlacementPolicy::Detached)
6975 0 : || shard.reconciler.is_some()
6976 : {
6977 : // Do not start any optimizations while another change to the tenant is ongoing: this
6978 : // is not necessary for correctness, but simplifies operations and implicitly throttles
6979 : // optimization changes to happen in a "trickle" over time.
6980 0 : continue;
6981 0 : }
6982 0 :
6983 0 : // Fast path: we may quickly identify shards that don't have any possible optimisations
6984 0 : if !shard.maybe_optimizable(scheduler, &schedule_context) {
6985 0 : if cfg!(feature = "testing") {
6986 : // Check that maybe_optimizable doesn't disagree with the actual optimization functions.
6987 : // Only do this in testing builds because it is not a correctness-critical check, so we shouldn't
6988 : // panic in prod if we hit this, or spend cycles on it in prod.
6989 0 : assert!(
6990 0 : shard
6991 0 : .optimize_attachment(scheduler, &schedule_context)
6992 0 : .is_none()
6993 0 : );
6994 0 : assert!(
6995 0 : shard
6996 0 : .optimize_secondary(scheduler, &schedule_context)
6997 0 : .is_none()
6998 0 : );
6999 0 : }
7000 0 : continue;
7001 0 : }
7002 :
7003 0 : if let Some(optimization) =
7004 : // If idle, maybe optimize attachments: if a shard has a secondary location that is preferable to
7005 : // its primary location based on soft constraints, cut it over.
7006 0 : shard.optimize_attachment(scheduler, &schedule_context)
7007 : {
7008 0 : tracing::info!(tenant_shard_id=%shard.tenant_shard_id, "Identified optimization for attachment: {optimization:?}");
7009 0 : work.push((shard.tenant_shard_id, optimization));
7010 0 : break;
7011 0 : } else if let Some(optimization) =
7012 : // If idle, maybe optimize secondary locations: if a shard has a secondary location that would be
7013 : // better placed on another node, based on ScheduleContext, then adjust it. This
7014 : // covers cases like after a shard split, where we might have too many shards
7015 : // in the same tenant with secondary locations on the node where they originally split.
7016 0 : shard.optimize_secondary(scheduler, &schedule_context)
7017 : {
7018 0 : tracing::info!(tenant_shard_id=%shard.tenant_shard_id, "Identified optimization for secondary: {optimization:?}");
7019 0 : work.push((shard.tenant_shard_id, optimization));
7020 0 : break;
7021 0 : }
7022 : }
7023 : }
7024 :
7025 0 : work
7026 0 : }
7027 :
7028 0 : async fn optimize_all_validate(
7029 0 : &self,
7030 0 : candidate_work: Vec<(TenantShardId, ScheduleOptimization)>,
7031 0 : ) -> Vec<(TenantShardId, ScheduleOptimization)> {
7032 0 : // Take a clone of the node map to use outside the lock in async validation phase
7033 0 : let validation_nodes = { self.inner.read().unwrap().nodes.clone() };
7034 0 :
7035 0 : let mut want_secondary_status = Vec::new();
7036 0 :
7037 0 : // Validate our plans: this is an async phase where we may do I/O to pageservers to
7038 0 : // check that the state of locations is acceptable to run the optimization, such as
7039 0 : // checking that a secondary location is sufficiently warmed-up to cleanly cut over
7040 0 : // in a live migration.
7041 0 : let mut validated_work = Vec::new();
7042 0 : for (tenant_shard_id, optimization) in candidate_work {
7043 0 : match optimization.action {
7044 : ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
7045 : old_attached_node_id: _,
7046 0 : new_attached_node_id,
7047 0 : }) => {
7048 0 : match validation_nodes.get(&new_attached_node_id) {
7049 0 : None => {
7050 0 : // Node was dropped between planning and validation
7051 0 : }
7052 0 : Some(node) => {
7053 0 : if !node.is_available() {
7054 0 : tracing::info!(
7055 0 : "Skipping optimization migration of {tenant_shard_id} to {new_attached_node_id} because node unavailable"
7056 : );
7057 0 : } else {
7058 0 : // Accumulate optimizations that require fetching secondary status, so that we can execute these
7059 0 : // remote API requests concurrently.
7060 0 : want_secondary_status.push((
7061 0 : tenant_shard_id,
7062 0 : node.clone(),
7063 0 : optimization,
7064 0 : ));
7065 0 : }
7066 : }
7067 : }
7068 : }
7069 : ScheduleOptimizationAction::ReplaceSecondary(_)
7070 : | ScheduleOptimizationAction::CreateSecondary(_)
7071 : | ScheduleOptimizationAction::RemoveSecondary(_) => {
7072 : // No extra checks needed to manage secondaries: this does not interrupt client access
7073 0 : validated_work.push((tenant_shard_id, optimization))
7074 : }
7075 : };
7076 : }
7077 :
7078 : // Call into pageserver API to find out if the destination secondary location is warm enough for a reasonably smooth migration: we
7079 : // do this so that we avoid spawning a Reconciler that would have to wait minutes/hours for a destination to warm up: that reconciler
7080 : // would hold a precious reconcile semaphore unit the whole time it was waiting for the destination to warm up.
7081 0 : let results = self
7082 0 : .tenant_for_shards_api(
7083 0 : want_secondary_status
7084 0 : .iter()
7085 0 : .map(|i| (i.0, i.1.clone()))
7086 0 : .collect(),
7087 0 : |tenant_shard_id, client| async move {
7088 0 : client.tenant_secondary_status(tenant_shard_id).await
7089 0 : },
7090 0 : 1,
7091 0 : 1,
7092 0 : SHORT_RECONCILE_TIMEOUT,
7093 0 : &self.cancel,
7094 0 : )
7095 0 : .await;
7096 :
7097 0 : for ((tenant_shard_id, node, optimization), secondary_status) in
7098 0 : want_secondary_status.into_iter().zip(results.into_iter())
7099 : {
7100 0 : match secondary_status {
7101 0 : Err(e) => {
7102 0 : tracing::info!(
7103 0 : "Skipping migration of {tenant_shard_id} to {node}, error querying secondary: {e}"
7104 : );
7105 : }
7106 0 : Ok(progress) => {
7107 : // We require secondary locations to have less than 10GiB of downloads pending before we will use
7108 : // them in an optimization
7109 : const DOWNLOAD_FRESHNESS_THRESHOLD: u64 = 10 * 1024 * 1024 * 1024;
7110 :
7111 0 : if progress.heatmap_mtime.is_none()
7112 0 : || progress.bytes_total < DOWNLOAD_FRESHNESS_THRESHOLD
7113 0 : && progress.bytes_downloaded != progress.bytes_total
7114 0 : || progress.bytes_total - progress.bytes_downloaded
7115 0 : > DOWNLOAD_FRESHNESS_THRESHOLD
7116 : {
7117 0 : tracing::info!(
7118 0 : "Skipping migration of {tenant_shard_id} to {node} because secondary isn't ready: {progress:?}"
7119 : );
7120 :
7121 : #[cfg(feature = "testing")]
7122 0 : if progress.heatmap_mtime.is_none() {
7123 : // No heatmap might mean the attached location has never uploaded one, or that
7124 : // the secondary download hasn't happened yet. This is relatively unusual in the field,
7125 : // but fairly common in tests.
7126 0 : self.kick_secondary_download(tenant_shard_id).await;
7127 0 : }
7128 : } else {
7129 : // Location looks ready: proceed
7130 0 : tracing::info!(
7131 0 : "{tenant_shard_id} secondary on {node} is warm enough for migration: {progress:?}"
7132 : );
7133 0 : validated_work.push((tenant_shard_id, optimization))
7134 : }
7135 : }
7136 : }
7137 : }
7138 :
7139 0 : validated_work
7140 0 : }
7141 :
7142 : /// Some aspects of scheduling optimisation wait for secondary locations to be warm. This
7143 : /// happens on multi-minute timescales in the field, which is fine because optimisation is meant
7144 : /// to be a lazy background thing. However, when testing, it is not practical to wait around, so
7145 : /// we have this helper to move things along faster.
7146 : #[cfg(feature = "testing")]
7147 0 : async fn kick_secondary_download(&self, tenant_shard_id: TenantShardId) {
7148 0 : let (attached_node, secondaries) = {
7149 0 : let locked = self.inner.read().unwrap();
7150 0 : let Some(shard) = locked.tenants.get(&tenant_shard_id) else {
7151 0 : tracing::warn!(
7152 0 : "Skipping kick of secondary download for {tenant_shard_id}: not found"
7153 : );
7154 0 : return;
7155 : };
7156 :
7157 0 : let Some(attached) = shard.intent.get_attached() else {
7158 0 : tracing::warn!(
7159 0 : "Skipping kick of secondary download for {tenant_shard_id}: no attached"
7160 : );
7161 0 : return;
7162 : };
7163 :
7164 0 : let secondaries = shard
7165 0 : .intent
7166 0 : .get_secondary()
7167 0 : .iter()
7168 0 : .map(|n| locked.nodes.get(n).unwrap().clone())
7169 0 : .collect::<Vec<_>>();
7170 0 :
7171 0 : (locked.nodes.get(attached).unwrap().clone(), secondaries)
7172 0 : };
7173 0 :
7174 0 : // Make remote API calls to upload + download heatmaps: we ignore errors because this is just
7175 0 : // a 'kick' to let scheduling optimisation run more promptly.
7176 0 : match attached_node
7177 0 : .with_client_retries(
7178 0 : |client| async move { client.tenant_heatmap_upload(tenant_shard_id).await },
7179 0 : &self.config.pageserver_jwt_token,
7180 0 : 3,
7181 0 : 10,
7182 0 : SHORT_RECONCILE_TIMEOUT,
7183 0 : &self.cancel,
7184 0 : )
7185 0 : .await
7186 : {
7187 0 : Some(Err(e)) => {
7188 0 : tracing::info!(
7189 0 : "Failed to upload heatmap from {attached_node} for {tenant_shard_id}: {e}"
7190 : );
7191 : }
7192 : None => {
7193 0 : tracing::info!(
7194 0 : "Cancelled while uploading heatmap from {attached_node} for {tenant_shard_id}"
7195 : );
7196 : }
7197 : Some(Ok(_)) => {
7198 0 : tracing::info!(
7199 0 : "Successfully uploaded heatmap from {attached_node} for {tenant_shard_id}"
7200 : );
7201 : }
7202 : }
7203 :
7204 0 : for secondary_node in secondaries {
7205 0 : match secondary_node
7206 0 : .with_client_retries(
7207 0 : |client| async move {
7208 0 : client
7209 0 : .tenant_secondary_download(
7210 0 : tenant_shard_id,
7211 0 : Some(Duration::from_secs(1)),
7212 0 : )
7213 0 : .await
7214 0 : },
7215 0 : &self.config.pageserver_jwt_token,
7216 0 : 3,
7217 0 : 10,
7218 0 : SHORT_RECONCILE_TIMEOUT,
7219 0 : &self.cancel,
7220 0 : )
7221 0 : .await
7222 : {
7223 0 : Some(Err(e)) => {
7224 0 : tracing::info!(
7225 0 : "Failed to download heatmap from {secondary_node} for {tenant_shard_id}: {e}"
7226 : );
7227 : }
7228 : None => {
7229 0 : tracing::info!(
7230 0 : "Cancelled while downloading heatmap from {secondary_node} for {tenant_shard_id}"
7231 : );
7232 : }
7233 0 : Some(Ok(progress)) => {
7234 0 : tracing::info!(
7235 0 : "Successfully downloaded heatmap from {secondary_node} for {tenant_shard_id}: {progress:?}"
7236 : );
7237 : }
7238 : }
7239 : }
7240 0 : }
7241 :
7242 : /// Look for shards which are oversized and in need of splitting
7243 0 : async fn autosplit_tenants(self: &Arc<Self>) {
7244 0 : let Some(split_threshold) = self.config.split_threshold else {
7245 : // Auto-splitting is disabled
7246 0 : return;
7247 : };
7248 :
7249 0 : let nodes = self.inner.read().unwrap().nodes.clone();
7250 :
7251 : const SPLIT_TO_MAX: ShardCount = ShardCount::new(8);
7252 :
7253 0 : let mut top_n = Vec::new();
7254 0 :
7255 0 : // Call into each node to look for big tenants
7256 0 : let top_n_request = TopTenantShardsRequest {
7257 0 : // We currently split based on logical size, for simplicity: logical size is a signal of
7258 0 : // the user's intent to run a large database, whereas physical/resident size can be symptoms
7259 0 : // of compaction issues. Eventually we should switch to using resident size to bound the
7260 0 : // disk space impact of one shard.
7261 0 : order_by: models::TenantSorting::MaxLogicalSize,
7262 0 : limit: 10,
7263 0 : where_shards_lt: Some(SPLIT_TO_MAX),
7264 0 : where_gt: Some(split_threshold),
7265 0 : };
7266 0 : for node in nodes.values() {
7267 0 : let request_ref = &top_n_request;
7268 0 : match node
7269 0 : .with_client_retries(
7270 0 : |client| async move {
7271 0 : let request = request_ref.clone();
7272 0 : client.top_tenant_shards(request.clone()).await
7273 0 : },
7274 0 : &self.config.pageserver_jwt_token,
7275 0 : 3,
7276 0 : 3,
7277 0 : Duration::from_secs(5),
7278 0 : &self.cancel,
7279 0 : )
7280 0 : .await
7281 : {
7282 0 : Some(Ok(node_top_n)) => {
7283 0 : top_n.extend(node_top_n.shards.into_iter());
7284 0 : }
7285 : Some(Err(mgmt_api::Error::Cancelled)) => {
7286 0 : continue;
7287 : }
7288 0 : Some(Err(e)) => {
7289 0 : tracing::warn!("Failed to fetch top N tenants from {node}: {e}");
7290 0 : continue;
7291 : }
7292 : None => {
7293 : // Node is shutting down
7294 0 : continue;
7295 : }
7296 : };
7297 : }
7298 :
7299 : // Pick the biggest tenant to split first
7300 0 : top_n.sort_by_key(|i| i.resident_size);
7301 0 :
7302 0 : // Filter out tenants in a prohibiting scheduling mode
7303 0 : {
7304 0 : let locked = self.inner.read().unwrap();
7305 0 : top_n.retain(|i| {
7306 0 : if let Some(shard) = locked.tenants.get(&i.id) {
7307 0 : matches!(shard.get_scheduling_policy(), ShardSchedulingPolicy::Active)
7308 : } else {
7309 0 : false
7310 : }
7311 0 : });
7312 0 : }
7313 :
7314 0 : let Some(split_candidate) = top_n.into_iter().next() else {
7315 0 : tracing::debug!("No split-elegible shards found");
7316 0 : return;
7317 : };
7318 :
7319 : // We spawn a task to run this, so it's exactly like some external API client requesting it. We don't
7320 : // want to block the background reconcile loop on this.
7321 0 : tracing::info!(
7322 0 : "Auto-splitting tenant for size threshold {split_threshold}: current size {split_candidate:?}"
7323 : );
7324 :
7325 0 : let this = self.clone();
7326 0 : tokio::spawn(
7327 0 : async move {
7328 0 : match this
7329 0 : .tenant_shard_split(
7330 0 : split_candidate.id.tenant_id,
7331 0 : TenantShardSplitRequest {
7332 0 : // Always split to the max number of shards: this avoids stepping through
7333 0 : // intervening shard counts and encountering the overrhead of a split+cleanup
7334 0 : // each time as a tenant grows, and is not too expensive because our max shard
7335 0 : // count is relatively low anyway.
7336 0 : // This policy will be adjusted in future once we support higher shard count.
7337 0 : new_shard_count: SPLIT_TO_MAX.literal(),
7338 0 : new_stripe_size: Some(ShardParameters::DEFAULT_STRIPE_SIZE),
7339 0 : },
7340 0 : )
7341 0 : .await
7342 : {
7343 : Ok(_) => {
7344 0 : tracing::info!("Successful auto-split");
7345 : }
7346 0 : Err(e) => {
7347 0 : tracing::error!("Auto-split failed: {e}");
7348 : }
7349 : }
7350 0 : }
7351 0 : .instrument(tracing::info_span!("auto_split", tenant_id=%split_candidate.id.tenant_id)),
7352 : );
7353 0 : }
7354 :
7355 : /// Useful for tests: run whatever work a background [`Self::reconcile_all`] would have done, but
7356 : /// also wait for any generated Reconcilers to complete. Calling this until it returns zero should
7357 : /// put the system into a quiescent state where future background reconciliations won't do anything.
7358 0 : pub(crate) async fn reconcile_all_now(&self) -> Result<usize, ReconcileWaitError> {
7359 0 : let reconciles_spawned = self.reconcile_all();
7360 0 : let reconciles_spawned = if reconciles_spawned == 0 {
7361 : // Only optimize when we are otherwise idle
7362 0 : self.optimize_all().await
7363 : } else {
7364 0 : reconciles_spawned
7365 : };
7366 :
7367 0 : let waiters = {
7368 0 : let mut waiters = Vec::new();
7369 0 : let locked = self.inner.read().unwrap();
7370 0 : for (_tenant_shard_id, shard) in locked.tenants.iter() {
7371 0 : if let Some(waiter) = shard.get_waiter() {
7372 0 : waiters.push(waiter);
7373 0 : }
7374 : }
7375 0 : waiters
7376 0 : };
7377 0 :
7378 0 : let waiter_count = waiters.len();
7379 0 : match self.await_waiters(waiters, RECONCILE_TIMEOUT).await {
7380 0 : Ok(()) => {}
7381 0 : Err(ReconcileWaitError::Failed(_, reconcile_error))
7382 0 : if matches!(*reconcile_error, ReconcileError::Cancel) =>
7383 0 : {
7384 0 : // Ignore reconciler cancel errors: this reconciler might have shut down
7385 0 : // because some other change superceded it. We will return a nonzero number,
7386 0 : // so the caller knows they might have to call again to quiesce the system.
7387 0 : }
7388 0 : Err(e) => {
7389 0 : return Err(e);
7390 : }
7391 : };
7392 :
7393 0 : tracing::info!(
7394 0 : "{} reconciles in reconcile_all, {} waiters",
7395 : reconciles_spawned,
7396 : waiter_count
7397 : );
7398 :
7399 0 : Ok(std::cmp::max(waiter_count, reconciles_spawned))
7400 0 : }
7401 :
7402 0 : async fn stop_reconciliations(&self, reason: StopReconciliationsReason) {
7403 0 : // Cancel all on-going reconciles and wait for them to exit the gate.
7404 0 : tracing::info!("{reason}: cancelling and waiting for in-flight reconciles");
7405 0 : self.reconcilers_cancel.cancel();
7406 0 : self.reconcilers_gate.close().await;
7407 :
7408 : // Signal the background loop in [`Service::process_results`] to exit once
7409 : // it has proccessed the results from all the reconciles we cancelled earlier.
7410 0 : tracing::info!("{reason}: processing results from previously in-flight reconciles");
7411 0 : self.result_tx.send(ReconcileResultRequest::Stop).ok();
7412 0 : self.result_tx.closed().await;
7413 0 : }
7414 :
7415 0 : pub async fn shutdown(&self) {
7416 0 : self.stop_reconciliations(StopReconciliationsReason::ShuttingDown)
7417 0 : .await;
7418 :
7419 : // Background tasks hold gate guards: this notifies them of the cancellation and
7420 : // waits for them all to complete.
7421 0 : tracing::info!("Shutting down: cancelling and waiting for background tasks to exit");
7422 0 : self.cancel.cancel();
7423 0 : self.gate.close().await;
7424 0 : }
7425 :
7426 : /// Spot check the download lag for a secondary location of a shard.
7427 : /// Should be used as a heuristic, since it's not always precise: the
7428 : /// secondary might have not downloaded the new heat map yet and, hence,
7429 : /// is not aware of the lag.
7430 : ///
7431 : /// Returns:
7432 : /// * Ok(None) if the lag could not be determined from the status,
7433 : /// * Ok(Some(_)) if the lag could be determind
7434 : /// * Err on failures to query the pageserver.
7435 0 : async fn secondary_lag(
7436 0 : &self,
7437 0 : secondary: &NodeId,
7438 0 : tenant_shard_id: TenantShardId,
7439 0 : ) -> Result<Option<u64>, mgmt_api::Error> {
7440 0 : let nodes = self.inner.read().unwrap().nodes.clone();
7441 0 : let node = nodes.get(secondary).ok_or(mgmt_api::Error::ApiError(
7442 0 : StatusCode::NOT_FOUND,
7443 0 : format!("Node with id {} not found", secondary),
7444 0 : ))?;
7445 :
7446 0 : match node
7447 0 : .with_client_retries(
7448 0 : |client| async move { client.tenant_secondary_status(tenant_shard_id).await },
7449 0 : &self.config.pageserver_jwt_token,
7450 0 : 1,
7451 0 : 3,
7452 0 : Duration::from_millis(250),
7453 0 : &self.cancel,
7454 0 : )
7455 0 : .await
7456 : {
7457 0 : Some(Ok(status)) => match status.heatmap_mtime {
7458 0 : Some(_) => Ok(Some(status.bytes_total - status.bytes_downloaded)),
7459 0 : None => Ok(None),
7460 : },
7461 0 : Some(Err(e)) => Err(e),
7462 0 : None => Err(mgmt_api::Error::Cancelled),
7463 : }
7464 0 : }
7465 :
7466 : /// Drain a node by moving the shards attached to it as primaries.
7467 : /// This is a long running operation and it should run as a separate Tokio task.
7468 0 : pub(crate) async fn drain_node(
7469 0 : self: &Arc<Self>,
7470 0 : node_id: NodeId,
7471 0 : cancel: CancellationToken,
7472 0 : ) -> Result<(), OperationError> {
7473 : const MAX_SECONDARY_LAG_BYTES_DEFAULT: u64 = 256 * 1024 * 1024;
7474 0 : let max_secondary_lag_bytes = self
7475 0 : .config
7476 0 : .max_secondary_lag_bytes
7477 0 : .unwrap_or(MAX_SECONDARY_LAG_BYTES_DEFAULT);
7478 :
7479 : // By default, live migrations are generous about the wait time for getting
7480 : // the secondary location up to speed. When draining, give up earlier in order
7481 : // to not stall the operation when a cold secondary is encountered.
7482 : const SECONDARY_WARMUP_TIMEOUT: Duration = Duration::from_secs(20);
7483 : const SECONDARY_DOWNLOAD_REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
7484 0 : let reconciler_config = ReconcilerConfigBuilder::new(ReconcilerPriority::Normal)
7485 0 : .secondary_warmup_timeout(SECONDARY_WARMUP_TIMEOUT)
7486 0 : .secondary_download_request_timeout(SECONDARY_DOWNLOAD_REQUEST_TIMEOUT)
7487 0 : .build();
7488 0 :
7489 0 : let mut waiters = Vec::new();
7490 0 :
7491 0 : let mut tid_iter = TenantShardIterator::new({
7492 0 : let service = self.clone();
7493 0 : move |last_inspected_shard: Option<TenantShardId>| {
7494 0 : let locked = &service.inner.read().unwrap();
7495 0 : let tenants = &locked.tenants;
7496 0 : let entry = match last_inspected_shard {
7497 0 : Some(skip_past) => {
7498 0 : // Skip to the last seen tenant shard id
7499 0 : let mut cursor = tenants.iter().skip_while(|(tid, _)| **tid != skip_past);
7500 0 :
7501 0 : // Skip past the last seen
7502 0 : cursor.nth(1)
7503 : }
7504 0 : None => tenants.first_key_value(),
7505 : };
7506 :
7507 0 : entry.map(|(tid, _)| tid).copied()
7508 0 : }
7509 0 : });
7510 :
7511 0 : while !tid_iter.finished() {
7512 0 : if cancel.is_cancelled() {
7513 0 : match self
7514 0 : .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
7515 0 : .await
7516 : {
7517 0 : Ok(()) => return Err(OperationError::Cancelled),
7518 0 : Err(err) => {
7519 0 : return Err(OperationError::FinalizeError(
7520 0 : format!(
7521 0 : "Failed to finalise drain cancel of {} by setting scheduling policy to Active: {}",
7522 0 : node_id, err
7523 0 : )
7524 0 : .into(),
7525 0 : ));
7526 : }
7527 : }
7528 0 : }
7529 0 :
7530 0 : drain_utils::validate_node_state(&node_id, self.inner.read().unwrap().nodes.clone())?;
7531 :
7532 0 : while waiters.len() < MAX_RECONCILES_PER_OPERATION {
7533 0 : let tid = match tid_iter.next() {
7534 0 : Some(tid) => tid,
7535 : None => {
7536 0 : break;
7537 : }
7538 : };
7539 :
7540 0 : let tid_drain = TenantShardDrain {
7541 0 : drained_node: node_id,
7542 0 : tenant_shard_id: tid,
7543 0 : };
7544 :
7545 0 : let dest_node_id = {
7546 0 : let locked = self.inner.read().unwrap();
7547 0 :
7548 0 : match tid_drain
7549 0 : .tenant_shard_eligible_for_drain(&locked.tenants, &locked.scheduler)
7550 : {
7551 0 : Some(node_id) => node_id,
7552 : None => {
7553 0 : continue;
7554 : }
7555 : }
7556 : };
7557 :
7558 0 : match self.secondary_lag(&dest_node_id, tid).await {
7559 0 : Ok(Some(lag)) if lag <= max_secondary_lag_bytes => {
7560 0 : // The secondary is reasonably up to date.
7561 0 : // Migrate to it
7562 0 : }
7563 0 : Ok(Some(lag)) => {
7564 0 : tracing::info!(
7565 0 : tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
7566 0 : "Secondary on node {dest_node_id} is lagging by {lag}. Skipping reconcile."
7567 : );
7568 0 : continue;
7569 : }
7570 : Ok(None) => {
7571 0 : tracing::info!(
7572 0 : tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
7573 0 : "Could not determine lag for secondary on node {dest_node_id}. Skipping reconcile."
7574 : );
7575 0 : continue;
7576 : }
7577 0 : Err(err) => {
7578 0 : tracing::warn!(
7579 0 : tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
7580 0 : "Failed to get secondary lag from node {dest_node_id}. Skipping reconcile: {err}"
7581 : );
7582 0 : continue;
7583 : }
7584 : }
7585 :
7586 : {
7587 0 : let mut locked = self.inner.write().unwrap();
7588 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
7589 0 : let rescheduled = tid_drain.reschedule_to_secondary(
7590 0 : dest_node_id,
7591 0 : tenants,
7592 0 : scheduler,
7593 0 : nodes,
7594 0 : )?;
7595 :
7596 0 : if let Some(tenant_shard) = rescheduled {
7597 0 : let waiter = self.maybe_configured_reconcile_shard(
7598 0 : tenant_shard,
7599 0 : nodes,
7600 0 : reconciler_config,
7601 0 : );
7602 0 : if let Some(some) = waiter {
7603 0 : waiters.push(some);
7604 0 : }
7605 0 : }
7606 : }
7607 : }
7608 :
7609 0 : waiters = self
7610 0 : .await_waiters_remainder(waiters, WAITER_FILL_DRAIN_POLL_TIMEOUT)
7611 0 : .await;
7612 :
7613 0 : failpoint_support::sleep_millis_async!("sleepy-drain-loop", &cancel);
7614 : }
7615 :
7616 0 : while !waiters.is_empty() {
7617 0 : if cancel.is_cancelled() {
7618 0 : match self
7619 0 : .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
7620 0 : .await
7621 : {
7622 0 : Ok(()) => return Err(OperationError::Cancelled),
7623 0 : Err(err) => {
7624 0 : return Err(OperationError::FinalizeError(
7625 0 : format!(
7626 0 : "Failed to finalise drain cancel of {} by setting scheduling policy to Active: {}",
7627 0 : node_id, err
7628 0 : )
7629 0 : .into(),
7630 0 : ));
7631 : }
7632 : }
7633 0 : }
7634 0 :
7635 0 : tracing::info!("Awaiting {} pending drain reconciliations", waiters.len());
7636 :
7637 0 : waiters = self
7638 0 : .await_waiters_remainder(waiters, SHORT_RECONCILE_TIMEOUT)
7639 0 : .await;
7640 : }
7641 :
7642 : // At this point we have done the best we could to drain shards from this node.
7643 : // Set the node scheduling policy to `[NodeSchedulingPolicy::PauseForRestart]`
7644 : // to complete the drain.
7645 0 : if let Err(err) = self
7646 0 : .node_configure(node_id, None, Some(NodeSchedulingPolicy::PauseForRestart))
7647 0 : .await
7648 : {
7649 : // This is not fatal. Anything that is polling the node scheduling policy to detect
7650 : // the end of the drain operations will hang, but all such places should enforce an
7651 : // overall timeout. The scheduling policy will be updated upon node re-attach and/or
7652 : // by the counterpart fill operation.
7653 0 : return Err(OperationError::FinalizeError(
7654 0 : format!(
7655 0 : "Failed to finalise drain of {node_id} by setting scheduling policy to PauseForRestart: {err}"
7656 0 : )
7657 0 : .into(),
7658 0 : ));
7659 0 : }
7660 0 :
7661 0 : Ok(())
7662 0 : }
7663 :
7664 : /// Create a node fill plan (pick secondaries to promote), based on:
7665 : /// 1. Shards which have a secondary on this node, and this node is in their home AZ, and are currently attached to a node
7666 : /// outside their home AZ, should be migrated back here.
7667 : /// 2. If after step 1 we have not migrated enough shards for this node to have its fair share of
7668 : /// attached shards, we will promote more shards from the nodes with the most attached shards, unless
7669 : /// those shards have a home AZ that doesn't match the node we're filling.
7670 0 : fn fill_node_plan(&self, node_id: NodeId) -> Vec<TenantShardId> {
7671 0 : let mut locked = self.inner.write().unwrap();
7672 0 : let (nodes, tenants, _scheduler) = locked.parts_mut();
7673 0 :
7674 0 : let node_az = nodes
7675 0 : .get(&node_id)
7676 0 : .expect("Node must exist")
7677 0 : .get_availability_zone_id()
7678 0 : .clone();
7679 0 :
7680 0 : // The tenant shard IDs that we plan to promote from secondary to attached on this node
7681 0 : let mut plan = Vec::new();
7682 0 :
7683 0 : // Collect shards which do not have a preferred AZ & are elegible for moving in stage 2
7684 0 : let mut free_tids_by_node: HashMap<NodeId, Vec<TenantShardId>> = HashMap::new();
7685 0 :
7686 0 : // Don't respect AZ preferences if there is only one AZ. This comes up in tests, but it could
7687 0 : // conceivably come up in real life if deploying a single-AZ region intentionally.
7688 0 : let respect_azs = nodes
7689 0 : .values()
7690 0 : .map(|n| n.get_availability_zone_id())
7691 0 : .unique()
7692 0 : .count()
7693 0 : > 1;
7694 :
7695 : // Step 1: collect all shards that we are required to migrate back to this node because their AZ preference
7696 : // requires it.
7697 0 : for (tsid, tenant_shard) in tenants {
7698 0 : if !tenant_shard.intent.get_secondary().contains(&node_id) {
7699 : // Shard doesn't have a secondary on this node, ignore it.
7700 0 : continue;
7701 0 : }
7702 0 :
7703 0 : // AZ check: when filling nodes after a restart, our intent is to move _back_ the
7704 0 : // shards which belong on this node, not to promote shards whose scheduling preference
7705 0 : // would be on their currently attached node. So will avoid promoting shards whose
7706 0 : // home AZ doesn't match the AZ of the node we're filling.
7707 0 : match tenant_shard.preferred_az() {
7708 0 : _ if !respect_azs => {
7709 0 : if let Some(primary) = tenant_shard.intent.get_attached() {
7710 0 : free_tids_by_node.entry(*primary).or_default().push(*tsid);
7711 0 : }
7712 : }
7713 : None => {
7714 : // Shard doesn't have an AZ preference: it is elegible to be moved, but we
7715 : // will only do so if our target shard count requires it.
7716 0 : if let Some(primary) = tenant_shard.intent.get_attached() {
7717 0 : free_tids_by_node.entry(*primary).or_default().push(*tsid);
7718 0 : }
7719 : }
7720 0 : Some(az) if az == &node_az => {
7721 : // This shard's home AZ is equal to the node we're filling: it should
7722 : // be moved back to this node as part of filling, unless its currently
7723 : // attached location is also in its home AZ.
7724 0 : if let Some(primary) = tenant_shard.intent.get_attached() {
7725 0 : if nodes
7726 0 : .get(primary)
7727 0 : .expect("referenced node must exist")
7728 0 : .get_availability_zone_id()
7729 0 : != tenant_shard
7730 0 : .preferred_az()
7731 0 : .expect("tenant must have an AZ preference")
7732 : {
7733 0 : plan.push(*tsid)
7734 0 : }
7735 : } else {
7736 0 : plan.push(*tsid)
7737 : }
7738 : }
7739 0 : Some(_) => {
7740 0 : // This shard's home AZ is somewhere other than the node we're filling,
7741 0 : // it may not be moved back to this node as part of filling. Ignore it
7742 0 : }
7743 : }
7744 : }
7745 :
7746 : // Step 2: also promote any AZ-agnostic shards as required to achieve the target number of attachments
7747 0 : let fill_requirement = locked.scheduler.compute_fill_requirement(node_id);
7748 0 :
7749 0 : let expected_attached = locked.scheduler.expected_attached_shard_count();
7750 0 : let nodes_by_load = locked.scheduler.nodes_by_attached_shard_count();
7751 0 :
7752 0 : let mut promoted_per_tenant: HashMap<TenantId, usize> = HashMap::new();
7753 :
7754 0 : for (node_id, attached) in nodes_by_load {
7755 0 : let available = locked.nodes.get(&node_id).is_some_and(|n| n.is_available());
7756 0 : if !available {
7757 0 : continue;
7758 0 : }
7759 0 :
7760 0 : if plan.len() >= fill_requirement
7761 0 : || free_tids_by_node.is_empty()
7762 0 : || attached <= expected_attached
7763 : {
7764 0 : break;
7765 0 : }
7766 0 :
7767 0 : let can_take = attached - expected_attached;
7768 0 : let needed = fill_requirement - plan.len();
7769 0 : let mut take = std::cmp::min(can_take, needed);
7770 0 :
7771 0 : let mut remove_node = false;
7772 0 : while take > 0 {
7773 0 : match free_tids_by_node.get_mut(&node_id) {
7774 0 : Some(tids) => match tids.pop() {
7775 0 : Some(tid) => {
7776 0 : let max_promote_for_tenant = std::cmp::max(
7777 0 : tid.shard_count.count() as usize / locked.nodes.len(),
7778 0 : 1,
7779 0 : );
7780 0 : let promoted = promoted_per_tenant.entry(tid.tenant_id).or_default();
7781 0 : if *promoted < max_promote_for_tenant {
7782 0 : plan.push(tid);
7783 0 : *promoted += 1;
7784 0 : take -= 1;
7785 0 : }
7786 : }
7787 : None => {
7788 0 : remove_node = true;
7789 0 : break;
7790 : }
7791 : },
7792 : None => {
7793 0 : break;
7794 : }
7795 : }
7796 : }
7797 :
7798 0 : if remove_node {
7799 0 : free_tids_by_node.remove(&node_id);
7800 0 : }
7801 : }
7802 :
7803 0 : plan
7804 0 : }
7805 :
7806 : /// Fill a node by promoting its secondaries until the cluster is balanced
7807 : /// with regards to attached shard counts. Note that this operation only
7808 : /// makes sense as a counterpart to the drain implemented in [`Service::drain_node`].
7809 : /// This is a long running operation and it should run as a separate Tokio task.
7810 0 : pub(crate) async fn fill_node(
7811 0 : &self,
7812 0 : node_id: NodeId,
7813 0 : cancel: CancellationToken,
7814 0 : ) -> Result<(), OperationError> {
7815 : const SECONDARY_WARMUP_TIMEOUT: Duration = Duration::from_secs(20);
7816 : const SECONDARY_DOWNLOAD_REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
7817 0 : let reconciler_config = ReconcilerConfigBuilder::new(ReconcilerPriority::Normal)
7818 0 : .secondary_warmup_timeout(SECONDARY_WARMUP_TIMEOUT)
7819 0 : .secondary_download_request_timeout(SECONDARY_DOWNLOAD_REQUEST_TIMEOUT)
7820 0 : .build();
7821 0 :
7822 0 : let mut tids_to_promote = self.fill_node_plan(node_id);
7823 0 : let mut waiters = Vec::new();
7824 :
7825 : // Execute the plan we've composed above. Before aplying each move from the plan,
7826 : // we validate to ensure that it has not gone stale in the meantime.
7827 0 : while !tids_to_promote.is_empty() {
7828 0 : if cancel.is_cancelled() {
7829 0 : match self
7830 0 : .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
7831 0 : .await
7832 : {
7833 0 : Ok(()) => return Err(OperationError::Cancelled),
7834 0 : Err(err) => {
7835 0 : return Err(OperationError::FinalizeError(
7836 0 : format!(
7837 0 : "Failed to finalise drain cancel of {} by setting scheduling policy to Active: {}",
7838 0 : node_id, err
7839 0 : )
7840 0 : .into(),
7841 0 : ));
7842 : }
7843 : }
7844 0 : }
7845 0 :
7846 0 : {
7847 0 : let mut locked = self.inner.write().unwrap();
7848 0 : let (nodes, tenants, scheduler) = locked.parts_mut();
7849 :
7850 0 : let node = nodes.get(&node_id).ok_or(OperationError::NodeStateChanged(
7851 0 : format!("node {node_id} was removed").into(),
7852 0 : ))?;
7853 :
7854 0 : let current_policy = node.get_scheduling();
7855 0 : if !matches!(current_policy, NodeSchedulingPolicy::Filling) {
7856 : // TODO(vlad): maybe cancel pending reconciles before erroring out. need to think
7857 : // about it
7858 0 : return Err(OperationError::NodeStateChanged(
7859 0 : format!("node {node_id} changed state to {current_policy:?}").into(),
7860 0 : ));
7861 0 : }
7862 :
7863 0 : while waiters.len() < MAX_RECONCILES_PER_OPERATION {
7864 0 : if let Some(tid) = tids_to_promote.pop() {
7865 0 : if let Some(tenant_shard) = tenants.get_mut(&tid) {
7866 : // If the node being filled is not a secondary anymore,
7867 : // skip the promotion.
7868 0 : if !tenant_shard.intent.get_secondary().contains(&node_id) {
7869 0 : continue;
7870 0 : }
7871 0 :
7872 0 : let previously_attached_to = *tenant_shard.intent.get_attached();
7873 0 : match tenant_shard.reschedule_to_secondary(Some(node_id), scheduler) {
7874 0 : Err(e) => {
7875 0 : tracing::warn!(
7876 0 : tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
7877 0 : "Scheduling error when filling pageserver {} : {e}", node_id
7878 : );
7879 : }
7880 : Ok(()) => {
7881 0 : tracing::info!(
7882 0 : tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
7883 0 : "Rescheduled shard while filling node {}: {:?} -> {}",
7884 : node_id,
7885 : previously_attached_to,
7886 : node_id
7887 : );
7888 :
7889 0 : if let Some(waiter) = self.maybe_configured_reconcile_shard(
7890 0 : tenant_shard,
7891 0 : nodes,
7892 0 : reconciler_config,
7893 0 : ) {
7894 0 : waiters.push(waiter);
7895 0 : }
7896 : }
7897 : }
7898 0 : }
7899 : } else {
7900 0 : break;
7901 : }
7902 : }
7903 : }
7904 :
7905 0 : waiters = self
7906 0 : .await_waiters_remainder(waiters, WAITER_FILL_DRAIN_POLL_TIMEOUT)
7907 0 : .await;
7908 : }
7909 :
7910 0 : while !waiters.is_empty() {
7911 0 : if cancel.is_cancelled() {
7912 0 : match self
7913 0 : .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
7914 0 : .await
7915 : {
7916 0 : Ok(()) => return Err(OperationError::Cancelled),
7917 0 : Err(err) => {
7918 0 : return Err(OperationError::FinalizeError(
7919 0 : format!(
7920 0 : "Failed to finalise drain cancel of {} by setting scheduling policy to Active: {}",
7921 0 : node_id, err
7922 0 : )
7923 0 : .into(),
7924 0 : ));
7925 : }
7926 : }
7927 0 : }
7928 0 :
7929 0 : tracing::info!("Awaiting {} pending fill reconciliations", waiters.len());
7930 :
7931 0 : waiters = self
7932 0 : .await_waiters_remainder(waiters, SHORT_RECONCILE_TIMEOUT)
7933 0 : .await;
7934 : }
7935 :
7936 0 : if let Err(err) = self
7937 0 : .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
7938 0 : .await
7939 : {
7940 : // This isn't a huge issue since the filling process starts upon request. However, it
7941 : // will prevent the next drain from starting. The only case in which this can fail
7942 : // is database unavailability. Such a case will require manual intervention.
7943 0 : return Err(OperationError::FinalizeError(
7944 0 : format!("Failed to finalise fill of {node_id} by setting scheduling policy to Active: {err}")
7945 0 : .into(),
7946 0 : ));
7947 0 : }
7948 0 :
7949 0 : Ok(())
7950 0 : }
7951 :
7952 : /// Updates scrubber metadata health check results.
7953 0 : pub(crate) async fn metadata_health_update(
7954 0 : &self,
7955 0 : update_req: MetadataHealthUpdateRequest,
7956 0 : ) -> Result<(), ApiError> {
7957 0 : let now = chrono::offset::Utc::now();
7958 0 : let (healthy_records, unhealthy_records) = {
7959 0 : let locked = self.inner.read().unwrap();
7960 0 : let healthy_records = update_req
7961 0 : .healthy_tenant_shards
7962 0 : .into_iter()
7963 0 : // Retain only health records associated with tenant shards managed by storage controller.
7964 0 : .filter(|tenant_shard_id| locked.tenants.contains_key(tenant_shard_id))
7965 0 : .map(|tenant_shard_id| MetadataHealthPersistence::new(tenant_shard_id, true, now))
7966 0 : .collect();
7967 0 : let unhealthy_records = update_req
7968 0 : .unhealthy_tenant_shards
7969 0 : .into_iter()
7970 0 : .filter(|tenant_shard_id| locked.tenants.contains_key(tenant_shard_id))
7971 0 : .map(|tenant_shard_id| MetadataHealthPersistence::new(tenant_shard_id, false, now))
7972 0 : .collect();
7973 0 :
7974 0 : (healthy_records, unhealthy_records)
7975 0 : };
7976 0 :
7977 0 : self.persistence
7978 0 : .update_metadata_health_records(healthy_records, unhealthy_records, now)
7979 0 : .await?;
7980 0 : Ok(())
7981 0 : }
7982 :
7983 : /// Lists the tenant shards that has unhealthy metadata status.
7984 0 : pub(crate) async fn metadata_health_list_unhealthy(
7985 0 : &self,
7986 0 : ) -> Result<Vec<TenantShardId>, ApiError> {
7987 0 : let result = self
7988 0 : .persistence
7989 0 : .list_unhealthy_metadata_health_records()
7990 0 : .await?
7991 0 : .iter()
7992 0 : .map(|p| p.get_tenant_shard_id().unwrap())
7993 0 : .collect();
7994 0 :
7995 0 : Ok(result)
7996 0 : }
7997 :
7998 : /// Lists the tenant shards that have not been scrubbed for some duration.
7999 0 : pub(crate) async fn metadata_health_list_outdated(
8000 0 : &self,
8001 0 : not_scrubbed_for: Duration,
8002 0 : ) -> Result<Vec<MetadataHealthRecord>, ApiError> {
8003 0 : let earlier = chrono::offset::Utc::now() - not_scrubbed_for;
8004 0 : let result = self
8005 0 : .persistence
8006 0 : .list_outdated_metadata_health_records(earlier)
8007 0 : .await?
8008 0 : .into_iter()
8009 0 : .map(|record| record.into())
8010 0 : .collect();
8011 0 : Ok(result)
8012 0 : }
8013 :
8014 0 : pub(crate) fn get_leadership_status(&self) -> LeadershipStatus {
8015 0 : self.inner.read().unwrap().get_leadership_status()
8016 0 : }
8017 :
8018 0 : pub(crate) async fn step_down(&self) -> GlobalObservedState {
8019 0 : tracing::info!("Received step down request from peer");
8020 0 : failpoint_support::sleep_millis_async!("sleep-on-step-down-handling");
8021 :
8022 0 : self.inner.write().unwrap().step_down();
8023 0 : // TODO: would it make sense to have a time-out for this?
8024 0 : self.stop_reconciliations(StopReconciliationsReason::SteppingDown)
8025 0 : .await;
8026 :
8027 0 : let mut global_observed = GlobalObservedState::default();
8028 0 : let locked = self.inner.read().unwrap();
8029 0 : for (tid, tenant_shard) in locked.tenants.iter() {
8030 0 : global_observed
8031 0 : .0
8032 0 : .insert(*tid, tenant_shard.observed.clone());
8033 0 : }
8034 :
8035 0 : global_observed
8036 0 : }
8037 :
8038 0 : pub(crate) async fn safekeepers_list(
8039 0 : &self,
8040 0 : ) -> Result<Vec<SafekeeperDescribeResponse>, DatabaseError> {
8041 0 : let locked = self.inner.read().unwrap();
8042 0 : let mut list = locked
8043 0 : .safekeepers
8044 0 : .iter()
8045 0 : .map(|sk| sk.1.describe_response())
8046 0 : .collect::<Result<Vec<_>, _>>()?;
8047 0 : list.sort_by_key(|v| v.id);
8048 0 : Ok(list)
8049 0 : }
8050 :
8051 0 : pub(crate) async fn get_safekeeper(
8052 0 : &self,
8053 0 : id: i64,
8054 0 : ) -> Result<SafekeeperDescribeResponse, DatabaseError> {
8055 0 : let locked = self.inner.read().unwrap();
8056 0 : let sk = locked
8057 0 : .safekeepers
8058 0 : .get(&NodeId(id as u64))
8059 0 : .ok_or(diesel::result::Error::NotFound)?;
8060 0 : sk.describe_response()
8061 0 : }
8062 :
8063 0 : pub(crate) async fn upsert_safekeeper(
8064 0 : &self,
8065 0 : record: crate::persistence::SafekeeperUpsert,
8066 0 : ) -> Result<(), DatabaseError> {
8067 0 : let node_id = NodeId(record.id as u64);
8068 0 : self.persistence.safekeeper_upsert(record.clone()).await?;
8069 :
8070 0 : if self.config.load_safekeepers {
8071 0 : let mut locked = self.inner.write().unwrap();
8072 0 : let mut safekeepers = (*locked.safekeepers).clone();
8073 0 : match safekeepers.entry(node_id) {
8074 0 : std::collections::hash_map::Entry::Occupied(mut entry) => {
8075 0 : entry.get_mut().update_from_record(record);
8076 0 : }
8077 0 : std::collections::hash_map::Entry::Vacant(entry) => {
8078 0 : entry.insert(Safekeeper::from_persistence(
8079 0 : crate::persistence::SafekeeperPersistence::from_upsert(
8080 0 : record,
8081 0 : SkSchedulingPolicy::Pause,
8082 0 : ),
8083 0 : CancellationToken::new(),
8084 0 : ));
8085 0 : }
8086 : }
8087 0 : locked.safekeepers = Arc::new(safekeepers);
8088 0 : }
8089 0 : Ok(())
8090 0 : }
8091 :
8092 0 : pub(crate) async fn set_safekeeper_scheduling_policy(
8093 0 : &self,
8094 0 : id: i64,
8095 0 : scheduling_policy: SkSchedulingPolicy,
8096 0 : ) -> Result<(), DatabaseError> {
8097 0 : self.persistence
8098 0 : .set_safekeeper_scheduling_policy(id, scheduling_policy)
8099 0 : .await?;
8100 0 : let node_id = NodeId(id as u64);
8101 0 : // After the change has been persisted successfully, update the in-memory state
8102 0 : if self.config.load_safekeepers {
8103 0 : let mut locked = self.inner.write().unwrap();
8104 0 : let mut safekeepers = (*locked.safekeepers).clone();
8105 0 : let sk = safekeepers
8106 0 : .get_mut(&node_id)
8107 0 : .ok_or(DatabaseError::Logical("Not found".to_string()))?;
8108 0 : sk.set_scheduling_policy(scheduling_policy);
8109 0 :
8110 0 : locked.safekeepers = Arc::new(safekeepers);
8111 0 : }
8112 0 : Ok(())
8113 0 : }
8114 :
8115 0 : pub(crate) async fn update_shards_preferred_azs(
8116 0 : &self,
8117 0 : req: ShardsPreferredAzsRequest,
8118 0 : ) -> Result<ShardsPreferredAzsResponse, ApiError> {
8119 0 : let preferred_azs = req.preferred_az_ids.into_iter().collect::<Vec<_>>();
8120 0 : let updated = self
8121 0 : .persistence
8122 0 : .set_tenant_shard_preferred_azs(preferred_azs)
8123 0 : .await
8124 0 : .map_err(|err| {
8125 0 : ApiError::InternalServerError(anyhow::anyhow!(
8126 0 : "Failed to persist preferred AZs: {err}"
8127 0 : ))
8128 0 : })?;
8129 :
8130 0 : let mut updated_in_mem_and_db = Vec::default();
8131 0 :
8132 0 : let mut locked = self.inner.write().unwrap();
8133 0 : for (tid, az_id) in updated {
8134 0 : let shard = locked.tenants.get_mut(&tid);
8135 0 : if let Some(shard) = shard {
8136 0 : shard.set_preferred_az(az_id);
8137 0 : updated_in_mem_and_db.push(tid);
8138 0 : }
8139 : }
8140 :
8141 0 : Ok(ShardsPreferredAzsResponse {
8142 0 : updated: updated_in_mem_and_db,
8143 0 : })
8144 0 : }
8145 : }
|