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