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