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