1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

use std::io::SeekFrom;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;

use chrono::DateTime;
use log::debug;

use super::core::*;
use super::lister::FsLister;
use super::reader::FsReader;
use super::writer::FsWriter;
use super::writer::FsWriters;
use crate::raw::*;
use crate::services::FsConfig;
use crate::*;

impl Configurator for FsConfig {
    type Builder = FsBuilder;
    fn into_builder(self) -> Self::Builder {
        FsBuilder { config: self }
    }
}

/// POSIX file system support.
#[doc = include_str!("docs.md")]
#[derive(Default, Debug)]
pub struct FsBuilder {
    config: FsConfig,
}

impl FsBuilder {
    /// Set root for backend.
    pub fn root(mut self, root: &str) -> Self {
        self.config.root = if root.is_empty() {
            None
        } else {
            Some(root.to_string())
        };

        self
    }

    /// Set temp dir for atomic write.
    ///
    /// # Notes
    ///
    /// - When append is enabled, we will not use atomic write
    ///   to avoid data loss and performance issue.
    pub fn atomic_write_dir(mut self, dir: &str) -> Self {
        if !dir.is_empty() {
            self.config.atomic_write_dir = Some(dir.to_string());
        }

        self
    }
}

impl Builder for FsBuilder {
    const SCHEME: Scheme = Scheme::Fs;
    type Config = FsConfig;

    fn build(self) -> Result<impl Access> {
        debug!("backend build started: {:?}", &self);

        let root = match self.config.root.map(PathBuf::from) {
            Some(root) => Ok(root),
            None => Err(Error::new(
                ErrorKind::ConfigInvalid,
                "root is not specified",
            )),
        }?;
        debug!("backend use root {}", root.to_string_lossy());

        // If root dir is not exist, we must create it.
        if let Err(e) = std::fs::metadata(&root) {
            if e.kind() == std::io::ErrorKind::NotFound {
                std::fs::create_dir_all(&root).map_err(|e| {
                    Error::new(ErrorKind::Unexpected, "create root dir failed")
                        .with_operation("Builder::build")
                        .with_context("root", root.to_string_lossy())
                        .set_source(e)
                })?;
            }
        }

        let atomic_write_dir = self.config.atomic_write_dir.map(PathBuf::from);

        // If atomic write dir is not exist, we must create it.
        if let Some(d) = &atomic_write_dir {
            if let Err(e) = std::fs::metadata(d) {
                if e.kind() == std::io::ErrorKind::NotFound {
                    std::fs::create_dir_all(d).map_err(|e| {
                        Error::new(ErrorKind::Unexpected, "create atomic write dir failed")
                            .with_operation("Builder::build")
                            .with_context("atomic_write_dir", d.to_string_lossy())
                            .set_source(e)
                    })?;
                }
            }
        }

        // Canonicalize the root directory. This should work since we already know that we can
        // get the metadata of the path.
        let root = root.canonicalize().map_err(|e| {
            Error::new(
                ErrorKind::Unexpected,
                "canonicalize of root directory failed",
            )
            .with_operation("Builder::build")
            .with_context("root", root.to_string_lossy())
            .set_source(e)
        })?;

        // Canonicalize the atomic_write_dir directory. This should work since we already know that
        // we can get the metadata of the path.
        let atomic_write_dir = atomic_write_dir
            .map(|p| {
                p.canonicalize().map(Some).map_err(|e| {
                    Error::new(
                        ErrorKind::Unexpected,
                        "canonicalize of atomic_write_dir directory failed",
                    )
                    .with_operation("Builder::build")
                    .with_context("root", root.to_string_lossy())
                    .set_source(e)
                })
            })
            .unwrap_or(Ok(None))?;

        Ok(FsBackend {
            core: Arc::new(FsCore {
                root,
                atomic_write_dir,
                buf_pool: oio::PooledBuf::new(16).with_initial_capacity(256 * 1024),
            }),
        })
    }
}

/// Backend is used to serve `Accessor` support for posix-like fs.
#[derive(Debug, Clone)]
pub struct FsBackend {
    core: Arc<FsCore>,
}

