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