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