LCOV - code coverage report
Current view: top level - libs/compute_api/src - spec.rs (source / functions) Coverage Total Hit
Test: 07bee600374ccd486c69370d0972d9035964fe68.info Lines: 96.6 % 203 196
Test Date: 2025-02-20 13:11:02 Functions: 11.3 % 247 28

            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              : /// String type alias representing Postgres extension version
      20              : pub type ExtVersion = String;
      21              : 
      22            6 : fn default_reconfigure_concurrency() -> usize {
      23            6 :     1
      24            6 : }
      25              : 
      26              : /// Cluster spec or configuration represented as an optional number of
      27              : /// delta operations + final cluster state description.
      28           45 : #[derive(Clone, Debug, Default, Deserialize, Serialize)]
      29              : pub struct ComputeSpec {
      30              :     pub format_version: f32,
      31              : 
      32              :     // The control plane also includes a 'timestamp' field in the JSON document,
      33              :     // but we don't use it for anything. Serde will ignore missing fields when
      34              :     // deserializing it.
      35              :     pub operation_uuid: Option<String>,
      36              : 
      37              :     /// Compute features to enable. These feature flags are provided, when we
      38              :     /// know all the details about client's compute, so they cannot be used
      39              :     /// to change `Empty` compute behavior.
      40              :     #[serde(default)]
      41              :     pub features: Vec<ComputeFeature>,
      42              : 
      43              :     /// If compute_ctl was passed `--resize-swap-on-bind`, a value of `Some(_)` instructs
      44              :     /// compute_ctl to `/neonvm/bin/resize-swap` with the given size, when the spec is first
      45              :     /// received.
      46              :     ///
      47              :     /// Both this field and `--resize-swap-on-bind` are required, so that the control plane's
      48              :     /// spec generation doesn't need to be aware of the actual compute it's running on, while
      49              :     /// guaranteeing gradual rollout of swap. Otherwise, without `--resize-swap-on-bind`, we could
      50              :     /// end up trying to resize swap in VMs without it -- or end up *not* resizing swap, thus
      51              :     /// giving every VM much more swap than it should have (32GiB).
      52              :     ///
      53              :     /// Eventually we may remove `--resize-swap-on-bind` and exclusively use `swap_size_bytes` for
      54              :     /// enabling the swap resizing behavior once rollout is complete.
      55              :     ///
      56              :     /// See neondatabase/cloud#12047 for more.
      57              :     #[serde(default)]
      58              :     pub swap_size_bytes: Option<u64>,
      59              : 
      60              :     /// If compute_ctl was passed `--set-disk-quota-for-fs`, a value of `Some(_)` instructs
      61              :     /// compute_ctl to run `/neonvm/bin/set-disk-quota` with the given size and fs, when the
      62              :     /// spec is first received.
      63              :     ///
      64              :     /// Both this field and `--set-disk-quota-for-fs` are required, so that the control plane's
      65              :     /// spec generation doesn't need to be aware of the actual compute it's running on, while
      66              :     /// guaranteeing gradual rollout of disk quota.
      67              :     #[serde(default)]
      68              :     pub disk_quota_bytes: Option<u64>,
      69              : 
      70              :     /// Disables the vm-monitor behavior that resizes LFC on upscale/downscale, instead relying on
      71              :     /// the initial size of LFC.
      72              :     ///
      73              :     /// This is intended for use when the LFC size is being overridden from the default but
      74              :     /// autoscaling is still enabled, and we don't want the vm-monitor to interfere with the custom
      75              :     /// LFC sizing.
      76              :     #[serde(default)]
      77              :     pub disable_lfc_resizing: Option<bool>,
      78              : 
      79              :     /// Expected cluster state at the end of transition process.
      80              :     pub cluster: Cluster,
      81              :     pub delta_operations: Option<Vec<DeltaOp>>,
      82              : 
      83              :     /// An optional hint that can be passed to speed up startup time if we know
      84              :     /// that no pg catalog mutations (like role creation, database creation,
      85              :     /// extension creation) need to be done on the actual database to start.
      86              :     #[serde(default)] // Default false
      87              :     pub skip_pg_catalog_updates: bool,
      88              : 
      89              :     // Information needed to connect to the storage layer.
      90              :     //
      91              :     // `tenant_id`, `timeline_id` and `pageserver_connstring` are always needed.
      92              :     //
      93              :     // Depending on `mode`, this can be a primary read-write node, a read-only
      94              :     // replica, or a read-only node pinned at an older LSN.
      95              :     // `safekeeper_connstrings` must be set for a primary.
      96              :     //
      97              :     // For backwards compatibility, the control plane may leave out all of
      98              :     // these, and instead set the "neon.tenant_id", "neon.timeline_id",
      99              :     // etc. GUCs in cluster.settings. TODO: Once the control plane has been
     100              :     // updated to fill these fields, we can make these non optional.
     101              :     pub tenant_id: Option<TenantId>,
     102              :     pub timeline_id: Option<TimelineId>,
     103              :     pub pageserver_connstring: Option<String>,
     104              : 
     105              :     #[serde(default)]
     106              :     pub safekeeper_connstrings: Vec<String>,
     107              : 
     108              :     #[serde(default)]
     109              :     pub mode: ComputeMode,
     110              : 
     111              :     /// If set, 'storage_auth_token' is used as the password to authenticate to
     112              :     /// the pageserver and safekeepers.
     113              :     pub storage_auth_token: Option<String>,
     114              : 
     115              :     // information about available remote extensions
     116              :     pub remote_extensions: Option<RemoteExtSpec>,
     117              : 
     118              :     pub pgbouncer_settings: Option<HashMap<String, String>>,
     119              : 
     120              :     // Stripe size for pageserver sharding, in pages
     121              :     #[serde(default)]
     122              :     pub shard_stripe_size: Option<usize>,
     123              : 
     124              :     /// Local Proxy configuration used for JWT authentication
     125              :     #[serde(default)]
     126              :     pub local_proxy_config: Option<LocalProxySpec>,
     127              : 
     128              :     /// Number of concurrent connections during the parallel RunInEachDatabase
     129              :     /// phase of the apply config process.
     130              :     ///
     131              :     /// We need a higher concurrency during reconfiguration in case of many DBs,
     132              :     /// but instance is already running and used by client. We can easily get out of
     133              :     /// `max_connections` limit, and the current code won't handle that.
     134              :     ///
     135              :     /// Default is 1, but also allow control plane to override this value for specific
     136              :     /// projects. It's also recommended to bump `superuser_reserved_connections` +=
     137              :     /// `reconfigure_concurrency` for such projects to ensure that we always have
     138              :     /// enough spare connections for reconfiguration process to succeed.
     139              :     #[serde(default = "default_reconfigure_concurrency")]
     140              :     pub reconfigure_concurrency: usize,
     141              : 
     142              :     /// If set to true, the compute_ctl will drop all subscriptions before starting the
     143              :     /// compute. This is needed when we start an endpoint on a branch, so that child
     144              :     /// would not compete with parent branch subscriptions
     145              :     /// over the same replication content from publisher.
     146              :     #[serde(default)] // Default false
     147              :     pub drop_subscriptions_before_start: bool,
     148              : }
     149              : 
     150              : /// Feature flag to signal `compute_ctl` to enable certain experimental functionality.
     151            3 : #[derive(Serialize, Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
     152              : #[serde(rename_all = "snake_case")]
     153              : pub enum ComputeFeature {
     154              :     // XXX: Add more feature flags here.
     155              :     /// Enable the experimental activity monitor logic, which uses `pg_stat_database` to
     156              :     /// track short-lived connections as user activity.
     157              :     ActivityMonitorExperimental,
     158              : 
     159              :     /// Pre-install and initialize anon extension for every database in the cluster
     160              :     AnonExtension,
     161              : 
     162              :     /// This is a special feature flag that is used to represent unknown feature flags.
     163              :     /// Basically all unknown to enum flags are represented as this one. See unit test
     164              :     /// `parse_unknown_features()` for more details.
     165              :     #[serde(other)]
     166              :     UnknownFeature,
     167              : }
     168              : 
     169           44 : #[derive(Clone, Debug, Default, Deserialize, Serialize)]
     170              : pub struct RemoteExtSpec {
     171              :     pub public_extensions: Option<Vec<String>>,
     172              :     pub custom_extensions: Option<Vec<String>>,
     173              :     pub library_index: HashMap<String, String>,
     174              :     pub extension_data: HashMap<String, ExtensionData>,
     175              : }
     176              : 
     177           30 : #[derive(Clone, Debug, Serialize, Deserialize)]
     178              : pub struct ExtensionData {
     179              :     pub control_data: HashMap<String, String>,
     180              :     pub archive_path: String,
     181              : }
     182              : 
     183              : impl RemoteExtSpec {
     184            6 :     pub fn get_ext(
     185            6 :         &self,
     186            6 :         ext_name: &str,
     187            6 :         is_library: bool,
     188            6 :         build_tag: &str,
     189            6 :         pg_major_version: &str,
     190            6 :     ) -> anyhow::Result<(String, RemotePath)> {
     191            6 :         let mut real_ext_name = ext_name;
     192            6 :         if is_library {
     193              :             // sometimes library names might have a suffix like
     194              :             // library.so or library.so.3. We strip this off
     195              :             // because library_index is based on the name without the file extension
     196            1 :             let strip_lib_suffix = Regex::new(r"\.so.*").unwrap();
     197            1 :             let lib_raw_name = strip_lib_suffix.replace(real_ext_name, "").to_string();
     198            1 : 
     199            1 :             real_ext_name = self
     200            1 :                 .library_index
     201            1 :                 .get(&lib_raw_name)
     202            1 :                 .ok_or(anyhow::anyhow!("library {} is not found", lib_raw_name))?;
     203            5 :         }
     204              : 
     205              :         // Check if extension is present in public or custom.
     206              :         // If not, then it is not allowed to be used by this compute.
     207            6 :         if !self
     208            6 :             .public_extensions
     209            6 :             .as_ref()
     210            6 :             .is_some_and(|exts| exts.iter().any(|e| e == real_ext_name))
     211            4 :             && !self
     212            4 :                 .custom_extensions
     213            4 :                 .as_ref()
     214            4 :                 .is_some_and(|exts| exts.iter().any(|e| e == real_ext_name))
     215              :         {
     216            3 :             return Err(anyhow::anyhow!("extension {} is not found", real_ext_name));
     217            3 :         }
     218            3 : 
     219            3 :         match self.extension_data.get(real_ext_name) {
     220            3 :             Some(_ext_data) => {
     221            3 :                 // Construct the path to the extension archive
     222            3 :                 // BUILD_TAG/PG_MAJOR_VERSION/extensions/EXTENSION_NAME.tar.zst
     223            3 :                 //
     224            3 :                 // Keep it in sync with path generation in
     225            3 :                 // https://github.com/neondatabase/build-custom-extensions/tree/main
     226            3 :                 let archive_path_str =
     227            3 :                     format!("{build_tag}/{pg_major_version}/extensions/{real_ext_name}.tar.zst");
     228            3 :                 Ok((
     229            3 :                     real_ext_name.to_string(),
     230            3 :                     RemotePath::from_string(&archive_path_str)?,
     231              :                 ))
     232              :             }
     233            0 :             None => Err(anyhow::anyhow!(
     234            0 :                 "real_ext_name {} is not found",
     235            0 :                 real_ext_name
     236            0 :             )),
     237              :         }
     238            6 :     }
     239              : }
     240              : 
     241            0 : #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
     242              : pub enum ComputeMode {
     243              :     /// A read-write node
     244              :     #[default]
     245              :     Primary,
     246              :     /// A read-only node, pinned at a particular LSN
     247              :     Static(Lsn),
     248              :     /// A read-only node that follows the tip of the branch in hot standby mode
     249              :     ///
     250              :     /// Future versions may want to distinguish between replicas with hot standby
     251              :     /// feedback and other kinds of replication configurations.
     252              :     Replica,
     253              : }
     254              : 
     255           36 : #[derive(Clone, Debug, Default, Deserialize, Serialize)]
     256              : pub struct Cluster {
     257              :     pub cluster_id: Option<String>,
     258              :     pub name: Option<String>,
     259              :     pub state: Option<String>,
     260              :     pub roles: Vec<Role>,
     261              :     pub databases: Vec<Database>,
     262              : 
     263              :     /// Desired contents of 'postgresql.conf' file. (The 'compute_ctl'
     264              :     /// tool may add additional settings to the final file.)
     265              :     pub postgresql_conf: Option<String>,
     266              : 
     267              :     /// Additional settings that will be appended to the 'postgresql.conf' file.
     268              :     pub settings: GenericOptions,
     269              : }
     270              : 
     271              : /// Single cluster state changing operation that could not be represented as
     272              : /// a static `Cluster` structure. For example:
     273              : /// - DROP DATABASE
     274              : /// - DROP ROLE
     275              : /// - ALTER ROLE name RENAME TO new_name
     276              : /// - ALTER DATABASE name RENAME TO new_name
     277           60 : #[derive(Clone, Debug, Deserialize, Serialize)]
     278              : pub struct DeltaOp {
     279              :     pub action: String,
     280              :     pub name: PgIdent,
     281              :     pub new_name: Option<PgIdent>,
     282              : }
     283              : 
     284              : /// Rust representation of Postgres role info with only those fields
     285              : /// that matter for us.
     286           90 : #[derive(Clone, Debug, Deserialize, Serialize)]
     287              : pub struct Role {
     288              :     pub name: PgIdent,
     289              :     pub encrypted_password: Option<String>,
     290              :     pub options: GenericOptions,
     291              : }
     292              : 
     293              : /// Rust representation of Postgres database info with only those fields
     294              : /// that matter for us.
     295           42 : #[derive(Clone, Debug, Deserialize, Serialize)]
     296              : pub struct Database {
     297              :     pub name: PgIdent,
     298              :     pub owner: PgIdent,
     299              :     pub options: GenericOptions,
     300              :     // These are derived flags, not present in the spec file.
     301              :     // They are never set by the control plane.
     302              :     #[serde(skip_deserializing, default)]
     303              :     pub restrict_conn: bool,
     304              :     #[serde(skip_deserializing, default)]
     305              :     pub invalid: bool,
     306              : }
     307              : 
     308              : /// Common type representing both SQL statement params with or without value,
     309              : /// like `LOGIN` or `OWNER username` in the `CREATE/ALTER ROLE`, and config
     310              : /// options like `wal_level = logical`.
     311          468 : #[derive(Clone, Debug, Deserialize, Serialize)]
     312              : pub struct GenericOption {
     313              :     pub name: String,
     314              :     pub value: Option<String>,
     315              :     pub vartype: String,
     316              : }
     317              : 
     318              : /// Optional collection of `GenericOption`'s. Type alias allows us to
     319              : /// declare a `trait` on it.
     320              : pub type GenericOptions = Option<Vec<GenericOption>>;
     321              : 
     322              : /// Configured the local_proxy application with the relevant JWKS and roles it should
     323              : /// use for authorizing connect requests using JWT.
     324            0 : #[derive(Clone, Debug, Deserialize, Serialize)]
     325              : pub struct LocalProxySpec {
     326              :     #[serde(default)]
     327              :     #[serde(skip_serializing_if = "Option::is_none")]
     328              :     pub jwks: Option<Vec<JwksSettings>>,
     329              : }
     330              : 
     331            0 : #[derive(Clone, Debug, Deserialize, Serialize)]
     332              : pub struct JwksSettings {
     333              :     pub id: String,
     334              :     pub role_names: Vec<String>,
     335              :     pub jwks_url: String,
     336              :     pub provider_name: String,
     337              :     pub jwt_audience: Option<String>,
     338              : }
     339              : 
     340              : #[cfg(test)]
     341              : mod tests {
     342              :     use super::*;
     343              :     use std::fs::File;
     344              : 
     345              :     #[test]
     346            1 :     fn allow_installing_remote_extensions() {
     347            1 :         let rspec: RemoteExtSpec = serde_json::from_value(serde_json::json!({
     348            1 :             "public_extensions": null,
     349            1 :             "custom_extensions": null,
     350            1 :             "library_index": {},
     351            1 :             "extension_data": {},
     352            1 :         }))
     353            1 :         .unwrap();
     354            1 : 
     355            1 :         rspec
     356            1 :             .get_ext("ext", false, "latest", "v17")
     357            1 :             .expect_err("Extension should not be found");
     358            1 : 
     359            1 :         let rspec: RemoteExtSpec = serde_json::from_value(serde_json::json!({
     360            1 :             "public_extensions": [],
     361            1 :             "custom_extensions": null,
     362            1 :             "library_index": {},
     363            1 :             "extension_data": {},
     364            1 :         }))
     365            1 :         .unwrap();
     366            1 : 
     367            1 :         rspec
     368            1 :             .get_ext("ext", false, "latest", "v17")
     369            1 :             .expect_err("Extension should not be found");
     370            1 : 
     371            1 :         let rspec: RemoteExtSpec = serde_json::from_value(serde_json::json!({
     372            1 :             "public_extensions": [],
     373            1 :             "custom_extensions": [],
     374            1 :             "library_index": {
     375            1 :                 "ext": "ext"
     376            1 :             },
     377            1 :             "extension_data": {
     378            1 :                 "ext": {
     379            1 :                     "control_data": {
     380            1 :                         "ext.control": ""
     381            1 :                     },
     382            1 :                     "archive_path": ""
     383            1 :                 }
     384            1 :             },
     385            1 :         }))
     386            1 :         .unwrap();
     387            1 : 
     388            1 :         rspec
     389            1 :             .get_ext("ext", false, "latest", "v17")
     390            1 :             .expect_err("Extension should not be found");
     391            1 : 
     392            1 :         let rspec: RemoteExtSpec = serde_json::from_value(serde_json::json!({
     393            1 :             "public_extensions": [],
     394            1 :             "custom_extensions": ["ext"],
     395            1 :             "library_index": {
     396            1 :                 "ext": "ext"
     397            1 :             },
     398            1 :             "extension_data": {
     399            1 :                 "ext": {
     400            1 :                     "control_data": {
     401            1 :                         "ext.control": ""
     402            1 :                     },
     403            1 :                     "archive_path": ""
     404            1 :                 }
     405            1 :             },
     406            1 :         }))
     407            1 :         .unwrap();
     408            1 : 
     409            1 :         rspec
     410            1 :             .get_ext("ext", false, "latest", "v17")
     411            1 :             .expect("Extension should be found");
     412            1 : 
     413            1 :         let rspec: RemoteExtSpec = serde_json::from_value(serde_json::json!({
     414            1 :             "public_extensions": ["ext"],
     415            1 :             "custom_extensions": [],
     416            1 :             "library_index": {
     417            1 :                 "extlib": "ext",
     418            1 :             },
     419            1 :             "extension_data": {
     420            1 :                 "ext": {
     421            1 :                     "control_data": {
     422            1 :                         "ext.control": ""
     423            1 :                     },
     424            1 :                     "archive_path": ""
     425            1 :                 }
     426            1 :             },
     427            1 :         }))
     428            1 :         .unwrap();
     429            1 : 
     430            1 :         rspec
     431            1 :             .get_ext("ext", false, "latest", "v17")
     432            1 :             .expect("Extension should be found");
     433            1 : 
     434            1 :         // test library index for the case when library name
     435            1 :         // doesn't match the extension name
     436            1 :         rspec
     437            1 :             .get_ext("extlib", true, "latest", "v17")
     438            1 :             .expect("Library should be found");
     439            1 :     }
     440              : 
     441              :     #[test]
     442            1 :     fn parse_spec_file() {
     443            1 :         let file = File::open("tests/cluster_spec.json").unwrap();
     444            1 :         let spec: ComputeSpec = serde_json::from_reader(file).unwrap();
     445            1 : 
     446            1 :         // Features list defaults to empty vector.
     447            1 :         assert!(spec.features.is_empty());
     448              : 
     449              :         // Reconfigure concurrency defaults to 1.
     450            1 :         assert_eq!(spec.reconfigure_concurrency, 1);
     451            1 :     }
     452              : 
     453              :     #[test]
     454            1 :     fn parse_unknown_fields() {
     455            1 :         // Forward compatibility test
     456            1 :         let file = File::open("tests/cluster_spec.json").unwrap();
     457            1 :         let mut json: serde_json::Value = serde_json::from_reader(file).unwrap();
     458            1 :         let ob = json.as_object_mut().unwrap();
     459            1 :         ob.insert("unknown_field_123123123".into(), "hello".into());
     460            1 :         let _spec: ComputeSpec = serde_json::from_value(json).unwrap();
     461            1 :     }
     462              : 
     463              :     #[test]
     464            1 :     fn parse_unknown_features() {
     465            1 :         // Test that unknown feature flags do not cause any errors.
     466            1 :         let file = File::open("tests/cluster_spec.json").unwrap();
     467            1 :         let mut json: serde_json::Value = serde_json::from_reader(file).unwrap();
     468            1 :         let ob = json.as_object_mut().unwrap();
     469            1 : 
     470            1 :         // Add unknown feature flags.
     471            1 :         let features = vec!["foo_bar_feature", "baz_feature"];
     472            1 :         ob.insert("features".into(), features.into());
     473            1 : 
     474            1 :         let spec: ComputeSpec = serde_json::from_value(json).unwrap();
     475            1 : 
     476            1 :         assert!(spec.features.len() == 2);
     477            1 :         assert!(spec.features.contains(&ComputeFeature::UnknownFeature));
     478            1 :         assert_eq!(spec.features, vec![ComputeFeature::UnknownFeature; 2]);
     479            1 :     }
     480              : 
     481              :     #[test]
     482            1 :     fn parse_known_features() {
     483            1 :         // Test that we can properly parse known feature flags.
     484            1 :         let file = File::open("tests/cluster_spec.json").unwrap();
     485            1 :         let mut json: serde_json::Value = serde_json::from_reader(file).unwrap();
     486            1 :         let ob = json.as_object_mut().unwrap();
     487            1 : 
     488            1 :         // Add known feature flags.
     489            1 :         let features = vec!["activity_monitor_experimental"];
     490            1 :         ob.insert("features".into(), features.into());
     491            1 : 
     492            1 :         let spec: ComputeSpec = serde_json::from_value(json).unwrap();
     493            1 : 
     494            1 :         assert_eq!(
     495            1 :             spec.features,
     496            1 :             vec![ComputeFeature::ActivityMonitorExperimental]
     497            1 :         );
     498            1 :     }
     499              : }
        

Generated by: LCOV version 2.1-beta