Line data Source code
1 : //! Code to manage safekeepers
2 : //!
3 : //! In the local test environment, the data for each safekeeper is stored in
4 : //!
5 : //! ```text
6 : //! .neon/safekeepers/<safekeeper id>
7 : //! ```
8 : use std::io::Write;
9 : use std::path::PathBuf;
10 : use std::{io, result};
11 :
12 : use anyhow::Context;
13 : use camino::Utf8PathBuf;
14 : use postgres_connection::PgConnectionConfig;
15 : use reqwest::{IntoUrl, Method};
16 : use thiserror::Error;
17 : use utils::{http::error::HttpErrorBody, id::NodeId};
18 :
19 : use crate::{
20 : background_process,
21 : local_env::{LocalEnv, SafekeeperConf},
22 : };
23 :
24 0 : #[derive(Error, Debug)]
25 : pub enum SafekeeperHttpError {
26 : #[error("Reqwest error: {0}")]
27 : Transport(#[from] reqwest::Error),
28 :
29 : #[error("Error: {0}")]
30 : Response(String),
31 : }
32 :
33 : type Result<T> = result::Result<T, SafekeeperHttpError>;
34 :
35 : #[async_trait::async_trait]
36 : pub trait ResponseErrorMessageExt: Sized {
37 : async fn error_from_body(self) -> Result<Self>;
38 : }
39 :
40 : #[async_trait::async_trait]
41 : impl ResponseErrorMessageExt for reqwest::Response {
42 0 : async fn error_from_body(self) -> Result<Self> {
43 0 : let status = self.status();
44 0 : if !(status.is_client_error() || status.is_server_error()) {
45 0 : return Ok(self);
46 0 : }
47 0 :
48 0 : // reqwest does not export its error construction utility functions, so let's craft the message ourselves
49 0 : let url = self.url().to_owned();
50 0 : Err(SafekeeperHttpError::Response(
51 0 : match self.json::<HttpErrorBody>().await {
52 0 : Ok(err_body) => format!("Error: {}", err_body.msg),
53 0 : Err(_) => format!("Http error ({}) at {}.", status.as_u16(), url),
54 0 : },
55 0 : ))
56 0 : }
57 : }
58 :
59 : //
60 : // Control routines for safekeeper.
61 : //
62 : // Used in CLI and tests.
63 : //
64 : #[derive(Debug)]
65 : pub struct SafekeeperNode {
66 : pub id: NodeId,
67 :
68 : pub conf: SafekeeperConf,
69 :
70 : pub pg_connection_config: PgConnectionConfig,
71 : pub env: LocalEnv,
72 : pub http_client: reqwest::Client,
73 : pub listen_addr: String,
74 : pub http_base_url: String,
75 : }
76 :
77 : impl SafekeeperNode {
78 0 : pub fn from_env(env: &LocalEnv, conf: &SafekeeperConf) -> SafekeeperNode {
79 0 : let listen_addr = if let Some(ref listen_addr) = conf.listen_addr {
80 0 : listen_addr.clone()
81 : } else {
82 0 : "127.0.0.1".to_string()
83 : };
84 0 : SafekeeperNode {
85 0 : id: conf.id,
86 0 : conf: conf.clone(),
87 0 : pg_connection_config: Self::safekeeper_connection_config(&listen_addr, conf.pg_port),
88 0 : env: env.clone(),
89 0 : http_client: reqwest::Client::new(),
90 0 : http_base_url: format!("http://{}:{}/v1", listen_addr, conf.http_port),
91 0 : listen_addr,
92 0 : }
93 0 : }
94 :
95 : /// Construct libpq connection string for connecting to this safekeeper.
96 0 : fn safekeeper_connection_config(addr: &str, port: u16) -> PgConnectionConfig {
97 0 : PgConnectionConfig::new_host_port(url::Host::parse(addr).unwrap(), port)
98 0 : }
99 :
100 0 : pub fn datadir_path_by_id(env: &LocalEnv, sk_id: NodeId) -> PathBuf {
101 0 : env.safekeeper_data_dir(&format!("sk{sk_id}"))
102 0 : }
103 :
104 0 : pub fn datadir_path(&self) -> PathBuf {
105 0 : SafekeeperNode::datadir_path_by_id(&self.env, self.id)
106 0 : }
107 :
108 0 : pub fn pid_file(&self) -> Utf8PathBuf {
109 0 : Utf8PathBuf::from_path_buf(self.datadir_path().join("safekeeper.pid"))
110 0 : .expect("non-Unicode path")
111 0 : }
112 :
113 0 : pub async fn start(&self, extra_opts: Vec<String>) -> anyhow::Result<()> {
114 0 : print!(
115 0 : "Starting safekeeper at '{}' in '{}'",
116 0 : self.pg_connection_config.raw_address(),
117 0 : self.datadir_path().display()
118 0 : );
119 0 : io::stdout().flush().unwrap();
120 0 :
121 0 : let listen_pg = format!("{}:{}", self.listen_addr, self.conf.pg_port);
122 0 : let listen_http = format!("{}:{}", self.listen_addr, self.conf.http_port);
123 0 : let id = self.id;
124 0 : let datadir = self.datadir_path();
125 0 :
126 0 : let id_string = id.to_string();
127 0 : // TODO: add availability_zone to the config.
128 0 : // Right now we just specify any value here and use it to check metrics in tests.
129 0 : let availability_zone = format!("sk-{}", id_string);
130 :
131 0 : let mut args = vec![
132 0 : "-D".to_owned(),
133 0 : datadir
134 0 : .to_str()
135 0 : .with_context(|| {
136 0 : format!("Datadir path {datadir:?} cannot be represented as a unicode string")
137 0 : })?
138 0 : .to_owned(),
139 0 : "--id".to_owned(),
140 0 : id_string,
141 0 : "--listen-pg".to_owned(),
142 0 : listen_pg,
143 0 : "--listen-http".to_owned(),
144 0 : listen_http,
145 0 : "--availability-zone".to_owned(),
146 0 : availability_zone,
147 : ];
148 0 : if let Some(pg_tenant_only_port) = self.conf.pg_tenant_only_port {
149 0 : let listen_pg_tenant_only = format!("{}:{}", self.listen_addr, pg_tenant_only_port);
150 0 : args.extend(["--listen-pg-tenant-only".to_owned(), listen_pg_tenant_only]);
151 0 : }
152 0 : if !self.conf.sync {
153 0 : args.push("--no-sync".to_owned());
154 0 : }
155 :
156 0 : let broker_endpoint = format!("{}", self.env.broker.client_url());
157 0 : args.extend(["--broker-endpoint".to_owned(), broker_endpoint]);
158 0 :
159 0 : let mut backup_threads = String::new();
160 0 : if let Some(threads) = self.conf.backup_threads {
161 0 : backup_threads = threads.to_string();
162 0 : args.extend(["--backup-threads".to_owned(), backup_threads]);
163 0 : } else {
164 0 : drop(backup_threads);
165 0 : }
166 :
167 0 : if let Some(ref remote_storage) = self.conf.remote_storage {
168 0 : args.extend(["--remote-storage".to_owned(), remote_storage.clone()]);
169 0 : }
170 :
171 0 : let key_path = self.env.base_data_dir.join("auth_public_key.pem");
172 0 : if self.conf.auth_enabled {
173 0 : let key_path_string = key_path
174 0 : .to_str()
175 0 : .with_context(|| {
176 0 : format!("Key path {key_path:?} cannot be represented as a unicode string")
177 0 : })?
178 0 : .to_owned();
179 0 : args.extend([
180 0 : "--pg-auth-public-key-path".to_owned(),
181 0 : key_path_string.clone(),
182 0 : ]);
183 0 : args.extend([
184 0 : "--pg-tenant-only-auth-public-key-path".to_owned(),
185 0 : key_path_string.clone(),
186 0 : ]);
187 0 : args.extend([
188 0 : "--http-auth-public-key-path".to_owned(),
189 0 : key_path_string.clone(),
190 0 : ]);
191 0 : }
192 :
193 0 : args.extend(extra_opts);
194 0 :
195 0 : background_process::start_process(
196 0 : &format!("safekeeper-{id}"),
197 0 : &datadir,
198 0 : &self.env.safekeeper_bin(),
199 0 : &args,
200 0 : [],
201 0 : background_process::InitialPidFile::Expect(self.pid_file()),
202 0 : || async {
203 0 : match self.check_status().await {
204 0 : Ok(()) => Ok(true),
205 0 : Err(SafekeeperHttpError::Transport(_)) => Ok(false),
206 0 : Err(e) => Err(anyhow::anyhow!("Failed to check node status: {e}")),
207 0 : }
208 0 : },
209 0 : )
210 0 : .await
211 0 : }
212 :
213 : ///
214 : /// Stop the server.
215 : ///
216 : /// If 'immediate' is true, we use SIGQUIT, killing the process immediately.
217 : /// Otherwise we use SIGTERM, triggering a clean shutdown
218 : ///
219 : /// If the server is not running, returns success
220 : ///
221 0 : pub fn stop(&self, immediate: bool) -> anyhow::Result<()> {
222 0 : background_process::stop_process(
223 0 : immediate,
224 0 : &format!("safekeeper {}", self.id),
225 0 : &self.pid_file(),
226 0 : )
227 0 : }
228 :
229 0 : fn http_request<U: IntoUrl>(&self, method: Method, url: U) -> reqwest::RequestBuilder {
230 0 : // TODO: authentication
231 0 : //if self.env.auth_type == AuthType::NeonJWT {
232 0 : // builder = builder.bearer_auth(&self.env.safekeeper_auth_token)
233 0 : //}
234 0 : self.http_client.request(method, url)
235 0 : }
236 :
237 0 : pub async fn check_status(&self) -> Result<()> {
238 0 : self.http_request(Method::GET, format!("{}/{}", self.http_base_url, "status"))
239 0 : .send()
240 0 : .await?
241 0 : .error_from_body()
242 0 : .await?;
243 0 : Ok(())
244 0 : }
245 : }
|