lvp 1.0.0

Misc utilities for axum (dynamic TLS, OIDC, logger, errors, CORS, and JWT auth)
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
use std::{
    io::ErrorKind,
    os::fd::AsRawFd,
    path::{Path, PathBuf},
    process::Stdio,
};

use crate::{
    config::CONFIG,
    controller::parse_volume_capability,
    proto::{
        node_server::Node, node_service_capability::rpc::Type as RpcType,
        node_service_capability::Rpc, node_service_capability::Type as CapabilityType, *,
    },
    store::{self, Filesystem, VolumeMode, VolumeState},
};
use log::{error, info};
use tokio::{fs::OpenOptions, process::Command};
use tonic::{Request, Response, Status};

#[derive(Debug)]
pub struct NodeService {}

async fn mount_volume(
    loop_device: Option<&Path>,
    source: &Path,
    target: &Path,
    is_readonly: bool,
    filesystem: Filesystem,
) -> std::io::Result<Option<PathBuf>> {
    if filesystem == Filesystem::Bind {
        let mut mount_args = vec![];
        if is_readonly {
            mount_args.push("-r");
        }
        let output = Command::new("mount")
            .arg("--bind")
            .args(mount_args)
            .arg(source)
            .arg(target)
            .spawn()?
            .wait()
            .await?;
        if !output.success() {
            return Err(std::io::Error::new(
                ErrorKind::Other,
                &*format!(
                    "mount exited with code {}",
                    output.code().unwrap_or_default()
                ),
            ));
        }
        return Ok(None);
    }
    let loop_device = if let Some(device) = loop_device {
        device.to_path_buf()
    } else {
        let output = Command::new("losetup")
            .arg("--show")
            .arg("-L")
            .arg("-f")
            .arg(source)
            .stdout(Stdio::piped())
            .spawn()?
            .wait_with_output()
            .await?;
        if !output.status.success() {
            return Err(std::io::Error::new(
                ErrorKind::Other,
                &*format!(
                    "losetup exited with code {}",
                    output.status.code().unwrap_or_default()
                ),
            ));
        }
        let pipe = String::from_utf8(output.stdout)
            .unwrap_or_default()
            .trim()
            .to_string();
        info!("losetup pipe: {pipe}");
        if !tokio::fs::try_exists(&pipe).await? {
            return Err(std::io::Error::new(ErrorKind::Other, "failed to find pipe"));
        }
        pipe.into()
    };
    let mut mount_args = vec![];
    if is_readonly {
        mount_args.push("-r");
    }
    let output = Command::new("mount")
        .args(mount_args)
        .arg(&loop_device)
        .arg(target)
        .spawn()?
        .wait()
        .await?;
    if !output.success() {
        return Err(std::io::Error::new(
            ErrorKind::Other,
            &*format!(
                "mount exited with code {}",
                output.code().unwrap_or_default()
            ),
        ));
    }
    Ok(Some(loop_device))
}

async fn unloop_volume(target: &Path) -> std::io::Result<()> {
    let output = Command::new("losetup")
        .arg("-d")
        .arg(target)
        .spawn()?
        .wait()
        .await?;
    if !output.success() {
        return Err(std::io::Error::new(
            ErrorKind::Other,
            &*format!(
                "losetup -d exited with code {}",
                output.code().unwrap_or_default()
            ),
        ));
    }
    Ok(())
}

async fn unmount_volume(target: &Path) -> std::io::Result<()> {
    let output = Command::new("umount").arg(target).spawn()?.wait().await?;
    if !output.success() {
        return Err(std::io::Error::new(
            ErrorKind::Other,
            &*format!(
                "umount exited with code {}",
                output.code().unwrap_or_default()
            ),
        ));
    }
    Ok(())
}

