[lxc-devel] [lxd/master] Cleanups (golint and scripts)
stgraber on Github
lxc-bot at linuxcontainers.org
Sat Feb 17 05:03:24 UTC 2018
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/20180217/f239d5cf/attachment.bin>
-------------- next part --------------
From 5e40c98e1679523cfb936b93a7eedcc72bbe2d49 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Graber?= <stgraber at ubuntu.com>
Date: Fri, 16 Feb 2018 21:39:55 -0500
Subject: [PATCH 1/8] vagrant: Remove vagrant integration (outdated)
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>
---
Vagrantfile | 14 --------------
scripts/vagrant/install-go.sh | 15 ---------------
scripts/vagrant/install-lxd.sh | 41 -----------------------------------------
3 files changed, 70 deletions(-)
delete mode 100644 Vagrantfile
delete mode 100644 scripts/vagrant/install-go.sh
delete mode 100644 scripts/vagrant/install-lxd.sh
diff --git a/Vagrantfile b/Vagrantfile
deleted file mode 100644
index 4d186e490..000000000
--- a/Vagrantfile
+++ /dev/null
@@ -1,14 +0,0 @@
-Vagrant.configure('2') do |config|
- # grab Ubuntu 14.04 boxcutter image: https://atlas.hashicorp.com/boxcutter
- config.vm.box = "boxcutter/ubuntu1404" # Ubuntu 14.04
-
- # fix issues with slow dns https://www.virtualbox.org/ticket/13002
- config.vm.provider :virtualbox do |vb, override|
- vb.customize ["modifyvm", :id, "--natdnsproxy1", "off"]
- end
-
- config.vm.network "forwarded_port", guest: 443, host: 8443
- config.vm.provision :shell, :privileged => false, :path => "scripts/vagrant/install-go.sh"
- config.vm.provision :shell, :privileged => false, :path => "scripts/vagrant/install-lxd.sh"
-
-end
diff --git a/scripts/vagrant/install-go.sh b/scripts/vagrant/install-go.sh
deleted file mode 100644
index a1ca00e49..000000000
--- a/scripts/vagrant/install-go.sh
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/bin/bash
-
-set -xe
-export DEBIAN_FRONTEND=noninteractive
-
-sudo apt-get update
-which go || sudo apt-get install -y golang
-
-[ -e $HOME/go ] || mkdir -p $HOME/go
-
-cat << 'EOF' | sudo tee /etc/profile.d/S99go.sh
-export GOPATH=$HOME/go
-export PATH=$PATH:$GOPATH/bin
-EOF
-
diff --git a/scripts/vagrant/install-lxd.sh b/scripts/vagrant/install-lxd.sh
deleted file mode 100644
index d2fee6e34..000000000
--- a/scripts/vagrant/install-lxd.sh
+++ /dev/null
@@ -1,41 +0,0 @@
-#!/bin/bash
-
-set -xe
-export DEBIAN_FRONTEND=noninteractive
-
-# install runtime dependencies
-sudo apt-get -y install xz-utils tar acl curl gettext \
- jq sqlite3
-
-# install build dependencies
-sudo apt-get -y install lxc lxc-dev mercurial git pkg-config \
- protobuf-compiler golang-goprotobuf-dev squashfs-tools
-
-# setup env
-[ -e uid_gid_setup ] || \
- echo "root:1000000:65536" | sudo tee -a /etc/subuid /etc/subgid && \
- touch uid_gid_setup
-
-
-go get github.com/lxc/lxd
-cd $GOPATH/src/github.com/lxc/lxd
-go get -v -d ./...
-make
-
-
-cat << 'EOF' | sudo tee /etc/init/lxd.conf
-description "LXD daemon"
-author "John Brooker"
-
-start on filesystem or runlevel [2345]
-stop on shutdown
-
-script
-
- exec /home/vagrant/go/bin/lxd --group vagrant
-
-end script
-
-EOF
-
-sudo service lxd start
From d717267dfd3474db053de09e68b5b0ee6d4afcb4 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Graber?= <stgraber at ubuntu.com>
Date: Fri, 16 Feb 2018 21:40:53 -0500
Subject: [PATCH 2/8] Move bash completion under scripts
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>
---
{config => scripts}/bash/lxd-client | 0
1 file changed, 0 insertions(+), 0 deletions(-)
rename {config => scripts}/bash/lxd-client (100%)
diff --git a/config/bash/lxd-client b/scripts/bash/lxd-client
similarity index 100%
rename from config/bash/lxd-client
rename to scripts/bash/lxd-client
From 26479adcaf2af5affa5967bf50aeb30d8dedd108 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Graber?= <stgraber at ubuntu.com>
Date: Fri, 16 Feb 2018 21:50:38 -0500
Subject: [PATCH 3/8] lxc: Fix golint
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.go | 2 +-
lxc/console.go | 8 ++++----
lxc/copy.go | 2 +-
lxc/file.go | 16 ++++++++--------
lxc/image.go | 12 ++++++------
lxc/info.go | 10 +++++-----
lxc/init.go | 14 +++++++-------
lxc/list.go | 16 ++++++++--------
lxc/utils.go | 38 +++++++++++++++++++-------------------
9 files changed, 59 insertions(+), 59 deletions(-)
diff --git a/lxc/config.go b/lxc/config.go
index bf23d4c7b..68b7b604c 100644
--- a/lxc/config.go
+++ b/lxc/config.go
@@ -403,7 +403,7 @@ func (c *configCmd) run(conf *config.Config, args []string) error {
i18n.G("COMMON NAME"),
i18n.G("ISSUE DATE"),
i18n.G("EXPIRY DATE")})
- sort.Sort(StringList(data))
+ sort.Sort(stringList(data))
table.AppendBulk(data)
table.Render()
diff --git a/lxc/console.go b/lxc/console.go
index 4c08298ab..ff05a78be 100644
--- a/lxc/console.go
+++ b/lxc/console.go
@@ -67,12 +67,12 @@ func (c *consoleCmd) sendTermSize(control *websocket.Conn) error {
return err
}
-type ReadWriteCloser struct {
+type readWriteCloser struct {
io.Reader
io.WriteCloser
}
-type StdinMirror struct {
+type stdinMirror struct {
r io.Reader
consoleDisconnect chan<- bool
foundEscape *bool
@@ -80,7 +80,7 @@ type StdinMirror struct {
// The pty has been switched to raw mode so we will only ever read a single
// byte. The buffer size is therefore uninteresting to us.
-func (er StdinMirror) Read(p []byte) (int, error) {
+func (er stdinMirror) Read(p []byte) (int, error) {
n, err := er.r.Read(p)
v := rune(p[0])
@@ -159,7 +159,7 @@ func (c *consoleCmd) run(conf *config.Config, args []string) error {
sendDisconnect := make(chan bool)
defer close(sendDisconnect)
consoleArgs := lxd.ContainerConsoleArgs{
- Terminal: &ReadWriteCloser{StdinMirror{os.Stdin,
+ Terminal: &readWriteCloser{stdinMirror{os.Stdin,
sendDisconnect, new(bool)}, os.Stdout},
Control: handler,
ConsoleDisconnect: consoleDisconnect,
diff --git a/lxc/copy.go b/lxc/copy.go
index 31392c7df..85acaeb63 100644
--- a/lxc/copy.go
+++ b/lxc/copy.go
@@ -195,7 +195,7 @@ func (c *copyCmd) copyContainer(conf *config.Config, sourceResource string,
}
// Watch the background operation
- progress := ProgressRenderer{Format: i18n.G("Transferring container: %s")}
+ progress := progressRenderer{Format: i18n.G("Transferring container: %s")}
_, err = op.AddHandler(progress.UpdateOp)
if err != nil {
progress.Done("")
diff --git a/lxc/file.go b/lxc/file.go
index 600a8ada7..d3e127fe4 100644
--- a/lxc/file.go
+++ b/lxc/file.go
@@ -238,7 +238,7 @@ func (c *fileCmd) recursiveMkdir(d lxd.ContainerServer, container string, p stri
return nil
}
-func (c *fileCmd) push(conf *config.Config, send_file_perms bool, args []string) error {
+func (c *fileCmd) push(conf *config.Config, sendFilePerms bool, args []string) error {
if len(args) < 2 {
return errArgs
}
@@ -369,14 +369,14 @@ func (c *fileCmd) push(conf *config.Config, send_file_perms bool, args []string)
return err
}
- _, dUid, dGid := shared.GetOwnerMode(finfo)
+ _, dUID, dGID := shared.GetOwnerMode(finfo)
if c.uid == -1 || c.gid == -1 {
if c.uid == -1 {
- uid = dUid
+ uid = dUID
}
if c.gid == -1 {
- gid = dGid
+ gid = dGID
}
}
@@ -393,14 +393,14 @@ func (c *fileCmd) push(conf *config.Config, send_file_perms bool, args []string)
Mode: -1,
}
- if send_file_perms {
+ if sendFilePerms {
if c.mode == "" || c.uid == -1 || c.gid == -1 {
finfo, err := f.Stat()
if err != nil {
return err
}
- fMode, fUid, fGid := shared.GetOwnerMode(finfo)
+ fMode, fUID, fGID := shared.GetOwnerMode(finfo)
if err != nil {
return err
}
@@ -410,11 +410,11 @@ func (c *fileCmd) push(conf *config.Config, send_file_perms bool, args []string)
}
if c.uid == -1 {
- uid = fUid
+ uid = fUID
}
if c.gid == -1 {
- gid = fGid
+ gid = fGID
}
}
diff --git a/lxc/image.go b/lxc/image.go
index 78b90cd33..eaccbb231 100644
--- a/lxc/image.go
+++ b/lxc/image.go
@@ -445,7 +445,7 @@ func (c *imageCmd) run(conf *config.Config, args []string) error {
}
// Register progress handler
- progress := ProgressRenderer{Format: i18n.G("Copying the image: %s")}
+ progress := progressRenderer{Format: i18n.G("Copying the image: %s")}
_, err = op.AddHandler(progress.UpdateOp)
if err != nil {
progress.Done("")
@@ -525,7 +525,7 @@ func (c *imageCmd) run(conf *config.Config, args []string) error {
}
image := c.dereferenceAlias(d, inName)
- progress := ProgressRenderer{Format: i18n.G("Refreshing the image: %s")}
+ progress := progressRenderer{Format: i18n.G("Refreshing the image: %s")}
op, err := d.RefreshImage(image)
if err != nil {
return err
@@ -713,7 +713,7 @@ func (c *imageCmd) run(conf *config.Config, args []string) error {
image.Properties[strings.TrimSpace(fields[0])] = strings.TrimSpace(fields[1])
}
- progress := ProgressRenderer{Format: i18n.G("Transferring image: %s")}
+ progress := progressRenderer{Format: i18n.G("Transferring image: %s")}
if strings.HasPrefix(imageFile, "https://") {
image.Source = &api.ImagesPostSource{}
image.Source.Type = "url"
@@ -918,7 +918,7 @@ func (c *imageCmd) run(conf *config.Config, args []string) error {
defer destRootfs.Close()
// Prepare the download request
- progress := ProgressRenderer{Format: i18n.G("Exporting the image: %s")}
+ progress := progressRenderer{Format: i18n.G("Exporting the image: %s")}
req := lxd.ImageFileRequest{
MetaFile: io.WriteSeeker(dest),
RootfsFile: io.WriteSeeker(destRootfs),
@@ -1065,7 +1065,7 @@ func (c *imageCmd) showImages(images []api.Image, filters []string, columns []im
data = append(data, row)
}
- sort.Sort(StringList(data))
+ sort.Sort(stringList(data))
return data
}
@@ -1135,7 +1135,7 @@ func (c *imageCmd) showAliases(aliases []api.ImageAliasesEntry, filters []string
i18n.G("ALIAS"),
i18n.G("FINGERPRINT"),
i18n.G("DESCRIPTION")})
- sort.Sort(StringList(data))
+ sort.Sort(stringList(data))
table.AppendBulk(data)
table.Render()
diff --git a/lxc/info.go b/lxc/info.go
index fdb9f250d..acb453e2f 100644
--- a/lxc/info.go
+++ b/lxc/info.go
@@ -64,9 +64,9 @@ func (c *infoCmd) run(conf *config.Config, args []string) error {
if cName == "" {
return c.remoteInfo(d)
- } else {
- return c.containerInfo(d, conf.Remotes[remote], cName, c.showLog)
}
+
+ return c.containerInfo(d, conf.Remotes[remote], cName, c.showLog)
}
func (c *infoCmd) remoteInfo(d lxd.ContainerServer) error {
@@ -226,14 +226,14 @@ func (c *infoCmd) containerInfo(d lxd.ContainerServer, remote config.Remote, nam
}
// List snapshots
- first_snapshot := true
+ firstSnapshot := true
snaps, err := d.GetContainerSnapshots(name)
if err != nil {
return nil
}
for _, snap := range snaps {
- if first_snapshot {
+ if firstSnapshot {
fmt.Println(i18n.G("Snapshots:"))
}
@@ -251,7 +251,7 @@ func (c *infoCmd) containerInfo(d lxd.ContainerServer, remote config.Remote, nam
}
fmt.Printf("\n")
- first_snapshot = false
+ firstSnapshot = false
}
if showLog {
diff --git a/lxc/init.go b/lxc/init.go
index b0005e029..4b8fcf3fc 100644
--- a/lxc/init.go
+++ b/lxc/init.go
@@ -86,7 +86,7 @@ Examples:
lxc init ubuntu:16.04 u1`)
}
-func (c *initCmd) is_ephem(s string) bool {
+func (c *initCmd) isEphemeral(s string) bool {
switch s {
case "-e":
return true
@@ -96,7 +96,7 @@ func (c *initCmd) is_ephem(s string) bool {
return false
}
-func (c *initCmd) is_profile(s string) bool {
+func (c *initCmd) isProfile(s string) bool {
switch s {
case "-p":
return true
@@ -106,13 +106,13 @@ func (c *initCmd) is_profile(s string) bool {
return false
}
-func (c *initCmd) massage_args() {
+func (c *initCmd) massageArgs() {
l := len(os.Args)
if l < 2 {
return
}
- if c.is_profile(os.Args[l-1]) {
+ if c.isProfile(os.Args[l-1]) {
initRequestedEmptyProfiles = true
os.Args = os.Args[0 : l-1]
return
@@ -123,7 +123,7 @@ func (c *initCmd) massage_args() {
}
/* catch "lxc init ubuntu -p -e */
- if c.is_ephem(os.Args[l-1]) && c.is_profile(os.Args[l-2]) {
+ if c.isEphemeral(os.Args[l-1]) && c.isProfile(os.Args[l-2]) {
initRequestedEmptyProfiles = true
newargs := os.Args[0 : l-2]
newargs = append(newargs, os.Args[l-1])
@@ -133,7 +133,7 @@ func (c *initCmd) massage_args() {
}
func (c *initCmd) flags() {
- c.massage_args()
+ c.massageArgs()
gnuflag.Var(&c.confArgs, "config", i18n.G("Config key/value to apply to the new container"))
gnuflag.Var(&c.confArgs, "c", i18n.G("Config key/value to apply to the new container"))
gnuflag.Var(&c.profArgs, "profile", i18n.G("Profile to apply to the new container"))
@@ -286,7 +286,7 @@ func (c *initCmd) create(conf *config.Config, args []string) (lxd.ContainerServe
}
// Watch the background operation
- progress := ProgressRenderer{Format: i18n.G("Retrieving image: %s")}
+ progress := progressRenderer{Format: i18n.G("Retrieving image: %s")}
_, err = op.AddHandler(progress.UpdateOp)
if err != nil {
progress.Done("")
diff --git a/lxc/list.go b/lxc/list.go
index 4796af0d4..8dfe9ebeb 100644
--- a/lxc/list.go
+++ b/lxc/list.go
@@ -478,9 +478,9 @@ func (c *listCmd) parseColumns() ([]column, error) {
if c.columnsRaw != "ns46tS" {
// --columns was specified too
return nil, fmt.Errorf("Can't specify --fast with --columns")
- } else {
- c.columnsRaw = "nsacPt"
}
+
+ c.columnsRaw = "nsacPt"
}
columnList := strings.Split(c.columnsRaw, ",")
@@ -587,9 +587,9 @@ func (c *listCmd) IP4ColumnData(cInfo api.Container, cState *api.ContainerState,
}
sort.Sort(sort.Reverse(sort.StringSlice(ipv4s)))
return strings.Join(ipv4s, "\n")
- } else {
- return ""
}
+
+ return ""
}
func (c *listCmd) IP6ColumnData(cInfo api.Container, cState *api.ContainerState, cSnaps []api.ContainerSnapshot) string {
@@ -612,17 +612,17 @@ func (c *listCmd) IP6ColumnData(cInfo api.Container, cState *api.ContainerState,
}
sort.Sort(sort.Reverse(sort.StringSlice(ipv6s)))
return strings.Join(ipv6s, "\n")
- } else {
- return ""
}
+
+ return ""
}
func (c *listCmd) typeColumnData(cInfo api.Container, cState *api.ContainerState, cSnaps []api.ContainerSnapshot) string {
if cInfo.Ephemeral {
return i18n.G("EPHEMERAL")
- } else {
- return i18n.G("PERSISTENT")
}
+
+ return i18n.G("PERSISTENT")
}
func (c *listCmd) numberSnapshotsColumnData(cInfo api.Container, cState *api.ContainerState, cSnaps []api.ContainerSnapshot) string {
diff --git a/lxc/utils.go b/lxc/utils.go
index 802b852d9..97d367249 100644
--- a/lxc/utils.go
+++ b/lxc/utils.go
@@ -27,7 +27,7 @@ const (
)
// Progress tracking
-type ProgressRenderer struct {
+type progressRenderer struct {
Format string
maxLength int
@@ -36,7 +36,7 @@ type ProgressRenderer struct {
lock sync.Mutex
}
-func (p *ProgressRenderer) Done(msg string) {
+func (p *progressRenderer) Done(msg string) {
// Acquire rendering lock
p.lock.Lock()
defer p.lock.Unlock()
@@ -64,7 +64,7 @@ func (p *ProgressRenderer) Done(msg string) {
fmt.Print(msg)
}
-func (p *ProgressRenderer) Update(status string) {
+func (p *progressRenderer) Update(status string) {
// Wait if needed
timeout := p.wait.Sub(time.Now())
if timeout.Seconds() > 0 {
@@ -97,7 +97,7 @@ func (p *ProgressRenderer) Update(status string) {
fmt.Print(msg)
}
-func (p *ProgressRenderer) Warn(status string, timeout time.Duration) {
+func (p *progressRenderer) Warn(status string, timeout time.Duration) {
// Acquire rendering lock
p.lock.Lock()
defer p.lock.Unlock()
@@ -120,11 +120,11 @@ func (p *ProgressRenderer) Warn(status string, timeout time.Duration) {
fmt.Print(msg)
}
-func (p *ProgressRenderer) UpdateProgress(progress ioprogress.ProgressData) {
+func (p *progressRenderer) UpdateProgress(progress ioprogress.ProgressData) {
p.Update(progress.Text)
}
-func (p *ProgressRenderer) UpdateOp(op api.Operation) {
+func (p *progressRenderer) UpdateOp(op api.Operation) {
if op.Metadata == nil {
return
}
@@ -138,17 +138,17 @@ func (p *ProgressRenderer) UpdateOp(op api.Operation) {
}
}
-type StringList [][]string
+type stringList [][]string
-func (a StringList) Len() int {
+func (a stringList) Len() int {
return len(a)
}
-func (a StringList) Swap(i, j int) {
+func (a stringList) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
-func (a StringList) Less(i, j int) bool {
+func (a stringList) Less(i, j int) bool {
x := 0
for x = range a[i] {
if a[i][x] != a[j][x] {
@@ -344,7 +344,7 @@ func profileDeviceAdd(client lxd.ContainerServer, name string, devName string, d
}
// Wait for an operation and cancel it on SIGINT/SIGTERM
-func cancelableWait(op *lxd.RemoteOperation, progress *ProgressRenderer) error {
+func cancelableWait(op *lxd.RemoteOperation, progress *progressRenderer) error {
// Signal handling
chSignal := make(chan os.Signal)
signal.Notify(chSignal, os.Interrupt)
@@ -365,16 +365,16 @@ func cancelableWait(op *lxd.RemoteOperation, progress *ProgressRenderer) error {
err := op.CancelTarget()
if err == nil {
return fmt.Errorf(i18n.G("Remote operation canceled by user"))
- } else {
- count++
+ }
+
+ count++
- if count == 3 {
- return fmt.Errorf(i18n.G("User signaled us three times, exiting. The remote operation will keep running."))
- }
+ if count == 3 {
+ return fmt.Errorf(i18n.G("User signaled us three times, exiting. The remote operation will keep running."))
+ }
- if progress != nil {
- progress.Warn(fmt.Sprintf(i18n.G("%v (interrupt two more times to force)"), err), time.Second*5)
- }
+ if progress != nil {
+ progress.Warn(fmt.Sprintf(i18n.G("%v (interrupt two more times to force)"), err), time.Second*5)
}
}
}
From 69a2f63722db9b04b8b8f20c255d2425ea63b9a0 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Graber?= <stgraber at ubuntu.com>
Date: Fri, 16 Feb 2018 21:52:51 -0500
Subject: [PATCH 4/8] lxd-benchmark: Fix golint
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>
---
lxd-benchmark/main.go | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/lxd-benchmark/main.go b/lxd-benchmark/main.go
index 0472cef6c..50cdfe87d 100644
--- a/lxd-benchmark/main.go
+++ b/lxd-benchmark/main.go
@@ -57,7 +57,7 @@ func run(args []string) error {
return nil
}
- return fmt.Errorf("A valid action (launch, start, stop, delete) must be passed.")
+ return fmt.Errorf("A valid action (launch, start, stop, delete) must be passed")
}
gnuflag.Parse(true)
From 19b8fa5c013015ec048b8dfd15b264cfc3c18373 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Graber?= <stgraber at ubuntu.com>
Date: Fri, 16 Feb 2018 22:43:54 -0500
Subject: [PATCH 5/8] lxd/types: Make golint clean
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>
---
lxd/types/devices.go | 133 +++++----------------------------------------
lxd/types/devices_sort.go | 47 ++++++++++++++++
lxd/types/devices_utils.go | 37 +++++++++++++
3 files changed, 98 insertions(+), 119 deletions(-)
create mode 100644 lxd/types/devices_sort.go
create mode 100644 lxd/types/devices_utils.go
diff --git a/lxd/types/devices.go b/lxd/types/devices.go
index 501455482..3dc683c93 100644
--- a/lxd/types/devices.go
+++ b/lxd/types/devices.go
@@ -6,20 +6,14 @@ import (
"github.com/lxc/lxd/shared"
)
+// Device represents a LXD container device
type Device map[string]string
-type Devices map[string]map[string]string
-
-func (list Devices) ContainsName(k string) bool {
- if list[k] != nil {
- return true
- }
- return false
-}
-func (d Device) get(key string) string {
- return d[key]
-}
+// Devices represents a set of LXD container devices
+type Devices map[string]map[string]string
+// Contains checks if a given device exists in the set and if it's
+// identical to that provided
func (list Devices) Contains(k string, d Device) bool {
// If it didn't exist, it's different
if list[k] == nil {
@@ -31,55 +25,20 @@ func (list Devices) Contains(k string, d Device) bool {
return deviceEquals(old, d)
}
-func deviceEquals(old Device, d Device) bool {
- // Check for any difference and addition/removal of properties
- for k := range d {
- if d[k] != old[k] {
- return false
- }
- }
-
- for k := range old {
- if d[k] != old[k] {
- return false
- }
- }
-
- return true
-}
-
-func deviceEqualsDiffKeys(old Device, d Device) []string {
- keys := []string{}
-
- // Check for any difference and addition/removal of properties
- for k := range d {
- if d[k] != old[k] {
- keys = append(keys, k)
- }
- }
-
- for k := range old {
- if d[k] != old[k] {
- keys = append(keys, k)
- }
- }
-
- return keys
-}
-
-func (old Devices) Update(newlist Devices) (map[string]Device, map[string]Device, map[string]Device, []string) {
+// Update returns the difference between two sets
+func (list Devices) Update(newlist Devices) (map[string]Device, map[string]Device, map[string]Device, []string) {
rmlist := map[string]Device{}
addlist := map[string]Device{}
updatelist := map[string]Device{}
- for key, d := range old {
+ for key, d := range list {
if !newlist.Contains(key, d) {
rmlist[key] = d
}
}
for key, d := range newlist {
- if !old.Contains(key, d) {
+ if !list.Contains(key, d) {
addlist[key] = d
}
}
@@ -117,77 +76,13 @@ func (old Devices) Update(newlist Devices) (map[string]Device, map[string]Device
return rmlist, addlist, updatelist, updateDiff
}
-func (newBaseDevices Devices) ExtendFromProfile(currentFullDevices Devices, newDevicesFromProfile Devices) error {
- // For any entry which exists in a profile and doesn't in the container config, add it
-
- for name, newDev := range newDevicesFromProfile {
- if curDev, ok := currentFullDevices[name]; ok {
- newBaseDevices[name] = curDev
- } else {
- newBaseDevices[name] = newDev
- }
+// DeviceNames returns the name of all devices in the set, sorted properly
+func (list Devices) DeviceNames() []string {
+ sortable := sortableDevices{}
+ for k, d := range list {
+ sortable = append(sortable, namedDevice{k, d})
}
- return nil
-}
-
-type namedDevice struct {
- name string
- device Device
-}
-type sortableDevices []namedDevice
-
-func (devices Devices) toSortable() sortableDevices {
- named := []namedDevice{}
- for k, d := range devices {
- named = append(named, namedDevice{k, d})
- }
-
- return named
-}
-
-func (devices sortableDevices) Len() int {
- return len(devices)
-}
-
-func (devices sortableDevices) Less(i, j int) bool {
- a := devices[i]
- b := devices[j]
-
- // First sort by types
- if a.device["type"] != b.device["type"] {
- return a.device["type"] < b.device["type"]
- }
-
- // Special case disk paths
- if a.device["type"] == "disk" && b.device["type"] == "disk" {
- if a.device["path"] != b.device["path"] {
- return a.device["path"] < b.device["path"]
- }
- }
-
- // Fallback to sorting by names
- return a.name < b.name
-}
-
-func (devices sortableDevices) Swap(i, j int) {
- tmp := devices[i]
- devices[i] = devices[j]
- devices[j] = tmp
-}
-
-func (devices sortableDevices) Names() []string {
- result := []string{}
- for _, d := range devices {
- result = append(result, d.name)
- }
-
- return result
-}
-
-/* DeviceNames returns the device names for this Devices in sorted order */
-func (devices Devices) DeviceNames() []string {
- sortable := devices.toSortable()
sort.Sort(sortable)
return sortable.Names()
}
diff --git a/lxd/types/devices_sort.go b/lxd/types/devices_sort.go
new file mode 100644
index 000000000..359431ee4
--- /dev/null
+++ b/lxd/types/devices_sort.go
@@ -0,0 +1,47 @@
+package types
+
+type namedDevice struct {
+ name string
+ device Device
+}
+
+type sortableDevices []namedDevice
+
+func (devices sortableDevices) Len() int {
+ return len(devices)
+}
+
+func (devices sortableDevices) Less(i, j int) bool {
+ a := devices[i]
+ b := devices[j]
+
+ // First sort by types
+ if a.device["type"] != b.device["type"] {
+ return a.device["type"] < b.device["type"]
+ }
+
+ // Special case disk paths
+ if a.device["type"] == "disk" && b.device["type"] == "disk" {
+ if a.device["path"] != b.device["path"] {
+ return a.device["path"] < b.device["path"]
+ }
+ }
+
+ // Fallback to sorting by names
+ return a.name < b.name
+}
+
+func (devices sortableDevices) Swap(i, j int) {
+ tmp := devices[i]
+ devices[i] = devices[j]
+ devices[j] = tmp
+}
+
+func (devices sortableDevices) Names() []string {
+ result := []string{}
+ for _, d := range devices {
+ result = append(result, d.name)
+ }
+
+ return result
+}
diff --git a/lxd/types/devices_utils.go b/lxd/types/devices_utils.go
new file mode 100644
index 000000000..4ded0ccee
--- /dev/null
+++ b/lxd/types/devices_utils.go
@@ -0,0 +1,37 @@
+package types
+
+func deviceEquals(old Device, d Device) bool {
+ // Check for any difference and addition/removal of properties
+ for k := range d {
+ if d[k] != old[k] {
+ return false
+ }
+ }
+
+ for k := range old {
+ if d[k] != old[k] {
+ return false
+ }
+ }
+
+ return true
+}
+
+func deviceEqualsDiffKeys(old Device, d Device) []string {
+ keys := []string{}
+
+ // Check for any difference and addition/removal of properties
+ for k := range d {
+ if d[k] != old[k] {
+ keys = append(keys, k)
+ }
+ }
+
+ for k := range old {
+ if d[k] != old[k] {
+ keys = append(keys, k)
+ }
+ }
+
+ return keys
+}
From fa75e8ce2c2d90712780a29d95dc4fb23f3756e4 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Graber?= <stgraber at ubuntu.com>
Date: Fri, 16 Feb 2018 23:22:01 -0500
Subject: [PATCH 6/8] lxd/util: Fix golint
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>
---
lxd/resources.go | 2 +-
lxd/util/encryption.go | 3 ++-
lxd/util/fs_32bit.go | 3 +--
lxd/util/fs_64bit.go | 1 +
lxd/util/http.go | 6 ++++++
lxd/util/resources.go | 8 +++++---
lxd/util/sys.go | 3 +++
7 files changed, 19 insertions(+), 7 deletions(-)
diff --git a/lxd/resources.go b/lxd/resources.go
index 66b8fb8f4..509da323c 100644
--- a/lxd/resources.go
+++ b/lxd/resources.go
@@ -14,7 +14,7 @@ import (
func serverResourcesGet(d *Daemon, r *http.Request) Response {
res := api.Resources{}
- cpu, err := util.CpuResource()
+ cpu, err := util.CPUResource()
if err != nil {
return SmartError(err)
}
diff --git a/lxd/util/encryption.go b/lxd/util/encryption.go
index a015bf514..1a70658a2 100644
--- a/lxd/util/encryption.go
+++ b/lxd/util/encryption.go
@@ -8,7 +8,8 @@ import (
"golang.org/x/crypto/scrypt"
)
-func PasswordCheck(secret, password string) error {
+// PasswordCheck validates the provided password against the encoded secret
+func PasswordCheck(secret string, password string) error {
// No password set
if secret == "" {
return fmt.Errorf("No password is set")
diff --git a/lxd/util/fs_32bit.go b/lxd/util/fs_32bit.go
index 9e39f83fb..3747d0e12 100644
--- a/lxd/util/fs_32bit.go
+++ b/lxd/util/fs_32bit.go
@@ -3,7 +3,6 @@
package util
const (
- /* This is really 0x9123683E, go wants us to give it in signed form
- * since we use it as a signed constant. */
+ // FilesystemSuperMagicBtrfs is the 32bit magic for Btrfs (as signed constant)
FilesystemSuperMagicBtrfs = -1859950530
)
diff --git a/lxd/util/fs_64bit.go b/lxd/util/fs_64bit.go
index 9ff591362..88ba4c408 100644
--- a/lxd/util/fs_64bit.go
+++ b/lxd/util/fs_64bit.go
@@ -3,5 +3,6 @@
package util
const (
+ // FilesystemSuperMagicBtrfs is the 64bit magic for Btrfs
FilesystemSuperMagicBtrfs = 0x9123683E
)
diff --git a/lxd/util/http.go b/lxd/util/http.go
index d33c6cb63..2d88ed5aa 100644
--- a/lxd/util/http.go
+++ b/lxd/util/http.go
@@ -25,6 +25,7 @@ import (
"github.com/lxc/lxd/shared/logger"
)
+// WriteJSON encodes the body as JSON and sends it back to the client
func WriteJSON(w http.ResponseWriter, body interface{}, debug bool) error {
var output io.Writer
var captured *bytes.Buffer
@@ -44,6 +45,7 @@ func WriteJSON(w http.ResponseWriter, body interface{}, debug bool) error {
return err
}
+// EtagHash hashes the provided data and returns the sha256
func EtagHash(data interface{}) (string, error) {
etag := sha256.New()
err := json.NewEncoder(etag).Encode(data)
@@ -54,6 +56,8 @@ func EtagHash(data interface{}) (string, error) {
return fmt.Sprintf("%x", etag.Sum(nil)), nil
}
+// EtagCheck validates the hash of the current state with the hash
+// provided by the client
func EtagCheck(r *http.Request, data interface{}) error {
match := r.Header.Get("If-Match")
if match == "" {
@@ -157,6 +161,8 @@ func IsRecursionRequest(r *http.Request) bool {
return recursion == 1
}
+// ListenAddresses returns a list of host:port combinations at which
+// this machine can be reached
func ListenAddresses(value string) ([]string, error) {
addresses := make([]string, 0)
diff --git a/lxd/util/resources.go b/lxd/util/resources.go
index 6487e4f07..708062693 100644
--- a/lxd/util/resources.go
+++ b/lxd/util/resources.go
@@ -157,7 +157,7 @@ func parseCpuinfo() ([]thread, error) {
return threads, err
}
-func parseSysDevSystemCpu() ([]thread, error) {
+func parseSysDevSystemCPU() ([]thread, error) {
ents, err := ioutil.ReadDir("/sys/devices/system/cpu/")
if err != nil {
return nil, err
@@ -230,7 +230,7 @@ func getThreads() ([]thread, error) {
return threads, nil
}
- threads, err = parseSysDevSystemCpu()
+ threads, err = parseSysDevSystemCPU()
if err != nil {
return nil, err
}
@@ -238,7 +238,8 @@ func getThreads() ([]thread, error) {
return threads, nil
}
-func CpuResource() (*api.ResourcesCPU, error) {
+// CPUResource returns the system CPU information
+func CPUResource() (*api.ResourcesCPU, error) {
c := api.ResourcesCPU{}
threads, err := getThreads()
@@ -271,6 +272,7 @@ func CpuResource() (*api.ResourcesCPU, error) {
return &c, nil
}
+// MemoryResource returns the system memory information
func MemoryResource() (*api.ResourcesMemory, error) {
var buffers uint64
var cached uint64
diff --git a/lxd/util/sys.go b/lxd/util/sys.go
index 24a4c222c..cb6498223 100644
--- a/lxd/util/sys.go
+++ b/lxd/util/sys.go
@@ -83,6 +83,8 @@ func GetIdmapSet() *idmap.IdmapSet {
return idmapSet
}
+// RuntimeLiblxcVersionAtLeast checks if the system's liblxc matches the
+// provided version requirement
func RuntimeLiblxcVersionAtLeast(major int, minor int, micro int) bool {
version := golxc.Version()
version = strings.Replace(version, " (devel)", "-devel", 1)
@@ -151,6 +153,7 @@ func RuntimeLiblxcVersionAtLeast(major int, minor int, micro int) bool {
return true
}
+// GetExecPath returns the path to the current binary
func GetExecPath() string {
execPath := os.Getenv("LXD_EXEC_PATH")
if execPath != "" {
From 032e095bfacab6f72dea3f8343f60bda8d6f94e7 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Graber?= <stgraber at ubuntu.com>
Date: Fri, 16 Feb 2018 23:30:44 -0500
Subject: [PATCH 7/8] test/macaroon-identity: Fix golint
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/macaroon-identity/auth.go | 22 +++++++++++-----------
test/macaroon-identity/credentials.go | 12 ++++++------
test/macaroon-identity/http.go | 10 +++++-----
test/macaroon-identity/main.go | 2 +-
4 files changed, 23 insertions(+), 23 deletions(-)
diff --git a/test/macaroon-identity/auth.go b/test/macaroon-identity/auth.go
index b062455c9..3711b8632 100644
--- a/test/macaroon-identity/auth.go
+++ b/test/macaroon-identity/auth.go
@@ -24,29 +24,29 @@ type loginResponse struct {
}
// AuthService is an HTTP service for authentication using macaroons.
-type AuthService struct {
- HTTPService
+type authService struct {
+ httpService
KeyPair *bakery.KeyPair
- Checker CredentialsChecker
+ Checker credentialsChecker
userTokens map[string]string // map user token to username
uuidGenerator *fastuuid.Generator
}
// NewAuthService returns an AuthService
-func NewAuthService(listenAddr string, logger *log.Logger) *AuthService {
+func newAuthService(listenAddr string, logger *log.Logger) *authService {
key := bakery.MustGenerateKey()
mux := http.NewServeMux()
- s := AuthService{
- HTTPService: HTTPService{
+ s := authService{
+ httpService: httpService{
Name: "auth",
ListenAddr: listenAddr,
Logger: logger,
Mux: mux,
},
KeyPair: key,
- Checker: NewCredentialsChecker(),
+ Checker: newCredentialsChecker(),
uuidGenerator: fastuuid.MustNewGenerator(),
userTokens: map[string]string{},
}
@@ -61,7 +61,7 @@ func NewAuthService(listenAddr string, logger *log.Logger) *AuthService {
return &s
}
-func (s *AuthService) thirdPartyChecker(ctx context.Context, req *http.Request, info *bakery.ThirdPartyCaveatInfo, token *httpbakery.DischargeToken) ([]checkers.Caveat, error) {
+func (s *authService) thirdPartyChecker(ctx context.Context, req *http.Request, info *bakery.ThirdPartyCaveatInfo, token *httpbakery.DischargeToken) ([]checkers.Caveat, error) {
if token == nil {
err := httpbakery.NewInteractionRequiredError(nil, req)
err.SetInteraction("form", form.InteractionInfo{URL: formURL})
@@ -84,7 +84,7 @@ func (s *AuthService) thirdPartyChecker(ctx context.Context, req *http.Request,
}, nil
}
-func (s *AuthService) formHandler(w http.ResponseWriter, req *http.Request) {
+func (s *authService) formHandler(w http.ResponseWriter, req *http.Request) {
s.LogRequest(req)
switch req.Method {
case "GET":
@@ -130,7 +130,7 @@ func (s *AuthService) formHandler(w http.ResponseWriter, req *http.Request) {
}
}
-func (s *AuthService) getRandomToken() string {
+func (s *authService) getRandomToken() string {
uuid := make([]byte, 24)
for i, b := range s.uuidGenerator.Next() {
uuid[i] = b
@@ -138,6 +138,6 @@ func (s *AuthService) getRandomToken() string {
return base64.StdEncoding.EncodeToString(uuid)
}
-func (s *AuthService) bakeryFail(w http.ResponseWriter, msg string, args ...interface{}) {
+func (s *authService) bakeryFail(w http.ResponseWriter, msg string, args ...interface{}) {
httpbakery.WriteError(context.TODO(), w, fmt.Errorf(msg, args...))
}
diff --git a/test/macaroon-identity/credentials.go b/test/macaroon-identity/credentials.go
index 4801dc816..488593fe9 100644
--- a/test/macaroon-identity/credentials.go
+++ b/test/macaroon-identity/credentials.go
@@ -6,15 +6,15 @@ import (
"os"
)
-type CredentialsChecker struct {
+type credentialsChecker struct {
creds map[string]string
}
-func NewCredentialsChecker() CredentialsChecker {
- return CredentialsChecker{creds: map[string]string{}}
+func newCredentialsChecker() credentialsChecker {
+ return credentialsChecker{creds: map[string]string{}}
}
-func (c *CredentialsChecker) Check(form interface{}) bool {
+func (c *credentialsChecker) Check(form interface{}) bool {
m := form.(map[string]interface{})
username := m["username"].(string)
password := m["password"].(string)
@@ -22,13 +22,13 @@ func (c *CredentialsChecker) Check(form interface{}) bool {
return ok && pass == password
}
-func (c *CredentialsChecker) AddCreds(creds map[string]string) {
+func (c *credentialsChecker) AddCreds(creds map[string]string) {
for user, pass := range creds {
c.creds[user] = pass
}
}
-func (c *CredentialsChecker) LoadCreds(csvFile string) error {
+func (c *credentialsChecker) LoadCreds(csvFile string) error {
f, err := os.Open(csvFile)
if err != nil {
return err
diff --git a/test/macaroon-identity/http.go b/test/macaroon-identity/http.go
index c74fbf10c..f3be4b97b 100644
--- a/test/macaroon-identity/http.go
+++ b/test/macaroon-identity/http.go
@@ -7,7 +7,7 @@ import (
"net/http"
)
-type HTTPService struct {
+type httpService struct {
Name string
ListenAddr string
Logger *log.Logger
@@ -16,7 +16,7 @@ type HTTPService struct {
listener net.Listener
}
-func (s *HTTPService) Endpoint() string {
+func (s *httpService) Endpoint() string {
if s.listener == nil {
return ""
}
@@ -24,7 +24,7 @@ func (s *HTTPService) Endpoint() string {
return "http://" + s.listener.Addr().String()
}
-func (s *HTTPService) Start(background bool) error {
+func (s *httpService) Start(background bool) error {
listener, err := net.Listen("tcp", s.ListenAddr)
if err != nil {
return err
@@ -47,11 +47,11 @@ func (s *HTTPService) Start(background bool) error {
return nil
}
-func (s *HTTPService) LogRequest(req *http.Request) {
+func (s *httpService) LogRequest(req *http.Request) {
s.Logger.Printf("%s - %s %s", s.Name, req.Method, req.URL.Path)
}
// Fail returns an HTTP error with the specified message
-func (s *HTTPService) Fail(w http.ResponseWriter, code int, msg string, args ...interface{}) {
+func (s *httpService) Fail(w http.ResponseWriter, code int, msg string, args ...interface{}) {
http.Error(w, fmt.Sprintf(msg, args...), code)
}
diff --git a/test/macaroon-identity/main.go b/test/macaroon-identity/main.go
index babf449c3..0cde7d385 100644
--- a/test/macaroon-identity/main.go
+++ b/test/macaroon-identity/main.go
@@ -14,7 +14,7 @@ type flags struct {
func main() {
flags := parseFlags()
logger := log.New(os.Stdout, "", log.Ldate|log.Ltime)
- s := NewAuthService(flags.Endpoint, logger)
+ s := newAuthService(flags.Endpoint, logger)
if err := s.Checker.LoadCreds(flags.CredsFile); err != nil {
panic(err)
}
From f5d7ac8c4fd38836d700cff770d956b2bdf8e842 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Graber?= <stgraber at ubuntu.com>
Date: Sat, 17 Feb 2018 00:01:45 -0500
Subject: [PATCH 8/8] tests: Update list of golint clean packages
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 | 29 ++++++++++++++++++++++++++++-
1 file changed, 28 insertions(+), 1 deletion(-)
diff --git a/test/suites/static_analysis.sh b/test/suites/static_analysis.sh
index 91c3ab5a6..04a3a3921 100644
--- a/test/suites/static_analysis.sh
+++ b/test/suites/static_analysis.sh
@@ -56,19 +56,46 @@ test_static_analysis() {
## golint
if which golint >/dev/null 2>&1; then
golint -set_exit_status client/
+
+ golint -set_exit_status fuidshift/
+
+ golint -set_exit_status lxc/
golint -set_exit_status lxc/config/
- golint -set_exit_status lxd/template/
+
+ golint -set_exit_status lxd-benchmark
+ golint -set_exit_status lxd-benchmark/benchmark
+
+ golint -set_exit_status lxd/config
+ golint -set_exit_status lxd/db/node
+ golint -set_exit_status lxd/db/query
+ golint -set_exit_status lxd/db/schema
+ golint -set_exit_status lxd/debug
+ golint -set_exit_status lxd/endpoints
+ golint -set_exit_status lxd/maas
+ golint -set_exit_status lxd/node
+ golint -set_exit_status lxd/sqlite
+ golint -set_exit_status lxd/state
+ golint -set_exit_status lxd/sys
+ golint -set_exit_status lxd/task
+ golint -set_exit_status lxd/template
+ golint -set_exit_status lxd/types
+ golint -set_exit_status lxd/util
+
golint -set_exit_status shared/api/
golint -set_exit_status shared/cancel/
golint -set_exit_status shared/cmd/
golint -set_exit_status shared/gnuflag/
golint -set_exit_status shared/i18n/
golint -set_exit_status shared/ioprogress/
+ golint -set_exit_status shared/log15/stack
golint -set_exit_status shared/logger/
golint -set_exit_status shared/logging/
+ golint -set_exit_status shared/subtest/
golint -set_exit_status shared/termios/
golint -set_exit_status shared/version/
+
golint -set_exit_status test/deps/
+ golint -set_exit_status test/macaroon-identity
fi
## deadcode
More information about the lxc-devel
mailing list