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