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