Line data Source code
1 : pub mod detach_ancestor;
2 : pub mod partitioning;
3 : pub mod utilization;
4 :
5 : pub use utilization::PageserverUtilization;
6 :
7 : use std::{
8 : collections::HashMap,
9 : io::{BufRead, Read},
10 : num::{NonZeroU32, NonZeroU64, NonZeroUsize},
11 : str::FromStr,
12 : sync::atomic::AtomicUsize,
13 : time::{Duration, SystemTime},
14 : };
15 :
16 : use byteorder::{BigEndian, ReadBytesExt};
17 : use postgres_ffi::BLCKSZ;
18 : use serde::{Deserialize, Serialize};
19 : use serde_with::serde_as;
20 : use utils::{
21 : completion,
22 : id::{NodeId, TenantId, TimelineId},
23 : lsn::Lsn,
24 : serde_system_time,
25 : };
26 :
27 : use crate::{
28 : reltag::RelTag,
29 : shard::{ShardCount, ShardStripeSize, TenantShardId},
30 : };
31 : use anyhow::bail;
32 : use bytes::{Buf, BufMut, Bytes, BytesMut};
33 :
34 : /// The state of a tenant in this pageserver.
35 : ///
36 : /// ```mermaid
37 : /// stateDiagram-v2
38 : ///
39 : /// [*] --> Loading: spawn_load()
40 : /// [*] --> Attaching: spawn_attach()
41 : ///
42 : /// Loading --> Activating: activate()
43 : /// Attaching --> Activating: activate()
44 : /// Activating --> Active: infallible
45 : ///
46 : /// Loading --> Broken: load() failure
47 : /// Attaching --> Broken: attach() failure
48 : ///
49 : /// Active --> Stopping: set_stopping(), part of shutdown & detach
50 : /// Stopping --> Broken: late error in remove_tenant_from_memory
51 : ///
52 : /// Broken --> [*]: ignore / detach / shutdown
53 : /// Stopping --> [*]: remove_from_memory complete
54 : ///
55 : /// Active --> Broken: cfg(testing)-only tenant break point
56 : /// ```
57 : #[derive(
58 : Clone,
59 : PartialEq,
60 : Eq,
61 1 : serde::Serialize,
62 6 : serde::Deserialize,
63 0 : strum_macros::Display,
64 : strum_macros::EnumVariantNames,
65 0 : strum_macros::AsRefStr,
66 1129 : strum_macros::IntoStaticStr,
67 : )]
68 : #[serde(tag = "slug", content = "data")]
69 : pub enum TenantState {
70 : /// This tenant is being loaded from local disk.
71 : ///
72 : /// `set_stopping()` and `set_broken()` do not work in this state and wait for it to pass.
73 : Loading,
74 : /// This tenant is being attached to the pageserver.
75 : ///
76 : /// `set_stopping()` and `set_broken()` do not work in this state and wait for it to pass.
77 : Attaching,
78 : /// The tenant is transitioning from Loading/Attaching to Active.
79 : ///
80 : /// While in this state, the individual timelines are being activated.
81 : ///
82 : /// `set_stopping()` and `set_broken()` do not work in this state and wait for it to pass.
83 : Activating(ActivatingFrom),
84 : /// The tenant has finished activating and is open for business.
85 : ///
86 : /// Transitions out of this state are possible through `set_stopping()` and `set_broken()`.
87 : Active,
88 : /// The tenant is recognized by pageserver, but it is being detached or the
89 : /// system is being shut down.
90 : ///
91 : /// Transitions out of this state are possible through `set_broken()`.
92 : Stopping {
93 : // Because of https://github.com/serde-rs/serde/issues/2105 this has to be a named field,
94 : // otherwise it will not be skipped during deserialization
95 : #[serde(skip)]
96 : progress: completion::Barrier,
97 : },
98 : /// The tenant is recognized by the pageserver, but can no longer be used for
99 : /// any operations.
100 : ///
101 : /// If the tenant fails to load or attach, it will transition to this state
102 : /// and it is guaranteed that no background tasks are running in its name.
103 : ///
104 : /// The other way to transition into this state is from `Stopping` state
105 : /// through `set_broken()` called from `remove_tenant_from_memory()`. That happens
106 : /// if the cleanup future executed by `remove_tenant_from_memory()` fails.
107 : Broken { reason: String, backtrace: String },
108 : }
109 :
110 : impl TenantState {
111 0 : pub fn attachment_status(&self) -> TenantAttachmentStatus {
112 : use TenantAttachmentStatus::*;
113 :
114 : // Below TenantState::Activating is used as "transient" or "transparent" state for
115 : // attachment_status determining.
116 0 : match self {
117 : // The attach procedure writes the marker file before adding the Attaching tenant to the tenants map.
118 : // So, technically, we can return Attached here.
119 : // However, as soon as Console observes Attached, it will proceed with the Postgres-level health check.
120 : // But, our attach task might still be fetching the remote timelines, etc.
121 : // So, return `Maybe` while Attaching, making Console wait for the attach task to finish.
122 0 : Self::Attaching | Self::Activating(ActivatingFrom::Attaching) => Maybe,
123 : // tenant mgr startup distinguishes attaching from loading via marker file.
124 0 : Self::Loading | Self::Activating(ActivatingFrom::Loading) => Attached,
125 : // We only reach Active after successful load / attach.
126 : // So, call atttachment status Attached.
127 0 : Self::Active => Attached,
128 : // If the (initial or resumed) attach procedure fails, the tenant becomes Broken.
129 : // However, it also becomes Broken if the regular load fails.
130 : // From Console's perspective there's no practical difference
131 : // because attachment_status is polled by console only during attach operation execution.
132 0 : Self::Broken { reason, .. } => Failed {
133 0 : reason: reason.to_owned(),
134 0 : },
135 : // Why is Stopping a Maybe case? Because, during pageserver shutdown,
136 : // we set the Stopping state irrespective of whether the tenant
137 : // has finished attaching or not.
138 0 : Self::Stopping { .. } => Maybe,
139 : }
140 0 : }
141 :
142 0 : pub fn broken_from_reason(reason: String) -> Self {
143 0 : let backtrace_str: String = format!("{}", std::backtrace::Backtrace::force_capture());
144 0 : Self::Broken {
145 0 : reason,
146 0 : backtrace: backtrace_str,
147 0 : }
148 0 : }
149 : }
150 :
151 : impl std::fmt::Debug for TenantState {
152 2 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153 2 : match self {
154 2 : Self::Broken { reason, backtrace } if !reason.is_empty() => {
155 2 : write!(f, "Broken due to: {reason}. Backtrace:\n{backtrace}")
156 : }
157 0 : _ => write!(f, "{self}"),
158 : }
159 2 : }
160 : }
161 :
162 : /// A temporary lease to a specific lsn inside a timeline.
163 : /// Access to the lsn is guaranteed by the pageserver until the expiration indicated by `valid_until`.
164 : #[serde_as]
165 0 : #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
166 : pub struct LsnLease {
167 : #[serde_as(as = "SystemTimeAsRfc3339Millis")]
168 : pub valid_until: SystemTime,
169 : }
170 :
171 : serde_with::serde_conv!(
172 : SystemTimeAsRfc3339Millis,
173 : SystemTime,
174 0 : |time: &SystemTime| humantime::format_rfc3339_millis(*time).to_string(),
175 0 : |value: String| -> Result<_, humantime::TimestampError> { humantime::parse_rfc3339(&value) }
176 : );
177 :
178 : impl LsnLease {
179 : /// The default length for an explicit LSN lease request (10 minutes).
180 : pub const DEFAULT_LENGTH: Duration = Duration::from_secs(10 * 60);
181 :
182 : /// The default length for an implicit LSN lease granted during
183 : /// `get_lsn_by_timestamp` request (1 minutes).
184 : pub const DEFAULT_LENGTH_FOR_TS: Duration = Duration::from_secs(60);
185 :
186 : /// Checks whether the lease is expired.
187 18 : pub fn is_expired(&self, now: &SystemTime) -> bool {
188 18 : now > &self.valid_until
189 18 : }
190 : }
191 :
192 : /// The only [`TenantState`] variants we could be `TenantState::Activating` from.
193 4 : #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
194 : pub enum ActivatingFrom {
195 : /// Arrived to [`TenantState::Activating`] from [`TenantState::Loading`]
196 : Loading,
197 : /// Arrived to [`TenantState::Activating`] from [`TenantState::Attaching`]
198 : Attaching,
199 : }
200 :
201 : /// A state of a timeline in pageserver's memory.
202 0 : #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
203 : pub enum TimelineState {
204 : /// The timeline is recognized by the pageserver but is not yet operational.
205 : /// In particular, the walreceiver connection loop is not running for this timeline.
206 : /// It will eventually transition to state Active or Broken.
207 : Loading,
208 : /// The timeline is fully operational.
209 : /// It can be queried, and the walreceiver connection loop is running.
210 : Active,
211 : /// The timeline was previously Loading or Active but is shutting down.
212 : /// It cannot transition back into any other state.
213 : Stopping,
214 : /// The timeline is broken and not operational (previous states: Loading or Active).
215 : Broken { reason: String, backtrace: String },
216 : }
217 :
218 0 : #[derive(Serialize, Deserialize, Clone)]
219 : pub struct TimelineCreateRequest {
220 : pub new_timeline_id: TimelineId,
221 : #[serde(default)]
222 : pub ancestor_timeline_id: Option<TimelineId>,
223 : #[serde(default)]
224 : pub existing_initdb_timeline_id: Option<TimelineId>,
225 : #[serde(default)]
226 : pub ancestor_start_lsn: Option<Lsn>,
227 : pub pg_version: Option<u32>,
228 : }
229 :
230 0 : #[derive(Serialize, Deserialize, Clone)]
231 : pub struct LsnLeaseRequest {
232 : pub lsn: Lsn,
233 : }
234 :
235 0 : #[derive(Serialize, Deserialize)]
236 : pub struct TenantShardSplitRequest {
237 : pub new_shard_count: u8,
238 :
239 : // A tenant's stripe size is only meaningful the first time their shard count goes
240 : // above 1: therefore during a split from 1->N shards, we may modify the stripe size.
241 : //
242 : // If this is set while the stripe count is being increased from an already >1 value,
243 : // then the request will fail with 400.
244 : pub new_stripe_size: Option<ShardStripeSize>,
245 : }
246 :
247 0 : #[derive(Serialize, Deserialize)]
248 : pub struct TenantShardSplitResponse {
249 : pub new_shards: Vec<TenantShardId>,
250 : }
251 :
252 : /// Parameters that apply to all shards in a tenant. Used during tenant creation.
253 0 : #[derive(Serialize, Deserialize, Debug)]
254 : #[serde(deny_unknown_fields)]
255 : pub struct ShardParameters {
256 : pub count: ShardCount,
257 : pub stripe_size: ShardStripeSize,
258 : }
259 :
260 : impl ShardParameters {
261 : pub const DEFAULT_STRIPE_SIZE: ShardStripeSize = ShardStripeSize(256 * 1024 / 8);
262 :
263 0 : pub fn is_unsharded(&self) -> bool {
264 0 : self.count.is_unsharded()
265 0 : }
266 : }
267 :
268 : impl Default for ShardParameters {
269 589 : fn default() -> Self {
270 589 : Self {
271 589 : count: ShardCount::new(0),
272 589 : stripe_size: Self::DEFAULT_STRIPE_SIZE,
273 589 : }
274 589 : }
275 : }
276 :
277 : /// An alternative representation of `pageserver::tenant::TenantConf` with
278 : /// simpler types.
279 2 : #[derive(Serialize, Deserialize, Debug, Default, Clone, Eq, PartialEq)]
280 : pub struct TenantConfig {
281 : pub checkpoint_distance: Option<u64>,
282 : pub checkpoint_timeout: Option<String>,
283 : pub compaction_target_size: Option<u64>,
284 : pub compaction_period: Option<String>,
285 : pub compaction_threshold: Option<usize>,
286 : // defer parsing compaction_algorithm, like eviction_policy
287 : pub compaction_algorithm: Option<CompactionAlgorithmSettings>,
288 : pub gc_horizon: Option<u64>,
289 : pub gc_period: Option<String>,
290 : pub image_creation_threshold: Option<usize>,
291 : pub pitr_interval: Option<String>,
292 : pub walreceiver_connect_timeout: Option<String>,
293 : pub lagging_wal_timeout: Option<String>,
294 : pub max_lsn_wal_lag: Option<NonZeroU64>,
295 : pub eviction_policy: Option<EvictionPolicy>,
296 : pub min_resident_size_override: Option<u64>,
297 : pub evictions_low_residence_duration_metric_threshold: Option<String>,
298 : pub heatmap_period: Option<String>,
299 : pub lazy_slru_download: Option<bool>,
300 : pub timeline_get_throttle: Option<ThrottleConfig>,
301 : pub image_layer_creation_check_threshold: Option<u8>,
302 : pub switch_aux_file_policy: Option<AuxFilePolicy>,
303 : pub lsn_lease_length: Option<String>,
304 : pub lsn_lease_length_for_ts: Option<String>,
305 : }
306 :
307 : /// The policy for the aux file storage. It can be switched through `switch_aux_file_policy`
308 : /// tenant config. When the first aux file written, the policy will be persisted in the
309 : /// `index_part.json` file and has a limited migration path.
310 : ///
311 : /// Currently, we only allow the following migration path:
312 : ///
313 : /// Unset -> V1
314 : /// -> V2
315 : /// -> CrossValidation -> V2
316 : #[derive(
317 : Eq,
318 : PartialEq,
319 : Debug,
320 : Copy,
321 : Clone,
322 9 : strum_macros::EnumString,
323 62 : strum_macros::Display,
324 0 : serde_with::DeserializeFromStr,
325 : serde_with::SerializeDisplay,
326 : )]
327 : #[strum(serialize_all = "kebab-case")]
328 : pub enum AuxFilePolicy {
329 : /// V1 aux file policy: store everything in AUX_FILE_KEY
330 : #[strum(ascii_case_insensitive)]
331 : V1,
332 : /// V2 aux file policy: store in the AUX_FILE keyspace
333 : #[strum(ascii_case_insensitive)]
334 : V2,
335 : /// Cross validation runs both formats on the write path and does validation
336 : /// on the read path.
337 : #[strum(ascii_case_insensitive)]
338 : CrossValidation,
339 : }
340 :
341 : impl AuxFilePolicy {
342 102 : pub fn is_valid_migration_path(from: Option<Self>, to: Self) -> bool {
343 62 : matches!(
344 102 : (from, to),
345 : (None, _) | (Some(AuxFilePolicy::CrossValidation), AuxFilePolicy::V2)
346 : )
347 102 : }
348 :
349 : /// If a tenant writes aux files without setting `switch_aux_policy`, this value will be used.
350 1314 : pub fn default_tenant_config() -> Self {
351 1314 : Self::V2
352 1314 : }
353 : }
354 :
355 : /// The aux file policy memory flag. Users can store `Option<AuxFilePolicy>` into this atomic flag. 0 == unspecified.
356 : pub struct AtomicAuxFilePolicy(AtomicUsize);
357 :
358 : impl AtomicAuxFilePolicy {
359 1236 : pub fn new(policy: Option<AuxFilePolicy>) -> Self {
360 1236 : Self(AtomicUsize::new(
361 1236 : policy.map(AuxFilePolicy::to_usize).unwrap_or_default(),
362 1236 : ))
363 1236 : }
364 :
365 924 : pub fn load(&self) -> Option<AuxFilePolicy> {
366 924 : match self.0.load(std::sync::atomic::Ordering::Acquire) {
367 726 : 0 => None,
368 198 : other => Some(AuxFilePolicy::from_usize(other)),
369 : }
370 924 : }
371 :
372 66 : pub fn store(&self, policy: Option<AuxFilePolicy>) {
373 66 : self.0.store(
374 66 : policy.map(AuxFilePolicy::to_usize).unwrap_or_default(),
375 66 : std::sync::atomic::Ordering::Release,
376 66 : );
377 66 : }
378 : }
379 :
380 : impl AuxFilePolicy {
381 60 : pub fn to_usize(self) -> usize {
382 60 : match self {
383 12 : Self::V1 => 1,
384 6 : Self::CrossValidation => 2,
385 42 : Self::V2 => 3,
386 : }
387 60 : }
388 :
389 198 : pub fn try_from_usize(this: usize) -> Option<Self> {
390 198 : match this {
391 12 : 1 => Some(Self::V1),
392 18 : 2 => Some(Self::CrossValidation),
393 168 : 3 => Some(Self::V2),
394 0 : _ => None,
395 : }
396 198 : }
397 :
398 198 : pub fn from_usize(this: usize) -> Self {
399 198 : Self::try_from_usize(this).unwrap()
400 198 : }
401 : }
402 :
403 12 : #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
404 : #[serde(tag = "kind")]
405 : pub enum EvictionPolicy {
406 : NoEviction,
407 : LayerAccessThreshold(EvictionPolicyLayerAccessThreshold),
408 : OnlyImitiate(EvictionPolicyLayerAccessThreshold),
409 : }
410 :
411 : impl EvictionPolicy {
412 0 : pub fn discriminant_str(&self) -> &'static str {
413 0 : match self {
414 0 : EvictionPolicy::NoEviction => "NoEviction",
415 0 : EvictionPolicy::LayerAccessThreshold(_) => "LayerAccessThreshold",
416 0 : EvictionPolicy::OnlyImitiate(_) => "OnlyImitiate",
417 : }
418 0 : }
419 : }
420 :
421 : #[derive(
422 : Eq,
423 : PartialEq,
424 : Debug,
425 : Copy,
426 : Clone,
427 0 : strum_macros::EnumString,
428 0 : strum_macros::Display,
429 0 : serde_with::DeserializeFromStr,
430 : serde_with::SerializeDisplay,
431 : )]
432 : #[strum(serialize_all = "kebab-case")]
433 : pub enum CompactionAlgorithm {
434 : Legacy,
435 : Tiered,
436 : }
437 :
438 0 : #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
439 : pub enum ImageCompressionAlgorithm {
440 : // Disabled for writes, support decompressing during read path
441 : Disabled,
442 : /// Zstandard compression. Level 0 means and None mean the same (default level). Levels can be negative as well.
443 : /// For details, see the [manual](http://facebook.github.io/zstd/zstd_manual.html).
444 : Zstd {
445 : level: Option<i8>,
446 : },
447 : }
448 :
449 : impl FromStr for ImageCompressionAlgorithm {
450 : type Err = anyhow::Error;
451 670 : fn from_str(s: &str) -> Result<Self, Self::Err> {
452 670 : let mut components = s.split(['(', ')']);
453 670 : let first = components
454 670 : .next()
455 670 : .ok_or_else(|| anyhow::anyhow!("empty string"))?;
456 670 : match first {
457 670 : "disabled" => Ok(ImageCompressionAlgorithm::Disabled),
458 669 : "zstd" => {
459 669 : let level = if let Some(v) = components.next() {
460 668 : let v: i8 = v.parse()?;
461 668 : Some(v)
462 : } else {
463 1 : None
464 : };
465 :
466 669 : Ok(ImageCompressionAlgorithm::Zstd { level })
467 : }
468 0 : _ => anyhow::bail!("invalid specifier '{first}'"),
469 : }
470 670 : }
471 : }
472 :
473 0 : #[derive(Eq, PartialEq, Debug, Clone, Serialize, Deserialize)]
474 : pub struct CompactionAlgorithmSettings {
475 : pub kind: CompactionAlgorithm,
476 : }
477 :
478 60 : #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
479 : pub struct EvictionPolicyLayerAccessThreshold {
480 : #[serde(with = "humantime_serde")]
481 : pub period: Duration,
482 : #[serde(with = "humantime_serde")]
483 : pub threshold: Duration,
484 : }
485 :
486 0 : #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
487 : pub struct ThrottleConfig {
488 : pub task_kinds: Vec<String>, // TaskKind
489 : pub initial: u32,
490 : #[serde(with = "humantime_serde")]
491 : pub refill_interval: Duration,
492 : pub refill_amount: NonZeroU32,
493 : pub max: u32,
494 : }
495 :
496 : impl ThrottleConfig {
497 1254 : pub fn disabled() -> Self {
498 1254 : Self {
499 1254 : task_kinds: vec![], // effectively disables the throttle
500 1254 : // other values don't matter with emtpy `task_kinds`.
501 1254 : initial: 0,
502 1254 : refill_interval: Duration::from_millis(1),
503 1254 : refill_amount: NonZeroU32::new(1).unwrap(),
504 1254 : max: 1,
505 1254 : }
506 1254 : }
507 : /// The requests per second allowed by the given config.
508 0 : pub fn steady_rps(&self) -> f64 {
509 0 : (self.refill_amount.get() as f64) / (self.refill_interval.as_secs_f64())
510 0 : }
511 : }
512 :
513 : /// A flattened analog of a `pagesever::tenant::LocationMode`, which
514 : /// lists out all possible states (and the virtual "Detached" state)
515 : /// in a flat form rather than using rust-style enums.
516 0 : #[derive(Serialize, Deserialize, Debug, Clone, Copy, Eq, PartialEq)]
517 : pub enum LocationConfigMode {
518 : AttachedSingle,
519 : AttachedMulti,
520 : AttachedStale,
521 : Secondary,
522 : Detached,
523 : }
524 :
525 0 : #[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
526 : pub struct LocationConfigSecondary {
527 : pub warm: bool,
528 : }
529 :
530 : /// An alternative representation of `pageserver::tenant::LocationConf`,
531 : /// for use in external-facing APIs.
532 0 : #[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
533 : pub struct LocationConfig {
534 : pub mode: LocationConfigMode,
535 : /// If attaching, in what generation?
536 : #[serde(default)]
537 : pub generation: Option<u32>,
538 :
539 : // If requesting mode `Secondary`, configuration for that.
540 : #[serde(default)]
541 : pub secondary_conf: Option<LocationConfigSecondary>,
542 :
543 : // Shard parameters: if shard_count is nonzero, then other shard_* fields
544 : // must be set accurately.
545 : #[serde(default)]
546 : pub shard_number: u8,
547 : #[serde(default)]
548 : pub shard_count: u8,
549 : #[serde(default)]
550 : pub shard_stripe_size: u32,
551 :
552 : // This configuration only affects attached mode, but should be provided irrespective
553 : // of the mode, as a secondary location might transition on startup if the response
554 : // to the `/re-attach` control plane API requests it.
555 : pub tenant_conf: TenantConfig,
556 : }
557 :
558 0 : #[derive(Serialize, Deserialize)]
559 : pub struct LocationConfigListResponse {
560 : pub tenant_shards: Vec<(TenantShardId, Option<LocationConfig>)>,
561 : }
562 :
563 : #[derive(Serialize)]
564 : pub struct StatusResponse {
565 : pub id: NodeId,
566 : }
567 :
568 0 : #[derive(Serialize, Deserialize, Debug)]
569 : #[serde(deny_unknown_fields)]
570 : pub struct TenantLocationConfigRequest {
571 : #[serde(flatten)]
572 : pub config: LocationConfig, // as we have a flattened field, we should reject all unknown fields in it
573 : }
574 :
575 0 : #[derive(Serialize, Deserialize, Debug)]
576 : #[serde(deny_unknown_fields)]
577 : pub struct TenantTimeTravelRequest {
578 : pub shard_counts: Vec<ShardCount>,
579 : }
580 :
581 0 : #[derive(Serialize, Deserialize, Debug)]
582 : #[serde(deny_unknown_fields)]
583 : pub struct TenantShardLocation {
584 : pub shard_id: TenantShardId,
585 : pub node_id: NodeId,
586 : }
587 :
588 0 : #[derive(Serialize, Deserialize, Debug)]
589 : #[serde(deny_unknown_fields)]
590 : pub struct TenantLocationConfigResponse {
591 : pub shards: Vec<TenantShardLocation>,
592 : // If the shards' ShardCount count is >1, stripe_size will be set.
593 : pub stripe_size: Option<ShardStripeSize>,
594 : }
595 :
596 3 : #[derive(Serialize, Deserialize, Debug)]
597 : #[serde(deny_unknown_fields)]
598 : pub struct TenantConfigRequest {
599 : pub tenant_id: TenantId,
600 : #[serde(flatten)]
601 : pub config: TenantConfig, // as we have a flattened field, we should reject all unknown fields in it
602 : }
603 :
604 : impl std::ops::Deref for TenantConfigRequest {
605 : type Target = TenantConfig;
606 :
607 0 : fn deref(&self) -> &Self::Target {
608 0 : &self.config
609 0 : }
610 : }
611 :
612 : impl TenantConfigRequest {
613 0 : pub fn new(tenant_id: TenantId) -> TenantConfigRequest {
614 0 : let config = TenantConfig::default();
615 0 : TenantConfigRequest { tenant_id, config }
616 0 : }
617 : }
618 :
619 : /// See [`TenantState::attachment_status`] and the OpenAPI docs for context.
620 0 : #[derive(Serialize, Deserialize, Clone)]
621 : #[serde(tag = "slug", content = "data", rename_all = "snake_case")]
622 : pub enum TenantAttachmentStatus {
623 : Maybe,
624 : Attached,
625 : Failed { reason: String },
626 : }
627 :
628 0 : #[derive(Serialize, Deserialize, Clone)]
629 : pub struct TenantInfo {
630 : pub id: TenantShardId,
631 : // NB: intentionally not part of OpenAPI, we don't want to commit to a specific set of TenantState's
632 : pub state: TenantState,
633 : /// Sum of the size of all layer files.
634 : /// If a layer is present in both local FS and S3, it counts only once.
635 : pub current_physical_size: Option<u64>, // physical size is only included in `tenant_status` endpoint
636 : pub attachment_status: TenantAttachmentStatus,
637 : pub generation: u32,
638 :
639 : /// Opaque explanation if gc is being blocked.
640 : ///
641 : /// Only looked up for the individual tenant detail, not the listing. This is purely for
642 : /// debugging, not included in openapi.
643 : #[serde(skip_serializing_if = "Option::is_none")]
644 : pub gc_blocking: Option<String>,
645 : }
646 :
647 0 : #[derive(Serialize, Deserialize, Clone)]
648 : pub struct TenantDetails {
649 : #[serde(flatten)]
650 : pub tenant_info: TenantInfo,
651 :
652 : pub walredo: Option<WalRedoManagerStatus>,
653 :
654 : pub timelines: Vec<TimelineId>,
655 : }
656 :
657 0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Copy, Debug)]
658 : pub enum TimelineArchivalState {
659 : Archived,
660 : Unarchived,
661 : }
662 :
663 0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone)]
664 : pub struct TimelineArchivalConfigRequest {
665 : pub state: TimelineArchivalState,
666 : }
667 :
668 : /// This represents the output of the "timeline_detail" and "timeline_list" API calls.
669 0 : #[derive(Debug, Serialize, Deserialize, Clone)]
670 : pub struct TimelineInfo {
671 : pub tenant_id: TenantShardId,
672 : pub timeline_id: TimelineId,
673 :
674 : pub ancestor_timeline_id: Option<TimelineId>,
675 : pub ancestor_lsn: Option<Lsn>,
676 : pub last_record_lsn: Lsn,
677 : pub prev_record_lsn: Option<Lsn>,
678 : pub latest_gc_cutoff_lsn: Lsn,
679 : pub disk_consistent_lsn: Lsn,
680 :
681 : /// The LSN that we have succesfully uploaded to remote storage
682 : pub remote_consistent_lsn: Lsn,
683 :
684 : /// The LSN that we are advertizing to safekeepers
685 : pub remote_consistent_lsn_visible: Lsn,
686 :
687 : /// The LSN from the start of the root timeline (never changes)
688 : pub initdb_lsn: Lsn,
689 :
690 : pub current_logical_size: u64,
691 : pub current_logical_size_is_accurate: bool,
692 :
693 : pub directory_entries_counts: Vec<u64>,
694 :
695 : /// Sum of the size of all layer files.
696 : /// If a layer is present in both local FS and S3, it counts only once.
697 : pub current_physical_size: Option<u64>, // is None when timeline is Unloaded
698 : pub current_logical_size_non_incremental: Option<u64>,
699 :
700 : /// How many bytes of WAL are within this branch's pitr_interval. If the pitr_interval goes
701 : /// beyond the branch's branch point, we only count up to the branch point.
702 : pub pitr_history_size: u64,
703 :
704 : /// Whether this branch's branch point is within its ancestor's PITR interval (i.e. any
705 : /// ancestor data used by this branch would have been retained anyway). If this is false, then
706 : /// this branch may be imposing a cost on the ancestor by causing it to retain layers that it would
707 : /// otherwise be able to GC.
708 : pub within_ancestor_pitr: bool,
709 :
710 : pub timeline_dir_layer_file_size_sum: Option<u64>,
711 :
712 : pub wal_source_connstr: Option<String>,
713 : pub last_received_msg_lsn: Option<Lsn>,
714 : /// the timestamp (in microseconds) of the last received message
715 : pub last_received_msg_ts: Option<u128>,
716 : pub pg_version: u32,
717 :
718 : pub state: TimelineState,
719 : pub is_archived: bool,
720 :
721 : pub walreceiver_status: String,
722 :
723 : /// The last aux file policy being used on this timeline
724 : pub last_aux_file_policy: Option<AuxFilePolicy>,
725 : }
726 :
727 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
728 : pub struct LayerMapInfo {
729 : pub in_memory_layers: Vec<InMemoryLayerInfo>,
730 : pub historic_layers: Vec<HistoricLayerInfo>,
731 : }
732 :
733 : /// The residence status of a layer
734 0 : #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
735 : pub enum LayerResidenceStatus {
736 : /// Residence status for a layer file that exists locally.
737 : /// It may also exist on the remote, we don't care here.
738 : Resident,
739 : /// Residence status for a layer file that only exists on the remote.
740 : Evicted,
741 : }
742 :
743 : #[serde_as]
744 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
745 : pub struct LayerAccessStats {
746 : #[serde_as(as = "serde_with::TimestampMilliSeconds")]
747 : pub access_time: SystemTime,
748 :
749 : #[serde_as(as = "serde_with::TimestampMilliSeconds")]
750 : pub residence_time: SystemTime,
751 :
752 : pub visible: bool,
753 : }
754 :
755 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
756 : #[serde(tag = "kind")]
757 : pub enum InMemoryLayerInfo {
758 : Open { lsn_start: Lsn },
759 : Frozen { lsn_start: Lsn, lsn_end: Lsn },
760 : }
761 :
762 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
763 : #[serde(tag = "kind")]
764 : pub enum HistoricLayerInfo {
765 : Delta {
766 : layer_file_name: String,
767 : layer_file_size: u64,
768 :
769 : lsn_start: Lsn,
770 : lsn_end: Lsn,
771 : remote: bool,
772 : access_stats: LayerAccessStats,
773 :
774 : l0: bool,
775 : },
776 : Image {
777 : layer_file_name: String,
778 : layer_file_size: u64,
779 :
780 : lsn_start: Lsn,
781 : remote: bool,
782 : access_stats: LayerAccessStats,
783 : },
784 : }
785 :
786 : impl HistoricLayerInfo {
787 0 : pub fn layer_file_name(&self) -> &str {
788 0 : match self {
789 : HistoricLayerInfo::Delta {
790 0 : layer_file_name, ..
791 0 : } => layer_file_name,
792 : HistoricLayerInfo::Image {
793 0 : layer_file_name, ..
794 0 : } => layer_file_name,
795 : }
796 0 : }
797 0 : pub fn is_remote(&self) -> bool {
798 0 : match self {
799 0 : HistoricLayerInfo::Delta { remote, .. } => *remote,
800 0 : HistoricLayerInfo::Image { remote, .. } => *remote,
801 : }
802 0 : }
803 0 : pub fn set_remote(&mut self, value: bool) {
804 0 : let field = match self {
805 0 : HistoricLayerInfo::Delta { remote, .. } => remote,
806 0 : HistoricLayerInfo::Image { remote, .. } => remote,
807 : };
808 0 : *field = value;
809 0 : }
810 0 : pub fn layer_file_size(&self) -> u64 {
811 0 : match self {
812 : HistoricLayerInfo::Delta {
813 0 : layer_file_size, ..
814 0 : } => *layer_file_size,
815 : HistoricLayerInfo::Image {
816 0 : layer_file_size, ..
817 0 : } => *layer_file_size,
818 : }
819 0 : }
820 : }
821 :
822 0 : #[derive(Debug, Serialize, Deserialize)]
823 : pub struct DownloadRemoteLayersTaskSpawnRequest {
824 : pub max_concurrent_downloads: NonZeroUsize,
825 : }
826 :
827 0 : #[derive(Debug, Serialize, Deserialize)]
828 : pub struct IngestAuxFilesRequest {
829 : pub aux_files: HashMap<String, String>,
830 : }
831 :
832 0 : #[derive(Debug, Serialize, Deserialize)]
833 : pub struct ListAuxFilesRequest {
834 : pub lsn: Lsn,
835 : }
836 :
837 0 : #[derive(Debug, Serialize, Deserialize, Clone)]
838 : pub struct DownloadRemoteLayersTaskInfo {
839 : pub task_id: String,
840 : pub state: DownloadRemoteLayersTaskState,
841 : pub total_layer_count: u64, // stable once `completed`
842 : pub successful_download_count: u64, // stable once `completed`
843 : pub failed_download_count: u64, // stable once `completed`
844 : }
845 :
846 0 : #[derive(Debug, Serialize, Deserialize, Clone)]
847 : pub enum DownloadRemoteLayersTaskState {
848 : Running,
849 : Completed,
850 : ShutDown,
851 : }
852 :
853 0 : #[derive(Debug, Serialize, Deserialize)]
854 : pub struct TimelineGcRequest {
855 : pub gc_horizon: Option<u64>,
856 : }
857 :
858 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
859 : pub struct WalRedoManagerProcessStatus {
860 : pub pid: u32,
861 : }
862 :
863 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
864 : pub struct WalRedoManagerStatus {
865 : pub last_redo_at: Option<chrono::DateTime<chrono::Utc>>,
866 : pub process: Option<WalRedoManagerProcessStatus>,
867 : }
868 :
869 : /// The progress of a secondary tenant is mostly useful when doing a long running download: e.g. initiating
870 : /// a download job, timing out while waiting for it to run, and then inspecting this status to understand
871 : /// what's happening.
872 0 : #[derive(Default, Debug, Serialize, Deserialize, Clone)]
873 : pub struct SecondaryProgress {
874 : /// The remote storage LastModified time of the heatmap object we last downloaded.
875 : pub heatmap_mtime: Option<serde_system_time::SystemTime>,
876 :
877 : /// The number of layers currently on-disk
878 : pub layers_downloaded: usize,
879 : /// The number of layers in the most recently seen heatmap
880 : pub layers_total: usize,
881 :
882 : /// The number of layer bytes currently on-disk
883 : pub bytes_downloaded: u64,
884 : /// The number of layer bytes in the most recently seen heatmap
885 : pub bytes_total: u64,
886 : }
887 :
888 0 : #[derive(Serialize, Deserialize, Debug)]
889 : pub struct TenantScanRemoteStorageShard {
890 : pub tenant_shard_id: TenantShardId,
891 : pub generation: Option<u32>,
892 : }
893 :
894 0 : #[derive(Serialize, Deserialize, Debug, Default)]
895 : pub struct TenantScanRemoteStorageResponse {
896 : pub shards: Vec<TenantScanRemoteStorageShard>,
897 : }
898 :
899 0 : #[derive(Serialize, Deserialize, Debug, Clone)]
900 : #[serde(rename_all = "snake_case")]
901 : pub enum TenantSorting {
902 : ResidentSize,
903 : MaxLogicalSize,
904 : }
905 :
906 : impl Default for TenantSorting {
907 0 : fn default() -> Self {
908 0 : Self::ResidentSize
909 0 : }
910 : }
911 :
912 0 : #[derive(Serialize, Deserialize, Debug, Clone)]
913 : pub struct TopTenantShardsRequest {
914 : // How would you like to sort the tenants?
915 : pub order_by: TenantSorting,
916 :
917 : // How many results?
918 : pub limit: usize,
919 :
920 : // Omit tenants with more than this many shards (e.g. if this is the max number of shards
921 : // that the caller would ever split to)
922 : pub where_shards_lt: Option<ShardCount>,
923 :
924 : // Omit tenants where the ordering metric is less than this (this is an optimization to
925 : // let us quickly exclude numerous tiny shards)
926 : pub where_gt: Option<u64>,
927 : }
928 :
929 0 : #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
930 : pub struct TopTenantShardItem {
931 : pub id: TenantShardId,
932 :
933 : /// Total size of layers on local disk for all timelines in this tenant
934 : pub resident_size: u64,
935 :
936 : /// Total size of layers in remote storage for all timelines in this tenant
937 : pub physical_size: u64,
938 :
939 : /// The largest logical size of a timeline within this tenant
940 : pub max_logical_size: u64,
941 : }
942 :
943 0 : #[derive(Serialize, Deserialize, Debug, Default)]
944 : pub struct TopTenantShardsResponse {
945 : pub shards: Vec<TopTenantShardItem>,
946 : }
947 :
948 : pub mod virtual_file {
949 : use std::path::PathBuf;
950 :
951 : #[derive(
952 : Copy,
953 : Clone,
954 : PartialEq,
955 : Eq,
956 : Hash,
957 1266 : strum_macros::EnumString,
958 0 : strum_macros::Display,
959 0 : serde_with::DeserializeFromStr,
960 : serde_with::SerializeDisplay,
961 : Debug,
962 : )]
963 : #[strum(serialize_all = "kebab-case")]
964 : pub enum IoEngineKind {
965 : StdFs,
966 : #[cfg(target_os = "linux")]
967 : TokioEpollUring,
968 : }
969 :
970 : /// Direct IO modes for a pageserver.
971 0 : #[derive(Debug, PartialEq, Eq, Clone, serde::Deserialize, serde::Serialize, Default)]
972 : #[serde(tag = "mode", rename_all = "kebab-case", deny_unknown_fields)]
973 : pub enum DirectIoMode {
974 : /// Direct IO disabled (uses usual buffered IO).
975 : #[default]
976 : Disabled,
977 : /// Direct IO disabled (performs checks and perf simulations).
978 : Evaluate {
979 : /// Alignment check level
980 : alignment_check: DirectIoAlignmentCheckLevel,
981 : /// Latency padded for performance simulation.
982 : latency_padding: DirectIoLatencyPadding,
983 : },
984 : /// Direct IO enabled.
985 : Enabled {
986 : /// Actions to perform on alignment error.
987 : on_alignment_error: DirectIoOnAlignmentErrorAction,
988 : },
989 : }
990 :
991 0 : #[derive(Debug, PartialEq, Eq, Clone, serde::Deserialize, serde::Serialize, Default)]
992 : #[serde(rename_all = "kebab-case")]
993 : pub enum DirectIoAlignmentCheckLevel {
994 : #[default]
995 : Error,
996 : Log,
997 : None,
998 : }
999 :
1000 0 : #[derive(Debug, PartialEq, Eq, Clone, serde::Deserialize, serde::Serialize, Default)]
1001 : #[serde(rename_all = "kebab-case")]
1002 : pub enum DirectIoOnAlignmentErrorAction {
1003 : Error,
1004 : #[default]
1005 : FallbackToBuffered,
1006 : }
1007 :
1008 0 : #[derive(Debug, PartialEq, Eq, Clone, serde::Deserialize, serde::Serialize, Default)]
1009 : #[serde(tag = "type", rename_all = "kebab-case")]
1010 : pub enum DirectIoLatencyPadding {
1011 : /// Pad virtual file operations with IO to a fake file.
1012 : FakeFileRW { path: PathBuf },
1013 : #[default]
1014 : None,
1015 : }
1016 : }
1017 :
1018 : // Wrapped in libpq CopyData
1019 : #[derive(PartialEq, Eq, Debug)]
1020 : pub enum PagestreamFeMessage {
1021 : Exists(PagestreamExistsRequest),
1022 : Nblocks(PagestreamNblocksRequest),
1023 : GetPage(PagestreamGetPageRequest),
1024 : DbSize(PagestreamDbSizeRequest),
1025 : GetSlruSegment(PagestreamGetSlruSegmentRequest),
1026 : }
1027 :
1028 : // Wrapped in libpq CopyData
1029 0 : #[derive(strum_macros::EnumProperty)]
1030 : pub enum PagestreamBeMessage {
1031 : Exists(PagestreamExistsResponse),
1032 : Nblocks(PagestreamNblocksResponse),
1033 : GetPage(PagestreamGetPageResponse),
1034 : Error(PagestreamErrorResponse),
1035 : DbSize(PagestreamDbSizeResponse),
1036 : GetSlruSegment(PagestreamGetSlruSegmentResponse),
1037 : }
1038 :
1039 : // Keep in sync with `pagestore_client.h`
1040 : #[repr(u8)]
1041 : enum PagestreamBeMessageTag {
1042 : Exists = 100,
1043 : Nblocks = 101,
1044 : GetPage = 102,
1045 : Error = 103,
1046 : DbSize = 104,
1047 : GetSlruSegment = 105,
1048 : }
1049 : impl TryFrom<u8> for PagestreamBeMessageTag {
1050 : type Error = u8;
1051 0 : fn try_from(value: u8) -> Result<Self, u8> {
1052 0 : match value {
1053 0 : 100 => Ok(PagestreamBeMessageTag::Exists),
1054 0 : 101 => Ok(PagestreamBeMessageTag::Nblocks),
1055 0 : 102 => Ok(PagestreamBeMessageTag::GetPage),
1056 0 : 103 => Ok(PagestreamBeMessageTag::Error),
1057 0 : 104 => Ok(PagestreamBeMessageTag::DbSize),
1058 0 : 105 => Ok(PagestreamBeMessageTag::GetSlruSegment),
1059 0 : _ => Err(value),
1060 : }
1061 0 : }
1062 : }
1063 :
1064 : // A GetPage request contains two LSN values:
1065 : //
1066 : // request_lsn: Get the page version at this point in time. Lsn::Max is a special value that means
1067 : // "get the latest version present". It's used by the primary server, which knows that no one else
1068 : // is writing WAL. 'not_modified_since' must be set to a proper value even if request_lsn is
1069 : // Lsn::Max. Standby servers use the current replay LSN as the request LSN.
1070 : //
1071 : // not_modified_since: Hint to the pageserver that the client knows that the page has not been
1072 : // modified between 'not_modified_since' and the request LSN. It's always correct to set
1073 : // 'not_modified_since equal' to 'request_lsn' (unless Lsn::Max is used as the 'request_lsn'), but
1074 : // passing an earlier LSN can speed up the request, by allowing the pageserver to process the
1075 : // request without waiting for 'request_lsn' to arrive.
1076 : //
1077 : // The now-defunct V1 interface contained only one LSN, and a boolean 'latest' flag. The V1 interface was
1078 : // sufficient for the primary; the 'lsn' was equivalent to the 'not_modified_since' value, and
1079 : // 'latest' was set to true. The V2 interface was added because there was no correct way for a
1080 : // standby to request a page at a particular non-latest LSN, and also include the
1081 : // 'not_modified_since' hint. That led to an awkward choice of either using an old LSN in the
1082 : // request, if the standby knows that the page hasn't been modified since, and risk getting an error
1083 : // if that LSN has fallen behind the GC horizon, or requesting the current replay LSN, which could
1084 : // require the pageserver unnecessarily to wait for the WAL to arrive up to that point. The new V2
1085 : // interface allows sending both LSNs, and let the pageserver do the right thing. There was no
1086 : // difference in the responses between V1 and V2.
1087 : //
1088 : #[derive(Clone, Copy)]
1089 : pub enum PagestreamProtocolVersion {
1090 : V2,
1091 : }
1092 :
1093 : #[derive(Debug, PartialEq, Eq)]
1094 : pub struct PagestreamExistsRequest {
1095 : pub request_lsn: Lsn,
1096 : pub not_modified_since: Lsn,
1097 : pub rel: RelTag,
1098 : }
1099 :
1100 : #[derive(Debug, PartialEq, Eq)]
1101 : pub struct PagestreamNblocksRequest {
1102 : pub request_lsn: Lsn,
1103 : pub not_modified_since: Lsn,
1104 : pub rel: RelTag,
1105 : }
1106 :
1107 : #[derive(Debug, PartialEq, Eq)]
1108 : pub struct PagestreamGetPageRequest {
1109 : pub request_lsn: Lsn,
1110 : pub not_modified_since: Lsn,
1111 : pub rel: RelTag,
1112 : pub blkno: u32,
1113 : }
1114 :
1115 : #[derive(Debug, PartialEq, Eq)]
1116 : pub struct PagestreamDbSizeRequest {
1117 : pub request_lsn: Lsn,
1118 : pub not_modified_since: Lsn,
1119 : pub dbnode: u32,
1120 : }
1121 :
1122 : #[derive(Debug, PartialEq, Eq)]
1123 : pub struct PagestreamGetSlruSegmentRequest {
1124 : pub request_lsn: Lsn,
1125 : pub not_modified_since: Lsn,
1126 : pub kind: u8,
1127 : pub segno: u32,
1128 : }
1129 :
1130 : #[derive(Debug)]
1131 : pub struct PagestreamExistsResponse {
1132 : pub exists: bool,
1133 : }
1134 :
1135 : #[derive(Debug)]
1136 : pub struct PagestreamNblocksResponse {
1137 : pub n_blocks: u32,
1138 : }
1139 :
1140 : #[derive(Debug)]
1141 : pub struct PagestreamGetPageResponse {
1142 : pub page: Bytes,
1143 : }
1144 :
1145 : #[derive(Debug)]
1146 : pub struct PagestreamGetSlruSegmentResponse {
1147 : pub segment: Bytes,
1148 : }
1149 :
1150 : #[derive(Debug)]
1151 : pub struct PagestreamErrorResponse {
1152 : pub message: String,
1153 : }
1154 :
1155 : #[derive(Debug)]
1156 : pub struct PagestreamDbSizeResponse {
1157 : pub db_size: i64,
1158 : }
1159 :
1160 : // This is a cut-down version of TenantHistorySize from the pageserver crate, omitting fields
1161 : // that require pageserver-internal types. It is sufficient to get the total size.
1162 0 : #[derive(Serialize, Deserialize, Debug)]
1163 : pub struct TenantHistorySize {
1164 : pub id: TenantId,
1165 : /// Size is a mixture of WAL and logical size, so the unit is bytes.
1166 : ///
1167 : /// Will be none if `?inputs_only=true` was given.
1168 : pub size: Option<u64>,
1169 : }
1170 :
1171 : impl PagestreamFeMessage {
1172 : /// Serialize a compute -> pageserver message. This is currently only used in testing
1173 : /// tools. Always uses protocol version 2.
1174 4 : pub fn serialize(&self) -> Bytes {
1175 4 : let mut bytes = BytesMut::new();
1176 4 :
1177 4 : match self {
1178 1 : Self::Exists(req) => {
1179 1 : bytes.put_u8(0);
1180 1 : bytes.put_u64(req.request_lsn.0);
1181 1 : bytes.put_u64(req.not_modified_since.0);
1182 1 : bytes.put_u32(req.rel.spcnode);
1183 1 : bytes.put_u32(req.rel.dbnode);
1184 1 : bytes.put_u32(req.rel.relnode);
1185 1 : bytes.put_u8(req.rel.forknum);
1186 1 : }
1187 :
1188 1 : Self::Nblocks(req) => {
1189 1 : bytes.put_u8(1);
1190 1 : bytes.put_u64(req.request_lsn.0);
1191 1 : bytes.put_u64(req.not_modified_since.0);
1192 1 : bytes.put_u32(req.rel.spcnode);
1193 1 : bytes.put_u32(req.rel.dbnode);
1194 1 : bytes.put_u32(req.rel.relnode);
1195 1 : bytes.put_u8(req.rel.forknum);
1196 1 : }
1197 :
1198 1 : Self::GetPage(req) => {
1199 1 : bytes.put_u8(2);
1200 1 : bytes.put_u64(req.request_lsn.0);
1201 1 : bytes.put_u64(req.not_modified_since.0);
1202 1 : bytes.put_u32(req.rel.spcnode);
1203 1 : bytes.put_u32(req.rel.dbnode);
1204 1 : bytes.put_u32(req.rel.relnode);
1205 1 : bytes.put_u8(req.rel.forknum);
1206 1 : bytes.put_u32(req.blkno);
1207 1 : }
1208 :
1209 1 : Self::DbSize(req) => {
1210 1 : bytes.put_u8(3);
1211 1 : bytes.put_u64(req.request_lsn.0);
1212 1 : bytes.put_u64(req.not_modified_since.0);
1213 1 : bytes.put_u32(req.dbnode);
1214 1 : }
1215 :
1216 0 : Self::GetSlruSegment(req) => {
1217 0 : bytes.put_u8(4);
1218 0 : bytes.put_u64(req.request_lsn.0);
1219 0 : bytes.put_u64(req.not_modified_since.0);
1220 0 : bytes.put_u8(req.kind);
1221 0 : bytes.put_u32(req.segno);
1222 0 : }
1223 : }
1224 :
1225 4 : bytes.into()
1226 4 : }
1227 :
1228 4 : pub fn parse<R: std::io::Read>(body: &mut R) -> anyhow::Result<PagestreamFeMessage> {
1229 : // these correspond to the NeonMessageTag enum in pagestore_client.h
1230 : //
1231 : // TODO: consider using protobuf or serde bincode for less error prone
1232 : // serialization.
1233 4 : let msg_tag = body.read_u8()?;
1234 :
1235 : // these two fields are the same for every request type
1236 4 : let request_lsn = Lsn::from(body.read_u64::<BigEndian>()?);
1237 4 : let not_modified_since = Lsn::from(body.read_u64::<BigEndian>()?);
1238 :
1239 4 : match msg_tag {
1240 : 0 => Ok(PagestreamFeMessage::Exists(PagestreamExistsRequest {
1241 1 : request_lsn,
1242 1 : not_modified_since,
1243 1 : rel: RelTag {
1244 1 : spcnode: body.read_u32::<BigEndian>()?,
1245 1 : dbnode: body.read_u32::<BigEndian>()?,
1246 1 : relnode: body.read_u32::<BigEndian>()?,
1247 1 : forknum: body.read_u8()?,
1248 : },
1249 : })),
1250 : 1 => Ok(PagestreamFeMessage::Nblocks(PagestreamNblocksRequest {
1251 1 : request_lsn,
1252 1 : not_modified_since,
1253 1 : rel: RelTag {
1254 1 : spcnode: body.read_u32::<BigEndian>()?,
1255 1 : dbnode: body.read_u32::<BigEndian>()?,
1256 1 : relnode: body.read_u32::<BigEndian>()?,
1257 1 : forknum: body.read_u8()?,
1258 : },
1259 : })),
1260 : 2 => Ok(PagestreamFeMessage::GetPage(PagestreamGetPageRequest {
1261 1 : request_lsn,
1262 1 : not_modified_since,
1263 1 : rel: RelTag {
1264 1 : spcnode: body.read_u32::<BigEndian>()?,
1265 1 : dbnode: body.read_u32::<BigEndian>()?,
1266 1 : relnode: body.read_u32::<BigEndian>()?,
1267 1 : forknum: body.read_u8()?,
1268 : },
1269 1 : blkno: body.read_u32::<BigEndian>()?,
1270 : })),
1271 : 3 => Ok(PagestreamFeMessage::DbSize(PagestreamDbSizeRequest {
1272 1 : request_lsn,
1273 1 : not_modified_since,
1274 1 : dbnode: body.read_u32::<BigEndian>()?,
1275 : })),
1276 : 4 => Ok(PagestreamFeMessage::GetSlruSegment(
1277 : PagestreamGetSlruSegmentRequest {
1278 0 : request_lsn,
1279 0 : not_modified_since,
1280 0 : kind: body.read_u8()?,
1281 0 : segno: body.read_u32::<BigEndian>()?,
1282 : },
1283 : )),
1284 0 : _ => bail!("unknown smgr message tag: {:?}", msg_tag),
1285 : }
1286 4 : }
1287 : }
1288 :
1289 : impl PagestreamBeMessage {
1290 0 : pub fn serialize(&self) -> Bytes {
1291 0 : let mut bytes = BytesMut::new();
1292 0 :
1293 0 : use PagestreamBeMessageTag as Tag;
1294 0 : match self {
1295 0 : Self::Exists(resp) => {
1296 0 : bytes.put_u8(Tag::Exists as u8);
1297 0 : bytes.put_u8(resp.exists as u8);
1298 0 : }
1299 :
1300 0 : Self::Nblocks(resp) => {
1301 0 : bytes.put_u8(Tag::Nblocks as u8);
1302 0 : bytes.put_u32(resp.n_blocks);
1303 0 : }
1304 :
1305 0 : Self::GetPage(resp) => {
1306 0 : bytes.put_u8(Tag::GetPage as u8);
1307 0 : bytes.put(&resp.page[..]);
1308 0 : }
1309 :
1310 0 : Self::Error(resp) => {
1311 0 : bytes.put_u8(Tag::Error as u8);
1312 0 : bytes.put(resp.message.as_bytes());
1313 0 : bytes.put_u8(0); // null terminator
1314 0 : }
1315 0 : Self::DbSize(resp) => {
1316 0 : bytes.put_u8(Tag::DbSize as u8);
1317 0 : bytes.put_i64(resp.db_size);
1318 0 : }
1319 :
1320 0 : Self::GetSlruSegment(resp) => {
1321 0 : bytes.put_u8(Tag::GetSlruSegment as u8);
1322 0 : bytes.put_u32((resp.segment.len() / BLCKSZ as usize) as u32);
1323 0 : bytes.put(&resp.segment[..]);
1324 0 : }
1325 : }
1326 :
1327 0 : bytes.into()
1328 0 : }
1329 :
1330 0 : pub fn deserialize(buf: Bytes) -> anyhow::Result<Self> {
1331 0 : let mut buf = buf.reader();
1332 0 : let msg_tag = buf.read_u8()?;
1333 :
1334 : use PagestreamBeMessageTag as Tag;
1335 0 : let ok =
1336 0 : match Tag::try_from(msg_tag).map_err(|tag: u8| anyhow::anyhow!("invalid tag {tag}"))? {
1337 : Tag::Exists => {
1338 0 : let exists = buf.read_u8()?;
1339 0 : Self::Exists(PagestreamExistsResponse {
1340 0 : exists: exists != 0,
1341 0 : })
1342 : }
1343 : Tag::Nblocks => {
1344 0 : let n_blocks = buf.read_u32::<BigEndian>()?;
1345 0 : Self::Nblocks(PagestreamNblocksResponse { n_blocks })
1346 : }
1347 : Tag::GetPage => {
1348 0 : let mut page = vec![0; 8192]; // TODO: use MaybeUninit
1349 0 : buf.read_exact(&mut page)?;
1350 0 : PagestreamBeMessage::GetPage(PagestreamGetPageResponse { page: page.into() })
1351 : }
1352 : Tag::Error => {
1353 0 : let mut msg = Vec::new();
1354 0 : buf.read_until(0, &mut msg)?;
1355 0 : let cstring = std::ffi::CString::from_vec_with_nul(msg)?;
1356 0 : let rust_str = cstring.to_str()?;
1357 0 : PagestreamBeMessage::Error(PagestreamErrorResponse {
1358 0 : message: rust_str.to_owned(),
1359 0 : })
1360 : }
1361 : Tag::DbSize => {
1362 0 : let db_size = buf.read_i64::<BigEndian>()?;
1363 0 : Self::DbSize(PagestreamDbSizeResponse { db_size })
1364 : }
1365 : Tag::GetSlruSegment => {
1366 0 : let n_blocks = buf.read_u32::<BigEndian>()?;
1367 0 : let mut segment = vec![0; n_blocks as usize * BLCKSZ as usize];
1368 0 : buf.read_exact(&mut segment)?;
1369 0 : Self::GetSlruSegment(PagestreamGetSlruSegmentResponse {
1370 0 : segment: segment.into(),
1371 0 : })
1372 : }
1373 : };
1374 0 : let remaining = buf.into_inner();
1375 0 : if !remaining.is_empty() {
1376 0 : anyhow::bail!(
1377 0 : "remaining bytes in msg with tag={msg_tag}: {}",
1378 0 : remaining.len()
1379 0 : );
1380 0 : }
1381 0 : Ok(ok)
1382 0 : }
1383 :
1384 0 : pub fn kind(&self) -> &'static str {
1385 0 : match self {
1386 0 : Self::Exists(_) => "Exists",
1387 0 : Self::Nblocks(_) => "Nblocks",
1388 0 : Self::GetPage(_) => "GetPage",
1389 0 : Self::Error(_) => "Error",
1390 0 : Self::DbSize(_) => "DbSize",
1391 0 : Self::GetSlruSegment(_) => "GetSlruSegment",
1392 : }
1393 0 : }
1394 : }
1395 :
1396 : #[cfg(test)]
1397 : mod tests {
1398 : use serde_json::json;
1399 : use std::str::FromStr;
1400 :
1401 : use super::*;
1402 :
1403 : #[test]
1404 1 : fn test_pagestream() {
1405 1 : // Test serialization/deserialization of PagestreamFeMessage
1406 1 : let messages = vec![
1407 1 : PagestreamFeMessage::Exists(PagestreamExistsRequest {
1408 1 : request_lsn: Lsn(4),
1409 1 : not_modified_since: Lsn(3),
1410 1 : rel: RelTag {
1411 1 : forknum: 1,
1412 1 : spcnode: 2,
1413 1 : dbnode: 3,
1414 1 : relnode: 4,
1415 1 : },
1416 1 : }),
1417 1 : PagestreamFeMessage::Nblocks(PagestreamNblocksRequest {
1418 1 : request_lsn: Lsn(4),
1419 1 : not_modified_since: Lsn(4),
1420 1 : rel: RelTag {
1421 1 : forknum: 1,
1422 1 : spcnode: 2,
1423 1 : dbnode: 3,
1424 1 : relnode: 4,
1425 1 : },
1426 1 : }),
1427 1 : PagestreamFeMessage::GetPage(PagestreamGetPageRequest {
1428 1 : request_lsn: Lsn(4),
1429 1 : not_modified_since: Lsn(3),
1430 1 : rel: RelTag {
1431 1 : forknum: 1,
1432 1 : spcnode: 2,
1433 1 : dbnode: 3,
1434 1 : relnode: 4,
1435 1 : },
1436 1 : blkno: 7,
1437 1 : }),
1438 1 : PagestreamFeMessage::DbSize(PagestreamDbSizeRequest {
1439 1 : request_lsn: Lsn(4),
1440 1 : not_modified_since: Lsn(3),
1441 1 : dbnode: 7,
1442 1 : }),
1443 1 : ];
1444 5 : for msg in messages {
1445 4 : let bytes = msg.serialize();
1446 4 : let reconstructed = PagestreamFeMessage::parse(&mut bytes.reader()).unwrap();
1447 4 : assert!(msg == reconstructed);
1448 : }
1449 1 : }
1450 :
1451 : #[test]
1452 1 : fn test_tenantinfo_serde() {
1453 1 : // Test serialization/deserialization of TenantInfo
1454 1 : let original_active = TenantInfo {
1455 1 : id: TenantShardId::unsharded(TenantId::generate()),
1456 1 : state: TenantState::Active,
1457 1 : current_physical_size: Some(42),
1458 1 : attachment_status: TenantAttachmentStatus::Attached,
1459 1 : generation: 1,
1460 1 : gc_blocking: None,
1461 1 : };
1462 1 : let expected_active = json!({
1463 1 : "id": original_active.id.to_string(),
1464 1 : "state": {
1465 1 : "slug": "Active",
1466 1 : },
1467 1 : "current_physical_size": 42,
1468 1 : "attachment_status": {
1469 1 : "slug":"attached",
1470 1 : },
1471 1 : "generation" : 1
1472 1 : });
1473 1 :
1474 1 : let original_broken = TenantInfo {
1475 1 : id: TenantShardId::unsharded(TenantId::generate()),
1476 1 : state: TenantState::Broken {
1477 1 : reason: "reason".into(),
1478 1 : backtrace: "backtrace info".into(),
1479 1 : },
1480 1 : current_physical_size: Some(42),
1481 1 : attachment_status: TenantAttachmentStatus::Attached,
1482 1 : generation: 1,
1483 1 : gc_blocking: None,
1484 1 : };
1485 1 : let expected_broken = json!({
1486 1 : "id": original_broken.id.to_string(),
1487 1 : "state": {
1488 1 : "slug": "Broken",
1489 1 : "data": {
1490 1 : "backtrace": "backtrace info",
1491 1 : "reason": "reason",
1492 1 : }
1493 1 : },
1494 1 : "current_physical_size": 42,
1495 1 : "attachment_status": {
1496 1 : "slug":"attached",
1497 1 : },
1498 1 : "generation" : 1
1499 1 : });
1500 1 :
1501 1 : assert_eq!(
1502 1 : serde_json::to_value(&original_active).unwrap(),
1503 1 : expected_active
1504 1 : );
1505 :
1506 1 : assert_eq!(
1507 1 : serde_json::to_value(&original_broken).unwrap(),
1508 1 : expected_broken
1509 1 : );
1510 1 : assert!(format!("{:?}", &original_broken.state).contains("reason"));
1511 1 : assert!(format!("{:?}", &original_broken.state).contains("backtrace info"));
1512 1 : }
1513 :
1514 : #[test]
1515 1 : fn test_reject_unknown_field() {
1516 1 : let id = TenantId::generate();
1517 1 : let config_request = json!({
1518 1 : "tenant_id": id.to_string(),
1519 1 : "unknown_field": "unknown_value".to_string(),
1520 1 : });
1521 1 : let err = serde_json::from_value::<TenantConfigRequest>(config_request).unwrap_err();
1522 1 : assert!(
1523 1 : err.to_string().contains("unknown field `unknown_field`"),
1524 0 : "expect unknown field `unknown_field` error, got: {}",
1525 : err
1526 : );
1527 1 : }
1528 :
1529 : #[test]
1530 1 : fn tenantstatus_activating_serde() {
1531 1 : let states = [
1532 1 : TenantState::Activating(ActivatingFrom::Loading),
1533 1 : TenantState::Activating(ActivatingFrom::Attaching),
1534 1 : ];
1535 1 : let expected = "[{\"slug\":\"Activating\",\"data\":\"Loading\"},{\"slug\":\"Activating\",\"data\":\"Attaching\"}]";
1536 1 :
1537 1 : let actual = serde_json::to_string(&states).unwrap();
1538 1 :
1539 1 : assert_eq!(actual, expected);
1540 :
1541 1 : let parsed = serde_json::from_str::<Vec<TenantState>>(&actual).unwrap();
1542 1 :
1543 1 : assert_eq!(states.as_slice(), &parsed);
1544 1 : }
1545 :
1546 : #[test]
1547 1 : fn tenantstatus_activating_strum() {
1548 1 : // tests added, because we use these for metrics
1549 1 : let examples = [
1550 1 : (line!(), TenantState::Loading, "Loading"),
1551 1 : (line!(), TenantState::Attaching, "Attaching"),
1552 1 : (
1553 1 : line!(),
1554 1 : TenantState::Activating(ActivatingFrom::Loading),
1555 1 : "Activating",
1556 1 : ),
1557 1 : (
1558 1 : line!(),
1559 1 : TenantState::Activating(ActivatingFrom::Attaching),
1560 1 : "Activating",
1561 1 : ),
1562 1 : (line!(), TenantState::Active, "Active"),
1563 1 : (
1564 1 : line!(),
1565 1 : TenantState::Stopping {
1566 1 : progress: utils::completion::Barrier::default(),
1567 1 : },
1568 1 : "Stopping",
1569 1 : ),
1570 1 : (
1571 1 : line!(),
1572 1 : TenantState::Broken {
1573 1 : reason: "Example".into(),
1574 1 : backtrace: "Looooong backtrace".into(),
1575 1 : },
1576 1 : "Broken",
1577 1 : ),
1578 1 : ];
1579 :
1580 8 : for (line, rendered, expected) in examples {
1581 7 : let actual: &'static str = rendered.into();
1582 7 : assert_eq!(actual, expected, "example on {line}");
1583 : }
1584 1 : }
1585 :
1586 : #[test]
1587 1 : fn test_aux_file_migration_path() {
1588 1 : assert!(AuxFilePolicy::is_valid_migration_path(
1589 1 : None,
1590 1 : AuxFilePolicy::V1
1591 1 : ));
1592 1 : assert!(AuxFilePolicy::is_valid_migration_path(
1593 1 : None,
1594 1 : AuxFilePolicy::V2
1595 1 : ));
1596 1 : assert!(AuxFilePolicy::is_valid_migration_path(
1597 1 : None,
1598 1 : AuxFilePolicy::CrossValidation
1599 1 : ));
1600 : // Self-migration is not a valid migration path, and the caller should handle it by itself.
1601 1 : assert!(!AuxFilePolicy::is_valid_migration_path(
1602 1 : Some(AuxFilePolicy::V1),
1603 1 : AuxFilePolicy::V1
1604 1 : ));
1605 1 : assert!(!AuxFilePolicy::is_valid_migration_path(
1606 1 : Some(AuxFilePolicy::V2),
1607 1 : AuxFilePolicy::V2
1608 1 : ));
1609 1 : assert!(!AuxFilePolicy::is_valid_migration_path(
1610 1 : Some(AuxFilePolicy::CrossValidation),
1611 1 : AuxFilePolicy::CrossValidation
1612 1 : ));
1613 : // Migrations not allowed
1614 1 : assert!(!AuxFilePolicy::is_valid_migration_path(
1615 1 : Some(AuxFilePolicy::CrossValidation),
1616 1 : AuxFilePolicy::V1
1617 1 : ));
1618 1 : assert!(!AuxFilePolicy::is_valid_migration_path(
1619 1 : Some(AuxFilePolicy::V1),
1620 1 : AuxFilePolicy::V2
1621 1 : ));
1622 1 : assert!(!AuxFilePolicy::is_valid_migration_path(
1623 1 : Some(AuxFilePolicy::V2),
1624 1 : AuxFilePolicy::V1
1625 1 : ));
1626 1 : assert!(!AuxFilePolicy::is_valid_migration_path(
1627 1 : Some(AuxFilePolicy::V2),
1628 1 : AuxFilePolicy::CrossValidation
1629 1 : ));
1630 1 : assert!(!AuxFilePolicy::is_valid_migration_path(
1631 1 : Some(AuxFilePolicy::V1),
1632 1 : AuxFilePolicy::CrossValidation
1633 1 : ));
1634 : // Migrations allowed
1635 1 : assert!(AuxFilePolicy::is_valid_migration_path(
1636 1 : Some(AuxFilePolicy::CrossValidation),
1637 1 : AuxFilePolicy::V2
1638 1 : ));
1639 1 : }
1640 :
1641 : #[test]
1642 1 : fn test_aux_parse() {
1643 1 : assert_eq!(AuxFilePolicy::from_str("V2").unwrap(), AuxFilePolicy::V2);
1644 1 : assert_eq!(AuxFilePolicy::from_str("v2").unwrap(), AuxFilePolicy::V2);
1645 1 : assert_eq!(
1646 1 : AuxFilePolicy::from_str("cross-validation").unwrap(),
1647 1 : AuxFilePolicy::CrossValidation
1648 1 : );
1649 1 : }
1650 :
1651 : #[test]
1652 1 : fn test_image_compression_algorithm_parsing() {
1653 1 : use ImageCompressionAlgorithm::*;
1654 1 : assert_eq!(
1655 1 : ImageCompressionAlgorithm::from_str("disabled").unwrap(),
1656 1 : Disabled
1657 1 : );
1658 1 : assert_eq!(
1659 1 : ImageCompressionAlgorithm::from_str("zstd").unwrap(),
1660 1 : Zstd { level: None }
1661 1 : );
1662 1 : assert_eq!(
1663 1 : ImageCompressionAlgorithm::from_str("zstd(18)").unwrap(),
1664 1 : Zstd { level: Some(18) }
1665 1 : );
1666 1 : assert_eq!(
1667 1 : ImageCompressionAlgorithm::from_str("zstd(-3)").unwrap(),
1668 1 : Zstd { level: Some(-3) }
1669 1 : );
1670 1 : }
1671 : }
|