impl Access for FsBackend {
    type Reader = FsReader<tokio::fs::File>;
    type Writer = FsWriters;
    type Lister = Option<FsLister<tokio::fs::ReadDir>>;
    type BlockingReader = FsReader<std::fs::File>;
    type BlockingWriter = FsWriter<std::fs::File>;
    type BlockingLister = Option<FsLister<std::fs::ReadDir>>;

    fn info(&self) -> Arc<AccessorInfo> {
        let mut am = AccessorInfo::default();
        am.set_scheme(Scheme::Fs)
            .set_root(&self.core.root.to_string_lossy())
            .set_native_capability(Capability {
                stat: true,

                read: true,

                write: true,
                write_can_empty: true,
                write_can_append: true,
                write_can_multi: true,
                create_dir: true,
                delete: true,

                list: true,

                copy: true,
                rename: true,
                blocking: true,

                shared: true,

                ..Default::default()
            });

        am.into()
    }

    async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
        let p = self.core.root.join(path.trim_end_matches('/'));

        tokio::fs::create_dir_all(&p)
            .await
            .map_err(new_std_io_error)?;

        Ok(RpCreateDir::default())
    }

    async fn stat(&self, path: &str, _: OpStat) -> Result<RpStat> {
        let p = self.core.root.join(path.trim_end_matches('/'));

        let meta = tokio::fs::metadata(&p).await.map_err(new_std_io_error)?;

        let mode = if meta.is_dir() {
            EntryMode::DIR
        } else if meta.is_file() {
            EntryMode::FILE
        } else {
            EntryMode::Unknown
        };
        let m = Metadata::new(mode)
            .with_content_length(meta.len())
            .with_last_modified(
                meta.modified()
                    .map(DateTime::from)
                    .map_err(new_std_io_error)?,
            );

        Ok(RpStat::new(m))
    }

    /// # Notes
    ///
    /// There are three ways to get the total file length:
    ///
    /// - call std::fs::metadata directly and then open. (400ns)
    /// - open file first, and then use `f.metadata()` (300ns)
    /// - open file first, and then use `seek`. (100ns)
    ///
    /// Benchmark could be found [here](https://gist.github.com/Xuanwo/48f9cfbc3022ea5f865388bb62e1a70f)
    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
        let p = self.core.root.join(path.trim_end_matches('/'));

        let mut f = tokio::fs::OpenOptions::new()
            .read(true)
            .open(&p)
            .await
            .map_err(new_std_io_error)?;

        if args.range().offset() != 0 {
            use tokio::io::AsyncSeekExt;

            f.seek(SeekFrom::Start(args.range().offset()))
                .await
                .map_err(new_std_io_error)?;
        }

        let r = FsReader::new(
            self.core.clone(),
            f,
            args.range().size().unwrap_or(u64::MAX) as _,
        );
        Ok((RpRead::new(), r))
    }

    async fn write(&self, path: &str, op: OpWrite) -> Result<(RpWrite, Self::Writer)> {
        let (target_path, tmp_path) = if let Some(atomic_write_dir) = &self.core.atomic_write_dir {
            let target_path = self
                .core
                .ensure_write_abs_path(&self.core.root, path)
                .await?;
            let tmp_path = self
                .core
                .ensure_write_abs_path(atomic_write_dir, &tmp_file_of(path))
                .await?;

            // If the target file exists, we should append to the end of it directly.
            if op.append()
                && tokio::fs::try_exists(&target_path)
                    .await
                    .map_err(new_std_io_error)?
            {
                (target_path, None)
            } else {
                (target_path, Some(tmp_path))
            }
        } else {
            let p = self
                .core
                .ensure_write_abs_path(&self.core.root, path)
                .await?;

            (p, None)
        };

        let mut open_options = tokio::fs::OpenOptions::new();
        open_options.create(true).write(true);
        if op.append() {
            open_options.append(true);
        } else {
            open_options.truncate(true);
        }

        let f = open_options
            .open(tmp_path.as_ref().unwrap_or(&target_path))
            .await
            .map_err(new_std_io_error)?;

        let w = FsWriter::new(target_path, tmp_path, f);

        let w = if op.append() {
            FsWriters::One(w)
        } else {
            FsWriters::Two(oio::PositionWriter::new(
                w,
                op.executor().cloned(),
                op.concurrent(),
            ))
        };

        Ok((RpWrite::default(), w))
    }

    async fn delete(&self, path: &str, _: OpDelete) -> Result<RpDelete> {
        let p = self.core.root.join(path.trim_end_matches('/'));

        let meta = tokio::fs::metadata(&p).await;

        match meta {
            Ok(meta) => {
                if meta.is_dir() {
                    tokio::fs::remove_dir(&p).await.map_err(new_std_io_error)?;
                } else {
                    tokio::fs::remove_file(&p).await.map_err(new_std_io_error)?;
                }

                Ok(RpDelete::default())
            }
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(RpDelete::default()),
            Err(err) => Err(new_std_io_error(err)),
        }
    }

    async fn list(&self, path: &str, _: OpList) -> Result<(RpList, Self::Lister)> {
        let p = self.core.root.join(path.trim_end_matches('/'));

        let f = match tokio::fs::read_dir(&p).await {
            Ok(rd) => rd,
            Err(e) => {
                return if e.kind() == std::io::ErrorKind::NotFound {
                    Ok((RpList::default(), None))
                } else {
                    Err(new_std_io_error(e))
                };
            }
        };

        let rd = FsLister::new(&self.core.root, path, f);
        Ok((RpList::default(), Some(rd)))
    }

    async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
        let from = self.core.root.join(from.trim_end_matches('/'));

        // try to get the metadata of the source file to ensure it exists
        tokio::fs::metadata(&from).await.map_err(new_std_io_error)?;

        let to = self
            .core
            .ensure_write_abs_path(&self.core.root, to.trim_end_matches('/'))
            .await?;

        tokio::fs::copy(from, to).await.map_err(new_std_io_error)?;

        Ok(RpCopy::default())
    }

    async fn rename(&self, from: &str, to: &str, _args: OpRename) -> Result<RpRename> {
        let from = self.core.root.join(from.trim_end_matches('/'));

        // try to get the metadata of the source file to ensure it exists
        tokio::fs::metadata(&from).await.map_err(new_std_io_error)?;

        let to = self
            .core
            .ensure_write_abs_path(&self.core.root, to.trim_end_matches('/'))
            .await?;

        tokio::fs::rename(from, to)
            .await
            .map_err(new_std_io_error)?;

        Ok(RpRename::default())
    }

    fn blocking_create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
        let p = self.core.root.join(path.trim_end_matches('/'));

        std::fs::create_dir_all(p).map_err(new_std_io_error)?;

        Ok(RpCreateDir::default())
    }

    fn blocking_stat(&self, path: &str, _: OpStat) -> Result<RpStat> {
        let p = self.core.root.join(path.trim_end_matches('/'));

        let meta = std::fs::metadata(p).map_err(new_std_io_error)?;

        let mode = if meta.is_dir() {
            EntryMode::DIR
        } else if meta.is_file() {
            EntryMode::FILE
        } else {
            EntryMode::Unknown
        };
        let m = Metadata::new(mode)
            .with_content_length(meta.len())
            .with_last_modified(
                meta.modified()
                    .map(DateTime::from)
                    .map_err(new_std_io_error)?,
            );

        Ok(RpStat::new(m))
    }

    fn blocking_read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::BlockingReader)> {
        let p = self.core.root.join(path.trim_end_matches('/'));

        let mut f = std::fs::OpenOptions::new()
            .read(true)
            .open(p)
            .map_err(new_std_io_error)?;

        if args.range().offset() != 0 {
            use std::io::Seek;

            f.seek(SeekFrom::Start(args.range().offset()))
                .map_err(new_std_io_error)?;
        }

        let r = FsReader::new(
            self.core.clone(),
            f,
            args.range().size().unwrap_or(u64::MAX) as _,
        );
        Ok((RpRead::new(), r))
    }

    fn blocking_write(&self, path: &str, op: OpWrite) -> Result<(RpWrite, Self::BlockingWriter)> {
        let (target_path, tmp_path) = if let Some(atomic_write_dir) = &self.core.atomic_write_dir {
            let target_path = self
                .core
                .blocking_ensure_write_abs_path(&self.core.root, path)?;
            let tmp_path = self
                .core
                .blocking_ensure_write_abs_path(atomic_write_dir, &tmp_file_of(path))?;

            // If the target file exists, we should append to the end of it directly.
            if op.append()
                && Path::new(&target_path)
                    .try_exists()
                    .map_err(new_std_io_error)?
            {
                (target_path, None)
            } else {
                (target_path, Some(tmp_path))
            }
        } else {
            let p = self
                .core
                .blocking_ensure_write_abs_path(&self.core.root, path)?;

            (p, None)
        };

        let mut f = std::fs::OpenOptions::new();
        f.create(true).write(true);

        if op.append() {
            f.append(true);
        } else {
            f.truncate(true);
        }

        let f = f
            .open(tmp_path.as_ref().unwrap_or(&target_path))
            .map_err(new_std_io_error)?;

        Ok((RpWrite::new(), FsWriter::new(target_path, tmp_path, f)))
    }

    fn blocking_delete(&self, path: &str, _: OpDelete) -> Result<RpDelete> {
        let p = self.core.root.join(path.trim_end_matches('/'));

        let meta = std::fs::metadata(&p);

        match meta {
            Ok(meta) => {
                if meta.is_dir() {
                    std::fs::remove_dir(&p).map_err(new_std_io_error)?;
                } else {
                    std::fs::remove_file(&p).map_err(new_std_io_error)?;
                }

                Ok(RpDelete::default())
            }
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(RpDelete::default()),
            Err(err) => Err(new_std_io_error(err)),
        }
    }

    fn blocking_list(&self, path: &str, _: OpList) -> Result<(RpList, Self::BlockingLister)> {
        let p = self.core.root.join(path.trim_end_matches('/'));

        let f = match std::fs::read_dir(p) {
            Ok(rd) => rd,
            Err(e) => {
                return if e.kind() == std::io::ErrorKind::NotFound {
                    Ok((RpList::default(), None))
                } else {
                    Err(new_std_io_error(e))
                };
            }
        };

        let rd = FsLister::new(&self.core.root, path, f);
        Ok((RpList::default(), Some(rd)))
    }

    fn blocking_copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
        let from = self.core.root.join(from.trim_end_matches('/'));

        // try to get the metadata of the source file to ensure it exists
        std::fs::metadata(&from).map_err(new_std_io_error)?;

        let to = self
            .core
            .blocking_ensure_write_abs_path(&self.core.root, to.trim_end_matches('/'))?;

        std::fs::copy(from, to).map_err(new_std_io_error)?;

        Ok(RpCopy::default())
    }

    fn blocking_rename(&self, from: &str, to: &str, _args: OpRename) -> Result<RpRename> {
        let from = self.core.root.join(from.trim_end_matches('/'));

        // try to get the metadata of the source file to ensure it exists
        std::fs::metadata(&from).map_err(new_std_io_error)?;

        let to = self
            .core
            .blocking_ensure_write_abs_path(&self.core.root, to.trim_end_matches('/'))?;

        std::fs::rename(from, to).map_err(new_std_io_error)?;

        Ok(RpRename::default())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_tmp_file_of() {
        let cases = vec![
            ("hello.txt", "hello.txt"),
            ("/tmp/opendal.log", "opendal.log"),
            ("/abc/def/hello.parquet", "hello.parquet"),
        ];

        for (path, expected_prefix) in cases {
            let tmp_file = tmp_file_of(path);
            assert!(tmp_file.len() > expected_prefix.len());
            assert!(tmp_file.starts_with(expected_prefix));
        }
    }
}