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