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