Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
lima-vm
GitHub Repository: lima-vm/lima
Path: blob/master/pkg/autostart/systemd/systemd.go
2609 views
1
// SPDX-FileCopyrightText: Copyright The Lima Authors
2
// SPDX-License-Identifier: Apache-2.0
3
4
package systemd
5
6
import (
7
"context"
8
_ "embed"
9
"fmt"
10
"os"
11
"os/exec"
12
"path/filepath"
13
14
"github.com/sirupsen/logrus"
15
16
"github.com/lima-vm/lima/v2/pkg/limatype"
17
)
18
19
//go:embed [email protected]
20
var Template string
21
22
// GetUnitPath returns the path to the systemd unit file for the given instance name.
23
func GetUnitPath(instName string) string {
24
// Use instance name as argument to systemd service
25
// Instance name available in unit file as %i
26
xdgConfigHome := os.Getenv("XDG_CONFIG_HOME")
27
if xdgConfigHome == "" {
28
xdgConfigHome = filepath.Join(os.Getenv("HOME"), ".config")
29
}
30
return fmt.Sprintf("%s/systemd/user/%s", xdgConfigHome, UnitNameFrom(instName))
31
}
32
33
// UnitNameFrom returns the systemd service name for the given instance name.
34
func UnitNameFrom(instName string) string {
35
return fmt.Sprintf("lima-vm@%s.service", instName)
36
}
37
38
// EnableDisableUnit enables or disables the systemd service for the given instance name.
39
func EnableDisableUnit(ctx context.Context, enable bool, instName string) error {
40
action := "enable"
41
if !enable {
42
action = "disable"
43
}
44
return systemctl(ctx, "--user", action, UnitNameFrom(instName))
45
}
46
47
func systemctl(ctx context.Context, args ...string) error {
48
cmd := exec.CommandContext(ctx, "systemctl", args...)
49
cmd.Stdout = os.Stdout
50
cmd.Stderr = os.Stderr
51
logrus.Debugf("running command: %v", cmd.Args)
52
return cmd.Run()
53
}
54
55
// AutoStartedUnitName returns the systemd service name if the instance is started by systemd.
56
func AutoStartedUnitName() string {
57
return CurrentUnitName()
58
}
59
60
func RequestStart(ctx context.Context, inst *limatype.Instance) error {
61
if err := systemctl(ctx, "--user", "start", UnitNameFrom(inst.Name)); err != nil {
62
return fmt.Errorf("failed to start the instance %q via systemctl: %w", inst.Name, err)
63
}
64
return nil
65
}
66
67
func RequestStop(ctx context.Context, inst *limatype.Instance) (bool, error) {
68
if inst.AutoStartedIdentifier == UnitNameFrom(inst.Name) {
69
logrus.Infof("Stopping the instance %q started by systemd", inst.Name)
70
if err := systemctl(ctx, "--user", "stop", inst.AutoStartedIdentifier); err != nil {
71
return false, fmt.Errorf("failed to stop the instance %q via systemctl: %w", inst.Name, err)
72
}
73
return true, nil
74
}
75
return false, nil
76
}
77
78