Line data Source code
1 : use std::collections::{HashMap, HashSet};
2 : use std::sync::Arc;
3 : use std::time::Duration;
4 :
5 : use futures::future::{self, Either};
6 : use itertools::Itertools;
7 : use pageserver_api::controller_api::{AvailabilityZone, PlacementPolicy, ShardSchedulingPolicy};
8 : use pageserver_api::models::{LocationConfig, LocationConfigMode, TenantConfig};
9 : use pageserver_api::shard::{ShardIdentity, TenantShardId};
10 : use serde::{Deserialize, Serialize};
11 : use tokio::task::JoinHandle;
12 : use tokio_util::sync::CancellationToken;
13 : use tracing::{Instrument, instrument};
14 : use utils::generation::Generation;
15 : use utils::id::NodeId;
16 : use utils::seqwait::{SeqWait, SeqWaitError};
17 : use utils::shard::ShardCount;
18 : use utils::sync::gate::GateGuard;
19 :
20 : use crate::compute_hook::ComputeHook;
21 : use crate::metrics::{
22 : self, ReconcileCompleteLabelGroup, ReconcileLongRunningLabelGroup, ReconcileOutcome,
23 : };
24 : use crate::node::Node;
25 : use crate::persistence::split_state::SplitState;
26 : use crate::persistence::{Persistence, TenantShardPersistence};
27 : use crate::reconciler::{
28 : ReconcileError, ReconcileUnits, Reconciler, ReconcilerConfig, TargetState,
29 : attached_location_conf, secondary_location_conf,
30 : };
31 : use crate::scheduler::{
32 : AffinityScore, AttachedShardTag, NodeSchedulingScore, NodeSecondarySchedulingScore,
33 : RefCountUpdate, ScheduleContext, ScheduleError, Scheduler, SecondaryShardTag, ShardTag,
34 : };
35 : use crate::service::ReconcileResultRequest;
36 : use crate::timeline_import::TimelineImportState;
37 : use crate::{Sequence, service};
38 :
39 : /// Serialization helper
40 0 : fn read_last_error<S, T>(v: &std::sync::Mutex<Option<T>>, serializer: S) -> Result<S::Ok, S::Error>
41 0 : where
42 0 : S: serde::ser::Serializer,
43 0 : T: std::fmt::Display,
44 : {
45 0 : serializer.collect_str(
46 0 : &v.lock()
47 0 : .unwrap()
48 0 : .as_ref()
49 0 : .map(|e| format!("{e}"))
50 0 : .unwrap_or("".to_string()),
51 : )
52 0 : }
53 :
54 : /// In-memory state for a particular tenant shard.
55 : ///
56 : /// This struct implement Serialize for debugging purposes, but is _not_ persisted
57 : /// itself: see [`crate::persistence`] for the subset of tenant shard state that is persisted.
58 : #[derive(Serialize)]
59 : pub(crate) struct TenantShard {
60 : pub(crate) tenant_shard_id: TenantShardId,
61 :
62 : pub(crate) shard: ShardIdentity,
63 :
64 : // Runtime only: sequence used to coordinate when updating this object while
65 : // with background reconcilers may be running. A reconciler runs to a particular
66 : // sequence.
67 : pub(crate) sequence: Sequence,
68 :
69 : // Latest generation number: next time we attach, increment this
70 : // and use the incremented number when attaching.
71 : //
72 : // None represents an incompletely onboarded tenant via the [`Service::location_config`]
73 : // API, where this tenant may only run in PlacementPolicy::Secondary.
74 : pub(crate) generation: Option<Generation>,
75 :
76 : // High level description of how the tenant should be set up. Provided
77 : // externally.
78 : pub(crate) policy: PlacementPolicy,
79 :
80 : // Low level description of exactly which pageservers should fulfil
81 : // which role. Generated by `Self::schedule`.
82 : pub(crate) intent: IntentState,
83 :
84 : // Low level description of how the tenant is configured on pageservers:
85 : // if this does not match `Self::intent` then the tenant needs reconciliation
86 : // with `Self::reconcile`.
87 : pub(crate) observed: ObservedState,
88 :
89 : // Tenant configuration, passed through opaquely to the pageserver. Identical
90 : // for all shards in a tenant.
91 : pub(crate) config: TenantConfig,
92 :
93 : /// If a reconcile task is currently in flight, it may be joined here (it is
94 : /// only safe to join if either the result has been received or the reconciler's
95 : /// cancellation token has been fired)
96 : #[serde(skip)]
97 : pub(crate) reconciler: Option<ReconcilerHandle>,
98 :
99 : /// If a tenant is being split, then all shards with that TenantId will have a
100 : /// SplitState set, this acts as a guard against other operations such as background
101 : /// reconciliation, and timeline creation.
102 : pub(crate) splitting: SplitState,
103 :
104 : /// Flag indicating whether the tenant has an in-progress timeline import.
105 : /// Used to disallow shard splits while an import is in progress.
106 : pub(crate) importing: TimelineImportState,
107 :
108 : /// If a tenant was enqueued for later reconcile due to hitting concurrency limit, this flag
109 : /// is set. This flag is cleared when the tenant is popped off the delay queue.
110 : pub(crate) delayed_reconcile: bool,
111 :
112 : /// Optionally wait for reconciliation to complete up to a particular
113 : /// sequence number.
114 : #[serde(skip)]
115 : pub(crate) waiter: std::sync::Arc<SeqWait<Sequence, Sequence>>,
116 :
117 : /// Indicates sequence number for which we have encountered an error reconciling. If
118 : /// this advances ahead of [`Self::waiter`] then a reconciliation error has occurred,
119 : /// and callers should stop waiting for `waiter` and propagate the error.
120 : #[serde(skip)]
121 : pub(crate) error_waiter: std::sync::Arc<SeqWait<Sequence, Sequence>>,
122 :
123 : /// The most recent error from a reconcile on this tenant. This is a nested Arc
124 : /// because:
125 : /// - ReconcileWaiters need to Arc-clone the overall object to read it later
126 : /// - ReconcileWaitError needs to use an `Arc<ReconcileError>` because we can construct
127 : /// many waiters for one shard, and the underlying error types are not Clone.
128 : ///
129 : /// TODO: generalize to an array of recent events
130 : /// TOOD: use a ArcSwap instead of mutex for faster reads?
131 : #[serde(serialize_with = "read_last_error")]
132 : pub(crate) last_error: std::sync::Arc<std::sync::Mutex<Option<Arc<ReconcileError>>>>,
133 :
134 : /// Amount of consecutive [`crate::service::Service::reconcile_all`] iterations that have been
135 : /// scheduled a reconciliation for this shard.
136 : ///
137 : /// If this reaches `MAX_CONSECUTIVE_RECONCILES`, the shard is considered "stuck" and will be
138 : /// ignored when deciding whether optimizations can run. This includes both successful and failed
139 : /// reconciliations.
140 : ///
141 : /// Incremented in [`crate::service::Service::process_result`], and reset to 0 when
142 : /// [`crate::service::Service::reconcile_all`] determines no reconciliation is needed for this shard.
143 : pub(crate) consecutive_reconciles_count: usize,
144 :
145 : /// If we have a pending compute notification that for some reason we weren't able to send,
146 : /// set this to true. If this is set, calls to [`Self::get_reconcile_needed`] will return Yes
147 : /// and trigger a Reconciler run. This is the mechanism by which compute notifications are included in the scope
148 : /// of state that we publish externally in an eventually consistent way.
149 : pub(crate) pending_compute_notification: bool,
150 :
151 : /// To do a graceful migration, set this field to the destination pageserver, and optimization
152 : /// functions will consider this node the best location and react appropriately.
153 : preferred_node: Option<NodeId>,
154 :
155 : // Support/debug tool: if something is going wrong or flapping with scheduling, this may
156 : // be set to a non-active state to avoid making changes while the issue is fixed.
157 : scheduling_policy: ShardSchedulingPolicy,
158 : }
159 :
160 : #[derive(Clone, Debug, Serialize)]
161 : pub(crate) struct IntentState {
162 : attached: Option<NodeId>,
163 : secondary: Vec<NodeId>,
164 :
165 : // We should attempt to schedule this shard in the provided AZ to
166 : // decrease chances of cross-AZ compute.
167 : preferred_az_id: Option<AvailabilityZone>,
168 : }
169 :
170 : impl IntentState {
171 12860 : pub(crate) fn new(preferred_az_id: Option<AvailabilityZone>) -> Self {
172 12860 : Self {
173 12860 : attached: None,
174 12860 : secondary: vec![],
175 12860 : preferred_az_id,
176 12860 : }
177 12860 : }
178 0 : pub(crate) fn single(
179 0 : scheduler: &mut Scheduler,
180 0 : node_id: Option<NodeId>,
181 0 : preferred_az_id: Option<AvailabilityZone>,
182 0 : ) -> Self {
183 0 : if let Some(node_id) = node_id {
184 0 : scheduler.update_node_ref_counts(
185 0 : node_id,
186 0 : preferred_az_id.as_ref(),
187 0 : RefCountUpdate::Attach,
188 0 : );
189 0 : }
190 0 : Self {
191 0 : attached: node_id,
192 0 : secondary: vec![],
193 0 : preferred_az_id,
194 0 : }
195 0 : }
196 :
197 12859 : pub(crate) fn set_attached(&mut self, scheduler: &mut Scheduler, new_attached: Option<NodeId>) {
198 12859 : if self.attached != new_attached {
199 12859 : if let Some(old_attached) = self.attached.take() {
200 0 : scheduler.update_node_ref_counts(
201 0 : old_attached,
202 0 : self.preferred_az_id.as_ref(),
203 0 : RefCountUpdate::Detach,
204 0 : );
205 12859 : }
206 12859 : if let Some(new_attached) = &new_attached {
207 12859 : scheduler.update_node_ref_counts(
208 12859 : *new_attached,
209 12859 : self.preferred_az_id.as_ref(),
210 12859 : RefCountUpdate::Attach,
211 12859 : );
212 12859 : }
213 12859 : self.attached = new_attached;
214 0 : }
215 :
216 12859 : if let Some(new_attached) = &new_attached {
217 12859 : assert!(!self.secondary.contains(new_attached));
218 0 : }
219 12859 : }
220 :
221 : /// Like set_attached, but the node is from [`Self::secondary`]. This swaps the node from
222 : /// secondary to attached while maintaining the scheduler's reference counts.
223 7 : pub(crate) fn promote_attached(
224 7 : &mut self,
225 7 : scheduler: &mut Scheduler,
226 7 : promote_secondary: NodeId,
227 7 : ) {
228 : // If we call this with a node that isn't in secondary, it would cause incorrect
229 : // scheduler reference counting, since we assume the node is already referenced as a secondary.
230 7 : debug_assert!(self.secondary.contains(&promote_secondary));
231 :
232 16 : self.secondary.retain(|n| n != &promote_secondary);
233 :
234 7 : let demoted = self.attached;
235 7 : self.attached = Some(promote_secondary);
236 :
237 7 : scheduler.update_node_ref_counts(
238 7 : promote_secondary,
239 7 : self.preferred_az_id.as_ref(),
240 7 : RefCountUpdate::PromoteSecondary,
241 : );
242 7 : if let Some(demoted) = demoted {
243 0 : scheduler.update_node_ref_counts(
244 0 : demoted,
245 0 : self.preferred_az_id.as_ref(),
246 0 : RefCountUpdate::DemoteAttached,
247 0 : );
248 7 : }
249 7 : }
250 :
251 12848 : pub(crate) fn push_secondary(&mut self, scheduler: &mut Scheduler, new_secondary: NodeId) {
252 : // Every assertion here should probably have a corresponding check in
253 : // `validate_optimization` unless it is an invariant that should never be violated. Note
254 : // that the lock is not held between planning optimizations and applying them so you have to
255 : // assume any valid state transition of the intent state may have occurred
256 12848 : assert!(!self.secondary.contains(&new_secondary));
257 12848 : assert!(self.attached != Some(new_secondary));
258 12848 : scheduler.update_node_ref_counts(
259 12848 : new_secondary,
260 12848 : self.preferred_az_id.as_ref(),
261 12848 : RefCountUpdate::AddSecondary,
262 : );
263 12848 : self.secondary.push(new_secondary);
264 12848 : }
265 :
266 : /// It is legal to call this with a node that is not currently a secondary: that is a no-op
267 9 : pub(crate) fn remove_secondary(&mut self, scheduler: &mut Scheduler, node_id: NodeId) {
268 13 : let index = self.secondary.iter().position(|n| *n == node_id);
269 9 : if let Some(index) = index {
270 9 : scheduler.update_node_ref_counts(
271 9 : node_id,
272 9 : self.preferred_az_id.as_ref(),
273 9 : RefCountUpdate::RemoveSecondary,
274 9 : );
275 9 : self.secondary.remove(index);
276 9 : }
277 9 : }
278 :
279 12859 : pub(crate) fn clear_secondary(&mut self, scheduler: &mut Scheduler) {
280 12859 : for secondary in self.secondary.drain(..) {
281 12840 : scheduler.update_node_ref_counts(
282 12840 : secondary,
283 12840 : self.preferred_az_id.as_ref(),
284 12840 : RefCountUpdate::RemoveSecondary,
285 12840 : );
286 12840 : }
287 12859 : }
288 :
289 : /// Remove the last secondary node from the list of secondaries
290 0 : pub(crate) fn pop_secondary(&mut self, scheduler: &mut Scheduler) {
291 0 : if let Some(node_id) = self.secondary.pop() {
292 0 : scheduler.update_node_ref_counts(
293 0 : node_id,
294 0 : self.preferred_az_id.as_ref(),
295 0 : RefCountUpdate::RemoveSecondary,
296 0 : );
297 0 : }
298 0 : }
299 :
300 12859 : pub(crate) fn clear(&mut self, scheduler: &mut Scheduler) {
301 12859 : if let Some(old_attached) = self.attached.take() {
302 12857 : scheduler.update_node_ref_counts(
303 12857 : old_attached,
304 12857 : self.preferred_az_id.as_ref(),
305 12857 : RefCountUpdate::Detach,
306 12857 : );
307 12857 : }
308 :
309 12859 : self.clear_secondary(scheduler);
310 12859 : }
311 :
312 12901 : pub(crate) fn all_pageservers(&self) -> Vec<NodeId> {
313 12901 : let mut result = Vec::new();
314 12901 : if let Some(p) = self.attached {
315 12896 : result.push(p)
316 5 : }
317 :
318 12901 : result.extend(self.secondary.iter().copied());
319 :
320 12901 : result
321 12901 : }
322 :
323 12624 : pub(crate) fn get_attached(&self) -> &Option<NodeId> {
324 12624 : &self.attached
325 12624 : }
326 :
327 12706 : pub(crate) fn get_secondary(&self) -> &Vec<NodeId> {
328 12706 : &self.secondary
329 12706 : }
330 :
331 : /// If the node is in use as the attached location, demote it into
332 : /// the list of secondary locations. This is used when a node goes offline,
333 : /// and we want to use a different node for attachment, but not permanently
334 : /// forget the location on the offline node.
335 : ///
336 : /// Returns true if a change was made
337 8 : pub(crate) fn demote_attached(&mut self, scheduler: &mut Scheduler, node_id: NodeId) -> bool {
338 8 : if self.attached == Some(node_id) {
339 8 : self.attached = None;
340 8 : self.secondary.push(node_id);
341 8 : scheduler.update_node_ref_counts(
342 8 : node_id,
343 8 : self.preferred_az_id.as_ref(),
344 8 : RefCountUpdate::DemoteAttached,
345 : );
346 8 : true
347 : } else {
348 0 : false
349 : }
350 8 : }
351 :
352 2 : pub(crate) fn set_preferred_az(
353 2 : &mut self,
354 2 : scheduler: &mut Scheduler,
355 2 : preferred_az: Option<AvailabilityZone>,
356 2 : ) {
357 2 : let new_az = preferred_az.as_ref();
358 2 : let old_az = self.preferred_az_id.as_ref();
359 :
360 2 : if old_az != new_az {
361 2 : if let Some(node_id) = self.attached {
362 2 : scheduler.update_node_ref_counts(
363 2 : node_id,
364 2 : new_az,
365 2 : RefCountUpdate::ChangePreferredAzFrom(old_az),
366 2 : );
367 2 : }
368 4 : for node_id in &self.secondary {
369 2 : scheduler.update_node_ref_counts(
370 2 : *node_id,
371 2 : new_az,
372 2 : RefCountUpdate::ChangePreferredAzFrom(old_az),
373 2 : );
374 2 : }
375 2 : self.preferred_az_id = preferred_az;
376 0 : }
377 2 : }
378 :
379 12508 : pub(crate) fn get_preferred_az(&self) -> Option<&AvailabilityZone> {
380 12508 : self.preferred_az_id.as_ref()
381 12508 : }
382 : }
383 :
384 : impl Drop for IntentState {
385 12860 : fn drop(&mut self) {
386 : // Must clear before dropping, to avoid leaving stale refcounts in the Scheduler.
387 : // We do not check this while panicking, to avoid polluting unit test failures or
388 : // other assertions with this assertion's output. It's still wrong to leak these,
389 : // but if we already have a panic then we don't need to independently flag this case.
390 12860 : if !(std::thread::panicking()) {
391 12860 : debug_assert!(self.attached.is_none() && self.secondary.is_empty());
392 0 : }
393 12859 : }
394 : }
395 :
396 0 : #[derive(Default, Clone, Serialize, Deserialize, Debug)]
397 : pub(crate) struct ObservedState {
398 : pub(crate) locations: HashMap<NodeId, ObservedStateLocation>,
399 : }
400 :
401 : /// Our latest knowledge of how this tenant is configured in the outside world.
402 : ///
403 : /// Meaning:
404 : /// * No instance of this type exists for a node: we are certain that we have nothing configured on that
405 : /// node for this shard.
406 : /// * Instance exists with conf==None: we *might* have some state on that node, but we don't know
407 : /// what it is (e.g. we failed partway through configuring it)
408 : /// * Instance exists with conf==Some: this tells us what we last successfully configured on this node,
409 : /// and that configuration will still be present unless something external interfered.
410 0 : #[derive(Clone, Serialize, Deserialize, Debug)]
411 : pub(crate) struct ObservedStateLocation {
412 : /// If None, it means we do not know the status of this shard's location on this node, but
413 : /// we know that we might have some state on this node.
414 : pub(crate) conf: Option<LocationConfig>,
415 : }
416 :
417 : pub(crate) struct ReconcilerWaiter {
418 : // For observability purposes, remember the ID of the shard we're
419 : // waiting for.
420 : pub(crate) tenant_shard_id: TenantShardId,
421 :
422 : seq_wait: std::sync::Arc<SeqWait<Sequence, Sequence>>,
423 : error_seq_wait: std::sync::Arc<SeqWait<Sequence, Sequence>>,
424 : error: std::sync::Arc<std::sync::Mutex<Option<Arc<ReconcileError>>>>,
425 : seq: Sequence,
426 : }
427 :
428 : pub(crate) enum ReconcilerStatus {
429 : Done,
430 : Failed,
431 : InProgress,
432 : }
433 :
434 : #[derive(thiserror::Error, Debug)]
435 : pub(crate) enum ReconcileWaitError {
436 : #[error("Timeout waiting for shard {0}")]
437 : Timeout(TenantShardId),
438 : #[error("shutting down")]
439 : Shutdown,
440 : #[error("Reconcile error on shard {0}: {1}")]
441 : Failed(TenantShardId, Arc<ReconcileError>),
442 : }
443 :
444 : #[derive(Eq, PartialEq, Debug, Clone)]
445 : pub(crate) struct ReplaceSecondary {
446 : old_node_id: NodeId,
447 : new_node_id: NodeId,
448 : }
449 :
450 : #[derive(Eq, PartialEq, Debug, Clone)]
451 : pub(crate) struct MigrateAttachment {
452 : pub(crate) old_attached_node_id: NodeId,
453 : pub(crate) new_attached_node_id: NodeId,
454 : }
455 :
456 : #[derive(Eq, PartialEq, Debug, Clone)]
457 : pub(crate) enum ScheduleOptimizationAction {
458 : // Replace one of our secondary locations with a different node
459 : ReplaceSecondary(ReplaceSecondary),
460 : // Migrate attachment to an existing secondary location
461 : MigrateAttachment(MigrateAttachment),
462 : // Create a secondary location, with the intent of later migrating to it
463 : CreateSecondary(NodeId),
464 : // Remove a secondary location that we previously created to facilitate a migration
465 : RemoveSecondary(NodeId),
466 : }
467 :
468 : #[derive(Eq, PartialEq, Debug, Clone)]
469 : pub(crate) struct ScheduleOptimization {
470 : // What was the reconcile sequence when we generated this optimization? The optimization
471 : // should only be applied if the shard's sequence is still at this value, in case other changes
472 : // happened between planning the optimization and applying it.
473 : sequence: Sequence,
474 :
475 : pub(crate) action: ScheduleOptimizationAction,
476 : }
477 :
478 : impl ReconcilerWaiter {
479 0 : pub(crate) async fn wait_timeout(&self, timeout: Duration) -> Result<(), ReconcileWaitError> {
480 0 : tokio::select! {
481 0 : result = self.seq_wait.wait_for_timeout(self.seq, timeout)=> {
482 0 : result.map_err(|e| match e {
483 0 : SeqWaitError::Timeout => ReconcileWaitError::Timeout(self.tenant_shard_id),
484 0 : SeqWaitError::Shutdown => ReconcileWaitError::Shutdown
485 0 : })?;
486 : },
487 0 : result = self.error_seq_wait.wait_for(self.seq) => {
488 0 : result.map_err(|e| match e {
489 0 : SeqWaitError::Shutdown => ReconcileWaitError::Shutdown,
490 0 : SeqWaitError::Timeout => unreachable!()
491 0 : })?;
492 :
493 0 : return Err(ReconcileWaitError::Failed(self.tenant_shard_id,
494 0 : self.error.lock().unwrap().clone().expect("If error_seq_wait was advanced error was set").clone()))
495 : }
496 : }
497 :
498 0 : Ok(())
499 0 : }
500 :
501 0 : pub(crate) fn get_status(&self) -> ReconcilerStatus {
502 0 : if self.seq_wait.would_wait_for(self.seq).is_ok() {
503 0 : ReconcilerStatus::Done
504 0 : } else if self.error_seq_wait.would_wait_for(self.seq).is_ok() {
505 0 : ReconcilerStatus::Failed
506 : } else {
507 0 : ReconcilerStatus::InProgress
508 : }
509 0 : }
510 : }
511 :
512 : /// Having spawned a reconciler task, the tenant shard's state will carry enough
513 : /// information to optionally cancel & await it later.
514 : pub(crate) struct ReconcilerHandle {
515 : sequence: Sequence,
516 : handle: JoinHandle<()>,
517 : cancel: CancellationToken,
518 : }
519 :
520 : pub(crate) enum ReconcileNeeded {
521 : /// shard either doesn't need reconciliation, or is forbidden from spawning a reconciler
522 : /// in its current state (e.g. shard split in progress, or ShardSchedulingPolicy forbids it)
523 : No,
524 : /// shard has a reconciler running, and its intent hasn't changed since that one was
525 : /// spawned: wait for the existing reconciler rather than spawning a new one.
526 : WaitExisting(ReconcilerWaiter),
527 : /// shard needs reconciliation: call into [`TenantShard::spawn_reconciler`]
528 : Yes(ReconcileReason),
529 : }
530 :
531 : #[derive(Debug)]
532 : pub(crate) enum ReconcileReason {
533 : ActiveNodesDirty,
534 : UnknownLocation,
535 : PendingComputeNotification,
536 : }
537 :
538 : /// Pending modification to the observed state of a tenant shard.
539 : /// Produced by [`Reconciler::observed_deltas`] and applied in [`crate::service::Service::process_result`].
540 : pub(crate) enum ObservedStateDelta {
541 : Upsert(Box<(NodeId, ObservedStateLocation)>),
542 : Delete(NodeId),
543 : }
544 :
545 : impl ObservedStateDelta {
546 0 : pub(crate) fn node_id(&self) -> &NodeId {
547 0 : match self {
548 0 : Self::Upsert(up) => &up.0,
549 0 : Self::Delete(nid) => nid,
550 : }
551 0 : }
552 : }
553 :
554 : /// When a reconcile task completes, it sends this result object
555 : /// to be applied to the primary TenantShard.
556 : pub(crate) struct ReconcileResult {
557 : pub(crate) sequence: Sequence,
558 : /// On errors, `observed` should be treated as an incompleted description
559 : /// of state (i.e. any nodes present in the result should override nodes
560 : /// present in the parent tenant state, but any unmentioned nodes should
561 : /// not be removed from parent tenant state)
562 : pub(crate) result: Result<(), ReconcileError>,
563 :
564 : pub(crate) tenant_shard_id: TenantShardId,
565 : pub(crate) generation: Option<Generation>,
566 : pub(crate) observed_deltas: Vec<ObservedStateDelta>,
567 :
568 : /// Set [`TenantShard::pending_compute_notification`] from this flag
569 : pub(crate) pending_compute_notification: bool,
570 : }
571 :
572 : impl ObservedState {
573 0 : pub(crate) fn new() -> Self {
574 0 : Self {
575 0 : locations: HashMap::new(),
576 0 : }
577 0 : }
578 :
579 0 : pub(crate) fn is_empty(&self) -> bool {
580 0 : self.locations.is_empty()
581 0 : }
582 : }
583 :
584 : impl TenantShard {
585 12843 : pub(crate) fn new(
586 12843 : tenant_shard_id: TenantShardId,
587 12843 : shard: ShardIdentity,
588 12843 : policy: PlacementPolicy,
589 12843 : preferred_az_id: Option<AvailabilityZone>,
590 12843 : ) -> Self {
591 12843 : metrics::METRICS_REGISTRY
592 12843 : .metrics_group
593 12843 : .storage_controller_tenant_shards
594 12843 : .inc();
595 :
596 12843 : Self {
597 12843 : tenant_shard_id,
598 12843 : policy,
599 12843 : intent: IntentState::new(preferred_az_id),
600 12843 : generation: Some(Generation::new(0)),
601 12843 : shard,
602 12843 : observed: ObservedState::default(),
603 12843 : config: TenantConfig::default(),
604 12843 : reconciler: None,
605 12843 : splitting: SplitState::Idle,
606 12843 : importing: TimelineImportState::Idle,
607 12843 : sequence: Sequence(1),
608 12843 : delayed_reconcile: false,
609 12843 : waiter: Arc::new(SeqWait::new(Sequence(0))),
610 12843 : error_waiter: Arc::new(SeqWait::new(Sequence(0))),
611 12843 : last_error: Arc::default(),
612 12843 : consecutive_reconciles_count: 0,
613 12843 : pending_compute_notification: false,
614 12843 : scheduling_policy: ShardSchedulingPolicy::default(),
615 12843 : preferred_node: None,
616 12843 : }
617 12843 : }
618 :
619 : /// For use on startup when learning state from pageservers: generate my [`IntentState`] from my
620 : /// [`ObservedState`], even if it violates my [`PlacementPolicy`]. Call [`Self::schedule`] next,
621 : /// to get an intent state that complies with placement policy. The overall goal is to do scheduling
622 : /// in a way that makes use of any configured locations that already exist in the outside world.
623 1 : pub(crate) fn intent_from_observed(&mut self, scheduler: &mut Scheduler) {
624 : // Choose an attached location by filtering observed locations, and then sorting to get the highest
625 : // generation
626 1 : let mut attached_locs = self
627 1 : .observed
628 1 : .locations
629 1 : .iter()
630 2 : .filter_map(|(node_id, l)| {
631 2 : if let Some(conf) = &l.conf {
632 2 : if conf.mode == LocationConfigMode::AttachedMulti
633 1 : || conf.mode == LocationConfigMode::AttachedSingle
634 1 : || conf.mode == LocationConfigMode::AttachedStale
635 : {
636 2 : Some((node_id, conf.generation))
637 : } else {
638 0 : None
639 : }
640 : } else {
641 0 : None
642 : }
643 2 : })
644 1 : .collect::<Vec<_>>();
645 :
646 1 : attached_locs.sort_by_key(|i| i.1);
647 1 : if let Some((node_id, _gen)) = attached_locs.into_iter().next_back() {
648 1 : self.intent.set_attached(scheduler, Some(*node_id));
649 1 : }
650 :
651 : // All remaining observed locations generate secondary intents. This includes None
652 : // observations, as these may well have some local content on disk that is usable (this
653 : // is an edge case that might occur if we restarted during a migration or other change)
654 : //
655 : // We may leave intent.attached empty if we didn't find any attached locations: [`Self::schedule`]
656 : // will take care of promoting one of these secondaries to be attached.
657 2 : self.observed.locations.keys().for_each(|node_id| {
658 2 : if Some(*node_id) != self.intent.attached {
659 1 : self.intent.push_secondary(scheduler, *node_id);
660 1 : }
661 2 : });
662 1 : }
663 :
664 : /// Part of [`Self::schedule`] that is used to choose exactly one node to act as the
665 : /// attached pageserver for a shard.
666 : ///
667 : /// Returns whether we modified it, and the NodeId selected.
668 12832 : fn schedule_attached(
669 12832 : &mut self,
670 12832 : scheduler: &mut Scheduler,
671 12832 : context: &ScheduleContext,
672 12832 : ) -> Result<(bool, NodeId), ScheduleError> {
673 : // No work to do if we already have an attached tenant
674 12832 : if let Some(node_id) = self.intent.attached {
675 0 : return Ok((false, node_id));
676 12832 : }
677 :
678 12832 : if let Some(promote_secondary) = self.preferred_secondary(scheduler) {
679 : // Promote a secondary
680 2 : tracing::debug!("Promoted secondary {} to attached", promote_secondary);
681 2 : self.intent.promote_attached(scheduler, promote_secondary);
682 2 : Ok((true, promote_secondary))
683 : } else {
684 : // Pick a fresh node: either we had no secondaries or none were schedulable
685 12830 : let node_id = scheduler.schedule_shard::<AttachedShardTag>(
686 12830 : &self.intent.secondary,
687 12830 : &self.intent.preferred_az_id,
688 12830 : context,
689 0 : )?;
690 12830 : tracing::debug!("Selected {} as attached", node_id);
691 12830 : self.intent.set_attached(scheduler, Some(node_id));
692 12830 : Ok((true, node_id))
693 : }
694 12832 : }
695 :
696 : #[instrument(skip_all, fields(
697 : tenant_id=%self.tenant_shard_id.tenant_id,
698 : shard_id=%self.tenant_shard_id.shard_slug(),
699 : sequence=%self.sequence
700 : ))]
701 : pub(crate) fn schedule(
702 : &mut self,
703 : scheduler: &mut Scheduler,
704 : context: &mut ScheduleContext,
705 : ) -> Result<(), ScheduleError> {
706 : let r = self.do_schedule(scheduler, context);
707 :
708 : context.avoid(&self.intent.all_pageservers());
709 :
710 : r
711 : }
712 :
713 12836 : pub(crate) fn do_schedule(
714 12836 : &mut self,
715 12836 : scheduler: &mut Scheduler,
716 12836 : context: &ScheduleContext,
717 12836 : ) -> Result<(), ScheduleError> {
718 : // TODO: before scheduling new nodes, check if any existing content in
719 : // self.intent refers to pageservers that are offline, and pick other
720 : // pageservers if so.
721 :
722 : // TODO: respect the splitting bit on tenants: if they are currently splitting then we may not
723 : // change their attach location.
724 :
725 12836 : match self.scheduling_policy {
726 12835 : ShardSchedulingPolicy::Active | ShardSchedulingPolicy::Essential => {}
727 : ShardSchedulingPolicy::Pause | ShardSchedulingPolicy::Stop => {
728 : // Warn to make it obvious why other things aren't happening/working, if we skip scheduling
729 1 : tracing::warn!(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(),
730 0 : "Scheduling is disabled by policy {:?}", self.scheduling_policy);
731 1 : return Ok(());
732 : }
733 : }
734 :
735 : // Build the set of pageservers already in use by this tenant, to avoid scheduling
736 : // more work on the same pageservers we're already using.
737 12835 : let mut modified = false;
738 :
739 : // Add/remove nodes to fulfil policy
740 : use PlacementPolicy::*;
741 12835 : match self.policy {
742 12832 : Attached(secondary_count) => {
743 : // Should have exactly one attached, and at least N secondaries
744 12832 : let (modified_attached, attached_node_id) =
745 12832 : self.schedule_attached(scheduler, context)?;
746 12832 : modified |= modified_attached;
747 :
748 12832 : let mut used_pageservers = vec![attached_node_id];
749 25663 : while self.intent.secondary.len() < secondary_count {
750 12831 : let node_id = scheduler.schedule_shard::<SecondaryShardTag>(
751 12831 : &used_pageservers,
752 12831 : &self.intent.preferred_az_id,
753 12831 : context,
754 0 : )?;
755 12831 : self.intent.push_secondary(scheduler, node_id);
756 12831 : used_pageservers.push(node_id);
757 12831 : modified = true;
758 : }
759 : }
760 : Secondary => {
761 3 : if let Some(node_id) = self.intent.get_attached() {
762 2 : // Populate secondary by demoting the attached node
763 2 : self.intent.demote_attached(scheduler, *node_id);
764 2 :
765 2 : modified = true;
766 2 : } else if self.intent.secondary.is_empty() {
767 : // Populate secondary by scheduling a fresh node
768 : //
769 : // We use [`AttachedShardTag`] because when a secondary location is the only one
770 : // a shard has, we expect that its next use will be as an attached location: we want
771 : // the tenant to be ready to warm up and run fast in their preferred AZ.
772 1 : let node_id = scheduler.schedule_shard::<AttachedShardTag>(
773 1 : &[],
774 1 : &self.intent.preferred_az_id,
775 1 : context,
776 0 : )?;
777 1 : self.intent.push_secondary(scheduler, node_id);
778 1 : modified = true;
779 0 : }
780 4 : while self.intent.secondary.len() > 1 {
781 : // If we have multiple secondaries (e.g. when transitioning from Attached to Secondary and
782 : // having just demoted our attached location), then we should prefer to keep the location
783 : // in our preferred AZ. Tenants in Secondary mode want to be in the preferred AZ so that
784 : // they have a warm location to become attached when transitioning back into Attached.
785 :
786 1 : let mut candidates = self.intent.get_secondary().clone();
787 : // Sort to get secondaries outside preferred AZ last
788 1 : candidates
789 2 : .sort_by_key(|n| scheduler.get_node_az(n).as_ref() != self.preferred_az());
790 1 : let secondary_to_remove = candidates.pop().unwrap();
791 1 : self.intent.remove_secondary(scheduler, secondary_to_remove);
792 1 : modified = true;
793 : }
794 : }
795 : Detached => {
796 : // Never add locations in this mode
797 0 : if self.intent.get_attached().is_some() || !self.intent.get_secondary().is_empty() {
798 0 : self.intent.clear(scheduler);
799 0 : modified = true;
800 0 : }
801 : }
802 : }
803 :
804 12835 : if modified {
805 12835 : self.sequence.0 += 1;
806 12835 : }
807 :
808 12835 : Ok(())
809 12836 : }
810 :
811 : /// Reschedule this tenant shard to one of its secondary locations. Returns a scheduling error
812 : /// if the swap is not possible and leaves the intent state in its original state.
813 : ///
814 : /// Arguments:
815 : /// `promote_to`: an optional secondary location of this tenant shard. If set to None, we ask
816 : /// the scheduler to recommend a node
817 0 : pub(crate) fn reschedule_to_secondary(
818 0 : &mut self,
819 0 : promote_to: Option<NodeId>,
820 0 : scheduler: &mut Scheduler,
821 0 : ) -> Result<(), ScheduleError> {
822 0 : let promote_to = match promote_to {
823 0 : Some(node) => node,
824 0 : None => match self.preferred_secondary(scheduler) {
825 0 : Some(node) => node,
826 : None => {
827 0 : return Err(ScheduleError::ImpossibleConstraint);
828 : }
829 : },
830 : };
831 :
832 0 : assert!(self.intent.get_secondary().contains(&promote_to));
833 :
834 0 : if let Some(node) = self.intent.get_attached() {
835 0 : let demoted = self.intent.demote_attached(scheduler, *node);
836 0 : if !demoted {
837 0 : return Err(ScheduleError::ImpossibleConstraint);
838 0 : }
839 0 : }
840 :
841 0 : self.intent.promote_attached(scheduler, promote_to);
842 :
843 : // Increment the sequence number for the edge case where a
844 : // reconciler is already running to avoid waiting on the
845 : // current reconcile instead of spawning a new one.
846 0 : self.sequence = self.sequence.next();
847 :
848 0 : Ok(())
849 0 : }
850 :
851 : /// Returns None if the current location's score is unavailable, i.e. cannot draw a conclusion
852 68 : fn is_better_location<T: ShardTag>(
853 68 : &self,
854 68 : scheduler: &mut Scheduler,
855 68 : schedule_context: &ScheduleContext,
856 68 : current: NodeId,
857 68 : candidate: NodeId,
858 68 : ) -> Option<bool> {
859 68 : let Some(candidate_score) = scheduler.compute_node_score::<T::Score>(
860 68 : candidate,
861 68 : &self.intent.preferred_az_id,
862 68 : schedule_context,
863 68 : ) else {
864 : // The candidate node is unavailable for scheduling or otherwise couldn't get a score
865 1 : return None;
866 : };
867 :
868 : // If the candidate is our preferred node, then it is better than the current location, as long
869 : // as it is online -- the online check is part of the score calculation we did above, so it's
870 : // important that this check comes after that one.
871 67 : if let Some(preferred) = self.preferred_node.as_ref() {
872 3 : if preferred == &candidate {
873 1 : return Some(true);
874 2 : }
875 64 : }
876 :
877 66 : match scheduler.compute_node_score::<T::Score>(
878 66 : current,
879 66 : &self.intent.preferred_az_id,
880 66 : schedule_context,
881 66 : ) {
882 66 : Some(current_score) => {
883 : // Ignore utilization components when comparing scores: we don't want to migrate
884 : // because of transient load variations, it risks making the system thrash, and
885 : // migrating for utilization requires a separate high level view of the system to
886 : // e.g. prioritize moving larger or smaller tenants, rather than arbitrarily
887 : // moving things around in the order that we hit this function.
888 66 : let candidate_score = candidate_score.for_optimization();
889 66 : let current_score = current_score.for_optimization();
890 :
891 66 : if candidate_score < current_score {
892 8 : tracing::info!(
893 0 : "Found a lower scoring location! {candidate} is better than {current} ({candidate_score:?} is better than {current_score:?})"
894 : );
895 8 : Some(true)
896 : } else {
897 : // The candidate node is no better than our current location, so don't migrate
898 58 : tracing::debug!(
899 0 : "Candidate node {candidate} is no better than our current location {current} (candidate {candidate_score:?} vs current {current_score:?})",
900 : );
901 58 : Some(false)
902 : }
903 : }
904 : None => {
905 : // The current node is unavailable for scheduling, so we can't make any sensible
906 : // decisions about optimisation. This should be a transient state -- if the node
907 : // is offline then it will get evacuated, if is blocked by a scheduling mode
908 : // then we will respect that mode by doing nothing.
909 0 : tracing::debug!("Current node {current} is unavailable for scheduling");
910 0 : None
911 : }
912 : }
913 68 : }
914 :
915 48 : pub(crate) fn find_better_location<T: ShardTag>(
916 48 : &self,
917 48 : scheduler: &mut Scheduler,
918 48 : schedule_context: &ScheduleContext,
919 48 : current: NodeId,
920 48 : hard_exclude: &[NodeId],
921 48 : ) -> Option<NodeId> {
922 : // If we have a migration hint, then that is our better location
923 48 : if let Some(hint) = self.preferred_node.as_ref() {
924 1 : if hint == ¤t {
925 0 : return None;
926 1 : }
927 :
928 1 : return Some(*hint);
929 47 : }
930 :
931 : // Look for a lower-scoring location to attach to
932 47 : let Ok(candidate_node) = scheduler.schedule_shard::<T>(
933 47 : hard_exclude,
934 47 : &self.intent.preferred_az_id,
935 47 : schedule_context,
936 47 : ) else {
937 : // A scheduling error means we have no possible candidate replacements
938 0 : tracing::debug!("No candidate node found");
939 0 : return None;
940 : };
941 :
942 47 : if candidate_node == current {
943 : // We're already at the best possible location, so don't migrate
944 24 : tracing::debug!("Candidate node {candidate_node} is already in use");
945 24 : return None;
946 23 : }
947 :
948 23 : self.is_better_location::<T>(scheduler, schedule_context, current, candidate_node)
949 23 : .and_then(|better| if better { Some(candidate_node) } else { None })
950 48 : }
951 :
952 : /// This function is an optimization, used to avoid doing large numbers of scheduling operations
953 : /// when looking for optimizations. This function uses knowledge of how scores work to do some
954 : /// fast checks for whether it may to be possible to improve a score.
955 : ///
956 : /// If we return true, it only means that optimization _might_ be possible, not that it necessarily is. If we
957 : /// return no, it definitely means that calling [`Self::optimize_attachment`] or [`Self::optimize_secondary`] would do no
958 : /// work.
959 3 : pub(crate) fn maybe_optimizable(
960 3 : &self,
961 3 : scheduler: &mut Scheduler,
962 3 : schedule_context: &ScheduleContext,
963 3 : ) -> bool {
964 : // Tenant with preferred node: check if it is not already at the preferred node
965 3 : if let Some(preferred) = self.preferred_node.as_ref() {
966 0 : if Some(preferred) != self.intent.get_attached().as_ref() {
967 0 : return true;
968 0 : }
969 3 : }
970 :
971 : // Sharded tenant: check if any locations have a nonzero affinity score
972 3 : if self.shard.count >= ShardCount(1) {
973 3 : let schedule_context = schedule_context.project_detach(self);
974 5 : for node in self.intent.all_pageservers() {
975 5 : if let Some(af) = schedule_context.nodes.get(&node) {
976 5 : if *af > AffinityScore(0) {
977 3 : return true;
978 2 : }
979 0 : }
980 : }
981 0 : }
982 :
983 : // Attached tenant: check if the attachment is outside the preferred AZ
984 0 : if let PlacementPolicy::Attached(_) = self.policy {
985 0 : if let Some(attached) = self.intent.get_attached() {
986 0 : if scheduler.get_node_az(attached) != self.intent.preferred_az_id {
987 0 : return true;
988 0 : }
989 0 : }
990 0 : }
991 :
992 : // Tenant with secondary locations: check if any are within the preferred AZ
993 0 : for secondary in self.intent.get_secondary() {
994 0 : if scheduler.get_node_az(secondary) == self.intent.preferred_az_id {
995 0 : return true;
996 0 : }
997 : }
998 :
999 : // Does the tenant have excess secondaries?
1000 0 : if self.intent.get_secondary().len() > self.policy.want_secondaries() {
1001 0 : return true;
1002 0 : }
1003 :
1004 : // Fall through: no optimizations possible
1005 0 : false
1006 3 : }
1007 :
1008 : /// Optimize attachments: if a shard has a secondary location that is preferable to
1009 : /// its primary location based on soft constraints, switch that secondary location
1010 : /// to be attached.
1011 : ///
1012 : /// `schedule_context` should have been populated with all shards in the tenant, including
1013 : /// the one we're trying to optimize (this function will subtract its own contribution before making scoring decisions)
1014 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
1015 : pub(crate) fn optimize_attachment(
1016 : &self,
1017 : scheduler: &mut Scheduler,
1018 : schedule_context: &ScheduleContext,
1019 : ) -> Option<ScheduleOptimization> {
1020 : let attached = (*self.intent.get_attached())?;
1021 :
1022 : let schedule_context = schedule_context.project_detach(self);
1023 :
1024 : // If we already have a secondary that is higher-scoring than out current location,
1025 : // then simply migrate to it.
1026 : for secondary in self.intent.get_secondary() {
1027 : if let Some(true) = self.is_better_location::<AttachedShardTag>(
1028 : scheduler,
1029 : &schedule_context,
1030 : attached,
1031 : *secondary,
1032 : ) {
1033 : return Some(ScheduleOptimization {
1034 : sequence: self.sequence,
1035 : action: ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
1036 : old_attached_node_id: attached,
1037 : new_attached_node_id: *secondary,
1038 : }),
1039 : });
1040 : }
1041 : }
1042 :
1043 : // Given that none of our current secondaries is a better location than our current
1044 : // attached location (checked above), we may trim any secondaries that are not needed
1045 : // for the placement policy.
1046 : if self.intent.get_secondary().len() > self.policy.want_secondaries() {
1047 : // This code path cleans up extra secondaries after migrating, and/or
1048 : // trims extra secondaries after a PlacementPolicy::Attached(N) was
1049 : // modified to decrease N.
1050 :
1051 : let secondary_scores = self
1052 : .intent
1053 : .get_secondary()
1054 : .iter()
1055 12 : .map(|node_id| {
1056 12 : (
1057 12 : *node_id,
1058 12 : scheduler.compute_node_score::<NodeSecondarySchedulingScore>(
1059 12 : *node_id,
1060 12 : &self.intent.preferred_az_id,
1061 12 : &schedule_context,
1062 12 : ),
1063 12 : )
1064 12 : })
1065 : .collect::<HashMap<_, _>>();
1066 :
1067 11 : if secondary_scores.iter().any(|score| score.1.is_none()) {
1068 : // Trivial case: if we only have one secondary, drop that one
1069 : if self.intent.get_secondary().len() == 1 {
1070 : return Some(ScheduleOptimization {
1071 : sequence: self.sequence,
1072 : action: ScheduleOptimizationAction::RemoveSecondary(
1073 : *self.intent.get_secondary().first().unwrap(),
1074 : ),
1075 : });
1076 : }
1077 :
1078 : // Try to find a "good" secondary to keep, without relying on scores (one or more nodes is in a state
1079 : // where its score can't be calculated), and drop the others. This enables us to make progress in
1080 : // most cases, even if some nodes are offline or have scheduling=pause set.
1081 :
1082 : debug_assert!(self.intent.attached.is_some()); // We should not make it here unless attached -- this
1083 : // logic presumes we are in a mode where we want secondaries to be in non-home AZ
1084 1 : if let Some(retain_secondary) = self.intent.get_secondary().iter().find(|n| {
1085 1 : let in_home_az = scheduler.get_node_az(n) == self.intent.preferred_az_id;
1086 1 : let is_available = secondary_scores
1087 1 : .get(n)
1088 1 : .expect("Built from same list of nodes")
1089 1 : .is_some();
1090 1 : is_available && !in_home_az
1091 1 : }) {
1092 : // Great, we found one to retain. Pick some other to drop.
1093 : if let Some(victim) = self
1094 : .intent
1095 : .get_secondary()
1096 : .iter()
1097 2 : .find(|n| n != &retain_secondary)
1098 : {
1099 : return Some(ScheduleOptimization {
1100 : sequence: self.sequence,
1101 : action: ScheduleOptimizationAction::RemoveSecondary(*victim),
1102 : });
1103 : }
1104 : }
1105 :
1106 : // Fall through: we didn't identify one to remove. This ought to be rare.
1107 : tracing::warn!(
1108 : "Keeping extra secondaries: can't determine which of {:?} to remove (some nodes offline?)",
1109 : self.intent.get_secondary()
1110 : );
1111 : } else {
1112 : let victim = secondary_scores
1113 : .iter()
1114 10 : .max_by_key(|score| score.1.unwrap())
1115 : .unwrap()
1116 : .0;
1117 : return Some(ScheduleOptimization {
1118 : sequence: self.sequence,
1119 : action: ScheduleOptimizationAction::RemoveSecondary(*victim),
1120 : });
1121 : }
1122 : }
1123 :
1124 : let replacement = self.find_better_location::<AttachedShardTag>(
1125 : scheduler,
1126 : &schedule_context,
1127 : attached,
1128 : &[], // Don't exclude secondaries: our preferred attachment location may be a secondary
1129 : );
1130 :
1131 : // We have found a candidate and confirmed that its score is preferable
1132 : // to our current location. See if we have a secondary location in the preferred location already: if not,
1133 : // then create one.
1134 : if let Some(replacement) = replacement {
1135 : // If we are currently in non-preferred AZ, then the scheduler might suggest a location that is better, but still
1136 : // not in our preferred AZ. Migration has a cost in resources an impact to the workload, so we want to avoid doing
1137 : // multiple hops where we might go to some other AZ before eventually finding a suitable location in our preferred
1138 : // AZ: skip this optimization if it is not in our final, preferred AZ.
1139 : //
1140 : // This should be a transient state, there should always be capacity eventually in our preferred AZ (even if nodes
1141 : // there are too overloaded for scheduler to suggest them, more should be provisioned eventually).
1142 : if self.preferred_node.is_none()
1143 : && self.intent.preferred_az_id.is_some()
1144 : && scheduler.get_node_az(&replacement) != self.intent.preferred_az_id
1145 : {
1146 : tracing::debug!(
1147 : "Candidate node {replacement} is not in preferred AZ {:?}",
1148 : self.intent.preferred_az_id
1149 : );
1150 :
1151 : // This should only happen if our current location is not in the preferred AZ, otherwise
1152 : // [`Self::find_better_location`]` should have rejected any other location outside the preferred Az, because
1153 : // AZ is the highest priority part of NodeAttachmentSchedulingScore.
1154 : debug_assert!(scheduler.get_node_az(&attached) != self.intent.preferred_az_id);
1155 :
1156 : return None;
1157 : }
1158 :
1159 : if !self.intent.get_secondary().contains(&replacement) {
1160 : Some(ScheduleOptimization {
1161 : sequence: self.sequence,
1162 : action: ScheduleOptimizationAction::CreateSecondary(replacement),
1163 : })
1164 : } else {
1165 : // We already have a secondary in the preferred location, let's try migrating to it. Our caller
1166 : // will check the warmth of the destination before deciding whether to really execute this.
1167 : Some(ScheduleOptimization {
1168 : sequence: self.sequence,
1169 : action: ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
1170 : old_attached_node_id: attached,
1171 : new_attached_node_id: replacement,
1172 : }),
1173 : })
1174 : }
1175 : } else {
1176 : // We didn't find somewhere we'd rather be, and we don't have any excess secondaries
1177 : // to clean up: no action required.
1178 : None
1179 : }
1180 : }
1181 :
1182 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
1183 : pub(crate) fn optimize_secondary(
1184 : &self,
1185 : scheduler: &mut Scheduler,
1186 : schedule_context: &ScheduleContext,
1187 : ) -> Option<ScheduleOptimization> {
1188 : if self.intent.get_secondary().len() > self.policy.want_secondaries() {
1189 : // We have extra secondaries, perhaps to facilitate a migration of the attached location:
1190 : // do nothing, it is up to [`Self::optimize_attachment`] to clean them up. When that's done,
1191 : // and we are called again, we will proceed.
1192 : tracing::debug!("Too many secondaries: skipping");
1193 : return None;
1194 : }
1195 :
1196 : let schedule_context = schedule_context.project_detach(self);
1197 :
1198 : for secondary in self.intent.get_secondary() {
1199 : // Make sure we don't try to migrate a secondary to our attached location: this case happens
1200 : // easily in environments without multiple AZs.
1201 : let mut exclude = match self.intent.attached {
1202 : Some(attached) => vec![attached],
1203 : None => vec![],
1204 : };
1205 :
1206 : // Exclude all other secondaries from the scheduling process to avoid replacing
1207 : // one existing secondary with another existing secondary.
1208 : for another_secondary in self.intent.secondary.iter() {
1209 : if another_secondary != secondary {
1210 : exclude.push(*another_secondary);
1211 : }
1212 : }
1213 :
1214 : let replacement = match &self.policy {
1215 : PlacementPolicy::Attached(_) => {
1216 : // Secondaries for an attached shard should be scheduled using `SecondaryShardTag`
1217 : // to avoid placing them in the preferred AZ.
1218 : self.find_better_location::<SecondaryShardTag>(
1219 : scheduler,
1220 : &schedule_context,
1221 : *secondary,
1222 : &exclude,
1223 : )
1224 : }
1225 : PlacementPolicy::Secondary => {
1226 : // In secondary-only mode, we want our secondary locations in the preferred AZ,
1227 : // so that they're ready to take over as an attached location when we transition
1228 : // into PlacementPolicy::Attached.
1229 : self.find_better_location::<AttachedShardTag>(
1230 : scheduler,
1231 : &schedule_context,
1232 : *secondary,
1233 : &exclude,
1234 : )
1235 : }
1236 : PlacementPolicy::Detached => None,
1237 : };
1238 :
1239 : assert!(replacement != Some(*secondary));
1240 : if let Some(replacement) = replacement {
1241 : // We have found a candidate and confirmed that its score is preferable
1242 : // to our current location. See if we have a secondary location in the preferred location already: if not,
1243 : // then create one.
1244 : return Some(ScheduleOptimization {
1245 : sequence: self.sequence,
1246 : action: ScheduleOptimizationAction::ReplaceSecondary(ReplaceSecondary {
1247 : old_node_id: *secondary,
1248 : new_node_id: replacement,
1249 : }),
1250 : });
1251 : }
1252 : }
1253 :
1254 : None
1255 : }
1256 :
1257 : /// Start or abort a graceful migration of this shard to another pageserver. This works on top of the
1258 : /// other optimisation functions, to bias them to move to the destination node.
1259 0 : pub(crate) fn set_preferred_node(&mut self, node: Option<NodeId>) {
1260 0 : if let Some(hint) = self.preferred_node.as_ref() {
1261 0 : if Some(hint) != node.as_ref() {
1262 : // This is legal but a bit surprising: we expect that administrators wouldn't usually
1263 : // change their mind about where to migrate something.
1264 0 : tracing::warn!(
1265 0 : "Changing migration destination from {hint} to {node:?} (current intent {:?})",
1266 : self.intent
1267 : );
1268 0 : }
1269 0 : }
1270 :
1271 0 : self.preferred_node = node;
1272 0 : }
1273 :
1274 0 : pub(crate) fn get_preferred_node(&self) -> Option<NodeId> {
1275 0 : self.preferred_node
1276 0 : }
1277 :
1278 : /// Return true if the optimization was really applied: it will not be applied if the optimization's
1279 : /// sequence is behind this tenant shard's or if the intent state proposed by the optimization
1280 : /// is not compatible with the current intent state. The later may happen when the background
1281 : /// reconcile loops runs concurrently with HTTP driven optimisations.
1282 17 : pub(crate) fn apply_optimization(
1283 17 : &mut self,
1284 17 : scheduler: &mut Scheduler,
1285 17 : optimization: ScheduleOptimization,
1286 17 : ) -> bool {
1287 17 : if optimization.sequence != self.sequence {
1288 0 : return false;
1289 17 : }
1290 :
1291 17 : if !self.validate_optimization(&optimization) {
1292 0 : tracing::info!(
1293 0 : "Skipping optimization for {} because it does not match current intent: {:?}",
1294 : self.tenant_shard_id,
1295 : optimization,
1296 : );
1297 0 : return false;
1298 17 : }
1299 :
1300 17 : metrics::METRICS_REGISTRY
1301 17 : .metrics_group
1302 17 : .storage_controller_schedule_optimization
1303 17 : .inc();
1304 :
1305 17 : match optimization.action {
1306 : ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
1307 5 : old_attached_node_id,
1308 5 : new_attached_node_id,
1309 : }) => {
1310 5 : self.intent.demote_attached(scheduler, old_attached_node_id);
1311 5 : self.intent
1312 5 : .promote_attached(scheduler, new_attached_node_id);
1313 :
1314 5 : if let Some(hint) = self.preferred_node.as_ref() {
1315 1 : if hint == &new_attached_node_id {
1316 : // The migration target is not a long term pin: once we are done with the migration, clear it.
1317 1 : tracing::info!("Graceful migration to {hint} complete");
1318 1 : self.preferred_node = None;
1319 0 : }
1320 4 : }
1321 : }
1322 : ScheduleOptimizationAction::ReplaceSecondary(ReplaceSecondary {
1323 1 : old_node_id,
1324 1 : new_node_id,
1325 1 : }) => {
1326 1 : self.intent.remove_secondary(scheduler, old_node_id);
1327 1 : self.intent.push_secondary(scheduler, new_node_id);
1328 1 : }
1329 4 : ScheduleOptimizationAction::CreateSecondary(new_node_id) => {
1330 4 : self.intent.push_secondary(scheduler, new_node_id);
1331 4 : }
1332 7 : ScheduleOptimizationAction::RemoveSecondary(old_secondary) => {
1333 7 : self.intent.remove_secondary(scheduler, old_secondary);
1334 7 : }
1335 : }
1336 :
1337 17 : true
1338 17 : }
1339 :
1340 : /// Check that the desired modifications to the intent state are compatible with the current
1341 : /// intent state. Note that the lock is not held between planning optimizations and applying
1342 : /// them so any valid state transition of the intent state may have occurred.
1343 17 : fn validate_optimization(&self, optimization: &ScheduleOptimization) -> bool {
1344 17 : match optimization.action {
1345 : ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
1346 5 : old_attached_node_id,
1347 5 : new_attached_node_id,
1348 : }) => {
1349 5 : self.intent.attached == Some(old_attached_node_id)
1350 5 : && self.intent.secondary.contains(&new_attached_node_id)
1351 : }
1352 : ScheduleOptimizationAction::ReplaceSecondary(ReplaceSecondary {
1353 : old_node_id: _,
1354 1 : new_node_id,
1355 : }) => {
1356 : // It's legal to remove a secondary that is not present in the intent state
1357 1 : !self.intent.secondary.contains(&new_node_id)
1358 : // Ensure the secondary hasn't already been promoted to attached by a concurrent
1359 : // optimization/migration.
1360 1 : && self.intent.attached != Some(new_node_id)
1361 : }
1362 4 : ScheduleOptimizationAction::CreateSecondary(new_node_id) => {
1363 4 : !self.intent.secondary.contains(&new_node_id)
1364 : }
1365 : ScheduleOptimizationAction::RemoveSecondary(_) => {
1366 : // It's legal to remove a secondary that is not present in the intent state
1367 7 : true
1368 : }
1369 : }
1370 17 : }
1371 :
1372 : /// When a shard has several secondary locations, we need to pick one in situations where
1373 : /// we promote one of them to an attached location:
1374 : /// - When draining a node for restart
1375 : /// - When responding to a node failure
1376 : ///
1377 : /// In this context, 'preferred' does not mean the node with the best scheduling score: instead
1378 : /// we want to pick the node which is best for use _temporarily_ while the previous attached location
1379 : /// is unavailable (e.g. because it's down or deploying). That means we prefer to use secondary
1380 : /// locations in a non-preferred AZ, as they're more likely to have awarm cache than a temporary
1381 : /// secondary in the preferred AZ (which are usually only created for migrations, and if they exist
1382 : /// they're probably not warmed up yet). The latter behavior is based oni
1383 : ///
1384 : /// If the input is empty, or all the nodes are not elegible for scheduling, return None: the
1385 : /// caller needs to a pick a node some other way.
1386 12832 : pub(crate) fn preferred_secondary(&self, scheduler: &Scheduler) -> Option<NodeId> {
1387 12832 : let candidates = scheduler.filter_usable_nodes(&self.intent.secondary);
1388 :
1389 : // We will sort candidates to prefer nodes which are _not_ in our preferred AZ, i.e. we prefer
1390 : // to migrate to a long-lived secondary location (which would have been scheduled in a non-preferred AZ),
1391 : // rather than a short-lived secondary location being used for optimization/migration (which would have
1392 : // been scheduled in our preferred AZ).
1393 12832 : let mut candidates = candidates
1394 12832 : .iter()
1395 12832 : .map(|(node_id, node_az)| {
1396 2 : if node_az == &self.intent.preferred_az_id {
1397 1 : (1, *node_id)
1398 : } else {
1399 1 : (0, *node_id)
1400 : }
1401 2 : })
1402 12832 : .collect::<Vec<_>>();
1403 :
1404 12832 : candidates.sort();
1405 :
1406 12832 : candidates.first().map(|i| i.1)
1407 12832 : }
1408 :
1409 : /// Query whether the tenant's observed state for attached node matches its intent state, and if so,
1410 : /// yield the node ID. This is appropriate for emitting compute hook notifications: we are checking that
1411 : /// the node in question is not only where we intend to attach, but that the tenant is indeed already attached there.
1412 : ///
1413 : /// Reconciliation may still be needed for other aspects of state such as secondaries (see [`Self::dirty`]): this
1414 : /// funciton should not be used to decide whether to reconcile.
1415 0 : pub(crate) fn stably_attached(&self) -> Option<NodeId> {
1416 : // We have an intent to attach for this node
1417 0 : let attach_intent = self.intent.attached?;
1418 : // We have an observed state for this node
1419 0 : let location = self.observed.locations.get(&attach_intent)?;
1420 : // Our observed state is not None, i.e. not in flux
1421 0 : let location_config = location.conf.as_ref()?;
1422 :
1423 : // Check if our intent and observed state agree that this node is in an attached state.
1424 0 : match location_config.mode {
1425 : LocationConfigMode::AttachedMulti
1426 : | LocationConfigMode::AttachedSingle
1427 0 : | LocationConfigMode::AttachedStale => Some(attach_intent),
1428 0 : _ => None,
1429 : }
1430 0 : }
1431 :
1432 0 : fn dirty(&self, nodes: &Arc<HashMap<NodeId, Node>>) -> bool {
1433 0 : let mut dirty_nodes = HashSet::new();
1434 :
1435 0 : if let Some(node_id) = self.intent.attached {
1436 : // Maybe panic: it is a severe bug if we try to attach while generation is null.
1437 0 : let generation = self
1438 0 : .generation
1439 0 : .expect("Attempted to enter attached state without a generation");
1440 :
1441 0 : let wanted_conf = attached_location_conf(
1442 0 : generation,
1443 0 : &self.shard,
1444 0 : &self.config,
1445 0 : &self.policy,
1446 0 : self.intent.get_secondary().len(),
1447 : );
1448 0 : match self.observed.locations.get(&node_id) {
1449 0 : Some(conf) if conf.conf.as_ref() == Some(&wanted_conf) => {}
1450 0 : Some(_) | None => {
1451 0 : dirty_nodes.insert(node_id);
1452 0 : }
1453 : }
1454 0 : }
1455 :
1456 0 : for node_id in &self.intent.secondary {
1457 0 : let wanted_conf = secondary_location_conf(&self.shard, &self.config);
1458 0 : match self.observed.locations.get(node_id) {
1459 0 : Some(conf) if conf.conf.as_ref() == Some(&wanted_conf) => {}
1460 0 : Some(_) | None => {
1461 0 : dirty_nodes.insert(*node_id);
1462 0 : }
1463 : }
1464 : }
1465 :
1466 0 : for node_id in self.observed.locations.keys() {
1467 0 : if self.intent.attached != Some(*node_id) && !self.intent.secondary.contains(node_id) {
1468 0 : // We have observed state that isn't part of our intent: need to clean it up.
1469 0 : dirty_nodes.insert(*node_id);
1470 0 : }
1471 : }
1472 :
1473 0 : dirty_nodes.retain(|node_id| {
1474 0 : nodes
1475 0 : .get(node_id)
1476 0 : .map(|n| n.is_available())
1477 0 : .unwrap_or(false)
1478 0 : });
1479 :
1480 0 : !dirty_nodes.is_empty()
1481 0 : }
1482 :
1483 : #[allow(clippy::too_many_arguments)]
1484 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
1485 : pub(crate) fn get_reconcile_needed(
1486 : &mut self,
1487 : pageservers: &Arc<HashMap<NodeId, Node>>,
1488 : ) -> ReconcileNeeded {
1489 : // If there are any ambiguous observed states, and the nodes they refer to are available,
1490 : // we should reconcile to clean them up.
1491 : let mut dirty_observed = false;
1492 : for (node_id, observed_loc) in &self.observed.locations {
1493 : let node = pageservers
1494 : .get(node_id)
1495 : .expect("Nodes may not be removed while referenced");
1496 : if observed_loc.conf.is_none() && node.is_available() {
1497 : dirty_observed = true;
1498 : break;
1499 : }
1500 : }
1501 :
1502 : let active_nodes_dirty = self.dirty(pageservers);
1503 :
1504 : let reconcile_needed = match (
1505 : active_nodes_dirty,
1506 : dirty_observed,
1507 : self.pending_compute_notification,
1508 : ) {
1509 : (true, _, _) => ReconcileNeeded::Yes(ReconcileReason::ActiveNodesDirty),
1510 : (_, true, _) => ReconcileNeeded::Yes(ReconcileReason::UnknownLocation),
1511 : (_, _, true) => ReconcileNeeded::Yes(ReconcileReason::PendingComputeNotification),
1512 : _ => ReconcileNeeded::No,
1513 : };
1514 :
1515 : if matches!(reconcile_needed, ReconcileNeeded::No) {
1516 : tracing::debug!("Not dirty, no reconciliation needed.");
1517 : return ReconcileNeeded::No;
1518 : }
1519 :
1520 : // If we are currently splitting, then never start a reconciler task: the splitting logic
1521 : // requires that shards are not interfered with while it runs. Do this check here rather than
1522 : // up top, so that we only log this message if we would otherwise have done a reconciliation.
1523 : if !matches!(self.splitting, SplitState::Idle) {
1524 : tracing::info!("Refusing to reconcile, splitting in progress");
1525 : return ReconcileNeeded::No;
1526 : }
1527 :
1528 : // Reconcile already in flight for the current sequence?
1529 : if let Some(handle) = &self.reconciler {
1530 : if handle.sequence == self.sequence {
1531 : tracing::info!(
1532 : "Reconciliation already in progress for sequence {:?}",
1533 : self.sequence,
1534 : );
1535 : return ReconcileNeeded::WaitExisting(ReconcilerWaiter {
1536 : tenant_shard_id: self.tenant_shard_id,
1537 : seq_wait: self.waiter.clone(),
1538 : error_seq_wait: self.error_waiter.clone(),
1539 : error: self.last_error.clone(),
1540 : seq: self.sequence,
1541 : });
1542 : }
1543 : }
1544 :
1545 : // Pre-checks done: finally check whether we may actually do the work
1546 : match self.scheduling_policy {
1547 : ShardSchedulingPolicy::Active
1548 : | ShardSchedulingPolicy::Essential
1549 : | ShardSchedulingPolicy::Pause => {}
1550 : ShardSchedulingPolicy::Stop => {
1551 : // We only reach this point if there is work to do and we're going to skip
1552 : // doing it: warn it obvious why this tenant isn't doing what it ought to.
1553 : tracing::warn!("Skipping reconcile for policy {:?}", self.scheduling_policy);
1554 : return ReconcileNeeded::No;
1555 : }
1556 : }
1557 :
1558 : reconcile_needed
1559 : }
1560 :
1561 : /// Ensure the sequence number is set to a value where waiting for this value will make us wait
1562 : /// for the next reconcile: i.e. it is ahead of all completed or running reconcilers.
1563 : ///
1564 : /// Constructing a ReconcilerWaiter with the resulting sequence number gives the property
1565 : /// that the waiter will not complete until some future Reconciler is constructed and run.
1566 0 : fn ensure_sequence_ahead(&mut self) {
1567 : // Find the highest sequence for which a Reconciler has previously run or is currently
1568 : // running
1569 0 : let max_seen = std::cmp::max(
1570 0 : self.reconciler
1571 0 : .as_ref()
1572 0 : .map(|r| r.sequence)
1573 0 : .unwrap_or(Sequence(0)),
1574 0 : std::cmp::max(self.waiter.load(), self.error_waiter.load()),
1575 : );
1576 :
1577 0 : if self.sequence <= max_seen {
1578 0 : self.sequence = max_seen.next();
1579 0 : }
1580 0 : }
1581 :
1582 : /// Create a waiter that will wait for some future Reconciler that hasn't been spawned yet.
1583 : ///
1584 : /// This is appropriate when you can't spawn a reconciler (e.g. due to resource limits), but
1585 : /// you would like to wait on the next reconciler that gets spawned in the background.
1586 0 : pub(crate) fn future_reconcile_waiter(&mut self) -> ReconcilerWaiter {
1587 0 : self.ensure_sequence_ahead();
1588 :
1589 0 : ReconcilerWaiter {
1590 0 : tenant_shard_id: self.tenant_shard_id,
1591 0 : seq_wait: self.waiter.clone(),
1592 0 : error_seq_wait: self.error_waiter.clone(),
1593 0 : error: self.last_error.clone(),
1594 0 : seq: self.sequence,
1595 0 : }
1596 0 : }
1597 :
1598 0 : async fn reconcile(
1599 0 : sequence: Sequence,
1600 0 : mut reconciler: Reconciler,
1601 0 : must_notify: bool,
1602 0 : ) -> ReconcileResult {
1603 : // Attempt to make observed state match intent state
1604 0 : let result = reconciler.reconcile().await;
1605 :
1606 : // If we know we had a pending compute notification from some previous action, send a notification irrespective
1607 : // of whether the above reconcile() did any work. It has to be Ok() though, because otherwise we might be
1608 : // sending a notification of a location that isn't really attached.
1609 0 : if result.is_ok() && must_notify {
1610 : // If this fails we will send the need to retry in [`ReconcileResult::pending_compute_notification`]
1611 0 : reconciler.compute_notify().await.ok();
1612 0 : } else if must_notify {
1613 0 : // Carry this flag so that the reconciler's result will indicate that it still needs to retry
1614 0 : // the compute hook notification eventually.
1615 0 : reconciler.compute_notify_failure = true;
1616 0 : }
1617 :
1618 : // Update result counter
1619 0 : let outcome_label = match &result {
1620 : Ok(_) => {
1621 0 : if reconciler.compute_notify_failure {
1622 0 : ReconcileOutcome::SuccessNoNotify
1623 : } else {
1624 0 : ReconcileOutcome::Success
1625 : }
1626 : }
1627 0 : Err(ReconcileError::Cancel) => ReconcileOutcome::Cancel,
1628 0 : Err(_) => ReconcileOutcome::Error,
1629 : };
1630 :
1631 0 : metrics::METRICS_REGISTRY
1632 0 : .metrics_group
1633 0 : .storage_controller_reconcile_complete
1634 0 : .inc(ReconcileCompleteLabelGroup {
1635 0 : status: outcome_label,
1636 0 : });
1637 :
1638 : // Constructing result implicitly drops Reconciler, freeing any ReconcileUnits before the Service might
1639 : // try and schedule more work in response to our result.
1640 0 : ReconcileResult {
1641 0 : sequence,
1642 0 : result,
1643 0 : tenant_shard_id: reconciler.tenant_shard_id,
1644 0 : generation: reconciler.generation,
1645 0 : observed_deltas: reconciler.observed_deltas(),
1646 0 : pending_compute_notification: reconciler.compute_notify_failure,
1647 0 : }
1648 0 : }
1649 :
1650 : #[allow(clippy::too_many_arguments)]
1651 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
1652 : pub(crate) fn spawn_reconciler(
1653 : &mut self,
1654 : reason: ReconcileReason,
1655 : result_tx: &tokio::sync::mpsc::UnboundedSender<ReconcileResultRequest>,
1656 : pageservers: &Arc<HashMap<NodeId, Node>>,
1657 : compute_hook: &Arc<ComputeHook>,
1658 : reconciler_config: ReconcilerConfig,
1659 : service_config: &service::Config,
1660 : persistence: &Arc<Persistence>,
1661 : units: ReconcileUnits,
1662 : gate_guard: GateGuard,
1663 : cancel: &CancellationToken,
1664 : http_client: reqwest::Client,
1665 : ) -> Option<ReconcilerWaiter> {
1666 : // Reconcile in flight for a stale sequence? Our sequence's task will wait for it before
1667 : // doing our sequence's work.
1668 : let old_handle = self.reconciler.take();
1669 :
1670 : // Build list of nodes from which the reconciler should detach
1671 : let mut detach = Vec::new();
1672 : for node_id in self.observed.locations.keys() {
1673 : if self.intent.get_attached() != &Some(*node_id)
1674 : && !self.intent.secondary.contains(node_id)
1675 : {
1676 : detach.push(
1677 : pageservers
1678 : .get(node_id)
1679 : .expect("Intent references non-existent pageserver")
1680 : .clone(),
1681 : )
1682 : }
1683 : }
1684 :
1685 : // Advance the sequence before spawning a reconciler, so that sequence waiters
1686 : // can distinguish between before+after the reconcile completes.
1687 : self.ensure_sequence_ahead();
1688 :
1689 : let reconciler_cancel = cancel.child_token();
1690 : let reconciler_intent = TargetState::from_intent(pageservers, &self.intent);
1691 : let reconciler = Reconciler {
1692 : tenant_shard_id: self.tenant_shard_id,
1693 : shard: self.shard,
1694 : placement_policy: self.policy.clone(),
1695 : generation: self.generation,
1696 : intent: reconciler_intent,
1697 : detach,
1698 : reconciler_config,
1699 : config: self.config.clone(),
1700 : preferred_az: self.intent.preferred_az_id.clone(),
1701 : observed: self.observed.clone(),
1702 : original_observed: self.observed.clone(),
1703 : compute_hook: compute_hook.clone(),
1704 : service_config: service_config.clone(),
1705 : _gate_guard: gate_guard,
1706 : _resource_units: units,
1707 : cancel: reconciler_cancel.clone(),
1708 : persistence: persistence.clone(),
1709 : compute_notify_failure: false,
1710 : http_client,
1711 : };
1712 :
1713 : let reconcile_seq = self.sequence;
1714 : let long_reconcile_threshold = service_config.long_reconcile_threshold;
1715 :
1716 : tracing::info!(seq=%reconcile_seq, "Spawning Reconciler ({reason:?})");
1717 : let must_notify = self.pending_compute_notification;
1718 : let reconciler_span = tracing::info_span!(parent: None, "reconciler", seq=%reconcile_seq,
1719 : tenant_id=%reconciler.tenant_shard_id.tenant_id,
1720 : shard_id=%reconciler.tenant_shard_id.shard_slug());
1721 : metrics::METRICS_REGISTRY
1722 : .metrics_group
1723 : .storage_controller_reconcile_spawn
1724 : .inc();
1725 : let result_tx = result_tx.clone();
1726 : let join_handle = tokio::task::spawn(
1727 0 : async move {
1728 : // Wait for any previous reconcile task to complete before we start
1729 0 : if let Some(old_handle) = old_handle {
1730 0 : old_handle.cancel.cancel();
1731 0 : if let Err(e) = old_handle.handle.await {
1732 : // We can't do much with this other than log it: the task is done, so
1733 : // we may proceed with our work.
1734 0 : tracing::error!("Unexpected join error waiting for reconcile task: {e}");
1735 0 : }
1736 0 : }
1737 :
1738 : // Early check for cancellation before doing any work
1739 : // TODO: wrap all remote API operations in cancellation check
1740 : // as well.
1741 0 : if reconciler.cancel.is_cancelled() {
1742 0 : metrics::METRICS_REGISTRY
1743 0 : .metrics_group
1744 0 : .storage_controller_reconcile_complete
1745 0 : .inc(ReconcileCompleteLabelGroup {
1746 0 : status: ReconcileOutcome::Cancel,
1747 0 : });
1748 0 : return;
1749 0 : }
1750 :
1751 0 : let (tenant_id_label, shard_number_label, sequence_label) = {
1752 0 : (
1753 0 : reconciler.tenant_shard_id.tenant_id.to_string(),
1754 0 : reconciler.tenant_shard_id.shard_number.0.to_string(),
1755 0 : reconcile_seq.to_string(),
1756 0 : )
1757 0 : };
1758 :
1759 0 : let label_group = ReconcileLongRunningLabelGroup {
1760 0 : tenant_id: &tenant_id_label,
1761 0 : shard_number: &shard_number_label,
1762 0 : sequence: &sequence_label,
1763 0 : };
1764 :
1765 0 : let reconcile_fut = Self::reconcile(reconcile_seq, reconciler, must_notify);
1766 0 : let long_reconcile_fut = {
1767 0 : let label_group = label_group.clone();
1768 0 : async move {
1769 0 : tokio::time::sleep(long_reconcile_threshold).await;
1770 :
1771 0 : tracing::warn!("Reconcile passed the long running threshold of {long_reconcile_threshold:?}");
1772 :
1773 0 : metrics::METRICS_REGISTRY
1774 0 : .metrics_group
1775 0 : .storage_controller_reconcile_long_running
1776 0 : .inc(label_group);
1777 0 : }
1778 : };
1779 :
1780 0 : let reconcile_fut = std::pin::pin!(reconcile_fut);
1781 0 : let long_reconcile_fut = std::pin::pin!(long_reconcile_fut);
1782 :
1783 0 : let (was_long, result) =
1784 0 : match future::select(reconcile_fut, long_reconcile_fut).await {
1785 0 : Either::Left((reconcile_result, _)) => (false, reconcile_result),
1786 0 : Either::Right((_, reconcile_fut)) => (true, reconcile_fut.await),
1787 : };
1788 :
1789 0 : if was_long {
1790 0 : let id = metrics::METRICS_REGISTRY
1791 0 : .metrics_group
1792 0 : .storage_controller_reconcile_long_running
1793 0 : .with_labels(label_group);
1794 0 : metrics::METRICS_REGISTRY
1795 0 : .metrics_group
1796 0 : .storage_controller_reconcile_long_running
1797 0 : .remove_metric(id);
1798 0 : }
1799 :
1800 0 : result_tx
1801 0 : .send(ReconcileResultRequest::ReconcileResult(result))
1802 0 : .ok();
1803 0 : }
1804 : .instrument(reconciler_span),
1805 : );
1806 :
1807 : self.reconciler = Some(ReconcilerHandle {
1808 : sequence: self.sequence,
1809 : handle: join_handle,
1810 : cancel: reconciler_cancel,
1811 : });
1812 :
1813 : Some(ReconcilerWaiter {
1814 : tenant_shard_id: self.tenant_shard_id,
1815 : seq_wait: self.waiter.clone(),
1816 : error_seq_wait: self.error_waiter.clone(),
1817 : error: self.last_error.clone(),
1818 : seq: self.sequence,
1819 : })
1820 : }
1821 :
1822 0 : pub(crate) fn cancel_reconciler(&self) {
1823 0 : if let Some(handle) = self.reconciler.as_ref() {
1824 0 : handle.cancel.cancel()
1825 0 : }
1826 0 : }
1827 :
1828 : /// Get a waiter for any reconciliation in flight, but do not start reconciliation
1829 : /// if it is not already running
1830 0 : pub(crate) fn get_waiter(&self) -> Option<ReconcilerWaiter> {
1831 0 : if self.reconciler.is_some() {
1832 0 : Some(ReconcilerWaiter {
1833 0 : tenant_shard_id: self.tenant_shard_id,
1834 0 : seq_wait: self.waiter.clone(),
1835 0 : error_seq_wait: self.error_waiter.clone(),
1836 0 : error: self.last_error.clone(),
1837 0 : seq: self.sequence,
1838 0 : })
1839 : } else {
1840 0 : None
1841 : }
1842 0 : }
1843 :
1844 : /// Called when a ReconcileResult has been emitted and the service is updating
1845 : /// our state: if the result is from a sequence >= my ReconcileHandle, then drop
1846 : /// the handle to indicate there is no longer a reconciliation in progress.
1847 0 : pub(crate) fn reconcile_complete(&mut self, sequence: Sequence) {
1848 0 : if let Some(reconcile_handle) = &self.reconciler {
1849 0 : if reconcile_handle.sequence <= sequence {
1850 0 : self.reconciler = None;
1851 0 : }
1852 0 : }
1853 0 : }
1854 :
1855 : /// If we had any state at all referring to this node ID, drop it. Does not
1856 : /// attempt to reschedule.
1857 : ///
1858 : /// Returns true if we modified the node's intent state.
1859 0 : pub(crate) fn deref_node(&mut self, node_id: NodeId) -> bool {
1860 0 : let mut intent_modified = false;
1861 :
1862 : // Drop if this node was our attached intent
1863 0 : if self.intent.attached == Some(node_id) {
1864 0 : self.intent.attached = None;
1865 0 : intent_modified = true;
1866 0 : }
1867 :
1868 : // Drop from the list of secondaries, and check if we modified it
1869 0 : let had_secondaries = self.intent.secondary.len();
1870 0 : self.intent.secondary.retain(|n| n != &node_id);
1871 0 : intent_modified |= self.intent.secondary.len() != had_secondaries;
1872 :
1873 0 : debug_assert!(!self.intent.all_pageservers().contains(&node_id));
1874 :
1875 0 : if self.preferred_node == Some(node_id) {
1876 0 : self.preferred_node = None;
1877 0 : }
1878 :
1879 0 : intent_modified
1880 0 : }
1881 :
1882 0 : pub(crate) fn set_scheduling_policy(&mut self, p: ShardSchedulingPolicy) {
1883 0 : self.scheduling_policy = p;
1884 0 : }
1885 :
1886 0 : pub(crate) fn get_scheduling_policy(&self) -> ShardSchedulingPolicy {
1887 0 : self.scheduling_policy
1888 0 : }
1889 :
1890 0 : pub(crate) fn set_last_error(&mut self, sequence: Sequence, error: ReconcileError) {
1891 : // Ordering: always set last_error before advancing sequence, so that sequence
1892 : // waiters are guaranteed to see a Some value when they see an error.
1893 0 : *(self.last_error.lock().unwrap()) = Some(Arc::new(error));
1894 0 : self.error_waiter.advance(sequence);
1895 0 : }
1896 :
1897 0 : pub(crate) fn from_persistent(
1898 0 : tsp: TenantShardPersistence,
1899 0 : intent: IntentState,
1900 0 : ) -> anyhow::Result<Self> {
1901 0 : let tenant_shard_id = tsp.get_tenant_shard_id()?;
1902 0 : let shard_identity = tsp.get_shard_identity()?;
1903 :
1904 0 : metrics::METRICS_REGISTRY
1905 0 : .metrics_group
1906 0 : .storage_controller_tenant_shards
1907 0 : .inc();
1908 :
1909 : Ok(Self {
1910 0 : tenant_shard_id,
1911 0 : shard: shard_identity,
1912 0 : sequence: Sequence::initial(),
1913 0 : generation: tsp.generation.map(|g| Generation::new(g as u32)),
1914 0 : policy: serde_json::from_str(&tsp.placement_policy).unwrap(),
1915 0 : intent,
1916 0 : observed: ObservedState::new(),
1917 0 : config: serde_json::from_str(&tsp.config).unwrap(),
1918 0 : reconciler: None,
1919 0 : splitting: tsp.splitting,
1920 : // Filled in during [`Service::startup_reconcile`]
1921 0 : importing: TimelineImportState::Idle,
1922 0 : waiter: Arc::new(SeqWait::new(Sequence::initial())),
1923 0 : error_waiter: Arc::new(SeqWait::new(Sequence::initial())),
1924 0 : last_error: Arc::default(),
1925 : consecutive_reconciles_count: 0,
1926 : pending_compute_notification: false,
1927 : delayed_reconcile: false,
1928 0 : scheduling_policy: serde_json::from_str(&tsp.scheduling_policy).unwrap(),
1929 0 : preferred_node: None,
1930 : })
1931 0 : }
1932 :
1933 0 : pub(crate) fn to_persistent(&self) -> TenantShardPersistence {
1934 : TenantShardPersistence {
1935 0 : tenant_id: self.tenant_shard_id.tenant_id.to_string(),
1936 0 : shard_number: self.tenant_shard_id.shard_number.0 as i32,
1937 0 : shard_count: self.tenant_shard_id.shard_count.literal() as i32,
1938 0 : shard_stripe_size: self.shard.stripe_size.0 as i32,
1939 0 : generation: self.generation.map(|g| g.into().unwrap_or(0) as i32),
1940 0 : generation_pageserver: self.intent.get_attached().map(|n| n.0 as i64),
1941 0 : placement_policy: serde_json::to_string(&self.policy).unwrap(),
1942 0 : config: serde_json::to_string(&self.config).unwrap(),
1943 0 : splitting: SplitState::default(),
1944 0 : scheduling_policy: serde_json::to_string(&self.scheduling_policy).unwrap(),
1945 0 : preferred_az_id: self.intent.preferred_az_id.as_ref().map(|az| az.0.clone()),
1946 : }
1947 0 : }
1948 :
1949 12508 : pub(crate) fn preferred_az(&self) -> Option<&AvailabilityZone> {
1950 12508 : self.intent.get_preferred_az()
1951 12508 : }
1952 :
1953 2 : pub(crate) fn set_preferred_az(
1954 2 : &mut self,
1955 2 : scheduler: &mut Scheduler,
1956 2 : preferred_az_id: Option<AvailabilityZone>,
1957 2 : ) {
1958 2 : self.intent.set_preferred_az(scheduler, preferred_az_id);
1959 2 : }
1960 :
1961 : /// Returns all the nodes to which this tenant shard is attached according to the
1962 : /// observed state and the generations. Return vector is sorted from latest generation
1963 : /// to earliest.
1964 0 : pub(crate) fn attached_locations(&self) -> Vec<(NodeId, Generation)> {
1965 0 : self.observed
1966 0 : .locations
1967 0 : .iter()
1968 0 : .filter_map(|(node_id, observed)| {
1969 : use LocationConfigMode::{AttachedMulti, AttachedSingle, AttachedStale};
1970 :
1971 0 : let conf = observed.conf.as_ref()?;
1972 :
1973 0 : match (conf.generation, conf.mode) {
1974 0 : (Some(gen_), AttachedMulti | AttachedSingle | AttachedStale) => {
1975 0 : Some((*node_id, gen_))
1976 : }
1977 0 : _ => None,
1978 : }
1979 0 : })
1980 0 : .sorted_by(|(_lhs_node_id, lhs_gen), (_rhs_node_id, rhs_gen)| {
1981 0 : lhs_gen.cmp(rhs_gen).reverse()
1982 0 : })
1983 0 : .map(|(node_id, gen_)| (node_id, Generation::new(gen_)))
1984 0 : .collect()
1985 0 : }
1986 :
1987 : /// Update the observed state of the tenant by applying incremental deltas
1988 : ///
1989 : /// Deltas are generated by reconcilers via [`Reconciler::observed_deltas`].
1990 : /// They are then filtered in [`crate::service::Service::process_result`].
1991 0 : pub(crate) fn apply_observed_deltas(
1992 0 : &mut self,
1993 0 : deltas: impl Iterator<Item = ObservedStateDelta>,
1994 0 : ) {
1995 0 : for delta in deltas {
1996 0 : match delta {
1997 0 : ObservedStateDelta::Upsert(ups) => {
1998 0 : let (node_id, loc) = *ups;
1999 :
2000 : // If the generation of the observed location in the delta is lagging
2001 : // behind the current one, then we have a race condition and cannot
2002 : // be certain about the true observed state. Set the observed state
2003 : // to None in order to reflect this.
2004 0 : let crnt_gen = self
2005 0 : .observed
2006 0 : .locations
2007 0 : .get(&node_id)
2008 0 : .and_then(|loc| loc.conf.as_ref())
2009 0 : .and_then(|conf| conf.generation);
2010 0 : let new_gen = loc.conf.as_ref().and_then(|conf| conf.generation);
2011 0 : match (crnt_gen, new_gen) {
2012 0 : (Some(crnt), Some(new)) if crnt_gen > new_gen => {
2013 0 : tracing::warn!(
2014 0 : "Skipping observed state update {}: {:?} and using None due to stale generation ({} > {})",
2015 : node_id,
2016 : loc,
2017 : crnt,
2018 : new
2019 : );
2020 :
2021 0 : self.observed
2022 0 : .locations
2023 0 : .insert(node_id, ObservedStateLocation { conf: None });
2024 :
2025 0 : continue;
2026 : }
2027 0 : _ => {}
2028 : }
2029 :
2030 0 : if let Some(conf) = &loc.conf {
2031 0 : tracing::info!("Updating observed location {}: {:?}", node_id, conf);
2032 : } else {
2033 0 : tracing::info!("Setting observed location {} to None", node_id,)
2034 : }
2035 :
2036 0 : self.observed.locations.insert(node_id, loc);
2037 : }
2038 0 : ObservedStateDelta::Delete(node_id) => {
2039 0 : tracing::info!("Deleting observed location {}", node_id);
2040 0 : self.observed.locations.remove(&node_id);
2041 : }
2042 : }
2043 : }
2044 0 : }
2045 :
2046 : /// Returns true if the tenant shard is attached to a node that is outside the preferred AZ.
2047 : ///
2048 : /// If the shard does not have a preferred AZ, returns false.
2049 0 : pub(crate) fn is_attached_outside_preferred_az(&self, nodes: &HashMap<NodeId, Node>) -> bool {
2050 0 : self.intent
2051 0 : .get_attached()
2052 0 : .map(|node_id| {
2053 0 : Some(
2054 0 : nodes
2055 0 : .get(&node_id)
2056 0 : .expect("referenced node exists")
2057 0 : .get_availability_zone_id(),
2058 0 : ) != self.intent.preferred_az_id.as_ref()
2059 0 : })
2060 0 : .unwrap_or(false)
2061 0 : }
2062 : }
2063 :
2064 : impl Drop for TenantShard {
2065 12843 : fn drop(&mut self) {
2066 12843 : metrics::METRICS_REGISTRY
2067 12843 : .metrics_group
2068 12843 : .storage_controller_tenant_shards
2069 12843 : .dec();
2070 12843 : }
2071 : }
2072 :
2073 : #[cfg(test)]
2074 : pub(crate) mod tests {
2075 : use std::cell::RefCell;
2076 : use std::rc::Rc;
2077 :
2078 : use pageserver_api::controller_api::NodeAvailability;
2079 : use pageserver_api::shard::{DEFAULT_STRIPE_SIZE, ShardCount, ShardNumber};
2080 : use rand::SeedableRng;
2081 : use rand::rngs::StdRng;
2082 : use utils::id::TenantId;
2083 :
2084 : use super::*;
2085 : use crate::scheduler::test_utils::make_test_nodes;
2086 :
2087 12 : fn make_test_tenant_shard(policy: PlacementPolicy) -> TenantShard {
2088 12 : let tenant_id = TenantId::generate();
2089 12 : let shard_number = ShardNumber(0);
2090 12 : let shard_count = ShardCount::new(1);
2091 12 : let stripe_size = DEFAULT_STRIPE_SIZE;
2092 :
2093 12 : let tenant_shard_id = TenantShardId {
2094 12 : tenant_id,
2095 12 : shard_number,
2096 12 : shard_count,
2097 12 : };
2098 12 : TenantShard::new(
2099 12 : tenant_shard_id,
2100 12 : ShardIdentity::new(shard_number, shard_count, stripe_size).unwrap(),
2101 12 : policy,
2102 12 : None,
2103 : )
2104 12 : }
2105 :
2106 5004 : pub(crate) fn make_test_tenant(
2107 5004 : policy: PlacementPolicy,
2108 5004 : shard_count: ShardCount,
2109 5004 : preferred_az: Option<AvailabilityZone>,
2110 5004 : ) -> Vec<TenantShard> {
2111 5004 : make_test_tenant_with_id(TenantId::generate(), policy, shard_count, preferred_az)
2112 5004 : }
2113 :
2114 5007 : pub(crate) fn make_test_tenant_with_id(
2115 5007 : tenant_id: TenantId,
2116 5007 : policy: PlacementPolicy,
2117 5007 : shard_count: ShardCount,
2118 5007 : preferred_az: Option<AvailabilityZone>,
2119 5007 : ) -> Vec<TenantShard> {
2120 5007 : let stripe_size = DEFAULT_STRIPE_SIZE;
2121 5007 : (0..shard_count.count())
2122 12522 : .map(|i| {
2123 12522 : let shard_number = ShardNumber(i);
2124 :
2125 12522 : let tenant_shard_id = TenantShardId {
2126 12522 : tenant_id,
2127 12522 : shard_number,
2128 12522 : shard_count,
2129 12522 : };
2130 12522 : TenantShard::new(
2131 12522 : tenant_shard_id,
2132 12522 : ShardIdentity::new(shard_number, shard_count, stripe_size).unwrap(),
2133 12522 : policy.clone(),
2134 12522 : preferred_az.clone(),
2135 : )
2136 12522 : })
2137 5007 : .collect()
2138 5007 : }
2139 :
2140 : /// Test the scheduling behaviors used when a tenant configured for HA is subject
2141 : /// to nodes being marked offline.
2142 : #[test]
2143 1 : fn tenant_ha_scheduling() -> anyhow::Result<()> {
2144 : // Start with three nodes. Our tenant will only use two. The third one is
2145 : // expected to remain unused.
2146 1 : let mut nodes = make_test_nodes(3, &[]);
2147 :
2148 1 : let mut scheduler = Scheduler::new(nodes.values());
2149 1 : let mut context = ScheduleContext::default();
2150 :
2151 1 : let mut tenant_shard = make_test_tenant_shard(PlacementPolicy::Attached(1));
2152 1 : tenant_shard
2153 1 : .schedule(&mut scheduler, &mut context)
2154 1 : .expect("we have enough nodes, scheduling should work");
2155 :
2156 : // Expect to initially be schedule on to different nodes
2157 1 : assert_eq!(tenant_shard.intent.secondary.len(), 1);
2158 1 : assert!(tenant_shard.intent.attached.is_some());
2159 :
2160 1 : let attached_node_id = tenant_shard.intent.attached.unwrap();
2161 1 : let secondary_node_id = *tenant_shard.intent.secondary.iter().last().unwrap();
2162 1 : assert_ne!(attached_node_id, secondary_node_id);
2163 :
2164 : // Notifying the attached node is offline should demote it to a secondary
2165 1 : let changed = tenant_shard
2166 1 : .intent
2167 1 : .demote_attached(&mut scheduler, attached_node_id);
2168 1 : assert!(changed);
2169 1 : assert!(tenant_shard.intent.attached.is_none());
2170 1 : assert_eq!(tenant_shard.intent.secondary.len(), 2);
2171 :
2172 : // Update the scheduler state to indicate the node is offline
2173 1 : nodes
2174 1 : .get_mut(&attached_node_id)
2175 1 : .unwrap()
2176 1 : .set_availability(NodeAvailability::Offline);
2177 1 : scheduler.node_upsert(nodes.get(&attached_node_id).unwrap());
2178 :
2179 : // Scheduling the node should promote the still-available secondary node to attached
2180 1 : tenant_shard
2181 1 : .schedule(&mut scheduler, &mut context)
2182 1 : .expect("active nodes are available");
2183 1 : assert_eq!(tenant_shard.intent.attached.unwrap(), secondary_node_id);
2184 :
2185 : // The original attached node should have been retained as a secondary
2186 1 : assert_eq!(
2187 1 : *tenant_shard.intent.secondary.iter().last().unwrap(),
2188 : attached_node_id
2189 : );
2190 :
2191 1 : tenant_shard.intent.clear(&mut scheduler);
2192 :
2193 1 : Ok(())
2194 1 : }
2195 :
2196 : #[test]
2197 1 : fn intent_from_observed() -> anyhow::Result<()> {
2198 1 : let nodes = make_test_nodes(3, &[]);
2199 1 : let mut scheduler = Scheduler::new(nodes.values());
2200 :
2201 1 : let mut tenant_shard = make_test_tenant_shard(PlacementPolicy::Attached(1));
2202 :
2203 1 : tenant_shard.observed.locations.insert(
2204 1 : NodeId(3),
2205 1 : ObservedStateLocation {
2206 1 : conf: Some(LocationConfig {
2207 1 : mode: LocationConfigMode::AttachedMulti,
2208 1 : generation: Some(2),
2209 1 : secondary_conf: None,
2210 1 : shard_number: tenant_shard.shard.number.0,
2211 1 : shard_count: tenant_shard.shard.count.literal(),
2212 1 : shard_stripe_size: tenant_shard.shard.stripe_size.0,
2213 1 : tenant_conf: TenantConfig::default(),
2214 1 : }),
2215 1 : },
2216 : );
2217 :
2218 1 : tenant_shard.observed.locations.insert(
2219 1 : NodeId(2),
2220 1 : ObservedStateLocation {
2221 1 : conf: Some(LocationConfig {
2222 1 : mode: LocationConfigMode::AttachedStale,
2223 1 : generation: Some(1),
2224 1 : secondary_conf: None,
2225 1 : shard_number: tenant_shard.shard.number.0,
2226 1 : shard_count: tenant_shard.shard.count.literal(),
2227 1 : shard_stripe_size: tenant_shard.shard.stripe_size.0,
2228 1 : tenant_conf: TenantConfig::default(),
2229 1 : }),
2230 1 : },
2231 : );
2232 :
2233 1 : tenant_shard.intent_from_observed(&mut scheduler);
2234 :
2235 : // The highest generationed attached location gets used as attached
2236 1 : assert_eq!(tenant_shard.intent.attached, Some(NodeId(3)));
2237 : // Other locations get used as secondary
2238 1 : assert_eq!(tenant_shard.intent.secondary, vec![NodeId(2)]);
2239 :
2240 1 : scheduler.consistency_check(nodes.values(), [&tenant_shard].into_iter())?;
2241 :
2242 1 : tenant_shard.intent.clear(&mut scheduler);
2243 1 : Ok(())
2244 1 : }
2245 :
2246 : #[test]
2247 1 : fn scheduling_mode() -> anyhow::Result<()> {
2248 1 : let nodes = make_test_nodes(3, &[]);
2249 1 : let mut scheduler = Scheduler::new(nodes.values());
2250 :
2251 1 : let mut tenant_shard = make_test_tenant_shard(PlacementPolicy::Attached(1));
2252 :
2253 : // In pause mode, schedule() shouldn't do anything
2254 1 : tenant_shard.scheduling_policy = ShardSchedulingPolicy::Pause;
2255 1 : assert!(
2256 1 : tenant_shard
2257 1 : .schedule(&mut scheduler, &mut ScheduleContext::default())
2258 1 : .is_ok()
2259 : );
2260 1 : assert!(tenant_shard.intent.all_pageservers().is_empty());
2261 :
2262 : // In active mode, schedule() works
2263 1 : tenant_shard.scheduling_policy = ShardSchedulingPolicy::Active;
2264 1 : assert!(
2265 1 : tenant_shard
2266 1 : .schedule(&mut scheduler, &mut ScheduleContext::default())
2267 1 : .is_ok()
2268 : );
2269 1 : assert!(!tenant_shard.intent.all_pageservers().is_empty());
2270 :
2271 1 : tenant_shard.intent.clear(&mut scheduler);
2272 1 : Ok(())
2273 1 : }
2274 :
2275 : #[test]
2276 : /// Simple case: moving attachment to somewhere better where we already have a secondary
2277 1 : fn optimize_attachment_simple() -> anyhow::Result<()> {
2278 1 : let nodes = make_test_nodes(
2279 : 3,
2280 1 : &[
2281 1 : AvailabilityZone("az-a".to_string()),
2282 1 : AvailabilityZone("az-b".to_string()),
2283 1 : AvailabilityZone("az-c".to_string()),
2284 1 : ],
2285 : );
2286 1 : let mut scheduler = Scheduler::new(nodes.values());
2287 :
2288 1 : let mut shard_a = make_test_tenant_shard(PlacementPolicy::Attached(1));
2289 1 : shard_a.intent.preferred_az_id = Some(AvailabilityZone("az-a".to_string()));
2290 1 : let mut shard_b = make_test_tenant_shard(PlacementPolicy::Attached(1));
2291 1 : shard_b.intent.preferred_az_id = Some(AvailabilityZone("az-a".to_string()));
2292 :
2293 : // Initially: both nodes attached on shard 1, and both have secondary locations
2294 : // on different nodes.
2295 1 : shard_a.intent.set_attached(&mut scheduler, Some(NodeId(2)));
2296 1 : shard_a.intent.push_secondary(&mut scheduler, NodeId(1));
2297 1 : shard_b.intent.set_attached(&mut scheduler, Some(NodeId(1)));
2298 1 : shard_b.intent.push_secondary(&mut scheduler, NodeId(2));
2299 :
2300 1 : fn make_schedule_context(shard_a: &TenantShard, shard_b: &TenantShard) -> ScheduleContext {
2301 1 : let mut schedule_context = ScheduleContext::default();
2302 1 : schedule_context.avoid(&shard_a.intent.all_pageservers());
2303 1 : schedule_context.avoid(&shard_b.intent.all_pageservers());
2304 1 : schedule_context
2305 1 : }
2306 :
2307 1 : let schedule_context = make_schedule_context(&shard_a, &shard_b);
2308 1 : let optimization_a = shard_a.optimize_attachment(&mut scheduler, &schedule_context);
2309 1 : assert_eq!(
2310 : optimization_a,
2311 1 : Some(ScheduleOptimization {
2312 1 : sequence: shard_a.sequence,
2313 1 : action: ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
2314 1 : old_attached_node_id: NodeId(2),
2315 1 : new_attached_node_id: NodeId(1)
2316 1 : })
2317 1 : })
2318 : );
2319 1 : shard_a.apply_optimization(&mut scheduler, optimization_a.unwrap());
2320 :
2321 : // // Either shard should recognize that it has the option to switch to a secondary location where there
2322 : // // would be no other shards from the same tenant, and request to do so.
2323 : // assert_eq!(
2324 : // optimization_a_prepare,
2325 : // Some(ScheduleOptimization {
2326 : // sequence: shard_a.sequence,
2327 : // action: ScheduleOptimizationAction::CreateSecondary(NodeId(2))
2328 : // })
2329 : // );
2330 : // shard_a.apply_optimization(&mut scheduler, optimization_a_prepare.unwrap());
2331 :
2332 : // let schedule_context = make_schedule_context(&shard_a, &shard_b);
2333 : // let optimization_a_migrate = shard_a.optimize_attachment(&mut scheduler, &schedule_context);
2334 : // assert_eq!(
2335 : // optimization_a_migrate,
2336 : // Some(ScheduleOptimization {
2337 : // sequence: shard_a.sequence,
2338 : // action: ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
2339 : // old_attached_node_id: NodeId(1),
2340 : // new_attached_node_id: NodeId(2)
2341 : // })
2342 : // })
2343 : // );
2344 : // shard_a.apply_optimization(&mut scheduler, optimization_a_migrate.unwrap());
2345 :
2346 : // let schedule_context = make_schedule_context(&shard_a, &shard_b);
2347 : // let optimization_a_cleanup = shard_a.optimize_attachment(&mut scheduler, &schedule_context);
2348 : // assert_eq!(
2349 : // optimization_a_cleanup,
2350 : // Some(ScheduleOptimization {
2351 : // sequence: shard_a.sequence,
2352 : // action: ScheduleOptimizationAction::RemoveSecondary(NodeId(1))
2353 : // })
2354 : // );
2355 : // shard_a.apply_optimization(&mut scheduler, optimization_a_cleanup.unwrap());
2356 :
2357 : // // Shard B should not be moved anywhere, since the pressure on node 1 was relieved by moving shard A
2358 : // let schedule_context = make_schedule_context(&shard_a, &shard_b);
2359 : // assert_eq!(shard_b.optimize_attachment(&mut scheduler, &schedule_context), None);
2360 :
2361 1 : shard_a.intent.clear(&mut scheduler);
2362 1 : shard_b.intent.clear(&mut scheduler);
2363 :
2364 1 : Ok(())
2365 1 : }
2366 :
2367 : #[test]
2368 : /// Complicated case: moving attachment to somewhere better where we do not have a secondary
2369 : /// already, creating one as needed.
2370 1 : fn optimize_attachment_multistep() -> anyhow::Result<()> {
2371 1 : let nodes = make_test_nodes(
2372 : 3,
2373 1 : &[
2374 1 : AvailabilityZone("az-a".to_string()),
2375 1 : AvailabilityZone("az-b".to_string()),
2376 1 : AvailabilityZone("az-c".to_string()),
2377 1 : ],
2378 : );
2379 1 : let mut scheduler = Scheduler::new(nodes.values());
2380 :
2381 : // Two shards of a tenant that wants to be in AZ A
2382 1 : let mut shard_a = make_test_tenant_shard(PlacementPolicy::Attached(1));
2383 1 : shard_a.intent.preferred_az_id = Some(AvailabilityZone("az-a".to_string()));
2384 1 : let mut shard_b = make_test_tenant_shard(PlacementPolicy::Attached(1));
2385 1 : shard_b.intent.preferred_az_id = Some(AvailabilityZone("az-a".to_string()));
2386 :
2387 : // Both shards are initially attached in non-home AZ _and_ have secondaries in non-home AZs
2388 1 : shard_a.intent.set_attached(&mut scheduler, Some(NodeId(2)));
2389 1 : shard_a.intent.push_secondary(&mut scheduler, NodeId(3));
2390 1 : shard_b.intent.set_attached(&mut scheduler, Some(NodeId(3)));
2391 1 : shard_b.intent.push_secondary(&mut scheduler, NodeId(2));
2392 :
2393 3 : fn make_schedule_context(shard_a: &TenantShard, shard_b: &TenantShard) -> ScheduleContext {
2394 3 : let mut schedule_context = ScheduleContext::default();
2395 3 : schedule_context.avoid(&shard_a.intent.all_pageservers());
2396 3 : schedule_context.avoid(&shard_b.intent.all_pageservers());
2397 3 : schedule_context
2398 3 : }
2399 :
2400 1 : let schedule_context = make_schedule_context(&shard_a, &shard_b);
2401 1 : let optimization_a_prepare = shard_a.optimize_attachment(&mut scheduler, &schedule_context);
2402 1 : assert_eq!(
2403 : optimization_a_prepare,
2404 1 : Some(ScheduleOptimization {
2405 1 : sequence: shard_a.sequence,
2406 1 : action: ScheduleOptimizationAction::CreateSecondary(NodeId(1))
2407 1 : })
2408 : );
2409 1 : shard_a.apply_optimization(&mut scheduler, optimization_a_prepare.unwrap());
2410 :
2411 1 : let schedule_context = make_schedule_context(&shard_a, &shard_b);
2412 1 : let optimization_a_migrate = shard_a.optimize_attachment(&mut scheduler, &schedule_context);
2413 1 : assert_eq!(
2414 : optimization_a_migrate,
2415 1 : Some(ScheduleOptimization {
2416 1 : sequence: shard_a.sequence,
2417 1 : action: ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
2418 1 : old_attached_node_id: NodeId(2),
2419 1 : new_attached_node_id: NodeId(1)
2420 1 : })
2421 1 : })
2422 : );
2423 1 : shard_a.apply_optimization(&mut scheduler, optimization_a_migrate.unwrap());
2424 :
2425 1 : let schedule_context = make_schedule_context(&shard_a, &shard_b);
2426 1 : let optimization_a_cleanup = shard_a.optimize_attachment(&mut scheduler, &schedule_context);
2427 1 : assert_eq!(
2428 : optimization_a_cleanup,
2429 1 : Some(ScheduleOptimization {
2430 1 : sequence: shard_a.sequence,
2431 1 : action: ScheduleOptimizationAction::RemoveSecondary(NodeId(3))
2432 1 : })
2433 : );
2434 1 : shard_a.apply_optimization(&mut scheduler, optimization_a_cleanup.unwrap());
2435 :
2436 : // // Shard B should not be moved anywhere, since the pressure on node 1 was relieved by moving shard A
2437 : // let schedule_context = make_schedule_context(&shard_a, &shard_b);
2438 : // assert_eq!(shard_b.optimize_attachment(&mut scheduler, &schedule_context), None);
2439 :
2440 1 : shard_a.intent.clear(&mut scheduler);
2441 1 : shard_b.intent.clear(&mut scheduler);
2442 :
2443 1 : Ok(())
2444 1 : }
2445 :
2446 : #[test]
2447 : /// How the optimisation code handles a shard with a preferred node set; this is an example
2448 : /// of the multi-step migration, but driven by a different input.
2449 1 : fn optimize_attachment_multi_preferred_node() -> anyhow::Result<()> {
2450 1 : let nodes = make_test_nodes(
2451 : 4,
2452 1 : &[
2453 1 : AvailabilityZone("az-a".to_string()),
2454 1 : AvailabilityZone("az-a".to_string()),
2455 1 : AvailabilityZone("az-b".to_string()),
2456 1 : AvailabilityZone("az-b".to_string()),
2457 1 : ],
2458 : );
2459 1 : let mut scheduler = Scheduler::new(nodes.values());
2460 :
2461 : // Two shards of a tenant that wants to be in AZ A
2462 1 : let mut shard_a = make_test_tenant_shard(PlacementPolicy::Attached(1));
2463 1 : shard_a.intent.preferred_az_id = Some(AvailabilityZone("az-a".to_string()));
2464 :
2465 : // Initially attached in a stable location
2466 1 : shard_a.intent.set_attached(&mut scheduler, Some(NodeId(1)));
2467 1 : shard_a.intent.push_secondary(&mut scheduler, NodeId(3));
2468 :
2469 : // Set the preferred node to node 2, an equally high scoring node to its current location
2470 1 : shard_a.preferred_node = Some(NodeId(2));
2471 :
2472 3 : fn make_schedule_context(shard_a: &TenantShard) -> ScheduleContext {
2473 3 : let mut schedule_context = ScheduleContext::default();
2474 3 : schedule_context.avoid(&shard_a.intent.all_pageservers());
2475 3 : schedule_context
2476 3 : }
2477 :
2478 1 : let schedule_context = make_schedule_context(&shard_a);
2479 1 : let optimization_a_prepare = shard_a.optimize_attachment(&mut scheduler, &schedule_context);
2480 1 : assert_eq!(
2481 : optimization_a_prepare,
2482 1 : Some(ScheduleOptimization {
2483 1 : sequence: shard_a.sequence,
2484 1 : action: ScheduleOptimizationAction::CreateSecondary(NodeId(2))
2485 1 : })
2486 : );
2487 1 : shard_a.apply_optimization(&mut scheduler, optimization_a_prepare.unwrap());
2488 :
2489 : // The first step of the optimisation should not have cleared the preferred node
2490 1 : assert_eq!(shard_a.preferred_node, Some(NodeId(2)));
2491 :
2492 1 : let schedule_context = make_schedule_context(&shard_a);
2493 1 : let optimization_a_migrate = shard_a.optimize_attachment(&mut scheduler, &schedule_context);
2494 1 : assert_eq!(
2495 : optimization_a_migrate,
2496 1 : Some(ScheduleOptimization {
2497 1 : sequence: shard_a.sequence,
2498 1 : action: ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
2499 1 : old_attached_node_id: NodeId(1),
2500 1 : new_attached_node_id: NodeId(2)
2501 1 : })
2502 1 : })
2503 : );
2504 1 : shard_a.apply_optimization(&mut scheduler, optimization_a_migrate.unwrap());
2505 :
2506 : // The cutover step of the optimisation should have cleared the preferred node
2507 1 : assert_eq!(shard_a.preferred_node, None);
2508 :
2509 1 : let schedule_context = make_schedule_context(&shard_a);
2510 1 : let optimization_a_cleanup = shard_a.optimize_attachment(&mut scheduler, &schedule_context);
2511 1 : assert_eq!(
2512 : optimization_a_cleanup,
2513 1 : Some(ScheduleOptimization {
2514 1 : sequence: shard_a.sequence,
2515 1 : action: ScheduleOptimizationAction::RemoveSecondary(NodeId(1))
2516 1 : })
2517 : );
2518 1 : shard_a.apply_optimization(&mut scheduler, optimization_a_cleanup.unwrap());
2519 :
2520 1 : shard_a.intent.clear(&mut scheduler);
2521 :
2522 1 : Ok(())
2523 1 : }
2524 :
2525 : #[test]
2526 : /// Check that multi-step migration works when moving to somewhere that is only better by
2527 : /// 1 AffinityScore -- this ensures that we don't have a bug like the intermediate secondary
2528 : /// counting toward the affinity score such that it prevents the rest of the migration from happening.
2529 1 : fn optimize_attachment_marginal() -> anyhow::Result<()> {
2530 1 : let nodes = make_test_nodes(2, &[]);
2531 1 : let mut scheduler = Scheduler::new(nodes.values());
2532 :
2533 : // Multi-sharded tenant, we will craft a situation where affinity
2534 : // scores differ only slightly
2535 1 : let mut shards = make_test_tenant(PlacementPolicy::Attached(0), ShardCount::new(4), None);
2536 :
2537 : // 1 attached on node 1
2538 1 : shards[0]
2539 1 : .intent
2540 1 : .set_attached(&mut scheduler, Some(NodeId(1)));
2541 : // 3 attached on node 2
2542 1 : shards[1]
2543 1 : .intent
2544 1 : .set_attached(&mut scheduler, Some(NodeId(2)));
2545 1 : shards[2]
2546 1 : .intent
2547 1 : .set_attached(&mut scheduler, Some(NodeId(2)));
2548 1 : shards[3]
2549 1 : .intent
2550 1 : .set_attached(&mut scheduler, Some(NodeId(2)));
2551 :
2552 : // The scheduler should figure out that we need to:
2553 : // - Create a secondary for shard 3 on node 1
2554 : // - Migrate shard 3 to node 1
2555 : // - Remove shard 3's location on node 2
2556 :
2557 4 : fn make_schedule_context(shards: &Vec<TenantShard>) -> ScheduleContext {
2558 4 : let mut schedule_context = ScheduleContext::default();
2559 20 : for shard in shards {
2560 16 : schedule_context.avoid(&shard.intent.all_pageservers());
2561 16 : }
2562 4 : schedule_context
2563 4 : }
2564 :
2565 1 : let schedule_context = make_schedule_context(&shards);
2566 1 : let optimization_a_prepare =
2567 1 : shards[1].optimize_attachment(&mut scheduler, &schedule_context);
2568 1 : assert_eq!(
2569 : optimization_a_prepare,
2570 1 : Some(ScheduleOptimization {
2571 1 : sequence: shards[1].sequence,
2572 1 : action: ScheduleOptimizationAction::CreateSecondary(NodeId(1))
2573 1 : })
2574 : );
2575 1 : shards[1].apply_optimization(&mut scheduler, optimization_a_prepare.unwrap());
2576 :
2577 1 : let schedule_context = make_schedule_context(&shards);
2578 1 : let optimization_a_migrate =
2579 1 : shards[1].optimize_attachment(&mut scheduler, &schedule_context);
2580 1 : assert_eq!(
2581 : optimization_a_migrate,
2582 1 : Some(ScheduleOptimization {
2583 1 : sequence: shards[1].sequence,
2584 1 : action: ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
2585 1 : old_attached_node_id: NodeId(2),
2586 1 : new_attached_node_id: NodeId(1)
2587 1 : })
2588 1 : })
2589 : );
2590 1 : shards[1].apply_optimization(&mut scheduler, optimization_a_migrate.unwrap());
2591 :
2592 1 : let schedule_context = make_schedule_context(&shards);
2593 1 : let optimization_a_cleanup =
2594 1 : shards[1].optimize_attachment(&mut scheduler, &schedule_context);
2595 1 : assert_eq!(
2596 : optimization_a_cleanup,
2597 1 : Some(ScheduleOptimization {
2598 1 : sequence: shards[1].sequence,
2599 1 : action: ScheduleOptimizationAction::RemoveSecondary(NodeId(2))
2600 1 : })
2601 : );
2602 1 : shards[1].apply_optimization(&mut scheduler, optimization_a_cleanup.unwrap());
2603 :
2604 : // Everything should be stable now
2605 1 : let schedule_context = make_schedule_context(&shards);
2606 1 : assert_eq!(
2607 1 : shards[0].optimize_attachment(&mut scheduler, &schedule_context),
2608 : None
2609 : );
2610 1 : assert_eq!(
2611 1 : shards[1].optimize_attachment(&mut scheduler, &schedule_context),
2612 : None
2613 : );
2614 1 : assert_eq!(
2615 1 : shards[2].optimize_attachment(&mut scheduler, &schedule_context),
2616 : None
2617 : );
2618 1 : assert_eq!(
2619 1 : shards[3].optimize_attachment(&mut scheduler, &schedule_context),
2620 : None
2621 : );
2622 :
2623 5 : for mut shard in shards {
2624 4 : shard.intent.clear(&mut scheduler);
2625 4 : }
2626 :
2627 1 : Ok(())
2628 1 : }
2629 :
2630 : #[test]
2631 1 : fn optimize_secondary() -> anyhow::Result<()> {
2632 1 : let nodes = make_test_nodes(4, &[]);
2633 1 : let mut scheduler = Scheduler::new(nodes.values());
2634 :
2635 1 : let mut shard_a = make_test_tenant_shard(PlacementPolicy::Attached(1));
2636 1 : let mut shard_b = make_test_tenant_shard(PlacementPolicy::Attached(1));
2637 :
2638 : // Initially: both nodes attached on shard 1, and both have secondary locations
2639 : // on different nodes.
2640 1 : shard_a.intent.set_attached(&mut scheduler, Some(NodeId(1)));
2641 1 : shard_a.intent.push_secondary(&mut scheduler, NodeId(3));
2642 1 : shard_b.intent.set_attached(&mut scheduler, Some(NodeId(2)));
2643 1 : shard_b.intent.push_secondary(&mut scheduler, NodeId(3));
2644 :
2645 1 : let mut schedule_context = ScheduleContext::default();
2646 1 : schedule_context.avoid(&shard_a.intent.all_pageservers());
2647 1 : schedule_context.avoid(&shard_b.intent.all_pageservers());
2648 :
2649 1 : let optimization_a = shard_a.optimize_secondary(&mut scheduler, &schedule_context);
2650 :
2651 : // Since there is a node with no locations available, the node with two locations for the
2652 : // same tenant should generate an optimization to move one away
2653 1 : assert_eq!(
2654 : optimization_a,
2655 1 : Some(ScheduleOptimization {
2656 1 : sequence: shard_a.sequence,
2657 1 : action: ScheduleOptimizationAction::ReplaceSecondary(ReplaceSecondary {
2658 1 : old_node_id: NodeId(3),
2659 1 : new_node_id: NodeId(4)
2660 1 : })
2661 1 : })
2662 : );
2663 :
2664 1 : shard_a.apply_optimization(&mut scheduler, optimization_a.unwrap());
2665 1 : assert_eq!(shard_a.intent.get_attached(), &Some(NodeId(1)));
2666 1 : assert_eq!(shard_a.intent.get_secondary(), &vec![NodeId(4)]);
2667 :
2668 1 : shard_a.intent.clear(&mut scheduler);
2669 1 : shard_b.intent.clear(&mut scheduler);
2670 :
2671 1 : Ok(())
2672 1 : }
2673 :
2674 : /// Test how the optimisation code behaves with an extra secondary
2675 : #[test]
2676 1 : fn optimize_removes_secondary() -> anyhow::Result<()> {
2677 1 : let az_a_tag = AvailabilityZone("az-a".to_string());
2678 1 : let az_b_tag = AvailabilityZone("az-b".to_string());
2679 1 : let mut nodes = make_test_nodes(
2680 : 4,
2681 1 : &[
2682 1 : az_a_tag.clone(),
2683 1 : az_b_tag.clone(),
2684 1 : az_a_tag.clone(),
2685 1 : az_b_tag.clone(),
2686 1 : ],
2687 : );
2688 1 : let mut scheduler = Scheduler::new(nodes.values());
2689 :
2690 1 : let mut schedule_context = ScheduleContext::default();
2691 :
2692 1 : let mut shard_a = make_test_tenant_shard(PlacementPolicy::Attached(1));
2693 1 : shard_a.intent.preferred_az_id = Some(az_a_tag.clone());
2694 1 : shard_a
2695 1 : .schedule(&mut scheduler, &mut schedule_context)
2696 1 : .unwrap();
2697 :
2698 : // Attached on node 1, secondary on node 2
2699 1 : assert_eq!(shard_a.intent.get_attached(), &Some(NodeId(1)));
2700 1 : assert_eq!(shard_a.intent.get_secondary(), &vec![NodeId(2)]);
2701 :
2702 : // Initially optimiser is idle
2703 1 : assert_eq!(
2704 1 : shard_a.optimize_attachment(&mut scheduler, &schedule_context),
2705 : None
2706 : );
2707 1 : assert_eq!(
2708 1 : shard_a.optimize_secondary(&mut scheduler, &schedule_context),
2709 : None
2710 : );
2711 :
2712 : // A spare secondary in the home AZ: it should be removed -- this is the situation when we're midway through a graceful migration, after cutting over
2713 : // to our new location
2714 1 : shard_a.intent.push_secondary(&mut scheduler, NodeId(3));
2715 1 : let optimization = shard_a.optimize_attachment(&mut scheduler, &schedule_context);
2716 1 : assert_eq!(
2717 : optimization,
2718 1 : Some(ScheduleOptimization {
2719 1 : sequence: shard_a.sequence,
2720 1 : action: ScheduleOptimizationAction::RemoveSecondary(NodeId(3))
2721 1 : })
2722 : );
2723 1 : shard_a.apply_optimization(&mut scheduler, optimization.unwrap());
2724 :
2725 : // A spare secondary in the non-home AZ, and one of them is offline
2726 1 : shard_a.intent.push_secondary(&mut scheduler, NodeId(4));
2727 1 : nodes
2728 1 : .get_mut(&NodeId(4))
2729 1 : .unwrap()
2730 1 : .set_availability(NodeAvailability::Offline);
2731 1 : scheduler.node_upsert(nodes.get(&NodeId(4)).unwrap());
2732 1 : let optimization = shard_a.optimize_attachment(&mut scheduler, &schedule_context);
2733 1 : assert_eq!(
2734 : optimization,
2735 1 : Some(ScheduleOptimization {
2736 1 : sequence: shard_a.sequence,
2737 1 : action: ScheduleOptimizationAction::RemoveSecondary(NodeId(4))
2738 1 : })
2739 : );
2740 1 : shard_a.apply_optimization(&mut scheduler, optimization.unwrap());
2741 :
2742 : // A spare secondary when should have none
2743 1 : shard_a.policy = PlacementPolicy::Attached(0);
2744 1 : let optimization = shard_a.optimize_attachment(&mut scheduler, &schedule_context);
2745 1 : assert_eq!(
2746 : optimization,
2747 1 : Some(ScheduleOptimization {
2748 1 : sequence: shard_a.sequence,
2749 1 : action: ScheduleOptimizationAction::RemoveSecondary(NodeId(2))
2750 1 : })
2751 : );
2752 1 : shard_a.apply_optimization(&mut scheduler, optimization.unwrap());
2753 1 : assert_eq!(shard_a.intent.get_attached(), &Some(NodeId(1)));
2754 1 : assert_eq!(shard_a.intent.get_secondary(), &vec![]);
2755 :
2756 : // Check that in secondary mode, we preserve the secondary in the preferred AZ
2757 1 : let mut schedule_context = ScheduleContext::default(); // Fresh context, we're about to call schedule()
2758 1 : shard_a.policy = PlacementPolicy::Secondary;
2759 1 : shard_a
2760 1 : .schedule(&mut scheduler, &mut schedule_context)
2761 1 : .unwrap();
2762 1 : assert_eq!(shard_a.intent.get_attached(), &None);
2763 1 : assert_eq!(shard_a.intent.get_secondary(), &vec![NodeId(1)]);
2764 1 : assert_eq!(
2765 1 : shard_a.optimize_attachment(&mut scheduler, &schedule_context),
2766 : None
2767 : );
2768 1 : assert_eq!(
2769 1 : shard_a.optimize_secondary(&mut scheduler, &schedule_context),
2770 : None
2771 : );
2772 :
2773 1 : shard_a.intent.clear(&mut scheduler);
2774 :
2775 1 : Ok(())
2776 1 : }
2777 :
2778 : // Optimize til quiescent: this emulates what Service::optimize_all does, when
2779 : // called repeatedly in the background.
2780 : // Returns the applied optimizations
2781 3 : fn optimize_til_idle(
2782 3 : scheduler: &mut Scheduler,
2783 3 : shards: &mut [TenantShard],
2784 3 : ) -> Vec<ScheduleOptimization> {
2785 3 : let mut loop_n = 0;
2786 3 : let mut optimizations = Vec::default();
2787 : loop {
2788 6 : let mut schedule_context = ScheduleContext::default();
2789 6 : let mut any_changed = false;
2790 :
2791 24 : for shard in shards.iter() {
2792 24 : schedule_context.avoid(&shard.intent.all_pageservers());
2793 24 : }
2794 :
2795 15 : for shard in shards.iter_mut() {
2796 15 : let optimization = shard.optimize_attachment(scheduler, &schedule_context);
2797 15 : tracing::info!(
2798 0 : "optimize_attachment({})={:?}",
2799 : shard.tenant_shard_id,
2800 : optimization
2801 : );
2802 15 : if let Some(optimization) = optimization {
2803 : // Check that maybe_optimizable wouldn't have wrongly claimed this optimization didn't exist
2804 3 : assert!(shard.maybe_optimizable(scheduler, &schedule_context));
2805 3 : optimizations.push(optimization.clone());
2806 3 : shard.apply_optimization(scheduler, optimization);
2807 3 : any_changed = true;
2808 3 : break;
2809 12 : }
2810 :
2811 12 : let optimization = shard.optimize_secondary(scheduler, &schedule_context);
2812 12 : tracing::info!(
2813 0 : "optimize_secondary({})={:?}",
2814 : shard.tenant_shard_id,
2815 : optimization
2816 : );
2817 12 : if let Some(optimization) = optimization {
2818 : // Check that maybe_optimizable wouldn't have wrongly claimed this optimization didn't exist
2819 0 : assert!(shard.maybe_optimizable(scheduler, &schedule_context));
2820 :
2821 0 : optimizations.push(optimization.clone());
2822 0 : shard.apply_optimization(scheduler, optimization);
2823 0 : any_changed = true;
2824 0 : break;
2825 12 : }
2826 : }
2827 :
2828 6 : if !any_changed {
2829 3 : break;
2830 3 : }
2831 :
2832 : // Assert no infinite loop
2833 3 : loop_n += 1;
2834 3 : assert!(loop_n < 1000);
2835 : }
2836 :
2837 3 : optimizations
2838 3 : }
2839 :
2840 : /// Test the balancing behavior of shard scheduling: that it achieves a balance, and
2841 : /// that it converges.
2842 : #[test]
2843 1 : fn optimize_add_nodes() -> anyhow::Result<()> {
2844 1 : let nodes = make_test_nodes(
2845 : 9,
2846 1 : &[
2847 1 : // Initial 6 nodes
2848 1 : AvailabilityZone("az-a".to_string()),
2849 1 : AvailabilityZone("az-a".to_string()),
2850 1 : AvailabilityZone("az-b".to_string()),
2851 1 : AvailabilityZone("az-b".to_string()),
2852 1 : AvailabilityZone("az-c".to_string()),
2853 1 : AvailabilityZone("az-c".to_string()),
2854 1 : // Three we will add later
2855 1 : AvailabilityZone("az-a".to_string()),
2856 1 : AvailabilityZone("az-b".to_string()),
2857 1 : AvailabilityZone("az-c".to_string()),
2858 1 : ],
2859 : );
2860 :
2861 : // Only show the scheduler two nodes in each AZ to start with
2862 1 : let mut scheduler = Scheduler::new([].iter());
2863 7 : for i in 1..=6 {
2864 6 : scheduler.node_upsert(nodes.get(&NodeId(i)).unwrap());
2865 6 : }
2866 :
2867 1 : let mut shards = make_test_tenant(
2868 1 : PlacementPolicy::Attached(1),
2869 1 : ShardCount::new(4),
2870 1 : Some(AvailabilityZone("az-a".to_string())),
2871 : );
2872 1 : let mut schedule_context = ScheduleContext::default();
2873 5 : for shard in &mut shards {
2874 4 : assert!(
2875 4 : shard
2876 4 : .schedule(&mut scheduler, &mut schedule_context)
2877 4 : .is_ok()
2878 : );
2879 : }
2880 :
2881 : // Initial: attached locations land in the tenant's home AZ.
2882 1 : assert_eq!(scheduler.get_node_shard_count(NodeId(1)), 2);
2883 1 : assert_eq!(scheduler.get_node_attached_shard_count(NodeId(1)), 2);
2884 1 : assert_eq!(scheduler.get_node_shard_count(NodeId(2)), 2);
2885 1 : assert_eq!(scheduler.get_node_attached_shard_count(NodeId(2)), 2);
2886 :
2887 : // Initial: secondary locations in a remote AZ
2888 1 : assert_eq!(scheduler.get_node_shard_count(NodeId(3)), 1);
2889 1 : assert_eq!(scheduler.get_node_attached_shard_count(NodeId(3)), 0);
2890 1 : assert_eq!(scheduler.get_node_shard_count(NodeId(4)), 1);
2891 1 : assert_eq!(scheduler.get_node_attached_shard_count(NodeId(4)), 0);
2892 1 : assert_eq!(scheduler.get_node_shard_count(NodeId(5)), 1);
2893 1 : assert_eq!(scheduler.get_node_attached_shard_count(NodeId(5)), 0);
2894 1 : assert_eq!(scheduler.get_node_shard_count(NodeId(6)), 1);
2895 1 : assert_eq!(scheduler.get_node_attached_shard_count(NodeId(6)), 0);
2896 :
2897 : // Add another three nodes: we should see the shards spread out when their optimize
2898 : // methods are called
2899 1 : scheduler.node_upsert(nodes.get(&NodeId(7)).unwrap());
2900 1 : scheduler.node_upsert(nodes.get(&NodeId(8)).unwrap());
2901 1 : scheduler.node_upsert(nodes.get(&NodeId(9)).unwrap());
2902 1 : optimize_til_idle(&mut scheduler, &mut shards);
2903 :
2904 : // We expect one attached location was moved to the new node in the tenant's home AZ
2905 1 : assert_eq!(scheduler.get_node_shard_count(NodeId(7)), 1);
2906 1 : assert_eq!(scheduler.get_node_attached_shard_count(NodeId(7)), 1);
2907 : // The original node has one less attached shard
2908 1 : assert_eq!(scheduler.get_node_shard_count(NodeId(1)), 1);
2909 1 : assert_eq!(scheduler.get_node_attached_shard_count(NodeId(1)), 1);
2910 :
2911 : // One of the original nodes still has two attachments, since there are an odd number of nodes
2912 1 : assert_eq!(scheduler.get_node_shard_count(NodeId(2)), 2);
2913 1 : assert_eq!(scheduler.get_node_attached_shard_count(NodeId(2)), 2);
2914 :
2915 : // None of our secondaries moved, since we already had enough nodes for those to be
2916 : // scheduled perfectly
2917 1 : assert_eq!(scheduler.get_node_shard_count(NodeId(3)), 1);
2918 1 : assert_eq!(scheduler.get_node_attached_shard_count(NodeId(3)), 0);
2919 1 : assert_eq!(scheduler.get_node_shard_count(NodeId(4)), 1);
2920 1 : assert_eq!(scheduler.get_node_attached_shard_count(NodeId(4)), 0);
2921 1 : assert_eq!(scheduler.get_node_shard_count(NodeId(5)), 1);
2922 1 : assert_eq!(scheduler.get_node_attached_shard_count(NodeId(5)), 0);
2923 1 : assert_eq!(scheduler.get_node_shard_count(NodeId(6)), 1);
2924 1 : assert_eq!(scheduler.get_node_attached_shard_count(NodeId(6)), 0);
2925 :
2926 4 : for shard in shards.iter_mut() {
2927 4 : shard.intent.clear(&mut scheduler);
2928 4 : }
2929 :
2930 1 : Ok(())
2931 1 : }
2932 :
2933 : /// Test that initial shard scheduling is optimal. By optimal we mean
2934 : /// that the optimizer cannot find a way to improve it.
2935 : ///
2936 : /// This test is an example of the scheduling issue described in
2937 : /// https://github.com/neondatabase/neon/issues/8969
2938 : #[test]
2939 1 : fn initial_scheduling_is_optimal() -> anyhow::Result<()> {
2940 : use itertools::Itertools;
2941 :
2942 1 : let nodes = make_test_nodes(2, &[]);
2943 :
2944 1 : let mut scheduler = Scheduler::new([].iter());
2945 1 : scheduler.node_upsert(nodes.get(&NodeId(1)).unwrap());
2946 1 : scheduler.node_upsert(nodes.get(&NodeId(2)).unwrap());
2947 :
2948 1 : let mut a = make_test_tenant(PlacementPolicy::Attached(1), ShardCount::new(4), None);
2949 1 : let a_context = Rc::new(RefCell::new(ScheduleContext::default()));
2950 :
2951 1 : let mut b = make_test_tenant(PlacementPolicy::Attached(1), ShardCount::new(4), None);
2952 1 : let b_context = Rc::new(RefCell::new(ScheduleContext::default()));
2953 :
2954 4 : let a_shards_with_context = a.iter_mut().map(|shard| (shard, a_context.clone()));
2955 4 : let b_shards_with_context = b.iter_mut().map(|shard| (shard, b_context.clone()));
2956 :
2957 1 : let schedule_order = a_shards_with_context.interleave(b_shards_with_context);
2958 :
2959 9 : for (shard, context) in schedule_order {
2960 8 : let context = &mut *context.borrow_mut();
2961 8 : shard.schedule(&mut scheduler, context).unwrap();
2962 8 : }
2963 :
2964 1 : let applied_to_a = optimize_til_idle(&mut scheduler, &mut a);
2965 1 : assert_eq!(applied_to_a, vec![]);
2966 :
2967 1 : let applied_to_b = optimize_til_idle(&mut scheduler, &mut b);
2968 1 : assert_eq!(applied_to_b, vec![]);
2969 :
2970 8 : for shard in a.iter_mut().chain(b.iter_mut()) {
2971 8 : shard.intent.clear(&mut scheduler);
2972 8 : }
2973 :
2974 1 : Ok(())
2975 1 : }
2976 :
2977 : #[test]
2978 1 : fn random_az_shard_scheduling() -> anyhow::Result<()> {
2979 : use rand::seq::SliceRandom;
2980 :
2981 51 : for seed in 0..50 {
2982 50 : eprintln!("Running test with seed {seed}");
2983 50 : let mut rng = StdRng::seed_from_u64(seed);
2984 :
2985 50 : let az_a_tag = AvailabilityZone("az-a".to_string());
2986 50 : let az_b_tag = AvailabilityZone("az-b".to_string());
2987 50 : let azs = [az_a_tag, az_b_tag];
2988 50 : let nodes = make_test_nodes(4, &azs);
2989 50 : let mut shards_per_az: HashMap<AvailabilityZone, u32> = HashMap::new();
2990 :
2991 50 : let mut scheduler = Scheduler::new([].iter());
2992 200 : for node in nodes.values() {
2993 200 : scheduler.node_upsert(node);
2994 200 : }
2995 :
2996 50 : let mut shards = Vec::default();
2997 50 : let mut contexts = Vec::default();
2998 50 : let mut az_picker = azs.iter().cycle().cloned();
2999 5050 : for i in 0..100 {
3000 5000 : let az = az_picker.next().unwrap();
3001 5000 : let shard_count = i % 4 + 1;
3002 5000 : *shards_per_az.entry(az.clone()).or_default() += shard_count;
3003 :
3004 5000 : let tenant_shards = make_test_tenant(
3005 5000 : PlacementPolicy::Attached(1),
3006 5000 : ShardCount::new(shard_count.try_into().unwrap()),
3007 5000 : Some(az),
3008 : );
3009 5000 : let context = Rc::new(RefCell::new(ScheduleContext::default()));
3010 :
3011 5000 : contexts.push(context.clone());
3012 5000 : let with_ctx = tenant_shards
3013 5000 : .into_iter()
3014 12500 : .map(|shard| (shard, context.clone()));
3015 17500 : for shard_with_ctx in with_ctx {
3016 12500 : shards.push(shard_with_ctx);
3017 12500 : }
3018 : }
3019 :
3020 50 : shards.shuffle(&mut rng);
3021 :
3022 : #[derive(Default, Debug)]
3023 : struct NodeStats {
3024 : attachments: u32,
3025 : secondaries: u32,
3026 : }
3027 :
3028 50 : let mut node_stats: HashMap<NodeId, NodeStats> = HashMap::default();
3029 50 : let mut attachments_in_wrong_az = 0;
3030 50 : let mut secondaries_in_wrong_az = 0;
3031 :
3032 12550 : for (shard, context) in &mut shards {
3033 12500 : let context = &mut *context.borrow_mut();
3034 12500 : shard.schedule(&mut scheduler, context).unwrap();
3035 :
3036 12500 : let attached_node = shard.intent.get_attached().unwrap();
3037 12500 : let stats = node_stats.entry(attached_node).or_default();
3038 12500 : stats.attachments += 1;
3039 :
3040 12500 : let secondary_node = *shard.intent.get_secondary().first().unwrap();
3041 12500 : let stats = node_stats.entry(secondary_node).or_default();
3042 12500 : stats.secondaries += 1;
3043 :
3044 12500 : let attached_node_az = nodes
3045 12500 : .get(&attached_node)
3046 12500 : .unwrap()
3047 12500 : .get_availability_zone_id();
3048 12500 : let secondary_node_az = nodes
3049 12500 : .get(&secondary_node)
3050 12500 : .unwrap()
3051 12500 : .get_availability_zone_id();
3052 12500 : let preferred_az = shard.preferred_az().unwrap();
3053 :
3054 12500 : if attached_node_az != preferred_az {
3055 0 : eprintln!(
3056 0 : "{} attachment was scheduled in AZ {} but preferred AZ {}",
3057 0 : shard.tenant_shard_id, attached_node_az, preferred_az
3058 0 : );
3059 0 : attachments_in_wrong_az += 1;
3060 12500 : }
3061 :
3062 12500 : if secondary_node_az == preferred_az {
3063 0 : eprintln!(
3064 0 : "{} secondary was scheduled in AZ {} which matches preference",
3065 0 : shard.tenant_shard_id, attached_node_az
3066 0 : );
3067 0 : secondaries_in_wrong_az += 1;
3068 12500 : }
3069 : }
3070 :
3071 50 : let mut violations = Vec::default();
3072 :
3073 50 : if attachments_in_wrong_az > 0 {
3074 0 : violations.push(format!(
3075 0 : "{attachments_in_wrong_az} attachments scheduled to the incorrect AZ"
3076 0 : ));
3077 50 : }
3078 :
3079 50 : if secondaries_in_wrong_az > 0 {
3080 0 : violations.push(format!(
3081 0 : "{secondaries_in_wrong_az} secondaries scheduled to the incorrect AZ"
3082 0 : ));
3083 50 : }
3084 :
3085 50 : eprintln!(
3086 50 : "attachments_in_wrong_az={attachments_in_wrong_az} secondaries_in_wrong_az={secondaries_in_wrong_az}"
3087 : );
3088 :
3089 250 : for (node_id, stats) in &node_stats {
3090 200 : let node_az = nodes.get(node_id).unwrap().get_availability_zone_id();
3091 200 : let ideal_attachment_load = shards_per_az.get(node_az).unwrap() / 2;
3092 200 : let allowed_attachment_load =
3093 200 : (ideal_attachment_load - 1)..(ideal_attachment_load + 2);
3094 :
3095 200 : if !allowed_attachment_load.contains(&stats.attachments) {
3096 0 : violations.push(format!(
3097 0 : "Found {} attachments on node {}, but expected {}",
3098 0 : stats.attachments, node_id, ideal_attachment_load
3099 0 : ));
3100 200 : }
3101 :
3102 200 : eprintln!(
3103 200 : "{}: attachments={} secondaries={} ideal_attachment_load={}",
3104 : node_id, stats.attachments, stats.secondaries, ideal_attachment_load
3105 : );
3106 : }
3107 :
3108 50 : assert!(violations.is_empty(), "{violations:?}");
3109 :
3110 12550 : for (mut shard, _ctx) in shards {
3111 12500 : shard.intent.clear(&mut scheduler);
3112 12500 : }
3113 : }
3114 1 : Ok(())
3115 1 : }
3116 :
3117 : /// Check how the shard's scheduling behaves when in PlacementPolicy::Secondary mode.
3118 : #[test]
3119 1 : fn tenant_secondary_scheduling() -> anyhow::Result<()> {
3120 1 : let az_a = AvailabilityZone("az-a".to_string());
3121 1 : let nodes = make_test_nodes(
3122 : 3,
3123 1 : &[
3124 1 : az_a.clone(),
3125 1 : AvailabilityZone("az-b".to_string()),
3126 1 : AvailabilityZone("az-c".to_string()),
3127 1 : ],
3128 : );
3129 :
3130 1 : let mut scheduler = Scheduler::new(nodes.values());
3131 1 : let mut context = ScheduleContext::default();
3132 :
3133 1 : let mut tenant_shard = make_test_tenant_shard(PlacementPolicy::Secondary);
3134 1 : tenant_shard.intent.preferred_az_id = Some(az_a.clone());
3135 1 : tenant_shard
3136 1 : .schedule(&mut scheduler, &mut context)
3137 1 : .expect("we have enough nodes, scheduling should work");
3138 1 : assert_eq!(tenant_shard.intent.secondary.len(), 1);
3139 1 : assert!(tenant_shard.intent.attached.is_none());
3140 :
3141 : // Should have scheduled into the preferred AZ
3142 1 : assert_eq!(
3143 1 : scheduler
3144 1 : .get_node_az(&tenant_shard.intent.secondary[0])
3145 1 : .as_ref(),
3146 1 : tenant_shard.preferred_az()
3147 : );
3148 :
3149 : // Optimizer should agree
3150 1 : assert_eq!(
3151 1 : tenant_shard.optimize_attachment(&mut scheduler, &context),
3152 : None
3153 : );
3154 1 : assert_eq!(
3155 1 : tenant_shard.optimize_secondary(&mut scheduler, &context),
3156 : None
3157 : );
3158 :
3159 : // Switch to PlacementPolicy::Attached
3160 1 : tenant_shard.policy = PlacementPolicy::Attached(1);
3161 1 : tenant_shard
3162 1 : .schedule(&mut scheduler, &mut context)
3163 1 : .expect("we have enough nodes, scheduling should work");
3164 1 : assert_eq!(tenant_shard.intent.secondary.len(), 1);
3165 1 : assert!(tenant_shard.intent.attached.is_some());
3166 : // Secondary should now be in non-preferred AZ
3167 1 : assert_ne!(
3168 1 : scheduler
3169 1 : .get_node_az(&tenant_shard.intent.secondary[0])
3170 1 : .as_ref(),
3171 1 : tenant_shard.preferred_az()
3172 : );
3173 : // Attached should be in preferred AZ
3174 1 : assert_eq!(
3175 1 : scheduler
3176 1 : .get_node_az(&tenant_shard.intent.attached.unwrap())
3177 1 : .as_ref(),
3178 1 : tenant_shard.preferred_az()
3179 : );
3180 :
3181 : // Optimizer should agree
3182 1 : assert_eq!(
3183 1 : tenant_shard.optimize_attachment(&mut scheduler, &context),
3184 : None
3185 : );
3186 1 : assert_eq!(
3187 1 : tenant_shard.optimize_secondary(&mut scheduler, &context),
3188 : None
3189 : );
3190 :
3191 : // Switch back to PlacementPolicy::Secondary
3192 1 : tenant_shard.policy = PlacementPolicy::Secondary;
3193 1 : tenant_shard
3194 1 : .schedule(&mut scheduler, &mut context)
3195 1 : .expect("we have enough nodes, scheduling should work");
3196 1 : assert_eq!(tenant_shard.intent.secondary.len(), 1);
3197 1 : assert!(tenant_shard.intent.attached.is_none());
3198 : // When we picked a location to keep, we should have kept the one in the preferred AZ
3199 1 : assert_eq!(
3200 1 : scheduler
3201 1 : .get_node_az(&tenant_shard.intent.secondary[0])
3202 1 : .as_ref(),
3203 1 : tenant_shard.preferred_az()
3204 : );
3205 :
3206 : // Optimizer should agree
3207 1 : assert_eq!(
3208 1 : tenant_shard.optimize_attachment(&mut scheduler, &context),
3209 : None
3210 : );
3211 1 : assert_eq!(
3212 1 : tenant_shard.optimize_secondary(&mut scheduler, &context),
3213 : None
3214 : );
3215 :
3216 1 : tenant_shard.intent.clear(&mut scheduler);
3217 :
3218 1 : Ok(())
3219 1 : }
3220 : }
|