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