This repository has been archived by the owner on Feb 27, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
run.go
204 lines (176 loc) · 5.77 KB
/
run.go
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
package qemurun
import (
"fmt"
"io"
"net/http"
"os"
"os/signal"
"path/filepath"
"strconv"
"syscall"
"time"
graceful "gopkg.in/tylerb/graceful.v1"
"github.com/taskcluster/slugid-go/slugid"
"github.com/taskcluster/taskcluster-worker/engines/qemu/image"
"github.com/taskcluster/taskcluster-worker/engines/qemu/metaservice"
"github.com/taskcluster/taskcluster-worker/engines/qemu/network"
"github.com/taskcluster/taskcluster-worker/engines/qemu/vm"
"github.com/taskcluster/taskcluster-worker/plugins/interactive"
"github.com/taskcluster/taskcluster-worker/runtime"
"github.com/taskcluster/taskcluster-worker/runtime/atomics"
"github.com/taskcluster/taskcluster-worker/runtime/gc"
"github.com/taskcluster/taskcluster-worker/runtime/monitoring"
"github.com/taskcluster/taskcluster-worker/runtime/util"
)
var debug = util.Debug("qemurun")
type cmd struct{}
func (cmd) Summary() string {
return "Run a QEMU image for debugging"
}
func (cmd) Usage() string {
return `
taskcluster-worker qemu-run will run a given command inside an image to test it,
and give you an VNC viewer to get you into the virtual machine.
usage: taskcluster-worker qemu-run [options] <image> -- <command>...
options:
--vnc <port> Expose VNC on given port.
--meta <port> Expose metadata service on port [default: 8080].
--keep-alive Keep the VM running until signal is received.
--log-level <level> Log level debug, info, warning, error [default: warning].
-h --help Show this screen.
`
}
func (cmd) Execute(arguments map[string]interface{}) bool {
// Read arguments
imageFile := arguments["<image>"].(string)
command := arguments["<command>"].([]string)
keepAlive := arguments["--keep-alive"].(bool)
logLevel := arguments["--log-level"].(string)
var vncPort int64
var err error
if vnc, ok := arguments["--vnc"].(string); ok {
vncPort, err = strconv.ParseInt(vnc, 10, 32)
if err != nil {
panic(fmt.Sprint("Couldn't parse --vnc, error: ", err))
}
}
metaPort, err := strconv.ParseInt(arguments["--meta"].(string), 10, 32)
if err != nil {
panic(fmt.Sprint("Couldn't parse --meta, error: ", err))
}
// Create temporary storage and environment
storage, err := runtime.NewTemporaryStorage(os.TempDir())
if err != nil {
panic("Failed to create TemporaryStorage")
}
environment := &runtime.Environment{
TemporaryStorage: storage,
}
monitor := monitoring.NewLoggingMonitor(logLevel, nil, "").WithTag("component", "qemu-run")
// Create a temporary folder
tempFolder := filepath.Join("/tmp", slugid.Nice())
if err = os.Mkdir(tempFolder, 0777); err != nil {
monitor.Panic("Failed to create temporary folder in /tmp, error: ", err)
}
// Create the necessary runtime setup
gc := &gc.GarbageCollector{}
// Create image manager
monitor.Info("Creating image manager")
manager, err := image.NewManager(filepath.Join(tempFolder, "/images/"), gc, monitor.WithTag("component", "image-manager"))
if err != nil {
monitor.Panic("Failed to create image manager", err)
}
// Get an instance of the image
monitor.Info("Creating instance of image")
image, err := manager.Instance("image", func(target *os.File) error {
f, ferr := os.Open(imageFile)
if ferr != nil {
return ferr
}
defer f.Close()
_, ferr = io.Copy(target, f)
return ferr
})
if err != nil {
monitor.Panic("Failed to create instance of image, error: ", err)
}
// Setup a user-space network
monitor.Info("Creating user-space network")
net, err := network.NewUserNetwork(tempFolder)
if err != nil {
monitor.Panic("Failed to create user-space network, error: ", err)
}
// Create virtual machine
monitor.Info("Creating virtual machine")
vm, err := vm.NewVirtualMachine(
image.Machine().DeriveLimits(), image, net, tempFolder,
"", "", vm.LinuxBootOptions{},
monitor.WithTag("component", "vm"),
)
if err != nil {
monitor.Panic("Failed to create virtual-machine, error: ", err)
}
// Create meta-data service
monitor.Info("Creating meta-data service")
var shellServer *interactive.ShellServer
var displayServer *interactive.DisplayServer
retval := atomics.NewBool(false)
ms := metaservice.New(command, make(map[string]string), os.Stdout, func(result bool) {
monitor.Info("Task Completed, result = ", result)
if !keepAlive {
retval.Set(result)
shellServer.WaitAndClose()
displayServer.Abort()
vm.Kill()
}
}, environment)
// Setup http handler for network
vm.SetHTTPHandler(ms)
// Create ShellServer
shellServer = interactive.NewShellServer(
ms.ExecShell, monitor.WithTag("component", "shell-server"),
)
// Create displayServer
displayServer = interactive.NewDisplayServer(
&socketDisplayProvider{socket: vm.VNCSocket()},
monitor.WithTag("component", "display-server"),
)
interactiveHandler := http.NewServeMux()
interactiveHandler.Handle("/shell/", shellServer)
interactiveHandler.Handle("/display/", displayServer)
interactiveServer := graceful.Server{
Timeout: 30 * time.Second,
Server: &http.Server{
Addr: fmt.Sprintf(":%d", metaPort),
Handler: interactiveHandler,
},
NoSignalHandling: true,
}
go interactiveServer.ListenAndServe()
// Start the virtual machine
monitor.Info("Start the virtual machine")
vm.Start()
// Start vncviewer
done := make(chan struct{})
if vncPort != 0 {
go ExposeVNC(vm.VNCSocket(), int(vncPort), done)
}
// Wait for SIGINT/SIGKILL or vm.Done
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM) // This pattern leaks, acceptable here
select {
case <-c:
signal.Stop(c)
monitor.Info("Terminating QEMU")
vm.Kill()
case <-vm.Done:
monitor.Info("QEMU terminated")
}
close(done)
// Ensure that QEMU has terminated before we continue
<-vm.Done
interactiveServer.Stop(100 * time.Millisecond)
// Clean up anything left in the garbage collector
gc.CollectAll()
return retval.Get()
}