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