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