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 : #[serde(skip_serializing_if = "Option::is_none")]
629 : pub generation: Option<u32>,
630 : }
631 :
632 0 : #[derive(Serialize, Deserialize, Clone)]
633 : pub struct TenantDetails {
634 : #[serde(flatten)]
635 : pub tenant_info: TenantInfo,
636 :
637 : pub walredo: Option<WalRedoManagerStatus>,
638 :
639 : pub timelines: Vec<TimelineId>,
640 : }
641 :
642 : /// This represents the output of the "timeline_detail" and "timeline_list" API calls.
643 0 : #[derive(Debug, Serialize, Deserialize, Clone)]
644 : pub struct TimelineInfo {
645 : pub tenant_id: TenantShardId,
646 : pub timeline_id: TimelineId,
647 :
648 : pub ancestor_timeline_id: Option<TimelineId>,
649 : pub ancestor_lsn: Option<Lsn>,
650 : pub last_record_lsn: Lsn,
651 : pub prev_record_lsn: Option<Lsn>,
652 : pub latest_gc_cutoff_lsn: Lsn,
653 : pub disk_consistent_lsn: Lsn,
654 :
655 : /// The LSN that we have succesfully uploaded to remote storage
656 : pub remote_consistent_lsn: Lsn,
657 :
658 : /// The LSN that we are advertizing to safekeepers
659 : pub remote_consistent_lsn_visible: Lsn,
660 :
661 : /// The LSN from the start of the root timeline (never changes)
662 : pub initdb_lsn: Lsn,
663 :
664 : pub current_logical_size: u64,
665 : pub current_logical_size_is_accurate: bool,
666 :
667 : pub directory_entries_counts: Vec<u64>,
668 :
669 : /// Sum of the size of all layer files.
670 : /// If a layer is present in both local FS and S3, it counts only once.
671 : pub current_physical_size: Option<u64>, // is None when timeline is Unloaded
672 : pub current_logical_size_non_incremental: Option<u64>,
673 :
674 : pub timeline_dir_layer_file_size_sum: Option<u64>,
675 :
676 : pub wal_source_connstr: Option<String>,
677 : pub last_received_msg_lsn: Option<Lsn>,
678 : /// the timestamp (in microseconds) of the last received message
679 : pub last_received_msg_ts: Option<u128>,
680 : pub pg_version: u32,
681 :
682 : pub state: TimelineState,
683 :
684 : pub walreceiver_status: String,
685 :
686 : /// The last aux file policy being used on this timeline
687 : pub last_aux_file_policy: Option<AuxFilePolicy>,
688 : }
689 :
690 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
691 : pub struct LayerMapInfo {
692 : pub in_memory_layers: Vec<InMemoryLayerInfo>,
693 : pub historic_layers: Vec<HistoricLayerInfo>,
694 : }
695 :
696 0 : #[derive(Debug, Hash, PartialEq, Eq, Clone, Copy, Serialize, Deserialize, enum_map::Enum)]
697 : #[repr(usize)]
698 : pub enum LayerAccessKind {
699 : GetValueReconstructData,
700 : Iter,
701 : KeyIter,
702 : Dump,
703 : }
704 :
705 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
706 : pub struct LayerAccessStatFullDetails {
707 : pub when_millis_since_epoch: u64,
708 : pub task_kind: Cow<'static, str>,
709 : pub access_kind: LayerAccessKind,
710 : }
711 :
712 : /// An event that impacts the layer's residence status.
713 : #[serde_as]
714 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
715 : pub struct LayerResidenceEvent {
716 : /// The time when the event occurred.
717 : /// NB: this timestamp is captured while the residence status changes.
718 : /// So, it might be behind/ahead of the actual residence change by a short amount of time.
719 : ///
720 : #[serde(rename = "timestamp_millis_since_epoch")]
721 : #[serde_as(as = "serde_with::TimestampMilliSeconds")]
722 : pub timestamp: SystemTime,
723 : /// The new residence status of the layer.
724 : pub status: LayerResidenceStatus,
725 : /// The reason why we had to record this event.
726 : pub reason: LayerResidenceEventReason,
727 : }
728 :
729 : /// The reason for recording a given [`LayerResidenceEvent`].
730 0 : #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
731 : pub enum LayerResidenceEventReason {
732 : /// The layer map is being populated, e.g. during timeline load or attach.
733 : /// This includes [`RemoteLayer`] objects created in [`reconcile_with_remote`].
734 : /// We need to record such events because there is no persistent storage for the events.
735 : ///
736 : // https://github.com/rust-lang/rust/issues/74481
737 : /// [`RemoteLayer`]: ../../tenant/storage_layer/struct.RemoteLayer.html
738 : /// [`reconcile_with_remote`]: ../../tenant/struct.Timeline.html#method.reconcile_with_remote
739 : LayerLoad,
740 : /// We just created the layer (e.g., freeze_and_flush or compaction).
741 : /// Such layers are always [`LayerResidenceStatus::Resident`].
742 : LayerCreate,
743 : /// We on-demand downloaded or evicted the given layer.
744 : ResidenceChange,
745 : }
746 :
747 : /// The residence status of the layer, after the given [`LayerResidenceEvent`].
748 0 : #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
749 : pub enum LayerResidenceStatus {
750 : /// Residence status for a layer file that exists locally.
751 : /// It may also exist on the remote, we don't care here.
752 : Resident,
753 : /// Residence status for a layer file that only exists on the remote.
754 : Evicted,
755 : }
756 :
757 : impl LayerResidenceEvent {
758 3224 : pub fn new(status: LayerResidenceStatus, reason: LayerResidenceEventReason) -> Self {
759 3224 : Self {
760 3224 : status,
761 3224 : reason,
762 3224 : timestamp: SystemTime::now(),
763 3224 : }
764 3224 : }
765 : }
766 :
767 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
768 : pub struct LayerAccessStats {
769 : pub access_count_by_access_kind: HashMap<LayerAccessKind, u64>,
770 : pub task_kind_access_flag: Vec<Cow<'static, str>>,
771 : pub first: Option<LayerAccessStatFullDetails>,
772 : pub accesses_history: HistoryBufferWithDropCounter<LayerAccessStatFullDetails, 16>,
773 : pub residence_events_history: HistoryBufferWithDropCounter<LayerResidenceEvent, 16>,
774 : }
775 :
776 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
777 : #[serde(tag = "kind")]
778 : pub enum InMemoryLayerInfo {
779 : Open { lsn_start: Lsn },
780 : Frozen { lsn_start: Lsn, lsn_end: Lsn },
781 : }
782 :
783 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
784 : #[serde(tag = "kind")]
785 : pub enum HistoricLayerInfo {
786 : Delta {
787 : layer_file_name: String,
788 : layer_file_size: u64,
789 :
790 : lsn_start: Lsn,
791 : lsn_end: Lsn,
792 : remote: bool,
793 : access_stats: LayerAccessStats,
794 :
795 : l0: bool,
796 : },
797 : Image {
798 : layer_file_name: String,
799 : layer_file_size: u64,
800 :
801 : lsn_start: Lsn,
802 : remote: bool,
803 : access_stats: LayerAccessStats,
804 : },
805 : }
806 :
807 : impl HistoricLayerInfo {
808 0 : pub fn layer_file_name(&self) -> &str {
809 0 : match self {
810 : HistoricLayerInfo::Delta {
811 0 : layer_file_name, ..
812 0 : } => layer_file_name,
813 : HistoricLayerInfo::Image {
814 0 : layer_file_name, ..
815 0 : } => layer_file_name,
816 : }
817 0 : }
818 0 : pub fn is_remote(&self) -> bool {
819 0 : match self {
820 0 : HistoricLayerInfo::Delta { remote, .. } => *remote,
821 0 : HistoricLayerInfo::Image { remote, .. } => *remote,
822 : }
823 0 : }
824 0 : pub fn set_remote(&mut self, value: bool) {
825 0 : let field = match self {
826 0 : HistoricLayerInfo::Delta { remote, .. } => remote,
827 0 : HistoricLayerInfo::Image { remote, .. } => remote,
828 : };
829 0 : *field = value;
830 0 : }
831 0 : pub fn layer_file_size(&self) -> u64 {
832 0 : match self {
833 : HistoricLayerInfo::Delta {
834 0 : layer_file_size, ..
835 0 : } => *layer_file_size,
836 : HistoricLayerInfo::Image {
837 0 : layer_file_size, ..
838 0 : } => *layer_file_size,
839 : }
840 0 : }
841 : }
842 :
843 0 : #[derive(Debug, Serialize, Deserialize)]
844 : pub struct DownloadRemoteLayersTaskSpawnRequest {
845 : pub max_concurrent_downloads: NonZeroUsize,
846 : }
847 :
848 0 : #[derive(Debug, Serialize, Deserialize)]
849 : pub struct IngestAuxFilesRequest {
850 : pub aux_files: HashMap<String, String>,
851 : }
852 :
853 0 : #[derive(Debug, Serialize, Deserialize)]
854 : pub struct ListAuxFilesRequest {
855 : pub lsn: Lsn,
856 : }
857 :
858 0 : #[derive(Debug, Serialize, Deserialize, Clone)]
859 : pub struct DownloadRemoteLayersTaskInfo {
860 : pub task_id: String,
861 : pub state: DownloadRemoteLayersTaskState,
862 : pub total_layer_count: u64, // stable once `completed`
863 : pub successful_download_count: u64, // stable once `completed`
864 : pub failed_download_count: u64, // stable once `completed`
865 : }
866 :
867 0 : #[derive(Debug, Serialize, Deserialize, Clone)]
868 : pub enum DownloadRemoteLayersTaskState {
869 : Running,
870 : Completed,
871 : ShutDown,
872 : }
873 :
874 0 : #[derive(Debug, Serialize, Deserialize)]
875 : pub struct TimelineGcRequest {
876 : pub gc_horizon: Option<u64>,
877 : }
878 :
879 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
880 : pub struct WalRedoManagerProcessStatus {
881 : pub pid: u32,
882 : }
883 :
884 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
885 : pub struct WalRedoManagerStatus {
886 : pub last_redo_at: Option<chrono::DateTime<chrono::Utc>>,
887 : pub process: Option<WalRedoManagerProcessStatus>,
888 : }
889 :
890 : /// The progress of a secondary tenant is mostly useful when doing a long running download: e.g. initiating
891 : /// a download job, timing out while waiting for it to run, and then inspecting this status to understand
892 : /// what's happening.
893 0 : #[derive(Default, Debug, Serialize, Deserialize, Clone)]
894 : pub struct SecondaryProgress {
895 : /// The remote storage LastModified time of the heatmap object we last downloaded.
896 : pub heatmap_mtime: Option<serde_system_time::SystemTime>,
897 :
898 : /// The number of layers currently on-disk
899 : pub layers_downloaded: usize,
900 : /// The number of layers in the most recently seen heatmap
901 : pub layers_total: usize,
902 :
903 : /// The number of layer bytes currently on-disk
904 : pub bytes_downloaded: u64,
905 : /// The number of layer bytes in the most recently seen heatmap
906 : pub bytes_total: u64,
907 : }
908 :
909 0 : #[derive(Serialize, Deserialize, Debug)]
910 : pub struct TenantScanRemoteStorageShard {
911 : pub tenant_shard_id: TenantShardId,
912 : pub generation: Option<u32>,
913 : }
914 :
915 0 : #[derive(Serialize, Deserialize, Debug, Default)]
916 : pub struct TenantScanRemoteStorageResponse {
917 : pub shards: Vec<TenantScanRemoteStorageShard>,
918 : }
919 :
920 0 : #[derive(Serialize, Deserialize, Debug, Clone)]
921 : #[serde(rename_all = "snake_case")]
922 : pub enum TenantSorting {
923 : ResidentSize,
924 : MaxLogicalSize,
925 : }
926 :
927 : impl Default for TenantSorting {
928 0 : fn default() -> Self {
929 0 : Self::ResidentSize
930 0 : }
931 : }
932 :
933 0 : #[derive(Serialize, Deserialize, Debug, Clone)]
934 : pub struct TopTenantShardsRequest {
935 : // How would you like to sort the tenants?
936 : pub order_by: TenantSorting,
937 :
938 : // How many results?
939 : pub limit: usize,
940 :
941 : // Omit tenants with more than this many shards (e.g. if this is the max number of shards
942 : // that the caller would ever split to)
943 : pub where_shards_lt: Option<ShardCount>,
944 :
945 : // Omit tenants where the ordering metric is less than this (this is an optimization to
946 : // let us quickly exclude numerous tiny shards)
947 : pub where_gt: Option<u64>,
948 : }
949 :
950 0 : #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
951 : pub struct TopTenantShardItem {
952 : pub id: TenantShardId,
953 :
954 : /// Total size of layers on local disk for all timelines in this tenant
955 : pub resident_size: u64,
956 :
957 : /// Total size of layers in remote storage for all timelines in this tenant
958 : pub physical_size: u64,
959 :
960 : /// The largest logical size of a timeline within this tenant
961 : pub max_logical_size: u64,
962 : }
963 :
964 0 : #[derive(Serialize, Deserialize, Debug, Default)]
965 : pub struct TopTenantShardsResponse {
966 : pub shards: Vec<TopTenantShardItem>,
967 : }
968 :
969 : pub mod virtual_file {
970 : #[derive(
971 : Copy,
972 : Clone,
973 : PartialEq,
974 : Eq,
975 : Hash,
976 354 : strum_macros::EnumString,
977 0 : strum_macros::Display,
978 0 : serde_with::DeserializeFromStr,
979 : serde_with::SerializeDisplay,
980 : Debug,
981 : )]
982 : #[strum(serialize_all = "kebab-case")]
983 : pub enum IoEngineKind {
984 : StdFs,
985 : #[cfg(target_os = "linux")]
986 : TokioEpollUring,
987 : }
988 : }
989 :
990 : // Wrapped in libpq CopyData
991 : #[derive(PartialEq, Eq, Debug)]
992 : pub enum PagestreamFeMessage {
993 : Exists(PagestreamExistsRequest),
994 : Nblocks(PagestreamNblocksRequest),
995 : GetPage(PagestreamGetPageRequest),
996 : DbSize(PagestreamDbSizeRequest),
997 : GetSlruSegment(PagestreamGetSlruSegmentRequest),
998 : }
999 :
1000 : // Wrapped in libpq CopyData
1001 0 : #[derive(strum_macros::EnumProperty)]
1002 : pub enum PagestreamBeMessage {
1003 : Exists(PagestreamExistsResponse),
1004 : Nblocks(PagestreamNblocksResponse),
1005 : GetPage(PagestreamGetPageResponse),
1006 : Error(PagestreamErrorResponse),
1007 : DbSize(PagestreamDbSizeResponse),
1008 : GetSlruSegment(PagestreamGetSlruSegmentResponse),
1009 : }
1010 :
1011 : // Keep in sync with `pagestore_client.h`
1012 : #[repr(u8)]
1013 : enum PagestreamBeMessageTag {
1014 : Exists = 100,
1015 : Nblocks = 101,
1016 : GetPage = 102,
1017 : Error = 103,
1018 : DbSize = 104,
1019 : GetSlruSegment = 105,
1020 : }
1021 : impl TryFrom<u8> for PagestreamBeMessageTag {
1022 : type Error = u8;
1023 0 : fn try_from(value: u8) -> Result<Self, u8> {
1024 0 : match value {
1025 0 : 100 => Ok(PagestreamBeMessageTag::Exists),
1026 0 : 101 => Ok(PagestreamBeMessageTag::Nblocks),
1027 0 : 102 => Ok(PagestreamBeMessageTag::GetPage),
1028 0 : 103 => Ok(PagestreamBeMessageTag::Error),
1029 0 : 104 => Ok(PagestreamBeMessageTag::DbSize),
1030 0 : 105 => Ok(PagestreamBeMessageTag::GetSlruSegment),
1031 0 : _ => Err(value),
1032 : }
1033 0 : }
1034 : }
1035 :
1036 : // In the V2 protocol version, a GetPage request contains two LSN values:
1037 : //
1038 : // request_lsn: Get the page version at this point in time. Lsn::Max is a special value that means
1039 : // "get the latest version present". It's used by the primary server, which knows that no one else
1040 : // is writing WAL. 'not_modified_since' must be set to a proper value even if request_lsn is
1041 : // Lsn::Max. Standby servers use the current replay LSN as the request LSN.
1042 : //
1043 : // not_modified_since: Hint to the pageserver that the client knows that the page has not been
1044 : // modified between 'not_modified_since' and the request LSN. It's always correct to set
1045 : // 'not_modified_since equal' to 'request_lsn' (unless Lsn::Max is used as the 'request_lsn'), but
1046 : // passing an earlier LSN can speed up the request, by allowing the pageserver to process the
1047 : // request without waiting for 'request_lsn' to arrive.
1048 : //
1049 : // The legacy V1 interface contained only one LSN, and a boolean 'latest' flag. The V1 interface was
1050 : // sufficient for the primary; the 'lsn' was equivalent to the 'not_modified_since' value, and
1051 : // 'latest' was set to true. The V2 interface was added because there was no correct way for a
1052 : // standby to request a page at a particular non-latest LSN, and also include the
1053 : // 'not_modified_since' hint. That led to an awkward choice of either using an old LSN in the
1054 : // request, if the standby knows that the page hasn't been modified since, and risk getting an error
1055 : // if that LSN has fallen behind the GC horizon, or requesting the current replay LSN, which could
1056 : // require the pageserver unnecessarily to wait for the WAL to arrive up to that point. The new V2
1057 : // interface allows sending both LSNs, and let the pageserver do the right thing. There is no
1058 : // difference in the responses between V1 and V2.
1059 : //
1060 : // The Request structs below reflect the V2 interface. If V1 is used, the parse function
1061 : // maps the old format requests to the new format.
1062 : //
1063 : #[derive(Clone, Copy)]
1064 : pub enum PagestreamProtocolVersion {
1065 : V1,
1066 : V2,
1067 : }
1068 :
1069 : #[derive(Debug, PartialEq, Eq)]
1070 : pub struct PagestreamExistsRequest {
1071 : pub request_lsn: Lsn,
1072 : pub not_modified_since: Lsn,
1073 : pub rel: RelTag,
1074 : }
1075 :
1076 : #[derive(Debug, PartialEq, Eq)]
1077 : pub struct PagestreamNblocksRequest {
1078 : pub request_lsn: Lsn,
1079 : pub not_modified_since: Lsn,
1080 : pub rel: RelTag,
1081 : }
1082 :
1083 : #[derive(Debug, PartialEq, Eq)]
1084 : pub struct PagestreamGetPageRequest {
1085 : pub request_lsn: Lsn,
1086 : pub not_modified_since: Lsn,
1087 : pub rel: RelTag,
1088 : pub blkno: u32,
1089 : }
1090 :
1091 : #[derive(Debug, PartialEq, Eq)]
1092 : pub struct PagestreamDbSizeRequest {
1093 : pub request_lsn: Lsn,
1094 : pub not_modified_since: Lsn,
1095 : pub dbnode: u32,
1096 : }
1097 :
1098 : #[derive(Debug, PartialEq, Eq)]
1099 : pub struct PagestreamGetSlruSegmentRequest {
1100 : pub request_lsn: Lsn,
1101 : pub not_modified_since: Lsn,
1102 : pub kind: u8,
1103 : pub segno: u32,
1104 : }
1105 :
1106 : #[derive(Debug)]
1107 : pub struct PagestreamExistsResponse {
1108 : pub exists: bool,
1109 : }
1110 :
1111 : #[derive(Debug)]
1112 : pub struct PagestreamNblocksResponse {
1113 : pub n_blocks: u32,
1114 : }
1115 :
1116 : #[derive(Debug)]
1117 : pub struct PagestreamGetPageResponse {
1118 : pub page: Bytes,
1119 : }
1120 :
1121 : #[derive(Debug)]
1122 : pub struct PagestreamGetSlruSegmentResponse {
1123 : pub segment: Bytes,
1124 : }
1125 :
1126 : #[derive(Debug)]
1127 : pub struct PagestreamErrorResponse {
1128 : pub message: String,
1129 : }
1130 :
1131 : #[derive(Debug)]
1132 : pub struct PagestreamDbSizeResponse {
1133 : pub db_size: i64,
1134 : }
1135 :
1136 : // This is a cut-down version of TenantHistorySize from the pageserver crate, omitting fields
1137 : // that require pageserver-internal types. It is sufficient to get the total size.
1138 0 : #[derive(Serialize, Deserialize, Debug)]
1139 : pub struct TenantHistorySize {
1140 : pub id: TenantId,
1141 : /// Size is a mixture of WAL and logical size, so the unit is bytes.
1142 : ///
1143 : /// Will be none if `?inputs_only=true` was given.
1144 : pub size: Option<u64>,
1145 : }
1146 :
1147 : impl PagestreamFeMessage {
1148 : /// Serialize a compute -> pageserver message. This is currently only used in testing
1149 : /// tools. Always uses protocol version 2.
1150 8 : pub fn serialize(&self) -> Bytes {
1151 8 : let mut bytes = BytesMut::new();
1152 8 :
1153 8 : match self {
1154 2 : Self::Exists(req) => {
1155 2 : bytes.put_u8(0);
1156 2 : bytes.put_u64(req.request_lsn.0);
1157 2 : bytes.put_u64(req.not_modified_since.0);
1158 2 : bytes.put_u32(req.rel.spcnode);
1159 2 : bytes.put_u32(req.rel.dbnode);
1160 2 : bytes.put_u32(req.rel.relnode);
1161 2 : bytes.put_u8(req.rel.forknum);
1162 2 : }
1163 :
1164 2 : Self::Nblocks(req) => {
1165 2 : bytes.put_u8(1);
1166 2 : bytes.put_u64(req.request_lsn.0);
1167 2 : bytes.put_u64(req.not_modified_since.0);
1168 2 : bytes.put_u32(req.rel.spcnode);
1169 2 : bytes.put_u32(req.rel.dbnode);
1170 2 : bytes.put_u32(req.rel.relnode);
1171 2 : bytes.put_u8(req.rel.forknum);
1172 2 : }
1173 :
1174 2 : Self::GetPage(req) => {
1175 2 : bytes.put_u8(2);
1176 2 : bytes.put_u64(req.request_lsn.0);
1177 2 : bytes.put_u64(req.not_modified_since.0);
1178 2 : bytes.put_u32(req.rel.spcnode);
1179 2 : bytes.put_u32(req.rel.dbnode);
1180 2 : bytes.put_u32(req.rel.relnode);
1181 2 : bytes.put_u8(req.rel.forknum);
1182 2 : bytes.put_u32(req.blkno);
1183 2 : }
1184 :
1185 2 : Self::DbSize(req) => {
1186 2 : bytes.put_u8(3);
1187 2 : bytes.put_u64(req.request_lsn.0);
1188 2 : bytes.put_u64(req.not_modified_since.0);
1189 2 : bytes.put_u32(req.dbnode);
1190 2 : }
1191 :
1192 0 : Self::GetSlruSegment(req) => {
1193 0 : bytes.put_u8(4);
1194 0 : bytes.put_u64(req.request_lsn.0);
1195 0 : bytes.put_u64(req.not_modified_since.0);
1196 0 : bytes.put_u8(req.kind);
1197 0 : bytes.put_u32(req.segno);
1198 0 : }
1199 : }
1200 :
1201 8 : bytes.into()
1202 8 : }
1203 :
1204 8 : pub fn parse<R: std::io::Read>(
1205 8 : body: &mut R,
1206 8 : protocol_version: PagestreamProtocolVersion,
1207 8 : ) -> anyhow::Result<PagestreamFeMessage> {
1208 : // these correspond to the NeonMessageTag enum in pagestore_client.h
1209 : //
1210 : // TODO: consider using protobuf or serde bincode for less error prone
1211 : // serialization.
1212 8 : let msg_tag = body.read_u8()?;
1213 :
1214 8 : let (request_lsn, not_modified_since) = match protocol_version {
1215 : PagestreamProtocolVersion::V2 => (
1216 8 : Lsn::from(body.read_u64::<BigEndian>()?),
1217 8 : Lsn::from(body.read_u64::<BigEndian>()?),
1218 : ),
1219 : PagestreamProtocolVersion::V1 => {
1220 : // In the old protocol, each message starts with a boolean 'latest' flag,
1221 : // followed by 'lsn'. Convert that to the two LSNs, 'request_lsn' and
1222 : // 'not_modified_since', used in the new protocol version.
1223 0 : let latest = body.read_u8()? != 0;
1224 0 : let request_lsn = Lsn::from(body.read_u64::<BigEndian>()?);
1225 0 : if latest {
1226 0 : (Lsn::MAX, request_lsn) // get latest version
1227 : } else {
1228 0 : (request_lsn, request_lsn) // get version at specified LSN
1229 : }
1230 : }
1231 : };
1232 :
1233 : // The rest of the messages are the same between V1 and V2
1234 8 : match msg_tag {
1235 : 0 => Ok(PagestreamFeMessage::Exists(PagestreamExistsRequest {
1236 2 : request_lsn,
1237 2 : not_modified_since,
1238 2 : rel: RelTag {
1239 2 : spcnode: body.read_u32::<BigEndian>()?,
1240 2 : dbnode: body.read_u32::<BigEndian>()?,
1241 2 : relnode: body.read_u32::<BigEndian>()?,
1242 2 : forknum: body.read_u8()?,
1243 : },
1244 : })),
1245 : 1 => Ok(PagestreamFeMessage::Nblocks(PagestreamNblocksRequest {
1246 2 : request_lsn,
1247 2 : not_modified_since,
1248 2 : rel: RelTag {
1249 2 : spcnode: body.read_u32::<BigEndian>()?,
1250 2 : dbnode: body.read_u32::<BigEndian>()?,
1251 2 : relnode: body.read_u32::<BigEndian>()?,
1252 2 : forknum: body.read_u8()?,
1253 : },
1254 : })),
1255 : 2 => Ok(PagestreamFeMessage::GetPage(PagestreamGetPageRequest {
1256 2 : request_lsn,
1257 2 : not_modified_since,
1258 2 : rel: RelTag {
1259 2 : spcnode: body.read_u32::<BigEndian>()?,
1260 2 : dbnode: body.read_u32::<BigEndian>()?,
1261 2 : relnode: body.read_u32::<BigEndian>()?,
1262 2 : forknum: body.read_u8()?,
1263 : },
1264 2 : blkno: body.read_u32::<BigEndian>()?,
1265 : })),
1266 : 3 => Ok(PagestreamFeMessage::DbSize(PagestreamDbSizeRequest {
1267 2 : request_lsn,
1268 2 : not_modified_since,
1269 2 : dbnode: body.read_u32::<BigEndian>()?,
1270 : })),
1271 : 4 => Ok(PagestreamFeMessage::GetSlruSegment(
1272 : PagestreamGetSlruSegmentRequest {
1273 0 : request_lsn,
1274 0 : not_modified_since,
1275 0 : kind: body.read_u8()?,
1276 0 : segno: body.read_u32::<BigEndian>()?,
1277 : },
1278 : )),
1279 0 : _ => bail!("unknown smgr message tag: {:?}", msg_tag),
1280 : }
1281 8 : }
1282 : }
1283 :
1284 : impl PagestreamBeMessage {
1285 0 : pub fn serialize(&self) -> Bytes {
1286 0 : let mut bytes = BytesMut::new();
1287 0 :
1288 0 : use PagestreamBeMessageTag as Tag;
1289 0 : match self {
1290 0 : Self::Exists(resp) => {
1291 0 : bytes.put_u8(Tag::Exists as u8);
1292 0 : bytes.put_u8(resp.exists as u8);
1293 0 : }
1294 :
1295 0 : Self::Nblocks(resp) => {
1296 0 : bytes.put_u8(Tag::Nblocks as u8);
1297 0 : bytes.put_u32(resp.n_blocks);
1298 0 : }
1299 :
1300 0 : Self::GetPage(resp) => {
1301 0 : bytes.put_u8(Tag::GetPage as u8);
1302 0 : bytes.put(&resp.page[..]);
1303 0 : }
1304 :
1305 0 : Self::Error(resp) => {
1306 0 : bytes.put_u8(Tag::Error as u8);
1307 0 : bytes.put(resp.message.as_bytes());
1308 0 : bytes.put_u8(0); // null terminator
1309 0 : }
1310 0 : Self::DbSize(resp) => {
1311 0 : bytes.put_u8(Tag::DbSize as u8);
1312 0 : bytes.put_i64(resp.db_size);
1313 0 : }
1314 :
1315 0 : Self::GetSlruSegment(resp) => {
1316 0 : bytes.put_u8(Tag::GetSlruSegment as u8);
1317 0 : bytes.put_u32((resp.segment.len() / BLCKSZ as usize) as u32);
1318 0 : bytes.put(&resp.segment[..]);
1319 0 : }
1320 : }
1321 :
1322 0 : bytes.into()
1323 0 : }
1324 :
1325 0 : pub fn deserialize(buf: Bytes) -> anyhow::Result<Self> {
1326 0 : let mut buf = buf.reader();
1327 0 : let msg_tag = buf.read_u8()?;
1328 :
1329 : use PagestreamBeMessageTag as Tag;
1330 0 : let ok =
1331 0 : match Tag::try_from(msg_tag).map_err(|tag: u8| anyhow::anyhow!("invalid tag {tag}"))? {
1332 : Tag::Exists => {
1333 0 : let exists = buf.read_u8()?;
1334 0 : Self::Exists(PagestreamExistsResponse {
1335 0 : exists: exists != 0,
1336 0 : })
1337 : }
1338 : Tag::Nblocks => {
1339 0 : let n_blocks = buf.read_u32::<BigEndian>()?;
1340 0 : Self::Nblocks(PagestreamNblocksResponse { n_blocks })
1341 : }
1342 : Tag::GetPage => {
1343 0 : let mut page = vec![0; 8192]; // TODO: use MaybeUninit
1344 0 : buf.read_exact(&mut page)?;
1345 0 : PagestreamBeMessage::GetPage(PagestreamGetPageResponse { page: page.into() })
1346 : }
1347 : Tag::Error => {
1348 0 : let mut msg = Vec::new();
1349 0 : buf.read_until(0, &mut msg)?;
1350 0 : let cstring = std::ffi::CString::from_vec_with_nul(msg)?;
1351 0 : let rust_str = cstring.to_str()?;
1352 0 : PagestreamBeMessage::Error(PagestreamErrorResponse {
1353 0 : message: rust_str.to_owned(),
1354 0 : })
1355 : }
1356 : Tag::DbSize => {
1357 0 : let db_size = buf.read_i64::<BigEndian>()?;
1358 0 : Self::DbSize(PagestreamDbSizeResponse { db_size })
1359 : }
1360 : Tag::GetSlruSegment => {
1361 0 : let n_blocks = buf.read_u32::<BigEndian>()?;
1362 0 : let mut segment = vec![0; n_blocks as usize * BLCKSZ as usize];
1363 0 : buf.read_exact(&mut segment)?;
1364 0 : Self::GetSlruSegment(PagestreamGetSlruSegmentResponse {
1365 0 : segment: segment.into(),
1366 0 : })
1367 : }
1368 : };
1369 0 : let remaining = buf.into_inner();
1370 0 : if !remaining.is_empty() {
1371 0 : anyhow::bail!(
1372 0 : "remaining bytes in msg with tag={msg_tag}: {}",
1373 0 : remaining.len()
1374 0 : );
1375 0 : }
1376 0 : Ok(ok)
1377 0 : }
1378 :
1379 0 : pub fn kind(&self) -> &'static str {
1380 0 : match self {
1381 0 : Self::Exists(_) => "Exists",
1382 0 : Self::Nblocks(_) => "Nblocks",
1383 0 : Self::GetPage(_) => "GetPage",
1384 0 : Self::Error(_) => "Error",
1385 0 : Self::DbSize(_) => "DbSize",
1386 0 : Self::GetSlruSegment(_) => "GetSlruSegment",
1387 : }
1388 0 : }
1389 : }
1390 :
1391 : #[cfg(test)]
1392 : mod tests {
1393 : use serde_json::json;
1394 : use std::str::FromStr;
1395 :
1396 : use super::*;
1397 :
1398 : #[test]
1399 2 : fn test_pagestream() {
1400 2 : // Test serialization/deserialization of PagestreamFeMessage
1401 2 : let messages = vec![
1402 2 : PagestreamFeMessage::Exists(PagestreamExistsRequest {
1403 2 : request_lsn: Lsn(4),
1404 2 : not_modified_since: Lsn(3),
1405 2 : rel: RelTag {
1406 2 : forknum: 1,
1407 2 : spcnode: 2,
1408 2 : dbnode: 3,
1409 2 : relnode: 4,
1410 2 : },
1411 2 : }),
1412 2 : PagestreamFeMessage::Nblocks(PagestreamNblocksRequest {
1413 2 : request_lsn: Lsn(4),
1414 2 : not_modified_since: Lsn(4),
1415 2 : rel: RelTag {
1416 2 : forknum: 1,
1417 2 : spcnode: 2,
1418 2 : dbnode: 3,
1419 2 : relnode: 4,
1420 2 : },
1421 2 : }),
1422 2 : PagestreamFeMessage::GetPage(PagestreamGetPageRequest {
1423 2 : request_lsn: Lsn(4),
1424 2 : not_modified_since: Lsn(3),
1425 2 : rel: RelTag {
1426 2 : forknum: 1,
1427 2 : spcnode: 2,
1428 2 : dbnode: 3,
1429 2 : relnode: 4,
1430 2 : },
1431 2 : blkno: 7,
1432 2 : }),
1433 2 : PagestreamFeMessage::DbSize(PagestreamDbSizeRequest {
1434 2 : request_lsn: Lsn(4),
1435 2 : not_modified_since: Lsn(3),
1436 2 : dbnode: 7,
1437 2 : }),
1438 2 : ];
1439 10 : for msg in messages {
1440 8 : let bytes = msg.serialize();
1441 8 : let reconstructed =
1442 8 : PagestreamFeMessage::parse(&mut bytes.reader(), PagestreamProtocolVersion::V2)
1443 8 : .unwrap();
1444 8 : assert!(msg == reconstructed);
1445 : }
1446 2 : }
1447 :
1448 : #[test]
1449 2 : fn test_tenantinfo_serde() {
1450 2 : // Test serialization/deserialization of TenantInfo
1451 2 : let original_active = TenantInfo {
1452 2 : id: TenantShardId::unsharded(TenantId::generate()),
1453 2 : state: TenantState::Active,
1454 2 : current_physical_size: Some(42),
1455 2 : attachment_status: TenantAttachmentStatus::Attached,
1456 2 : generation: None,
1457 2 : };
1458 2 : let expected_active = json!({
1459 2 : "id": original_active.id.to_string(),
1460 2 : "state": {
1461 2 : "slug": "Active",
1462 2 : },
1463 2 : "current_physical_size": 42,
1464 2 : "attachment_status": {
1465 2 : "slug":"attached",
1466 2 : }
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: None,
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 : });
1493 2 :
1494 2 : assert_eq!(
1495 2 : serde_json::to_value(&original_active).unwrap(),
1496 2 : expected_active
1497 2 : );
1498 :
1499 2 : assert_eq!(
1500 2 : serde_json::to_value(&original_broken).unwrap(),
1501 2 : expected_broken
1502 2 : );
1503 2 : assert!(format!("{:?}", &original_broken.state).contains("reason"));
1504 2 : assert!(format!("{:?}", &original_broken.state).contains("backtrace info"));
1505 2 : }
1506 :
1507 : #[test]
1508 2 : fn test_reject_unknown_field() {
1509 2 : let id = TenantId::generate();
1510 2 : let create_request = json!({
1511 2 : "new_tenant_id": id.to_string(),
1512 2 : "unknown_field": "unknown_value".to_string(),
1513 2 : });
1514 2 : let err = serde_json::from_value::<TenantCreateRequest>(create_request).unwrap_err();
1515 2 : assert!(
1516 2 : err.to_string().contains("unknown field `unknown_field`"),
1517 0 : "expect unknown field `unknown_field` error, got: {}",
1518 : err
1519 : );
1520 :
1521 2 : let id = TenantId::generate();
1522 2 : let config_request = json!({
1523 2 : "tenant_id": id.to_string(),
1524 2 : "unknown_field": "unknown_value".to_string(),
1525 2 : });
1526 2 : let err = serde_json::from_value::<TenantConfigRequest>(config_request).unwrap_err();
1527 2 : assert!(
1528 2 : err.to_string().contains("unknown field `unknown_field`"),
1529 0 : "expect unknown field `unknown_field` error, got: {}",
1530 : err
1531 : );
1532 2 : }
1533 :
1534 : #[test]
1535 2 : fn tenantstatus_activating_serde() {
1536 2 : let states = [
1537 2 : TenantState::Activating(ActivatingFrom::Loading),
1538 2 : TenantState::Activating(ActivatingFrom::Attaching),
1539 2 : ];
1540 2 : let expected = "[{\"slug\":\"Activating\",\"data\":\"Loading\"},{\"slug\":\"Activating\",\"data\":\"Attaching\"}]";
1541 2 :
1542 2 : let actual = serde_json::to_string(&states).unwrap();
1543 2 :
1544 2 : assert_eq!(actual, expected);
1545 :
1546 2 : let parsed = serde_json::from_str::<Vec<TenantState>>(&actual).unwrap();
1547 2 :
1548 2 : assert_eq!(states.as_slice(), &parsed);
1549 2 : }
1550 :
1551 : #[test]
1552 2 : fn tenantstatus_activating_strum() {
1553 2 : // tests added, because we use these for metrics
1554 2 : let examples = [
1555 2 : (line!(), TenantState::Loading, "Loading"),
1556 2 : (line!(), TenantState::Attaching, "Attaching"),
1557 2 : (
1558 2 : line!(),
1559 2 : TenantState::Activating(ActivatingFrom::Loading),
1560 2 : "Activating",
1561 2 : ),
1562 2 : (
1563 2 : line!(),
1564 2 : TenantState::Activating(ActivatingFrom::Attaching),
1565 2 : "Activating",
1566 2 : ),
1567 2 : (line!(), TenantState::Active, "Active"),
1568 2 : (
1569 2 : line!(),
1570 2 : TenantState::Stopping {
1571 2 : progress: utils::completion::Barrier::default(),
1572 2 : },
1573 2 : "Stopping",
1574 2 : ),
1575 2 : (
1576 2 : line!(),
1577 2 : TenantState::Broken {
1578 2 : reason: "Example".into(),
1579 2 : backtrace: "Looooong backtrace".into(),
1580 2 : },
1581 2 : "Broken",
1582 2 : ),
1583 2 : ];
1584 :
1585 16 : for (line, rendered, expected) in examples {
1586 14 : let actual: &'static str = rendered.into();
1587 14 : assert_eq!(actual, expected, "example on {line}");
1588 : }
1589 2 : }
1590 :
1591 : #[test]
1592 2 : fn test_aux_file_migration_path() {
1593 2 : assert!(AuxFilePolicy::is_valid_migration_path(
1594 2 : None,
1595 2 : AuxFilePolicy::V1
1596 2 : ));
1597 2 : assert!(AuxFilePolicy::is_valid_migration_path(
1598 2 : None,
1599 2 : AuxFilePolicy::V2
1600 2 : ));
1601 2 : assert!(AuxFilePolicy::is_valid_migration_path(
1602 2 : None,
1603 2 : AuxFilePolicy::CrossValidation
1604 2 : ));
1605 : // Self-migration is not a valid migration path, and the caller should handle it by itself.
1606 2 : assert!(!AuxFilePolicy::is_valid_migration_path(
1607 2 : Some(AuxFilePolicy::V1),
1608 2 : AuxFilePolicy::V1
1609 2 : ));
1610 2 : assert!(!AuxFilePolicy::is_valid_migration_path(
1611 2 : Some(AuxFilePolicy::V2),
1612 2 : AuxFilePolicy::V2
1613 2 : ));
1614 2 : assert!(!AuxFilePolicy::is_valid_migration_path(
1615 2 : Some(AuxFilePolicy::CrossValidation),
1616 2 : AuxFilePolicy::CrossValidation
1617 2 : ));
1618 : // Migrations not allowed
1619 2 : assert!(!AuxFilePolicy::is_valid_migration_path(
1620 2 : Some(AuxFilePolicy::CrossValidation),
1621 2 : AuxFilePolicy::V1
1622 2 : ));
1623 2 : assert!(!AuxFilePolicy::is_valid_migration_path(
1624 2 : Some(AuxFilePolicy::V1),
1625 2 : AuxFilePolicy::V2
1626 2 : ));
1627 2 : assert!(!AuxFilePolicy::is_valid_migration_path(
1628 2 : Some(AuxFilePolicy::V2),
1629 2 : AuxFilePolicy::V1
1630 2 : ));
1631 2 : assert!(!AuxFilePolicy::is_valid_migration_path(
1632 2 : Some(AuxFilePolicy::V2),
1633 2 : AuxFilePolicy::CrossValidation
1634 2 : ));
1635 2 : assert!(!AuxFilePolicy::is_valid_migration_path(
1636 2 : Some(AuxFilePolicy::V1),
1637 2 : AuxFilePolicy::CrossValidation
1638 2 : ));
1639 : // Migrations allowed
1640 2 : assert!(AuxFilePolicy::is_valid_migration_path(
1641 2 : Some(AuxFilePolicy::CrossValidation),
1642 2 : AuxFilePolicy::V2
1643 2 : ));
1644 2 : }
1645 :
1646 : #[test]
1647 2 : fn test_aux_parse() {
1648 2 : assert_eq!(AuxFilePolicy::from_str("V2").unwrap(), AuxFilePolicy::V2);
1649 2 : assert_eq!(AuxFilePolicy::from_str("v2").unwrap(), AuxFilePolicy::V2);
1650 2 : assert_eq!(
1651 2 : AuxFilePolicy::from_str("cross-validation").unwrap(),
1652 2 : AuxFilePolicy::CrossValidation
1653 2 : );
1654 2 : }
1655 : }
|