transfer.rs 12.8 KB
Newer Older
Ryan Olson's avatar
Ryan Olson committed
1
2
3
4
5
// SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use super::*;

6
use futures::future::try_join_all;
Ryan Olson's avatar
Ryan Olson committed
7
8
9
10
11
12
13
use nixl_sys::NixlDescriptor;
use utils::*;
use zmq::*;

use BlockTransferPool::*;

use crate::block_manager::{
jthomson04's avatar
jthomson04 committed
14
    Storage,
Ryan Olson's avatar
Ryan Olson committed
15
    block::{
jthomson04's avatar
jthomson04 committed
16
17
        BasicMetadata, Block, BlockDataProvider, BlockDataProviderMut, ReadableBlock,
        WritableBlock,
Ryan Olson's avatar
Ryan Olson committed
18
19
20
21
22
        data::local::LocalBlockData,
        locality,
        transfer::{TransferContext, WriteTo, WriteToStrategy},
    },
    connector::scheduler::{SchedulingDecision, TransferSchedulerClient},
23
    offload::MAX_TRANSFER_BATCH_SIZE,
Ryan Olson's avatar
Ryan Olson committed
24
    storage::{DeviceStorage, DiskStorage, Local, PinnedStorage},
jthomson04's avatar
jthomson04 committed
25
26
27
28
    v2::physical::{
        layout::PhysicalLayout, manager::TransportManager, transfer::LayoutHandle,
        transfer::options::TransferOptions,
    },
Ryan Olson's avatar
Ryan Olson committed
29
30
31
32
33
34
35
36
37
};

use anyhow::Result;
use async_trait::async_trait;
use std::{any::Any, sync::Arc};

type LocalBlock<S, M> = Block<S, locality::Local, M>;
type LocalBlockDataList<S> = Vec<LocalBlockData<S>>;

38
39
40
41
42
43
44
45
46
47
48
49
50
51
/// A batching wrapper for connector transfers to prevent resource exhaustion.
/// Splits large transfers into smaller batches that can be handled by the resource pools.
#[derive(Clone, Debug)]
pub struct ConnectorTransferBatcher {
    max_batch_size: usize,
}

impl ConnectorTransferBatcher {
    pub fn new() -> Self {
        Self {
            max_batch_size: MAX_TRANSFER_BATCH_SIZE,
        }
    }

jthomson04's avatar
jthomson04 committed
52
    pub async fn execute_batched_transfer<T: BlockTransferDirectHandler>(
53
        &self,
jthomson04's avatar
jthomson04 committed
54
        handler: &T,
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
        request: BlockTransferRequest,
    ) -> Result<()> {
        let blocks = request.blocks();
        let num_blocks = blocks.len();

        if num_blocks <= self.max_batch_size {
            return handler.execute_transfer_direct(request).await;
        }

        let batches = blocks.chunks(self.max_batch_size);

        let batch_futures: Vec<_> = batches
            .map(|batch| {
                let batch_request = BlockTransferRequest {
                    from_pool: *request.from_pool(),
                    to_pool: *request.to_pool(),
                    blocks: batch.to_vec(),
                    connector_req: None,
                };
                handler.execute_transfer_direct(batch_request)
            })
            .collect();

        // Execute all batches concurrently
        tracing::debug!("Executing {} batches concurrently", batch_futures.len());

        match try_join_all(batch_futures).await {
            Ok(_) => Ok(()),
            Err(e) => {
                tracing::error!("Batched connector transfer failed: {}", e);
                Err(e)
            }
        }
    }
}

jthomson04's avatar
jthomson04 committed
91
92
93
94
95
96
97
98
99
100
101
102
#[async_trait]
pub trait BlockTransferHandler: Send + Sync {
    async fn execute_transfer(&self, request: BlockTransferRequest) -> Result<()>;

    fn scheduler_client(&self) -> Option<TransferSchedulerClient>;
}

#[async_trait]
pub trait BlockTransferDirectHandler {
    async fn execute_transfer_direct(&self, request: BlockTransferRequest) -> Result<()>;
}

Ryan Olson's avatar
Ryan Olson committed
103
104
/// A handler for all block transfers. Wraps a group of [`BlockTransferPoolManager`]s.
#[derive(Clone)]
jthomson04's avatar
jthomson04 committed
105
pub struct BlockTransferHandlerV1 {
Ryan Olson's avatar
Ryan Olson committed
106
107
108
109
110
    device: Option<LocalBlockDataList<DeviceStorage>>,
    host: Option<LocalBlockDataList<PinnedStorage>>,
    disk: Option<LocalBlockDataList<DiskStorage>>,
    context: Arc<TransferContext>,
    scheduler_client: Option<TransferSchedulerClient>,
111
    batcher: ConnectorTransferBatcher,
Ryan Olson's avatar
Ryan Olson committed
112
113
114
    // add worker-connector scheduler client here
}

jthomson04's avatar
jthomson04 committed
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
#[async_trait]
impl BlockTransferHandler for BlockTransferHandlerV1 {
    async fn execute_transfer(&self, request: BlockTransferRequest) -> Result<()> {
        self.batcher.execute_batched_transfer(self, request).await
    }

