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