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