    fn scheduler_client(&self) -> Option<TransferSchedulerClient> {
        self.scheduler_client.clone()
    }
}

#[async_trait]
impl BlockTransferDirectHandler for BlockTransferHandlerV1 {
    async fn execute_transfer_direct(&self, request: BlockTransferRequest) -> Result<()> {
        tracing::debug!(
            "Performing transfer of {} blocks from {:?} to {:?}",
            request.blocks().len(),
            request.from_pool(),
            request.to_pool()
        );

        tracing::debug!("request: {request:#?}");

        let notify = match (request.from_pool(), request.to_pool()) {
            (Device, Host) => self.begin_transfer(&self.device, &self.host, request).await,
            (Device, Disk) => self.begin_transfer(&self.device, &self.disk, request).await,
            (Host, Device) => self.begin_transfer(&self.host, &self.device, request).await,
            (Host, Disk) => self.begin_transfer(&self.host, &self.disk, request).await,
            (Disk, Device) => self.begin_transfer(&self.disk, &self.device, request).await,
            _ => {
                return Err(anyhow::anyhow!("Invalid transfer type."));
            }
        }?;

        notify.await?;
        Ok(())
    }
}

impl BlockTransferHandlerV1 {
Ryan Olson's avatar
Ryan Olson committed
155
156
157
158
159
160
161
162
163
164
165
166
167
168
    pub fn new(
        device_blocks: Option<Vec<LocalBlock<DeviceStorage, BasicMetadata>>>,
        host_blocks: Option<Vec<LocalBlock<PinnedStorage, BasicMetadata>>>,
        disk_blocks: Option<Vec<LocalBlock<DiskStorage, BasicMetadata>>>,
        context: Arc<TransferContext>,
        scheduler_client: Option<TransferSchedulerClient>,
        // add worker-connector scheduler client here
    ) -> Result<Self> {
        Ok(Self {
            device: Self::get_local_data(device_blocks),
            host: Self::get_local_data(host_blocks),
            disk: Self::get_local_data(disk_blocks),
            context,
            scheduler_client,
169
            batcher: ConnectorTransferBatcher::new(),
Ryan Olson's avatar
Ryan Olson committed
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
        })
    }

    fn get_local_data<S: Storage>(
        blocks: Option<Vec<LocalBlock<S, BasicMetadata>>>,
    ) -> Option<LocalBlockDataList<S>> {
        blocks.map(|blocks| {
            blocks
                .into_iter()
                .map(|b| {
                    let block_data = b.block_data() as &dyn Any;

                    block_data
                        .downcast_ref::<LocalBlockData<S>>()
                        .unwrap()
                        .clone()
                })
                .collect()
        })
    }

    /// Initiate a transfer between two pools.
    async fn begin_transfer<Source, Target>(
        &self,
        source_pool_list: &Option<LocalBlockDataList<Source>>,
        target_pool_list: &Option<LocalBlockDataList<Target>>,
        request: BlockTransferRequest,
    ) -> Result<tokio::sync::oneshot::Receiver<()>>
    where
        Source: Storage + NixlDescriptor,
        Target: Storage + NixlDescriptor,
        // Check that the source block is readable, local, and writable to the target block.
        LocalBlockData<Source>:
            ReadableBlock<StorageType = Source> + Local + WriteToStrategy<LocalBlockData<Target>>,
        // Check that the target block is writable.
        LocalBlockData<Target>: WritableBlock<StorageType = Target>,
        LocalBlockData<Source>: BlockDataProvider<Locality = locality::Local>,
        LocalBlockData<Target>: BlockDataProviderMut<Locality = locality::Local>,
    {
        let Some(source_pool_list) = source_pool_list else {
            return Err(anyhow::anyhow!("Source pool manager not initialized"));
        };
        let Some(target_pool_list) = target_pool_list else {
            return Err(anyhow::anyhow!("Target pool manager not initialized"));
        };

        // Extract the `from` and `to` indices from the request.
        let source_idxs = request.blocks().iter().map(|(from, _)| *from);
        let target_idxs = request.blocks().iter().map(|(_, to)| *to);

        // Get the blocks corresponding to the indices.
        let sources: Vec<LocalBlockData<Source>> = source_idxs
            .map(|idx| source_pool_list[idx].clone())
            .collect();
        let mut targets: Vec<LocalBlockData<Target>> = target_idxs
            .map(|idx| target_pool_list[idx].clone())
            .collect();

        // Perform the transfer, and return the notifying channel.
229
        match sources.write_to(&mut targets, self.context.clone()) {
Ryan Olson's avatar
Ryan Olson committed
230
231
232
233
234
            Ok(channel) => Ok(channel),
            Err(e) => {
                tracing::error!("Failed to write to blocks: {:?}", e);
                Err(e.into())
            }
235
        }
Ryan Olson's avatar
Ryan Olson committed
236
    }
jthomson04's avatar
jthomson04 committed
237
238
239
240
241
242
243
244
245
246
247
}

