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