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