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,8 +16,11 @@ import (
)
const (
//nolint:stylecheck
MB_ICONWARNING = 0x00000030
//nolint:stylecheck
MB_OK = 0x00000000
//nolint:stylecheck
MB_DEFBUTTON1 = 0x00000000
)
@ -85,7 +88,7 @@ func warn(title string, caption string) int {
func main() {
args := os.Args
setupLogging(path.Base(args[0]))
_, _ = setupLogging(path.Base(args[0]))
if wutil.IsWSLInstalled() {
// nothing to do
logrus.Info("WSL Kernel already installed")

View File

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

View File

@ -15,7 +15,7 @@ set -e
BUILD_TAGS_DEFAULT="apparmor,seccomp,selinux"
BUILD_TAGS_ABI="$BUILD_TAGS_DEFAULT,systemd"
BUILD_TAGS_TUNNEL="$BUILD_TAGS_DEFAULT,remote"
BUILD_TAGS_REMOTE="remote"
BUILD_TAGS_REMOTE="remote,containers_image_openpgp"
SKIP_DIRS_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
# to focus or debug a single, specific linting category.
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

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) {

View File

@ -236,7 +236,9 @@ func isWSL() bool {
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) {
GinkgoWriter.Println(binary + " " + strings.Join(cmdArgs, " "))
c := exec.Command(binary, cmdArgs...)

View File

@ -87,6 +87,7 @@ var _ = Describe("podman machine init - windows only", func() {
}()
i := new(initMachine)
session, err := mb.setName(name).setCmd(i.withImagePath(mb.imagePath)).run()
Expect(err).ToNot(HaveOccurred())
Expect(session).To(Exit(125))
Expect(session.errorToString()).To(ContainSubstring("already exists on hypervisor"))
})

View File

@ -14,7 +14,7 @@ func DetermineMachineArch() string {
current, _ := syscall.GetCurrentProcess()
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
return runtime.GOARCH
}
@ -26,7 +26,7 @@ func DetermineMachineArch() string {
case 0x8664:
return "amd64"
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
}
}

View File

@ -3,38 +3,10 @@ package machine
import (
"fmt"
"strconv"
"time"
"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
func CleanupGVProxy(f define.VMFile) error {
gvPid, err := f.Read()

View File

@ -6,11 +6,38 @@ import (
"errors"
"fmt"
"syscall"
"time"
psutil "github.com/shirou/gopsutil/v3/process"
"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
// 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.

View File

@ -16,6 +16,7 @@ func waitOnProcess(processID int) error {
// 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
// nothing left to do, so return without error
//nolint:nilerr
return nil
}

View File

@ -381,7 +381,10 @@ func (h HyperVStubber) PostStartNetworking(mc *vmconfigs.MachineConfig, noInfo b
defer callbackFuncs.CleanIfErr(&err)
go callbackFuncs.CleanOnSignal()
if len(mc.Mounts) != 0 {
if len(mc.Mounts) == 0 {
return nil
}
var (
dirs *define.MachineDirs
gvproxyPID int
@ -431,16 +434,16 @@ func (h HyperVStubber) PostStartNetworking(mc *vmconfigs.MachineConfig, noInfo b
}
err = fsCmd.Start()
if err == nil {
logrus.Infof("Started podman 9p server as PID %d", fsCmd.Process.Pid)
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
}

View File

@ -29,7 +29,7 @@ func removeShares(mc *vmconfigs.MachineConfig) error {
if err := vsockReg.Remove(); err != 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)
}
@ -44,7 +44,7 @@ func startShares(mc *vmconfigs.MachineConfig) error {
if logrus.IsLevelEnabled(logrus.DebugLevel) {
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 {
return errors.New("cannot start 9p shares with undefined vsock number")
}

View File

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

View File

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

View File

@ -2,18 +2,24 @@
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 {
return false
}
//nolint:unused
func claimDockerSock() bool {
return false
}
//nolint:unused
func dockerClaimSupported() bool {
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`
//nolint:unused
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
@ -240,7 +241,7 @@ http://docs.microsoft.com/en-us/windows/wsl/install\
const (
gvProxy = "gvproxy.exe"
winSShProxy = "win-sshproxy.exe"
winSSHProxy = "win-sshproxy.exe"
pipePrefix = "npipe:////./pipe/"
globalPipe = "docker_engine"
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)
}
//nolint:unused
func getConfigPath(name string) (string, error) {
return getConfigPathExt(name, "json")
}
//nolint:unused
func getConfigPathExt(name string, extension string) (string, error) {
vmConfigDir, err := machine.GetConfDir(vmtype)
if err != nil {
@ -396,7 +398,9 @@ func attemptFeatureInstall(reExec, admin bool) error {
}
func launchElevate(operation string) error {
truncateElevatedOutputFile()
if err := truncateElevatedOutputFile(); err != nil {
return err
}
err := relaunchElevatedWait()
if err != nil {
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...)
}
//nolint:unused
func wslCreateKeys(identityPath string, dist string) (string, error) {
return machine.CreateSSHKeysPrefix(identityPath, true, true, wutil.FindWSL(), "-u", "root", "-d", dist)
}
@ -619,6 +624,7 @@ func setupWslProxyEnv() (hasProxy bool) {
return
}
//nolint:unused
func obtainGlobalConfigLock() (*fileLock, error) {
lockDir, err := machine.GetGlobalDataDir()
if err != nil {
@ -734,6 +740,7 @@ func isRunning(name string) (bool, error) {
return sysd, err
}
//nolint:unused
func getDiskSize(name string) uint64 {
vmDataDir, err := machine.GetDataDir(vmtype)
if err != nil {
@ -748,6 +755,7 @@ func getDiskSize(name string) uint64 {
return uint64(info.Size())
}
//nolint:unused
func getCPUs(name string) (uint64, error) {
dist := machine.ToDist(name)
if run, _ := isWSLRunning(dist); !run {
@ -772,6 +780,7 @@ func getCPUs(name string) (uint64, error) {
return uint64(ret), err
}
//nolint:unused
func getMem(name string) (uint64, error) {
dist := machine.ToDist(name)
if run, _ := isWSLRunning(dist); !run {
@ -808,6 +817,7 @@ func getMem(name string) (uint64, error) {
return total - available, err
}
//nolint:unused
func getResources(mc *vmconfigs.MachineConfig) (resources vmconfigs.ResourceConfig) {
resources.CPUs, _ = getCPUs(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)
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

View File

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

View File

@ -19,7 +19,6 @@ import (
"golang.org/x/sys/windows/registry"
)
// nolint
type SHELLEXECUTEINFO struct {
cbSize uint32
fMask uint32
@ -38,7 +37,6 @@ type SHELLEXECUTEINFO struct {
hProcess syscall.Handle
}
// nolint
type Luid struct {
lowPart uint32
highPart int32
@ -54,18 +52,29 @@ type TokenPrivileges struct {
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 (
//nolint:stylecheck
SEE_MASK_NOCLOSEPROCESS = 0x40
//nolint:stylecheck
EWX_FORCEIFHUNG = 0x10
//nolint:stylecheck
EWX_REBOOT = 0x02
//nolint:stylecheck
EWX_RESTARTAPPS = 0x40
//nolint:stylecheck
SHTDN_REASON_MAJOR_APPLICATION = 0x00040000
//nolint:stylecheck
SHTDN_REASON_MINOR_INSTALLATION = 0x00000002
//nolint:stylecheck
SHTDN_REASON_FLAG_PLANNED = 0x80000000
//nolint:stylecheck
TOKEN_ADJUST_PRIVILEGES = 0x0020
//nolint:stylecheck
TOKEN_QUERY = 0x0008
//nolint:stylecheck
SE_PRIVILEGE_ENABLED = 0x00000002
//nolint:stylecheck
SE_ERR_ACCESSDENIED = 0x05
)
@ -101,7 +110,9 @@ func hasAdminRights() bool {
logrus.Warnf("SID allocation error: %s", err)
return false
}
defer windows.FreeSid(sid)
defer func() {
_ = windows.FreeSid(sid)
}()
// From MS docs:
// "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)
}
handle := syscall.Handle(info.hProcess)
defer syscall.CloseHandle(handle)
handle := info.hProcess
defer func() {
_ = syscall.CloseHandle(handle)
}()
w, err := syscall.WaitForSingleObject(handle, syscall.INFINITE)
switch w {
@ -265,6 +278,7 @@ func obtainShutdownPrivilege() error {
}
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 {
return fmt.Errorf("looking up shutdown privilege: %w", err)
}

View File

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

View File

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

View File

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

View File

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