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