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