aboutsummaryrefslogtreecommitdiffstats
path: root/zoned/src/error.rs
blob: 18f4b7744c66f03a89fa037a8a9ec2796cf51803 (plain)
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
use axum::{
    extract::ws::Message,
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};
use serde_json::json;

pub type Result<T> = std::result::Result<T, Error>;

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("Zone Error: {0:?}")]
    Zone(String),

    #[error("Container Error: {0:?}")]
    Container(String),

    #[error("Container not found")]
    NotFound,

    #[error("WebSocket Error: {0:?}")]
    WebSocket(#[from] WebSocketError),

    #[error("Command Error: {0:?}")]
    Command(#[from] CommandError),

    #[error("PTY Error: {0:?}")]
    Pty(#[from] PtyError),

    #[error("ZFS Error: {0:?}")]
    ZFS(#[from] zone_zfs::Error),

    #[error("NSpawn Error: {0:?}")]
    Nspawn(#[from] zone_nspawn::Error),

    #[error("Config Error: {0:?}")]
    Config(#[from] figment::Error),

    #[error("Axum Error: {0:?}")]
    Axum(#[from] axum::Error),

    #[error("Json Error: {0:?}")]
    Json(#[from] serde_json::error::Error),

    #[error("Send Error: {0:?}")]
    Send(#[from] tokio::sync::mpsc::error::SendError<Message>),

    #[error(transparent)]
    Other(#[from] anyhow::Error),
}

impl IntoResponse for Error {
    fn into_response(self) -> Response {
        let (status, error_message) = match self {
            Error::Container(source) => (StatusCode::NOT_FOUND, source),
            err => (StatusCode::INTERNAL_SERVER_ERROR, format!("{}", err)),
        };

        let body = Json(json!({
            "error": error_message,
        }));

        (status, body).into_response()
    }
}

#[derive(thiserror::Error, Debug)]
pub enum CommandError {
    #[error("Command process failed to execute: {0:?}")]
    Execution(#[from] std::io::Error),

    #[error("Command process exited with status code: {0:?}")]
    ExitStatus(i32),

    #[error("Failed to parse command output: {0:?}")]
    Parsing(#[from] std::string::FromUtf8Error),
}

impl From<i32> for CommandError {
    fn from(i: i32) -> Self {
        Self::ExitStatus(i)
    }
}

#[derive(thiserror::Error, Debug)]
pub enum PtyError {
    #[error("Failed to write to PTY: {0:?}")]
    Write(#[source] std::io::Error),

    #[error("Failed to read from PTY: {0:?}")]
    Read(#[source] std::io::Error),

    #[error("Failed to resize PTY: {0:?}")]
    Resize(#[source] std::io::Error),
}

#[derive(thiserror::Error, Debug)]
pub enum WebSocketError {
    #[error("Missing initialization message")]
    Initialization,

    #[error("Axum Error: {0:?}")]
    Axum(#[from] axum::Error),
}