async fn expand_volume(
    source_file: &Path,
    loop_device: &Path,
    size: u64,
    filesystem: Filesystem,
) -> std::io::Result<()> {
    if filesystem == Filesystem::Bind {
        return Ok(());
    }
    // expand source volume
    let file = OpenOptions::new().write(true).open(source_file).await?;
    tokio::task::spawn_blocking(move || {
        if unsafe { libc::ftruncate(file.as_raw_fd(), size as i64) } < 0 {
            Err(std::io::Error::last_os_error())
        } else {
            Ok(())
        }
    })
    .await??;
    // expand loop device
    let status = Command::new("losetup")
        .arg("-c")
        .arg(loop_device)
        .spawn()?
        .wait()
        .await?;
    if !status.success() {
        return Err(std::io::Error::new(
            ErrorKind::Other,
            &*format!("losetup -c exited with status {status}"),
        ));
    }

    // expand filesystem
    match filesystem {
        Filesystem::Ext4 => {
            let status = Command::new("resize2fs")
                .arg(loop_device)
                .spawn()?
                .wait()
                .await?;
            if !status.success() {
                return Err(std::io::Error::new(
                    ErrorKind::Other,
                    &*format!("resize2fs exited with status {status}"),
                ));
            }
        }
        Filesystem::Xfs => {
            let status = Command::new("xfs_growfs")
                .arg("-d")
                .arg(loop_device)
                .spawn()?
                .wait()
                .await?;
            if !status.success() {
                return Err(std::io::Error::new(
                    ErrorKind::Other,
                    &*format!("xfs_growfs exited with status {status}"),
                ));
            }
        }
        Filesystem::Bind => (),
    }

    Ok(())
}

#[async_trait::async_trait]
impl Node for NodeService {
    async fn node_stage_volume(
        &self,
        request: Request<NodeStageVolumeRequest>,
    ) -> Result<Response<NodeStageVolumeResponse>, Status> {
        let request = request.into_inner();
        info!("node_stage_volume = {request:#?}");

        Err(Status::unimplemented("STAGE_UNSTAGE_VOLUME not set"))
    }

    async fn node_unstage_volume(
        &self,
        request: Request<NodeUnstageVolumeRequest>,
    ) -> Result<Response<NodeUnstageVolumeResponse>, Status> {
        let request = request.into_inner();
        info!("node_unstage_volume = {request:#?}");

        Err(Status::unimplemented("STAGE_UNSTAGE_VOLUME not set"))
    }

    async fn node_publish_volume(
        &self,
        request: Request<NodePublishVolumeRequest>,
    ) -> Result<Response<NodePublishVolumeResponse>, Status> {
        let request = request.into_inner();

        if request.volume_id.is_empty() {
            return Err(Status::invalid_argument("volume_id is missing"));
        }
        if request.target_path.is_empty() {
            return Err(Status::invalid_argument("missing target_path"));
        }
        let target: PathBuf = request.target_path.into();

        let Some(capability) = &request.volume_capability else {
            return Err(Status::invalid_argument("missing volume_capability"));
        };
        let (requested_config, requested_filesystem) = parse_volume_capability(capability)?;

        let mut volume = match store::Volume::load(request.volume_id).await {
            Ok(Some(x)) => x,
            Ok(None) => return Err(Status::not_found("volume_id not found")),
            Err(e) => {
                error!("failed to load volume for deletion: {e:#}");
                return Err(Status::internal("internal failure"));
            }
        };

        if !volume.valid_configs.contains(&requested_config)
            || requested_filesystem
                .map(|x| x != volume.filesystem)
                .unwrap_or_default()
        {
            return Err(Status::already_exists("incompatible volume_capability"));
        }

        match volume.state {
            VolumeState::NodePublished => {
                if let Some(config) = &volume.published_config {
                    match config.mode {
                        VolumeMode::SingleNodeMultiWriter => (),
                        _ => {
                            if !volume.mount_paths.contains(&target) {
                                return Err(Status::failed_precondition("volume already published on node and not configured for multiwrite"));
                            }
                        } //todo: something for singlewriter?
                    }
                    if config != &requested_config {
                        return Err(Status::failed_precondition(
                            "volume attempted to mount in different mode",
                        ));
                    }
                }
            }
            VolumeState::Open => {
                return Err(Status::failed_precondition(
                    "volume not published on controller",
                ))
            }
            VolumeState::ControllerPublished => (),
        }

        if volume.mount_paths.contains(&target) {
            return Ok(Response::new(NodePublishVolumeResponse {}));
        }

        if let Err(e) = tokio::fs::create_dir_all(&target).await {
            error!(
                "failed to create volume mountdir '{}': {e}",
                target.display()
            );
            return Err(Status::internal("failed to create volume mountdir"));
        }

        let total_path = CONFIG.host_prefix.join(&volume.host_path);

        let loop_device = match mount_volume(
            volume.loop_device.as_deref(),
            &total_path,
            &target,
            request.readonly || volume.published_readonly,
            volume.filesystem,
        )
        .await
        {
            Ok(x) => x,
            Err(e) => {
                error!(
                    "failed to mount volume '{}' to '{}': {e}",
                    total_path.display(),
                    target.display()
                );
                return Err(Status::internal("failed to mount volume"));
            }
        };

        if volume.loop_device.is_none() && loop_device.is_some() {
            volume.loop_device = loop_device;
        }
        volume.mount_paths.push(target);

        volume.state = VolumeState::NodePublished;
        volume.update().await.map_err(|e| {
            error!("failed to update volume: {e:#}");
            Status::internal("failed to update volume")
        })?;

        Ok(Response::new(NodePublishVolumeResponse {}))
    }

