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::{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 2 : serde::Serialize,
62 12 : serde::Deserialize,
63 0 : strum_macros::Display,
64 : strum_macros::EnumVariantNames,
65 0 : strum_macros::AsRefStr,
66 360 : 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 4 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153 4 : match self {
154 4 : Self::Broken { reason, backtrace } if !reason.is_empty() => {
155 4 : write!(f, "Broken due to: {reason}. Backtrace:\n{backtrace}")
156 : }
157 0 : _ => write!(f, "{self}"),
158 : }
159 4 : }
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 6 : pub fn is_expired(&self, now: &SystemTime) -> bool {
188 6 : now > &self.valid_until
189 6 : }
190 : }
191 :
192 : /// The only [`TenantState`] variants we could be `TenantState::Activating` from.
193 8 : #[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 184 : fn default() -> Self {
270 184 : Self {
271 184 : count: ShardCount::new(0),
272 184 : stripe_size: Self::DEFAULT_STRIPE_SIZE,
273 184 : }
274 184 : }
275 : }
276 :
277 : /// An alternative representation of `pageserver::tenant::TenantConf` with
278 : /// simpler types.
279 4 : #[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 8 : strum_macros::EnumString,
323 21 : 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 54 : pub fn is_valid_migration_path(from: Option<Self>, to: Self) -> bool {
343 34 : matches!(
344 54 : (from, to),
345 : (None, _) | (Some(AuxFilePolicy::CrossValidation), AuxFilePolicy::V2)
346 : )
347 54 : }
348 :
349 : /// If a tenant writes aux files without setting `switch_aux_policy`, this value will be used.
350 402 : pub fn default_tenant_config() -> Self {
351 402 : Self::V1
352 402 : }
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 398 : pub fn new(policy: Option<AuxFilePolicy>) -> Self {
360 398 : Self(AtomicUsize::new(
361 398 : policy.map(AuxFilePolicy::to_usize).unwrap_or_default(),
362 398 : ))
363 398 : }
364 :
365 308 : pub fn load(&self) -> Option<AuxFilePolicy> {
366 308 : match self.0.load(std::sync::atomic::Ordering::Acquire) {
367 242 : 0 => None,
368 66 : other => Some(AuxFilePolicy::from_usize(other)),
369 : }
370 308 : }
371 :
372 22 : pub fn store(&self, policy: Option<AuxFilePolicy>) {
373 22 : self.0.store(
374 22 : policy.map(AuxFilePolicy::to_usize).unwrap_or_default(),
375 22 : std::sync::atomic::Ordering::Release,
376 22 : );
377 22 : }
378 : }
379 :
380 : impl AuxFilePolicy {
381 20 : pub fn to_usize(self) -> usize {
382 20 : match self {
383 14 : Self::V1 => 1,
384 2 : Self::CrossValidation => 2,
385 4 : Self::V2 => 3,
386 : }
387 20 : }
388 :
389 66 : pub fn try_from_usize(this: usize) -> Option<Self> {
390 66 : match this {
391 36 : 1 => Some(Self::V1),
392 6 : 2 => Some(Self::CrossValidation),
393 24 : 3 => Some(Self::V2),
394 0 : _ => None,
395 : }
396 66 : }
397 :
398 66 : pub fn from_usize(this: usize) -> Self {
399 66 : Self::try_from_usize(this).unwrap()
400 66 : }
401 : }
402 :
403 4 : #[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 8 : fn from_str(s: &str) -> Result<Self, Self::Err> {
452 8 : let mut components = s.split(['(', ')']);
453 8 : let first = components
454 8 : .next()
455 8 : .ok_or_else(|| anyhow::anyhow!("empty string"))?;
456 8 : match first {
457 8 : "disabled" => Ok(ImageCompressionAlgorithm::Disabled),
458 6 : "zstd" => {
459 6 : let level = if let Some(v) = components.next() {
460 4 : let v: i8 = v.parse()?;
461 4 : Some(v)
462 : } else {
463 2 : None
464 : };
465 :
466 6 : Ok(ImageCompressionAlgorithm::Zstd { level })
467 : }
468 0 : _ => anyhow::bail!("invalid specifier '{first}'"),
469 : }
470 8 : }
471 : }
472 :
473 0 : #[derive(Eq, PartialEq, Debug, Clone, Serialize, Deserialize)]
474 : pub struct CompactionAlgorithmSettings {
475 : pub kind: CompactionAlgorithm,
476 : }
477 :
478 20 : #[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: usize,
490 : #[serde(with = "humantime_serde")]
491 : pub refill_interval: Duration,
492 : pub refill_amount: NonZeroUsize,
493 : pub max: usize,
494 : pub fair: bool,
495 : }
496 :
497 : impl ThrottleConfig {
498 384 : pub fn disabled() -> Self {
499 384 : Self {
500 384 : task_kinds: vec![], // effectively disables the throttle
501 384 : // other values don't matter with emtpy `task_kinds`.
502 384 : initial: 0,
503 384 : refill_interval: Duration::from_millis(1),
504 384 : refill_amount: NonZeroUsize::new(1).unwrap(),
505 384 : max: 1,
506 384 : fair: true,
507 384 : }
508 384 : }
509 : /// The requests per second allowed by the given config.
510 0 : pub fn steady_rps(&self) -> f64 {
511 0 : (self.refill_amount.get() as f64) / (self.refill_interval.as_secs_f64())
512 0 : }
513 : }
514 :
515 : /// A flattened analog of a `pagesever::tenant::LocationMode`, which
516 : /// lists out all possible states (and the virtual "Detached" state)
517 : /// in a flat form rather than using rust-style enums.
518 0 : #[derive(Serialize, Deserialize, Debug, Clone, Copy, Eq, PartialEq)]
519 : pub enum LocationConfigMode {
520 : AttachedSingle,
521 : AttachedMulti,
522 : AttachedStale,
523 : Secondary,
524 : Detached,
525 : }
526 :
527 0 : #[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
528 : pub struct LocationConfigSecondary {
529 : pub warm: bool,
530 : }
531 :
532 : /// An alternative representation of `pageserver::tenant::LocationConf`,
533 : /// for use in external-facing APIs.
534 0 : #[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
535 : pub struct LocationConfig {
536 : pub mode: LocationConfigMode,
537 : /// If attaching, in what generation?
538 : #[serde(default)]
539 : pub generation: Option<u32>,
540 :
541 : // If requesting mode `Secondary`, configuration for that.
542 : #[serde(default)]
543 : pub secondary_conf: Option<LocationConfigSecondary>,
544 :
545 : // Shard parameters: if shard_count is nonzero, then other shard_* fields
546 : // must be set accurately.
547 : #[serde(default)]
548 : pub shard_number: u8,
549 : #[serde(default)]
550 : pub shard_count: u8,
551 : #[serde(default)]
552 : pub shard_stripe_size: u32,
553 :
554 : // This configuration only affects attached mode, but should be provided irrespective
555 : // of the mode, as a secondary location might transition on startup if the response
556 : // to the `/re-attach` control plane API requests it.
557 : pub tenant_conf: TenantConfig,
558 : }
559 :
560 0 : #[derive(Serialize, Deserialize)]
561 : pub struct LocationConfigListResponse {
562 : pub tenant_shards: Vec<(TenantShardId, Option<LocationConfig>)>,
563 : }
564 :
565 : #[derive(Serialize)]
566 : pub struct StatusResponse {
567 : pub id: NodeId,
568 : }
569 :
570 0 : #[derive(Serialize, Deserialize, Debug)]
571 : #[serde(deny_unknown_fields)]
572 : pub struct TenantLocationConfigRequest {
573 : #[serde(flatten)]
574 : pub config: LocationConfig, // as we have a flattened field, we should reject all unknown fields in it
575 : }
576 :
577 0 : #[derive(Serialize, Deserialize, Debug)]
578 : #[serde(deny_unknown_fields)]
579 : pub struct TenantTimeTravelRequest {
580 : pub shard_counts: Vec<ShardCount>,
581 : }
582 :
583 0 : #[derive(Serialize, Deserialize, Debug)]
584 : #[serde(deny_unknown_fields)]
585 : pub struct TenantShardLocation {
586 : pub shard_id: TenantShardId,
587 : pub node_id: NodeId,
588 : }
589 :
590 0 : #[derive(Serialize, Deserialize, Debug)]
591 : #[serde(deny_unknown_fields)]
592 : pub struct TenantLocationConfigResponse {
593 : pub shards: Vec<TenantShardLocation>,
594 : // If the shards' ShardCount count is >1, stripe_size will be set.
595 : pub stripe_size: Option<ShardStripeSize>,
596 : }
597 :
598 6 : #[derive(Serialize, Deserialize, Debug)]
599 : #[serde(deny_unknown_fields)]
600 : pub struct TenantConfigRequest {
601 : pub tenant_id: TenantId,
602 : #[serde(flatten)]
603 : pub config: TenantConfig, // as we have a flattened field, we should reject all unknown fields in it
604 : }
605 :
606 : impl std::ops::Deref for TenantConfigRequest {
607 : type Target = TenantConfig;
608 :
609 0 : fn deref(&self) -> &Self::Target {
610 0 : &self.config
611 0 : }
612 : }
613 :
614 : impl TenantConfigRequest {
615 0 : pub fn new(tenant_id: TenantId) -> TenantConfigRequest {
616 0 : let config = TenantConfig::default();
617 0 : TenantConfigRequest { tenant_id, config }
618 0 : }
619 : }
620 :
621 : /// See [`TenantState::attachment_status`] and the OpenAPI docs for context.
622 0 : #[derive(Serialize, Deserialize, Clone)]
623 : #[serde(tag = "slug", content = "data", rename_all = "snake_case")]
624 : pub enum TenantAttachmentStatus {
625 : Maybe,
626 : Attached,
627 : Failed { reason: String },
628 : }
629 :
630 0 : #[derive(Serialize, Deserialize, Clone)]
631 : pub struct TenantInfo {
632 : pub id: TenantShardId,
633 : // NB: intentionally not part of OpenAPI, we don't want to commit to a specific set of TenantState's
634 : pub state: TenantState,
635 : /// Sum of the size of all layer files.
636 : /// If a layer is present in both local FS and S3, it counts only once.
637 : pub current_physical_size: Option<u64>, // physical size is only included in `tenant_status` endpoint
638 : pub attachment_status: TenantAttachmentStatus,
639 : pub generation: u32,
640 : }
641 :
642 0 : #[derive(Serialize, Deserialize, Clone)]
643 : pub struct TenantDetails {
644 : #[serde(flatten)]
645 : pub tenant_info: TenantInfo,
646 :
647 : pub walredo: Option<WalRedoManagerStatus>,
648 :
649 : pub timelines: Vec<TimelineId>,
650 : }
651 :
652 0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Copy, Debug)]
653 : pub enum TimelineArchivalState {
654 : Archived,
655 : Unarchived,
656 : }
657 :
658 0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone)]
659 : pub struct TimelineArchivalConfigRequest {
660 : pub state: TimelineArchivalState,
661 : }
662 :
663 : /// This represents the output of the "timeline_detail" and "timeline_list" API calls.
664 0 : #[derive(Debug, Serialize, Deserialize, Clone)]
665 : pub struct TimelineInfo {
666 : pub tenant_id: TenantShardId,
667 : pub timeline_id: TimelineId,
668 :
669 : pub ancestor_timeline_id: Option<TimelineId>,
670 : pub ancestor_lsn: Option<Lsn>,
671 : pub last_record_lsn: Lsn,
672 : pub prev_record_lsn: Option<Lsn>,
673 : pub latest_gc_cutoff_lsn: Lsn,
674 : pub disk_consistent_lsn: Lsn,
675 :
676 : /// The LSN that we have succesfully uploaded to remote storage
677 : pub remote_consistent_lsn: Lsn,
678 :
679 : /// The LSN that we are advertizing to safekeepers
680 : pub remote_consistent_lsn_visible: Lsn,
681 :
682 : /// The LSN from the start of the root timeline (never changes)
683 : pub initdb_lsn: Lsn,
684 :
685 : pub current_logical_size: u64,
686 : pub current_logical_size_is_accurate: bool,
687 :
688 : pub directory_entries_counts: Vec<u64>,
689 :
690 : /// Sum of the size of all layer files.
691 : /// If a layer is present in both local FS and S3, it counts only once.
692 : pub current_physical_size: Option<u64>, // is None when timeline is Unloaded
693 : pub current_logical_size_non_incremental: Option<u64>,
694 :
695 : /// How many bytes of WAL are within this branch's pitr_interval. If the pitr_interval goes
696 : /// beyond the branch's branch point, we only count up to the branch point.
697 : pub pitr_history_size: u64,
698 :
699 : /// Whether this branch's branch point is within its ancestor's PITR interval (i.e. any
700 : /// ancestor data used by this branch would have been retained anyway). If this is false, then
701 : /// this branch may be imposing a cost on the ancestor by causing it to retain layers that it would
702 : /// otherwise be able to GC.
703 : pub within_ancestor_pitr: bool,
704 :
705 : pub timeline_dir_layer_file_size_sum: Option<u64>,
706 :
707 : pub wal_source_connstr: Option<String>,
708 : pub last_received_msg_lsn: Option<Lsn>,
709 : /// the timestamp (in microseconds) of the last received message
710 : pub last_received_msg_ts: Option<u128>,
711 : pub pg_version: u32,
712 :
713 : pub state: TimelineState,
714 :
715 : pub walreceiver_status: String,
716 :
717 : /// The last aux file policy being used on this timeline
718 : pub last_aux_file_policy: Option<AuxFilePolicy>,
719 : }
720 :
721 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
722 : pub struct LayerMapInfo {
723 : pub in_memory_layers: Vec<InMemoryLayerInfo>,
724 : pub historic_layers: Vec<HistoricLayerInfo>,
725 : }
726 :
727 : /// The residence status of a layer
728 0 : #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
729 : pub enum LayerResidenceStatus {
730 : /// Residence status for a layer file that exists locally.
731 : /// It may also exist on the remote, we don't care here.
732 : Resident,
733 : /// Residence status for a layer file that only exists on the remote.
734 : Evicted,
735 : }
736 :
737 : #[serde_as]
738 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
739 : pub struct LayerAccessStats {
740 : #[serde_as(as = "serde_with::TimestampMilliSeconds")]
741 : pub access_time: SystemTime,
742 :
743 : #[serde_as(as = "serde_with::TimestampMilliSeconds")]
744 : pub residence_time: SystemTime,
745 :
746 : pub visible: bool,
747 : }
748 :
749 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
750 : #[serde(tag = "kind")]
751 : pub enum InMemoryLayerInfo {
752 : Open { lsn_start: Lsn },
753 : Frozen { lsn_start: Lsn, lsn_end: Lsn },
754 : }
755 :
756 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
757 : #[serde(tag = "kind")]
758 : pub enum HistoricLayerInfo {
759 : Delta {
760 : layer_file_name: String,
761 : layer_file_size: u64,
762 :
763 : lsn_start: Lsn,
764 : lsn_end: Lsn,
765 : remote: bool,
766 : access_stats: LayerAccessStats,
767 :
768 : l0: bool,
769 : },
770 : Image {
771 : layer_file_name: String,
772 : layer_file_size: u64,
773 :
774 : lsn_start: Lsn,
775 : remote: bool,
776 : access_stats: LayerAccessStats,
777 : },
778 : }
779 :
780 : impl HistoricLayerInfo {
781 0 : pub fn layer_file_name(&self) -> &str {
782 0 : match self {
783 : HistoricLayerInfo::Delta {
784 0 : layer_file_name, ..
785 0 : } => layer_file_name,
786 : HistoricLayerInfo::Image {
787 0 : layer_file_name, ..
788 0 : } => layer_file_name,
789 : }
790 0 : }
791 0 : pub fn is_remote(&self) -> bool {
792 0 : match self {
793 0 : HistoricLayerInfo::Delta { remote, .. } => *remote,
794 0 : HistoricLayerInfo::Image { remote, .. } => *remote,
795 : }
796 0 : }
797 0 : pub fn set_remote(&mut self, value: bool) {
798 0 : let field = match self {
799 0 : HistoricLayerInfo::Delta { remote, .. } => remote,
800 0 : HistoricLayerInfo::Image { remote, .. } => remote,
801 : };
802 0 : *field = value;
803 0 : }
804 0 : pub fn layer_file_size(&self) -> u64 {
805 0 : match self {
806 : HistoricLayerInfo::Delta {
807 0 : layer_file_size, ..
808 0 : } => *layer_file_size,
809 : HistoricLayerInfo::Image {
810 0 : layer_file_size, ..
811 0 : } => *layer_file_size,
812 : }
813 0 : }
814 : }
815 :
816 0 : #[derive(Debug, Serialize, Deserialize)]
817 : pub struct DownloadRemoteLayersTaskSpawnRequest {
818 : pub max_concurrent_downloads: NonZeroUsize,
819 : }
820 :
821 0 : #[derive(Debug, Serialize, Deserialize)]
822 : pub struct IngestAuxFilesRequest {
823 : pub aux_files: HashMap<String, String>,
824 : }
825 :
826 0 : #[derive(Debug, Serialize, Deserialize)]
827 : pub struct ListAuxFilesRequest {
828 : pub lsn: Lsn,
829 : }
830 :
831 0 : #[derive(Debug, Serialize, Deserialize, Clone)]
832 : pub struct DownloadRemoteLayersTaskInfo {
833 : pub task_id: String,
834 : pub state: DownloadRemoteLayersTaskState,
835 : pub total_layer_count: u64, // stable once `completed`
836 : pub successful_download_count: u64, // stable once `completed`
837 : pub failed_download_count: u64, // stable once `completed`
838 : }
839 :
840 0 : #[derive(Debug, Serialize, Deserialize, Clone)]
841 : pub enum DownloadRemoteLayersTaskState {
842 : Running,
843 : Completed,
844 : ShutDown,
845 : }
846 :
847 0 : #[derive(Debug, Serialize, Deserialize)]
848 : pub struct TimelineGcRequest {
849 : pub gc_horizon: Option<u64>,
850 : }
851 :
852 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
853 : pub struct WalRedoManagerProcessStatus {
854 : pub pid: u32,
855 : }
856 :
857 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
858 : pub struct WalRedoManagerStatus {
859 : pub last_redo_at: Option<chrono::DateTime<chrono::Utc>>,
860 : pub process: Option<WalRedoManagerProcessStatus>,
861 : }
862 :
863 : /// The progress of a secondary tenant is mostly useful when doing a long running download: e.g. initiating
864 : /// a download job, timing out while waiting for it to run, and then inspecting this status to understand
865 : /// what's happening.
866 0 : #[derive(Default, Debug, Serialize, Deserialize, Clone)]
867 : pub struct SecondaryProgress {
868 : /// The remote storage LastModified time of the heatmap object we last downloaded.
869 : pub heatmap_mtime: Option<serde_system_time::SystemTime>,
870 :
871 : /// The number of layers currently on-disk
872 : pub layers_downloaded: usize,
873 : /// The number of layers in the most recently seen heatmap
874 : pub layers_total: usize,
875 :
876 : /// The number of layer bytes currently on-disk
877 : pub bytes_downloaded: u64,
878 : /// The number of layer bytes in the most recently seen heatmap
879 : pub bytes_total: u64,
880 : }
881 :
882 0 : #[derive(Serialize, Deserialize, Debug)]
883 : pub struct TenantScanRemoteStorageShard {
884 : pub tenant_shard_id: TenantShardId,
885 : pub generation: Option<u32>,
886 : }
887 :
888 0 : #[derive(Serialize, Deserialize, Debug, Default)]
889 : pub struct TenantScanRemoteStorageResponse {
890 : pub shards: Vec<TenantScanRemoteStorageShard>,
891 : }
892 :
893 0 : #[derive(Serialize, Deserialize, Debug, Clone)]
894 : #[serde(rename_all = "snake_case")]
895 : pub enum TenantSorting {
896 : ResidentSize,
897 : MaxLogicalSize,
898 : }
899 :
900 : impl Default for TenantSorting {
901 0 : fn default() -> Self {
902 0 : Self::ResidentSize
903 0 : }
904 : }
905 :
906 0 : #[derive(Serialize, Deserialize, Debug, Clone)]
907 : pub struct TopTenantShardsRequest {
908 : // How would you like to sort the tenants?
909 : pub order_by: TenantSorting,
910 :
911 : // How many results?
912 : pub limit: usize,
913 :
914 : // Omit tenants with more than this many shards (e.g. if this is the max number of shards
915 : // that the caller would ever split to)
916 : pub where_shards_lt: Option<ShardCount>,
917 :
918 : // Omit tenants where the ordering metric is less than this (this is an optimization to
919 : // let us quickly exclude numerous tiny shards)
920 : pub where_gt: Option<u64>,
921 : }
922 :
923 0 : #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
924 : pub struct TopTenantShardItem {
925 : pub id: TenantShardId,
926 :
927 : /// Total size of layers on local disk for all timelines in this tenant
928 : pub resident_size: u64,
929 :
930 : /// Total size of layers in remote storage for all timelines in this tenant
931 : pub physical_size: u64,
932 :
933 : /// The largest logical size of a timeline within this tenant
934 : pub max_logical_size: u64,
935 : }
936 :
937 0 : #[derive(Serialize, Deserialize, Debug, Default)]
938 : pub struct TopTenantShardsResponse {
939 : pub shards: Vec<TopTenantShardItem>,
940 : }
941 :
942 : pub mod virtual_file {
943 : #[derive(
944 : Copy,
945 : Clone,
946 : PartialEq,
947 : Eq,
948 : Hash,
949 382 : strum_macros::EnumString,
950 0 : strum_macros::Display,
951 0 : serde_with::DeserializeFromStr,
952 : serde_with::SerializeDisplay,
953 : Debug,
954 : )]
955 : #[strum(serialize_all = "kebab-case")]
956 : pub enum IoEngineKind {
957 : StdFs,
958 : #[cfg(target_os = "linux")]
959 : TokioEpollUring,
960 : }
961 : }
962 :
963 : // Wrapped in libpq CopyData
964 : #[derive(PartialEq, Eq, Debug)]
965 : pub enum PagestreamFeMessage {
966 : Exists(PagestreamExistsRequest),
967 : Nblocks(PagestreamNblocksRequest),
968 : GetPage(PagestreamGetPageRequest),
969 : DbSize(PagestreamDbSizeRequest),
970 : GetSlruSegment(PagestreamGetSlruSegmentRequest),
971 : }
972 :
973 : // Wrapped in libpq CopyData
974 0 : #[derive(strum_macros::EnumProperty)]
975 : pub enum PagestreamBeMessage {
976 : Exists(PagestreamExistsResponse),
977 : Nblocks(PagestreamNblocksResponse),
978 : GetPage(PagestreamGetPageResponse),
979 : Error(PagestreamErrorResponse),
980 : DbSize(PagestreamDbSizeResponse),
981 : GetSlruSegment(PagestreamGetSlruSegmentResponse),
982 : }
983 :
984 : // Keep in sync with `pagestore_client.h`
985 : #[repr(u8)]
986 : enum PagestreamBeMessageTag {
987 : Exists = 100,
988 : Nblocks = 101,
989 : GetPage = 102,
990 : Error = 103,
991 : DbSize = 104,
992 : GetSlruSegment = 105,
993 : }
994 : impl TryFrom<u8> for PagestreamBeMessageTag {
995 : type Error = u8;
996 0 : fn try_from(value: u8) -> Result<Self, u8> {
997 0 : match value {
998 0 : 100 => Ok(PagestreamBeMessageTag::Exists),
999 0 : 101 => Ok(PagestreamBeMessageTag::Nblocks),
1000 0 : 102 => Ok(PagestreamBeMessageTag::GetPage),
1001 0 : 103 => Ok(PagestreamBeMessageTag::Error),
1002 0 : 104 => Ok(PagestreamBeMessageTag::DbSize),
1003 0 : 105 => Ok(PagestreamBeMessageTag::GetSlruSegment),
1004 0 : _ => Err(value),
1005 : }
1006 0 : }
1007 : }
1008 :
1009 : // In the V2 protocol version, a GetPage request contains two LSN values:
1010 : //
1011 : // request_lsn: Get the page version at this point in time. Lsn::Max is a special value that means
1012 : // "get the latest version present". It's used by the primary server, which knows that no one else
1013 : // is writing WAL. 'not_modified_since' must be set to a proper value even if request_lsn is
1014 : // Lsn::Max. Standby servers use the current replay LSN as the request LSN.
1015 : //
1016 : // not_modified_since: Hint to the pageserver that the client knows that the page has not been
1017 : // modified between 'not_modified_since' and the request LSN. It's always correct to set
1018 : // 'not_modified_since equal' to 'request_lsn' (unless Lsn::Max is used as the 'request_lsn'), but
1019 : // passing an earlier LSN can speed up the request, by allowing the pageserver to process the
1020 : // request without waiting for 'request_lsn' to arrive.
1021 : //
1022 : // The legacy V1 interface contained only one LSN, and a boolean 'latest' flag. The V1 interface was
1023 : // sufficient for the primary; the 'lsn' was equivalent to the 'not_modified_since' value, and
1024 : // 'latest' was set to true. The V2 interface was added because there was no correct way for a
1025 : // standby to request a page at a particular non-latest LSN, and also include the
1026 : // 'not_modified_since' hint. That led to an awkward choice of either using an old LSN in the
1027 : // request, if the standby knows that the page hasn't been modified since, and risk getting an error
1028 : // if that LSN has fallen behind the GC horizon, or requesting the current replay LSN, which could
1029 : // require the pageserver unnecessarily to wait for the WAL to arrive up to that point. The new V2
1030 : // interface allows sending both LSNs, and let the pageserver do the right thing. There is no
1031 : // difference in the responses between V1 and V2.
1032 : //
1033 : // The Request structs below reflect the V2 interface. If V1 is used, the parse function
1034 : // maps the old format requests to the new format.
1035 : //
1036 : #[derive(Clone, Copy)]
1037 : pub enum PagestreamProtocolVersion {
1038 : V1,
1039 : V2,
1040 : }
1041 :
1042 : #[derive(Debug, PartialEq, Eq)]
1043 : pub struct PagestreamExistsRequest {
1044 : pub request_lsn: Lsn,
1045 : pub not_modified_since: Lsn,
1046 : pub rel: RelTag,
1047 : }
1048 :
1049 : #[derive(Debug, PartialEq, Eq)]
1050 : pub struct PagestreamNblocksRequest {
1051 : pub request_lsn: Lsn,
1052 : pub not_modified_since: Lsn,
1053 : pub rel: RelTag,
1054 : }
1055 :
1056 : #[derive(Debug, PartialEq, Eq)]
1057 : pub struct PagestreamGetPageRequest {
1058 : pub request_lsn: Lsn,
1059 : pub not_modified_since: Lsn,
1060 : pub rel: RelTag,
1061 : pub blkno: u32,
1062 : }
1063 :
1064 : #[derive(Debug, PartialEq, Eq)]
1065 : pub struct PagestreamDbSizeRequest {
1066 : pub request_lsn: Lsn,
1067 : pub not_modified_since: Lsn,
1068 : pub dbnode: u32,
1069 : }
1070 :
1071 : #[derive(Debug, PartialEq, Eq)]
1072 : pub struct PagestreamGetSlruSegmentRequest {
1073 : pub request_lsn: Lsn,
1074 : pub not_modified_since: Lsn,
1075 : pub kind: u8,
1076 : pub segno: u32,
1077 : }
1078 :
1079 : #[derive(Debug)]
1080 : pub struct PagestreamExistsResponse {
1081 : pub exists: bool,
1082 : }
1083 :
1084 : #[derive(Debug)]
1085 : pub struct PagestreamNblocksResponse {
1086 : pub n_blocks: u32,
1087 : }
1088 :
1089 : #[derive(Debug)]
1090 : pub struct PagestreamGetPageResponse {
1091 : pub page: Bytes,
1092 : }
1093 :
1094 : #[derive(Debug)]
1095 : pub struct PagestreamGetSlruSegmentResponse {
1096 : pub segment: Bytes,
1097 : }
1098 :
1099 : #[derive(Debug)]
1100 : pub struct PagestreamErrorResponse {
1101 : pub message: String,
1102 : }
1103 :
1104 : #[derive(Debug)]
1105 : pub struct PagestreamDbSizeResponse {
1106 : pub db_size: i64,
1107 : }
1108 :
1109 : // This is a cut-down version of TenantHistorySize from the pageserver crate, omitting fields
1110 : // that require pageserver-internal types. It is sufficient to get the total size.
1111 0 : #[derive(Serialize, Deserialize, Debug)]
1112 : pub struct TenantHistorySize {
1113 : pub id: TenantId,
1114 : /// Size is a mixture of WAL and logical size, so the unit is bytes.
1115 : ///
1116 : /// Will be none if `?inputs_only=true` was given.
1117 : pub size: Option<u64>,
1118 : }
1119 :
1120 : impl PagestreamFeMessage {
1121 : /// Serialize a compute -> pageserver message. This is currently only used in testing
1122 : /// tools. Always uses protocol version 2.
1123 8 : pub fn serialize(&self) -> Bytes {
1124 8 : let mut bytes = BytesMut::new();
1125 8 :
1126 8 : match self {
1127 2 : Self::Exists(req) => {
1128 2 : bytes.put_u8(0);
1129 2 : bytes.put_u64(req.request_lsn.0);
1130 2 : bytes.put_u64(req.not_modified_since.0);
1131 2 : bytes.put_u32(req.rel.spcnode);
1132 2 : bytes.put_u32(req.rel.dbnode);
1133 2 : bytes.put_u32(req.rel.relnode);
1134 2 : bytes.put_u8(req.rel.forknum);
1135 2 : }
1136 :
1137 2 : Self::Nblocks(req) => {
1138 2 : bytes.put_u8(1);
1139 2 : bytes.put_u64(req.request_lsn.0);
1140 2 : bytes.put_u64(req.not_modified_since.0);
1141 2 : bytes.put_u32(req.rel.spcnode);
1142 2 : bytes.put_u32(req.rel.dbnode);
1143 2 : bytes.put_u32(req.rel.relnode);
1144 2 : bytes.put_u8(req.rel.forknum);
1145 2 : }
1146 :
1147 2 : Self::GetPage(req) => {
1148 2 : bytes.put_u8(2);
1149 2 : bytes.put_u64(req.request_lsn.0);
1150 2 : bytes.put_u64(req.not_modified_since.0);
1151 2 : bytes.put_u32(req.rel.spcnode);
1152 2 : bytes.put_u32(req.rel.dbnode);
1153 2 : bytes.put_u32(req.rel.relnode);
1154 2 : bytes.put_u8(req.rel.forknum);
1155 2 : bytes.put_u32(req.blkno);
1156 2 : }
1157 :
1158 2 : Self::DbSize(req) => {
1159 2 : bytes.put_u8(3);
1160 2 : bytes.put_u64(req.request_lsn.0);
1161 2 : bytes.put_u64(req.not_modified_since.0);
1162 2 : bytes.put_u32(req.dbnode);
1163 2 : }
1164 :
1165 0 : Self::GetSlruSegment(req) => {
1166 0 : bytes.put_u8(4);
1167 0 : bytes.put_u64(req.request_lsn.0);
1168 0 : bytes.put_u64(req.not_modified_since.0);
1169 0 : bytes.put_u8(req.kind);
1170 0 : bytes.put_u32(req.segno);
1171 0 : }
1172 : }
1173 :
1174 8 : bytes.into()
1175 8 : }
1176 :
1177 8 : pub fn parse<R: std::io::Read>(
1178 8 : body: &mut R,
1179 8 : protocol_version: PagestreamProtocolVersion,
1180 8 : ) -> anyhow::Result<PagestreamFeMessage> {
1181 : // these correspond to the NeonMessageTag enum in pagestore_client.h
1182 : //
1183 : // TODO: consider using protobuf or serde bincode for less error prone
1184 : // serialization.
1185 8 : let msg_tag = body.read_u8()?;
1186 :
1187 8 : let (request_lsn, not_modified_since) = match protocol_version {
1188 : PagestreamProtocolVersion::V2 => (
1189 8 : Lsn::from(body.read_u64::<BigEndian>()?),
1190 8 : Lsn::from(body.read_u64::<BigEndian>()?),
1191 : ),
1192 : PagestreamProtocolVersion::V1 => {
1193 : // In the old protocol, each message starts with a boolean 'latest' flag,
1194 : // followed by 'lsn'. Convert that to the two LSNs, 'request_lsn' and
1195 : // 'not_modified_since', used in the new protocol version.
1196 0 : let latest = body.read_u8()? != 0;
1197 0 : let request_lsn = Lsn::from(body.read_u64::<BigEndian>()?);
1198 0 : if latest {
1199 0 : (Lsn::MAX, request_lsn) // get latest version
1200 : } else {
1201 0 : (request_lsn, request_lsn) // get version at specified LSN
1202 : }
1203 : }
1204 : };
1205 :
1206 : // The rest of the messages are the same between V1 and V2
1207 8 : match msg_tag {
1208 : 0 => Ok(PagestreamFeMessage::Exists(PagestreamExistsRequest {
1209 2 : request_lsn,
1210 2 : not_modified_since,
1211 2 : rel: RelTag {
1212 2 : spcnode: body.read_u32::<BigEndian>()?,
1213 2 : dbnode: body.read_u32::<BigEndian>()?,
1214 2 : relnode: body.read_u32::<BigEndian>()?,
1215 2 : forknum: body.read_u8()?,
1216 : },
1217 : })),
1218 : 1 => Ok(PagestreamFeMessage::Nblocks(PagestreamNblocksRequest {
1219 2 : request_lsn,
1220 2 : not_modified_since,
1221 2 : rel: RelTag {
1222 2 : spcnode: body.read_u32::<BigEndian>()?,
1223 2 : dbnode: body.read_u32::<BigEndian>()?,
1224 2 : relnode: body.read_u32::<BigEndian>()?,
1225 2 : forknum: body.read_u8()?,
1226 : },
1227 : })),
1228 : 2 => Ok(PagestreamFeMessage::GetPage(PagestreamGetPageRequest {
1229 2 : request_lsn,
1230 2 : not_modified_since,
1231 2 : rel: RelTag {
1232 2 : spcnode: body.read_u32::<BigEndian>()?,
1233 2 : dbnode: body.read_u32::<BigEndian>()?,
1234 2 : relnode: body.read_u32::<BigEndian>()?,
1235 2 : forknum: body.read_u8()?,
1236 : },
1237 2 : blkno: body.read_u32::<BigEndian>()?,
1238 : })),
1239 : 3 => Ok(PagestreamFeMessage::DbSize(PagestreamDbSizeRequest {
1240 2 : request_lsn,
1241 2 : not_modified_since,
1242 2 : dbnode: body.read_u32::<BigEndian>()?,
1243 : })),
1244 : 4 => Ok(PagestreamFeMessage::GetSlruSegment(
1245 : PagestreamGetSlruSegmentRequest {
1246 0 : request_lsn,
1247 0 : not_modified_since,
1248 0 : kind: body.read_u8()?,
1249 0 : segno: body.read_u32::<BigEndian>()?,
1250 : },
1251 : )),
1252 0 : _ => bail!("unknown smgr message tag: {:?}", msg_tag),
1253 : }
1254 8 : }
1255 : }
1256 :
1257 : impl PagestreamBeMessage {
1258 0 : pub fn serialize(&self) -> Bytes {
1259 0 : let mut bytes = BytesMut::new();
1260 0 :
1261 0 : use PagestreamBeMessageTag as Tag;
1262 0 : match self {
1263 0 : Self::Exists(resp) => {
1264 0 : bytes.put_u8(Tag::Exists as u8);
1265 0 : bytes.put_u8(resp.exists as u8);
1266 0 : }
1267 :
1268 0 : Self::Nblocks(resp) => {
1269 0 : bytes.put_u8(Tag::Nblocks as u8);
1270 0 : bytes.put_u32(resp.n_blocks);
1271 0 : }
1272 :
1273 0 : Self::GetPage(resp) => {
1274 0 : bytes.put_u8(Tag::GetPage as u8);
1275 0 : bytes.put(&resp.page[..]);
1276 0 : }
1277 :
1278 0 : Self::Error(resp) => {
1279 0 : bytes.put_u8(Tag::Error as u8);
1280 0 : bytes.put(resp.message.as_bytes());
1281 0 : bytes.put_u8(0); // null terminator
1282 0 : }
1283 0 : Self::DbSize(resp) => {
1284 0 : bytes.put_u8(Tag::DbSize as u8);
1285 0 : bytes.put_i64(resp.db_size);
1286 0 : }
1287 :
1288 0 : Self::GetSlruSegment(resp) => {
1289 0 : bytes.put_u8(Tag::GetSlruSegment as u8);
1290 0 : bytes.put_u32((resp.segment.len() / BLCKSZ as usize) as u32);
1291 0 : bytes.put(&resp.segment[..]);
1292 0 : }
1293 : }
1294 :
1295 0 : bytes.into()
1296 0 : }
1297 :
1298 0 : pub fn deserialize(buf: Bytes) -> anyhow::Result<Self> {
1299 0 : let mut buf = buf.reader();
1300 0 : let msg_tag = buf.read_u8()?;
1301 :
1302 : use PagestreamBeMessageTag as Tag;
1303 0 : let ok =
1304 0 : match Tag::try_from(msg_tag).map_err(|tag: u8| anyhow::anyhow!("invalid tag {tag}"))? {
1305 : Tag::Exists => {
1306 0 : let exists = buf.read_u8()?;
1307 0 : Self::Exists(PagestreamExistsResponse {
1308 0 : exists: exists != 0,
1309 0 : })
1310 : }
1311 : Tag::Nblocks => {
1312 0 : let n_blocks = buf.read_u32::<BigEndian>()?;
1313 0 : Self::Nblocks(PagestreamNblocksResponse { n_blocks })
1314 : }
1315 : Tag::GetPage => {
1316 0 : let mut page = vec![0; 8192]; // TODO: use MaybeUninit
1317 0 : buf.read_exact(&mut page)?;
1318 0 : PagestreamBeMessage::GetPage(PagestreamGetPageResponse { page: page.into() })
1319 : }
1320 : Tag::Error => {
1321 0 : let mut msg = Vec::new();
1322 0 : buf.read_until(0, &mut msg)?;
1323 0 : let cstring = std::ffi::CString::from_vec_with_nul(msg)?;
1324 0 : let rust_str = cstring.to_str()?;
1325 0 : PagestreamBeMessage::Error(PagestreamErrorResponse {
1326 0 : message: rust_str.to_owned(),
1327 0 : })
1328 : }
1329 : Tag::DbSize => {
1330 0 : let db_size = buf.read_i64::<BigEndian>()?;
1331 0 : Self::DbSize(PagestreamDbSizeResponse { db_size })
1332 : }
1333 : Tag::GetSlruSegment => {
1334 0 : let n_blocks = buf.read_u32::<BigEndian>()?;
1335 0 : let mut segment = vec![0; n_blocks as usize * BLCKSZ as usize];
1336 0 : buf.read_exact(&mut segment)?;
1337 0 : Self::GetSlruSegment(PagestreamGetSlruSegmentResponse {
1338 0 : segment: segment.into(),
1339 0 : })
1340 : }
1341 : };
1342 0 : let remaining = buf.into_inner();
1343 0 : if !remaining.is_empty() {
1344 0 : anyhow::bail!(
1345 0 : "remaining bytes in msg with tag={msg_tag}: {}",
1346 0 : remaining.len()
1347 0 : );
1348 0 : }
1349 0 : Ok(ok)
1350 0 : }
1351 :
1352 0 : pub fn kind(&self) -> &'static str {
1353 0 : match self {
1354 0 : Self::Exists(_) => "Exists",
1355 0 : Self::Nblocks(_) => "Nblocks",
1356 0 : Self::GetPage(_) => "GetPage",
1357 0 : Self::Error(_) => "Error",
1358 0 : Self::DbSize(_) => "DbSize",
1359 0 : Self::GetSlruSegment(_) => "GetSlruSegment",
1360 : }
1361 0 : }
1362 : }
1363 :
1364 : #[cfg(test)]
1365 : mod tests {
1366 : use serde_json::json;
1367 : use std::str::FromStr;
1368 :
1369 : use super::*;
1370 :
1371 : #[test]
1372 2 : fn test_pagestream() {
1373 2 : // Test serialization/deserialization of PagestreamFeMessage
1374 2 : let messages = vec![
1375 2 : PagestreamFeMessage::Exists(PagestreamExistsRequest {
1376 2 : request_lsn: Lsn(4),
1377 2 : not_modified_since: Lsn(3),
1378 2 : rel: RelTag {
1379 2 : forknum: 1,
1380 2 : spcnode: 2,
1381 2 : dbnode: 3,
1382 2 : relnode: 4,
1383 2 : },
1384 2 : }),
1385 2 : PagestreamFeMessage::Nblocks(PagestreamNblocksRequest {
1386 2 : request_lsn: Lsn(4),
1387 2 : not_modified_since: Lsn(4),
1388 2 : rel: RelTag {
1389 2 : forknum: 1,
1390 2 : spcnode: 2,
1391 2 : dbnode: 3,
1392 2 : relnode: 4,
1393 2 : },
1394 2 : }),
1395 2 : PagestreamFeMessage::GetPage(PagestreamGetPageRequest {
1396 2 : request_lsn: Lsn(4),
1397 2 : not_modified_since: Lsn(3),
1398 2 : rel: RelTag {
1399 2 : forknum: 1,
1400 2 : spcnode: 2,
1401 2 : dbnode: 3,
1402 2 : relnode: 4,
1403 2 : },
1404 2 : blkno: 7,
1405 2 : }),
1406 2 : PagestreamFeMessage::DbSize(PagestreamDbSizeRequest {
1407 2 : request_lsn: Lsn(4),
1408 2 : not_modified_since: Lsn(3),
1409 2 : dbnode: 7,
1410 2 : }),
1411 2 : ];
1412 10 : for msg in messages {
1413 8 : let bytes = msg.serialize();
1414 8 : let reconstructed =
1415 8 : PagestreamFeMessage::parse(&mut bytes.reader(), PagestreamProtocolVersion::V2)
1416 8 : .unwrap();
1417 8 : assert!(msg == reconstructed);
1418 : }
1419 2 : }
1420 :
1421 : #[test]
1422 2 : fn test_tenantinfo_serde() {
1423 2 : // Test serialization/deserialization of TenantInfo
1424 2 : let original_active = TenantInfo {
1425 2 : id: TenantShardId::unsharded(TenantId::generate()),
1426 2 : state: TenantState::Active,
1427 2 : current_physical_size: Some(42),
1428 2 : attachment_status: TenantAttachmentStatus::Attached,
1429 2 : generation: 1,
1430 2 : };
1431 2 : let expected_active = json!({
1432 2 : "id": original_active.id.to_string(),
1433 2 : "state": {
1434 2 : "slug": "Active",
1435 2 : },
1436 2 : "current_physical_size": 42,
1437 2 : "attachment_status": {
1438 2 : "slug":"attached",
1439 2 : },
1440 2 : "generation" : 1
1441 2 : });
1442 2 :
1443 2 : let original_broken = TenantInfo {
1444 2 : id: TenantShardId::unsharded(TenantId::generate()),
1445 2 : state: TenantState::Broken {
1446 2 : reason: "reason".into(),
1447 2 : backtrace: "backtrace info".into(),
1448 2 : },
1449 2 : current_physical_size: Some(42),
1450 2 : attachment_status: TenantAttachmentStatus::Attached,
1451 2 : generation: 1,
1452 2 : };
1453 2 : let expected_broken = json!({
1454 2 : "id": original_broken.id.to_string(),
1455 2 : "state": {
1456 2 : "slug": "Broken",
1457 2 : "data": {
1458 2 : "backtrace": "backtrace info",
1459 2 : "reason": "reason",
1460 2 : }
1461 2 : },
1462 2 : "current_physical_size": 42,
1463 2 : "attachment_status": {
1464 2 : "slug":"attached",
1465 2 : },
1466 2 : "generation" : 1
1467 2 : });
1468 2 :
1469 2 : assert_eq!(
1470 2 : serde_json::to_value(&original_active).unwrap(),
1471 2 : expected_active
1472 2 : );
1473 :
1474 2 : assert_eq!(
1475 2 : serde_json::to_value(&original_broken).unwrap(),
1476 2 : expected_broken
1477 2 : );
1478 2 : assert!(format!("{:?}", &original_broken.state).contains("reason"));
1479 2 : assert!(format!("{:?}", &original_broken.state).contains("backtrace info"));
1480 2 : }
1481 :
1482 : #[test]
1483 2 : fn test_reject_unknown_field() {
1484 2 : let id = TenantId::generate();
1485 2 : let config_request = json!({
1486 2 : "tenant_id": id.to_string(),
1487 2 : "unknown_field": "unknown_value".to_string(),
1488 2 : });
1489 2 : let err = serde_json::from_value::<TenantConfigRequest>(config_request).unwrap_err();
1490 2 : assert!(
1491 2 : err.to_string().contains("unknown field `unknown_field`"),
1492 0 : "expect unknown field `unknown_field` error, got: {}",
1493 : err
1494 : );
1495 2 : }
1496 :
1497 : #[test]
1498 2 : fn tenantstatus_activating_serde() {
1499 2 : let states = [
1500 2 : TenantState::Activating(ActivatingFrom::Loading),
1501 2 : TenantState::Activating(ActivatingFrom::Attaching),
1502 2 : ];
1503 2 : let expected = "[{\"slug\":\"Activating\",\"data\":\"Loading\"},{\"slug\":\"Activating\",\"data\":\"Attaching\"}]";
1504 2 :
1505 2 : let actual = serde_json::to_string(&states).unwrap();
1506 2 :
1507 2 : assert_eq!(actual, expected);
1508 :
1509 2 : let parsed = serde_json::from_str::<Vec<TenantState>>(&actual).unwrap();
1510 2 :
1511 2 : assert_eq!(states.as_slice(), &parsed);
1512 2 : }
1513 :
1514 : #[test]
1515 2 : fn tenantstatus_activating_strum() {
1516 2 : // tests added, because we use these for metrics
1517 2 : let examples = [
1518 2 : (line!(), TenantState::Loading, "Loading"),
1519 2 : (line!(), TenantState::Attaching, "Attaching"),
1520 2 : (
1521 2 : line!(),
1522 2 : TenantState::Activating(ActivatingFrom::Loading),
1523 2 : "Activating",
1524 2 : ),
1525 2 : (
1526 2 : line!(),
1527 2 : TenantState::Activating(ActivatingFrom::Attaching),
1528 2 : "Activating",
1529 2 : ),
1530 2 : (line!(), TenantState::Active, "Active"),
1531 2 : (
1532 2 : line!(),
1533 2 : TenantState::Stopping {
1534 2 : progress: utils::completion::Barrier::default(),
1535 2 : },
1536 2 : "Stopping",
1537 2 : ),
1538 2 : (
1539 2 : line!(),
1540 2 : TenantState::Broken {
1541 2 : reason: "Example".into(),
1542 2 : backtrace: "Looooong backtrace".into(),
1543 2 : },
1544 2 : "Broken",
1545 2 : ),
1546 2 : ];
1547 :
1548 16 : for (line, rendered, expected) in examples {
1549 14 : let actual: &'static str = rendered.into();
1550 14 : assert_eq!(actual, expected, "example on {line}");
1551 : }
1552 2 : }
1553 :
1554 : #[test]
1555 2 : fn test_aux_file_migration_path() {
1556 2 : assert!(AuxFilePolicy::is_valid_migration_path(
1557 2 : None,
1558 2 : AuxFilePolicy::V1
1559 2 : ));
1560 2 : assert!(AuxFilePolicy::is_valid_migration_path(
1561 2 : None,
1562 2 : AuxFilePolicy::V2
1563 2 : ));
1564 2 : assert!(AuxFilePolicy::is_valid_migration_path(
1565 2 : None,
1566 2 : AuxFilePolicy::CrossValidation
1567 2 : ));
1568 : // Self-migration is not a valid migration path, and the caller should handle it by itself.
1569 2 : assert!(!AuxFilePolicy::is_valid_migration_path(
1570 2 : Some(AuxFilePolicy::V1),
1571 2 : AuxFilePolicy::V1
1572 2 : ));
1573 2 : assert!(!AuxFilePolicy::is_valid_migration_path(
1574 2 : Some(AuxFilePolicy::V2),
1575 2 : AuxFilePolicy::V2
1576 2 : ));
1577 2 : assert!(!AuxFilePolicy::is_valid_migration_path(
1578 2 : Some(AuxFilePolicy::CrossValidation),
1579 2 : AuxFilePolicy::CrossValidation
1580 2 : ));
1581 : // Migrations not allowed
1582 2 : assert!(!AuxFilePolicy::is_valid_migration_path(
1583 2 : Some(AuxFilePolicy::CrossValidation),
1584 2 : AuxFilePolicy::V1
1585 2 : ));
1586 2 : assert!(!AuxFilePolicy::is_valid_migration_path(
1587 2 : Some(AuxFilePolicy::V1),
1588 2 : AuxFilePolicy::V2
1589 2 : ));
1590 2 : assert!(!AuxFilePolicy::is_valid_migration_path(
1591 2 : Some(AuxFilePolicy::V2),
1592 2 : AuxFilePolicy::V1
1593 2 : ));
1594 2 : assert!(!AuxFilePolicy::is_valid_migration_path(
1595 2 : Some(AuxFilePolicy::V2),
1596 2 : AuxFilePolicy::CrossValidation
1597 2 : ));
1598 2 : assert!(!AuxFilePolicy::is_valid_migration_path(
1599 2 : Some(AuxFilePolicy::V1),
1600 2 : AuxFilePolicy::CrossValidation
1601 2 : ));
1602 : // Migrations allowed
1603 2 : assert!(AuxFilePolicy::is_valid_migration_path(
1604 2 : Some(AuxFilePolicy::CrossValidation),
1605 2 : AuxFilePolicy::V2
1606 2 : ));
1607 2 : }
1608 :
1609 : #[test]
1610 2 : fn test_aux_parse() {
1611 2 : assert_eq!(AuxFilePolicy::from_str("V2").unwrap(), AuxFilePolicy::V2);
1612 2 : assert_eq!(AuxFilePolicy::from_str("v2").unwrap(), AuxFilePolicy::V2);
1613 2 : assert_eq!(
1614 2 : AuxFilePolicy::from_str("cross-validation").unwrap(),
1615 2 : AuxFilePolicy::CrossValidation
1616 2 : );
1617 2 : }
1618 :
1619 : #[test]
1620 2 : fn test_image_compression_algorithm_parsing() {
1621 2 : use ImageCompressionAlgorithm::*;
1622 2 : assert_eq!(
1623 2 : ImageCompressionAlgorithm::from_str("disabled").unwrap(),
1624 2 : Disabled
1625 2 : );
1626 2 : assert_eq!(
1627 2 : ImageCompressionAlgorithm::from_str("zstd").unwrap(),
1628 2 : Zstd { level: None }
1629 2 : );
1630 2 : assert_eq!(
1631 2 : ImageCompressionAlgorithm::from_str("zstd(18)").unwrap(),
1632 2 : Zstd { level: Some(18) }
1633 2 : );
1634 2 : assert_eq!(
1635 2 : ImageCompressionAlgorithm::from_str("zstd(-3)").unwrap(),
1636 2 : Zstd { level: Some(-3) }
1637 2 : );
1638 2 : }
1639 : }
|