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
use super::{
    config_storage::XDGConfigStorage,
    image::{QEmuImageHandler, QEMU_IMG_DEFAULT_FORMAT},
    launcher::QEmuLauncher,
    supervisor::SystemdSupervisor,
    traits::{ConfigStorageHandler, ImageHandler, Launcher, SupervisorHandler},
    vm::VM,
};
use crate::{
    qmp::{Client, UnixSocket},
    util::valid_filename,
};
use anyhow::{anyhow, Result};
use std::{os::unix::net::UnixStream, path::PathBuf, process::Command, sync::Arc};
use tokio::{
    io::{AsyncReadExt, AsyncWriteExt, Interest},
    sync::Mutex,
};

#[derive(Debug, Clone)]
pub struct CommandHandler {
    launcher: Arc<Box<dyn Launcher>>,
    config: Arc<Box<dyn ConfigStorageHandler>>,
    image: Arc<Box<dyn ImageHandler>>,
}

impl Default for CommandHandler {
    fn default() -> Self {
        Self {
            launcher: Arc::new(Box::new(QEmuLauncher::default())),
            config: Arc::new(Box::new(XDGConfigStorage::default())),
            image: Arc::new(Box::new(QEmuImageHandler::default())),
        }
    }
}

impl CommandHandler {
    pub fn list(&self, running: bool) -> Result<()> {
        if running {
            let mut v = Vec::new();

            for item in self.config.vm_list()? {
                if item.supervisor().is_active(&item).unwrap_or_default() {
                    v.push(item)
                }
            }

            Ok(v)
        } else {
            self.config.vm_list()
        }?
        .iter()
        .for_each(|vm| {
            let supervisor = vm.supervisor();

            let (status, is_running) = if supervisor.supervised() {
                match supervisor.is_active(vm) {
                    Ok(res) => {
                        if res {
                            ("supervised: running".to_string(), true)
                        } else {
                            ("supervised: not running".to_string(), false)
                        }
                    }
                    Err(e) => (
                        format!("supervised: could not determine status: {}", e.to_string()),
                        false,
                    ),
                }
            } else if supervisor.is_active(vm).unwrap_or_default() {
                (format!("pid: {}", supervisor.pidof(vm).unwrap()), true)
            } else {
                ("unsupervised".to_string(), false)
            };

            if running && is_running || !running {
                println!(
                    "{} ({}) (size: {:.2})",
                    vm.name(),
                    status,
                    byte_unit::Byte::from_u128(self.config.size(vm).unwrap() as u128)
                        .unwrap()
                        .get_appropriate_unit(byte_unit::UnitType::Decimal)
                );
            }
        });

        Ok(())
    }

    pub fn rename(&self, old: &VM, new: &VM) -> Result<()> {
        match self.config.rename(old, new) {
            Ok(_) => {
                println!("Renamed {} to {}", old, new);
            }
            Err(_) => {
                println!(
                    "Could not rename {}. Does it exist, or does {} already exist?",
                    old, new
                );
            }
        }

        Ok(())
    }

    pub fn supervised(&self) -> Result<()> {
        for item in self.config.vm_list()? {
            if item.supervisor().supervised() {
                let status = if item.supervisor().is_active(&item).unwrap_or_default() {
                    "running"
                } else {
                    "not running"
                };
                println!("{}: {}", item, status)
            }
        }

        Ok(())
    }

