"docs/pages/kubernetes/README.md" did not exist on "a91e63482ccbbc5c389a21993032d09d90f4939e"
disk.rs 5.06 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed 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 super::*;

18
use core::ffi::c_char;
19
use nix::fcntl::{fallocate, FallocateFlags};
Ryan Olson's avatar
Ryan Olson committed
20
21
use nix::unistd::unlink;
use std::ffi::CStr;
22
use std::ffi::CString;
Ryan Olson's avatar
Ryan Olson committed
23
24
25
26
use std::path::Path;

const DISK_CACHE_KEY: &str = "DYN_KVBM_DISK_CACHE_DIR";
const DEFAULT_DISK_CACHE_DIR: &str = "/tmp/";
27
28
29

#[derive(Debug)]
pub struct DiskStorage {
Ryan Olson's avatar
Ryan Olson committed
30
    fd: u64,
31
32
33
    file_name: String,
    size: usize,
    handles: RegistrationHandles,
Ryan Olson's avatar
Ryan Olson committed
34
    unlinked: bool,
35
36
37
38
39
40
41
42
43
44
}

impl Local for DiskStorage {}
impl SystemAccessible for DiskStorage {}

impl DiskStorage {
    pub fn new(size: usize) -> Result<Self, StorageError> {
        // We need to open our file with some special flags that aren't supported by the tempfile crate.
        // Instead, we'll use the mkostemp function to create a temporary file with the correct flags.

Ryan Olson's avatar
Ryan Olson committed
45
46
47
48
49
50
51
52
53
54
55
        let specified_dir =
            std::env::var(DISK_CACHE_KEY).unwrap_or_else(|_| DEFAULT_DISK_CACHE_DIR.to_string());
        let file_path = Path::new(&specified_dir).join("dynamo-kvbm-disk-cache-XXXXXX");

        if !file_path.exists() {
            std::fs::create_dir_all(file_path.parent().unwrap()).unwrap();
        }

        tracing::debug!("Allocating disk cache file at {}", file_path.display());

        let template = CString::new(file_path.to_str().unwrap()).unwrap();
56
57
58
59
        let mut template_bytes = template.into_bytes_with_nul();

        let raw_fd = unsafe {
            nix::libc::mkostemp(
60
                template_bytes.as_mut_ptr() as *mut c_char,
61
62
63
64
65
66
67
                // For maximum performance, GPU DirectStorage requires O_DIRECT.
                // This allows transfers to bypass the kernel page cache.
                // It also introduces the restriction that all accesses must be page-aligned.
                nix::libc::O_RDWR | nix::libc::O_DIRECT,
            )
        };

Ryan Olson's avatar
Ryan Olson committed
68
69
70
71
72
73
        let file_name = CStr::from_bytes_with_nul(template_bytes.as_slice())
            .unwrap()
            .to_str()
            .map_err(|e| {
                StorageError::AllocationFailed(format!("Failed to read temp file name: {}", e))
            })?
74
75
76
            .to_string();

        // We need to use fallocate to actually allocate the storage and create the blocks on disk.
Ryan Olson's avatar
Ryan Olson committed
77
78
        fallocate(raw_fd, FallocateFlags::empty(), 0, size as i64).map_err(|e| {
            StorageError::AllocationFailed(format!("Failed to allocate temp file: {}", e))
79
80
81
        })?;

        Ok(Self {
Ryan Olson's avatar
Ryan Olson committed
82
            fd: raw_fd as u64,
83
84
85
            file_name,
            size,
            handles: RegistrationHandles::new(),
Ryan Olson's avatar
Ryan Olson committed
86
            unlinked: false,
87
88
89
90
        })
    }

    pub fn fd(&self) -> u64 {
Ryan Olson's avatar
Ryan Olson committed
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
        self.fd
    }

    /// Unlink our temp file.
    /// This means that when this process terminates, the file will be automatically deleted by the OS.
    /// Unfortunately, GDS requires that files we try to register must be linked.
    /// To get around this, we unlink the file only after we've registered it with NIXL.
    pub fn unlink(&mut self) -> Result<(), StorageError> {
        if self.unlinked {
            return Ok(());
        }

        self.unlinked = true;

        unlink(self.file_name.as_str()).map_err(|e| {
            StorageError::AllocationFailed(format!("Failed to unlink temp file: {}", e))
        })
    }

    pub fn unlinked(&self) -> bool {
        self.unlinked
112
113
114
115
116
    }
}

impl Drop for DiskStorage {
    fn drop(&mut self) {
117
        self.handles.release();
Ryan Olson's avatar
Ryan Olson committed
118
        let _ = self.unlink();
119
120
121
122
123
    }
}

impl Storage for DiskStorage {
    fn storage_type(&self) -> StorageType {
Ryan Olson's avatar
Ryan Olson committed
124
        StorageType::Disk(self.fd())
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
    }

    fn addr(&self) -> u64 {
        0
    }

    fn size(&self) -> usize {
        self.size
    }

    unsafe fn as_ptr(&self) -> *const u8 {
        std::ptr::null()
    }

    unsafe fn as_mut_ptr(&mut self) -> *mut u8 {
        std::ptr::null_mut()
    }
}

impl RegisterableStorage for DiskStorage {
    fn register(
        &mut self,
        key: &str,
        handle: Box<dyn RegistationHandle>,
    ) -> Result<(), StorageError> {
        self.handles.register(key, handle)
    }

    fn is_registered(&self, key: &str) -> bool {
        self.handles.is_registered(key)
    }

    fn registration_handle(&self, key: &str) -> Option<&dyn RegistationHandle> {
        self.handles.registration_handle(key)
    }
}

#[derive(Default)]
pub struct DiskAllocator;

impl StorageAllocator<DiskStorage> for DiskAllocator {
    fn allocate(&self, size: usize) -> Result<DiskStorage, StorageError> {
        DiskStorage::new(size)
    }
}