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