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