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