Line data Source code
1 : //! Safekeeper communication endpoint to WAL proposer (compute node).
2 : //! Gets messages from the network, passes them down to consensus module and
3 : //! sends replies back.
4 :
5 : use std::collections::HashMap;
6 : use std::sync::Arc;
7 : use std::time::Duration;
8 :
9 : use anyhow::{Result, bail};
10 : use bytes::{Bytes, BytesMut};
11 : use camino::Utf8PathBuf;
12 : use desim::executor::{self, PollSome};
13 : use desim::network::TCP;
14 : use desim::node_os::NodeOs;
15 : use desim::proto::{AnyMessage, NetEvent, NodeEvent};
16 : use http::Uri;
17 : use safekeeper::SafeKeeperConf;
18 : use safekeeper::safekeeper::{
19 : ProposerAcceptorMessage, SK_PROTO_VERSION_3, SafeKeeper, UNKNOWN_SERVER_VERSION,
20 : };
21 : use safekeeper::state::{TimelinePersistentState, TimelineState};
22 : use safekeeper::timeline::TimelineError;
23 : use safekeeper::wal_storage::Storage;
24 : use safekeeper_api::ServerInfo;
25 : use safekeeper_api::membership::Configuration;
26 : use tracing::{debug, info_span, warn};
27 : use utils::id::{NodeId, TenantId, TenantTimelineId, TimelineId};
28 : use utils::lsn::Lsn;
29 :
30 : use super::safekeeper_disk::{DiskStateStorage, DiskWALStorage, SafekeeperDisk, TimelineDisk};
31 :
32 : struct SharedState {
33 : sk: SafeKeeper<DiskStateStorage, DiskWALStorage>,
34 : disk: Arc<TimelineDisk>,
35 : }
36 :
37 : struct GlobalMap {
38 : timelines: HashMap<TenantTimelineId, SharedState>,
39 : conf: SafeKeeperConf,
40 : disk: Arc<SafekeeperDisk>,
41 : }
42 :
43 : impl GlobalMap {
44 : /// Restores global state from disk.
45 9958 : fn new(disk: Arc<SafekeeperDisk>, conf: SafeKeeperConf) -> Result<Self> {
46 9958 : let mut timelines = HashMap::new();
47 :
48 9958 : for (&ttid, disk) in disk.timelines.lock().iter() {
49 7587 : debug!("loading timeline {}", ttid);
50 7587 : let state = disk.state.lock().clone();
51 7587 :
52 7587 : if state.server.wal_seg_size == 0 {
53 0 : bail!(TimelineError::UninitializedWalSegSize(ttid));
54 7587 : }
55 7587 :
56 7587 : if state.server.pg_version == UNKNOWN_SERVER_VERSION {
57 0 : bail!(TimelineError::UninitialinzedPgVersion(ttid));
58 7587 : }
59 7587 :
60 7587 : if state.commit_lsn < state.local_start_lsn {
61 0 : bail!(
62 0 : "commit_lsn {} is smaller than local_start_lsn {}",
63 0 : state.commit_lsn,
64 0 : state.local_start_lsn
65 0 : );
66 7587 : }
67 7587 :
68 7587 : let control_store = DiskStateStorage::new(disk.clone());
69 7587 : let wal_store = DiskWALStorage::new(disk.clone(), &control_store)?;
70 :
71 7587 : let sk = SafeKeeper::new(TimelineState::new(control_store), wal_store, conf.my_id)?;
72 7587 : timelines.insert(
73 7587 : ttid,
74 7587 : SharedState {
75 7587 : sk,
76 7587 : disk: disk.clone(),
77 7587 : },
78 7587 : );
79 : }
80 :
81 9958 : Ok(Self {
82 9958 : timelines,
83 9958 : conf,
84 9958 : disk,
85 9958 : })
86 9958 : }
87 :
88 1458 : fn create(&mut self, ttid: TenantTimelineId, server_info: ServerInfo) -> Result<()> {
89 1458 : if self.timelines.contains_key(&ttid) {
90 0 : bail!("timeline {} already exists", ttid);
91 1458 : }
92 1458 :
93 1458 : debug!("creating new timeline {}", ttid);
94 :
95 1458 : let commit_lsn = Lsn::INVALID;
96 1458 : let local_start_lsn = Lsn::INVALID;
97 :
98 1458 : let state = TimelinePersistentState::new(
99 1458 : &ttid,
100 1458 : Configuration::empty(),
101 1458 : server_info,
102 1458 : commit_lsn,
103 1458 : local_start_lsn,
104 1458 : )?;
105 :
106 1458 : let disk_timeline = self.disk.put_state(&ttid, state);
107 1458 : let control_store = DiskStateStorage::new(disk_timeline.clone());
108 1458 : let wal_store = DiskWALStorage::new(disk_timeline.clone(), &control_store)?;
109 :
110 1458 : let sk = SafeKeeper::new(
111 1458 : TimelineState::new(control_store),
112 1458 : wal_store,
113 1458 : self.conf.my_id,
114 1458 : )?;
115 :
116 1458 : self.timelines.insert(
117 1458 : ttid,
118 1458 : SharedState {
119 1458 : sk,
120 1458 : disk: disk_timeline,
121 1458 : },
122 1458 : );
123 1458 : Ok(())
124 1458 : }
125 :
126 29242 : fn get(&mut self, ttid: &TenantTimelineId) -> &mut SharedState {
127 29242 : self.timelines.get_mut(ttid).expect("timeline must exist")
128 29242 : }
129 :
130 20192 : fn has_tli(&self, ttid: &TenantTimelineId) -> bool {
131 20192 : self.timelines.contains_key(ttid)
132 20192 : }
133 : }
134 :
135 : /// State of a single connection to walproposer.
136 : struct ConnState {
137 : tcp: TCP,
138 :
139 : greeting: bool,
140 : ttid: TenantTimelineId,
141 : flush_pending: bool,
142 :
143 : runtime: tokio::runtime::Runtime,
144 : }
145 :
146 9958 : pub fn run_server(os: NodeOs, disk: Arc<SafekeeperDisk>) -> Result<()> {
147 9958 : let _enter = info_span!("safekeeper", id = os.id()).entered();
148 9958 : debug!("started server");
149 9958 : os.log_event("started;safekeeper".to_owned());
150 9958 : let conf = SafeKeeperConf {
151 9958 : workdir: Utf8PathBuf::from("."),
152 9958 : my_id: NodeId(os.id() as u64),
153 9958 : listen_pg_addr: String::new(),
154 9958 : listen_http_addr: String::new(),
155 9958 : listen_https_addr: None,
156 9958 : no_sync: false,
157 9958 : broker_endpoint: "/".parse::<Uri>().unwrap(),
158 9958 : broker_keepalive_interval: Duration::from_secs(0),
159 9958 : heartbeat_timeout: Duration::from_secs(0),
160 9958 : remote_storage: None,
161 9958 : max_offloader_lag_bytes: 0,
162 9958 : wal_backup_enabled: false,
163 9958 : listen_pg_addr_tenant_only: None,
164 9958 : advertise_pg_addr: None,
165 9958 : availability_zone: None,
166 9958 : peer_recovery_enabled: false,
167 9958 : backup_parallel_jobs: 0,
168 9958 : pg_auth: None,
169 9958 : pg_tenant_only_auth: None,
170 9958 : http_auth: None,
171 9958 : sk_auth_token: None,
172 9958 : current_thread_runtime: false,
173 9958 : walsenders_keep_horizon: false,
174 9958 : partial_backup_timeout: Duration::from_secs(0),
175 9958 : disable_periodic_broker_push: false,
176 9958 : enable_offload: false,
177 9958 : delete_offloaded_wal: false,
178 9958 : control_file_save_interval: Duration::from_secs(1),
179 9958 : partial_backup_concurrency: 1,
180 9958 : eviction_min_resident: Duration::ZERO,
181 9958 : wal_reader_fanout: false,
182 9958 : max_delta_for_fanout: None,
183 9958 : ssl_key_file: Utf8PathBuf::from(""),
184 9958 : ssl_cert_file: Utf8PathBuf::from(""),
185 9958 : ssl_cert_reload_period: Duration::ZERO,
186 9958 : ssl_ca_certs: Vec::new(),
187 9958 : use_https_safekeeper_api: false,
188 9958 : enable_tls_wal_service_api: false,
189 9958 : };
190 :
191 9958 : let mut global = GlobalMap::new(disk, conf.clone())?;
192 9958 : let mut conns: HashMap<usize, ConnState> = HashMap::new();
193 :
194 9958 : for (&_ttid, shared_state) in global.timelines.iter_mut() {
195 7587 : let flush_lsn = shared_state.sk.wal_store.flush_lsn();
196 7587 : let commit_lsn = shared_state.sk.state.commit_lsn;
197 7587 : os.log_event(format!("tli_loaded;{};{}", flush_lsn.0, commit_lsn.0));
198 7587 : }
199 :
200 9958 : let node_events = os.node_events();
201 9958 : let mut epoll_vec: Vec<Box<dyn PollSome>> = vec![];
202 9958 : let mut epoll_idx: Vec<usize> = vec![];
203 :
204 : // TODO: batch events processing (multiple events per tick)
205 : loop {
206 76960 : epoll_vec.clear();
207 76960 : epoll_idx.clear();
208 76960 :
209 76960 : // node events channel
210 76960 : epoll_vec.push(Box::new(node_events.clone()));
211 76960 : epoll_idx.push(0);
212 :
213 : // tcp connections
214 275748 : for conn in conns.values() {
215 275748 : epoll_vec.push(Box::new(conn.tcp.recv_chan()));
216 275748 : epoll_idx.push(conn.tcp.connection_id());
217 275748 : }
218 :
219 : // waiting for the next message
220 76960 : let index = executor::epoll_chans(&epoll_vec, -1).unwrap();
221 76960 :
222 76960 : if index == 0 {
223 : // got a new connection
224 26012 : match node_events.must_recv() {
225 26012 : NodeEvent::Accept(tcp) => {
226 26012 : conns.insert(
227 26012 : tcp.connection_id(),
228 26012 : ConnState {
229 26012 : tcp,
230 26012 : greeting: false,
231 26012 : ttid: TenantTimelineId::empty(),
232 26012 : flush_pending: false,
233 26012 : runtime: tokio::runtime::Builder::new_current_thread().build()?,
234 : },
235 : );
236 : }
237 0 : NodeEvent::Internal(_) => unreachable!(),
238 : }
239 26012 : continue;
240 50948 : }
241 50948 :
242 50948 : let connection_id = epoll_idx[index];
243 50948 : let conn = conns.get_mut(&connection_id).unwrap();
244 50948 : let mut next_event = Some(conn.tcp.recv_chan().must_recv());
245 :
246 : loop {
247 82710 : let event = match next_event {
248 41911 : Some(event) => event,
249 40799 : None => break,
250 : };
251 :
252 41911 : match event {
253 26808 : NetEvent::Message(msg) => {
254 26808 : let res = conn.process_any(msg, &mut global);
255 26808 : if res.is_err() {
256 10149 : let e = res.unwrap_err();
257 10149 : let estr = e.to_string();
258 10149 : if !estr.contains("finished processing START_REPLICATION") {
259 9958 : warn!("conn {:?} error: {:?}", connection_id, e);
260 9958 : panic!("unexpected error at safekeeper: {:#}", e);
261 191 : }
262 191 : conns.remove(&connection_id);
263 191 : break;
264 16659 : }
265 : }
266 15103 : NetEvent::Closed => {
267 15103 : // TODO: remove from conns?
268 15103 : }
269 : }
270 :
271 31762 : next_event = conn.tcp.recv_chan().try_recv();
272 : }
273 :
274 179152 : conns.retain(|_, conn| {
275 179152 : let res = conn.flush(&mut global);
276 179152 : if res.is_err() {
277 0 : debug!("conn {:?} error: {:?}", conn.tcp, res);
278 179152 : }
279 179152 : res.is_ok()
280 179152 : });
281 : }
282 0 : }
283 :
284 : impl ConnState {
285 : /// Process a message from the network. It can be START_REPLICATION request or a valid ProposerAcceptorMessage message.
286 26808 : fn process_any(&mut self, any: AnyMessage, global: &mut GlobalMap) -> Result<()> {
287 26808 : if let AnyMessage::Bytes(copy_data) = any {
288 26808 : let repl_prefix = b"START_REPLICATION ";
289 26808 : if !self.greeting && copy_data.starts_with(repl_prefix) {
290 191 : self.process_start_replication(copy_data.slice(repl_prefix.len()..), global)?;
291 191 : bail!("finished processing START_REPLICATION")
292 26617 : }
293 :
294 26617 : let msg = ProposerAcceptorMessage::parse(copy_data, SK_PROTO_VERSION_3)?;
295 26617 : debug!("got msg: {:?}", msg);
296 26617 : self.process(msg, global)
297 : } else {
298 0 : bail!("unexpected message, expected AnyMessage::Bytes");
299 : }
300 26808 : }
301 :
302 : /// Process START_REPLICATION request.
303 191 : fn process_start_replication(
304 191 : &mut self,
305 191 : copy_data: Bytes,
306 191 : global: &mut GlobalMap,
307 191 : ) -> Result<()> {
308 : // format is "<tenant_id> <timeline_id> <start_lsn> <end_lsn>"
309 191 : let str = String::from_utf8(copy_data.to_vec())?;
310 :
311 191 : let mut parts = str.split(' ');
312 191 : let tenant_id = parts.next().unwrap().parse::<TenantId>()?;
313 191 : let timeline_id = parts.next().unwrap().parse::<TimelineId>()?;
314 191 : let start_lsn = parts.next().unwrap().parse::<u64>()?;
315 191 : let end_lsn = parts.next().unwrap().parse::<u64>()?;
316 :
317 191 : let ttid = TenantTimelineId::new(tenant_id, timeline_id);
318 191 : let shared_state = global.get(&ttid);
319 191 :
320 191 : // read bytes from start_lsn to end_lsn
321 191 : let mut buf = vec![0; (end_lsn - start_lsn) as usize];
322 191 : shared_state.disk.wal.lock().read(start_lsn, &mut buf);
323 191 :
324 191 : // send bytes to the client
325 191 : self.tcp.send(AnyMessage::Bytes(Bytes::from(buf)));
326 191 : Ok(())
327 191 : }
328 :
329 : /// Get or create a timeline.
330 20192 : fn init_timeline(
331 20192 : &mut self,
332 20192 : ttid: TenantTimelineId,
333 20192 : server_info: ServerInfo,
334 20192 : global: &mut GlobalMap,
335 20192 : ) -> Result<()> {
336 20192 : self.ttid = ttid;
337 20192 : if global.has_tli(&ttid) {
338 18734 : return Ok(());
339 1458 : }
340 1458 :
341 1458 : global.create(ttid, server_info)
342 20192 : }
343 :
344 : /// Process a ProposerAcceptorMessage.
345 26617 : fn process(&mut self, msg: ProposerAcceptorMessage, global: &mut GlobalMap) -> Result<()> {
346 26617 : if !self.greeting {
347 20192 : self.greeting = true;
348 20192 :
349 20192 : match msg {
350 20192 : ProposerAcceptorMessage::Greeting(ref greeting) => {
351 20192 : tracing::info!(
352 0 : "start handshake with walproposer {:?} {:?}",
353 : self.tcp,
354 : greeting
355 : );
356 20192 : let server_info = ServerInfo {
357 20192 : pg_version: greeting.pg_version,
358 20192 : system_id: greeting.system_id,
359 20192 : wal_seg_size: greeting.wal_seg_size,
360 20192 : };
361 20192 : let ttid = TenantTimelineId::new(greeting.tenant_id, greeting.timeline_id);
362 20192 : self.init_timeline(ttid, server_info, global)?
363 : }
364 : _ => {
365 0 : bail!("unexpected message {msg:?} instead of greeting");
366 : }
367 : }
368 6425 : }
369 :
370 26617 : let tli = global.get(&self.ttid);
371 26617 :
372 26617 : match msg {
373 2930 : ProposerAcceptorMessage::AppendRequest(append_request) => {
374 2930 : self.flush_pending = true;
375 2930 : self.process_sk_msg(
376 2930 : tli,
377 2930 : &ProposerAcceptorMessage::NoFlushAppendRequest(append_request),
378 2930 : )?;
379 : }
380 23687 : other => {
381 23687 : self.process_sk_msg(tli, &other)?;
382 : }
383 : }
384 :
385 26617 : Ok(())
386 26617 : }
387 :
388 : /// Process FlushWAL if needed.
389 179152 : fn flush(&mut self, global: &mut GlobalMap) -> Result<()> {
390 179152 : // TODO: try to add extra flushes in simulation, to verify that extra flushes don't break anything
391 179152 : if !self.flush_pending {
392 176718 : return Ok(());
393 2434 : }
394 2434 : self.flush_pending = false;
395 2434 : let shared_state = global.get(&self.ttid);
396 2434 : self.process_sk_msg(shared_state, &ProposerAcceptorMessage::FlushWAL)
397 179152 : }
398 :
399 : /// Make safekeeper process a message and send a reply to the TCP
400 29051 : fn process_sk_msg(
401 29051 : &mut self,
402 29051 : shared_state: &mut SharedState,
403 29051 : msg: &ProposerAcceptorMessage,
404 29051 : ) -> Result<()> {
405 29051 : let mut reply = self.runtime.block_on(shared_state.sk.process_msg(msg))?;
406 29051 : if let Some(reply) = &mut reply {
407 : // TODO: if this is AppendResponse, fill in proper hot standby feedback and disk consistent lsn
408 :
409 25413 : let mut buf = BytesMut::with_capacity(128);
410 25413 : reply.serialize(&mut buf, SK_PROTO_VERSION_3)?;
411 :
412 25413 : self.tcp.send(AnyMessage::Bytes(buf.into()));
413 3638 : }
414 29051 : Ok(())
415 29051 : }
416 : }
417 :
418 : impl Drop for ConnState {
419 25984 : fn drop(&mut self) {
420 25984 : debug!("dropping conn: {:?}", self.tcp);
421 25984 : if !std::thread::panicking() {
422 191 : self.tcp.close();
423 25793 : }
424 : // TODO: clean up non-fsynced WAL
425 25984 : }
426 : }
|