    async fn node_unpublish_volume(
        &self,
        request: Request<NodeUnpublishVolumeRequest>,
    ) -> Result<Response<NodeUnpublishVolumeResponse>, Status> {
        let request = request.into_inner();

        if request.volume_id.is_empty() {
            return Err(Status::invalid_argument("volume_id not found"));
        }
        if request.target_path.is_empty() {
            return Err(Status::invalid_argument("missing target_path"));
        }

        let mut volume = match store::Volume::load(request.volume_id).await {
            Ok(Some(x)) => x,
            Ok(None) => return Err(Status::not_found("volume_id not found")),
            Err(e) => {
                error!("failed to load volume for deletion: {e:#}");
                return Err(Status::internal("internal failure"));
            }
        };

        let target: PathBuf = request.target_path.into();
        if !matches!(volume.state, VolumeState::NodePublished)
            || !volume.mount_paths.contains(&target)
        {
            return Ok(Response::new(NodeUnpublishVolumeResponse {}));
        }

        if let Err(e) = unmount_volume(&target).await {
            error!("failed to unmount volume '{}': {e}", target.display());
            return Err(Status::internal("failed to unmount volume"));
        }

        volume.mount_paths.retain(|x| x != &target);
        if volume.mount_paths.is_empty() {
            volume.state = VolumeState::ControllerPublished;
            if let Some(loop_device) = volume.loop_device.take() {
                if let Err(e) = unloop_volume(&loop_device).await {
                    error!("failed to unloop volume '{}': {e}", target.display());
                    // not returning here since we've already gone too far
                }
            }
        }
        volume.update().await.map_err(|e| {
            error!("failed to save volume: {e:#}");
            Status::internal("failed to save volume")
        })?;
        if let Err(e) = tokio::fs::remove_dir(&target).await {
            error!("failed to delete target dir, ignoring: {e}");
        }

        Ok(Response::new(NodeUnpublishVolumeResponse {}))
    }

    async fn node_get_volume_stats(
        &self,
        request: Request<NodeGetVolumeStatsRequest>,
    ) -> Result<Response<NodeGetVolumeStatsResponse>, Status> {
        let request = request.into_inner();

        if request.volume_id.is_empty() {
            return Err(Status::invalid_argument("volume_id not found"));
        }
        if request.volume_path.is_empty() {
            return Err(Status::invalid_argument("volume_path not found"));
        }

        let volume = match store::Volume::load(request.volume_id).await {
            Ok(Some(x)) => x,
            Ok(None) => return Err(Status::not_found("volume_id not found")),
            Err(e) => {
                error!("failed to load volume for deletion: {e:#}");
                return Err(Status::internal("internal failure"));
            }
        };

        let volume_path: PathBuf = request.volume_path.into();

        if !matches!(volume.state, VolumeState::NodePublished)
            || !volume.mount_paths.contains(&volume_path)
        {
            return Err(Status::not_found("volume path and id not found"));
        }

        match crate::statfs::statfs(&volume_path).await {
            Err(e) => {
                error!(
                    "failed to fetch volume stats for '{}': {e}",
                    volume_path.display()
                );
                Err(Status::internal("internal failure"))
            }
            Ok(stats) => Ok(Response::new(NodeGetVolumeStatsResponse {
                usage: vec![
                    VolumeUsage {
                        available: (stats.blocks_free_unprivileged * stats.block_size) as i64,
                        total: (stats.block_count * stats.block_size) as i64,
                        used: ((stats.block_count - stats.blocks_free_unprivileged)
                            * stats.block_size) as i64,
                        unit: volume_usage::Unit::Bytes as i32,
                    },
                    VolumeUsage {
                        available: stats.inodes_free_unprivileged as i64,
                        total: stats.inodes as i64,
                        used: (stats.inodes - stats.inodes_free_unprivileged) as i64,
                        unit: volume_usage::Unit::Inodes as i32,
                    },
                ],
                volume_condition: Some(VolumeCondition {
                    abnormal: false,
                    message: String::new(),
                }),
            })),
        }
    }

