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