    pub async fn nc(&self, vm: &VM, port: u16) -> Result<()> {
        let config = vm.config();

        if config.ports.contains_key(&port.to_string()) {
            let (s, mut r) = tokio::sync::mpsc::unbounded_channel();
            let (close_s, close_r) = tokio::sync::mpsc::unbounded_channel();
            let close_r = Arc::new(Mutex::new(close_r));

            let close_s2 = close_s.clone();
            let close_r2 = close_r.clone();

            tokio::spawn(async move {
                let mut buf = [0_u8; 4096];
                while let Ok(size) = tokio::io::stdin().read(&mut buf).await {
                    if size > 0 {
                        s.send(buf[..size].to_vec()).unwrap();
                    } else {
                        break;
                    }

                    if close_r2.lock().await.try_recv().is_ok() {
                        return;
                    }
                }
                close_s2.send(()).unwrap();
            });

            let mut stream = tokio::net::TcpStream::connect(
                format!("127.0.0.1:{}", port).parse::<std::net::SocketAddr>()?,
            )
            .await?;

            let mut buf = [0_u8; 4096];
            let interest = Interest::WRITABLE.clone();
            let interest = interest.add(Interest::READABLE);
            let interest = interest.add(Interest::ERROR);

            loop {
                let state = stream.ready(interest).await?;

                if state.is_error() {
                    close_s.send(())?;
                    break;
                }

                if state.is_readable() {
                    while let Ok(size) = stream.try_read(&mut buf) {
                        if size > 0 {
                            tokio::io::stdout().write(&buf[..size]).await?;
                        } else {
                            break;
                        }
                    }
                }

                if state.is_writable() {
                    while let Ok(buf) = r.try_recv() {
                        stream.write(&buf).await?;
                    }
                }

                if close_r.lock().await.try_recv().is_ok() {
                    break;
                }
            }
        }

        Ok(())
    }

    pub fn ssh(&self, vm: &VM, args: Option<Vec<String>>) -> Result<()> {
        let mut cmd = Command::new("ssh");
        let port = vm.config().machine.ssh_port.to_string();
        let mut all_args = vec!["-p", &port, "localhost"];

        let args = args.unwrap_or_default();
        all_args.append(&mut args.iter().map(String::as_str).collect());

        if cmd.args(all_args).spawn()?.wait()?.success() {
            Ok(())
        } else {
            Err(anyhow!("SSH failed with non-zero status"))
        }
    }

    pub fn create(&self, vm: &VM, size: usize, append: bool) -> Result<()> {
        if !append {
            if self.config.vm_exists(vm) {
                return Err(anyhow!("vm already exists"));
            }

            if !valid_filename(&vm.name()) {
                return Err(anyhow!("filename contains invalid characters"));
            }

            std::fs::create_dir_all(self.config.vm_root(vm))?;
        }

        self.image.create(self.config.vm_root(vm), size)
    }

    pub fn list_disks(&self, vm: &VM) -> Result<()> {
        if !self.config.vm_exists(vm) {
            return Err(anyhow!("vm doesn't exist"));
        }

        for disk in self.config.disk_list(vm)? {
            let disk = disk
                .file_name()
                .unwrap()
                .to_str()
                .unwrap()
                .trim_start_matches("qemu-")
                .trim_end_matches(QEMU_IMG_DEFAULT_FORMAT)
                .trim_end_matches(".");
            println!("{}", disk);
        }

        Ok(())
    }

    pub fn delete(&self, vm: &VM, disk: Option<String>) -> Result<()> {
        if !self.config.vm_exists(vm) {
            return Err(anyhow!("vm doesn't exist"));
        }

        let root = self.config.vm_root(vm);
        if let Some(disk) = disk {
            std::fs::remove_file(root.join(format!("qemu-{}.{}", disk, QEMU_IMG_DEFAULT_FORMAT)))?;
        } else {
            std::fs::remove_dir_all(root)?;
            if let Err(_) = self.unsupervise(vm) {
                println!("Could not remove systemd unit; assuming it was never installed")
            }
        }

        Ok(())
    }

    pub fn supervise(&self, vm: &VM) -> Result<()> {
        if !self.config.vm_exists(vm) {
            return Err(anyhow!("vm doesn't exist"));
        }

        let supervisor = SystemdSupervisor::default();

        supervisor.storage().create(vm)?;
        supervisor.reload()
    }

    pub fn unsupervise(&self, vm: &VM) -> Result<()> {
        let supervisor = vm.supervisor();
        supervisor.storage().remove(vm)?;
        supervisor.reload()
    }

