-
Notifications
You must be signed in to change notification settings - Fork 0
/
machine.go
494 lines (401 loc) · 9.72 KB
/
machine.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
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
package sdk
import (
"context"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"os/exec"
"strconv"
"sync"
"time"
"github.com/jumppad-labs/cloudhypervisor-go-sdk/api"
)
// TODO: set up networking
// TODO: handle signals
// TODO: set up vm/vmm logging -> stderr/stdout?
// TODO: set up vm/vmm metrics -> get metrics from process?
// TODO: create overlayfs disk
/*
# set the kernel boot args to use overlay-init
"boot_args": "console=ttyS0 reboot=k panic=1 pci=off overlay_root=vdb init=/sbin/overlay-init"
- overlay_root: the disk that is the overlay root
- init: override the default init program to set up the overlay filesystem
# create read only filesystem
sudo mkdir -p $MOUNTDIR/overlay/root $MOUNTDIR/overlay/work $MOUNTDIR/mnt $MOUNTDIR/rom
sudo cp files/overlay-init $MOUNTDIR/sbin/overlay-init
sudo mksquashfs $MOUNTDIR $SQUASHFS -noappend
https://github.com/cloud-hypervisor/cloud-hypervisor/blob/main/docs/custom-image.md
*/
type Option func(*MachineImpl) error
const (
defaultSocket = "/tmp/cloud-hypervisor.sock"
defaultURL = "http://localhost/api/v1/"
virtiofsSocket = "/tmp/virtiofs.sock"
)
type Machine interface {
PID() (int, error)
Start(ctx context.Context) error
Pause(ctx context.Context) error
Resume(ctx context.Context) error
Snapshot(ctx context.Context, destination string) error
Restore(ctx context.Context, source string) error
Reboot(ctx context.Context) error
PowerButton(ctx context.Context) error
Shutdown(ctx context.Context) error
Wait(ctx context.Context) error
Info(ctx context.Context) (*api.VmInfo, error)
}
type MachineImpl struct {
context context.Context
client *api.Client
cmd *exec.Cmd
config api.VmConfig
startOnce sync.Once
exitCh chan struct{}
fatalErr error
logger *log.Logger
}
func newVMMCommand(socket string, logger *log.Logger) (*exec.Cmd, error) {
path, err := exec.LookPath("cloud-hypervisor")
if err != nil {
return nil, err
}
args := []string{
"--api-socket", socket,
}
// if logger.GetLevel() == log.InfoLevel {
args = append(args, "-v")
// } else if logger.GetLevel() == log.DebugLevel {
// args = append(args, "-vv")
// }
cmd := exec.Command(path, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
return cmd, nil
}
func newClient() (*api.Client, error) {
unixClient := &http.Client{
Transport: &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", defaultSocket)
},
},
}
client, err := api.NewClient(defaultURL, api.WithHTTPClient(unixClient))
if err != nil {
return nil, err
}
return client, nil
}
func NewMachine(ctx context.Context, config api.VmConfig, logger *log.Logger) (Machine, error) {
cmd, err := newVMMCommand(defaultSocket, logger)
if err != nil {
return nil, err
}
client, err := newClient()
if err != nil {
return nil, err
}
// TODO: validate config
// err = config.Validate()
// TODO: convert config to vm config
return &MachineImpl{
context: ctx,
client: client,
cmd: cmd,
config: config,
exitCh: make(chan struct{}),
logger: logger,
}, nil
}
func (m *MachineImpl) PID() (int, error) {
if m.cmd == nil || m.cmd.Process == nil {
return 0, fmt.Errorf("machine is not running")
}
select {
case <-m.exitCh:
return 0, fmt.Errorf("machine process has exited")
default:
}
return m.cmd.Process.Pid, nil
}
func (m *MachineImpl) Start(ctx context.Context) error {
alreadyStarted := true
m.startOnce.Do(func() {
m.logger.Println("marking machine as started")
alreadyStarted = false
})
if alreadyStarted {
return fmt.Errorf("machine already started")
}
// start vmm
err := m.startVMM()
if err != nil {
return err
}
errCh := make(chan error)
go func() {
waitErr := m.cmd.Wait()
if waitErr != nil {
errCh <- waitErr
}
close(errCh)
}()
// m.StartVirtioFS()
// wait for vmm to start
err = m.waitForSocket(10*time.Second, errCh)
if err != nil {
m.logger.Println(err)
m.fatalErr = err
close(m.exitCh)
return err
}
m.logger.Println("vmm is ready")
err = m.createVM()
if err != nil {
m.logger.Println(err)
m.fatalErr = err
close(m.exitCh)
return err
}
err = m.bootVM()
if err != nil {
m.logger.Println(err)
m.fatalErr = err
close(m.exitCh)
return err
}
return nil
}
func (m *MachineImpl) startVMM() error {
err := m.cmd.Start()
if err != nil {
return err
}
return nil
}
func (m *MachineImpl) waitForSocket(timeout time.Duration, exitCh chan error) error {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
ticker := time.NewTicker(10 * time.Millisecond)
defer func() {
cancel()
ticker.Stop()
}()
for {
select {
case <-ctx.Done():
return ctx.Err()
case err := <-exitCh:
return err
case <-ticker.C:
if _, err := os.Stat(defaultSocket); err != nil {
continue
}
if err := m.ping(); err != nil {
continue
}
return nil
}
}
}
func (m *MachineImpl) createVM() error {
resp, err := m.client.CreateVM(m.context, m.config)
if err != nil {
return err
}
if resp.StatusCode != http.StatusNoContent {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("could not create vm: %s", string(body))
}
return nil
}
func (m *MachineImpl) bootVM() error {
resp, err := m.client.BootVM(m.context)
if err != nil {
return err
}
// TODO: check for 204, 404
if resp.StatusCode != http.StatusNoContent {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("could not boot vm: %s", string(body))
}
return nil
}
func (m *MachineImpl) Pause(ctx context.Context) error {
_, err := m.client.PauseVM(m.context)
if err != nil {
return err
}
// TODO: check for 204, 404, 405
return nil
}
func (m *MachineImpl) Resume(ctx context.Context) error {
_, err := m.client.ResumeVM(m.context)
if err != nil {
return err
}
// TODO: check for 204, 404, 405
return nil
}
func (m *MachineImpl) Snapshot(ctx context.Context, destination string) error {
config := api.VmSnapshotConfig{}
_, err := m.client.PutVmSnapshot(m.context, config)
if err != nil {
return err
}
return nil
}
func (m *MachineImpl) Restore(ctx context.Context, source string) error {
config := api.RestoreConfig{}
_, err := m.client.PutVmRestore(m.context, config)
if err != nil {
return err
}
return nil
}
func (m *MachineImpl) Reboot(ctx context.Context) error {
_, err := m.client.RebootVM(m.context)
if err != nil {
return err
}
// TODO: check for 204, 404, 405
return nil
}
func (m *MachineImpl) PowerButton(ctx context.Context) error {
_, err := m.client.PowerButtonVM(m.context)
if err != nil {
return err
}
// TODO: check for 204, 404, 405
return nil
}
func (m *MachineImpl) Shutdown(ctx context.Context) error {
resp, err := m.client.ShutdownVM(m.context)
if err != nil {
return err
}
// TODO: check for 204, 404, 405
if resp.StatusCode != http.StatusNoContent {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("could not shutdown vm: %s", string(body))
}
resp, err = m.client.ShutdownVMM(m.context)
if err != nil {
return err
}
if resp.StatusCode != http.StatusNoContent {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("could not shutdown vmm: %s", string(body))
}
return nil
}
func (m *MachineImpl) Delete() error {
resp, err := m.client.DeleteVM(m.context)
if err != nil {
return err
}
if resp.StatusCode != http.StatusNoContent {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("could not delete vm: %s", string(body))
}
return nil
}
func (m *MachineImpl) ping() error {
resp, err := m.client.GetVmmPing(m.context)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("could not ping vmm: %s", string(body))
}
_, err = api.ParseGetVmmPingResponse(resp)
if err != nil {
return err
}
return nil
}
func (m *MachineImpl) Wait(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-m.exitCh:
return m.fatalErr
}
}
func (m *MachineImpl) Version(ctx context.Context) (string, error) {
resp, err := m.client.GetVmmPing(ctx)
if err != nil {
return "", err
}
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return "", fmt.Errorf("could not get vmm info: %s", string(body))
}
info, err := api.ParseGetVmmPingResponse(resp)
if err != nil {
return "", err
}
return info.JSON200.Version, nil
}
func (m *MachineImpl) Info(ctx context.Context) (*api.VmInfo, error) {
resp, err := m.client.GetVmInfo(ctx)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("could not get vm info: %s", string(body))
}
info, err := api.ParseGetVmInfoResponse(resp)
if err != nil {
return nil, err
}
return info.JSON200, nil
}
func newVirtioFSCommand(socket string, directories []string, threads int) (*exec.Cmd, error) {
path, err := exec.LookPath("virtiofsd")
if err != nil {
return nil, err
}
args := []string{
"--socket-path", socket,
"--log-level", "debug",
"--cache", "never",
"--thread-pool-size", strconv.Itoa(threads),
}
for _, dir := range directories {
args = append(args, "--shared-dir", dir)
}
cmd := exec.Command(path, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
return cmd, nil
}
func (m *MachineImpl) StartVirtioFS() {
directories := []string{"/var/lib/docker/overlay2"}
for _, dir := range *m.config.Fs {
directories = append(directories, dir.Socket)
}
virtioCh := make(chan error)
go func() {
virtioCmd, err := newVirtioFSCommand(virtiofsSocket, directories, 4)
if err != nil {
m.logger.Println(err)
m.fatalErr = err
close(m.exitCh)
}
err = virtioCmd.Start()
if err != nil {
m.logger.Println(err)
m.fatalErr = err
close(m.exitCh)
}
virtioCh <- virtioCmd.Wait()
}()
}