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