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