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 9595 : fn new(disk: Arc<SafekeeperDisk>, conf: SafeKeeperConf) -> Result<Self> {
46 9595 : let mut timelines = HashMap::new();
47 :
48 9595 : for (&ttid, disk) in disk.timelines.lock().iter() {
49 7240 : debug!("loading timeline {}", ttid);
50 7240 : let state = disk.state.lock().clone();
51 7240 :
52 7240 : if state.server.wal_seg_size == 0 {
53 0 : bail!(TimelineError::UninitializedWalSegSize(ttid));
54 7240 : }
55 7240 :
56 7240 : if state.server.pg_version == UNKNOWN_SERVER_VERSION {
57 0 : bail!(TimelineError::UninitialinzedPgVersion(ttid));
58 7240 : }
59 7240 :
60 7240 : 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 7240 : }
67 7240 :
68 7240 : let control_store = DiskStateStorage::new(disk.clone());
69 7240 : let wal_store = DiskWALStorage::new(disk.clone(), &control_store)?;
70 :
71 7240 : let sk = SafeKeeper::new(TimelineState::new(control_store), wal_store, conf.my_id)?;
72 7240 : timelines.insert(
73 7240 : ttid,
74 7240 : SharedState {
75 7240 : sk,
76 7240 : disk: disk.clone(),
77 7240 : },
78 7240 : );
79 : }
80 :
81 9595 : Ok(Self {
82 9595 : timelines,
83 9595 : conf,
84 9595 : disk,
85 9595 : })
86 9595 : }
87 :
88 1461 : fn create(&mut self, ttid: TenantTimelineId, server_info: ServerInfo) -> Result<()> {
89 1461 : if self.timelines.contains_key(&ttid) {
90 0 : bail!("timeline {} already exists", ttid);
91 1461 : }
92 1461 :
93 1461 : debug!("creating new timeline {}", ttid);
94 :
95 1461 : let commit_lsn = Lsn::INVALID;
96 1461 : let local_start_lsn = Lsn::INVALID;
97 :
98 1461 : let state = TimelinePersistentState::new(
99 1461 : &ttid,
100 1461 : Configuration::empty(),
101 1461 : server_info,
102 1461 : commit_lsn,
103 1461 : local_start_lsn,
104 1461 : )?;
105 :
106 1461 : let disk_timeline = self.disk.put_state(&ttid, state);
107 1461 : let control_store = DiskStateStorage::new(disk_timeline.clone());
108 1461 : let wal_store = DiskWALStorage::new(disk_timeline.clone(), &control_store)?;
109 :
110 1461 : let sk = SafeKeeper::new(
111 1461 : TimelineState::new(control_store),
112 1461 : wal_store,
113 1461 : self.conf.my_id,
114 1461 : )?;
115 :
116 1461 : self.timelines.insert(
117 1461 : ttid,
118 1461 : SharedState {
119 1461 : sk,
120 1461 : disk: disk_timeline,
121 1461 : },
122 1461 : );
123 1461 : Ok(())
124 1461 : }
125 :
126 28950 : fn get(&mut self, ttid: &TenantTimelineId) -> &mut SharedState {
127 28950 : self.timelines.get_mut(ttid).expect("timeline must exist")
128 28950 : }
129 :
130 19099 : fn has_tli(&self, ttid: &TenantTimelineId) -> bool {
131 19099 : self.timelines.contains_key(ttid)
132 19099 : }
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 9595 : pub fn run_server(os: NodeOs, disk: Arc<SafekeeperDisk>) -> Result<()> {
147 9595 : let _enter = info_span!("safekeeper", id = os.id()).entered();
148 9595 : debug!("started server");
149 9595 : os.log_event("started;safekeeper".to_owned());
150 9595 : let conf = SafeKeeperConf {
151 9595 : workdir: Utf8PathBuf::from("."),
152 9595 : my_id: NodeId(os.id() as u64),
153 9595 : listen_pg_addr: String::new(),
154 9595 : listen_http_addr: String::new(),
155 9595 : no_sync: false,
156 9595 : broker_endpoint: "/".parse::<Uri>().unwrap(),
157 9595 : broker_keepalive_interval: Duration::from_secs(0),
158 9595 : heartbeat_timeout: Duration::from_secs(0),
159 9595 : remote_storage: None,
160 9595 : max_offloader_lag_bytes: 0,
161 9595 : wal_backup_enabled: false,
162 9595 : listen_pg_addr_tenant_only: None,
163 9595 : advertise_pg_addr: None,
164 9595 : availability_zone: None,
165 9595 : peer_recovery_enabled: false,
166 9595 : backup_parallel_jobs: 0,
167 9595 : pg_auth: None,
168 9595 : pg_tenant_only_auth: None,
169 9595 : http_auth: None,
170 9595 : sk_auth_token: None,
171 9595 : current_thread_runtime: false,
172 9595 : walsenders_keep_horizon: false,
173 9595 : partial_backup_timeout: Duration::from_secs(0),
174 9595 : disable_periodic_broker_push: false,
175 9595 : enable_offload: false,
176 9595 : delete_offloaded_wal: false,
177 9595 : control_file_save_interval: Duration::from_secs(1),
178 9595 : partial_backup_concurrency: 1,
179 9595 : eviction_min_resident: Duration::ZERO,
180 9595 : wal_reader_fanout: false,
181 9595 : max_delta_for_fanout: None,
182 9595 : };
183 :
184 9595 : let mut global = GlobalMap::new(disk, conf.clone())?;
185 9595 : let mut conns: HashMap<usize, ConnState> = HashMap::new();
186 :
187 9595 : for (&_ttid, shared_state) in global.timelines.iter_mut() {
188 7240 : let flush_lsn = shared_state.sk.wal_store.flush_lsn();
189 7240 : let commit_lsn = shared_state.sk.state.commit_lsn;
190 7240 : os.log_event(format!("tli_loaded;{};{}", flush_lsn.0, commit_lsn.0));
191 7240 : }
192 :
193 9595 : let node_events = os.node_events();
194 9595 : let mut epoll_vec: Vec<Box<dyn PollSome>> = vec![];
195 9595 : let mut epoll_idx: Vec<usize> = vec![];
196 :
197 : // TODO: batch events processing (multiple events per tick)
198 : loop {
199 73060 : epoll_vec.clear();
200 73060 : epoll_idx.clear();
201 73060 :
202 73060 : // node events channel
203 73060 : epoll_vec.push(Box::new(node_events.clone()));
204 73060 : epoll_idx.push(0);
205 :
206 : // tcp connections
207 254890 : for conn in conns.values() {
208 254890 : epoll_vec.push(Box::new(conn.tcp.recv_chan()));
209 254890 : epoll_idx.push(conn.tcp.connection_id());
210 254890 : }
211 :
212 : // waiting for the next message
213 73060 : let index = executor::epoll_chans(&epoll_vec, -1).unwrap();
214 73060 :
215 73060 : if index == 0 {
216 : // got a new connection
217 24518 : match node_events.must_recv() {
218 24518 : NodeEvent::Accept(tcp) => {
219 24518 : conns.insert(
220 24518 : tcp.connection_id(),
221 24518 : ConnState {
222 24518 : tcp,
223 24518 : greeting: false,
224 24518 : ttid: TenantTimelineId::empty(),
225 24518 : flush_pending: false,
226 24518 : runtime: tokio::runtime::Builder::new_current_thread().build()?,
227 : },
228 : );
229 : }
230 0 : NodeEvent::Internal(_) => unreachable!(),
231 : }
232 24518 : continue;
233 48542 : }
234 48542 :
235 48542 : let connection_id = epoll_idx[index];
236 48542 : let conn = conns.get_mut(&connection_id).unwrap();
237 48542 : let mut next_event = Some(conn.tcp.recv_chan().must_recv());
238 :
239 : loop {
240 88308 : let event = match next_event {
241 49586 : Some(event) => event,
242 38722 : None => break,
243 : };
244 :
245 49586 : match event {
246 35777 : NetEvent::Message(msg) => {
247 35777 : let res = conn.process_any(msg, &mut global);
248 35777 : if res.is_err() {
249 9820 : let e = res.unwrap_err();
250 9820 : let estr = e.to_string();
251 9820 : if !estr.contains("finished processing START_REPLICATION") {
252 9595 : warn!("conn {:?} error: {:?}", connection_id, e);
253 0 : panic!("unexpected error at safekeeper: {:#}", e);
254 225 : }
255 225 : conns.remove(&connection_id);
256 225 : break;
257 25957 : }
258 : }
259 13809 : NetEvent::Closed => {
260 13809 : // TODO: remove from conns?
261 13809 : }
262 : }
263 :
264 39766 : next_event = conn.tcp.recv_chan().try_recv();
265 : }
266 :
267 165968 : conns.retain(|_, conn| {
268 165968 : let res = conn.flush(&mut global);
269 165968 : if res.is_err() {
270 0 : debug!("conn {:?} error: {:?}", conn.tcp, res);
271 165968 : }
272 165968 : res.is_ok()
273 165968 : });
274 : }
275 0 : }
276 :
277 : impl ConnState {
278 : /// Process a message from the network. It can be START_REPLICATION request or a valid ProposerAcceptorMessage message.
279 26182 : fn process_any(&mut self, any: AnyMessage, global: &mut GlobalMap) -> Result<()> {
280 26182 : if let AnyMessage::Bytes(copy_data) = any {
281 26182 : let repl_prefix = b"START_REPLICATION ";
282 26182 : if !self.greeting && copy_data.starts_with(repl_prefix) {
283 225 : self.process_start_replication(copy_data.slice(repl_prefix.len()..), global)?;
284 225 : bail!("finished processing START_REPLICATION")
285 25957 : }
286 :
287 25957 : let msg = ProposerAcceptorMessage::parse(copy_data, SK_PROTO_VERSION_3)?;
288 25957 : debug!("got msg: {:?}", msg);
289 25957 : self.process(msg, global)
290 : } else {
291 0 : bail!("unexpected message, expected AnyMessage::Bytes");
292 : }
293 26182 : }
294 :
295 : /// Process START_REPLICATION request.
296 225 : fn process_start_replication(
297 225 : &mut self,
298 225 : copy_data: Bytes,
299 225 : global: &mut GlobalMap,
300 225 : ) -> Result<()> {
301 : // format is "<tenant_id> <timeline_id> <start_lsn> <end_lsn>"
302 225 : let str = String::from_utf8(copy_data.to_vec())?;
303 :
304 225 : let mut parts = str.split(' ');
305 225 : let tenant_id = parts.next().unwrap().parse::<TenantId>()?;
306 225 : let timeline_id = parts.next().unwrap().parse::<TimelineId>()?;
307 225 : let start_lsn = parts.next().unwrap().parse::<u64>()?;
308 225 : let end_lsn = parts.next().unwrap().parse::<u64>()?;
309 :
310 225 : let ttid = TenantTimelineId::new(tenant_id, timeline_id);
311 225 : let shared_state = global.get(&ttid);
312 225 :
313 225 : // read bytes from start_lsn to end_lsn
314 225 : let mut buf = vec![0; (end_lsn - start_lsn) as usize];
315 225 : shared_state.disk.wal.lock().read(start_lsn, &mut buf);
316 225 :
317 225 : // send bytes to the client
318 225 : self.tcp.send(AnyMessage::Bytes(Bytes::from(buf)));
319 225 : Ok(())
320 225 : }
321 :
322 : /// Get or create a timeline.
323 19099 : fn init_timeline(
324 19099 : &mut self,
325 19099 : ttid: TenantTimelineId,
326 19099 : server_info: ServerInfo,
327 19099 : global: &mut GlobalMap,
328 19099 : ) -> Result<()> {
329 19099 : self.ttid = ttid;
330 19099 : if global.has_tli(&ttid) {
331 17638 : return Ok(());
332 1461 : }
333 1461 :
334 1461 : global.create(ttid, server_info)
335 19099 : }
336 :
337 : /// Process a ProposerAcceptorMessage.
338 25957 : fn process(&mut self, msg: ProposerAcceptorMessage, global: &mut GlobalMap) -> Result<()> {
339 25957 : if !self.greeting {
340 19099 : self.greeting = true;
341 19099 :
342 19099 : match msg {
343 19099 : ProposerAcceptorMessage::Greeting(ref greeting) => {
344 19099 : tracing::info!(
345 0 : "start handshake with walproposer {:?} {:?}",
346 : self.tcp,
347 : greeting
348 : );
349 19099 : let server_info = ServerInfo {
350 19099 : pg_version: greeting.pg_version,
351 19099 : system_id: greeting.system_id,
352 19099 : wal_seg_size: greeting.wal_seg_size,
353 19099 : };
354 19099 : let ttid = TenantTimelineId::new(greeting.tenant_id, greeting.timeline_id);
355 19099 : self.init_timeline(ttid, server_info, global)?
356 : }
357 : _ => {
358 0 : bail!("unexpected message {msg:?} instead of greeting");
359 : }
360 : }
361 6858 : }
362 :
363 25957 : let tli = global.get(&self.ttid);
364 25957 :
365 25957 : match msg {
366 3343 : ProposerAcceptorMessage::AppendRequest(append_request) => {
367 3343 : self.flush_pending = true;
368 3343 : self.process_sk_msg(
369 3343 : tli,
370 3343 : &ProposerAcceptorMessage::NoFlushAppendRequest(append_request),
371 3343 : )?;
372 : }
373 22614 : other => {
374 22614 : self.process_sk_msg(tli, &other)?;
375 : }
376 : }
377 :
378 25957 : Ok(())
379 25957 : }
380 :
381 : /// Process FlushWAL if needed.
382 165968 : fn flush(&mut self, global: &mut GlobalMap) -> Result<()> {
383 165968 : // TODO: try to add extra flushes in simulation, to verify that extra flushes don't break anything
384 165968 : if !self.flush_pending {
385 163200 : return Ok(());
386 2768 : }
387 2768 : self.flush_pending = false;
388 2768 : let shared_state = global.get(&self.ttid);
389 2768 : self.process_sk_msg(shared_state, &ProposerAcceptorMessage::FlushWAL)
390 165968 : }
391 :
392 : /// Make safekeeper process a message and send a reply to the TCP
393 28725 : fn process_sk_msg(
394 28725 : &mut self,
395 28725 : shared_state: &mut SharedState,
396 28725 : msg: &ProposerAcceptorMessage,
397 28725 : ) -> Result<()> {
398 28725 : let mut reply = self.runtime.block_on(shared_state.sk.process_msg(msg))?;
399 28725 : if let Some(reply) = &mut reply {
400 : // TODO: if this is AppendResponse, fill in proper hot standby feedback and disk consistent lsn
401 :
402 24559 : let mut buf = BytesMut::with_capacity(128);
403 24559 : reply.serialize(&mut buf, SK_PROTO_VERSION_3)?;
404 :
405 24559 : self.tcp.send(AnyMessage::Bytes(buf.into()));
406 4166 : }
407 28725 : Ok(())
408 28725 : }
409 : }
410 :
411 : impl Drop for ConnState {
412 24490 : fn drop(&mut self) {
413 24490 : debug!("dropping conn: {:?}", self.tcp);
414 24490 : if !std::thread::panicking() {
415 225 : self.tcp.close();
416 24265 : }
417 : // TODO: clean up non-fsynced WAL
418 24490 : }
419 : }
|