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