Line data Source code
1 : use anyhow::Result;
2 : use std::fmt::Write as FmtWrite;
3 : use std::fs::{File, OpenOptions};
4 : use std::io;
5 : use std::io::Write;
6 : use std::io::prelude::*;
7 : use std::path::Path;
8 :
9 : use compute_api::responses::TlsConfig;
10 : use compute_api::spec::{
11 : ComputeAudit, ComputeMode, ComputeSpec, DatabricksSettings, GenericOption,
12 : };
13 :
14 : use crate::compute::ComputeNodeParams;
15 : use crate::pg_helpers::{
16 : DatabricksSettingsExt as _, GenericOptionExt, GenericOptionsSearch, PgOptionsSerialize,
17 : escape_conf_value,
18 : };
19 : use crate::tls::{self, SERVER_CRT, SERVER_KEY};
20 :
21 : /// Check that `line` is inside a text file and put it there if it is not.
22 : /// Create file if it doesn't exist.
23 3 : pub fn line_in_file(path: &Path, line: &str) -> Result<bool> {
24 3 : let mut file = OpenOptions::new()
25 3 : .read(true)
26 3 : .write(true)
27 3 : .create(true)
28 3 : .append(false)
29 3 : .truncate(false)
30 3 : .open(path)?;
31 3 : let buf = io::BufReader::new(&file);
32 3 : let mut count: usize = 0;
33 :
34 5 : for l in buf.lines() {
35 5 : if l? == line {
36 1 : return Ok(false);
37 4 : }
38 4 : count = 1;
39 : }
40 :
41 2 : write!(file, "{}{}", "\n".repeat(count), line)?;
42 2 : Ok(true)
43 3 : }
44 :
45 : /// Create or completely rewrite configuration file specified by `path`
46 : #[allow(clippy::too_many_arguments)]
47 0 : pub fn write_postgres_conf(
48 0 : pgdata_path: &Path,
49 0 : params: &ComputeNodeParams,
50 0 : spec: &ComputeSpec,
51 0 : postgres_port: Option<u16>,
52 0 : extension_server_port: u16,
53 0 : tls_config: &Option<TlsConfig>,
54 0 : databricks_settings: Option<&DatabricksSettings>,
55 0 : lakebase_mode: bool,
56 0 : ) -> Result<()> {
57 0 : let path = pgdata_path.join("postgresql.conf");
58 : // File::create() destroys the file content if it exists.
59 0 : let mut file = File::create(path)?;
60 :
61 : // Write the postgresql.conf content from the spec file as is.
62 0 : if let Some(conf) = &spec.cluster.postgresql_conf {
63 0 : writeln!(file, "{conf}")?;
64 0 : }
65 :
66 : // Stripe size GUC should be defined prior to connection string
67 0 : if let Some(stripe_size) = spec.shard_stripe_size {
68 0 : writeln!(file, "neon.stripe_size={stripe_size}")?;
69 0 : }
70 : // Add options for connecting to storage
71 0 : writeln!(file, "# Neon storage settings")?;
72 0 : if let Some(s) = &spec.pageserver_connstring {
73 0 : writeln!(file, "neon.pageserver_connstring={}", escape_conf_value(s))?;
74 0 : }
75 0 : if !spec.safekeeper_connstrings.is_empty() {
76 0 : let mut neon_safekeepers_value = String::new();
77 0 : tracing::info!(
78 0 : "safekeepers_connstrings is not zero, gen: {:?}",
79 : spec.safekeepers_generation
80 : );
81 : // If generation is given, prepend sk list with g#number:
82 0 : if let Some(generation) = spec.safekeepers_generation {
83 0 : write!(neon_safekeepers_value, "g#{generation}:")?;
84 0 : }
85 0 : neon_safekeepers_value.push_str(&spec.safekeeper_connstrings.join(","));
86 0 : writeln!(
87 0 : file,
88 0 : "neon.safekeepers={}",
89 0 : escape_conf_value(&neon_safekeepers_value)
90 0 : )?;
91 0 : }
92 0 : if let Some(s) = &spec.tenant_id {
93 0 : writeln!(file, "neon.tenant_id={}", escape_conf_value(&s.to_string()))?;
94 0 : }
95 0 : if let Some(s) = &spec.timeline_id {
96 0 : writeln!(
97 0 : file,
98 0 : "neon.timeline_id={}",
99 0 : escape_conf_value(&s.to_string())
100 0 : )?;
101 0 : }
102 0 : if let Some(s) = &spec.project_id {
103 0 : writeln!(file, "neon.project_id={}", escape_conf_value(s))?;
104 0 : }
105 0 : if let Some(s) = &spec.branch_id {
106 0 : writeln!(file, "neon.branch_id={}", escape_conf_value(s))?;
107 0 : }
108 0 : if let Some(s) = &spec.endpoint_id {
109 0 : writeln!(file, "neon.endpoint_id={}", escape_conf_value(s))?;
110 0 : }
111 :
112 : // tls
113 0 : if let Some(tls_config) = tls_config {
114 0 : writeln!(file, "ssl = on")?;
115 :
116 : // postgres requires the keyfile to be in a secure file,
117 : // currently too complicated to ensure that at the VM level,
118 : // so we just copy them to another file instead. :shrug:
119 0 : tls::update_key_path_blocking(pgdata_path, tls_config);
120 :
121 : // these are the default, but good to be explicit.
122 0 : writeln!(file, "ssl_cert_file = '{SERVER_CRT}'")?;
123 0 : writeln!(file, "ssl_key_file = '{SERVER_KEY}'")?;
124 0 : }
125 :
126 : // Locales
127 0 : if cfg!(target_os = "macos") {
128 0 : writeln!(file, "lc_messages='C'")?;
129 0 : writeln!(file, "lc_monetary='C'")?;
130 0 : writeln!(file, "lc_time='C'")?;
131 0 : writeln!(file, "lc_numeric='C'")?;
132 : } else {
133 0 : writeln!(file, "lc_messages='C.UTF-8'")?;
134 0 : writeln!(file, "lc_monetary='C.UTF-8'")?;
135 0 : writeln!(file, "lc_time='C.UTF-8'")?;
136 0 : writeln!(file, "lc_numeric='C.UTF-8'")?;
137 : }
138 :
139 0 : writeln!(file, "neon.compute_mode={}", spec.mode.to_type_str())?;
140 0 : match spec.mode {
141 0 : ComputeMode::Primary => {}
142 0 : ComputeMode::Static(lsn) => {
143 : // hot_standby is 'on' by default, but let's be explicit
144 0 : writeln!(file, "hot_standby=on")?;
145 0 : writeln!(file, "recovery_target_lsn='{lsn}'")?;
146 : }
147 : ComputeMode::Replica => {
148 : // hot_standby is 'on' by default, but let's be explicit
149 0 : writeln!(file, "hot_standby=on")?;
150 : }
151 : }
152 :
153 0 : if cfg!(target_os = "linux") {
154 : // Check /proc/sys/vm/overcommit_memory -- if it equals 2 (i.e. linux memory overcommit is
155 : // disabled), then the control plane has enabled swap and we should set
156 : // dynamic_shared_memory_type = 'mmap'.
157 : //
158 : // This is (maybe?) temporary - for more, see https://github.com/neondatabase/cloud/issues/12047.
159 0 : let overcommit_memory_contents = std::fs::read_to_string("/proc/sys/vm/overcommit_memory")
160 : // ignore any errors - they may be expected to occur under certain situations (e.g. when
161 : // not running in Linux).
162 0 : .unwrap_or_else(|_| String::new());
163 0 : if overcommit_memory_contents.trim() == "2" {
164 0 : let opt = GenericOption {
165 0 : name: "dynamic_shared_memory_type".to_owned(),
166 0 : value: Some("mmap".to_owned()),
167 0 : vartype: "enum".to_owned(),
168 0 : };
169 :
170 0 : writeln!(file, "{}", opt.to_pg_setting())?;
171 0 : }
172 0 : }
173 :
174 0 : writeln!(
175 0 : file,
176 0 : "neon.privileged_role_name={}",
177 0 : escape_conf_value(params.privileged_role_name.as_str())
178 0 : )?;
179 :
180 : // If there are any extra options in the 'settings' field, append those
181 0 : if spec.cluster.settings.is_some() {
182 0 : writeln!(file, "# Managed by compute_ctl: begin")?;
183 0 : write!(file, "{}", spec.cluster.settings.as_pg_settings())?;
184 0 : writeln!(file, "# Managed by compute_ctl: end")?;
185 0 : }
186 :
187 : // If base audit logging is enabled, configure it.
188 : // In this setup, the audit log will be written to the standard postgresql log.
189 : //
190 : // If compliance audit logging is enabled, configure pgaudit.
191 : //
192 : // Note, that this is called after the settings from spec are written.
193 : // This way we always override the settings from the spec
194 : // and don't allow the user or the control plane admin to change them.
195 0 : match spec.audit_log_level {
196 0 : ComputeAudit::Disabled => {}
197 : ComputeAudit::Log | ComputeAudit::Base => {
198 0 : writeln!(file, "# Managed by compute_ctl base audit settings: start")?;
199 0 : writeln!(file, "pgaudit.log='ddl,role'")?;
200 : // Disable logging of catalog queries to reduce the noise
201 0 : writeln!(file, "pgaudit.log_catalog=off")?;
202 :
203 0 : if let Some(libs) = spec.cluster.settings.find("shared_preload_libraries") {
204 0 : let mut extra_shared_preload_libraries = String::new();
205 0 : if !libs.contains("pgaudit") {
206 0 : extra_shared_preload_libraries.push_str(",pgaudit");
207 0 : }
208 0 : writeln!(
209 0 : file,
210 0 : "shared_preload_libraries='{libs}{extra_shared_preload_libraries}'"
211 0 : )?;
212 : } else {
213 : // Typically, this should be unreacheable,
214 : // because we always set at least some shared_preload_libraries in the spec
215 : // but let's handle it explicitly anyway.
216 0 : writeln!(file, "shared_preload_libraries='neon,pgaudit'")?;
217 : }
218 0 : writeln!(file, "# Managed by compute_ctl base audit settings: end")?;
219 : }
220 : ComputeAudit::Hipaa | ComputeAudit::Extended | ComputeAudit::Full => {
221 0 : writeln!(
222 0 : file,
223 0 : "# Managed by compute_ctl compliance audit settings: begin"
224 0 : )?;
225 : // Enable logging of parameters.
226 : // This is very verbose and may contain sensitive data.
227 0 : if spec.audit_log_level == ComputeAudit::Full {
228 0 : writeln!(file, "pgaudit.log_parameter=on")?;
229 0 : writeln!(file, "pgaudit.log='all'")?;
230 : } else {
231 0 : writeln!(file, "pgaudit.log_parameter=off")?;
232 0 : writeln!(file, "pgaudit.log='all, -misc'")?;
233 : }
234 : // Disable logging of catalog queries
235 : // The catalog doesn't contain sensitive data, so we don't need to audit it.
236 0 : writeln!(file, "pgaudit.log_catalog=off")?;
237 : // Set log rotation to 5 minutes
238 : // TODO: tune this after performance testing
239 0 : writeln!(file, "pgaudit.log_rotation_age=5")?;
240 :
241 : // Enable audit logs for pg_session_jwt extension
242 : // TODO: Consider a good approach for shipping pg_session_jwt logs to the same sink as
243 : // pgAudit - additional context in https://github.com/neondatabase/cloud/issues/28863
244 : //
245 : // writeln!(file, "pg_session_jwt.audit_log=on")?;
246 :
247 : // Add audit shared_preload_libraries, if they are not present.
248 : //
249 : // The caller who sets the flag is responsible for ensuring that the necessary
250 : // shared_preload_libraries are present in the compute image,
251 : // otherwise the compute start will fail.
252 0 : if let Some(libs) = spec.cluster.settings.find("shared_preload_libraries") {
253 0 : let mut extra_shared_preload_libraries = String::new();
254 0 : if !libs.contains("pgaudit") {
255 0 : extra_shared_preload_libraries.push_str(",pgaudit");
256 0 : }
257 0 : if !libs.contains("pgauditlogtofile") {
258 0 : extra_shared_preload_libraries.push_str(",pgauditlogtofile");
259 0 : }
260 0 : writeln!(
261 0 : file,
262 0 : "shared_preload_libraries='{libs}{extra_shared_preload_libraries}'"
263 0 : )?;
264 : } else {
265 : // Typically, this should be unreacheable,
266 : // because we always set at least some shared_preload_libraries in the spec
267 : // but let's handle it explicitly anyway.
268 0 : writeln!(
269 0 : file,
270 0 : "shared_preload_libraries='neon,pgaudit,pgauditlogtofile'"
271 0 : )?;
272 : }
273 0 : writeln!(
274 0 : file,
275 0 : "# Managed by compute_ctl compliance audit settings: end"
276 0 : )?;
277 : }
278 : }
279 :
280 0 : writeln!(file, "neon.extension_server_port={extension_server_port}")?;
281 :
282 0 : if spec.drop_subscriptions_before_start {
283 0 : writeln!(file, "neon.disable_logical_replication_subscribers=true")?;
284 : } else {
285 : // be explicit about the default value
286 0 : writeln!(file, "neon.disable_logical_replication_subscribers=false")?;
287 : }
288 :
289 : // We need Postgres to send logs to rsyslog so that we can forward them
290 : // further to customers' log aggregation systems.
291 0 : if spec.logs_export_host.is_some() {
292 0 : writeln!(file, "log_destination='stderr,syslog'")?;
293 0 : }
294 :
295 0 : if lakebase_mode {
296 : // Explicitly set the port based on the connstr, overriding any previous port setting.
297 : // Note: It is important that we don't specify a different port again after this.
298 0 : let port = postgres_port.expect("port must be present in connstr");
299 0 : writeln!(file, "port = {port}")?;
300 :
301 : // This is databricks specific settings.
302 : // This should be at the end of the file but before `compute_ctl_temp_override.conf` below
303 : // so that it can override any settings above.
304 : // `compute_ctl_temp_override.conf` is intended to override any settings above during specific operations.
305 : // To prevent potential breakage in the future, we keep it above `compute_ctl_temp_override.conf`.
306 0 : writeln!(file, "# Databricks settings start")?;
307 0 : if let Some(settings) = databricks_settings {
308 0 : writeln!(file, "{}", settings.as_pg_settings())?;
309 0 : }
310 0 : writeln!(file, "# Databricks settings end")?;
311 0 : }
312 :
313 : // This is essential to keep this line at the end of the file,
314 : // because it is intended to override any settings above.
315 0 : writeln!(file, "include_if_exists = 'compute_ctl_temp_override.conf'")?;
316 :
317 0 : Ok(())
318 0 : }
319 :
320 0 : pub fn with_compute_ctl_tmp_override<F>(pgdata_path: &Path, options: &str, exec: F) -> Result<()>
321 0 : where
322 0 : F: FnOnce() -> Result<()>,
323 : {
324 0 : let path = pgdata_path.join("compute_ctl_temp_override.conf");
325 0 : let mut file = File::create(path)?;
326 0 : write!(file, "{options}")?;
327 :
328 0 : let res = exec();
329 :
330 0 : file.set_len(0)?;
331 :
332 0 : res
333 0 : }
|