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