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