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