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