-
-
Notifications
You must be signed in to change notification settings - Fork 606
Expand file tree
/
Copy pathapp.go
More file actions
772 lines (655 loc) · 19.5 KB
/
Copy pathapp.go
File metadata and controls
772 lines (655 loc) · 19.5 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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
package app
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/abiosoft/colima/cli"
"github.com/abiosoft/colima/config"
"github.com/abiosoft/colima/config/configmanager"
"github.com/abiosoft/colima/environment"
"github.com/abiosoft/colima/environment/container/containerd"
"github.com/abiosoft/colima/environment/container/docker"
"github.com/abiosoft/colima/environment/container/incus"
"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/environment/vm/native"
"github.com/abiosoft/colima/store"
"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(data, force bool) 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 using the saved instance's VM type.
func New() (App, error) {
return NewWithVMType("")
}
// NewWithVMType creates a new app with the specified VM type.
// If vmType is empty, it loads from saved instance state or uses the default.
func NewWithVMType(vmType string) (App, error) {
h := host.New()
if vmType == "" {
if conf, err := configmanager.LoadInstance(); err == nil && conf.VMType != "" {
vmType = conf.VMType
} else {
vmType = environment.DefaultVMType()
}
}
var guest environment.VM
if vmType == "native" && util.Linux() {
guest = native.New(h)
} else {
guest = lima.New(h)
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 and containerd
switch conf.Runtime {
case docker.Name, containerd.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)
// print the full path of current profile being used
log.Tracef("starting with config file: %s\n", config.CurrentProfile().File())
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)
}
// run after-boot provision scripts
c.runProvisionScripts(conf, config.ProvisionModeAfterBoot)
// 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)
}
}
// run ready provision scripts
c.runProvisionScripts(conf, config.ProvisionModeReady)
// 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) runProvisionScripts(conf config.Config, mode string) {
var failed bool
for _, s := range conf.Provision {
if s.Mode != mode {
continue
}
if err := c.guest.Run("sh", "-c", s.Script); err != nil {
failed = true
}
}
if failed {
log.Warnln(fmt.Errorf("error running %s provision script(s)", mode))
}
}
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 c.guest.Running(ctx) {
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, force); 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(data, force bool) error {
confirmContainerDestruction := func() bool {
return cli.Prompt("\033[31m\033[1mthis will delete ALL container data. Are you sure you want to continue")
}
s, _ := store.Load()
diskInUse := s.DiskFormatted
if !force {
y := cli.Prompt("are you sure you want to delete " + config.CurrentProfile().DisplayName + " and all settings")
if !y {
return nil
}
// runtime disk not in use or data deletion is requested,
// deletion deletes all data, warn accordingly.
if !diskInUse || data {
if y := confirmContainerDestruction(); !y {
return nil
}
}
}
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)
}
// delete runtime disk if disk in use and data deletion is requested
if diskInUse && data {
conf, _ := configmanager.LoadInstance()
if conf.VMType != "native" {
log.Println("deleting container data")
if err := limautil.DeleteDisk(); err != nil {
return fmt.Errorf("error deleting container data: %w", err)
}
}
if err := store.Reset(); err != nil {
log.Trace("error resetting store: %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))
workDir = ""
}
return c.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,omitempty"`
DockerSocket string `json:"docker_socket,omitempty"`
ContainerdSocket string `json:"containerd_socket,omitempty"`
BuildkitdSocket string `json:"buildkitd_socket,omitempty"`
IncusSocket string `json:"incus_socket,omitempty"`
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
if conf.VMType == "native" {
status.IPAddress = native.HostIPAddress()
cpu, mem, disk := native.HostResources()
status.CPU = cpu
status.Memory = mem
status.Disk = disk
} else {
ipAddress := limautil.IPAddress(config.CurrentProfile().ID)
if ipAddress != "127.0.0.1" {
status.IPAddress = ipAddress
}
if inst, err := limautil.Instance(); err == nil {
status.CPU = inst.CPU
status.Memory = inst.Memory
status.Disk = inst.Disk
}
}
if currentRuntime == docker.Name {
if conf.VMType == "native" {
status.DockerSocket = "unix:///var/run/docker.sock"
} else {
status.DockerSocket = "unix://" + docker.HostSocketFile()
status.ContainerdSocket = "unix://" + containerd.HostSocketFiles().Containerd
}
}
if currentRuntime == containerd.Name {
if conf.VMType == "native" {
status.ContainerdSocket = "unix:///run/containerd/containerd.sock"
} else {
status.ContainerdSocket = "unix://" + containerd.HostSocketFiles().Containerd
status.BuildkitdSocket = "unix://" + containerd.HostSocketFiles().Buildkitd
}
}
if currentRuntime == incus.Name {
if conf.VMType == "native" {
status.IncusSocket = "unix:///var/lib/incus/unix.socket"
} else {
status.IncusSocket = "unix://" + incus.HostSocketFile()
}
}
if k, err := c.Kubernetes(); err == nil && k.Running(ctx) {
status.Kubernetes = true
}
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("docker socket:", status.DockerSocket)
}
if status.ContainerdSocket != "" {
log.Println("containerd socket:", status.ContainerdSocket)
}
if status.BuildkitdSocket != "" {
log.Println("buildkitd socket:", status.BuildkitdSocket)
}
if status.IncusSocket != "" {
log.Println("incus socket:", status.IncusSocket)
}
// 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 == "" {
// Fallback: read runtime from persisted config (needed for native mode
// where the Lima store mechanism is not available)
conf, err := configmanager.LoadInstance()
if err == nil && conf.Runtime != "" {
return conf.Runtime, nil
}
return "", fmt.Errorf("error retrieving current runtime: empty value")
}
return r, nil
}
func (c colimaApp) setRuntime(runtime string) error {
err := store.Set(func(s *store.Store) {
// update runtime if runtime disk is in use
if s.DiskFormatted {
s.DiskRuntime = runtime
}
})
if err != nil {
log.Traceln(fmt.Errorf("error persisting store: %w", err))
}
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 {
// Skip SSH config generation for native mode (no VM to SSH into)
if conf, err := configmanager.LoadInstance(); err == nil && conf.VMType == "native" {
return nil
}
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
}