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