LCOV - code coverage report
Current view: top level - libs/compute_api/src - spec.rs (source / functions) Coverage Total Hit
Test: 86c536b7fe84b2afe03c3bb264199e9c319ae0f8.info Lines: 56.4 % 101 57
Test Date: 2024-06-24 16:38:41 Functions: 22.3 % 211 47

            Line data    Source code
       1              : //! `ComputeSpec` represents the contents of the spec.json file.
       2              : //!
       3              : //! The spec.json file is used to pass information to 'compute_ctl'. It contains
       4              : //! all the information needed to start up the right version of PostgreSQL,
       5              : //! and connect it to the storage nodes.
       6              : use std::collections::HashMap;
       7              : 
       8              : use serde::{Deserialize, Serialize};
       9              : use utils::id::{TenantId, TimelineId};
      10              : use utils::lsn::Lsn;
      11              : 
      12              : use regex::Regex;
      13              : use remote_storage::RemotePath;
      14              : 
      15              : /// String type alias representing Postgres identifier and
      16              : /// intended to be used for DB / role names.
      17              : pub type PgIdent = String;
      18              : 
      19              : /// Cluster spec or configuration represented as an optional number of
      20              : /// delta operations + final cluster state description.
      21          102 : #[derive(Clone, Debug, Default, Deserialize, Serialize)]
      22              : pub struct ComputeSpec {
      23              :     pub format_version: f32,
      24              : 
      25              :     // The control plane also includes a 'timestamp' field in the JSON document,
      26              :     // but we don't use it for anything. Serde will ignore missing fields when
      27              :     // deserializing it.
      28              :     pub operation_uuid: Option<String>,
      29              : 
      30              :     /// Compute features to enable. These feature flags are provided, when we
      31              :     /// know all the details about client's compute, so they cannot be used
      32              :     /// to change `Empty` compute behavior.
      33              :     #[serde(default)]
      34              :     pub features: Vec<ComputeFeature>,
      35              : 
      36              :     /// If compute_ctl was passed `--resize-swap-on-bind`, a value of `Some(_)` instructs
      37              :     /// compute_ctl to `/neonvm/bin/resize-swap` with the given size, when the spec is first
      38              :     /// received.
      39              :     ///
      40              :     /// Both this field and `--resize-swap-on-bind` are required, so that the control plane's
      41              :     /// spec generation doesn't need to be aware of the actual compute it's running on, while
      42              :     /// guaranteeing gradual rollout of swap. Otherwise, without `--resize-swap-on-bind`, we could
      43              :     /// end up trying to resize swap in VMs without it -- or end up *not* resizing swap, thus
      44              :     /// giving every VM much more swap than it should have (32GiB).
      45              :     ///
      46              :     /// Eventually we may remove `--resize-swap-on-bind` and exclusively use `swap_size_bytes` for
      47              :     /// enabling the swap resizing behavior once rollout is complete.
      48              :     ///
      49              :     /// See neondatabase/cloud#12047 for more.
      50              :     #[serde(default)]
      51              :     pub swap_size_bytes: Option<u64>,
      52              : 
      53              :     /// Expected cluster state at the end of transition process.
      54              :     pub cluster: Cluster,
      55              :     pub delta_operations: Option<Vec<DeltaOp>>,
      56              : 
      57              :     /// An optinal hint that can be passed to speed up startup time if we know
      58              :     /// that no pg catalog mutations (like role creation, database creation,
      59              :     /// extension creation) need to be done on the actual database to start.
      60              :     #[serde(default)] // Default false
      61              :     pub skip_pg_catalog_updates: bool,
      62              : 
      63              :     // Information needed to connect to the storage layer.
      64              :     //
      65              :     // `tenant_id`, `timeline_id` and `pageserver_connstring` are always needed.
      66              :     //
      67              :     // Depending on `mode`, this can be a primary read-write node, a read-only
      68              :     // replica, or a read-only node pinned at an older LSN.
      69              :     // `safekeeper_connstrings` must be set for a primary.
      70              :     //
      71              :     // For backwards compatibility, the control plane may leave out all of
      72              :     // these, and instead set the "neon.tenant_id", "neon.timeline_id",
      73              :     // etc. GUCs in cluster.settings. TODO: Once the control plane has been
      74              :     // updated to fill these fields, we can make these non optional.
      75              :     pub tenant_id: Option<TenantId>,
      76              : 
      77              :     pub timeline_id: Option<TimelineId>,
      78              : 
      79              :     pub pageserver_connstring: Option<String>,
      80              : 
      81              :     #[serde(default)]
      82              :     pub safekeeper_connstrings: Vec<String>,
      83              : 
      84              :     #[serde(default)]
      85              :     pub mode: ComputeMode,
      86              : 
      87              :     /// If set, 'storage_auth_token' is used as the password to authenticate to
      88              :     /// the pageserver and safekeepers.
      89              :     pub storage_auth_token: Option<String>,
      90              : 
      91              :     // information about available remote extensions
      92              :     pub remote_extensions: Option<RemoteExtSpec>,
      93              : 
      94              :     pub pgbouncer_settings: Option<HashMap<String, String>>,
      95              : 
      96              :     // Stripe size for pageserver sharding, in pages
      97              :     #[serde(default)]
      98              :     pub shard_stripe_size: Option<usize>,
      99              : 
     100              :     // When we are starting a new replica in hot standby mode,
     101              :     // we need to know if the primary is running.
     102              :     // This is used to determine if replica should wait for
     103              :     // RUNNING_XACTS from primary or not.
     104              :     pub primary_is_running: Option<bool>,
     105              : }
     106              : 
     107              : /// Feature flag to signal `compute_ctl` to enable certain experimental functionality.
     108           12 : #[derive(Serialize, Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
     109              : #[serde(rename_all = "snake_case")]
     110              : pub enum ComputeFeature {
     111              :     // XXX: Add more feature flags here.
     112              :     /// Enable the experimental activity monitor logic, which uses `pg_stat_database` to
     113              :     /// track short-lived connections as user activity.
     114              :     ActivityMonitorExperimental,
     115              : 
     116              :     /// Pre-install and initialize anon extension for every database in the cluster
     117              :     AnonExtension,
     118              : 
     119              :     /// This is a special feature flag that is used to represent unknown feature flags.
     120              :     /// Basically all unknown to enum flags are represented as this one. See unit test
     121              :     /// `parse_unknown_features()` for more details.
     122              :     #[serde(other)]
     123              :     UnknownFeature,
     124              : }
     125              : 
     126           60 : #[derive(Clone, Debug, Default, Deserialize, Serialize)]
     127              : pub struct RemoteExtSpec {
     128              :     pub public_extensions: Option<Vec<String>>,
     129              :     pub custom_extensions: Option<Vec<String>>,
     130              :     pub library_index: HashMap<String, String>,
     131              :     pub extension_data: HashMap<String, ExtensionData>,
     132              : }
     133              : 
     134           72 : #[derive(Clone, Debug, Serialize, Deserialize)]
     135              : pub struct ExtensionData {
     136              :     pub control_data: HashMap<String, String>,
     137              :     pub archive_path: String,
     138              : }
     139              : 
     140              : impl RemoteExtSpec {
     141            0 :     pub fn get_ext(
     142            0 :         &self,
     143            0 :         ext_name: &str,
     144            0 :         is_library: bool,
     145            0 :         build_tag: &str,
     146            0 :         pg_major_version: &str,
     147            0 :     ) -> anyhow::Result<(String, RemotePath)> {
     148            0 :         let mut real_ext_name = ext_name;
     149            0 :         if is_library {
     150              :             // sometimes library names might have a suffix like
     151              :             // library.so or library.so.3. We strip this off
     152              :             // because library_index is based on the name without the file extension
     153            0 :             let strip_lib_suffix = Regex::new(r"\.so.*").unwrap();
     154            0 :             let lib_raw_name = strip_lib_suffix.replace(real_ext_name, "").to_string();
     155            0 : 
     156            0 :             real_ext_name = self
     157            0 :                 .library_index
     158            0 :                 .get(&lib_raw_name)
     159            0 :                 .ok_or(anyhow::anyhow!("library {} is not found", lib_raw_name))?;
     160            0 :         }
     161              : 
     162              :         // Check if extension is present in public or custom.
     163              :         // If not, then it is not allowed to be used by this compute.
     164            0 :         if let Some(public_extensions) = &self.public_extensions {
     165            0 :             if !public_extensions.contains(&real_ext_name.to_string()) {
     166            0 :                 if let Some(custom_extensions) = &self.custom_extensions {
     167            0 :                     if !custom_extensions.contains(&real_ext_name.to_string()) {
     168            0 :                         return Err(anyhow::anyhow!("extension {} is not found", real_ext_name));
     169            0 :                     }
     170            0 :                 }
     171            0 :             }
     172            0 :         }
     173              : 
     174            0 :         match self.extension_data.get(real_ext_name) {
     175            0 :             Some(_ext_data) => {
     176            0 :                 // Construct the path to the extension archive
     177            0 :                 // BUILD_TAG/PG_MAJOR_VERSION/extensions/EXTENSION_NAME.tar.zst
     178            0 :                 //
     179            0 :                 // Keep it in sync with path generation in
     180            0 :                 // https://github.com/neondatabase/build-custom-extensions/tree/main
     181            0 :                 let archive_path_str =
     182            0 :                     format!("{build_tag}/{pg_major_version}/extensions/{real_ext_name}.tar.zst");
     183            0 :                 Ok((
     184            0 :                     real_ext_name.to_string(),
     185            0 :                     RemotePath::from_string(&archive_path_str)?,
     186              :                 ))
     187              :             }
     188            0 :             None => Err(anyhow::anyhow!(
     189            0 :                 "real_ext_name {} is not found",
     190            0 :                 real_ext_name
     191            0 :             )),
     192              :         }
     193            0 :     }
     194              : }
     195              : 
     196            0 : #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
     197              : pub enum ComputeMode {
     198              :     /// A read-write node
     199              :     #[default]
     200              :     Primary,
     201              :     /// A read-only node, pinned at a particular LSN
     202              :     Static(Lsn),
     203              :     /// A read-only node that follows the tip of the branch in hot standby mode
     204              :     ///
     205              :     /// Future versions may want to distinguish between replicas with hot standby
     206              :     /// feedback and other kinds of replication configurations.
     207              :     Replica,
     208              : }
     209              : 
     210           84 : #[derive(Clone, Debug, Default, Deserialize, Serialize)]
     211              : pub struct Cluster {
     212              :     pub cluster_id: Option<String>,
     213              :     pub name: Option<String>,
     214              :     pub state: Option<String>,
     215              :     pub roles: Vec<Role>,
     216              :     pub databases: Vec<Database>,
     217              : 
     218              :     /// Desired contents of 'postgresql.conf' file. (The 'compute_ctl'
     219              :     /// tool may add additional settings to the final file.)
     220              :     pub postgresql_conf: Option<String>,
     221              : 
     222              :     /// Additional settings that will be appended to the 'postgresql.conf' file.
     223              :     pub settings: GenericOptions,
     224              : }
     225              : 
     226              : /// Single cluster state changing operation that could not be represented as
     227              : /// a static `Cluster` structure. For example:
     228              : /// - DROP DATABASE
     229              : /// - DROP ROLE
     230              : /// - ALTER ROLE name RENAME TO new_name
     231              : /// - ALTER DATABASE name RENAME TO new_name
     232          168 : #[derive(Clone, Debug, Deserialize, Serialize)]
     233              : pub struct DeltaOp {
     234              :     pub action: String,
     235              :     pub name: PgIdent,
     236              :     pub new_name: Option<PgIdent>,
     237              : }
     238              : 
     239              : /// Rust representation of Postgres role info with only those fields
     240              : /// that matter for us.
     241          252 : #[derive(Clone, Debug, Deserialize, Serialize)]
     242              : pub struct Role {
     243              :     pub name: PgIdent,
     244              :     pub encrypted_password: Option<String>,
     245              :     pub options: GenericOptions,
     246              : }
     247              : 
     248              : /// Rust representation of Postgres database info with only those fields
     249              : /// that matter for us.
     250          120 : #[derive(Clone, Debug, Deserialize, Serialize)]
     251              : pub struct Database {
     252              :     pub name: PgIdent,
     253              :     pub owner: PgIdent,
     254              :     pub options: GenericOptions,
     255              :     // These are derived flags, not present in the spec file.
     256              :     // They are never set by the control plane.
     257              :     #[serde(skip_deserializing, default)]
     258              :     pub restrict_conn: bool,
     259              :     #[serde(skip_deserializing, default)]
     260              :     pub invalid: bool,
     261              : }
     262              : 
     263              : /// Common type representing both SQL statement params with or without value,
     264              : /// like `LOGIN` or `OWNER username` in the `CREATE/ALTER ROLE`, and config
     265              : /// options like `wal_level = logical`.
     266         1248 : #[derive(Clone, Debug, Deserialize, Serialize)]
     267              : pub struct GenericOption {
     268              :     pub name: String,
     269              :     pub value: Option<String>,
     270              :     pub vartype: String,
     271              : }
     272              : 
     273              : /// Optional collection of `GenericOption`'s. Type alias allows us to
     274              : /// declare a `trait` on it.
     275              : pub type GenericOptions = Option<Vec<GenericOption>>;
     276              : 
     277              : #[cfg(test)]
     278              : mod tests {
     279              :     use super::*;
     280              :     use std::fs::File;
     281              : 
     282              :     #[test]
     283            2 :     fn parse_spec_file() {
     284            2 :         let file = File::open("tests/cluster_spec.json").unwrap();
     285            2 :         let spec: ComputeSpec = serde_json::from_reader(file).unwrap();
     286            2 : 
     287            2 :         // Features list defaults to empty vector.
     288            2 :         assert!(spec.features.is_empty());
     289            2 :     }
     290              : 
     291              :     #[test]
     292            2 :     fn parse_unknown_fields() {
     293            2 :         // Forward compatibility test
     294            2 :         let file = File::open("tests/cluster_spec.json").unwrap();
     295            2 :         let mut json: serde_json::Value = serde_json::from_reader(file).unwrap();
     296            2 :         let ob = json.as_object_mut().unwrap();
     297            2 :         ob.insert("unknown_field_123123123".into(), "hello".into());
     298            2 :         let _spec: ComputeSpec = serde_json::from_value(json).unwrap();
     299            2 :     }
     300              : 
     301              :     #[test]
     302            2 :     fn parse_unknown_features() {
     303            2 :         // Test that unknown feature flags do not cause any errors.
     304            2 :         let file = File::open("tests/cluster_spec.json").unwrap();
     305            2 :         let mut json: serde_json::Value = serde_json::from_reader(file).unwrap();
     306            2 :         let ob = json.as_object_mut().unwrap();
     307            2 : 
     308            2 :         // Add unknown feature flags.
     309            2 :         let features = vec!["foo_bar_feature", "baz_feature"];
     310            2 :         ob.insert("features".into(), features.into());
     311            2 : 
     312            2 :         let spec: ComputeSpec = serde_json::from_value(json).unwrap();
     313            2 : 
     314            2 :         assert!(spec.features.len() == 2);
     315            2 :         assert!(spec.features.contains(&ComputeFeature::UnknownFeature));
     316            2 :         assert_eq!(spec.features, vec![ComputeFeature::UnknownFeature; 2]);
     317            2 :     }
     318              : 
     319              :     #[test]
     320            2 :     fn parse_known_features() {
     321            2 :         // Test that we can properly parse known feature flags.
     322            2 :         let file = File::open("tests/cluster_spec.json").unwrap();
     323            2 :         let mut json: serde_json::Value = serde_json::from_reader(file).unwrap();
     324            2 :         let ob = json.as_object_mut().unwrap();
     325            2 : 
     326            2 :         // Add known feature flags.
     327            2 :         let features = vec!["activity_monitor_experimental"];
     328            2 :         ob.insert("features".into(), features.into());
     329            2 : 
     330            2 :         let spec: ComputeSpec = serde_json::from_value(json).unwrap();
     331            2 : 
     332            2 :         assert_eq!(
     333            2 :             spec.features,
     334            2 :             vec![ComputeFeature::ActivityMonitorExperimental]
     335            2 :         );
     336            2 :     }
     337              : }
        

Generated by: LCOV version 2.1-beta