-
Notifications
You must be signed in to change notification settings - Fork 618
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added a new public CLI command: `limactl start-at-login INSTANCE
--enabled`. This command facilitates the generation of unit files for `launchd/systemd`, providing users with a straightforward way to control `limactl` autostart behavior. Signed-off-by: roman-kiselenko <[email protected]>
- Loading branch information
1 parent
752afc0
commit 8a32a29
Showing
7 changed files
with
373 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
package main | ||
|
||
import ( | ||
"errors" | ||
"os" | ||
"runtime" | ||
|
||
"github.com/lima-vm/lima/pkg/autostart" | ||
"github.com/lima-vm/lima/pkg/store" | ||
"github.com/sirupsen/logrus" | ||
"github.com/spf13/cobra" | ||
) | ||
|
||
func startAtLoginCommand() *cobra.Command { | ||
resetCommand := &cobra.Command{ | ||
Use: "start-at-login INSTANCE", | ||
Short: "Register/Unregister the unit file for instance", | ||
Args: WrapArgsError(cobra.MaximumNArgs(1)), | ||
RunE: startAtLoginAction, | ||
ValidArgsFunction: startAtLoginComplete, | ||
GroupID: advancedCommand, | ||
} | ||
|
||
resetCommand.Flags().Bool( | ||
"enabled", true, | ||
"--enabled=true/false the "+map[string]string{"darwin": "launchd", "linux": "systemd"}[runtime.GOOS]+" unit file for instance", | ||
) | ||
|
||
return resetCommand | ||
} | ||
|
||
func startAtLoginAction(cmd *cobra.Command, args []string) error { | ||
instName := DefaultInstanceName | ||
if len(args) > 0 { | ||
instName = args[0] | ||
} | ||
|
||
inst, err := store.Inspect(instName) | ||
if err != nil { | ||
if errors.Is(err, os.ErrNotExist) { | ||
logrus.Infof("Instance %q not found", instName) | ||
return nil | ||
} | ||
return err | ||
} | ||
|
||
flags := cmd.Flags() | ||
startAtLogin, err := flags.GetBool("enabled") | ||
if err != nil { | ||
return err | ||
} | ||
if startAtLogin { | ||
if err := autostart.CreateStartAtLoginEntry(runtime.GOOS, inst.Name, inst.Dir); err != nil { | ||
logrus.WithError(err) | ||
} else { | ||
logrus.Infof("The autostart file (%q) has been created", autostart.GetStartAtLoginEntryPath(runtime.GOOS, inst.Name)) | ||
} | ||
} else { | ||
deleted, err := autostart.DeleteStartAtLoginEntry(runtime.GOOS, instName) | ||
if err != nil { | ||
logrus.WithError(err) | ||
} else if deleted { | ||
logrus.Infof("The autostart file (%q) has been deleted", autostart.GetStartAtLoginEntryPath(runtime.GOOS, instName)) | ||
} | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func startAtLoginComplete(cmd *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) { | ||
return bashCompleteInstanceNames(cmd) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,125 @@ | ||
// Package autostart manage start at login unit files for darwin/linux | ||
package autostart | ||
|
||
import ( | ||
_ "embed" | ||
"errors" | ||
"fmt" | ||
"os" | ||
"os/exec" | ||
"path" | ||
"path/filepath" | ||
"strconv" | ||
"strings" | ||
|
||
"github.com/lima-vm/lima/pkg/textutil" | ||
) | ||
|
||
//go:embed [email protected] | ||
var systemdTemplate string | ||
|
||
//go:embed io.lima-vm.autostart.INSTANCE.plist | ||
var launchdTemplate string | ||
|
||
// CreateStartAtLoginEntry respect host OS arch and create unit file | ||
func CreateStartAtLoginEntry(hostOS, instName, workDir string) error { | ||
unitPath := GetStartAtLoginEntryPath(hostOS, instName) | ||
if _, err := os.Stat(unitPath); !errors.Is(err, os.ErrNotExist) { | ||
return err | ||
} | ||
tmpl, err := renderTemplate(hostOS, workDir, instName, os.Executable) | ||
if err != nil { | ||
return err | ||
} | ||
if err := os.MkdirAll(filepath.Dir(unitPath), os.ModePerm); err != nil { | ||
return err | ||
} | ||
if err := os.WriteFile(unitPath, tmpl, 0o644); err != nil { | ||
if !errors.Is(err, os.ErrExist) && !errors.Is(err, os.ErrNotExist) { | ||
return err | ||
} | ||
} | ||
return enableDisableService("enable", hostOS, GetStartAtLoginEntryPath(hostOS, instName)) | ||
} | ||
|
||
// DeleteStartAtLoginEntry respect host OS arch and delete unit file | ||
// return true, nil if unit file has been deleted | ||
func DeleteStartAtLoginEntry(hostOS, instName string) (bool, error) { | ||
unitPath := GetStartAtLoginEntryPath(hostOS, instName) | ||
if _, err := os.Stat(unitPath); err != nil { | ||
// Skip error log if file not present | ||
if errors.Is(err, os.ErrNotExist) { | ||
return false, nil | ||
} | ||
return false, err | ||
} | ||
if err := enableDisableService("disable", hostOS, GetStartAtLoginEntryPath(hostOS, instName)); err != nil { | ||
return false, err | ||
} | ||
if err := os.Remove(unitPath); err != nil { | ||
return false, err | ||
} | ||
return true, nil | ||
} | ||
|
||
// GetFilePath returns the path to autostart file with respect of host | ||
func GetStartAtLoginEntryPath(hostOS, instName string) string { | ||
var fileTmp string | ||
if hostOS == "darwin" { // launchd plist | ||
fileTmp = fmt.Sprintf("%s/Library/LaunchAgents/io.lima-vm.autostart.%s.plist", os.Getenv("HOME"), instName) | ||
} | ||
if hostOS == "linux" { // systemd service | ||
// Use instance name as argument to systemd service | ||
// Instance name available in unit file as %i | ||
xdgConfigHome := os.Getenv("XDG_CONFIG_HOME") | ||
if xdgConfigHome == "" { | ||
xdgConfigHome = filepath.Join(os.Getenv("HOME"), ".config") | ||
} | ||
fileTmp = fmt.Sprintf("%s/systemd/user/lima-vm@%s.service", xdgConfigHome, instName) | ||
} | ||
return fileTmp | ||
} | ||
|
||
func enableDisableService(action, hostOS, serviceWithPath string) error { | ||
// Get filename without extension | ||
filename := strings.TrimSuffix(path.Base(serviceWithPath), filepath.Ext(path.Base(serviceWithPath))) | ||
|
||
var args []string | ||
if hostOS == "darwin" { | ||
// man launchctl | ||
args = append(args, []string{ | ||
"launchctl", | ||
action, | ||
fmt.Sprintf("gui/%s/%s", strconv.Itoa(os.Getuid()), filename), | ||
}...) | ||
} else { | ||
args = append(args, []string{ | ||
"systemctl", | ||
"--user", | ||
action, | ||
filename, | ||
}...) | ||
} | ||
cmd := exec.Command(args[0], args[1:]...) | ||
cmd.Stdout = os.Stdout | ||
cmd.Stderr = os.Stderr | ||
return cmd.Run() | ||
} | ||
|
||
func renderTemplate(hostOS, instName, workDir string, getExecutable func() (string, error)) ([]byte, error) { | ||
selfExeAbs, err := getExecutable() | ||
if err != nil { | ||
return nil, err | ||
} | ||
tmpToExecute := systemdTemplate | ||
if hostOS == "darwin" { | ||
tmpToExecute = launchdTemplate | ||
} | ||
return textutil.ExecuteTemplate( | ||
tmpToExecute, | ||
map[string]string{ | ||
"Binary": selfExeAbs, | ||
"Instance": instName, | ||
"WorkDir": workDir, | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,124 @@ | ||
package autostart | ||
|
||
import ( | ||
"runtime" | ||
"strings" | ||
"testing" | ||
|
||
"gotest.tools/v3/assert" | ||
) | ||
|
||
func TestRenderTemplate(t *testing.T) { | ||
if runtime.GOOS == "windows" { | ||
t.Skip("skipping testing on windows host") | ||
} | ||
tests := []struct { | ||
Name string | ||
InstanceName string | ||
HostOS string | ||
Expected string | ||
WorkDir string | ||
GetExecutable func() (string, error) | ||
}{ | ||
{ | ||
Name: "render darwin launchd plist", | ||
InstanceName: "default", | ||
HostOS: "darwin", | ||
Expected: `<?xml version="1.0" encoding="UTF-8"?> | ||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> | ||
<plist version="1.0"> | ||
<dict> | ||
<key>Label</key> | ||
<string>io.lima-vm.autostart.default</string> | ||
<key>ProgramArguments</key> | ||
<array> | ||
<string>/limactl</string> | ||
<string>start</string> | ||
<string>default</string> | ||
<string>--foreground</string> | ||
</array> | ||
<key>RunAtLoad</key> | ||
<true/> | ||
<key>StandardErrorPath</key> | ||
<string>launchd.stderr.log</string> | ||
<key>StandardOutPath</key> | ||
<string>launchd.stdout.log</string> | ||
<key>WorkingDirectory</key> | ||
<string>/some/path</string> | ||
<key>ProcessType</key> | ||
<string>Background</string> | ||
</dict> | ||
</plist>`, | ||
GetExecutable: func() (string, error) { | ||
return "/limactl", nil | ||
}, | ||
WorkDir: "/some/path", | ||
}, | ||
{ | ||
Name: "render linux systemd service", | ||
InstanceName: "default", | ||
HostOS: "linux", | ||
Expected: `[Unit] | ||
Description=Lima - Linux virtual machines, with a focus on running containers. | ||
Documentation=man:lima(1) | ||
[Service] | ||
ExecStart=/limactl start %i --foreground | ||
WorkingDirectory=%h | ||
Type=simple | ||
TimeoutSec=10 | ||
Restart=on-failure | ||
[Install] | ||
WantedBy=multi-user.target`, | ||
GetExecutable: func() (string, error) { | ||
return "/limactl", nil | ||
}, | ||
WorkDir: "/some/path", | ||
}, | ||
} | ||
for _, tt := range tests { | ||
t.Run(tt.Name, func(t *testing.T) { | ||
tmpl, err := renderTemplate(tt.HostOS, tt.InstanceName, tt.WorkDir, tt.GetExecutable) | ||
assert.NilError(t, err) | ||
assert.Equal(t, string(tmpl), tt.Expected) | ||
}) | ||
} | ||
} | ||
|
||
func TestGetFilePath(t *testing.T) { | ||
if runtime.GOOS == "windows" { | ||
t.Skip("skipping testing on windows host") | ||
} | ||
tests := []struct { | ||
Name string | ||
HostOS string | ||
InstanceName string | ||
HomeEnv string | ||
Expected string | ||
}{ | ||
{ | ||
Name: "darwin with docker instance name", | ||
HostOS: "darwin", | ||
InstanceName: "docker", | ||
Expected: "Library/LaunchAgents/io.lima-vm.autostart.docker.plist", | ||
}, | ||
{ | ||
Name: "linux with docker instance name", | ||
HostOS: "linux", | ||
InstanceName: "docker", | ||
Expected: ".config/systemd/user/[email protected]", | ||
}, | ||
{ | ||
Name: "empty with empty instance name", | ||
HostOS: "", | ||
InstanceName: "", | ||
Expected: "", | ||
}, | ||
} | ||
for _, tt := range tests { | ||
t.Run(tt.Name, func(t *testing.T) { | ||
assert.Check(t, strings.HasSuffix(GetStartAtLoginEntryPath(tt.HostOS, tt.InstanceName), tt.Expected)) | ||
}) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
<?xml version="1.0" encoding="UTF-8"?> | ||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> | ||
<plist version="1.0"> | ||
<dict> | ||
<key>Label</key> | ||
<string>io.lima-vm.autostart.{{ .Instance }}</string> | ||
<key>ProgramArguments</key> | ||
<array> | ||
<string>{{ .Binary }}</string> | ||
<string>start</string> | ||
<string>{{ .Instance }}</string> | ||
<string>--foreground</string> | ||
</array> | ||
<key>RunAtLoad</key> | ||
<true/> | ||
<key>StandardErrorPath</key> | ||
<string>launchd.stderr.log</string> | ||
<key>StandardOutPath</key> | ||
<string>launchd.stdout.log</string> | ||
<key>WorkingDirectory</key> | ||
<string>{{ .WorkDir }}</string> | ||
<key>ProcessType</key> | ||
<string>Background</string> | ||
</dict> | ||
</plist> |
Oops, something went wrong.