[lxc-devel] [lxd/master] Typos and unchecked variables

stgraber on Github lxc-bot at linuxcontainers.org
Thu Nov 9 22:34:35 UTC 2017


A non-text attachment was scrubbed...
Name: not available
Type: text/x-mailbox
Size: 301 bytes
Desc: not available
URL: <http://lists.linuxcontainers.org/pipermail/lxc-devel/attachments/20171109/2631edec/attachment.bin>
-------------- next part --------------
From a09aa131a2110a40cd0ca64bff4de704f14177b6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Graber?= <stgraber at ubuntu.com>
Date: Thu, 9 Nov 2017 15:54:58 -0500
Subject: [PATCH 1/4] Fix some typos
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Signed-off-by: Stéphane Graber <stgraber at ubuntu.com>
---
 doc/api-extensions.md        | 2 +-
 doc/container-environment.md | 4 ++--
 doc/containers.md            | 6 +++---
 doc/index.md                 | 2 +-
 doc/preseed.md               | 2 +-
 scripts/lxc-to-lxd           | 2 +-
 test/includes/check.sh       | 2 +-
 test/suites/config.sh        | 2 +-
 8 files changed, 11 insertions(+), 11 deletions(-)

diff --git a/doc/api-extensions.md b/doc/api-extensions.md
index 53a29c05e..681a6442c 100644
--- a/doc/api-extensions.md
+++ b/doc/api-extensions.md
@@ -291,7 +291,7 @@ map auto-selection process for isolated containers and specify what host
 uid/gid to use as the base.
 
 ## file\_symlinks
-This adds support for transfering symlinks through the file API.
+This adds support for transferring symlinks through the file API.
 X-LXD-type can now be "symlink" with the request content being the target path.
 
 ## container\_push\_target
diff --git a/doc/container-environment.md b/doc/container-environment.md
index d354ea0ca..dd91c899e 100644
--- a/doc/container-environment.md
+++ b/doc/container-environment.md
@@ -76,7 +76,7 @@ privileged containers.
 
 ## Network
 LXD containers may have any number of network devices attached to them.
-The naming for those unless overriden by the user is ethX where X is an incrementing number.
+The naming for those unless overridden by the user is ethX where X is an incrementing number.
 
 ## Container to host communication
 LXD sets up a socket at `/dev/lxd/sock` which root in the container can use to communicate with LXD on the host.
@@ -86,5 +86,5 @@ The API is [documented here](dev-lxd.md).
 ## LXCFS
 If LXCFS is present on the host, it will automatically be setup for the container.
 
-This normally results in a number of `/proc` files being overriden through bind-mounts.
+This normally results in a number of `/proc` files being overridden through bind-mounts.
 On older kernels a virtual version of `/sys/fs/cgroup` may also be setup by LXCFS.
diff --git a/doc/containers.md b/doc/containers.md
index 8a86c6f80..8d93f1f0a 100644
--- a/doc/containers.md
+++ b/doc/containers.md
@@ -102,7 +102,7 @@ and should whenever possible be avoided.
 # Devices configuration
 LXD will always provide the container with the basic devices which are required
 for a standard POSIX system to work. These aren't visible in container or
-profile configuration and may not be overriden.
+profile configuration and may not be overridden.
 
 Those includes:
 
@@ -128,7 +128,7 @@ Devices may be added or removed while the container is running.
 
 Every device entry is identified by a unique name. If the same name is used in
 a subsequent profile or in the container's own configuration, the whole entry
-is overriden by the new definition.
+is overridden by the new definition.
 
 Device entries are added to a container through:
 
@@ -212,7 +212,7 @@ The `sriov` interface type supports SR-IOV enabled network devices. These
 devices associate a set of virtual functions (VFs) with the single physical
 function (PF) of the network device. PFs are standard PCIe functions. VFs on
 the other hand are very lightweight PCIe functions that are optimized for data
-movement. They come with a limited set of configuration capabilites to prevent
+movement. They come with a limited set of configuration capabilities to prevent
 changing properties of the PF. Given that VFs appear as regular PCIe devices to
 the system they can be passed to containers just like a regular physical
 device. The `sriov` interface type expects to be passed the name of an SR-IOV
