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