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