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