Skip to content

Commit

Permalink
Merge pull request canonical#10580 from markylaing/govet-ineffassign-…
Browse files Browse the repository at this point in the history
…staticcheck

Adds staticcheck and fixes lint errors
  • Loading branch information
tomponline authored Jun 22, 2022
2 parents 554a8c6 + 8796c9b commit 659887e
Show file tree
Hide file tree
Showing 44 changed files with 126 additions and 108 deletions.
3 changes: 1 addition & 2 deletions client/lxd.go
Original file line number Diff line number Diff line change
Expand Up @@ -409,8 +409,7 @@ func (r *ProtocolLXD) rawWebsocket(url string) (*websocket.Conn, error) {

// Setup a new websocket dialer based on it
dialer := websocket.Dialer{
//lint:ignore SA1019 DialContext doesn't exist in Go 1.13
NetDial: httpTransport.Dial,
NetDialContext: httpTransport.DialContext,
TLSClientConfig: httpTransport.TLSClientConfig,
Proxy: httpTransport.Proxy,
HandshakeTimeout: time.Second * 5,
Expand Down
7 changes: 4 additions & 3 deletions client/lxd_instances.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package lxd

import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
Expand Down Expand Up @@ -1370,9 +1371,9 @@ func (r *ProtocolLXD) rawSFTPConn(apiURL *url.URL) (net.Conn, error) {
var err error

if httpTransport.TLSClientConfig != nil {
conn, err = httpTransport.DialTLS("tcp", apiURL.Host)
conn, err = httpTransport.DialTLSContext(context.Background(), "tcp", apiURL.Host)
} else {
conn, err = httpTransport.Dial("tcp", apiURL.Host)
conn, err = httpTransport.DialContext(context.Background(), "tcp", apiURL.Host)
}
if err != nil {
return nil, err
Expand Down Expand Up @@ -1413,7 +1414,7 @@ func (r *ProtocolLXD) rawSFTPConn(apiURL *url.URL) (net.Conn, error) {
// GetInstanceFileSFTPConn returns a connection to the instance's SFTP endpoint.
func (r *ProtocolLXD) GetInstanceFileSFTPConn(instanceName string) (net.Conn, error) {
apiURL := api.NewURL()
apiURL.URL = *&r.httpBaseURL // Preload the URL with the client base URL.
apiURL.URL = r.httpBaseURL // Preload the URL with the client base URL.
apiURL.Path("1.0", "instances", instanceName, "sftp")
r.setURLQueryAttributes(&apiURL.URL)

Expand Down
5 changes: 3 additions & 2 deletions client/simplestreams_images.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package lxd

import (
"context"
"crypto/sha256"
"fmt"
"io"
Expand Down Expand Up @@ -91,7 +92,7 @@ func (r *ProtocolSimpleStreams) GetImageFile(fingerprint string, req ImageFileRe
return -1, err
}

size, err := shared.DownloadFileHash(nil, r.http, r.httpUserAgent, req.ProgressHandler, req.Canceler, filename, url, hash, sha256.New(), target)
size, err := shared.DownloadFileHash(context.TODO(), r.http, r.httpUserAgent, req.ProgressHandler, req.Canceler, filename, url, hash, sha256.New(), target)
if err != nil {
// Handle cancelation
if err.Error() == "net/http: request canceled" {
Expand All @@ -104,7 +105,7 @@ func (r *ProtocolSimpleStreams) GetImageFile(fingerprint string, req ImageFileRe
return -1, err
}

size, err = shared.DownloadFileHash(nil, r.http, r.httpUserAgent, req.ProgressHandler, req.Canceler, filename, url, hash, sha256.New(), target)
size, err = shared.DownloadFileHash(context.TODO(), r.http, r.httpUserAgent, req.ProgressHandler, req.Canceler, filename, url, hash, sha256.New(), target)
if err != nil {
return -1, err
}
Expand Down
9 changes: 5 additions & 4 deletions client/util.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package lxd

import (
"context"
"crypto/tls"
"fmt"
"net"
Expand All @@ -22,7 +23,7 @@ func tlsHTTPClient(client *http.Client, tlsClientCert string, tlsClientKey strin
// Define the http transport
transport := &http.Transport{
TLSClientConfig: tlsConfig,
Dial: shared.RFC3493Dialer,
DialContext: shared.RFC3493Dialer,
Proxy: shared.ProxyFromEnvironment,
DisableKeepAlives: true,
ExpectContinueTimeout: time.Second * 30,
Expand All @@ -41,7 +42,7 @@ func tlsHTTPClient(client *http.Client, tlsClientCert string, tlsClientKey strin
tlsDial := func(network string, addr string, config *tls.Config, resetName bool) (net.Conn, error) {
// TCP connection
//lint:ignore SA1019 DialContext doesn't exist in Go 1.13
conn, err := transport.Dial(network, addr)
conn, err := transport.DialContext(context.Background(), network, addr)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -104,7 +105,7 @@ func tlsHTTPClient(client *http.Client, tlsClientCert string, tlsClientKey strin

func unixHTTPClient(client *http.Client, path string) (*http.Client, error) {
// Setup a Unix socket dialer
unixDial := func(network, addr string) (net.Conn, error) {
unixDial := func(_ context.Context, network, addr string) (net.Conn, error) {
raddr, err := net.ResolveUnixAddr("unix", path)
if err != nil {
return nil, err
Expand All @@ -115,7 +116,7 @@ func unixHTTPClient(client *http.Client, path string) (*http.Client, error) {

// Define the http transport
transport := &http.Transport{
Dial: unixDial,
DialContext: unixDial,
DisableKeepAlives: true,
ExpectContinueTimeout: time.Second * 30,
ResponseHeaderTimeout: time.Second * 3600,
Expand Down
2 changes: 1 addition & 1 deletion lxc-to-lxd/main_migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ func convertContainer(d lxd.ContainerServer, container *liblxc.Container, storag

// Make sure we don't have a conflict
fmt.Println("Checking for existing containers")
containers, err := d.GetContainerNames()
containers, err := d.GetInstanceNames(api.InstanceTypeContainer)
if err != nil {
return err
}
Expand Down
7 changes: 5 additions & 2 deletions lxc/config/remote.go
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,10 @@ func (c *Config) getConnectionArgs(name string) (*lxd.ConnectionArgs, error) {
}

pemKey, _ := pem.Decode(content)
if x509.IsEncryptedPEMBlock(pemKey) {
// Golang has deprecated all methods relating to PEM encryption due to a vulnerability.
// However, the weakness does not make PEM unsafe for our purposes as it pertains to password protection on the
// key file (client.key is only readable to the user in any case), so we'll ignore deprecation.
if x509.IsEncryptedPEMBlock(pemKey) { //nolint:staticcheck
if c.PromptPassword == nil {
return nil, fmt.Errorf("Private key is password protected and no helper was configured")
}
Expand All @@ -303,7 +306,7 @@ func (c *Config) getConnectionArgs(name string) (*lxd.ConnectionArgs, error) {
return nil, err
}

derKey, err := x509.DecryptPEMBlock(pemKey, []byte(password))
derKey, err := x509.DecryptPEMBlock(pemKey, []byte(password)) //nolint:staticcheck
if err != nil {
return nil, err
}
Expand Down
5 changes: 2 additions & 3 deletions lxc/remote.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,6 @@ func (c *cmdRemoteAdd) RunToken(server string, token string, rawToken *api.Certi

var certificate *x509.Certificate
var err error
var d lxd.InstanceServer

if !conf.HasClientCertificate() {
fmt.Fprintf(os.Stderr, i18n.G("Generating a client certificate. This may take a minute...")+"\n")
Expand All @@ -170,7 +169,7 @@ func (c *cmdRemoteAdd) RunToken(server string, token string, rawToken *api.Certi

conf.Remotes[server] = config.Remote{Addr: addr, Protocol: c.flagProtocol, AuthType: c.flagAuthType, Domain: c.flagDomain}

d, err = conf.GetInstanceServer(server)
_, err = conf.GetInstanceServer(server)
if err != nil {
certificate, err = shared.GetRemoteCertificate(addr, c.global.conf.UserAgent)
if err != nil {
Expand Down Expand Up @@ -206,7 +205,7 @@ func (c *cmdRemoteAdd) RunToken(server string, token string, rawToken *api.Certi
}
}

d, err = conf.GetInstanceServer(server)
d, err := conf.GetInstanceServer(server)
if err != nil {
continue
}
Expand Down
2 changes: 1 addition & 1 deletion lxd-agent/network.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func (l *networkListener) Accept() (net.Conn, error) {
break
}

if err.(net.Error).Temporary() {
if err.(net.Error).Timeout() {
time.Sleep(100 * time.Millisecond)
continue
}
Expand Down
3 changes: 2 additions & 1 deletion lxd/cluster/membership.go
Original file line number Diff line number Diff line change
Expand Up @@ -558,8 +558,9 @@ func NotifyHeartbeat(state *state.State, gateway *Gateway) {
heartbeatCancel()

// Wait for heartbeat to finish and then release.
// Ignore staticcheck "SA2001: empty critical section" because we want to wait for the lock.
gateway.HeartbeatLock.Lock()
gateway.HeartbeatLock.Unlock()
gateway.HeartbeatLock.Unlock() //nolint:staticcheck
}

hbState := NewAPIHearbeat(state.DB.Cluster)
Expand Down
1 change: 0 additions & 1 deletion lxd/daemon.go
Original file line number Diff line number Diff line change
Expand Up @@ -633,7 +633,6 @@ func (d *Daemon) createCmd(restAPI *mux.Router, version string, c APIEndpoint) {

// Actually process the request
var resp response.Response
resp = response.NotImplemented(nil)

// Return Unavailable Error (503) if daemon is shutting down.
// There are some exceptions:
Expand Down
2 changes: 1 addition & 1 deletion lxd/db/generate/db/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ func parseField(f *ast.Field, kind string) (*Field, error) {
name := f.Names[0]

if !name.IsExported() {
//return nil, fmt.Errorf("Unexported field name %q", name.Name)
return nil, fmt.Errorf("Unexported field name %q", name.Name)
}

// Ignore fields that are marked with a tag of `db:"ingore"`
Expand Down
5 changes: 4 additions & 1 deletion lxd/db/generate/lex/case.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@ import (
"bytes"
"strings"
"unicode"

"golang.org/x/text/cases"
"golang.org/x/text/language"
)

// Capital capitalizes the given string ("foo" -> "Foo")
func Capital(s string) string {
return strings.Title(s)
return cases.Title(language.English).String(s)
}

// Minuscule turns the first character to lower case ("Foo" -> "foo") or the whole word if it is all uppercase ("UUID" -> "uuid")
Expand Down
2 changes: 1 addition & 1 deletion lxd/device/gpu_mdev.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ func (d *gpuMdev) startVM() (*deviceConfig.RunConfig, error) {
if mdevUUID == "" || !shared.PathExists(fmt.Sprintf("/sys/bus/pci/devices/%s/%s", pciAddress, mdevUUID)) {
mdevUUID = uuid.New()

err = ioutil.WriteFile(filepath.Join(fmt.Sprintf("/sys/bus/pci/devices/%s/mdev_supported_types/%s/create", pciAddress, d.config["mdev"])), []byte(mdevUUID), 200)
err = ioutil.WriteFile(filepath.Join(fmt.Sprintf("/sys/bus/pci/devices/%s/mdev_supported_types/%s/create", pciAddress, d.config["mdev"])), []byte(mdevUUID), 0200)
if err != nil {
if os.IsNotExist(err) {
return nil, fmt.Errorf("The requested profile %q does not exist", d.config["mdev"])
Expand Down
4 changes: 2 additions & 2 deletions lxd/devlxd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ type DevLxdDialer struct {
Path string
}

func (d DevLxdDialer) DevLxdDial(network, path string) (net.Conn, error) {
func (d DevLxdDialer) DevLxdDial(ctx context.Context, network, path string) (net.Conn, error) {
addr, err := net.ResolveUnixAddr("unix", d.Path)
if err != nil {
return nil, err
Expand Down Expand Up @@ -146,7 +146,7 @@ func TestHttpRequest(t *testing.T) {
}
defer func() { _ = d.Stop(context.Background(), unix.SIGQUIT) }()

c := http.Client{Transport: &http.Transport{Dial: DevLxdDialer{Path: fmt.Sprintf("%s/devlxd/sock", testDir)}.DevLxdDial}}
c := http.Client{Transport: &http.Transport{DialContext: DevLxdDialer{Path: fmt.Sprintf("%s/devlxd/sock", testDir)}.DevLxdDial}}

raw, err := c.Get("http://1.0")
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions lxd/dnsmasq/dhcpalloc/dhcpalloc.go
Original file line number Diff line number Diff line change
Expand Up @@ -377,8 +377,8 @@ func AllocateTask(opts *Options, f func(*Transaction) error) error {

// If MAC or either IPv4 or IPv6 assigned is different than what is in dnsmasq config, rebuild config.
macChanged := !bytes.Equal(opts.HostMAC, t.currentDHCPMAC)
ipv4Changed := (t.allocatedIPv4 != nil && !bytes.Equal(t.currentDHCPv4.IP, t.allocatedIPv4.To4()))
ipv6Changed := (t.allocatedIPv6 != nil && !bytes.Equal(t.currentDHCPv6.IP, t.allocatedIPv6.To16()))
ipv4Changed := t.allocatedIPv4 != nil && !t.currentDHCPv4.IP.Equal(t.allocatedIPv4.To4())
ipv6Changed := t.allocatedIPv6 != nil && !t.currentDHCPv6.IP.Equal(t.allocatedIPv6.To16())

if macChanged || ipv4Changed || ipv6Changed {
var IPv4Str, IPv6Str string
Expand Down
5 changes: 3 additions & 2 deletions lxd/endpoints/endpoints_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package endpoints_test

import (
"context"
"fmt"
"io/ioutil"
"log"
Expand Down Expand Up @@ -56,10 +57,10 @@ func newEndpoints(t *testing.T) (*endpoints.Endpoints, *endpoints.Config, func()

// Perform an HTTP GET "/" over the unix socket at the given path.
func httpGetOverUnixSocket(path string) error {
dial := func(network, addr string) (net.Conn, error) {
dial := func(_ context.Context, network, addr string) (net.Conn, error) {
return net.Dial("unix", path)
}
client := &http.Client{Transport: &http.Transport{Dial: dial}}
client := &http.Client{Transport: &http.Transport{DialContext: dial}}
_, err := client.Get("http://unix.socket/")
return err
}
Expand Down
4 changes: 2 additions & 2 deletions lxd/firewall/drivers/drivers_xtables.go
Original file line number Diff line number Diff line change
Expand Up @@ -1180,13 +1180,13 @@ func (d Xtables) matchEbtablesRule(activeRule []string, matchRule []string, dele
matchIPMaskStr := strings.SplitN(match, "/", 2)
if len(matchIPMaskStr) == 2 && matchIPMaskStr[0] == strings.Split(active, "/")[0] {
// If the active subnet is a CIDR string we have a match if the masks are identical.
activeIP, activeIPNet, err := net.ParseCIDR(active)
_, activeIPNet, err := net.ParseCIDR(active)
if err == nil {
return subnetMask(activeIPNet) == matchIPMaskStr[1]
}

// If the active subnet is a single IP then we have a match if the generated mask is a full mask.
activeIP = net.ParseIP(active)
activeIP := net.ParseIP(active)
if activeIP != nil {
if activeIP.To4() != nil {
return matchIPMaskStr[1] == "255.255.255.255"
Expand Down
7 changes: 2 additions & 5 deletions lxd/instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,6 @@ func instanceCreateAsCopy(s *state.State, opts instanceCreateAsCopyOpts, op *ope
return nil, err
}

snapList := []*instance.Instance{}
var snapshots []instance.Instance

if !opts.instanceOnly {
Expand Down Expand Up @@ -319,7 +318,7 @@ func instanceCreateAsCopy(s *state.State, opts instanceCreateAsCopyOpts, op *ope
"path": "/",
"pool": instRootDiskDevice["pool"],
}
} else {
} else { //nolint:staticcheck // (keep the empty branch for the comment)
// Snapshot has multiple root disk devices, we can't automatically fix this so
// leave alone so we don't prevent copy.
}
Expand All @@ -342,14 +341,12 @@ func instanceCreateAsCopy(s *state.State, opts instanceCreateAsCopyOpts, op *ope
}

// Create the snapshots.
snapInst, snapInstOp, cleanup, err := instance.CreateInternal(s, snapInstArgs, true)
_, snapInstOp, cleanup, err := instance.CreateInternal(s, snapInstArgs, true)
if err != nil {
return nil, fmt.Errorf("Failed creating instance snapshot record %q: %w", newSnapName, err)
}
revert.Add(cleanup)
defer snapInstOp.Done(err)

snapList = append(snapList, &snapInst)
}
}

Expand Down
2 changes: 1 addition & 1 deletion lxd/instance/drivers/driver_qemu.go
Original file line number Diff line number Diff line change
Expand Up @@ -5245,7 +5245,7 @@ func (d *qemu) FileSFTPConn() (net.Conn, error) {
req.Header["Upgrade"] = []string{"sftp"}
req.Header["Connection"] = []string{"Upgrade"}

conn, err := httpTransport.Dial("tcp", "8443")
conn, err := httpTransport.DialContext(context.Background(), "tcp", "8443")
if err != nil {
return nil, err
}
Expand Down
2 changes: 1 addition & 1 deletion lxd/instance/drivers/driver_qemu_templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -763,7 +763,7 @@ func qemuUSB(opts *qemuUSBOpts) []cfgSection {
{key: "name", value: "usbredir"},
},
}, {
name: fmt.Sprintf(fmt.Sprintf(`device "qemu_spice-usb%d"`, i)),
name: fmt.Sprintf(`device "qemu_spice-usb%d"`, i),
entries: []cfgEntry{
{key: "driver", value: "usb-redir"},
{key: "chardev", value: chardev},
Expand Down
2 changes: 1 addition & 1 deletion lxd/instances_post.go
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,7 @@ func createFromMigration(d *Daemon, r *http.Request, projectName string, req *ap
URL: req.Source.Operation,
Dialer: websocket.Dialer{
TLSClientConfig: config,
NetDial: shared.RFC3493Dialer,
NetDialContext: shared.RFC3493Dialer,
HandshakeTimeout: time.Second * 5,
},
Instance: inst,
Expand Down
4 changes: 3 additions & 1 deletion lxd/main_recover.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"strings"

"github.com/spf13/cobra"
"golang.org/x/text/cases"
"golang.org/x/text/language"

"github.com/lxc/lxd/client"
"github.com/lxc/lxd/shared/api"
Expand Down Expand Up @@ -195,7 +197,7 @@ func (c *cmdRecover) Run(cmd *cobra.Command, args []string) error {
if len(res.UnknownVolumes) > 0 {
fmt.Print("The following unknown volumes have been found:\n")
for _, unknownVol := range res.UnknownVolumes {
fmt.Printf(" - %s %q on pool %q in project %q (includes %d snapshots)\n", strings.Title(unknownVol.Type), unknownVol.Name, unknownVol.Pool, unknownVol.Project, unknownVol.SnapshotCount)
fmt.Printf(" - %s %q on pool %q in project %q (includes %d snapshots)\n", cases.Title(language.English).String(unknownVol.Type), unknownVol.Name, unknownVol.Pool, unknownVol.Project, unknownVol.SnapshotCount)
}
}

Expand Down
2 changes: 1 addition & 1 deletion lxd/migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ func (s *migrationSourceWs) ConnectTarget(certificate string, operation string,

dialer := websocket.Dialer{
TLSClientConfig: config,
NetDial: shared.RFC3493Dialer,
NetDialContext: shared.RFC3493Dialer,
HandshakeTimeout: time.Second * 5,
}

Expand Down
2 changes: 1 addition & 1 deletion lxd/migrate_instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -385,7 +385,7 @@ func (s *migrationSourceWs) Do(state *state.State, migrateOp *operations.Operati
// or not it's doing a refresh as the migration sink/receiver will know
// this, and adjust the migration types accordingly.
poolMigrationTypes = pool.MigrationTypes(storagePools.InstanceContentType(s.instance), false)
if len(poolMigrationTypes) < 0 {
if len(poolMigrationTypes) == 0 {
return abort(fmt.Errorf("No source migration types available"))
}

Expand Down
2 changes: 1 addition & 1 deletion lxd/migrate_storage_volumes.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func (s *migrationSourceWs) DoStorage(state *state.State, projectName string, po
// or not it's doing a refresh as the migration sink/receiver will know
// this, and adjust the migration types accordingly.
poolMigrationTypes = pool.MigrationTypes(storageDrivers.ContentType(srcConfig.Volume.ContentType), false)
if len(poolMigrationTypes) < 0 {
if len(poolMigrationTypes) == 0 {
return fmt.Errorf("No source migration types available")
}

Expand Down
Loading

0 comments on commit 659887e

Please sign in to comment.