Line data Source code
1 : use std::collections::{HashMap, HashSet};
2 : use std::fmt::{Debug, Formatter};
3 : use std::future::Future;
4 : use std::iter::{empty, once};
5 : use std::sync::Arc;
6 :
7 : use anyhow::{Context, Result};
8 : use compute_api::responses::ComputeStatus;
9 : use compute_api::spec::{ComputeAudit, ComputeSpec, Database, PgIdent, Role};
10 : use futures::future::join_all;
11 : use tokio::sync::RwLock;
12 : use tokio_postgres::Client;
13 : use tokio_postgres::error::SqlState;
14 : use tracing::{Instrument, debug, error, info, info_span, instrument, warn};
15 :
16 : use crate::compute::{ComputeNode, ComputeNodeParams, ComputeState};
17 : use crate::pg_helpers::{
18 : DatabaseExt, Escaping, GenericOptionsSearch, RoleExt, get_existing_dbs_async,
19 : get_existing_roles_async,
20 : };
21 : use crate::spec_apply::ApplySpecPhase::{
22 : CreateAndAlterDatabases, CreateAndAlterRoles, CreateAvailabilityCheck, CreatePgauditExtension,
23 : CreatePgauditlogtofileExtension, CreatePrivilegedRole, CreateSchemaNeon,
24 : DisablePostgresDBPgAudit, DropInvalidDatabases, DropRoles, FinalizeDropLogicalSubscriptions,
25 : HandleNeonExtension, HandleOtherExtensions, RenameAndDeleteDatabases, RenameRoles,
26 : RunInEachDatabase,
27 : };
28 : use crate::spec_apply::PerDatabasePhase::{
29 : ChangeSchemaPerms, DeleteDBRoleReferences, DropLogicalSubscriptions,
30 : };
31 :
32 : impl ComputeNode {
33 : /// Apply the spec to the running PostgreSQL instance.
34 : /// The caller can decide to run with multiple clients in parallel, or
35 : /// single mode. Either way, the commands executed will be the same, and
36 : /// only commands run in different databases are parallelized.
37 : #[instrument(skip_all)]
38 : pub fn apply_spec_sql(
39 : &self,
40 : spec: Arc<ComputeSpec>,
41 : conf: Arc<tokio_postgres::Config>,
42 : concurrency: usize,
43 : ) -> Result<()> {
44 : info!("Applying config with max {} concurrency", concurrency);
45 : debug!("Config: {:?}", spec);
46 :
47 : let rt = tokio::runtime::Handle::current();
48 0 : rt.block_on(async {
49 : // Proceed with post-startup configuration. Note, that order of operations is important.
50 0 : let client = Self::get_maintenance_client(&conf).await?;
51 0 : let spec = spec.clone();
52 0 : let params = Arc::new(self.params.clone());
53 :
54 0 : let databases = get_existing_dbs_async(&client).await?;
55 0 : let roles = get_existing_roles_async(&client)
56 0 : .await?
57 0 : .into_iter()
58 0 : .map(|role| (role.name.clone(), role))
59 0 : .collect::<HashMap<String, Role>>();
60 :
61 : // Check if we need to drop subscriptions before starting the endpoint.
62 : //
63 : // It is important to do this operation exactly once when endpoint starts on a new branch.
64 : // Otherwise, we may drop not inherited, but newly created subscriptions.
65 : //
66 : // We cannot rely only on spec.drop_subscriptions_before_start flag,
67 : // because if for some reason compute restarts inside VM,
68 : // it will start again with the same spec and flag value.
69 : //
70 : // To handle this, we save the fact of the operation in the database
71 : // in the neon.drop_subscriptions_done table.
72 : // If the table does not exist, we assume that the operation was never performed, so we must do it.
73 : // If table exists, we check if the operation was performed on the current timelilne.
74 : //
75 0 : let mut drop_subscriptions_done = false;
76 :
77 0 : if spec.drop_subscriptions_before_start {
78 0 : let timeline_id = self.get_timeline_id().context("timeline_id must be set")?;
79 :
80 0 : info!("Checking if drop subscription operation was already performed for timeline_id: {}", timeline_id);
81 :
82 : drop_subscriptions_done = match
83 0 : client.query("select 1 from neon.drop_subscriptions_done where timeline_id = $1", &[&timeline_id.to_string()]).await {
84 0 : Ok(result) => !result.is_empty(),
85 0 : Err(e) =>
86 : {
87 0 : match e.code() {
88 0 : Some(&SqlState::UNDEFINED_TABLE) => false,
89 : _ => {
90 : // We don't expect any other error here, except for the schema/table not existing
91 0 : error!("Error checking if drop subscription operation was already performed: {}", e);
92 0 : return Err(e.into());
93 : }
94 : }
95 : }
96 : }
97 0 : };
98 :
99 :
100 0 : let jwks_roles = Arc::new(
101 0 : spec.as_ref()
102 0 : .local_proxy_config
103 0 : .iter()
104 0 : .flat_map(|it| &it.jwks)
105 0 : .flatten()
106 0 : .flat_map(|setting| &setting.role_names)
107 0 : .cloned()
108 0 : .collect::<HashSet<_>>(),
109 : );
110 :
111 0 : let ctx = Arc::new(tokio::sync::RwLock::new(MutableApplyContext {
112 0 : roles,
113 0 : dbs: databases,
114 0 : }));
115 :
116 : // Apply special pre drop database phase.
117 : // NOTE: we use the code of RunInEachDatabase phase for parallelism
118 : // and connection management, but we don't really run it in *each* database,
119 : // only in databases, we're about to drop.
120 0 : info!("Applying PerDatabase (pre-dropdb) phase");
121 0 : let concurrency_token = Arc::new(tokio::sync::Semaphore::new(concurrency));
122 :
123 : // Run the phase for each database that we're about to drop.
124 0 : let db_processes = spec
125 0 : .delta_operations
126 0 : .iter()
127 0 : .flatten()
128 0 : .filter_map(move |op| {
129 0 : if op.action.as_str() == "delete_db" {
130 0 : Some(op.name.clone())
131 : } else {
132 0 : None
133 : }
134 0 : })
135 0 : .map(|dbname| {
136 0 : let spec = spec.clone();
137 0 : let ctx = ctx.clone();
138 0 : let jwks_roles = jwks_roles.clone();
139 0 : let mut conf = conf.as_ref().clone();
140 0 : let concurrency_token = concurrency_token.clone();
141 : // We only need dbname field for this phase, so set other fields to dummy values
142 0 : let db = DB::UserDB(Database {
143 0 : name: dbname.clone(),
144 0 : owner: "cloud_admin".to_string(),
145 0 : options: None,
146 0 : restrict_conn: false,
147 0 : invalid: false,
148 0 : });
149 :
150 0 : debug!("Applying per-database phases for Database {:?}", &db);
151 :
152 0 : match &db {
153 0 : DB::SystemDB => {}
154 0 : DB::UserDB(db) => {
155 0 : conf.dbname(db.name.as_str());
156 0 : }
157 : }
158 :
159 0 : let conf = Arc::new(conf);
160 0 : let fut = Self::apply_spec_sql_db(
161 0 : params.clone(),
162 0 : spec.clone(),
163 0 : conf,
164 0 : ctx.clone(),
165 0 : jwks_roles.clone(),
166 0 : concurrency_token.clone(),
167 0 : db,
168 0 : [DropLogicalSubscriptions].to_vec(),
169 : );
170 :
171 0 : Ok(tokio::spawn(fut))
172 0 : })
173 0 : .collect::<Vec<Result<_, anyhow::Error>>>();
174 :
175 0 : for process in db_processes.into_iter() {
176 0 : let handle = process?;
177 0 : if let Err(e) = handle.await? {
178 : // Handle the error case where the database does not exist
179 : // We do not check whether the DB exists or not in the deletion phase,
180 : // so we shouldn't be strict about it in pre-deletion cleanup as well.
181 0 : if e.to_string().contains("does not exist") {
182 0 : warn!("Error dropping subscription: {}", e);
183 : } else {
184 0 : return Err(e);
185 : }
186 0 : };
187 : }
188 :
189 0 : for phase in [
190 0 : CreatePrivilegedRole,
191 0 : DropInvalidDatabases,
192 0 : RenameRoles,
193 0 : CreateAndAlterRoles,
194 0 : RenameAndDeleteDatabases,
195 0 : CreateAndAlterDatabases,
196 0 : CreateSchemaNeon,
197 : ] {
198 0 : info!("Applying phase {:?}", &phase);
199 0 : apply_operations(
200 0 : params.clone(),
201 0 : spec.clone(),
202 0 : ctx.clone(),
203 0 : jwks_roles.clone(),
204 0 : phase,
205 0 : || async { Ok(&client) },
206 : )
207 0 : .await?;
208 : }
209 :
210 0 : info!("Applying RunInEachDatabase2 phase");
211 0 : let concurrency_token = Arc::new(tokio::sync::Semaphore::new(concurrency));
212 :
213 0 : let db_processes = spec
214 0 : .cluster
215 0 : .databases
216 0 : .iter()
217 0 : .map(|db| DB::new(db.clone()))
218 : // include
219 0 : .chain(once(DB::SystemDB))
220 0 : .map(|db| {
221 0 : let spec = spec.clone();
222 0 : let ctx = ctx.clone();
223 0 : let jwks_roles = jwks_roles.clone();
224 0 : let mut conf = conf.as_ref().clone();
225 0 : let concurrency_token = concurrency_token.clone();
226 0 : let db = db.clone();
227 :
228 0 : debug!("Applying per-database phases for Database {:?}", &db);
229 :
230 0 : match &db {
231 0 : DB::SystemDB => {}
232 0 : DB::UserDB(db) => {
233 0 : conf.dbname(db.name.as_str());
234 0 : }
235 : }
236 :
237 0 : let conf = Arc::new(conf);
238 0 : let mut phases = vec![
239 0 : DeleteDBRoleReferences,
240 0 : ChangeSchemaPerms,
241 : ];
242 :
243 0 : if spec.drop_subscriptions_before_start && !drop_subscriptions_done {
244 0 : info!("Adding DropLogicalSubscriptions phase because drop_subscriptions_before_start is set");
245 0 : phases.push(DropLogicalSubscriptions);
246 0 : }
247 :
248 0 : let fut = Self::apply_spec_sql_db(
249 0 : params.clone(),
250 0 : spec.clone(),
251 0 : conf,
252 0 : ctx.clone(),
253 0 : jwks_roles.clone(),
254 0 : concurrency_token.clone(),
255 0 : db,
256 0 : phases,
257 : );
258 :
259 0 : Ok(tokio::spawn(fut))
260 0 : })
261 0 : .collect::<Vec<Result<_, anyhow::Error>>>();
262 :
263 0 : for process in db_processes.into_iter() {
264 0 : let handle = process?;
265 0 : handle.await??;
266 : }
267 :
268 0 : let mut phases = vec![
269 0 : HandleOtherExtensions,
270 0 : HandleNeonExtension, // This step depends on CreateSchemaNeon
271 0 : CreateAvailabilityCheck,
272 0 : DropRoles,
273 : ];
274 :
275 : // This step depends on CreateSchemaNeon
276 0 : if spec.drop_subscriptions_before_start && !drop_subscriptions_done {
277 0 : info!("Adding FinalizeDropLogicalSubscriptions phase because drop_subscriptions_before_start is set");
278 0 : phases.push(FinalizeDropLogicalSubscriptions);
279 0 : }
280 :
281 : // Keep DisablePostgresDBPgAudit phase at the end,
282 : // so that all config operations are audit logged.
283 0 : match spec.audit_log_level
284 : {
285 0 : ComputeAudit::Hipaa | ComputeAudit::Extended | ComputeAudit::Full => {
286 0 : phases.push(CreatePgauditExtension);
287 0 : phases.push(CreatePgauditlogtofileExtension);
288 0 : phases.push(DisablePostgresDBPgAudit);
289 0 : }
290 0 : ComputeAudit::Log | ComputeAudit::Base => {
291 0 : phases.push(CreatePgauditExtension);
292 0 : phases.push(DisablePostgresDBPgAudit);
293 0 : }
294 0 : ComputeAudit::Disabled => {}
295 : }
296 :
297 0 : for phase in phases {
298 0 : debug!("Applying phase {:?}", &phase);
299 0 : apply_operations(
300 0 : params.clone(),
301 0 : spec.clone(),
302 0 : ctx.clone(),
303 0 : jwks_roles.clone(),
304 0 : phase,
305 0 : || async { Ok(&client) },
306 : )
307 0 : .await?;
308 : }
309 :
310 0 : Ok::<(), anyhow::Error>(())
311 0 : })?;
312 :
313 : Ok(())
314 : }
315 :
316 : /// Apply SQL migrations of the RunInEachDatabase phase.
317 : ///
318 : /// May opt to not connect to databases that don't have any scheduled
319 : /// operations. The function is concurrency-controlled with the provided
320 : /// semaphore. The caller has to make sure the semaphore isn't exhausted.
321 : #[allow(clippy::too_many_arguments)] // TODO: needs bigger refactoring
322 0 : async fn apply_spec_sql_db(
323 0 : params: Arc<ComputeNodeParams>,
324 0 : spec: Arc<ComputeSpec>,
325 0 : conf: Arc<tokio_postgres::Config>,
326 0 : ctx: Arc<tokio::sync::RwLock<MutableApplyContext>>,
327 0 : jwks_roles: Arc<HashSet<String>>,
328 0 : concurrency_token: Arc<tokio::sync::Semaphore>,
329 0 : db: DB,
330 0 : subphases: Vec<PerDatabasePhase>,
331 0 : ) -> Result<()> {
332 0 : let _permit = concurrency_token.acquire().await?;
333 :
334 0 : let mut client_conn = None;
335 :
336 0 : for subphase in subphases {
337 0 : apply_operations(
338 0 : params.clone(),
339 0 : spec.clone(),
340 0 : ctx.clone(),
341 0 : jwks_roles.clone(),
342 0 : RunInEachDatabase {
343 0 : db: db.clone(),
344 0 : subphase,
345 0 : },
346 : // Only connect if apply_operation actually wants a connection.
347 : // It's quite possible this database doesn't need any queries,
348 : // so by not connecting we save time and effort connecting to
349 : // that database.
350 0 : || async {
351 0 : if client_conn.is_none() {
352 0 : let db_client = Self::get_maintenance_client(&conf).await?;
353 0 : client_conn.replace(db_client);
354 0 : }
355 0 : let client = client_conn.as_ref().unwrap();
356 0 : Ok(client)
357 0 : },
358 : )
359 0 : .await?;
360 : }
361 :
362 0 : drop(client_conn);
363 :
364 0 : Ok::<(), anyhow::Error>(())
365 0 : }
366 :
367 : /// Choose how many concurrent connections to use for applying the spec changes.
368 0 : pub fn max_service_connections(
369 0 : &self,
370 0 : compute_state: &ComputeState,
371 0 : spec: &ComputeSpec,
372 0 : ) -> usize {
373 : // If the cluster is in Init state we don't have to deal with user connections,
374 : // and can thus use all `max_connections` connection slots. However, that's generally not
375 : // very efficient, so we generally still limit it to a smaller number.
376 0 : if compute_state.status == ComputeStatus::Init {
377 : // If the settings contain 'max_connections', use that as template
378 0 : if let Some(config) = spec.cluster.settings.find("max_connections") {
379 0 : config.parse::<usize>().ok()
380 : } else {
381 : // Otherwise, try to find the setting in the postgresql_conf string
382 0 : spec.cluster
383 0 : .postgresql_conf
384 0 : .iter()
385 0 : .flat_map(|conf| conf.split("\n"))
386 0 : .filter_map(|line| {
387 0 : if !line.contains("max_connections") {
388 0 : return None;
389 0 : }
390 :
391 0 : let (key, value) = line.split_once("=")?;
392 0 : let key = key
393 0 : .trim_start_matches(char::is_whitespace)
394 0 : .trim_end_matches(char::is_whitespace);
395 :
396 0 : let value = value
397 0 : .trim_start_matches(char::is_whitespace)
398 0 : .trim_end_matches(char::is_whitespace);
399 :
400 0 : if key != "max_connections" {
401 0 : return None;
402 0 : }
403 :
404 0 : value.parse::<usize>().ok()
405 0 : })
406 0 : .next()
407 : }
408 : // If max_connections is present, use at most 1/3rd of that.
409 : // When max_connections is lower than 30, try to use at least 10 connections, but
410 : // never more than max_connections.
411 0 : .map(|limit| match limit {
412 0 : 0..10 => limit,
413 0 : 10..30 => 10,
414 0 : 30.. => limit / 3,
415 0 : })
416 : // If we didn't find max_connections, default to 10 concurrent connections.
417 0 : .unwrap_or(10)
418 : } else {
419 : // state == Running
420 : // Because the cluster is already in the Running state, we should assume users are
421 : // already connected to the cluster, and high concurrency could negatively
422 : // impact user connectivity. Therefore, we can limit concurrency to the number of
423 : // reserved superuser connections, which users wouldn't be able to use anyway.
424 0 : spec.cluster
425 0 : .settings
426 0 : .find("superuser_reserved_connections")
427 0 : .iter()
428 0 : .filter_map(|val| val.parse::<usize>().ok())
429 0 : .map(|val| if val > 1 { val - 1 } else { 1 })
430 0 : .next_back()
431 0 : .unwrap_or(3)
432 : }
433 0 : }
434 : }
435 :
436 : #[derive(Clone)]
437 : pub enum DB {
438 : SystemDB,
439 : UserDB(Database),
440 : }
441 :
442 : impl DB {
443 0 : pub fn new(db: Database) -> DB {
444 0 : Self::UserDB(db)
445 0 : }
446 :
447 0 : pub fn is_owned_by(&self, role: &PgIdent) -> bool {
448 0 : match self {
449 0 : DB::SystemDB => false,
450 0 : DB::UserDB(db) => &db.owner == role,
451 : }
452 0 : }
453 : }
454 :
455 : impl Debug for DB {
456 0 : fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
457 0 : match self {
458 0 : DB::SystemDB => f.debug_tuple("SystemDB").finish(),
459 0 : DB::UserDB(db) => f.debug_tuple("UserDB").field(&db.name).finish(),
460 : }
461 0 : }
462 : }
463 :
464 : #[derive(Copy, Clone, Debug)]
465 : pub enum PerDatabasePhase {
466 : DeleteDBRoleReferences,
467 : ChangeSchemaPerms,
468 : /// This is a shared phase, used for both i) dropping dangling LR subscriptions
469 : /// before dropping the DB, and ii) dropping all subscriptions after creating
470 : /// a fresh branch.
471 : /// N.B. we will skip all DBs that are not present in Postgres, invalid, or
472 : /// have `datallowconn = false` (`restrict_conn`).
473 : DropLogicalSubscriptions,
474 : }
475 :
476 : #[derive(Clone, Debug)]
477 : pub enum ApplySpecPhase {
478 : CreatePrivilegedRole,
479 : DropInvalidDatabases,
480 : RenameRoles,
481 : CreateAndAlterRoles,
482 : RenameAndDeleteDatabases,
483 : CreateAndAlterDatabases,
484 : CreateSchemaNeon,
485 : RunInEachDatabase { db: DB, subphase: PerDatabasePhase },
486 : CreatePgauditExtension,
487 : CreatePgauditlogtofileExtension,
488 : DisablePostgresDBPgAudit,
489 : HandleOtherExtensions,
490 : HandleNeonExtension,
491 : CreateAvailabilityCheck,
492 : DropRoles,
493 : FinalizeDropLogicalSubscriptions,
494 : }
495 :
496 : pub struct Operation {
497 : pub query: String,
498 : pub comment: Option<String>,
499 : }
500 :
501 : pub struct MutableApplyContext {
502 : pub roles: HashMap<String, Role>,
503 : pub dbs: HashMap<String, Database>,
504 : }
505 :
506 : /// Apply the operations that belong to the given spec apply phase.
507 : ///
508 : /// Commands within a single phase are executed in order of Iterator yield.
509 : /// Commands of ApplySpecPhase::RunInEachDatabase will execute in the database
510 : /// indicated by its `db` field, and can share a single client for all changes
511 : /// to that database.
512 : ///
513 : /// Notes:
514 : /// - Commands are pipelined, and thus may cause incomplete apply if one
515 : /// command of many fails.
516 : /// - Failing commands will fail the phase's apply step once the return value
517 : /// is processed.
518 : /// - No timeouts have (yet) been implemented.
519 : /// - The caller is responsible for limiting and/or applying concurrency.
520 0 : pub async fn apply_operations<'a, Fut, F>(
521 0 : params: Arc<ComputeNodeParams>,
522 0 : spec: Arc<ComputeSpec>,
523 0 : ctx: Arc<RwLock<MutableApplyContext>>,
524 0 : jwks_roles: Arc<HashSet<String>>,
525 0 : apply_spec_phase: ApplySpecPhase,
526 0 : client: F,
527 0 : ) -> Result<()>
528 0 : where
529 0 : F: FnOnce() -> Fut,
530 0 : Fut: Future<Output = Result<&'a Client>>,
531 0 : {
532 0 : debug!("Starting phase {:?}", &apply_spec_phase);
533 0 : let span = info_span!("db_apply_changes", phase=?apply_spec_phase);
534 0 : let span2 = span.clone();
535 0 : async move {
536 0 : debug!("Processing phase {:?}", &apply_spec_phase);
537 0 : let ctx = ctx;
538 :
539 0 : let mut ops = get_operations(¶ms, &spec, &ctx, &jwks_roles, &apply_spec_phase)
540 0 : .await?
541 0 : .peekable();
542 :
543 : // Return (and by doing so, skip requesting the PostgreSQL client) if
544 : // we don't have any operations scheduled.
545 0 : if ops.peek().is_none() {
546 0 : return Ok(());
547 0 : }
548 :
549 0 : let client = client().await?;
550 :
551 0 : debug!("Applying phase {:?}", &apply_spec_phase);
552 :
553 0 : let active_queries = ops
554 0 : .map(|op| {
555 0 : let Operation { comment, query } = op;
556 0 : let inspan = match comment {
557 0 : None => span.clone(),
558 0 : Some(comment) => info_span!("phase {}: {}", comment),
559 : };
560 :
561 0 : async {
562 0 : let query = query;
563 0 : let res = client.simple_query(&query).await;
564 0 : debug!(
565 0 : "{} {}",
566 0 : if res.is_ok() {
567 0 : "successfully executed"
568 : } else {
569 0 : "failed to execute"
570 : },
571 : query
572 : );
573 0 : res
574 0 : }
575 0 : .instrument(inspan)
576 0 : })
577 0 : .collect::<Vec<_>>();
578 :
579 0 : drop(ctx);
580 :
581 0 : for it in join_all(active_queries).await {
582 0 : drop(it?);
583 : }
584 :
585 0 : debug!("Completed phase {:?}", &apply_spec_phase);
586 :
587 0 : Ok(())
588 0 : }
589 0 : .instrument(span2)
590 0 : .await
591 0 : }
592 :
593 : /// Create a stream of operations to be executed for that phase of applying
594 : /// changes.
595 : ///
596 : /// In the future we may generate a single stream of changes and then
597 : /// sort/merge/batch execution, but for now this is a nice way to improve
598 : /// batching behavior of the commands.
599 0 : async fn get_operations<'a>(
600 0 : params: &'a ComputeNodeParams,
601 0 : spec: &'a ComputeSpec,
602 0 : ctx: &'a RwLock<MutableApplyContext>,
603 0 : jwks_roles: &'a HashSet<String>,
604 0 : apply_spec_phase: &'a ApplySpecPhase,
605 0 : ) -> Result<Box<dyn Iterator<Item = Operation> + 'a + Send>> {
606 0 : match apply_spec_phase {
607 0 : ApplySpecPhase::CreatePrivilegedRole => Ok(Box::new(once(Operation {
608 0 : query: format!(
609 0 : include_str!("sql/create_privileged_role.sql"),
610 0 : privileged_role_name = params.privileged_role_name
611 0 : ),
612 0 : comment: None,
613 0 : }))),
614 : ApplySpecPhase::DropInvalidDatabases => {
615 0 : let mut ctx = ctx.write().await;
616 0 : let databases = &mut ctx.dbs;
617 :
618 0 : let keys: Vec<_> = databases
619 0 : .iter()
620 0 : .filter(|(_, db)| db.invalid)
621 0 : .map(|(dbname, _)| dbname.clone())
622 0 : .collect();
623 :
624 : // After recent commit in Postgres, interrupted DROP DATABASE
625 : // leaves the database in the invalid state. According to the
626 : // commit message, the only option for user is to drop it again.
627 : // See:
628 : // https://github.com/postgres/postgres/commit/a4b4cc1d60f7e8ccfcc8ff8cb80c28ee411ad9a9
629 : //
630 : // Postgres Neon extension is done the way, that db is de-registered
631 : // in the control plane metadata only after it is dropped. So there is
632 : // a chance that it still thinks that the db should exist. This means
633 : // that it will be re-created by the `CreateDatabases` phase. This
634 : // is fine, as user can just drop the table again (in vanilla
635 : // Postgres they would need to do the same).
636 0 : let operations = keys
637 0 : .into_iter()
638 0 : .filter_map(move |dbname| ctx.dbs.remove(&dbname))
639 0 : .map(|db| Operation {
640 0 : query: format!("DROP DATABASE IF EXISTS {}", db.name.pg_quote()),
641 0 : comment: Some(format!("Dropping invalid database {}", db.name)),
642 0 : });
643 :
644 0 : Ok(Box::new(operations))
645 : }
646 : ApplySpecPhase::RenameRoles => {
647 0 : let mut ctx = ctx.write().await;
648 :
649 0 : let operations = spec
650 0 : .delta_operations
651 0 : .iter()
652 0 : .flatten()
653 0 : .filter(|op| op.action == "rename_role")
654 0 : .filter_map(move |op| {
655 0 : let roles = &mut ctx.roles;
656 :
657 0 : if roles.contains_key(op.name.as_str()) {
658 0 : None
659 : } else {
660 0 : let new_name = op.new_name.as_ref().unwrap();
661 0 : let mut role = roles.remove(op.name.as_str()).unwrap();
662 :
663 0 : role.name = new_name.clone();
664 0 : role.encrypted_password = None;
665 0 : roles.insert(role.name.clone(), role);
666 :
667 0 : Some(Operation {
668 0 : query: format!(
669 0 : "ALTER ROLE {} RENAME TO {}",
670 0 : op.name.pg_quote(),
671 0 : new_name.pg_quote()
672 0 : ),
673 0 : comment: Some(format!("renaming role '{}' to '{}'", op.name, new_name)),
674 0 : })
675 : }
676 0 : });
677 :
678 0 : Ok(Box::new(operations))
679 : }
680 : ApplySpecPhase::CreateAndAlterRoles => {
681 0 : let mut ctx = ctx.write().await;
682 :
683 0 : let operations = spec.cluster.roles
684 0 : .iter()
685 0 : .filter_map(move |role| {
686 0 : let roles = &mut ctx.roles;
687 0 : let db_role = roles.get(&role.name);
688 :
689 0 : match db_role {
690 0 : Some(db_role) => {
691 0 : if db_role.encrypted_password != role.encrypted_password {
692 : // This can be run on /every/ role! Not just ones created through the console.
693 : // This means that if you add some funny ALTER here that adds a permission,
694 : // this will get run even on user-created roles! This will result in different
695 : // behavior before and after a spec gets reapplied. The below ALTER as it stands
696 : // now only grants LOGIN and changes the password. Please do not allow this branch
697 : // to do anything silly.
698 0 : Some(Operation {
699 0 : query: format!(
700 0 : "ALTER ROLE {} {}",
701 0 : role.name.pg_quote(),
702 0 : role.to_pg_options(),
703 0 : ),
704 0 : comment: None,
705 0 : })
706 : } else {
707 0 : None
708 : }
709 : }
710 : None => {
711 0 : let query = if !jwks_roles.contains(role.name.as_str()) {
712 0 : format!(
713 0 : "CREATE ROLE {} INHERIT CREATEROLE CREATEDB BYPASSRLS REPLICATION IN ROLE {} {}",
714 0 : role.name.pg_quote(),
715 : params.privileged_role_name,
716 0 : role.to_pg_options(),
717 : )
718 : } else {
719 0 : format!(
720 0 : "CREATE ROLE {} {}",
721 0 : role.name.pg_quote(),
722 0 : role.to_pg_options(),
723 : )
724 : };
725 0 : Some(Operation {
726 0 : query,
727 0 : comment: Some(format!("creating role {}", role.name)),
728 0 : })
729 : }
730 : }
731 0 : });
732 :
733 0 : Ok(Box::new(operations))
734 : }
735 : ApplySpecPhase::RenameAndDeleteDatabases => {
736 0 : let mut ctx = ctx.write().await;
737 :
738 0 : let operations = spec
739 0 : .delta_operations
740 0 : .iter()
741 0 : .flatten()
742 0 : .filter_map(move |op| {
743 0 : let databases = &mut ctx.dbs;
744 0 : match op.action.as_str() {
745 : // We do not check whether the DB exists or not,
746 : // Postgres will take care of it for us
747 0 : "delete_db" => {
748 0 : let (db_name, outer_tag) = op.name.pg_quote_dollar();
749 : // In Postgres we can't drop a database if it is a template.
750 : // So we need to unset the template flag first, but it could
751 : // be a retry, so we could've already dropped the database.
752 : // Check that database exists first to make it idempotent.
753 0 : let unset_template_query: String = format!(
754 0 : include_str!("sql/unset_template_for_drop_dbs.sql"),
755 : datname = db_name,
756 : outer_tag = outer_tag,
757 : );
758 :
759 : // Use FORCE to drop database even if there are active connections.
760 : // We run this from `cloud_admin`, so it should have enough privileges.
761 : //
762 : // NB: there could be other db states, which prevent us from dropping
763 : // the database. For example, if db is used by any active subscription
764 : // or replication slot.
765 : // Such cases are handled in the DropLogicalSubscriptions
766 : // phase. We do all the cleanup before actually dropping the database.
767 0 : let drop_db_query: String = format!(
768 0 : "DROP DATABASE IF EXISTS {} WITH (FORCE)",
769 0 : &op.name.pg_quote()
770 : );
771 :
772 0 : databases.remove(&op.name);
773 :
774 0 : Some(vec![
775 0 : Operation {
776 0 : query: unset_template_query,
777 0 : comment: Some(format!(
778 0 : "optionally clearing template flags for DB {}",
779 0 : op.name,
780 0 : )),
781 0 : },
782 0 : Operation {
783 0 : query: drop_db_query,
784 0 : comment: Some(format!("deleting database {}", op.name,)),
785 0 : },
786 0 : ])
787 : }
788 0 : "rename_db" => {
789 0 : if let Some(mut db) = databases.remove(&op.name) {
790 : // update state of known databases
791 0 : let new_name = op.new_name.as_ref().unwrap();
792 0 : db.name = new_name.clone();
793 0 : databases.insert(db.name.clone(), db);
794 :
795 0 : Some(vec![Operation {
796 0 : query: format!(
797 0 : "ALTER DATABASE {} RENAME TO {}",
798 0 : op.name.pg_quote(),
799 0 : new_name.pg_quote(),
800 0 : ),
801 0 : comment: Some(format!(
802 0 : "renaming database '{}' to '{}'",
803 0 : op.name, new_name
804 0 : )),
805 0 : }])
806 : } else {
807 0 : None
808 : }
809 : }
810 0 : _ => None,
811 : }
812 0 : })
813 0 : .flatten();
814 :
815 0 : Ok(Box::new(operations))
816 : }
817 : ApplySpecPhase::CreateAndAlterDatabases => {
818 0 : let mut ctx = ctx.write().await;
819 :
820 0 : let operations = spec
821 0 : .cluster
822 0 : .databases
823 0 : .iter()
824 0 : .filter_map(move |db| {
825 0 : let databases = &mut ctx.dbs;
826 0 : if let Some(edb) = databases.get_mut(&db.name) {
827 0 : let change_owner = if edb.owner.starts_with('"') {
828 0 : db.owner.pg_quote() != edb.owner
829 : } else {
830 0 : db.owner != edb.owner
831 : };
832 :
833 0 : edb.owner = db.owner.clone();
834 :
835 0 : if change_owner {
836 0 : Some(vec![Operation {
837 0 : query: format!(
838 0 : "ALTER DATABASE {} OWNER TO {}",
839 0 : db.name.pg_quote(),
840 0 : db.owner.pg_quote()
841 0 : ),
842 0 : comment: Some(format!(
843 0 : "changing database owner of database {} to {}",
844 0 : db.name, db.owner
845 0 : )),
846 0 : }])
847 : } else {
848 0 : None
849 : }
850 : } else {
851 0 : databases.insert(db.name.clone(), db.clone());
852 :
853 0 : Some(vec![
854 0 : Operation {
855 0 : query: format!(
856 0 : "CREATE DATABASE {} {}",
857 0 : db.name.pg_quote(),
858 0 : db.to_pg_options(),
859 0 : ),
860 0 : comment: None,
861 0 : },
862 0 : Operation {
863 0 : // ALL PRIVILEGES grants CREATE, CONNECT, and TEMPORARY on the database
864 0 : // (see https://www.postgresql.org/docs/current/ddl-priv.html)
865 0 : query: format!(
866 0 : "GRANT ALL PRIVILEGES ON DATABASE {} TO {}",
867 0 : db.name.pg_quote(),
868 0 : params.privileged_role_name
869 0 : ),
870 0 : comment: None,
871 0 : },
872 0 : ])
873 : }
874 0 : })
875 0 : .flatten();
876 :
877 0 : Ok(Box::new(operations))
878 : }
879 0 : ApplySpecPhase::CreateSchemaNeon => Ok(Box::new(once(Operation {
880 0 : query: String::from("CREATE SCHEMA IF NOT EXISTS neon"),
881 0 : comment: Some(String::from(
882 0 : "create schema for neon extension and utils tables",
883 0 : )),
884 0 : }))),
885 0 : ApplySpecPhase::RunInEachDatabase { db, subphase } => {
886 : // Do some checks that user DB exists and we can access it.
887 : //
888 : // During the phases like DropLogicalSubscriptions, DeleteDBRoleReferences,
889 : // which happen before dropping the DB, the current run could be a retry,
890 : // so it's a valid case when DB is absent already. The case of
891 : // `pg_database.datallowconn = false`/`restrict_conn` is a bit tricky, as
892 : // in theory user can have some dangling objects there, so we will fail at
893 : // the actual drop later. Yet, to fix that in the current code we would need
894 : // to ALTER DATABASE, and then check back, but that even more invasive, so
895 : // that's not what we really want to do here.
896 : //
897 : // For ChangeSchemaPerms, skipping DBs we cannot access is totally fine.
898 0 : if let DB::UserDB(db) = db {
899 0 : let databases = &ctx.read().await.dbs;
900 :
901 0 : let edb = match databases.get(&db.name) {
902 0 : Some(edb) => edb,
903 : None => {
904 0 : warn!(
905 0 : "skipping RunInEachDatabase phase {:?}, database {} doesn't exist in PostgreSQL",
906 : subphase, db.name
907 : );
908 0 : return Ok(Box::new(empty()));
909 : }
910 : };
911 :
912 0 : if edb.restrict_conn || edb.invalid {
913 0 : warn!(
914 0 : "skipping RunInEachDatabase phase {:?}, database {} is (restrict_conn={}, invalid={})",
915 : subphase, db.name, edb.restrict_conn, edb.invalid
916 : );
917 0 : return Ok(Box::new(empty()));
918 0 : }
919 0 : }
920 :
921 0 : match subphase {
922 : PerDatabasePhase::DropLogicalSubscriptions => {
923 0 : match &db {
924 0 : DB::UserDB(db) => {
925 0 : let (db_name, outer_tag) = db.name.pg_quote_dollar();
926 0 : let drop_subscription_query: String = format!(
927 0 : include_str!("sql/drop_subscriptions.sql"),
928 : datname_str = db_name,
929 : outer_tag = outer_tag,
930 : );
931 :
932 0 : let operations = vec![Operation {
933 0 : query: drop_subscription_query,
934 0 : comment: Some(format!(
935 0 : "optionally dropping subscriptions for DB {}",
936 0 : db.name,
937 0 : )),
938 0 : }]
939 0 : .into_iter();
940 :
941 0 : Ok(Box::new(operations))
942 : }
943 : // skip this cleanup for the system databases
944 : // because users can't drop them
945 0 : DB::SystemDB => Ok(Box::new(empty())),
946 : }
947 : }
948 : PerDatabasePhase::DeleteDBRoleReferences => {
949 0 : let ctx = ctx.read().await;
950 :
951 0 : let operations = spec
952 0 : .delta_operations
953 0 : .iter()
954 0 : .flatten()
955 0 : .filter(|op| op.action == "delete_role")
956 0 : .filter_map(move |op| {
957 0 : if db.is_owned_by(&op.name) {
958 0 : return None;
959 0 : }
960 0 : if !ctx.roles.contains_key(&op.name) {
961 0 : return None;
962 0 : }
963 0 : let quoted = op.name.pg_quote();
964 0 : let new_owner = match &db {
965 0 : DB::SystemDB => PgIdent::from("cloud_admin").pg_quote(),
966 0 : DB::UserDB(db) => db.owner.pg_quote(),
967 : };
968 0 : let (escaped_role, outer_tag) = op.name.pg_quote_dollar();
969 :
970 0 : Some(vec![
971 0 : // This will reassign all dependent objects to the db owner
972 0 : Operation {
973 0 : query: format!("REASSIGN OWNED BY {quoted} TO {new_owner}",),
974 0 : comment: None,
975 0 : },
976 0 : // Revoke some potentially blocking privileges (Neon-specific currently)
977 0 : Operation {
978 0 : query: format!(
979 0 : include_str!("sql/pre_drop_role_revoke_privileges.sql"),
980 0 : // N.B. this has to be properly dollar-escaped with `pg_quote_dollar()`
981 0 : role_name = escaped_role,
982 0 : outer_tag = outer_tag,
983 0 : ),
984 0 : comment: None,
985 0 : },
986 0 : // This now will only drop privileges of the role
987 0 : // TODO: this is obviously not 100% true because of the above case,
988 0 : // there could be still some privileges that are not revoked. Maybe this
989 0 : // only drops privileges that were granted *by this* role, not *to this* role,
990 0 : // but this has to be checked.
991 0 : Operation {
992 0 : query: format!("DROP OWNED BY {quoted}"),
993 0 : comment: None,
994 0 : },
995 0 : ])
996 0 : })
997 0 : .flatten();
998 :
999 0 : Ok(Box::new(operations))
1000 : }
1001 : PerDatabasePhase::ChangeSchemaPerms => {
1002 0 : let db = match &db {
1003 : // ignore schema permissions on the system database
1004 0 : DB::SystemDB => return Ok(Box::new(empty())),
1005 0 : DB::UserDB(db) => db,
1006 : };
1007 0 : let (db_owner, outer_tag) = db.owner.pg_quote_dollar();
1008 :
1009 0 : let operations = vec![
1010 0 : Operation {
1011 0 : query: format!(
1012 0 : include_str!("sql/set_public_schema_owner.sql"),
1013 0 : db_owner = db_owner,
1014 0 : outer_tag = outer_tag,
1015 0 : ),
1016 0 : comment: None,
1017 0 : },
1018 0 : Operation {
1019 0 : query: String::from(include_str!("sql/default_grants.sql")),
1020 0 : comment: None,
1021 0 : },
1022 : ]
1023 0 : .into_iter();
1024 :
1025 0 : Ok(Box::new(operations))
1026 : }
1027 : }
1028 : }
1029 : // Interestingly, we only install p_s_s in the main database, even when
1030 : // it's preloaded.
1031 : ApplySpecPhase::HandleOtherExtensions => {
1032 0 : if let Some(libs) = spec.cluster.settings.find("shared_preload_libraries") {
1033 0 : if libs.contains("pg_stat_statements") {
1034 0 : return Ok(Box::new(once(Operation {
1035 0 : query: String::from("CREATE EXTENSION IF NOT EXISTS pg_stat_statements"),
1036 0 : comment: Some(String::from("create system extensions")),
1037 0 : })));
1038 0 : }
1039 0 : }
1040 0 : Ok(Box::new(empty()))
1041 : }
1042 0 : ApplySpecPhase::CreatePgauditExtension => Ok(Box::new(once(Operation {
1043 0 : query: String::from("CREATE EXTENSION IF NOT EXISTS pgaudit"),
1044 0 : comment: Some(String::from("create pgaudit extensions")),
1045 0 : }))),
1046 0 : ApplySpecPhase::CreatePgauditlogtofileExtension => Ok(Box::new(once(Operation {
1047 0 : query: String::from("CREATE EXTENSION IF NOT EXISTS pgauditlogtofile"),
1048 0 : comment: Some(String::from("create pgauditlogtofile extensions")),
1049 0 : }))),
1050 : // Disable pgaudit logging for postgres database.
1051 : // Postgres is neon system database used by monitors
1052 : // and compute_ctl tuning functions and thus generates a lot of noise.
1053 : // We do not consider data stored in this database as sensitive.
1054 : ApplySpecPhase::DisablePostgresDBPgAudit => {
1055 0 : let query = "ALTER DATABASE postgres SET pgaudit.log to 'none'";
1056 0 : Ok(Box::new(once(Operation {
1057 0 : query: query.to_string(),
1058 0 : comment: Some(query.to_string()),
1059 0 : })))
1060 : }
1061 : ApplySpecPhase::HandleNeonExtension => {
1062 0 : let operations = vec![
1063 0 : Operation {
1064 0 : query: String::from("CREATE EXTENSION IF NOT EXISTS neon WITH SCHEMA neon"),
1065 0 : comment: Some(String::from(
1066 0 : "init: install the extension if not already installed",
1067 0 : )),
1068 0 : },
1069 0 : Operation {
1070 0 : query: String::from(
1071 0 : "UPDATE pg_extension SET extrelocatable = true WHERE extname = 'neon'",
1072 0 : ),
1073 0 : comment: Some(String::from("compat/fix: make neon relocatable")),
1074 0 : },
1075 0 : Operation {
1076 0 : query: String::from("ALTER EXTENSION neon SET SCHEMA neon"),
1077 0 : comment: Some(String::from("compat/fix: alter neon extension schema")),
1078 0 : },
1079 0 : Operation {
1080 0 : query: String::from("ALTER EXTENSION neon UPDATE"),
1081 0 : comment: Some(String::from("compat/update: update neon extension version")),
1082 0 : },
1083 : ]
1084 0 : .into_iter();
1085 :
1086 0 : Ok(Box::new(operations))
1087 : }
1088 0 : ApplySpecPhase::CreateAvailabilityCheck => Ok(Box::new(once(Operation {
1089 0 : query: String::from(include_str!("sql/add_availabilitycheck_tables.sql")),
1090 0 : comment: None,
1091 0 : }))),
1092 : ApplySpecPhase::DropRoles => {
1093 0 : let operations = spec
1094 0 : .delta_operations
1095 0 : .iter()
1096 0 : .flatten()
1097 0 : .filter(|op| op.action == "delete_role")
1098 0 : .map(|op| Operation {
1099 0 : query: format!("DROP ROLE IF EXISTS {}", op.name.pg_quote()),
1100 0 : comment: None,
1101 0 : });
1102 :
1103 0 : Ok(Box::new(operations))
1104 : }
1105 0 : ApplySpecPhase::FinalizeDropLogicalSubscriptions => Ok(Box::new(once(Operation {
1106 0 : query: String::from(include_str!("sql/finalize_drop_subscriptions.sql")),
1107 0 : comment: None,
1108 0 : }))),
1109 : }
1110 0 : }
|