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