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