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