diff --git a/doc/index.md b/doc/index.md
index f85f3ea2d..b907fd500 100644
--- a/doc/index.md
+++ b/doc/index.md
@@ -228,7 +228,7 @@ Note that LXD containers cannot load kernel modules, so depending on your
 Docker configuration you may need to have the needed extra kernel modules
 loaded by the host.
 
-You can do so by setting a comma seperate list of kernel modules that your container needs with:
+You can do so by setting a comma separate list of kernel modules that your container needs with:
 
 ```bash
 lxc config set <container> linux.kernel_modules <modules>
diff --git a/doc/preseed.md b/doc/preseed.md
index a066d1d0c..5dd3f978e 100644
--- a/doc/preseed.md
+++ b/doc/preseed.md
@@ -68,7 +68,7 @@ preseed.
 
 Differently from the interactive init mode, the `lxd init --preseed`
 command line will not modify the default profile in any particular
-way, unless you explicitely express that in the provided YAML payload.
+way, unless you explicitly express that in the provided YAML payload.
 
 For instance, you will typically want to attach a root disk device and
 a network interface to your default profile. See below for an example.
diff --git a/scripts/lxc-to-lxd b/scripts/lxc-to-lxd
index b9728d346..1aaa964a2 100755
--- a/scripts/lxc-to-lxd
+++ b/scripts/lxc-to-lxd
@@ -173,7 +173,7 @@ def config_parse(path):
                             config.append("lxc.mount.entry = %s" % line)
                 continue
 
-            # Proces normal configuration keys
+            # Process normal configuration keys
             if line and not line.strip().startswith("#"):
                 config.append(line)
 
diff --git a/test/includes/check.sh b/test/includes/check.sh
index 532cd9306..cf83b5f0b 100644
--- a/test/includes/check.sh
+++ b/test/includes/check.sh
@@ -1,4 +1,4 @@
-# Miscellanous test checks.
+# Miscellaneous test checks.
 
 check_dependencies() {
     # shellcheck disable=SC2039
diff --git a/test/suites/config.sh b/test/suites/config.sh
index 2f4e21a59..5097bc133 100644
--- a/test/suites/config.sh
+++ b/test/suites/config.sh
@@ -210,7 +210,7 @@ test_config_profiles() {
   bad=0
   lxc config set foo user.prop 2>/dev/null && bad=1
   if [ "${bad}" -eq 1 ]; then
-    echo "property set succeded when it shouldn't have"
+    echo "property set succeeded when it shouldn't have"
     false
   fi
 

From db88d6174faa6520ff2b7d458fa2a2dc540f82b2 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Graber?= <stgraber at ubuntu.com>
Date: Thu, 9 Nov 2017 16:02:54 -0500
Subject: [PATCH 2/4] tests: Check for typos
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Signed-off-by: Stéphane Graber <stgraber at ubuntu.com>
---
 test/suites/static_analysis.sh | 11 +++++++++++
 1 file changed, 11 insertions(+)

diff --git a/test/suites/static_analysis.sh b/test/suites/static_analysis.sh
index 3c651577a..5f6edab15 100644
--- a/test/suites/static_analysis.sh
+++ b/test/suites/static_analysis.sh
@@ -64,6 +64,7 @@ test_static_analysis() {
       fi
     fi
 
+    ## imports
     OUT=$(go list -f '{{ join .Imports "\n" }}' ./client ./shared/api ./lxc/config | sort -u | grep \\. | diff -u test/godeps.list - || true)
     if [ -n "${OUT}" ]; then
       echo "ERROR: you added a new dependency to the client or shared; please make sure this is what you want"
@@ -71,6 +72,16 @@ test_static_analysis() {
       exit 1
     fi
 
+    ## misspell
+    if which misspell >/dev/null 2>&1; then
+      OUT=$(misspell ./ | grep -v po/ | grep -Ev "test/includes/lxd.sh.*monitord" | grep -Ev "test/suites/static_analysis.sh.*monitord" || true)
+      if [ -n "${OUT}" ]; then
+        echo "Found some typos"
+        echo "${OUT}"
+        exit 1
+      fi
+    fi
+
     # Skip the tests which require git
     if ! git status; then
       return

From d8d6948021a974018a0f6422030390328f9e0f28 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Graber?= <stgraber at ubuntu.com>
Date: Thu, 9 Nov 2017 17:17:32 -0500
Subject: [PATCH 3/4] Fix a number of unchecked variables
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Signed-off-by: Stéphane Graber <stgraber at ubuntu.com>
---
 lxc/config/file.go                    |  4 ++++
 lxc/file.go                           |  3 +++
 lxd/container_lxc.go                  | 20 +++++++++++++++++---
 lxd/container_put.go                  |  3 +--
 lxd/db/containers.go                  |  4 ++--
 lxd/db/db_internal_test.go            |  1 +
 lxd/db/images.go                      |  4 ++++
 lxd/db/networks.go                    |  3 +++
 lxd/db/node/open_test.go              |  1 +
 lxd/db/profiles.go                    |  3 +++
 lxd/db/schema/schema_test.go          |  1 +
 lxd/db/storage_pools.go               |  3 +++
 lxd/db/storage_volumes.go             |  3 +++
 lxd/devices.go                        |  3 +++
 lxd/main_forkmigrate.go               |  4 ++++
 lxd/networks_utils.go                 |  9 ++++-----
 lxd/patches.go                        |  9 +++------
 lxd/profiles_test.go                  |  5 +++++
 lxd/storage_ceph_utils.go             |  2 +-
 lxd/storage_lvm.go                    |  4 ++--
 lxd/storage_lvm_utils.go              |  3 +--
 lxd/storage_pools.go                  |  5 +++++
 lxd/storage_utils.go                  | 21 +++++++++++----------
 lxd/storage_zfs.go                    |  8 +++++++-
 shared/ioprogress/tracker.go          |  2 +-
 shared/simplestreams/simplestreams.go |  2 +-
 26 files changed, 94 insertions(+), 36 deletions(-)

diff --git a/lxc/config/file.go b/lxc/config/file.go
index 6d237049a..4f6f54198 100644
--- a/lxc/config/file.go
+++ b/lxc/config/file.go
@@ -78,6 +78,10 @@ func (c *Config) SaveConfig(path string) error {
 
 	// Write the new config
 	data, err := yaml.Marshal(c)
+	if err != nil {
+		return fmt.Errorf("Unable to marshal the configuration: %v", err)
+	}
+
 	_, err = f.Write(data)
 	if err != nil {
 		return fmt.Errorf("Unable to write the configuration: %v", err)
diff --git a/lxc/file.go b/lxc/file.go
index 36df47e66..69b8c6a53 100644
--- a/lxc/file.go
+++ b/lxc/file.go
@@ -563,6 +563,9 @@ func (c *fileCmd) edit(conf *config.Config, args []string) error {
 
 	// Create temp file
 	f, err := ioutil.TempFile("", "lxd_file_edit_")
+	if err != nil {
+		return fmt.Errorf("Unable to create a temporary file: %v", err)
+	}
 	fname := f.Name()
 	f.Close()
 	os.Remove(fname)
diff --git a/lxd/container_lxc.go b/lxd/container_lxc.go
index 6c5f51e09..e23b4fcb1 100644
--- a/lxd/container_lxc.go
+++ b/lxd/container_lxc.go
@@ -5153,9 +5153,15 @@ func (c *containerLXC) cpuState() api.ContainerStateCPU {
 
 	// CPU usage in seconds
 	value, err := c.CGroupGet("cpuacct.usage")
+	if err != nil {
+		cpu.Usage = -1
+		return cpu
+	}
+
 	valueInt, err := strconv.ParseInt(value, 10, 64)
 	if err != nil {
-		valueInt = -1
+		cpu.Usage = -1
+		return cpu
 	}
 
 	cpu.Usage = valueInt
@@ -5283,6 +5289,10 @@ func (c *containerLXC) processesState() int64 {
 
 	if c.state.OS.CGroupPidsController {
 		value, err := c.CGroupGet("pids.current")
+		if err != nil {
+			return -1
+		}
+
 		valueInt, err := strconv.ParseInt(value, 10, 64)
 		if err != nil {
 			return -1
@@ -5431,7 +5441,7 @@ func (c *containerLXC) StorageStartSensitive() (bool, error) {
 		return false, err
 	}
 
-	isOurOperation := false
+	var isOurOperation bool
 	if c.IsSnapshot() {
 		isOurOperation, err = c.storage.ContainerSnapshotStart(c)
 	} else {
@@ -5448,7 +5458,7 @@ func (c *containerLXC) StorageStop() (bool, error) {
 		return false, err
 	}
 
-	isOurOperation := false
+	var isOurOperation bool
 	if c.IsSnapshot() {
 		isOurOperation, err = c.storage.ContainerSnapshotStop(c)
 	} else {
@@ -6314,6 +6324,10 @@ func (c *containerLXC) createNetworkFilter(name string, bridge string, hwaddr st
 
 func (c *containerLXC) removeNetworkFilter(hwaddr string, bridge string) error {
 	out, err := shared.RunCommand("ebtables", "-L", "--Lmac2", "--Lx")
+	if err != nil {
+		return err
+	}
+
 	for _, line := range strings.Split(out, "\n") {
 		line = strings.TrimSpace(line)
 		fields := strings.Fields(line)
diff --git a/lxd/container_put.go b/lxd/container_put.go
index c208a4ca7..02a05c643 100644
--- a/lxd/container_put.go
+++ b/lxd/container_put.go
@@ -45,8 +45,7 @@ func containerPut(d *Daemon, r *http.Request) Response {
 		architecture = 0
 	}
 
-	var do = func(*operation) error { return nil }
-
+	var do func(*operation) error
 	if configRaw.Restore == "" {
 		// Update container configuration
 		do = func(op *operation) error {
diff --git a/lxd/db/containers.go b/lxd/db/containers.go
index e49bf5755..9eac650d5 100644
--- a/lxd/db/containers.go
+++ b/lxd/db/containers.go
@@ -136,7 +136,7 @@ func (n *Node) ContainerGet(name string) (ContainerArgs, error) {
 }
 
 func (n *Node) ContainerCreate(args ContainerArgs) (int, error) {
-	id, err := n.ContainerId(args.Name)
+	_, err := n.ContainerId(args.Name)
 	if err == nil {
 		return 0, DbErrAlreadyDefined
 	}
@@ -178,7 +178,7 @@ func (n *Node) ContainerCreate(args ContainerArgs) (int, error) {
 		return 0, fmt.Errorf("Error inserting %s into database", args.Name)
 	}
 	// TODO: is this really int64? we should fix it everywhere if so
-	id = int(id64)
+	id := int(id64)
 	if err := ContainerConfigInsert(tx, id, args.Config); err != nil {
 		tx.Rollback()
 		return 0, err
diff --git a/lxd/db/db_internal_test.go b/lxd/db/db_internal_test.go
index 23fc183b8..bdebdc3e9 100644
--- a/lxd/db/db_internal_test.go
+++ b/lxd/db/db_internal_test.go
@@ -124,6 +124,7 @@ func (s *dbTestSuite) Test_deleting_a_profile_cascades_on_related_tables() {
 	// Make sure there are 0 container_profiles entries left.
 	statements = `SELECT count(*) FROM containers_profiles WHERE profile_id = 2;`
 	err = s.db.DB().QueryRow(statements).Scan(&count)
+	s.Nil(err)
 	s.Equal(count, 0, "Deleting a profile didn't delete the container association!")
 
 	// Make sure there are 0 profiles_devices entries left.
diff --git a/lxd/db/images.go b/lxd/db/images.go
index 9bff6240e..7e63f8b07 100644
--- a/lxd/db/images.go
+++ b/lxd/db/images.go
@@ -435,6 +435,10 @@ func (n *Node) ImageUpdate(id int, fname string, sz int64, public bool, autoUpda
 	}
 
 	_, err = tx.Exec(`DELETE FROM images_properties WHERE image_id=?`, id)
+	if err != nil {
+		tx.Rollback()
+		return err
+	}
 
 	stmt, err = tx.Prepare(`INSERT INTO images_properties (image_id, type, key, value) VALUES (?, ?, ?, ?)`)
 	if err != nil {
diff --git a/lxd/db/networks.go b/lxd/db/networks.go
index 5860ac71d..66b3b5913 100644
--- a/lxd/db/networks.go
+++ b/lxd/db/networks.go
@@ -215,6 +215,9 @@ func NetworkConfigAdd(tx *sql.Tx, id int64, config map[string]string) error {
 	str := fmt.Sprintf("INSERT INTO networks_config (network_id, key, value) VALUES(?, ?, ?)")
 	stmt, err := tx.Prepare(str)
 	defer stmt.Close()
+	if err != nil {
+		return err
+	}
 
 	for k, v := range config {
 		if v == "" {
diff --git a/lxd/db/node/open_test.go b/lxd/db/node/open_test.go
index e71f1054b..161040442 100644
--- a/lxd/db/node/open_test.go
+++ b/lxd/db/node/open_test.go
@@ -27,6 +27,7 @@ func TestEnsureSchema(t *testing.T) {
 	defer cleanup()
 
 	db, err := node.Open(dir)
+	require.NoError(t, err)
 	defer db.Close()
 
 	hookHasRun := false
diff --git a/lxd/db/profiles.go b/lxd/db/profiles.go
index c4a24967a..61bbd386f 100644
--- a/lxd/db/profiles.go
+++ b/lxd/db/profiles.go
@@ -222,6 +222,9 @@ func ProfileConfigAdd(tx *sql.Tx, id int64, config map[string]string) error {
 	str := fmt.Sprintf("INSERT INTO profiles_config (profile_id, key, value) VALUES(?, ?, ?)")
 	stmt, err := tx.Prepare(str)
 	defer stmt.Close()
+	if err != nil {
+		return err
+	}
 
 	for k, v := range config {
 		_, err = stmt.Exec(id, k, v)
diff --git a/lxd/db/schema/schema_test.go b/lxd/db/schema/schema_test.go
index 8d9111196..cd4130952 100644
--- a/lxd/db/schema/schema_test.go
+++ b/lxd/db/schema/schema_test.go
@@ -71,6 +71,7 @@ func TestSchemaEnsure_MissingVersion(t *testing.T) {
 	assert.NoError(t, err)
 
 	_, err = db.Exec(`INSERT INTO schema (version, updated_at) VALUES (3, strftime("%s"))`)
+	assert.NoError(t, err)
 
 	schema.Add(updateNoop)
 	schema.Add(updateNoop)
diff --git a/lxd/db/storage_pools.go b/lxd/db/storage_pools.go
index 23fb83de9..0f2036633 100644
--- a/lxd/db/storage_pools.go
+++ b/lxd/db/storage_pools.go
@@ -169,6 +169,9 @@ func StoragePoolConfigAdd(tx *sql.Tx, poolID int64, poolConfig map[string]string
 	str := "INSERT INTO storage_pools_config (storage_pool_id, key, value) VALUES(?, ?, ?)"
 	stmt, err := tx.Prepare(str)
 	defer stmt.Close()
+	if err != nil {
+		return err
+	}
 
 	for k, v := range poolConfig {
 		if v == "" {
diff --git a/lxd/db/storage_volumes.go b/lxd/db/storage_volumes.go
index 420b84597..49da9d45a 100644
--- a/lxd/db/storage_volumes.go
+++ b/lxd/db/storage_volumes.go
@@ -58,6 +58,9 @@ func StorageVolumeConfigAdd(tx *sql.Tx, volumeID int64, volumeConfig map[string]
 	str := "INSERT INTO storage_volumes_config (storage_volume_id, key, value) VALUES(?, ?, ?)"
 	stmt, err := tx.Prepare(str)
 	defer stmt.Close()
+	if err != nil {
+		return err
+	}
 
 	for k, v := range volumeConfig {
 		if v == "" {
diff --git a/lxd/devices.go b/lxd/devices.go
index 785045741..fd9211d3b 100644
--- a/lxd/devices.go
+++ b/lxd/devices.go
@@ -442,6 +442,9 @@ func deviceNetlinkListener() (chan []string, chan []string, chan usbDevice, erro
 				}
 
 				devname, ok := props["DEVNAME"]
+				if !ok {
+					continue
+				}
 
 				busnum, ok := props["BUSNUM"]
 				if !ok {
diff --git a/lxd/main_forkmigrate.go b/lxd/main_forkmigrate.go
index ab3191c38..00792635b 100644
--- a/lxd/main_forkmigrate.go
+++ b/lxd/main_forkmigrate.go
@@ -28,7 +28,11 @@ func cmdForkMigrate(args *Args) error {
 	lxcpath := args.Params[1]
 	configPath := args.Params[2]
 	imagesDir := args.Params[3]
+
 	preservesInodes, err := strconv.ParseBool(args.Params[4])
+	if err != nil {
+		return err
+	}
 
 	c, err := lxc.NewContainer(name, lxcpath)
 	if err != nil {
diff --git a/lxd/networks_utils.go b/lxd/networks_utils.go
index 080e5aa4d..fa7c0fd9b 100644
--- a/lxd/networks_utils.go
+++ b/lxd/networks_utils.go
@@ -183,8 +183,7 @@ func networkGetIP(subnet *net.IPNet, host int64) net.IP {
 
 	// Generate an IPv6
 	if subnet.IP.To4() == nil {
-		newIp := make(net.IP, 16)
-		newIp = bigIP.Bytes()
+		newIp := bigIP.Bytes()
 		return newIp
 	}
 
@@ -300,7 +299,7 @@ func networkInRoutingTable(subnet *net.IPNet) bool {
 		fields := strings.Fields(string(line))
 
 		// Get the IP
-		ip := net.IP{}
+		var ip net.IP
 		if filename == "ipv6_route" {
 			ip, err = hex.DecodeString(fields[0])
 			if err != nil {
@@ -316,7 +315,7 @@ func networkInRoutingTable(subnet *net.IPNet) bool {
 		}
 
 		// Get the mask
-		mask := net.IPMask{}
+		var mask net.IPMask
 		if filename == "ipv6_route" {
 			size, err := strconv.ParseInt(fmt.Sprintf("0x%s", fields[1]), 0, 64)
 			if err != nil {
@@ -751,7 +750,7 @@ func networkUpdateStatic(s *state.State, networkName string) error {
 	}
 
 	// Get all the networks
-	networks := []string{}
+	var networks []string
 	if networkName == "" {
 		var err error
 		networks, err = s.DB.Networks()
diff --git a/lxd/patches.go b/lxd/patches.go
index 9cef17c0e..e8d74208b 100644
--- a/lxd/patches.go
+++ b/lxd/patches.go
@@ -717,7 +717,7 @@ func upgradeFromStorageTypeDir(name string, d *Daemon, defaultPoolName string, d
 
 		// If the snapshots directory for that container is empty,
 		// remove it.
-		isEmpty, err := shared.PathIsEmpty(oldSnapshotMntPoint)
+		isEmpty, _ := shared.PathIsEmpty(oldSnapshotMntPoint)
 		if isEmpty {
 			os.Remove(oldSnapshotMntPoint)
 			continue
@@ -841,13 +841,10 @@ func upgradeFromStorageTypeLvm(name string, d *Daemon, defaultPoolName string, d
 		poolConfig["volume.block.mount_options"] = fsMntOpts
 	}
 
-	thinPoolName := "LXDPool"
 	poolConfig["lvm.thinpool_name"] = daemonConfig["storage.lvm_thinpool_name"].Get()
-	if poolConfig["lvm.thinpool_name"] != "" {
-		thinPoolName = poolConfig["lvm.thinpool_name"]
-	} else {
+	if poolConfig["lvm.thinpool_name"] == "" {
 		// If empty we need to set it to the old default.
-		poolConfig["lvm.thinpool_name"] = thinPoolName
+		poolConfig["lvm.thinpool_name"] = "LXDPool"
 	}
 
 	poolConfig["lvm.vg_name"] = daemonConfig["storage.lvm_vg_name"].Get()
diff --git a/lxd/profiles_test.go b/lxd/profiles_test.go
index 43227b64f..b609da126 100644
--- a/lxd/profiles_test.go
+++ b/lxd/profiles_test.go
@@ -17,7 +17,12 @@ func Test_removing_a_profile_deletes_associated_configuration_entries(t *testing
 		t.Fatal(err)
 	}
 	defer os.RemoveAll(d.os.VarDir)
+
 	err = initializeDbObject(d)
+	if err != nil {
+		t.Fatal(err)
+	}
+
 	db = d.db.DB()
 
 	// Insert a container and a related profile. Dont't forget that the profile
diff --git a/lxd/storage_ceph_utils.go b/lxd/storage_ceph_utils.go
index b562b0780..22017c67b 100644
--- a/lxd/storage_ceph_utils.go
+++ b/lxd/storage_ceph_utils.go
@@ -783,7 +783,7 @@ func (s *storageCeph) copyWithoutSnapshotsSparse(target container,
 	sourceContainerName := source.Name()
 	targetContainerName := target.Name()
 	sourceContainerOnlyName := sourceContainerName
-	sourceSnapshotOnlyName := sourceContainerName
+	sourceSnapshotOnlyName := ""
 	snapshotName := fmt.Sprintf("zombie_snapshot_%s",
 		uuid.NewRandom().String())
 	if sourceIsSnapshot {
diff --git a/lxd/storage_lvm.go b/lxd/storage_lvm.go
index 4a1bc0383..6e0937962 100644
--- a/lxd/storage_lvm.go
+++ b/lxd/storage_lvm.go
@@ -111,9 +111,9 @@ func (s *storageLvm) StoragePoolCreate() error {
 	s.pool.Config["volatile.initial_source"] = s.pool.Config["source"]
 
 	var globalErr error
+	var pvExisted bool
+	var vgExisted bool
 	tryUndo := true
-	pvExisted := false
-	vgExisted := false
 	poolName := s.getOnDiskPoolName()
 	source := s.pool.Config["source"]
 	// must be initialized
diff --git a/lxd/storage_lvm_utils.go b/lxd/storage_lvm_utils.go
index 05ca8f37e..3eed137a9 100644
--- a/lxd/storage_lvm_utils.go
+++ b/lxd/storage_lvm_utils.go
@@ -783,10 +783,9 @@ func lvmCreateLv(vgName string, thinPoolName string, lvName string, lvFsType str
 	var output string
 	var err error
 
-	targetVg := vgName
 	lvmPoolVolumeName := getPrefixedLvName(volumeType, lvName)
 	if makeThinLv {
-		targetVg = fmt.Sprintf("%s/%s", vgName, thinPoolName)
+		targetVg := fmt.Sprintf("%s/%s", vgName, thinPoolName)
 		output, err = shared.TryRunCommand("lvcreate", "--thin", "-n", lvmPoolVolumeName, "--virtualsize", lvSize+"B", targetVg)
 	} else {
 		output, err = shared.TryRunCommand("lvcreate", "-n", lvmPoolVolumeName, "--size", lvSize+"B", vgName)
diff --git a/lxd/storage_pools.go b/lxd/storage_pools.go
index 9580347c1..b08e0125a 100644
--- a/lxd/storage_pools.go
+++ b/lxd/storage_pools.go
@@ -211,6 +211,10 @@ func storagePoolDelete(d *Daemon, r *http.Request) Response {
 	// Check if the storage pool has any volumes associated with it, if so
 	// error out.
 	volumeCount, err := d.db.StoragePoolVolumesGetNames(poolID)
+	if err != nil {
+		return InternalError(err)
+	}
+
 	if volumeCount > 0 {
 		return BadRequest(fmt.Errorf("storage pool \"%s\" has volumes attached to it", poolName))
 	}
@@ -220,6 +224,7 @@ func storagePoolDelete(d *Daemon, r *http.Request) Response {
 	if err != nil {
 		return SmartError(err)
 	}
+
 	if len(profiles) > 0 {
 		return BadRequest(fmt.Errorf("Storage pool \"%s\" has profiles using it:\n%s", poolName, strings.Join(profiles, "\n")))
 	}
diff --git a/lxd/storage_utils.go b/lxd/storage_utils.go
index 62243c290..923980aee 100644
--- a/lxd/storage_utils.go
+++ b/lxd/storage_utils.go
@@ -253,29 +253,30 @@ func growFileSystem(fsType string, devPath string, mntpoint string) error {
 }
 
 func shrinkFileSystem(fsType string, devPath string, mntpoint string, byteSize int64) error {
-	var msg string
-	var err error
 	strSize := fmt.Sprintf("%dK", byteSize/1024)
+
 	switch fsType {
 	case "": // if not specified, default to ext4
 		fallthrough
 	case "ext4":
-		msg, err = shared.TryRunCommand("e2fsck", "-f", "-y", devPath)
+		_, err := shared.TryRunCommand("e2fsck", "-f", "-y", devPath)
+		if err != nil {
+			return err
+		}
+
+		_, err = shared.TryRunCommand("resize2fs", devPath, strSize)
 		if err != nil {
 			return err
 		}
-		msg, err = shared.TryRunCommand("resize2fs", devPath, strSize)
 	case "btrfs":
-		msg, err = shared.TryRunCommand("btrfs", "filesystem", "resize", strSize, mntpoint)
+		_, err := shared.TryRunCommand("btrfs", "filesystem", "resize", strSize, mntpoint)
+		if err != nil {
+			return err
+		}
 	default:
 		return fmt.Errorf(`Shrinking not supported for filesystem type "%s"`, fsType)
 	}
 
-	if err != nil {
-		errorMsg := fmt.Sprintf(`Could not reduce underlying %s filesystem for "%s": %s`, fsType, devPath, msg)
-		logger.Errorf(errorMsg)
-		return fmt.Errorf(errorMsg)
-	}
 	return nil
 }
 
diff --git a/lxd/storage_zfs.go b/lxd/storage_zfs.go
index fc92bbc1e..d8eaab5f0 100644
--- a/lxd/storage_zfs.go
+++ b/lxd/storage_zfs.go
@@ -1111,7 +1111,7 @@ func (s *storageZfs) copyWithoutSnapshotFull(target container, source container)
 
 	targetName := target.Name()
 	targetDataset := fmt.Sprintf("%s/containers/%s", poolName, targetName)
-	targetSnapshotDataset := targetDataset
+	targetSnapshotDataset := ""
 
 	if sourceIsSnapshot {
 		sourceParentName, sourceSnapOnlyName, _ := containerGetParentAndSnapshotName(source.Name())
@@ -1272,8 +1272,14 @@ func (s *storageZfs) ContainerCopy(target container, source container, container
 	if containerOnly || len(snapshots) == 0 {
 		if s.pool.Config["zfs.clone_copy"] != "" && !shared.IsTrue(s.pool.Config["zfs.clone_copy"]) {
 			err = s.copyWithoutSnapshotFull(target, source)
+			if err != nil {
+				return err
+			}
 		} else {
 			err = s.copyWithoutSnapshotsSparse(target, source)
+			if err != nil {
+				return err
+			}
 		}
 	} else {
 		targetContainerName := target.Name()
diff --git a/shared/ioprogress/tracker.go b/shared/ioprogress/tracker.go
index ad790890f..494f4b66c 100644
--- a/shared/ioprogress/tracker.go
+++ b/shared/ioprogress/tracker.go
@@ -58,7 +58,7 @@ func (pt *ProgressTracker) update(n int) {
 	}
 
 	// Determine progress
-	progressInt := int64(0)
+	var progressInt int64
 	if pt.Length > 0 {
 		pt.percentage = percentage
 		progressInt = int64(1 - (int(percentage) % 1) + int(percentage))
diff --git a/shared/simplestreams/simplestreams.go b/shared/simplestreams/simplestreams.go
index 322f4fffe..5edb78d7b 100644
--- a/shared/simplestreams/simplestreams.go
+++ b/shared/simplestreams/simplestreams.go
@@ -142,12 +142,12 @@ func (s *SimpleStreamsManifest) ToLXD() ([]api.Image, map[string][][]string) {
 				continue
 			}
 
+			var rootfsSize int64
 			metaPath := meta.Path
 			metaHash := meta.HashSha256
 			metaSize := meta.Size
 			rootfsPath := ""
 			rootfsHash := ""
-			rootfsSize := int64(0)
 			fields := strings.Split(meta.Path, "/")
 			filename := fields[len(fields)-1]
 			size := meta.Size

From 9112b452957f94e0db63dea70244dc9addf0e2e7 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Graber?= <stgraber at ubuntu.com>
Date: Thu, 9 Nov 2017 17:29:04 -0500
Subject: [PATCH 4/4] tests: Add test for unused variables
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Signed-off-by: Stéphane Graber <stgraber at ubuntu.com>
---
 test/suites/static_analysis.sh | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/test/suites/static_analysis.sh b/test/suites/static_analysis.sh
index 5f6edab15..b0d8672ce 100644
--- a/test/suites/static_analysis.sh
+++ b/test/suites/static_analysis.sh
@@ -82,6 +82,11 @@ test_static_analysis() {
       fi
     fi
 
+    ## ineffassign
+    if which ineffassign >/dev/null 2>&1; then
+      ineffassign ./
+    fi
+
     # Skip the tests which require git
     if ! git status; then
       return


More information about the lxc-devel mailing list