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