| 1 | |
| 2 | |
| 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 | |
| 20 | var Template string |
| 21 | |
| 22 | |
| 23 | func GetUnitPath(instName string) string { |
| 24 | |
| 25 | |
| 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 | |
| 34 | func UnitNameFrom(instName string) string { |
| 35 | return fmt.Sprintf("lima-vm@%s.service", instName) |
| 36 | } |
| 37 | |
| 38 | |
| 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 | |
| 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 | } |