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