68 Commits
v0.2 ... v0.4

Author SHA1 Message Date
e6f086f88a Switch to buildGoModule 2020-06-18 16:08:56 +00:00
8264f71eb2 Follow redirect 2020-06-18 15:27:16 +00:00
ba80fba648 Add --network switch to select a networking model (#22) 2020-04-06 09:12:46 +00:00
e588479701 Add --cli switch that disables the GUI window. (#20) 2020-04-05 14:47:10 +00:00
a583335865 Allow VMs with hostname other than default (#19)
The VM runner created by nix is called `./run-<hostname>-vm`.
So far, the code hardcoded it as `./result/bin/run-nixos-vm`, but
for the users that want to change VM hostname it may be problematic.
2020-04-05 13:30:48 +00:00
aaede60c4d Switch to NixOS 20.03 2020-04-01 07:39:23 +00:00
6e26754cec Do not specify session explicitly 2020-04-01 07:39:04 +00:00
c0801541b3 Fix random panics during autoballonning. (#17)
There is a race condition, when good behaving VMs will temporarily
truncate .memory_used to 0 bytes (update is not atomic).

Also, as a matter of principle, VMs should not crash the host,
ever.

Co-authored-by: msm <msm@cert.pl>
2020-03-30 21:53:02 +00:00
63cd3fc79d GitHub Actions: Use latest stable nixpkgs channel 2020-02-21 00:29:49 +00:00
00f705d757 Update screenshot 2020-02-02 02:55:37 +00:00
218e81a6ac virt-viewer: use title as subtitle 2020-02-02 02:13:57 +00:00
7cad1efce8 Move installation guide to docs 2020-02-02 01:43:35 +00:00
cc5262b10f Execute GitHub action on pull requests too 2020-01-31 08:03:05 +00:00
e02edbacf4 Use default machine 2020-01-28 00:12:48 +00:00
2bc5247ac1 Note about the group name
Resolves #14
2020-01-26 19:15:53 +00:00
545291b9cf Suggest to use latest stable channel 2020-01-26 10:23:33 +00:00
9b828ff575 Update installation guide 2020-01-26 01:39:36 +00:00
dc636c3919 Revert "virt-manager: disable subtitle"
This reverts commit d07d51c7ec.
2020-01-22 02:33:02 +00:00
d07d51c7ec virt-manager: disable subtitle 2020-01-22 02:29:54 +00:00
19b92aec1b virt-viewer: use name of appvm applications as a title 2020-01-22 02:21:19 +00:00
680aff06f7 Build appvm from ../default.nix 2020-01-22 01:18:25 +00:00
7b76368699 Cleanup 2020-01-22 01:13:26 +00:00
5a2ce12c2f Build from the source directory 2020-01-22 01:13:05 +00:00
f8bfca0466 GitHub Actions: Do not generate ISO 2020-01-22 00:59:46 +00:00
01a0d206db virt-viewer: do not grab keyboard/mouse 2020-01-22 00:50:54 +00:00
44cb4697ec Remove virt-viewer menu bar 2020-01-22 00:33:20 +00:00
219c48b976 Add dashboard access token 2020-01-20 09:22:40 +00:00
c68f3bf10d Donations 2020-01-16 23:50:39 +00:00
8b271a3e5e Copy templates at start of tool not vm 2020-01-09 23:31:12 +00:00
2146397906 Avoid of changing current work directory 2020-01-09 23:13:48 +00:00
1fbbdee76a Handle case when there's no actions in .desktop file 2020-01-09 23:07:37 +00:00
1f4214199e Build appvm iso with the same source code not master 2020-01-09 23:02:00 +00:00
4e7c6e9895 Build ISO only on master 2020-01-09 23:01:03 +00:00
88718323f0 Add flag for build vm to appvm generate 2020-01-09 22:59:45 +00:00
4ce1c5643f Ignore iso files 2020-01-08 22:25:48 +00:00
9c9a71c2c8 Set default password for user 2020-01-08 22:24:11 +00:00
fca2f89046 Support remove run with nix run 2020-01-08 20:52:29 +00:00
bd63fcd48f Add dot-desktop-fuse service 2020-01-08 11:37:45 +00:00
f15d0fb07a Use master instead of latest tag 2020-01-08 11:20:26 +00:00
a264cb2ced Add missed deps 2020-01-08 11:16:14 +00:00
33cdae7a47 go modules init for dot-desktop-fuse 2020-01-08 01:44:41 +00:00
41f25418e8 Initial implementation for .desktop fuse fs 2020-01-07 21:22:44 +00:00
2be0f82e4a User host user id 2020-01-07 20:01:52 +00:00
dad147eb91 Do not exit on autoballoon errors, keep adjust memory for other VMs 2020-01-05 09:08:43 +00:00
806448df17 Memory autoballoon (host side) 2020-01-05 09:02:03 +00:00
573be66059 Do no enable anything in default local.nix 2020-01-05 08:55:36 +00:00
7df36ae8fc Add channel snapshot to image itself 2020-01-05 08:49:48 +00:00
4066e347ef GitHub Actions: iso artifact 2020-01-05 07:02:34 +00:00
de77abd3ee slim -> lightdm 2020-01-05 06:58:46 +00:00
cead5bab74 GitHub Actions: Live ISO 2020-01-05 06:56:47 +00:00
6536200669 Use lightdm (slim is removed from NixOS) 2020-01-05 06:43:55 +00:00
1095218222 GitHub Actions: Nix environment 2020-01-05 06:20:51 +00:00
a4138a4b44 Add Nix build job 2020-01-05 06:13:56 +00:00
287c6d6043 Update .gitignore 2020-01-05 06:12:18 +00:00
477b48d783 Use go build by default 2020-01-05 06:12:05 +00:00
843ca6864e Refactor 2020-01-05 06:07:02 +00:00
02832a6e38 Add Documentation Status 2020-01-05 06:03:59 +00:00
3f8aa0cc59 Init docs 2020-01-05 05:57:55 +00:00
5526cbee02 Initial implementation of appvm-based OS 2020-01-04 20:58:00 +00:00
7d6d524b67 Add Nix package 2020-01-04 18:20:27 +00:00
40ef3fe50e Use only nixos.org channels if guess 2020-01-04 11:23:40 +00:00
d973179557 Do not install to user profile 2020-01-04 10:52:16 +00:00
49b8790032 Add TODO 2020-01-03 23:01:23 +00:00
355fb314a1 Implements stateless VMs 2020-01-03 22:56:27 +00:00
e037770c38 Revert "Do not install apps to nix user profile"
This reverts commit 02dda8bcf9.
2020-01-03 22:42:27 +00:00
57e15fa0a0 Move shared directory creation out of vm generating function 2020-01-03 22:10:18 +00:00
f1fd2e1505 spice-vdagent should be alive 2020-01-03 10:14:28 +00:00
02dda8bcf9 Do not install apps to nix user profile 2020-01-03 09:36:39 +00:00
30 changed files with 786 additions and 165 deletions

View File

@ -1,4 +1,4 @@
Makes sure these boxes are checked before submitting your pull request -- thank you!
<!-- Makes sure these boxes are checked before submitting your pull request -- thank you! -->
- [ ] I tested it locally.
- [ ] I tried to run at least one application VM and it works.

25
.github/workflows/donate.yml vendored Normal file
View File

@ -0,0 +1,25 @@
name: donate
on:
issues:
types: [opened, closed]
schedule:
- cron: '35 * * * *' # for updating balance
jobs:
comment:
runs-on: ubuntu-latest
steps:
- env:
# https://github.com/jollheef/donate/blob/master/dashboard/whitelist.go
DASHBOARD_ACCESS_TOKEN: ${{ secrets.DONATE_DASHBOARD_ACCESS_TOKEN }}
# the scope is current repository only
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TOOL: "https://github.com/jollheef/donate/archive/master.tar.gz"
run: |
curl -L https://nixos.org/nix/install | sh
. ~/.nix-profile/etc/profile.d/nix.sh
# Use latest stable nixpkgs channel
nix-channel --add https://nixos.org/channels/nixos-20.03 nixpkgs
nix-channel --update
nix run -f $TOOL -c donate-ci

View File

@ -1,6 +1,6 @@
name: Ubuntu
on: [push]
on: [push, pull_request]
jobs:
build:
@ -14,3 +14,20 @@ jobs:
- name: Build
run: go build
nix-build:
name: nix-build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Install Nix
run: |
curl -L https://nixos.org/nix/install | sh
. ~/.nix-profile/etc/profile.d/nix.sh
nix-channel --update
- name: Build
run: |
. ~/.nix-profile/etc/profile.d/nix.sh
make nix

2
.gitignore vendored
View File

@ -1 +1 @@
nix/local.nix
appvm

5
Makefile Normal file
View File

@ -0,0 +1,5 @@
go:
go build
nix:
nix-build #-E '((import <nixpkgs> {}).callPackage (import ./default.nix) { })' --option sandbox true --no-out-link

View File

@ -1,3 +1,4 @@
[![Documentation Status](https://readthedocs.org/projects/appvm/badge/?version=latest)](https://appvm.readthedocs.io/en/latest/?badge=latest)
[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=R8W2UQPZ5X5JE&source=url)
[![Donate](https://img.shields.io/badge/Donate-BitCoin-green.svg)](https://blockchair.com/bitcoin/address/bc1q23fyuq7kmngrgqgp6yq9hk8a5q460f39m8nv87)
@ -7,55 +8,24 @@ Simple application VMs (hypervisor-based sandbox) based on Nix package manager.
Uses one **read-only** /nix directory for all appvms. So creating a new appvm (but not first) is just about one minute.
![appvm screenshot](screenshots/2018-07-05.png)
![appvm screenshot](https://gateway.ipfs.io/ipfs/QmetVp2LRwcy3baxuAjDgBPwv5ych5kRfXeULoNpQAFsaP)
## Dependencies
## Installation
$ sudo apt install golang virt-manager curl git
$ sudo usermod -a -G libvirt $USER
See [related documentation](https://appvm.readthedocs.io/en/latest/installation.html).
$ echo 'export GOPATH=$HOME/go' >> ~/.bash_profile
$ echo 'export PATH=$PATH:$GOPATH/bin' >> ~/.bash_profile
$ echo 'source ~/.bash_profile' >> ~/.bashrc
$ source ~/.bash_profile
## Usage
You need to **relogin** if you install virt-manager (libvirt) first time.
## Install Nix package manager
$ sudo mkdir -m 0755 /nix && sudo chown $USER /nix
$ curl https://nixos.org/nix/install | sh
$ . ~/.nix-profile/etc/profile.d/nix.sh
## Libvirt from user (required if you need access to shared files)
$ echo user = "\"$USER\"" | sudo tee -a /etc/libvirt/qemu.conf
$ sudo systemctl restart libvirtd
## Install appvm tool
$ go get code.dumpstack.io/tools/appvm
## Update appvm tool
$ go get -u code.dumpstack.io/tools/appvm
## Search for applications
### Search for applications
$ appvm search chromium
## Generate new application
$ nix-channel --list
nix https://nixos.org/channels/nixos-unstable
$ appvm generate nix.firefox
## Run application
### Run application
$ appvm start chromium
$ # ... long wait for first time, because we need to collect a lot of packages
## Synchronize remote repos for applications
### Synchronize remote repos for applications
$ appvm sync
@ -63,17 +33,17 @@ You can customize local settings in **~/.config/appvm/nix/local.nix**.
Default hotkey to release cursor: ctrl+alt.
## Shared directory
### Shared directory
$ ls appvm/chromium
foo.tar.gz
bar.tar.gz
## Close VM
### Close VM
$ appvm stop chromium
## Automatic ballooning
### Automatic ballooning
Add this command:

192
appvm.go
View File

@ -13,6 +13,7 @@ import (
"io"
"io/ioutil"
"log"
"math/rand"
"net"
"os"
"os/exec"
@ -30,6 +31,15 @@ import (
kingpin "gopkg.in/alecthomas/kingpin.v2"
)
type networkModel int
const (
networkOffline networkModel = iota
networkQemu networkModel = iota
networkLibvirt networkModel = iota
)
func list(l *libvirt.Libvirt) {
domains, err := l.Domains()
if err != nil {
@ -105,10 +115,10 @@ func streamStdOutErr(command *cmd.Cmd) {
}
}
func generateVM(name string, verbose bool) (realpath, reginfo, qcow2 string, err error) {
func generateVM(path, name string, verbose bool) (realpath, reginfo, qcow2 string, err error) {
command := cmd.NewCmdOptions(cmd.Options{Buffered: false, Streaming: true},
"nix-build", "<nixpkgs/nixos>", "-A", "config.system.build.vm",
"-I", "nixos-config=nix/"+name+".nix", "-I", ".")
"-I", "nixos-config="+path+"/nix/"+name+".nix", "-I", path)
if verbose {
go streamStdOutErr(command)
@ -132,8 +142,13 @@ func generateVM(name string, verbose bool) (realpath, reginfo, qcow2 string, err
return
}
bytes, err := ioutil.ReadFile("result/bin/run-nixos-vm")
if err != nil {
matches, err := filepath.Glob("result/bin/run-*-vm")
if err != nil || len(matches) != 1 {
return
}
bytes, err := ioutil.ReadFile(matches[0])
if err != nil || len(matches) != 1 {
return
}
@ -165,23 +180,16 @@ func isRunning(l *libvirt.Libvirt, name string) bool {
return err == nil
}
func generateAppVM(l *libvirt.Libvirt, appvmPath, name string, verbose,
online bool) (err error) {
func generateAppVM(l *libvirt.Libvirt,
nixName, vmName, appvmPath, sharedDir string,
verbose bool, network networkModel, gui bool) (err error) {
err = os.Chdir(appvmPath)
realpath, reginfo, qcow2, err := generateVM(appvmPath, nixName, verbose)
if err != nil {
return
}
realpath, reginfo, qcow2, err := generateVM(name, verbose)
if err != nil {
return
}
sharedDir := fmt.Sprintf(os.Getenv("HOME") + "/appvm/" + name)
os.MkdirAll(sharedDir, 0700)
xml := generateXML(name, online, realpath, reginfo, qcow2, sharedDir)
xml := generateXML(vmName, network, gui, realpath, reginfo, qcow2, sharedDir)
_, err = l.DomainCreateXML(xml, libvirt.DomainStartValidate)
return
}
@ -210,14 +218,31 @@ func isAppvmConfigurationExists(appvmPath, name string) bool {
return fileExists(appvmPath + "/nix/" + name + ".nix")
}
func start(l *libvirt.Libvirt, name string, verbose, online bool,
args, open string) {
func start(l *libvirt.Libvirt, name string, verbose bool, network networkModel,
gui, stateless bool, args, open string) {
appvmPath := configDir
vmHomePath := os.Getenv("HOME") + "/appvm/" + name + "/"
statelessName := fmt.Sprintf("tmp_%d_%s", rand.Int(), name)
sharedDir := os.Getenv("HOME") + "/appvm/"
if stateless {
sharedDir += statelessName
} else {
sharedDir += name
}
os.MkdirAll(sharedDir, 0700)
vmName := "appvm_"
if stateless {
vmName += statelessName
} else {
vmName += name
}
if open != "" {
filename := vmHomePath + filepath.Base(open)
filename := sharedDir + "/" + filepath.Base(open)
err := copyFile(open, filename)
if err != nil {
log.Println("Can't copy file")
@ -228,7 +253,7 @@ func start(l *libvirt.Libvirt, name string, verbose, online bool,
}
if args != "" {
err := ioutil.WriteFile(vmHomePath+".args", []byte(args), 0700)
err := ioutil.WriteFile(sharedDir+"/"+".args", []byte(args), 0700)
if err != nil {
log.Println("Can't write args")
return
@ -238,31 +263,29 @@ func start(l *libvirt.Libvirt, name string, verbose, online bool,
if !isAppvmConfigurationExists(appvmPath, name) {
log.Println("No configuration exists for app, " +
"trying to generate")
err := generate(l, name, "", "")
err := generate(name, "", "", false)
if err != nil {
log.Println("Can't auto generate")
return
}
}
// Copy templates
err := prepareTemplates(appvmPath)
if err != nil {
log.Fatal(err)
}
if !isRunning(l, name) {
if !isRunning(l, vmName) {
if !verbose {
go stupidProgressBar()
}
err = generateAppVM(l, appvmPath, name, verbose, online)
err := generateAppVM(l, name, vmName, appvmPath, sharedDir,
verbose, network, gui)
if err != nil {
log.Fatal(err)
}
}
cmd := exec.Command("virt-viewer", "-c", "qemu:///system", "appvm_"+name)
cmd.Start()
if gui {
cmd := exec.Command("virt-viewer", "-c", "qemu:///system", vmName)
cmd.Start()
}
}
func stop(l *libvirt.Libvirt, name string) {
@ -300,17 +323,24 @@ func autoBalloon(l *libvirt.Libvirt, memoryMin, adjustPercent uint64) {
memoryUsedRaw, err := ioutil.ReadFile(os.Getenv("HOME") + "/appvm/" + name + "/.memory_used")
if err != nil {
log.Fatal(err)
log.Println(err)
continue
}
if len(memoryUsedRaw) == 0 {
log.Println("Empty .memory_used file for domain", name)
continue
}
memoryUsedMiB, err := strconv.Atoi(string(memoryUsedRaw[0 : len(memoryUsedRaw)-1]))
if err != nil {
log.Fatal(err)
log.Println(err)
continue
}
memoryUsed := memoryUsedMiB * 1024
_, memoryMax, memoryCurrent, _, _, err := l.DomainGetInfo(d)
if err != nil {
log.Fatal(err)
log.Println(err)
continue
}
memoryNew := uint64(float64(memoryUsed) * (1 + float64(adjustPercent)/100))
@ -325,7 +355,8 @@ func autoBalloon(l *libvirt.Libvirt, memoryMin, adjustPercent uint64) {
err = l.DomainSetMemory(d, memoryNew)
if err != nil {
log.Fatal(err)
log.Println(err)
continue
}
table.Append([]string{name,
@ -365,9 +396,56 @@ func sync() {
log.Println("Done")
}
func cleanupStatelessVMs(l *libvirt.Libvirt) {
domains, err := l.Domains()
if err != nil {
log.Fatal(err)
}
dirs, err := ioutil.ReadDir(appvmHomesDir)
if err != nil {
log.Fatal(err)
}
for _, f := range dirs {
if !strings.HasPrefix(f.Name(), "tmp_") {
continue
}
alive := false
for _, d := range domains {
if d.Name == "appvm_"+f.Name() {
alive = true
}
}
if !alive {
os.RemoveAll(appvmHomesDir + f.Name())
}
}
}
func parseNetworkModel(flagOffline bool, flagNetworking string) networkModel {
if flagNetworking != "" && flagOffline {
log.Fatal("Can't use both --network and --offline switches")
}
if flagOffline || flagNetworking == "offline" {
return networkOffline
}
if flagNetworking == "libvirt" {
return networkLibvirt
}
if flagNetworking == "qemu" {
return networkQemu
}
return networkQemu // qemu is the default network model
}
var configDir = os.Getenv("HOME") + "/.config/appvm/"
var appvmHomesDir = os.Getenv("HOME") + "/appvm/"
func main() {
rand.Seed(time.Now().UnixNano())
os.Mkdir(os.Getenv("HOME")+"/appvm", 0700)
os.MkdirAll(configDir+"/nix", 0700)
@ -377,22 +455,17 @@ func main() {
log.Fatal(err)
}
err = ioutil.WriteFile(configDir+"/nix/base.nix", base_nix, 0644)
err = ioutil.WriteFile(configDir+"/nix/base.nix", baseNix(), 0644)
if err != nil {
log.Fatal(err)
}
c, err := net.DialTimeout("unix", "/var/run/libvirt/libvirt-sock", time.Second)
// Copy templates
err = prepareTemplates(configDir)
if err != nil {
log.Fatal(err)
}
l := libvirt.New(c)
if err := l.Connect(); err != nil {
log.Fatal(err)
}
defer l.Disconnect()
kingpin.Command("list", "List applications")
autoballonCommand := kingpin.Command("autoballoon", "Automatically adjust/reduce app vm memory")
minMemory := autoballonCommand.Flag("min-memory", "Set minimal memory (megabytes)").Default("1024").Uint64()
@ -404,6 +477,9 @@ func main() {
startArgs := startCommand.Flag("args", "Command line arguments").String()
startOpen := startCommand.Flag("open", "Pass file to application").String()
startOffline := startCommand.Flag("offline", "Disconnect").Bool()
startCli := startCommand.Flag("cli", "Disable graphics mode, enable serial").Bool()
startStateless := startCommand.Flag("stateless", "Do not use default state directory").Bool()
startNetwork := startCommand.Flag("network", "Used networking model").Enum("offline", "qemu", "libvirt")
stopName := kingpin.Command("stop", "Stop application").Arg("name", "Application name").Required().String()
dropName := kingpin.Command("drop", "Remove application data").Arg("name", "Application name").Required().String()
@ -412,21 +488,45 @@ func main() {
generateName := generateCommand.Arg("name", "Nix package name").Required().String()
generateBin := generateCommand.Arg("bin", "Binary").Default("").String()
generateVMName := generateCommand.Flag("vm", "Use VM Name").Default("").String()
generateBuildVM := generateCommand.Flag("build", "Build VM").Bool()
searchCommand := kingpin.Command("search", "Search for application")
searchName := searchCommand.Arg("name", "Application name").Required().String()
kingpin.Command("sync", "Synchronize remote repos for applications")
var l *libvirt.Libvirt
if kingpin.Parse() != "generate" {
c, err := net.DialTimeout(
"unix",
"/var/run/libvirt/libvirt-sock",
time.Second,
)
if err != nil {
log.Fatal(err)
}
l = libvirt.New(c)
if err := l.Connect(); err != nil {
log.Fatal(err)
}
defer l.Disconnect()
cleanupStatelessVMs(l)
}
switch kingpin.Parse() {
case "list":
list(l)
case "search":
search(*searchName)
case "generate":
generate(l, *generateName, *generateBin, *generateVMName)
generate(*generateName, *generateBin, *generateVMName,
*generateBuildVM)
case "start":
start(l, *startName, !*startQuiet, !*startOffline,
networkModel := parseNetworkModel(*startOffline, *startNetwork)
start(l, *startName,
!*startQuiet, networkModel, !*startCli, *startStateless,
*startArgs, *startOpen)
case "stop":
stop(l, *stopName)

View File

@ -1,6 +1,12 @@
package main
var base_nix = []byte(`
import (
"fmt"
"log"
"os/user"
)
var base_nix = `
{pkgs, ...}:
{
imports = [
@ -10,18 +16,20 @@ var base_nix = []byte(`
services.xserver = {
enable = true;
desktopManager.xterm.enable = false;
displayManager.slim = {
displayManager.lightdm = {
enable = true;
defaultUser = "user";
autoLogin = true;
autoLogin = {
enable = true;
user = "user";
};
};
windowManager.xmonad.enable = true;
windowManager.default = "xmonad";
};
services.spice-vdagentd.enable = true;
users.extraUsers.user = {
uid = %s;
isNormalUser = true;
extraGroups = [ "audio" ];
createHome = true;
@ -37,7 +45,7 @@ main = xmonad defaultConfig
startup :: X ()
startup = do
spawn "${pkgs.spice-vdagent}/bin/spice-vdagent"
spawn "while [ 1 ]; do ${pkgs.spice-vdagent}/bin/spice-vdagent -x; done &"
'';
systemd.services.home-user-build-xmonad = {
@ -56,7 +64,7 @@ startup = do
systemd.services.mount-home-user = {
description = "Mount /home/user (crutch)";
serviceConfig = {
ExecStart = "/bin/sh -c '/run/current-system/sw/bin/mount -t 9p -o trans=virtio,version=9p2000.L,uid=1000 home /home/user'";
ExecStart = "/bin/sh -c '/run/current-system/sw/bin/mount -t 9p -o trans=virtio,version=9p2000.L home /home/user'";
RemainAfterExit = "yes";
Type = "oneshot";
User = "root";
@ -104,4 +112,12 @@ startup = do
wantedBy = ["timers.target"];
};
}
`)
`
func baseNix() []byte {
u, err := user.Current()
if err != nil {
log.Fatal(err)
}
return []byte(fmt.Sprintf(base_nix, u.Uid))
}

37
default.nix Normal file
View File

@ -0,0 +1,37 @@
let
pkgs = import <nixpkgs> {};
virt-manager-without-menu = pkgs.virt-viewer.overrideAttrs(x: {
patches = [
./patches/0001-Remove-menu-bar.patch
./patches/0002-Do-not-grab-keyboard-mouse.patch
./patches/0003-Use-name-of-appvm-applications-as-a-title.patch
./patches/0004-Use-title-application-name-as-subtitle.patch
];
});
in with pkgs;
buildGoModule rec {
pname = "appvm";
version = "master";
buildInputs = [ makeWrapper ];
goPackagePath = "code.dumpstack.io/tools/${pname}";
src = ./.;
vendorSha256 = "1aimli23jdqv8rifsn22qfbj2c0nc0s5czsd8qprhnr4hcsbdnkf";
modSha256 = "${vendorSha256}"; # backward compatibility
postFixup = ''
wrapProgram $out/bin/appvm \
--prefix PATH : "${lib.makeBinPath [ nix virt-manager-without-menu ]}"
'';
meta = {
description = "Nix-based app VMs";
homepage = "https://code.dumpstack.io/tools/${pname}";
maintainers = [ lib.maintainers.dump_stack ];
license = lib.licenses.gpl3;
};
}

4
docs/architecture.rst Normal file
View File

@ -0,0 +1,4 @@
Architecture
============
*TODO*

30
docs/index.rst Normal file
View File

@ -0,0 +1,30 @@
appvm
=====
*appvm* is the thin easy-to-use hypervisor-based sandboxing software.
*appvm* was created for the purpose of decreasing complexity of using
graphical software inside virtual machines, at the same time
maintaining reasonable security and keep *appvm* itself simple and
portable.
While I'm trying to keep that documentation up-to-date, there may be
some missing information. Use ``appvm --help-long`` for checking all
features.
If you found anything missed here, please make a pull request or send
patches to patch@dumpstack.io.
If you need personal support, your company is interested in the
project or you just want to share some thoughts -- feel free to create
a new issue or write to root@dumpstack.io.
Contents
========
:ref:`Keyword Index <genindex>`
.. toctree::
architecture.rst
threat-model.rst

42
docs/installation.rst Normal file
View File

@ -0,0 +1,42 @@
Installation
============
NixOS
-----
/etc/nixos/configuration.nix::
virtualisation.libvirtd = {
enable = true;
qemuVerbatimConfig = ''
namespaces = []
user = "${username}"
group = "users"
'';
};
users.users."${username}".extraGroups = [ ... "libvirtd" ];
shell::
nix run -f https://code.dumpstack.io/tools/appvm/archive/master.tar.gz -c appvm
Ubuntu 20.04
------
Requirements::
sudo apt install virt-manager curl git
echo user = "\"$USER\"" | sudo tee -a /etc/libvirt/qemu.conf
echo '/var/tmp/** rwlk,' | sudo tee -a /etc/apparmor.d/local/abstractions/libvirt-qemu
curl -L https://nixos.org/nix/install | sh
systemctl reboot
Use latest stable nixpkgs channel::
nix-channel --add https://nixos.org/channels/nixos-20.03 nixpkgs
nix-channel --update
Install appvm::
nix-env -if https://code.dumpstack.io/tools/appvm/archive/master.tar.gz

4
docs/threat-model.rst Normal file
View File

@ -0,0 +1,4 @@
Threat model
=======================
*TODO*

88
dot-desktop-fuse/main.go Normal file
View File

@ -0,0 +1,88 @@
package main
import (
"bytes"
"context"
"io/ioutil"
"log"
"os"
"os/signal"
"path/filepath"
"regexp"
"syscall"
"github.com/hanwen/go-fuse/v2/fs"
"github.com/hanwen/go-fuse/v2/fuse"
)
type ddf struct {
Path string
fs.Inode
}
func (r *ddf) OnAdd(ctx context.Context) {
files, err := ioutil.ReadDir(r.Path)
if err != nil {
log.Fatal(err)
}
for _, file := range files {
b, err := ioutil.ReadFile(filepath.Join(r.Path, file.Name()))
if err != nil {
log.Fatal(err)
}
if bytes.Contains(b, []byte("Actions=")) {
b = bytes.ReplaceAll(b, []byte("Actions="), []byte("Actions=appvm;"))
} else {
b = bytes.ReplaceAll(b, []byte("Exec="), []byte("Actions=appvm;\nExec="))
}
raw := string(regexp.MustCompile("Exec=[a-zA-Z0-9]*").Find(b))
var app string
if len(raw) > 5 {
app = string(raw)[5:]
} else {
log.Println("Can't find Exec entry for", file.Name())
continue
}
b = append(b, []byte("\n[Desktop Action appvm]\n")...)
b = append(b, []byte("Name=Open in appvm\n")...)
b = append(b, []byte("Exec=appvm start "+app+"\n")...)
ch := r.NewPersistentInode(
ctx, &fs.MemRegularFile{
Data: b,
Attr: fuse.Attr{Mode: 0444},
}, fs.StableAttr{})
r.AddChild(file.Name(), ch, false)
}
}
var _ = (fs.NodeOnAdder)((*ddf)(nil))
func setupSigintHandler(server *fuse.Server) {
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
server.Unmount()
os.Exit(1)
}()
}
func main() {
const from = "/var/run/current-system/sw/share/applications/"
to := filepath.Join(os.Getenv("HOME"), "/.local/share/applications")
os.MkdirAll(to, 0755)
server, err := fs.Mount(to, &ddf{Path: from}, nil)
if err != nil {
log.Fatal(err)
}
setupSigintHandler(server)
server.Wait()
}

View File

@ -8,8 +8,6 @@ import (
"os"
"os/exec"
"strings"
"github.com/digitalocean/go-libvirt"
)
var template = `
@ -34,12 +32,8 @@ in {
}
`
func isPackageExists(name string) bool {
cmd := exec.Command("nix-env", "-iA", name)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
return err == nil
func isPackageExists(channel, name string) bool {
return nil == exec.Command("nix-build", "<"+channel+">", "-A", name).Run()
}
func nixPath(name string) (path string, err error) {
@ -62,8 +56,10 @@ func guessChannel() (channel string, err error) {
for _, line := range channels {
fields := strings.Fields(line)
if len(fields) == 2 {
channel = fields[0]
return
if strings.Contains(fields[1], "nixos.org/channels") {
channel = fields[0]
return
}
}
}
@ -80,34 +76,38 @@ func filterDotfiles(files []os.FileInfo) (notHiddenFiles []os.FileInfo) {
return
}
func generate(l *libvirt.Libvirt, pkg, bin, vmname string) (err error) {
var name string
func generate(pkg, bin, vmname string, build bool) (err error) {
// TODO refactor
var name, channel string
if strings.Contains(pkg, ".") {
name = pkg
channel = strings.Split(pkg, ".")[0]
name = strings.Join(strings.Split(pkg, ".")[1:], ".")
} else {
log.Println("Package name does not contains channel")
log.Println("Trying to guess")
var channel string
channel, err = guessChannel()
if err != nil {
log.Println("Cannot guess channel")
log.Println("Check nix-channel --list")
return
log.Println("Will try <nixpkgs>")
channel = "nixpkgs"
err = nil
}
name = channel + "." + pkg
log.Println("Use", name)
name = pkg
log.Println("Use", channel+"."+pkg)
}
if !isPackageExists(name) {
if !isPackageExists(channel, name) {
s := "Package " + name + " does not exists"
err = errors.New(s)
log.Println(s)
return
}
path, err := nixPath(name)
path, err := nixPath(channel + "." + name)
if err != nil {
log.Println("Cannot find nix path")
return
@ -171,25 +171,14 @@ func generate(l *libvirt.Libvirt, pkg, bin, vmname string) (err error) {
bin = files[0].Name()
}
var realName string
for i, s := range strings.Split(name, ".") {
if i == 0 {
continue
}
if i != 1 {
realName += "."
}
realName += s
}
var appFilename string
if vmname != "" {
appFilename = configDir + "/nix/" + vmname + ".nix"
} else {
appFilename = configDir + "/nix/" + realName + ".nix"
appFilename = configDir + "/nix/" + name + ".nix"
}
appNixConfig := fmt.Sprintf(template, realName, bin)
appNixConfig := fmt.Sprintf(template, name, bin)
err = ioutil.WriteFile(appFilename, []byte(appNixConfig), 0600)
if err != nil {
@ -199,5 +188,18 @@ func generate(l *libvirt.Libvirt, pkg, bin, vmname string) (err error) {
fmt.Print(appNixConfig + "\n")
log.Println("Configuration file is saved to", appFilename)
if build {
if vmname != "" {
_, _, _, err = generateVM(configDir, vmname, true)
} else {
_, _, _, err = generateVM(configDir, name, true)
}
if err != nil {
return
}
}
return
}

3
go.mod
View File

@ -1,12 +1,13 @@
module code.dumpstack.io/tools/appvm
go 1.12
go 1.14
require (
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 // indirect
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d // indirect
github.com/digitalocean/go-libvirt v0.0.0-20190715144809-7b622097a793
github.com/go-cmd/cmd v1.1.0
github.com/hanwen/go-fuse/v2 v2.0.3
github.com/jollheef/go-system v0.0.0-20160710075518-6ed6b1d2b8db
github.com/olekukonko/tablewriter v0.0.4
gopkg.in/alecthomas/kingpin.v2 v2.2.6

13
go.sum
View File

@ -2,22 +2,35 @@ github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 h1:JYp7IbQjafo
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d h1:UQZhZ2O0vMHr2cI+DC1Mbh0TJxzA3RcLoMsFw+aXw7E=
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho=
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/digitalocean/go-libvirt v0.0.0-20190715144809-7b622097a793 h1:+ItaX1GKKT70bYwazNtWeYz8QBfirNC85J70psPGgN0=
github.com/digitalocean/go-libvirt v0.0.0-20190715144809-7b622097a793/go.mod h1:PRcPVAAma6zcLpFd4GZrjR/MRpood3TamjKI2m/z/Uw=
github.com/go-cmd/cmd v1.1.0 h1:LxXflJCRKNZgoKl/0TJdzIDSGFdik3zxaeyL1yXCTsI=
github.com/go-cmd/cmd v1.1.0/go.mod h1:bkfdaV0aMvVwTINGdkU5jlQEd9gF0z4irQutl37pOd8=
github.com/go-test/deep v1.0.1 h1:UQhStjbkDClarlmv0am7OXXO4/GaPdCGiUiMTvi28sg=
github.com/go-test/deep v1.0.1/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA=
github.com/hanwen/go-fuse v1.0.0 h1:GxS9Zrn6c35/BnfiVsZVWmsG803xwE7eVRDvcf/BEVc=
github.com/hanwen/go-fuse v1.0.0/go.mod h1:unqXarDXqzAk0rt98O2tVndEPIpUgLD9+rwFisZH3Ok=
github.com/hanwen/go-fuse/v2 v2.0.3 h1:kpV28BKeSyVgZREItBLnaVBvOEwv2PuhNdKetwnvNHo=
github.com/hanwen/go-fuse/v2 v2.0.3/go.mod h1:0EQM6aH2ctVpvZ6a+onrQ/vaykxh2GH7hy3e13vzTUY=
github.com/jollheef/go-system v0.0.0-20160710075518-6ed6b1d2b8db h1:HGcWru24Gt24VFEsX7mxKtO+/NnKCuQ0LYtardulWMc=
github.com/jollheef/go-system v0.0.0-20160710075518-6ed6b1d2b8db/go.mod h1:Cj2JA+Wov6pwK3QTq2PuRXkZ5UM+DT3apJtBDUS8zKE=
github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k=
github.com/mattn/go-runewidth v0.0.7 h1:Ei8KR0497xHyKJPAv59M1dkC+rOZCMBJ+t3fZ+twI54=
github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/olekukonko/tablewriter v0.0.4 h1:vHD/YYe1Wolo78koG299f7V/VAS08c6IpCLn+Ejf/w8=
github.com/olekukonko/tablewriter v0.0.4/go.mod h1:zq6QwlOf5SlnkVbMSr5EoBv3636FWnp+qbPhuoO21uA=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522 h1:Ve1ORMCxvRmSXBwJK+t3Oy+V2vRW2OetUQBq4rJIkZE=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
gopkg.in/alecthomas/kingpin.v2 v2.2.6 h1:jMFz6MfLP0/4fUyZle81rXUoxOBFi19VUFKVDOQfozc=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

View File

@ -2,7 +2,6 @@ package main
var local_nix_template = []byte(`
{
services.xserver.layout = "us,ru";
services.xserver.xkbOptions = "ctrl:nocaps,grp:rctrl_toggle";
#services.xserver.xkbOptions = "ctrl:nocaps";
}
`)

4
os/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
*.iso
target.nix
result
nixos.qcow2

20
os/Makefile Normal file
View File

@ -0,0 +1,20 @@
test: vm cleanup
vm:
ln -sf vm.nix target.nix
nix-build '<nixpkgs/nixos>' -A vm -I nixos-config=configuration.nix
@echo "Use Ctrl-Alt-Q to close VM" | grep --color=always '.*'
./result/bin/run-nixos-vm -cpu host
cleanup:
rm -f nixos.qcow2
unlink result
iso:
@echo "Not yet available. Use \`make live-iso\`." | grep --color=always '.*'
live-iso:
ln -sf live-iso.nix target.nix
nix-build '<nixpkgs/nixos>' -A config.system.build.isoImage -I nixos-config=configuration.nix
cp result/iso/* appvm.iso
unlink result

11
os/README.md Normal file
View File

@ -0,0 +1,11 @@
# $Placeholder OS
The primary goal of appvm is to provide application VMs as a tool, but some people ask for a complete distro so why not.
## Usage
make test
or
make live-iso

76
os/configuration.nix Normal file
View File

@ -0,0 +1,76 @@
{ config, pkgs, lib, ... }:
let
appvm = (import ../default.nix);
in {
imports = [
<nixpkgs/nixos/modules/installer/cd-dvd/channel.nix>
./target.nix
#./hardware-configuration.nix
];
time.timeZone = "UTC";
boot.loader.systemd-boot.enable = true;
# You can not use networking.networkmanager with networking.wireless
networking.wireless.enable = false;
users.users.user = {
isNormalUser = true;
initialPassword = "user"; # should be changed right after start
extraGroups = [ "audio" "libvirtd" ];
};
virtualisation.libvirtd = {
enable = true;
qemuVerbatimConfig = ''
namespaces = []
user = "user"
group = "users"
'';
};
systemd.user.services."dot-desktop-fuse" = {
serviceConfig = {
ExecStart = "${appvm}/bin/dot-desktop-fuse";
Restart = "on-failure";
};
path = [ "/run/wrappers" ];
wantedBy = [ "default.target" ];
};
systemd.user.services."autoballoon" = {
serviceConfig.StartLimitBurst = 64;
script = "${appvm}/bin/appvm autoballoon";
};
systemd.user.timers."autoballoon" = {
description = "Autoupdate resolution crutch";
timerConfig = {
OnBootSec = "1s";
OnUnitInactiveSec = "1s";
Unit = "autoballoon.service";
AccuracySec = "1us";
};
wantedBy = ["timers.target"];
};
environment.systemPackages = with pkgs; [
appvm virtmanager chromium
# Cache packages required for application VMs
xmonad-with-packages spice-vdagent bc qemu_test lightdm
];
services.xserver.enable = true;
services.xserver.displayManager.gdm = {
enable = true;
wayland = false; # FIXME
autoLogin = {
enable = true;
user = "user";
};
};
services.xserver.desktopManager.gnome3.enable = true;
}

6
os/live-iso.nix Normal file
View File

@ -0,0 +1,6 @@
{
imports = [
#<nixpkgs/nixos/modules/profiles/hardened.nix>
<nixpkgs/nixos/modules/installer/cd-dvd/installation-cd-minimal.nix>
];
}

5
os/vm.nix Normal file
View File

@ -0,0 +1,5 @@
{
# vm.nix is used for testing only
users.users.root.initialPassword = "root";
virtualisation.memorySize = 8196;
}

View File

@ -0,0 +1,25 @@
From c26580442a4ac18f805b1795ec250d6cf5857a49 Mon Sep 17 00:00:00 2001
From: Mikhail Klementev <blame@dumpstack.io>
Date: Wed, 22 Jan 2020 00:25:16 +0000
Subject: [PATCH 1/4] Remove menu bar
---
src/resources/ui/virt-viewer.ui | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/resources/ui/virt-viewer.ui b/src/resources/ui/virt-viewer.ui
index 93471a4..b029ad7 100644
--- a/src/resources/ui/virt-viewer.ui
+++ b/src/resources/ui/virt-viewer.ui
@@ -18,7 +18,7 @@
<property name="can_focus">False</property>
<child>
<object class="GtkMenuBar" id="top-menu">
- <property name="visible">True</property>
+ <property name="visible">False</property>
<property name="can_focus">False</property>
<child>
<object class="GtkMenuItem" id="menu-file">
--
2.23.1

View File

@ -0,0 +1,27 @@
From eac430d01f486e15b55d6fa992e77ded77bb4b1a Mon Sep 17 00:00:00 2001
From: Mikhail Klementev <blame@dumpstack.io>
Date: Wed, 22 Jan 2020 00:41:34 +0000
Subject: [PATCH 2/4] Do not grab keyboard/mouse
---
src/virt-viewer-display-spice.c | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/virt-viewer-display-spice.c b/src/virt-viewer-display-spice.c
index 311178b..8e68de2 100644
--- a/src/virt-viewer-display-spice.c
+++ b/src/virt-viewer-display-spice.c
@@ -307,8 +307,8 @@ virt_viewer_display_spice_new(VirtViewerSessionSpice *session,
gtk_container_add(GTK_CONTAINER(self), GTK_WIDGET(self->priv->display));
gtk_widget_show(GTK_WIDGET(self->priv->display));
g_object_set(self->priv->display,
- "grab-keyboard", TRUE,
- "grab-mouse", TRUE,
+ "grab-keyboard", FALSE,
+ "grab-mouse", FALSE,
"resize-guest", FALSE,
"scaling", TRUE,
NULL);
--
2.23.1

View File

@ -0,0 +1,26 @@
From c5b51c0a540af34499f2b2a49cb64599c06ba293 Mon Sep 17 00:00:00 2001
From: Mikhail Klementev <blame@dumpstack.io>
Date: Wed, 22 Jan 2020 01:24:57 +0000
Subject: [PATCH 3/4] Use name of appvm applications as a title
---
src/virt-viewer-window.c | 3 +++
1 file changed, 3 insertions(+)
diff --git a/src/virt-viewer-window.c b/src/virt-viewer-window.c
index 4c08423..cc8a440 100644
--- a/src/virt-viewer-window.c
+++ b/src/virt-viewer-window.c
@@ -1362,6 +1362,9 @@ virt_viewer_window_update_title(VirtViewerWindow *self)
if (!ungrab && !priv->subtitle)
title = g_strdup(g_get_application_name());
+ else if (g_str_has_prefix(priv->subtitle, "appvm_"))
+ /* Use name of the application as a title */
+ title = g_strdup_printf(_("%s"), &priv->subtitle[strlen("appvm_")]);
else
/* translators:
* This is "<ungrab (or empty)><space (or empty)><subtitle (or empty)> - <appname>"
--
2.23.1

View File

@ -0,0 +1,44 @@
From 8e95408365b57c64a738381d132ecdc844013afb Mon Sep 17 00:00:00 2001
From: Mikhail Klementev <blame@dumpstack.io>
Date: Wed, 22 Jan 2020 02:27:26 +0000
Subject: [PATCH 4/4] Use title (application name) as subtitle
---
src/virt-viewer-app.c | 21 ++-------------------
1 file changed, 2 insertions(+), 19 deletions(-)
diff --git a/src/virt-viewer-app.c b/src/virt-viewer-app.c
index 343b1af..8267f82 100644
--- a/src/virt-viewer-app.c
+++ b/src/virt-viewer-app.c
@@ -718,25 +718,8 @@ virt_viewer_app_set_window_subtitle(VirtViewerApp *app,
gchar *subtitle = NULL;
const gchar *title = virt_viewer_app_get_title(app);
- if (title != NULL) {
- VirtViewerDisplay *display = virt_viewer_window_get_display(window);
- gchar *d = strstr(title, "%d");
- gchar *desc = NULL;
-
- if (display && VIRT_VIEWER_IS_DISPLAY_VTE(display)) {
- g_object_get(display, "name", &desc, NULL);
- } else {
- desc = g_strdup_printf("%d", nth + 1);
- }
-
- if (d != NULL) {
- *d = '\0';
- subtitle = g_strdup_printf("%s%s%s", title, desc, d + 2);
- *d = '%';
- } else
- subtitle = g_strdup_printf("%s (%s)", title, desc);
- g_free(desc);
- }
+ if (title != NULL)
+ subtitle = g_strdup_printf("%s", title);
g_object_set(window, "subtitle", subtitle, NULL);
g_free(subtitle);
--
2.23.1

Binary file not shown.

Before

Width:  |  Height:  |  Size: 509 KiB

88
xml.go
View File

@ -5,29 +5,65 @@ import "fmt"
// You may think that you want to rewrite to proper golang structures.
// Believe me, you shouldn't.
func generateXML(name string, online bool, vmNixPath, reginfo, img, sharedDir string) string {
qemuParams := `
<qemu:commandline>
<qemu:arg value='-device'/>
<qemu:arg value='e1000,netdev=net0'/>
<qemu:arg value='-netdev'/>
<qemu:arg value='user,id=net0'/>
<qemu:arg value='-snapshot'/>
</qemu:commandline>
`
func generateXML(vmName string, network networkModel, gui bool,
vmNixPath, reginfo, img, sharedDir string) string {
if !online {
qemuParams = `
<qemu:commandline>
<qemu:arg value='-snapshot'/>
</qemu:commandline>
`
devices := ""
if gui {
devices = guiDevices
}
return fmt.Sprintf(xmlTmpl, "appvm_"+name, vmNixPath, vmNixPath, vmNixPath,
reginfo, img, sharedDir, sharedDir, sharedDir, qemuParams)
qemuParams := qemuParamsDefault
if network == networkQemu {
qemuParams = qemuParamsWithNetwork
} else if network == networkLibvirt {
devices += netDevices
}
return fmt.Sprintf(xmlTmpl, vmName, vmNixPath, vmNixPath, vmNixPath,
reginfo, img, sharedDir, sharedDir, sharedDir, devices, qemuParams)
}
var qemuParamsDefault = `
<qemu:commandline>
<qemu:arg value='-snapshot'/>
</qemu:commandline>
`
var qemuParamsWithNetwork = `
<qemu:commandline>
<qemu:arg value='-device'/>
<qemu:arg value='e1000,netdev=net0'/>
<qemu:arg value='-netdev'/>
<qemu:arg value='user,id=net0'/>
<qemu:arg value='-snapshot'/>
</qemu:commandline>
`
var netDevices = `
<interface type='network'>
<source network='default'/>
</interface>
`
var guiDevices = `
<!-- Graphical console -->
<graphics type='spice' autoport='yes'>
<listen type='address'/>
<image compression='off'/>
</graphics>
<!-- Guest additionals support -->
<channel type='spicevmc'>
<target type='virtio' name='com.redhat.spice.0'/>
</channel>
<video>
<model type='qxl' ram='524288' vram='524288' vgamem='262144' heads='1' primary='yes'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/>
</video>
`
var xmlTmpl = `
<domain type='kvm' xmlns:qemu='http://libvirt.org/schemas/domain/qemu/1.0'>
<name>%s</name>
@ -35,7 +71,7 @@ var xmlTmpl = `
<currentMemory unit='GiB'>1</currentMemory>
<vcpu>4</vcpu>
<os>
<type arch='x86_64' machine='pc-i440fx-2.12'>hvm</type>
<type arch='x86_64'>hvm</type>
<kernel>%s/kernel</kernel>
<initrd>%s/initrd</initrd>
<cmdline>loglevel=4 init=%s/init %s</cmdline>
@ -48,25 +84,12 @@ var xmlTmpl = `
<on_reboot>restart</on_reboot>
<on_crash>destroy</on_crash>
<devices>
<!-- Graphical console -->
<graphics type='spice' autoport='yes'>
<listen type='address'/>
<image compression='off'/>
</graphics>
<!-- Guest additionals support -->
<channel type='spicevmc'>
<target type='virtio' name='com.redhat.spice.0'/>
</channel>
<!-- Fake (because -snapshot) writeback image -->
<disk type='file' device='disk'>
<driver name='qemu' type='qcow2' cache='writeback' error_policy='report'/>
<source file='%s'/>
<target dev='vda' bus='virtio'/>
</disk>
<video>
<model type='qxl' ram='524288' vram='524288' vgamem='262144' heads='1' primary='yes'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/>
</video>
<!-- filesystems -->
<filesystem type='mount' accessmode='passthrough'>
<source dir='/nix/store'/>
@ -85,6 +108,7 @@ var xmlTmpl = `
<source dir='%s'/>
<target dir='home'/>
</filesystem>
%s
</devices>
%s
</domain>