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