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