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
//! Simple and modular write-ahead-logging implementation.
//!
//! # Examples
//!
//! ```
//! use growthring::{WALStoreAIO, wal::WALLoader};
//! use futures::executor::block_on;
//! let mut loader = WALLoader::new();
//! loader.file_nbit(9).block_nbit(8);
//!
//!
//! // Start with empty WAL (truncate = true).
//! let store = WALStoreAIO::new("./walfiles", true, None, None).unwrap();
//! let mut wal = block_on(loader.load(store, |_, _| {Ok(())})).unwrap();
//! // Write a vector of records to WAL.
//! for f in wal.grow(vec!["record1(foo)", "record2(bar)", "record3(foobar)"]).into_iter() {
//!     let ring_id = block_on(f).unwrap().1;
//!     println!("WAL recorded record to {:?}", ring_id);
//! }
//!
//!
//! // Load from WAL (truncate = false).
//! let store = WALStoreAIO::new("./walfiles", false, None, None).unwrap();
//! let mut wal = block_on(loader.load(store, |payload, ringid| {
//!     // redo the operations in your application
//!     println!("recover(payload={}, ringid={:?})",
//!              std::str::from_utf8(&payload).unwrap(),
//!              ringid);
//!     Ok(())
//! })).unwrap();
//! // We saw some log playback, even there is no failure.
//! // Let's try to grow the WAL to create many files.
//! let ring_ids = wal.grow((1..100).into_iter().map(|i| "a".repeat(i)).collect::<Vec<_>>())
//!                   .into_iter().map(|f| block_on(f).unwrap().1).collect::<Vec<_>>();
//! // Then assume all these records are not longer needed. We can tell WALWriter by the `peel`
//! // method.
//! block_on(wal.peel(ring_ids)).unwrap();
//! // There will only be one remaining file in ./walfiles.
//!
//! let store = WALStoreAIO::new("./walfiles", false, None, None).unwrap();
//! let wal = block_on(loader.load(store, |payload, _| {
//!     println!("payload.len() = {}", payload.len());
//!     Ok(())
//! })).unwrap();
//! // After each recovery, the ./walfiles is empty.
//! ```

#[macro_use] extern crate scan_fmt;
pub mod wal;

use aiofut::{AIOBuilder, AIOManager};
use async_trait::async_trait;
use libc::off_t;
use nix::fcntl::{fallocate, open, openat, FallocateFlags, OFlag};
use nix::sys::stat::Mode;
use nix::unistd::{close, ftruncate, mkdir, unlinkat, UnlinkatFlags};
use std::os::unix::io::RawFd;
use std::sync::Arc;
use wal::{WALBytes, WALFile, WALPos, WALStore};

pub struct WALFileAIO {
    fd: RawFd,
    aiomgr: Arc<AIOManager>,
}

impl WALFileAIO {
    pub fn new(
        rootfd: RawFd,
        filename: &str,
        aiomgr: Arc<AIOManager>,
    ) -> Result<Self, ()> {
        openat(
            rootfd,
            filename,
            OFlag::O_CREAT | OFlag::O_RDWR,
            Mode::S_IRUSR | Mode::S_IWUSR,
        )
        .and_then(|fd| Ok(WALFileAIO { fd, aiomgr }))
        .or_else(|_| Err(()))
    }
}

impl Drop for WALFileAIO {
    fn drop(&mut self) {
        close(self.fd).unwrap();
    }
}

#[async_trait(?Send)]
impl WALFile for WALFileAIO {
    async fn allocate(&self, offset: WALPos, length: usize) -> Result<(), ()> {
        // TODO: is there any async version of fallocate?
        fallocate(
            self.fd,
            FallocateFlags::FALLOC_FL_ZERO_RANGE,
            offset as off_t,
            length as off_t,
        )
        .and_then(|_| Ok(()))
        .or_else(|_| Err(()))
    }

    fn truncate(&self, length: usize) -> Result<(), ()> {
        ftruncate(self.fd, length as off_t).or_else(|_| Err(()))
    }

