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