Fix Lint on Windows and enable the job

[NO NEW TESTS NEEDED] Purely refactoring

Signed-off-by: Matt Heon <mheon@redhat.com>
This commit is contained in:
Matt Heon
2024-02-19 10:46:50 -05:00
parent d5a17ad9a0
commit ec68f07c04
25 changed files with 212 additions and 151 deletions

View File

@ -16,9 +16,12 @@ import (
) )
const ( const (
//nolint:stylecheck
MB_ICONWARNING = 0x00000030 MB_ICONWARNING = 0x00000030
MB_OK = 0x00000000 //nolint:stylecheck
MB_DEFBUTTON1 = 0x00000000 MB_OK = 0x00000000
//nolint:stylecheck
MB_DEFBUTTON1 = 0x00000000
) )
const KernelWarning = "WSL Kernel installation did not complete successfully. " + const KernelWarning = "WSL Kernel installation did not complete successfully. " +
@ -85,7 +88,7 @@ func warn(title string, caption string) int {
func main() { func main() {
args := os.Args args := os.Args
setupLogging(path.Base(args[0])) _, _ = setupLogging(path.Base(args[0]))
if wutil.IsWSLInstalled() { if wutil.IsWSLInstalled() {
// nothing to do // nothing to do
logrus.Info("WSL Kernel already installed") logrus.Info("WSL Kernel already installed")

View File

@ -18,13 +18,19 @@ import (
type operation int type operation int
const ( const (
HWND_BROADCAST = 0xFFFF //nolint:stylecheck
WM_SETTINGCHANGE = 0x001A HWND_BROADCAST = 0xFFFF
SMTO_ABORTIFHUNG = 0x0002 //nolint:stylecheck
ERR_BAD_ARGS = 0x000A WM_SETTINGCHANGE = 0x001A
OPERATION_FAILED = 0x06AC //nolint:stylecheck
Environment = "Environment" SMTO_ABORTIFHUNG = 0x0002
Add operation = iota //nolint:stylecheck
ERR_BAD_ARGS = 0x000A
//nolint:stylecheck
OPERATION_FAILED = 0x06AC
Environment = "Environment"
Add operation = iota
Remove Remove
Open Open
NotSpecified NotSpecified
@ -143,6 +149,8 @@ func removePathFromRegistry(path string) error {
return err return err
} }
// No point preallocating we can't know how big the array needs to be.
//nolint:prealloc
var elements []string var elements []string
for _, element := range strings.Split(existing, ";") { for _, element := range strings.Split(existing, ";") {
if strings.EqualFold(element, path) { if strings.EqualFold(element, path) {
@ -174,6 +182,7 @@ func broadcastEnvironmentChange() {
user32 := syscall.NewLazyDLL("user32") user32 := syscall.NewLazyDLL("user32")
proc := user32.NewProc("SendMessageTimeoutW") proc := user32.NewProc("SendMessageTimeoutW")
millis := 3000 millis := 3000
//nolint:dogsled
_, _, _ = proc.Call(HWND_BROADCAST, WM_SETTINGCHANGE, 0, uintptr(unsafe.Pointer(env)), SMTO_ABORTIFHUNG, uintptr(millis), 0) _, _, _ = proc.Call(HWND_BROADCAST, WM_SETTINGCHANGE, 0, uintptr(unsafe.Pointer(env)), SMTO_ABORTIFHUNG, uintptr(millis), 0)
} }

View File

@ -281,7 +281,8 @@ function _run_altbuild() {
rm -rf $context_dir rm -rf $context_dir
;; ;;
*Windows*) *Windows*)
showrun make lint GOOS=windows || true # TODO: Enable when code passes check showrun make .install.pre-commit
showrun make lint GOOS=windows CGO_ENABLED=0
showrun make podman-remote-release-windows_amd64.zip showrun make podman-remote-release-windows_amd64.zip
;; ;;
*RPM*) *RPM*)

View File

@ -15,7 +15,7 @@ set -e
BUILD_TAGS_DEFAULT="apparmor,seccomp,selinux" BUILD_TAGS_DEFAULT="apparmor,seccomp,selinux"
BUILD_TAGS_ABI="$BUILD_TAGS_DEFAULT,systemd" BUILD_TAGS_ABI="$BUILD_TAGS_DEFAULT,systemd"
BUILD_TAGS_TUNNEL="$BUILD_TAGS_DEFAULT,remote" BUILD_TAGS_TUNNEL="$BUILD_TAGS_DEFAULT,remote"
BUILD_TAGS_REMOTE="remote" BUILD_TAGS_REMOTE="remote,containers_image_openpgp"
SKIP_DIRS_ABI="" SKIP_DIRS_ABI=""
SKIP_DIRS_TUNNEL="pkg/api,pkg/domain/infra/abi" SKIP_DIRS_TUNNEL="pkg/api,pkg/domain/infra/abi"
@ -40,6 +40,6 @@ for to_lint in "${to_lint[@]}"; do
# Make it really easy for a developer to copy-paste the command-line # Make it really easy for a developer to copy-paste the command-line
# to focus or debug a single, specific linting category. # to focus or debug a single, specific linting category.
set -x set -x
./bin/golangci-lint run --build-tags="${!tags_var}" --skip-dirs="${!skip_var}" "$@" ./bin/golangci-lint run --timeout=10m --build-tags="${!tags_var}" --skip-dirs="${!skip_var}" "$@"
) )
done done

View File

@ -61,7 +61,6 @@ func notifyWinChange(ctx context.Context, winChange chan os.Signal, stdin *os.Fi
} }
} }
}() }()
} }
func getTermSize(stdin *os.File, stdout *os.File) (width, height int, err error) { func getTermSize(stdin *os.File, stdout *os.File) (width, height int, err error) {

View File

@ -236,7 +236,9 @@ func isWSL() bool {
return isVmtype(define.WSLVirt) return isVmtype(define.WSLVirt)
} }
//nolint:unused // Only used on Windows
//
//nolint:unparam,unused
func runSystemCommand(binary string, cmdArgs []string, timeout time.Duration, wait bool) (*machineSession, error) { func runSystemCommand(binary string, cmdArgs []string, timeout time.Duration, wait bool) (*machineSession, error) {
GinkgoWriter.Println(binary + " " + strings.Join(cmdArgs, " ")) GinkgoWriter.Println(binary + " " + strings.Join(cmdArgs, " "))
c := exec.Command(binary, cmdArgs...) c := exec.Command(binary, cmdArgs...)

View File

@ -38,12 +38,12 @@ var _ = Describe("podman machine init - windows only", func() {
Expect(session).To(Exit(0)) Expect(session).To(Exit(0))
defer func() { defer func() {
_, err := runSystemCommand(wutil.FindWSL(), []string{"--terminate", "podman-net-usermode"}, defaultTimeout, true) _, err := runSystemCommand(wutil.FindWSL(), []string{"--terminate", "podman-net-usermode"}, defaultTimeout, true)
if err != nil { if err != nil {
fmt.Println("unable to terminate podman-net-usermode") fmt.Println("unable to terminate podman-net-usermode")
} }
_, err = runSystemCommand(wutil.FindWSL(), []string{"--unregister", "podman-net-usermode"}, defaultTimeout, true) _, err = runSystemCommand(wutil.FindWSL(), []string{"--unregister", "podman-net-usermode"}, defaultTimeout, true)
if err != nil { if err != nil {
fmt.Println("unable to unregister podman-net-usermode") fmt.Println("unable to unregister podman-net-usermode")
} }
@ -87,6 +87,7 @@ var _ = Describe("podman machine init - windows only", func() {
}() }()
i := new(initMachine) i := new(initMachine)
session, err := mb.setName(name).setCmd(i.withImagePath(mb.imagePath)).run() session, err := mb.setName(name).setCmd(i.withImagePath(mb.imagePath)).run()
Expect(err).ToNot(HaveOccurred())
Expect(session).To(Exit(125)) Expect(session).To(Exit(125))
Expect(session.errorToString()).To(ContainSubstring("already exists on hypervisor")) Expect(session.errorToString()).To(ContainSubstring("already exists on hypervisor"))
}) })

View File

@ -14,7 +14,7 @@ func DetermineMachineArch() string {
current, _ := syscall.GetCurrentProcess() current, _ := syscall.GetCurrentProcess()
if err := windows.IsWow64Process2(windows.Handle(current), &machine, &native); err != nil { if err := windows.IsWow64Process2(windows.Handle(current), &machine, &native); err != nil {
logrus.Warnf("Failure detecting native system architecture, %s: %w", fallbackMsg, err) logrus.Warnf("Failure detecting native system architecture, %s: %v", fallbackMsg, err)
// Fall-back to binary arch // Fall-back to binary arch
return runtime.GOARCH return runtime.GOARCH
} }
@ -26,7 +26,7 @@ func DetermineMachineArch() string {
case 0x8664: case 0x8664:
return "amd64" return "amd64"
default: default:
logrus.Warnf("Unknown or unsupported native system architecture [%d], %s", fallbackMsg) logrus.Warnf("Unknown or unsupported native system architecture [%d], %s", native, fallbackMsg)
return runtime.GOARCH return runtime.GOARCH
} }
} }

View File

@ -3,38 +3,10 @@ package machine
import ( import (
"fmt" "fmt"
"strconv" "strconv"
"time"
"github.com/containers/podman/v5/pkg/machine/define" "github.com/containers/podman/v5/pkg/machine/define"
psutil "github.com/shirou/gopsutil/v3/process"
) )
const (
loops = 8
sleepTime = time.Millisecond * 1
)
// backoffForProcess checks if the process still exists, for something like
// sigterm. If the process still exists after loops and sleep time are exhausted,
// an error is returned
func backoffForProcess(p *psutil.Process) error {
sleepInterval := sleepTime
for i := 0; i < loops; i++ {
running, err := p.IsRunning()
if err != nil {
return fmt.Errorf("checking if process running: %w", err)
}
if !running {
return nil
}
time.Sleep(sleepInterval)
// double the time
sleepInterval += sleepInterval
}
return fmt.Errorf("process %d has not ended", p.Pid)
}
// CleanupGVProxy reads the --pid-file for gvproxy attempts to stop it // CleanupGVProxy reads the --pid-file for gvproxy attempts to stop it
func CleanupGVProxy(f define.VMFile) error { func CleanupGVProxy(f define.VMFile) error {
gvPid, err := f.Read() gvPid, err := f.Read()

View File

@ -6,11 +6,38 @@ import (
"errors" "errors"
"fmt" "fmt"
"syscall" "syscall"
"time"
psutil "github.com/shirou/gopsutil/v3/process" psutil "github.com/shirou/gopsutil/v3/process"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
const (
loops = 8
sleepTime = time.Millisecond * 1
)
// backoffForProcess checks if the process still exists, for something like
// sigterm. If the process still exists after loops and sleep time are exhausted,
// an error is returned
func backoffForProcess(p *psutil.Process) error {
sleepInterval := sleepTime
for i := 0; i < loops; i++ {
running, err := p.IsRunning()
if err != nil {
return fmt.Errorf("checking if process running: %w", err)
}
if !running {
return nil
}
time.Sleep(sleepInterval)
// double the time
sleepInterval += sleepInterval
}
return fmt.Errorf("process %d has not ended", p.Pid)
}
// / waitOnProcess takes a pid and sends a sigterm to it. it then waits for the // / waitOnProcess takes a pid and sends a sigterm to it. it then waits for the
// process to not exist. if the sigterm does not end the process after an interval, // process to not exist. if the sigterm does not end the process after an interval,
// then sigkill is sent. it also waits for the process to exit after the sigkill too. // then sigkill is sent. it also waits for the process to exit after the sigkill too.

View File

@ -16,6 +16,7 @@ func waitOnProcess(processID int) error {
// FindProcess on Windows will return an error when the process is not found // FindProcess on Windows will return an error when the process is not found
// if a process can not be found then it has already exited and there is // if a process can not be found then it has already exited and there is
// nothing left to do, so return without error // nothing left to do, so return without error
//nolint:nilerr
return nil return nil
} }

View File

@ -381,66 +381,69 @@ func (h HyperVStubber) PostStartNetworking(mc *vmconfigs.MachineConfig, noInfo b
defer callbackFuncs.CleanIfErr(&err) defer callbackFuncs.CleanIfErr(&err)
go callbackFuncs.CleanOnSignal() go callbackFuncs.CleanOnSignal()
if len(mc.Mounts) != 0 { if len(mc.Mounts) == 0 {
var ( return nil
dirs *define.MachineDirs
gvproxyPID int
)
dirs, err = machine.GetMachineDirs(h.VMType())
if err != nil {
return err
}
// GvProxy PID file path is now derived
gvproxyPIDFile, err := dirs.RuntimeDir.AppendToNewVMFile("gvproxy.pid", nil)
if err != nil {
return err
}
gvproxyPID, err = gvproxyPIDFile.ReadPIDFrom()
if err != nil {
return err
}
executable, err = os.Executable()
if err != nil {
return err
}
// Start the 9p server in the background
p9ServerArgs := []string{}
if logrus.IsLevelEnabled(logrus.DebugLevel) {
p9ServerArgs = append(p9ServerArgs, "--log-level=debug")
}
p9ServerArgs = append(p9ServerArgs, "machine", "server9p")
for _, mount := range mc.Mounts {
if mount.VSockNumber == nil {
return fmt.Errorf("mount %s has not vsock port defined", mount.Source)
}
p9ServerArgs = append(p9ServerArgs, "--serve", fmt.Sprintf("%s:%s", mount.Source, winio.VsockServiceID(uint32(*mount.VSockNumber)).String()))
}
p9ServerArgs = append(p9ServerArgs, fmt.Sprintf("%d", gvproxyPID))
logrus.Debugf("Going to start 9p server using command: %s %v", executable, p9ServerArgs)
fsCmd := exec.Command(executable, p9ServerArgs...)
if logrus.IsLevelEnabled(logrus.DebugLevel) {
err = logCommandToFile(fsCmd, "podman-machine-server9.log")
if err != nil {
return err
}
}
err = fsCmd.Start()
if err == nil {
logrus.Infof("Started podman 9p server as PID %d", fsCmd.Process.Pid)
}
// Note: No callback is needed to stop the 9p server, because it will stop when
// gvproxy stops
// Finalize starting shares after we are confident gvproxy is still alive.
err = startShares(mc)
} }
var (
dirs *define.MachineDirs
gvproxyPID int
)
dirs, err = machine.GetMachineDirs(h.VMType())
if err != nil {
return err
}
// GvProxy PID file path is now derived
gvproxyPIDFile, err := dirs.RuntimeDir.AppendToNewVMFile("gvproxy.pid", nil)
if err != nil {
return err
}
gvproxyPID, err = gvproxyPIDFile.ReadPIDFrom()
if err != nil {
return err
}
executable, err = os.Executable()
if err != nil {
return err
}
// Start the 9p server in the background
p9ServerArgs := []string{}
if logrus.IsLevelEnabled(logrus.DebugLevel) {
p9ServerArgs = append(p9ServerArgs, "--log-level=debug")
}
p9ServerArgs = append(p9ServerArgs, "machine", "server9p")
for _, mount := range mc.Mounts {
if mount.VSockNumber == nil {
return fmt.Errorf("mount %s has not vsock port defined", mount.Source)
}
p9ServerArgs = append(p9ServerArgs, "--serve", fmt.Sprintf("%s:%s", mount.Source, winio.VsockServiceID(uint32(*mount.VSockNumber)).String()))
}
p9ServerArgs = append(p9ServerArgs, fmt.Sprintf("%d", gvproxyPID))
logrus.Debugf("Going to start 9p server using command: %s %v", executable, p9ServerArgs)
fsCmd := exec.Command(executable, p9ServerArgs...)
if logrus.IsLevelEnabled(logrus.DebugLevel) {
err = logCommandToFile(fsCmd, "podman-machine-server9.log")
if err != nil {
return err
}
}
err = fsCmd.Start()
if err != nil {
return fmt.Errorf("unable to start 9p server: %v", err)
}
logrus.Infof("Started podman 9p server as PID %d", fsCmd.Process.Pid)
// Note: No callback is needed to stop the 9p server, because it will stop when
// gvproxy stops
// Finalize starting shares after we are confident gvproxy is still alive.
err = startShares(mc)
return err return err
} }

View File

@ -29,7 +29,7 @@ func removeShares(mc *vmconfigs.MachineConfig) error {
if err := vsockReg.Remove(); err != nil { if err := vsockReg.Remove(); err != nil {
if removalErr != nil { if removalErr != nil {
logrus.Errorf("Error removing vsock: %w", removalErr) logrus.Errorf("Error removing vsock: %v", removalErr)
} }
removalErr = fmt.Errorf("removing vsock %d for mountpoint %s: %w", *mount.VSockNumber, mount.Target, err) removalErr = fmt.Errorf("removing vsock %d for mountpoint %s: %w", *mount.VSockNumber, mount.Target, err)
} }
@ -44,7 +44,7 @@ func startShares(mc *vmconfigs.MachineConfig) error {
if logrus.IsLevelEnabled(logrus.DebugLevel) { if logrus.IsLevelEnabled(logrus.DebugLevel) {
args = append(args, "--log-level=debug") args = append(args, "--log-level=debug")
} }
//just being protective here; in a perfect world, this cannot happen // just being protective here; in a perfect world, this cannot happen
if mount.VSockNumber == nil { if mount.VSockNumber == nil {
return errors.New("cannot start 9p shares with undefined vsock number") return errors.New("cannot start 9p shares with undefined vsock number")
} }

View File

@ -24,8 +24,8 @@ const (
HvsockPurpose = "Purpose" HvsockPurpose = "Purpose"
// VsockRegistryPath describes the registry path to where the hvsock registry entries live // VsockRegistryPath describes the registry path to where the hvsock registry entries live
VsockRegistryPath = `SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\GuestCommunicationServices` VsockRegistryPath = `SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\GuestCommunicationServices`
// LinuxVm is the default guid for a Linux VM on Windows // LinuxVM is the default guid for a Linux VM on Windows
LinuxVm = "FACB-11E6-BD58-64006A7986D3" LinuxVM = "FACB-11E6-BD58-64006A7986D3"
) )
// HVSockPurpose describes what the hvsock is needed for // HVSockPurpose describes what the hvsock is needed for
@ -141,7 +141,6 @@ func (hv *HVSockRegistryEntry) validate() error {
if len(hv.KeyName) < 1 { if len(hv.KeyName) < 1 {
return errors.New("required field keypath is empty") return errors.New("required field keypath is empty")
} }
//decimal_num, err = strconv.ParseInt(hexadecimal_num, 16, 64)
return nil return nil
} }
@ -150,7 +149,7 @@ func (hv *HVSockRegistryEntry) exists() (bool, error) {
_ = foo _ = foo
_, err := openVSockRegistryEntry(hv.fqPath()) _, err := openVSockRegistryEntry(hv.fqPath())
if err == nil { if err == nil {
return true, err return true, nil
} }
if errors.Is(err, registry.ErrNotExist) { if errors.Is(err, registry.ErrNotExist) {
return false, nil return false, nil
@ -191,7 +190,7 @@ func findOpenHVSockPort() (uint64, error) {
func NewHVSockRegistryEntry(machineName string, purpose HVSockPurpose) (*HVSockRegistryEntry, error) { func NewHVSockRegistryEntry(machineName string, purpose HVSockPurpose) (*HVSockRegistryEntry, error) {
// a so-called wildcard entry ... everything from FACB -> 6D3 is MS special sauce // a so-called wildcard entry ... everything from FACB -> 6D3 is MS special sauce
// for a " linux vm". this first segment is hexi for the hvsock port number // for a " linux vm". this first segment is hexi for the hvsock port number
//00000400-FACB-11E6-BD58-64006A7986D3 // 00000400-FACB-11E6-BD58-64006A7986D3
port, err := findOpenHVSockPort() port, err := findOpenHVSockPort()
if err != nil { if err != nil {
return nil, err return nil, err
@ -212,7 +211,7 @@ func portToKeyName(port uint64) string {
// this could be flattened but given the complexity, I thought it might // this could be flattened but given the complexity, I thought it might
// be more difficult to read // be more difficult to read
hexi := strings.ToUpper(fmt.Sprintf("%08x", port)) hexi := strings.ToUpper(fmt.Sprintf("%08x", port))
return fmt.Sprintf("%s-%s", hexi, LinuxVm) return fmt.Sprintf("%s-%s", hexi, LinuxVM)
} }
func LoadHVSockRegistryEntry(port uint64) (*HVSockRegistryEntry, error) { func LoadHVSockRegistryEntry(port uint64) (*HVSockRegistryEntry, error) {

View File

@ -23,8 +23,8 @@ import (
const ( const (
NamedPipePrefix = "npipe:////./pipe/" NamedPipePrefix = "npipe:////./pipe/"
GlobalNamedPipe = "docker_engine" GlobalNamedPipe = "docker_engine"
winSShProxy = "win-sshproxy.exe" winSSHProxy = "win-sshproxy.exe"
winSshProxyTid = "win-sshproxy.tid" winSSHProxyTid = "win-sshproxy.tid"
rootfulSock = "/run/podman/podman.sock" rootfulSock = "/run/podman/podman.sock"
rootlessSock = "/run/user/1000/podman/podman.sock" rootlessSock = "/run/user/1000/podman/podman.sock"
@ -33,7 +33,8 @@ const (
GlobalNameWait = 250 * time.Millisecond GlobalNameWait = 250 * time.Millisecond
) )
const WM_QUIT = 0x12 //nolint //nolint:stylecheck
const WM_QUIT = 0x12
type WinProxyOpts struct { type WinProxyOpts struct {
Name string Name string
@ -92,7 +93,7 @@ func WaitPipeExists(pipeName string, retries int, checkFailure func() error) err
} }
func DialNamedPipe(ctx context.Context, path string) (net.Conn, error) { func DialNamedPipe(ctx context.Context, path string) (net.Conn, error) {
path = strings.Replace(path, "/", "\\", -1) path = strings.ReplaceAll(path, "/", "\\")
return winio.DialPipeContext(ctx, path) return winio.DialPipeContext(ctx, path)
} }
@ -131,7 +132,7 @@ func launchWinProxy(opts WinProxyOpts) (bool, string, error) {
globalName = true globalName = true
} }
command, err := FindExecutablePeer(winSShProxy) command, err := FindExecutablePeer(winSSHProxy)
if err != nil { if err != nil {
return globalName, "", err return globalName, "", err
} }
@ -181,6 +182,7 @@ func StopWinProxy(name string, vmtype define.VMType) error {
proc, err := os.FindProcess(int(pid)) proc, err := os.FindProcess(int(pid))
if err != nil { if err != nil {
//nolint:nilerr
return nil return nil
} }
sendQuit(tid) sendQuit(tid)
@ -196,7 +198,7 @@ func readWinProxyTid(name string, vmtype define.VMType) (uint32, uint32, string,
return 0, 0, "", err return 0, 0, "", err
} }
tidFile := filepath.Join(stateDir, winSshProxyTid) tidFile := filepath.Join(stateDir, winSSHProxyTid)
contents, err := os.ReadFile(tidFile) contents, err := os.ReadFile(tidFile)
if err != nil { if err != nil {
return 0, 0, "", err return 0, 0, "", err
@ -210,13 +212,13 @@ func readWinProxyTid(name string, vmtype define.VMType) (uint32, uint32, string,
func waitTimeout(proc *os.Process, timeout time.Duration) bool { func waitTimeout(proc *os.Process, timeout time.Duration) bool {
done := make(chan bool) done := make(chan bool)
go func() { go func() {
proc.Wait() _, _ = proc.Wait()
done <- true done <- true
}() }()
ret := false ret := false
select { select {
case <-time.After(timeout): case <-time.After(timeout):
proc.Kill() _ = proc.Kill()
<-done <-done
case <-done: case <-done:
ret = true ret = true
@ -229,7 +231,8 @@ func waitTimeout(proc *os.Process, timeout time.Duration) bool {
func sendQuit(tid uint32) { func sendQuit(tid uint32) {
user32 := syscall.NewLazyDLL("user32.dll") user32 := syscall.NewLazyDLL("user32.dll")
postMessage := user32.NewProc("PostThreadMessageW") postMessage := user32.NewProc("PostThreadMessageW")
postMessage.Call(uintptr(tid), WM_QUIT, 0, 0) //nolint:dogsled
_, _, _ = postMessage.Call(uintptr(tid), WM_QUIT, 0, 0)
} }
func FindExecutablePeer(name string) (string, error) { func FindExecutablePeer(name string) (string, error) {

View File

@ -2,18 +2,24 @@
package shim package shim
func findClaimHelper() string {
return ""
}
// All of these are unused on Windows but are used on Linux.
// So we're just silencing Windows lint warnings here.
//nolint:unused
func dockerClaimHelperInstalled() bool { func dockerClaimHelperInstalled() bool {
return false return false
} }
//nolint:unused
func claimDockerSock() bool { func claimDockerSock() bool {
return false return false
} }
//nolint:unused
func dockerClaimSupported() bool { func dockerClaimSupported() bool {
return false return false
} }
func findClaimHelper() string {
return ""
}

View File

@ -19,6 +19,7 @@ const registriesConf = `unqualified-search-registries=["docker.io"]
const appendPort = `grep -q Port\ %d /etc/ssh/sshd_config || echo Port %d >> /etc/ssh/sshd_config` const appendPort = `grep -q Port\ %d /etc/ssh/sshd_config || echo Port %d >> /etc/ssh/sshd_config`
//nolint:unused
const changePort = `sed -E -i 's/^Port[[:space:]]+[0-9]+/Port %d/' /etc/ssh/sshd_config` const changePort = `sed -E -i 's/^Port[[:space:]]+[0-9]+/Port %d/' /etc/ssh/sshd_config`
const configServices = `ln -fs /usr/lib/systemd/system/sshd.service /etc/systemd/system/multi-user.target.wants/sshd.service const configServices = `ln -fs /usr/lib/systemd/system/sshd.service /etc/systemd/system/multi-user.target.wants/sshd.service
@ -240,7 +241,7 @@ http://docs.microsoft.com/en-us/windows/wsl/install\
const ( const (
gvProxy = "gvproxy.exe" gvProxy = "gvproxy.exe"
winSShProxy = "win-sshproxy.exe" winSSHProxy = "win-sshproxy.exe"
pipePrefix = "npipe:////./pipe/" pipePrefix = "npipe:////./pipe/"
globalPipe = "docker_engine" globalPipe = "docker_engine"
userModeDist = "podman-net-usermode" userModeDist = "podman-net-usermode"

View File

@ -40,10 +40,12 @@ func (e *ExitCodeError) Error() string {
return fmt.Sprintf("Process failed with exit code: %d", e.code) return fmt.Sprintf("Process failed with exit code: %d", e.code)
} }
//nolint:unused
func getConfigPath(name string) (string, error) { func getConfigPath(name string) (string, error) {
return getConfigPathExt(name, "json") return getConfigPathExt(name, "json")
} }
//nolint:unused
func getConfigPathExt(name string, extension string) (string, error) { func getConfigPathExt(name string, extension string) (string, error) {
vmConfigDir, err := machine.GetConfDir(vmtype) vmConfigDir, err := machine.GetConfDir(vmtype)
if err != nil { if err != nil {
@ -396,7 +398,9 @@ func attemptFeatureInstall(reExec, admin bool) error {
} }
func launchElevate(operation string) error { func launchElevate(operation string) error {
truncateElevatedOutputFile() if err := truncateElevatedOutputFile(); err != nil {
return err
}
err := relaunchElevatedWait() err := relaunchElevatedWait()
if err != nil { if err != nil {
if eerr, ok := err.(*ExitCodeError); ok { if eerr, ok := err.(*ExitCodeError); ok {
@ -565,6 +569,7 @@ func wslPipe(input string, dist string, arg ...string) error {
return pipeCmdPassThrough(wutil.FindWSL(), input, newArgs...) return pipeCmdPassThrough(wutil.FindWSL(), input, newArgs...)
} }
//nolint:unused
func wslCreateKeys(identityPath string, dist string) (string, error) { func wslCreateKeys(identityPath string, dist string) (string, error) {
return machine.CreateSSHKeysPrefix(identityPath, true, true, wutil.FindWSL(), "-u", "root", "-d", dist) return machine.CreateSSHKeysPrefix(identityPath, true, true, wutil.FindWSL(), "-u", "root", "-d", dist)
} }
@ -619,6 +624,7 @@ func setupWslProxyEnv() (hasProxy bool) {
return return
} }
//nolint:unused
func obtainGlobalConfigLock() (*fileLock, error) { func obtainGlobalConfigLock() (*fileLock, error) {
lockDir, err := machine.GetGlobalDataDir() lockDir, err := machine.GetGlobalDataDir()
if err != nil { if err != nil {
@ -734,6 +740,7 @@ func isRunning(name string) (bool, error) {
return sysd, err return sysd, err
} }
//nolint:unused
func getDiskSize(name string) uint64 { func getDiskSize(name string) uint64 {
vmDataDir, err := machine.GetDataDir(vmtype) vmDataDir, err := machine.GetDataDir(vmtype)
if err != nil { if err != nil {
@ -748,6 +755,7 @@ func getDiskSize(name string) uint64 {
return uint64(info.Size()) return uint64(info.Size())
} }
//nolint:unused
func getCPUs(name string) (uint64, error) { func getCPUs(name string) (uint64, error) {
dist := machine.ToDist(name) dist := machine.ToDist(name)
if run, _ := isWSLRunning(dist); !run { if run, _ := isWSLRunning(dist); !run {
@ -772,6 +780,7 @@ func getCPUs(name string) (uint64, error) {
return uint64(ret), err return uint64(ret), err
} }
//nolint:unused
func getMem(name string) (uint64, error) { func getMem(name string) (uint64, error) {
dist := machine.ToDist(name) dist := machine.ToDist(name)
if run, _ := isWSLRunning(dist); !run { if run, _ := isWSLRunning(dist); !run {
@ -808,6 +817,7 @@ func getMem(name string) (uint64, error) {
return total - available, err return total - available, err
} }
//nolint:unused
func getResources(mc *vmconfigs.MachineConfig) (resources vmconfigs.ResourceConfig) { func getResources(mc *vmconfigs.MachineConfig) (resources vmconfigs.ResourceConfig) {
resources.CPUs, _ = getCPUs(mc.Name) resources.CPUs, _ = getCPUs(mc.Name)
resources.Memory, _ = getMem(mc.Name) resources.Memory, _ = getMem(mc.Name)

View File

@ -160,7 +160,7 @@ func (w WSLStubber) SetProviderAttrs(mc *vmconfigs.MachineConfig, opts define.Se
dist := machine.ToDist(mc.Name) dist := machine.ToDist(mc.Name)
if err := changeDistUserModeNetworking(dist, mc.SSH.RemoteUsername, mc.ImagePath.GetPath(), *opts.UserModeNetworking); err != nil { if err := changeDistUserModeNetworking(dist, mc.SSH.RemoteUsername, mc.ImagePath.GetPath(), *opts.UserModeNetworking); err != nil {
return fmt.Errorf("failure changing state of user-mode networking setting", err) return fmt.Errorf("failure changing state of user-mode networking setting: %w", err)
} }
mc.WSLHypervisor.UserModeNetworking = *opts.UserModeNetworking mc.WSLHypervisor.UserModeNetworking = *opts.UserModeNetworking

View File

@ -5,12 +5,12 @@ package wsl
import ( import (
"errors" "errors"
"fmt" "fmt"
"github.com/containers/podman/v5/pkg/machine/vmconfigs"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"github.com/containers/podman/v5/pkg/machine" "github.com/containers/podman/v5/pkg/machine"
"github.com/containers/podman/v5/pkg/machine/vmconfigs"
"github.com/containers/podman/v5/pkg/machine/wsl/wutil" "github.com/containers/podman/v5/pkg/machine/wsl/wutil"
"github.com/containers/podman/v5/pkg/specgen" "github.com/containers/podman/v5/pkg/specgen"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
@ -84,7 +84,9 @@ func startUserModeNetworking(mc *vmconfigs.MachineConfig) error {
if err != nil { if err != nil {
return err return err
} }
defer flock.unlock() defer func() {
_ = flock.unlock()
}()
running, err := isWSLRunning(userModeDist) running, err := isWSLRunning(userModeDist)
if err != nil { if err != nil {
@ -121,7 +123,9 @@ func stopUserModeNetworking(mc *vmconfigs.MachineConfig) error {
if err != nil { if err != nil {
return err return err
} }
defer flock.unlock() defer func() {
_ = flock.unlock()
}()
err = removeUserModeNetEntry(mc.Name) err = removeUserModeNetEntry(mc.Name)
if err != nil { if err != nil {
@ -322,7 +326,7 @@ func obtainUserModeNetLock() (*fileLock, error) {
func changeDistUserModeNetworking(dist string, user string, image string, enable bool) error { func changeDistUserModeNetworking(dist string, user string, image string, enable bool) error {
// Only install if user-mode is being enabled and there was an image path passed // Only install if user-mode is being enabled and there was an image path passed
if enable { if enable {
if len(image) <= 0 { if len(image) == 0 {
return errors.New("existing machine configuration is corrupt, no image is defined") return errors.New("existing machine configuration is corrupt, no image is defined")
} }
if err := installUserModeDist(dist, image); err != nil { if err := installUserModeDist(dist, image); err != nil {

View File

@ -19,7 +19,6 @@ import (
"golang.org/x/sys/windows/registry" "golang.org/x/sys/windows/registry"
) )
// nolint
type SHELLEXECUTEINFO struct { type SHELLEXECUTEINFO struct {
cbSize uint32 cbSize uint32
fMask uint32 fMask uint32
@ -38,7 +37,6 @@ type SHELLEXECUTEINFO struct {
hProcess syscall.Handle hProcess syscall.Handle
} }
// nolint
type Luid struct { type Luid struct {
lowPart uint32 lowPart uint32
highPart int32 highPart int32
@ -54,19 +52,30 @@ type TokenPrivileges struct {
privileges [1]LuidAndAttributes privileges [1]LuidAndAttributes
} }
// nolint // Cleaner to refer to the official OS constant names, and consistent with syscall // Cleaner to refer to the official OS constant names, and consistent with syscall
const ( const (
SEE_MASK_NOCLOSEPROCESS = 0x40 //nolint:stylecheck
EWX_FORCEIFHUNG = 0x10 SEE_MASK_NOCLOSEPROCESS = 0x40
EWX_REBOOT = 0x02 //nolint:stylecheck
EWX_RESTARTAPPS = 0x40 EWX_FORCEIFHUNG = 0x10
SHTDN_REASON_MAJOR_APPLICATION = 0x00040000 //nolint:stylecheck
EWX_REBOOT = 0x02
//nolint:stylecheck
EWX_RESTARTAPPS = 0x40
//nolint:stylecheck
SHTDN_REASON_MAJOR_APPLICATION = 0x00040000
//nolint:stylecheck
SHTDN_REASON_MINOR_INSTALLATION = 0x00000002 SHTDN_REASON_MINOR_INSTALLATION = 0x00000002
SHTDN_REASON_FLAG_PLANNED = 0x80000000 //nolint:stylecheck
TOKEN_ADJUST_PRIVILEGES = 0x0020 SHTDN_REASON_FLAG_PLANNED = 0x80000000
TOKEN_QUERY = 0x0008 //nolint:stylecheck
SE_PRIVILEGE_ENABLED = 0x00000002 TOKEN_ADJUST_PRIVILEGES = 0x0020
SE_ERR_ACCESSDENIED = 0x05 //nolint:stylecheck
TOKEN_QUERY = 0x0008
//nolint:stylecheck
SE_PRIVILEGE_ENABLED = 0x00000002
//nolint:stylecheck
SE_ERR_ACCESSDENIED = 0x05
) )
func winVersionAtLeast(major uint, minor uint, build uint) bool { func winVersionAtLeast(major uint, minor uint, build uint) bool {
@ -101,7 +110,9 @@ func hasAdminRights() bool {
logrus.Warnf("SID allocation error: %s", err) logrus.Warnf("SID allocation error: %s", err)
return false return false
} }
defer windows.FreeSid(sid) defer func() {
_ = windows.FreeSid(sid)
}()
// From MS docs: // From MS docs:
// "If TokenHandle is NULL, CheckTokenMembership uses the impersonation // "If TokenHandle is NULL, CheckTokenMembership uses the impersonation
@ -148,8 +159,10 @@ func relaunchElevatedWait() error {
return wrapMaybef(err, "could not launch process, ShellEX Error = %d", info.hInstApp) return wrapMaybef(err, "could not launch process, ShellEX Error = %d", info.hInstApp)
} }
handle := syscall.Handle(info.hProcess) handle := info.hProcess
defer syscall.CloseHandle(handle) defer func() {
_ = syscall.CloseHandle(handle)
}()
w, err := syscall.WaitForSingleObject(handle, syscall.INFINITE) w, err := syscall.WaitForSingleObject(handle, syscall.INFINITE)
switch w { switch w {
@ -265,6 +278,7 @@ func obtainShutdownPrivilege() error {
} }
var privs TokenPrivileges var privs TokenPrivileges
//nolint:staticcheck
if ret, _, err := LookupPrivilegeValue.Call(uintptr(0), uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(SeShutdownName))), uintptr(unsafe.Pointer(&(privs.privileges[0].luid)))); ret != 1 { if ret, _, err := LookupPrivilegeValue.Call(uintptr(0), uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(SeShutdownName))), uintptr(unsafe.Pointer(&(privs.privileges[0].luid)))); ret != 1 {
return fmt.Errorf("looking up shutdown privilege: %w", err) return fmt.Errorf("looking up shutdown privilege: %w", err)
} }

View File

@ -1,9 +1,10 @@
package specgen package specgen
import ( import (
"github.com/sirupsen/logrus"
"os" "os"
"path/filepath" "path/filepath"
"github.com/sirupsen/logrus"
) )
func shouldResolveUnixWinVariant(path string) bool { func shouldResolveUnixWinVariant(path string) bool {

View File

@ -1,3 +1,5 @@
//go:build !windows
package notifyproxy package notifyproxy
import ( import (

View File

@ -1,3 +1,5 @@
//go:build !windows
package notifyproxy package notifyproxy
import ( import (

View File

@ -25,6 +25,7 @@ func setConsoleMode(handle windows.Handle, flags uint32) error {
var mode uint32 var mode uint32
err := windows.GetConsoleMode(handle, &mode) err := windows.GetConsoleMode(handle, &mode)
if err != nil { if err != nil {
//nolint:nilerr
return nil // not a terminal return nil // not a terminal
} }
if err := windows.SetConsoleMode(handle, mode|flags); err != nil { if err := windows.SetConsoleMode(handle, mode|flags); err != nil {