    async fn node_expand_volume(
        &self,
        request: Request<NodeExpandVolumeRequest>,
    ) -> Result<Response<NodeExpandVolumeResponse>, Status> {
        let request = request.into_inner();

        if request.volume_id.is_empty() {
            return Err(Status::invalid_argument("volume_id not found"));
        }
        if request.volume_path.is_empty() {
            return Err(Status::invalid_argument("volume_path not found"));
        }

        let mut volume = match store::Volume::load(request.volume_id).await {
            Ok(Some(x)) => x,
            Ok(None) => return Err(Status::not_found("volume_id not found")),
            Err(e) => {
                error!("failed to load volume for deletion: {e:#}");
                return Err(Status::internal("internal failure"));
            }
        };

        let volume_path: PathBuf = request.volume_path.into();

        if !matches!(volume.state, VolumeState::NodePublished)
            || !volume.mount_paths.contains(&volume_path)
        {
            return Err(Status::not_found("volume path and id not found"));
        }

        let target_capacity = match request.capacity_range {
            None => 1073741824, // 1 GiB
            Some(capacity) => capacity.required_bytes as u64,
        };
        if target_capacity <= volume.size {
            return Ok(Response::new(NodeExpandVolumeResponse {
                capacity_bytes: volume.size as i64,
            }));
        }

        let Some(loop_device) = &volume.loop_device else {
            return Err(Status::not_found("loop device not found"));
        };

        let total_path = CONFIG.host_prefix.join(&volume.host_path);
        if let Err(e) = expand_volume(
            &total_path,
            &loop_device,
            target_capacity,
            volume.filesystem,
        )
        .await
        {
            error!("failed to resize volume: {e}");
            return Err(Status::internal("failed to resize volume"));
        }

        volume.size = target_capacity;
        volume.update().await.map_err(|e| {
            error!("failed to save volume: {e:#}");
            Status::internal("failed to save volume")
        })?;

        return Ok(Response::new(NodeExpandVolumeResponse {
            capacity_bytes: volume.size as i64,
        }));
    }

    async fn node_get_capabilities(
        &self,
        _request: Request<NodeGetCapabilitiesRequest>,
    ) -> Result<Response<NodeGetCapabilitiesResponse>, Status> {
        Ok(Response::new(NodeGetCapabilitiesResponse {
            capabilities: vec![
                NodeServiceCapability {
                    r#type: Some(CapabilityType::Rpc(Rpc {
                        r#type: RpcType::ExpandVolume as i32,
                    })),
                },
                NodeServiceCapability {
                    r#type: Some(CapabilityType::Rpc(Rpc {
                        r#type: RpcType::SingleNodeMultiWriter as i32,
                    })),
                },
                NodeServiceCapability {
                    r#type: Some(CapabilityType::Rpc(Rpc {
                        r#type: RpcType::GetVolumeStats as i32,
                    })),
                },
            ],
        }))
    }

    async fn node_get_info(
        &self,
        _request: Request<NodeGetInfoRequest>,
    ) -> Result<Response<NodeGetInfoResponse>, Status> {
        Ok(Response::new(NodeGetInfoResponse {
            node_id: CONFIG.node_id.clone(),
            max_volumes_per_node: 0,
            accessible_topology: Some(Topology {
                segments: CONFIG.topology.clone(),
            }),
        }))
    }
}