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