Line data Source code
1 : use std::str::FromStr;
2 : use std::time::Duration;
3 :
4 : use pageserver_api::controller_api::{
5 : AvailabilityZone, NodeAvailability, NodeDescribeResponse, NodeLifecycle, NodeRegisterRequest,
6 : NodeSchedulingPolicy, TenantLocateResponseShard,
7 : };
8 : use pageserver_api::shard::TenantShardId;
9 : use pageserver_client::mgmt_api;
10 : use reqwest::StatusCode;
11 : use serde::Serialize;
12 : use tokio_util::sync::CancellationToken;
13 : use utils::backoff;
14 : use utils::id::NodeId;
15 :
16 : use crate::pageserver_client::PageserverClient;
17 : use crate::persistence::NodePersistence;
18 : use crate::scheduler::MaySchedule;
19 :
20 : /// Represents the in-memory description of a Node.
21 : ///
22 : /// Scheduling statistics are maintened separately in [`crate::scheduler`].
23 : ///
24 : /// The persistent subset of the Node is defined in [`crate::persistence::NodePersistence`]: the
25 : /// implementation of serialization on this type is only for debug dumps.
26 : #[derive(Clone, Serialize)]
27 : pub(crate) struct Node {
28 : id: NodeId,
29 :
30 : availability: NodeAvailability,
31 : scheduling: NodeSchedulingPolicy,
32 : lifecycle: NodeLifecycle,
33 :
34 : listen_http_addr: String,
35 : listen_http_port: u16,
36 : listen_https_port: Option<u16>,
37 :
38 : listen_pg_addr: String,
39 : listen_pg_port: u16,
40 :
41 : availability_zone_id: AvailabilityZone,
42 :
43 : // Flag from storcon's config to use https for pageserver admin API.
44 : // Invariant: if |true|, listen_https_port should contain a value.
45 : use_https: bool,
46 : // This cancellation token means "stop any RPCs in flight to this node, and don't start
47 : // any more". It is not related to process shutdown.
48 : #[serde(skip)]
49 : cancel: CancellationToken,
50 : }
51 :
52 : /// When updating [`Node::availability`] we use this type to indicate to the caller
53 : /// whether/how they changed it.
54 : pub(crate) enum AvailabilityTransition {
55 : ToActive,
56 : ToWarmingUpFromActive,
57 : ToWarmingUpFromOffline,
58 : ToOffline,
59 : Unchanged,
60 : }
61 :
62 : impl Node {
63 0 : pub(crate) fn base_url(&self) -> String {
64 0 : if self.use_https {
65 0 : format!(
66 0 : "https://{}:{}",
67 0 : self.listen_http_addr,
68 0 : self.listen_https_port
69 0 : .expect("https port should be specified if use_https is on")
70 0 : )
71 : } else {
72 0 : format!("http://{}:{}", self.listen_http_addr, self.listen_http_port)
73 : }
74 0 : }
75 :
76 285 : pub(crate) fn get_id(&self) -> NodeId {
77 285 : self.id
78 285 : }
79 :
80 : #[allow(unused)]
81 25481 : pub(crate) fn get_availability_zone_id(&self) -> &AvailabilityZone {
82 25481 : &self.availability_zone_id
83 25481 : }
84 :
85 0 : pub(crate) fn get_scheduling(&self) -> NodeSchedulingPolicy {
86 0 : self.scheduling
87 0 : }
88 :
89 0 : pub(crate) fn set_scheduling(&mut self, scheduling: NodeSchedulingPolicy) {
90 0 : self.scheduling = scheduling
91 0 : }
92 :
93 0 : pub(crate) fn has_https_port(&self) -> bool {
94 0 : self.listen_https_port.is_some()
95 0 : }
96 :
97 : /// Does this registration request match `self`? This is used when deciding whether a registration
98 : /// request should be allowed to update an existing record with the same node ID.
99 0 : pub(crate) fn registration_match(&self, register_req: &NodeRegisterRequest) -> bool {
100 0 : self.id == register_req.node_id
101 0 : && self.listen_http_addr == register_req.listen_http_addr
102 0 : && self.listen_http_port == register_req.listen_http_port
103 : // Note: listen_https_port may change. See [`Self::need_update`] for mode details.
104 : // && self.listen_https_port == register_req.listen_https_port
105 0 : && self.listen_pg_addr == register_req.listen_pg_addr
106 0 : && self.listen_pg_port == register_req.listen_pg_port
107 0 : && self.availability_zone_id == register_req.availability_zone_id
108 0 : }
109 :
110 : // Do we need to update an existing record in DB on this registration request?
111 0 : pub(crate) fn need_update(&self, register_req: &NodeRegisterRequest) -> bool {
112 0 : // listen_https_port is checked here because it may change during migration to https.
113 0 : // After migration, this check may be moved to registration_match.
114 0 : self.listen_https_port != register_req.listen_https_port
115 0 : }
116 :
117 : /// For a shard located on this node, populate a response object
118 : /// with this node's address information.
119 0 : pub(crate) fn shard_location(&self, shard_id: TenantShardId) -> TenantLocateResponseShard {
120 0 : TenantLocateResponseShard {
121 0 : shard_id,
122 0 : node_id: self.id,
123 0 : listen_http_addr: self.listen_http_addr.clone(),
124 0 : listen_http_port: self.listen_http_port,
125 0 : listen_https_port: self.listen_https_port,
126 0 : listen_pg_addr: self.listen_pg_addr.clone(),
127 0 : listen_pg_port: self.listen_pg_port,
128 0 : }
129 0 : }
130 :
131 0 : pub(crate) fn get_availability(&self) -> &NodeAvailability {
132 0 : &self.availability
133 0 : }
134 :
135 282 : pub(crate) fn set_availability(&mut self, availability: NodeAvailability) {
136 : use AvailabilityTransition::*;
137 : use NodeAvailability::WarmingUp;
138 :
139 282 : match self.get_availability_transition(&availability) {
140 278 : ToActive => {
141 278 : // Give the node a new cancellation token, effectively resetting it to un-cancelled. Any
142 278 : // users of previously-cloned copies of the node will still see the old cancellation
143 278 : // state. For example, Reconcilers in flight will have to complete and be spawned
144 278 : // again to realize that the node has become available.
145 278 : self.cancel = CancellationToken::new();
146 278 : }
147 2 : ToOffline | ToWarmingUpFromActive => {
148 2 : // Fire the node's cancellation token to cancel any in-flight API requests to it
149 2 : self.cancel.cancel();
150 2 : }
151 2 : Unchanged | ToWarmingUpFromOffline => {}
152 : }
153 :
154 282 : if let (WarmingUp(crnt), WarmingUp(proposed)) = (&self.availability, &availability) {
155 0 : self.availability = WarmingUp(std::cmp::max(*crnt, *proposed));
156 282 : } else {
157 282 : self.availability = availability;
158 282 : }
159 282 : }
160 :
161 : /// Without modifying the availability of the node, convert the intended availability
162 : /// into a description of the transition.
163 282 : pub(crate) fn get_availability_transition(
164 282 : &self,
165 282 : availability: &NodeAvailability,
166 282 : ) -> AvailabilityTransition {
167 : use AvailabilityTransition::*;
168 : use NodeAvailability::*;
169 :
170 282 : match (&self.availability, availability) {
171 278 : (Offline, Active(_)) => ToActive,
172 2 : (Active(_), Offline) => ToOffline,
173 0 : (Active(_), WarmingUp(_)) => ToWarmingUpFromActive,
174 0 : (WarmingUp(_), Offline) => ToOffline,
175 0 : (WarmingUp(_), Active(_)) => ToActive,
176 0 : (Offline, WarmingUp(_)) => ToWarmingUpFromOffline,
177 2 : _ => Unchanged,
178 : }
179 282 : }
180 :
181 : /// Whether we may send API requests to this node.
182 278 : pub(crate) fn is_available(&self) -> bool {
183 : // When we clone a node, [`Self::availability`] is a snapshot, but [`Self::cancel`] holds
184 : // a reference to the original Node's cancellation status. Checking both of these results
185 : // in a "pessimistic" check where we will consider a Node instance unavailable if it was unavailable
186 : // when we cloned it, or if the original Node instance's cancellation token was fired.
187 278 : matches!(self.availability, NodeAvailability::Active(_)) && !self.cancel.is_cancelled()
188 278 : }
189 :
190 : /// Is this node elegible to have work scheduled onto it?
191 285 : pub(crate) fn may_schedule(&self) -> MaySchedule {
192 285 : let utilization = match &self.availability {
193 283 : NodeAvailability::Active(u) => u.clone(),
194 2 : NodeAvailability::Offline | NodeAvailability::WarmingUp(_) => return MaySchedule::No,
195 : };
196 :
197 283 : match self.scheduling {
198 283 : NodeSchedulingPolicy::Active => MaySchedule::Yes(utilization),
199 0 : NodeSchedulingPolicy::Draining => MaySchedule::No,
200 0 : NodeSchedulingPolicy::Filling => MaySchedule::Yes(utilization),
201 0 : NodeSchedulingPolicy::Pause => MaySchedule::No,
202 0 : NodeSchedulingPolicy::PauseForRestart => MaySchedule::No,
203 : }
204 285 : }
205 :
206 : #[allow(clippy::too_many_arguments)]
207 278 : pub(crate) fn new(
208 278 : id: NodeId,
209 278 : listen_http_addr: String,
210 278 : listen_http_port: u16,
211 278 : listen_https_port: Option<u16>,
212 278 : listen_pg_addr: String,
213 278 : listen_pg_port: u16,
214 278 : availability_zone_id: AvailabilityZone,
215 278 : use_https: bool,
216 278 : ) -> anyhow::Result<Self> {
217 278 : if use_https && listen_https_port.is_none() {
218 0 : anyhow::bail!(
219 0 : "cannot create node {id}: \
220 0 : https is enabled, but https port is not specified"
221 0 : );
222 278 : }
223 278 :
224 278 : Ok(Self {
225 278 : id,
226 278 : listen_http_addr,
227 278 : listen_http_port,
228 278 : listen_https_port,
229 278 : listen_pg_addr,
230 278 : listen_pg_port,
231 278 : scheduling: NodeSchedulingPolicy::Active,
232 278 : lifecycle: NodeLifecycle::Active,
233 278 : availability: NodeAvailability::Offline,
234 278 : availability_zone_id,
235 278 : use_https,
236 278 : cancel: CancellationToken::new(),
237 278 : })
238 278 : }
239 :
240 0 : pub(crate) fn to_persistent(&self) -> NodePersistence {
241 0 : NodePersistence {
242 0 : node_id: self.id.0 as i64,
243 0 : scheduling_policy: self.scheduling.into(),
244 0 : lifecycle: self.lifecycle.into(),
245 0 : listen_http_addr: self.listen_http_addr.clone(),
246 0 : listen_http_port: self.listen_http_port as i32,
247 0 : listen_https_port: self.listen_https_port.map(|x| x as i32),
248 0 : listen_pg_addr: self.listen_pg_addr.clone(),
249 0 : listen_pg_port: self.listen_pg_port as i32,
250 0 : availability_zone_id: self.availability_zone_id.0.clone(),
251 0 : }
252 0 : }
253 :
254 0 : pub(crate) fn from_persistent(np: NodePersistence, use_https: bool) -> anyhow::Result<Self> {
255 0 : if use_https && np.listen_https_port.is_none() {
256 0 : anyhow::bail!(
257 0 : "cannot load node {} from persistent: \
258 0 : https is enabled, but https port is not specified",
259 0 : np.node_id,
260 0 : );
261 0 : }
262 0 :
263 0 : Ok(Self {
264 0 : id: NodeId(np.node_id as u64),
265 0 : // At startup we consider a node offline until proven otherwise.
266 0 : availability: NodeAvailability::Offline,
267 0 : scheduling: NodeSchedulingPolicy::from_str(&np.scheduling_policy)
268 0 : .expect("Bad scheduling policy in DB"),
269 0 : lifecycle: NodeLifecycle::from_str(&np.lifecycle).expect("Bad lifecycle in DB"),
270 0 : listen_http_addr: np.listen_http_addr,
271 0 : listen_http_port: np.listen_http_port as u16,
272 0 : listen_https_port: np.listen_https_port.map(|x| x as u16),
273 0 : listen_pg_addr: np.listen_pg_addr,
274 0 : listen_pg_port: np.listen_pg_port as u16,
275 0 : availability_zone_id: AvailabilityZone(np.availability_zone_id),
276 0 : use_https,
277 0 : cancel: CancellationToken::new(),
278 0 : })
279 0 : }
280 :
281 : /// Wrapper for issuing requests to pageserver management API: takes care of generic
282 : /// retry/backoff for retryable HTTP status codes.
283 : ///
284 : /// This will return None to indicate cancellation. Cancellation may happen from
285 : /// the cancellation token passed in, or from Self's cancellation token (i.e. node
286 : /// going offline).
287 : #[allow(clippy::too_many_arguments)]
288 0 : pub(crate) async fn with_client_retries<T, O, F>(
289 0 : &self,
290 0 : mut op: O,
291 0 : http_client: &reqwest::Client,
292 0 : jwt: &Option<String>,
293 0 : warn_threshold: u32,
294 0 : max_retries: u32,
295 0 : timeout: Duration,
296 0 : cancel: &CancellationToken,
297 0 : ) -> Option<mgmt_api::Result<T>>
298 0 : where
299 0 : O: FnMut(PageserverClient) -> F,
300 0 : F: std::future::Future<Output = mgmt_api::Result<T>>,
301 0 : {
302 0 : fn is_fatal(e: &mgmt_api::Error) -> bool {
303 : use mgmt_api::Error::*;
304 0 : match e {
305 0 : SendRequest(_) | ReceiveBody(_) | ReceiveErrorBody(_) => false,
306 : ApiError(StatusCode::SERVICE_UNAVAILABLE, _)
307 : | ApiError(StatusCode::GATEWAY_TIMEOUT, _)
308 0 : | ApiError(StatusCode::REQUEST_TIMEOUT, _) => false,
309 0 : ApiError(_, _) => true,
310 0 : Cancelled => true,
311 0 : Timeout(_) => false,
312 : }
313 0 : }
314 :
315 0 : backoff::retry(
316 0 : || {
317 0 : let client = PageserverClient::new(
318 0 : self.get_id(),
319 0 : http_client.clone(),
320 0 : self.base_url(),
321 0 : jwt.as_deref(),
322 0 : );
323 0 :
324 0 : let node_cancel_fut = self.cancel.cancelled();
325 0 :
326 0 : let op_fut = tokio::time::timeout(timeout, op(client));
327 :
328 0 : async {
329 0 : tokio::select! {
330 0 : r = op_fut => match r {
331 0 : Ok(r) => r,
332 0 : Err(e) => Err(mgmt_api::Error::Timeout(format!("{e}"))),
333 : },
334 0 : _ = node_cancel_fut => {
335 0 : Err(mgmt_api::Error::Cancelled)
336 : }}
337 0 : }
338 0 : },
339 0 : is_fatal,
340 0 : warn_threshold,
341 0 : max_retries,
342 0 : &format!(
343 0 : "Call to node {} ({}) management API",
344 0 : self.id,
345 0 : self.base_url(),
346 0 : ),
347 0 : cancel,
348 0 : )
349 0 : .await
350 0 : }
351 :
352 : /// Generate the simplified API-friendly description of a node's state
353 0 : pub(crate) fn describe(&self) -> NodeDescribeResponse {
354 0 : NodeDescribeResponse {
355 0 : id: self.id,
356 0 : availability: self.availability.clone().into(),
357 0 : scheduling: self.scheduling,
358 0 : availability_zone_id: self.availability_zone_id.0.clone(),
359 0 : listen_http_addr: self.listen_http_addr.clone(),
360 0 : listen_http_port: self.listen_http_port,
361 0 : listen_https_port: self.listen_https_port,
362 0 : listen_pg_addr: self.listen_pg_addr.clone(),
363 0 : listen_pg_port: self.listen_pg_port,
364 0 : }
365 0 : }
366 : }
367 :
368 : impl std::fmt::Display for Node {
369 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
370 0 : write!(f, "{} ({})", self.id, self.listen_http_addr)
371 0 : }
372 : }
373 :
374 : impl std::fmt::Debug for Node {
375 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
376 0 : write!(f, "{} ({})", self.id, self.listen_http_addr)
377 0 : }
378 : }
|