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