]> git.proxmox.com Git - proxmox-backup.git/blame - src/bin/proxmox-restore-daemon.rs
restore daemon: create /run/proxmox-backup on startup
[proxmox-backup.git] / src / bin / proxmox-restore-daemon.rs
CommitLineData
dd9cef56
SR
1///! Daemon binary to run inside a micro-VM for secure single file restore of disk images
2use anyhow::{bail, format_err, Error};
d32a8652 3use lazy_static::lazy_static;
9a06eb16 4use log::{info, error};
dd9cef56
SR
5
6use std::os::unix::{
7 io::{FromRawFd, RawFd},
8 net,
9};
10use std::path::Path;
d32a8652 11use std::sync::{Arc, Mutex};
dd9cef56
SR
12
13use tokio::sync::mpsc;
14use tokio_stream::wrappers::ReceiverStream;
15
16use proxmox::api::RpcEnvironmentType;
17use proxmox_backup::client::DEFAULT_VSOCK_PORT;
18use proxmox_backup::server::{rest::*, ApiConfig};
19
20mod proxmox_restore_daemon;
21use proxmox_restore_daemon::*;
22
23/// Maximum amount of pending requests. If saturated, virtio-vsock returns ETIMEDOUT immediately.
24/// We should never have more than a few requests in queue, so use a low number.
25pub const MAX_PENDING: usize = 32;
26
27/// Will be present in base initramfs
28pub const VM_DETECT_FILE: &str = "/restore-vm-marker";
29
d32a8652
SR
30lazy_static! {
31 /// The current disks state. Use for accessing data on the attached snapshots.
32 pub static ref DISK_STATE: Arc<Mutex<DiskState>> = {
33 Arc::new(Mutex::new(DiskState::scan().unwrap()))
34 };
35}
36
dd9cef56
SR
37/// This is expected to be run by 'proxmox-file-restore' within a mini-VM
38fn main() -> Result<(), Error> {
39 if !Path::new(VM_DETECT_FILE).exists() {
309e14eb
TL
40 bail!(
41 "This binary is not supposed to be run manually, use 'proxmox-file-restore' instead."
42 );
dd9cef56
SR
43 }
44
45 // don't have a real syslog (and no persistance), so use env_logger to print to a log file (via
46 // stdout to a serial terminal attached by QEMU)
47 env_logger::from_env(env_logger::Env::default().default_filter_or("info"))
48 .write_style(env_logger::WriteStyle::Never)
49 .init();
50
33d7292f
TL
51 // the API may save some stuff there, e.g., the memcon tracking file
52 // we do not care much, but it's way less headache to just create it
53 std::fs::create_dir_all("/run/proxmox-backup")?;
54
d32a8652
SR
55 // scan all attached disks now, before starting the API
56 // this will panic and stop the VM if anything goes wrong
9a06eb16 57 info!("scanning all disks...");
d32a8652
SR
58 {
59 let _disk_state = DISK_STATE.lock().unwrap();
60 }
61
9a06eb16
TL
62 info!("disk scan complete, starting main runtime...");
63
dd9cef56
SR
64 proxmox_backup::tools::runtime::main(run())
65}
66
67async fn run() -> Result<(), Error> {
a26ebad5
SR
68 watchdog_init();
69
dd9cef56
SR
70 let auth_config = Arc::new(
71 auth::ticket_auth().map_err(|err| format_err!("reading ticket file failed: {}", err))?,
72 );
73 let config = ApiConfig::new("", &ROUTER, RpcEnvironmentType::PUBLIC, auth_config)?;
74 let rest_server = RestServer::new(config);
75
76 let vsock_fd = get_vsock_fd()?;
77 let connections = accept_vsock_connections(vsock_fd);
78 let receiver_stream = ReceiverStream::new(connections);
79 let acceptor = hyper::server::accept::from_stream(receiver_stream);
80
81 hyper::Server::builder(acceptor).serve(rest_server).await?;
82
83 bail!("hyper server exited");
84}
85
86fn accept_vsock_connections(
87 vsock_fd: RawFd,
88) -> mpsc::Receiver<Result<tokio::net::UnixStream, Error>> {
89 use nix::sys::socket::*;
90 let (sender, receiver) = mpsc::channel(MAX_PENDING);
91
92 tokio::spawn(async move {
93 loop {
94 let stream: Result<tokio::net::UnixStream, Error> = tokio::task::block_in_place(|| {
95 // we need to accept manually, as UnixListener aborts if socket type != AF_UNIX ...
96 let client_fd = accept(vsock_fd)?;
97 let stream = unsafe { net::UnixStream::from_raw_fd(client_fd) };
98 stream.set_nonblocking(true)?;
99 tokio::net::UnixStream::from_std(stream).map_err(|err| err.into())
100 });
101
102 match stream {
103 Ok(stream) => {
104 if sender.send(Ok(stream)).await.is_err() {
105 error!("connection accept channel was closed");
106 }
107 }
108 Err(err) => {
109 error!("error accepting vsock connetion: {}", err);
110 }
111 }
112 }
113 });
114
115 receiver
116}
117
118fn get_vsock_fd() -> Result<RawFd, Error> {
119 use nix::sys::socket::*;
120 let sock_fd = socket(
121 AddressFamily::Vsock,
122 SockType::Stream,
123 SockFlag::empty(),
124 None,
125 )?;
126 let sock_addr = VsockAddr::new(libc::VMADDR_CID_ANY, DEFAULT_VSOCK_PORT as u32);
127 bind(sock_fd, &SockAddr::Vsock(sock_addr))?;
128 listen(sock_fd, MAX_PENDING)?;
129 Ok(sock_fd)
130}