#[derive(Clone)]
pub struct BlockTransferHandlerV2 {
    device_handle: Option<LayoutHandle>,
    host_handle: Option<LayoutHandle>,
    disk_handle: Option<LayoutHandle>,
    transport_manager: TransportManager,
    scheduler_client: Option<TransferSchedulerClient>,
    batcher: ConnectorTransferBatcher,
}
Ryan Olson's avatar
Ryan Olson committed
248

jthomson04's avatar
jthomson04 committed
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
impl BlockTransferHandlerV2 {
    pub fn new(
        device_layout: Option<PhysicalLayout>,
        host_layout: Option<PhysicalLayout>,
        disk_layout: Option<PhysicalLayout>,
        transport_manager: TransportManager,
        scheduler_client: Option<TransferSchedulerClient>,
    ) -> Result<Self> {
        Ok(Self {
            device_handle: device_layout
                .map(|layout| transport_manager.register_layout(layout).unwrap()),
            host_handle: host_layout
                .map(|layout| transport_manager.register_layout(layout).unwrap()),
            disk_handle: disk_layout
                .map(|layout| transport_manager.register_layout(layout).unwrap()),
            transport_manager,
            scheduler_client,
            batcher: ConnectorTransferBatcher::new(),
        })
    }
}

#[async_trait]
impl BlockTransferHandler for BlockTransferHandlerV2 {
    async fn execute_transfer(&self, request: BlockTransferRequest) -> Result<()> {
274
275
276
        self.batcher.execute_batched_transfer(self, request).await
    }

jthomson04's avatar
jthomson04 committed
277
278
279
280
    fn scheduler_client(&self) -> Option<TransferSchedulerClient> {
        self.scheduler_client.clone()
    }
}
Ryan Olson's avatar
Ryan Olson committed
281

jthomson04's avatar
jthomson04 committed
282
283
284
285
286
287
288
289
290
291
292
#[async_trait]
impl BlockTransferDirectHandler for BlockTransferHandlerV2 {
    async fn execute_transfer_direct(&self, request: BlockTransferRequest) -> Result<()> {
        let (src, dst) = match (request.from_pool(), request.to_pool()) {
            (Device, Host) => (self.device_handle.as_ref(), self.host_handle.as_ref()),
            (Device, Disk) => (self.device_handle.as_ref(), self.disk_handle.as_ref()),
            (Host, Device) => (self.host_handle.as_ref(), self.device_handle.as_ref()),
            (Host, Disk) => (self.host_handle.as_ref(), self.disk_handle.as_ref()),
            (Disk, Device) => (self.disk_handle.as_ref(), self.device_handle.as_ref()),
            _ => return Err(anyhow::anyhow!("Invalid transfer type.")),
        };
Ryan Olson's avatar
Ryan Olson committed
293

jthomson04's avatar
jthomson04 committed
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
        if let (Some(src), Some(dst)) = (src, dst) {
            let src_block_ids = request
                .blocks()
                .iter()
                .map(|(from, _)| *from)
                .collect::<Vec<_>>();
            let dst_block_ids = request
                .blocks()
                .iter()
                .map(|(_, to)| *to)
                .collect::<Vec<_>>();

            self.transport_manager
                .execute_transfer(
                    *src,
                    &src_block_ids,
                    *dst,
                    &dst_block_ids,
                    TransferOptions::default(),
                )?
                .await?;
        } else {
            return Err(anyhow::anyhow!("Invalid transfer type."));
        }
Ryan Olson's avatar
Ryan Olson committed
318
319
320
321
322
323

        Ok(())
    }
}

#[async_trait]
jthomson04's avatar
jthomson04 committed
324
impl<T: ?Sized + BlockTransferHandler> Handler for T {
Ryan Olson's avatar
Ryan Olson committed
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
    async fn handle(&self, mut message: MessageHandle) -> Result<()> {
        if message.data.len() != 1 {
            return Err(anyhow::anyhow!(
                "Block transfer request must have exactly one data element"
            ));
        }

        let mut request: BlockTransferRequest = serde_json::from_slice(&message.data[0])?;

        let result = if let Some(req) = request.connector_req.take() {
            let operation_id = req.uuid;

            tracing::debug!(
                request_id = %req.request_id,
                operation_id = %operation_id,
                "scheduling transfer"
            );

            let client = self
jthomson04's avatar
jthomson04 committed
344
345
                .scheduler_client()
                .expect("scheduler client is required");
Ryan Olson's avatar
Ryan Olson committed
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

            let handle = client.schedule_transfer(req).await?;

            // we don't support cancellation yet
            assert_eq!(handle.scheduler_decision(), SchedulingDecision::Execute);

            match self.execute_transfer(request).await {
                Ok(_) => {
                    handle.mark_complete(Ok(())).await;
                    Ok(())
                }
                Err(e) => {
                    handle.mark_complete(Err(anyhow::anyhow!("{}", e))).await;
                    Err(e)
                }
            }
        } else {
            self.execute_transfer(request).await
        };

        // we always ack regardless of if we error or not
        message.ack().await?;

        // the error may trigger a cancellation
        result
    }
}