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