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