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