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