Line data Source code
1 : use std::collections::HashMap;
2 : use std::fmt::Debug;
3 :
4 : use http_utils::error::ApiError;
5 : use itertools::Itertools;
6 : use pageserver_api::controller_api::AvailabilityZone;
7 : use pageserver_api::models::PageserverUtilization;
8 : use serde::Serialize;
9 : use utils::id::NodeId;
10 :
11 : use crate::metrics::NodeLabelGroup;
12 : use crate::node::Node;
13 : use crate::tenant_shard::TenantShard;
14 :
15 : /// Scenarios in which we cannot find a suitable location for a tenant shard
16 : #[derive(thiserror::Error, Debug)]
17 : pub enum ScheduleError {
18 : #[error("No pageservers found")]
19 : NoPageservers,
20 : #[error("No pageserver found matching constraint")]
21 : ImpossibleConstraint,
22 : }
23 :
24 : impl From<ScheduleError> for ApiError {
25 0 : fn from(value: ScheduleError) -> Self {
26 0 : ApiError::Conflict(format!("Scheduling error: {}", value))
27 0 : }
28 : }
29 :
30 : #[derive(Serialize)]
31 : pub enum MaySchedule {
32 : Yes(PageserverUtilization),
33 : No,
34 : }
35 :
36 : #[derive(Serialize)]
37 : pub(crate) struct SchedulerNode {
38 : /// How many shards are currently scheduled on this node, via their [`crate::tenant_shard::IntentState`].
39 : shard_count: usize,
40 : /// How many shards are currently attached on this node, via their [`crate::tenant_shard::IntentState`].
41 : attached_shard_count: usize,
42 : /// How many shards have a location on this node (via [`crate::tenant_shard::IntentState`]) _and_ this node
43 : /// is in their preferred AZ (i.e. this is their 'home' location)
44 : home_shard_count: usize,
45 : /// Availability zone id in which the node resides
46 : az: AvailabilityZone,
47 :
48 : /// Whether this node is currently elegible to have new shards scheduled (this is derived
49 : /// from a node's availability state and scheduling policy).
50 : may_schedule: MaySchedule,
51 : }
52 :
53 : pub(crate) trait NodeSchedulingScore: Debug + Ord + Copy + Sized {
54 : fn generate(
55 : node_id: &NodeId,
56 : node: &mut SchedulerNode,
57 : preferred_az: &Option<AvailabilityZone>,
58 : context: &ScheduleContext,
59 : ) -> Option<Self>;
60 :
61 : /// Return a score that drops any components based on node utilization: this is useful
62 : /// for finding scores for scheduling optimisation, when we want to avoid rescheduling
63 : /// shards due to e.g. disk usage, to avoid flapping.
64 : fn for_optimization(&self) -> Self;
65 :
66 : fn is_overloaded(&self) -> bool;
67 : fn node_id(&self) -> NodeId;
68 : }
69 :
70 : pub(crate) trait ShardTag {
71 : type Score: NodeSchedulingScore;
72 : }
73 :
74 : pub(crate) struct AttachedShardTag {}
75 : impl ShardTag for AttachedShardTag {
76 : type Score = NodeAttachmentSchedulingScore;
77 : }
78 :
79 : pub(crate) struct SecondaryShardTag {}
80 : impl ShardTag for SecondaryShardTag {
81 : type Score = NodeSecondarySchedulingScore;
82 : }
83 :
84 : #[derive(PartialEq, Eq, Debug, Clone, Copy)]
85 : enum AzMatch {
86 : Yes,
87 : No,
88 : Unknown,
89 : }
90 :
91 : impl AzMatch {
92 91473 : fn new(node_az: &AvailabilityZone, shard_preferred_az: Option<&AvailabilityZone>) -> Self {
93 91301 : match shard_preferred_az {
94 91301 : Some(preferred_az) if preferred_az == node_az => Self::Yes,
95 52680 : Some(_preferred_az) => Self::No,
96 172 : None => Self::Unknown,
97 : }
98 91473 : }
99 : }
100 :
101 : #[derive(PartialEq, Eq, Debug, Clone, Copy)]
102 : struct AttachmentAzMatch(AzMatch);
103 :
104 : impl Ord for AttachmentAzMatch {
105 65502 : fn cmp(&self, other: &Self) -> std::cmp::Ordering {
106 65502 : // Lower scores indicate a more suitable node.
107 65502 : // Note that we prefer a node for which we don't have
108 65502 : // info to a node which we are certain doesn't match the
109 65502 : // preferred AZ of the shard.
110 131004 : let az_match_score = |az_match: &AzMatch| match az_match {
111 64339 : AzMatch::Yes => 0,
112 166 : AzMatch::Unknown => 1,
113 66499 : AzMatch::No => 2,
114 131004 : };
115 :
116 65502 : az_match_score(&self.0).cmp(&az_match_score(&other.0))
117 65502 : }
118 : }
119 :
120 : impl PartialOrd for AttachmentAzMatch {
121 65502 : fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
122 65502 : Some(self.cmp(other))
123 65502 : }
124 : }
125 :
126 : #[derive(PartialEq, Eq, Debug, Clone, Copy)]
127 : struct SecondaryAzMatch(AzMatch);
128 :
129 : impl Ord for SecondaryAzMatch {
130 36447 : fn cmp(&self, other: &Self) -> std::cmp::Ordering {
131 36447 : // Lower scores indicate a more suitable node.
132 36447 : // For secondary locations we wish to avoid the preferred AZ
133 36447 : // of the shard.
134 72894 : let az_match_score = |az_match: &AzMatch| match az_match {
135 50565 : AzMatch::No => 0,
136 22 : AzMatch::Unknown => 1,
137 22307 : AzMatch::Yes => 2,
138 72894 : };
139 :
140 36447 : az_match_score(&self.0).cmp(&az_match_score(&other.0))
141 36447 : }
142 : }
143 :
144 : impl PartialOrd for SecondaryAzMatch {
145 36444 : fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
146 36444 : Some(self.cmp(other))
147 36444 : }
148 : }
149 :
150 : /// Scheduling score of a given node for shard attachments.
151 : /// Lower scores indicate more suitable nodes.
152 : /// Ordering is given by member declaration order (top to bottom).
153 : #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
154 : pub(crate) struct NodeAttachmentSchedulingScore {
155 : /// Flag indicating whether this node matches the preferred AZ
156 : /// of the shard. For equal affinity scores, nodes in the matching AZ
157 : /// are considered first.
158 : az_match: AttachmentAzMatch,
159 : /// The number of shards belonging to the tenant currently being
160 : /// scheduled that are attached to this node.
161 : affinity_score: AffinityScore,
162 : /// Utilisation score that combines shard count and disk utilisation
163 : utilization_score: u64,
164 : /// Total number of shards attached to this node. When nodes have identical utilisation, this
165 : /// acts as an anti-affinity between attached shards.
166 : total_attached_shard_count: usize,
167 : /// Convenience to make selection deterministic in tests and empty systems
168 : node_id: NodeId,
169 : }
170 :
171 : impl NodeSchedulingScore for NodeAttachmentSchedulingScore {
172 52280 : fn generate(
173 52280 : node_id: &NodeId,
174 52280 : node: &mut SchedulerNode,
175 52280 : preferred_az: &Option<AvailabilityZone>,
176 52280 : context: &ScheduleContext,
177 52280 : ) -> Option<Self> {
178 52280 : let utilization = match &mut node.may_schedule {
179 52278 : MaySchedule::Yes(u) => u,
180 : MaySchedule::No => {
181 2 : return None;
182 : }
183 : };
184 :
185 52278 : Some(Self {
186 52278 : affinity_score: context
187 52278 : .nodes
188 52278 : .get(node_id)
189 52278 : .copied()
190 52278 : .unwrap_or(AffinityScore::FREE),
191 52278 : az_match: AttachmentAzMatch(AzMatch::new(&node.az, preferred_az.as_ref())),
192 52278 : utilization_score: utilization.cached_score(),
193 52278 : total_attached_shard_count: node.attached_shard_count,
194 52278 : node_id: *node_id,
195 52278 : })
196 52280 : }
197 :
198 : /// For use in scheduling optimisation, where we only want to consider the aspects
199 : /// of the score that can only be resolved by moving things (such as inter-shard affinity
200 : /// and AZ affinity), and ignore aspects that reflect the total utilization of a node (which
201 : /// can fluctuate for other reasons)
202 110 : fn for_optimization(&self) -> Self {
203 110 : Self {
204 110 : utilization_score: 0,
205 110 : total_attached_shard_count: 0,
206 110 : node_id: NodeId(0),
207 110 : ..*self
208 110 : }
209 110 : }
210 :
211 52168 : fn is_overloaded(&self) -> bool {
212 52168 : PageserverUtilization::is_overloaded(self.utilization_score)
213 52168 : }
214 :
215 12879 : fn node_id(&self) -> NodeId {
216 12879 : self.node_id
217 12879 : }
218 : }
219 :
220 : /// Scheduling score of a given node for shard secondaries.
221 : /// Lower scores indicate more suitable nodes.
222 : /// Ordering is given by member declaration order (top to bottom).
223 : #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
224 : pub(crate) struct NodeSecondarySchedulingScore {
225 : /// Flag indicating whether this node matches the preferred AZ
226 : /// of the shard. For secondary locations we wish to avoid nodes in.
227 : /// the preferred AZ of the shard, since that's where the attached location
228 : /// should be scheduled and having the secondary in the same AZ is bad for HA.
229 : az_match: SecondaryAzMatch,
230 : /// The number of shards belonging to the tenant currently being
231 : /// scheduled that are attached to this node.
232 : affinity_score: AffinityScore,
233 : /// Utilisation score that combines shard count and disk utilisation
234 : utilization_score: u64,
235 : /// Anti-affinity with other non-home locations: this gives the behavior that secondaries
236 : /// will spread out across the nodes in an AZ.
237 : total_non_home_shard_count: usize,
238 : /// Convenience to make selection deterministic in tests and empty systems
239 : node_id: NodeId,
240 : }
241 :
242 : impl NodeSchedulingScore for NodeSecondarySchedulingScore {
243 39196 : fn generate(
244 39196 : node_id: &NodeId,
245 39196 : node: &mut SchedulerNode,
246 39196 : preferred_az: &Option<AvailabilityZone>,
247 39196 : context: &ScheduleContext,
248 39196 : ) -> Option<Self> {
249 39196 : let utilization = match &mut node.may_schedule {
250 39195 : MaySchedule::Yes(u) => u,
251 : MaySchedule::No => {
252 1 : return None;
253 : }
254 : };
255 :
256 39195 : Some(Self {
257 39195 : az_match: SecondaryAzMatch(AzMatch::new(&node.az, preferred_az.as_ref())),
258 39195 : affinity_score: context
259 39195 : .nodes
260 39195 : .get(node_id)
261 39195 : .copied()
262 39195 : .unwrap_or(AffinityScore::FREE),
263 39195 : utilization_score: utilization.cached_score(),
264 39195 : total_non_home_shard_count: (node.shard_count - node.home_shard_count),
265 39195 : node_id: *node_id,
266 39195 : })
267 39196 : }
268 :
269 14 : fn for_optimization(&self) -> Self {
270 14 : Self {
271 14 : utilization_score: 0,
272 14 : total_non_home_shard_count: 0,
273 14 : node_id: NodeId(0),
274 14 : ..*self
275 14 : }
276 14 : }
277 :
278 39172 : fn is_overloaded(&self) -> bool {
279 39172 : PageserverUtilization::is_overloaded(self.utilization_score)
280 39172 : }
281 :
282 12846 : fn node_id(&self) -> NodeId {
283 12846 : self.node_id
284 12846 : }
285 : }
286 :
287 : impl PartialEq for SchedulerNode {
288 3 : fn eq(&self, other: &Self) -> bool {
289 3 : let may_schedule_matches = matches!(
290 3 : (&self.may_schedule, &other.may_schedule),
291 : (MaySchedule::Yes(_), MaySchedule::Yes(_)) | (MaySchedule::No, MaySchedule::No)
292 : );
293 :
294 3 : may_schedule_matches
295 3 : && self.shard_count == other.shard_count
296 3 : && self.attached_shard_count == other.attached_shard_count
297 3 : && self.az == other.az
298 3 : }
299 : }
300 :
301 : impl Eq for SchedulerNode {}
302 :
303 : /// This type is responsible for selecting which node is used when a tenant shard needs to choose a pageserver
304 : /// on which to run.
305 : ///
306 : /// The type has no persistent state of its own: this is all populated at startup. The Serialize
307 : /// impl is only for debug dumps.
308 : #[derive(Serialize)]
309 : pub(crate) struct Scheduler {
310 : nodes: HashMap<NodeId, SchedulerNode>,
311 : }
312 :
313 : /// Score for soft constraint scheduling: lower scores are preferred to higher scores.
314 : ///
315 : /// For example, we may set an affinity score based on the number of shards from the same
316 : /// tenant already on a node, to implicitly prefer to balance out shards.
317 : #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
318 : pub(crate) struct AffinityScore(pub(crate) usize);
319 :
320 : impl AffinityScore {
321 : /// If we have no anti-affinity at all toward a node, this is its score. It means
322 : /// the scheduler has a free choice amongst nodes with this score, and may pick a node
323 : /// based on other information such as total utilization.
324 : pub(crate) const FREE: Self = Self(0);
325 :
326 25773 : pub(crate) fn inc(&mut self) {
327 25773 : self.0 += 1;
328 25773 : }
329 :
330 118 : pub(crate) fn dec(&mut self) {
331 118 : self.0 -= 1;
332 118 : }
333 : }
334 :
335 : impl std::ops::Add for AffinityScore {
336 : type Output = Self;
337 :
338 0 : fn add(self, rhs: Self) -> Self::Output {
339 0 : Self(self.0 + rhs.0)
340 0 : }
341 : }
342 :
343 : /// Hint for whether this is a sincere attempt to schedule, or a speculative
344 : /// check for where we _would_ schedule (done during optimization)
345 : #[derive(Debug, Clone)]
346 : pub(crate) enum ScheduleMode {
347 : Normal,
348 : Speculative,
349 : }
350 :
351 : impl Default for ScheduleMode {
352 5330 : fn default() -> Self {
353 5330 : Self::Normal
354 5330 : }
355 : }
356 :
357 : // For carrying state between multiple calls to [`TenantShard::schedule`], e.g. when calling
358 : // it for many shards in the same tenant.
359 : #[derive(Debug, Default, Clone)]
360 : pub(crate) struct ScheduleContext {
361 : /// Sparse map of nodes: omitting a node implicitly makes its affinity [`AffinityScore::FREE`]
362 : pub(crate) nodes: HashMap<NodeId, AffinityScore>,
363 :
364 : pub(crate) mode: ScheduleMode,
365 : }
366 :
367 : impl ScheduleContext {
368 3 : pub(crate) fn new(mode: ScheduleMode) -> Self {
369 3 : Self {
370 3 : nodes: HashMap::new(),
371 3 : mode,
372 3 : }
373 3 : }
374 :
375 : /// Input is a list of nodes we would like to avoid using again within this context. The more
376 : /// times a node is passed into this call, the less inclined we are to use it.
377 12896 : pub(crate) fn avoid(&mut self, nodes: &[NodeId]) {
378 38669 : for node_id in nodes {
379 25773 : let entry = self.nodes.entry(*node_id).or_insert(AffinityScore::FREE);
380 25773 : entry.inc()
381 : }
382 12896 : }
383 :
384 : /// Remove `shard`'s contributions to this context. This is useful when considering scheduling
385 : /// this shard afresh, where we don't want it to e.g. experience anti-affinity to its current location.
386 60 : pub(crate) fn project_detach(&self, shard: &TenantShard) -> Self {
387 60 : let mut new_context = self.clone();
388 :
389 60 : if let Some(attached) = shard.intent.get_attached() {
390 57 : if let Some(score) = new_context.nodes.get_mut(attached) {
391 57 : score.dec();
392 57 : }
393 3 : }
394 :
395 63 : for secondary in shard.intent.get_secondary() {
396 63 : if let Some(score) = new_context.nodes.get_mut(secondary) {
397 61 : score.dec();
398 61 : }
399 : }
400 :
401 60 : new_context
402 60 : }
403 :
404 : /// For test, track the sum of AffinityScore values, which is effectively how many
405 : /// attached or secondary locations have been registered with this context.
406 : #[cfg(test)]
407 3 : pub(crate) fn location_count(&self) -> usize {
408 7 : self.nodes.values().map(|i| i.0).sum()
409 3 : }
410 : }
411 :
412 : pub(crate) enum RefCountUpdate {
413 : PromoteSecondary,
414 : Attach,
415 : Detach,
416 : DemoteAttached,
417 : AddSecondary,
418 : RemoveSecondary,
419 : }
420 :
421 : impl Scheduler {
422 68 : pub(crate) fn new<'a>(nodes: impl Iterator<Item = &'a Node>) -> Self {
423 68 : let mut scheduler_nodes = HashMap::new();
424 129 : for node in nodes {
425 61 : scheduler_nodes.insert(
426 61 : node.get_id(),
427 61 : SchedulerNode {
428 61 : shard_count: 0,
429 61 : attached_shard_count: 0,
430 61 : home_shard_count: 0,
431 61 : may_schedule: node.may_schedule(),
432 61 : az: node.get_availability_zone_id().clone(),
433 61 : },
434 61 : );
435 61 : }
436 :
437 68 : Self {
438 68 : nodes: scheduler_nodes,
439 68 : }
440 68 : }
441 :
442 : /// For debug/support: check that our internal statistics are in sync with the state of
443 : /// the nodes & tenant shards.
444 : ///
445 : /// If anything is inconsistent, log details and return an error.
446 1 : pub(crate) fn consistency_check<'a>(
447 1 : &self,
448 1 : nodes: impl Iterator<Item = &'a Node>,
449 1 : shards: impl Iterator<Item = &'a TenantShard>,
450 1 : ) -> anyhow::Result<()> {
451 1 : let mut expect_nodes: HashMap<NodeId, SchedulerNode> = HashMap::new();
452 4 : for node in nodes {
453 3 : expect_nodes.insert(
454 3 : node.get_id(),
455 3 : SchedulerNode {
456 3 : shard_count: 0,
457 3 : attached_shard_count: 0,
458 3 : home_shard_count: 0,
459 3 : may_schedule: node.may_schedule(),
460 3 : az: node.get_availability_zone_id().clone(),
461 3 : },
462 3 : );
463 3 : }
464 :
465 2 : for shard in shards {
466 1 : if let Some(node_id) = shard.intent.get_attached() {
467 1 : match expect_nodes.get_mut(node_id) {
468 1 : Some(node) => {
469 1 : node.shard_count += 1;
470 1 : node.attached_shard_count += 1;
471 1 : if Some(&node.az) == shard.preferred_az() {
472 0 : node.home_shard_count += 1;
473 1 : }
474 : }
475 0 : None => anyhow::bail!(
476 0 : "Tenant {} references nonexistent node {}",
477 0 : shard.tenant_shard_id,
478 0 : node_id
479 0 : ),
480 : }
481 0 : }
482 :
483 1 : for node_id in shard.intent.get_secondary() {
484 1 : match expect_nodes.get_mut(node_id) {
485 1 : Some(node) => {
486 1 : node.shard_count += 1;
487 1 : if Some(&node.az) == shard.preferred_az() {
488 0 : node.home_shard_count += 1;
489 1 : }
490 : }
491 0 : None => anyhow::bail!(
492 0 : "Tenant {} references nonexistent node {}",
493 0 : shard.tenant_shard_id,
494 0 : node_id
495 0 : ),
496 : }
497 : }
498 : }
499 :
500 4 : for (node_id, expect_node) in &expect_nodes {
501 3 : let Some(self_node) = self.nodes.get(node_id) else {
502 0 : anyhow::bail!("Node {node_id} not found in Self")
503 : };
504 :
505 3 : if self_node != expect_node {
506 0 : tracing::error!("Inconsistency detected in scheduling state for node {node_id}");
507 0 : tracing::error!("Expected state: {}", serde_json::to_string(expect_node)?);
508 0 : tracing::error!("Self state: {}", serde_json::to_string(self_node)?);
509 :
510 0 : anyhow::bail!("Inconsistent state on {node_id}");
511 3 : }
512 : }
513 :
514 1 : if expect_nodes.len() != self.nodes.len() {
515 : // We just checked that all the expected nodes are present. If the lengths don't match,
516 : // it means that we have nodes in Self that are unexpected.
517 0 : for node_id in self.nodes.keys() {
518 0 : if !expect_nodes.contains_key(node_id) {
519 0 : anyhow::bail!("Node {node_id} found in Self but not in expected nodes");
520 0 : }
521 : }
522 1 : }
523 :
524 1 : Ok(())
525 1 : }
526 :
527 : /// Update the reference counts of a node. These reference counts are used to guide scheduling
528 : /// decisions, not for memory management: they represent the number of tenant shard whose IntentState
529 : /// targets this node and the number of tenants shars whose IntentState is attached to this
530 : /// node.
531 : ///
532 : /// It is an error to call this for a node that is not known to the scheduler (i.e. passed into
533 : /// [`Self::new`] or [`Self::node_upsert`])
534 51416 : pub(crate) fn update_node_ref_counts(
535 51416 : &mut self,
536 51416 : node_id: NodeId,
537 51416 : preferred_az: Option<&AvailabilityZone>,
538 51416 : update: RefCountUpdate,
539 51416 : ) {
540 51416 : let Some(node) = self.nodes.get_mut(&node_id) else {
541 0 : debug_assert!(false);
542 0 : tracing::error!("Scheduler missing node {node_id}");
543 0 : return;
544 : };
545 :
546 51416 : let is_home_az = Some(&node.az) == preferred_az;
547 51416 :
548 51416 : match update {
549 6 : RefCountUpdate::PromoteSecondary => {
550 6 : node.attached_shard_count += 1;
551 6 : }
552 : RefCountUpdate::Attach => {
553 12857 : node.shard_count += 1;
554 12857 : node.attached_shard_count += 1;
555 12857 : if is_home_az {
556 12817 : node.home_shard_count += 1;
557 12817 : }
558 : }
559 : RefCountUpdate::Detach => {
560 12855 : node.shard_count -= 1;
561 12855 : node.attached_shard_count -= 1;
562 12855 : if is_home_az {
563 12818 : node.home_shard_count -= 1;
564 12818 : }
565 : }
566 7 : RefCountUpdate::DemoteAttached => {
567 7 : node.attached_shard_count -= 1;
568 7 : }
569 : RefCountUpdate::AddSecondary => {
570 12845 : node.shard_count += 1;
571 12845 : if is_home_az {
572 5 : node.home_shard_count += 1;
573 12840 : }
574 : }
575 : RefCountUpdate::RemoveSecondary => {
576 12846 : node.shard_count -= 1;
577 12846 : if is_home_az {
578 4 : node.home_shard_count -= 1;
579 12842 : }
580 : }
581 : }
582 :
583 : // Maybe update PageserverUtilization
584 51416 : match update {
585 : RefCountUpdate::AddSecondary | RefCountUpdate::Attach => {
586 : // Referencing the node: if this takes our shard_count above the utilzation structure's
587 : // shard count, then artifically bump it: this ensures that the scheduler immediately
588 : // recognizes that this node has more work on it, without waiting for the next heartbeat
589 : // to update the utilization.
590 25702 : if let MaySchedule::Yes(utilization) = &mut node.may_schedule {
591 25702 : utilization.adjust_shard_count_max(node.shard_count as u32);
592 25702 : }
593 : }
594 : RefCountUpdate::PromoteSecondary
595 : | RefCountUpdate::Detach
596 : | RefCountUpdate::RemoveSecondary
597 25714 : | RefCountUpdate::DemoteAttached => {
598 25714 : // De-referencing the node: leave the utilization's shard_count at a stale higher
599 25714 : // value until some future heartbeat after we have physically removed this shard
600 25714 : // from the node: this prevents the scheduler over-optimistically trying to schedule
601 25714 : // more work onto the node before earlier detaches are done.
602 25714 : }
603 : }
604 51416 : }
605 :
606 : // Check if the number of shards attached to a given node is lagging below
607 : // the cluster average. If that's the case, the node should be filled.
608 0 : pub(crate) fn compute_fill_requirement(&self, node_id: NodeId) -> usize {
609 0 : let Some(node) = self.nodes.get(&node_id) else {
610 0 : debug_assert!(false);
611 0 : tracing::error!("Scheduler missing node {node_id}");
612 0 : return 0;
613 : };
614 0 : assert!(!self.nodes.is_empty());
615 0 : let expected_attached_shards_per_node = self.expected_attached_shard_count();
616 :
617 0 : for (node_id, node) in self.nodes.iter() {
618 0 : tracing::trace!(%node_id, "attached_shard_count={} shard_count={} expected={}", node.attached_shard_count, node.shard_count, expected_attached_shards_per_node);
619 : }
620 :
621 0 : if node.attached_shard_count < expected_attached_shards_per_node {
622 0 : expected_attached_shards_per_node - node.attached_shard_count
623 : } else {
624 0 : 0
625 : }
626 0 : }
627 :
628 0 : pub(crate) fn expected_attached_shard_count(&self) -> usize {
629 0 : let total_attached_shards: usize =
630 0 : self.nodes.values().map(|n| n.attached_shard_count).sum();
631 0 :
632 0 : assert!(!self.nodes.is_empty());
633 0 : total_attached_shards / self.nodes.len()
634 0 : }
635 :
636 0 : pub(crate) fn nodes_by_attached_shard_count(&self) -> Vec<(NodeId, usize)> {
637 0 : self.nodes
638 0 : .iter()
639 0 : .map(|(node_id, stats)| (*node_id, stats.attached_shard_count))
640 0 : .sorted_by(|lhs, rhs| Ord::cmp(&lhs.1, &rhs.1).reverse())
641 0 : .collect()
642 0 : }
643 :
644 215 : pub(crate) fn node_upsert(&mut self, node: &Node) {
645 : use std::collections::hash_map::Entry::*;
646 215 : match self.nodes.entry(node.get_id()) {
647 4 : Occupied(mut entry) => {
648 4 : // Updates to MaySchedule are how we receive updated PageserverUtilization: adjust these values
649 4 : // to account for any shards scheduled on the controller but not yet visible to the pageserver.
650 4 : let mut may_schedule = node.may_schedule();
651 4 : match &mut may_schedule {
652 2 : MaySchedule::Yes(utilization) => {
653 2 : utilization.adjust_shard_count_max(entry.get().shard_count as u32);
654 2 : }
655 2 : MaySchedule::No => { // Nothing to tweak
656 2 : }
657 : }
658 :
659 4 : entry.get_mut().may_schedule = may_schedule;
660 : }
661 211 : Vacant(entry) => {
662 211 : entry.insert(SchedulerNode {
663 211 : shard_count: 0,
664 211 : attached_shard_count: 0,
665 211 : home_shard_count: 0,
666 211 : may_schedule: node.may_schedule(),
667 211 : az: node.get_availability_zone_id().clone(),
668 211 : });
669 211 : }
670 : }
671 215 : }
672 :
673 0 : pub(crate) fn node_remove(&mut self, node_id: NodeId) {
674 0 : if self.nodes.remove(&node_id).is_none() {
675 0 : tracing::warn!(node_id=%node_id, "Removed non-existent node from scheduler");
676 0 : }
677 0 : }
678 :
679 : /// Calculate a single node's score, used in optimizer logic to compare specific
680 : /// nodes' scores.
681 135 : pub(crate) fn compute_node_score<Score>(
682 135 : &mut self,
683 135 : node_id: NodeId,
684 135 : preferred_az: &Option<AvailabilityZone>,
685 135 : context: &ScheduleContext,
686 135 : ) -> Option<Score>
687 135 : where
688 135 : Score: NodeSchedulingScore,
689 135 : {
690 135 : self.nodes
691 135 : .get_mut(&node_id)
692 135 : .and_then(|node| Score::generate(&node_id, node, preferred_az, context))
693 135 : }
694 :
695 : /// Compute a schedulling score for each node that the scheduler knows of
696 : /// minus a set of hard excluded nodes.
697 25725 : fn compute_node_scores<Score>(
698 25725 : &mut self,
699 25725 : hard_exclude: &[NodeId],
700 25725 : preferred_az: &Option<AvailabilityZone>,
701 25725 : context: &ScheduleContext,
702 25725 : ) -> Vec<Score>
703 25725 : where
704 25725 : Score: NodeSchedulingScore,
705 25725 : {
706 25725 : self.nodes
707 25725 : .iter_mut()
708 104187 : .filter_map(|(k, v)| {
709 104187 : if hard_exclude.contains(k) {
710 12846 : None
711 : } else {
712 91341 : Score::generate(k, v, preferred_az, context)
713 : }
714 104187 : })
715 25725 : .collect()
716 25725 : }
717 :
718 : /// hard_exclude: it is forbidden to use nodes in this list, typically becacuse they
719 : /// are already in use by this shard -- we use this to avoid picking the same node
720 : /// as both attached and secondary location. This is a hard constraint: if we cannot
721 : /// find any nodes that aren't in this list, then we will return a [`ScheduleError::ImpossibleConstraint`].
722 : ///
723 : /// context: we prefer to avoid using nodes identified in the context, according
724 : /// to their anti-affinity score. We use this to prefeer to avoid placing shards in
725 : /// the same tenant on the same node. This is a soft constraint: the context will never
726 : /// cause us to fail to schedule a shard.
727 25725 : pub(crate) fn schedule_shard<Tag: ShardTag>(
728 25725 : &mut self,
729 25725 : hard_exclude: &[NodeId],
730 25725 : preferred_az: &Option<AvailabilityZone>,
731 25725 : context: &ScheduleContext,
732 25725 : ) -> Result<NodeId, ScheduleError> {
733 25725 : if self.nodes.is_empty() {
734 0 : return Err(ScheduleError::NoPageservers);
735 25725 : }
736 25725 :
737 25725 : let mut scores =
738 25725 : self.compute_node_scores::<Tag::Score>(hard_exclude, preferred_az, context);
739 25725 :
740 25725 : // Exclude nodes whose utilization is critically high, if there are alternatives available. This will
741 25725 : // cause us to violate affinity rules if it is necessary to avoid critically overloading nodes: for example
742 25725 : // we may place shards in the same tenant together on the same pageserver if all other pageservers are
743 25725 : // overloaded.
744 25725 : let non_overloaded_scores = scores
745 25725 : .iter()
746 91340 : .filter(|i| !i.is_overloaded())
747 25725 : .copied()
748 25725 : .collect::<Vec<_>>();
749 25725 : if !non_overloaded_scores.is_empty() {
750 25725 : scores = non_overloaded_scores;
751 25725 : }
752 :
753 : // Sort the nodes by score. The one with the lowest scores will be the preferred node.
754 : // Refer to [`NodeAttachmentSchedulingScore`] for attached locations and
755 : // [`NodeSecondarySchedulingScore`] for secondary locations to understand how the nodes
756 : // are ranked.
757 25725 : scores.sort();
758 25725 :
759 25725 : if scores.is_empty() {
760 : // After applying constraints, no pageservers were left.
761 0 : if !matches!(context.mode, ScheduleMode::Speculative) {
762 : // If this was not a speculative attempt, log details to understand why we couldn't
763 : // schedule: this may help an engineer understand if some nodes are marked offline
764 : // in a way that's preventing progress.
765 0 : tracing::info!(
766 0 : "Scheduling failure, while excluding {hard_exclude:?}, node states:"
767 : );
768 0 : for (node_id, node) in &self.nodes {
769 0 : tracing::info!(
770 0 : "Node {node_id}: may_schedule={} shards={}",
771 0 : !matches!(node.may_schedule, MaySchedule::No),
772 : node.shard_count
773 : );
774 : }
775 0 : }
776 0 : return Err(ScheduleError::ImpossibleConstraint);
777 25725 : }
778 25725 :
779 25725 : // Lowest score wins
780 25725 : let node_id = scores.first().unwrap().node_id();
781 :
782 25725 : if !matches!(context.mode, ScheduleMode::Speculative) {
783 25725 : tracing::info!(
784 0 : "scheduler selected node {node_id} (elegible nodes {:?}, hard exclude: {hard_exclude:?}, soft exclude: {context:?}, preferred_az: {:?})",
785 0 : scores.iter().map(|i| i.node_id().0).collect::<Vec<_>>(),
786 : preferred_az,
787 : );
788 0 : }
789 :
790 : // Note that we do not update shard count here to reflect the scheduling: that
791 : // is IntentState's job when the scheduled location is used.
792 :
793 25725 : Ok(node_id)
794 25725 : }
795 :
796 : /// Selects any available node. This is suitable for performing background work (e.g. S3
797 : /// deletions).
798 0 : pub(crate) fn any_available_node(&mut self) -> Result<NodeId, ScheduleError> {
799 0 : self.schedule_shard::<AttachedShardTag>(&[], &None, &ScheduleContext::default())
800 0 : }
801 :
802 : /// For choosing which AZ to schedule a new shard into, use this. It will return the
803 : /// AZ with the the lowest number of shards currently scheduled in this AZ as their home
804 : /// location.
805 : ///
806 : /// We use an AZ-wide measure rather than simply selecting the AZ of the least-loaded
807 : /// node, because while tenants start out single sharded, when they grow and undergo
808 : /// shard-split, they will occupy space on many nodes within an AZ. It is important
809 : /// that we pick the AZ in a way that balances this _future_ load.
810 : ///
811 : /// Once we've picked an AZ, subsequent scheduling within that AZ will be driven by
812 : /// nodes' utilization scores.
813 303 : pub(crate) fn get_az_for_new_tenant(&self) -> Option<AvailabilityZone> {
814 303 : if self.nodes.is_empty() {
815 0 : return None;
816 303 : }
817 :
818 : #[derive(Default)]
819 : struct AzScore {
820 : home_shard_count: usize,
821 : scheduleable: bool,
822 : }
823 :
824 303 : let mut azs: HashMap<&AvailabilityZone, AzScore> = HashMap::new();
825 1818 : for node in self.nodes.values() {
826 1818 : let az = azs.entry(&node.az).or_default();
827 1818 : az.home_shard_count += node.home_shard_count;
828 1818 : az.scheduleable |= matches!(node.may_schedule, MaySchedule::Yes(_));
829 : }
830 :
831 : // If any AZs are schedulable, then filter out the non-schedulable ones (i.e. AZs where
832 : // all nodes are overloaded or otherwise unschedulable).
833 303 : if azs.values().any(|i| i.scheduleable) {
834 906 : azs.retain(|_, i| i.scheduleable);
835 303 : }
836 :
837 : // Find the AZ with the lowest number of shards currently allocated
838 303 : Some(
839 303 : azs.into_iter()
840 906 : .min_by_key(|i| (i.1.home_shard_count, i.0))
841 303 : .unwrap()
842 303 : .0
843 303 : .clone(),
844 303 : )
845 303 : }
846 :
847 9 : pub(crate) fn get_node_az(&self, node_id: &NodeId) -> Option<AvailabilityZone> {
848 9 : self.nodes.get(node_id).map(|n| n.az.clone())
849 9 : }
850 :
851 : /// For use when choosing a preferred secondary location: filter out nodes that are not
852 : /// available, and gather their AZs.
853 12831 : pub(crate) fn filter_usable_nodes(
854 12831 : &self,
855 12831 : nodes: &[NodeId],
856 12831 : ) -> Vec<(NodeId, Option<AvailabilityZone>)> {
857 12831 : nodes
858 12831 : .iter()
859 12831 : .filter_map(|node_id| {
860 3 : let node = self
861 3 : .nodes
862 3 : .get(node_id)
863 3 : .expect("Referenced nodes always exist");
864 3 : if matches!(node.may_schedule, MaySchedule::Yes(_)) {
865 2 : Some((*node_id, Some(node.az.clone())))
866 : } else {
867 1 : None
868 : }
869 12831 : })
870 12831 : .collect()
871 12831 : }
872 :
873 : /// Unit test access to internal state
874 : #[cfg(test)]
875 19 : pub(crate) fn get_node_shard_count(&self, node_id: NodeId) -> usize {
876 19 : self.nodes.get(&node_id).unwrap().shard_count
877 19 : }
878 :
879 : #[cfg(test)]
880 19 : pub(crate) fn get_node_attached_shard_count(&self, node_id: NodeId) -> usize {
881 19 : self.nodes.get(&node_id).unwrap().attached_shard_count
882 19 : }
883 :
884 : /// Some metrics that we only calculate periodically: this is simpler than
885 : /// rigorously updating them on every change.
886 0 : pub(crate) fn update_metrics(&self) {
887 0 : for (node_id, node) in &self.nodes {
888 0 : let node_id_str = format!("{}", node_id);
889 0 : let label_group = NodeLabelGroup {
890 0 : az: &node.az.0,
891 0 : node_id: &node_id_str,
892 0 : };
893 0 :
894 0 : crate::metrics::METRICS_REGISTRY
895 0 : .metrics_group
896 0 : .storage_controller_node_shards
897 0 : .set(label_group.clone(), node.shard_count as i64);
898 0 :
899 0 : crate::metrics::METRICS_REGISTRY
900 0 : .metrics_group
901 0 : .storage_controller_node_attached_shards
902 0 : .set(label_group.clone(), node.attached_shard_count as i64);
903 0 :
904 0 : crate::metrics::METRICS_REGISTRY
905 0 : .metrics_group
906 0 : .storage_controller_node_home_shards
907 0 : .set(label_group.clone(), node.home_shard_count as i64);
908 0 : }
909 0 : }
910 : }
911 :
912 : #[cfg(test)]
913 : pub(crate) mod test_utils {
914 :
915 : use std::collections::HashMap;
916 :
917 : use pageserver_api::controller_api::{AvailabilityZone, NodeAvailability};
918 : use pageserver_api::models::utilization::test_utilization;
919 : use utils::id::NodeId;
920 :
921 : use crate::node::Node;
922 :
923 : /// Test helper: synthesize the requested number of nodes, all in active state.
924 : ///
925 : /// Node IDs start at one.
926 : ///
927 : /// The `azs` argument specifies the list of availability zones which will be assigned
928 : /// to nodes in round-robin fashion. If empy, a default AZ is assigned.
929 68 : pub(crate) fn make_test_nodes(n: u64, azs: &[AvailabilityZone]) -> HashMap<NodeId, Node> {
930 68 : let mut az_iter = azs.iter().cycle();
931 68 :
932 68 : (1..n + 1)
933 272 : .map(|i| {
934 272 : (NodeId(i), {
935 272 : let mut node = Node::new(
936 272 : NodeId(i),
937 272 : format!("httphost-{i}"),
938 272 : 80 + i as u16,
939 272 : None,
940 272 : format!("pghost-{i}"),
941 272 : 5432 + i as u16,
942 272 : az_iter
943 272 : .next()
944 272 : .cloned()
945 272 : .unwrap_or(AvailabilityZone("test-az".to_string())),
946 272 : false,
947 272 : )
948 272 : .unwrap();
949 272 : node.set_availability(NodeAvailability::Active(test_utilization::simple(0, 0)));
950 272 : assert!(node.is_available());
951 272 : node
952 272 : })
953 272 : })
954 68 : .collect()
955 68 : }
956 : }
957 :
958 : #[cfg(test)]
959 : mod tests {
960 : use pageserver_api::controller_api::NodeAvailability;
961 : use pageserver_api::models::utilization::test_utilization;
962 : use pageserver_api::shard::ShardIdentity;
963 : use utils::id::TenantId;
964 : use utils::shard::{ShardCount, ShardNumber, TenantShardId};
965 :
966 : use super::*;
967 : use crate::tenant_shard::IntentState;
968 : #[test]
969 1 : fn scheduler_basic() -> anyhow::Result<()> {
970 1 : let nodes = test_utils::make_test_nodes(2, &[]);
971 1 :
972 1 : let mut scheduler = Scheduler::new(nodes.values());
973 1 : let mut t1_intent = IntentState::new(None);
974 1 : let mut t2_intent = IntentState::new(None);
975 1 :
976 1 : let context = ScheduleContext::default();
977 :
978 1 : let scheduled = scheduler.schedule_shard::<AttachedShardTag>(&[], &None, &context)?;
979 1 : t1_intent.set_attached(&mut scheduler, Some(scheduled));
980 1 : let scheduled = scheduler.schedule_shard::<AttachedShardTag>(&[], &None, &context)?;
981 1 : t2_intent.set_attached(&mut scheduler, Some(scheduled));
982 1 :
983 1 : assert_eq!(scheduler.get_node_shard_count(NodeId(1)), 1);
984 1 : assert_eq!(scheduler.get_node_attached_shard_count(NodeId(1)), 1);
985 :
986 1 : assert_eq!(scheduler.get_node_shard_count(NodeId(2)), 1);
987 1 : assert_eq!(scheduler.get_node_attached_shard_count(NodeId(2)), 1);
988 :
989 1 : let scheduled = scheduler.schedule_shard::<AttachedShardTag>(
990 1 : &t1_intent.all_pageservers(),
991 1 : &None,
992 1 : &context,
993 1 : )?;
994 1 : t1_intent.push_secondary(&mut scheduler, scheduled);
995 1 :
996 1 : assert_eq!(scheduler.get_node_shard_count(NodeId(1)), 1);
997 1 : assert_eq!(scheduler.get_node_attached_shard_count(NodeId(1)), 1);
998 :
999 1 : assert_eq!(scheduler.get_node_shard_count(NodeId(2)), 2);
1000 1 : assert_eq!(scheduler.get_node_attached_shard_count(NodeId(2)), 1);
1001 :
1002 1 : t1_intent.clear(&mut scheduler);
1003 1 : assert_eq!(scheduler.get_node_shard_count(NodeId(1)), 0);
1004 1 : assert_eq!(scheduler.get_node_shard_count(NodeId(2)), 1);
1005 :
1006 1 : let total_attached = scheduler.get_node_attached_shard_count(NodeId(1))
1007 1 : + scheduler.get_node_attached_shard_count(NodeId(2));
1008 1 : assert_eq!(total_attached, 1);
1009 :
1010 1 : if cfg!(debug_assertions) {
1011 : // Dropping an IntentState without clearing it causes a panic in debug mode,
1012 : // because we have failed to properly update scheduler shard counts.
1013 1 : let result = std::panic::catch_unwind(move || {
1014 1 : drop(t2_intent);
1015 1 : });
1016 1 : assert!(result.is_err());
1017 : } else {
1018 0 : t2_intent.clear(&mut scheduler);
1019 0 :
1020 0 : assert_eq!(scheduler.get_node_shard_count(NodeId(1)), 0);
1021 0 : assert_eq!(scheduler.get_node_attached_shard_count(NodeId(1)), 0);
1022 :
1023 0 : assert_eq!(scheduler.get_node_shard_count(NodeId(2)), 0);
1024 0 : assert_eq!(scheduler.get_node_attached_shard_count(NodeId(2)), 0);
1025 : }
1026 :
1027 1 : Ok(())
1028 1 : }
1029 :
1030 : #[test]
1031 : /// Test the PageserverUtilization's contribution to scheduling algorithm
1032 1 : fn scheduler_utilization() {
1033 1 : let mut nodes = test_utils::make_test_nodes(3, &[]);
1034 1 : let mut scheduler = Scheduler::new(nodes.values());
1035 1 :
1036 1 : // Need to keep these alive because they contribute to shard counts via RAII
1037 1 : let mut scheduled_intents = Vec::new();
1038 1 :
1039 1 : let empty_context = ScheduleContext::default();
1040 :
1041 11 : fn assert_scheduler_chooses(
1042 11 : expect_node: NodeId,
1043 11 : scheduled_intents: &mut Vec<IntentState>,
1044 11 : scheduler: &mut Scheduler,
1045 11 : context: &ScheduleContext,
1046 11 : ) {
1047 11 : let scheduled = scheduler
1048 11 : .schedule_shard::<AttachedShardTag>(&[], &None, context)
1049 11 : .unwrap();
1050 11 : let mut intent = IntentState::new(None);
1051 11 : intent.set_attached(scheduler, Some(scheduled));
1052 11 : scheduled_intents.push(intent);
1053 11 : assert_eq!(scheduled, expect_node);
1054 11 : }
1055 :
1056 : // Independent schedule calls onto empty nodes should round-robin, because each node's
1057 : // utilization's shard count is updated inline. The order is determinsitic because when all other factors are
1058 : // equal, we order by node ID.
1059 1 : assert_scheduler_chooses(
1060 1 : NodeId(1),
1061 1 : &mut scheduled_intents,
1062 1 : &mut scheduler,
1063 1 : &empty_context,
1064 1 : );
1065 1 : assert_scheduler_chooses(
1066 1 : NodeId(2),
1067 1 : &mut scheduled_intents,
1068 1 : &mut scheduler,
1069 1 : &empty_context,
1070 1 : );
1071 1 : assert_scheduler_chooses(
1072 1 : NodeId(3),
1073 1 : &mut scheduled_intents,
1074 1 : &mut scheduler,
1075 1 : &empty_context,
1076 1 : );
1077 1 :
1078 1 : // Manually setting utilization higher should cause schedule calls to round-robin the other nodes
1079 1 : // which have equal utilization.
1080 1 : nodes
1081 1 : .get_mut(&NodeId(1))
1082 1 : .unwrap()
1083 1 : .set_availability(NodeAvailability::Active(test_utilization::simple(
1084 1 : 10,
1085 1 : 1024 * 1024 * 1024,
1086 1 : )));
1087 1 : scheduler.node_upsert(nodes.get(&NodeId(1)).unwrap());
1088 1 :
1089 1 : assert_scheduler_chooses(
1090 1 : NodeId(2),
1091 1 : &mut scheduled_intents,
1092 1 : &mut scheduler,
1093 1 : &empty_context,
1094 1 : );
1095 1 : assert_scheduler_chooses(
1096 1 : NodeId(3),
1097 1 : &mut scheduled_intents,
1098 1 : &mut scheduler,
1099 1 : &empty_context,
1100 1 : );
1101 1 : assert_scheduler_chooses(
1102 1 : NodeId(2),
1103 1 : &mut scheduled_intents,
1104 1 : &mut scheduler,
1105 1 : &empty_context,
1106 1 : );
1107 1 : assert_scheduler_chooses(
1108 1 : NodeId(3),
1109 1 : &mut scheduled_intents,
1110 1 : &mut scheduler,
1111 1 : &empty_context,
1112 1 : );
1113 1 :
1114 1 : // The scheduler should prefer nodes with lower affinity score,
1115 1 : // even if they have higher utilization (as long as they aren't utilized at >100%)
1116 1 : let mut context_prefer_node1 = ScheduleContext::default();
1117 1 : context_prefer_node1.avoid(&[NodeId(2), NodeId(3)]);
1118 1 : assert_scheduler_chooses(
1119 1 : NodeId(1),
1120 1 : &mut scheduled_intents,
1121 1 : &mut scheduler,
1122 1 : &context_prefer_node1,
1123 1 : );
1124 1 : assert_scheduler_chooses(
1125 1 : NodeId(1),
1126 1 : &mut scheduled_intents,
1127 1 : &mut scheduler,
1128 1 : &context_prefer_node1,
1129 1 : );
1130 1 :
1131 1 : // If a node is over-utilized, it will not be used even if affinity scores prefer it
1132 1 : nodes
1133 1 : .get_mut(&NodeId(1))
1134 1 : .unwrap()
1135 1 : .set_availability(NodeAvailability::Active(test_utilization::simple(
1136 1 : 20000,
1137 1 : 1024 * 1024 * 1024,
1138 1 : )));
1139 1 : scheduler.node_upsert(nodes.get(&NodeId(1)).unwrap());
1140 1 : assert_scheduler_chooses(
1141 1 : NodeId(2),
1142 1 : &mut scheduled_intents,
1143 1 : &mut scheduler,
1144 1 : &context_prefer_node1,
1145 1 : );
1146 1 : assert_scheduler_chooses(
1147 1 : NodeId(3),
1148 1 : &mut scheduled_intents,
1149 1 : &mut scheduler,
1150 1 : &context_prefer_node1,
1151 1 : );
1152 :
1153 12 : for mut intent in scheduled_intents {
1154 11 : intent.clear(&mut scheduler);
1155 11 : }
1156 1 : }
1157 :
1158 : #[test]
1159 : /// A simple test that showcases AZ-aware scheduling and its interaction with
1160 : /// affinity scores.
1161 1 : fn az_scheduling() {
1162 1 : let az_a_tag = AvailabilityZone("az-a".to_string());
1163 1 : let az_b_tag = AvailabilityZone("az-b".to_string());
1164 1 :
1165 1 : let nodes = test_utils::make_test_nodes(3, &[az_a_tag.clone(), az_b_tag.clone()]);
1166 1 : let mut scheduler = Scheduler::new(nodes.values());
1167 1 :
1168 1 : // Need to keep these alive because they contribute to shard counts via RAII
1169 1 : let mut scheduled_intents = Vec::new();
1170 1 :
1171 1 : let mut context = ScheduleContext::default();
1172 :
1173 4 : fn assert_scheduler_chooses<Tag: ShardTag>(
1174 4 : expect_node: NodeId,
1175 4 : preferred_az: Option<AvailabilityZone>,
1176 4 : scheduled_intents: &mut Vec<IntentState>,
1177 4 : scheduler: &mut Scheduler,
1178 4 : context: &mut ScheduleContext,
1179 4 : ) {
1180 4 : let scheduled = scheduler
1181 4 : .schedule_shard::<Tag>(&[], &preferred_az, context)
1182 4 : .unwrap();
1183 4 : let mut intent = IntentState::new(preferred_az.clone());
1184 4 : intent.set_attached(scheduler, Some(scheduled));
1185 4 : scheduled_intents.push(intent);
1186 4 : assert_eq!(scheduled, expect_node);
1187 :
1188 4 : context.avoid(&[scheduled]);
1189 4 : }
1190 :
1191 1 : assert_scheduler_chooses::<AttachedShardTag>(
1192 1 : NodeId(1),
1193 1 : Some(az_a_tag.clone()),
1194 1 : &mut scheduled_intents,
1195 1 : &mut scheduler,
1196 1 : &mut context,
1197 1 : );
1198 1 :
1199 1 : // Node 2 and 3 have affinity score equal to 0, but node 3
1200 1 : // is in "az-a" so we prefer that.
1201 1 : assert_scheduler_chooses::<AttachedShardTag>(
1202 1 : NodeId(3),
1203 1 : Some(az_a_tag.clone()),
1204 1 : &mut scheduled_intents,
1205 1 : &mut scheduler,
1206 1 : &mut context,
1207 1 : );
1208 1 :
1209 1 : // Node 1 and 3 (az-a) have same affinity score, so prefer the lowest node id.
1210 1 : assert_scheduler_chooses::<AttachedShardTag>(
1211 1 : NodeId(1),
1212 1 : Some(az_a_tag.clone()),
1213 1 : &mut scheduled_intents,
1214 1 : &mut scheduler,
1215 1 : &mut context,
1216 1 : );
1217 1 :
1218 1 : // Avoid nodes in "az-a" for the secondary location.
1219 1 : assert_scheduler_chooses::<SecondaryShardTag>(
1220 1 : NodeId(2),
1221 1 : Some(az_a_tag.clone()),
1222 1 : &mut scheduled_intents,
1223 1 : &mut scheduler,
1224 1 : &mut context,
1225 1 : );
1226 :
1227 5 : for mut intent in scheduled_intents {
1228 4 : intent.clear(&mut scheduler);
1229 4 : }
1230 1 : }
1231 :
1232 : #[test]
1233 1 : fn az_scheduling_for_new_tenant() {
1234 1 : let az_a_tag = AvailabilityZone("az-a".to_string());
1235 1 : let az_b_tag = AvailabilityZone("az-b".to_string());
1236 1 : let nodes = test_utils::make_test_nodes(
1237 1 : 6,
1238 1 : &[
1239 1 : az_a_tag.clone(),
1240 1 : az_a_tag.clone(),
1241 1 : az_a_tag.clone(),
1242 1 : az_b_tag.clone(),
1243 1 : az_b_tag.clone(),
1244 1 : az_b_tag.clone(),
1245 1 : ],
1246 1 : );
1247 1 :
1248 1 : let mut scheduler = Scheduler::new(nodes.values());
1249 :
1250 : /// Force the `home_shard_count` of a node directly: this is the metric used
1251 : /// by the scheduler when picking AZs.
1252 3 : fn set_shard_count(scheduler: &mut Scheduler, node_id: NodeId, shard_count: usize) {
1253 3 : let node = scheduler.nodes.get_mut(&node_id).unwrap();
1254 3 : node.home_shard_count = shard_count;
1255 3 : }
1256 :
1257 : // Initial empty state. Scores are tied, scheduler prefers lower AZ ID.
1258 1 : assert_eq!(scheduler.get_az_for_new_tenant(), Some(az_a_tag.clone()));
1259 :
1260 : // Home shard count is higher in AZ A, so AZ B will be preferred
1261 1 : set_shard_count(&mut scheduler, NodeId(1), 10);
1262 1 : assert_eq!(scheduler.get_az_for_new_tenant(), Some(az_b_tag.clone()));
1263 :
1264 : // Total home shard count is higher in AZ B, so we revert to preferring AZ A
1265 1 : set_shard_count(&mut scheduler, NodeId(4), 6);
1266 1 : set_shard_count(&mut scheduler, NodeId(5), 6);
1267 1 : assert_eq!(scheduler.get_az_for_new_tenant(), Some(az_a_tag.clone()));
1268 1 : }
1269 :
1270 : /// Test that when selecting AZs for many new tenants, we get the expected balance across nodes
1271 : #[test]
1272 1 : fn az_selection_many() {
1273 1 : let az_a_tag = AvailabilityZone("az-a".to_string());
1274 1 : let az_b_tag = AvailabilityZone("az-b".to_string());
1275 1 : let az_c_tag = AvailabilityZone("az-c".to_string());
1276 1 : let nodes = test_utils::make_test_nodes(
1277 1 : 6,
1278 1 : &[
1279 1 : az_a_tag.clone(),
1280 1 : az_b_tag.clone(),
1281 1 : az_c_tag.clone(),
1282 1 : az_a_tag.clone(),
1283 1 : az_b_tag.clone(),
1284 1 : az_c_tag.clone(),
1285 1 : ],
1286 1 : );
1287 1 :
1288 1 : let mut scheduler = Scheduler::new(nodes.values());
1289 1 :
1290 1 : // We should get 1/6th of these on each node, give or take a few...
1291 1 : let total_tenants = 300;
1292 1 :
1293 1 : // ...where the 'few' is the number of AZs, because the scheduling will sometimes overshoot
1294 1 : // on one AZ before correcting itself. This is because we select the 'home' AZ based on
1295 1 : // an AZ-wide metric, but we select the location for secondaries on a purely node-based
1296 1 : // metric (while excluding the home AZ).
1297 1 : let grace = 3;
1298 1 :
1299 1 : let mut scheduled_shards = Vec::new();
1300 300 : for _i in 0..total_tenants {
1301 300 : let preferred_az = scheduler.get_az_for_new_tenant().unwrap();
1302 300 :
1303 300 : let mut node_home_counts = scheduler
1304 300 : .nodes
1305 300 : .iter()
1306 1800 : .map(|(node_id, node)| (node_id, node.home_shard_count))
1307 300 : .collect::<Vec<_>>();
1308 3600 : node_home_counts.sort_by_key(|i| i.0);
1309 300 : eprintln!("Selected {}, vs nodes {:?}", preferred_az, node_home_counts);
1310 300 :
1311 300 : let tenant_shard_id = TenantShardId {
1312 300 : tenant_id: TenantId::generate(),
1313 300 : shard_number: ShardNumber(0),
1314 300 : shard_count: ShardCount(1),
1315 300 : };
1316 300 :
1317 300 : let shard_identity = ShardIdentity::new(
1318 300 : tenant_shard_id.shard_number,
1319 300 : tenant_shard_id.shard_count,
1320 300 : pageserver_api::shard::ShardStripeSize(1),
1321 300 : )
1322 300 : .unwrap();
1323 300 : let mut shard = TenantShard::new(
1324 300 : tenant_shard_id,
1325 300 : shard_identity,
1326 300 : pageserver_api::controller_api::PlacementPolicy::Attached(1),
1327 300 : Some(preferred_az),
1328 300 : );
1329 300 :
1330 300 : let mut context = ScheduleContext::default();
1331 300 : shard.schedule(&mut scheduler, &mut context).unwrap();
1332 300 : eprintln!("Scheduled shard at {:?}", shard.intent);
1333 300 :
1334 300 : scheduled_shards.push(shard);
1335 300 : }
1336 :
1337 7 : for (node_id, node) in &scheduler.nodes {
1338 6 : eprintln!(
1339 6 : "Node {}: {} {} {}",
1340 6 : node_id, node.shard_count, node.attached_shard_count, node.home_shard_count
1341 6 : );
1342 6 : }
1343 :
1344 6 : for node in scheduler.nodes.values() {
1345 6 : assert!((node.home_shard_count as i64 - total_tenants as i64 / 6).abs() < grace);
1346 : }
1347 :
1348 301 : for mut shard in scheduled_shards {
1349 300 : shard.intent.clear(&mut scheduler);
1350 300 : }
1351 1 : }
1352 :
1353 : #[test]
1354 : /// Make sure that when we have an odd number of nodes and an even number of shards, we still
1355 : /// get scheduling stability.
1356 1 : fn odd_nodes_stability() {
1357 1 : let az_a = AvailabilityZone("az-a".to_string());
1358 1 : let az_b = AvailabilityZone("az-b".to_string());
1359 1 :
1360 1 : let nodes = test_utils::make_test_nodes(
1361 1 : 10,
1362 1 : &[
1363 1 : az_a.clone(),
1364 1 : az_a.clone(),
1365 1 : az_a.clone(),
1366 1 : az_a.clone(),
1367 1 : az_a.clone(),
1368 1 : az_b.clone(),
1369 1 : az_b.clone(),
1370 1 : az_b.clone(),
1371 1 : az_b.clone(),
1372 1 : az_b.clone(),
1373 1 : ],
1374 1 : );
1375 1 : let mut scheduler = Scheduler::new(nodes.values());
1376 1 :
1377 1 : // Need to keep these alive because they contribute to shard counts via RAII
1378 1 : let mut scheduled_shards = Vec::new();
1379 1 :
1380 1 : let mut context = ScheduleContext::default();
1381 :
1382 8 : fn schedule_shard(
1383 8 : tenant_shard_id: TenantShardId,
1384 8 : expect_attached: NodeId,
1385 8 : expect_secondary: NodeId,
1386 8 : scheduled_shards: &mut Vec<TenantShard>,
1387 8 : scheduler: &mut Scheduler,
1388 8 : preferred_az: Option<AvailabilityZone>,
1389 8 : context: &mut ScheduleContext,
1390 8 : ) {
1391 8 : let shard_identity = ShardIdentity::new(
1392 8 : tenant_shard_id.shard_number,
1393 8 : tenant_shard_id.shard_count,
1394 8 : pageserver_api::shard::ShardStripeSize(1),
1395 8 : )
1396 8 : .unwrap();
1397 8 : let mut shard = TenantShard::new(
1398 8 : tenant_shard_id,
1399 8 : shard_identity,
1400 8 : pageserver_api::controller_api::PlacementPolicy::Attached(1),
1401 8 : preferred_az,
1402 8 : );
1403 8 :
1404 8 : shard.schedule(scheduler, context).unwrap();
1405 8 :
1406 8 : assert_eq!(shard.intent.get_attached().unwrap(), expect_attached);
1407 8 : assert_eq!(
1408 8 : shard.intent.get_secondary().first().unwrap(),
1409 8 : &expect_secondary
1410 8 : );
1411 :
1412 8 : scheduled_shards.push(shard);
1413 8 : }
1414 :
1415 1 : let tenant_id = TenantId::generate();
1416 1 :
1417 1 : schedule_shard(
1418 1 : TenantShardId {
1419 1 : tenant_id,
1420 1 : shard_number: ShardNumber(0),
1421 1 : shard_count: ShardCount(8),
1422 1 : },
1423 1 : NodeId(1),
1424 1 : NodeId(6),
1425 1 : &mut scheduled_shards,
1426 1 : &mut scheduler,
1427 1 : Some(az_a.clone()),
1428 1 : &mut context,
1429 1 : );
1430 1 :
1431 1 : schedule_shard(
1432 1 : TenantShardId {
1433 1 : tenant_id,
1434 1 : shard_number: ShardNumber(1),
1435 1 : shard_count: ShardCount(8),
1436 1 : },
1437 1 : NodeId(2),
1438 1 : NodeId(7),
1439 1 : &mut scheduled_shards,
1440 1 : &mut scheduler,
1441 1 : Some(az_a.clone()),
1442 1 : &mut context,
1443 1 : );
1444 1 :
1445 1 : schedule_shard(
1446 1 : TenantShardId {
1447 1 : tenant_id,
1448 1 : shard_number: ShardNumber(2),
1449 1 : shard_count: ShardCount(8),
1450 1 : },
1451 1 : NodeId(3),
1452 1 : NodeId(8),
1453 1 : &mut scheduled_shards,
1454 1 : &mut scheduler,
1455 1 : Some(az_a.clone()),
1456 1 : &mut context,
1457 1 : );
1458 1 :
1459 1 : schedule_shard(
1460 1 : TenantShardId {
1461 1 : tenant_id,
1462 1 : shard_number: ShardNumber(3),
1463 1 : shard_count: ShardCount(8),
1464 1 : },
1465 1 : NodeId(4),
1466 1 : NodeId(9),
1467 1 : &mut scheduled_shards,
1468 1 : &mut scheduler,
1469 1 : Some(az_a.clone()),
1470 1 : &mut context,
1471 1 : );
1472 1 :
1473 1 : schedule_shard(
1474 1 : TenantShardId {
1475 1 : tenant_id,
1476 1 : shard_number: ShardNumber(4),
1477 1 : shard_count: ShardCount(8),
1478 1 : },
1479 1 : NodeId(5),
1480 1 : NodeId(10),
1481 1 : &mut scheduled_shards,
1482 1 : &mut scheduler,
1483 1 : Some(az_a.clone()),
1484 1 : &mut context,
1485 1 : );
1486 1 :
1487 1 : schedule_shard(
1488 1 : TenantShardId {
1489 1 : tenant_id,
1490 1 : shard_number: ShardNumber(5),
1491 1 : shard_count: ShardCount(8),
1492 1 : },
1493 1 : NodeId(1),
1494 1 : NodeId(6),
1495 1 : &mut scheduled_shards,
1496 1 : &mut scheduler,
1497 1 : Some(az_a.clone()),
1498 1 : &mut context,
1499 1 : );
1500 1 :
1501 1 : schedule_shard(
1502 1 : TenantShardId {
1503 1 : tenant_id,
1504 1 : shard_number: ShardNumber(6),
1505 1 : shard_count: ShardCount(8),
1506 1 : },
1507 1 : NodeId(2),
1508 1 : NodeId(7),
1509 1 : &mut scheduled_shards,
1510 1 : &mut scheduler,
1511 1 : Some(az_a.clone()),
1512 1 : &mut context,
1513 1 : );
1514 1 :
1515 1 : schedule_shard(
1516 1 : TenantShardId {
1517 1 : tenant_id,
1518 1 : shard_number: ShardNumber(7),
1519 1 : shard_count: ShardCount(8),
1520 1 : },
1521 1 : NodeId(3),
1522 1 : NodeId(8),
1523 1 : &mut scheduled_shards,
1524 1 : &mut scheduler,
1525 1 : Some(az_a.clone()),
1526 1 : &mut context,
1527 1 : );
1528 :
1529 : // Assert that the optimizer suggests nochanges, i.e. our initial scheduling was stable.
1530 9 : for shard in &scheduled_shards {
1531 8 : assert_eq!(shard.optimize_attachment(&mut scheduler, &context), None);
1532 : }
1533 :
1534 9 : for mut shard in scheduled_shards {
1535 8 : shard.intent.clear(&mut scheduler);
1536 8 : }
1537 1 : }
1538 : }
|