    async fn write(&self, offset: WALPos, data: WALBytes) -> Result<(), ()> {
        let (res, data) = self.aiomgr.write(self.fd, offset, data, None).await;
        res.or_else(|_| Err(())).and_then(|nwrote| {
            if nwrote == data.len() {
                Ok(())
            } else {
                Err(())
            }
        })
    }

    async fn read(
        &self,
        offset: WALPos,
        length: usize,
    ) -> Result<Option<WALBytes>, ()> {
        let (res, data) = self.aiomgr.read(self.fd, offset, length, None).await;
        res.or_else(|_| Err(())).and_then(|nread| {
            Ok(if nread == length { Some(data) } else { None })
        })
    }
}

pub struct WALStoreAIO {
    rootfd: RawFd,
    aiomgr: Arc<AIOManager>,
}

unsafe impl Send for WALStoreAIO {}

impl WALStoreAIO {
    pub fn new(
        wal_dir: &str,
        truncate: bool,
        rootfd: Option<RawFd>,
        aiomgr: Option<AIOManager>,
    ) -> Result<Self, ()> {
        let aiomgr = Arc::new(aiomgr.ok_or(Err(())).or_else(
            |_: Result<AIOManager, ()>| {
                AIOBuilder::default().build().or(Err(()))
            },
        )?);

        if truncate {
            let _ = std::fs::remove_dir_all(wal_dir);
        }
        let walfd;
        match rootfd {
            None => {
                match mkdir(
                    wal_dir,
                    Mode::S_IRUSR | Mode::S_IWUSR | Mode::S_IXUSR,
                ) {
                    Err(e) => {
                        if truncate {
                            panic!("error while creating directory: {}", e)
                        }
                    }
                    Ok(_) => (),
                }
                walfd = match open(
                    wal_dir,
                    OFlag::O_DIRECTORY | OFlag::O_PATH,
                    Mode::empty(),
                ) {
                    Ok(fd) => fd,
                    Err(_) => panic!("error while opening the WAL directory"),
                }
            }
            Some(fd) => {
                let dirstr = std::ffi::CString::new(wal_dir).unwrap();
                let ret = unsafe {
                    libc::mkdirat(
                        fd,
                        dirstr.as_ptr(),
                        libc::S_IRUSR | libc::S_IWUSR | libc::S_IXUSR,
                    )
                };
                if ret != 0 {
                    if truncate {
                        panic!("error while creating directory")
                    }
                }
                walfd = match nix::fcntl::openat(
                    fd,
                    wal_dir,
                    OFlag::O_DIRECTORY | OFlag::O_PATH,
                    Mode::empty(),
                ) {
                    Ok(fd) => fd,
                    Err(_) => panic!("error while opening the WAL directory"),
                }
            }
        }
        Ok(WALStoreAIO {
            rootfd: walfd,
            aiomgr,
        })
    }
}

#[async_trait(?Send)]
impl WALStore for WALStoreAIO {
    type FileNameIter = std::vec::IntoIter<String>;

    async fn open_file(
        &self,
        filename: &str,
        _touch: bool,
    ) -> Result<Box<dyn WALFile>, ()> {
        let filename = filename.to_string();
        WALFileAIO::new(self.rootfd, &filename, self.aiomgr.clone())
            .and_then(|f| Ok(Box::new(f) as Box<dyn WALFile>))
    }

    async fn remove_file(&self, filename: String) -> Result<(), ()> {
        unlinkat(
            Some(self.rootfd),
            filename.as_str(),
            UnlinkatFlags::NoRemoveDir,
        )
        .or_else(|_| Err(()))
    }

    fn enumerate_files(&self) -> Result<Self::FileNameIter, ()> {
        let mut logfiles = Vec::new();
        for ent in nix::dir::Dir::openat(
            self.rootfd,
            "./",
            OFlag::empty(),
            Mode::empty(),
        )
        .unwrap()
        .iter()
        {
            logfiles
                .push(ent.unwrap().file_name().to_str().unwrap().to_string())
        }
        Ok(logfiles.into_iter())
    }
}

impl Drop for WALStoreAIO {
    fn drop(&mut self) {
        nix::unistd::close(self.rootfd).ok();
    }
}