    pub fn is_active(&self, vm: &VM) -> Result<()> {
        if vm.supervisor().is_active(&vm).unwrap_or_default() {
            println!("{} is active", vm);
        } else {
            println!("{} is not active", vm);
        }

        Ok(())
    }

    pub fn shutdown(&self, vm: &VM, nowait: bool) -> Result<()> {
        if nowait {
            self.launcher.shutdown_immediately(vm)
        } else {
            if let Ok(status) = self.launcher.shutdown_wait(vm) {
                println!(
                    "qemu exited with {} status",
                    status.code().unwrap_or_default()
                );
            }

            Ok(())
        }
    }

    pub fn run(&self, vm: &VM, detach: bool) -> Result<()> {
        if detach {
            self.launcher.launch_detached(vm)
        } else {
            match self.launcher.launch_attached(vm) {
                Ok(status) => {
                    if status.success() {
                        Ok(())
                    } else {
                        Err(anyhow!("qemu exited uncleanly: {}", status))
                    }
                }
                Err(e) => Err(e),
            }
        }
    }

    pub fn import(&self, vm: &VM, from_file: PathBuf, format: String) -> Result<()> {
        if !self.config.vm_exists(vm) {
            std::fs::create_dir_all(self.config.vm_root(vm))?;
        }

        self.image.import(
            self.config.vm_root(vm).join(from_file.file_name().unwrap()),
            from_file,
            format,
        )
    }

    pub fn clone(&self, from: &VM, to: &VM) -> Result<()> {
        if self.config.vm_exists(to) {
            return Err(anyhow!("vm already exists"));
        }

        std::fs::create_dir_all(self.config.vm_root(to))?;
        for img in self.config.disk_list(from)? {
            self.image.clone_image(
                img.clone(),
                self.config.vm_root(to).join(img.file_name().unwrap()),
            )?;
        }

        Ok(())
    }

    pub fn config_copy(&self, from: &VM, to: &VM) -> Result<()> {
        if !self.config.vm_exists(from) {
            println!("VM {} does not exist", from);
            return Ok(());
        }

        let mut to = to.clone();

        to.set_config(from.config());
        self.config.write_config(to)
    }

    pub fn show_config(&self, vm: &VM) -> Result<()> {
        if !self.config.vm_exists(vm) {
            println!("VM {} does not exist", vm);
            return Ok(());
        }
        println!("{}", vm.config().to_string());
        Ok(())
    }

    pub fn config_set(&self, vm: &VM, key: String, value: String) -> Result<()> {
        let mut vm = vm.clone();
        let mut config = vm.config();
        config.set_machine_value(&key, &value)?;
        vm.set_config(config);
        match self.config.write_config(vm.clone()) {
            Ok(_) => {}
            Err(_) => {
                println!("VM {} does not exist", vm);
            }
        }

        Ok(())
    }

    pub fn port_map(&self, vm: &VM, hostport: u16, guestport: u16) -> Result<()> {
        let mut vm = vm.clone();
        let mut config = vm.config();
        config.map_port(hostport, guestport);
        vm.set_config(config);
        self.config.write_config(vm)
    }

    pub fn port_unmap(&self, vm: &VM, hostport: u16) -> Result<()> {
        let mut vm = vm.clone();
        let mut config = vm.config();
        config.unmap_port(hostport);
        vm.set_config(config);
        self.config.write_config(vm)
    }

    pub fn qmp(&self, vm: &VM, command: &str, args: Option<&str>) -> Result<()> {
        let stream = UnixStream::connect(self.config.monitor_path(vm))?;
        let mut us = UnixSocket::new(stream)?;
        us.handshake()?;
        us.send_command("qmp_capabilities", None)?;
        let val = match args {
            Some(args) => us.send_command(command, Some(serde_json::from_str(args)?))?,
            None => us.send_command(command, None)?,
        };

        println!("{}", val);
        Ok(())
    }
}