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