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