-
-
Notifications
You must be signed in to change notification settings - Fork 606
Expand file tree
/
Copy pathapp.go
More file actions
634 lines (529 loc) · 15.3 KB
/
Copy pathapp.go
File metadata and controls
634 lines (529 loc) · 15.3 KB
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
package app
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/abiosoft/colima/config"
"github.com/abiosoft/colima/config/configmanager"
"github.com/abiosoft/colima/environment"
"github.com/abiosoft/colima/environment/container/apple"
"github.com/abiosoft/colima/environment/container/containerd"
"github.com/abiosoft/colima/environment/container/docker"
"github.com/abiosoft/colima/environment/container/kubernetes"
"github.com/abiosoft/colima/environment/host"
"github.com/abiosoft/colima/environment/vm/lima"
"github.com/abiosoft/colima/environment/vm/lima/limautil"
"github.com/abiosoft/colima/util"
"github.com/docker/go-units"
log "github.com/sirupsen/logrus"
)
type App interface {
Active() bool
Start(config.Config) error
Stop(force bool) error
Delete() error
SSH(args ...string) error
Status(extended bool, json bool) error
Version() error
Runtime() (string, error)
Update() error
Kubernetes() (environment.Container, error)
}
var _ App = (*colimaApp)(nil)
// New creates a new app.
func New() (App, error) {
guest := lima.New(host.New())
if err := host.IsInstalled(guest); err != nil {
return nil, fmt.Errorf("dependency check failed for VM: %w", err)
}
return &colimaApp{
guest: guest,
}, nil
}
type colimaApp struct {
guest environment.VM
}
func (c colimaApp) startWithRuntime(conf config.Config) ([]environment.Container, error) {
kubernetesEnabled := conf.Kubernetes.Enabled
// Kubernetes can only be enabled for docker, containerd, and apple
switch conf.Runtime {
case docker.Name, containerd.Name, apple.Name:
default:
kubernetesEnabled = false
}
var containers []environment.Container
{
runtime := conf.Runtime
if kubernetesEnabled {
runtime += "+k3s"
}
log.Println("runtime:", runtime)
}
// runtime
{
env, err := c.containerEnvironment(conf.Runtime)
if err != nil {
return nil, err
}
containers = append(containers, env)
}
// kubernetes should come after required runtime
if kubernetesEnabled {
env, err := c.containerEnvironment(kubernetes.Name)
if err != nil {
return nil, err
}
containers = append(containers, env)
}
return containers, nil
}
func (c colimaApp) Start(conf config.Config) error {
ctx := context.WithValue(context.Background(), config.CtxKey(), conf)
log.Println("starting", config.CurrentProfile().DisplayName)
var containers []environment.Container
if !environment.IsNoneRuntime(conf.Runtime) {
cs, err := c.startWithRuntime(conf)
if err != nil {
return err
}
containers = cs
}
// the order for start is:
// vm start -> container runtime provision -> container runtime start
// start vm
if err := c.guest.Start(ctx, conf); err != nil {
return fmt.Errorf("error starting vm: %w", err)
}
// provision and start container runtimes
for _, cont := range containers {
log := log.WithField("context", cont.Name())
log.Println("provisioning ...")
if err := cont.Provision(ctx); err != nil {
return fmt.Errorf("error provisioning %s: %w", cont.Name(), err)
}
log.Println("starting ...")
if err := cont.Start(ctx); err != nil {
return fmt.Errorf("error starting %s: %w", cont.Name(), err)
}
}
// persist the current runtime
if err := c.setRuntime(conf.Runtime); err != nil {
log.Error(fmt.Errorf("error persisting runtime settings: %w", err))
}
// persist the kubernetes config
if err := c.setKubernetes(conf.Kubernetes); err != nil {
log.Error(fmt.Errorf("error persisting kubernetes settings: %w", err))
}
log.Println("done")
if err := generateSSHConfig(conf.SSHConfig); err != nil {
log.Trace("error generating ssh_config: %w", err)
}
return nil
}
func (c colimaApp) Stop(force bool) error {
ctx := context.Background()
log.Println("stopping", config.CurrentProfile().DisplayName)
// the order for stop is:
// container stop -> vm stop
// stop container runtimes if not a forceful shutdown
if c.guest.Running(ctx) && !force {
containers, err := c.currentContainerEnvironments(ctx)
if err != nil {
log.Warnln(fmt.Errorf("error retrieving runtimes: %w", err))
}
// stop happens in reverse of start
for i := len(containers) - 1; i >= 0; i-- {
cont := containers[i]
log := log.WithField("context", cont.Name())
log.Println("stopping ...")
if err := cont.Stop(ctx); err != nil {
// failure to stop a container runtime is not fatal
// it is only meant for graceful shutdown.
// the VM will shut down anyways.
log.Warnln(fmt.Errorf("error stopping %s: %w", cont.Name(), err))
}
}
}
// stop vm
// no need to check running status, it may be in a state that requires stopping.
if err := c.guest.Stop(ctx, force); err != nil {
return fmt.Errorf("error stopping vm: %w", err)
}
log.Println("done")
if err := generateSSHConfig(false); err != nil {
log.Trace("error generating ssh_config: %w", err)
}
return nil
}
func (c colimaApp) Delete() error {
ctx := context.Background()
log.Println("deleting", config.CurrentProfile().DisplayName)
// the order for teardown is:
// container teardown -> vm teardown
// vm teardown would've sufficed but container provision
// may have created configurations on the host.
// it is thereby necessary to teardown containers as well.
// teardown container runtimes
if c.guest.Running(ctx) {
containers, err := c.currentContainerEnvironments(ctx)
if err != nil {
log.Warnln(fmt.Errorf("error retrieving runtimes: %w", err))
}
for _, cont := range containers {
log := log.WithField("context", cont.Name())
log.Println("deleting ...")
if err := cont.Teardown(ctx); err != nil {
// failure here is not fatal
log.Warnln(fmt.Errorf("error during teardown of %s: %w", cont.Name(), err))
}
}
}
// teardown vm
if err := c.guest.Teardown(ctx); err != nil {
return fmt.Errorf("error during teardown of vm: %w", err)
}
// delete configs
if err := configmanager.Teardown(); err != nil {
return fmt.Errorf("error deleting configs: %w", err)
}
log.Println("done")
if err := generateSSHConfig(false); err != nil {
log.Trace("error generating ssh_config: %w", err)
}
return nil
}
func (c colimaApp) SSH(args ...string) error {
ctx := context.Background()
if !c.guest.Running(ctx) {
return fmt.Errorf("%s not running", config.CurrentProfile().DisplayName)
}
workDir, err := os.Getwd()
if err != nil {
return fmt.Errorf("error retrieving current working directory: %w", err)
}
// peek the current directory to see if it is mounted to prevent `cd` errors
// with limactl ssh
if err := func() error {
conf, err := configmanager.LoadInstance()
if err != nil {
return err
}
pwd, err := util.CleanPath(workDir)
if err != nil {
return err
}
for _, m := range conf.MountsOrDefault() {
location := m.MountPoint
if location == "" {
location = m.Location
}
location, err := util.CleanPath(location)
if err != nil {
log.Trace(err)
continue
}
if strings.HasPrefix(pwd, location) {
return nil
}
}
return fmt.Errorf("not a mounted directory: %s", workDir)
}(); err != nil {
// the errors returned here is not critical and thereby silenced.
// the goal is to prevent unnecessary warning message from Lima.
log.Trace(fmt.Errorf("error checking if PWD is mounted: %w", err))
// fallback to the user's homedir
username, err := c.guest.User()
if err == nil {
workDir = "/home/" + username + ".linux"
}
}
guest := lima.New(host.New())
return guest.SSH(workDir, args...)
}
type statusInfo struct {
DisplayName string `json:"display_name"`
Driver string `json:"driver"`
Arch string `json:"arch"`
Runtime string `json:"runtime"`
MountType string `json:"mount_type"`
IPAddress string `json:"ip_address"`
DockerSocket string `json:"docker_socket"`
Kubernetes bool `json:"kubernetes"`
CPU int `json:"cpu"`
Memory int64 `json:"memory"`
Disk int64 `json:"disk"`
}
func (c colimaApp) getStatus() (status statusInfo, err error) {
ctx := context.Background()
if !c.guest.Running(ctx) {
return status, fmt.Errorf("%s is not running", config.CurrentProfile().DisplayName)
}
currentRuntime, err := c.currentRuntime(ctx)
if err != nil {
return status, err
}
status.DisplayName = config.CurrentProfile().DisplayName
status.Driver = "QEMU"
conf, _ := configmanager.LoadInstance()
if !conf.Empty() {
status.Driver = conf.DriverLabel()
}
status.Arch = string(c.guest.Arch())
status.Runtime = currentRuntime
status.MountType = conf.MountType
ipAddress := limautil.IPAddress(config.CurrentProfile().ID)
if ipAddress != "127.0.0.1" {
status.IPAddress = ipAddress
}
if currentRuntime == docker.Name {
status.DockerSocket = "unix://" + docker.HostSocketFile()
}
if k, err := c.Kubernetes(); err == nil && k.Running(ctx) {
status.Kubernetes = true
}
if inst, err := limautil.Instance(); err == nil {
status.CPU = inst.CPU
status.Memory = inst.Memory
status.Disk = inst.Disk
}
return status, nil
}
func (c colimaApp) Status(extended bool, jsonOutput bool) error {
status, err := c.getStatus()
if err != nil {
return err
}
if jsonOutput {
if err := json.NewEncoder(os.Stdout).Encode(status); err != nil {
return fmt.Errorf("error encoding status as json: %w", err)
}
} else {
log.Println(config.CurrentProfile().DisplayName, "is running using", status.Driver)
log.Println("arch:", status.Arch)
log.Println("runtime:", status.Runtime)
if status.MountType != "" {
log.Println("mountType:", status.MountType)
}
// ip address
if status.IPAddress != "" {
log.Println("address:", status.IPAddress)
}
// docker socket
if status.DockerSocket != "" {
log.Println("socket:", status.DockerSocket)
}
// kubernetes
if status.Kubernetes {
log.Println("kubernetes: enabled")
}
// additional details
if extended {
if status.CPU > 0 {
log.Println("cpu:", status.CPU)
}
if status.Memory > 0 {
log.Println("mem:", units.BytesSize(float64(status.Memory)))
}
if status.Disk > 0 {
log.Println("disk:", units.BytesSize(float64(status.Disk)))
}
}
}
return nil
}
func (c colimaApp) Version() error {
ctx := context.Background()
if !c.guest.Running(ctx) {
return nil
}
containerRuntimes, err := c.currentContainerEnvironments(ctx)
if err != nil {
return err
}
var kube environment.Container
for _, cont := range containerRuntimes {
if cont.Name() == kubernetes.Name {
kube = cont
continue
}
fmt.Println()
fmt.Println("runtime:", cont.Name())
fmt.Println("arch:", c.guest.Arch())
fmt.Println(cont.Version(ctx))
}
if kube != nil && kube.Version(ctx) != "" {
fmt.Println()
fmt.Println(kubernetes.Name)
fmt.Println(kube.Version(ctx))
}
return nil
}
func (c colimaApp) currentRuntime(ctx context.Context) (string, error) {
if !c.guest.Running(ctx) {
return "", fmt.Errorf("%s is not running", config.CurrentProfile().DisplayName)
}
r := c.guest.Get(environment.ContainerRuntimeKey)
if r == "" {
return "", fmt.Errorf("error retrieving current runtime: empty value")
}
return r, nil
}
func (c colimaApp) setRuntime(runtime string) error {
return c.guest.Set(environment.ContainerRuntimeKey, runtime)
}
func (c colimaApp) setKubernetes(conf config.Kubernetes) error {
b, err := json.Marshal(conf)
if err != nil {
return err
}
return c.guest.Set(kubernetes.ConfigKey, string(b))
}
func (c colimaApp) currentContainerEnvironments(ctx context.Context) ([]environment.Container, error) {
var containers []environment.Container
// runtime
{
runtime, err := c.currentRuntime(ctx)
if err != nil {
return nil, err
}
if environment.IsNoneRuntime(runtime) {
return nil, nil
}
env, err := c.containerEnvironment(runtime)
if err != nil {
return nil, err
}
containers = append(containers, env)
}
// detect and add kubernetes
if k, err := c.containerEnvironment(kubernetes.Name); err == nil && k.Running(ctx) {
containers = append(containers, k)
}
return containers, nil
}
func (c colimaApp) containerEnvironment(runtime string) (environment.Container, error) {
env, err := environment.NewContainer(runtime, c.guest.Host(), c.guest)
if err != nil {
return nil, fmt.Errorf("error initiating container runtime: %w", err)
}
if err := host.IsInstalled(env); err != nil {
return nil, fmt.Errorf("dependency check failed for %s: %w", runtime, err)
}
return env, nil
}
func (c colimaApp) Runtime() (string, error) {
return c.currentRuntime(context.Background())
}
func (c colimaApp) Kubernetes() (environment.Container, error) {
return c.containerEnvironment(kubernetes.Name)
}
func (c colimaApp) Active() bool {
return c.guest.Running(context.Background())
}
func (c *colimaApp) Update() error {
ctx := context.Background()
if !c.guest.Running(ctx) {
return fmt.Errorf("runtime cannot be updated, %s is not running", config.CurrentProfile().DisplayName)
}
runtime, err := c.currentRuntime(ctx)
if err != nil {
return err
}
container, err := c.containerEnvironment(runtime)
if err != nil {
return err
}
oldVersion := container.Version(ctx)
updated, err := container.Update(ctx)
if err != nil {
return err
}
if updated {
fmt.Println()
fmt.Println("Previous")
fmt.Println(oldVersion)
fmt.Println()
fmt.Println("Current")
fmt.Println(container.Version(ctx))
}
return nil
}
func generateSSHConfig(modifySSHConfig bool) error {
instances, err := limautil.Instances()
if err != nil {
return fmt.Errorf("error retrieving instances: %w", err)
}
var buf bytes.Buffer
for _, i := range instances {
if !i.Running() {
continue
}
profile := config.ProfileFromName(i.Name)
resp, err := limautil.ShowSSH(profile.ID)
if err != nil {
log.Trace(fmt.Errorf("error retrieving SSH config for '%s': %w", i.Name, err))
continue
}
fmt.Fprintln(&buf, resp.Output)
}
sshFileColima := config.SSHConfigFile()
if err := os.WriteFile(sshFileColima, buf.Bytes(), 0644); err != nil {
return fmt.Errorf("error writing ssh_config file: %w", err)
}
if !modifySSHConfig {
// ~/.ssh/config modification disabled
return nil
}
includeLine := "Include " + sshFileColima
sshFileSystem := filepath.Join(util.HomeDir(), ".ssh", "config")
// include the SSH config file if not included
// if ssh file missing, the only content will be the include
if _, err := os.Stat(sshFileSystem); err != nil {
if err := os.MkdirAll(filepath.Dir(sshFileSystem), 0700); err != nil {
return fmt.Errorf("error creating ssh directory: %w", err)
}
if err := os.WriteFile(sshFileSystem, []byte(includeLine), 0644); err != nil {
return fmt.Errorf("error modifying %s: %w", sshFileSystem, err)
}
return nil
}
sshContent, err := os.ReadFile(sshFileSystem)
if err != nil {
return fmt.Errorf("error reading ssh config: %w", err)
}
scanner := bufio.NewScanner(bytes.NewReader(sshContent))
for scanner.Scan() {
words := strings.Fields(scanner.Text())
// empty line
if len(words) == 0 {
continue
}
// comment
if strings.HasPrefix(words[0], "#") {
continue
}
// not an include line
if len(words) < 2 {
continue
}
if words[0] == "Include" {
sshConfig := words[1]
sshConfig = strings.Replace(sshConfig, "~/", "$HOME/", 1)
sshConfig = os.ExpandEnv(sshConfig)
if sshConfig == sshFileColima {
// already present
return nil
}
}
}
// not found, prepend file
if err := os.WriteFile(sshFileSystem, []byte(includeLine+"\n\n"+string(sshContent)), 0644); err != nil {
return fmt.Errorf("error modifying %s: %w", sshFileSystem, err)
}
return nil
}