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