Line data Source code
1 : //! [`super::VirtualFile`] supports different IO engines.
2 : //!
3 : //! The [`IoEngineKind`] enum identifies them.
4 : //!
5 : //! The choice of IO engine is global.
6 : //! Initialize using [`init`].
7 : //!
8 : //! Then use [`get`] and [`super::OpenOptions`].
9 : //!
10 : //!
11 :
12 : #[cfg(target_os = "linux")]
13 : pub(super) mod tokio_epoll_uring_ext;
14 :
15 : use tokio_epoll_uring::{IoBuf, Slice};
16 : use tracing::Instrument;
17 :
18 : pub(crate) use super::api::IoEngineKind;
19 : #[derive(Clone, Copy)]
20 : #[repr(u8)]
21 : pub(crate) enum IoEngine {
22 : NotSet,
23 : StdFs,
24 : #[cfg(target_os = "linux")]
25 : TokioEpollUring,
26 : }
27 :
28 : impl From<IoEngineKind> for IoEngine {
29 164 : fn from(value: IoEngineKind) -> Self {
30 164 : match value {
31 82 : IoEngineKind::StdFs => IoEngine::StdFs,
32 : #[cfg(target_os = "linux")]
33 82 : IoEngineKind::TokioEpollUring => IoEngine::TokioEpollUring,
34 : }
35 164 : }
36 : }
37 :
38 : impl TryFrom<u8> for IoEngine {
39 : type Error = u8;
40 :
41 1539816 : fn try_from(value: u8) -> Result<Self, Self::Error> {
42 1539816 : Ok(match value {
43 1539816 : v if v == (IoEngine::NotSet as u8) => IoEngine::NotSet,
44 1539652 : v if v == (IoEngine::StdFs as u8) => IoEngine::StdFs,
45 : #[cfg(target_os = "linux")]
46 769687 : v if v == (IoEngine::TokioEpollUring as u8) => IoEngine::TokioEpollUring,
47 0 : x => return Err(x),
48 : })
49 1539816 : }
50 : }
51 :
52 : static IO_ENGINE: AtomicU8 = AtomicU8::new(IoEngine::NotSet as u8);
53 :
54 164 : pub(crate) fn set(engine_kind: IoEngineKind) {
55 164 : let engine: IoEngine = engine_kind.into();
56 164 : IO_ENGINE.store(engine as u8, std::sync::atomic::Ordering::Relaxed);
57 164 : #[cfg(not(test))]
58 164 : {
59 164 : let metric = &crate::metrics::virtual_file_io_engine::KIND;
60 164 : metric.reset();
61 164 : metric
62 164 : .with_label_values(&[&format!("{engine_kind}")])
63 164 : .set(1);
64 164 : }
65 164 : }
66 :
67 : #[cfg(not(test))]
68 0 : pub(super) fn init(engine_kind: IoEngineKind) {
69 0 : set(engine_kind);
70 0 : }
71 :
72 : /// Longer-term, this API should only be used by [`super::VirtualFile`].
73 1539816 : pub(crate) fn get() -> IoEngine {
74 1539816 : let cur = IoEngine::try_from(IO_ENGINE.load(Ordering::Relaxed)).unwrap();
75 1539816 : if cfg!(test) {
76 1539816 : let env_var_name = "NEON_PAGESERVER_UNIT_TEST_VIRTUAL_FILE_IOENGINE";
77 1539816 : match cur {
78 : IoEngine::NotSet => {
79 164 : let kind = match std::env::var(env_var_name) {
80 164 : Ok(v) => match v.parse::<IoEngineKind>() {
81 164 : Ok(engine_kind) => engine_kind,
82 0 : Err(e) => {
83 0 : panic!("invalid VirtualFile io engine for env var {env_var_name}: {e:#}: {v:?}")
84 : }
85 : },
86 : Err(std::env::VarError::NotPresent) => {
87 0 : crate::config::defaults::DEFAULT_VIRTUAL_FILE_IO_ENGINE
88 0 : .parse()
89 0 : .unwrap()
90 : }
91 : Err(std::env::VarError::NotUnicode(_)) => {
92 0 : panic!("env var {env_var_name} is not unicode");
93 : }
94 : };
95 164 : self::set(kind);
96 164 : self::get()
97 : }
98 1539652 : x => x,
99 : }
100 : } else {
101 0 : cur
102 : }
103 1539816 : }
104 :
105 : use std::{
106 : os::unix::prelude::FileExt,
107 : sync::atomic::{AtomicU8, Ordering},
108 : };
109 :
110 : use super::{owned_buffers_io::slice::SliceExt, FileGuard, Metadata};
111 :
112 : #[cfg(target_os = "linux")]
113 2 : fn epoll_uring_error_to_std(e: tokio_epoll_uring::Error<std::io::Error>) -> std::io::Error {
114 2 : match e {
115 2 : tokio_epoll_uring::Error::Op(e) => e,
116 0 : tokio_epoll_uring::Error::System(system) => {
117 0 : std::io::Error::new(std::io::ErrorKind::Other, system)
118 : }
119 : }
120 2 : }
121 :
122 : impl IoEngine {
123 411984 : pub(super) async fn read_at<Buf>(
124 411984 : &self,
125 411984 : file_guard: FileGuard,
126 411984 : offset: u64,
127 411984 : mut slice: tokio_epoll_uring::Slice<Buf>,
128 411984 : ) -> (
129 411984 : (FileGuard, tokio_epoll_uring::Slice<Buf>),
130 411984 : std::io::Result<usize>,
131 411984 : )
132 411984 : where
133 411984 : Buf: tokio_epoll_uring::IoBufMut + Send,
134 411984 : {
135 411984 : match self {
136 0 : IoEngine::NotSet => panic!("not initialized"),
137 : IoEngine::StdFs => {
138 206133 : let rust_slice = slice.as_mut_rust_slice_full_zeroed();
139 206133 : let res = file_guard.with_std_file(|std_file| std_file.read_at(rust_slice, offset));
140 206133 : ((file_guard, slice), res)
141 : }
142 : #[cfg(target_os = "linux")]
143 : IoEngine::TokioEpollUring => {
144 205851 : let system = tokio_epoll_uring_ext::thread_local_system().await;
145 205895 : let (resources, res) = system.read(file_guard, offset, slice).await;
146 205851 : (resources, res.map_err(epoll_uring_error_to_std))
147 : }
148 : }
149 411984 : }
150 2731 : pub(super) async fn sync_all(&self, file_guard: FileGuard) -> (FileGuard, std::io::Result<()>) {
151 2731 : match self {
152 0 : IoEngine::NotSet => panic!("not initialized"),
153 : IoEngine::StdFs => {
154 1364 : let res = file_guard.with_std_file(|std_file| std_file.sync_all());
155 1364 : (file_guard, res)
156 : }
157 : #[cfg(target_os = "linux")]
158 : IoEngine::TokioEpollUring => {
159 1367 : let system = tokio_epoll_uring_ext::thread_local_system().await;
160 1368 : let (resources, res) = system.fsync(file_guard).await;
161 1367 : (resources, res.map_err(epoll_uring_error_to_std))
162 : }
163 : }
164 2731 : }
165 0 : pub(super) async fn sync_data(
166 0 : &self,
167 0 : file_guard: FileGuard,
168 0 : ) -> (FileGuard, std::io::Result<()>) {
169 0 : match self {
170 0 : IoEngine::NotSet => panic!("not initialized"),
171 : IoEngine::StdFs => {
172 0 : let res = file_guard.with_std_file(|std_file| std_file.sync_data());
173 0 : (file_guard, res)
174 : }
175 : #[cfg(target_os = "linux")]
176 : IoEngine::TokioEpollUring => {
177 0 : let system = tokio_epoll_uring_ext::thread_local_system().await;
178 0 : let (resources, res) = system.fdatasync(file_guard).await;
179 0 : (resources, res.map_err(epoll_uring_error_to_std))
180 : }
181 : }
182 0 : }
183 1568 : pub(super) async fn metadata(
184 1568 : &self,
185 1568 : file_guard: FileGuard,
186 1568 : ) -> (FileGuard, std::io::Result<Metadata>) {
187 1568 : match self {
188 0 : IoEngine::NotSet => panic!("not initialized"),
189 : IoEngine::StdFs => {
190 784 : let res =
191 784 : file_guard.with_std_file(|std_file| std_file.metadata().map(Metadata::from));
192 784 : (file_guard, res)
193 : }
194 : #[cfg(target_os = "linux")]
195 : IoEngine::TokioEpollUring => {
196 784 : let system = tokio_epoll_uring_ext::thread_local_system().await;
197 784 : let (resources, res) = system.statx(file_guard).await;
198 784 : (
199 784 : resources,
200 784 : res.map_err(epoll_uring_error_to_std).map(Metadata::from),
201 784 : )
202 : }
203 : }
204 1568 : }
205 1116496 : pub(super) async fn write_at<B: IoBuf + Send>(
206 1116496 : &self,
207 1116496 : file_guard: FileGuard,
208 1116496 : offset: u64,
209 1116496 : buf: Slice<B>,
210 1116496 : ) -> ((FileGuard, Slice<B>), std::io::Result<usize>) {
211 1116496 : match self {
212 0 : IoEngine::NotSet => panic!("not initialized"),
213 : IoEngine::StdFs => {
214 558249 : let result = file_guard.with_std_file(|std_file| std_file.write_at(&buf, offset));
215 558249 : ((file_guard, buf), result)
216 : }
217 : #[cfg(target_os = "linux")]
218 : IoEngine::TokioEpollUring => {
219 558247 : let system = tokio_epoll_uring_ext::thread_local_system().await;
220 558259 : let (resources, res) = system.write(file_guard, offset, buf).await;
221 558247 : (resources, res.map_err(epoll_uring_error_to_std))
222 : }
223 : }
224 1116496 : }
225 :
226 : /// If we switch a user of [`tokio::fs`] to use [`super::io_engine`],
227 : /// they'd start blocking the executor thread if [`IoEngine::StdFs`] is configured
228 : /// whereas before the switch to [`super::io_engine`], that wasn't the case.
229 : /// This method helps avoid such a regression.
230 : ///
231 : /// Panics if the `spawn_blocking` fails, see [`tokio::task::JoinError`] for reasons why that can happen.
232 6 : pub(crate) async fn spawn_blocking_and_block_on_if_std<Fut, R>(&self, work: Fut) -> R
233 6 : where
234 6 : Fut: 'static + Send + std::future::Future<Output = R>,
235 6 : R: 'static + Send,
236 6 : {
237 6 : match self {
238 0 : IoEngine::NotSet => panic!("not initialized"),
239 : IoEngine::StdFs => {
240 3 : let span = tracing::info_span!("spawn_blocking_block_on_if_std");
241 3 : tokio::task::spawn_blocking({
242 3 : move || tokio::runtime::Handle::current().block_on(work.instrument(span))
243 3 : })
244 3 : .await
245 3 : .expect("failed to join blocking code most likely it panicked, panicking as well")
246 : }
247 : #[cfg(target_os = "linux")]
248 6 : IoEngine::TokioEpollUring => work.await,
249 : }
250 6 : }
251 : }
252 :
253 : pub enum FeatureTestResult {
254 : PlatformPreferred(IoEngineKind),
255 : Worse {
256 : engine: IoEngineKind,
257 : remark: String,
258 : },
259 : }
260 :
261 : impl FeatureTestResult {
262 : #[cfg(target_os = "linux")]
263 : const PLATFORM_PREFERRED: IoEngineKind = IoEngineKind::TokioEpollUring;
264 : #[cfg(not(target_os = "linux"))]
265 : const PLATFORM_PREFERRED: IoEngineKind = IoEngineKind::StdFs;
266 : }
267 :
268 : impl From<FeatureTestResult> for IoEngineKind {
269 0 : fn from(val: FeatureTestResult) -> Self {
270 0 : match val {
271 0 : FeatureTestResult::PlatformPreferred(e) => e,
272 0 : FeatureTestResult::Worse { engine, .. } => engine,
273 : }
274 0 : }
275 : }
276 :
277 : /// Somewhat costly under the hood, do only once.
278 : /// Panics if we can't set up the feature test.
279 18 : pub fn feature_test() -> anyhow::Result<FeatureTestResult> {
280 18 : std::thread::spawn(|| {
281 18 :
282 18 : #[cfg(not(target_os = "linux"))]
283 18 : {
284 18 : Ok(FeatureTestResult::PlatformPreferred(
285 18 : FeatureTestResult::PLATFORM_PREFERRED,
286 18 : ))
287 18 : }
288 18 : #[cfg(target_os = "linux")]
289 18 : {
290 18 : let rt = tokio::runtime::Builder::new_current_thread()
291 18 : .enable_all()
292 18 : .build()
293 18 : .unwrap();
294 18 : Ok(match rt.block_on(tokio_epoll_uring::System::launch()) {
295 : Ok(_) => FeatureTestResult::PlatformPreferred({
296 18 : assert!(matches!(
297 18 : IoEngineKind::TokioEpollUring,
298 : FeatureTestResult::PLATFORM_PREFERRED
299 : ));
300 18 : FeatureTestResult::PLATFORM_PREFERRED
301 : }),
302 0 : Err(tokio_epoll_uring::LaunchResult::IoUringBuild(e)) => {
303 0 : let remark = match e.raw_os_error() {
304 : Some(nix::libc::EPERM) => {
305 : // fall back
306 0 : "creating tokio-epoll-uring fails with EPERM, assuming it's admin-disabled "
307 0 : .to_string()
308 : }
309 : Some(nix::libc::EFAULT) => {
310 : // fail feature test
311 0 : anyhow::bail!(
312 0 : "creating tokio-epoll-uring fails with EFAULT, might have corrupted memory"
313 0 : );
314 : }
315 : Some(_) | None => {
316 : // fall back
317 0 : format!("creating tokio-epoll-uring fails with error: {e:#}")
318 : }
319 : };
320 0 : FeatureTestResult::Worse {
321 0 : engine: IoEngineKind::StdFs,
322 0 : remark,
323 0 : }
324 : }
325 : })
326 : }
327 18 : })
328 18 : .join()
329 18 : .unwrap()
330 18 : }
|