From adae817ae74b8e5b41c648df4f6b65dbfcdffe78 Mon Sep 17 00:00:00 2001 From: oothman Date: Fri, 24 Dec 2021 00:18:25 +0100 Subject: [PATCH] Upgrade the bmclib dependency (to v0.4.14). Also ran `gofumpt -l -w`. --- cmd/create.go | 4 +- cmd/root.go | 8 +- go.mod | 2 +- go.sum | 15 + internal/notification/notification.go | 4 +- internal/stats/stats.go | 8 +- resolver/resolver.go | 4 +- resource/response.go | 6 +- .../github.com/GeertJohan/go.rice/appended.go | 5 + vendor/github.com/GeertJohan/go.rice/box.go | 1 - .../github.com/GeertJohan/go.rice/embedded.go | 4 +- .../github.com/GeertJohan/go.rice/virtual.go | 4 - vendor/github.com/GeertJohan/go.rice/walk.go | 8 - .../bmclib/cfgresources/cfgresources.go | 83 ++- .../bmclib/cfgresources/supermicro.go | 1 - .../bmc-toolbox/bmclib/devices/interfaces.go | 10 +- .../bmc-toolbox/bmclib/discover/discover.go | 17 +- .../bmc-toolbox/bmclib/discover/probe.go | 40 +- .../bmc-toolbox/bmclib/errors/errors.go | 21 + .../bmc-toolbox/bmclib/internal/utils.go | 42 +- .../bmc-toolbox/bmclib/providers/dell/dell.go | 6 +- .../bmclib/providers/dell/idrac8/actions.go | 35 +- .../bmclib/providers/dell/idrac8/configure.go | 549 +++++++++++------- .../bmclib/providers/dell/idrac8/helpers.go | 94 --- .../bmclib/providers/dell/idrac8/idrac8.go | 130 +++-- .../bmclib/providers/dell/idrac8/model.go | 19 +- .../bmclib/providers/dell/idrac8/query.go | 71 +-- .../providers/dell/idrac8/setupConnections.go | 13 +- .../bmclib/providers/dell/idrac9/actions.go | 36 +- .../bmclib/providers/dell/idrac9/configure.go | 451 +++++++------- .../bmclib/providers/dell/idrac9/helpers.go | 249 +++----- .../bmclib/providers/dell/idrac9/idrac.go | 42 +- .../bmclib/providers/dell/idrac9/idrac9.go | 124 ++-- .../bmclib/providers/dell/idrac9/model.go | 85 ++- .../providers/dell/idrac9/model_odata.go | 12 +- .../bmclib/providers/dell/idrac9/query.go | 89 +-- .../providers/dell/idrac9/redfish_helpers.go | 65 +-- .../providers/dell/idrac9/setupConnections.go | 30 +- .../bmclib/providers/dell/m1000e/actions.go | 13 +- .../bmclib/providers/dell/m1000e/configure.go | 42 +- .../providers/dell/m1000e/constructors.go | 26 +- .../bmclib/providers/dell/m1000e/m1000e.go | 25 +- .../bmclib/providers/dell/m1000e/model.go | 244 ++++---- .../bmclib/providers/dummy/ibmc/configure.go | 4 +- .../bmclib/providers/dummy/ibmc/ibmc.go | 13 +- .../bmclib/providers/hp/c7000/actions.go | 34 +- .../bmclib/providers/hp/c7000/c7000.go | 2 +- .../bmclib/providers/hp/c7000/configure.go | 341 ++++++----- .../providers/hp/c7000/setupConnections.go | 6 +- .../bmclib/providers/hp/c7000/xmlhelpers.go | 18 +- .../bmclib/providers/hp/c7000/xmlmodel.go | 2 +- .../bmclib/providers/hp/ilo/actions.go | 24 +- .../bmclib/providers/hp/ilo/configure.go | 467 ++++++++------- .../bmclib/providers/hp/ilo/helpers.go | 8 - .../bmclib/providers/hp/ilo/ilo.go | 251 +++++--- .../bmclib/providers/hp/ilo/model.go | 20 +- .../bmclib/providers/hp/ilo/query.go | 186 +++--- .../providers/hp/ilo/setupConnection.go | 3 +- .../supermicro/supermicrox/actions.go | 8 +- .../supermicro/supermicrox/configure.go | 258 ++++---- .../providers/supermicro/supermicrox/model.go | 104 ++-- .../providers/supermicro/supermicrox/query.go | 18 +- .../supermicro/supermicrox/supermicrox.go | 14 +- .../supermicro/supermicrox11/actions.go | 8 +- .../supermicro/supermicrox11/configure.go | 306 +++++----- .../supermicro/supermicrox11/model.go | 106 ++-- .../supermicro/supermicrox11/query.go | 10 +- .../supermicro/supermicrox11/supermicrox.go | 14 +- .../bmc-toolbox/gin-go-metrics/helpers.go | 3 +- .../bmc-toolbox/gin-go-metrics/metrics.go | 55 +- .../gin-go-metrics/middleware/middleware.go | 4 +- .../github.com/bombsimon/logrusr/logrusr.go | 2 +- .../go-metrics-graphite/graphite.go | 2 +- vendor/github.com/fsnotify/fsnotify/kqueue.go | 5 +- .../github.com/fsnotify/fsnotify/windows.go | 6 +- .../github.com/gedex/inflector/inflector.go | 7 +- .../github.com/gin-contrib/sse/sse-decoder.go | 4 +- .../github.com/gin-contrib/sse/sse-encoder.go | 6 +- .../github.com/gin-gonic/gin/binding/form.go | 8 +- .../gin-gonic/gin/binding/form_mapping.go | 3 +- .../gin-gonic/gin/binding/header.go | 1 - .../github.com/gin-gonic/gin/binding/xml.go | 1 + vendor/github.com/gin-gonic/gin/mode.go | 6 +- vendor/github.com/gin-gonic/gin/recovery.go | 2 +- .../github.com/gin-gonic/gin/render/html.go | 1 + .../github.com/gin-gonic/gin/render/json.go | 8 +- .../gin-gonic/gin/render/msgpack.go | 4 +- vendor/github.com/go-logr/zapr/zapr.go | 6 +- .../github.com/go-playground/locales/rules.go | 5 - .../universal-translator/errors.go | 20 +- .../universal-translator/import_export.go | 17 +- .../universal-translator/translator.go | 24 +- .../universal_translator.go | 6 - .../go-playground/validator/v10/baked_in.go | 57 +- .../validator/v10/country_codes.go | 1 + .../go-playground/validator/v10/doc.go | 2 +- .../go-playground/validator/v10/errors.go | 11 +- .../validator/v10/struct_level.go | 2 - .../go-playground/validator/v10/util.go | 6 - .../go-playground/validator/v10/validator.go | 7 - .../validator/v10/validator_instance.go | 7 - .../github.com/go-sql-driver/mysql/buffer.go | 6 +- .../go-sql-driver/mysql/collations.go | 6 +- .../github.com/go-sql-driver/mysql/const.go | 1 + .../github.com/go-sql-driver/mysql/packets.go | 7 +- .../go-sql-driver/mysql/statement.go | 2 +- .../github.com/go-sql-driver/mysql/utils.go | 6 +- .../github.com/golang/protobuf/proto/proto.go | 1 + .../golang/protobuf/proto/registry.go | 6 +- vendor/github.com/hashicorp/hcl/decoder.go | 12 +- .../hashicorp/hcl/hcl/printer/nodes.go | 4 +- .../jacobweinstock/registrar/registrar.go | 4 +- vendor/github.com/jinzhu/gorm/association.go | 12 +- .../github.com/jinzhu/gorm/callback_query.go | 2 +- .../jinzhu/gorm/callback_query_preload.go | 6 +- .../github.com/jinzhu/gorm/dialect_common.go | 5 +- .../github.com/jinzhu/gorm/dialect_mysql.go | 2 +- .../jinzhu/gorm/dialect_postgres.go | 2 +- .../github.com/jinzhu/gorm/dialect_sqlite3.go | 2 +- .../jinzhu/gorm/dialects/postgres/postgres.go | 1 - vendor/github.com/jinzhu/gorm/errors.go | 2 +- vendor/github.com/jinzhu/gorm/logger.go | 4 +- vendor/github.com/jinzhu/gorm/main.go | 7 +- vendor/github.com/jinzhu/gorm/model_struct.go | 12 +- vendor/github.com/jinzhu/gorm/scope.go | 18 +- vendor/github.com/jinzhu/gorm/utils.go | 12 +- .../jinzhu/inflection/inflections.go | 30 +- vendor/github.com/json-iterator/go/any.go | 6 +- vendor/github.com/json-iterator/go/any_str.go | 1 - vendor/github.com/json-iterator/go/config.go | 10 +- vendor/github.com/json-iterator/go/iter.go | 6 +- .../github.com/json-iterator/go/iter_float.go | 10 +- .../github.com/json-iterator/go/iter_int.go | 14 +- vendor/github.com/json-iterator/go/reflect.go | 1 + .../json-iterator/go/reflect_array.go | 3 +- .../json-iterator/go/reflect_dynamic.go | 6 +- .../json-iterator/go/reflect_extension.go | 20 +- .../json-iterator/go/reflect_json_number.go | 15 +- .../go/reflect_json_raw_message.go | 15 +- .../json-iterator/go/reflect_map.go | 3 +- .../json-iterator/go/reflect_marshaler.go | 10 +- .../json-iterator/go/reflect_native.go | 36 +- .../json-iterator/go/reflect_optional.go | 11 +- .../json-iterator/go/reflect_slice.go | 3 +- .../go/reflect_struct_decoder.go | 48 +- .../go/reflect_struct_encoder.go | 6 +- vendor/github.com/labstack/echo/bind.go | 1 - vendor/github.com/labstack/echo/context.go | 1 - vendor/github.com/labstack/echo/echo.go | 26 +- vendor/github.com/leodido/go-urn/machine.go | 12 +- vendor/github.com/leodido/go-urn/urn.go | 2 +- vendor/github.com/lib/pq/array.go | 14 +- vendor/github.com/lib/pq/conn.go | 9 +- vendor/github.com/lib/pq/encode.go | 8 +- vendor/github.com/lib/pq/scram/scram.go | 2 +- vendor/github.com/lib/pq/ssl_permissions.go | 2 +- .../magiconair/properties/decode.go | 2 + .../magiconair/properties/properties.go | 1 - vendor/github.com/manyminds/api2go/api.go | 2 - .../manyminds/api2go/api_interfaces.go | 6 +- .../github.com/manyminds/api2go/api_public.go | 2 +- vendor/github.com/manyminds/api2go/error.go | 1 - .../manyminds/api2go/jsonapi/data_structs.go | 8 +- .../manyminds/api2go/routing/gingonic.go | 2 +- .../manyminds/api2go/routing/gorillamux.go | 2 +- .../mattn/go-colorable/colorable_windows.go | 16 +- vendor/github.com/mattn/go-sqlite3/backup.go | 1 + .../github.com/mattn/go-sqlite3/callback.go | 6 +- vendor/github.com/mattn/go-sqlite3/sqlite3.go | 1 + .../mattn/go-sqlite3/sqlite3_go18.go | 3 +- .../go-sqlite3/sqlite3_load_extension.go | 1 + .../go-sqlite3/sqlite3_load_extension_omit.go | 1 + .../go-sqlite3/sqlite3_opt_preupdate_hook.go | 1 + .../go-sqlite3/sqlite3_opt_unlock_notify.go | 1 + .../mattn/go-sqlite3/sqlite3_opt_userauth.go | 1 + .../mattn/go-sqlite3/sqlite3_trace.go | 6 +- .../mattn/go-sqlite3/sqlite3_type.go | 1 + .../mitchellh/go-homedir/homedir.go | 6 +- .../mitchellh/mapstructure/mapstructure.go | 1 - vendor/github.com/modern-go/concurrent/log.go | 6 +- .../concurrent/unbounded_executor.go | 2 +- .../github.com/modern-go/reflect2/reflect2.go | 15 +- .../github.com/modern-go/reflect2/type_map.go | 6 +- vendor/github.com/nats-io/go-nats/enc.go | 6 +- .../go-nats/encoders/builtin/default_enc.go | 11 +- .../go-nats/encoders/builtin/gob_enc.go | 3 +- .../go-nats/encoders/builtin/json_enc.go | 3 +- vendor/github.com/nats-io/go-nats/nats.go | 21 +- .../github.com/pelletier/go-toml/marshal.go | 20 +- vendor/github.com/pelletier/go-toml/parser.go | 6 +- vendor/github.com/pelletier/go-toml/toml.go | 6 +- .../pmezard/go-difflib/difflib/difflib.go | 14 +- .../github.com/rcrowley/go-metrics/debug.go | 10 +- .../rcrowley/go-metrics/graphite.go | 2 +- vendor/github.com/rcrowley/go-metrics/json.go | 2 +- vendor/github.com/rcrowley/go-metrics/log.go | 2 +- .../rcrowley/go-metrics/opentsdb.go | 2 +- .../rcrowley/go-metrics/registry.go | 2 +- .../github.com/rcrowley/go-metrics/runtime.go | 2 +- .../github.com/rcrowley/go-metrics/syslog.go | 2 +- .../github.com/rcrowley/go-metrics/writer.go | 2 +- vendor/github.com/selvatico/go-mocket/conn.go | 2 +- .../selvatico/go-mocket/response.go | 18 +- vendor/github.com/selvatico/go-mocket/stmt.go | 3 +- .../github.com/sirupsen/logrus/buffer_pool.go | 4 +- vendor/github.com/sirupsen/logrus/exported.go | 6 +- vendor/github.com/sirupsen/logrus/logger.go | 6 +- .../sirupsen/logrus/text_formatter.go | 1 - vendor/github.com/spf13/afero/afero.go | 2 +- .../github.com/spf13/afero/copyOnWriteFs.go | 4 +- vendor/github.com/spf13/afero/ioutil.go | 11 +- vendor/github.com/spf13/afero/mem/file.go | 7 +- vendor/github.com/spf13/afero/memmap.go | 6 +- vendor/github.com/spf13/afero/unionFile.go | 5 +- vendor/github.com/spf13/afero/util.go | 7 +- vendor/github.com/spf13/cast/caste.go | 16 +- .../spf13/cobra/bash_completions.go | 1 + vendor/github.com/spf13/cobra/cobra.go | 1 - .../spf13/cobra/custom_completions.go | 2 +- vendor/github.com/spf13/pflag/bool_slice.go | 2 - vendor/github.com/spf13/pflag/bytes.go | 6 - vendor/github.com/spf13/pflag/flag.go | 1 - vendor/github.com/spf13/pflag/golangflag.go | 2 +- vendor/github.com/spf13/pflag/ip_slice.go | 2 - vendor/github.com/spf13/pflag/string.go | 1 + vendor/github.com/spf13/viper/viper.go | 60 +- .../stretchr/testify/assert/assertions.go | 24 +- vendor/github.com/ugorji/go/codec/binc.go | 22 +- vendor/github.com/ugorji/go/codec/cbor.go | 16 +- vendor/github.com/ugorji/go/codec/decimal.go | 16 +- vendor/github.com/ugorji/go/codec/decode.go | 17 +- vendor/github.com/ugorji/go/codec/doc.go | 2 +- vendor/github.com/ugorji/go/codec/encode.go | 18 +- .../ugorji/go/codec/fast-path.generated.go | 303 +++++++++- .../ugorji/go/codec/fast-path.not.go | 22 +- vendor/github.com/ugorji/go/codec/gen.go | 46 +- vendor/github.com/ugorji/go/codec/helper.go | 25 +- .../ugorji/go/codec/helper_not_unsafe.go | 6 + .../ugorji/go/codec/helper_unsafe.go | 26 +- vendor/github.com/ugorji/go/codec/json.go | 26 +- vendor/github.com/ugorji/go/codec/msgpack.go | 30 +- vendor/github.com/ugorji/go/codec/reader.go | 3 +- vendor/github.com/ugorji/go/codec/rpc.go | 2 +- vendor/github.com/ugorji/go/codec/simple.go | 16 +- .../ugorji/go/codec/sort-slice.generated.go | 8 +- vendor/github.com/ugorji/go/codec/writer.go | 15 + vendor/go.uber.org/zap/sink.go | 2 +- vendor/go.uber.org/zap/stacktrace.go | 12 +- vendor/go.uber.org/zap/zapcore/entry.go | 14 +- .../x/crypto/acme/autocert/cache.go | 2 +- .../x/crypto/acme/autocert/listener.go | 2 +- vendor/golang.org/x/crypto/ssh/certs.go | 3 +- vendor/golang.org/x/crypto/ssh/channel.go | 12 +- vendor/golang.org/x/crypto/ssh/common.go | 1 - vendor/golang.org/x/crypto/ssh/handshake.go | 1 - .../ssh/internal/bcrypt_pbkdf/bcrypt_pbkdf.go | 1 + vendor/golang.org/x/crypto/ssh/kex.go | 6 +- vendor/golang.org/x/crypto/ssh/messages.go | 15 +- vendor/golang.org/x/crypto/ssh/ssh_gss.go | 10 +- vendor/golang.org/x/net/idna/trieval.go | 2 +- vendor/golang.org/x/sys/cpu/byteorder.go | 6 +- vendor/golang.org/x/sys/cpu/cpu_arm.go | 1 - vendor/golang.org/x/sys/cpu/cpu_x86.go | 1 - vendor/golang.org/x/sys/cpu/hwcap_linux.go | 6 +- vendor/golang.org/x/sys/unix/aliases.go | 8 +- vendor/golang.org/x/sys/unix/cap_freebsd.go | 10 +- vendor/golang.org/x/sys/unix/epoll_zos.go | 5 +- vendor/golang.org/x/sys/unix/fstatfs_zos.go | 12 +- .../x/sys/unix/readdirent_getdirentries.go | 2 +- .../golang.org/x/sys/unix/syscall_darwin.go | 2 +- vendor/golang.org/x/sys/unix/syscall_linux.go | 2 +- .../x/sys/unix/syscall_linux_386.go | 6 +- .../x/sys/unix/syscall_linux_arm.go | 6 +- .../x/sys/unix/syscall_linux_mipsx.go | 6 +- vendor/golang.org/x/sys/unix/syscall_unix.go | 2 +- .../x/sys/unix/syscall_unix_gc_ppc64x.go | 3 + .../x/sys/unix/syscall_zos_s390x.go | 20 +- .../golang.org/x/sys/unix/zsyscall_aix_ppc.go | 1 + .../x/sys/unix/zsyscall_aix_ppc64_gc.go | 4 +- .../x/sys/unix/zsyscall_aix_ppc64_gccgo.go | 1 + .../x/sys/unix/zsyscall_illumos_amd64.go | 4 +- .../x/sys/unix/zsyscall_solaris_amd64.go | 4 +- .../golang.org/x/sys/unix/ztypes_aix_ppc.go | 9 +- .../golang.org/x/sys/unix/ztypes_aix_ppc64.go | 9 +- .../golang.org/x/sys/unix/ztypes_zos_s390x.go | 8 +- vendor/golang.org/x/sys/windows/aliases.go | 6 +- .../x/sys/windows/security_windows.go | 3 + .../x/sys/windows/syscall_windows.go | 8 +- .../golang.org/x/sys/windows/types_windows.go | 51 +- vendor/golang.org/x/text/unicode/bidi/core.go | 4 - .../x/text/unicode/norm/tables10.0.0.go | 6 +- .../x/text/unicode/norm/tables11.0.0.go | 6 +- .../x/text/unicode/norm/tables12.0.0.go | 6 +- .../x/text/unicode/norm/tables13.0.0.go | 6 +- .../x/text/unicode/norm/tables9.0.0.go | 6 +- .../protobuf/encoding/prototext/encode.go | 2 +- .../protobuf/internal/descfmt/stringer.go | 2 + .../protobuf/internal/filedesc/desc.go | 7 + .../protobuf/internal/filedesc/desc_init.go | 4 + .../internal/filedesc/desc_list_gen.go | 27 + .../protobuf/internal/impl/codec_gen.go | 6 - .../protobuf/internal/impl/convert.go | 27 + .../protobuf/internal/impl/convert_list.go | 8 + .../protobuf/internal/impl/convert_map.go | 9 + .../protobuf/internal/impl/extension.go | 7 + .../protobuf/internal/impl/legacy_enum.go | 5 + .../protobuf/internal/impl/legacy_export.go | 2 +- .../protobuf/internal/impl/legacy_file.go | 2 + .../protobuf/internal/impl/legacy_message.go | 21 + .../protobuf/internal/impl/merge_gen.go | 2 - .../protobuf/internal/impl/message.go | 1 + .../protobuf/internal/impl/message_reflect.go | 6 + .../internal/impl/message_reflect_gen.go | 30 + .../protobuf/internal/impl/pointer_unsafe.go | 4 + .../protobuf/internal/set/ints.go | 6 + .../protobuf/internal/strs/strings.go | 2 + .../reflect/protoreflect/value_pure.go | 4 + .../reflect/protoreflect/value_unsafe.go | 4 + .../go-playground/validator.v9/baked_in.go | 57 +- .../go-playground/validator.v9/errors.go | 11 +- .../validator.v9/struct_level.go | 2 - .../go-playground/validator.v9/util.go | 6 - .../go-playground/validator.v9/validator.go | 7 - .../validator.v9/validator_instance.go | 7 - vendor/gopkg.in/ini.v1/deprecated.go | 6 +- vendor/gopkg.in/ini.v1/file.go | 2 +- vendor/gopkg.in/ini.v1/key.go | 3 - vendor/gopkg.in/ini.v1/parser.go | 1 - vendor/gopkg.in/ini.v1/section.go | 1 - vendor/gopkg.in/yaml.v2/apic.go | 2 +- vendor/gopkg.in/yaml.v2/decode.go | 2 +- vendor/gopkg.in/yaml.v2/emitterc.go | 4 - vendor/gopkg.in/yaml.v2/parserc.go | 5 +- vendor/gopkg.in/yaml.v2/readerc.go | 4 +- vendor/gopkg.in/yaml.v2/resolve.go | 10 +- vendor/gopkg.in/yaml.v2/scannerc.go | 14 +- vendor/gopkg.in/yaml.v2/sorter.go | 2 +- vendor/gopkg.in/yaml.v2/yaml.go | 8 +- vendor/gopkg.in/yaml.v2/yamlprivateh.go | 9 +- vendor/gopkg.in/yaml.v3/apic.go | 10 +- vendor/gopkg.in/yaml.v3/decode.go | 6 +- vendor/gopkg.in/yaml.v3/emitterc.go | 22 +- vendor/gopkg.in/yaml.v3/encode.go | 4 +- vendor/gopkg.in/yaml.v3/parserc.go | 5 +- vendor/gopkg.in/yaml.v3/readerc.go | 10 +- vendor/gopkg.in/yaml.v3/resolve.go | 14 +- vendor/gopkg.in/yaml.v3/scannerc.go | 37 +- vendor/gopkg.in/yaml.v3/writerc.go | 8 +- vendor/gopkg.in/yaml.v3/yaml.go | 12 +- vendor/gopkg.in/yaml.v3/yamlh.go | 1 - vendor/gopkg.in/yaml.v3/yamlprivateh.go | 29 +- vendor/modules.txt | 2 +- web/rice-box.go | 2 - 353 files changed, 4085 insertions(+), 3521 deletions(-) delete mode 100644 vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/helpers.go diff --git a/cmd/create.go b/cmd/create.go index 2f346823..55eaab11 100644 --- a/cmd/create.go +++ b/cmd/create.go @@ -99,12 +99,12 @@ var createCmd = &cobra.Command{ configDir := fmt.Sprintf("%s/.bmc-toolbox", home) configFile := fmt.Sprintf("%s/dora.yaml", configDir) if _, err := os.Stat(configFile); os.IsNotExist(err) { - err = os.MkdirAll(configDir, 0755) + err = os.MkdirAll(configDir, 0o755) if err != nil { fmt.Printf("Failed to create the config directory %s: %s\n", configDir, err) os.Exit(1) } - err = ioutil.WriteFile(configFile, sampleConfig, 0755) + err = ioutil.WriteFile(configFile, sampleConfig, 0o755) if err != nil { fmt.Printf("Failed to create the temp config %s: %s\n", configFile, err) os.Exit(1) diff --git a/cmd/root.go b/cmd/root.go index 9b1a21ff..82f143b1 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -24,9 +24,11 @@ import ( "github.com/spf13/viper" ) -var cfgFile string -var subject string -var queue string +var ( + cfgFile string + subject string + queue string +) // RootCmd represents the base command when called without any subcommands var RootCmd = &cobra.Command{ diff --git a/go.mod b/go.mod index 5476339d..e3a47fcd 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,7 @@ go 1.13 require ( github.com/DATA-DOG/go-sqlmock v1.5.0 github.com/GeertJohan/go.rice v1.0.2 - github.com/bmc-toolbox/bmclib v0.4.13 + github.com/bmc-toolbox/bmclib v0.4.14 github.com/bmc-toolbox/gin-go-metrics v0.0.2 github.com/daaku/go.zipexe v1.0.1 // indirect github.com/gin-gonic/gin v1.7.2 diff --git a/go.sum b/go.sum index 5354f5e3..65bbf9dc 100644 --- a/go.sum +++ b/go.sum @@ -35,17 +35,23 @@ github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmV github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84= github.com/bmc-toolbox/bmclib v0.4.13 h1:JOJvQ14Ns8HL2/SW358kJHlBMPdYTKwDFeCYDORoB7Q= github.com/bmc-toolbox/bmclib v0.4.13/go.mod h1:0WeM06Sacej9UMbt6yFtIRfrwmsl5IK2f4sAUMaNN+4= +github.com/bmc-toolbox/bmclib v0.4.14 h1:G8bBF/awNoZB4FWUJ8/roSwCoYo0e1V5jy5OkAz6W0I= +github.com/bmc-toolbox/bmclib v0.4.14/go.mod h1:9YhAIIwp9tQtlo1LZtN5Qd89e+RfvgQ62ikbreEKOs0= github.com/bmc-toolbox/gin-go-metrics v0.0.2 h1:fIyChVWWq1+7npgx0F+SZc3RSVsekPBW+bmeKaHRFF0= github.com/bmc-toolbox/gin-go-metrics v0.0.2/go.mod h1:JgW/TlIv2rVW1dIFBSUY61L4Fz4fbSQco8hd8BDxOtw= github.com/bombsimon/logrusr v1.0.0 h1:CTCkURYAt5nhCCnKH9eLShYayj2/8Kn/4Qg3QfiU+Ro= github.com/bombsimon/logrusr v1.0.0/go.mod h1:Jq0nHtvxabKE5EMwAAdgTaz7dfWE8C4i11NOltxGQpc= +github.com/cenkalti/backoff/v4 v4.0.2 h1:JIufpQLbh4DkbQoii76ItQIUFzevQSqOLZca4eamEDs= github.com/cenkalti/backoff/v4 v4.0.2/go.mod h1:eEew/i+1Q6OrCDZh3WiXYv3+nJwBASZ8Bog/87DQnVg= +github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= +github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= @@ -72,6 +78,7 @@ github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5Kwzbycv github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/gebn/bmc v0.0.0-20200904230046-a5643220ab2a h1:AyC9EwIaY0IwLIxj/tZZDdFgNQ9MJk0jlE+luzCTIMo= github.com/gebn/bmc v0.0.0-20200904230046-a5643220ab2a/go.mod h1:VlKWLGIyVIhqHRj4hp9lx20lZcSn9PgNKRmDwcyRT7w= github.com/gedex/inflector v0.0.0-20170307190818-16278e9db813 h1:Uc+IZ7gYqAf/rSGFplbWBSHaGolEQlNLgMgSE3ccnIQ= github.com/gedex/inflector v0.0.0-20170307190818-16278e9db813/go.mod h1:P+oSoE9yhSRvsmYyZsshflcR6ePWYLql6UU1amW13IM= @@ -142,6 +149,7 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-querystring v1.0.0 h1:Xkwi/a1rcvNg1PPYe5vI8GbeBY/jrVuDX5ASuANWTrk= github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/gopacket v1.1.18 h1:lum7VRA9kdlvBi7/v2p7/zcbkduHaCH/SVVyurs7OpY= github.com/google/gopacket v1.1.18/go.mod h1:UdDNZ1OO62aGYVnPhxT1U6aI7ukYtA/kB8vaU0diBUM= github.com/google/gops v0.3.14 h1:4Gpv4sABlEsVqrtKxiSynzD0//kzjTIUwUm5UgkGILI= github.com/google/gops v0.3.14/go.mod h1:zjT9F4XsKzazOvdVad3+Zwga79UHKziX3r9TN05rVN8= @@ -252,6 +260,7 @@ github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Ky github.com/mattn/go-sqlite3 v1.14.0/go.mod h1:JIl7NbARA7phWnGvh0LKTyg7S9BA+6gx71ShQilpsus= github.com/mattn/go-sqlite3 v1.14.6 h1:dNPt6NO46WmLVt2DLNpwczCmdV5boIZ6g/tlDrlRUbg= github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= +github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= @@ -308,17 +317,21 @@ github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndr github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.7.1 h1:NTGy1Ja9pByO+xAeH/qiWnLrKtr3hJPNjaVUwnjpdpA= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M= github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.10.0 h1:RyRA7RzGXQZiW+tGMr7sxa85G1z0yOpM1qq5c8lNawc= github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.1.3 h1:F0+tqvhOksq22sc6iCHF5WGlWjdwj92p0udFh1VFBS8= github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a h1:9ZKAASQSHhDYGoxY8uLVpewe1GDZ2vu2Tr/vTdVAkFQ= @@ -361,6 +374,8 @@ github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5q github.com/spf13/viper v1.7.1 h1:pM5oEahlgWv/WnHXpgbKz7iLIxRf65tye2Ci+XFK5sk= github.com/spf13/viper v1.7.1/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= github.com/stmcginnis/gofish v0.8.0/go.mod h1:BGtQsY16q48M2K6KDAs38QXtNoHrkXaY/WZ/mmyMgNc= +github.com/stmcginnis/gofish v0.12.0 h1:6UbNePjA++XkHtCKKLr7envKENxljJ1YyD8f4vS3Zeo= +github.com/stmcginnis/gofish v0.12.0/go.mod h1:BGtQsY16q48M2K6KDAs38QXtNoHrkXaY/WZ/mmyMgNc= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= diff --git a/internal/notification/notification.go b/internal/notification/notification.go index bf4a74b0..12ef860d 100644 --- a/internal/notification/notification.go +++ b/internal/notification/notification.go @@ -9,9 +9,7 @@ import ( "github.com/spf13/viper" ) -var ( - notifyChange chan string -) +var notifyChange chan string func init() { // Creates a channel with a buffer for 600 messages diff --git a/internal/stats/stats.go b/internal/stats/stats.go index 8cac27a8..0c3b5076 100644 --- a/internal/stats/stats.go +++ b/internal/stats/stats.go @@ -57,7 +57,7 @@ type Stats struct { // UpdateUptime updates uptime based on StartTime func (s *Stats) UpdateUptime() { - s.Uptime = float32(time.Since(s.StartTime).Seconds() * 1e3) //1e3 == 1000 + s.Uptime = float32(time.Since(s.StartTime).Seconds() * 1e3) // 1e3 == 1000 } // GatherDBStats triggers GatherDBStats function from all resources types @@ -80,7 +80,8 @@ func (s *Stats) GatherDBStats( "scanned_ports", "psus", "disks", - "fans"} + "fans", + } for i, r := range []countable{ chassisStorage, @@ -91,7 +92,8 @@ func (s *Stats) GatherDBStats( scannedPortStorage, psuStorage, diskStorage, - fanStorage} { + fanStorage, + } { u := &UnitStats{} switch i { case 0: diff --git a/resolver/resolver.go b/resolver/resolver.go index dbf97cd1..dd3ab1e8 100644 --- a/resolver/resolver.go +++ b/resolver/resolver.go @@ -10,12 +10,12 @@ type RequestURL struct { Port int } -//SetRequest to implement `RequestAwareResolverInterface` +// SetRequest to implement `RequestAwareResolverInterface` func (m *RequestURL) SetRequest(r http.Request) { m.r = r } -//GetBaseURL implements `URLResolver` interface +// GetBaseURL implements `URLResolver` interface func (m RequestURL) GetBaseURL() string { return fmt.Sprintf("https://localhost:%d", m.Port) } diff --git a/resource/response.go b/resource/response.go index e2ba262d..326d3637 100644 --- a/resource/response.go +++ b/resource/response.go @@ -8,10 +8,8 @@ type Response struct { Code int } -var ( - // ErrPageSizeAndNumber is returned when page[number] and page[size] are sent on the http request - ErrPageSizeAndNumber = errors.New("filters page[number] and page[size] are not supported, please stick to page[offset] and page[limit]") -) +// ErrPageSizeAndNumber is returned when page[number] and page[size] are sent on the http request +var ErrPageSizeAndNumber = errors.New("filters page[number] and page[size] are not supported, please stick to page[offset] and page[limit]") // Metadata returns additional meta data func (r Response) Metadata() map[string]interface{} { diff --git a/vendor/github.com/GeertJohan/go.rice/appended.go b/vendor/github.com/GeertJohan/go.rice/appended.go index 38d78f92..39c7d1da 100644 --- a/vendor/github.com/GeertJohan/go.rice/appended.go +++ b/vendor/github.com/GeertJohan/go.rice/appended.go @@ -125,18 +125,23 @@ type appendedDirInfo struct { func (adi *appendedDirInfo) Name() string { return adi.name } + func (adi *appendedDirInfo) Size() int64 { return 0 } + func (adi *appendedDirInfo) Mode() os.FileMode { return os.ModeDir } + func (adi *appendedDirInfo) ModTime() time.Time { return adi.time } + func (adi *appendedDirInfo) IsDir() bool { return true } + func (adi *appendedDirInfo) Sys() interface{} { return nil } diff --git a/vendor/github.com/GeertJohan/go.rice/box.go b/vendor/github.com/GeertJohan/go.rice/box.go index 208b1689..0094a7e2 100644 --- a/vendor/github.com/GeertJohan/go.rice/box.go +++ b/vendor/github.com/GeertJohan/go.rice/box.go @@ -140,7 +140,6 @@ func (b *Box) resolveAbsolutePathFromCaller() error { } b.absolutePath = path return nil - } func (b *Box) resolveAbsolutePathFromWorkingDirectory() error { diff --git a/vendor/github.com/GeertJohan/go.rice/embedded.go b/vendor/github.com/GeertJohan/go.rice/embedded.go index 4f03fe1f..8a974e90 100644 --- a/vendor/github.com/GeertJohan/go.rice/embedded.go +++ b/vendor/github.com/GeertJohan/go.rice/embedded.go @@ -27,7 +27,7 @@ func (ed *embeddedDirInfo) Size() int64 { // Mode returns the file mode bits // (implementing os.FileInfo) func (ed *embeddedDirInfo) Mode() os.FileMode { - return os.FileMode(0555 | os.ModeDir) // dr-xr-xr-x + return os.FileMode(0o555 | os.ModeDir) // dr-xr-xr-x } // ModTime returns the modification time @@ -68,7 +68,7 @@ func (ef *embeddedFileInfo) Size() int64 { // Mode returns the file mode bits // (implementing os.FileInfo) func (ef *embeddedFileInfo) Mode() os.FileMode { - return os.FileMode(0555) // r-xr-xr-x + return os.FileMode(0o555) // r-xr-xr-x } // ModTime returns the modification time diff --git a/vendor/github.com/GeertJohan/go.rice/virtual.go b/vendor/github.com/GeertJohan/go.rice/virtual.go index b175849b..fc65147e 100644 --- a/vendor/github.com/GeertJohan/go.rice/virtual.go +++ b/vendor/github.com/GeertJohan/go.rice/virtual.go @@ -100,7 +100,6 @@ func (vf *virtualFile) read(bts []byte) (int, error) { n := copy(bts, vf.Content[vf.offset:end]) vf.offset += int64(n) return n, nil - } func (vf *virtualFile) seek(offset int64, whence int) (int64, error) { @@ -181,7 +180,6 @@ func (vd *virtualDir) stat() (os.FileInfo, error) { } func (vd *virtualDir) readdir(n int) ([]os.FileInfo, error) { - if vd.closed { return nil, &os.PathError{ Op: "readdir", @@ -225,11 +223,9 @@ func (vd *virtualDir) readdir(n int) ([]os.FileInfo, error) { offset := vd.offset vd.offset += n return files[offset : offset+n], nil - } func (vd *virtualDir) readdirnames(n int) ([]string, error) { - if vd.closed { return nil, &os.PathError{ Op: "readdir", diff --git a/vendor/github.com/GeertJohan/go.rice/walk.go b/vendor/github.com/GeertJohan/go.rice/walk.go index ee08ed5f..a4f574c6 100644 --- a/vendor/github.com/GeertJohan/go.rice/walk.go +++ b/vendor/github.com/GeertJohan/go.rice/walk.go @@ -10,7 +10,6 @@ import ( // Walk is like filepath.Walk() // Visit http://golang.org/pkg/path/filepath/#Walk for more information func (b *Box) Walk(path string, walkFn filepath.WalkFunc) error { - pathFile, err := b.Open(path) if err != nil { return err @@ -28,19 +27,15 @@ func (b *Box) Walk(path string, walkFn filepath.WalkFunc) error { // We don't have any embedded or appended box so use live filesystem mode return filepath.Walk(filepath.Join(b.absolutePath, path), func(path string, info os.FileInfo, err error) error { - // Strip out the box name from the returned paths path = strings.TrimPrefix(path, b.absolutePath+string(os.PathSeparator)) return walkFn(path, info, err) - }) - } // walk recursively descends path. // See walk() in $GOROOT/src/pkg/path/filepath/path.go func (b *Box) walk(path string, info os.FileInfo, walkFn filepath.WalkFunc) error { - err := walkFn(path, info, nil) if err != nil { if info.IsDir() && err == filepath.SkipDir { @@ -83,13 +78,11 @@ func (b *Box) walk(path string, info os.FileInfo, walkFn filepath.WalkFunc) erro } return nil - } // readDirNames reads the directory named by path and returns a sorted list of directory entries. // See readDirNames() in $GOROOT/pkg/path/filepath/path.go func (b *Box) readDirNames(path string) ([]string, error) { - f, err := b.Open(path) if err != nil { return nil, err @@ -118,5 +111,4 @@ func (b *Box) readDirNames(path string) ([]string, error) { sort.Strings(names) return names, nil - } diff --git a/vendor/github.com/bmc-toolbox/bmclib/cfgresources/cfgresources.go b/vendor/github.com/bmc-toolbox/bmclib/cfgresources/cfgresources.go index c6602b8f..22c82e4f 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/cfgresources/cfgresources.go +++ b/vendor/github.com/bmc-toolbox/bmclib/cfgresources/cfgresources.go @@ -1,6 +1,10 @@ package cfgresources -import "time" +import ( + "encoding/json" + "os/exec" + "time" +) // SetupChassis struct holds attributes for one time chassis setup. type SetupChassis struct { @@ -15,7 +19,7 @@ type SetupChassis struct { // ResourcesConfig struct holds all the configuration to be applied. type ResourcesConfig struct { Ldap *Ldap `yaml:"ldap"` - LdapGroup []*LdapGroup `yaml:"ldapGroup"` + LdapGroups *LdapGroups `yaml:"ldapGroups"` License *License `yaml:"license"` Network *Network `yaml:"network"` Syslog *Syslog `yaml:"syslog"` @@ -24,7 +28,7 @@ type ResourcesConfig struct { Ntp *Ntp `yaml:"ntp"` Bios *Bios `yaml:"bios"` Power *Power `yaml:"power"` - Supermicro *Supermicro `yaml:"supermicro"` //supermicro specific config, example of issue #34 + Supermicro *Supermicro `yaml:"supermicro"` SetupChassis *SetupChassis `yaml:"setupChassis"` } @@ -44,20 +48,19 @@ type BladeBmcAccount struct { Password string `yaml:"password"` } -//Enable/Disable Virtual Mac addresses for blades in a chassis. -//FlexAddresses in M1000e jargon. -//Virtual connect in HP C7000 jargon. +// Enable/Disable Virtual Mac addresses for blades in a chassis. +// FlexAddresses in M1000e jargon. +// Virtual connect in HP C7000 jargon. type flexAddress struct { Enable bool `yaml:"enable"` } -//Enable/Disable ipmi over lan type ipmiOverLan struct { Enable bool `yaml:"enable"` } -//'Dynamic Power' in HP C7000 Jargon. -//'DPSE' (dynamic PSU engagement) in M1000e Dell jargon. +// 'Dynamic Power' in HP C7000 Jargon. +// 'DPSE' (dynamic PSU engagement) in M1000e Dell jargon. type dynamicPower struct { Enable bool `yaml:"enable"` } @@ -69,10 +72,12 @@ type bladesPower struct { // User struct holds a BMC user account configuration. type User struct { - Name string `yaml:"name"` - Password string `yaml:"password"` - Role string `yaml:"role"` - Enable bool `yaml:"enable,omitempty"` + Name string `yaml:"name"` + Password string `yaml:"password"` + Role string `yaml:"role"` + Enable bool `yaml:"enable,omitempty"` + SolEnable bool `yaml:"solEnable,omitempty"` + SNMPv3Enable bool `yaml:"snmpV3Enable,omitempty"` } // Syslog struct holds BMC syslog configuration. @@ -88,8 +93,8 @@ type Ldap struct { Port int `yaml:"port"` Enable bool `yaml:"enable"` Role string `yaml:"role"` - BaseDn string `yaml:"baseDn"` //BaseDN is the starting point of the LDAP tree search. - BindDn string `yaml:"bindDn"` //BindDN is used to gain access to the LDAP tree. + BaseDn string `yaml:"baseDn"` // BaseDN is the starting point of the LDAP tree search. + BindDn string `yaml:"bindDn"` // BindDN is used to gain access to the LDAP tree. Group string `yaml:"group"` GroupBaseDn string `yaml:"groupBaseDn"` UserAttribute string `yaml:"userAttribute"` @@ -97,12 +102,54 @@ type Ldap struct { SearchFilter string `yaml:"searchFilter"` } -// License struct holds BMC licencing configuration. +// License struct holds BMC licensing configuration. type License struct { Key string `yaml:"key"` } -// LdapGroup struct holds BMC LDAP role group configuration. +type LdapBin struct { + Executor string `yaml:"executor"` + Path string `yaml:"path"` +} + +// LdapGroups holds all group-related configuration parameters. +// ExtraGroups is used in combination with Bin to add more groups at runtime. +type LdapGroups struct { + Bin *LdapBin `yaml:"bin"` + Groups []*LdapGroup `yaml:"groups"` + ExtraAdminGroups []*LdapGroup `json:"admins"` + ExtraUserGroups []*LdapGroup `json:"users"` +} + +// If you want to add extra groups at runtime using a script, you have +// the option of specifying +// * Bin.Executor: Usually /bin/sh or /bin/bash and the like. +// * Bin.Path: Path your actual script. +// You get the serial of the asset and its vendor as two arguments. +// If you want more, create a GitHub issue and we will take a look. +func (l *LdapGroups) GetExtraGroups(serial, vendor string) (string, error) { + if l.Bin.Path == "" { + return "nothing", nil + } + + cmd := exec.Command(l.Bin.Executor, l.Bin.Path, serial, vendor) + stdout, err := cmd.CombinedOutput() + if err != nil { + return string(stdout), err + } + + err = json.Unmarshal(stdout, &l) + if err != nil { + return string(stdout), err + } + + l.Groups = append(l.Groups, l.ExtraAdminGroups...) + l.Groups = append(l.Groups, l.ExtraUserGroups...) + + return "success", nil +} + +// LdapGroup struct holds a single BMC LDAP role group configuration. type LdapGroup struct { Role string `yaml:"role"` Group string `yaml:"group"` @@ -137,7 +184,7 @@ type Network struct { DNSFromDHCP bool `yaml:"dnsFromDhcp"` SSHEnable bool `yaml:"sshEnable"` SSHPort int `yaml:"sshPort"` - SolEnable bool `yaml:"solEnable"` //Serial over lan + SolEnable bool `yaml:"solEnable"` // SerialOverLan IpmiEnable bool `yaml:"ipmiEnable"` DhcpEnable bool `yaml:"dhcpEnable"` IpmiPort int `yaml:"ipmiPort"` diff --git a/vendor/github.com/bmc-toolbox/bmclib/cfgresources/supermicro.go b/vendor/github.com/bmc-toolbox/bmclib/cfgresources/supermicro.go index e71c371a..58c70b26 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/cfgresources/supermicro.go +++ b/vendor/github.com/bmc-toolbox/bmclib/cfgresources/supermicro.go @@ -6,7 +6,6 @@ type Supermicro struct { } // SupermicroNetworkCfg holds configuration for supermicro network. -//this is an example for issue #34 type SupermicroNetworkCfg struct { Web string `yaml:"web"` WebSsl int `yaml:"webSsl"` diff --git a/vendor/github.com/bmc-toolbox/bmclib/devices/interfaces.go b/vendor/github.com/bmc-toolbox/bmclib/devices/interfaces.go index 26ceb0a7..6c0a6604 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/devices/interfaces.go +++ b/vendor/github.com/bmc-toolbox/bmclib/devices/interfaces.go @@ -23,13 +23,14 @@ type Bmc interface { PowerCycleBmc() (bool, error) // BMCResetter PowerCycle() (bool, error) // PowerSetter UpdateCredentials(string, string) - UpdateFirmware(string, string) (bool, error) + UpdateFirmware(string, string) (bool, string, error) + CheckFirmwareVersion() (string, error) } // BmcCollection represents the requirement of items to be collected a server type BmcCollection interface { BiosVersion() (string, error) - HardwareType() string + HardwareType() string // ilo4, ilo5, idrac8 or idrac9, etc Version() (string, error) CPU() (string, int, int, int, error) Disks() ([]*Disk, error) @@ -77,7 +78,8 @@ type Cmc interface { PxeOnceBlade(int) (bool, error) ReseatBlade(int) (bool, error) UpdateCredentials(string, string) - UpdateFirmware(string, string) (bool, error) + UpdateFirmware(string, string) (bool, string, error) + CheckFirmwareVersion() (string, error) } // CmcCollection represents the requirement of items to be collected from a chassis @@ -125,7 +127,7 @@ type Configure interface { Syslog(*cfgresources.Syslog) error Ntp(*cfgresources.Ntp) error Ldap(*cfgresources.Ldap) error - LdapGroup([]*cfgresources.LdapGroup, *cfgresources.Ldap) error + LdapGroups([]*cfgresources.LdapGroup, *cfgresources.Ldap) error Network(*cfgresources.Network) (bool, error) SetLicense(*cfgresources.License) error Bios(*cfgresources.Bios) error diff --git a/vendor/github.com/bmc-toolbox/bmclib/discover/discover.go b/vendor/github.com/bmc-toolbox/bmclib/discover/discover.go index 7c4473e4..7da4e4e1 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/discover/discover.go +++ b/vendor/github.com/bmc-toolbox/bmclib/discover/discover.go @@ -24,7 +24,7 @@ const ( ProbeHpCl100 = "hpcl100" ) -// ScanAndConnect will scan the bmc trying to learn the device type and return a working connection. +// ScanAndConnect will scan the BMC trying to deduce the device type and return a working connection. func ScanAndConnect(host string, username string, password string, options ...Option) (bmcConnection interface{}, err error) { opts := &Options{HintCallback: func(_ string) error { return nil }} for _, optFn := range options { @@ -51,9 +51,9 @@ func ScanAndConnect(host string, username string, password string, options ...Op return nil, err } - var probe = Probe{client: client, username: username, password: password, host: host} + probe := Probe{client: client, username: username, password: password, host: host} - var devices = map[string]func(context.Context, logr.Logger) (interface{}, error){ + devices := map[string]func(context.Context, logr.Logger) (interface{}, error){ ProbeHpIlo: probe.hpIlo, ProbeIdrac8: probe.idrac8, ProbeIdrac9: probe.idrac9, @@ -65,7 +65,8 @@ func ScanAndConnect(host string, username string, password string, options ...Op ProbeHpCl100: probe.hpCl100, } - order := []string{ProbeHpIlo, + order := []string{ + ProbeHpIlo, ProbeIdrac8, ProbeIdrac9, ProbeSupermicrox11, @@ -86,11 +87,15 @@ func ScanAndConnect(host string, username string, password string, options ...Op opts.Logger.V(1).Info("probing to identify device", "step", "ScanAndConnect", "host", host, "vendor", probeID) bmcConnection, err := probeDevice(opts.Context, opts.Logger) - // if the device didn't match continue to probe if err != nil { // log error if probe is not successful - opts.Logger.V(1).Info("probe failed", "step", "ScanAndConnect", "host", host, "vendor", probeID, "error", err) + opts.Logger.V(1).Info("Probe failed!", + "step", "ScanAndConnect", + "host", host, + "vendor", probeID, + "Error", err, + ) continue } if hintErr := opts.HintCallback(probeID); hintErr != nil { diff --git a/vendor/github.com/bmc-toolbox/bmclib/discover/probe.go b/vendor/github.com/bmc-toolbox/bmclib/discover/probe.go index 050e09d9..7d56c300 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/discover/probe.go +++ b/vendor/github.com/bmc-toolbox/bmclib/discover/probe.go @@ -9,6 +9,7 @@ import ( "io/ioutil" "net/http" "strings" + "time" "github.com/bmc-toolbox/bmclib/devices" @@ -38,6 +39,9 @@ type Probe struct { } func (p *Probe) hpIlo(ctx context.Context, log logr.Logger) (bmcConnection interface{}, err error) { + ctx, cancel := context.WithTimeout(ctx, time.Duration(time.Second*60)) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("https://%s/xmldata?item=all", p.host), nil) if err != nil { return bmcConnection, err @@ -60,7 +64,6 @@ func (p *Probe) hpIlo(ctx context.Context, log logr.Logger) (bmcConnection inter } if bytes.Contains(payload[:6], []byte("RIMP")) { - iloXMLC := &hp.Rimp{} err = xml.Unmarshal(payload, iloXMLC) if err != nil { @@ -87,6 +90,9 @@ func (p *Probe) hpIlo(ctx context.Context, log logr.Logger) (bmcConnection inter } func (p *Probe) hpC7000(ctx context.Context, log logr.Logger) (bmcConnection interface{}, err error) { + ctx, cancel := context.WithTimeout(ctx, time.Duration(time.Second*60)) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("https://%s/xmldata?item=all", p.host), nil) if err != nil { return bmcConnection, err @@ -109,7 +115,6 @@ func (p *Probe) hpC7000(ctx context.Context, log logr.Logger) (bmcConnection int } if bytes.Contains(payload[:6], []byte("RIMP")) { - iloXMLC := &hp.Rimp{} err = xml.Unmarshal(payload, iloXMLC) if err != nil { @@ -120,15 +125,15 @@ func (p *Probe) hpC7000(ctx context.Context, log logr.Logger) (bmcConnection int log.V(1).Info("step", "ScanAndConnect", "host", p.host, "vendor", string(devices.HP), "msg", "it's a chassis") return c7000.New(ctx, p.host, p.username, p.password, log) } - } return bmcConnection, errors.ErrDeviceNotMatched } -// hpCl100 attempts to identify a cloudline device +// Attempts to identify an HPE Cloudline CL100 device. func (p *Probe) hpCl100(ctx context.Context, log logr.Logger) (bmcConnection interface{}, err error) { + ctx, cancel := context.WithTimeout(ctx, time.Duration(time.Second*60)) + defer cancel() - // HPE Cloudline CL100 req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("https://%s/res/ok.png", p.host), nil) if err != nil { return bmcConnection, err @@ -141,7 +146,7 @@ func (p *Probe) hpCl100(ctx context.Context, log logr.Logger) (bmcConnection int defer resp.Body.Close() defer io.Copy(ioutil.Discard, resp.Body) // nolint - var firstBytes = make([]byte, 8) + firstBytes := make([]byte, 8) _, err = io.ReadFull(resp.Body, firstBytes) if err != nil { return bmcConnection, err @@ -153,10 +158,12 @@ func (p *Probe) hpCl100(ctx context.Context, log logr.Logger) (bmcConnection int } return bmcConnection, errors.ErrDeviceNotMatched - } func (p *Probe) idrac8(ctx context.Context, log logr.Logger) (bmcConnection interface{}, err error) { + ctx, cancel := context.WithTimeout(ctx, time.Duration(time.Second*60)) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("https://%s/session?aimGetProp=hostname,gui_str_title_bar,OEMHostName,fwVersion,sysDesc", p.host), nil) if err != nil { return bmcConnection, err @@ -183,6 +190,9 @@ func (p *Probe) idrac8(ctx context.Context, log logr.Logger) (bmcConnection inte } func (p *Probe) idrac9(ctx context.Context, log logr.Logger) (bmcConnection interface{}, err error) { + ctx, cancel := context.WithTimeout(ctx, time.Duration(time.Second*60)) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("https://%s/sysmgmt/2015/bmc/info", p.host), nil) if err != nil { return bmcConnection, err @@ -209,6 +219,9 @@ func (p *Probe) idrac9(ctx context.Context, log logr.Logger) (bmcConnection inte } func (p *Probe) m1000e(ctx context.Context, log logr.Logger) (bmcConnection interface{}, err error) { + ctx, cancel := context.WithTimeout(ctx, time.Duration(time.Second*60)) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("https://%s/cgi-bin/webcgi/login", p.host), nil) if err != nil { return bmcConnection, err @@ -235,6 +248,9 @@ func (p *Probe) m1000e(ctx context.Context, log logr.Logger) (bmcConnection inte } func (p *Probe) supermicrox(ctx context.Context, log logr.Logger) (bmcConnection interface{}, err error) { + ctx, cancel := context.WithTimeout(ctx, time.Duration(time.Second*60)) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("https://%s/cgi/login.cgi", p.host), nil) if err != nil { return bmcConnection, err @@ -255,6 +271,7 @@ func (p *Probe) supermicrox(ctx context.Context, log logr.Logger) (bmcConnection // looking for ATEN in the response payload isn't the most ideal way, although it is unique to Supermicros if resp.StatusCode == 200 && bytes.Contains(payload, []byte("ATEN International")) { log.V(1).Info("it's a supermicro", "step", "connection", "host", p.host, "vendor", devices.Supermicro, "hardwareType", supermicrox.X10) + conn, err := supermicrox.New(ctx, p.host, p.username, p.password, log) if err != nil { return bmcConnection, err @@ -271,6 +288,9 @@ func (p *Probe) supermicrox(ctx context.Context, log logr.Logger) (bmcConnection } func (p *Probe) supermicrox11(ctx context.Context, log logr.Logger) (bmcConnection interface{}, err error) { + ctx, cancel := context.WithTimeout(ctx, time.Duration(time.Second*60)) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("https://%s/cgi/login.cgi", p.host), nil) if err != nil { return bmcConnection, err @@ -290,6 +310,7 @@ func (p *Probe) supermicrox11(ctx context.Context, log logr.Logger) (bmcConnecti // looking for ATEN in the response payload isn't the most ideal way, although it is unique to Supermicros if resp.StatusCode == 200 && bytes.Contains(payload, []byte("ATEN International")) { log.V(1).Info("it's a supermicrox11", "step", "connection", "host", p.host, "vendor", devices.Supermicro, "hardwareType", supermicrox11.X11) + conn, err := supermicrox11.New(ctx, p.host, p.username, p.password, log) if err != nil { return bmcConnection, err @@ -306,6 +327,9 @@ func (p *Probe) supermicrox11(ctx context.Context, log logr.Logger) (bmcConnecti } func (p *Probe) quanta(ctx context.Context, log logr.Logger) (bmcConnection interface{}, err error) { + ctx, cancel := context.WithTimeout(ctx, time.Duration(time.Second*60)) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("https://%s/page/login.html", p.host), nil) if err != nil { return bmcConnection, err @@ -323,7 +347,7 @@ func (p *Probe) quanta(ctx context.Context, log logr.Logger) (bmcConnection inte return bmcConnection, err } - // ensure the response we got included a png + // Ensure the response we got includes a PNG. if resp.StatusCode == 200 && bytes.Contains(payload, []byte("Quanta")) { log.V(1).Info("step", "ScanAndConnect", "host", p.host, "vendor", string(devices.Quanta), "msg", "it's a quanta") return bmcConnection, errors.NewErrUnsupportedHardware("quanta hardware not supported") diff --git a/vendor/github.com/bmc-toolbox/bmclib/errors/errors.go b/vendor/github.com/bmc-toolbox/bmclib/errors/errors.go index ccffb950..59bccd54 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/errors/errors.go +++ b/vendor/github.com/bmc-toolbox/bmclib/errors/errors.go @@ -50,6 +50,27 @@ var ( // ErrDeviceNotMatched is the error returned when the device was not a type it was probed for ErrDeviceNotMatched = errors.New("the vendor device did not match the probe") + + // ErrRetrievingUserAccounts is returned when bmclib is unable to retrieve user accounts from the BMC + ErrRetrievingUserAccounts = errors.New("error retrieving user accounts") + + // ErrInvalidUserRole is returned when the given user account role is not valid + ErrInvalidUserRole = errors.New("invalid user account role") + + // ErrUserParamsRequired is returned when all the required user parameters are not provided - username, password, role + ErrUserParamsRequired = errors.New("username, password and role are required parameters") + + // ErrUserAccountExists is returned when a user account with the username is already present + ErrUserAccountExists = errors.New("user account already exists") + + // ErrNoUserSlotsAvailable is returned when there are no user account slots available + ErrNoUserSlotsAvailable = errors.New("no user account slots available") + + // ErrUserAccountNotFound is returned when the user account is not present + ErrUserAccountNotFound = errors.New("given user account does not exist") + + // ErrUserAccountUpdate is returned when the user account failed to be updated + ErrUserAccountUpdate = errors.New("user account attributes could not be updated") ) type ErrUnsupportedHardware struct { diff --git a/vendor/github.com/bmc-toolbox/bmclib/internal/utils.go b/vendor/github.com/bmc-toolbox/bmclib/internal/utils.go index 2fdc6248..71b19875 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/internal/utils.go +++ b/vendor/github.com/bmc-toolbox/bmclib/internal/utils.go @@ -1,15 +1,47 @@ package internal -import "unicode" +import ( + "errors" + "unicode" + + "github.com/bmc-toolbox/bmclib/cfgresources" +) // IsntLetterOrNumber check if the give rune is not a letter nor a number func IsntLetterOrNumber(c rune) bool { return !unicode.IsLetter(c) && !unicode.IsNumber(c) } -func ErrStringOrEmpty(err error) string { - if err == nil { - return "" +func IsRoleValid(role string) bool { + return role == "admin" || role == "user" || role == "operator" +} + +func ValidateUserConfig(cfgUsers []*cfgresources.User) (err error) { + for _, cfgUser := range cfgUsers { + if cfgUser.Name == "" { + msg := "User resource expects parameter: Name." + return errors.New(msg) + } + + if cfgUser.Password == "" { + msg := "User resource expects parameter: Password." + return errors.New(msg) + } + + if !IsRoleValid(cfgUser.Role) { + msg := "Parameter \"Role\" is one of ['admin', 'user']. You sent " + cfgUser.Role + return errors.New(msg + "!") + } + } + + return nil +} + +func StringInSlice(str string, sl []string) bool { + for _, s := range sl { + if str == s { + return true + } } - return err.Error() + return false } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/dell.go b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/dell.go index 3a8e91b0..c217f19f 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/dell.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/dell.go @@ -239,8 +239,7 @@ type IDracRoot struct { } // IDracPsSensorList contains a list of psu sensors -type IDracPsSensorList struct { -} +type IDracPsSensorList struct{} // IDracPsSensor contains the information regarding the psu devices type IDracPsSensor struct { @@ -395,7 +394,7 @@ type CMCWWNBlade struct { IsInstalled string `json:"isInstalled"` PortPMAC string `json:"portPMAC"` PortFMAC string `json:"portFMAC"` - IsSelected int `json:"isSelected"` //flexaddress enabled/disabled + IsSelected int `json:"isSelected"` // FlexAddress enabled/disabled. } `json:"is_not_double_height"` } @@ -441,7 +440,6 @@ func (d *CMCSlotMacWwn) UnmarshalJSON(data []byte) error { d.SlotMacWwnList[pos] = b } } - } return nil diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/actions.go b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/actions.go index d5fe87a9..310792b7 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/actions.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/actions.go @@ -3,6 +3,7 @@ package idrac8 import ( "fmt" "net/url" + "regexp" "strings" ) @@ -102,26 +103,36 @@ func (i *IDrac8) IsOn() (bool, error) { } // UpdateFirmware updates the bmc firmware -func (i *IDrac8) UpdateFirmware(source, file string) (bool, error) { - u, err := url.Parse(source) +func (i *IDrac8) UpdateFirmware(source, file string) (bool, string, error) { + _, err := url.Parse(source) if err != nil { - return false, err + return false, "", err } - password, ok := u.User.Password() - if !ok { - password = "anonymous" - } - - cmd := fmt.Sprintf("racadm fwupdate -f %s %s %s -d %s/%s", u.Host, u.User.Username(), password, u.Path, file) + cmd := fmt.Sprintf("racadm fwupdate -g -u -a %s -d %s", source, file) output, err := i.sshClient.Run(cmd) if err != nil { - return false, fmt.Errorf("output: %q: %w", output, err) + return false, output, fmt.Errorf("unexpected output: %q, error: %w", output, err) } if strings.Contains(output, "Firmware update completed successfully") { - return true, nil + return true, output, nil + } + + return false, output, fmt.Errorf("unexpected output: %q", output) +} + +func (i *IDrac8) CheckFirmwareVersion() (version string, err error) { + output, err := i.sshClient.Run("racadm getversion -f idrac") + if err != nil { + return "", fmt.Errorf("output: %q: %w", output, err) + } + + re := regexp.MustCompile(`.*iDRAC Version.*= ((\d+\.)+\d+)`) + matches := re.FindStringSubmatch(output) + if len(matches) > 1 { + return matches[1], nil } - return false, err + return "", fmt.Errorf("unexpected output: %q", output) } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/configure.go b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/configure.go index ad9af2ec..2e649a10 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/configure.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/configure.go @@ -50,12 +50,13 @@ func (i *IDrac8) Bios(cfg *cfgresources.Bios) (err error) { return err } -// escapeLdapString escapes ldap parameters strings func escapeLdapString(s string) string { r := "" for _, c := range s { - if c == '=' || c == ',' { - r += fmt.Sprintf("\\%c", c) + if c == '=' { + r += "%5C%3D" + } else if c == ',' { + r += "%5C%2C" } else { r += string(c) } @@ -64,126 +65,211 @@ func escapeLdapString(s string) string { return r } -// Return bool value if the role is valid. -func (i *IDrac8) isRoleValid(role string) bool { +func (i *IDrac8) runSshCommand(command string, id int) (success bool) { + output, err := i.sshClient.Run(command) + if err != nil { + // "The specified value is not allowed to be configured if the user name \nor password is blank\n" + // is an acceptable error while cleaning. Don't log that. + errString := err.Error() + if !strings.Contains(errString, "is blank") { + msg := fmt.Sprintf("IDRAC8 User(): Unable to reset existing user (ID %d). Error: %s", id, errString) + i.log.V(1).Error(err, msg, + "step", "applyUserParams", + "IP", i.ip, + "HardwareType", i.HardwareType(), + ) + } + return false + } - validRoles := []string{"admin", "user"} - for _, v := range validRoles { - if role == v { - return true + if !strings.Contains(output, "successful") { + msg := fmt.Sprintf("IDRAC8 User(): Unable to reset existing user (ID %d). Output: %s", id, output) + // "The specified value is not allowed to be configured if the user name \nor password is blank\n" + // is an acceptable error while cleaning. Don't log that. + if !strings.Contains(output, "is blank") { + err = errors.New("The output of the command `" + command + "` is " + output) + i.log.V(1).Error(err, msg, + "step", "applyUserParams", + "IP", i.ip, + "HardwareType", i.HardwareType(), + ) + return false } } - return false + return true } -// User applies the User configuration resource, -// if the user exists, it updates the users password, -// User implements the Configure interface. -// Iterate over iDrac users and adds/removes/modifies user accounts +// Applies the User configuration resource, obliterating any existing users. +// Implements the Configure interface. +// TODO: Forgives any errors happening (just logs though). Maybe that's not what we want? func (i *IDrac8) User(cfgUsers []*cfgresources.User) (err error) { - - err = i.validateUserCfg(cfgUsers) + err = internal.ValidateUserConfig(cfgUsers) if err != nil { - msg := "User config validation failed." + msg := "User config validation failed: " + err.Error() err = errors.New(msg) i.log.V(1).Error(err, msg, "step", "applyUserParams", "IP", i.ip, - "Model", i.HardwareType(), - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", i.HardwareType(), ) return err } - idracUsers, err := i.queryUsers() + usersInfo, err := i.queryUsers() if err != nil { - msg := "Unable to query existing users" - err = errors.New(msg) + msg := "IDRAC8 User(): Unable to query existing users." i.log.V(1).Error(err, msg, - "step", "applyUserParams", "IP", i.ip, - "Model", i.HardwareType(), - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", i.HardwareType(), ) - return err + return errors.New(msg + " Error: " + err.Error()) } - ////for each configuration user + usedIDs := make(map[int]bool) for _, cfgUser := range cfgUsers { + // If the user is not enabled in the config, just skip. + // The next section is going to wipe it out. + if !cfgUser.Enable { + continue + } - userID, userInfo, uExists := userInIdrac(cfgUser.Name, idracUsers) - //user to be added/updated - if cfgUser.Enable { - - //new user to be added - if !uExists { - userID, userInfo, err = getEmptyUserSlot(idracUsers) - if err != nil { - i.log.V(1).Info("Unable to add new User.", - "IP", i.ip, - "Model", i.HardwareType(), - "step", helper.WhosCalling(), - "User", cfgUser.Name, - "Error", internal.ErrStringOrEmpty(err), - ) - continue - } + // Does the user already exist? + newID := 0 + for userID, userInfo := range usersInfo { + if userInfo.UserName == cfgUser.Name { + usedIDs[userID] = true + newID = userID + break } + } - userInfo.Enable = "Enabled" - userInfo.SolEnable = "Enabled" - userInfo.UserName = cfgUser.Name - userInfo.Password = cfgUser.Password - - //set appropriate privileges - if cfgUser.Role == "admin" { - userInfo.Privilege = "511" - userInfo.IpmiLanPrivilege = "Administrator" - } else { - userInfo.Privilege = "499" - userInfo.IpmiLanPrivilege = "Operator" + // New user, pick an available ID. + if newID == 0 { + for userID := 2; userID <= 16; userID++ { + if !usedIDs[userID] { + usedIDs[userID] = true + newID = userID + break + } } + } - err = i.putUser(userID, userInfo) - if err != nil { - i.log.V(1).Info("Add/Update user request failed.", - "IP", i.ip, - "Model", i.HardwareType(), - "step", helper.WhosCalling(), - "User", cfgUser.Name, - "Error", internal.ErrStringOrEmpty(err), - ) - continue - } + // No available slots! + if newID == 0 { + msg := "IDRAC8 User(): Finding an empty user slot failed." + err = errors.New("No more available slots!") + i.log.V(1).Error(err, msg, + "IP", i.ip, + "HardwareType", i.HardwareType(), + ) + return errors.New(msg + " Error: " + err.Error()) + } - } // end if cfgUser.Enable - - //if the user exists but is disabled in our config, remove the user - if !cfgUser.Enable && uExists { - - userInfo.Enable = "Disabled" - userInfo.SolEnable = "Disabled" - userInfo.UserName = cfgUser.Name - userInfo.Privilege = "0" - userInfo.IpmiLanPrivilege = "No Access" - - err = i.putUser(userID, userInfo) - if err != nil { - i.log.V(1).Info("Disable user request failed.", - "IP", i.ip, - "Model", i.HardwareType(), - "step", helper.WhosCalling(), - "User", cfgUser.Name, - "Error", internal.ErrStringOrEmpty(err), - ) - } + mainCommand := fmt.Sprintf("racadm set iDRAC.Users.%d.", newID) + + command := mainCommand + fmt.Sprintf("Username \"%s\"", cfgUser.Name) + i.runSshCommand(command, newID) + + command = mainCommand + fmt.Sprintf("Password \"%s\"", cfgUser.Password) + i.runSshCommand(command, newID) + + command = mainCommand + "Enable \"Enabled\"" + i.runSshCommand(command, newID) + + if cfgUser.SolEnable { + command = mainCommand + "SolEnable \"Enabled\"" + } else { + command = mainCommand + "SolEnable \"Disabled\"" + } + i.runSshCommand(command, newID) + + if cfgUser.SNMPv3Enable { + command = mainCommand + "SNMPv3Enable \"Enabled\"" + } else { + command = mainCommand + "SNMPv3Enable \"Disabled\"" + } + i.runSshCommand(command, newID) + + if cfgUser.Role == "admin" { + // The number comes from 0x1FF. We reverse-engineered that by setting the user + // manually to have Administrator access in IDRAC's UI, and then SSH and run + // `racadm get iDRAC.Users.4` (replace 4 by the user you have edited). + // You get something like + // [Key=iDRAC.Embedded.1#Users.4] + // Enable=Enabled + // IpmiLanPrivilege=3 + // MD5v3Key=... + // !!Password=******** (Write-Only) + // Privilege=0x1ff + // SHA1v3Key=... + // SHA256Password=... + // SHA256PasswordSalt=... + // SNMPv3AuthenticationType=SHA + // SNMPv3Enable=Disabled + // SNMPv3PrivacyType=AES + // SolEnable=Disabled + // UserName=HOperator + command = mainCommand + "Privilege 511" + } else if cfgUser.Role == "operator" { + // The number comes from 0x1F3. + command = mainCommand + "Privilege 499" + } else if cfgUser.Role == "user" { + // This one is actually called Read Only in IDRAC, but for simplicity + // we use the same value for both Privilege and IpmiLanPrivilege. + command = mainCommand + "Privilege 1" + } else { + command = mainCommand + "Privilege 0" // No Access! + } + i.runSshCommand(command, newID) + + if cfgUser.Role == "admin" { + command = mainCommand + "IpmiLanPrivilege 4" + } else if cfgUser.Role == "operator" { + command = mainCommand + "IpmiLanPrivilege 3" + } else if cfgUser.Role == "user" { + command = mainCommand + "IpmiLanPrivilege 2" + } else { + command = mainCommand + "IpmiLanPrivilege 15" // No Access! + } + i.runSshCommand(command, newID) + } + + for userID := 2; userID <= 16; userID++ { + // Avoid used slots. + if usedIDs[userID] { + continue } - i.log.V(1).Info("User parameters applied.", "IP", i.ip, "Model", i.HardwareType(), "User", cfgUser.Name) + mainCommand := fmt.Sprintf("racadm set iDRAC.Users.%d.", userID) + + // Just temporarily. Some of the commands will fail with the message + // "The specified value is not allowed to be configured if the user name or password is blank." + // That's why we give a temporary name, and then blank it at the end. + command := mainCommand + fmt.Sprintf("Username \"TempUser%02d\"", userID) + i.runSshCommand(command, userID) + + command = mainCommand + "Enable \"Disabled\"" + i.runSshCommand(command, userID) + + command = mainCommand + "SolEnable \"Disabled\"" + i.runSshCommand(command, userID) + + command = mainCommand + "SNMPv3Enable \"Disabled\"" + i.runSshCommand(command, userID) + + command = mainCommand + "Privilege 0" + i.runSshCommand(command, userID) + + command = mainCommand + "IpmiLanPrivilege 15" + i.runSshCommand(command, userID) + + // Now, really clean the username. + command = mainCommand + "Username \"\"" + i.runSshCommand(command, userID) } - return err + return nil } // Syslog applies the Syslog configuration resource @@ -194,7 +280,6 @@ func (i *IDrac8) User(cfgUsers []*cfgresources.User) (err error) { // and since not all BMCs currently support configuring filtering for alerts, // for now the configuration for alert filters/enabling is managed through this method. func (i *IDrac8) Syslog(cfg *cfgresources.Syslog) (err error) { - var port int enable := "Enabled" @@ -266,7 +351,7 @@ func (i *IDrac8) Syslog(cfg *cfgresources.Syslog) (err error) { return err } - i.log.V(1).Info("Syslog parameters applied.", "IP", i.ip, "Model", i.HardwareType()) + i.log.V(1).Info("Syslog parameters applied.", "IP", i.ip, "HardwareType", i.HardwareType()) return err } @@ -274,7 +359,6 @@ func (i *IDrac8) Syslog(cfg *cfgresources.Syslog) (err error) { // Ntp applies NTP configuration params // Ntp implements the Configure interface. func (i *IDrac8) Ntp(cfg *cfgresources.Ntp) (err error) { - if cfg.Server1 == "" { i.log.V(1).Info("NTP resource expects parameter: server1.", "step", "apply-ntp-cfg") return @@ -292,7 +376,6 @@ func (i *IDrac8) Ntp(cfg *cfgresources.Ntp) (err error) { } func (i *IDrac8) applyNtpServerParam(cfg *cfgresources.Ntp) { - var enable int if !cfg.Enable { i.log.V(1).Info("Ntp resource declared with enable: false.", "step", helper.WhosCalling()) @@ -301,54 +384,56 @@ func (i *IDrac8) applyNtpServerParam(cfg *cfgresources.Ntp) { enable = 1 } - //https://10.193.251.10/data?set=tm_ntp_int_opmode:1, \\ - // tm_ntp_str_server1:ntp0.lhr4.example.com, \\ - // tm_ntp_str_server2:ntp0.ams4.example.com, \\ + // https://10.193.251.10/data?set=tm_ntp_int_opmode:1, + // tm_ntp_str_server1:ntp0.lhr4.example.com, + // tm_ntp_str_server2:ntp0.ams4.example.com, // tm_ntp_str_server3:ntp0.fra4.example.com queryStr := fmt.Sprintf("set=tm_ntp_int_opmode:%d,", enable) queryStr += fmt.Sprintf("tm_ntp_str_server1:%s,", cfg.Server1) queryStr += fmt.Sprintf("tm_ntp_str_server2:%s,", cfg.Server2) queryStr += fmt.Sprintf("tm_ntp_str_server3:%s,", cfg.Server3) - //GET - params as query string - //ntp servers - endpoint := fmt.Sprintf("data?%s", queryStr) - response, err := i.get(endpoint, nil) - if err != nil { - i.log.V(1).Info("GET request failed.", + statusCode, response, err := i.get(endpoint, nil) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + i.log.V(1).Error(err, "applyNtpServerParam(): GET request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "endpoint", endpoint, + "StatusCode", statusCode, "step", helper.WhosCalling(), "response", string(response), ) } - i.log.V(1).Info("NTP servers param applied.", "IP", i.ip, "Model", i.HardwareType()) - + i.log.V(1).Info("NTP servers param applied.", "IP", i.ip, "HardwareType", i.HardwareType()) } // Ldap applies LDAP configuration params. // Ldap implements the Configure interface. func (i *IDrac8) Ldap(cfg *cfgresources.Ldap) error { - if cfg.Server == "" { - msg := "ldap resource parameter Server required but not declared." + msg := "LDAP resource parameter \"Server\" required but not declared." err := errors.New(msg) i.log.V(1).Error(err, msg, "step", "applyLdapServerParam") return err } endpoint := fmt.Sprintf("data?set=xGLServer:%s", cfg.Server) - response, err := i.get(endpoint, nil) - if err != nil { - msg := "Request to set ldap server failed." - err = errors.New(msg) - i.log.V(1).Error(err, msg, + statusCode, response, err := i.get(endpoint, nil) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + i.log.V(1).Error(err, "Request to set LDAP server failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "endpoint", endpoint, + "StatusCode", statusCode, "step", helper.WhosCalling(), "response", string(response), ) @@ -360,14 +445,13 @@ func (i *IDrac8) Ldap(cfg *cfgresources.Ldap) error { return err } - i.log.V(1).Info("Ldap server param set.", "IP", i.ip, "Model", i.HardwareType()) + i.log.V(1).Info("Ldap server param set.", "IP", i.ip, "HardwareType", i.HardwareType()) return nil } // Applies ldap search filter param. // set=xGLSearchFilter:objectClass\=posixAccount func (i *IDrac8) applyLdapSearchFilterParam(cfg *cfgresources.Ldap) error { - if cfg.SearchFilter == "" { msg := "Ldap resource parameter SearchFilter required but not declared." err := errors.New(msg) @@ -376,122 +460,123 @@ func (i *IDrac8) applyLdapSearchFilterParam(cfg *cfgresources.Ldap) error { } endpoint := fmt.Sprintf("data?set=xGLSearchFilter:%s", escapeLdapString(cfg.SearchFilter)) - response, err := i.get(endpoint, nil) - if err != nil { - msg := "request to set ldap search filter failed." - i.log.V(1).Error(err, msg, + statusCode, response, err := i.get(endpoint, nil) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + i.log.V(1).Error(err, "Request to set LDAP search filter failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "endpoint", endpoint, + "StatusCode", statusCode, "step", helper.WhosCalling(), "response", string(response), ) return err } - i.log.V(1).Info("Ldap search filter param applied.", "IP", i.ip, "Model", i.HardwareType()) + i.log.V(1).Info("Ldap search filter param applied.", "IP", i.ip, "HardwareType", i.HardwareType()) return nil } -// LdapGroup applies LDAP Group/Role related configuration -// LdapGroup implements the Configure interface. -// nolint: gocyclo -func (i *IDrac8) LdapGroup(cfgGroup []*cfgresources.LdapGroup, cfgLdap *cfgresources.Ldap) (err error) { - - groupID := 1 - - //set to decide what privileges the group should have - //497 == operator - //511 == administrator (full privileges) - privID := "0" - - //groupPrivilegeParam is populated per group and is passed to i.applyLdapRoleGroupPrivParam - groupPrivilegeParam := "" - - //first some preliminary checks +// Applies LDAP Group/Role related configuration. +// Implements the Configure interface. +func (i *IDrac8) LdapGroups(cfgGroups []*cfgresources.LdapGroup, cfgLdap *cfgresources.Ldap) (err error) { + // Preliminary checks: if cfgLdap.Port == 0 { - msg := "Ldap resource parameter Port required but not declared" + msg := "LDAP resource parameter \"Port\" is required!" err = errors.New(msg) i.log.V(1).Error(err, msg, "step", "applyLdapRoleGroupPrivParam") return err } if cfgLdap.BaseDn == "" { - msg := "Ldap resource parameter BaseDn required but not declared." + msg := "LDAP resource parameter \"BaseDn\" is required!" err = errors.New(msg) i.log.V(1).Error(err, msg, "step", "applyLdapRoleGroupPrivParam") return err } if cfgLdap.UserAttribute == "" { - msg := "Ldap resource parameter userAttribute required but not declared." + msg := "LDAP resource parameter \"userAttribute\" is required!" err = errors.New(msg) i.log.V(1).Error(err, msg, "step", "applyLdapRoleGroupPrivParam") return err } if cfgLdap.GroupAttribute == "" { - msg := "Ldap resource parameter groupAttribute required but not declared." + msg := "LDAP resource parameter \"groupAttribute\" is required!" err = errors.New(msg) i.log.V(1).Error(err, msg, "step", "applyLdapRoleGroupPrivParam") return err } - //for each ldap group - for _, group := range cfgGroup { - - //if a group has been set to disable in the config, - //its configuration is skipped and removed. - if !group.Enable { - continue - } - - if group.Role == "" { - msg := "Ldap resource parameter Role required but not declared." - i.log.V(1).Info(msg, "Role", group.Role, "step", "applyLdapGroupParams") - continue - } - + for _, group := range cfgGroups { if group.Group == "" { - msg := "Ldap resource parameter Group required but not declared." + msg := "LDAP resource parameter \"Group\" is required!" err = errors.New(msg) - i.log.V(1).Error(err, msg, "Role", group.Role, "step", "applyLdapGroupParams") + i.log.V(1).Error(err, msg, "step", "applyLdapGroupParams") return err } if group.GroupBaseDn == "" { - msg := "Ldap resource parameter GroupBaseDn required but not declared." + msg := "LDAP resource parameter \"GroupBaseDn\" is required!" err = errors.New(msg) - i.log.V(1).Error(err, msg, "Role", group.Role, "step", "applyLdapGroupParams") + i.log.V(1).Error(err, msg, "step", "applyLdapGroupParams") return err } - if !i.isRoleValid(group.Role) { - msg := "Ldap resource Role must be a valid role: admin OR user." + if !internal.IsRoleValid(group.Role) { + msg := "LDAP resource parameter \"Role\" must be a valid role: \"admin\" OR \"user\"." err = errors.New(msg) i.log.V(1).Error(err, msg, "Role", group.Role, "step", "applyLdapGroupParams") return err } + } + + // Now, time to do the actual work! + groupID := 1 + + // What privileges should the group have? + // 497: Operator + // 511: Administrator (full privileges) + privID := "0" + + // Populated per group, passed to i.applyLdapRoleGroupPrivParam() + groupPrivilegeParam := "" + + for _, group := range cfgGroups { + // If a group has been set to `disable` in the config, its configuration is skipped. + if !group.Enable { + continue + } groupDn := fmt.Sprintf("%s,%s", group.Group, group.GroupBaseDn) groupDn = escapeLdapString(groupDn) endpoint := fmt.Sprintf("data?set=xGLGroup%dName:%s", groupID, groupDn) - response, err := i.get(endpoint, nil) - if err != nil { - i.log.V(1).Error(err, "GET request failed.", + statusCode, response, err := i.get(endpoint, nil) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + i.log.V(1).Error(err, "LdapGroups(): GET request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "endpoint", endpoint, + "StatusCode", statusCode, "step", "applyLdapGroupParams", "response", string(response), ) return err } - i.log.V(1).Info("Ldap GroupDN config applied.", + i.log.V(1).Info("LDAP GroupDN config applied.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "Role", group.Role, ) @@ -504,19 +589,37 @@ func (i *IDrac8) LdapGroup(cfgGroup []*cfgresources.LdapGroup, cfgLdap *cfgresou groupPrivilegeParam += fmt.Sprintf("xGLGroup%dPriv:%s,", groupID, privID) groupID++ - } - //set the rest of the group privileges to 0 - for i := groupID + 1; i <= 5; i++ { - groupPrivilegeParam += fmt.Sprintf("xGLGroup%dPriv:0,", i) + // Set the rest of the group privileges to 0, and the DNs to empty strings. + // Dell supports only 5 groups. + for g := groupID; g <= 5; g++ { + groupPrivilegeParam += fmt.Sprintf("xGLGroup%dPriv:0,", g) + + endpoint := fmt.Sprintf("data?set=xGLGroup%dName:%s", g, "") + statusCode, response, err := i.get(endpoint, nil) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + i.log.V(1).Error(err, "GET request failed.", + "IP", i.ip, + "HardwareType", i.HardwareType(), + "endpoint", endpoint, + "StatusCode", statusCode, + "step", "applyLdapGroupParams", + "response", string(response), + ) + // No need to return an error here, since the privilege of this group is none anyway. + } } err = i.applyLdapRoleGroupPrivParam(cfgLdap, groupPrivilegeParam) if err != nil { i.log.V(1).Error(err, "Unable to set Ldap Role Group Privileges.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", "applyLdapGroupParams", ) return err @@ -525,18 +628,16 @@ func (i *IDrac8) LdapGroup(cfgGroup []*cfgresources.LdapGroup, cfgLdap *cfgresou } // Apply ldap group privileges -//https://10.193.251.10/postset?ldapconf +// https://10.193.251.10/postset?ldapconf // data=LDAPEnableMode:3,xGLNameSearchEnabled:0,xGLBaseDN:ou%5C%3DPeople%5C%2Cdc%5C%3Dactivehotels%5C%2Cdc%5C%3Dcom,xGLUserLogin:uid,xGLGroupMem:memberUid,xGLBindDN:,xGLCertValidationEnabled:1,xGLGroup1Priv:511,xGLGroup2Priv:97,xGLGroup3Priv:0,xGLGroup4Priv:0,xGLGroup5Priv:0,xGLServerPort:636 func (i *IDrac8) applyLdapRoleGroupPrivParam(cfg *cfgresources.Ldap, groupPrivilegeParam string) (err error) { - baseDn := escapeLdapString(cfg.BaseDn) - payload := "data=LDAPEnableMode:3," //setup generic ldap - payload += "xGLNameSearchEnabled:0," //lookup ldap server from dns + payload := "data=LDAPEnableMode:3," // Generic LDAP + payload += "xGLNameSearchEnabled:0," // Lookup LDAP server from DNS payload += fmt.Sprintf("xGLBaseDN:%s,", baseDn) payload += fmt.Sprintf("xGLUserLogin:%s,", cfg.UserAttribute) payload += fmt.Sprintf("xGLGroupMem:%s,", cfg.GroupAttribute) - //if bindDn was declared, we set it. if cfg.BindDn != "" { bindDn := escapeLdapString(cfg.BindDn) payload += fmt.Sprintf("xGLBindDN:%s,", bindDn) @@ -544,17 +645,16 @@ func (i *IDrac8) applyLdapRoleGroupPrivParam(cfg *cfgresources.Ldap, groupPrivil payload += "xGLBindDN:," } - payload += "xGLCertValidationEnabled:0," //we may want to be able to set this from config + payload += "xGLCertValidationEnabled:0," // TODO: Set this from config? payload += groupPrivilegeParam payload += fmt.Sprintf("xGLServerPort:%d", cfg.Port) - //fmt.Println(payload) endpoint := "postset?ldapconf" responseCode, responseBody, err := i.post(endpoint, []byte(payload), "") if err != nil || responseCode != 200 { i.log.V(1).Error(err, "POST request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "endpoint", endpoint, "step", helper.WhosCalling(), "responseCode", responseCode, @@ -563,36 +663,38 @@ func (i *IDrac8) applyLdapRoleGroupPrivParam(cfg *cfgresources.Ldap, groupPrivil return err } - i.log.V(1).Info("Ldap Group role privileges applied.", "IP", i.ip, "Model", i.HardwareType()) + i.log.V(1).Info("LDAP Group role privileges applied.", "IP", i.ip, "HardwareType", i.HardwareType()) return err } func (i *IDrac8) applyTimezoneParam(timezone string) { - //POST - params as query string - //timezone - //https://10.193.251.10/data?set=tm_tz_str_zone:CET + // POST - params as query string + // https://10.193.251.10/data?set=tm_tz_str_zone:CET endpoint := fmt.Sprintf("data?set=tm_tz_str_zone:%s", timezone) - response, err := i.get(endpoint, nil) - if err != nil { - i.log.V(1).Info("GET request failed.", + statusCode, response, err := i.get(endpoint, nil) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + i.log.V(1).Error(err, "applyTimezoneParam(): GET request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "endpoint", endpoint, + "StatusCode", statusCode, "step", helper.WhosCalling(), "response", string(response), ) } - i.log.V(1).Info("Timezone param applied.", "IP", i.ip, "Model", i.HardwareType()) - + i.log.V(1).Info("Timezone param applied.", "IP", i.ip, "HardwareType", i.HardwareType()) } // Network method implements the Configure interface // applies various network parameters. func (i *IDrac8) Network(cfg *cfgresources.Network) (reset bool, err error) { - params := map[string]int{ "EnableIPv4": 1, "DHCPEnable": 1, @@ -619,8 +721,8 @@ func (i *IDrac8) Network(cfg *cfgresources.Network) (reset bool, err error) { payload := fmt.Sprintf("dhcpForDNSDomain:%d,", params["DNSFromDHCP"]) payload += fmt.Sprintf("ipmiLAN:%d,", params["EnableIpmiOverLan"]) payload += fmt.Sprintf("serialOverLanEnabled:%d,", params["EnableSerialOverLan"]) - payload += "serialOverLanBaud:3," //115.2 kbps - payload += "serialOverLanPriv:0," //Administrator + payload += "serialOverLanBaud:3," // 115.2 kbps + payload += "serialOverLanPriv:0," // Administrator payload += fmt.Sprintf("racRedirectEna:%d,", params["EnableSerialRedirection"]) payload += "racEscKey:^\\\\" @@ -628,7 +730,7 @@ func (i *IDrac8) Network(cfg *cfgresources.Network) (reset bool, err error) { if err != nil || responseCode != 200 { i.log.V(1).Error(err, "POST request to set Network params failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "endpoint", endpoint, "step", helper.WhosCalling(), "responseCode", responseCode, @@ -637,13 +739,12 @@ func (i *IDrac8) Network(cfg *cfgresources.Network) (reset bool, err error) { return reset, err } - i.log.V(1).Info("Network config parameters applied.", "IP", i.ip, "Model", i.HardwareType()) + i.log.V(1).Info("Network config parameters applied.", "IP", i.ip, "HardwareType", i.HardwareType()) return reset, err } // GenerateCSR generates a CSR request on the BMC. func (i *IDrac8) GenerateCSR(cert *cfgresources.HTTPSCertAttributes) ([]byte, error) { - var payload []string endpoint := "bindata?set" @@ -660,19 +761,23 @@ func (i *IDrac8) GenerateCSR(cert *cfgresources.HTTPSCertAttributes) ([]byte, er queryString := url.QueryEscape(fmt.Sprintf("%s=serverCSR(%s)", endpoint, strings.Join(payload, ","))) - body, err := i.get(queryString, nil) - if err != nil { - i.log.V(1).Error(err, "GET request failed.", + statusCode, response, err := i.get(queryString, nil) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + i.log.V(1).Error(err, "GenerateCSR(): GET request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "endpoint", endpoint, + "StatusCode", statusCode, "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) return []byte{}, err } - return body, nil + return response, nil } // UploadHTTPSCert uploads the given CRT cert, @@ -680,7 +785,6 @@ func (i *IDrac8) GenerateCSR(cert *cfgresources.HTTPSCertAttributes) ([]byte, er // 1. POST upload signed x509 cert in multipart form. // 2. POST returned resource URI func (i *IDrac8) UploadHTTPSCert(cert []byte, certFileName string, key []byte, keyFileName string) (bool, error) { - endpoint := "sysmgmt/2012/server/transient/filestore?fileupload=true" endpoint += fmt.Sprintf("&ST1=%s", i.st1) @@ -720,36 +824,38 @@ func (i *IDrac8) UploadHTTPSCert(cert []byte, certFileName string, key []byte, k // 1. POST upload x509 cert status, body, err := i.post(endpoint, form.Bytes(), w.FormDataContentType()) if err != nil || status != 201 { - i.log.V(1).Error(err, "Cert form upload POST request failed, expected 201.", + if err == nil { + err = fmt.Errorf("Cert form upload POST request to %s failed with status code %d.", endpoint, status) + } + + i.log.V(1).Error(err, "UploadHTTPSCert(): Cert form upload POST request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "endpoint", endpoint, "step", helper.WhosCalling(), - "status", status, + "StatusCode", status, ) return false, err } // extract resourceURI from response - var certStore = new(certStore) + certStore := new(certStore) err = json.Unmarshal(body, certStore) if err != nil { - i.log.V(1).Error(err, "Unable to unmarshal cert store response payload.", + i.log.V(1).Error(err, "UploadHTTPSCert(): Unable to unmarshal cert store response payload.", "step", helper.WhosCalling(), "IP", i.ip, - "Model", i.HardwareType(), - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", i.HardwareType(), ) return false, err } resourceURI, err := json.Marshal(certStore.File) if err != nil { - i.log.V(1).Error(err, "Unable to marshal cert store resource URI.", + i.log.V(1).Error(err, "UploadHTTPSCert(): Unable to marshal cert store resource URI.", "step", helper.WhosCalling(), "IP", i.ip, - "Model", i.HardwareType(), - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", i.HardwareType(), ) return false, err } @@ -758,16 +864,19 @@ func (i *IDrac8) UploadHTTPSCert(cert []byte, certFileName string, key []byte, k endpoint = "sysmgmt/2012/server/network/ssl/cert" status, _, err = i.post(endpoint, []byte(resourceURI), "") if err != nil || status != 201 { - i.log.V(1).Error(err, "Cert form upload POST request failed, expected 201.", + if err == nil { + err = fmt.Errorf("Cert form upload POST request to %s failed with status code %d.", endpoint, status) + } + + i.log.V(1).Error(err, "UploadHTTPSCert(): Cert form upload POST request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "endpoint", endpoint, "step", helper.WhosCalling(), - "status", status, + "StatusCode", status, ) return false, err } - return true, err - + return true, nil } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/helpers.go b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/helpers.go deleted file mode 100644 index 58226f46..00000000 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/helpers.go +++ /dev/null @@ -1,94 +0,0 @@ -package idrac8 - -import ( - "encoding/json" - "errors" - "fmt" - - "github.com/bmc-toolbox/bmclib/cfgresources" -) - -// Return bool value if the role is valid. -func isRoleValid(role string) bool { - validRoles := []string{"admin", "user"} - for _, v := range validRoles { - if role == v { - return true - } - } - - return false -} - -// Return bool value if the role is valid. -func (i *IDrac8) validateUserCfg(cfgUsers []*cfgresources.User) error { - for _, cfgUser := range cfgUsers { - if cfgUser.Name == "" { - return errors.New("user resource expects parameter: Name") - } - - if cfgUser.Password == "" { - return errors.New("user resource expects parameter: Password") - } - - if !isRoleValid(cfgUser.Role) { - return errors.New("user resource expects parameter Role to be one of 'admin', 'user'") - } - } - - return nil -} - -// IDrac8 supports upto 16 users, user 0 is reserved -// this function returns an empty user slot that can be used for a new user account -func getEmptyUserSlot(idracUsers UserInfo) (userID int, user User, err error) { - for userID, user := range idracUsers { - if userID == 1 { - continue - } - - // from the web UI idrac8 doesn't allow removing users only disabling users. - // There is a case where all user.UserName are NOT == "". This doens't mean that a new - // user cannot be created. Disabled users regardless of whether user.UserName == "" can be - // used for new user creation. FYI, ipmitool can remove the name: ipmitool user set name "" - if user.UserName == "" || user.Enable == "disabled" { - return userID, user, err - } - } - - return 0, user, errors.New("all user account slots in use, remove an account before adding a new one") -} - -// checks if a user is present in a given list -func userInIdrac(user string, usersInfo UserInfo) (userID int, userInfo User, exists bool) { - for userID, userInfo := range usersInfo { - if userInfo.UserName == user { - return userID, userInfo, true - } - } - - return userID, userInfo, false -} - -// PUTs user config -func (i *IDrac8) putUser(userID int, user User) error { - idracPayload := make(map[string]User) - idracPayload["iDRAC.Users"] = user - - payload, err := json.Marshal(idracPayload) - if err != nil { - return fmt.Errorf("error unmarshalling User payload: %w", err) - } - - endpoint := fmt.Sprintf("sysmgmt/2012/server/configgroup/iDRAC.Users.%d", userID) - statusCode, _, err := i.put(endpoint, payload) - if err != nil { - return fmt.Errorf("PUT request to set User config returned error: %w", err) - } - - if statusCode != 200 { - return fmt.Errorf("PUT request to set User config returned status code: %d", statusCode) - } - - return nil -} diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/idrac8.go b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/idrac8.go index d95bdda6..fa039471 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/idrac8.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/idrac8.go @@ -65,13 +65,13 @@ func (i *IDrac8) put(endpoint string, payload []byte) (statusCode int, response req, err := http.NewRequest("PUT", fmt.Sprintf("%s/%s", bmcURL, endpoint), bytes.NewReader(payload)) if err != nil { - return statusCode, response, err + return 0, nil, err } req.Header.Add("ST2", i.st2) u, err := url.Parse(bmcURL) if err != nil { - return statusCode, response, err + return 0, nil, err } for _, cookie := range i.httpClient.Jar.Cookies(u) { @@ -85,8 +85,9 @@ func (i *IDrac8) put(endpoint string, payload []byte) (statusCode int, response resp, err := i.httpClient.Do(req) if err != nil { - return statusCode, response, err + return 0, nil, err } + defer resp.Body.Close() respDump, _ := httputil.DumpResponse(resp, true) @@ -127,7 +128,6 @@ func (i *IDrac8) post(endpoint string, data []byte, formDataContentType string) if formDataContentType == "" { req.Header.Add("Content-Type", "application/x-www-form-urlencoded") } else { - // Set multipart form content type req.Header.Set("Content-Type", formDataContentType) @@ -155,18 +155,16 @@ func (i *IDrac8) post(endpoint string, data []byte, formDataContentType string) return 0, []byte{}, err } - //fmt.Printf("%s\n", body) return resp.StatusCode, body, err } -// get calls a given json endpoint of the ilo and returns the data -func (i *IDrac8) get(endpoint string, extraHeaders *map[string]string) (payload []byte, err error) { +func (i *IDrac8) get(endpoint string, extraHeaders *map[string]string) (statusCode int, payload []byte, err error) { i.log.V(1).Info("retrieving data from bmc", "step", "bmc connection", "vendor", dell.VendorID, "ip", i.ip, "endpoint", endpoint) bmcURL := fmt.Sprintf("https://%s", i.ip) req, err := http.NewRequest("GET", fmt.Sprintf("%s/%s", bmcURL, endpoint), nil) if err != nil { - return payload, err + return 0, nil, err } req.Header.Add("ST2", i.st2) if extraHeaders != nil { @@ -177,7 +175,7 @@ func (i *IDrac8) get(endpoint string, extraHeaders *map[string]string) (payload u, err := url.Parse(bmcURL) if err != nil { - return payload, err + return 0, nil, err } for _, cookie := range i.httpClient.Jar.Cookies(u) { @@ -190,7 +188,7 @@ func (i *IDrac8) get(endpoint string, extraHeaders *map[string]string) (payload resp, err := i.httpClient.Do(req) if err != nil { - return payload, err + return 0, nil, err } defer resp.Body.Close() respDump, _ := httputil.DumpResponse(resp, true) @@ -198,14 +196,14 @@ func (i *IDrac8) get(endpoint string, extraHeaders *map[string]string) (payload payload, err = ioutil.ReadAll(resp.Body) if err != nil { - return payload, err + return 0, nil, err } if resp.StatusCode == 404 { - return payload, errors.ErrPageNotFound + return 404, payload, errors.ErrPageNotFound } - return payload, err + return resp.StatusCode, payload, err } // Nics returns all found Nics in the device @@ -267,19 +265,19 @@ func (i *IDrac8) Nics() (nics []*devices.Nic, err error) { func (i *IDrac8) Serial() (serial string, err error) { err = i.loadHwData() if err != nil { - return serial, err + return "", err } for _, component := range i.iDracInventory.Component { if component.Classname == "DCIM_SystemView" { for _, property := range component.Properties { if property.Name == "NodeID" && property.Type == "string" { - return strings.ToLower(property.Value), err + return strings.ToLower(property.Value), nil } } } } - return serial, err + return "", nil } // ChassisSerial returns the serial number of the chassis where the blade is attached @@ -305,23 +303,27 @@ func (i *IDrac8) ChassisSerial() (serial string, err error) { func (i *IDrac8) Status() (status string, err error) { err = i.httpLogin() if err != nil { - return status, err + return "", err } extraHeaders := &map[string]string{ "X-SYSMGMT-OPTIMIZE": "true", } - url := "sysmgmt/2016/server/extended_health" - payload, err := i.get(url, extraHeaders) - if err != nil { - return status, err + endpoint := "sysmgmt/2016/server/extended_health" + statusCode, response, err := i.get(endpoint, extraHeaders) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + return "", err } iDracHealthStatus := &dell.IDracHealthStatus{} - err = json.Unmarshal(payload, iDracHealthStatus) + err = json.Unmarshal(response, iDracHealthStatus) if err != nil { - return status, err + return "", err } for _, entry := range iDracHealthStatus.HealthStatus { @@ -340,14 +342,18 @@ func (i *IDrac8) PowerKw() (power float64, err error) { return power, err } - url := "data?get=powermonitordata" - payload, err := i.get(url, nil) - if err != nil { + endpoint := "data?get=powermonitordata" + statusCode, response, err := i.get(endpoint, nil) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + return power, err } iDracRoot := &dell.IDracRoot{} - err = xml.Unmarshal(payload, iDracRoot) + err = xml.Unmarshal(response, iDracRoot) if err != nil { return power, err } @@ -501,23 +507,27 @@ func (i *IDrac8) HardwareType() (bmcType string) { func (i *IDrac8) License() (name string, licType string, err error) { err = i.httpLogin() if err != nil { - return name, licType, err + return "", "", err } extraHeaders := &map[string]string{ "X_SYSMGMT_OPTIMIZE": "true", } - url := "sysmgmt/2012/server/license" - payload, err := i.get(url, extraHeaders) - if err != nil { - return name, licType, err + endpoint := "sysmgmt/2012/server/license" + statusCode, response, err := i.get(endpoint, extraHeaders) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + return "", "", err } iDracLicense := &dell.IDracLicense{} - err = json.Unmarshal(payload, iDracLicense) + err = json.Unmarshal(response, iDracLicense) if err != nil { - return name, licType, err + return "", "", err } if iDracLicense.License.VConsole == 1 { @@ -603,23 +613,27 @@ func (i *IDrac8) Disks() (disks []*devices.Disk, err error) { func (i *IDrac8) TempC() (temp int, err error) { err = i.httpLogin() if err != nil { - return temp, err + return 0, err } extraHeaders := &map[string]string{ "X_SYSMGMT_OPTIMIZE": "true", } - url := "sysmgmt/2012/server/temperature" - payload, err := i.get(url, extraHeaders) - if err != nil { - return temp, err + endpoint := "sysmgmt/2012/server/temperature" + statusCode, response, err := i.get(endpoint, extraHeaders) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + return 0, err } iDracTemp := &dell.IDracTemp{} - err = json.Unmarshal(payload, iDracTemp) + err = json.Unmarshal(response, iDracTemp) if err != nil { - return temp, err + return 0, err } return iDracTemp.Temperatures.IDRACEmbedded1SystemBoardInletTemp.Reading, err @@ -636,14 +650,18 @@ func (i *IDrac8) CPU() (cpu string, cpuCount int, coreCount int, hyperthreadCoun "X_SYSMGMT_OPTIMIZE": "true", } - url := "sysmgmt/2012/server/processor" - payload, err := i.get(url, extraHeaders) - if err != nil { - return cpu, cpuCount, coreCount, hyperthreadCount, err + endpoint := "sysmgmt/2012/server/processor" + statusCode, response, err := i.get(endpoint, extraHeaders) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + return "", 0, 0, 0, err } dellBladeProc := &dell.BladeProcessorEndpoint{} - err = json.Unmarshal(payload, dellBladeProc) + err = json.Unmarshal(response, dellBladeProc) if err != nil { return cpu, cpuCount, coreCount, hyperthreadCount, err } @@ -684,19 +702,23 @@ func (i *IDrac8) IsBlade() (isBlade bool, err error) { func (i *IDrac8) Psus() (psus []*devices.Psu, err error) { err = i.httpLogin() if err != nil { - return psus, err + return nil, err } - url := "data?get=powerSupplies" - payload, err := i.get(url, nil) - if err != nil { - return psus, err + endpoint := "data?get=powerSupplies" + statusCode, response, err := i.get(endpoint, nil) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + return nil, err } iDracRoot := &dell.IDracRoot{} - err = xml.Unmarshal(payload, iDracRoot) + err = xml.Unmarshal(response, iDracRoot) if err != nil { - return psus, err + return nil, err } serial, _ := i.Serial() @@ -722,7 +744,7 @@ func (i *IDrac8) Psus() (psus []*devices.Psu, err error) { psus = append(psus, p) } - return psus, err + return psus, nil } // Vendor returns bmc's vendor diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/model.go b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/model.go index 151cd810..7710d670 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/model.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/model.go @@ -5,10 +5,10 @@ import ( ) // UserInfo type is used to unmarshal user accounts payload. -type UserInfo map[int]User +type UsersInfo map[int]UserInfo // Syslog struct holds syslog configuration payload -//https://10.193.251.5/sysmgmt/2012/server/configgroup/iDRAC.SysLog +// https://10.193.251.5/sysmgmt/2012/server/configgroup/iDRAC.SysLog type Syslog struct { Port string `json:"Port"` Enable string `json:"SysLogEnable"` @@ -18,14 +18,15 @@ type Syslog struct { } // User struct holds user account configuration payload -//https://10.193.251.5/sysmgmt/2012/server/configgroup/iDRAC.Users.3 -type User struct { +// https://10.193.251.5/sysmgmt/2012/server/configgroup/iDRAC.Users.3 +type UserInfo struct { UserName string `json:"UserName"` Password string `json:"Password"` Enable string `json:"Enable"` Privilege string `json:"Privilege"` IpmiLanPrivilege string `json:"IpmiLanPrivilege"` SolEnable string `json:"SolEnable"` + SNMPv3Enable string `json:"SNMPv3Enable"` } // certStore is the response received when uploading a multipart form, @@ -38,8 +39,8 @@ type certStore struct { } // NtpServer struct holds NTP configuration payload -//GET - params as query string -//https://10.193.251.10/data?set=tm_ntp_int_opmode:1,tm_ntp_str_server1:ntp0.lhr4.example.com,tm_ntp_str_server2:ntp0.ams4.example.com,tm_ntp_str_server3:ntp0.fra4.example.com +// GET - params as query string +// https://10.193.251.10/data?set=tm_ntp_int_opmode:1,tm_ntp_str_server1:ntp0.lhr4.example.com,tm_ntp_str_server2:ntp0.ams4.example.com,tm_ntp_str_server3:ntp0.fra4.example.com type NtpServer struct { Enable bool `url:"tm_ntp_int_opmode,int"` Server1 string `url:"tm_ntp_str_server1"` @@ -59,10 +60,10 @@ type XMLRoot struct { type XMLUserAccount struct { Name string `xml:"name"` ID int `xml:"id"` - Privileges int `xml:"privileges"` //511 = Administrator, 0 = None, + Privileges int `xml:"privileges"` // 511 = Administrator, 0 = None, Enabled int `xml:"enabled"` - LanPriv int `xml:"lanPriv"` //4 = Administrator, 3 = Operator, 2 = User, 15 = None - SerialPriv int `xml:"serialPriv"` //4 = Administrator, 3 = Operator, 2 = User, 15 = None + LanPriv int `xml:"lanPriv"` // 4 = Administrator, 3 = Operator, 2 = User, 15 = None + SerialPriv int `xml:"serialPriv"` // 4 = Administrator, 3 = Operator, 2 = User, 15 = None SolEnabled int `xml:"solEnabled"` SnmpV3Enabled int `xml:"SNMPV3Enabled"` SnmpPrivType int `xml:"snmpPrivType"` diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/query.go b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/query.go index 8101a0c2..dc9fafe6 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/query.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/query.go @@ -10,7 +10,6 @@ import ( "strings" "time" - "github.com/bmc-toolbox/bmclib/internal" "github.com/bmc-toolbox/bmclib/internal/helper" ) @@ -18,13 +17,11 @@ import ( // The bool value returned indicates if the BMC supports CSR generation. // CurrentHTTPSCert implements the Configure interface func (i *IDrac8) CurrentHTTPSCert() ([]*x509.Certificate, bool, error) { - dialer := &net.Dialer{ Timeout: time.Duration(10) * time.Second, } conn, err := tls.DialWithDialer(dialer, "tcp", i.ip+":"+"443", &tls.Config{InsecureSkipVerify: true}) - if err != nil { return []*x509.Certificate{{}}, true, err } @@ -32,77 +29,85 @@ func (i *IDrac8) CurrentHTTPSCert() ([]*x509.Certificate, bool, error) { defer conn.Close() return conn.ConnectionState().PeerCertificates, true, nil - } // Screenshot Grab screen preview. func (i *IDrac8) Screenshot() (response []byte, extension string, err error) { err = i.httpLogin() if err != nil { - return response, extension, err + return nil, "", err } - endpoint1 := fmt.Sprintf("data?get=consolepreview[auto%%20%d]", + endpoint := fmt.Sprintf("data?get=consolepreview[auto%%20%d]", time.Now().UnixNano()/int64(time.Millisecond)) extension = "png" // here we expect an empty response - response, err = i.get(endpoint1, &map[string]string{"idracAutoRefresh": "1"}) - if err != nil { - return []byte{}, extension, err + statusCode, response, err := i.get(endpoint, &map[string]string{"idracAutoRefresh": "1"}) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + return nil, "", err } if !strings.Contains(string(response), "ok") { - return []byte{}, extension, fmt.Errorf(string(response)) + return nil, "", fmt.Errorf(string(response)) } - endpoint2 := fmt.Sprintf("capconsole/scapture0.png?%d", + endpoint = fmt.Sprintf("capconsole/scapture0.png?%d", time.Now().UnixNano()/int64(time.Millisecond)) - response, err = i.get(endpoint2, &map[string]string{}) - if err != nil { - return []byte{}, extension, err + statusCode, response, err = i.get(endpoint, &map[string]string{}) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + return nil, "", err } - return response, extension, err + return response, extension, nil } -//Queries Idrac8 for current user accounts -func (i *IDrac8) queryUsers() (userInfo UserInfo, err error) { - - userInfo = make(UserInfo) +// Queries for current user accounts. +func (i *IDrac8) queryUsers() (usersInfo UsersInfo, err error) { + usersInfo = make(UsersInfo) endpoint := "data?get=user" - response, err := i.get(endpoint, &map[string]string{}) - if err != nil { - i.log.V(1).Error(err, "GET request failed.", + statusCode, response, err := i.get(endpoint, &map[string]string{}) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + i.log.V(1).Error(err, "queryUsers(): GET request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "endpoint", endpoint, + "StatusCode", statusCode, "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) - return userInfo, err + return usersInfo, err } xmlData := XMLRoot{} err = xml.Unmarshal(response, &xmlData) if err != nil { - i.log.V(1).Error(err, "Unable to unmarshal payload.", + i.log.V(1).Error(err, "queryUsers(): Unable to unmarshal payload.", "step", "queryUserInfo", "resource", "User", "IP", i.ip, - "Model", i.HardwareType(), - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", i.HardwareType(), ) - return userInfo, err + return usersInfo, err } for _, userAccount := range xmlData.XMLUserAccount { - - user := User{ + user := UserInfo{ UserName: userAccount.Name, Privilege: strconv.Itoa(userAccount.Privileges), } @@ -126,8 +131,8 @@ func (i *IDrac8) queryUsers() (userInfo UserInfo, err error) { user.Enable = "disabled" } - userInfo[userAccount.ID] = user + usersInfo[userAccount.ID] = user } - return userInfo, err + return usersInfo, err } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/setupConnections.go b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/setupConnections.go index 64ecdb88..062cb53f 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/setupConnections.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac8/setupConnections.go @@ -78,17 +78,21 @@ func (i *IDrac8) loadHwData() (err error) { } if i.iDracInventory != nil { - return err + return nil } url := "sysmgmt/2012/server/inventory/hardware" - payload, err := i.get(url, nil) + statusCode, response, err := i.get(url, nil) if err != nil { return err } + if statusCode != 200 { + return fmt.Errorf("Call to %s returned %d!", url, statusCode) + } + iDracInventory := &dell.IDracInventory{} - err = xml.Unmarshal(payload, iDracInventory) + err = xml.Unmarshal(response, iDracInventory) if err != nil { return err } @@ -98,8 +102,7 @@ func (i *IDrac8) loadHwData() (err error) { } i.iDracInventory = iDracInventory - - return err + return nil } // Close closes the connection properly diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/actions.go b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/actions.go index 893842b1..09e50fa3 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/actions.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/actions.go @@ -3,6 +3,7 @@ package idrac9 import ( "fmt" "net/url" + "regexp" "strings" ) @@ -85,7 +86,6 @@ func (i *IDrac9) PxeOnce() (bool, error) { // IsOn tells if a machine is currently powered on func (i *IDrac9) IsOn() (status bool, err error) { - output, err := i.sshClient.Run("racadm serveraction powerstatus") if err != nil { return false, fmt.Errorf("output: %q: %w", output, err) @@ -103,26 +103,36 @@ func (i *IDrac9) IsOn() (status bool, err error) { } // UpdateFirmware updates the bmc firmware -func (i *IDrac9) UpdateFirmware(source, file string) (bool, error) { - u, err := url.Parse(source) +func (i *IDrac9) UpdateFirmware(source, file string) (bool, string, error) { + _, err := url.Parse(source) if err != nil { - return false, err - } - - password, ok := u.User.Password() - if !ok { - password = "anonymous" + return false, "", err } - cmd := fmt.Sprintf("racadm fwupdate -f %s %s %s -d %s/%s", u.Host, u.User.Username(), password, u.Path, file) + cmd := fmt.Sprintf("racadm fwupdate -g -u -a %s -d %s", source, file) output, err := i.sshClient.Run(cmd) if err != nil { - return false, fmt.Errorf("output: %q: %w", output, err) + return false, output, fmt.Errorf("output: %q: %w", output, err) } if strings.Contains(output, "Firmware update completed successfully") { - return true, nil + return true, output, nil } - return false, fmt.Errorf(output) + return false, output, fmt.Errorf(output) +} + +func (i *IDrac9) CheckFirmwareVersion() (version string, err error) { + output, err := i.sshClient.Run("racadm getversion -f idrac") + if err != nil { + return "", fmt.Errorf("output: %q: %w", output, err) + } + + re := regexp.MustCompile(`.*iDRAC Version.*= ((\d+\.)+\d+)`) + matches := re.FindStringSubmatch(output) + if len(matches) > 1 { + return matches[1], nil + } + + return "", fmt.Errorf("unexpected output: %q", output) } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/configure.go b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/configure.go index 6a64b764..f389fe8a 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/configure.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/configure.go @@ -49,88 +49,80 @@ func (i *IDrac9) Power(cfg *cfgresources.Power) (err error) { // Bios sets up Bios configuration // Bios implements the Configure interface func (i *IDrac9) Bios(cfg *cfgresources.Bios) (err error) { - newBiosSettings := cfg.Dell.Idrac9BiosSettings - //validate config validate := validator.New() err = validate.Struct(newBiosSettings) if err != nil { - i.log.V(1).Error(err, "Config validation failed.", "step", "applyBiosParams", "Error", internal.ErrStringOrEmpty(err)) + i.log.V(1).Error(err, "Bios(): Config validation failed.", "step", "applyBiosParams") return err } - //GET current settings currentBiosSettings, err := i.getBiosSettings() if err != nil || currentBiosSettings == nil { - msg := "Unable to get current bios settings through redfish." + if err == nil { + err = fmt.Errorf("Call to getBiosSettings() returned nil.") + } + + msg := "Bios(): Unable to get current BIOS settings through RedFish." i.log.V(1).Error(err, msg, "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) return errors.New(msg) } - //Compare current bios settings with our declared config. + // Compare current BIOS settings with our declared config. if *newBiosSettings != *currentBiosSettings { - - //retrieve fields that is the config to be applied toApplyBiosSettings, err := diffBiosSettings(newBiosSettings, currentBiosSettings) if err != nil { i.log.V(1).Error(err, "diffBiosSettings returned error.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) return err } - i.log.V(0).Info("Bios configuration to be applied", + i.log.V(0).Info("BIOS configuration to be applied...", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), "Changes (Ignore empty fields)", fmt.Sprintf("%+v", toApplyBiosSettings), ) - //purge any existing pending bios setting jobs - //or we will not be able to set any params + // Purge any existing pending BIOS setting jobs (otherwise, we won't be able to set any params): err = i.purgeJobsForBiosSettings() if err != nil { - i.log.V(1).Info("Unable to purge pending bios setting jobs.", + i.log.V(1).Error(err, "Bios(): Unable to purge pending BIOS setting jobs.", "step", "applyBiosParams", "resource", "Bios", "IP", i.ip, - "Model", i.HardwareType(), - "Bios settings pending", internal.ErrStringOrEmpty(err), + "HardwareType", i.HardwareType(), ) } err = i.setBiosSettings(toApplyBiosSettings) if err != nil { - msg := "setBiosAttributes returned error." + msg := "setBiosAttributes() returned error." i.log.V(1).Error(err, msg, "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) return errors.New(msg) } - i.log.V(0).Info("Bios configuration update job queued in iDrac.", + i.log.V(0).Info("BIOS configuration update job queued in IDRAC.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), ) - } else { - i.log.V(0).Info("Bios configuration is up to date.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), ) } @@ -146,110 +138,112 @@ func (i *IDrac9) Bios(cfg *cfgresources.Bios) (err error) { func (i *IDrac9) User(cfgUsers []*cfgresources.User) (err error) { err = i.httpLogin() if err != nil { - return err + msg := "IDRAC9 User(): HTTP login failed: " + err.Error() + i.log.V(1).Error(err, msg, + "step", "applyUserParams", + "IP", i.ip, + "HardwareType", i.HardwareType(), + ) + return errors.New(msg) } - err = i.validateCfg(cfgUsers) + + err = internal.ValidateUserConfig(cfgUsers) if err != nil { - msg := "Config validation failed." + msg := "IDRAC9 User(): User config validation failed: " + err.Error() i.log.V(1).Error(err, msg, "step", "applyUserParams", "IP", i.ip, - "Model", i.HardwareType(), - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", i.HardwareType(), ) return errors.New(msg) } idracUsers, err := i.queryUsers() if err != nil { - msg := "Unable to query existing users" + msg := "IDRAC9 User(): Unable to query existing users." i.log.V(1).Error(err, msg, "step", "applyUserParams", "IP", i.ip, + "HardwareType", i.HardwareType(), "Model", i.HardwareType(), - "Error", internal.ErrStringOrEmpty(err), ) - return errors.New(msg) + return errors.New(msg + " Error: " + err.Error()) } - //for each configuration user - for _, cfgUser := range cfgUsers { + // This user is reserved for IDRAC usage, we can't delete it. + delete(idracUsers, 1) - userID, userInfo, uExists := userInIdrac(cfgUser.Name, idracUsers) - - //user to be added/updated - if cfgUser.Enable { - - //new user to be added - if !uExists { - userID, userInfo, err = getEmptyUserSlot(idracUsers) - if err != nil { - i.log.V(1).Error(err, "Unable to add new User.", - "IP", i.ip, - "Model", i.HardwareType(), - "step", helper.WhosCalling(), - "User", cfgUser.Name, - "Error", internal.ErrStringOrEmpty(err), - ) - continue - } - } - - userInfo.Enable = "Enabled" - userInfo.SolEnable = "Enabled" - userInfo.UserName = cfgUser.Name - userInfo.Password = cfgUser.Password - - //set appropriate privileges - if cfgUser.Role == "admin" { - userInfo.Privilege = "511" - userInfo.IpmiLanPrivilege = "Administrator" - } else { - userInfo.Privilege = "499" - userInfo.IpmiLanPrivilege = "Operator" - } - - err = i.putUser(userID, userInfo) - if err != nil { - i.log.V(1).Error(err, "Add/Update user request failed.", - "IP", i.ip, - "Model", i.HardwareType(), - "step", helper.WhosCalling(), - "User", cfgUser.Name, - "Error", internal.ErrStringOrEmpty(err), - ) - continue - } - - } // end if cfgUser.Enable - - //if the user exists but is disabled in our config, remove the user - if !cfgUser.Enable && uExists { - endpoint := fmt.Sprintf("sysmgmt/2017/server/user?userid=%d", userID) - statusCode, response, err := i.delete(endpoint) - if err != nil { - i.log.V(1).Error(err, "Delete user request failed.", - "IP", i.ip, - "Model", i.HardwareType(), - "step", helper.WhosCalling(), - "User", cfgUser.Name, - "Error", internal.ErrStringOrEmpty(err), - "StatusCode", statusCode, - "Response", response, - ) - continue - } + // Start from a clean slate. + for id := range idracUsers { + statusCode, payload, err := i.delete(fmt.Sprintf("sysmgmt/2017/server/user?userid=%d", id)) + if err != nil { + msg := fmt.Sprintf("IDRAC9 User(): Unable to remove existing user (ID %d): %s", id, err.Error()) + i.log.V(1).Error(err, msg, + "step", "applyUserParams", + "IP", i.ip, + "HardwareType", i.HardwareType(), + ) + return err } - i.log.V(1).Info("User parameters applied.", - "IP", i.ip, - "Model", i.HardwareType(), - "User", cfgUser.Name, - ) + if statusCode > 299 { + err = fmt.Errorf("Request failed with status code %d and payload %s.", statusCode, string(payload)) + msg := fmt.Sprintf("IDRAC9 User(): Unable to remove existing user (ID %d): %s", id, err.Error()) + i.log.V(1).Error(err, msg, + "step", "applyUserParams", + "IP", i.ip, + "HardwareType", i.HardwareType(), + ) + return err + } + } + // As mentioned before, user ID 1 is reserved for IDRAC usage. + userID := 2 + + for _, cfgUser := range cfgUsers { + // If the user is not enabled in the config, just skip. + if !cfgUser.Enable { + continue + } + + user := UserInfo{} + user.Enable = "Enabled" + user.UserName = cfgUser.Name + user.Password = cfgUser.Password + if cfgUser.SolEnable { + user.SolEnable = "Enabled" + } else { + user.SolEnable = "Disabled" + } + if cfgUser.SNMPv3Enable { + user.ProtocolEnable = "Enabled" + } else { + user.ProtocolEnable = "Disabled" + } + if cfgUser.Role == "admin" { + user.Privilege = "511" + user.IpmiLanPrivilege = "Administrator" + } else { + user.Privilege = "499" + user.IpmiLanPrivilege = "Operator" + } + + err = i.putUser(userID, user) + if err != nil { + i.log.V(1).Error(err, "User(): Add/Update user request failed.", + "IP", i.ip, + "HardwareType", i.HardwareType(), + "step", helper.WhosCalling(), + "User", cfgUser.Name, + ) + continue + } + i.log.V(1).Info("User parameters applied.", "IP", i.ip, "HardwareType", i.HardwareType(), "User", cfgUser.Name) + userID++ } - return err + return nil } // Ldap applies LDAP configuration params. @@ -270,7 +264,7 @@ func (i *IDrac9) Ldap(cfg *cfgresources.Ldap) (err error) { err = errors.New(msg) i.log.V(1).Error(err, msg, "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling, ) return err @@ -280,7 +274,7 @@ func (i *IDrac9) Ldap(cfg *cfgresources.Ldap) (err error) { msg := "Ldap resource parameter BaseDn required but not declared." err = errors.New(msg) i.log.V(1).Error(err, msg, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling, ) return err @@ -325,9 +319,8 @@ func (i *IDrac9) Ldap(cfg *cfgresources.Ldap) (err error) { err = errors.New(msg) i.log.V(1).Error(err, msg, "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) return err } @@ -335,113 +328,76 @@ func (i *IDrac9) Ldap(cfg *cfgresources.Ldap) (err error) { return err } -// LdapGroup applies LDAP Group/Role related configuration -// LdapGroup implements the Configure interface. -// nolint: gocyclo -func (i *IDrac9) LdapGroup(cfg []*cfgresources.LdapGroup, cfgLdap *cfgresources.Ldap) (err error) { +// Applies LDAP Group/Role-related configuration. +// Implements the Configure interface. +func (i *IDrac9) LdapGroups(cfgGroups []*cfgresources.LdapGroup, cfgLdap *cfgresources.Ldap) (err error) { + roleID := 0 + for _, cfgRole := range cfgGroups { + if !cfgRole.Enable { + continue + } - idracLdapRoleGroups, err := i.queryLdapRoleGroups() - if err != nil { - msg := "Unable to query existing users" - err = errors.New(msg) - i.log.V(1).Error(err, msg, - "step", "applyUserParams", - "IP", i.ip, - "Model", i.HardwareType(), - "Error", internal.ErrStringOrEmpty(err), - ) - return err - } + // Use the next slot. + roleID++ - //for each configuration ldap role group - for _, cfgRole := range cfg { - - // the distinguished name of the group - // example, if the GroupBaseDn is ou=Group,dc=example,dc=com and the Group is cn=fooUsers - // the groupDN will be Group+GroupBaseDn = cn=fooUsers,ou=Group,dc=example,dc=com - var groupDN = fmt.Sprintf("%s,%s", cfgRole.Group, cfgRole.GroupBaseDn) - - roleID, role, rExists := ldapRoleGroupInIdrac(groupDN, idracLdapRoleGroups) - - //role to be added/updated - if cfgRole.Enable { - - //new role to be added - if !rExists { - roleID, role, err = getEmptyLdapRoleGroupSlot(idracLdapRoleGroups) - if err != nil { - i.log.V(1).Error(err, "Unable to add new Ldap Role Group.", - "IP", i.ip, - "Model", i.HardwareType(), - "step", helper.WhosCalling(), - "Ldap Role Group", cfgRole.Group, - "Role Group DN", cfgRole.Role, - "Error", internal.ErrStringOrEmpty(err), - ) - continue - } - } - - role.DN = groupDN - - //set appropriate privileges - if cfgRole.Role == "admin" { - role.Privilege = "511" - } else { - role.Privilege = "499" - } - - err = i.putLdapRoleGroup(roleID, role) - if err != nil { - i.log.V(1).Error(err, "Add/Update LDAP Role Group request failed.", - "IP", i.ip, - "Model", i.HardwareType(), - "step", helper.WhosCalling(), - "Ldap Role Group", cfgRole.Group, - "Role Group DN", cfgRole.Role, - "Error", internal.ErrStringOrEmpty(err), - ) - continue - } - - } // end if cfgUser.Enable - - //if the role exists but is disabled in our config, remove the role - if !cfgRole.Enable && rExists { - - role.DN = "" - role.Privilege = "0" - err = i.putLdapRoleGroup(roleID, role) - if err != nil { - i.log.V(1).Error(err, "Remove LDAP Role Group request failed.", - "IP", i.ip, - "Model", i.HardwareType(), - "step", helper.WhosCalling(), - "Ldap Role Group", cfgRole.Group, - "Role Group DN", cfgRole.Role, - "Error", internal.ErrStringOrEmpty(err), - ) - continue - } + // The distinguished name of the group: + // e.g. If `GroupBaseDn` is ou=Group,dc=example,dc=com and `Group` is cn=fooUsers; + // `groupDN` will be cn=fooUsers,ou=Group,dc=example,dc=com. + role := LdapRoleGroup{ + DN: fmt.Sprintf("%s,%s", cfgRole.Group, cfgRole.GroupBaseDn), + Privilege: "0", } - i.log.V(1).Info("Ldap Role Group parameters applied.", - "IP", i.ip, - "Model", i.HardwareType(), - "Step", helper.WhosCalling(), - "Ldap Role Group", cfgRole.Role, - "Role Group DN", cfgRole.Role, - ) + if cfgRole.Role == "admin" { + role.Privilege = "511" + } else if cfgRole.Role == "user" { + role.Privilege = "499" + } + // Actual query: + err = i.putLdapRoleGroup(fmt.Sprintf("%d", roleID), role) + if err == nil { + i.log.V(1).Info("LDAP Role Group parameters applied.", + "IP", i.ip, + "HardwareType", i.HardwareType(), + "Step", helper.WhosCalling(), + "Ldap Role Group", cfgRole.Role, + "Role Group DN", cfgRole.Role, + ) + } else { + i.log.V(1).Error(err, "Add/Update LDAP Role Group request failed.", + "IP", i.ip, + "HardwareType", i.HardwareType(), + "step", helper.WhosCalling(), + "Ldap Role Group", cfgRole.Group, + "Role Group DN", cfgRole.Role, + ) + continue + } } - return err + // Remove all the rest. + for roleID++; roleID <= 5; roleID++ { + role := LdapRoleGroup{ + DN: "", + Privilege: "0", + } + err = i.putLdapRoleGroup(fmt.Sprintf("%d", roleID), role) + if err != nil { + i.log.V(1).Error(err, "Remove LDAP Role Group request failed.", + "IP", i.ip, + "HardwareType", i.HardwareType(), + "step", helper.WhosCalling(), + ) + } + } + + return nil } // Ntp applies NTP configuration params // Ntp implements the Configure interface. func (i *IDrac9) Ntp(cfg *cfgresources.Ntp) (err error) { - var enable string if cfg.Enable { @@ -455,7 +411,7 @@ func (i *IDrac9) Ntp(cfg *cfgresources.Ntp) (err error) { err = errors.New(msg) i.log.V(1).Error(err, msg, "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "Step", helper.WhosCalling(), ) return err @@ -466,7 +422,7 @@ func (i *IDrac9) Ntp(cfg *cfgresources.Ntp) (err error) { err = errors.New(msg) i.log.V(1).Error(err, msg, "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "Step", helper.WhosCalling(), ) return err @@ -478,7 +434,7 @@ func (i *IDrac9) Ntp(cfg *cfgresources.Ntp) (err error) { err = errors.New(msg) i.log.V(1).Error(err, msg, "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), "Unknown Timezone", cfg.Timezone, ) @@ -489,10 +445,9 @@ func (i *IDrac9) Ntp(cfg *cfgresources.Ntp) (err error) { if err != nil { i.log.V(1).Error(err, "PUT timezone request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), "Timezone", cfg.Timezone, - "Error", internal.ErrStringOrEmpty(err), ) return err } @@ -508,16 +463,15 @@ func (i *IDrac9) Ntp(cfg *cfgresources.Ntp) (err error) { if err != nil { i.log.V(1).Error(err, "PUT Ntp request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) return err } i.log.V(1).Info("NTP servers param applied.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), ) return err @@ -531,14 +485,13 @@ func (i *IDrac9) Ntp(cfg *cfgresources.Ntp) (err error) { // and since not all BMCs currently support configuring filtering for alerts, // for now the configuration for alert filters/enabling is managed through this method. func (i *IDrac9) Syslog(cfg *cfgresources.Syslog) (err error) { - var port int enable := "Enabled" if cfg.Server == "" { i.log.V(1).Info("Syslog resource expects parameter: Server.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), ) return @@ -567,9 +520,8 @@ func (i *IDrac9) Syslog(cfg *cfgresources.Syslog) (err error) { if err != nil { i.log.V(1).Error(err, "PUT Syslog request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) return err } @@ -579,9 +531,8 @@ func (i *IDrac9) Syslog(cfg *cfgresources.Syslog) (err error) { if err != nil { i.log.V(1).Error(err, "PUT to enable Alerts failed request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) return err } @@ -591,21 +542,19 @@ func (i *IDrac9) Syslog(cfg *cfgresources.Syslog) (err error) { if err != nil { i.log.V(1).Error(err, "PUT to configure alerts failed request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) return err } - i.log.V(1).Info("Syslog and alert parameters applied.", "IP", i.ip, "Model", i.HardwareType()) + i.log.V(1).Info("Syslog and alert parameters applied.", "IP", i.ip, "HardwareType", i.HardwareType()) return err } // Network method implements the Configure interface // applies various network parameters. func (i *IDrac9) Network(cfg *cfgresources.Network) (reset bool, err error) { - params := map[string]string{ "EnableIPv4": "Enabled", "DHCPEnable": "Enabled", @@ -653,45 +602,41 @@ func (i *IDrac9) Network(cfg *cfgresources.Network) (reset bool, err error) { err = i.putIPv4(ipv4) if err != nil { - i.log.V(1).Info("PUT IPv4 request failed.", + i.log.V(1).Error(err, "PUT IPv4 request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) } err = i.putSerialOverLan(serialOverLan) if err != nil { - i.log.V(1).Info("PUT SerialOverLan request failed.", + i.log.V(1).Error(err, "PUT SerialOverLan request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) } err = i.putSerialRedirection(serialRedirection) if err != nil { - i.log.V(1).Info("PUT SerialRedirection request failed.", + i.log.V(1).Error(err, "PUT SerialRedirection request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) } err = i.putIpmiOverLan(ipmiOverLan) if err != nil { - i.log.V(1).Info("PUT IpmiOverLan request failed.", + i.log.V(1).Error(err, "PUT IpmiOverLan request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) } - i.log.V(1).Info("Network config parameters applied.", "IP", i.ip, "Model", i.HardwareType()) + i.log.V(1).Info("Network config parameters applied.", "IP", i.ip, "HardwareType", i.HardwareType()) return reset, err } @@ -705,7 +650,6 @@ func (i *IDrac9) SetLicense(cfg *cfgresources.License) (err error) { // 1. PUT CSR info based on configuration // 2. POST sysmgmt/2012/server/network/ssl/csr which returns a base64encoded CSR. func (i *IDrac9) GenerateCSR(cert *cfgresources.HTTPSCertAttributes) ([]byte, error) { - c := CSRInfo{ CommonName: cert.CommonName, CountryCode: cert.CountryCode, @@ -738,7 +682,6 @@ func (i *IDrac9) GenerateCSR(cert *cfgresources.HTTPSCertAttributes) ([]byte, er // 1. POST upload signed x509 cert in multipart form. // 2. POST returned resource URI func (i *IDrac9) UploadHTTPSCert(cert []byte, certFileName string, key []byte, keyFileName string) (bool, error) { - endpoint := "sysmgmt/2012/server/transient/filestore" // setup a buffer for our multipart form @@ -762,25 +705,28 @@ func (i *IDrac9) UploadHTTPSCert(cert []byte, certFileName string, key []byte, k // 1. POST upload x509 cert status, body, err := i.post(endpoint, form.Bytes(), w.FormDataContentType()) if err != nil || status != 201 { - i.log.V(1).Error(err, "Cert form upload POST request failed, expected 201.", + if err == nil { + err = fmt.Errorf("Cert form upload POST request to %s failed with status code %d.", endpoint, status) + } + + i.log.V(1).Error(err, "UploadHTTPSCert(): Cert form upload POST request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "endpoint", endpoint, "step", helper.WhosCalling(), - "status", status, + "StatusCode", status, ) return false, err } // extract resourceURI from response - var certStore = new(certStore) + certStore := new(certStore) err = json.Unmarshal(body, certStore) if err != nil { i.log.V(1).Error(err, "Unable to unmarshal cert store response payload.", "step", helper.WhosCalling(), "IP", i.ip, - "Model", i.HardwareType(), - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", i.HardwareType(), ) return false, err } @@ -790,8 +736,7 @@ func (i *IDrac9) UploadHTTPSCert(cert []byte, certFileName string, key []byte, k i.log.V(1).Error(err, "Unable to marshal cert store resource URI.", "step", helper.WhosCalling(), "IP", i.ip, - "Model", i.HardwareType(), - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", i.HardwareType(), ) return false, err } @@ -800,15 +745,19 @@ func (i *IDrac9) UploadHTTPSCert(cert []byte, certFileName string, key []byte, k endpoint = "sysmgmt/2012/server/network/ssl/cert" status, _, err = i.post(endpoint, []byte(resourceURI), "") if err != nil || status != 201 { - i.log.V(1).Error(err, "Cert form upload POST request failed, expected 201.", + if err == nil { + err = fmt.Errorf("Cert form upload POST request to %s failed with status code %d.", endpoint, status) + } + + i.log.V(1).Error(err, "UploadHTTPSCert(): Cert form upload POST request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "endpoint", endpoint, "step", helper.WhosCalling(), - "status", status, + "StatusCode", status, ) return false, err } - return true, err + return true, nil } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/helpers.go b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/helpers.go index 93250ca6..f2b5da34 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/helpers.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/helpers.go @@ -4,100 +4,32 @@ import ( "encoding/json" "errors" "fmt" - - "github.com/bmc-toolbox/bmclib/cfgresources" ) -// Return bool value if the role is valid. -func isRoleValid(role string) bool { - - validRoles := []string{"admin", "user"} - for _, v := range validRoles { - if role == v { - return true - } - } - - return false -} - -// Return bool value if the role is valid. -func (i *IDrac9) validateCfg(cfgUsers []*cfgresources.User) (err error) { - - for _, cfgUser := range cfgUsers { - if cfgUser.Name == "" { - msg := "User resource expects parameter: Name." - return errors.New(msg) - } - - if cfgUser.Password == "" { - msg := "User resource expects parameter: Password." - return errors.New(msg) - } - - if !isRoleValid(cfgUser.Role) { - msg := "User resource expects parameter Role to be one of 'admin', 'user'" - return errors.New(msg) - } - } - - return nil -} - -// iDrac9 supports upto 16 users, user 0 is reserved -// this function returns an empty user slot that can be used for a new user account -func getEmptyUserSlot(idracUsers userInfo) (userID int, user User, err error) { - for userID, user := range idracUsers { - - if userID == 1 { - continue - } - - if user.UserName == "" { - return userID, user, err - } - } - - return 0, user, errors.New("All user account slots in use, remove an account before adding a new one") -} - -// checks if a user is present in a given list -func userInIdrac(user string, usersInfo userInfo) (userID int, userInfo User, exists bool) { - - for userID, userInfo := range usersInfo { - if userInfo.UserName == user { - return userID, userInfo, true - } - } - - return userID, userInfo, false -} - // PUTs user config -func (i *IDrac9) putUser(userID int, user User) (err error) { - - idracPayload := make(map[string]User) +func (i *IDrac9) putUser(userID int, user UserInfo) (err error) { + idracPayload := make(map[string]UserInfo) idracPayload["iDRAC.Users"] = user payload, err := json.Marshal(idracPayload) if err != nil { - msg := fmt.Sprintf("Error unmarshalling User payload: %s", err) + msg := fmt.Sprintf("Error unmarshalling user payload: %s", err) return errors.New(msg) } endpoint := fmt.Sprintf("sysmgmt/2012/server/configgroup/iDRAC.Users.%d", userID) statusCode, _, err := i.put(endpoint, payload) - if err != nil || statusCode != 200 { - msg := fmt.Sprintf("PUT request to set User config returned error, return code: %d", statusCode) - return errors.New(msg) + if err != nil { + return fmt.Errorf("PUT request to set User config failed with error %s!", err.Error()) + } else if statusCode != 200 { + return fmt.Errorf("PUT request to set User config failed with status code %d!", statusCode) } - return err + return nil } // PUTs ldap config func (i *IDrac9) putLdap(ldap Ldap) (err error) { - idracPayload := make(map[string]Ldap) idracPayload["iDRAC.LDAP"] = ldap @@ -109,265 +41,240 @@ func (i *IDrac9) putLdap(ldap Ldap) (err error) { endpoint := "sysmgmt/2012/server/configgroup/iDRAC.LDAP" statusCode, _, err := i.put(endpoint, payload) - if err != nil || statusCode != 200 { - msg := fmt.Sprintf("PUT request to set User config returned error, return code: %d", statusCode) - return errors.New(msg) - } - - return err -} - -// checks if a role group is in idrac -func ldapRoleGroupInIdrac(group string, roleGroups LdapRoleGroups) (roleID string, roleGroup LdapRoleGroup, exists bool) { - - for roleID, roleGroup := range roleGroups { - if roleGroup.DN == group { - return roleID, roleGroup, true - } - } - - return roleID, roleGroup, false -} - -// iDrac9 supports upto 5 ldap role groups -// this function returns an empty user slot that can be used for a new ldap role group. -func getEmptyLdapRoleGroupSlot(roleGroups LdapRoleGroups) (roleID string, roleGroup LdapRoleGroup, err error) { - - for roleID, roleGroup := range roleGroups { - if roleGroup.DN == "" { - return roleID, roleGroup, err - } + if err != nil { + return fmt.Errorf("PUT request to set LDAP config failed with error %s!", err.Error()) + } else if statusCode != 200 { + return fmt.Errorf("PUT request to set LDAP config failed with status code %d!", statusCode) } - return roleID, roleGroup, errors.New("All Ldap Role Group slots in use, remove a Role group before adding a new one") + return nil } -// PUTs ldap role group config func (i *IDrac9) putLdapRoleGroup(roleID string, ldapRoleGroup LdapRoleGroup) (err error) { - idracPayload := make(map[string]LdapRoleGroup) idracPayload["iDRAC.LDAPRoleGroup"] = ldapRoleGroup payload, err := json.Marshal(idracPayload) if err != nil { - msg := fmt.Sprintf("Error marshalling Ldap Role Group payload: %s", err) + msg := fmt.Sprintf("Error marshaling LDAP Role Group payload: %s", err) return errors.New(msg) } endpoint := fmt.Sprintf("sysmgmt/2012/server/configgroup/iDRAC.LDAPRoleGroup.%s", roleID) statusCode, _, err := i.put(endpoint, payload) - if err != nil || statusCode != 200 { - msg := fmt.Sprintf("PUT request to set Ldap Role Group config returned error, return code: %d", statusCode) - return errors.New(msg) + if err != nil { + return fmt.Errorf("PUT request to set LDAPRoleGroup config failed with error %s!", err.Error()) + } else if statusCode != 200 { + return fmt.Errorf("PUT request to set LDAPRoleGroup config failed with status code %d!", statusCode) } - return err + return nil } // PUTs timezone config func (i *IDrac9) putTimezone(timezone Timezone) (err error) { - idracPayload := make(map[string]Timezone) idracPayload["iDRAC.Time"] = timezone payload, err := json.Marshal(idracPayload) if err != nil { - msg := fmt.Sprintf("Error marshalling Timezone payload: %s", err) + msg := fmt.Sprintf("Error marshaling Timezone payload: %s", err) return errors.New(msg) } endpoint := "sysmgmt/2012/server/configgroup/iDRAC.Time" statusCode, _, err := i.put(endpoint, payload) - if err != nil || statusCode != 200 { - msg := fmt.Sprintf("PUT request to set Timezone config returned error, return code: %d", statusCode) - return errors.New(msg) + if err != nil { + return fmt.Errorf("PUT request to set Timezone config failed with error %s!", err.Error()) + } else if statusCode != 200 { + return fmt.Errorf("PUT request to set Timezone config failed with status code %d!", statusCode) } - return err + return nil } // PUTs NTP config func (i *IDrac9) putNtpConfig(ntpConfig NtpConfig) (err error) { - idracPayload := make(map[string]NtpConfig) idracPayload["iDRAC.NTPConfigGroup"] = ntpConfig payload, err := json.Marshal(idracPayload) if err != nil { - msg := fmt.Sprintf("Error marshalling NTP payload: %s", err) + msg := fmt.Sprintf("Error marshaling NTP payload: %s", err) return errors.New(msg) } endpoint := "sysmgmt/2012/server/configgroup/iDRAC.NTPConfigGroup" statusCode, _, err := i.put(endpoint, payload) - if err != nil || statusCode != 200 { - msg := fmt.Sprintf("PUT request to set Timezone config returned error, return code: %d", statusCode) - return errors.New(msg) + if err != nil { + return fmt.Errorf("PUT request to set NTP config failed with error %s!", err.Error()) + } else if statusCode != 200 { + return fmt.Errorf("PUT request to set NTP config failed with status code %d!", statusCode) } - return err + return nil } // PUTs NTP config func (i *IDrac9) putSyslog(syslog Syslog) (err error) { - idracPayload := make(map[string]Syslog) idracPayload["iDRAC.SysLog"] = syslog payload, err := json.Marshal(idracPayload) if err != nil { - msg := fmt.Sprintf("Error marshalling Syslog payload: %s", err) + msg := fmt.Sprintf("Error marshaling Syslog payload: %s", err) return errors.New(msg) } endpoint := "sysmgmt/2012/server/configgroup/iDRAC.Syslog" statusCode, _, err := i.put(endpoint, payload) - if err != nil || statusCode != 200 { - msg := fmt.Sprintf("PUT request to set Syslog config returned error, return code: %d", statusCode) - return errors.New(msg) + if err != nil { + return fmt.Errorf("PUT request to set Syslog config failed with error %s!", err.Error()) + } else if statusCode != 200 { + return fmt.Errorf("PUT request to set Syslog config failed with status code %d!", statusCode) } - return err + return nil } // PUTs IPv4 config func (i *IDrac9) putIPv4(ipv4 Ipv4) (err error) { - idracPayload := make(map[string]Ipv4) idracPayload["iDRAC.IPv4"] = ipv4 payload, err := json.Marshal(idracPayload) if err != nil { - msg := fmt.Sprintf("Error marshalling Ipv4 payload: %s", err) + msg := fmt.Sprintf("Error marshaling Ipv4 payload: %s", err) return errors.New(msg) } endpoint := "sysmgmt/2012/server/configgroup/iDRAC.IPv4" statusCode, _, err := i.put(endpoint, payload) - if err != nil || statusCode != 200 { - msg := fmt.Sprintf("PUT request to set IPv4 config returned error, return code: %d", statusCode) - return errors.New(msg) + if err != nil { + return fmt.Errorf("PUT request to set IPv4 config failed with error %s!", err.Error()) + } else if statusCode != 200 { + return fmt.Errorf("PUT request to set IPv4 config failed with status code %d!", statusCode) } - return err + return nil } // PUTs SerialOverLan config func (i *IDrac9) putSerialOverLan(serialOverLan SerialOverLan) (err error) { - idracPayload := make(map[string]SerialOverLan) idracPayload["iDRAC.IPMISOL"] = serialOverLan payload, err := json.Marshal(idracPayload) if err != nil { - msg := fmt.Sprintf("Error marshalling SerialOverLan payload: %s", err) + msg := fmt.Sprintf("Error marshaling SerialOverLan payload: %s", err) return errors.New(msg) } endpoint := "sysmgmt/2012/server/configgroup/iDRAC.IPMISOL" statusCode, _, err := i.put(endpoint, payload) - if err != nil || statusCode != 200 { - msg := fmt.Sprintf("PUT request to set SerialOverLan config returned error, return code: %d", statusCode) - return errors.New(msg) + if err != nil { + return fmt.Errorf("PUT request to set SerialOverLAN config failed with error %s!", err.Error()) + } else if statusCode != 200 { + return fmt.Errorf("PUT request to set SerialOverLAN config failed with status code %d!", statusCode) } - return err + return nil } // PUTs SerialRedirection config func (i *IDrac9) putSerialRedirection(serialRedirection SerialRedirection) (err error) { - idracPayload := make(map[string]SerialRedirection) idracPayload["iDRAC.SerialRedirection"] = serialRedirection payload, err := json.Marshal(idracPayload) if err != nil { - msg := fmt.Sprintf("Error marshalling serialRedirection payload: %s", err) + msg := fmt.Sprintf("Error marshaling serialRedirection payload: %s", err) return errors.New(msg) } endpoint := "sysmgmt/2012/server/configgroup/iDRAC.SerialRedirection" statusCode, _, err := i.put(endpoint, payload) - if err != nil || statusCode != 200 { - msg := fmt.Sprintf("PUT request to set serialRedirection config returned error, return code: %d", statusCode) - return errors.New(msg) + if err != nil { + return fmt.Errorf("PUT request to set SerialRedirection config failed with error %s!", err.Error()) + } else if statusCode != 200 { + return fmt.Errorf("PUT request to set SerialRedirection config failed with status code %d!", statusCode) } - return err + return nil } // PUTs IpmiOverLan config func (i *IDrac9) putIpmiOverLan(ipmiOverLan IpmiOverLan) (err error) { - idracPayload := make(map[string]IpmiOverLan) idracPayload["iDRAC.IPMILan"] = ipmiOverLan payload, err := json.Marshal(idracPayload) if err != nil { - msg := fmt.Sprintf("Error marshalling ipmiOverLan payload: %s", err) + msg := fmt.Sprintf("Error marshaling ipmiOverLan payload: %s", err) return errors.New(msg) } endpoint := "sysmgmt/2012/server/configgroup/iDRAC.IPMILAN" statusCode, _, err := i.put(endpoint, payload) - if err != nil || statusCode != 200 { - msg := fmt.Sprintf("PUT request to set IpmiOverLan config returned error, return code: %d", statusCode) - return errors.New(msg) + if err != nil { + return fmt.Errorf("PUT request to set IPMIOverLAN config failed with error %s!", err.Error()) + } else if statusCode != 200 { + return fmt.Errorf("PUT request to set IPMIOverLAN config failed with status code %d!", statusCode) } - return err + return nil } // PUTs CSR request - request for a CSR based on given attributes. func (i *IDrac9) putCSR(csrInfo CSRInfo) (err error) { - m := map[string]CSRInfo{"iDRAC.Security": csrInfo} payload, err := json.Marshal(m) if err != nil { - msg := fmt.Sprintf("Error marshalling CSRInfo payload: %s", err) + msg := fmt.Sprintf("Error marshaling CSRInfo payload: %s", err) return errors.New(msg) } endpoint := "sysmgmt/2012/server/configgroup/iDRAC.Security" statusCode, _, err := i.put(endpoint, payload) - if err != nil || statusCode != 200 { - msg := fmt.Sprintf("PUT request to set CSR attributes returned: %d", statusCode) - return errors.New(msg) + if err != nil { + return fmt.Errorf("PUT request to set CSR config failed with error %s!", err.Error()) + } else if statusCode != 200 { + return fmt.Errorf("PUT request to set CSR attributes failed with status code %d!", statusCode) } - return err + return nil } // putAlertConfig sets up alert filtering/sysloging // see alertConfigPayload listed in model.go for payload. func (i *IDrac9) putAlertConfig() (err error) { - endpoint := "sysmgmt/2012/server/eventpolicy" statusCode, _, err := i.put(endpoint, alertConfigPayload) - if err != nil || statusCode != 200 { - msg := fmt.Sprintf("PUT request to set attributes returned: %d", statusCode) - return errors.New(msg) + if err != nil { + return fmt.Errorf("PUT request to set AlertConfig config failed with error %s!", err.Error()) + } else if statusCode != 200 { + return fmt.Errorf("PUT request to set AlertConfig config failed with status code %d!", statusCode) } - return err + return nil } // putAlertEnable - enables/disables alerts func (i *IDrac9) putAlertEnable(alertEnable AlertEnable) (err error) { - m := map[string]AlertEnable{"iDRAC.IPMILan": alertEnable} payload, err := json.Marshal(m) if err != nil { - msg := fmt.Sprintf("Error marshalling payload: %s", err) + msg := fmt.Sprintf("Error marshaling payload: %s", err) return errors.New(msg) } endpoint := "sysmgmt/2012/server/configgroup/iDRAC.IPMILAN" statusCode, _, err := i.put(endpoint, payload) - if err != nil || statusCode != 200 { - msg := fmt.Sprintf("PUT request to set attributes returned: %d", statusCode) - return errors.New(msg) + if err != nil { + return fmt.Errorf("PUT request to set AlertEnable config failed with error %s!", err.Error()) + } else if statusCode != 200 { + return fmt.Errorf("PUT request to set AlertEnable config failed with status code %d!", statusCode) } - return err + return nil } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/idrac.go b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/idrac.go index c824061f..fefc075a 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/idrac.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/idrac.go @@ -27,21 +27,17 @@ type Conn struct { } const ( - // ProviderName for the provider implementation - ProviderName = "idrac9" - // ProviderProtocol for the provider implementation + ProviderName = "idrac9" ProviderProtocol = "webgui" ) -var ( - // Features implemented by dell idrac9 provider - Features = registrar.Features{ - providers.FeatureUserCreate, - providers.FeatureUserUpdate, - providers.FeatureUserRead, - providers.FeatureUserDelete, - } -) +// Features implemented by Dell's idrac9 provider: +var Features = registrar.Features{ + providers.FeatureUserCreate, + providers.FeatureUserUpdate, + providers.FeatureUserRead, + providers.FeatureUserDelete, +} func (c *Conn) Name() string { return ProviderName @@ -110,13 +106,13 @@ func (c *Conn) Compatible(ctx context.Context) bool { } func (c *Conn) UserCreate(ctx context.Context, user, pass, role string) (ok bool, err error) { - idrac := &IDrac9{ip: c.Host, username: c.User, password: c.Pass, log: c.Log} - idrac.xsrfToken = c.xsrfToken - idrac.httpClient = c.conn + idrac9 := &IDrac9{ip: c.Host, username: c.User, password: c.Pass, log: c.Log} + idrac9.xsrfToken = c.xsrfToken + idrac9.httpClient = c.conn // check if user already exists and capture any open user slots - users, err := idrac.queryUsers() + users, err := idrac9.queryUsers() if err != nil { - return false, errors.Wrap(err, "unable to query existing users") + return false, errors.Wrap(err, "IDRAC9 UserCreate(): Unable to query existing users.") } var availableID int for id, usr := range users { @@ -133,7 +129,7 @@ func (c *Conn) UserCreate(ctx context.Context, user, pass, role string) (ok bool return false, errors.New("all user account slots are in use, remove an account before adding a new one") } - var userToCreate User + var userToCreate UserInfo userToCreate.Enable = "Enabled" userToCreate.SolEnable = "Enabled" userToCreate.UserName = user @@ -148,7 +144,7 @@ func (c *Conn) UserCreate(ctx context.Context, user, pass, role string) (ok bool } // create the user - err = idrac.putUser(availableID, userToCreate) + err = idrac9.putUser(availableID, userToCreate) if err != nil { return false, errors.Wrap(err, "error creating user") } @@ -163,7 +159,7 @@ func (c *Conn) UserUpdate(ctx context.Context, user, pass, role string) (ok bool // check if user exists and capture its ID users, err := idrac.queryUsers() if err != nil { - return false, errors.Wrap(err, "unable to query existing users") + return false, errors.Wrap(err, "IDRAC9 UserUpdate(): Unable to query existing users.") } var id int for idx, usr := range users { @@ -176,7 +172,7 @@ func (c *Conn) UserUpdate(ctx context.Context, user, pass, role string) (ok bool } // create the user payload - var userPayload User + var userPayload UserInfo userPayload.Enable = "Enabled" userPayload.SolEnable = "Enabled" userPayload.UserName = user @@ -205,7 +201,7 @@ func (c *Conn) UserDelete(ctx context.Context, user string) (ok bool, err error) // get the user ID from a name users, err := idrac.queryUsers() if err != nil { - return false, errors.Wrap(err, "unable to query existing users") + return false, errors.Wrap(err, "UserDelete(): Unable to query existing users.") } var userID int for id, usr := range users { @@ -238,7 +234,7 @@ func (c *Conn) UserRead(ctx context.Context) (users []map[string]string, err err // get the user ID from a name existingUsers, err := idrac.queryUsers() if err != nil { - return nil, errors.Wrap(err, "unable to query existing users") + return nil, errors.Wrap(err, "IDRAC9 UserRead(): Unable to query existing users.") } for id, usr := range existingUsers { if usr.UserName == "" { diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/idrac9.go b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/idrac9.go index 90aab332..8e400173 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/idrac9.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/idrac9.go @@ -61,13 +61,13 @@ func (i *IDrac9) CheckCredentials() (err error) { } // get calls a given json endpoint of the ilo and returns the data -func (i *IDrac9) get(endpoint string, extraHeaders *map[string]string) (payload []byte, err error) { +func (i *IDrac9) get(endpoint string, extraHeaders *map[string]string) (statusCode int, payload []byte, err error) { i.log.V(1).Info("retrieving data from bmc", "step", "bmc connection", "vendor", dell.VendorID, "ip", i.ip, "endpoint", endpoint) bmcURL := fmt.Sprintf("https://%s", i.ip) req, err := http.NewRequest("GET", fmt.Sprintf("%s/%s", bmcURL, endpoint), nil) if err != nil { - return payload, err + return 0, nil, err } req.Header.Add("XSRF-TOKEN", i.xsrfToken) @@ -83,7 +83,7 @@ func (i *IDrac9) get(endpoint string, extraHeaders *map[string]string) (payload resp, err := i.httpClient.Do(req) if err != nil { - return payload, err + return 0, nil, err } defer resp.Body.Close() @@ -92,23 +92,23 @@ func (i *IDrac9) get(endpoint string, extraHeaders *map[string]string) (payload payload, err = ioutil.ReadAll(resp.Body) if err != nil { - return payload, err + return 0, nil, err } if resp.StatusCode == 404 { - return payload, errors.ErrPageNotFound + return 404, payload, errors.ErrPageNotFound } - return payload, err + return resp.StatusCode, payload, err } // PUTs data -func (i *IDrac9) put(endpoint string, payload []byte) (statusCode int, response []byte, err error) { +func (i *IDrac9) put(endpoint string, body []byte) (statusCode int, payload []byte, err error) { bmcURL := fmt.Sprintf("https://%s", i.ip) - req, err := http.NewRequest("PUT", fmt.Sprintf("%s/%s", bmcURL, endpoint), bytes.NewReader(payload)) + req, err := http.NewRequest("PUT", fmt.Sprintf("%s/%s", bmcURL, endpoint), bytes.NewReader(body)) if err != nil { - return statusCode, response, err + return statusCode, payload, err } req.Header.Add("XSRF-TOKEN", i.xsrfToken) @@ -118,28 +118,27 @@ func (i *IDrac9) put(endpoint string, payload []byte) (statusCode int, response resp, err := i.httpClient.Do(req) if err != nil { - return statusCode, response, err + return statusCode, payload, err } defer resp.Body.Close() respDump, _ := httputil.DumpResponse(resp, true) i.log.V(2).Info("responseTrace", "responseDump", string(respDump)) - response, err = ioutil.ReadAll(resp.Body) + payload, err = ioutil.ReadAll(resp.Body) if err != nil { - return statusCode, response, err + return statusCode, payload, err } if resp.StatusCode == 500 { - return resp.StatusCode, response, errors.Err500 + return resp.StatusCode, payload, errors.Err500 } - return resp.StatusCode, response, err + return resp.StatusCode, payload, err } // calls delete on the given endpoint func (i *IDrac9) delete(endpoint string) (statusCode int, payload []byte, err error) { - bmcURL := fmt.Sprintf("https://%s", i.ip) req, err := http.NewRequest("DELETE", fmt.Sprintf("%s/%s", bmcURL, endpoint), nil) @@ -156,6 +155,7 @@ func (i *IDrac9) delete(endpoint string) (statusCode int, payload []byte, err er if err != nil { return statusCode, payload, err } + defer resp.Body.Close() respDump, _ := httputil.DumpResponse(resp, true) @@ -171,7 +171,6 @@ func (i *IDrac9) delete(endpoint string) (statusCode int, payload []byte, err er // posts the payload to the given endpoint func (i *IDrac9) post(endpoint string, data []byte, formDataContentType string) (statusCode int, body []byte, err error) { - u, err := url.Parse(fmt.Sprintf("https://%s/%s", i.ip, endpoint)) if err != nil { return 0, []byte{}, err @@ -268,11 +267,11 @@ func (i *IDrac9) Nics() (nics []*devices.Nic, err error) { return nics, err } -// Serial returns the device serial +// Returns the device serial or an empty string in case it doesn't find it. func (i *IDrac9) Serial() (serial string, err error) { err = i.loadHwData() if err != nil { - return serial, err + return "", err } for _, component := range i.iDracInventory.Component { @@ -284,7 +283,8 @@ func (i *IDrac9) Serial() (serial string, err error) { } } } - return serial, err + + return "", nil } // ChassisSerial returns the serial number of the chassis where the blade is attached @@ -317,10 +317,14 @@ func (i *IDrac9) Status() (status string, err error) { "X-SYSMGMT-OPTIMIZE": "true", } - url := "sysmgmt/2016/server/extended_health" - payload, err := i.get(url, extraHeaders) - if err != nil { - return status, err + endpoint := "sysmgmt/2016/server/extended_health" + statusCode, payload, err := i.get(endpoint, extraHeaders) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + return "", err } iDracHealthStatus := &dell.IDracHealthStatus{} @@ -342,13 +346,17 @@ func (i *IDrac9) Status() (status string, err error) { func (i *IDrac9) PowerKw() (power float64, err error) { err = i.httpLogin() if err != nil { - return power, err + return 0, err } - url := "sysmgmt/2015/server/sensor/power" - payload, err := i.get(url, nil) - if err != nil { - return power, err + endpoint := "sysmgmt/2015/server/sensor/power" + statusCode, payload, err := i.get(endpoint, nil) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + return 0, err } iDracPowerData := &dell.IDrac9PowerData{} @@ -485,10 +493,13 @@ func (i *IDrac9) Slot() (slot int, err error) { // slotC6420 returns the current slot for the C6420 blade within the chassis func (i *IDrac9) slotC6420() (slot int, err error) { + endpoint := "sysmgmt/2012/server/configgroup/System.ServerTopology" + statusCode, payload, err := i.get(endpoint, nil) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } - var url = "sysmgmt/2012/server/configgroup/System.ServerTopology" - payload, err := i.get(url, nil) - if err != nil { return -1, err } @@ -510,23 +521,24 @@ func (i *IDrac9) slotC6420() (slot int, err error) { return slot, err } -// Model returns the device model +// Returns the device model or an empty string in case it doesn't find it. func (i *IDrac9) Model() (model string, err error) { err = i.loadHwData() if err != nil { - return model, err + return "", err } for _, component := range i.iDracInventory.Component { if component.Classname == "DCIM_SystemView" { for _, property := range component.Properties { if property.Name == "Model" && property.Type == "string" { - return property.Value, err + return property.Value, nil } } } } - return model, err + + return "", nil } // HardwareType returns the type of bmc we are talking to @@ -545,16 +557,20 @@ func (i *IDrac9) License() (name string, licType string, err error) { "X_SYSMGMT_OPTIMIZE": "true", } - url := "sysmgmt/2012/server/license" - payload, err := i.get(url, extraHeaders) - if err != nil { - return name, licType, err + endpoint := "sysmgmt/2012/server/license" + statusCode, payload, err := i.get(endpoint, extraHeaders) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + return "", "", err } iDracLicense := &dell.IDracLicense{} err = json.Unmarshal(payload, iDracLicense) if err != nil { - return name, licType, err + return "", "", err } if iDracLicense.License.VConsole == 1 { @@ -590,26 +606,30 @@ func (i *IDrac9) Memory() (mem int, err error) { func (i *IDrac9) TempC() (temp int, err error) { err = i.httpLogin() if err != nil { - return temp, err + return 0, err } extraHeaders := &map[string]string{ "X-SYSMGMT-OPTIMIZE": "true", } - url := "sysmgmt/2012/server/temperature" - payload, err := i.get(url, extraHeaders) - if err != nil { - return temp, err + endpoint := "sysmgmt/2012/server/temperature" + statusCode, payload, err := i.get(endpoint, extraHeaders) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + return 0, err } iDracTemp := &dell.IDracTemp{} err = json.Unmarshal(payload, iDracTemp) if err != nil { - return temp, err + return 0, err } - return iDracTemp.Temperatures.IDRACEmbedded1SystemBoardInletTemp.Reading, err + return iDracTemp.Temperatures.IDRACEmbedded1SystemBoardInletTemp.Reading, nil } // CPU return the cpu, cores and hyperthreads the server @@ -679,9 +699,13 @@ func (i *IDrac9) Psus() (psus []*devices.Psu, err error) { "X-SYSMGMT-OPTIMIZE": "true", } - url := "sysmgmt/2013/server/sensor/powersupplyunit" - payload, err := i.get(url, extraHeaders) - if err != nil { + endpoint := "sysmgmt/2013/server/sensor/powersupplyunit" + statusCode, payload, err := i.get(endpoint, extraHeaders) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + return psus, err } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/model.go b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/model.go index d699e0ad..0ae1e6f2 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/model.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/model.go @@ -1,44 +1,42 @@ package idrac9 -type userInfo map[int]User -type idracUsers map[string]userInfo +type ( + UsersInfo map[int]UserInfo + IdracUsers map[string]UsersInfo +) // User struct declares user configuration payload. -type User struct { - UserName string `json:"UserName,omitempty"` - Password string `json:"Password,omitempty"` - Enable string `json:"Enable,omitempty"` //Enabled, Disabled - Privilege string `json:"Privilege,omitempty"` //511, 499 - IpmiLanPrivilege string `json:"IpmiLanPrivilege,omitempty"` //Administrator, Operator - SolEnable string `json:"SolEnable,omitempty"` //Disabled, Enabled - ProtocolEnable string `json:"ProtocolEnable,omitempty"` //Disabled, Enabled (SNMPv2) - AuthenticationProtocol string `json:"AuthenticationProtocol,omitempty"` //SHA, MD5, None - PrivacyProtocol string `json:"PrivacyProtocol,omitempty"` //AES, DES, None +type UserInfo struct { + UserName string `json:"UserName,omitempty"` + Password string `json:"Password,omitempty"` + Enable string `json:"Enable,omitempty"` // Enabled, Disabled + Privilege string `json:"Privilege,omitempty"` // 511, 499 + IpmiLanPrivilege string `json:"IpmiLanPrivilege,omitempty"` // Administrator, Operator + SolEnable string `json:"SolEnable,omitempty"` // Disabled, Enabled + ProtocolEnable string `json:"ProtocolEnable,omitempty"` // Disabled, Enabled (SNMPv3) } // Ldap struct declares Ldap configuration payload. type Ldap struct { - BaseDN string `json:"BaseDN"` //dell - BindDN string `json:"BindDN"` //cn=dell - CertValidationEnable string `json:"CertValidationEnable"` //Disabled - Enable string `json:"Enable"` //Enabled - GroupAttribute string `json:"GroupAttribute"` //memberUid - GroupAttributeIsDN string `json:"GroupAttributeIsDN"` //Enabled - Port string `json:"Port"` //636 - SearchFilter string `json:"SearchFilter"` //objectClass=posixAccount - Server string `json:"Server"` //ldap.example.com" - UserAttribute string `json:"UserAttribute"` //uid + BaseDN string `json:"BaseDN"` // dell + BindDN string `json:"BindDN"` // cn=dell + CertValidationEnable string `json:"CertValidationEnable"` // Disabled + Enable string `json:"Enable"` // Enabled + GroupAttribute string `json:"GroupAttribute"` // memberUid + GroupAttributeIsDN string `json:"GroupAttributeIsDN"` // Enabled + Port string `json:"Port"` // 636 + SearchFilter string `json:"SearchFilter"` // objectClass=posixAccount + Server string `json:"Server"` // ldap.example.com" + UserAttribute string `json:"UserAttribute"` // uid } -type idracLdapRoleGroups map[string]LdapRoleGroups - -// LdapRoleGroups declares the format in which ldap role groups are un/marshalled. +// LdapRoleGroups declares the format in which LDAP role groups are (un)marshaled. type LdapRoleGroups map[string]LdapRoleGroup // LdapRoleGroup declares Ldap role group configuration payload. type LdapRoleGroup struct { - DN string `json:"DN"` //cn=dell,cn=bmcAdmins - Privilege string `json:"Privilege"` //511 (Administrator), 499 (Operator) + DN string `json:"DN"` // cn=dell,cn=bmcAdmins + Privilege string `json:"Privilege"` // 511 (Administrator), 499 (Operator) } // Syslog declares syslog configuration payload. @@ -52,42 +50,42 @@ type Syslog struct { // NtpConfig declares NTP configuration payload. type NtpConfig struct { - Enable string `json:"NTPEnable"` //Enabled - NTP1 string `json:"NTP1"` //example0.ntp.com - NTP2 string `json:"NTP2"` //example1.ntp.com - NTP3 string `json:"NTP3"` //example2.ntp.com + Enable string `json:"NTPEnable"` // Enabled + NTP1 string `json:"NTP1"` // example0.ntp.com + NTP2 string `json:"NTP2"` // example1.ntp.com + NTP3 string `json:"NTP3"` // example2.ntp.com } // Ipv4 declares IPv4 configuration payload. type Ipv4 struct { - Enable string `json:"Enable"` //Enabled - DHCPEnable string `json:"DHCPEnable"` //Enabled - DNSFromDHCP string `json:"DNSFromDHCP"` //Enabled + Enable string `json:"Enable"` // Enabled + DHCPEnable string `json:"DHCPEnable"` // Enabled + DNSFromDHCP string `json:"DNSFromDHCP"` // Enabled } // IpmiOverLan declares IpmiOverLan configuration payload. type IpmiOverLan struct { - Enable string `json:"Enable"` //Enabled - PrivLimit string `json:"PrivLimit"` //Administrator - EncryptionKey string `json:"EncryptionKey"` //0000000000000000000000000000000000000000 + Enable string `json:"Enable"` // Enabled + PrivLimit string `json:"PrivLimit"` // Administrator + EncryptionKey string `json:"EncryptionKey"` // 0000000000000000000000000000000000000000 } // SerialRedirection declares serial console configuration payload. type SerialRedirection struct { - Enable string `json:"Enable"` //Enabled + Enable string `json:"Enable"` // Enabled QuitKey string `json:"QuitKey"` //^\\ } -// SerialOverLan declares serial over lan configuration payload. +// SerialOverLan configuration payload. type SerialOverLan struct { - Enable string `json:"Enable"` //Enabled - BaudRate string `json:"BaudRate"` //115200 - MinPrivilege string `json:"MinPrivilege"` //Administrator + Enable string `json:"Enable"` // Enabled + BaudRate string `json:"BaudRate"` // 115200 + MinPrivilege string `json:"MinPrivilege"` // Administrator } // Timezone declares timezone configuration payload. type Timezone struct { - Timezone string `json:"Timezone"` //CET + Timezone string `json:"Timezone"` // CET } // CSRInfo declares SSL/TLS CSR request payloads. @@ -576,6 +574,7 @@ var alertConfigPayload = []byte(`{ }`) // Timezones declares all known timezones, taken from the idrac web interface. +// nolint: spell var Timezones = map[string]string{ "Africa/Abidjan": "Africa/Abidjan", "Africa/Accra": "Africa/Accra", diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/model_odata.go b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/model_odata.go index 0c9104b1..e41fc2e5 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/model_odata.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/model_odata.go @@ -14,14 +14,12 @@ type Odata struct { JobState string `json:"JobState,omitempty"` } -// BiosSettings is an alias type of cfgresources.Idrac9BiosSettings -//All supported bios settings can be queried from through redfish/v1/Systems/System.Embedded.1/Bios -//NOTE: all fields int this struct are expected to be of type string, for details see diffBiosSettings() -// This type aliasing tightly couples config resources, maybe theres another aproach here. +// BiosSettings is an alias type of cfgresources.Idrac9BiosSettings. +// All supported BIOS settings can be queried from through redfish/v1/Systems/System.Embedded.1/Bios. +// NOTE: All fields in this struct are expected to be of type string, for details see diffBiosSettings(). +// This type aliasing tightly couples config resources, maybe there's another aproach here. type BiosSettings = cfgresources.Idrac9BiosSettings -// TargetSettingsURI struct declares parameters to unmarshal TargetSettingsURI. -//Post Jobs to be done type TargetSettingsURI struct { - TargetSettingsURI string `json:"TargetSettingsURI"` //e.g /redfish/v1/Systems/System.Embedded.1/Bios/Settings + TargetSettingsURI string `json:"TargetSettingsURI"` // e.g. /redfish/v1/Systems/System.Embedded.1/Bios/Settings } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/query.go b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/query.go index 2c52e9d4..e598baf0 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/query.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/query.go @@ -4,10 +4,10 @@ import ( "crypto/tls" "crypto/x509" "encoding/json" + "fmt" "net" "time" - "github.com/bmc-toolbox/bmclib/internal" "github.com/bmc-toolbox/bmclib/internal/helper" ) @@ -15,13 +15,11 @@ import ( // The bool value returned indicates if the BMC supports CSR generation. // CurrentHTTPSCert implements the Configure interface. func (i *IDrac9) CurrentHTTPSCert() ([]*x509.Certificate, bool, error) { - dialer := &net.Dialer{ Timeout: time.Duration(10) * time.Second, } conn, err := tls.DialWithDialer(dialer, "tcp", i.ip+":"+"443", &tls.Config{InsecureSkipVerify: true}) - if err != nil { return []*x509.Certificate{{}}, true, err } @@ -29,92 +27,67 @@ func (i *IDrac9) CurrentHTTPSCert() ([]*x509.Certificate, bool, error) { defer conn.Close() return conn.ConnectionState().PeerCertificates, true, nil - } // Screenshot grab screen preview. func (i *IDrac9) Screenshot() (response []byte, extension string, err error) { err = i.httpLogin() if err != nil { - return response, extension, err + return nil, "", err } extension = "png" - endpoint1 := "sysmgmt/2015/server/preview" - _, err = i.get(endpoint1, &map[string]string{}) - if err != nil { - return []byte{}, extension, err + endpoint := "sysmgmt/2015/server/preview" + statusCode, _, err := i.get(endpoint, &map[string]string{}) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + return nil, "", err } - endpoint2 := "capconsole/scapture0.png" - response, err = i.get(endpoint2, &map[string]string{}) - if err != nil { - return []byte{}, extension, err + endpoint = "capconsole/scapture0.png" + statusCode, response, err = i.get(endpoint, &map[string]string{}) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + return nil, "", err } - return response, extension, err + return response, extension, nil } -func (i *IDrac9) queryUsers() (users map[int]User, err error) { - +func (i *IDrac9) queryUsers() (users UsersInfo, err error) { endpoint := "sysmgmt/2012/server/configgroup/iDRAC.Users" + statusCode, response, err := i.get(endpoint, &map[string]string{}) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } - data, err := i.get(endpoint, &map[string]string{}) - if err != nil { - i.log.V(1).Error(err, "GET request failed.", + i.log.V(1).Error(err, "queryUsers(): GET request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "endpoint", endpoint, "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) return users, err } - userData := make(idracUsers) - err = json.Unmarshal(data, &userData) + userData := make(IdracUsers) + err = json.Unmarshal(response, &userData) if err != nil { i.log.V(1).Error(err, "Unable to unmarshal payload.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "resource", "User", "step", "queryUserInfo", - "Error", internal.ErrStringOrEmpty(err), ) return users, err } - return userData["iDRAC.Users"], err -} - -func (i *IDrac9) queryLdapRoleGroups() (ldapRoleGroups LdapRoleGroups, err error) { - - endpoint := "sysmgmt/2012/server/configgroup/iDRAC.LDAPRoleGroup" - - data, err := i.get(endpoint, &map[string]string{}) - if err != nil { - i.log.V(1).Error(err, "GET request failed.", - "IP", i.ip, - "Model", i.HardwareType(), - "endpoint", endpoint, - "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), - ) - return ldapRoleGroups, err - } - - idracLdapRoleGroups := make(idracLdapRoleGroups) - err = json.Unmarshal(data, &idracLdapRoleGroups) - if err != nil { - i.log.V(1).Error(err, "Unable to unmarshal payload.", - "IP", i.ip, - "Model", i.HardwareType(), - "resource", "User", - "step", "queryUserInfo", - "Error", internal.ErrStringOrEmpty(err), - ) - return ldapRoleGroups, err - } - - return idracLdapRoleGroups["iDRAC.LDAPRoleGroup"], err + return userData["iDRAC.Users"], nil } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/redfish_helpers.go b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/redfish_helpers.go index 0dc553ce..90496da4 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/redfish_helpers.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/redfish_helpers.go @@ -15,11 +15,10 @@ import ( "github.com/pkg/errors" ) -//diffs two BiosSettings and returns a BiosSettings with the difference. -//!! Note this assumes the struct fields in BiosSettings are all strings !! +// Diffs two BiosSettings and returns a BiosSettings with the difference. +// NOTE: This assumes the struct fields in BiosSettings are all strings! func diffBiosSettings(new *BiosSettings, current *BiosSettings) (diff *BiosSettings, err error) { - - //the struct that holds the changes + // This struct only holds the changes to be corrected. diff = &BiosSettings{} struct1V := reflect.ValueOf(new).Elem() @@ -51,7 +50,6 @@ func diffBiosSettings(new *BiosSettings, current *BiosSettings) (diff *BiosSetti } func (i *IDrac9) getBiosSettings() (biosSettings *BiosSettings, err error) { - endpoint := "redfish/v1/Systems/System.Embedded.1/Bios" oData := Odata{} @@ -66,7 +64,6 @@ func (i *IDrac9) getBiosSettings() (biosSettings *BiosSettings, err error) { } return oData.Attributes, err - } /* @@ -97,59 +94,57 @@ func (i *IDrac9) biosSettingsPendingReboot() (pendingBiosSettings *BiosSettings, // PATCHs Bios settings, queues setting to be applied at next boot. func (i *IDrac9) setBiosSettings(biosSettings *BiosSettings) (err error) { - biosSettingsURI := "redfish/v1/Systems/System.Embedded.1/Bios/Settings" idracPayload := make(map[string]*BiosSettings) idracPayload["Attributes"] = biosSettings payload, err := json.Marshal(idracPayload) if err != nil { - msg := fmt.Sprintf("Error marshalling biosAttributes payload: %s", err) + msg := fmt.Sprintf("Error marshaling biosAttributes payload: %s", err) return errors.New(msg) } - //PATCH bios settings statusCode, _, err := i.queryRedfish("PATCH", biosSettingsURI, payload) - if err != nil || statusCode != 200 { - msg := fmt.Sprintf("PATCH request to set Bios config, returned code: %d", statusCode) - return errors.New(msg) + if err != nil { + return fmt.Errorf("PATCH request to set BIOS config failed with error %s!", err.Error()) + } else if statusCode != 200 { + return fmt.Errorf("PATCH request to set BIOS config failed with status code %d!", statusCode) } - //Queue config to be set at next boot. + // Queue config to be set at next boot. return i.queueJobs(biosSettingsURI) } func (i *IDrac9) queueJobs(jobURI string) (err error) { - endpoint := "redfish/v1/Managers/iDRAC.Embedded.1/Jobs" if !strings.HasPrefix(jobURI, "/") { jobURI = fmt.Sprintf("/%s", jobURI) } - //Queue this setting to be applied at the next boot. + // Queue this setting to be applied at the next boot. targetSetting := TargetSettingsURI{ TargetSettingsURI: jobURI, } payload, err := json.Marshal(targetSetting) if err != nil { - msg := fmt.Sprintf("Error marshalling job queue payload for uri: %s, error: %s", jobURI, err) + msg := fmt.Sprintf("Error marshaling job queue payload for uri: %s, error: %s", jobURI, err) return errors.New(msg) } statusCode, _, err := i.queryRedfish("POST", endpoint, payload) - if err != nil || statusCode != 200 { - msg := fmt.Sprintf("POST request to queue job, returned code: %d", statusCode) - return errors.New(msg) + if err != nil { + return fmt.Errorf("POST request to queue job %s failed with error %s!", jobURI, err.Error()) + } else if statusCode != 200 { + return fmt.Errorf("POST request to queue job %s failed with status code %d!", jobURI, statusCode) } - return err + return nil } // Given a Job ID, purge it from the job queue func (i *IDrac9) purgeJob(jobID string) (err error) { - if !strings.Contains(jobID, "JID") { return errors.New("Invalid Job ID given, Job IDs should be prefixed with JID_") } @@ -157,24 +152,22 @@ func (i *IDrac9) purgeJob(jobID string) (err error) { endpoint := fmt.Sprintf("%s/%s", "redfish/v1/Managers/iDRAC.Embedded.1/Jobs", jobID) statusCode, _, err := i.queryRedfish("DELETE", endpoint, nil) - if err != nil || statusCode != 200 { - msg := fmt.Sprintf("DELETE request to purge job, returned code: %d", statusCode) - return errors.New(msg) + if err != nil { + return fmt.Errorf("DELETE request to purge job %s failed with error %s!", jobID, err.Error()) + } else if statusCode != 200 { + return fmt.Errorf("DELETE request to purge job %s failed with status code %d!", jobID, statusCode) } - return err + return nil } -// Purges any jobs related to Bios configuration +// Purges any jobs related to BIOS configuration. func (i *IDrac9) purgeJobsForBiosSettings() (err error) { - - //get current job ids jobIDs, err := i.getJobIds() if err != nil { return err } - //check if any jobs are queued for bios configuration if len(jobIDs) > 0 { err = i.purgeJobsByType(jobIDs, "BIOSConfiguration") if err != nil { @@ -185,7 +178,7 @@ func (i *IDrac9) purgeJobsForBiosSettings() (err error) { return err } -//Purges jobs of the given type - if they are in the "Scheduled" state +// Purges jobs of the given type (if they are in the "Scheduled" state). func (i *IDrac9) purgeJobsByType(jobIDs []string, jobType string) (err error) { for _, jobID := range jobIDs { jState, jType, err := i.getJob(jobID) @@ -203,9 +196,8 @@ func (i *IDrac9) purgeJobsByType(jobIDs []string, jobType string) (err error) { return err } -//Returns the job state, Type for the given Job id +// Returns the job state and type for the given job ID. func (i *IDrac9) getJob(jobID string) (jobState string, jobType string, err error) { - endpoint := fmt.Sprintf("%s/%s", "redfish/v1/Managers/iDRAC.Embedded.1/Jobs/", jobID) oData := Odata{} @@ -220,12 +212,10 @@ func (i *IDrac9) getJob(jobID string) (jobState string, jobType string, err erro } return oData.JobState, oData.JobType, err - } // Returns Job ids func (i *IDrac9) getJobIds() (jobs []string, err error) { - endpoint := "redfish/v1/Managers/iDRAC.Embedded.1/Jobs" oData := Odata{} @@ -239,15 +229,15 @@ func (i *IDrac9) getJobIds() (jobs []string, err error) { return jobs, err } - //No jobs present. + // No jobs present. if oData.MembersCount < 1 { return jobs, err } - //[{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/Jobs/JID_367624308519"}] + // e.g. [{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/Jobs/JID_367624308519"}] for _, m := range oData.Members { for _, v := range m { - //extract the Job id from the string + // Extract the Job ID from the string: tokens := strings.Split(v, "/") jobID := tokens[len(tokens)-1] jobs = append(jobs, jobID) @@ -270,7 +260,6 @@ func isRequestMethodValid(method string) (valid bool) { // GET data func (i *IDrac9) queryRedfish(method string, endpoint string, payload []byte) (statusCode int, response []byte, err error) { - if !isRequestMethodValid(method) { return statusCode, response, fmt.Errorf("Invalid request method: %v", method) } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/setupConnections.go b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/setupConnections.go index ffeb22ea..162ab962 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/setupConnections.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/idrac9/setupConnections.go @@ -67,43 +67,47 @@ func (i *IDrac9) httpLogin() (err error) { return err } - //0 = login success. - //7 = login success with default credentials. + // 0 = Login successful. + // 7 = Login successful with default credentials. if iDracAuth.AuthResult != 0 && iDracAuth.AuthResult != 7 { return errors.ErrLoginFailed } i.httpClient = httpClient - - return err + return nil } // loadHwData load the full hardware information from the iDrac func (i *IDrac9) loadHwData() (err error) { err = i.httpLogin() if err != nil { - return err + return fmt.Errorf("IDrac9.loadHwData(): HTTP login problem: " + err.Error()) } url := "sysmgmt/2012/server/inventory/hardware" - payload, err := i.get(url, nil) - if err != nil { - return err + statusCode, response, err := i.get(url, nil) + if err != nil || statusCode != 200 { + msg := fmt.Sprintf("Status code is %d", statusCode) + if err != nil { + msg += ", Error: " + err.Error() + } else { + msg += ", Response: " + string(response) + } + return fmt.Errorf("IDrac9.loadHwData(): GET request failed. " + msg) } iDracInventory := &dell.IDracInventory{} - err = xml.Unmarshal(payload, iDracInventory) + err = xml.Unmarshal(response, iDracInventory) if err != nil { - return err + return fmt.Errorf("IDrac9.loadHwData(): XML unmarshal problem: " + err.Error()) } if iDracInventory.Component == nil { - return errors.ErrUnableToReadData + return fmt.Errorf("IDrac9.loadHwData(): HTTP login problem: " + errors.ErrUnableToReadData.Error()) } i.iDracInventory = iDracInventory - - return err + return nil } // Close closes the connection properly diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/m1000e/actions.go b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/m1000e/actions.go index a3e795f5..dff54495 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/m1000e/actions.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/m1000e/actions.go @@ -197,7 +197,7 @@ func (m *M1000e) PxeOnceBlade(position int) (bool, error) { return false, fmt.Errorf(output) } -// SetIpmiOverLan Enable/Disable IPMI over lan parameter per blade in chassis +// Enable/Disable the IpmiOverLan parameter per blade in the chassis. func (m *M1000e) SetIpmiOverLan(position int, enable bool) (bool, error) { var state int if enable { @@ -215,7 +215,6 @@ func (m *M1000e) SetIpmiOverLan(position int, enable bool) (bool, error) { } return false, fmt.Errorf(output) - } // SetDynamicPower Enable/Disable Dynamic Power - Dynamic Power Supply Engagement (DPSE) in Dell jargon. @@ -273,10 +272,10 @@ func (m *M1000e) SetFlexAddressState(position int, enable bool) (bool, error) { } // UpdateFirmware updates the chassis firmware -func (m *M1000e) UpdateFirmware(source, file string) (bool, error) { +func (m *M1000e) UpdateFirmware(source, file string) (bool, string, error) { u, err := url.Parse(source) if err != nil { - return false, err + return false, "", err } password, ok := u.User.Password() @@ -287,14 +286,14 @@ func (m *M1000e) UpdateFirmware(source, file string) (bool, error) { cmd := fmt.Sprintf("fwupdate -f %s %s %s -d %s -m cmc-active -m cmc-standby", u.Host, u.User.Username(), password, u.Path) output, err := m.sshClient.Run(cmd) if err != nil { - return false, fmt.Errorf("output: %q: %w", output, err) + return false, output, fmt.Errorf("output: %q: %w", output, err) } if strings.Contains(output, "Firmware update has been initiated") { - return true, nil + return true, output, nil } - return false, err + return false, output, err } // UpdateFirmwareBmcBlade updates the blade BMC firmware diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/m1000e/configure.go b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/m1000e/configure.go index 77d5493f..ae1ff9c3 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/m1000e/configure.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/m1000e/configure.go @@ -11,7 +11,6 @@ import ( "github.com/bmc-toolbox/bmclib/cfgresources" "github.com/bmc-toolbox/bmclib/devices" - "github.com/bmc-toolbox/bmclib/internal" "github.com/google/go-querystring/query" ) @@ -85,11 +84,8 @@ func (m *M1000e) User(cfgUsers []*cfgresources.User) (err error) { } for id, cfgUser := range cfgUsers { - userID := id + 1 - //setup params to post userParams := m.newUserCfg(cfgUser, userID) - userParams.SessionToken = m.SessionToken path := fmt.Sprintf("user?id=%d", userID) form, _ := query.Values(userParams) @@ -98,8 +94,7 @@ func (m *M1000e) User(cfgUsers []*cfgresources.User) (err error) { return err } - m.log.V(1).Info("User account config parameters applied.", "IP", m.ip, "Model", m.HardwareType()) - + m.log.V(1).Info("User account config parameters applied.", "IP", m.ip, "HardwareType", m.HardwareType()) } return err @@ -110,7 +105,6 @@ func (m *M1000e) User(cfgUsers []*cfgresources.User) (err error) { // TODO: this currently applies network config as well, // figure a way to split the two. func (m *M1000e) Syslog(cfg *cfgresources.Syslog) (err error) { - interfaceParams := m.newInterfaceCfg(cfg) interfaceParams.SessionToken = m.SessionToken @@ -120,14 +114,13 @@ func (m *M1000e) Syslog(cfg *cfgresources.Syslog) (err error) { return err } - m.log.V(1).Info("Interface config parameters applied.", "IP", m.ip, "Model", m.HardwareType()) + m.log.V(1).Info("Interface config parameters applied.", "IP", m.ip, "HardwareType", m.HardwareType()) return err } // Ntp applies NTP configuration params // Ntp implements the Configure interface. func (m *M1000e) Ntp(cfg *cfgresources.Ntp) (err error) { - err = m.httpLogin() if err != nil { return err @@ -143,14 +136,13 @@ func (m *M1000e) Ntp(cfg *cfgresources.Ntp) (err error) { return err } - m.log.V(1).Info("DateTime config parameters applied.", "IP", m.ip, "Model", m.HardwareType()) + m.log.V(1).Info("DateTime config parameters applied.", "IP", m.ip, "HardwareType", m.HardwareType()) return err } // Ldap applies LDAP configuration params. // Ldap implements the Configure interface. func (m *M1000e) Ldap(cfg *cfgresources.Ldap) (err error) { - directoryServicesParams := m.newDirectoryServicesCfg(cfg) directoryServicesParams.SessionToken = m.SessionToken @@ -161,7 +153,7 @@ func (m *M1000e) Ldap(cfg *cfgresources.Ldap) (err error) { return err } - m.log.V(1).Info("Ldap config parameters applied.", "IP", m.ip, "Model", m.HardwareType()) + m.log.V(1).Info("Ldap config parameters applied.", "IP", m.ip, "HardwareType", m.HardwareType()) return err } @@ -181,24 +173,22 @@ func (m *M1000e) applyLdapRoleCfg(cfg LdapArgParams, roleID int) (err error) { return err } - m.log.V(1).Info("Ldap Role group config parameters applied.", "IP", m.ip, "Model", m.HardwareType()) + m.log.V(1).Info("Ldap Role group config parameters applied.", "IP", m.ip, "HardwareType", m.HardwareType()) return err } -// LdapGroup applies LDAP Group/Role related configuration -// LdapGroup implements the Configure interface. -func (m *M1000e) LdapGroup(cfg []*cfgresources.LdapGroup, cfgLdap *cfgresources.Ldap) (err error) { - +// LdapGroups applies LDAP Group/Role related configuration +// LdapGroups implements the Configure interface. +func (m *M1000e) LdapGroups(cfgGroups []*cfgresources.LdapGroup, cfgLdap *cfgresources.Ldap) (err error) { roleID := 1 - for _, group := range cfg { + for _, group := range cfgGroups { ldapRoleParams, err := m.newLdapRoleCfg(group, roleID) if err != nil { m.log.V(1).Error(err, "Unable to apply Ldap role group config.", "step", "applyLdapGroupParams", "Ldap role", group.Role, "IP", m.ip, - "Model", m.HardwareType(), - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", m.HardwareType(), ) return err } @@ -209,7 +199,7 @@ func (m *M1000e) LdapGroup(cfg []*cfgresources.LdapGroup, cfgLdap *cfgresources. "step", "applyLdapGroupParams", "Ldap role", group.Role, "IP", m.ip, - "Model", m.HardwareType(), + "HardwareType", m.HardwareType(), "Error", err, ) return err @@ -217,7 +207,7 @@ func (m *M1000e) LdapGroup(cfg []*cfgresources.LdapGroup, cfgLdap *cfgresources. m.log.V(1).Info("Ldap group parameters applied.", "IP", m.ip, - "Model", m.HardwareType(), + "HardwareType", m.HardwareType(), "Role", group.Role, "Group", group.Group, ) @@ -273,7 +263,7 @@ func (m *M1000e) CurrentHTTPSCert() (c []*x509.Certificate, b bool, e error) { // // m.log.V(1).Info("", // "IP": m.ip, -// "Model": m.HardwareType(), +// "HardwareType": m.HardwareType(), // }).Debug("SSL certs uploaded.") // return err //} @@ -397,9 +387,6 @@ func (m *M1000e) post(endpoint string, form *url.Values) (err error) { reqDump, _ := httputil.DumpRequestOut(req, true) m.log.V(2).Info("requestTrace", "requestDump", string(reqDump), "url", fmt.Sprintf("https://%s/cgi-bin/webcgi/%s", m.ip, endpoint)) - //XXX to debug - //fmt.Printf("--> %+v\n", form.Encode()) - //return err resp, err := m.httpClient.Do(req) if err != nil { return err @@ -430,7 +417,6 @@ func (m *M1000e) ApplySecurityCfg(cfg LoginSecurityParams) (err error) { return err } - m.log.V(1).Info("Security config parameters applied.", "IP", m.ip, "Model", m.HardwareType()) + m.log.V(1).Info("Security config parameters applied.", "IP", m.ip, "HardwareType", m.HardwareType()) return err - } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/m1000e/constructors.go b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/m1000e/constructors.go index 218bfcb1..2a7bdc8b 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/m1000e/constructors.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/m1000e/constructors.go @@ -24,7 +24,6 @@ import ( // Given the Ntp resource, // populate the required Datetime params func (m *M1000e) newDatetimeCfg(ntp *cfgresources.Ntp) DatetimeParams { - if ntp.Timezone == "" { // TODO update method with error return and return err in this if, was doing logrus.Fatal here msg := "ntp resource parameter timezone required but not declared" @@ -58,7 +57,6 @@ func (m *M1000e) newDatetimeCfg(ntp *cfgresources.Ntp) DatetimeParams { // A multipart form would be required to upload the cacert // Given the Ldap resource, populate required DirectoryServicesParams func (m *M1000e) newDirectoryServicesCfg(ldap *cfgresources.Ldap) DirectoryServicesParams { - var userAttribute, groupAttribute string if ldap.Server == "" { m.log.V(1).Info("Ldap resource parameter Server required but not declared.", "step", "newDirectoryServicesCfg") @@ -97,7 +95,7 @@ func (m *M1000e) newDirectoryServicesCfg(ldap *cfgresources.Ldap) DirectoryServi GenLdapCertValidateEnableCk: true, GenLdapCertValidateEnable: false, GenLdapBindDn: ldap.BindDn, - GenLdapBindPasswd: "PASSWORD", //we + GenLdapBindPasswd: "PASSWORD", GenLdapBindPasswdChanged: false, GenLdapBaseDn: ldap.BaseDn, GenLdapUserAttribute: userAttribute, @@ -131,7 +129,6 @@ func (m *M1000e) newDirectoryServicesCfg(ldap *cfgresources.Ldap) DirectoryServi // Return bool value if the role is valid. func (m *M1000e) isRoleValid(role string) bool { - validRoles := []string{"admin", "user"} for _, v := range validRoles { if role == v { @@ -143,34 +140,33 @@ func (m *M1000e) isRoleValid(role string) bool { } // Given the Ldap resource, populate required LdapArgParams -func (m *M1000e) newLdapRoleCfg(cfg *cfgresources.LdapGroup, roleID int) (ldapArgCfg LdapArgParams, err error) { - +func (m *M1000e) newLdapRoleCfg(cfgGroups *cfgresources.LdapGroup, roleID int) (ldapArgCfg LdapArgParams, err error) { var privBitmap, genLdapRolePrivilege int - if cfg.Group == "" { + if cfgGroups.Group == "" { msg := "Ldap resource parameter Group required but not declared." err = errors.New(msg) - m.log.V(1).Error(err, msg, "Role", cfg.Role, "step", "newLdapRoleCfg") + m.log.V(1).Error(err, msg, "Role", cfgGroups.Role, "step", "newLdapRoleCfg") return ldapArgCfg, err } - if cfg.GroupBaseDn == "" && cfg.Enable { + if cfgGroups.GroupBaseDn == "" && cfgGroups.Enable { msg := "Ldap resource parameter GroupBaseDn required but not declared." err = errors.New(msg) - m.log.V(1).Error(err, msg, "Role", cfg.Role, "step", "newLdapRoleCfg") + m.log.V(1).Error(err, msg, "Role", cfgGroups.Role, "step", "newLdapRoleCfg") return ldapArgCfg, err } - if !m.isRoleValid(cfg.Role) { + if !m.isRoleValid(cfgGroups.Role) { msg := "Ldap resource Role must be a valid role: admin OR user." err = errors.New(msg) - m.log.V(1).Error(err, msg, "Role", cfg.Role, "step", "newLdapRoleCfg") + m.log.V(1).Error(err, msg, "Role", cfgGroups.Role, "step", "newLdapRoleCfg") return ldapArgCfg, err } - groupDn := fmt.Sprintf("cn=%s,%s", cfg.Group, cfg.GroupBaseDn) + groupDn := fmt.Sprintf("cn=%s,%s", cfgGroups.Group, cfgGroups.GroupBaseDn) - switch cfg.Role { + switch cfgGroups.Role { case "admin": privBitmap = 4095 genLdapRolePrivilege = privBitmap @@ -204,7 +200,6 @@ func (m *M1000e) newLdapRoleCfg(cfg *cfgresources.LdapGroup, roleID int) (ldapAr // Given the syslog resource, populate the required InterfaceParams // check for missing params func (m *M1000e) newInterfaceCfg(syslog *cfgresources.Syslog) InterfaceParams { - var syslogPort int if syslog.Server == "" { @@ -262,7 +257,6 @@ func (m *M1000e) newInterfaceCfg(syslog *cfgresources.Syslog) InterfaceParams { // Given the user resource, populate the required UserParams // check for missing params func (m *M1000e) newUserCfg(user *cfgresources.User, userID int) UserParams { - var cmcGroup, privilege int if user.Name == "" { diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/m1000e/m1000e.go b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/m1000e/m1000e.go index 82d9d3cc..b4c73c7e 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/m1000e/m1000e.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/m1000e/m1000e.go @@ -13,7 +13,6 @@ import ( "github.com/bmc-toolbox/bmclib/devices" "github.com/bmc-toolbox/bmclib/errors" - "github.com/bmc-toolbox/bmclib/internal" "github.com/bmc-toolbox/bmclib/internal/sshclient" "github.com/bmc-toolbox/bmclib/providers/dell" "github.com/go-logr/logr" @@ -30,7 +29,7 @@ var ( findRedundancyMode = regexp.MustCompile("selected=\"selected\">(.+)") ) -// M1000e holds the status and properties of a connection to a CMC device +// Holds the status and properties of a connection to a CMC device. type M1000e struct { ip string username string @@ -39,12 +38,12 @@ type M1000e struct { sshClient *sshclient.SSHClient cmcJSON *dell.CMC cmcWWN *dell.CMCWWN - SessionToken string //required to set config + SessionToken string // Required to set config! ctx context.Context log logr.Logger } -// New returns a connection to M1000e +// Returns a connection to an M1000e. func New(ctx context.Context, host string, username string, password string, log logr.Logger) (*M1000e, error) { sshClient, err := sshclient.New(host, username, password) if err != nil { @@ -100,7 +99,11 @@ func (m *M1000e) Name() (name string, err error) { // HardwareType returns just Model id string - m1000e func (m *M1000e) HardwareType() (model string) { - return BMCType + return "m1000e" +} + +func (m *M1000e) CheckFirmwareVersion() (version string, err error) { + return "", fmt.Errorf("not yet implemented") } // Model returns the full device model string @@ -345,12 +348,11 @@ func (m *M1000e) StorageBlades() (storageBlades []*devices.StorageBlade, err err storageBlade.PowerKw = float64(dellBlade.ActualPwrConsump) / 1000 temp, err := strconv.Atoi(dellBlade.BladeTemperature) if err != nil { - m.log.V(1).Info("Auditing blade", + m.log.V(1).Error(err, "Auditing blade", "operation", "connection", "ip", m.ip, "position", storageBlade.BladePosition, "type", "chassis", - "error", internal.ErrStringOrEmpty(err), ) continue } @@ -391,16 +393,17 @@ func (m *M1000e) Blades() (blades []*devices.Blade, err error) { blade.PowerKw = float64(dellBlade.ActualPwrConsump) / 1000 temp, err := strconv.Atoi(dellBlade.BladeTemperature) if err != nil { - m.log.V(1).Info(internal.ErrStringOrEmpty(err), + m.log.V(1).Error(err, "Blades(): Failed to get the blade temperature.", "operation", "connection", "ip", m.ip, "position", blade.BladePosition, "type", "chassis", ) continue - } else { - blade.TempC = temp } + + blade.TempC = temp + if dellBlade.BladeLogDescription == "No Errors" { blade.Status = "OK" } else { @@ -432,7 +435,7 @@ func (m *M1000e) Blades() (blades []*devices.Blade, err error) { if strings.HasPrefix(blade.BmcAddress, "[") { payload, err := m.get(fmt.Sprintf("blade_status?id=%d&cat=C10&tab=T41&id=P78", blade.BladePosition)) if err != nil { - m.log.V(1).Info(internal.ErrStringOrEmpty(err), + m.log.V(1).Error(err, "Blades(): Getting blade_status failed.", "operation", "connection", "ip", m.ip, "position", blade.BladePosition, diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/m1000e/model.go b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/m1000e/model.go index 9b7c8e76..edef748e 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/dell/m1000e/model.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/dell/m1000e/model.go @@ -9,89 +9,89 @@ package m1000e // 1 = Guest user - login access only // /cgi-bin/webcgi/ldaprg?index=1 type LdapArgParams struct { - SessionToken string `url:"ST2"` //ST2=2ee3449549f4f61b292e31c251da2b36 - PrivBitmap int `url:"PrivBitmap"` //PrivBitmap=4095 - Index int `url:"index"` //index=1 - GenLdapRoleDn string `url:"GENLDAP_ROLE_dn"` //GENLDAP_ROLE_dn=cn=bmcAdmins,ou=Group,dc=activehotels,dc=com - GenLdapRolePrivilege int `url:"GENLDAP_ROLE_privilege"` //GENLDAP_ROLE_privilege=4095 - Login bool `url:"login,int"` //login=1 - Cfg bool `url:"cfg,int"` //cfg=1 - Cfguser bool `url:"cfguser,int"` //cfguser=1 - Clearlog bool `url:"clearlog,int"` //clearlog=1 - Chassiscontrol bool `url:"chassiscontrol,int"` //chassiscontrol=1 - Superuser bool `url:"superuser,int"` //superuser=1 - Serveradmin bool `url:"serveradmin,int"` //serveradmin=1 - Testalert bool `url:"testalert,int"` //testalert=1 - Debug bool `url:"debug,int"` //debug=1 - Afabricadmin bool `url:"afabricadmin,int"` //afabricadmin=1 - Bfabricadmin bool `url:"bfabricadmin,int"` //bfabricadmin=1 + SessionToken string `url:"ST2"` // ST2=2ee3449549f4f61b292e31c251da2b36 + PrivBitmap int `url:"PrivBitmap"` // PrivBitmap=4095 + Index int `url:"index"` // index=1 + GenLdapRoleDn string `url:"GENLDAP_ROLE_dn"` // GENLDAP_ROLE_dn=cn=bmcAdmins,ou=Group,dc=activehotels,dc=com + GenLdapRolePrivilege int `url:"GENLDAP_ROLE_privilege"` // GENLDAP_ROLE_privilege=4095 + Login bool `url:"login,int"` // login=1 + Cfg bool `url:"cfg,int"` // cfg=1 + Cfguser bool `url:"cfguser,int"` // cfguser=1 + Clearlog bool `url:"clearlog,int"` // clearlog=1 + Chassiscontrol bool `url:"chassiscontrol,int"` // chassiscontrol=1 + Superuser bool `url:"superuser,int"` // superuser=1 + Serveradmin bool `url:"serveradmin,int"` // serveradmin=1 + Testalert bool `url:"testalert,int"` // testalert=1 + Debug bool `url:"debug,int"` // debug=1 + Afabricadmin bool `url:"afabricadmin,int"` // afabricadmin=1 + Bfabricadmin bool `url:"bfabricadmin,int"` // bfabricadmin=1 } // DirectoryServicesParams declares parameters for various LDAP configuration. // /cgi-bin/webcgi/dirsvcs type DirectoryServicesParams struct { SessionToken string `url:"ST2"` - SeviceSelected string `url:"service_selected"` //service_selected=ldap - CertType int `url:"certType"` //certType=5 - Action int `url:"action"` //action=1 - Choose int `url:"choose"` //choose=2 - GenLdapEnableCk bool `url:"GENLDAP_enable_ck,int"` //GENLDAP_enable_ck=1 - GenLdapEnable bool `url:"GENLDAP_enable,int"` //GENLDAP_enable=1 - GenLdapGroupAttributeIsDnCk bool `url:"GENLDAP_group_attribute_is_dn_ck,int"` //GENLDAP_group_attribute_is_dn_ck=1 - GenLdapGroupAttributeIsDn bool `url:"GENLDAP_group_attribute_is_dn,int"` //GENLDAP_group_attribute_is_dn=1 - GenLdapCertValidateEnableCk bool `url:"GENLDAP_cert_validate_enable_ck,int"` //GENLDAP_cert_validate_enable_ck=1 - GenLdapCertValidateEnable bool `url:"GENLDAP_cert_validate_enable,int"` //GENLDAP_cert_validate_enable=1 - GenLdapBindDn string `url:"GENLDAP_bind_dn"` //GENLDAP_bind_dn= - GenLdapBindPasswd string `url:"GENLDAP_bind_passwd"` //GENLDAP_bind_passwd=PASSWORD - GenLdapBindPasswdChanged bool `url:"GENLDAP_bind_passwd_changed,int"` //GENLDAP_bind_passwd_changed=0 - GenLdapBaseDn string `url:"GENLDAP_base_dn"` //GENLDAP_base_dn=ou=People,dc=foo,dc=com - GenLdapUserAttribute string `url:"GENLDAP_user_attribute"` //GENLDAP_user_attribute=uid - GenLdapGroupAttribute string `url:"GENLDAP_group_attribute"` //GENLDAP_group_attribute=memberUid - GenLdapSearchFilter string `url:"GENLDAP_search_filter"` //GENLDAP_search_filter= - GenLdapConnectTimeoutSeconds int `url:"GENLDAP_connect_timeout_seconds"` //GENLDAP_connect_timeout_seconds=30 - GenLdapSearchTimeoutSeconds int `url:"GENLDAP_search_timeout_seconds"` //GENLDAP_search_timeout_seconds=120 - LdapServers int `url:"ldapservers"` //ldapservers=1 - GenLdapServerAddr string `url:"GENLDAP_server_addr"` //GENLDAP_server_addr=ldaps.prod.foo.com - GenLdapServerPort int `url:"GENLDAP_server_port"` //GENLDAP_server_port=636 - GenLdapSrvLookupEnable bool `url:"GENLDAP_srvlookup_enable,int"` //GENLDAP_srvlookup_enable=0 - AdEnable bool `url:"AD_enable,int"` //AD_enable=0 - AdTfaSsoEnableBitmask1 int `url:"AD_tfa_sso_enable_bitmask.1"` //AD_tfa_sso_enable_bitmask.1=0 - AdTfaSsoEnableBitmask2 int `url:"AD_tfa_sso_enable_bitmask.2"` //AD_tfa_sso_enable_bitmask.2=0 - AdCertValidateEnableCk bool `url:"AD_cert_validate_enable_ck,int"` //AD_cert_validate_enable_ck=1 - AdCertValidateEnable bool `url:"AD_cert_validate_enable,int"` //AD_cert_validate_enable=1 - AdRootDomain string `url:"AD_root_domain"` //AD_root_domain= - AdTimeout int `url:"AD_timeout"` //AD_timeout=120 - AdFilterEnable bool `url:"AD_filter_enable,int"` //AD_filter_enable=0 - AdDcFilter string `url:"AD_dc_filter"` //AD_dc_filter= - AdGcFilter string `url:"AD_gc_filter"` //AD_gc_filter= - AdSchemaExt int `url:"AD_schema_ext"` //AD_schema_ext=1 - RoleGroupFlag int `url:"RoleGroupFlag"` //RoleGroupFlag=0 - RoleGroupIndex string `url:"RoleGroupIndex"` //RoleGroupIndex= - AdCmcName string `url:"AD_cmc_name"` //AD_cmc_name= - AdCmcdomain string `url:"AD_cmc_domain"` //AD_cmc_domain= + SeviceSelected string `url:"service_selected"` // service_selected=ldap + CertType int `url:"certType"` // certType=5 + Action int `url:"action"` // action=1 + Choose int `url:"choose"` // choose=2 + GenLdapEnableCk bool `url:"GENLDAP_enable_ck,int"` // GENLDAP_enable_ck=1 + GenLdapEnable bool `url:"GENLDAP_enable,int"` // GENLDAP_enable=1 + GenLdapGroupAttributeIsDnCk bool `url:"GENLDAP_group_attribute_is_dn_ck,int"` // GENLDAP_group_attribute_is_dn_ck=1 + GenLdapGroupAttributeIsDn bool `url:"GENLDAP_group_attribute_is_dn,int"` // GENLDAP_group_attribute_is_dn=1 + GenLdapCertValidateEnableCk bool `url:"GENLDAP_cert_validate_enable_ck,int"` // GENLDAP_cert_validate_enable_ck=1 + GenLdapCertValidateEnable bool `url:"GENLDAP_cert_validate_enable,int"` // GENLDAP_cert_validate_enable=1 + GenLdapBindDn string `url:"GENLDAP_bind_dn"` // GENLDAP_bind_dn= + GenLdapBindPasswd string `url:"GENLDAP_bind_passwd"` // GENLDAP_bind_passwd=PASSWORD + GenLdapBindPasswdChanged bool `url:"GENLDAP_bind_passwd_changed,int"` // GENLDAP_bind_passwd_changed=0 + GenLdapBaseDn string `url:"GENLDAP_base_dn"` // GENLDAP_base_dn=ou=People,dc=foo,dc=com + GenLdapUserAttribute string `url:"GENLDAP_user_attribute"` // GENLDAP_user_attribute=uid + GenLdapGroupAttribute string `url:"GENLDAP_group_attribute"` // GENLDAP_group_attribute=memberUid + GenLdapSearchFilter string `url:"GENLDAP_search_filter"` // GENLDAP_search_filter= + GenLdapConnectTimeoutSeconds int `url:"GENLDAP_connect_timeout_seconds"` // GENLDAP_connect_timeout_seconds=30 + GenLdapSearchTimeoutSeconds int `url:"GENLDAP_search_timeout_seconds"` // GENLDAP_search_timeout_seconds=120 + LdapServers int `url:"ldapservers"` // ldapservers=1 + GenLdapServerAddr string `url:"GENLDAP_server_addr"` // GENLDAP_server_addr=ldaps.prod.foo.com + GenLdapServerPort int `url:"GENLDAP_server_port"` // GENLDAP_server_port=636 + GenLdapSrvLookupEnable bool `url:"GENLDAP_srvlookup_enable,int"` // GENLDAP_srvlookup_enable=0 + AdEnable bool `url:"AD_enable,int"` // AD_enable=0 + AdTfaSsoEnableBitmask1 int `url:"AD_tfa_sso_enable_bitmask.1"` // AD_tfa_sso_enable_bitmask.1=0 + AdTfaSsoEnableBitmask2 int `url:"AD_tfa_sso_enable_bitmask.2"` // AD_tfa_sso_enable_bitmask.2=0 + AdCertValidateEnableCk bool `url:"AD_cert_validate_enable_ck,int"` // AD_cert_validate_enable_ck=1 + AdCertValidateEnable bool `url:"AD_cert_validate_enable,int"` // AD_cert_validate_enable=1 + AdRootDomain string `url:"AD_root_domain"` // AD_root_domain= + AdTimeout int `url:"AD_timeout"` // AD_timeout=120 + AdFilterEnable bool `url:"AD_filter_enable,int"` // AD_filter_enable=0 + AdDcFilter string `url:"AD_dc_filter"` // AD_dc_filter= + AdGcFilter string `url:"AD_gc_filter"` // AD_gc_filter= + AdSchemaExt int `url:"AD_schema_ext"` // AD_schema_ext=1 + RoleGroupFlag int `url:"RoleGroupFlag"` // RoleGroupFlag=0 + RoleGroupIndex string `url:"RoleGroupIndex"` // RoleGroupIndex= + AdCmcName string `url:"AD_cmc_name"` // AD_cmc_name= + AdCmcdomain string `url:"AD_cmc_domain"` // AD_cmc_domain= } // LoginSecurityParams declares payload to apply Login related security params. // /cgi-bin/webcgi/loginSecurity type LoginSecurityParams struct { - SessionToken string `url:"ST2"` //7bdaaa73307ebb471d0e71a9cecc44fb most likely the auth token - EnforcedIPBlockEnable bool `url:"ENFORCED_IPBLOCK_enable,int"` //1 - EnforcedIPBlockFailcount int `url:"ENFORCED_IPBLOCK_failcount"` //5 - EnforcedIPBlockFailwindow int `url:"ENFORCED_IPBLOCK_failwindow"` //60 - EnforcedIPBlockPenaltyTime int `url:"ENFORCED_IPBLOCK_penaltytime"` //300 + SessionToken string `url:"ST2"` // 7bdaaa73307ebb471d0e71a9cecc44fb most likely the auth token + EnforcedIPBlockEnable bool `url:"ENFORCED_IPBLOCK_enable,int"` // 1 + EnforcedIPBlockFailcount int `url:"ENFORCED_IPBLOCK_failcount"` // 5 + EnforcedIPBlockFailwindow int `url:"ENFORCED_IPBLOCK_failwindow"` // 60 + EnforcedIPBlockPenaltyTime int `url:"ENFORCED_IPBLOCK_penaltytime"` // 300 } // DatetimeParams declares payload to apply time params. // cgi-bin/webcgi/datetime type DatetimeParams struct { - SessionToken string `url:"ST2"` //ST2=ba9a6bbf88764c829ca4f49146fd4817 - NtpEnable bool `url:"NTP_enable,int"` //NTP_enable=1 - NtpServer1 string `url:"NTP_server1"` //NTP_server1=ntp0.example.com - NtpServer2 string `url:"NTP_server2"` //NTP_server2=ntp2.example.com - NtpServer3 string `url:"NTP_server3"` //NTP_server3=ntp3.example.com - DateTimeChanged bool `url:"datetimeChanged,int"` //datetimeChanged=0 - CmcTimeTimezoneString string `url:"CMC_TIME_timezone_string"` //CMC_TIME_timezone_string=CET - TzChanged bool `url:"tzChanged,int"` //tzChanged=1 + SessionToken string `url:"ST2"` // ST2=ba9a6bbf88764c829ca4f49146fd4817 + NtpEnable bool `url:"NTP_enable,int"` // NTP_enable=1 + NtpServer1 string `url:"NTP_server1"` // NTP_server1=ntp0.example.com + NtpServer2 string `url:"NTP_server2"` // NTP_server2=ntp2.example.com + NtpServer3 string `url:"NTP_server3"` // NTP_server3=ntp3.example.com + DateTimeChanged bool `url:"datetimeChanged,int"` // datetimeChanged=0 + CmcTimeTimezoneString string `url:"CMC_TIME_timezone_string"` // CMC_TIME_timezone_string=CET + TzChanged bool `url:"tzChanged,int"` // tzChanged=1 } // UserParams declares payload to configure user accounts. @@ -103,66 +103,66 @@ type DatetimeParams struct { // 1 = Guest user - login access only // Endpoint /webcgi/user?id=1 type UserParams struct { - SessionToken string `url:"ST2"` //ST2=ba9a6bbf88764c829ca4f49146fd4817 - Privilege int `url:"Privilege"` //Privilege=4095 - UserID int `url:"UserID"` //UserID=1 - EnableUser bool `url:"EnableUser,int"` //EnableUser=1 - UserName string `url:"UserName"` //UserName=Test - ChangePassword bool `url:"ChangePassword,int"` //ChangePassword=1 - Password string `url:"Password"` //Password=foobar - ConfirmPassword string `url:"ConfirmPassword"` //ConfirmPassword=foobar - CmcGroup int `url:"CMC_GROUP"` //CMC_GROUP=4095 - Login bool `url:"login,int"` //login=1 - Cfg bool `url:"cfg,int"` //cfg=1 - CfgUser bool `url:"cfguser,int"` //cfguser=1 - ClearLog bool `url:"clearlog,int"` //clearlog=1 - ChassisControl bool `url:"chassiscontrol,int"` //chassiscontrol=1 - SuperUser bool `url:"superuser,int"` //superuser=1 - ServerAdmin bool `url:"serveradmin,int"` //serveradmin=1 - TestAlert bool `url:"testalert,int"` //testalert=1 - Debug bool `url:"debug,int"` //debug=1 - AFabricAdmin bool `url:"afabricadmin,int"` //afabricadmin=1 - BFabricAdmin bool `url:"bfabricadmin,int"` //bfabricadmin=1 - CFabricAcminc bool `url:"cfabricadmin,int"` //cfabricadmin=1 + SessionToken string `url:"ST2"` // ST2=ba9a6bbf88764c829ca4f49146fd4817 + Privilege int `url:"Privilege"` // Privilege=4095 + UserID int `url:"UserID"` // UserID=1 + EnableUser bool `url:"EnableUser,int"` // EnableUser=1 + UserName string `url:"UserName"` // UserName=Test + ChangePassword bool `url:"ChangePassword,int"` // ChangePassword=1 + Password string `url:"Password"` // Password=foobar + ConfirmPassword string `url:"ConfirmPassword"` // ConfirmPassword=foobar + CmcGroup int `url:"CMC_GROUP"` // CMC_GROUP=4095 + Login bool `url:"login,int"` // login=1 + Cfg bool `url:"cfg,int"` // cfg=1 + CfgUser bool `url:"cfguser,int"` // cfguser=1 + ClearLog bool `url:"clearlog,int"` // clearlog=1 + ChassisControl bool `url:"chassiscontrol,int"` // chassiscontrol=1 + SuperUser bool `url:"superuser,int"` // superuser=1 + ServerAdmin bool `url:"serveradmin,int"` // serveradmin=1 + TestAlert bool `url:"testalert,int"` // testalert=1 + Debug bool `url:"debug,int"` // debug=1 + AFabricAdmin bool `url:"afabricadmin,int"` // afabricadmin=1 + BFabricAdmin bool `url:"bfabricadmin,int"` // bfabricadmin=1 + CFabricAcminc bool `url:"cfabricadmin,int"` // cfabricadmin=1 } // InterfaceParams declares payload to configure interface options. // /cgi-bin/webcgi/interfaces type InterfaceParams struct { - SessionToken string `url:"ST2"` //ST2=2754be61766abf5808085b3f2dd7bd94 - SerialEnable bool `url:"SERIAL_enable,int"` //SERIAL_enable=1 - SerialRedirect bool `url:"SERIAL_redirect_enable,int"` //SERIAL_redirect_enable=1 - SerialTimeout int `url:"SERIAL_timeout"` //SERIAL_timeout=1800 - SerialBaudrate int `url:"SERIAL_baudrate"` //SERIAL_baudrate=115200 - SerialConsoleNoAuth bool `url:"SERIAL_console_no_auth,int"` //SERIAL_console_no_auth=0 - SerialQuitKey string `url:"SERIAL_quit_key"` //SERIAL_quit_key=^\ - SerialHistoryBufSize int `url:"SERIAL_history_buf_size"` //SERIAL_history_buf_size=8192 - SerialLoginCommand string `url:"SERIAL_login_command"` //SERIAL_login_command= - WebserverEnable bool `url:"WEBSERVER_enable,int"` //WEBSERVER_enable=1 - WebserverMaxSessions int `url:"WEBSERVER_maxsessions"` //WEBSERVER_maxsessions=4 - WebserverTimeout int `url:"WEBSERVER_timeout"` //WEBSERVER_timeout=1800 - WebserverHTTPPort int `url:"WEBSERVER_http_port"` //WEBSERVER_http_port=80 - WebserverHTTPSPort int `url:"WEBSERVER_https_port"` //WEBSERVER_https_port=443 - SSHEnable bool `url:"SSH_enable,int"` //SSH_enable=1 - SSHMaxSessions int `url:"SSH_maxsessions"` //SSH_maxsessions=4 - SSHTimeout int `url:"SSH_timeout"` //SSH_timeout=1800 - SSHPort int `url:"SSH_port"` //SSH_port=22 - TelnetEnable bool `url:"TELNET_enable,int"` //TELNET_enable=1 - TelnetMaxSessions int `url:"TELNET_maxsessions"` //TELNET_maxsessions=4 - TelnetTimeout int `url:"TELNET_timeout"` //TELNET_timeout=1800 - TelnetPort int `url:"TELNET_port"` //TELNET_port=23 - RacadmEnable bool `url:"RACADM_enable,int"` //RACADM_enable=1 - RacadmMaxSessions int `url:"RACADM_maxsessions"` //RACADM_maxsessions=4 - RacadmTimeout int `url:"RACADM_timeout"` //RACADM_timeout=60 - SnmpEnable bool `url:"SNMP_enable,int"` //SNMP_enable=1 - SnmpCommunityNameGet string `url:"SNMP_COMMUNITYNAME_get"` //SNMP_COMMUNITYNAME_get=public - SnmpProtocol int `url:"SNMP_Protocol"` //SNMP_Protocol=0 - SnmpDiscoveryPortSet int `url:"SNMP_DiscoveryPort_set"` //SNMP_DiscoveryPort_set=161 - ChassisLoggingRemoteSyslogEnable bool `url:"CHASSIS_LOGGING_remote_syslog_enable,int"` //CHASSIS_LOGGING_remote_syslog_enable=1 - ChassisLoggingRemoteSyslogHost1 string `url:"CHASSIS_LOGGING_remote_syslog_host_1"` //CHASSIS_LOGGING_remote_syslog_host_1=machine.example.com - ChassisLoggingRemoteSyslogHost2 string `url:"CHASSIS_LOGGING_remote_syslog_host_2"` //CHASSIS_LOGGING_remote_syslog_host_2= - ChassisLoggingRemoteSyslogHost3 string `url:"CHASSIS_LOGGING_remote_syslog_host_3"` //CHASSIS_LOGGING_remote_syslog_host_3= - ChassisLoggingRemoteSyslogPort int `url:"CHASSIS_LOGGING_remote_syslog_port"` //CHASSIS_LOGGING_remote_syslog_port=514 + SessionToken string `url:"ST2"` // ST2=2754be61766abf5808085b3f2dd7bd94 + SerialEnable bool `url:"SERIAL_enable,int"` // SERIAL_enable=1 + SerialRedirect bool `url:"SERIAL_redirect_enable,int"` // SERIAL_redirect_enable=1 + SerialTimeout int `url:"SERIAL_timeout"` // SERIAL_timeout=1800 + SerialBaudrate int `url:"SERIAL_baudrate"` // SERIAL_baudrate=115200 + SerialConsoleNoAuth bool `url:"SERIAL_console_no_auth,int"` // SERIAL_console_no_auth=0 + SerialQuitKey string `url:"SERIAL_quit_key"` // SERIAL_quit_key=^\ + SerialHistoryBufSize int `url:"SERIAL_history_buf_size"` // SERIAL_history_buf_size=8192 + SerialLoginCommand string `url:"SERIAL_login_command"` // SERIAL_login_command= + WebserverEnable bool `url:"WEBSERVER_enable,int"` // WEBSERVER_enable=1 + WebserverMaxSessions int `url:"WEBSERVER_maxsessions"` // WEBSERVER_maxsessions=4 + WebserverTimeout int `url:"WEBSERVER_timeout"` // WEBSERVER_timeout=1800 + WebserverHTTPPort int `url:"WEBSERVER_http_port"` // WEBSERVER_http_port=80 + WebserverHTTPSPort int `url:"WEBSERVER_https_port"` // WEBSERVER_https_port=443 + SSHEnable bool `url:"SSH_enable,int"` // SSH_enable=1 + SSHMaxSessions int `url:"SSH_maxsessions"` // SSH_maxsessions=4 + SSHTimeout int `url:"SSH_timeout"` // SSH_timeout=1800 + SSHPort int `url:"SSH_port"` // SSH_port=22 + TelnetEnable bool `url:"TELNET_enable,int"` // TELNET_enable=1 + TelnetMaxSessions int `url:"TELNET_maxsessions"` // TELNET_maxsessions=4 + TelnetTimeout int `url:"TELNET_timeout"` // TELNET_timeout=1800 + TelnetPort int `url:"TELNET_port"` // TELNET_port=23 + RacadmEnable bool `url:"RACADM_enable,int"` // RACADM_enable=1 + RacadmMaxSessions int `url:"RACADM_maxsessions"` // RACADM_maxsessions=4 + RacadmTimeout int `url:"RACADM_timeout"` // RACADM_timeout=60 + SnmpEnable bool `url:"SNMP_enable,int"` // SNMP_enable=1 + SnmpCommunityNameGet string `url:"SNMP_COMMUNITYNAME_get"` // SNMP_COMMUNITYNAME_get=public + SnmpProtocol int `url:"SNMP_Protocol"` // SNMP_Protocol=0 + SnmpDiscoveryPortSet int `url:"SNMP_DiscoveryPort_set"` // SNMP_DiscoveryPort_set=161 + ChassisLoggingRemoteSyslogEnable bool `url:"CHASSIS_LOGGING_remote_syslog_enable,int"` // CHASSIS_LOGGING_remote_syslog_enable=1 + ChassisLoggingRemoteSyslogHost1 string `url:"CHASSIS_LOGGING_remote_syslog_host_1"` // CHASSIS_LOGGING_remote_syslog_host_1=machine.example.com + ChassisLoggingRemoteSyslogHost2 string `url:"CHASSIS_LOGGING_remote_syslog_host_2"` // CHASSIS_LOGGING_remote_syslog_host_2= + ChassisLoggingRemoteSyslogHost3 string `url:"CHASSIS_LOGGING_remote_syslog_host_3"` // CHASSIS_LOGGING_remote_syslog_host_3= + ChassisLoggingRemoteSyslogPort int `url:"CHASSIS_LOGGING_remote_syslog_port"` // CHASSIS_LOGGING_remote_syslog_port=514 } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/dummy/ibmc/configure.go b/vendor/github.com/bmc-toolbox/bmclib/providers/dummy/ibmc/configure.go index e1dea38b..248792a4 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/dummy/ibmc/configure.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/dummy/ibmc/configure.go @@ -44,8 +44,8 @@ func (i *Ibmc) Ldap(cfg *cfgresources.Ldap) error { return nil } -// LdapGroup method implements the Configure interface -func (i *Ibmc) LdapGroup(cfgGroup []*cfgresources.LdapGroup, cfgLdap *cfgresources.Ldap) error { +// LdapGroups method implements the Configure interface +func (i *Ibmc) LdapGroups(cfgGroups []*cfgresources.LdapGroup, cfgLdap *cfgresources.Ldap) error { return nil } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/dummy/ibmc/ibmc.go b/vendor/github.com/bmc-toolbox/bmclib/providers/dummy/ibmc/ibmc.go index 9225b033..b73dce62 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/dummy/ibmc/ibmc.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/dummy/ibmc/ibmc.go @@ -2,6 +2,7 @@ package ibmc import ( "context" + "fmt" "github.com/bmc-toolbox/bmclib/cfgresources" "github.com/bmc-toolbox/bmclib/devices" @@ -41,7 +42,7 @@ func (i *Ibmc) BiosVersion() (string, error) { // HardwareType implements the Bmc interface func (i *Ibmc) HardwareType() string { - return "" + return "ibmc" } // Version implements the Bmc interface @@ -156,7 +157,7 @@ func (i *Ibmc) TempC() (int, error) { // Vendor implements the Bmc interface func (i *Ibmc) Vendor() string { - return "" + return "Ibmc" } // Screenshot implements the Bmc interface @@ -179,8 +180,8 @@ func (i *Ibmc) Slot() (int, error) { } // UpdateFirmware implements the Bmc inteface -func (i *Ibmc) UpdateFirmware(string, string) (b bool, e error) { - return b, e +func (i *Ibmc) UpdateFirmware(string, string) (bool, string, error) { + return false, "Not yet implemented", fmt.Errorf("not yet implemented") } // IsOn implements the Bmc interface @@ -202,3 +203,7 @@ func (i *Ibmc) GetBMCVersion(ctx context.Context) (string, error) { func (i *Ibmc) FirmwareUpdateBMC(ctx context.Context, filePath string) error { return errors.ErrNotImplemented } + +func (i *Ibmc) CheckFirmwareVersion() (version string, err error) { + return "", fmt.Errorf("not yet implemented") +} diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/c7000/actions.go b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/c7000/actions.go index 90183672..28900efa 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/c7000/actions.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/c7000/actions.go @@ -167,7 +167,7 @@ func (c *C7000) PxeOnceBlade(position int) (bool, error) { return false, fmt.Errorf(output) } -// SetDynamicPower configure the dynamic power behaviour +// Configures dynamic power behavior. func (c *C7000) SetDynamicPower(enable bool) (bool, error) { var state string if enable { @@ -190,18 +190,22 @@ func (c *C7000) SetDynamicPower(enable bool) (bool, error) { } // UpdateFirmware updates the chassis firmware -func (c *C7000) UpdateFirmware(source, file string) (bool, error) { +func (c *C7000) UpdateFirmware(source, file string) (bool, string, error) { cmd := fmt.Sprintf("update image %s/%s", source, file) output, err := c.sshClient.Run(cmd) if err != nil { - return false, fmt.Errorf("output: %q: %w", output, err) + return false, "", fmt.Errorf("output: %q: %w", output, err) } if strings.Contains(output, "Flashing Active Onboard Administrator") { - return true, nil + return true, output, nil } - return false, fmt.Errorf(output) + return false, output, fmt.Errorf(output) +} + +func (c *C7000) CheckFirmwareVersion() (version string, err error) { + return "", fmt.Errorf("not yet implemented") } // ModBladeBmcUser modfies BMC Admin user account password through the chassis, @@ -227,9 +231,9 @@ end_marker` return fmt.Errorf("output: %q: %w", output, err) } - //since there are multiple blades and this command - //could fail on any of the blades because they are un responsive - //we only validate the command actually ran and not if it succeeded on each blade. + // Since there are multiple blades and this command could fail on any of the blades because + // of unresponsiveness, we only check that the command actually ran and not if it has + // succeeded on each blade. if !strings.Contains(output, "END RIBCL RESULTS") { return fmt.Errorf(output) } @@ -267,9 +271,9 @@ end_marker` return fmt.Errorf("output: %q: %w", output, err) } - //since there are multiple blades and this command - //could fail on any of the blades because they are un responsive - //we only validate the command actually ran and not if it succeeded on each blade. + // Since there are multiple blades and this command could fail on any of the blades because + // of unresponsiveness, we only check that the command actually ran and not if it has + // succeeded on each blade. if !strings.Contains(output, "END RIBCL RESULTS") { return fmt.Errorf(output) } @@ -296,9 +300,9 @@ end_marker` return fmt.Errorf("output: %q: %w", output, err) } - //since there are multiple blades and this command - //could fail on any of the blades because they are un responsive - //we only validate the command actually ran and not if it succeeded on each blade. + // Since there are multiple blades and this command could fail on any of the blades because + // of unresponsiveness, we only check that the command actually ran and not if it has + // succeeded on each blade. if !strings.Contains(output, "END RIBCL RESULTS") { return fmt.Errorf(output) } @@ -312,7 +316,7 @@ func (c *C7000) SetFlexAddressState(_ int, _ bool) (bool, error) { return false, errors.ErrNotImplemented } -// SetIpmiOverLan Enable/Disable IPMI over lan parameter per blade in chassis +// Enable/Disable the IpmiOverLan parameter per blade in the chassis. func (c *C7000) SetIpmiOverLan(_ int, _ bool) (bool, error) { return false, errors.ErrNotImplemented } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/c7000/c7000.go b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/c7000/c7000.go index 14598432..623183ac 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/c7000/c7000.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/c7000/c7000.go @@ -26,7 +26,7 @@ type C7000 struct { ip string username string password string - XMLToken string //required to send SOAP XML payloads + XMLToken string // Required to send SOAP XML payloads. httpClient *http.Client sshClient *sshclient.SSHClient Rimp *hp.Rimp diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/c7000/configure.go b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/c7000/configure.go index 5687b239..c907efa3 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/c7000/configure.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/c7000/configure.go @@ -3,10 +3,10 @@ package c7000 import ( "crypto/x509" "errors" + "fmt" "github.com/bmc-toolbox/bmclib/cfgresources" "github.com/bmc-toolbox/bmclib/devices" - "github.com/bmc-toolbox/bmclib/internal" ) // This ensures the compiler errors if this type is missing @@ -42,7 +42,6 @@ func (c *C7000) ResourcesSetup() []string { // Return bool value if the role is valid. func (c *C7000) isRoleValid(role string) bool { - validRoles := []string{"admin", "user"} for _, v := range validRoles { if role == v { @@ -60,35 +59,33 @@ func (c *C7000) ApplyCfg(config *cfgresources.ResourcesConfig) (err error) { // Power implemented the Configure interface func (c *C7000) Power(cfg *cfgresources.Power) (err error) { - return err + return nil } -// Ldap applies LDAP configuration params. -// Ldap implements the Configure interface. -//1. apply ldap group params -//2. enable ldap auth -//3. apply ldap server params +// Applies LDAP configuration params. +// Implements the Configure interface. +// 1. Apply LDAP group params +// 2. Enable LDAP auth +// 3. Apply LDAP server params func (c *C7000) Ldap(cfg *cfgresources.Ldap) (err error) { err = c.applysetLdapInfo4(cfg) if err != nil { - c.log.V(1).Info("applyLdapParams returned error.", + c.log.V(1).Error(err, "applyLdapParams returned error.", "step", "applyLdapParams", "resource", "Ldap", "IP", c.ip, - "Model", c.HardwareType(), - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", c.HardwareType(), ) return err } err = c.applyEnableLdapAuth(cfg.Enable) if err != nil { - c.log.V(1).Info("applyLdapParams returned error.", + c.log.V(1).Error(err, "applyLdapParams returned error.", "step", "applyLdapParams", "resource", "Ldap", "IP", c.ip, - "Model", c.HardwareType(), - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", c.HardwareType(), ) return err } @@ -118,7 +115,7 @@ func (c *C7000) applysetLdapInfo4(cfg *cfgresources.Ldap) (err error) { if cfg.Server == "" { c.log.V(1).Info("Ldap resource parameter Server required but not declared.", "step", "applysetLdapInfo4", - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), ) return err } @@ -126,7 +123,7 @@ func (c *C7000) applysetLdapInfo4(cfg *cfgresources.Ldap) (err error) { if cfg.Port == 0 { c.log.V(1).Info("Ldap resource parameter Port required but not declared.", "step", "applysetLdapInfo4", - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), ) return err } @@ -157,21 +154,24 @@ func (c *C7000) applysetLdapInfo4(cfg *cfgresources.Ldap) (err error) { statusCode, _, err := c.postXML(payload) if statusCode != 200 || err != nil { - c.log.V(1).Info("Ldap applysetLdapInfo4 apply request returned non 200.", + if err == nil { + err = fmt.Errorf("LDAP applysetLdapInfo4 request failed.") + } + + c.log.V(1).Error(err, "applysetLdapInfo4(): POST request failed.", "step", "applysetLdapInfo4", "IP", c.ip, - "Model", c.HardwareType(), - "statusCode", statusCode, - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", c.HardwareType(), + "StatusCode", statusCode, ) return err } - c.log.V(1).Info("Ldap Server parameters applied.", + c.log.V(1).Info("LDAP Server parameters applied.", "IP", c.ip, - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), ) - return err + return nil } // @@ -179,56 +179,55 @@ func (c *C7000) applysetLdapInfo4(cfg *cfgresources.Ldap) (err error) { // true // func (c *C7000) applyEnableLdapAuth(enable bool) (err error) { - payload := enableLdapAuthentication{EnableLdap: enable, EnableLocalUsers: true} statusCode, _, err := c.postXML(payload) if statusCode != 200 || err != nil { - c.log.V(1).Info("Ldap applyEnableLdapAuth apply request returned non 200.", + if err == nil { + err = fmt.Errorf("applyEnableLdapAuth() POST request returned %d.", statusCode) + } + + c.log.V(1).Error(err, "applyEnableLdapAuth(): POST request failed.", "step", "applyEnableLdapAuth", "IP", c.ip, - "Model", c.HardwareType(), - "statusCode", statusCode, - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", c.HardwareType(), + "StatusCode", statusCode, ) return err } - c.log.V(1).Info("Ldap Enabled.", + c.log.V(1).Info("LDAP Enabled.", "IP", c.ip, - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), ) - return err + return nil } -// LdapGroup applies LDAP Group/Role related configuration -// LdapGroup implements the Configure interface. +// LdapGroups applies LDAP Group/Role related configuration +// LdapGroups implements the Configure interface. // Actions carried out in order // 1. addLdapGroup // 2. setLdapGroupBayACL // 3. addLdapGroupBayAccess (done) -func (c *C7000) LdapGroup(cfg []*cfgresources.LdapGroup, cfgLdap *cfgresources.Ldap) (err error) { - - for _, group := range cfg { - +func (c *C7000) LdapGroups(cfgGroups []*cfgresources.LdapGroup, cfgLdap *cfgresources.Ldap) (err error) { + for _, group := range cfgGroups { if group.Group == "" { c.log.V(1).Info("Ldap resource parameter Group required but not declared.", "step", "applyLdapGroupParams", - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), "Ldap role", group.Role, ) return } - //0. removeLdapGroup + // 0. removeLdapGroup if !group.Enable { err = c.applyRemoveLdapGroup(group.Group) if err != nil { - c.log.V(1).Info("Remove Ldap Group returned error.", + c.log.V(1).Error(err, "Remove Ldap Group returned error.", "step", "applyRemoveLdapGroup", "resource", "Ldap", "IP", c.ip, - "Model", c.HardwareType(), - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", c.HardwareType(), ) return } @@ -240,46 +239,43 @@ func (c *C7000) LdapGroup(cfg []*cfgresources.LdapGroup, cfgLdap *cfgresources.L c.log.V(1).Info("Ldap resource Role must be a valid role: admin OR user.", "step", "applyLdapGroupParams", "role", group.Role, - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), ) return } - //1. addLdapGroup + // 1. addLdapGroup err = c.applyAddLdapGroup(group.Group) if err != nil { - c.log.V(1).Info("addLdapGroup returned error.", + c.log.V(1).Error(err, "addLdapGroup returned error.", "step", "applyAddLdapGroup", "resource", "Ldap", "IP", c.ip, - "Model", c.HardwareType(), - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", c.HardwareType(), ) return } - //2. setLdapGroupBayACL + // 2. setLdapGroupBayACL err = c.applyLdapGroupBayACL(group.Role, group.Group) if err != nil { - c.log.V(1).Info("addLdapGroup returned error.", + c.log.V(1).Error(err, "addLdapGroup returned error.", "step", "setLdapGroupBayACL", "resource", "Ldap", "IP", c.ip, - "Model", c.HardwareType(), - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", c.HardwareType(), ) return } - //3. applyAddLdapGroupBayAccess + // 3. applyAddLdapGroupBayAccess err = c.applyAddLdapGroupBayAccess(group.Group) if err != nil { - c.log.V(1).Info("addLdapGroup returned error.", + c.log.V(1).Error(err, "addLdapGroup returned error.", "step", "applyAddLdapGroupBayAccess", "resource", "Ldap", "IP", c.ip, - "Model", c.HardwareType(), - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", c.HardwareType(), ) return } @@ -287,7 +283,7 @@ func (c *C7000) LdapGroup(cfg []*cfgresources.LdapGroup, cfgLdap *cfgresources.L c.log.V(1).Info("Ldap config applied", "IP", c.ip, - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), ) return } @@ -297,15 +293,14 @@ func (c *C7000) LdapGroup(cfg []*cfgresources.LdapGroup, cfgLdap *cfgresources.L // bmcAdmins // func (c *C7000) applyRemoveLdapGroup(group string) (err error) { - payload := removeLdapGroup{LdapGroup: ldapGroup{Text: group}} statusCode, _, err := c.postXML(payload) if statusCode == 200 || statusCode == 500 { // 500 indicates the group exists. c.log.V(1).Info("Ldap applyRemoveLdapGroup applied.", "step", "applyRemoveLdapGroup", "IP", c.ip, - "Model", c.HardwareType(), - "statusCode", statusCode, + "HardwareType", c.HardwareType(), + "StatusCode", statusCode, ) return nil } @@ -314,15 +309,15 @@ func (c *C7000) applyRemoveLdapGroup(group string) (err error) { c.log.V(1).Info("Ldap applyRemoveLdapGroup request returned non 200.", "step", "applyRemoveLdapGroup", "IP", c.ip, - "Model", c.HardwareType(), - "statusCode", statusCode, + "HardwareType", c.HardwareType(), + "StatusCode", statusCode, ) return err } c.log.V(1).Info("Ldap group removed.", "IP", c.ip, - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), "Group", group, ) return nil @@ -333,15 +328,14 @@ func (c *C7000) applyRemoveLdapGroup(group string) (err error) { // bmcAdmins // func (c *C7000) applyAddLdapGroup(group string) (err error) { - payload := addLdapGroup{LdapGroup: ldapGroup{Text: group}} statusCode, _, err := c.postXML(payload) if statusCode == 200 || statusCode == 500 { // 500 indicates the group exists. c.log.V(1).Info("Ldap applyAddLdapGroup applied.", "step", "applyAddLdapGroup", "IP", c.ip, - "Model", c.HardwareType(), - "statusCode", statusCode, + "HardwareType", c.HardwareType(), + "StatusCode", statusCode, ) return nil } @@ -350,15 +344,15 @@ func (c *C7000) applyAddLdapGroup(group string) (err error) { c.log.V(1).Info("Ldap applyAddLdapGroup request returned non 200.", "step", "applyAddLdapGroup", "IP", c.ip, - "Model", c.HardwareType(), - "statusCode", statusCode, + "HardwareType", c.HardwareType(), + "StatusCode", statusCode, ) return err } c.log.V(1).Info("Ldap group added.", "IP", c.ip, - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), ) return nil } @@ -369,35 +363,34 @@ func (c *C7000) applyAddLdapGroup(group string) (err error) { // ADMINISTRATOR // func (c *C7000) applyLdapGroupBayACL(role string, group string) (err error) { - - var userACL string - + userACL := "USER" if role == "admin" { userACL = "ADMINISTRATOR" - } else { - userACL = "USER" } payload := setLdapGroupBayACL{LdapGroup: ldapGroup{Text: group}, ACL: ACL{Text: userACL}} statusCode, _, err := c.postXML(payload) if statusCode != 200 || err != nil { - c.log.V(1).Info("LDAP applyLdapGroupBayACL request returned non 200.", + if err == nil { + err = fmt.Errorf("XML POST failed with status code %d.", statusCode) + } + + c.log.V(1).Error(err, "applyLdapGroupBayACL(): POST request failed.", "step", "applyLdapGroupBayACL", "IP", c.ip, - "Model", c.HardwareType(), - "statusCode", statusCode, - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", c.HardwareType(), + "StatusCode", statusCode, ) return err } - c.log.V(1).Info("Ldap group ACL added.", + c.log.V(1).Info("LDAP group ACL added.", "IP", c.ip, - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), "Role", role, "Group", group, ) - return err + return nil } // Set blade, interconnect access @@ -431,9 +424,7 @@ func (c *C7000) applyLdapGroupBayACL(role string, group string) (err error) { // func (c *C7000) applyAddLdapGroupBayAccess(group string) (err error) { - //group = "bmcAdmins" - - //setup blade bays payload + // setup blade bays payload bladebays := bladeBays{} for b := 1; b <= 16; b++ { baynumber := bayNumber{Text: b} @@ -442,7 +433,7 @@ func (c *C7000) applyAddLdapGroupBayAccess(group string) (err error) { bladebays.Blade = append(bladebays.Blade, blade) } - //setup interconnect tray bays payload + // setup interconnect tray bays payload interconnecttraybays := interconnectTrayBays{} for t := 1; t <= 8; t++ { access := access{Text: true} @@ -451,7 +442,7 @@ func (c *C7000) applyAddLdapGroupBayAccess(group string) (err error) { interconnecttraybays.InterconnectTray = append(interconnecttraybays.InterconnectTray, interconnecttray) } - //setup the bays payload + // setup the bays payload bayz := bays{ Hpoa: "hpoa.xsd", OaAccess: oaAccess{Text: true}, @@ -466,35 +457,37 @@ func (c *C7000) applyAddLdapGroupBayAccess(group string) (err error) { statusCode, _, err := c.postXML(payload) if statusCode != 200 || err != nil { - c.log.V(1).Info("LDAP applyAddLdapGroupBayAccess apply request returned non 200.", + if err == nil { + err = fmt.Errorf("POST XML request failed with status code %d.", statusCode) + } + + c.log.V(1).Error(err, "applyAddLdapGroupBayAccess(): POST request failed.", "step", "applyAddLdapGroupBayAccess", "IP", c.ip, - "Model", c.HardwareType(), - "statusCode", statusCode, - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", c.HardwareType(), + "StatusCode", statusCode, ) return err } c.log.V(1).Info("Ldap interconnect and bay ACLs added.", "IP", c.ip, - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), "Group", group, ) return err } -// User applies the User configuration resource, -// if the user exists, it updates the users password, -// User implements the Configure interface. +// Applies the User configuration resource. +// Implements the Configure interface. +// If the user exists, updates their password. func (c *C7000) User(users []*cfgresources.User) (err error) { - for _, cfg := range users { if cfg.Name == "" { err = errors.New("user resource expects parameter: Name") c.log.V(1).Error(err, "user resource expects parameter: Name", "step", "applyUserParams", - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), ) return err } @@ -503,7 +496,7 @@ func (c *C7000) User(users []*cfgresources.User) (err error) { err = errors.New("user resource expects parameter: Password") c.log.V(1).Error(err, "user resource expects parameter: Password", "step", "applyUserParams", - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), ) return err } @@ -512,7 +505,7 @@ func (c *C7000) User(users []*cfgresources.User) (err error) { err = errors.New("user resource Role must be declared and a valid role: admin") c.log.V(1).Error(err, "user resource Role must be declared and a valid role: admin", "step", "applyUserParams", - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), "Role", cfg.Role, ) return err @@ -521,24 +514,23 @@ func (c *C7000) User(users []*cfgresources.User) (err error) { username := Username{Text: cfg.Name} password := Password{Text: cfg.Password} - //if user account is disabled, remove the user + // User account is disabled? Remove them. if !cfg.Enable { payload := RemoveUser{Username: username} statusCode, _, _ := c.postXML(payload) - //user doesn't exist + // User doesn't exist? Nothing to do, success claimed! if statusCode != 400 { - return err + return nil } c.log.V(1).Info("User removed.", "IP", c.ip, - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), "User", cfg.Name, ) - //user exists and was removed. - return err + return nil } payload := AddUser{Username: username, Password: password} @@ -547,48 +539,41 @@ func (c *C7000) User(users []*cfgresources.User) (err error) { return err } - //user exists if statusCode == 400 { c.log.V(1).Info("User already exists, setting password.", "step", "applyUserParams", "user", cfg.Name, "IP", c.ip, - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), "Return code", statusCode, ) - //update user password err := c.setUserPassword(cfg.Name, cfg.Password) if err != nil { return err } - //update user acl err = c.setUserACL(cfg.Name, cfg.Role) if err != nil { return err } - //updates user blade bay access acls err = c.applyAddUserBayAccess(cfg.Name) if err != nil { return err } - } - c.log.V(1).Info("User cfg applied.", + c.log.V(1).Info("User config applied.", "IP", c.ip, - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), "user", cfg.Name, ) - } - return err + return nil } func (c *C7000) setUserPassword(user string, password string) (err error) { - u := Username{Text: user} p := Password{Text: password} payload := SetUserPassword{Username: u, Password: p} @@ -599,23 +584,21 @@ func (c *C7000) setUserPassword(user string, password string) (err error) { "step", "setUserPassword", "user", user, "IP", c.ip, - "Model", c.HardwareType(), - "return code", statusCode, - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", c.HardwareType(), + "StatusCode", statusCode, ) return err } c.log.V(1).Info("User password set.", "IP", c.ip, - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), "user", user, ) return err } func (c *C7000) setUserACL(user string, role string) (err error) { - var aclRole string if role == "admin" { aclRole = "ADMINISTRATOR" @@ -635,16 +618,15 @@ func (c *C7000) setUserACL(user string, role string) (err error) { "user", user, "ACL", role, "IP", c.ip, - "Model", c.HardwareType(), - "return code", statusCode, - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", c.HardwareType(), + "StatusCode", statusCode, ) return err } c.log.V(1).Info("User ACL set.", "IP", c.ip, - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), "User", user, "ACL", role, ) @@ -654,13 +636,12 @@ func (c *C7000) setUserACL(user string, role string) (err error) { // Applies user bay access to each blade, interconnect, // see applyAddLdapGroupBayAccess() for details. func (c *C7000) applyAddUserBayAccess(user string) (err error) { - - //The c7000 wont allow changes to the bay acls for the reserved Administrator user. + // The c7000 won't allow changes to the bay ACLs for the reserved Administrator user. if user == "Administrator" { return nil } - //setup blade bays payload + // setup blade bays payload bladebays := bladeBays{} for b := 1; b <= 16; b++ { baynumber := bayNumber{Text: b} @@ -669,7 +650,7 @@ func (c *C7000) applyAddUserBayAccess(user string) (err error) { bladebays.Blade = append(bladebays.Blade, blade) } - //setup interconnect tray bays payload + // setup interconnect tray bays payload interconnecttraybays := interconnectTrayBays{} for t := 1; t <= 8; t++ { access := access{Text: true} @@ -678,7 +659,7 @@ func (c *C7000) applyAddUserBayAccess(user string) (err error) { interconnecttraybays.InterconnectTray = append(interconnecttraybays.InterconnectTray, interconnecttray) } - //setup the bays payload + // setup the bays payload bayz := bays{ Hpoa: "hpoa.xsd", OaAccess: oaAccess{Text: true}, @@ -693,12 +674,15 @@ func (c *C7000) applyAddUserBayAccess(user string) (err error) { statusCode, _, err := c.postXML(payload) if statusCode != 200 || err != nil { - c.log.V(1).Error(err, "LDAP applyAddUserBayAccess apply request returned non 200.", + if err == nil { + err = fmt.Errorf("POST XML request failed with status code %d.", statusCode) + } + + c.log.V(1).Error(err, "applyAddUserBayAccess(): POST request failed.", "step", "applyAddUserBayAccess", "IP", c.ip, - "Model", c.HardwareType(), - "statusCode", statusCode, - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", c.HardwareType(), + "StatusCode", statusCode, ) return err } @@ -706,10 +690,10 @@ func (c *C7000) applyAddUserBayAccess(user string) (err error) { c.log.V(1).Info("User account related interconnect and bay ACLs added.", "step", "applyAddUserBayAccess", "IP", c.ip, - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), "user", user, ) - return err + return nil } // Ntp applies NTP configuration params @@ -728,11 +712,10 @@ func (c *C7000) applyAddUserBayAccess(user string) (err error) { // CET // func (c *C7000) Ntp(cfg *cfgresources.Ntp) (err error) { - if cfg.Server1 == "" { c.log.V(1).Info("NTP resource expects parameter: server1.", "step", "applyNtpParams", - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), ) return } @@ -740,7 +723,7 @@ func (c *C7000) Ntp(cfg *cfgresources.Ntp) (err error) { if cfg.Timezone == "" { c.log.V(1).Info("NTP resource expects parameter: timezone.", "step", "applyNtpParams", - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), ) return } @@ -748,62 +731,64 @@ func (c *C7000) Ntp(cfg *cfgresources.Ntp) (err error) { if !cfg.Enable { c.log.V(1).Info("Ntp resource declared with enable: false.", "step", "applyNtpParams", - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), ) return } - //setup ntp XML payload - ntppoll := NtpPoll{Text: "720"} //default period to poll the NTP server + // setup ntp XML payload + ntppoll := NtpPoll{Text: "720"} // default period to poll the NTP server primaryServer := NtpPrimary{Text: cfg.Server1} secondaryServer := NtpSecondary{Text: cfg.Server2} payload := configureNtp{NtpPrimary: primaryServer, NtpSecondary: secondaryServer, NtpPoll: ntppoll} - //fmt.Printf("%s\n", output) statusCode, _, err := c.postXML(payload) if err != nil || statusCode != 200 { - c.log.V(1).Info("NTP apply request returned non 200.", + if err == nil { + err = fmt.Errorf("POST XML request failed with status code %d.", statusCode) + } + + c.log.V(1).Error(err, "Ntp(): POST request failed.", "step", "applyNtpParams", "IP", c.ip, - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), "StatusCode", statusCode, - "Error", internal.ErrStringOrEmpty(err), ) return err } err = c.applyNtpTimezoneParam(cfg.Timezone) if err != nil { - c.log.V(1).Info("Unable to apply NTP timezone config.", + c.log.V(1).Error(err, "Unable to apply NTP timezone config.", "step", "applyNtpParams", "IP", c.ip, - "Model", c.HardwareType(), - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", c.HardwareType(), ) return err } c.log.V(1).Info("Date and time config applied.", "IP", c.ip, - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), ) - return err + return nil } -//applies timezone // TODO: validate timezone string. func (c *C7000) applyNtpTimezoneParam(timezone string) (err error) { - - //setup timezone XML payload + // setup timezone XML payload payload := setEnclosureTimeZone{Timezone: timeZone{Text: timezone}} statusCode, _, err := c.postXML(payload) if err != nil || statusCode != 200 { - c.log.V(1).Info("NTP applyNtpTimezoneParam request returned non 200.", + if err == nil { + err = fmt.Errorf("POST XML request failed with status code %d.", statusCode) + } + + c.log.V(1).Error(err, "applyNtpTimezoneParam(): POST request failed.", "step", "applyNtpTimezoneParam", "IP", c.ip, - "Model", c.HardwareType(), - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", c.HardwareType(), "StatusCode", statusCode, ) return err @@ -811,7 +796,7 @@ func (c *C7000) applyNtpTimezoneParam(timezone string) (err error) { c.log.V(1).Info("Timezone config applied.", "IP", c.ip, - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), ) return err } @@ -824,13 +809,12 @@ func (c *C7000) applyNtpTimezoneParam(timezone string) (err error) { // 3. enable syslog // theres no option to set the port func (c *C7000) Syslog(cfg *cfgresources.Syslog) (err error) { - var port int if cfg.Server == "" { c.log.V(1).Info("Syslog resource expects parameter: Server.", "step", "applySyslogParams", "IP", c.ip, - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), ) return } @@ -839,7 +823,7 @@ func (c *C7000) Syslog(cfg *cfgresources.Syslog) (err error) { c.log.V(1).Info("Syslog resource port set to default: 514.", "step", "applySyslogParams", "IP", c.ip, - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), ) port = 514 } else { @@ -850,7 +834,7 @@ func (c *C7000) Syslog(cfg *cfgresources.Syslog) (err error) { c.log.V(1).Info("Syslog resource declared with enable: false.", "step", "applySyslogParams", "IP", c.ip, - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), ) } @@ -860,7 +844,7 @@ func (c *C7000) Syslog(cfg *cfgresources.Syslog) (err error) { c.log.V(1).Info("Syslog config applied.", "IP", c.ip, - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), ) return err } @@ -870,15 +854,17 @@ func (c *C7000) Syslog(cfg *cfgresources.Syslog) (err error) { // foobar // func (c *C7000) applySyslogServer(server string) { - payload := SetRemoteSyslogServer{Server: server} statusCode, _, err := c.postXML(payload) if err != nil || statusCode != 200 { - c.log.V(1).Error(err, "Syslog set server request returned non 200.", + if err == nil { + err = fmt.Errorf("POST XML request failed with status code %d.", statusCode) + } + + c.log.V(1).Error(err, "applySyslogServer(): Syslog set server request failed.", "step", "applySyslogServer", "IP", c.ip, - "Model", c.HardwareType(), - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", c.HardwareType(), "StatusCode", statusCode, ) return @@ -886,7 +872,7 @@ func (c *C7000) applySyslogServer(server string) { c.log.V(1).Info("Syslog server set.", "IP", c.ip, - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), ) } @@ -898,11 +884,14 @@ func (c *C7000) applySyslogPort(port int) { payload := SetRemoteSyslogPort{Port: port} statusCode, _, err := c.postXML(payload) if err != nil || statusCode != 200 { - c.log.V(1).Error(err, "Syslog set port request returned non 200.", + if err == nil { + err = fmt.Errorf("POST XML request failed with status code %d.", statusCode) + } + + c.log.V(1).Error(err, "applySyslogPort(): Syslog set port request failed.", "step", "applySyslogPort", "IP", c.ip, - "Model", c.HardwareType(), - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", c.HardwareType(), "StatusCode", statusCode, ) return @@ -910,7 +899,7 @@ func (c *C7000) applySyslogPort(port int) { c.log.V(1).Info("Syslog port set.", "IP", c.ip, - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), ) } @@ -919,15 +908,17 @@ func (c *C7000) applySyslogPort(port int) { // true // func (c *C7000) applySyslogEnabled(enabled bool) { - payload := SetRemoteSyslogEnabled{Enabled: enabled} statusCode, _, err := c.postXML(payload) if err != nil || statusCode != 200 { - c.log.V(1).Error(err, "Syslog enable request returned non 200.", + if err == nil { + err = fmt.Errorf("POST XML request failed with status code %d.", statusCode) + } + + c.log.V(1).Error(err, "applySyslogEnabled(): Syslog enable request failed.", "step", "SetRemoteSyslogEnabled", "IP", c.ip, - "Model", c.HardwareType(), - "Error", internal.ErrStringOrEmpty(err), + "HardwareType", c.HardwareType(), "StatusCode", statusCode, ) return @@ -935,7 +926,7 @@ func (c *C7000) applySyslogEnabled(enabled bool) { c.log.V(1).Info("Syslog enabled.", "IP", c.ip, - "Model", c.HardwareType(), + "HardwareType", c.HardwareType(), ) } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/c7000/setupConnections.go b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/c7000/setupConnections.go index 05b85b1f..52768fbd 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/c7000/setupConnections.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/c7000/setupConnections.go @@ -25,12 +25,12 @@ func (c *C7000) httpLogin() (err error) { return err } - //setup the login payload + // setup the login payload username := Username{Text: c.username} password := Password{Text: c.password} userlogin := UserLogIn{Username: username, Password: password} - //wrap the XML doc in the SOAP envelope + // wrap the XML doc in the SOAP envelope doc := wrapXML(userlogin, "") payload, err := xml.MarshalIndent(doc, " ", " ") @@ -48,7 +48,7 @@ func (c *C7000) httpLogin() (err error) { return err } - //req.Header.Add("Content-Type", "application/soap+xml; charset=utf-8") + // req.Header.Add("Content-Type", "application/soap+xml; charset=utf-8") req.Header.Add("Content-Type", "text/plain;charset=UTF-8") reqDump, _ := httputil.DumpRequestOut(req, true) diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/c7000/xmlhelpers.go b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/c7000/xmlhelpers.go index a18475ef..7fa44926 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/c7000/xmlhelpers.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/c7000/xmlhelpers.go @@ -15,7 +15,6 @@ import ( // wraps the XML to be sent in the SOAP envelope func wrapXML(element interface{}, sessionKey string) (doc Envelope) { - body := Body{Content: element} doc = Envelope{ SOAPENV: "http://www.w3.org/2003/05/soap-envelope", @@ -28,13 +27,13 @@ func wrapXML(element interface{}, sessionKey string) (doc Envelope) { } if sessionKey != "" { - - doc.Header = Header{Security: Security{ - MustUnderstand: "true", - HpOaSessionKeyToken: HpOaSessionKeyToken{ - OaSessionKey: OaSessionKey{Text: sessionKey}, + doc.Header = Header{ + Security: Security{ + MustUnderstand: "true", + HpOaSessionKeyToken: HpOaSessionKeyToken{ + OaSessionKey: OaSessionKey{Text: sessionKey}, + }, }, - }, } } @@ -72,8 +71,8 @@ func (c *C7000) postXML(data interface{}) (statusCode int, body []byte, err erro return 0, []byte{}, err } - //Setup a context to cancel the request if it takes long, - //this prevents the http.Client.Timeout Deadline from kicking in and causing a panic. + // Setup a context to cancel the request if it takes long. + // This prevents the http.Client.Timeout deadline from kicking in and causing a panic. ctx, cancel := context.WithTimeout(req.Context(), 10*time.Second) defer cancel() @@ -98,6 +97,5 @@ func (c *C7000) postXML(data interface{}) (statusCode int, body []byte, err erro return 0, []byte{}, err } - //fmt.Printf("%+v\n", body) return resp.StatusCode, body, err } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/c7000/xmlmodel.go b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/c7000/xmlmodel.go index b21fb815..9e73980d 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/c7000/xmlmodel.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/c7000/xmlmodel.go @@ -243,7 +243,7 @@ type bays struct { type oaAccess struct { XMLName xml.Name `xml:"hpoa:oaAccess"` - Text bool `xml:",chardata"` //bool + Text bool `xml:",chardata"` } type bladeBays struct { diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/actions.go b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/actions.go index 5c1458a4..89d7e7ea 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/actions.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/actions.go @@ -3,6 +3,7 @@ package ilo import ( "context" "fmt" + "regexp" "strings" "github.com/bmc-toolbox/bmclib/internal/ipmi" @@ -107,16 +108,31 @@ func (i *Ilo) IsOn() (bool, error) { } // UpdateFirmware updates the bmc firmware -func (i *Ilo) UpdateFirmware(source, file string) (bool, error) { +func (i *Ilo) UpdateFirmware(source, file string) (bool, string, error) { cmd := fmt.Sprintf("load /map1/firmware1 -source %s/%s", source, file) output, err := i.sshClient.Run(cmd) if err != nil { - return false, fmt.Errorf("output: %q: %w", output, err) + return false, "", fmt.Errorf("output: %q: %w", output, err) } if strings.Contains(output, "Resetting iLO") { - return true, nil + return true, output, nil } - return false, fmt.Errorf(output) + return false, output, fmt.Errorf(output) +} + +func (i *Ilo) CheckFirmwareVersion() (version string, err error) { + output, err := i.sshClient.Run("show /map1/firmware1") + if err != nil { + return "", fmt.Errorf("output: %q: %w", output, err) + } + + re := regexp.MustCompile(`.*version=((\d+\.)+\d+)`) + matches := re.FindStringSubmatch(output) + if len(matches) > 1 { + return matches[1], nil + } + + return "", fmt.Errorf("unexpected output: %q", output) } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/configure.go b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/configure.go index 686199c5..e77d7492 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/configure.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/configure.go @@ -7,7 +7,6 @@ import ( "github.com/bmc-toolbox/bmclib/cfgresources" "github.com/bmc-toolbox/bmclib/devices" - "github.com/bmc-toolbox/bmclib/internal" "github.com/bmc-toolbox/bmclib/internal/helper" ) @@ -34,13 +33,11 @@ func (i *Ilo) Resources() []string { // ApplyCfg applies configuration // To be deprecated once the Configure interface is ready. func (i *Ilo) ApplyCfg(config *cfgresources.ResourcesConfig) (err error) { - - //check sessionKey is available if i.sessionKey == "" { msg := "Expected sessionKey not found, unable to configure BMC." i.log.V(1).Info(msg, "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", "Login()", ) return errors.New(msg) @@ -51,7 +48,6 @@ func (i *Ilo) ApplyCfg(config *cfgresources.ResourcesConfig) (err error) { // Return bool value if the role is valid. func (i *Ilo) isRoleValid(role string) bool { - validRoles := []string{"admin", "user"} for _, v := range validRoles { if role == v { @@ -62,9 +58,8 @@ func (i *Ilo) isRoleValid(role string) bool { return false } -// checks if a user is present in a given list +// Checks if a user is present in a given list. func userExists(user string, usersInfo []UserInfo) (userInfo UserInfo, exists bool) { - for _, userInfo := range usersInfo { if userInfo.UserName == user || userInfo.LoginName == user { return userInfo, true @@ -74,40 +69,23 @@ func userExists(user string, usersInfo []UserInfo) (userInfo UserInfo, exists bo return userInfo, false } -// checks if a ldap group is present in a given list -func ldapGroupExists(group string, directoryGroups []DirectoryGroups) (directoryGroup DirectoryGroups, exists bool) { - - for _, directoryGroup := range directoryGroups { - if directoryGroup.Dn == group { - return directoryGroup, true - } - } - - return directoryGroup, false -} - -// User applies the User configuration resource, -// if the user exists, it updates the users password, +// User applies the User configuration resource. +// If the user exists, it updates the password. // User implements the Configure interface. -// nolint: gocyclo func (i *Ilo) User(users []*cfgresources.User) (err error) { - existingUsers, err := i.queryUsers() if err != nil { - msg := "Unable to query existing users" - i.log.V(1).Info(msg, + msg := "ILO User(): Unable to query existing users." + i.log.V(1).Error(err, msg, "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", "applyUserParams", - "Error", internal.ErrStringOrEmpty(err), ) - return errors.New(msg) + return err } + // Validation cycle. for _, user := range users { - - var postPayload bool - if user.Name == "" { msg := "User resource expects parameter: Name." i.log.V(1).Info(msg, "step", "applyUserParams") @@ -125,13 +103,14 @@ func (i *Ilo) User(users []*cfgresources.User) (err error) { i.log.V(1).Info(msg, "step", "applyUserParams", "Username", user.Name) return errors.New(msg) } + } + + for _, user := range users { + var postPayload bool - //retrive userInfo userinfo, uexists := userExists(user.Name, existingUsers) - //set session key userinfo.SessionKey = i.sessionKey - //if the user is enabled setup parameters if user.Enable { userinfo.RemoteConsPriv = 1 userinfo.VirtualMediaPriv = 1 @@ -147,7 +126,6 @@ func (i *Ilo) User(users []*cfgresources.User) (err error) { userinfo.LoginPriv = 0 } - //if the user exists, modify it if uexists { userinfo.Method = "mod_user" userinfo.UserID = userinfo.ID @@ -164,14 +142,14 @@ func (i *Ilo) User(users []*cfgresources.User) (err error) { postPayload = true } - //if the user is disabled remove it + // If the user is disabled, remove them. if !user.Enable && uexists { userinfo.Method = "del_user" userinfo.UserID = userinfo.ID msg := "User disabled in config, will be removed." i.log.V(1).Info(msg, "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "User", user.Name, ) postPayload = true @@ -180,13 +158,12 @@ func (i *Ilo) User(users []*cfgresources.User) (err error) { if postPayload { payload, err := json.Marshal(userinfo) if err != nil { - msg := "Unable to marshal userInfo payload to set User config." - i.log.V(1).Info(msg, + msg := "User(): Unable to marshal userInfo payload to set User config." + i.log.V(1).Error(err, msg, "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), "User", user.Name, - "Error", internal.ErrStringOrEmpty(err), ) continue } @@ -194,27 +171,29 @@ func (i *Ilo) User(users []*cfgresources.User) (err error) { endpoint := "json/user_info" statusCode, response, err := i.post(endpoint, payload) if err != nil || statusCode != 200 { - msg := "POST request to set User config returned error." - i.log.V(1).Info(msg, + if err == nil { + err = fmt.Errorf("Received a %d status code from the POST request to %s.", statusCode, endpoint) + } else { + err = fmt.Errorf("POST request to %s failed with error: %s", endpoint, err.Error()) + } + + i.log.V(1).Error(err, "POST request to set User config failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "endpoint", endpoint, "step", helper.WhosCalling(), "User", user.Name, "StatusCode", statusCode, "response", string(response), - "Error", internal.ErrStringOrEmpty(err), ) - continue } i.log.V(1).Info("User parameters applied.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "User", user.Name, ) - } } @@ -224,7 +203,6 @@ func (i *Ilo) User(users []*cfgresources.User) (err error) { // Syslog applies the Syslog configuration resource // Syslog implements the Configure interface func (i *Ilo) Syslog(cfg *cfgresources.Syslog) (err error) { - var port int enable := 1 @@ -257,11 +235,10 @@ func (i *Ilo) Syslog(cfg *cfgresources.Syslog) (err error) { payload, err := json.Marshal(remoteSyslog) if err != nil { msg := "Unable to marshal RemoteSyslog payload to set Syslog config." - i.log.V(1).Info(msg, + i.log.V(1).Error(err, msg, "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) return errors.New(msg) } @@ -269,20 +246,24 @@ func (i *Ilo) Syslog(cfg *cfgresources.Syslog) (err error) { endpoint := "json/remote_syslog" statusCode, response, err := i.post(endpoint, payload) if err != nil || statusCode != 200 { - msg := "POST request to set User config returned error." - i.log.V(1).Info(msg, + if err == nil { + err = fmt.Errorf("Received a %d status code from the POST request to %s.", statusCode, endpoint) + } else { + err = fmt.Errorf("POST request to %s failed with error: %s", endpoint, err.Error()) + } + + i.log.V(1).Error(err, "POST request to set Syslog config failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "endpoint", endpoint, "step", helper.WhosCalling(), "StatusCode", statusCode, "response", string(response), - "Error", internal.ErrStringOrEmpty(err), ) - return errors.New(msg) + return err } - i.log.V(1).Info("Syslog parameters applied.", "IP", i.ip, "Model", i.HardwareType()) + i.log.V(1).Info("Syslog parameters applied.", "IP", i.ip, "HardwareType", i.HardwareType()) return err } @@ -290,7 +271,6 @@ func (i *Ilo) Syslog(cfg *cfgresources.Syslog) (err error) { // SetLicense applies license configuration params // SetLicense implements the Configure interface. func (i *Ilo) SetLicense(cfg *cfgresources.License) (err error) { - if cfg.Key == "" { msg := "License resource expects parameter: Key." i.log.V(1).Info(msg, "step", helper.WhosCalling()) @@ -306,32 +286,36 @@ func (i *Ilo) SetLicense(cfg *cfgresources.License) (err error) { payload, err := json.Marshal(license) if err != nil { msg := "Unable to marshal License payload to activate License." - i.log.V(1).Info(msg, + i.log.V(1).Error(err, msg, "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) - return errors.New(msg) + return errors.New(msg + ": " + err.Error()) } endpoint := "json/license_info" statusCode, response, err := i.post(endpoint, payload) if err != nil || statusCode != 200 { - msg := "POST request to set User config returned error." - i.log.V(1).Info(msg, + if err == nil { + err = fmt.Errorf("Received a %d status code from the POST request to %s.", statusCode, endpoint) + } else { + err = fmt.Errorf("POST request to %s failed with error: %s", endpoint, err.Error()) + } + + msg := "POST request to set License failed." + i.log.V(1).Error(err, msg, "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "endpoint", endpoint, "step", helper.WhosCalling(), "StatusCode", statusCode, "response", string(response), - "Error", internal.ErrStringOrEmpty(err), ) - return errors.New(msg) + return err } - i.log.V(1).Info("License activated.", "IP", i.ip, "Model", i.HardwareType()) + i.log.V(1).Info("License activated.", "IP", i.ip, "HardwareType", i.HardwareType()) return err } @@ -339,7 +323,6 @@ func (i *Ilo) SetLicense(cfg *cfgresources.License) (err error) { // Ntp applies NTP configuration params // Ntp implements the Configure interface. func (i *Ilo) Ntp(cfg *cfgresources.Ntp) (err error) { - enable := 1 if cfg.Server1 == "" { msg := "NTP resource expects parameter: server1." @@ -378,13 +361,12 @@ func (i *Ilo) Ntp(cfg *cfgresources.Ntp) (err error) { existingConfig, err := i.queryNetworkSntp() if err != nil { msg := "Unable to query existing config" - i.log.V(1).Info(msg, + i.log.V(1).Error(err, msg, "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) - return errors.New(msg) + return err } networkSntp := NetworkSntp{ @@ -396,7 +378,7 @@ func (i *Ilo) Ntp(cfg *cfgresources.Ntp) (err error) { Ipv6Disabled: 0, DhcpEnabled: enable, Dhcp6Enabled: enable, - UseDhcpSuppliedTimeServers: 0, //we probably want to expose these as params + UseDhcpSuppliedTimeServers: 0, // TODO: Maybe expose these as params? UseDhcp6SuppliedTimeServers: 0, Sdn1WCount: existingConfig.Sdn1WCount, Sdn2WCount: existingConfig.Sdn2WCount, @@ -411,60 +393,109 @@ func (i *Ilo) Ntp(cfg *cfgresources.Ntp) (err error) { payload, err := json.Marshal(networkSntp) if err != nil { msg := "Unable to marshal NetworkSntp payload to set NTP config." - i.log.V(1).Info(msg, + i.log.V(1).Error(err, msg, "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) - return errors.New(msg) + return err } endpoint := "json/network_sntp" statusCode, response, err := i.post(endpoint, payload) if err != nil || statusCode != 200 { - msg := "POST request to set NTP config returned error." - i.log.V(1).Info(msg, + if err == nil { + err = fmt.Errorf("Received a %d status code from the POST request to %s.", statusCode, endpoint) + } else { + err = fmt.Errorf("POST request to %s failed with error: %s", endpoint, err.Error()) + } + + i.log.V(1).Error(err, "POST request to set NTP config failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "endpoint", endpoint, "step", helper.WhosCalling(), "StatusCode", statusCode, "response", string(response), - "Error", internal.ErrStringOrEmpty(err), ) - return errors.New(msg) + return err } - i.log.V(1).Info("NTP parameters applied.", "IP", i.ip, "Model", i.HardwareType()) + i.log.V(1).Info("NTP parameters applied.", "IP", i.ip, "HardwareType", i.HardwareType()) return err } -// LdapGroup applies LDAP Group/Role related configuration -// LdapGroup implements the Configure interface. +// LdapGroups applies LDAP Group/Role related configuration +// LdapGroups implements the Configure interface. // nolint: gocyclo -func (i *Ilo) LdapGroup(cfg []*cfgresources.LdapGroup, cfgLdap *cfgresources.Ldap) (err error) { - +func (i *Ilo) LdapGroups(cfgGroups []*cfgresources.LdapGroup, cfgLdap *cfgresources.Ldap) (err error) { directoryGroups, err := i.queryDirectoryGroups() if err != nil { - msg := "Unable to query existing Ldap groups" - i.log.V(1).Info(msg, + msg := "Unable to query existing LDAP groups." + i.log.V(1).Error(err, msg, "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) - return errors.New(msg) + return err } - for _, group := range cfg { + endpoint := "json/directory_groups" + + // Let's start from a clean slate. + for _, group := range directoryGroups { + group.Method = "del_group" + group.SessionKey = i.sessionKey + + payload, err := json.Marshal(group) + if err != nil { + i.log.V(1).Error(err, "Unable to marshal directoryGroup payload to set LdapGroup config.", + "IP", i.ip, + "HardwareType", i.HardwareType(), + "step", helper.WhosCalling(), + "Group", group, + ) + continue + } + + statusCode, response, err := i.post(endpoint, payload) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the POST request to %s.", statusCode, endpoint) + } else { + err = fmt.Errorf("POST request to %s failed with error: %s", endpoint, err.Error()) + } + + i.log.V(1).Error(err, "POST request to delete LDAP groups failed.", + "IP", i.ip, + "HardwareType", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "Group", group, + "StatusCode", statusCode, + "response", string(response), + ) + continue + } + + i.log.V(1).Info("Old LDAP group deleted successfully.", + "IP", i.ip, + "HardwareType", i.HardwareType(), + "Group", group, + ) + } + + // Verify we have good configuration. + for _, group := range cfgGroups { + if !group.Enable { + continue + } - var postPayload bool if group.Group == "" { - msg := "Ldap resource parameter Group required but not declared." + msg := "LDAP resource parameter Group required but not declared." i.log.V(1).Info(msg, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), "Ldap role", group.Role, ) @@ -472,137 +503,120 @@ func (i *Ilo) LdapGroup(cfg []*cfgresources.LdapGroup, cfgLdap *cfgresources.Lda } if !i.isRoleValid(group.Role) { - msg := "Ldap resource Role must be a valid role: admin OR user." + msg := "LDAP resource Role must be a valid role: admin OR user." i.log.V(1).Info(msg, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), "Ldap role", group.Role, ) return errors.New(msg) } + } - groupDn := group.Group - directoryGroup, gexists := ldapGroupExists(groupDn, directoryGroups) + // Now, let's add what we have. + for _, group := range cfgGroups { + if !group.Enable { + continue + } - directoryGroup.Dn = groupDn + var directoryGroup DirectoryGroups + directoryGroup.Dn = fmt.Sprintf("%s,%s", group.Group, group.GroupBaseDn) + directoryGroup.Method = "add_group" directoryGroup.SessionKey = i.sessionKey - //if the group is enabled setup parameters - if group.Enable { - - directoryGroup.LoginPriv = 1 - directoryGroup.RemoteConsPriv = 1 - directoryGroup.VirtualMediaPriv = 1 - directoryGroup.ResetPriv = 1 - - if group.Role == "admin" { - directoryGroup.ConfigPriv = 1 - directoryGroup.UserPriv = 1 - } else if group.Role == "user" { - directoryGroup.ConfigPriv = 0 - directoryGroup.UserPriv = 0 - } - - //if the group exists, modify it - if gexists { - directoryGroup.Method = "mod_group" - } else { - - directoryGroup.Method = "add_group" - } - - postPayload = true + // Privileges + directoryGroup.LoginPriv = 1 + directoryGroup.RemoteConsPriv = 1 + directoryGroup.VirtualMediaPriv = 1 + directoryGroup.ResetPriv = 1 + + if group.Role == "admin" { + directoryGroup.ConfigPriv = 1 + directoryGroup.UserPriv = 1 + } else { + directoryGroup.ConfigPriv = 0 + directoryGroup.UserPriv = 0 } - //if the group is disabled remove it - if !group.Enable && gexists { - directoryGroup.Method = "del_group" - i.log.V(1).Info("Ldap role group disabled in config, will be removed.", + payload, err := json.Marshal(directoryGroup) + if err != nil { + i.log.V(1).Error(err, "LdapGroups(): Unable to marshal directoryGroup payload to set LdapGroup config.", "IP", i.ip, - "Model", i.HardwareType(), - "User", group.Group, + "HardwareType", i.HardwareType(), + "step", helper.WhosCalling(), + "Group", group.Group, ) - postPayload = true + continue } - if postPayload { - payload, err := json.Marshal(directoryGroup) - if err != nil { - i.log.V(1).Info("Unable to marshal directoryGroup payload to set LdapGroup config.", - "IP", i.ip, - "Model", i.HardwareType(), - "step", helper.WhosCalling(), - "Group", group.Group, - "Error", internal.ErrStringOrEmpty(err), - ) - continue - } - - endpoint := "json/directory_groups" - statusCode, response, err := i.post(endpoint, payload) - if err != nil || statusCode != 200 { - i.log.V(1).Info("POST request to set User config returned error.", - "IP", i.ip, - "Model", i.HardwareType(), - "endpoint", endpoint, - "step", helper.WhosCalling(), - "Group", group.Group, - "StatusCode", statusCode, - "response", string(response), - "Error", internal.ErrStringOrEmpty(err), - ) - continue + statusCode, response, err := i.post(endpoint, payload) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the POST request to %s.", statusCode, endpoint) + } else { + err = fmt.Errorf("POST request to %s failed with error: %s", endpoint, err.Error()) } - i.log.V(1).Info("LdapGroup parameters applied.", + i.log.V(1).Error(err, "POST request to set LDAP group failed.", "IP", i.ip, - "Model", i.HardwareType(), - "User", group.Group, + "HardwareType", i.HardwareType(), + "endpoint", endpoint, + "step", helper.WhosCalling(), + "Group", group.Group, + "StatusCode", statusCode, + "response", string(response), ) - + continue } + i.log.V(1).Info("LdapGroup parameters applied.", + "IP", i.ip, + "HardwareType", i.HardwareType(), + "Group", group.Group, + ) } - return err + return nil } // Ldap applies LDAP configuration params. // Ldap implements the Configure interface. func (i *Ilo) Ldap(cfg *cfgresources.Ldap) (err error) { - if cfg.Server == "" { - msg := "Ldap resource parameter Server required but not declared." - i.log.V(1).Info(msg, - "Model", i.HardwareType(), + msg := "Ldap(): LDAP resource parameter Server required but not declared." + err = errors.New(msg) + i.log.V(1).Error(err, msg, + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), ) - return errors.New(msg) + return err } if cfg.Port == 0 { - msg := "Ldap resource parameter Port required but not declared." - i.log.V(1).Info(msg, - "Model", i.HardwareType(), + msg := "Ldap(): LDAP resource parameter Port required but not declared." + err = errors.New(msg) + i.log.V(1).Error(err, msg, + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), ) - return errors.New(msg) + return err } if cfg.BaseDn == "" { - msg := "Ldap resource parameter BaseDn required but not declared." - i.log.V(1).Info(msg, - "Model", i.HardwareType(), + msg := "Ldap(): LDAP resource parameter BaseDn required but not declared." + err = errors.New(msg) + i.log.V(1).Error(err, msg, + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), ) - return errors.New(msg) + return err } var enable int - if !cfg.Enable { - enable = 0 - } else { + if cfg.Enable { enable = 1 + } else { + enable = 0 } directory := Directory{ @@ -620,11 +634,10 @@ func (i *Ilo) Ldap(cfg *cfgresources.Ldap) (err error) { payload, err := json.Marshal(directory) if err != nil { - i.log.V(1).Info("Unable to marshal directory payload to set Ldap config.", + i.log.V(1).Error(err, "Ldap(): Unable to marshal directory payload to set LDAP config.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) return err } @@ -632,23 +645,26 @@ func (i *Ilo) Ldap(cfg *cfgresources.Ldap) (err error) { endpoint := "json/directory" statusCode, response, err := i.post(endpoint, payload) if err != nil || statusCode != 200 { - msg := "POST request to set Ldap config returned error." - i.log.V(1).Info(msg, + if err == nil { + err = fmt.Errorf("Received a %d status code from the POST request to %s.", statusCode, endpoint) + } else { + err = fmt.Errorf("POST request to %s failed with error: %s", endpoint, err.Error()) + } + + i.log.V(1).Error(err, "POST request to set Ldap config failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "endpoint", endpoint, "step", helper.WhosCalling(), "StatusCode", statusCode, "response", string(response), - "Error", internal.ErrStringOrEmpty(err), ) return err } - i.log.V(1).Info("Ldap parameters applied.", "IP", i.ip, "Model", i.HardwareType()) + i.log.V(1).Info("Ldap parameters applied.", "IP", i.ip, "HardwareType", i.HardwareType()) return err - } // GenerateCSR generates a CSR request on the BMC. @@ -656,7 +672,6 @@ func (i *Ilo) Ldap(cfg *cfgresources.Ldap) (err error) { // the response will be a 500 with the body {"message":"JS_CERT_NOT_AVAILABLE","details":null} // If the configuration for the Subject has not changed and the CSR is ready a CSR is returned. func (i *Ilo) GenerateCSR(cert *cfgresources.HTTPSCertAttributes) ([]byte, error) { - csrConfig := &csr{ Country: cert.CountryCode, State: cert.StateName, @@ -676,22 +691,21 @@ func (i *Ilo) GenerateCSR(cert *cfgresources.HTTPSCertAttributes) ([]byte, error endpoint := "json/csr" statusCode, response, err := i.post(endpoint, payload) + // Some general error? + if err != nil { + return nil, err + } + if statusCode == 500 { return []byte{}, fmt.Errorf("CSR being generated, retry later") } - // if its a not a 200 at this point, - // something else went wrong. + // If it's a not a 200 at this point, something else went wrong. if statusCode != 200 { - return []byte{}, fmt.Errorf("Unexpected return code: %d", statusCode) + return []byte{}, fmt.Errorf("Unexpected return code %d calling %s!", statusCode, endpoint) } - // Some other error - if err != nil { - return []byte{}, err - } - - var r = new(csrResponse) + r := new(csrResponse) err = json.Unmarshal(response, r) if err != nil { return []byte{}, err @@ -704,7 +718,6 @@ func (i *Ilo) GenerateCSR(cert *cfgresources.HTTPSCertAttributes) ([]byte, error // UploadHTTPSCert implements the Configure interface. // return true if the bmc requires a reset. func (i *Ilo) UploadHTTPSCert(cert []byte, certFileName string, key []byte, keyFileName string) (bool, error) { - certPayload := &certImport{ Method: "import_certificate", CertificateData: string(cert), @@ -723,7 +736,7 @@ func (i *Ilo) UploadHTTPSCert(cert []byte, certFileName string, key []byte, keyF } if statusCode != 200 { - return false, fmt.Errorf("Unexpected return code: %d", statusCode) + return false, fmt.Errorf("Unexpected return code %d calling %s!", statusCode, endpoint) } // ILOs need a reset after cert upload. @@ -733,23 +746,25 @@ func (i *Ilo) UploadHTTPSCert(cert []byte, certFileName string, key []byte, keyF // Network method implements the Configure interface // nolint: gocyclo func (i *Ilo) Network(cfg *cfgresources.Network) (reset bool, err error) { - // check if AccessSettings configuration update is required. accessSettings, updateAccessSettings, err := i.cmpAccessSettings(cfg) if err != nil { - return reset, err + return false, err } if updateAccessSettings { payload, err := json.Marshal(accessSettings) if err != nil { - return reset, fmt.Errorf("Error marshaling AccessSettings payload: %s", err) + return false, fmt.Errorf("Error marshaling AccessSettings payload: %s", err) } endpoint := "json/access_settings" statusCode, _, err := i.post(endpoint, payload) - if err != nil || statusCode != 200 { - return reset, fmt.Errorf("Error/non 200 response calling access_settings, status: %d, error: %s", statusCode, err) + if err != nil { + return false, fmt.Errorf("Error calling access_settings: %s", err) + } + if statusCode != 200 { + return false, fmt.Errorf("Non-200 response calling access_settings: %d", statusCode) } reset = true @@ -762,7 +777,6 @@ func (i *Ilo) Network(cfg *cfgresources.Network) (reset bool, err error) { } if updateIPv4Settings { - payload, err := json.Marshal(networkIPv4Settings) if err != nil { return reset, fmt.Errorf("Error marshaling NetworkIPv4 payload: %s", err) @@ -770,8 +784,11 @@ func (i *Ilo) Network(cfg *cfgresources.Network) (reset bool, err error) { endpoint := "json/network_ipv4/interface/0" statusCode, _, err := i.post(endpoint, payload) - if err != nil || statusCode != 200 { - return reset, fmt.Errorf("Error/non 200 response calling access_settings, status: %d, error: %s", statusCode, err) + if err != nil { + return reset, fmt.Errorf("Error calling access_settings: %s", err) + } + if statusCode != 200 { + return reset, fmt.Errorf("Non-200 response calling access_settings: %d", statusCode) } reset = true @@ -782,13 +799,12 @@ func (i *Ilo) Network(cfg *cfgresources.Network) (reset bool, err error) { // Power settings func (i *Ilo) Power(cfg *cfgresources.Power) error { - if cfg.HPE == nil { return nil } // map of valid power_settings attributes to params passed to the iLO API - var powerRegulatorModes = map[string]string{ + powerRegulatorModes := map[string]string{ "dynamic": "dyn", "static_low": "min", "static_high": "max", @@ -797,7 +813,7 @@ func (i *Ilo) Power(cfg *cfgresources.Power) error { configMode, exists := powerRegulatorModes[cfg.HPE.PowerRegulator] if cfg.HPE.PowerRegulator == "" || !exists { - return fmt.Errorf("power regulator parameter must be one of dynamic, static_log, static_high, os_control") + return fmt.Errorf("power_regulator parameter must be one of dynamic, static_log, static_high, os_control") } // check if a configuration update is required based on current setting @@ -807,18 +823,18 @@ func (i *Ilo) Power(cfg *cfgresources.Power) error { } if !changeRequired { - i.log.V(2).Info("Power regulator config - no change required.", + i.log.V(2).Info("power_regulator config - no change required.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "current mode", config.PowerMode, "expected mode", configMode, ) return nil } - i.log.V(2).Info("Power regulator change to be applied.", + i.log.V(2).Info("power_regulator change to be applied.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "current mode", config.PowerMode, "expected mode", configMode, ) @@ -829,18 +845,21 @@ func (i *Ilo) Power(cfg *cfgresources.Power) error { payload, err := json.Marshal(config) if err != nil { - return fmt.Errorf("Error marshaling PowerRegulator payload: %s", err) + return fmt.Errorf("Error marshaling power_regulator payload: %s", err) } endpoint := "json/power_regulator" statusCode, _, err := i.post(endpoint, payload) - if err != nil || statusCode != 200 { - return fmt.Errorf("Error/non 200 response calling power_regulator, status: %d, error: %s", statusCode, err) + if err != nil { + return fmt.Errorf("Error calling power_regulator: %s", err) + } + if statusCode != 200 { + return fmt.Errorf("Non-200 response calling power_regulator: %d", statusCode) } - i.log.V(1).Info("Power regulator config applied.", + i.log.V(1).Info("power_regulator config applied.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), ) return nil diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/helpers.go b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/helpers.go index a3d754f7..a868f3c4 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/helpers.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/helpers.go @@ -8,12 +8,10 @@ import ( // cmdPowerSettings func (i *Ilo) cmpPowerSettings(regulatorMode string) (PowerRegulator, bool, error) { - // get current config currentConfig, err := i.queryPowerRegulator() if err != nil { return PowerRegulator{}, false, fmt.Errorf("Unable to query existing Power regulator config") - } settingsMatch := func() bool { @@ -26,12 +24,10 @@ func (i *Ilo) cmpPowerSettings(regulatorMode string) (PowerRegulator, bool, erro // configuration update required. return currentConfig, true, nil - } // compares the current Network IPv4 config with the given Network configuration func (i *Ilo) cmpNetworkIPv4Settings(cfg *cfgresources.Network) (NetworkIPv4, bool, error) { - // setup some params as int for comparison var dnsFromDHCP, dhcpEnable, ddnsEnable int @@ -51,7 +47,6 @@ func (i *Ilo) cmpNetworkIPv4Settings(cfg *cfgresources.Network) (NetworkIPv4, bo currentConfig, err := i.queryNetworkIPv4() if err != nil { return NetworkIPv4{}, false, fmt.Errorf("Unable to query existing IPv4 network config") - } settingsMatch := func() bool { @@ -89,7 +84,6 @@ func (i *Ilo) cmpNetworkIPv4Settings(cfg *cfgresources.Network) (NetworkIPv4, bo // returning an updated AccessSettings struct if an update is required. // nolint: gocyclo func (i *Ilo) cmpAccessSettings(cfg *cfgresources.Network) (AccessSettings, bool, error) { - // setup some params as int for comparison var sshEnable, ipmiEnable, serialEnable int @@ -113,7 +107,6 @@ func (i *Ilo) cmpAccessSettings(cfg *cfgresources.Network) (AccessSettings, bool // compare current configuration with configuration declared. settingsMatch := func() bool { - // compare currentConfig cofiguration with declared. if currentConfig.SSHStatus != sshEnable { return false @@ -162,5 +155,4 @@ func (i *Ilo) cmpAccessSettings(cfg *cfgresources.Network) (AccessSettings, bool // configuration update required. return currentConfig, true, nil - } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/ilo.go b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/ilo.go index c449e3ed..69fd5ee8 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/ilo.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/ilo.go @@ -105,19 +105,24 @@ func (i *Ilo) CheckCredentials() (err error) { return err } -// get calls a given json endpoint of the iLO and returns the data -func (i *Ilo) get(endpoint string, useSession bool) (payload []byte, err error) { - i.log.V(1).Info("retrieving data from bmc", "step", "bmc connection", "vendor", hp.VendorID, "ip", i.ip, "endpoint", endpoint) +// Calls a given JSON ILO endpoint and returns the status code and the data. +func (i *Ilo) get(endpoint string, useSession bool) (int, []byte, error) { + i.log.V(1).Info("Retrieving data from ILO...", + "step", "bmc connection", + "vendor", hp.VendorID, + "ip", i.ip, + "endpoint", endpoint, + ) bmcURL := fmt.Sprintf("https://%s", i.ip) req, err := http.NewRequest("GET", fmt.Sprintf("%s/%s", bmcURL, endpoint), nil) if err != nil { - return payload, err + return 0, nil, err } u, err := url.Parse(bmcURL) if err != nil { - return payload, err + return 0, nil, err } if useSession { @@ -135,27 +140,26 @@ func (i *Ilo) get(endpoint string, useSession bool) (payload []byte, err error) resp, err := i.httpClient.Do(req) if err != nil { - return payload, err + return 0, nil, err } defer resp.Body.Close() respDump, _ := httputil.DumpResponse(resp, true) i.log.V(2).Info("responseTrace", "responseDump", string(respDump)) - payload, err = ioutil.ReadAll(resp.Body) + payload, err := ioutil.ReadAll(resp.Body) if err != nil { - return payload, err + return 0, nil, err } if resp.StatusCode == 404 { - return payload, errors.ErrPageNotFound + return 404, nil, errors.ErrPageNotFound } - return payload, err + return resp.StatusCode, payload, nil } // posts the payload to the given endpoint func (i *Ilo) post(endpoint string, data []byte) (statusCode int, body []byte, err error) { - u, err := url.Parse(fmt.Sprintf("https://%s/%s", i.ip, endpoint)) if err != nil { return 0, []byte{}, err @@ -180,7 +184,9 @@ func (i *Ilo) post(endpoint string, data []byte) (statusCode int, body []byte, e if err != nil { return 0, []byte{}, err } + defer resp.Body.Close() + respDump, _ := httputil.DumpResponse(resp, true) i.log.V(2).Info("responseTrace", "responseDump", string(respDump)) @@ -197,15 +203,20 @@ func (i *Ilo) Serial() (serial string, err error) { return strings.ToLower(strings.TrimSpace(i.rimpBlade.HSI.Sbsn)), err } -// ChassisSerial returns the serial number of the chassis where the blade is attached +// Returns the serial number of the chassis where the blade is attached. func (i *Ilo) ChassisSerial() (string, error) { err := i.httpLogin() if err != nil { return "", err } - payload, err := i.get("json/rck_info", true) - if err != nil { + endpoint := "json/rck_info" + statusCode, payload, err := i.get(endpoint, true) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + return "", err } @@ -253,39 +264,45 @@ func (i *Ilo) Version() (bmcVersion string, err error) { return i.rimpBlade.MP.Fwri, err } -// Name returns the name of this server from the iLO point of view +// Returns the name of this server from the ILO point of view. func (i *Ilo) Name() (name string, err error) { err = i.httpLogin() if err != nil { return name, err } - url := "json/overview" - payload, err := i.get(url, true) - if err != nil { - return name, err + endpoint := "json/overview" + statusCode, payload, err := i.get(endpoint, true) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + return "", err } overview := &hp.Overview{} err = json.Unmarshal(payload, overview) if err != nil { - return name, err + return "", err } return overview.ServerName, err } -// Status returns health string status from the bmc +// Returns the health status from the ILO point of view. func (i *Ilo) Status() (health string, err error) { err = i.httpLogin() if err != nil { return health, err } - url := "json/overview" - payload, err := i.get(url, true) - if err != nil { - return health, err + endpoint := "json/overview" + statusCode, payload, err := i.get(endpoint, true) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + return "", err } overview := &hp.Overview{} @@ -301,158 +318,183 @@ func (i *Ilo) Status() (health string, err error) { return overview.SystemHealth, err } -// Memory returns the total amount of memory of the server +// Returns the total amount of memory of the server. func (i *Ilo) Memory() (mem int, err error) { err = i.httpLogin() if err != nil { - return mem, err + return 0, err } - url := "json/mem_info" - payload, err := i.get(url, true) - if err != nil { - return mem, err + endpoint := "json/mem_info" + statusCode, payload, err := i.get(endpoint, true) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + return 0, err } hpMemData := &hp.Mem{} err = json.Unmarshal(payload, hpMemData) if err != nil { - return mem, err + return 0, err } if hpMemData.MemTotalMemSize != 0 { - return hpMemData.MemTotalMemSize / 1024, err + return hpMemData.MemTotalMemSize / 1024, nil } for _, slot := range hpMemData.Memory { mem = mem + slot.MemSize } - return mem / 1024, err + return mem / 1024, nil } -// CPU returns the cpu, cores and hyperthreads of the server +// Finds the CPUs. +// Returns the description, cores count, and hyperthreads count of the first CPU it finds. +// Returns also the CPU count. +// TODO: Does this make any sense?! We either return all the information about all CPUs, or just say something generic! func (i *Ilo) CPU() (cpu string, cpuCount int, coreCount int, hyperthreadCount int, err error) { err = i.httpLogin() if err != nil { - return cpu, cpuCount, coreCount, hyperthreadCount, err + return "", 0, 0, 0, err } - url := "json/proc_info" - payload, err := i.get(url, true) - if err != nil { - return cpu, cpuCount, coreCount, hyperthreadCount, err + endpoint := "json/proc_info" + statusCode, payload, err := i.get(endpoint, true) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + return "", 0, 0, 0, err } hpProcData := &hp.Procs{} err = json.Unmarshal(payload, hpProcData) if err != nil { - return cpu, cpuCount, coreCount, hyperthreadCount, err + return "", 0, 0, 0, err } for _, proc := range hpProcData.Processors { - return httpclient.StandardizeProcessorName(proc.ProcName), len(hpProcData.Processors), proc.ProcNumCores, proc.ProcNumThreads, err + return httpclient.StandardizeProcessorName(proc.ProcName), len(hpProcData.Processors), proc.ProcNumCores, proc.ProcNumThreads, nil } return cpu, cpuCount, coreCount, hyperthreadCount, err } -// BiosVersion returns the current version of the bios +// Returns the current version of the BIOS. func (i *Ilo) BiosVersion() (version string, err error) { err = i.httpLogin() if err != nil { - return version, err + return "", err } - url := "json/overview" - payload, err := i.get(url, true) - if err != nil { - return version, err + endpoint := "json/overview" + statusCode, payload, err := i.get(endpoint, true) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + return "", err } overview := &hp.Overview{} err = json.Unmarshal(payload, overview) if err != nil { - return version, err + return "", err } if overview.SystemRom != "" { - return overview.SystemRom, err + return overview.SystemRom, nil } - return version, errors.ErrBiosNotFound + return "", errors.ErrBiosNotFound } // PowerKw returns the current power usage in Kw func (i *Ilo) PowerKw() (power float64, err error) { err = i.httpLogin() if err != nil { - return power, err + return 0, err } - url := "json/power_summary" - payload, err := i.get(url, true) - if err != nil { - return power, err + endpoint := "json/power_summary" + statusCode, payload, err := i.get(endpoint, true) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + return 0, err } hpPowerSummary := &hp.PowerSummary{} err = json.Unmarshal(payload, hpPowerSummary) if err != nil { - return power, err + return 0, err } - return float64(hpPowerSummary.PowerSupplyInputPower) / 1024, err + return float64(hpPowerSummary.PowerSupplyInputPower) / 1024, nil } // PowerState returns the current power state of the machine func (i *Ilo) PowerState() (state string, err error) { err = i.httpLogin() if err != nil { - return state, err + return "", err } - url := "json/power_summary" - payload, err := i.get(url, true) - if err != nil { - return state, err + endpoint := "json/power_summary" + statusCode, payload, err := i.get(endpoint, true) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + return "", err } hpPowerSummary := &hp.PowerSummary{} err = json.Unmarshal(payload, hpPowerSummary) if err != nil { - return state, err + return "", err } - return strings.ToLower(hpPowerSummary.HostpwrState), err + return strings.ToLower(hpPowerSummary.HostpwrState), nil } -// TempC returns the current temperature of the machine +// Returns the current temperature of the server. func (i *Ilo) TempC() (temp int, err error) { err = i.httpLogin() if err != nil { - return temp, err + return 0, err } - url := "json/health_temperature" - payload, err := i.get(url, true) - if err != nil { - return temp, err + endpoint := "json/health_temperature" + statusCode, payload, err := i.get(endpoint, true) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + return 0, err } hpHealthTemperature := &hp.HealthTemperature{} err = json.Unmarshal(payload, hpHealthTemperature) if err != nil { - return temp, err + return 0, err } for _, item := range hpHealthTemperature.Temperature { if item.Location == "Ambient" { - return item.Currentreading, err + return item.Currentreading, nil } } - return temp, err + return 0, errors.ErrFeatureUnavailable } // Nics returns all found Nics in the device @@ -480,26 +522,30 @@ func (i *Ilo) Nics() (nics []*devices.Nic, err error) { return nics, err } -// License returns the iLO's license information +// Returns the ILO's license information. func (i *Ilo) License() (name string, licType string, err error) { err = i.httpLogin() if err != nil { - return name, licType, err + return "", "", err } - url := "json/license" - payload, err := i.get(url, true) - if err != nil { - return name, licType, err + endpoint := "json/license" + statusCode, payload, err := i.get(endpoint, true) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + return "", "", err } hpIloLicense := &hp.IloLicense{} err = json.Unmarshal(payload, hpIloLicense) if err != nil { - return name, licType, err + return "", "", err } - return hpIloLicense.Name, hpIloLicense.Type, err + return hpIloLicense.Name, hpIloLicense.Type, nil } func (i *Ilo) parseChassisInfo() (*hp.ChassisInfo, error) { @@ -510,8 +556,8 @@ func (i *Ilo) parseChassisInfo() (*hp.ChassisInfo, error) { chassisInfo := &hp.ChassisInfo{} // We try the new way of doing things first (RedFish). - payload, err := i.get(hp.ChassisInfoNewURL, false) - if err == nil { + statusCode, payload, err := i.get(hp.ChassisInfoNewURL, false) + if err == nil && statusCode == 200 { err = json.Unmarshal(payload, chassisInfo) if err != nil { return nil, err @@ -526,10 +572,15 @@ func (i *Ilo) parseChassisInfo() (*hp.ChassisInfo, error) { if chassisInfo.Links.ContainedBy.ID == "/"+hp.ChassisInfoChassisURL { chassisInfo.ChassisType = "Blade" - payload, err = i.get(hp.ChassisInfoChassisURL, false) - if err != nil { + statusCode, payload, err = i.get(hp.ChassisInfoChassisURL, false) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, hp.ChassisInfoChassisURL) + } + return nil, err } + chassisExtendedInfo := &hp.ChassisInfo{} err = json.Unmarshal(payload, chassisExtendedInfo) if err != nil { @@ -554,8 +605,12 @@ func (i *Ilo) parseChassisInfo() (*hp.ChassisInfo, error) { } // This just means that we have to try the old way of doing things, since RedFish is not available. - payload, err = i.get(hp.ChassisInfoOldURL, true) - if err != nil { + statusCode, payload, err = i.get(hp.ChassisInfoOldURL, true) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, hp.ChassisInfoOldURL) + } + return nil, err } @@ -574,9 +629,13 @@ func (i *Ilo) Psus() (psus []*devices.Psu, err error) { return psus, err } - url := "json/power_supplies" - payload, err := i.get(url, true) - if err != nil { + endpoint := "json/power_supplies" + statusCode, payload, err := i.get(endpoint, true) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + return psus, err } @@ -617,9 +676,13 @@ func (i *Ilo) Disks() (disks []*devices.Disk, err error) { return disks, err } - url := "json/health_phy_drives" - payload, err := i.get(url, true) - if err != nil { + endpoint := "json/health_phy_drives" + statusCode, payload, err := i.get(endpoint, true) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + return disks, err } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/model.go b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/model.go index e5b39332..6714c5ea 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/model.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/model.go @@ -11,7 +11,7 @@ type DirectoryGroupAccts struct { } // LicenseInfo declares License information payload. -//POST https://10.183.244.173/json/license_info +// POST https://10.183.244.173/json/license_info type LicenseInfo struct { Key string `json:"key,omitempty"` Method string `json:"method,omitempty"` @@ -33,7 +33,7 @@ type UserInfo struct { ConfigPriv int `json:"config_priv,omitempty"` UserPriv int `json:"user_priv,omitempty"` LoginPriv int `json:"login_priv,omitempty"` - Method string `json:"method"` //mod_user, add_user, del_user + Method string `json:"method"` // mod_user, add_user, del_user UserID int `json:"user_id,omitempty"` SessionKey string `json:"session_key,omitempty"` } @@ -45,7 +45,7 @@ type UserInfo struct { type RemoteSyslog struct { SyslogEnable int `json:"syslog_enable"` SyslogPort int `json:"syslog_port"` - Method string `json:"method"` //syslog_save, + Method string `json:"method"` // syslog_save SyslogServer string `json:"syslog_server"` SessionKey string `json:"session_key,omitempty"` } @@ -67,9 +67,9 @@ type NetworkSntp struct { Sdn2WCount int `json:"sdn2_wcount"` SntpServer1 string `json:"sntp_server1"` SntpServer2 string `json:"sntp_server2"` - TimePropagate int `json:"time_propagate"` //propagate time from OA to blade - OurZone int `json:"our_zone"` //368 - see Timezones - Method string `json:"method"` //set_sntp + TimePropagate int `json:"time_propagate"` // propagate time from OA to blade + OurZone int `json:"our_zone"` // 368 - see Timezones + Method string `json:"method"` // set_sntp SessionKey string `json:"session_key,omitempty"` } @@ -81,7 +81,7 @@ type Directory struct { ServerPort int `json:"server_port"` UserContexts []string `json:"user_contexts"` AuthenticationEnabled int `json:"authentication_enabled"` - LocalUserAcct int `json:"local_user_acct"` //enable local user accounts + LocalUserAcct int `json:"local_user_acct"` // enable local user accounts EnableGroupAccount int `json:"enable_group_acct"` EnableKerberos int `json:"enable_kerberos"` KerberosKdcAddress string `json:"kerberos_kdc_address,omitempty"` @@ -96,7 +96,7 @@ type Directory struct { //{"dn":"cn=hp,cn=bmcUsers","new_dn":"cn=hp,cn=bmcUsers","sid":"","login_priv":1,"remote_cons_priv":1,"virtual_media_priv":1,"reset_priv":1,"config_priv":0,"user_priv":0,"method":"mod_group","session_key":"bc2dae77e36a45fbeffce0bddd2ccabe"} type DirectoryGroups struct { Dn string `json:"dn"` - NewDn string `json:"new_dn,omitempty"` //same as Dn, unless being modified + NewDn string `json:"new_dn,omitempty"` // same as Dn, unless being modified Sid string `json:"sid,omitempty"` LoginPriv int `json:"login_priv,omitempty"` RemoteConsPriv int `json:"remote_cons_priv,omitempty"` @@ -104,7 +104,7 @@ type DirectoryGroups struct { ResetPriv int `json:"reset_priv,omitempty"` ConfigPriv int `json:"config_priv,omitempty"` UserPriv int `json:"user_priv,omitempty"` - Method string `json:"method"` //add_group, mod_group, del_group + Method string `json:"method"` // add_group, mod_group, del_group SessionKey string `json:"session_key"` } @@ -256,7 +256,7 @@ var TimezonesIlo5 = map[string]int{ } // TimezonesIlo4 declares valid timezones. -//Important timezone ints taken from https://10.193.251.48/html/network_sntp.html?intf=0 +// Important timezone ints taken from https://10.193.251.48/html/network_sntp.html?intf=0 var TimezonesIlo4 = map[string]int{ "CET": 368, "CST6CDT": 371, diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/query.go b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/query.go index 5e48eaf9..f2d95b78 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/query.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/query.go @@ -4,11 +4,11 @@ import ( "crypto/tls" "crypto/x509" "encoding/json" + "fmt" "net" "time" "github.com/bmc-toolbox/bmclib/errors" - "github.com/bmc-toolbox/bmclib/internal" "github.com/bmc-toolbox/bmclib/internal/helper" ) @@ -16,13 +16,11 @@ import ( // The bool value returned indicates if the BMC supports CSR generation. // CurrentHTTPSCert implements the Configure interface func (i *Ilo) CurrentHTTPSCert() ([]*x509.Certificate, bool, error) { - dialer := &net.Dialer{ Timeout: time.Duration(10) * time.Second, } conn, err := tls.DialWithDialer(dialer, "tcp", i.ip+":"+"443", &tls.Config{InsecureSkipVerify: true}) - if err != nil { return []*x509.Certificate{{}}, true, err } @@ -30,228 +28,216 @@ func (i *Ilo) CurrentHTTPSCert() ([]*x509.Certificate, bool, error) { defer conn.Close() return conn.ConnectionState().PeerCertificates, true, nil - } // Screenshot returns a thumbnail of video display from the bmc. func (i *Ilo) Screenshot() (response []byte, extension string, err error) { + // Screen thumbnails are only available in ILO5. + if i.HardwareType() != "ilo5" { + return nil, "", errors.ErrFeatureUnavailable + } + err = i.httpLogin() if err != nil { - return response, extension, err + return nil, "", err } endpoint := "images/thumbnail.bmp" - extension = "bmp" - - // screen thumbnails are only available in ilo5. - if i.HardwareType() != "ilo5" { - return response, extension, errors.ErrFeatureUnavailable - } + statusCode, response, err := i.get(endpoint, true) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } - response, err = i.get(endpoint, true) - if err != nil { - return []byte{}, extension, err + return nil, "", err } - return response, extension, err + return response, "bmp", nil } -func (i *Ilo) queryDirectoryGroups() (directoryGroups []DirectoryGroups, err error) { - +func (i *Ilo) queryDirectoryGroups() ([]DirectoryGroups, error) { endpoint := "json/directory_groups" + statusCode, payload, err := i.get(endpoint, true) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } - payload, err := i.get(endpoint, true) - if err != nil { - msg := "GET request failed." - i.log.V(1).Info(msg, + i.log.V(1).Error(err, "queryDirectoryGroups(): GET request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "endpoint", endpoint, "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) - return directoryGroups, err + return nil, err } var directoryGroupAccts DirectoryGroupAccts - //fmt.Printf("--> %+v\n", userinfo["users"]) err = json.Unmarshal(payload, &directoryGroupAccts) if err != nil { - msg := "Unable to unmarshal payload." - i.log.V(1).Info(msg, + msg := "queryDirectoryGroups(): Unable to unmarshal payload." + i.log.V(1).Error(err, msg, "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) - return directoryGroups, err + return nil, err } - return directoryGroupAccts.Groups, err + return directoryGroupAccts.Groups, nil } -func (i *Ilo) queryUsers() (usersInfo []UserInfo, err error) { - +func (i *Ilo) queryUsers() ([]UserInfo, error) { endpoint := "json/user_info" - - payload, err := i.get(endpoint, true) - if err != nil { - msg := "GET request failed." - i.log.V(1).Info(msg, + statusCode, payload, err := i.get(endpoint, true) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + i.log.V(1).Error(err, "queryUsers(): GET request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "endpoint", endpoint, "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) - return usersInfo, err + return nil, err } var users Users - //fmt.Printf("--> %+v\n", userinfo["users"]) err = json.Unmarshal(payload, &users) if err != nil { msg := "Unable to unmarshal payload." - i.log.V(1).Info(msg, + i.log.V(1).Error(err, msg, "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "resource", "User", "step", "queryUserInfo", - "Error", internal.ErrStringOrEmpty(err), ) - return usersInfo, err + return nil, err } - return users.UsersInfo, err + return users.UsersInfo, nil } func (i *Ilo) queryNetworkSntp() (networkSntp NetworkSntp, err error) { - endpoint := "json/network_sntp/interface/0" + statusCode, payload, err := i.get(endpoint, true) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } - payload, err := i.get(endpoint, true) - if err != nil { - msg := "GET request failed." - i.log.V(1).Info(msg, + i.log.V(1).Error(err, "queryNetworkSntp(): GET request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "endpoint", endpoint, "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) return networkSntp, err } err = json.Unmarshal(payload, &networkSntp) if err != nil { - msg := "Unable to unmarshal payload." - i.log.V(1).Info(msg, + msg := "queryNetworkSntp(): Unable to unmarshal payload." + i.log.V(1).Error(err, msg, "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) return networkSntp, err } - return networkSntp, err + return networkSntp, nil } -func (i *Ilo) queryAccessSettings() (AccessSettings, error) { - +func (i *Ilo) queryAccessSettings() (accessSettings AccessSettings, err error) { endpoint := "json/access_settings" + statusCode, payload, err := i.get(endpoint, true) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } - var accessSettings AccessSettings - - payload, err := i.get(endpoint, true) - if err != nil { - msg := "GET request failed." - i.log.V(1).Info(msg, + i.log.V(1).Error(err, "queryAccessSettings(): GET request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "endpoint", endpoint, "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) return accessSettings, err } err = json.Unmarshal(payload, &accessSettings) if err != nil { - msg := "Unable to unmarshal payload." - i.log.V(1).Info(msg, + msg := "queryAccessSettings(): Unable to unmarshal payload." + i.log.V(1).Error(err, msg, "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) return accessSettings, err } - return accessSettings, err + return accessSettings, nil } -func (i *Ilo) queryNetworkIPv4() (NetworkIPv4, error) { - +func (i *Ilo) queryNetworkIPv4() (networkIPv4 NetworkIPv4, err error) { endpoint := "json/network_ipv4/interface/0" + statusCode, payload, err := i.get(endpoint, true) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } - var networkIPv4 NetworkIPv4 - - payload, err := i.get(endpoint, true) - if err != nil { - msg := "GET request failed." - i.log.V(1).Info(msg, + i.log.V(1).Error(err, "queryNetworkIPv4(): GET request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "endpoint", endpoint, "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) return networkIPv4, err } err = json.Unmarshal(payload, &networkIPv4) if err != nil { - msg := "Unable to unmarshal payload." - i.log.V(1).Info(msg, + i.log.V(1).Error(err, "queryNetworkIPv4(): Unable to unmarshal payload.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) return networkIPv4, err } - return networkIPv4, err + return networkIPv4, nil } func (i *Ilo) queryPowerRegulator() (PowerRegulator, error) { - endpoint := "json/power_regulator" var powerRegulator PowerRegulator - payload, err := i.get(endpoint, true) - if err != nil { - msg := "GET request failed." - i.log.V(1).Info(msg, + statusCode, payload, err := i.get(endpoint, true) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the GET request to %s.", statusCode, endpoint) + } + + i.log.V(1).Error(err, "queryPowerRegulator(): GET request failed.", "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "endpoint", endpoint, "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) return PowerRegulator{}, err } err = json.Unmarshal(payload, &powerRegulator) if err != nil { - msg := "Unable to unmarshal payload." - i.log.V(1).Info(msg, + msg := "queryPowerRegulator(): Unable to unmarshal payload." + i.log.V(1).Error(err, msg, "IP", i.ip, - "Model", i.HardwareType(), + "HardwareType", i.HardwareType(), "step", helper.WhosCalling(), - "Error", internal.ErrStringOrEmpty(err), ) return PowerRegulator{}, err } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/setupConnection.go b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/setupConnection.go index bca99d05..d373f777 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/setupConnection.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/hp/ilo/setupConnection.go @@ -59,7 +59,7 @@ func (i *Ilo) httpLogin() (err error) { } if i.sessionKey == "" { - i.log.V(1).Info("Expected sessionKey cookie value not found.", "step", "Login()", "IP", i.ip, "Model", i.HardwareType()) + i.log.V(1).Info("Expected sessionKey cookie value not found.", "step", "Login()", "IP", i.ip, "HardwareType", i.HardwareType()) } if resp.StatusCode == 404 { @@ -110,7 +110,6 @@ func (i *Ilo) Close(ctx context.Context) error { respDump, _ := httputil.DumpResponse(resp, true) i.log.V(2).Info("responseTrace", "responseDump", string(respDump)) - } } } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox/actions.go b/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox/actions.go index bd6d8b76..897a0054 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox/actions.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox/actions.go @@ -71,6 +71,10 @@ func (s *SupermicroX) IsOn() (status bool, err error) { } // UpdateFirmware updates the bmc firmware -func (s *SupermicroX) UpdateFirmware(source, file string) (status bool, err error) { - return true, fmt.Errorf("not supported yet") +func (s *SupermicroX) UpdateFirmware(source, file string) (status bool, output string, err error) { + return false, "Not yet implemented", fmt.Errorf("not yet implemented") +} + +func (s *SupermicroX) CheckFirmwareVersion() (version string, err error) { + return "Not yet implemented", fmt.Errorf("not yet implemented") } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox/configure.go b/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox/configure.go index 1be51c0c..c81abe0f 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox/configure.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox/configure.go @@ -13,7 +13,6 @@ import ( "github.com/bmc-toolbox/bmclib/cfgresources" "github.com/bmc-toolbox/bmclib/devices" - "github.com/bmc-toolbox/bmclib/internal" "github.com/bmc-toolbox/bmclib/internal/helper" "github.com/google/go-querystring/query" @@ -67,7 +66,6 @@ func timezoneToUtcOffset(location *time.Location) (offset int) { // Return bool value if the role is valid. func (s *SupermicroX) isRoleValid(role string) bool { - validRoles := []string{"admin", "user"} for _, v := range validRoles { if role == v { @@ -80,11 +78,10 @@ func (s *SupermicroX) isRoleValid(role string) bool { // returns a map of user accounts and their ids func (s *SupermicroX) queryUserAccounts() (userAccounts map[int]string, err error) { - userAccounts = make(map[int]string) ipmi, err := s.query("CONFIG_INFO.XML=(0,0)") if err != nil { - s.log.V(1).Info("error querying user accounts", "error", internal.ErrStringOrEmpty(err)) + s.log.V(1).Error(err, "queryUserAccounts(): Error querying user accounts.") return userAccounts, err } @@ -92,7 +89,7 @@ func (s *SupermicroX) queryUserAccounts() (userAccounts map[int]string, err erro userAccounts[idx] = account.Name } - return userAccounts, err + return userAccounts, nil } // User applies the User configuration resource, @@ -101,11 +98,14 @@ func (s *SupermicroX) queryUserAccounts() (userAccounts map[int]string, err erro // supermicro user accounts start with 1, account 0 which is a large empty string :\. // nolint: gocyclo func (s *SupermicroX) User(users []*cfgresources.User) (err error) { - currentUsers, err := s.queryUserAccounts() if err != nil { - msg := "Unable to query current user accounts." - s.log.V(1).Info(msg, "ip", s.ip, "model", s.HardwareType(), "step", helper.WhosCalling(), "error", internal.ErrStringOrEmpty(err)) + msg := "SupermicroX User(): Unable to query existing users." + s.log.V(1).Error(err, msg, + "ip", s.ip, + "HardwareType", s.HardwareType(), + "step", helper.WhosCalling(), + ) return errors.New(msg) } @@ -163,18 +163,23 @@ func (s *SupermicroX) User(users []*cfgresources.User) (err error) { form, _ := query.Values(configUser) statusCode, err := s.post(endpoint, &form, []byte{}, "") if err != nil || statusCode != 200 { - msg := "POST request to set User config returned error." - s.log.V(1).Info(msg, + if err == nil { + err = fmt.Errorf("Received a %d status code from the POST request to %s.", statusCode, endpoint) + } else { + err = fmt.Errorf("POST request to %s failed with error: %s", endpoint, err.Error()) + } + + s.log.V(1).Error(err, "POST request to set User config failed.", "ip", s.ip, - "model", s.HardwareType(), + "HardwareType", s.HardwareType(), "endpoint", endpoint, - "statusCode", statusCode, + "StatusCode", statusCode, "step", helper.WhosCalling(), - "error", internal.ErrStringOrEmpty(err)) - return errors.New(msg) + ) + return err } - s.log.V(1).Info("User parameters applied.", "ip", s.ip, "model", s.HardwareType(), "user", user.Name) + s.log.V(1).Info("User parameters applied.", "ip", s.ip, "HardwareType", s.HardwareType(), "user", user.Name) } return err @@ -183,7 +188,6 @@ func (s *SupermicroX) User(users []*cfgresources.User) (err error) { // Network method implements the Configure interface // applies various network parameters. func (s *SupermicroX) Network(cfg *cfgresources.Network) (reset bool, err error) { - sshPort := 22 if cfg.SSHPort != 0 && cfg.SSHPort != sshPort { @@ -213,47 +217,51 @@ func (s *SupermicroX) Network(cfg *cfgresources.Network) (reset bool, err error) form, _ := query.Values(configPort) statusCode, err := s.post(endpoint, &form, []byte{}, "") if err != nil || statusCode != 200 { - msg := "POST request to set Port config returned error." - s.log.V(1).Info(msg, + if err == nil { + err = fmt.Errorf("Received a %d status code from the POST request to %s.", statusCode, endpoint) + } else { + err = fmt.Errorf("POST request to %s failed with error: %s", endpoint, err.Error()) + } + + s.log.V(1).Error(err, "POST request to set Port config failed.", "ip", s.ip, - "model", s.HardwareType(), + "HardwareType", s.HardwareType(), "endpoint", endpoint, - "statusCode", statusCode, + "StatusCode", statusCode, "step", helper.WhosCalling(), - "error", internal.ErrStringOrEmpty(err)) - return reset, errors.New(msg) + ) + return false, err } - s.log.V(1).Info("Network config parameters applied.", "ip", s.ip, "model", s.HardwareType()) - return reset, err + s.log.V(1).Info("Network config parameters applied.", "ip", s.ip, "HardwareType", s.HardwareType()) + return false, err } // Ntp applies NTP configuration params // Ntp implements the Configure interface. func (s *SupermicroX) Ntp(cfg *cfgresources.Ntp) (err error) { - var enable string if cfg.Server1 == "" { s.log.V(1).Info("NTP resource expects parameter: server1.", "step", "applyNtpParams", - "model", s.HardwareType()) + "HardwareType", s.HardwareType()) return } if cfg.Timezone == "" { s.log.V(1).Info("NTP resource expects parameter: timezone.", "step", "applyNtpParams", - "model", s.HardwareType()) + "HardwareType", s.HardwareType()) return } tzLocation, err := time.LoadLocation(cfg.Timezone) if err != nil { - s.log.V(1).Info("NTP resource declared parameter timezone invalid.", + s.log.V(1).Error(err, "Ntp(): Invalid timezone parameter.", "step", "applyNtpParams", - "model", s.HardwareType(), - "declaredTtimezone", cfg.Timezone, - "error", internal.ErrStringOrEmpty(err)) + "HardwareType", s.HardwareType(), + "Timezone", cfg.Timezone, + ) return } @@ -262,14 +270,14 @@ func (s *SupermicroX) Ntp(cfg *cfgresources.Ntp) (err error) { if !cfg.Enable { s.log.V(1).Info("Ntp resource declared with enable: false.", "step", "applyNtpParams", - "model", s.HardwareType()) + "HardwareType", s.HardwareType()) return } enable = "on" t := time.Now().In(tzLocation) - //Fri Jun 06 2018 14:28:25 GMT+0100 (CET) + // Fri Jun 06 2018 14:28:25 GMT+0100 (CET) ts := fmt.Sprintf("%s %d %d:%d:%d %s (%s)", t.Format("Fri Jun 01"), t.Year(), @@ -282,7 +290,7 @@ func (s *SupermicroX) Ntp(cfg *cfgresources.Ntp) (err error) { configDateTime := ConfigDateTime{ Op: "config_date_time", Timezone: tzUtcOffset, - DstEn: false, //daylight savings + DstEn: false, Enable: enable, NtpServerPrimary: cfg.Server1, NtpServerSecondary: cfg.Server2, @@ -299,21 +307,26 @@ func (s *SupermicroX) Ntp(cfg *cfgresources.Ntp) (err error) { form, _ := query.Values(configDateTime) statusCode, err := s.post(endpoint, &form, []byte{}, "") if err != nil || statusCode != 200 { - msg := "POST request to set Syslog config returned error." - s.log.V(1).Info(msg, + if err == nil { + err = fmt.Errorf("Received a %d status code from the POST request to %s.", statusCode, endpoint) + } else { + err = fmt.Errorf("POST request to %s failed with error: %s", endpoint, err.Error()) + } + + s.log.V(1).Error(err, "POST request to set NTP config failed.", "ip", s.ip, - "model", s.HardwareType(), + "HardwareType", s.HardwareType(), "endpoint", endpoint, - "statusCode", statusCode, + "StatusCode", statusCode, "step", helper.WhosCalling(), - "error", internal.ErrStringOrEmpty(err)) - return errors.New(msg) + ) + return err } s.log.V(1).Info("NTP config parameters applied.", "ip", s.ip, - "model", s.HardwareType()) - return err + "HardwareType", s.HardwareType()) + return nil } // Ldap applies LDAP configuration params. @@ -324,55 +337,47 @@ func (s *SupermicroX) Ldap(cfgLdap *cfgresources.Ldap) error { return nil } -// LdapGroup applies LDAP and LDAP Group/Role related configuration, -// LdapGroup implements the Configure interface. +// LdapGroups applies LDAP and LDAP Group/Role related configuration, +// LdapGroups implements the Configure interface. // Supermicro does not have any separate configuration for Ldap groups just for generic ldap // nolint: gocyclo -func (s *SupermicroX) LdapGroup(cfgGroup []*cfgresources.LdapGroup, cfgLdap *cfgresources.Ldap) (err error) { - - var enable string - +func (s *SupermicroX) LdapGroups(cfgGroups []*cfgresources.LdapGroup, cfgLdap *cfgresources.Ldap) (err error) { if cfgLdap.Server == "" { msg := "Ldap resource parameter Server required but not declared." - s.log.V(1).Info(msg, "step", helper.WhosCalling(), "model", s.HardwareType()) + s.log.V(1).Info(msg, "step", helper.WhosCalling(), "HardwareType", s.HardwareType()) return errors.New(msg) } - //first some preliminary checks if cfgLdap.Port == 0 { msg := "Ldap resource parameter Port required but not declared" s.log.V(1).Info(msg, "step", helper.WhosCalling(), - "model", s.HardwareType()) + "HardwareType", s.HardwareType()) return errors.New(msg) } if !cfgLdap.Enable { s.log.V(1).Info("Ldap resource declared with enable: false.", "step", helper.WhosCalling(), - "model", s.HardwareType()) + "HardwareType", s.HardwareType()) return } - enable = "on" - if cfgLdap.BaseDn == "" { msg := "Ldap resource parameter BaseDn required but not declared." - s.log.V(1).Info(msg, "step", helper.WhosCalling(), "model", s.HardwareType()) + s.log.V(1).Info(msg, "step", helper.WhosCalling(), "HardwareType", s.HardwareType()) return errors.New(msg) } serverIP, err := net.LookupIP(cfgLdap.Server) if err != nil || serverIP == nil { msg := "Unable to lookup the IP for ldap server hostname." - s.log.V(1).Info(msg, "step", helper.WhosCalling(), "model", s.HardwareType()) + s.log.V(1).Info(msg, "step", helper.WhosCalling(), "HardwareType", s.HardwareType()) return errors.New(msg) } - //for each ldap group setup config - //since supermicro can work with just one Searchbase, we go with the 'user' role group - for _, group := range cfgGroup { - + // Since SuperMicro can work with just one search base, we go with the "user" role group. + for _, group := range cfgGroups { if !group.Enable { continue } @@ -410,32 +415,38 @@ func (s *SupermicroX) LdapGroup(cfgGroup []*cfgresources.LdapGroup, cfgLdap *cfg configLdap := ConfigLdap{ Op: "config_ldap", - Enable: enable, + Enable: "on", EnableSsl: true, LdapIP: string(serverIP[0]), BaseDn: group.Group, LdapPort: cfgLdap.Port, BindDn: cfgLdap.BindDn, - BindPassword: "********", //default value + BindPassword: "********", // default value } endpoint := "op.cgi" form, _ := query.Values(configLdap) statusCode, err := s.post(endpoint, &form, []byte{}, "") if err != nil || statusCode != 200 { - msg := "POST request to set Ldap config returned error." - s.log.V(1).Info(msg, + if err == nil { + err = fmt.Errorf("Received a %d status code from the POST request to %s.", statusCode, endpoint) + } else { + err = fmt.Errorf("POST request to %s failed with error: %s", endpoint, err.Error()) + } + + s.log.V(1).Error(err, "POST request to set LDAP group config failed.", "step", helper.WhosCalling(), "ip", s.ip, - "model", s.HardwareType(), + "HardwareType", s.HardwareType(), "endpoint", endpoint, - "statusCode", statusCode, - "error", internal.ErrStringOrEmpty(err)) - return errors.New(msg) + "StatusCode", statusCode, + "Group", group.Group, + ) + return err } } - s.log.V(1).Info("Ldap config parameters applied.", "ip", s.ip, "model", s.HardwareType()) + s.log.V(1).Info("LDAP config parameters applied.", "ip", s.ip, "HardwareType", s.HardwareType()) return err } @@ -443,18 +454,17 @@ func (s *SupermicroX) LdapGroup(cfgGroup []*cfgresources.LdapGroup, cfgLdap *cfg // Syslog implements the Configure interface // this also enables alerts from the BMC func (s *SupermicroX) Syslog(cfg *cfgresources.Syslog) (err error) { - var port int if cfg.Server == "" { msg := "Syslog resource expects parameter: Server." - s.log.V(1).Info(msg, "step", helper.WhosCalling(), "model", s.HardwareType()) + s.log.V(1).Info(msg, "step", helper.WhosCalling(), "HardwareType", s.HardwareType()) return errors.New(msg) } if cfg.Port == 0 { msg := "Syslog resource port set to default: 514." - s.log.V(1).Info(msg, "step", helper.WhosCalling(), "model", s.HardwareType()) + s.log.V(1).Info(msg, "step", helper.WhosCalling(), "HardwareType", s.HardwareType()) port = 514 } else { port = cfg.Port @@ -462,13 +472,13 @@ func (s *SupermicroX) Syslog(cfg *cfgresources.Syslog) (err error) { if !cfg.Enable { msg := "Syslog resource declared with disable." - s.log.V(1).Info(msg, "step", helper.WhosCalling(), "model", s.HardwareType()) + s.log.V(1).Info(msg, "step", helper.WhosCalling(), "HardwareType", s.HardwareType()) } serverIP, err := net.LookupIP(cfg.Server) if err != nil || serverIP == nil { msg := "Unable to lookup IP for syslog server hostname, yes supermicros requires the Syslog server IP :|." - s.log.V(1).Info(msg, "step", helper.WhosCalling(), "model", s.HardwareType()) + s.log.V(1).Info(msg, "step", helper.WhosCalling(), "HardwareType", s.HardwareType()) return errors.New(msg) } @@ -482,18 +492,22 @@ func (s *SupermicroX) Syslog(cfg *cfgresources.Syslog) (err error) { endpoint := "op.cgi" form, _ := query.Values(configSyslog) - //returns okStarting Syslog daemon if successful statusCode, err := s.post(endpoint, &form, []byte{}, "") if err != nil || statusCode != 200 { - msg := "POST request to set Syslog config returned error." - s.log.V(1).Info(msg, + if err == nil { + err = fmt.Errorf("Received a %d status code from the POST request to %s.", statusCode, endpoint) + } else { + err = fmt.Errorf("POST request to %s failed with error: %s", endpoint, err.Error()) + } + + s.log.V(1).Error(err, "POST request to set Syslog config returned error.", "step", helper.WhosCalling(), "ip", s.ip, - "model", s.HardwareType(), + "HardwareType", s.HardwareType(), "endpoint", endpoint, - "statusCode", statusCode, - "error", internal.ErrStringOrEmpty(err)) - return errors.New(msg) + "StatusCode", statusCode, + ) + return err } // enable maintenance events @@ -504,18 +518,23 @@ func (s *SupermicroX) Syslog(cfg *cfgresources.Syslog) (err error) { statusCode, err = s.post(endpoint, &form, []byte{}, "") if err != nil || statusCode != 200 { - msg := "POST request to enable maintenance alerts returned error." - s.log.V(1).Info(msg, + if err == nil { + err = fmt.Errorf("Received a %d status code from the POST request to %s.", statusCode, endpoint) + } else { + err = fmt.Errorf("POST request to %s failed with error: %s", endpoint, err.Error()) + } + + s.log.V(1).Error(err, "POST request to enable maintenance alerts failed.", "step", helper.WhosCalling(), "ip", s.ip, - "model", s.HardwareType(), + "HardwareType", s.HardwareType(), "endpoint", endpoint, - "statusCode", statusCode, - "error", internal.ErrStringOrEmpty(err)) - return errors.New(msg) + "StatusCode", statusCode, + ) + return err } - s.log.V(1).Info("Syslog config parameters applied.", "ip", s.ip, "model", s.HardwareType()) + s.log.V(1).Info("Syslog config parameters applied.", "ip", s.ip, "HardwareType", s.HardwareType()) return err } @@ -533,7 +552,6 @@ func (s *SupermicroX) GenerateCSR(cert *cfgresources.HTTPSCertAttributes) ([]byt // 4. delay for a second // 5. Request for the current: SSL_STATUS.XML (0,0) func (s *SupermicroX) UploadHTTPSCert(cert []byte, certFileName string, key []byte, keyFileName string) (bool, error) { - endpoint := "upload_ssl.cgi" // setup a buffer for our multipart form @@ -565,16 +583,19 @@ func (s *SupermicroX) UploadHTTPSCert(cert []byte, certFileName string, key []by w.Close() // 1. upload - status, err := s.post(endpoint, &url.Values{}, form.Bytes(), w.FormDataContentType()) - if err != nil || status != 200 { - msg := "Cert form upload POST request failed, expected 200." - s.log.V(1).Info(msg, + statusCode, err := s.post(endpoint, &url.Values{}, form.Bytes(), w.FormDataContentType()) + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("POST request to %s failed with status code %d.", endpoint, statusCode) + } + + s.log.V(1).Error(err, "UploadHTTPSCert(): Cert form upload POST request failed.", "step", helper.WhosCalling(), "ip", s.ip, - "model", s.HardwareType(), + "HardwareType", s.HardwareType(), "endpoint", endpoint, - "statusCode", status, - "error", internal.ErrStringOrEmpty(err)) + "StatusCode", statusCode, + ) return false, err } @@ -602,21 +623,24 @@ func (s *SupermicroX) UploadHTTPSCert(cert []byte, certFileName string, key []by // The second part of the certificate upload process, // we get the BMC to validate the uploaded SSL certificate. func (s *SupermicroX) validateSSL() error { - - var v = url.Values{} + v := url.Values{} v.Set("SSL_VALIDATE.XML", "(0,0)") - var endpoint = "ipmi.cgi" - status, err := s.post(endpoint, &v, []byte{}, "") - if err != nil || status != 200 { - msg := "Cert validate POST request failed, expected 200." - s.log.V(1).Info(msg, + endpoint := "ipmi.cgi" + statusCode, err := s.post(endpoint, &v, []byte{}, "") + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("POST request to %s failed with status code %d.", endpoint, statusCode) + } + + s.log.V(1).Error(err, "Cert validate POST request failed, expected 200.", "step", helper.WhosCalling(), "ip", s.ip, - "model", s.HardwareType(), + "HardwareType", s.HardwareType(), "endpoint", endpoint, - "statusCode", status, - "error", internal.ErrStringOrEmpty(err)) + "StatusCode", statusCode, + ) + return err } @@ -627,21 +651,23 @@ func (s *SupermicroX) validateSSL() error { // Get the current status of the certificate. // POST https://10.193.251.43/cgi/ipmi.cgi SSL_STATUS.XML: (0,0) func (s *SupermicroX) statusSSL() error { - - var v = url.Values{} + v := url.Values{} v.Add("SSL_STATUS.XML", "(0,0)") - var endpoint = "ipmi.cgi" - status, err := s.post(endpoint, &v, []byte{}, "") - if err != nil || status != 200 { - msg := "Cert status POST request failed, expected 200." - s.log.V(1).Info(msg, + endpoint := "ipmi.cgi" + statusCode, err := s.post(endpoint, &v, []byte{}, "") + if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("POST request to %s failed with status code %d.", endpoint, statusCode) + } + + s.log.V(1).Error(err, "statusSSL(): Cert status POST request failed.", "step", helper.WhosCalling(), "ip", s.ip, - "model", s.HardwareType(), + "HardwareType", s.HardwareType(), "endpoint", endpoint, - "statusCode", status, - "error", internal.ErrStringOrEmpty(err)) + "StatusCode", statusCode, + ) return err } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox/model.go b/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox/model.go index ef2e4b98..3c21e570 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox/model.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox/model.go @@ -3,85 +3,85 @@ package supermicrox // ConfigSyslog declares payload to configure syslog parameters. // /cgi/op.cgi type ConfigSyslog struct { - Op string `url:"op"` //op=config_syslog - SyslogIP1 string `url:"syslogip1"` //syslogip1=10.01.12.1 - SyslogIP2 string `url:"syslogip2"` //syslogip1=10.01.12.2 - SyslogIP3 string `url:"syslogip3"` //syslogip1=10.01.12.3 - SyslogPort1 int `url:"syslogport1"` //syslogport1=514 - SyslogPort2 int `url:"syslogport2"` //syslogport2=0 - SyslogPort3 int `url:"syslogport3"` //syslogport3=0 - Enable bool `url:"enable,int"` //enable=1 + Op string `url:"op"` // op=config_syslog + SyslogIP1 string `url:"syslogip1"` // syslogip1=10.01.12.1 + SyslogIP2 string `url:"syslogip2"` // syslogip1=10.01.12.2 + SyslogIP3 string `url:"syslogip3"` // syslogip1=10.01.12.3 + SyslogPort1 int `url:"syslogport1"` // syslogport1=514 + SyslogPort2 int `url:"syslogport2"` // syslogport2=0 + SyslogPort3 int `url:"syslogport3"` // syslogport3=0 + Enable bool `url:"enable,int"` // enable=1 } // ConfigDateTime declares payload to configure time parameters. // /cgi/op.cgi type ConfigDateTime struct { - Op string `url:"op"` //op=config_date_time - Timezone int `url:"timezone"` //timezone=-7200 - DstEn bool `url:"dst_en,int"` //dst_en=0 - Enable string `url:"ntp"` //ntp=on - NtpServerPrimary string `url:"ntp_server_pri"` //ntp_server_pri=ntp0.example.com - NtpServerSecondary string `url:"ntp_server_2nd"` //ntp_server_2nd=ntp1.example.com - Year int `url:"year"` //year=2018 - Month int `url:"month"` //month=6 - Day int `url:"day"` //day=1 - Hour int `url:"hour"` //hour=05 - Minute int `url:"min"` //min=49 - Second int `url:"sec"` //sec=42 - TimeStamp string `url:"time_stamp"` //time_stamp=Fri%20Jun%2001%202018%2009%3A58%3A19%20GMT%2B0200%20(CEST) + Op string `url:"op"` // op=config_date_time + Timezone int `url:"timezone"` // timezone=-7200 + DstEn bool `url:"dst_en,int"` // dst_en=0 + Enable string `url:"ntp"` // ntp=on + NtpServerPrimary string `url:"ntp_server_pri"` // ntp_server_pri=ntp0.example.com + NtpServerSecondary string `url:"ntp_server_2nd"` // ntp_server_2nd=ntp1.example.com + Year int `url:"year"` // year=2018 + Month int `url:"month"` // month=6 + Day int `url:"day"` // day=1 + Hour int `url:"hour"` // hour=05 + Minute int `url:"min"` // min=49 + Second int `url:"sec"` // sec=42 + TimeStamp string `url:"time_stamp"` // time_stamp=Fri%20Jun%2001%202018%2009%3A58%3A19%20GMT%2B0200%20(CEST) } // ConfigUser declares payload to configure User accounts. // /cgi/config_user.cgi type ConfigUser struct { Username string `url:"username"` - UserID int `url:"original_username"` //username integer + UserID int `url:"original_username"` // username integer Password string `url:"password,omitempty"` - NewPrivilege int `url:"new_privilege,omitempty"` //4 == administrator, 3 == operator + NewPrivilege int `url:"new_privilege,omitempty"` // 4 == administrator, 3 == operator } // ConfigLdap declares payload to configure LDAP. // /cgi/op.cgi type ConfigLdap struct { - Op string `url:"op"` //op=config_ldap - Enable string `url:"en_ldap"` //en_ldap=on - EnableSsl bool `url:"enSSL,int"` //enSSL=1 - LdapIP string `url:"ldapip"` //ldapip=10.252.13.5 - BaseDn string `url:"basedn"` //basedn=cn=Supermicro,cn=bmcUsers - LdapPort int `url:"ldapport"` //ldapport=636 - BindDn string `url:"bind_dn"` //bind_dn=undefined <- default value - BindPassword string `url:"bind_pwd"` //bind_pwd=******** <- default value + Op string `url:"op"` // op=config_ldap + Enable string `url:"en_ldap"` // en_ldap=on + EnableSsl bool `url:"enSSL,int"` // enSSL=1 + LdapIP string `url:"ldapip"` // ldapip=10.252.13.5 + BaseDn string `url:"basedn"` // basedn=cn=Supermicro,cn=bmcUsers + LdapPort int `url:"ldapport"` // ldapport=636 + BindDn string `url:"bind_dn"` // bind_dn=undefined <- default value + BindPassword string `url:"bind_pwd"` // bind_pwd=******** <- default value } // ConfigPort declares payload to configure services. type ConfigPort struct { - Op string `url:"op"` //op=config_port - HTTPPort int `url:"HTTP_PORT"` //HTTP_PORT=80 - HTTPSPort int `url:"HTTPS_PORT"` //HTTPS_PORT=443 - IkvmPort int `url:"IKVM_PORT"` //IKVM_PORT=5900 - VMPort int `url:"VM_PORT"` //VM_PORT=623 <- virtual media port - SSHPort int `url:"SSH_PORT"` //SSH_PORT=22 - WsmanPort int `url:"WSMAN_PORT"` //WSMAN_PORT=5985 - SnmpPort int `url:"SNMP_PORT"` //SNMP_PORT=161 - httpEnable bool `url:"HTTP_SERVICE,int"` //HTTP_SERVICE=1 - httpsEnable bool `url:"HTTPS_SERVICE,int"` //HTTPS_SERVICE=1 - IkvmEnable bool `url:"IKVM_SERVICE,int"` //IKVM_SERVICE=1 - VMEnable bool `url:"VM_SERVICE,int"` //VM_SERVICE=1 - SSHEnable bool `url:"SSH_SERVICE,int"` //SSH_SERVICE=1 - SnmpEnable bool `url:"SNMP_SERVICE,int"` //SNMP_SERVICE=1 - WsmanEnable bool `url:"WSMAN_SERVICE,int"` //WSMAN_SERVICE=0 - SslRedirectEnable bool `url:"SSL_REDIRECT,int"` //SSL_REDIRECT=1 + Op string `url:"op"` // op=config_port + HTTPPort int `url:"HTTP_PORT"` // HTTP_PORT=80 + HTTPSPort int `url:"HTTPS_PORT"` // HTTPS_PORT=443 + IkvmPort int `url:"IKVM_PORT"` // IKVM_PORT=5900 + VMPort int `url:"VM_PORT"` // VM_PORT=623 <- virtual media port + SSHPort int `url:"SSH_PORT"` // SSH_PORT=22 + WsmanPort int `url:"WSMAN_PORT"` // WSMAN_PORT=5985 + SnmpPort int `url:"SNMP_PORT"` // SNMP_PORT=161 + httpEnable bool `url:"HTTP_SERVICE,int"` // HTTP_SERVICE=1 + httpsEnable bool `url:"HTTPS_SERVICE,int"` // HTTPS_SERVICE=1 + IkvmEnable bool `url:"IKVM_SERVICE,int"` // IKVM_SERVICE=1 + VMEnable bool `url:"VM_SERVICE,int"` // VM_SERVICE=1 + SSHEnable bool `url:"SSH_SERVICE,int"` // SSH_SERVICE=1 + SnmpEnable bool `url:"SNMP_SERVICE,int"` // SNMP_SERVICE=1 + WsmanEnable bool `url:"WSMAN_SERVICE,int"` // WSMAN_SERVICE=0 + SslRedirectEnable bool `url:"SSL_REDIRECT,int"` // SSL_REDIRECT=1 } // CapturePreview declares payload to capture screen previews. type CapturePreview struct { - IkvmPreview string `url:"IKVM_PREVIEW.XML"` //IKVM_PREVIEW.XML=(0,0) - TimeStamp string `url:"time_stamp"` //time_stamp=Wed Oct 17 2018 15:56:08 GMT+0200 (CEST) + IkvmPreview string `url:"IKVM_PREVIEW.XML"` // IKVM_PREVIEW.XML=(0,0) + TimeStamp string `url:"time_stamp"` // time_stamp=Wed Oct 17 2018 15:56:08 GMT+0200 (CEST) } // URLRedirect declares payload sent when capturing screen previews type URLRedirect struct { - URLName string `url:"url_name"` //url_name=Snapshot - URLType string `url:"url_type"` //url_type=img - TimeStamp string `url:"time_stamp"` //time_stamp=Wed Oct 17 2018 15:56:08 GMT+0200 (CEST) + URLName string `url:"url_name"` // url_name=Snapshot + URLType string `url:"url_type"` // url_type=img + TimeStamp string `url:"time_stamp"` // time_stamp=Wed Oct 17 2018 15:56:08 GMT+0200 (CEST) } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox/query.go b/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox/query.go index 80a2a7f9..f3e2f073 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox/query.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox/query.go @@ -16,13 +16,11 @@ import ( // the bool value returned is set to true if the BMC support CSR generation. // CurrentHTTPSCert implements the Configure interface. func (s *SupermicroX) CurrentHTTPSCert() ([]*x509.Certificate, bool, error) { - dialer := &net.Dialer{ Timeout: time.Duration(10) * time.Second, } conn, err := tls.DialWithDialer(dialer, "tcp", s.ip+":"+"443", &tls.Config{InsecureSkipVerify: true}) - if err != nil { return []*x509.Certificate{{}}, false, err } @@ -30,7 +28,6 @@ func (s *SupermicroX) CurrentHTTPSCert() ([]*x509.Certificate, bool, error) { defer conn.Close() return conn.ConnectionState().PeerCertificates, false, nil - } // Screenshot returns a thumbnail of video display from the bmc. @@ -38,7 +35,6 @@ func (s *SupermicroX) CurrentHTTPSCert() ([]*x509.Certificate, bool, error) { // 2. sleep for 3 seconds to give ikvm time to ensure preview was captured // 3. request for preview. func (s *SupermicroX) Screenshot() (response []byte, extension string, err error) { - postEndpoint := "CapturePreview.cgi" getEndpoint := "cgi/url_redirect.cgi?" @@ -46,13 +42,13 @@ func (s *SupermicroX) Screenshot() (response []byte, extension string, err error // allow thumbnails only for supermicro x10s. if s.HardwareType() != "supermicrox" { - return response, extension, errors.ErrFeatureUnavailable + return nil, "", errors.ErrFeatureUnavailable } tzLocation, _ := time.LoadLocation("CET") t := time.Now().In(tzLocation) - //Fri Jun 06 2018 14:28:25 GMT+0100 (CET) + // Fri Jun 06 2018 14:28:25 GMT+0100 (CET) ts := fmt.Sprintf("%s %d %d:%d:%d %s (%s)", t.Format("Fri Jun 01"), t.Year(), @@ -70,15 +66,15 @@ func (s *SupermicroX) Screenshot() (response []byte, extension string, err error form, _ := query.Values(capturePreview) statusCode, err := s.post(postEndpoint, &form, []byte{}, "") if err != nil { - return response, extension, err + return nil, "", err } if statusCode != 200 { - return response, extension, fmt.Errorf("Non 200 response from endpoint") + return nil, "", fmt.Errorf("Non-200 response from endpoint %s: %d!", postEndpoint, statusCode) } time.Sleep(3 * time.Second) - //Fri Jun 06 2018 14:28:25 GMT+0100 (CET) + // Fri Jun 06 2018 14:28:25 GMT+0100 (CET) ts = fmt.Sprintf("%s %d %d:%d:%d %s (%s)", t.Format("Fri Jun 01"), t.Year(), @@ -99,8 +95,8 @@ func (s *SupermicroX) Screenshot() (response []byte, extension string, err error response, err = s.get(getEndpoint, false) if err != nil { - return []byte{}, extension, err + return nil, "", err } - return response, extension, err + return response, extension, nil } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox/supermicrox.go b/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox/supermicrox.go index 564c9cc6..81919cd3 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox/supermicrox.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox/supermicrox.go @@ -15,7 +15,6 @@ import ( "github.com/bmc-toolbox/bmclib/devices" "github.com/bmc-toolbox/bmclib/errors" - "github.com/bmc-toolbox/bmclib/internal" "github.com/bmc-toolbox/bmclib/internal/httpclient" "github.com/go-logr/logr" @@ -60,7 +59,8 @@ func New(ctx context.Context, ip string, username string, password string, log l username: username, password: password, ctx: ctx, - log: log}, err + log: log, + }, err } // CheckCredentials verify whether the credentials are valid or not @@ -127,7 +127,6 @@ func (s *SupermicroX) get(endpoint string, authentication bool) (payload []byte, // posts a urlencoded form to the given endpoint // nolint: gocyclo func (s *SupermicroX) post(endpoint string, urlValues *url.Values, form []byte, formDataContentType string) (statusCode int, err error) { - err = s.httpLogin() if err != nil { return statusCode, err @@ -141,15 +140,12 @@ func (s *SupermicroX) post(endpoint string, urlValues *url.Values, form []byte, var req *http.Request if formDataContentType == "" { - req, err = http.NewRequest("POST", u.String(), strings.NewReader(urlValues.Encode())) if err != nil { return statusCode, err } req.Header.Add("Content-Type", "application/x-www-form-urlencoded") - } else { - req, err = http.NewRequest("POST", u.String(), bytes.NewReader(form)) if err != nil { return statusCode, err @@ -277,10 +273,10 @@ func (s *SupermicroX) ChassisSerial() (serial string, err error) { func (s *SupermicroX) HardwareType() (model string) { m, err := s.Model() if err != nil { - // Here is your sin - s.log.V(1).Info("error getting hardwaretype", "err", internal.ErrStringOrEmpty(err)) - return model + s.log.V(1).Error(err, "HardwareType(): Getting the hardware type failed.") + return "" } + return m } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox11/actions.go b/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox11/actions.go index da68dee6..04334068 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox11/actions.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox11/actions.go @@ -71,6 +71,10 @@ func (s *SupermicroX) IsOn() (status bool, err error) { } // UpdateFirmware updates the bmc firmware -func (s *SupermicroX) UpdateFirmware(source, file string) (status bool, err error) { - return true, fmt.Errorf("not supported yet") +func (s *SupermicroX) UpdateFirmware(source, file string) (status bool, output string, err error) { + return false, "Not yet implemented", fmt.Errorf("not yet implemented") +} + +func (s *SupermicroX) CheckFirmwareVersion() (version string, err error) { + return "Not yet implemented", fmt.Errorf("not yet implemented") } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox11/configure.go b/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox11/configure.go index 61e26222..98cfb770 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox11/configure.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox11/configure.go @@ -68,7 +68,6 @@ func timezoneToUtcOffset(location *time.Location) (offset int) { // Return bool value if the role is valid. func (s *SupermicroX) isRoleValid(role string) bool { - validRoles := []string{"admin", "user"} for _, v := range validRoles { if role == v { @@ -81,7 +80,6 @@ func (s *SupermicroX) isRoleValid(role string) bool { // returns a map of user accounts and their ids func (s *SupermicroX) queryUserAccounts() (userAccounts map[string]int, err error) { - userAccounts = make(map[string]int) ipmi, err := s.query("op=CONFIG_INFO.XML&r=(0,0)") if err != nil { @@ -90,7 +88,6 @@ func (s *SupermicroX) queryUserAccounts() (userAccounts map[string]int, err erro } for idx, account := range ipmi.ConfigInfo.UserAccounts { - //idx++ if account.Name != "" { userAccounts[account.Name] = idx } @@ -105,15 +102,14 @@ func (s *SupermicroX) queryUserAccounts() (userAccounts map[string]int, err erro // supermicro user accounts start with 1, account 0 which is a large empty string :\. // nolint: gocyclo func (s *SupermicroX) User(users []*cfgresources.User) (err error) { - currentUsers, err := s.queryUserAccounts() if err != nil { msg := "Unable to query current user accounts." log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - "Step": helper.WhosCalling(), - "Error": err, + "IP": s.ip, + "HardwareType": s.HardwareType(), + "Step": helper.WhosCalling(), + "Error": err, }).Warn(msg) return errors.New(msg) } @@ -164,7 +160,6 @@ func (s *SupermicroX) User(users []*cfgresources.User) (err error) { configUser.NewPrivilege = 3 } if existingUserID, exists := currentUsers[user.Name]; exists { - //configUser.UserID = existingUserID - 1 configUser.UserID = existingUserID } else { configUser.UserID = numUsers @@ -186,33 +181,37 @@ func (s *SupermicroX) User(users []*cfgresources.User) (err error) { // 200 with this response: result=LANG_CONFUSR_RESULT_OK response, statusCode, err := s.post(endpoint, &form, []byte{}, "") if err != nil || statusCode != 200 { - msg := "POST request to set User config returned error." + if err == nil { + err = fmt.Errorf("Received a %d status code from the POST request to %s.", statusCode, endpoint) + } else { + err = fmt.Errorf("POST request to %s failed with error: %s", endpoint, err.Error()) + } + log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - "Endpoint": endpoint, - "StatusCode": statusCode, - "Step": helper.WhosCalling(), - "Error": err, - }).Warn(msg) - return errors.New(msg) + "IP": s.ip, + "HardwareType": s.HardwareType(), + "Endpoint": endpoint, + "StatusCode": statusCode, + "Step": helper.WhosCalling(), + "Error": err, + }).Error("POST request to set User config returned error.") + return err } if strings.Contains(response, "LANG_CONFUSER_COMMON_ERR7") { msg := "password did not meet complexity requirements" log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - "Response": response, + "IP": s.ip, + "HardwareType": s.HardwareType(), + "Response": response, }).Debug(msg) return errors.New(msg) } log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - "User": user.Name, + "IP": s.ip, + "HardwareType": s.HardwareType(), + "User": user.Name, }).Debug("User parameters applied.") - } return err @@ -221,7 +220,6 @@ func (s *SupermicroX) User(users []*cfgresources.User) (err error) { // Network method implements the Configure interface // applies various network parameters. func (s *SupermicroX) Network(cfg *cfgresources.Network) (reset bool, err error) { - sshPort := 22 if cfg.SSHPort != 0 && cfg.SSHPort != sshPort { @@ -251,21 +249,26 @@ func (s *SupermicroX) Network(cfg *cfgresources.Network) (reset bool, err error) form, _ := query.Values(configPort) _, statusCode, err := s.post(endpoint, &form, []byte{}, "") if err != nil || statusCode != 200 { - msg := "POST request to set Port config returned error." + if err == nil { + err = fmt.Errorf("Received a %d status code from the POST request to %s.", statusCode, endpoint) + } else { + err = fmt.Errorf("POST request to %s failed with error: %s", endpoint, err.Error()) + } + log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - "Endpoint": endpoint, - "StatusCode": statusCode, - "Step": helper.WhosCalling(), - "Error": err, - }).Warn(msg) - return reset, errors.New(msg) + "IP": s.ip, + "HardwareType": s.HardwareType(), + "Endpoint": endpoint, + "StatusCode": statusCode, + "Step": helper.WhosCalling(), + "Error": err, + }).Error("POST request to set Port config returned error.") + return reset, err } log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), + "IP": s.ip, + "HardwareType": s.HardwareType(), }).Debug("Network config parameters applied.") return reset, err } @@ -273,20 +276,19 @@ func (s *SupermicroX) Network(cfg *cfgresources.Network) (reset bool, err error) // Ntp applies NTP configuration params // Ntp implements the Configure interface. func (s *SupermicroX) Ntp(cfg *cfgresources.Ntp) (err error) { - var enable string if cfg.Server1 == "" { log.WithFields(log.Fields{ - "step": "applyNtpParams", - "Model": s.HardwareType(), + "step": "applyNtpParams", + "HardwareType": s.HardwareType(), }).Warn("NTP resource expects parameter: server1.") return } if cfg.Timezone == "" { log.WithFields(log.Fields{ - "step": "applyNtpParams", - "Model": s.HardwareType(), + "step": "applyNtpParams", + "HardwareType": s.HardwareType(), }).Warn("NTP resource expects parameter: timezone.") return } @@ -295,7 +297,7 @@ func (s *SupermicroX) Ntp(cfg *cfgresources.Ntp) (err error) { if err != nil { log.WithFields(log.Fields{ "step": "applyNtpParams", - "Model": s.HardwareType(), + "HardwareType": s.HardwareType(), "Declared timezone": cfg.Timezone, "Error": err, }).Warn("NTP resource declared parameter timezone invalid.") @@ -306,8 +308,8 @@ func (s *SupermicroX) Ntp(cfg *cfgresources.Ntp) (err error) { if !cfg.Enable { log.WithFields(log.Fields{ - "step": "applyNtpParams", - "Model": s.HardwareType(), + "step": "applyNtpParams", + "HardwareType": s.HardwareType(), }).Debug("Ntp resource declared with enable: false.") return } @@ -315,7 +317,7 @@ func (s *SupermicroX) Ntp(cfg *cfgresources.Ntp) (err error) { enable = "on" t := time.Now().In(tzLocation) - //Fri Jun 06 2018 14:28:25 GMT+0100 (CET) + // Fri Jun 06 2018 14:28:25 GMT+0100 (CET) ts := fmt.Sprintf("%s %d %d:%d:%d %s (%s)", t.Format("Fri Jun 01"), t.Year(), @@ -328,7 +330,7 @@ func (s *SupermicroX) Ntp(cfg *cfgresources.Ntp) (err error) { configDateTime := ConfigDateTime{ Op: "config_date_time", Timezone: tzUtcOffset, - DstEn: false, //daylight savings + DstEn: false, Enable: enable, NtpServerPrimary: cfg.Server1, NtpServerSecondary: cfg.Server2, @@ -345,24 +347,28 @@ func (s *SupermicroX) Ntp(cfg *cfgresources.Ntp) (err error) { form, _ := query.Values(configDateTime) _, statusCode, err := s.post(endpoint, &form, []byte{}, "") if err != nil || statusCode != 200 { - msg := "POST request to set Syslog config returned error." + if err == nil { + err = fmt.Errorf("Received a %d status code from the POST request to %s.", statusCode, endpoint) + } else { + err = fmt.Errorf("POST request to %s failed with error: %s", endpoint, err.Error()) + } + log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - "Endpoint": endpoint, - "StatusCode": statusCode, - "Step": helper.WhosCalling(), - "Error": err, - }).Warn(msg) - return errors.New(msg) + "IP": s.ip, + "HardwareType": s.HardwareType(), + "Endpoint": endpoint, + "StatusCode": statusCode, + "Step": helper.WhosCalling(), + "Error": err, + }).Error("POST request to set NTP config returned error.") + return err } - // log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), + "IP": s.ip, + "HardwareType": s.HardwareType(), }).Debug("NTP config parameters applied.") - return err + return nil } // Ldap applies LDAP configuration params. @@ -373,48 +379,42 @@ func (s *SupermicroX) Ldap(cfgLdap *cfgresources.Ldap) error { return nil } -// LdapGroup applies LDAP and LDAP Group/Role related configuration, -// LdapGroup implements the Configure interface. -// Supermicro does not have any separate configuration for Ldap groups just for generic ldap +// LdapGroups applies LDAP and LDAP Group/Role related configuration, +// LdapGroups implements the Configure interface. +// SuperMicro does not have any separate configuration for LDAP groups, just for generic LDAP. // nolint: gocyclo -func (s *SupermicroX) LdapGroup(cfgGroup []*cfgresources.LdapGroup, cfgLdap *cfgresources.Ldap) (err error) { - - var enable string - +func (s *SupermicroX) LdapGroups(cfgGroups []*cfgresources.LdapGroup, cfgLdap *cfgresources.Ldap) (err error) { if cfgLdap.Server == "" { msg := "Ldap resource parameter Server required but not declared." log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - "Model": s.HardwareType(), + "step": helper.WhosCalling(), + "HardwareType": s.HardwareType(), }).Warn(msg) return errors.New(msg) } - //first some preliminary checks if cfgLdap.Port == 0 { msg := "Ldap resource parameter Port required but not declared" log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - "Model": s.HardwareType(), + "step": helper.WhosCalling(), + "HardwareType": s.HardwareType(), }).Warn(msg) return errors.New(msg) } if !cfgLdap.Enable { log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - "Model": s.HardwareType(), + "step": helper.WhosCalling(), + "HardwareType": s.HardwareType(), }).Debug("Ldap resource declared with enable: false.") return } - enable = "on" - if cfgLdap.BaseDn == "" { msg := "Ldap resource parameter BaseDn required but not declared." log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - "Model": s.HardwareType(), + "step": helper.WhosCalling(), + "HardwareType": s.HardwareType(), }).Warn(msg) return errors.New(msg) } @@ -423,16 +423,14 @@ func (s *SupermicroX) LdapGroup(cfgGroup []*cfgresources.LdapGroup, cfgLdap *cfg if err != nil || serverIP == nil { msg := "Unable to lookup the IP for ldap server hostname." log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - "Model": s.HardwareType(), + "step": helper.WhosCalling(), + "HardwareType": s.HardwareType(), }).Warn(msg) return errors.New(msg) } - //for each ldap group setup config - //since supermicro can work with just one Searchbase, we go with the 'user' role group - for _, group := range cfgGroup { - + // Since SuperMicro can work with just one search base, we go with the "user" role group. + for _, group := range cfgGroups { if !group.Enable { continue } @@ -480,35 +478,40 @@ func (s *SupermicroX) LdapGroup(cfgGroup []*cfgresources.LdapGroup, cfgLdap *cfg configLdap := ConfigLdap{ Op: "config_ldap", - Enable: enable, + Enable: "on", EnableSsl: true, LdapIP: string(serverIP[0]), BaseDn: group.Group, LdapPort: cfgLdap.Port, BindDn: cfgLdap.BindDn, - BindPassword: "********", //default value + BindPassword: "********", // default value } endpoint := "op.cgi" form, _ := query.Values(configLdap) _, statusCode, err := s.post(endpoint, &form, []byte{}, "") if err != nil || statusCode != 200 { + if err == nil { + err = fmt.Errorf("Received a %d status code from the POST request to %s.", statusCode, endpoint) + } else { + err = fmt.Errorf("POST request to %s failed with error: %s", endpoint, err.Error()) + } msg := "POST request to set Ldap config returned error." log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - "Endpoint": endpoint, - "StatusCode": statusCode, - "Step": helper.WhosCalling(), - "Error": err, + "IP": s.ip, + "MHardwareTypeodel": s.HardwareType(), + "Endpoint": endpoint, + "StatusCode": statusCode, + "Step": helper.WhosCalling(), + "Error": err, }).Warn(msg) return errors.New(msg) } } log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), + "IP": s.ip, + "HardwareType": s.HardwareType(), }).Debug("Ldap config parameters applied.") return err } @@ -517,22 +520,21 @@ func (s *SupermicroX) LdapGroup(cfgGroup []*cfgresources.LdapGroup, cfgLdap *cfg // Syslog implements the Configure interface // this also enables alerts from the BMC func (s *SupermicroX) Syslog(cfg *cfgresources.Syslog) (err error) { - var port int if cfg.Server == "" { msg := "Syslog resource expects parameter: Server." log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - "Model": s.HardwareType(), + "step": helper.WhosCalling(), + "HardwareType": s.HardwareType(), }).Warn(msg) return errors.New(msg) } if cfg.Port == 0 { log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - "Model": s.HardwareType(), + "step": helper.WhosCalling(), + "HardwareType": s.HardwareType(), }).Debug("Syslog resource port set to default: 514.") port = 514 } else { @@ -541,8 +543,8 @@ func (s *SupermicroX) Syslog(cfg *cfgresources.Syslog) (err error) { if !cfg.Enable { log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - "Model": s.HardwareType(), + "step": helper.WhosCalling(), + "HardwareType": s.HardwareType(), }).Debug("Syslog resource declared with disable.") } @@ -550,8 +552,8 @@ func (s *SupermicroX) Syslog(cfg *cfgresources.Syslog) (err error) { if err != nil || serverIP == nil { msg := "Unable to lookup IP for syslog server hostname, yes supermicros requires the Syslog server IP :|." log.WithFields(log.Fields{ - "step": helper.WhosCalling(), - "Model": s.HardwareType(), + "step": helper.WhosCalling(), + "HardwareType": s.HardwareType(), }).Warn(msg) return errors.New(msg) } @@ -566,19 +568,23 @@ func (s *SupermicroX) Syslog(cfg *cfgresources.Syslog) (err error) { endpoint := "op.cgi" form, _ := query.Values(configSyslog) - //returns okStarting Syslog daemon if successful _, statusCode, err := s.post(endpoint, &form, []byte{}, "") if err != nil || statusCode != 200 { - msg := "POST request to set Syslog config returned error." + if err == nil { + err = fmt.Errorf("Received a %d status code from the POST request to %s.", statusCode, endpoint) + } else { + err = fmt.Errorf("POST request to %s failed with error: %s", endpoint, err.Error()) + } + log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - "Endpoint": endpoint, - "StatusCode": statusCode, - "step": helper.WhosCalling(), - "Error": err, - }).Warn(msg) - return errors.New(msg) + "IP": s.ip, + "HardwareType": s.HardwareType(), + "Endpoint": endpoint, + "StatusCode": statusCode, + "step": helper.WhosCalling(), + "Error": err, + }).Error("POST request to set Syslog config failed.") + return err } // enable maintenance events @@ -589,21 +595,26 @@ func (s *SupermicroX) Syslog(cfg *cfgresources.Syslog) (err error) { _, statusCode, err = s.post(endpoint, &form, []byte{}, "") if err != nil || statusCode != 200 { - msg := "POST request to enable maintenance alerts returned error." + if err == nil { + err = fmt.Errorf("Received a %d status code from the POST request to %s.", statusCode, endpoint) + } else { + err = fmt.Errorf("POST request to %s failed with error: %s", endpoint, err.Error()) + } + log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - "Endpoint": endpoint, - "StatusCode": statusCode, - "step": helper.WhosCalling(), - "Error": err, - }).Warn(msg) - return errors.New(msg) + "IP": s.ip, + "HardwareType": s.HardwareType(), + "Endpoint": endpoint, + "StatusCode": statusCode, + "step": helper.WhosCalling(), + "Error": err, + }).Error("POST request to enable maintenance alerts failed.") + return err } log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), + "IP": s.ip, + "HardwareType": s.HardwareType(), }).Debug("Syslog config parameters applied.") return err } @@ -622,7 +633,6 @@ func (s *SupermicroX) GenerateCSR(cert *cfgresources.HTTPSCertAttributes) ([]byt // 4. delay for a second // 5. Request for the current: SSL_STATUS.XML (0,0) func (s *SupermicroX) UploadHTTPSCert(cert []byte, certFileName string, key []byte, keyFileName string) (bool, error) { - endpoint := "upload_ssl.cgi" // setup a buffer for our multipart form @@ -657,12 +667,12 @@ func (s *SupermicroX) UploadHTTPSCert(cert []byte, certFileName string, key []by _, status, err := s.post(endpoint, &url.Values{}, form.Bytes(), w.FormDataContentType()) if err != nil || status != 200 { log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - "Endpoint": endpoint, - "StatusCode": status, - "Step": helper.WhosCalling(), - "Error": err, + "IP": s.ip, + "HardwareType": s.HardwareType(), + "Endpoint": endpoint, + "StatusCode": status, + "Step": helper.WhosCalling(), + "Error": err, }).Warn("Cert form upload POST request failed, expected 200.") return false, err } @@ -691,21 +701,20 @@ func (s *SupermicroX) UploadHTTPSCert(cert []byte, certFileName string, key []by // The second part of the certificate upload process, // we get the BMC to validate the uploaded SSL certificate. func (s *SupermicroX) validateSSL() error { - - var v = url.Values{} + v := url.Values{} v.Set("op", "SSL_VALIDATE.XML") v.Set("r", "(0,0)") - var endpoint = "ipmi.cgi" + endpoint := "ipmi.cgi" _, status, err := s.post(endpoint, &v, []byte{}, "") if err != nil || status != 200 { log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - "Endpoint": endpoint, - "StatusCode": status, - "Step": helper.WhosCalling(), - "Error": err, + "IP": s.ip, + "HardwareType": s.HardwareType(), + "Endpoint": endpoint, + "StatusCode": status, + "Step": helper.WhosCalling(), + "Error": err, }).Warn("Cert validate POST request failed, expected 200.") return err } @@ -717,21 +726,20 @@ func (s *SupermicroX) validateSSL() error { // Get the current status of the certificate. // POST https://10.193.251.43/cgi/ipmi.cgi SSL_STATUS.XML: (0,0) func (s *SupermicroX) statusSSL() error { - - var v = url.Values{} + v := url.Values{} v.Add("op", "SSL_STATUS.XML") v.Set("r", "(0,0)") - var endpoint = "ipmi.cgi" + endpoint := "ipmi.cgi" _, status, err := s.post(endpoint, &v, []byte{}, "") if err != nil || status != 200 { log.WithFields(log.Fields{ - "IP": s.ip, - "Model": s.HardwareType(), - "Endpoint": endpoint, - "StatusCode": status, - "Step": helper.WhosCalling(), - "Error": err, + "IP": s.ip, + "HardwareType": s.HardwareType(), + "Endpoint": endpoint, + "StatusCode": status, + "Step": helper.WhosCalling(), + "Error": err, }).Warn("Cert status POST request failed, expected 200.") return err } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox11/model.go b/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox11/model.go index aadb3d3b..00cf831a 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox11/model.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox11/model.go @@ -3,86 +3,86 @@ package supermicrox11 // ConfigSyslog declares payload to configure syslog parameters. // /cgi/op.cgi type ConfigSyslog struct { - Op string `url:"op"` //op=config_syslog - SyslogIP1 string `url:"syslogip1"` //syslogip1=10.01.12.1 - SyslogIP2 string `url:"syslogip2"` //syslogip1=10.01.12.2 - SyslogIP3 string `url:"syslogip3"` //syslogip1=10.01.12.3 - SyslogPort1 int `url:"syslogport1"` //syslogport1=514 - SyslogPort2 int `url:"syslogport2"` //syslogport2=0 - SyslogPort3 int `url:"syslogport3"` //syslogport3=0 - Enable bool `url:"enable,int"` //enable=1 + Op string `url:"op"` // op=config_syslog + SyslogIP1 string `url:"syslogip1"` // syslogip1=10.01.12.1 + SyslogIP2 string `url:"syslogip2"` // syslogip1=10.01.12.2 + SyslogIP3 string `url:"syslogip3"` // syslogip1=10.01.12.3 + SyslogPort1 int `url:"syslogport1"` // syslogport1=514 + SyslogPort2 int `url:"syslogport2"` // syslogport2=0 + SyslogPort3 int `url:"syslogport3"` // syslogport3=0 + Enable bool `url:"enable,int"` // enable=1 } // ConfigDateTime declares payload to configure time parameters. // /cgi/op.cgi type ConfigDateTime struct { - Op string `url:"op"` //op=config_date_time - Timezone int `url:"timezone"` //timezone=-7200 - DstEn bool `url:"dst_en,int"` //dst_en=0 - Enable string `url:"ntp"` //ntp=on - NtpServerPrimary string `url:"ntp_server_pri"` //ntp_server_pri=ntp0.example.com - NtpServerSecondary string `url:"ntp_server_2nd"` //ntp_server_2nd=ntp1.example.com - Year int `url:"year"` //year=2018 - Month int `url:"month"` //month=6 - Day int `url:"day"` //day=1 - Hour int `url:"hour"` //hour=05 - Minute int `url:"min"` //min=49 - Second int `url:"sec"` //sec=42 - TimeStamp string `url:"time_stamp"` //time_stamp=Fri%20Jun%2001%202018%2009%3A58%3A19%20GMT%2B0200%20(CEST) + Op string `url:"op"` // op=config_date_time + Timezone int `url:"timezone"` // timezone=-7200 + DstEn bool `url:"dst_en,int"` // dst_en=0 + Enable string `url:"ntp"` // ntp=on + NtpServerPrimary string `url:"ntp_server_pri"` // ntp_server_pri=ntp0.example.com + NtpServerSecondary string `url:"ntp_server_2nd"` // ntp_server_2nd=ntp1.example.com + Year int `url:"year"` // year=2018 + Month int `url:"month"` // month=6 + Day int `url:"day"` // day=1 + Hour int `url:"hour"` // hour=05 + Minute int `url:"min"` // min=49 + Second int `url:"sec"` // sec=42 + TimeStamp string `url:"time_stamp"` // time_stamp=Fri%20Jun%2001%202018%2009%3A58%3A19%20GMT%2B0200%20(CEST) } // ConfigUser declares payload to configure User accounts. // /cgi/op.cgi type ConfigUser struct { - Op string `url:"op"` //op=config_user + Op string `url:"op"` // op=config_user Username string `url:"username"` - UserID int `url:"original_username"` //username integer + UserID int `url:"original_username"` // username integer Password string `url:"password,omitempty"` - NewPrivilege int `url:"new_privilege,omitempty"` //4 == administrator, 3 == operator + NewPrivilege int `url:"new_privilege,omitempty"` // 4 == administrator, 3 == operator } // ConfigLdap declares payload to configure LDAP. // /cgi/op.cgi type ConfigLdap struct { - Op string `url:"op"` //op=config_ldap - Enable string `url:"en_ldap"` //en_ldap=on - EnableSsl bool `url:"enSSL,int"` //enSSL=1 - LdapIP string `url:"ldapip"` //ldapip=10.252.13.5 - BaseDn string `url:"basedn"` //basedn=cn=Supermicro,cn=bmcUsers - LdapPort int `url:"ldapport"` //ldapport=636 - BindDn string `url:"bind_dn"` //bind_dn=undefined <- default value - BindPassword string `url:"bind_pwd"` //bind_pwd=******** <- default value + Op string `url:"op"` // op=config_ldap + Enable string `url:"en_ldap"` // en_ldap=on + EnableSsl bool `url:"enSSL,int"` // enSSL=1 + LdapIP string `url:"ldapip"` // ldapip=10.252.13.5 + BaseDn string `url:"basedn"` // basedn=cn=Supermicro,cn=bmcUsers + LdapPort int `url:"ldapport"` // ldapport=636 + BindDn string `url:"bind_dn"` // bind_dn=undefined <- default value + BindPassword string `url:"bind_pwd"` // bind_pwd=******** <- default value } // ConfigPort declares payload to configure services. type ConfigPort struct { - Op string `url:"op"` //op=config_port - HTTPPort int `url:"HTTP_PORT"` //HTTP_PORT=80 - HTTPSPort int `url:"HTTPS_PORT"` //HTTPS_PORT=443 - IkvmPort int `url:"IKVM_PORT"` //IKVM_PORT=5900 - VMPort int `url:"VM_PORT"` //VM_PORT=623 <- virtual media port - SSHPort int `url:"SSH_PORT"` //SSH_PORT=22 - WsmanPort int `url:"WSMAN_PORT"` //WSMAN_PORT=5985 - SnmpPort int `url:"SNMP_PORT"` //SNMP_PORT=161 - httpEnable bool `url:"HTTP_SERVICE,int"` //HTTP_SERVICE=1 - httpsEnable bool `url:"HTTPS_SERVICE,int"` //HTTPS_SERVICE=1 - IkvmEnable bool `url:"IKVM_SERVICE,int"` //IKVM_SERVICE=1 - VMEnable bool `url:"VM_SERVICE,int"` //VM_SERVICE=1 - SSHEnable bool `url:"SSH_SERVICE,int"` //SSH_SERVICE=1 - SnmpEnable bool `url:"SNMP_SERVICE,int"` //SNMP_SERVICE=1 - WsmanEnable bool `url:"WSMAN_SERVICE,int"` //WSMAN_SERVICE=0 - SslRedirectEnable bool `url:"SSL_REDIRECT,int"` //SSL_REDIRECT=1 + Op string `url:"op"` // op=config_port + HTTPPort int `url:"HTTP_PORT"` // HTTP_PORT=80 + HTTPSPort int `url:"HTTPS_PORT"` // HTTPS_PORT=443 + IkvmPort int `url:"IKVM_PORT"` // IKVM_PORT=5900 + VMPort int `url:"VM_PORT"` // VM_PORT=623 <- virtual media port + SSHPort int `url:"SSH_PORT"` // SSH_PORT=22 + WsmanPort int `url:"WSMAN_PORT"` // WSMAN_PORT=5985 + SnmpPort int `url:"SNMP_PORT"` // SNMP_PORT=161 + httpEnable bool `url:"HTTP_SERVICE,int"` // HTTP_SERVICE=1 + httpsEnable bool `url:"HTTPS_SERVICE,int"` // HTTPS_SERVICE=1 + IkvmEnable bool `url:"IKVM_SERVICE,int"` // IKVM_SERVICE=1 + VMEnable bool `url:"VM_SERVICE,int"` // VM_SERVICE=1 + SSHEnable bool `url:"SSH_SERVICE,int"` // SSH_SERVICE=1 + SnmpEnable bool `url:"SNMP_SERVICE,int"` // SNMP_SERVICE=1 + WsmanEnable bool `url:"WSMAN_SERVICE,int"` // WSMAN_SERVICE=0 + SslRedirectEnable bool `url:"SSL_REDIRECT,int"` // SSL_REDIRECT=1 } // CapturePreview declares payload to capture screen previews. type CapturePreview struct { - IkvmPreview string `url:"IKVM_PREVIEW.XML"` //IKVM_PREVIEW.XML=(0,0) - TimeStamp string `url:"time_stamp"` //time_stamp=Wed Oct 17 2018 15:56:08 GMT+0200 (CEST) + IkvmPreview string `url:"IKVM_PREVIEW.XML"` // IKVM_PREVIEW.XML=(0,0) + TimeStamp string `url:"time_stamp"` // time_stamp=Wed Oct 17 2018 15:56:08 GMT+0200 (CEST) } // URLRedirect declares payload sent when capturing screen previews type URLRedirect struct { - URLName string `url:"url_name"` //url_name=Snapshot - URLType string `url:"url_type"` //url_type=img - TimeStamp string `url:"time_stamp"` //time_stamp=Wed Oct 17 2018 15:56:08 GMT+0200 (CEST) + URLName string `url:"url_name"` // url_name=Snapshot + URLType string `url:"url_type"` // url_type=img + TimeStamp string `url:"time_stamp"` // time_stamp=Wed Oct 17 2018 15:56:08 GMT+0200 (CEST) } diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox11/query.go b/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox11/query.go index 0254fc71..c402773d 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox11/query.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox11/query.go @@ -16,13 +16,11 @@ import ( // the bool value returned is set to true if the BMC support CSR generation. // CurrentHTTPSCert implements the Configure interface. func (s *SupermicroX) CurrentHTTPSCert() ([]*x509.Certificate, bool, error) { - dialer := &net.Dialer{ Timeout: time.Duration(10) * time.Second, } conn, err := tls.DialWithDialer(dialer, "tcp", s.ip+":"+"443", &tls.Config{InsecureSkipVerify: true}) - if err != nil { return []*x509.Certificate{{}}, false, err } @@ -30,7 +28,6 @@ func (s *SupermicroX) CurrentHTTPSCert() ([]*x509.Certificate, bool, error) { defer conn.Close() return conn.ConnectionState().PeerCertificates, false, nil - } // Screenshot returns a thumbnail of video display from the bmc. @@ -38,7 +35,6 @@ func (s *SupermicroX) CurrentHTTPSCert() ([]*x509.Certificate, bool, error) { // 2. sleep for 3 seconds to give ikvm time to ensure preview was captured // 3. request for preview. func (s *SupermicroX) Screenshot() (response []byte, extension string, err error) { - postEndpoint := "CapturePreview.cgi" getEndpoint := "cgi/url_redirect.cgi?" @@ -52,7 +48,7 @@ func (s *SupermicroX) Screenshot() (response []byte, extension string, err error tzLocation, _ := time.LoadLocation("CET") t := time.Now().In(tzLocation) - //Fri Jun 06 2018 14:28:25 GMT+0100 (CET) + // Fri Jun 06 2018 14:28:25 GMT+0100 (CET) ts := fmt.Sprintf("%s %d %d:%d:%d %s (%s)", t.Format("Fri Jun 01"), t.Year(), @@ -74,11 +70,11 @@ func (s *SupermicroX) Screenshot() (response []byte, extension string, err error } if statusCode != 200 { - return response, extension, fmt.Errorf("Non 200 response from endpoint") + return response, extension, fmt.Errorf("Non-200 response from endpoint %s: %d!", postEndpoint, statusCode) } time.Sleep(3 * time.Second) - //Fri Jun 06 2018 14:28:25 GMT+0100 (CET) + // Fri Jun 06 2018 14:28:25 GMT+0100 (CET) ts = fmt.Sprintf("%s %d %d:%d:%d %s (%s)", t.Format("Fri Jun 01"), t.Year(), diff --git a/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox11/supermicrox.go b/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox11/supermicrox.go index 0ecbe543..5554b546 100644 --- a/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox11/supermicrox.go +++ b/vendor/github.com/bmc-toolbox/bmclib/providers/supermicro/supermicrox11/supermicrox.go @@ -46,7 +46,8 @@ func New(ctx context.Context, ip string, username string, password string, log l username: username, password: password, ctx: ctx, - log: log}, err + log: log, + }, err } // CheckCredentials verify whether the credentials are valid or not @@ -60,7 +61,6 @@ func (s *SupermicroX) CheckCredentials() (err error) { // get calls a given json endpoint of the ilo and returns the data func (s *SupermicroX) get(endpoint string) (payload []byte, err error) { - bmcURL := fmt.Sprintf("https://%s/%s", s.ip, endpoint) req, err := http.NewRequest("GET", bmcURL, nil) if err != nil { @@ -122,15 +122,12 @@ func (s *SupermicroX) post(endpoint string, urlValues *url.Values, form []byte, var req *http.Request if formDataContentType == "" { - req, err = http.NewRequest("POST", u.String(), strings.NewReader(urlValues.Encode())) if err != nil { return response, statusCode, err } req.Header.Add("Content-Type", "application/x-www-form-urlencoded") - } else { - req, err = http.NewRequest("POST", u.String(), bytes.NewReader(form)) if err != nil { return response, statusCode, err @@ -251,8 +248,7 @@ func (s *SupermicroX) ChassisSerial() (serial string, err error) { func (s *SupermicroX) HardwareType() (model string) { m, err := s.Model() if err != nil { - // Here is your sin - return model + return "" } return m } @@ -289,6 +285,10 @@ func (s *SupermicroX) Version() (bmcVersion string, err error) { return bmcVersion, err } +func (s *SupermicroX) Class() (class string, err error) { + return "SupermicroX", nil +} + // Name returns the hostname of the machine func (s *SupermicroX) Name() (name string, err error) { ipmi, err := s.query("op=CONFIG_INFO.XML&r=(0,0)") diff --git a/vendor/github.com/bmc-toolbox/gin-go-metrics/helpers.go b/vendor/github.com/bmc-toolbox/gin-go-metrics/helpers.go index 74564d9a..19d451a8 100644 --- a/vendor/github.com/bmc-toolbox/gin-go-metrics/helpers.go +++ b/vendor/github.com/bmc-toolbox/gin-go-metrics/helpers.go @@ -56,7 +56,6 @@ func Scheduler(interval time.Duration, fn interface{}, args ...interface{}) { // GoRuntimeStats collects go runtime stats. // prefix is a slice of metric namespace nodes. func GoRuntimeStats(prefix []string) { - prefix = append(prefix, "runtime") UpdateGauge(append(prefix, "num_goroutines"), int64(runtime.NumGoroutine())) @@ -111,7 +110,7 @@ func GoRuntimeStats(prefix []string) { // MeasureRuntime measures time elapsed since invocation func MeasureRuntime(key []string, start time.Time) { - //convert time.Duration to milliseconds + // convert time.Duration to milliseconds elapsed := int64(time.Since(start) / time.Millisecond) UpdateGauge(key, elapsed) } diff --git a/vendor/github.com/bmc-toolbox/gin-go-metrics/metrics.go b/vendor/github.com/bmc-toolbox/gin-go-metrics/metrics.go index 9d023e1e..f9a10441 100644 --- a/vendor/github.com/bmc-toolbox/gin-go-metrics/metrics.go +++ b/vendor/github.com/bmc-toolbox/gin-go-metrics/metrics.go @@ -42,9 +42,9 @@ type emitter struct { // metric struct holds attributes for a metric. type metric struct { - Type string //counter/gauge - Key []string //metric key - Value float64 //metric value + Type string // counter/gauge + Key []string // metric key + Value float64 // metric value } // Setup sets up external and internal metric sinks. @@ -60,7 +60,7 @@ func Setup(clientType string, host string, port int, prefix string, flushInterva graphiteConfig = graphite.Config{} - //setup metrics client based on config + // setup metrics client based on config switch clientType { case "graphite": addr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", host, port)) @@ -81,7 +81,7 @@ func Setup(clientType string, host string, port int, prefix string, flushInterva return fmt.Errorf("no supported metrics client declared in config") } - //go routine that stores data + // go routine that stores data go emm.store() return err @@ -90,7 +90,7 @@ func Setup(clientType string, host string, port int, prefix string, flushInterva //- writes/updates metric key/vals to registry //- register and write metrics to the go-metrics registries. func (e *emitter) store() { - //A map of metric names to go-metrics registry + // A map of metric names to go-metrics registry goMetricsRegistry := make(map[string]interface{}) for { @@ -101,8 +101,8 @@ func (e *emitter) store() { key := strings.Join(data.Key, ".") - //register the metric with go-metrics, - //the metric key is used as the identifier. + // register the metric with go-metrics, + // the metric key is used as the identifier. _, registryExists := goMetricsRegistry[key] if !registryExists { switch data.Type { @@ -121,26 +121,26 @@ func (e *emitter) store() { } } - //based on the metric type, update the store/registry. + // based on the metric type, update the store/registry. switch data.Type { case "counter": - //type assert metrics registry to its type - metrics.Counter - //type cast float64 metric value type to int64 + // type assert metrics registry to its type - metrics.Counter + // type cast float64 metric value type to int64 goMetricsRegistry[key].(metrics.Counter).Inc( int64(data.Value)) case "gauge": - //type assert metrics registry to its type - metrics.Gauge - //type cast float64 metric value type to int64 + // type assert metrics registry to its type - metrics.Gauge + // type cast float64 metric value type to int64 goMetricsRegistry[key].(metrics.Gauge).Update( int64(data.Value)) case "timer": - //type assert metrics registry to its type - metrics.Timer - //type cast float64 metric value type to time.Duration + // type assert metrics registry to its type - metrics.Timer + // type cast float64 metric value type to time.Duration goMetricsRegistry[key].(metrics.Timer).Update( time.Duration(data.Value)) case "histogram": - //type assert metrics registry to its type - metrics.Histogram - //type cast float64 metric value type to int64 + // type assert metrics registry to its type - metrics.Histogram + // type cast float64 metric value type to int64 goMetricsRegistry[key].(metrics.Histogram).Update( int64(data.Value)) } @@ -148,10 +148,9 @@ func (e *emitter) store() { } // IncrCounter sets up metric attributes and passes them to the metricsChan. -//key = slice of strings that will be joined with "." to be used as the metric namespace -//val = float64 metric value +// key = slice of strings that will be joined with "." to be used as the metric namespace +// val = float64 metric value func IncrCounter(key []string, value int64) { - // incase this method was invoked without the emmiter being initialized. if emm == nil { return @@ -167,10 +166,9 @@ func IncrCounter(key []string, value int64) { } // UpdateGauge sets up the Gauge metric and passes them to the metricsChan. -//key = slice of strings that will be joined with "." to be used as the metric namespace -//val = float64 metric value +// key = slice of strings that will be joined with "." to be used as the metric namespace +// val = float64 metric value func UpdateGauge(key []string, value int64) { - // incase this method was invoked without the emmiter being initialized. if emm == nil { return @@ -186,10 +184,9 @@ func UpdateGauge(key []string, value int64) { } // UpdateTimer sets up the Timer metric and passes them to the metricsChan. -//key = slice of strings that will be joined with "." to be used as the metric namespace -//val = time.Time metric value +// key = slice of strings that will be joined with "." to be used as the metric namespace +// val = time.Time metric value func UpdateTimer(key []string, value time.Duration) { - // incase this method was invoked without the emmiter being initialized. if emm == nil { return @@ -205,10 +202,9 @@ func UpdateTimer(key []string, value time.Duration) { } // UpdateHistogram sets up the Histogram metric and passes them to the metricsChan. -//key = slice of strings that will be joined with "." to be used as the metric namespace -//val = int64 metric value +// key = slice of strings that will be joined with "." to be used as the metric namespace +// val = int64 metric value func UpdateHistogram(key []string, value int64) { - // incase this method was invoked without the emmiter being initialized. if emm == nil { return @@ -225,7 +221,6 @@ func UpdateHistogram(key []string, value int64) { // Close runs cleanup actions func Close(printStats bool) { - // incase this method was invoked without the emmiter being initialized. if emm == nil { return diff --git a/vendor/github.com/bmc-toolbox/gin-go-metrics/middleware/middleware.go b/vendor/github.com/bmc-toolbox/gin-go-metrics/middleware/middleware.go index 2a1c9deb..7ad87124 100644 --- a/vendor/github.com/bmc-toolbox/gin-go-metrics/middleware/middleware.go +++ b/vendor/github.com/bmc-toolbox/gin-go-metrics/middleware/middleware.go @@ -84,7 +84,7 @@ func contains(slice []string, s string) bool { return false } -//HandlerFunc is a function which should be used as middleware to count requests stats +// HandlerFunc is a function which should be used as middleware to count requests stats // such as request processing time, request and responce size and store it in rcrowley/go-metrics.DefaultRegistry. func (m *Metrics) HandlerFunc(metricsPrefix []string, ignoreURLs []string, replaceSlashWithUnderscore bool) gin.HandlerFunc { theRegistry := newRegistry() @@ -123,7 +123,7 @@ func (m *Metrics) HandlerFunc(metricsPrefix []string, ignoreURLs []string, repla ) theRegistry.timer(processTimeKey).Update(elapsed) theRegistry.histogram(reqSzKey).Update(reqSz) - theRegistry.histogram(resSzKey, ).Update(resSz) + theRegistry.histogram(resSzKey).Update(resSz) } } diff --git a/vendor/github.com/bombsimon/logrusr/logrusr.go b/vendor/github.com/bombsimon/logrusr/logrusr.go index e4d7ce9d..7fc29329 100644 --- a/vendor/github.com/bombsimon/logrusr/logrusr.go +++ b/vendor/github.com/bombsimon/logrusr/logrusr.go @@ -120,7 +120,7 @@ func (l *logrusr) Error(err error, msg string, keysAndValues ...interface{}) { // listToLogrusFields converts a list of arbitrary length to key/value paris. func listToLogrusFields(formatter func(interface{}) string, keysAndValues ...interface{}) logrus.Fields { - var f = logrus.Fields{} + f := logrus.Fields{} // Skip all fields if it's not an even lengthed list. if len(keysAndValues)%2 != 0 { diff --git a/vendor/github.com/cyberdelia/go-metrics-graphite/graphite.go b/vendor/github.com/cyberdelia/go-metrics-graphite/graphite.go index 4489f0be..67d68e50 100644 --- a/vendor/github.com/cyberdelia/go-metrics-graphite/graphite.go +++ b/vendor/github.com/cyberdelia/go-metrics-graphite/graphite.go @@ -40,7 +40,7 @@ func Graphite(r metrics.Registry, d time.Duration, prefix string, addr *net.TCPA // WithConfig is a blocking exporter function just like Graphite, // but it takes a GraphiteConfig instead. func WithConfig(c Config) { - for _ = range time.Tick(c.FlushInterval) { + for range time.Tick(c.FlushInterval) { if err := graphite(&c); nil != err { log.Println(err) } diff --git a/vendor/github.com/fsnotify/fsnotify/kqueue.go b/vendor/github.com/fsnotify/fsnotify/kqueue.go index 86e76a3d..ff3c2b66 100644 --- a/vendor/github.com/fsnotify/fsnotify/kqueue.go +++ b/vendor/github.com/fsnotify/fsnotify/kqueue.go @@ -73,7 +73,7 @@ func (w *Watcher) Close() error { w.isClosed = true // copy paths to remove while locked - var pathsToRemove = make([]string, 0, len(w.watches)) + pathsToRemove := make([]string, 0, len(w.watches)) for name := range w.watches { pathsToRemove = append(pathsToRemove, name) } @@ -215,7 +215,7 @@ func (w *Watcher) addWatch(name string, flags uint32) (string, error) { } } - watchfd, err = unix.Open(name, openMode, 0700) + watchfd, err = unix.Open(name, openMode, 0o700) if watchfd == -1 { return "", err } @@ -428,7 +428,6 @@ func (w *Watcher) sendDirectoryChangeEvents(dirPath string) { for _, fileInfo := range files { filePath := filepath.Join(dirPath, fileInfo.Name()) err := w.sendFileCreatedEventIfNew(filePath, fileInfo) - if err != nil { return } diff --git a/vendor/github.com/fsnotify/fsnotify/windows.go b/vendor/github.com/fsnotify/fsnotify/windows.go index 09436f31..2ac224b4 100644 --- a/vendor/github.com/fsnotify/fsnotify/windows.go +++ b/vendor/github.com/fsnotify/fsnotify/windows.go @@ -171,8 +171,10 @@ type watch struct { buf [4096]byte } -type indexMap map[uint64]*watch -type watchMap map[uint32]indexMap +type ( + indexMap map[uint64]*watch + watchMap map[uint32]indexMap +) func (w *Watcher) wakeupReader() error { e := syscall.PostQueuedCompletionStatus(w.port, 0, 0, nil) diff --git a/vendor/github.com/gedex/inflector/inflector.go b/vendor/github.com/gedex/inflector/inflector.go index 319f936c..b7e3f2c2 100644 --- a/vendor/github.com/gedex/inflector/inflector.go +++ b/vendor/github.com/gedex/inflector/inflector.go @@ -61,8 +61,10 @@ type compiledRule struct { } // threadsafe access to rules and caches -var mutex sync.Mutex -var rules = make(map[Rule]*InflectorRule) +var ( + mutex sync.Mutex + rules = make(map[Rule]*InflectorRule) +) // Words that should not be inflected var uninflected = []string{ @@ -102,7 +104,6 @@ var caches = make(map[Rule]cache) var irregularMaps = make(map[Rule]cache) func init() { - rules[Plural] = &InflectorRule{ Rules: []*ruleItem{ {`(?i)(s)tatus$`, `${1}${2}tatuses`}, diff --git a/vendor/github.com/gin-contrib/sse/sse-decoder.go b/vendor/github.com/gin-contrib/sse/sse-decoder.go index fd49b9c3..879373af 100644 --- a/vendor/github.com/gin-contrib/sse/sse-decoder.go +++ b/vendor/github.com/gin-contrib/sse/sse-decoder.go @@ -22,7 +22,7 @@ func Decode(r io.Reader) ([]Event, error) { func (d *decoder) dispatchEvent(event Event, data string) { dataLength := len(data) if dataLength > 0 { - //If the data buffer's last character is a U+000A LINE FEED (LF) character, then remove the last character from the data buffer. + // If the data buffer's last character is a U+000A LINE FEED (LF) character, then remove the last character from the data buffer. data = data[:dataLength-1] dataLength-- } @@ -105,7 +105,7 @@ func (d *decoder) decode(r io.Reader) ([]Event, error) { // then append a single U+000A LINE FEED (LF) character to the data buffer. dataBuffer.WriteString("\n") default: - //Otherwise. The field is ignored. + // Otherwise. The field is ignored. continue } } diff --git a/vendor/github.com/gin-contrib/sse/sse-encoder.go b/vendor/github.com/gin-contrib/sse/sse-encoder.go index f9c80875..42b40433 100644 --- a/vendor/github.com/gin-contrib/sse/sse-encoder.go +++ b/vendor/github.com/gin-contrib/sse/sse-encoder.go @@ -20,8 +20,10 @@ import ( const ContentType = "text/event-stream" -var contentType = []string{ContentType} -var noCache = []string{"no-cache"} +var ( + contentType = []string{ContentType} + noCache = []string{"no-cache"} +) var fieldReplacer = strings.NewReplacer( "\n", "\\n", diff --git a/vendor/github.com/gin-gonic/gin/binding/form.go b/vendor/github.com/gin-gonic/gin/binding/form.go index b93c34cf..8b45c505 100644 --- a/vendor/github.com/gin-gonic/gin/binding/form.go +++ b/vendor/github.com/gin-gonic/gin/binding/form.go @@ -10,9 +10,11 @@ import ( const defaultMemory = 32 << 20 -type formBinding struct{} -type formPostBinding struct{} -type formMultipartBinding struct{} +type ( + formBinding struct{} + formPostBinding struct{} + formMultipartBinding struct{} +) func (formBinding) Name() string { return "form" diff --git a/vendor/github.com/gin-gonic/gin/binding/form_mapping.go b/vendor/github.com/gin-gonic/gin/binding/form_mapping.go index 2f4e45b4..a6a818ea 100644 --- a/vendor/github.com/gin-gonic/gin/binding/form_mapping.go +++ b/vendor/github.com/gin-gonic/gin/binding/form_mapping.go @@ -71,7 +71,7 @@ func mapping(value reflect.Value, field reflect.StructField, setter setter, tag return false, nil } - var vKind = value.Kind() + vKind := value.Kind() if vKind == reflect.Ptr { var isNew bool @@ -298,7 +298,6 @@ func setTimeField(val string, structField reflect.StructField, value reflect.Val t := time.Unix(tv/int64(d), tv%int64(d)) value.Set(reflect.ValueOf(t)) return nil - } if val == "" { diff --git a/vendor/github.com/gin-gonic/gin/binding/header.go b/vendor/github.com/gin-gonic/gin/binding/header.go index 179ce4ea..d7211cd2 100644 --- a/vendor/github.com/gin-gonic/gin/binding/header.go +++ b/vendor/github.com/gin-gonic/gin/binding/header.go @@ -13,7 +13,6 @@ func (headerBinding) Name() string { } func (headerBinding) Bind(req *http.Request, obj interface{}) error { - if err := mapHeader(obj, req.Header); err != nil { return err } diff --git a/vendor/github.com/gin-gonic/gin/binding/xml.go b/vendor/github.com/gin-gonic/gin/binding/xml.go index 4e901149..b04b18d8 100644 --- a/vendor/github.com/gin-gonic/gin/binding/xml.go +++ b/vendor/github.com/gin-gonic/gin/binding/xml.go @@ -24,6 +24,7 @@ func (xmlBinding) Bind(req *http.Request, obj interface{}) error { func (xmlBinding) BindBody(body []byte, obj interface{}) error { return decodeXML(bytes.NewReader(body), obj) } + func decodeXML(r io.Reader, obj interface{}) error { decoder := xml.NewDecoder(r) if err := decoder.Decode(obj); err != nil { diff --git a/vendor/github.com/gin-gonic/gin/mode.go b/vendor/github.com/gin-gonic/gin/mode.go index c8813aff..4d199df3 100644 --- a/vendor/github.com/gin-gonic/gin/mode.go +++ b/vendor/github.com/gin-gonic/gin/mode.go @@ -41,8 +41,10 @@ var DefaultWriter io.Writer = os.Stdout // DefaultErrorWriter is the default io.Writer used by Gin to debug errors var DefaultErrorWriter io.Writer = os.Stderr -var ginMode = debugCode -var modeName = DebugMode +var ( + ginMode = debugCode + modeName = DebugMode +) func init() { mode := os.Getenv(EnvGinMode) diff --git a/vendor/github.com/gin-gonic/gin/recovery.go b/vendor/github.com/gin-gonic/gin/recovery.go index 563f5aaa..dd72c74f 100644 --- a/vendor/github.com/gin-gonic/gin/recovery.go +++ b/vendor/github.com/gin-gonic/gin/recovery.go @@ -34,7 +34,7 @@ func Recovery() HandlerFunc { return RecoveryWithWriter(DefaultErrorWriter) } -//CustomRecovery returns a middleware that recovers from any panics and calls the provided handle func to handle it. +// CustomRecovery returns a middleware that recovers from any panics and calls the provided handle func to handle it. func CustomRecovery(handle RecoveryFunc) HandlerFunc { return RecoveryWithWriter(DefaultErrorWriter, handle) } diff --git a/vendor/github.com/gin-gonic/gin/render/html.go b/vendor/github.com/gin-gonic/gin/render/html.go index 6696ece9..902604d6 100644 --- a/vendor/github.com/gin-gonic/gin/render/html.go +++ b/vendor/github.com/gin-gonic/gin/render/html.go @@ -63,6 +63,7 @@ func (r HTMLDebug) Instance(name string, data interface{}) Render { Data: data, } } + func (r HTMLDebug) loadTemplate() *template.Template { if r.FuncMap == nil { r.FuncMap = template.FuncMap{} diff --git a/vendor/github.com/gin-gonic/gin/render/json.go b/vendor/github.com/gin-gonic/gin/render/json.go index 41863093..e25415b0 100644 --- a/vendor/github.com/gin-gonic/gin/render/json.go +++ b/vendor/github.com/gin-gonic/gin/render/json.go @@ -46,9 +46,11 @@ type PureJSON struct { Data interface{} } -var jsonContentType = []string{"application/json; charset=utf-8"} -var jsonpContentType = []string{"application/javascript; charset=utf-8"} -var jsonAsciiContentType = []string{"application/json"} +var ( + jsonContentType = []string{"application/json; charset=utf-8"} + jsonpContentType = []string{"application/javascript; charset=utf-8"} + jsonAsciiContentType = []string{"application/json"} +) // Render (JSON) writes data with custom ContentType. func (r JSON) Render(w http.ResponseWriter) (err error) { diff --git a/vendor/github.com/gin-gonic/gin/render/msgpack.go b/vendor/github.com/gin-gonic/gin/render/msgpack.go index 6ef5b6e5..bf0bbaa8 100644 --- a/vendor/github.com/gin-gonic/gin/render/msgpack.go +++ b/vendor/github.com/gin-gonic/gin/render/msgpack.go @@ -13,9 +13,7 @@ import ( "github.com/ugorji/go/codec" ) -var ( - _ Render = MsgPack{} -) +var _ Render = MsgPack{} // MsgPack contains the given interface object. type MsgPack struct { diff --git a/vendor/github.com/go-logr/zapr/zapr.go b/vendor/github.com/go-logr/zapr/zapr.go index 0969a4a4..f7a140f7 100644 --- a/vendor/github.com/go-logr/zapr/zapr.go +++ b/vendor/github.com/go-logr/zapr/zapr.go @@ -182,5 +182,7 @@ func NewLogger(l *zap.Logger) logr.Logger { return newLoggerWithExtraSkip(l, 1) } -var _ logr.Logger = &zapLogger{} -var _ logr.CallDepthLogger = &zapLogger{} +var ( + _ logr.Logger = &zapLogger{} + _ logr.CallDepthLogger = &zapLogger{} +) diff --git a/vendor/github.com/go-playground/locales/rules.go b/vendor/github.com/go-playground/locales/rules.go index 92029001..29a3755f 100644 --- a/vendor/github.com/go-playground/locales/rules.go +++ b/vendor/github.com/go-playground/locales/rules.go @@ -156,7 +156,6 @@ type Translator interface { // String returns the string value of PluralRule func (p PluralRule) String() string { - switch p { case PluralRuleZero: return pluralsString[7:11] @@ -225,7 +224,6 @@ func (p PluralRule) String() string { // W returns the number of visible fraction digits in N, without trailing zeros. func W(n float64, v uint64) (w int64) { - s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64) // with either be '0' or '0.xxxx', so if 1 then w will be zero @@ -250,13 +248,11 @@ func W(n float64, v uint64) (w int64) { // F returns the visible fractional digits in N, with trailing zeros. func F(n float64, v uint64) (f int64) { - s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64) // with either be '0' or '0.xxxx', so if 1 then f will be zero // otherwise need to parse if len(s) != 1 { - // ignoring error, because it can't fail as we generated // the string internally from a real number f, _ = strconv.ParseInt(s[2:], 10, 64) @@ -267,7 +263,6 @@ func F(n float64, v uint64) (f int64) { // T returns the visible fractional digits in N, without trailing zeros. func T(n float64, v uint64) (t int64) { - s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64) // with either be '0' or '0.xxxx', so if 1 then t will be zero diff --git a/vendor/github.com/go-playground/universal-translator/errors.go b/vendor/github.com/go-playground/universal-translator/errors.go index 38b163b6..4fbb187b 100644 --- a/vendor/github.com/go-playground/universal-translator/errors.go +++ b/vendor/github.com/go-playground/universal-translator/errors.go @@ -7,18 +7,18 @@ import ( "github.com/go-playground/locales" ) +// ErrUnknowTranslation indicates the translation could not be found +var ErrUnknowTranslation = errors.New("Unknown Translation") + var ( - // ErrUnknowTranslation indicates the translation could not be found - ErrUnknowTranslation = errors.New("Unknown Translation") + _ error = new(ErrConflictingTranslation) + _ error = new(ErrRangeTranslation) + _ error = new(ErrOrdinalTranslation) + _ error = new(ErrCardinalTranslation) + _ error = new(ErrMissingPluralTranslation) + _ error = new(ErrExistingTranslator) ) -var _ error = new(ErrConflictingTranslation) -var _ error = new(ErrRangeTranslation) -var _ error = new(ErrOrdinalTranslation) -var _ error = new(ErrCardinalTranslation) -var _ error = new(ErrMissingPluralTranslation) -var _ error = new(ErrExistingTranslator) - // ErrExistingTranslator is the error representing a conflicting translator type ErrExistingTranslator struct { locale string @@ -39,7 +39,6 @@ type ErrConflictingTranslation struct { // Error returns ErrConflictingTranslation's internal error text func (e *ErrConflictingTranslation) Error() string { - if _, ok := e.key.(string); !ok { return fmt.Sprintf("error: conflicting key '%#v' rule '%s' with text '%s' for locale '%s', value being ignored", e.key, e.rule, e.text, e.locale) } @@ -88,7 +87,6 @@ type ErrMissingPluralTranslation struct { // Error returns ErrMissingPluralTranslation's internal error text func (e *ErrMissingPluralTranslation) Error() string { - if _, ok := e.key.(string); !ok { return fmt.Sprintf("error: missing '%s' plural rule '%s' for translation with key '%#v' and locale '%s'", e.translationType, e.rule, e.key, e.locale) } diff --git a/vendor/github.com/go-playground/universal-translator/import_export.go b/vendor/github.com/go-playground/universal-translator/import_export.go index 7bd76f26..6f83e211 100644 --- a/vendor/github.com/go-playground/universal-translator/import_export.go +++ b/vendor/github.com/go-playground/universal-translator/import_export.go @@ -3,12 +3,11 @@ package ut import ( "encoding/json" "fmt" + "io" "io/ioutil" "os" "path/filepath" - "io" - "github.com/go-playground/locales" ) @@ -39,7 +38,6 @@ const ( // // NOTE: this currently only works with string or int translations keys. func (t *UniversalTranslator) Export(format ImportExportFormat, dirname string) error { - _, err := os.Stat(dirname) fmt.Println(dirname, err, os.IsNotExist(err)) if err != nil { @@ -48,7 +46,7 @@ func (t *UniversalTranslator) Export(format ImportExportFormat, dirname string) return err } - if err = os.MkdirAll(dirname, 0744); err != nil { + if err = os.MkdirAll(dirname, 0o744); err != nil { return err } } @@ -69,7 +67,6 @@ func (t *UniversalTranslator) Export(format ImportExportFormat, dirname string) } for k, pluralTrans := range locale.(*translator).cardinalTanslations { - for i, plural := range pluralTrans { // leave enough for all plural rules @@ -89,7 +86,6 @@ func (t *UniversalTranslator) Export(format ImportExportFormat, dirname string) } for k, pluralTrans := range locale.(*translator).ordinalTanslations { - for i, plural := range pluralTrans { // leave enough for all plural rules @@ -109,7 +105,6 @@ func (t *UniversalTranslator) Export(format ImportExportFormat, dirname string) } for k, pluralTrans := range locale.(*translator).rangeTanslations { - for i, plural := range pluralTrans { // leave enough for all plural rules @@ -138,7 +133,7 @@ func (t *UniversalTranslator) Export(format ImportExportFormat, dirname string) return err } - err = ioutil.WriteFile(filepath.Join(dirname, fmt.Sprintf("%s%s", locale.Locale(), ext)), b, 0644) + err = ioutil.WriteFile(filepath.Join(dirname, fmt.Sprintf("%s%s", locale.Locale(), ext)), b, 0o644) if err != nil { return err } @@ -153,14 +148,12 @@ func (t *UniversalTranslator) Export(format ImportExportFormat, dirname string) // // NOTE: this currently only works with string or int translations keys. func (t *UniversalTranslator) Import(format ImportExportFormat, dirnameOrFilename string) error { - fi, err := os.Stat(dirnameOrFilename) if err != nil { return err } processFn := func(filename string) error { - f, err := os.Open(filename) if err != nil { return err @@ -176,7 +169,6 @@ func (t *UniversalTranslator) Import(format ImportExportFormat, dirnameOrFilenam // recursively go through directory walker := func(path string, info os.FileInfo, err error) error { - if info.IsDir() { return nil } @@ -199,7 +191,6 @@ func (t *UniversalTranslator) Import(format ImportExportFormat, dirnameOrFilenam // // NOTE: generally used when assets have been embedded into the binary and are already in memory. func (t *UniversalTranslator) ImportByReader(format ImportExportFormat, reader io.Reader) error { - b, err := ioutil.ReadAll(reader) if err != nil { return err @@ -255,7 +246,6 @@ func (t *UniversalTranslator) ImportByReader(format ImportExportFormat, reader i } func stringToPR(s string) locales.PluralRule { - switch s { case "One": return locales.PluralRuleOne @@ -270,5 +260,4 @@ func stringToPR(s string) locales.PluralRule { default: return locales.PluralRuleUnknown } - } diff --git a/vendor/github.com/go-playground/universal-translator/translator.go b/vendor/github.com/go-playground/universal-translator/translator.go index cfafce8a..cf22bf2a 100644 --- a/vendor/github.com/go-playground/universal-translator/translator.go +++ b/vendor/github.com/go-playground/universal-translator/translator.go @@ -66,8 +66,10 @@ type Translator interface { VerifyTranslations() error } -var _ Translator = new(translator) -var _ locales.Translator = new(translator) +var ( + _ Translator = new(translator) + _ locales.Translator = new(translator) +) type translator struct { locales.Translator @@ -96,7 +98,6 @@ func newTranslator(trans locales.Translator) Translator { // {#} is the only replacement type accepted and are ad infinitum // eg. one: '{0} day left' other: '{0} days left' func (t *translator) Add(key interface{}, text string, override bool) error { - if _, ok := t.translations[key]; ok && !override { return &ErrConflictingTranslation{locale: t.Locale(), key: key, text: text} } @@ -136,7 +137,6 @@ func (t *translator) Add(key interface{}, text string, override bool) error { // see AddRange below. // eg. in locale 'en' one: '{0} day left' other: '{0} days left' func (t *translator) AddCardinal(key interface{}, text string, rule locales.PluralRule, override bool) error { - var verified bool // verify plural rule exists for locale @@ -157,7 +157,6 @@ func (t *translator) AddCardinal(key interface{}, text string, rule locales.Plur if len(tarr) > 0 && tarr[rule] != nil && !override { return &ErrConflictingTranslation{locale: t.Locale(), key: key, rule: rule, text: text} } - } else { tarr = make([]*transText, 7, 7) t.cardinalTanslations[key] = tarr @@ -188,7 +187,6 @@ func (t *translator) AddCardinal(key interface{}, text string, rule locales.Plur // see AddRange below. // eg. in locale 'en' one: '{0}st day of spring' other: '{0}nd day of spring' - 1st, 2nd, 3rd... func (t *translator) AddOrdinal(key interface{}, text string, rule locales.PluralRule, override bool) error { - var verified bool // verify plural rule exists for locale @@ -209,7 +207,6 @@ func (t *translator) AddOrdinal(key interface{}, text string, rule locales.Plura if len(tarr) > 0 && tarr[rule] != nil && !override { return &ErrConflictingTranslation{locale: t.Locale(), key: key, rule: rule, text: text} } - } else { tarr = make([]*transText, 7, 7) t.ordinalTanslations[key] = tarr @@ -238,7 +235,6 @@ func (t *translator) AddOrdinal(key interface{}, text string, rule locales.Plura // {0} and {1} are the only replacement types accepted and only these are accepted. // eg. in locale 'nl' one: '{0}-{1} day left' other: '{0}-{1} days left' func (t *translator) AddRange(key interface{}, text string, rule locales.PluralRule, override bool) error { - var verified bool // verify plural rule exists for locale @@ -259,7 +255,6 @@ func (t *translator) AddRange(key interface{}, text string, rule locales.PluralR if len(tarr) > 0 && tarr[rule] != nil && !override { return &ErrConflictingTranslation{locale: t.Locale(), key: key, rule: rule, text: text} } - } else { tarr = make([]*transText, 7, 7) t.rangeTanslations[key] = tarr @@ -295,7 +290,6 @@ func (t *translator) AddRange(key interface{}, text string, rule locales.PluralR // T creates the translation for the locale given the 'key' and params passed in func (t *translator) T(key interface{}, params ...string) (string, error) { - trans, ok := t.translations[key] if !ok { return unknownTranslation, ErrUnknowTranslation @@ -321,7 +315,6 @@ func (t *translator) T(key interface{}, params ...string) (string, error) { // C creates the cardinal translation for the locale given the 'key', 'num' and 'digit' arguments and param passed in func (t *translator) C(key interface{}, num float64, digits uint64, param string) (string, error) { - tarr, ok := t.cardinalTanslations[key] if !ok { return unknownTranslation, ErrUnknowTranslation @@ -341,7 +334,6 @@ func (t *translator) C(key interface{}, num float64, digits uint64, param string // O creates the ordinal translation for the locale given the 'key', 'num' and 'digit' arguments and param passed in func (t *translator) O(key interface{}, num float64, digits uint64, param string) (string, error) { - tarr, ok := t.ordinalTanslations[key] if !ok { return unknownTranslation, ErrUnknowTranslation @@ -362,7 +354,6 @@ func (t *translator) O(key interface{}, num float64, digits uint64, param string // R creates the range translation for the locale given the 'key', 'num1', 'digit1', 'num2' and 'digit2' arguments // and 'param1' and 'param2' passed in func (t *translator) R(key interface{}, num1 float64, digits1 uint64, num2 float64, digits2 uint64, param1, param2 string) (string, error) { - tarr, ok := t.rangeTanslations[key] if !ok { return unknownTranslation, ErrUnknowTranslation @@ -385,11 +376,8 @@ func (t *translator) R(key interface{}, num1 float64, digits1 uint64, num2 float // VerifyTranslations checks to ensures that no plural rules have been // missed within the translations. func (t *translator) VerifyTranslations() error { - for k, v := range t.cardinalTanslations { - for _, rule := range t.PluralsCardinal() { - if v[rule] == nil { return &ErrMissingPluralTranslation{locale: t.Locale(), translationType: "plural", rule: rule, key: k} } @@ -397,9 +385,7 @@ func (t *translator) VerifyTranslations() error { } for k, v := range t.ordinalTanslations { - for _, rule := range t.PluralsOrdinal() { - if v[rule] == nil { return &ErrMissingPluralTranslation{locale: t.Locale(), translationType: "ordinal", rule: rule, key: k} } @@ -407,9 +393,7 @@ func (t *translator) VerifyTranslations() error { } for k, v := range t.rangeTanslations { - for _, rule := range t.PluralsRange() { - if v[rule] == nil { return &ErrMissingPluralTranslation{locale: t.Locale(), translationType: "range", rule: rule, key: k} } diff --git a/vendor/github.com/go-playground/universal-translator/universal_translator.go b/vendor/github.com/go-playground/universal-translator/universal_translator.go index dbf707f5..ed2bf236 100644 --- a/vendor/github.com/go-playground/universal-translator/universal_translator.go +++ b/vendor/github.com/go-playground/universal-translator/universal_translator.go @@ -15,7 +15,6 @@ type UniversalTranslator struct { // New returns a new UniversalTranslator instance set with // the fallback locale and locales it should support func New(fallback locales.Translator, supportedLocales ...locales.Translator) *UniversalTranslator { - t := &UniversalTranslator{ translators: make(map[string]Translator), } @@ -41,9 +40,7 @@ func New(fallback locales.Translator, supportedLocales ...locales.Translator) *U // and returns the first one it can find, otherwise returns the // fallback translator. func (t *UniversalTranslator) FindTranslator(locales ...string) (trans Translator, found bool) { - for _, locale := range locales { - if trans, found = t.translators[strings.ToLower(locale)]; found { return } @@ -55,7 +52,6 @@ func (t *UniversalTranslator) FindTranslator(locales ...string) (trans Translato // GetTranslator returns the specified translator for the given locale, // or fallback if not found func (t *UniversalTranslator) GetTranslator(locale string) (trans Translator, found bool) { - if trans, found = t.translators[strings.ToLower(locale)]; found { return } @@ -73,7 +69,6 @@ func (t *UniversalTranslator) GetFallback() Translator { // overridden; if the fallback matches the supplied translator it will be overridden as well // NOTE: this is normally only used when translator is embedded within a library func (t *UniversalTranslator) AddTranslator(translator locales.Translator, override bool) error { - lc := strings.ToLower(translator.Locale()) _, ok := t.translators[lc] if ok && !override { @@ -101,7 +96,6 @@ func (t *UniversalTranslator) AddTranslator(translator locales.Translator, overr // VerifyTranslations runs through all locales and identifies any issues // eg. missing plural rules for a locale func (t *UniversalTranslator) VerifyTranslations() (err error) { - for _, trans := range t.translators { err = trans.VerifyTranslations() if err != nil { diff --git a/vendor/github.com/go-playground/validator/v10/baked_in.go b/vendor/github.com/go-playground/validator/v10/baked_in.go index 6ce762d1..c6e45b8c 100644 --- a/vendor/github.com/go-playground/validator/v10/baked_in.go +++ b/vendor/github.com/go-playground/validator/v10/baked_in.go @@ -191,8 +191,10 @@ var ( } ) -var oneofValsCache = map[string][]string{} -var oneofValsCacheRWLock = sync.RWMutex{} +var ( + oneofValsCache = map[string][]string{} + oneofValsCacheRWLock = sync.RWMutex{} +) func parseOneOfParam2(s string) []string { oneofValsCacheRWLock.RLock() @@ -248,7 +250,6 @@ func isOneOf(fl FieldLevel) bool { // isUnique is the validation function for validating if each array|slice|map value is unique func isUnique(fl FieldLevel) bool { - field := fl.Field() param := fl.Param() v := reflect.ValueOf(struct{}{}) @@ -298,7 +299,6 @@ func isUnique(fl FieldLevel) bool { // IsMAC is the validation function for validating if the field's value is a valid MAC address. func isMAC(fl FieldLevel) bool { - _, err := net.ParseMAC(fl.Field().String()) return err == nil @@ -306,7 +306,6 @@ func isMAC(fl FieldLevel) bool { // IsCIDRv4 is the validation function for validating if the field's value is a valid v4 CIDR address. func isCIDRv4(fl FieldLevel) bool { - ip, _, err := net.ParseCIDR(fl.Field().String()) return err == nil && ip.To4() != nil @@ -314,7 +313,6 @@ func isCIDRv4(fl FieldLevel) bool { // IsCIDRv6 is the validation function for validating if the field's value is a valid v6 CIDR address. func isCIDRv6(fl FieldLevel) bool { - ip, _, err := net.ParseCIDR(fl.Field().String()) return err == nil && ip.To4() == nil @@ -322,7 +320,6 @@ func isCIDRv6(fl FieldLevel) bool { // IsCIDR is the validation function for validating if the field's value is a valid v4 or v6 CIDR address. func isCIDR(fl FieldLevel) bool { - _, _, err := net.ParseCIDR(fl.Field().String()) return err == nil @@ -330,7 +327,6 @@ func isCIDR(fl FieldLevel) bool { // IsIPv4 is the validation function for validating if a value is a valid v4 IP address. func isIPv4(fl FieldLevel) bool { - ip := net.ParseIP(fl.Field().String()) return ip != nil && ip.To4() != nil @@ -338,7 +334,6 @@ func isIPv4(fl FieldLevel) bool { // IsIPv6 is the validation function for validating if the field's value is a valid v6 IP address. func isIPv6(fl FieldLevel) bool { - ip := net.ParseIP(fl.Field().String()) return ip != nil && ip.To4() == nil @@ -346,7 +341,6 @@ func isIPv6(fl FieldLevel) bool { // IsIP is the validation function for validating if the field's value is a valid v4 or v6 IP address. func isIP(fl FieldLevel) bool { - ip := net.ParseIP(fl.Field().String()) return ip != nil @@ -354,7 +348,6 @@ func isIP(fl FieldLevel) bool { // IsSSN is the validation function for validating if the field's value is a valid SSN. func isSSN(fl FieldLevel) bool { - field := fl.Field() if field.Len() != 11 { @@ -412,7 +405,6 @@ func isLatitude(fl FieldLevel) bool { // IsDataURI is the validation function for validating if the field's value is a valid data URI. func isDataURI(fl FieldLevel) bool { - uri := strings.SplitN(fl.Field().String(), ",", 2) if len(uri) != 2 { @@ -428,7 +420,6 @@ func isDataURI(fl FieldLevel) bool { // HasMultiByteCharacter is the validation function for validating if the field's value has a multi byte character. func hasMultiByteCharacter(fl FieldLevel) bool { - field := fl.Field() if field.Len() == 0 { @@ -495,7 +486,6 @@ func isISBN(fl FieldLevel) bool { // IsISBN13 is the validation function for validating if the field's value is a valid v13 ISBN. func isISBN13(fl FieldLevel) bool { - s := strings.Replace(strings.Replace(fl.Field().String(), "-", "", 4), " ", "", 4) if !iSBN13Regex.MatchString(s) { @@ -516,7 +506,6 @@ func isISBN13(fl FieldLevel) bool { // IsISBN10 is the validation function for validating if the field's value is a valid v10 ISBN. func isISBN10(fl FieldLevel) bool { - s := strings.Replace(strings.Replace(fl.Field().String(), "-", "", 3), " ", "", 3) if !iSBN10Regex.MatchString(s) { @@ -704,7 +693,6 @@ func excludes(fl FieldLevel) bool { // ContainsRune is the validation function for validating that the field's value contains the rune specified within the param. func containsRune(fl FieldLevel) bool { - r, _ := utf8.DecodeRuneInString(fl.Param()) return strings.ContainsRune(fl.Field().String(), r) @@ -767,7 +755,6 @@ func fieldExcludes(fl FieldLevel) bool { // IsNeField is the validation function for validating if the current field's value is not equal to the field specified by the param's value. func isNeField(fl FieldLevel) bool { - field := fl.Field() kind := field.Kind() @@ -821,7 +808,6 @@ func isNe(fl FieldLevel) bool { // IsLteCrossStructField is the validation function for validating if the current field's value is less than or equal to the field, within a separate struct, specified by the param's value. func isLteCrossStructField(fl FieldLevel) bool { - field := fl.Field() kind := field.Kind() @@ -869,7 +855,6 @@ func isLteCrossStructField(fl FieldLevel) bool { // IsLtCrossStructField is the validation function for validating if the current field's value is less than the field, within a separate struct, specified by the param's value. // NOTE: This is exposed for use within your own custom functions and not intended to be called directly. func isLtCrossStructField(fl FieldLevel) bool { - field := fl.Field() kind := field.Kind() @@ -916,7 +901,6 @@ func isLtCrossStructField(fl FieldLevel) bool { // IsGteCrossStructField is the validation function for validating if the current field's value is greater than or equal to the field, within a separate struct, specified by the param's value. func isGteCrossStructField(fl FieldLevel) bool { - field := fl.Field() kind := field.Kind() @@ -963,7 +947,6 @@ func isGteCrossStructField(fl FieldLevel) bool { // IsGtCrossStructField is the validation function for validating if the current field's value is greater than the field, within a separate struct, specified by the param's value. func isGtCrossStructField(fl FieldLevel) bool { - field := fl.Field() kind := field.Kind() @@ -1010,7 +993,6 @@ func isGtCrossStructField(fl FieldLevel) bool { // IsNeCrossStructField is the validation function for validating that the current field's value is not equal to the field, within a separate struct, specified by the param's value. func isNeCrossStructField(fl FieldLevel) bool { - field := fl.Field() kind := field.Kind() @@ -1057,7 +1039,6 @@ func isNeCrossStructField(fl FieldLevel) bool { // IsEqCrossStructField is the validation function for validating that the current field's value is equal to the field, within a separate struct, specified by the param's value. func isEqCrossStructField(fl FieldLevel) bool { - field := fl.Field() kind := field.Kind() @@ -1104,7 +1085,6 @@ func isEqCrossStructField(fl FieldLevel) bool { // IsEqField is the validation function for validating if the current field's value is equal to the field specified by the param's value. func isEqField(fl FieldLevel) bool { - field := fl.Field() kind := field.Kind() @@ -1152,7 +1132,6 @@ func isEqField(fl FieldLevel) bool { // IsEq is the validation function for validating if the current field's value is equal to the param's value. func isEq(fl FieldLevel) bool { - field := fl.Field() param := fl.Param() @@ -1202,11 +1181,9 @@ func isBase64URL(fl FieldLevel) bool { // IsURI is the validation function for validating if the current field's value is a valid URI. func isURI(fl FieldLevel) bool { - field := fl.Field() switch field.Kind() { - case reflect.String: s := field.String() @@ -1231,11 +1208,9 @@ func isURI(fl FieldLevel) bool { // IsURL is the validation function for validating if the current field's value is a valid URL. func isURL(fl FieldLevel) bool { - field := fl.Field() switch field.Kind() { - case reflect.String: var i int @@ -1268,7 +1243,6 @@ func isUrnRFC2141(fl FieldLevel) bool { field := fl.Field() switch field.Kind() { - case reflect.String: str := field.String() @@ -1570,7 +1544,6 @@ func requiredWithoutAll(fl FieldLevel) bool { // IsGteField is the validation function for validating if the current field's value is greater than or equal to the field specified by the param's value. func isGteField(fl FieldLevel) bool { - field := fl.Field() kind := field.Kind() @@ -1617,7 +1590,6 @@ func isGteField(fl FieldLevel) bool { // IsGtField is the validation function for validating if the current field's value is greater than the field specified by the param's value. func isGtField(fl FieldLevel) bool { - field := fl.Field() kind := field.Kind() @@ -1664,7 +1636,6 @@ func isGtField(fl FieldLevel) bool { // IsGte is the validation function for validating if the current field's value is greater than or equal to the param's value. func isGte(fl FieldLevel) bool { - field := fl.Field() param := fl.Param() @@ -1711,7 +1682,6 @@ func isGte(fl FieldLevel) bool { // IsGt is the validation function for validating if the current field's value is greater than the param's value. func isGt(fl FieldLevel) bool { - field := fl.Field() param := fl.Param() @@ -1744,7 +1714,6 @@ func isGt(fl FieldLevel) bool { case reflect.Struct: if field.Type() == timeType { - return field.Interface().(time.Time).After(time.Now().UTC()) } } @@ -1754,7 +1723,6 @@ func isGt(fl FieldLevel) bool { // HasLengthOf is the validation function for validating if the current field's value is equal to the param's value. func hasLengthOf(fl FieldLevel) bool { - field := fl.Field() param := fl.Param() @@ -1796,7 +1764,6 @@ func hasMinOf(fl FieldLevel) bool { // IsLteField is the validation function for validating if the current field's value is less than or equal to the field specified by the param's value. func isLteField(fl FieldLevel) bool { - field := fl.Field() kind := field.Kind() @@ -1843,7 +1810,6 @@ func isLteField(fl FieldLevel) bool { // IsLtField is the validation function for validating if the current field's value is less than the field specified by the param's value. func isLtField(fl FieldLevel) bool { - field := fl.Field() kind := field.Kind() @@ -1890,7 +1856,6 @@ func isLtField(fl FieldLevel) bool { // IsLte is the validation function for validating if the current field's value is less than or equal to the param's value. func isLte(fl FieldLevel) bool { - field := fl.Field() param := fl.Param() @@ -1937,7 +1902,6 @@ func isLte(fl FieldLevel) bool { // IsLt is the validation function for validating if the current field's value is less than the param's value. func isLt(fl FieldLevel) bool { - field := fl.Field() param := fl.Param() @@ -1971,7 +1935,6 @@ func isLt(fl FieldLevel) bool { case reflect.Struct: if field.Type() == timeType { - return field.Interface().(time.Time).Before(time.Now().UTC()) } } @@ -1986,7 +1949,6 @@ func hasMaxOf(fl FieldLevel) bool { // IsTCP4AddrResolvable is the validation function for validating if the field's value is a resolvable tcp4 address. func isTCP4AddrResolvable(fl FieldLevel) bool { - if !isIP4Addr(fl) { return false } @@ -1997,7 +1959,6 @@ func isTCP4AddrResolvable(fl FieldLevel) bool { // IsTCP6AddrResolvable is the validation function for validating if the field's value is a resolvable tcp6 address. func isTCP6AddrResolvable(fl FieldLevel) bool { - if !isIP6Addr(fl) { return false } @@ -2009,7 +1970,6 @@ func isTCP6AddrResolvable(fl FieldLevel) bool { // IsTCPAddrResolvable is the validation function for validating if the field's value is a resolvable tcp address. func isTCPAddrResolvable(fl FieldLevel) bool { - if !isIP4Addr(fl) && !isIP6Addr(fl) { return false } @@ -2021,7 +1981,6 @@ func isTCPAddrResolvable(fl FieldLevel) bool { // IsUDP4AddrResolvable is the validation function for validating if the field's value is a resolvable udp4 address. func isUDP4AddrResolvable(fl FieldLevel) bool { - if !isIP4Addr(fl) { return false } @@ -2033,7 +1992,6 @@ func isUDP4AddrResolvable(fl FieldLevel) bool { // IsUDP6AddrResolvable is the validation function for validating if the field's value is a resolvable udp6 address. func isUDP6AddrResolvable(fl FieldLevel) bool { - if !isIP6Addr(fl) { return false } @@ -2045,7 +2003,6 @@ func isUDP6AddrResolvable(fl FieldLevel) bool { // IsUDPAddrResolvable is the validation function for validating if the field's value is a resolvable udp address. func isUDPAddrResolvable(fl FieldLevel) bool { - if !isIP4Addr(fl) && !isIP6Addr(fl) { return false } @@ -2057,7 +2014,6 @@ func isUDPAddrResolvable(fl FieldLevel) bool { // IsIP4AddrResolvable is the validation function for validating if the field's value is a resolvable ip4 address. func isIP4AddrResolvable(fl FieldLevel) bool { - if !isIPv4(fl) { return false } @@ -2069,7 +2025,6 @@ func isIP4AddrResolvable(fl FieldLevel) bool { // IsIP6AddrResolvable is the validation function for validating if the field's value is a resolvable ip6 address. func isIP6AddrResolvable(fl FieldLevel) bool { - if !isIPv6(fl) { return false } @@ -2081,7 +2036,6 @@ func isIP6AddrResolvable(fl FieldLevel) bool { // IsIPAddrResolvable is the validation function for validating if the field's value is a resolvable ip address. func isIPAddrResolvable(fl FieldLevel) bool { - if !isIP(fl) { return false } @@ -2093,14 +2047,12 @@ func isIPAddrResolvable(fl FieldLevel) bool { // IsUnixAddrResolvable is the validation function for validating if the field's value is a resolvable unix address. func isUnixAddrResolvable(fl FieldLevel) bool { - _, err := net.ResolveUnixAddr("unix", fl.Field().String()) return err == nil } func isIP4Addr(fl FieldLevel) bool { - val := fl.Field().String() if idx := strings.LastIndex(val, ":"); idx != -1 { @@ -2113,7 +2065,6 @@ func isIP4Addr(fl FieldLevel) bool { } func isIP6Addr(fl FieldLevel) bool { - val := fl.Field().String() if idx := strings.LastIndex(val, ":"); idx != -1 { diff --git a/vendor/github.com/go-playground/validator/v10/country_codes.go b/vendor/github.com/go-playground/validator/v10/country_codes.go index ef81eada..b0f145f4 100644 --- a/vendor/github.com/go-playground/validator/v10/country_codes.go +++ b/vendor/github.com/go-playground/validator/v10/country_codes.go @@ -107,6 +107,7 @@ var iso3166_1_alpha3 = map[string]bool{ "VNM": true, "VGB": true, "VIR": true, "WLF": true, "ESH": true, "YEM": true, "ZMB": true, "ZWE": true, "ALA": true, } + var iso3166_1_alpha_numeric = map[int]bool{ // see: https://www.iso.org/iso-3166-country-codes.html 4: true, 8: true, 12: true, 16: true, 20: true, diff --git a/vendor/github.com/go-playground/validator/v10/doc.go b/vendor/github.com/go-playground/validator/v10/doc.go index a816c20a..34f22ad4 100644 --- a/vendor/github.com/go-playground/validator/v10/doc.go +++ b/vendor/github.com/go-playground/validator/v10/doc.go @@ -1228,7 +1228,7 @@ Although empty value and Local value are allowed by time.LoadLocation golang fun More information on https://golang.org/pkg/time/#LoadLocation Usage: timezone - + Alias Validators and Tags diff --git a/vendor/github.com/go-playground/validator/v10/errors.go b/vendor/github.com/go-playground/validator/v10/errors.go index 63293cf9..5a4dce2b 100644 --- a/vendor/github.com/go-playground/validator/v10/errors.go +++ b/vendor/github.com/go-playground/validator/v10/errors.go @@ -24,7 +24,6 @@ type InvalidValidationError struct { // Error returns InvalidValidationError message func (e *InvalidValidationError) Error() string { - if e.Type == nil { return "validator: (nil)" } @@ -41,7 +40,6 @@ type ValidationErrors []FieldError // All information to create an error message specific to your application is contained within // the FieldError found within the ValidationErrors array func (ve ValidationErrors) Error() string { - buff := bytes.NewBufferString("") var fe *fieldError @@ -58,7 +56,6 @@ func (ve ValidationErrors) Error() string { // Translate translates all of the ValidationErrors func (ve ValidationErrors) Translate(ut ut.Translator) ValidationErrorsTranslations { - trans := make(ValidationErrorsTranslations) var fe *fieldError @@ -161,8 +158,10 @@ type FieldError interface { } // compile time interface checks -var _ FieldError = new(fieldError) -var _ error = new(fieldError) +var ( + _ FieldError = new(fieldError) + _ error = new(fieldError) +) // fieldError contains a single field's validation error along // with other properties that may be needed for error message creation @@ -207,7 +206,6 @@ func (fe *fieldError) StructNamespace() string { // Field returns the field's name with the tag name taking precedence over the // field's actual name. func (fe *fieldError) Field() string { - return fe.ns[len(fe.ns)-int(fe.fieldLen):] // // return fe.field // fld := fe.ns[len(fe.ns)-int(fe.fieldLen):] @@ -260,7 +258,6 @@ func (fe *fieldError) Error() string { // NOTE: if no registered translation can be found, it returns the original // untranslated error message. func (fe *fieldError) Translate(ut ut.Translator) string { - m, ok := fe.v.transTagFunc[ut] if !ok { return fe.Error() diff --git a/vendor/github.com/go-playground/validator/v10/struct_level.go b/vendor/github.com/go-playground/validator/v10/struct_level.go index 57691ee3..5f555973 100644 --- a/vendor/github.com/go-playground/validator/v10/struct_level.go +++ b/vendor/github.com/go-playground/validator/v10/struct_level.go @@ -107,7 +107,6 @@ func (v *validate) ExtractType(field reflect.Value) (reflect.Value, reflect.Kind // ReportError reports an error just by passing the field and tag information func (v *validate) ReportError(field interface{}, fieldName, structFieldName, tag, param string) { - fv, kind, _ := v.extractTypeInternal(reflect.ValueOf(field), false) if len(structFieldName) == 0 { @@ -161,7 +160,6 @@ func (v *validate) ReportError(field interface{}, fieldName, structFieldName, ta // // NOTE: this function prepends the current namespace to the relative ones. func (v *validate) ReportValidationErrors(relativeNamespace, relativeStructNamespace string, errs ValidationErrors) { - var err *fieldError for i := 0; i < len(errs); i++ { diff --git a/vendor/github.com/go-playground/validator/v10/util.go b/vendor/github.com/go-playground/validator/v10/util.go index 56420f43..02b110d2 100644 --- a/vendor/github.com/go-playground/validator/v10/util.go +++ b/vendor/github.com/go-playground/validator/v10/util.go @@ -11,7 +11,6 @@ import ( // It will dive into pointers, customTypes and return you the // underlying value and it's kind. func (v *validate) extractTypeInternal(current reflect.Value, nullable bool) (reflect.Value, reflect.Kind, bool) { - BEGIN: switch current.Kind() { case reflect.Ptr: @@ -42,7 +41,6 @@ BEGIN: default: if v.v.hasCustomFuncs { - if fn, ok := v.v.customFuncs[current.Type()]; ok { current = reflect.ValueOf(fn(current)) goto BEGIN @@ -59,7 +57,6 @@ BEGIN: // NOTE: when not successful ok will be false, this can happen when a nested struct is nil and so the field // could not be retrieved because it didn't exist. func (v *validate) getStructFieldOKInternal(val reflect.Value, namespace string) (current reflect.Value, kind reflect.Kind, nullable bool, found bool) { - BEGIN: current, kind, nullable = v.ExtractType(val) if kind == reflect.Invalid { @@ -254,7 +251,6 @@ func asIntFromType(t reflect.Type, param string) int64 { // asUint returns the parameter as a uint64 // or panics if it can't convert func asUint(param string) uint64 { - i, err := strconv.ParseUint(param, 0, 64) panicIf(err) @@ -264,7 +260,6 @@ func asUint(param string) uint64 { // asFloat returns the parameter as a float64 // or panics if it can't convert func asFloat(param string) float64 { - i, err := strconv.ParseFloat(param, 64) panicIf(err) @@ -274,7 +269,6 @@ func asFloat(param string) float64 { // asBool returns the parameter as a bool // or panics if it can't convert func asBool(param string) bool { - i, err := strconv.ParseBool(param) panicIf(err) diff --git a/vendor/github.com/go-playground/validator/v10/validator.go b/vendor/github.com/go-playground/validator/v10/validator.go index f097f394..4c0a2ba1 100644 --- a/vendor/github.com/go-playground/validator/v10/validator.go +++ b/vendor/github.com/go-playground/validator/v10/validator.go @@ -31,7 +31,6 @@ type validate struct { // parent and current will be the same the first run of validateStruct func (v *validate) validateStruct(ctx context.Context, parent reflect.Value, current reflect.Value, typ reflect.Type, ns []byte, structNs []byte, ct *cTag) { - cs, ok := v.v.structCache.Get(typ) if !ok { cs = v.v.extractStructCache(current, typ.Name()) @@ -57,13 +56,11 @@ func (v *validate) validateStruct(ctx context.Context, parent reflect.Value, cur f = cs.fields[i] if v.isPartial { - if v.ffn != nil { // used with StructFiltered if v.ffn(append(structNs, f.name...)) { continue } - } else { // used with StructPartial & StructExcept _, ok = v.includeExclude[string(append(structNs, f.name...))] @@ -355,7 +352,6 @@ OUTER: v.ct = ct if ct.fn(ctx, v) { - // drain rest of the 'or' values, then continue or leave for { @@ -390,7 +386,6 @@ OUTER: } if ct.hasAlias { - v.errs = append(v.errs, &fieldError{ v: v.v, @@ -406,7 +401,6 @@ OUTER: typ: typ, }, ) - } else { tVal := string(v.misc)[1:] @@ -473,5 +467,4 @@ OUTER: ct = ct.next } } - } diff --git a/vendor/github.com/go-playground/validator/v10/validator_instance.go b/vendor/github.com/go-playground/validator/v10/validator_instance.go index fe6a4877..b88f485b 100644 --- a/vendor/github.com/go-playground/validator/v10/validator_instance.go +++ b/vendor/github.com/go-playground/validator/v10/validator_instance.go @@ -86,7 +86,6 @@ type Validate struct { // New returns a new instance of 'validate' with sane defaults. func New() *Validate { - tc := new(tagCache) tc.m.Store(make(map[string]*cTag)) @@ -108,7 +107,6 @@ func New() *Validate { // must copy validators for separate validations to be used in each instance for k, val := range bakedInValidators { - switch k { // these require that even if the value is nil that the validation should run, omitempty still overrides this behaviour case requiredIfTag, requiredUnlessTag, requiredWithTag, requiredWithAllTag, requiredWithoutTag, requiredWithoutAllTag: @@ -196,7 +194,6 @@ func (v *Validate) registerValidation(tag string, fn FuncCtx, bakedIn bool, nilC // // NOTE: this function is not thread-safe it is intended that these all be registered prior to any validation func (v *Validate) RegisterAlias(alias, tags string) { - _, ok := restrictedTags[alias] if ok || strings.ContainsAny(alias, restrictedTagChars) { @@ -220,7 +217,6 @@ func (v *Validate) RegisterStructValidation(fn StructLevelFunc, types ...interfa // NOTE: // - this method is not thread-safe it is intended that these all be registered prior to any validation func (v *Validate) RegisterStructValidationCtx(fn StructLevelFuncCtx, types ...interface{}) { - if v.structLevelFuncs == nil { v.structLevelFuncs = make(map[reflect.Type]StructLevelFuncCtx) } @@ -239,7 +235,6 @@ func (v *Validate) RegisterStructValidationCtx(fn StructLevelFuncCtx, types ...i // // NOTE: this method is not thread-safe it is intended that these all be registered prior to any validation func (v *Validate) RegisterCustomTypeFunc(fn CustomTypeFunc, types ...interface{}) { - if v.customFuncs == nil { v.customFuncs = make(map[reflect.Type]CustomTypeFunc) } @@ -253,7 +248,6 @@ func (v *Validate) RegisterCustomTypeFunc(fn CustomTypeFunc, types ...interface{ // RegisterTranslation registers translations against the provided tag. func (v *Validate) RegisterTranslation(tag string, trans ut.Translator, registerFn RegisterTranslationsFunc, translationFn TranslationFunc) (err error) { - if v.transTagFunc == nil { v.transTagFunc = make(map[ut.Translator]map[string]TranslationFunc) } @@ -287,7 +281,6 @@ func (v *Validate) Struct(s interface{}) error { // It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. // You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. func (v *Validate) StructCtx(ctx context.Context, s interface{}) (err error) { - val := reflect.ValueOf(s) top := val diff --git a/vendor/github.com/go-sql-driver/mysql/buffer.go b/vendor/github.com/go-sql-driver/mysql/buffer.go index 0774c5c8..9d3827bf 100644 --- a/vendor/github.com/go-sql-driver/mysql/buffer.go +++ b/vendor/github.com/go-sql-driver/mysql/buffer.go @@ -14,8 +14,10 @@ import ( "time" ) -const defaultBufSize = 4096 -const maxCachedBufSize = 256 * 1024 +const ( + defaultBufSize = 4096 + maxCachedBufSize = 256 * 1024 +) // A buffer which is used for both reading and writing. // This is possible since communication on each connection is synchronous. diff --git a/vendor/github.com/go-sql-driver/mysql/collations.go b/vendor/github.com/go-sql-driver/mysql/collations.go index 8d2b5567..bdb07cf3 100644 --- a/vendor/github.com/go-sql-driver/mysql/collations.go +++ b/vendor/github.com/go-sql-driver/mysql/collations.go @@ -8,8 +8,10 @@ package mysql -const defaultCollation = "utf8mb4_general_ci" -const binaryCollation = "binary" +const ( + defaultCollation = "utf8mb4_general_ci" + binaryCollation = "binary" +) // A list of available collations mapped to the internal ID. // To update this map use the following MySQL query: diff --git a/vendor/github.com/go-sql-driver/mysql/const.go b/vendor/github.com/go-sql-driver/mysql/const.go index b1e6b85e..bf6a1df6 100644 --- a/vendor/github.com/go-sql-driver/mysql/const.go +++ b/vendor/github.com/go-sql-driver/mysql/const.go @@ -111,6 +111,7 @@ const ( fieldTypeVarChar fieldTypeBit ) + const ( fieldTypeJSON fieldType = iota + 0xf5 fieldTypeNewDecimal diff --git a/vendor/github.com/go-sql-driver/mysql/packets.go b/vendor/github.com/go-sql-driver/mysql/packets.go index 82ad7a20..d68eb552 100644 --- a/vendor/github.com/go-sql-driver/mysql/packets.go +++ b/vendor/github.com/go-sql-driver/mysql/packets.go @@ -591,7 +591,7 @@ func (mc *mysqlConn) handleErrorPacket(data []byte) error { // SQL State [optional: # + 5bytes string] if data[3] == 0x23 { - //sqlstate := string(data[4 : 4+5]) + // sqlstate := string(data[4 : 4+5]) pos = 9 } @@ -721,7 +721,7 @@ func (mc *mysqlConn) readColumns(count int) ([]mysqlField, error) { // Decimals [uint8] columns[i].decimals = data[pos] - //pos++ + // pos++ // Default value [len coded binary] //if pos < len(data) { @@ -787,7 +787,6 @@ func (rows *textRows) readRow(dest []driver.Value) error { continue } } - } else { dest[i] = nil continue @@ -1107,7 +1106,7 @@ func (stmt *mysqlStmt) writeExecutePacket(args []driver.Value) error { paramTypes[i+i+1] = 0x00 var a [64]byte - var b = a[:0] + b := a[:0] if v.IsZero() { b = append(b, "0000-00-00"...) diff --git a/vendor/github.com/go-sql-driver/mysql/statement.go b/vendor/github.com/go-sql-driver/mysql/statement.go index f7e37093..daf6fecd 100644 --- a/vendor/github.com/go-sql-driver/mysql/statement.go +++ b/vendor/github.com/go-sql-driver/mysql/statement.go @@ -26,7 +26,7 @@ func (stmt *mysqlStmt) Close() error { // driver.Stmt.Close can be called more than once, thus this function // has to be idempotent. // See also Issue #450 and golang/go#16019. - //errLog.Print(ErrInvalidConn) + // errLog.Print(ErrInvalidConn) return driver.ErrBadConn } diff --git a/vendor/github.com/go-sql-driver/mysql/utils.go b/vendor/github.com/go-sql-driver/mysql/utils.go index 9552e80b..98e7d5d4 100644 --- a/vendor/github.com/go-sql-driver/mysql/utils.go +++ b/vendor/github.com/go-sql-driver/mysql/utils.go @@ -173,8 +173,10 @@ func parseBinaryDateTime(num uint64, data []byte, loc *time.Location) (driver.Va // The current behavior depends on database/sql copying the result. var zeroDateTime = []byte("0000-00-00 00:00:00.000000") -const digits01 = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" -const digits10 = "0000000000111111111122222222223333333333444444444455555555556666666666777777777788888888889999999999" +const ( + digits01 = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" + digits10 = "0000000000111111111122222222223333333333444444444455555555556666666666777777777788888888889999999999" +) func appendMicrosecs(dst, src []byte, decimals int) []byte { if decimals <= 0 { diff --git a/vendor/github.com/golang/protobuf/proto/proto.go b/vendor/github.com/golang/protobuf/proto/proto.go index 5aee89c3..2ff784f6 100644 --- a/vendor/github.com/golang/protobuf/proto/proto.go +++ b/vendor/github.com/golang/protobuf/proto/proto.go @@ -114,6 +114,7 @@ func (e *RequiredNotSetError) Error() string { } return "proto: required field not set" } + func (e *RequiredNotSetError) RequiredNotSet() bool { return true } diff --git a/vendor/github.com/golang/protobuf/proto/registry.go b/vendor/github.com/golang/protobuf/proto/registry.go index 1e7ff642..76e0d2fc 100644 --- a/vendor/github.com/golang/protobuf/proto/registry.go +++ b/vendor/github.com/golang/protobuf/proto/registry.go @@ -92,8 +92,10 @@ type enumsByName = map[string]int32 // enumsByNumber maps enum values by number to their name counterpart. type enumsByNumber = map[int32]string -var enumCache sync.Map // map[enumName]enumsByName -var numFilesCache sync.Map // map[protoreflect.FullName]int +var ( + enumCache sync.Map // map[enumName]enumsByName + numFilesCache sync.Map // map[protoreflect.FullName]int +) // RegisterEnum is called from the generated code to register the mapping of // enum value names to enum numbers for the enum identified by s. diff --git a/vendor/github.com/hashicorp/hcl/decoder.go b/vendor/github.com/hashicorp/hcl/decoder.go index bed9ebbe..933a1fc6 100644 --- a/vendor/github.com/hashicorp/hcl/decoder.go +++ b/vendor/github.com/hashicorp/hcl/decoder.go @@ -16,10 +16,8 @@ import ( // This is the tag to use with structures to have settings for HCL const tagName = "hcl" -var ( - // nodeType holds a reference to the type of ast.Node - nodeType reflect.Type = findNodeType() -) +// nodeType holds a reference to the type of ast.Node +var nodeType reflect.Type = findNodeType() // Unmarshal accepts a byte slice as input and writes the // data to the value pointed to by v. @@ -483,12 +481,12 @@ func expandObject(node ast.Node, result reflect.Value) ast.Node { case reflect.Ptr: switch elemType.Elem().Kind() { case reflect.Struct: - //OK + // OK default: return node } case reflect.Struct: - //OK + // OK default: return node } @@ -505,7 +503,7 @@ func expandObject(node ast.Node, result reflect.Value) ast.Node { // we need to un-flatten the ast enough to decode newNode := &ast.ObjectItem{ Keys: []*ast.ObjectKey{ - &ast.ObjectKey{ + { Token: keyToken, }, }, diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/nodes.go b/vendor/github.com/hashicorp/hcl/hcl/printer/nodes.go index 7c038d12..98ae049c 100644 --- a/vendor/github.com/hashicorp/hcl/hcl/printer/nodes.go +++ b/vendor/github.com/hashicorp/hcl/hcl/printer/nodes.go @@ -16,9 +16,7 @@ const ( infinity = 1 << 30 // offset or line ) -var ( - unindent = []byte("\uE123") // in the private use space -) +var unindent = []byte("\uE123") // in the private use space type printer struct { cfg Config diff --git a/vendor/github.com/jacobweinstock/registrar/registrar.go b/vendor/github.com/jacobweinstock/registrar/registrar.go index 563205a3..e4fbaf64 100644 --- a/vendor/github.com/jacobweinstock/registrar/registrar.go +++ b/vendor/github.com/jacobweinstock/registrar/registrar.go @@ -56,7 +56,7 @@ func WithDrivers(drivers Drivers) Option { // NewRegistry returns a new Driver registry func NewRegistry(opts ...Option) *Registry { - var defaultRegistry = &Registry{ + defaultRegistry := &Registry{ Logger: defaultLogger(), } for _, opt := range opts { @@ -93,7 +93,7 @@ func (r Registry) GetDriverInterfaces() []interface{} { // interface. registered drivers must implement the Verifier interface for this. func (r Registry) FilterForCompatible(ctx context.Context) Drivers { var wg sync.WaitGroup - var mutex = &sync.Mutex{} + mutex := &sync.Mutex{} state := make(map[int]*Driver) for index, elem := range r.Drivers { diff --git a/vendor/github.com/jinzhu/gorm/association.go b/vendor/github.com/jinzhu/gorm/association.go index a73344fe..dd71ede8 100644 --- a/vendor/github.com/jinzhu/gorm/association.go +++ b/vendor/github.com/jinzhu/gorm/association.go @@ -54,7 +54,7 @@ func (association *Association) Replace(values ...interface{}) *Association { // Set foreign key to be null when clearing value (length equals 0) if len(values) == 0 { // Set foreign key to be nil - var foreignKeyMap = map[string]interface{}{} + foreignKeyMap := map[string]interface{}{} for _, foreignKey := range relationship.ForeignDBNames { foreignKeyMap[foreignKey] = nil } @@ -111,7 +111,7 @@ func (association *Association) Replace(values ...interface{}) *Association { } } else if relationship.Kind == "has_one" || relationship.Kind == "has_many" { // has_one or has_many relations, set foreign key to be nil (TODO or delete them?) - var foreignKeyMap = map[string]interface{}{} + foreignKeyMap := map[string]interface{}{} for idx, foreignKey := range relationship.ForeignDBNames { foreignKeyMap[foreignKey] = nil if field, ok := scope.FieldByName(relationship.AssociationForeignFieldNames[idx]); ok { @@ -160,7 +160,7 @@ func (association *Association) Delete(values ...interface{}) *Association { } // get association's foreign fields name - var associationScope = scope.New(reflect.New(field.Type()).Interface()) + associationScope := scope.New(reflect.New(field.Type()).Interface()) var associationForeignFieldNames []string for _, associationDBName := range relationship.AssociationForeignFieldNames { if field, ok := associationScope.FieldByName(associationDBName); ok { @@ -175,7 +175,7 @@ func (association *Association) Delete(values ...interface{}) *Association { association.setErr(relationship.JoinTableHandler.Delete(relationship.JoinTableHandler, newDB)) } else { - var foreignKeyMap = map[string]interface{}{} + foreignKeyMap := map[string]interface{}{} for _, foreignKey := range relationship.ForeignDBNames { foreignKeyMap[foreignKey] = nil } @@ -225,7 +225,7 @@ func (association *Association) Delete(values ...interface{}) *Association { for i := 0; i < field.Len(); i++ { reflectValue := field.Index(i) primaryKey := scope.getColumnAsArray(deletingResourcePrimaryFieldNames, reflectValue.Interface())[0] - var isDeleted = false + isDeleted := false for _, pk := range deletingPrimaryKeys { if equalAsString(primaryKey, pk) { isDeleted = true @@ -321,7 +321,7 @@ func (association *Association) saveAssociations(values ...interface{}) *Associa } // Assign Fields - var fieldType = field.Field.Type() + fieldType := field.Field.Type() var setFieldBackToValue, setSliceFieldBackToValue bool if reflectValue.Type().AssignableTo(fieldType) { field.Set(reflectValue) diff --git a/vendor/github.com/jinzhu/gorm/callback_query.go b/vendor/github.com/jinzhu/gorm/callback_query.go index 544afd63..ab6210ea 100644 --- a/vendor/github.com/jinzhu/gorm/callback_query.go +++ b/vendor/github.com/jinzhu/gorm/callback_query.go @@ -19,7 +19,7 @@ func queryCallback(scope *Scope) { return } - //we are only preloading relations, dont touch base model + // we are only preloading relations, dont touch base model if _, skip := scope.InstanceGet("gorm:only_preload"); skip { return } diff --git a/vendor/github.com/jinzhu/gorm/callback_query_preload.go b/vendor/github.com/jinzhu/gorm/callback_query_preload.go index a936180a..b57e9ebd 100644 --- a/vendor/github.com/jinzhu/gorm/callback_query_preload.go +++ b/vendor/github.com/jinzhu/gorm/callback_query_preload.go @@ -299,7 +299,7 @@ func (scope *Scope) handleManyToManyPreload(field *Field, conditions []interface fieldType = fieldType.Elem() } - var sourceKeys = []string{} + sourceKeys := []string{} for _, key := range joinTableHandler.SourceForeignKeys() { sourceKeys = append(sourceKeys, key.DBName) } @@ -348,7 +348,7 @@ func (scope *Scope) handleManyToManyPreload(field *Field, conditions []interface InstanceSet("gorm:skip_query_callback", true). callCallbacks(scope.db.parent.callbacks.queries) - var foreignKeys = make([]interface{}, len(sourceKeys)) + foreignKeys := make([]interface{}, len(sourceKeys)) // generate hashed forkey keys in join table for idx, joinTableField := range joinTableFields { if !joinTableField.Field.IsNil() { @@ -394,7 +394,7 @@ func (scope *Scope) handleManyToManyPreload(field *Field, conditions []interface for source, fields := range fieldsSourceMap { for _, f := range fields { - //If not 0 this means Value is a pointer and we already added preloaded models to it + // If not 0 this means Value is a pointer and we already added preloaded models to it if f.Len() != 0 { continue } diff --git a/vendor/github.com/jinzhu/gorm/dialect_common.go b/vendor/github.com/jinzhu/gorm/dialect_common.go index d549510c..009d21b4 100644 --- a/vendor/github.com/jinzhu/gorm/dialect_common.go +++ b/vendor/github.com/jinzhu/gorm/dialect_common.go @@ -12,8 +12,7 @@ import ( var keyNameRegex = regexp.MustCompile("[^a-zA-Z0-9]+") // DefaultForeignKeyNamer contains the default foreign key name generator method -type DefaultForeignKeyNamer struct { -} +type DefaultForeignKeyNamer struct{} type commonDialect struct { db SQLCommon @@ -48,7 +47,7 @@ func (s *commonDialect) fieldCanAutoIncrement(field *StructField) bool { } func (s *commonDialect) DataTypeOf(field *StructField) string { - var dataValue, sqlType, size, additionalType = ParseFieldStructForDialect(field, s) + dataValue, sqlType, size, additionalType := ParseFieldStructForDialect(field, s) if sqlType == "" { switch dataValue.Kind() { diff --git a/vendor/github.com/jinzhu/gorm/dialect_mysql.go b/vendor/github.com/jinzhu/gorm/dialect_mysql.go index b4467ffa..ffd57d31 100644 --- a/vendor/github.com/jinzhu/gorm/dialect_mysql.go +++ b/vendor/github.com/jinzhu/gorm/dialect_mysql.go @@ -31,7 +31,7 @@ func (mysql) Quote(key string) string { // Get Data Type for MySQL Dialect func (s *mysql) DataTypeOf(field *StructField) string { - var dataValue, sqlType, size, additionalType = ParseFieldStructForDialect(field, s) + dataValue, sqlType, size, additionalType := ParseFieldStructForDialect(field, s) // MySQL allows only one auto increment column per table, and it must // be a KEY column. diff --git a/vendor/github.com/jinzhu/gorm/dialect_postgres.go b/vendor/github.com/jinzhu/gorm/dialect_postgres.go index d2df3131..e6887073 100644 --- a/vendor/github.com/jinzhu/gorm/dialect_postgres.go +++ b/vendor/github.com/jinzhu/gorm/dialect_postgres.go @@ -26,7 +26,7 @@ func (postgres) BindVar(i int) string { } func (s *postgres) DataTypeOf(field *StructField) string { - var dataValue, sqlType, size, additionalType = ParseFieldStructForDialect(field, s) + dataValue, sqlType, size, additionalType := ParseFieldStructForDialect(field, s) if sqlType == "" { switch dataValue.Kind() { diff --git a/vendor/github.com/jinzhu/gorm/dialect_sqlite3.go b/vendor/github.com/jinzhu/gorm/dialect_sqlite3.go index 5f96c363..c4ef0632 100644 --- a/vendor/github.com/jinzhu/gorm/dialect_sqlite3.go +++ b/vendor/github.com/jinzhu/gorm/dialect_sqlite3.go @@ -21,7 +21,7 @@ func (sqlite3) GetName() string { // Get Data Type for Sqlite Dialect func (s *sqlite3) DataTypeOf(field *StructField) string { - var dataValue, sqlType, size, additionalType = ParseFieldStructForDialect(field, s) + dataValue, sqlType, size, additionalType := ParseFieldStructForDialect(field, s) if sqlType == "" { switch dataValue.Kind() { diff --git a/vendor/github.com/jinzhu/gorm/dialects/postgres/postgres.go b/vendor/github.com/jinzhu/gorm/dialects/postgres/postgres.go index e6c088b1..6f0dbf0c 100644 --- a/vendor/github.com/jinzhu/gorm/dialects/postgres/postgres.go +++ b/vendor/github.com/jinzhu/gorm/dialects/postgres/postgres.go @@ -3,7 +3,6 @@ package postgres import ( "database/sql" "database/sql/driver" - "encoding/json" "errors" "fmt" diff --git a/vendor/github.com/jinzhu/gorm/errors.go b/vendor/github.com/jinzhu/gorm/errors.go index d5ef8d57..bab8814a 100644 --- a/vendor/github.com/jinzhu/gorm/errors.go +++ b/vendor/github.com/jinzhu/gorm/errors.go @@ -64,7 +64,7 @@ func (errs Errors) Add(newErrors ...error) Errors { // Error takes a slice of all errors that have occurred and returns it as a formatted string func (errs Errors) Error() string { - var errors = []string{} + errors := []string{} for _, e := range errs { errors = append(errors, e.Error()) } diff --git a/vendor/github.com/jinzhu/gorm/logger.go b/vendor/github.com/jinzhu/gorm/logger.go index 88e167dd..5571a310 100644 --- a/vendor/github.com/jinzhu/gorm/logger.go +++ b/vendor/github.com/jinzhu/gorm/logger.go @@ -40,9 +40,9 @@ var LogFormatter = func(values ...interface{}) (messages []interface{}) { messages = []interface{}{source, currentTime} if len(values) == 2 { - //remove the line break + // remove the line break currentTime = currentTime[1:] - //remove the brackets + // remove the brackets source = fmt.Sprintf("\033[35m%v\033[0m", values[1]) messages = []interface{}{currentTime, source} diff --git a/vendor/github.com/jinzhu/gorm/main.go b/vendor/github.com/jinzhu/gorm/main.go index 466e80c3..43026e84 100644 --- a/vendor/github.com/jinzhu/gorm/main.go +++ b/vendor/github.com/jinzhu/gorm/main.go @@ -66,7 +66,7 @@ func Open(dialect string, args ...interface{}) (db *DB, err error) { switch value := args[0].(type) { case string: - var driver = dialect + driver := dialect if len(args) == 1 { source = value } else if len(args) >= 2 { @@ -354,7 +354,7 @@ func (s *DB) Find(out interface{}, where ...interface{}) *DB { return s.NewScope(out).inlineCondition(where...).callCallbacks(s.parent.callbacks.queries).db } -//Preloads preloads relations, don`t touch out +// Preloads preloads relations, don`t touch out func (s *DB) Preloads(out interface{}) *DB { return s.NewScope(out).InstanceSet("gorm:only_preload", 1).callCallbacks(s.parent.callbacks.queries).db } @@ -531,7 +531,6 @@ func (s *DB) Debug() *DB { // Transaction start a transaction as a block, // return error will rollback, otherwise to commit. func (s *DB) Transaction(fc func(tx *DB) error) (err error) { - if _, ok := s.db.(*sql.Tx); ok { return fc(s) } @@ -745,7 +744,7 @@ func (s *DB) RemoveForeignKey(field string, dest string) *DB { // Association start `Association Mode` to handler relations things easir in that mode, refer: https://jinzhu.github.io/gorm/associations.html#association-mode func (s *DB) Association(column string) *Association { var err error - var scope = s.Set("gorm:association:source", s.Value).NewScope(s.Value) + scope := s.Set("gorm:association:source", s.Value).NewScope(s.Value) if primaryField := scope.PrimaryField(); primaryField.IsBlank { err = errors.New("primary key can't be nil") diff --git a/vendor/github.com/jinzhu/gorm/model_struct.go b/vendor/github.com/jinzhu/gorm/model_struct.go index 57dbec38..e3313a08 100644 --- a/vendor/github.com/jinzhu/gorm/model_struct.go +++ b/vendor/github.com/jinzhu/gorm/model_struct.go @@ -367,8 +367,8 @@ func (scope *Scope) getModelStruct(rootScope *Scope, allFields []*StructField) * field.Relationship = relationship } else { // User has many comments, associationType is User, comment use UserID as foreign key - var associationType = reflectType.Name() - var toFields = toScope.GetStructFields() + associationType := reflectType.Name() + toFields := toScope.GetStructFields() relationship.Kind = "has_many" if polymorphic, _ := field.TagSettingsGet("POLYMORPHIC"); polymorphic != "" { @@ -494,8 +494,8 @@ func (scope *Scope) getModelStruct(rootScope *Scope, allFields []*StructField) * // Has One { - var foreignKeys = tagForeignKeys - var associationForeignKeys = tagAssociationForeignKeys + foreignKeys := tagForeignKeys + associationForeignKeys := tagAssociationForeignKeys // if no foreign keys defined with tag if len(foreignKeys) == 0 { // if no association foreign keys defined with tag @@ -557,8 +557,8 @@ func (scope *Scope) getModelStruct(rootScope *Scope, allFields []*StructField) * relationship.Kind = "has_one" field.Relationship = relationship } else { - var foreignKeys = tagForeignKeys - var associationForeignKeys = tagAssociationForeignKeys + foreignKeys := tagForeignKeys + associationForeignKeys := tagAssociationForeignKeys if len(foreignKeys) == 0 { // generate foreign keys & association foreign keys diff --git a/vendor/github.com/jinzhu/gorm/scope.go b/vendor/github.com/jinzhu/gorm/scope.go index 56c3d6e5..7e737405 100644 --- a/vendor/github.com/jinzhu/gorm/scope.go +++ b/vendor/github.com/jinzhu/gorm/scope.go @@ -206,7 +206,7 @@ func (scope *Scope) HasColumn(column string) bool { // SetColumn to set the column's value, column could be field or field's name/dbname func (scope *Scope) SetColumn(column interface{}, value interface{}) error { - var updateAttrs = map[string]interface{}{} + updateAttrs := map[string]interface{}{} if attrs, ok := scope.InstanceGet("gorm:update_attrs"); ok { updateAttrs = attrs.(map[string]interface{}) defer scope.InstanceSet("gorm:update_attrs", updateAttrs) @@ -875,7 +875,7 @@ func (scope *Scope) callCallbacks(funcs []*func(s *Scope)) *Scope { } func convertInterfaceToMap(values interface{}, withIgnoredField bool, db *DB) map[string]interface{} { - var attrs = map[string]interface{}{} + attrs := map[string]interface{}{} switch value := values.(type) { case map[string]interface{}: @@ -1167,7 +1167,7 @@ func (scope *Scope) createJoinTable(field *StructField) { func (scope *Scope) createTable() *Scope { var tags []string var primaryKeys []string - var primaryKeyInColumnType = false + primaryKeyInColumnType := false for _, field := range scope.GetModelStruct().StructFields { if field.IsNormal { sqlTag := scope.Dialect().DataTypeOf(field) @@ -1237,7 +1237,7 @@ func (scope *Scope) addForeignKey(field string, dest string, onDelete string, on if scope.Dialect().HasForeignKey(scope.TableName(), keyName) { return } - var query = `ALTER TABLE %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s ON DELETE %s ON UPDATE %s;` + query := `ALTER TABLE %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s ON DELETE %s ON UPDATE %s;` scope.Raw(fmt.Sprintf(query, scope.QuotedTableName(), scope.quoteIfPossible(keyName), scope.quoteIfPossible(field), dest, onDelete, onUpdate)).Exec() } @@ -1283,8 +1283,8 @@ func (scope *Scope) autoMigrate() *Scope { } func (scope *Scope) autoIndex() *Scope { - var indexes = map[string][]string{} - var uniqueIndexes = map[string][]string{} + indexes := map[string][]string{} + uniqueIndexes := map[string][]string{} for _, field := range scope.GetStructFields() { if name, ok := field.TagSettingsGet("INDEX"); ok { @@ -1336,8 +1336,8 @@ func (scope *Scope) getColumnAsArray(columns []string, values ...interface{}) (r case reflect.Slice: for i := 0; i < indirectValue.Len(); i++ { var result []interface{} - var object = indirect(indirectValue.Index(i)) - var hasValue = false + object := indirect(indirectValue.Index(i)) + hasValue := false for _, column := range columns { field := object.FieldByName(column) if hasValue || !isBlank(field) { @@ -1355,7 +1355,7 @@ func (scope *Scope) getColumnAsArray(columns []string, values ...interface{}) (r } case reflect.Struct: var result []interface{} - var hasValue = false + hasValue := false for _, column := range columns { field := indirectValue.FieldByName(column) if hasValue || !isBlank(field) { diff --git a/vendor/github.com/jinzhu/gorm/utils.go b/vendor/github.com/jinzhu/gorm/utils.go index d2ae9465..03a8221b 100644 --- a/vendor/github.com/jinzhu/gorm/utils.go +++ b/vendor/github.com/jinzhu/gorm/utils.go @@ -22,11 +22,15 @@ var NowFunc = func() time.Time { } // Copied from golint -var commonInitialisms = []string{"API", "ASCII", "CPU", "CSS", "DNS", "EOF", "GUID", "HTML", "HTTP", "HTTPS", "ID", "IP", "JSON", "LHS", "QPS", "RAM", "RHS", "RPC", "SLA", "SMTP", "SSH", "TLS", "TTL", "UID", "UI", "UUID", "URI", "URL", "UTF8", "VM", "XML", "XSRF", "XSS"} -var commonInitialismsReplacer *strings.Replacer +var ( + commonInitialisms = []string{"API", "ASCII", "CPU", "CSS", "DNS", "EOF", "GUID", "HTML", "HTTP", "HTTPS", "ID", "IP", "JSON", "LHS", "QPS", "RAM", "RHS", "RPC", "SLA", "SMTP", "SSH", "TLS", "TTL", "UID", "UI", "UUID", "URI", "URL", "UTF8", "VM", "XML", "XSRF", "XSS"} + commonInitialismsReplacer *strings.Replacer +) -var goSrcRegexp = regexp.MustCompile(`jinzhu/gorm(@.*)?/.*.go`) -var goTestRegexp = regexp.MustCompile(`jinzhu/gorm(@.*)?/.*test.go`) +var ( + goSrcRegexp = regexp.MustCompile(`jinzhu/gorm(@.*)?/.*.go`) + goTestRegexp = regexp.MustCompile(`jinzhu/gorm(@.*)?/.*test.go`) +) func init() { var commonInitialismsForReplacer []string diff --git a/vendor/github.com/jinzhu/inflection/inflections.go b/vendor/github.com/jinzhu/inflection/inflections.go index 606263bb..b7121c37 100644 --- a/vendor/github.com/jinzhu/inflection/inflections.go +++ b/vendor/github.com/jinzhu/inflection/inflections.go @@ -118,8 +118,10 @@ var irregularInflections = IrregularSlice{ var uncountableInflections = []string{"equipment", "information", "rice", "money", "species", "series", "fish", "sheep", "jeans", "police"} -var compiledPluralMaps []inflection -var compiledSingularMaps []inflection +var ( + compiledPluralMaps []inflection + compiledSingularMaps []inflection +) func compile() { compiledPluralMaps = []inflection{} @@ -135,18 +137,18 @@ func compile() { for _, value := range irregularInflections { infs := []inflection{ - inflection{regexp: regexp.MustCompile(strings.ToUpper(value.singular) + "$"), replace: strings.ToUpper(value.plural)}, - inflection{regexp: regexp.MustCompile(strings.Title(value.singular) + "$"), replace: strings.Title(value.plural)}, - inflection{regexp: regexp.MustCompile(value.singular + "$"), replace: value.plural}, + {regexp: regexp.MustCompile(strings.ToUpper(value.singular) + "$"), replace: strings.ToUpper(value.plural)}, + {regexp: regexp.MustCompile(strings.Title(value.singular) + "$"), replace: strings.Title(value.plural)}, + {regexp: regexp.MustCompile(value.singular + "$"), replace: value.plural}, } compiledPluralMaps = append(compiledPluralMaps, infs...) } for _, value := range irregularInflections { infs := []inflection{ - inflection{regexp: regexp.MustCompile(strings.ToUpper(value.plural) + "$"), replace: strings.ToUpper(value.singular)}, - inflection{regexp: regexp.MustCompile(strings.Title(value.plural) + "$"), replace: strings.Title(value.singular)}, - inflection{regexp: regexp.MustCompile(value.plural + "$"), replace: value.singular}, + {regexp: regexp.MustCompile(strings.ToUpper(value.plural) + "$"), replace: strings.ToUpper(value.singular)}, + {regexp: regexp.MustCompile(strings.Title(value.plural) + "$"), replace: strings.Title(value.singular)}, + {regexp: regexp.MustCompile(value.plural + "$"), replace: value.singular}, } compiledSingularMaps = append(compiledSingularMaps, infs...) } @@ -154,9 +156,9 @@ func compile() { for i := len(pluralInflections) - 1; i >= 0; i-- { value := pluralInflections[i] infs := []inflection{ - inflection{regexp: regexp.MustCompile(strings.ToUpper(value.find)), replace: strings.ToUpper(value.replace)}, - inflection{regexp: regexp.MustCompile(value.find), replace: value.replace}, - inflection{regexp: regexp.MustCompile("(?i)" + value.find), replace: value.replace}, + {regexp: regexp.MustCompile(strings.ToUpper(value.find)), replace: strings.ToUpper(value.replace)}, + {regexp: regexp.MustCompile(value.find), replace: value.replace}, + {regexp: regexp.MustCompile("(?i)" + value.find), replace: value.replace}, } compiledPluralMaps = append(compiledPluralMaps, infs...) } @@ -164,9 +166,9 @@ func compile() { for i := len(singularInflections) - 1; i >= 0; i-- { value := singularInflections[i] infs := []inflection{ - inflection{regexp: regexp.MustCompile(strings.ToUpper(value.find)), replace: strings.ToUpper(value.replace)}, - inflection{regexp: regexp.MustCompile(value.find), replace: value.replace}, - inflection{regexp: regexp.MustCompile("(?i)" + value.find), replace: value.replace}, + {regexp: regexp.MustCompile(strings.ToUpper(value.find)), replace: strings.ToUpper(value.replace)}, + {regexp: regexp.MustCompile(value.find), replace: value.replace}, + {regexp: regexp.MustCompile("(?i)" + value.find), replace: value.replace}, } compiledSingularMaps = append(compiledSingularMaps, infs...) } diff --git a/vendor/github.com/json-iterator/go/any.go b/vendor/github.com/json-iterator/go/any.go index f6b8aeab..9277e23a 100644 --- a/vendor/github.com/json-iterator/go/any.go +++ b/vendor/github.com/json-iterator/go/any.go @@ -3,11 +3,12 @@ package jsoniter import ( "errors" "fmt" - "github.com/modern-go/reflect2" "io" "reflect" "strconv" "unsafe" + + "github.com/modern-go/reflect2" ) // Any generic object representation. @@ -303,8 +304,7 @@ func (codec *anyCodec) IsEmpty(ptr unsafe.Pointer) bool { return any.Size() == 0 } -type directAnyCodec struct { -} +type directAnyCodec struct{} func (codec *directAnyCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { *(*Any)(ptr) = iter.readAny() diff --git a/vendor/github.com/json-iterator/go/any_str.go b/vendor/github.com/json-iterator/go/any_str.go index 1f12f661..0c8580b1 100644 --- a/vendor/github.com/json-iterator/go/any_str.go +++ b/vendor/github.com/json-iterator/go/any_str.go @@ -50,7 +50,6 @@ func (any *stringAny) ToBool() bool { func (any *stringAny) ToInt() int { return int(any.ToInt64()) - } func (any *stringAny) ToInt32() int32 { diff --git a/vendor/github.com/json-iterator/go/config.go b/vendor/github.com/json-iterator/go/config.go index 2adcdc3b..27c10741 100644 --- a/vendor/github.com/json-iterator/go/config.go +++ b/vendor/github.com/json-iterator/go/config.go @@ -211,6 +211,7 @@ func (cfg *frozenConfig) useNumber(extension DecoderExtension) { } }} } + func (cfg *frozenConfig) getTagKey() string { tagKey := cfg.configBeforeFrozen.TagKey if tagKey == "" { @@ -225,8 +226,7 @@ func (cfg *frozenConfig) RegisterExtension(extension Extension) { cfg.configBeforeFrozen = copied } -type lossyFloat32Encoder struct { -} +type lossyFloat32Encoder struct{} func (encoder *lossyFloat32Encoder) Encode(ptr unsafe.Pointer, stream *Stream) { stream.WriteFloat32Lossy(*((*float32)(ptr))) @@ -236,8 +236,7 @@ func (encoder *lossyFloat32Encoder) IsEmpty(ptr unsafe.Pointer) bool { return *((*float32)(ptr)) == 0 } -type lossyFloat64Encoder struct { -} +type lossyFloat64Encoder struct{} func (encoder *lossyFloat64Encoder) Encode(ptr unsafe.Pointer, stream *Stream) { stream.WriteFloat64Lossy(*((*float64)(ptr))) @@ -255,8 +254,7 @@ func (cfg *frozenConfig) marshalFloatWith6Digits(extension EncoderExtension) { extension[reflect2.TypeOfPtr((*float64)(nil)).Elem()] = &lossyFloat64Encoder{} } -type htmlEscapedStringEncoder struct { -} +type htmlEscapedStringEncoder struct{} func (encoder *htmlEscapedStringEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { str := *((*string)(ptr)) diff --git a/vendor/github.com/json-iterator/go/iter.go b/vendor/github.com/json-iterator/go/iter.go index 29b31cf7..11dc5508 100644 --- a/vendor/github.com/json-iterator/go/iter.go +++ b/vendor/github.com/json-iterator/go/iter.go @@ -26,8 +26,10 @@ const ( ObjectValue ) -var hexDigits []byte -var valueTypes []ValueType +var ( + hexDigits []byte + valueTypes []ValueType +) func init() { hexDigits = make([]byte, 256) diff --git a/vendor/github.com/json-iterator/go/iter_float.go b/vendor/github.com/json-iterator/go/iter_float.go index b9754638..c6cf4dbe 100644 --- a/vendor/github.com/json-iterator/go/iter_float.go +++ b/vendor/github.com/json-iterator/go/iter_float.go @@ -11,9 +11,11 @@ import ( var floatDigits []int8 -const invalidCharForNumber = int8(-1) -const endOfNumber = int8(-2) -const dotInNumber = int8(-3) +const ( + invalidCharForNumber = int8(-1) + endOfNumber = int8(-2) + dotInNumber = int8(-3) +) func init() { floatDigits = make([]int8, 256) @@ -66,7 +68,7 @@ func (iter *Iterator) ReadBigInt() (ret *big.Int) { return ret } -//ReadFloat32 read float32 +// ReadFloat32 read float32 func (iter *Iterator) ReadFloat32() (ret float32) { c := iter.nextToken() if c == '-' { diff --git a/vendor/github.com/json-iterator/go/iter_int.go b/vendor/github.com/json-iterator/go/iter_int.go index 21423203..a5f54f9c 100644 --- a/vendor/github.com/json-iterator/go/iter_int.go +++ b/vendor/github.com/json-iterator/go/iter_int.go @@ -7,8 +7,10 @@ import ( var intDigits []int8 -const uint32SafeToMultiply10 = uint32(0xffffffff)/10 - 1 -const uint64SafeToMultiple10 = uint64(0xffffffffffffffff)/10 - 1 +const ( + uint32SafeToMultiply10 = uint32(0xffffffff)/10 - 1 + uint64SafeToMultiple10 = uint64(0xffffffffffffffff)/10 - 1 +) func init() { intDigits = make([]int8, 256) @@ -144,8 +146,8 @@ func (iter *Iterator) readUint32(c byte) (ret uint32) { iter.assertInteger() return value*10 + uint32(ind2) } - //iter.head = i + 1 - //value = value * 100 + uint32(ind2) * 10 + uint32(ind3) + // iter.head = i + 1 + // value = value * 100 + uint32(ind2) * 10 + uint32(ind3) i++ ind4 := intDigits[iter.buf[i]] if ind4 == invalidCharForNumber { @@ -266,8 +268,8 @@ func (iter *Iterator) readUint64(c byte) (ret uint64) { iter.assertInteger() return value*10 + uint64(ind2) } - //iter.head = i + 1 - //value = value * 100 + uint32(ind2) * 10 + uint32(ind3) + // iter.head = i + 1 + // value = value * 100 + uint32(ind2) * 10 + uint32(ind3) i++ ind4 := intDigits[iter.buf[i]] if ind4 == invalidCharForNumber { diff --git a/vendor/github.com/json-iterator/go/reflect.go b/vendor/github.com/json-iterator/go/reflect.go index 74974ba7..f9299fa2 100644 --- a/vendor/github.com/json-iterator/go/reflect.go +++ b/vendor/github.com/json-iterator/go/reflect.go @@ -246,6 +246,7 @@ func createEncoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder { placeholder.encoder = encoder return encoder } + func _createEncoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder { encoder := createEncoderOfJsonRawMessage(ctx, typ) if encoder != nil { diff --git a/vendor/github.com/json-iterator/go/reflect_array.go b/vendor/github.com/json-iterator/go/reflect_array.go index 13a0b7b0..7eb5b1dc 100644 --- a/vendor/github.com/json-iterator/go/reflect_array.go +++ b/vendor/github.com/json-iterator/go/reflect_array.go @@ -2,9 +2,10 @@ package jsoniter import ( "fmt" - "github.com/modern-go/reflect2" "io" "unsafe" + + "github.com/modern-go/reflect2" ) func decoderOfArray(ctx *ctx, typ reflect2.Type) ValDecoder { diff --git a/vendor/github.com/json-iterator/go/reflect_dynamic.go b/vendor/github.com/json-iterator/go/reflect_dynamic.go index 8b6bc8b4..76527783 100644 --- a/vendor/github.com/json-iterator/go/reflect_dynamic.go +++ b/vendor/github.com/json-iterator/go/reflect_dynamic.go @@ -1,9 +1,10 @@ package jsoniter import ( - "github.com/modern-go/reflect2" "reflect" "unsafe" + + "github.com/modern-go/reflect2" ) type dynamicEncoder struct { @@ -19,8 +20,7 @@ func (encoder *dynamicEncoder) IsEmpty(ptr unsafe.Pointer) bool { return encoder.valType.UnsafeIndirect(ptr) == nil } -type efaceDecoder struct { -} +type efaceDecoder struct{} func (decoder *efaceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { pObj := (*interface{})(ptr) diff --git a/vendor/github.com/json-iterator/go/reflect_extension.go b/vendor/github.com/json-iterator/go/reflect_extension.go index 74a97bfe..4b27e0f2 100644 --- a/vendor/github.com/json-iterator/go/reflect_extension.go +++ b/vendor/github.com/json-iterator/go/reflect_extension.go @@ -2,19 +2,22 @@ package jsoniter import ( "fmt" - "github.com/modern-go/reflect2" "reflect" "sort" "strings" "unicode" "unsafe" + + "github.com/modern-go/reflect2" ) -var typeDecoders = map[string]ValDecoder{} -var fieldDecoders = map[string]ValDecoder{} -var typeEncoders = map[string]ValEncoder{} -var fieldEncoders = map[string]ValEncoder{} -var extensions = []Extension{} +var ( + typeDecoders = map[string]ValDecoder{} + fieldDecoders = map[string]ValDecoder{} + typeEncoders = map[string]ValEncoder{} + fieldEncoders = map[string]ValEncoder{} + extensions = []Extension{} +) // StructDescriptor describe how should we encode/decode the struct type StructDescriptor struct { @@ -56,8 +59,7 @@ type Extension interface { } // DummyExtension embed this type get dummy implementation for all methods of Extension -type DummyExtension struct { -} +type DummyExtension struct{} // UpdateStructDescriptor No-op func (extension *DummyExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) { @@ -253,6 +255,7 @@ func getTypeDecoderFromExtension(ctx *ctx, typ reflect2.Type) ValDecoder { } return decoder } + func _getTypeDecoderFromExtension(ctx *ctx, typ reflect2.Type) ValDecoder { for _, extension := range extensions { decoder := extension.CreateDecoder(typ) @@ -395,6 +398,7 @@ func describeStruct(ctx *ctx, typ reflect2.Type) *StructDescriptor { } return createStructDescriptor(ctx, typ, bindings, embeddedBindings) } + func createStructDescriptor(ctx *ctx, typ reflect2.Type, bindings []*Binding, embeddedBindings []*Binding) *StructDescriptor { structDescriptor := &StructDescriptor{ Type: typ, diff --git a/vendor/github.com/json-iterator/go/reflect_json_number.go b/vendor/github.com/json-iterator/go/reflect_json_number.go index 98d45c1e..4835911b 100644 --- a/vendor/github.com/json-iterator/go/reflect_json_number.go +++ b/vendor/github.com/json-iterator/go/reflect_json_number.go @@ -2,9 +2,10 @@ package jsoniter import ( "encoding/json" - "github.com/modern-go/reflect2" "strconv" "unsafe" + + "github.com/modern-go/reflect2" ) type Number string @@ -32,8 +33,10 @@ func CastJsonNumber(val interface{}) (string, bool) { return "", false } -var jsonNumberType = reflect2.TypeOfPtr((*json.Number)(nil)).Elem() -var jsoniterNumberType = reflect2.TypeOfPtr((*Number)(nil)).Elem() +var ( + jsonNumberType = reflect2.TypeOfPtr((*json.Number)(nil)).Elem() + jsoniterNumberType = reflect2.TypeOfPtr((*Number)(nil)).Elem() +) func createDecoderOfJsonNumber(ctx *ctx, typ reflect2.Type) ValDecoder { if typ.AssignableTo(jsonNumberType) { @@ -55,8 +58,7 @@ func createEncoderOfJsonNumber(ctx *ctx, typ reflect2.Type) ValEncoder { return nil } -type jsonNumberCodec struct { -} +type jsonNumberCodec struct{} func (codec *jsonNumberCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { switch iter.WhatIsNext() { @@ -83,8 +85,7 @@ func (codec *jsonNumberCodec) IsEmpty(ptr unsafe.Pointer) bool { return len(*((*json.Number)(ptr))) == 0 } -type jsoniterNumberCodec struct { -} +type jsoniterNumberCodec struct{} func (codec *jsoniterNumberCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { switch iter.WhatIsNext() { diff --git a/vendor/github.com/json-iterator/go/reflect_json_raw_message.go b/vendor/github.com/json-iterator/go/reflect_json_raw_message.go index f2619936..e59b816b 100644 --- a/vendor/github.com/json-iterator/go/reflect_json_raw_message.go +++ b/vendor/github.com/json-iterator/go/reflect_json_raw_message.go @@ -2,12 +2,15 @@ package jsoniter import ( "encoding/json" - "github.com/modern-go/reflect2" "unsafe" + + "github.com/modern-go/reflect2" ) -var jsonRawMessageType = reflect2.TypeOfPtr((*json.RawMessage)(nil)).Elem() -var jsoniterRawMessageType = reflect2.TypeOfPtr((*RawMessage)(nil)).Elem() +var ( + jsonRawMessageType = reflect2.TypeOfPtr((*json.RawMessage)(nil)).Elem() + jsoniterRawMessageType = reflect2.TypeOfPtr((*RawMessage)(nil)).Elem() +) func createEncoderOfJsonRawMessage(ctx *ctx, typ reflect2.Type) ValEncoder { if typ == jsonRawMessageType { @@ -29,8 +32,7 @@ func createDecoderOfJsonRawMessage(ctx *ctx, typ reflect2.Type) ValDecoder { return nil } -type jsonRawMessageCodec struct { -} +type jsonRawMessageCodec struct{} func (codec *jsonRawMessageCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { *((*json.RawMessage)(ptr)) = json.RawMessage(iter.SkipAndReturnBytes()) @@ -44,8 +46,7 @@ func (codec *jsonRawMessageCodec) IsEmpty(ptr unsafe.Pointer) bool { return len(*((*json.RawMessage)(ptr))) == 0 } -type jsoniterRawMessageCodec struct { -} +type jsoniterRawMessageCodec struct{} func (codec *jsoniterRawMessageCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { *((*RawMessage)(ptr)) = RawMessage(iter.SkipAndReturnBytes()) diff --git a/vendor/github.com/json-iterator/go/reflect_map.go b/vendor/github.com/json-iterator/go/reflect_map.go index 58296713..696194bd 100644 --- a/vendor/github.com/json-iterator/go/reflect_map.go +++ b/vendor/github.com/json-iterator/go/reflect_map.go @@ -2,11 +2,12 @@ package jsoniter import ( "fmt" - "github.com/modern-go/reflect2" "io" "reflect" "sort" "unsafe" + + "github.com/modern-go/reflect2" ) func decoderOfMap(ctx *ctx, typ reflect2.Type) ValDecoder { diff --git a/vendor/github.com/json-iterator/go/reflect_marshaler.go b/vendor/github.com/json-iterator/go/reflect_marshaler.go index 3e21f375..17647238 100644 --- a/vendor/github.com/json-iterator/go/reflect_marshaler.go +++ b/vendor/github.com/json-iterator/go/reflect_marshaler.go @@ -8,10 +8,12 @@ import ( "github.com/modern-go/reflect2" ) -var marshalerType = reflect2.TypeOfPtr((*json.Marshaler)(nil)).Elem() -var unmarshalerType = reflect2.TypeOfPtr((*json.Unmarshaler)(nil)).Elem() -var textMarshalerType = reflect2.TypeOfPtr((*encoding.TextMarshaler)(nil)).Elem() -var textUnmarshalerType = reflect2.TypeOfPtr((*encoding.TextUnmarshaler)(nil)).Elem() +var ( + marshalerType = reflect2.TypeOfPtr((*json.Marshaler)(nil)).Elem() + unmarshalerType = reflect2.TypeOfPtr((*json.Unmarshaler)(nil)).Elem() + textMarshalerType = reflect2.TypeOfPtr((*encoding.TextMarshaler)(nil)).Elem() + textUnmarshalerType = reflect2.TypeOfPtr((*encoding.TextUnmarshaler)(nil)).Elem() +) func createDecoderOfMarshaler(ctx *ctx, typ reflect2.Type) ValDecoder { ptrType := reflect2.PtrTo(typ) diff --git a/vendor/github.com/json-iterator/go/reflect_native.go b/vendor/github.com/json-iterator/go/reflect_native.go index f88722d1..d66dd023 100644 --- a/vendor/github.com/json-iterator/go/reflect_native.go +++ b/vendor/github.com/json-iterator/go/reflect_native.go @@ -202,8 +202,7 @@ func createDecoderOfNative(ctx *ctx, typ reflect2.Type) ValDecoder { return nil } -type stringCodec struct { -} +type stringCodec struct{} func (codec *stringCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { *((*string)(ptr)) = iter.ReadString() @@ -218,8 +217,7 @@ func (codec *stringCodec) IsEmpty(ptr unsafe.Pointer) bool { return *((*string)(ptr)) == "" } -type int8Codec struct { -} +type int8Codec struct{} func (codec *int8Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { if !iter.ReadNil() { @@ -235,8 +233,7 @@ func (codec *int8Codec) IsEmpty(ptr unsafe.Pointer) bool { return *((*int8)(ptr)) == 0 } -type int16Codec struct { -} +type int16Codec struct{} func (codec *int16Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { if !iter.ReadNil() { @@ -252,8 +249,7 @@ func (codec *int16Codec) IsEmpty(ptr unsafe.Pointer) bool { return *((*int16)(ptr)) == 0 } -type int32Codec struct { -} +type int32Codec struct{} func (codec *int32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { if !iter.ReadNil() { @@ -269,8 +265,7 @@ func (codec *int32Codec) IsEmpty(ptr unsafe.Pointer) bool { return *((*int32)(ptr)) == 0 } -type int64Codec struct { -} +type int64Codec struct{} func (codec *int64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { if !iter.ReadNil() { @@ -286,8 +281,7 @@ func (codec *int64Codec) IsEmpty(ptr unsafe.Pointer) bool { return *((*int64)(ptr)) == 0 } -type uint8Codec struct { -} +type uint8Codec struct{} func (codec *uint8Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { if !iter.ReadNil() { @@ -303,8 +297,7 @@ func (codec *uint8Codec) IsEmpty(ptr unsafe.Pointer) bool { return *((*uint8)(ptr)) == 0 } -type uint16Codec struct { -} +type uint16Codec struct{} func (codec *uint16Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { if !iter.ReadNil() { @@ -320,8 +313,7 @@ func (codec *uint16Codec) IsEmpty(ptr unsafe.Pointer) bool { return *((*uint16)(ptr)) == 0 } -type uint32Codec struct { -} +type uint32Codec struct{} func (codec *uint32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { if !iter.ReadNil() { @@ -337,8 +329,7 @@ func (codec *uint32Codec) IsEmpty(ptr unsafe.Pointer) bool { return *((*uint32)(ptr)) == 0 } -type uint64Codec struct { -} +type uint64Codec struct{} func (codec *uint64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { if !iter.ReadNil() { @@ -354,8 +345,7 @@ func (codec *uint64Codec) IsEmpty(ptr unsafe.Pointer) bool { return *((*uint64)(ptr)) == 0 } -type float32Codec struct { -} +type float32Codec struct{} func (codec *float32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { if !iter.ReadNil() { @@ -371,8 +361,7 @@ func (codec *float32Codec) IsEmpty(ptr unsafe.Pointer) bool { return *((*float32)(ptr)) == 0 } -type float64Codec struct { -} +type float64Codec struct{} func (codec *float64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { if !iter.ReadNil() { @@ -388,8 +377,7 @@ func (codec *float64Codec) IsEmpty(ptr unsafe.Pointer) bool { return *((*float64)(ptr)) == 0 } -type boolCodec struct { -} +type boolCodec struct{} func (codec *boolCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { if !iter.ReadNil() { diff --git a/vendor/github.com/json-iterator/go/reflect_optional.go b/vendor/github.com/json-iterator/go/reflect_optional.go index fa71f474..d71b0373 100644 --- a/vendor/github.com/json-iterator/go/reflect_optional.go +++ b/vendor/github.com/json-iterator/go/reflect_optional.go @@ -1,8 +1,9 @@ package jsoniter import ( - "github.com/modern-go/reflect2" "unsafe" + + "github.com/modern-go/reflect2" ) func decoderOfOptional(ctx *ctx, typ reflect2.Type) ValDecoder { @@ -30,12 +31,12 @@ func (decoder *OptionalDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { *((*unsafe.Pointer)(ptr)) = nil } else { if *((*unsafe.Pointer)(ptr)) == nil { - //pointer to null, we have to allocate memory to hold the value + // pointer to null, we have to allocate memory to hold the value newPtr := decoder.ValueType.UnsafeNew() decoder.ValueDecoder.Decode(newPtr, iter) *((*unsafe.Pointer)(ptr)) = newPtr } else { - //reuse existing instance + // reuse existing instance decoder.ValueDecoder.Decode(*((*unsafe.Pointer)(ptr)), iter) } } @@ -49,12 +50,12 @@ type dereferenceDecoder struct { func (decoder *dereferenceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { if *((*unsafe.Pointer)(ptr)) == nil { - //pointer to null, we have to allocate memory to hold the value + // pointer to null, we have to allocate memory to hold the value newPtr := decoder.valueType.UnsafeNew() decoder.valueDecoder.Decode(newPtr, iter) *((*unsafe.Pointer)(ptr)) = newPtr } else { - //reuse existing instance + // reuse existing instance decoder.valueDecoder.Decode(*((*unsafe.Pointer)(ptr)), iter) } } diff --git a/vendor/github.com/json-iterator/go/reflect_slice.go b/vendor/github.com/json-iterator/go/reflect_slice.go index 9441d79d..f363a716 100644 --- a/vendor/github.com/json-iterator/go/reflect_slice.go +++ b/vendor/github.com/json-iterator/go/reflect_slice.go @@ -2,9 +2,10 @@ package jsoniter import ( "fmt" - "github.com/modern-go/reflect2" "io" "unsafe" + + "github.com/modern-go/reflect2" ) func decoderOfSlice(ctx *ctx, typ reflect2.Type) ValDecoder { diff --git a/vendor/github.com/json-iterator/go/reflect_struct_decoder.go b/vendor/github.com/json-iterator/go/reflect_struct_decoder.go index d7eb0eb5..b424b581 100644 --- a/vendor/github.com/json-iterator/go/reflect_struct_decoder.go +++ b/vendor/github.com/json-iterator/go/reflect_struct_decoder.go @@ -111,10 +111,12 @@ func createStructDecoder(ctx *ctx, typ reflect2.Type, fields map[string]*structF fieldDecoder3 = fieldDecoder } } - return &threeFieldsStructDecoder{typ, + return &threeFieldsStructDecoder{ + typ, fieldName1, fieldDecoder1, fieldName2, fieldDecoder2, - fieldName3, fieldDecoder3} + fieldName3, fieldDecoder3, + } case 4: var fieldName1 int64 var fieldName2 int64 @@ -145,11 +147,13 @@ func createStructDecoder(ctx *ctx, typ reflect2.Type, fields map[string]*structF fieldDecoder4 = fieldDecoder } } - return &fourFieldsStructDecoder{typ, + return &fourFieldsStructDecoder{ + typ, fieldName1, fieldDecoder1, fieldName2, fieldDecoder2, fieldName3, fieldDecoder3, - fieldName4, fieldDecoder4} + fieldName4, fieldDecoder4, + } case 5: var fieldName1 int64 var fieldName2 int64 @@ -185,12 +189,14 @@ func createStructDecoder(ctx *ctx, typ reflect2.Type, fields map[string]*structF fieldDecoder5 = fieldDecoder } } - return &fiveFieldsStructDecoder{typ, + return &fiveFieldsStructDecoder{ + typ, fieldName1, fieldDecoder1, fieldName2, fieldDecoder2, fieldName3, fieldDecoder3, fieldName4, fieldDecoder4, - fieldName5, fieldDecoder5} + fieldName5, fieldDecoder5, + } case 6: var fieldName1 int64 var fieldName2 int64 @@ -231,13 +237,15 @@ func createStructDecoder(ctx *ctx, typ reflect2.Type, fields map[string]*structF fieldDecoder6 = fieldDecoder } } - return &sixFieldsStructDecoder{typ, + return &sixFieldsStructDecoder{ + typ, fieldName1, fieldDecoder1, fieldName2, fieldDecoder2, fieldName3, fieldDecoder3, fieldName4, fieldDecoder4, fieldName5, fieldDecoder5, - fieldName6, fieldDecoder6} + fieldName6, fieldDecoder6, + } case 7: var fieldName1 int64 var fieldName2 int64 @@ -283,14 +291,16 @@ func createStructDecoder(ctx *ctx, typ reflect2.Type, fields map[string]*structF fieldDecoder7 = fieldDecoder } } - return &sevenFieldsStructDecoder{typ, + return &sevenFieldsStructDecoder{ + typ, fieldName1, fieldDecoder1, fieldName2, fieldDecoder2, fieldName3, fieldDecoder3, fieldName4, fieldDecoder4, fieldName5, fieldDecoder5, fieldName6, fieldDecoder6, - fieldName7, fieldDecoder7} + fieldName7, fieldDecoder7, + } case 8: var fieldName1 int64 var fieldName2 int64 @@ -341,7 +351,8 @@ func createStructDecoder(ctx *ctx, typ reflect2.Type, fields map[string]*structF fieldDecoder8 = fieldDecoder } } - return &eightFieldsStructDecoder{typ, + return &eightFieldsStructDecoder{ + typ, fieldName1, fieldDecoder1, fieldName2, fieldDecoder2, fieldName3, fieldDecoder3, @@ -349,7 +360,8 @@ func createStructDecoder(ctx *ctx, typ reflect2.Type, fields map[string]*structF fieldName5, fieldDecoder5, fieldName6, fieldDecoder6, fieldName7, fieldDecoder7, - fieldName8, fieldDecoder8} + fieldName8, fieldDecoder8, + } case 9: var fieldName1 int64 var fieldName2 int64 @@ -405,7 +417,8 @@ func createStructDecoder(ctx *ctx, typ reflect2.Type, fields map[string]*structF fieldDecoder9 = fieldDecoder } } - return &nineFieldsStructDecoder{typ, + return &nineFieldsStructDecoder{ + typ, fieldName1, fieldDecoder1, fieldName2, fieldDecoder2, fieldName3, fieldDecoder3, @@ -414,7 +427,8 @@ func createStructDecoder(ctx *ctx, typ reflect2.Type, fields map[string]*structF fieldName6, fieldDecoder6, fieldName7, fieldDecoder7, fieldName8, fieldDecoder8, - fieldName9, fieldDecoder9} + fieldName9, fieldDecoder9, + } case 10: var fieldName1 int64 var fieldName2 int64 @@ -475,7 +489,8 @@ func createStructDecoder(ctx *ctx, typ reflect2.Type, fields map[string]*structF fieldDecoder10 = fieldDecoder } } - return &tenFieldsStructDecoder{typ, + return &tenFieldsStructDecoder{ + typ, fieldName1, fieldDecoder1, fieldName2, fieldDecoder2, fieldName3, fieldDecoder3, @@ -485,7 +500,8 @@ func createStructDecoder(ctx *ctx, typ reflect2.Type, fields map[string]*structF fieldName7, fieldDecoder7, fieldName8, fieldDecoder8, fieldName9, fieldDecoder9, - fieldName10, fieldDecoder10} + fieldName10, fieldDecoder10, + } } return &generalStructDecoder{typ, fields, false} } diff --git a/vendor/github.com/json-iterator/go/reflect_struct_encoder.go b/vendor/github.com/json-iterator/go/reflect_struct_encoder.go index 152e3ef5..46817a08 100644 --- a/vendor/github.com/json-iterator/go/reflect_struct_encoder.go +++ b/vendor/github.com/json-iterator/go/reflect_struct_encoder.go @@ -2,10 +2,11 @@ package jsoniter import ( "fmt" - "github.com/modern-go/reflect2" "io" "reflect" "unsafe" + + "github.com/modern-go/reflect2" ) func encoderOfStruct(ctx *ctx, typ reflect2.Type) ValEncoder { @@ -168,8 +169,7 @@ func (encoder *structEncoder) IsEmpty(ptr unsafe.Pointer) bool { return false } -type emptyStructEncoder struct { -} +type emptyStructEncoder struct{} func (encoder *emptyStructEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { stream.WriteEmptyObject() diff --git a/vendor/github.com/labstack/echo/bind.go b/vendor/github.com/labstack/echo/bind.go index 4998e25b..77bd9604 100644 --- a/vendor/github.com/labstack/echo/bind.go +++ b/vendor/github.com/labstack/echo/bind.go @@ -145,7 +145,6 @@ func (b *DefaultBinder) bindData(ptr interface{}, data map[string][]string, tag val.Field(i).Set(slice) } else if err := setWithProperType(typeField.Type.Kind(), inputValue[0], structField); err != nil { return err - } } return nil diff --git a/vendor/github.com/labstack/echo/context.go b/vendor/github.com/labstack/echo/context.go index d4722700..1b01c22b 100644 --- a/vendor/github.com/labstack/echo/context.go +++ b/vendor/github.com/labstack/echo/context.go @@ -597,4 +597,3 @@ func (c *context) Reset(r *http.Request, w http.ResponseWriter) { // NOTE: Don't reset because it has to have length c.echo.maxParam at all times // c.pvalues = nil } - diff --git a/vendor/github.com/labstack/echo/echo.go b/vendor/github.com/labstack/echo/echo.go index 98286515..4520b496 100644 --- a/vendor/github.com/labstack/echo/echo.go +++ b/vendor/github.com/labstack/echo/echo.go @@ -236,20 +236,18 @@ ____________________________________O/_______ ` ) -var ( - methods = [...]string{ - http.MethodConnect, - http.MethodDelete, - http.MethodGet, - http.MethodHead, - http.MethodOptions, - http.MethodPatch, - http.MethodPost, - PROPFIND, - http.MethodPut, - http.MethodTrace, - } -) +var methods = [...]string{ + http.MethodConnect, + http.MethodDelete, + http.MethodGet, + http.MethodHead, + http.MethodOptions, + http.MethodPatch, + http.MethodPost, + PROPFIND, + http.MethodPut, + http.MethodTrace, +} // Errors var ( diff --git a/vendor/github.com/leodido/go-urn/machine.go b/vendor/github.com/leodido/go-urn/machine.go index fe5a0cc8..25ba623a 100644 --- a/vendor/github.com/leodido/go-urn/machine.go +++ b/vendor/github.com/leodido/go-urn/machine.go @@ -13,11 +13,15 @@ var ( errParse = "parsing error [col %d]" ) -const start int = 1 -const firstFinal int = 44 +const ( + start int = 1 + firstFinal int = 44 +) -const enFail int = 46 -const enMain int = 1 +const ( + enFail int = 46 + enMain int = 1 +) // Machine is the interface representing the FSM type Machine interface { diff --git a/vendor/github.com/leodido/go-urn/urn.go b/vendor/github.com/leodido/go-urn/urn.go index d51a6c91..64153868 100644 --- a/vendor/github.com/leodido/go-urn/urn.go +++ b/vendor/github.com/leodido/go-urn/urn.go @@ -83,4 +83,4 @@ func (u *URN) UnmarshalJSON(bytes []byte) error { *u = *value } return nil -} \ No newline at end of file +} diff --git a/vendor/github.com/lib/pq/array.go b/vendor/github.com/lib/pq/array.go index 405da236..7625350a 100644 --- a/vendor/github.com/lib/pq/array.go +++ b/vendor/github.com/lib/pq/array.go @@ -11,9 +11,11 @@ import ( "strings" ) -var typeByteSlice = reflect.TypeOf([]byte{}) -var typeDriverValuer = reflect.TypeOf((*driver.Valuer)(nil)).Elem() -var typeSQLScanner = reflect.TypeOf((*sql.Scanner)(nil)).Elem() +var ( + typeByteSlice = reflect.TypeOf([]byte{}) + typeDriverValuer = reflect.TypeOf((*driver.Valuer)(nil)).Elem() + typeSQLScanner = reflect.TypeOf((*sql.Scanner)(nil)).Elem() +) // Array returns the optimal driver.Valuer and sql.Scanner for an array or // slice of any dimension. @@ -349,7 +351,7 @@ type GenericArray struct{ A interface{} } func (GenericArray) evaluateDestination(rt reflect.Type) (reflect.Type, func([]byte, reflect.Value) error, string) { var assign func([]byte, reflect.Value) error - var del = "," + del := "," // TODO calculate the assign function for other types // TODO repeat this section on the element type of arrays or slices (multidimensional) @@ -726,7 +728,7 @@ func appendArrayElement(b []byte, rv reflect.Value) ([]byte, string, error) { } } - var del = "," + del := "," var err error var iv interface{} = rv.Interface() @@ -811,7 +813,7 @@ Element: dims[depth-1] = 0 i++ case '"': - var elem = []byte{} + elem := []byte{} var escape bool for i++; i < len(src); i++ { if escape { diff --git a/vendor/github.com/lib/pq/conn.go b/vendor/github.com/lib/pq/conn.go index db0b6cef..11c21bb6 100644 --- a/vendor/github.com/lib/pq/conn.go +++ b/vendor/github.com/lib/pq/conn.go @@ -110,11 +110,13 @@ type defaultDialer struct { func (d defaultDialer) Dial(network, address string) (net.Conn, error) { return d.d.Dial(network, address) } + func (d defaultDialer) DialTimeout(network, address string, timeout time.Duration) (net.Conn, error) { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() return d.DialContext(ctx, network, address) } + func (d defaultDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) { return d.d.DialContext(ctx, network, address) } @@ -1302,8 +1304,10 @@ func (cn *conn) auth(r *readBuf, o values) { type format int -const formatText format = 0 -const formatBinary format = 1 +const ( + formatText format = 0 + formatBinary format = 1 +) // One result-column format code with the value 1 (i.e. all binary). var colFmtDataAllBinary = []byte{0, 1, 0, 1} @@ -1416,7 +1420,6 @@ func (st *stmt) exec(v []driver.Value) { cn.readBindResponse() cn.postExecuteWorkaround() - } func (st *stmt) NumInput() int { diff --git a/vendor/github.com/lib/pq/encode.go b/vendor/github.com/lib/pq/encode.go index c4dafe27..57251863 100644 --- a/vendor/github.com/lib/pq/encode.go +++ b/vendor/github.com/lib/pq/encode.go @@ -297,9 +297,11 @@ func (c *locationCache) getLocation(offset int) *time.Location { return location } -var infinityTsEnabled = false -var infinityTsNegative time.Time -var infinityTsPositive time.Time +var ( + infinityTsEnabled = false + infinityTsNegative time.Time + infinityTsPositive time.Time +) const ( infinityTsEnabledAlready = "pq: infinity timestamp enabled already" diff --git a/vendor/github.com/lib/pq/scram/scram.go b/vendor/github.com/lib/pq/scram/scram.go index 477216b6..e7cc965c 100644 --- a/vendor/github.com/lib/pq/scram/scram.go +++ b/vendor/github.com/lib/pq/scram/scram.go @@ -197,7 +197,7 @@ func (c *Client) step2(in []byte) error { func (c *Client) step3(in []byte) error { var isv, ise bool - var fields = bytes.Split(in, []byte(",")) + fields := bytes.Split(in, []byte(",")) if len(fields) == 1 { isv = bytes.HasPrefix(fields[0], []byte("v=")) ise = bytes.HasPrefix(fields[0], []byte("e=")) diff --git a/vendor/github.com/lib/pq/ssl_permissions.go b/vendor/github.com/lib/pq/ssl_permissions.go index 3b7c3a2a..8b2c7971 100644 --- a/vendor/github.com/lib/pq/ssl_permissions.go +++ b/vendor/github.com/lib/pq/ssl_permissions.go @@ -13,7 +13,7 @@ func sslKeyPermissions(sslkey string) error { if err != nil { return err } - if info.Mode().Perm()&0077 != 0 { + if info.Mode().Perm()&0o077 != 0 { return ErrSSLKeyHasWorldPermissions } return nil diff --git a/vendor/github.com/magiconair/properties/decode.go b/vendor/github.com/magiconair/properties/decode.go index 3ebf8049..4a5b717d 100644 --- a/vendor/github.com/magiconair/properties/decode.go +++ b/vendor/github.com/magiconair/properties/decode.go @@ -281,9 +281,11 @@ func isTime(t reflect.Type) bool { return t == reflect.TypeOf(time.Time{}) } func isFloat(t reflect.Type) bool { return t.Kind() == reflect.Float32 || t.Kind() == reflect.Float64 } + func isInt(t reflect.Type) bool { return t.Kind() == reflect.Int || t.Kind() == reflect.Int8 || t.Kind() == reflect.Int16 || t.Kind() == reflect.Int32 || t.Kind() == reflect.Int64 } + func isUint(t reflect.Type) bool { return t.Kind() == reflect.Uint || t.Kind() == reflect.Uint8 || t.Kind() == reflect.Uint16 || t.Kind() == reflect.Uint32 || t.Kind() == reflect.Uint64 } diff --git a/vendor/github.com/magiconair/properties/properties.go b/vendor/github.com/magiconair/properties/properties.go index 0d0fc282..4b5541ba 100644 --- a/vendor/github.com/magiconair/properties/properties.go +++ b/vendor/github.com/magiconair/properties/properties.go @@ -111,7 +111,6 @@ func (p *Properties) Get(key string) (value string, ok bool) { } expanded, err := p.expand(key, v) - // we guarantee that the expanded value is free of // circular references and malformed expressions // so we panic if we still get an error here. diff --git a/vendor/github.com/manyminds/api2go/api.go b/vendor/github.com/manyminds/api2go/api.go index 924c13a2..298524d2 100644 --- a/vendor/github.com/manyminds/api2go/api.go +++ b/vendor/github.com/manyminds/api2go/api.go @@ -573,7 +573,6 @@ func (res *resource) handleRead(c APIContexter, w http.ResponseWriter, r *http.R id := params["id"] response, err := source.FindOne(id, buildRequest(c, r)) - if err != nil { return err } @@ -770,7 +769,6 @@ func (res *resource) handleUpdate(c APIContexter, w http.ResponseWriter, r *http } response, err := source.Update(updatingObj.Interface(), buildRequest(c, r)) - if err != nil { return err } diff --git a/vendor/github.com/manyminds/api2go/api_interfaces.go b/vendor/github.com/manyminds/api2go/api_interfaces.go index 758addb6..1089093d 100644 --- a/vendor/github.com/manyminds/api2go/api_interfaces.go +++ b/vendor/github.com/manyminds/api2go/api_interfaces.go @@ -84,9 +84,9 @@ type ObjectInitializer interface { InitializeObject(interface{}) } -//URLResolver allows you to implement a static -//way to return a baseURL for all incoming -//requests for one api2go instance. +// URLResolver allows you to implement a static +// way to return a baseURL for all incoming +// requests for one api2go instance. type URLResolver interface { GetBaseURL() string } diff --git a/vendor/github.com/manyminds/api2go/api_public.go b/vendor/github.com/manyminds/api2go/api_public.go index c453d4e7..7d31558f 100644 --- a/vendor/github.com/manyminds/api2go/api_public.go +++ b/vendor/github.com/manyminds/api2go/api_public.go @@ -28,7 +28,7 @@ func (api API) Handler() http.Handler { return api.router.Handler() } -//Router returns the specified router on an api instance +// Router returns the specified router on an api instance func (api API) Router() routing.Routeable { return api.router } diff --git a/vendor/github.com/manyminds/api2go/error.go b/vendor/github.com/manyminds/api2go/error.go index 4b6ca75c..ac18cba3 100644 --- a/vendor/github.com/manyminds/api2go/error.go +++ b/vendor/github.com/manyminds/api2go/error.go @@ -57,7 +57,6 @@ func marshalHTTPError(input HTTPError) string { } data, err := json.Marshal(input) - if err != nil { log.Println(err) return "{}" diff --git a/vendor/github.com/manyminds/api2go/jsonapi/data_structs.go b/vendor/github.com/manyminds/api2go/jsonapi/data_structs.go index 279b6cf8..7b5d561c 100644 --- a/vendor/github.com/manyminds/api2go/jsonapi/data_structs.go +++ b/vendor/github.com/manyminds/api2go/jsonapi/data_structs.go @@ -6,9 +6,11 @@ import ( "errors" ) -var objectSuffix = []byte("{") -var arraySuffix = []byte("[") -var stringSuffix = []byte(`"`) +var ( + objectSuffix = []byte("{") + arraySuffix = []byte("[") + stringSuffix = []byte(`"`) +) // A Document represents a JSON API document as specified here: http://jsonapi.org. type Document struct { diff --git a/vendor/github.com/manyminds/api2go/routing/gingonic.go b/vendor/github.com/manyminds/api2go/routing/gingonic.go index 65f6424d..b19ac7ce 100644 --- a/vendor/github.com/manyminds/api2go/routing/gingonic.go +++ b/vendor/github.com/manyminds/api2go/routing/gingonic.go @@ -29,7 +29,7 @@ func (g ginRouter) Handle(protocol, route string, handler HandlerFunc) { g.router.Handle(protocol, route, wrappedCallback) } -//Gin creates a new api2go router to use with the gin framework +// Gin creates a new api2go router to use with the gin framework func Gin(g *gin.Engine) Routeable { return &ginRouter{router: g} } diff --git a/vendor/github.com/manyminds/api2go/routing/gorillamux.go b/vendor/github.com/manyminds/api2go/routing/gorillamux.go index f761359d..5e4e9d98 100644 --- a/vendor/github.com/manyminds/api2go/routing/gorillamux.go +++ b/vendor/github.com/manyminds/api2go/routing/gorillamux.go @@ -38,7 +38,7 @@ func (gm gorillamuxRouter) Handle(protocol, route string, handler HandlerFunc) { gm.router.HandleFunc(modroute, wrappedHandler).Methods(protocol) } -//Gorilla creates a new api2go router to use with the Gorilla mux framework +// Gorilla creates a new api2go router to use with the Gorilla mux framework func Gorilla(gm *mux.Router) Routeable { return &gorillamuxRouter{router: gm} } diff --git a/vendor/github.com/mattn/go-colorable/colorable_windows.go b/vendor/github.com/mattn/go-colorable/colorable_windows.go index 41215d7f..62203beb 100644 --- a/vendor/github.com/mattn/go-colorable/colorable_windows.go +++ b/vendor/github.com/mattn/go-colorable/colorable_windows.go @@ -42,10 +42,12 @@ const ( consoleTextmodeBuffer = 0x1 ) -type wchar uint16 -type short int16 -type dword uint32 -type word uint16 +type ( + wchar uint16 + short int16 + dword uint32 + word uint16 +) type coord struct { x short @@ -1008,8 +1010,10 @@ func minmax3f(a, b, c float32) (min, max float32) { } } -var n256foreAttr []word -var n256backAttr []word +var ( + n256foreAttr []word + n256backAttr []word +) func n256setup() { n256foreAttr = make([]word, 256) diff --git a/vendor/github.com/mattn/go-sqlite3/backup.go b/vendor/github.com/mattn/go-sqlite3/backup.go index e222cc88..d5aec95a 100644 --- a/vendor/github.com/mattn/go-sqlite3/backup.go +++ b/vendor/github.com/mattn/go-sqlite3/backup.go @@ -14,6 +14,7 @@ package sqlite3 #include */ import "C" + import ( "runtime" "unsafe" diff --git a/vendor/github.com/mattn/go-sqlite3/callback.go b/vendor/github.com/mattn/go-sqlite3/callback.go index c3ce7520..000f7800 100644 --- a/vendor/github.com/mattn/go-sqlite3/callback.go +++ b/vendor/github.com/mattn/go-sqlite3/callback.go @@ -103,8 +103,10 @@ type handleVal struct { val interface{} } -var handleLock sync.Mutex -var handleVals = make(map[unsafe.Pointer]handleVal) +var ( + handleLock sync.Mutex + handleVals = make(map[unsafe.Pointer]handleVal) +) func newHandle(db *SQLiteConn, v interface{}) unsafe.Pointer { handleLock.Lock() diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3.go b/vendor/github.com/mattn/go-sqlite3/sqlite3.go index d1ff4063..25320ed2 100644 --- a/vendor/github.com/mattn/go-sqlite3/sqlite3.go +++ b/vendor/github.com/mattn/go-sqlite3/sqlite3.go @@ -189,6 +189,7 @@ static int sqlite3_system_errno(sqlite3 *db) { #endif */ import "C" + import ( "context" "database/sql" diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3_go18.go b/vendor/github.com/mattn/go-sqlite3/sqlite3_go18.go index bd97cb87..9f8ddb0f 100644 --- a/vendor/github.com/mattn/go-sqlite3/sqlite3_go18.go +++ b/vendor/github.com/mattn/go-sqlite3/sqlite3_go18.go @@ -9,9 +9,8 @@ package sqlite3 import ( - "database/sql/driver" - "context" + "database/sql/driver" ) // Ping implement Pinger. diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3_load_extension.go b/vendor/github.com/mattn/go-sqlite3/sqlite3_load_extension.go index f2418196..4870b3f7 100644 --- a/vendor/github.com/mattn/go-sqlite3/sqlite3_load_extension.go +++ b/vendor/github.com/mattn/go-sqlite3/sqlite3_load_extension.go @@ -16,6 +16,7 @@ package sqlite3 #include */ import "C" + import ( "errors" "unsafe" diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3_load_extension_omit.go b/vendor/github.com/mattn/go-sqlite3/sqlite3_load_extension_omit.go index 8c75f9bd..67c1c89b 100644 --- a/vendor/github.com/mattn/go-sqlite3/sqlite3_load_extension_omit.go +++ b/vendor/github.com/mattn/go-sqlite3/sqlite3_load_extension_omit.go @@ -11,6 +11,7 @@ package sqlite3 #cgo CFLAGS: -DSQLITE_OMIT_LOAD_EXTENSION */ import "C" + import ( "errors" ) diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_preupdate_hook.go b/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_preupdate_hook.go index db7a6662..07a88af9 100644 --- a/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_preupdate_hook.go +++ b/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_preupdate_hook.go @@ -23,6 +23,7 @@ package sqlite3 void preUpdateHookTrampoline(void*, sqlite3 *, int, char *, char *, sqlite3_int64, sqlite3_int64); */ import "C" + import ( "errors" "unsafe" diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_unlock_notify.go b/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_unlock_notify.go index 43f53e80..f62f8815 100644 --- a/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_unlock_notify.go +++ b/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_unlock_notify.go @@ -17,6 +17,7 @@ package sqlite3 extern void unlock_notify_callback(void *arg, int argc); */ import "C" + import ( "fmt" "math" diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_userauth.go b/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_userauth.go index 94203b39..2686fad0 100644 --- a/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_userauth.go +++ b/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_userauth.go @@ -59,6 +59,7 @@ _sqlite3_auth_enabled(sqlite3* db) } */ import "C" + import ( "errors" "unsafe" diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3_trace.go b/vendor/github.com/mattn/go-sqlite3/sqlite3_trace.go index 4c8d9928..2c7b316d 100644 --- a/vendor/github.com/mattn/go-sqlite3/sqlite3_trace.go +++ b/vendor/github.com/mattn/go-sqlite3/sqlite3_trace.go @@ -202,8 +202,10 @@ type traceMapEntry struct { config TraceConfig } -var traceMapLock sync.Mutex -var traceMap = make(map[uintptr]traceMapEntry) +var ( + traceMapLock sync.Mutex + traceMap = make(map[uintptr]traceMapEntry) +) func addTraceMapping(connHandle uintptr, traceConf TraceConfig) { traceMapLock.Lock() diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3_type.go b/vendor/github.com/mattn/go-sqlite3/sqlite3_type.go index b4128db4..8c47cca1 100644 --- a/vendor/github.com/mattn/go-sqlite3/sqlite3_type.go +++ b/vendor/github.com/mattn/go-sqlite3/sqlite3_type.go @@ -13,6 +13,7 @@ package sqlite3 #endif */ import "C" + import ( "reflect" "time" diff --git a/vendor/github.com/mitchellh/go-homedir/homedir.go b/vendor/github.com/mitchellh/go-homedir/homedir.go index 25378537..cd419bad 100644 --- a/vendor/github.com/mitchellh/go-homedir/homedir.go +++ b/vendor/github.com/mitchellh/go-homedir/homedir.go @@ -16,8 +16,10 @@ import ( // by default. var DisableCache bool -var homedirCache string -var cacheLock sync.RWMutex +var ( + homedirCache string + cacheLock sync.RWMutex +) // Dir returns the home directory for the executing user. // diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure.go b/vendor/github.com/mitchellh/mapstructure/mapstructure.go index 3643901f..1f25ced9 100644 --- a/vendor/github.com/mitchellh/mapstructure/mapstructure.go +++ b/vendor/github.com/mitchellh/mapstructure/mapstructure.go @@ -1156,7 +1156,6 @@ func (d *Decoder) decodeArray(name string, data interface{}, val reflect.Value) if dataVal.Len() > arrayType.Len() { return fmt.Errorf( "'%s': expected source data to have length less or equal to %d, got %d", name, arrayType.Len(), dataVal.Len()) - } // Make a new array to hold our result, same size as the original data. diff --git a/vendor/github.com/modern-go/concurrent/log.go b/vendor/github.com/modern-go/concurrent/log.go index 9756fcc7..4899eed0 100644 --- a/vendor/github.com/modern-go/concurrent/log.go +++ b/vendor/github.com/modern-go/concurrent/log.go @@ -1,13 +1,13 @@ package concurrent import ( - "os" - "log" "io/ioutil" + "log" + "os" ) // ErrorLogger is used to print out error, can be set to writer other than stderr var ErrorLogger = log.New(os.Stderr, "", 0) // InfoLogger is used to print informational message, default to off -var InfoLogger = log.New(ioutil.Discard, "", 0) \ No newline at end of file +var InfoLogger = log.New(ioutil.Discard, "", 0) diff --git a/vendor/github.com/modern-go/concurrent/unbounded_executor.go b/vendor/github.com/modern-go/concurrent/unbounded_executor.go index 05a77dce..5ea18eb7 100644 --- a/vendor/github.com/modern-go/concurrent/unbounded_executor.go +++ b/vendor/github.com/modern-go/concurrent/unbounded_executor.go @@ -3,11 +3,11 @@ package concurrent import ( "context" "fmt" + "reflect" "runtime" "runtime/debug" "sync" "time" - "reflect" ) // HandlePanic logs goroutine panic by default diff --git a/vendor/github.com/modern-go/reflect2/reflect2.go b/vendor/github.com/modern-go/reflect2/reflect2.go index 63b49c79..86326b02 100644 --- a/vendor/github.com/modern-go/reflect2/reflect2.go +++ b/vendor/github.com/modern-go/reflect2/reflect2.go @@ -1,9 +1,10 @@ package reflect2 import ( - "github.com/modern-go/concurrent" "reflect" "unsafe" + + "github.com/modern-go/concurrent" ) type Type interface { @@ -125,8 +126,10 @@ type API interface { Type2(type1 reflect.Type) Type } -var ConfigUnsafe = Config{UseSafeImplementation: false}.Froze() -var ConfigSafe = Config{UseSafeImplementation: true}.Froze() +var ( + ConfigUnsafe = Config{UseSafeImplementation: false}.Froze() + ConfigSafe = Config{UseSafeImplementation: true}.Froze() +) type frozenConfig struct { useSafeImplementation bool @@ -136,7 +139,7 @@ type frozenConfig struct { func (cfg Config) Froze() *frozenConfig { return &frozenConfig{ useSafeImplementation: cfg.UseSafeImplementation, - cache: concurrent.NewMap(), + cache: concurrent.NewMap(), } } @@ -291,8 +294,8 @@ func UnsafeCastString(str string) []byte { stringHeader := (*reflect.StringHeader)(unsafe.Pointer(&str)) sliceHeader := &reflect.SliceHeader{ Data: stringHeader.Data, - Cap: stringHeader.Len, - Len: stringHeader.Len, + Cap: stringHeader.Len, + Len: stringHeader.Len, } return *(*[]byte)(unsafe.Pointer(sliceHeader)) } diff --git a/vendor/github.com/modern-go/reflect2/type_map.go b/vendor/github.com/modern-go/reflect2/type_map.go index 3acfb558..dfe3c93a 100644 --- a/vendor/github.com/modern-go/reflect2/type_map.go +++ b/vendor/github.com/modern-go/reflect2/type_map.go @@ -19,8 +19,10 @@ func typelinks2() (sections []unsafe.Pointer, offset [][]int32) // initOnce guards initialization of types and packages var initOnce sync.Once -var types map[string]reflect.Type -var packages map[string]map[string]reflect.Type +var ( + types map[string]reflect.Type + packages map[string]map[string]reflect.Type +) // discoverTypes initializes types and packages func discoverTypes() { diff --git a/vendor/github.com/nats-io/go-nats/enc.go b/vendor/github.com/nats-io/go-nats/enc.go index 08edfe53..85c1f199 100644 --- a/vendor/github.com/nats-io/go-nats/enc.go +++ b/vendor/github.com/nats-io/go-nats/enc.go @@ -30,8 +30,10 @@ type Encoder interface { Decode(subject string, data []byte, vPtr interface{}) error } -var encMap map[string]Encoder -var encLock sync.Mutex +var ( + encMap map[string]Encoder + encLock sync.Mutex +) // Indexe names into the Registered Encoders. const ( diff --git a/vendor/github.com/nats-io/go-nats/encoders/builtin/default_enc.go b/vendor/github.com/nats-io/go-nats/encoders/builtin/default_enc.go index 46d918ee..d5317687 100644 --- a/vendor/github.com/nats-io/go-nats/encoders/builtin/default_enc.go +++ b/vendor/github.com/nats-io/go-nats/encoders/builtin/default_enc.go @@ -26,13 +26,14 @@ import ( // turn numbers into appropriate strings that can be decoded. It will also // propely encoded and decode bools. If will encode a struct, but if you want // to properly handle structures you should use JsonEncoder. -type DefaultEncoder struct { - // Empty +type DefaultEncoder struct { // Empty } -var trueB = []byte("true") -var falseB = []byte("false") -var nilB = []byte("") +var ( + trueB = []byte("true") + falseB = []byte("false") + nilB = []byte("") +) // Encode func (je *DefaultEncoder) Encode(subject string, v interface{}) ([]byte, error) { diff --git a/vendor/github.com/nats-io/go-nats/encoders/builtin/gob_enc.go b/vendor/github.com/nats-io/go-nats/encoders/builtin/gob_enc.go index 632bcbd3..851e9e51 100644 --- a/vendor/github.com/nats-io/go-nats/encoders/builtin/gob_enc.go +++ b/vendor/github.com/nats-io/go-nats/encoders/builtin/gob_enc.go @@ -21,8 +21,7 @@ import ( // GobEncoder is a Go specific GOB Encoder implementation for EncodedConn. // This encoder will use the builtin encoding/gob to Marshal // and Unmarshal most types, including structs. -type GobEncoder struct { - // Empty +type GobEncoder struct { // Empty } // FIXME(dlc) - This could probably be more efficient. diff --git a/vendor/github.com/nats-io/go-nats/encoders/builtin/json_enc.go b/vendor/github.com/nats-io/go-nats/encoders/builtin/json_enc.go index c9670f31..7fe596da 100644 --- a/vendor/github.com/nats-io/go-nats/encoders/builtin/json_enc.go +++ b/vendor/github.com/nats-io/go-nats/encoders/builtin/json_enc.go @@ -21,8 +21,7 @@ import ( // JsonEncoder is a JSON Encoder implementation for EncodedConn. // This encoder will use the builtin encoding/json to Marshal // and Unmarshal most types, including structs. -type JsonEncoder struct { - // Empty +type JsonEncoder struct { // Empty } // Encode diff --git a/vendor/github.com/nats-io/go-nats/nats.go b/vendor/github.com/nats-io/go-nats/nats.go index 225b5400..7ced76e8 100644 --- a/vendor/github.com/nats-io/go-nats/nats.go +++ b/vendor/github.com/nats-io/go-nats/nats.go @@ -1056,7 +1056,6 @@ func (nc *Conn) setup() { // Process a connected connection and initialize properly. func (nc *Conn) processConnectInit() error { - // Set out deadline for the whole connect process nc.conn.SetDeadline(time.Now().Add(nc.Opts.Timeout)) defer nc.conn.SetDeadline(time.Time{}) @@ -1158,7 +1157,6 @@ func (nc *Conn) checkForSecure() error { // processExpectedInfo will look for the expected first INFO message // sent when a connection is established. The lock should be held entering. func (nc *Conn) processExpectedInfo() error { - c := &control{} // Read the protocol @@ -1209,9 +1207,11 @@ func (nc *Conn) connectProto() (string, error) { pass = nc.Opts.Password token = nc.Opts.Token } - cinfo := connectInfo{o.Verbose, o.Pedantic, + cinfo := connectInfo{ + o.Verbose, o.Pedantic, user, pass, token, - o.Secure, o.Name, LangString, Version, clientProtoInfo} + o.Secure, o.Name, LangString, Version, clientProtoInfo, + } b, err := json.Marshal(cinfo) if err != nil { return _EMPTY_, ErrJsonParse @@ -1230,7 +1230,6 @@ func normalizeErr(line string) string { // applicable. Will wait for a flush to return from the server for error // processing. func (nc *Conn) sendConnect() error { - // Construct the CONNECT protocol string cProto, err := nc.connectProto() if err != nil { @@ -2081,7 +2080,7 @@ func (nc *Conn) publish(subj, reply string, data []byte) error { // msgh = strconv.AppendInt(msgh, int64(len(data)), 10) var b [12]byte - var i = len(b) + i := len(b) if len(data) > 0 { for l := len(data); l > 0; l /= 10 { i -= 1 @@ -2249,9 +2248,11 @@ func (nc *Conn) oldRequest(subj string, data []byte, timeout time.Duration) (*Ms } // InboxPrefix is the prefix for all inbox subjects. -const InboxPrefix = "_INBOX." -const inboxPrefixLen = len(InboxPrefix) -const respInboxPrefixLen = inboxPrefixLen + nuidSize + 1 +const ( + InboxPrefix = "_INBOX." + inboxPrefixLen = len(InboxPrefix) + respInboxPrefixLen = inboxPrefixLen + nuidSize + 1 +) // NewInbox will return an inbox string which can be used for directed replies from // subscribers. These are guaranteed to be unique, but can be shared and subscribed @@ -3017,7 +3018,7 @@ func (nc *Conn) IsConnected() bool { // caller must lock func (nc *Conn) getServers(implicitOnly bool) []string { poolSize := len(nc.srvPool) - var servers = make([]string, 0) + servers := make([]string, 0) for i := 0; i < poolSize; i++ { if implicitOnly && !nc.srvPool[i].isImplicit { continue diff --git a/vendor/github.com/pelletier/go-toml/marshal.go b/vendor/github.com/pelletier/go-toml/marshal.go index 032e0ffc..e1875b89 100644 --- a/vendor/github.com/pelletier/go-toml/marshal.go +++ b/vendor/github.com/pelletier/go-toml/marshal.go @@ -68,15 +68,17 @@ const ( OrderPreserve ) -var timeType = reflect.TypeOf(time.Time{}) -var marshalerType = reflect.TypeOf(new(Marshaler)).Elem() -var unmarshalerType = reflect.TypeOf(new(Unmarshaler)).Elem() -var textMarshalerType = reflect.TypeOf(new(encoding.TextMarshaler)).Elem() -var textUnmarshalerType = reflect.TypeOf(new(encoding.TextUnmarshaler)).Elem() -var localDateType = reflect.TypeOf(LocalDate{}) -var localTimeType = reflect.TypeOf(LocalTime{}) -var localDateTimeType = reflect.TypeOf(LocalDateTime{}) -var mapStringInterfaceType = reflect.TypeOf(map[string]interface{}{}) +var ( + timeType = reflect.TypeOf(time.Time{}) + marshalerType = reflect.TypeOf(new(Marshaler)).Elem() + unmarshalerType = reflect.TypeOf(new(Unmarshaler)).Elem() + textMarshalerType = reflect.TypeOf(new(encoding.TextMarshaler)).Elem() + textUnmarshalerType = reflect.TypeOf(new(encoding.TextUnmarshaler)).Elem() + localDateType = reflect.TypeOf(LocalDate{}) + localTimeType = reflect.TypeOf(LocalTime{}) + localDateTimeType = reflect.TypeOf(LocalDateTime{}) + mapStringInterfaceType = reflect.TypeOf(map[string]interface{}{}) +) // Check if the given marshal type maps to a Tree primitive func isPrimitive(mtype reflect.Type) bool { diff --git a/vendor/github.com/pelletier/go-toml/parser.go b/vendor/github.com/pelletier/go-toml/parser.go index 7bf40bbd..3dbd1151 100644 --- a/vendor/github.com/pelletier/go-toml/parser.go +++ b/vendor/github.com/pelletier/go-toml/parser.go @@ -231,8 +231,10 @@ func (p *tomlParser) parseAssign() tomlParserStateFn { return p.parseStart } -var numberUnderscoreInvalidRegexp *regexp.Regexp -var hexNumberUnderscoreInvalidRegexp *regexp.Regexp +var ( + numberUnderscoreInvalidRegexp *regexp.Regexp + hexNumberUnderscoreInvalidRegexp *regexp.Regexp +) func numberContainsInvalidUnderscore(value string) error { if numberUnderscoreInvalidRegexp.MatchString(value) { diff --git a/vendor/github.com/pelletier/go-toml/toml.go b/vendor/github.com/pelletier/go-toml/toml.go index cbb89a9a..09d1b492 100644 --- a/vendor/github.com/pelletier/go-toml/toml.go +++ b/vendor/github.com/pelletier/go-toml/toml.go @@ -364,11 +364,13 @@ func (t *Tree) SetPathWithOptions(keys []string, opts SetOptions, value interfac v.multiline = opts.Multiline toInsert = v default: - toInsert = &tomlValue{value: value, + toInsert = &tomlValue{ + value: value, comment: opts.Comment, commented: opts.Commented, multiline: opts.Multiline, - position: Position{Line: subtree.position.Line + len(subtree.values) + 1, Col: subtree.position.Col}} + position: Position{Line: subtree.position.Line + len(subtree.values) + 1, Col: subtree.position.Col}, + } } subtree.values[keys[len(keys)-1]] = toInsert diff --git a/vendor/github.com/pmezard/go-difflib/difflib/difflib.go b/vendor/github.com/pmezard/go-difflib/difflib/difflib.go index 003e99fa..7fdac45a 100644 --- a/vendor/github.com/pmezard/go-difflib/difflib/difflib.go +++ b/vendor/github.com/pmezard/go-difflib/difflib/difflib.go @@ -161,12 +161,12 @@ func (m *SequenceMatcher) chainB() { m.bJunk = map[string]struct{}{} if m.IsJunk != nil { junk := m.bJunk - for s, _ := range b2j { + for s := range b2j { if m.IsJunk(s) { junk[s] = struct{}{} } } - for s, _ := range junk { + for s := range junk { delete(b2j, s) } } @@ -181,7 +181,7 @@ func (m *SequenceMatcher) chainB() { popular[s] = struct{}{} } } - for s, _ := range popular { + for s := range popular { delete(b2j, s) } } @@ -416,7 +416,7 @@ func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode { } codes := m.GetOpCodes() if len(codes) == 0 { - codes = []OpCode{OpCode{'e', 0, 1, 0, 1}} + codes = []OpCode{{'e', 0, 1, 0, 1}} } // Fixup leading and trailing groups if they show no changes. if codes[0].Tag == 'e' { @@ -437,8 +437,10 @@ func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode { // End the current group and start a new one whenever // there is a large range with no changes. if c.Tag == 'e' && i2-i1 > nn { - group = append(group, OpCode{c.Tag, i1, min(i2, i1+n), - j1, min(j2, j1+n)}) + group = append(group, OpCode{ + c.Tag, i1, min(i2, i1+n), + j1, min(j2, j1+n), + }) groups = append(groups, group) group = []OpCode{} i1, j1 = max(i1, i2-n), max(j1, j2-n) diff --git a/vendor/github.com/rcrowley/go-metrics/debug.go b/vendor/github.com/rcrowley/go-metrics/debug.go index 043ccefa..24c0aca7 100644 --- a/vendor/github.com/rcrowley/go-metrics/debug.go +++ b/vendor/github.com/rcrowley/go-metrics/debug.go @@ -11,7 +11,7 @@ var ( LastGC Gauge NumGC Gauge Pause Histogram - //PauseQuantiles Histogram + // PauseQuantiles Histogram PauseTotal Gauge } ReadGCStats Timer @@ -22,7 +22,7 @@ var ( // Capture new values for the Go garbage collector statistics exported in // debug.GCStats. This is designed to be called as a goroutine. func CaptureDebugGCStats(r Registry, d time.Duration) { - for _ = range time.Tick(d) { + for range time.Tick(d) { CaptureDebugGCStatsOnce(r) } } @@ -46,7 +46,7 @@ func CaptureDebugGCStatsOnce(r Registry) { if lastGC != gcStats.LastGC && 0 < len(gcStats.Pause) { debugMetrics.GCStats.Pause.Update(int64(gcStats.Pause[0])) } - //debugMetrics.GCStats.PauseQuantiles.Update(gcStats.PauseQuantiles) + // debugMetrics.GCStats.PauseQuantiles.Update(gcStats.PauseQuantiles) debugMetrics.GCStats.PauseTotal.Update(int64(gcStats.PauseTotal)) } @@ -57,14 +57,14 @@ func RegisterDebugGCStats(r Registry) { debugMetrics.GCStats.LastGC = NewGauge() debugMetrics.GCStats.NumGC = NewGauge() debugMetrics.GCStats.Pause = NewHistogram(NewExpDecaySample(1028, 0.015)) - //debugMetrics.GCStats.PauseQuantiles = NewHistogram(NewExpDecaySample(1028, 0.015)) + // debugMetrics.GCStats.PauseQuantiles = NewHistogram(NewExpDecaySample(1028, 0.015)) debugMetrics.GCStats.PauseTotal = NewGauge() debugMetrics.ReadGCStats = NewTimer() r.Register("debug.GCStats.LastGC", debugMetrics.GCStats.LastGC) r.Register("debug.GCStats.NumGC", debugMetrics.GCStats.NumGC) r.Register("debug.GCStats.Pause", debugMetrics.GCStats.Pause) - //r.Register("debug.GCStats.PauseQuantiles", debugMetrics.GCStats.PauseQuantiles) + // r.Register("debug.GCStats.PauseQuantiles", debugMetrics.GCStats.PauseQuantiles) r.Register("debug.GCStats.PauseTotal", debugMetrics.GCStats.PauseTotal) r.Register("debug.ReadGCStats", debugMetrics.ReadGCStats) } diff --git a/vendor/github.com/rcrowley/go-metrics/graphite.go b/vendor/github.com/rcrowley/go-metrics/graphite.go index abd0a7d2..142eec86 100644 --- a/vendor/github.com/rcrowley/go-metrics/graphite.go +++ b/vendor/github.com/rcrowley/go-metrics/graphite.go @@ -39,7 +39,7 @@ func Graphite(r Registry, d time.Duration, prefix string, addr *net.TCPAddr) { // but it takes a GraphiteConfig instead. func GraphiteWithConfig(c GraphiteConfig) { log.Printf("WARNING: This go-metrics client has been DEPRECATED! It has been moved to https://github.com/cyberdelia/go-metrics-graphite and will be removed from rcrowley/go-metrics on August 12th 2015") - for _ = range time.Tick(c.FlushInterval) { + for range time.Tick(c.FlushInterval) { if err := graphite(&c); nil != err { log.Println(err) } diff --git a/vendor/github.com/rcrowley/go-metrics/json.go b/vendor/github.com/rcrowley/go-metrics/json.go index 174b9477..2087d821 100644 --- a/vendor/github.com/rcrowley/go-metrics/json.go +++ b/vendor/github.com/rcrowley/go-metrics/json.go @@ -15,7 +15,7 @@ func (r *StandardRegistry) MarshalJSON() ([]byte, error) { // WriteJSON writes metrics from the given registry periodically to the // specified io.Writer as JSON. func WriteJSON(r Registry, d time.Duration, w io.Writer) { - for _ = range time.Tick(d) { + for range time.Tick(d) { WriteJSONOnce(r, w) } } diff --git a/vendor/github.com/rcrowley/go-metrics/log.go b/vendor/github.com/rcrowley/go-metrics/log.go index f8074c04..0c8ea7c9 100644 --- a/vendor/github.com/rcrowley/go-metrics/log.go +++ b/vendor/github.com/rcrowley/go-metrics/log.go @@ -18,7 +18,7 @@ func LogScaled(r Registry, freq time.Duration, scale time.Duration, l Logger) { du := float64(scale) duSuffix := scale.String()[1:] - for _ = range time.Tick(freq) { + for range time.Tick(freq) { r.Each(func(name string, i interface{}) { switch metric := i.(type) { case Counter: diff --git a/vendor/github.com/rcrowley/go-metrics/opentsdb.go b/vendor/github.com/rcrowley/go-metrics/opentsdb.go index 266b6c93..df7f152e 100644 --- a/vendor/github.com/rcrowley/go-metrics/opentsdb.go +++ b/vendor/github.com/rcrowley/go-metrics/opentsdb.go @@ -38,7 +38,7 @@ func OpenTSDB(r Registry, d time.Duration, prefix string, addr *net.TCPAddr) { // OpenTSDBWithConfig is a blocking exporter function just like OpenTSDB, // but it takes a OpenTSDBConfig instead. func OpenTSDBWithConfig(c OpenTSDBConfig) { - for _ = range time.Tick(c.FlushInterval) { + for range time.Tick(c.FlushInterval) { if err := openTSDB(&c); nil != err { log.Println(err) } diff --git a/vendor/github.com/rcrowley/go-metrics/registry.go b/vendor/github.com/rcrowley/go-metrics/registry.go index b3bab64e..aeaf4a18 100644 --- a/vendor/github.com/rcrowley/go-metrics/registry.go +++ b/vendor/github.com/rcrowley/go-metrics/registry.go @@ -194,7 +194,7 @@ func (r *StandardRegistry) Unregister(name string) { func (r *StandardRegistry) UnregisterAll() { r.mutex.Lock() defer r.mutex.Unlock() - for name, _ := range r.metrics { + for name := range r.metrics { r.stop(name) delete(r.metrics, name) } diff --git a/vendor/github.com/rcrowley/go-metrics/runtime.go b/vendor/github.com/rcrowley/go-metrics/runtime.go index 11c6b785..9450c479 100644 --- a/vendor/github.com/rcrowley/go-metrics/runtime.go +++ b/vendor/github.com/rcrowley/go-metrics/runtime.go @@ -55,7 +55,7 @@ var ( // Capture new values for the Go runtime statistics exported in // runtime.MemStats. This is designed to be called as a goroutine. func CaptureRuntimeMemStats(r Registry, d time.Duration) { - for _ = range time.Tick(d) { + for range time.Tick(d) { CaptureRuntimeMemStatsOnce(r) } } diff --git a/vendor/github.com/rcrowley/go-metrics/syslog.go b/vendor/github.com/rcrowley/go-metrics/syslog.go index 693f1908..a0ed4b1b 100644 --- a/vendor/github.com/rcrowley/go-metrics/syslog.go +++ b/vendor/github.com/rcrowley/go-metrics/syslog.go @@ -11,7 +11,7 @@ import ( // Output each metric in the given registry to syslog periodically using // the given syslogger. func Syslog(r Registry, d time.Duration, w *syslog.Writer) { - for _ = range time.Tick(d) { + for range time.Tick(d) { r.Each(func(name string, i interface{}) { switch metric := i.(type) { case Counter: diff --git a/vendor/github.com/rcrowley/go-metrics/writer.go b/vendor/github.com/rcrowley/go-metrics/writer.go index 091e971d..88521a80 100644 --- a/vendor/github.com/rcrowley/go-metrics/writer.go +++ b/vendor/github.com/rcrowley/go-metrics/writer.go @@ -10,7 +10,7 @@ import ( // Write sorts writes each metric in the given registry periodically to the // given io.Writer. func Write(r Registry, d time.Duration, w io.Writer) { - for _ = range time.Tick(d) { + for range time.Tick(d) { WriteOnce(r, w) } } diff --git a/vendor/github.com/selvatico/go-mocket/conn.go b/vendor/github.com/selvatico/go-mocket/conn.go index 3f5fb3d6..2eb52ac4 100644 --- a/vendor/github.com/selvatico/go-mocket/conn.go +++ b/vendor/github.com/selvatico/go-mocket/conn.go @@ -69,7 +69,7 @@ func (c *FakeConn) Prepare(query string) (driver.Stmt, error) { // context is for the preparation of the statement, // it must not store the context within the statement itself. func (c *FakeConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) { - var firstStmt = &FakeStmt{q: query, connection: c} + firstStmt := &FakeStmt{q: query, connection: c} // Checking how many placeholders do we have if strings.Contains(query, "$1") { r, err := regexp.Compile(`[$]\d+`) diff --git a/vendor/github.com/selvatico/go-mocket/response.go b/vendor/github.com/selvatico/go-mocket/response.go index 1b51a302..1be27d8d 100644 --- a/vendor/github.com/selvatico/go-mocket/response.go +++ b/vendor/github.com/selvatico/go-mocket/response.go @@ -14,10 +14,10 @@ const ( DriverName = "MOCK_FAKE_DRIVER" ) -//Catcher is global instance of Catcher used for attaching all mocks to connection +// Catcher is global instance of Catcher used for attaching all mocks to connection var Catcher *MockCatcher -//MockCatcher is global entity to save all mocks aka FakeResponses +// MockCatcher is global entity to save all mocks aka FakeResponses type MockCatcher struct { Mocks []*FakeResponse // Slice of all mocks Logging bool // Do we need to log what we catching? @@ -40,7 +40,7 @@ func (mc *MockCatcher) Attach(fr []*FakeResponse) { mc.Mocks = append(mc.Mocks, fr...) } -//FindResponse finds suitable response by provided +// FindResponse finds suitable response by provided func (mc *MockCatcher) FindResponse(query string, args []driver.NamedValue) *FakeResponse { if mc.Logging { log.Printf("mock_catcher: check query: %s", query) @@ -64,26 +64,26 @@ func (mc *MockCatcher) FindResponse(query string, args []driver.NamedValue) *Fak } } -//NewMock creates new FakeResponse and return for chains of attachments +// NewMock creates new FakeResponse and return for chains of attachments func (mc *MockCatcher) NewMock() *FakeResponse { fr := &FakeResponse{Exceptions: &Exceptions{}, Response: make([]map[string]interface{}, 0)} mc.Mocks = append(mc.Mocks, fr) return fr } -//Reset removes all Mocks to start process again +// Reset removes all Mocks to start process again func (mc *MockCatcher) Reset() *MockCatcher { mc.Mocks = make([]*FakeResponse, 0) return mc } -//Exceptions represents possible exceptions during query executions +// Exceptions represents possible exceptions during query executions type Exceptions struct { HookQueryBadConnection func() bool HookExecBadConnection func() bool } -//FakeResponse represents mock of response with holding all required values to return mocked response +// FakeResponse represents mock of response with holding all required values to return mocked response type FakeResponse struct { Pattern string // SQL query pattern to match with Args []interface{} // List args to be matched with @@ -120,12 +120,12 @@ func (fr *FakeResponse) IsMatch(query string, args []driver.NamedValue) bool { return fr.isQueryMatch(query) && fr.isArgsMatch(args) } -//MarkAsTriggered marks response as executed. For one time catches it will not make this possible to execute anymore +// MarkAsTriggered marks response as executed. For one time catches it will not make this possible to execute anymore func (fr *FakeResponse) MarkAsTriggered() { fr.Triggered = true } -//WithQuery adds SQL query pattern to match for +// WithQuery adds SQL query pattern to match for func (fr *FakeResponse) WithQuery(query string) *FakeResponse { fr.Pattern = query return fr diff --git a/vendor/github.com/selvatico/go-mocket/stmt.go b/vendor/github.com/selvatico/go-mocket/stmt.go index cfac6bdc..b22437bd 100644 --- a/vendor/github.com/selvatico/go-mocket/stmt.go +++ b/vendor/github.com/selvatico/go-mocket/stmt.go @@ -16,7 +16,7 @@ type FakeStmt struct { command string // String name of the command SELECT etc, taken as first word in the query next *FakeStmt // used for returning multiple results. closed bool // If connection closed already - colName []string //Names of columns in response + colName []string // Names of columns in response colType []string // Not used for now placeholders int // Amount of passed args } @@ -104,7 +104,6 @@ func (s *FakeStmt) Query(args []driver.Value) (driver.Rows, error) { // QueryContext executes a query that may return rows, such as a // SELECT. func (s *FakeStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) { - if s.closed { return nil, errClosed } diff --git a/vendor/github.com/sirupsen/logrus/buffer_pool.go b/vendor/github.com/sirupsen/logrus/buffer_pool.go index 4545dec0..cd4728ad 100644 --- a/vendor/github.com/sirupsen/logrus/buffer_pool.go +++ b/vendor/github.com/sirupsen/logrus/buffer_pool.go @@ -5,9 +5,7 @@ import ( "sync" ) -var ( - bufferPool BufferPool -) +var bufferPool BufferPool type BufferPool interface { Put(*bytes.Buffer) diff --git a/vendor/github.com/sirupsen/logrus/exported.go b/vendor/github.com/sirupsen/logrus/exported.go index 017c30ce..021443c0 100644 --- a/vendor/github.com/sirupsen/logrus/exported.go +++ b/vendor/github.com/sirupsen/logrus/exported.go @@ -6,10 +6,8 @@ import ( "time" ) -var ( - // std is the name of the standard logger in stdlib `log` - std = New() -) +// std is the name of the standard logger in stdlib `log` +var std = New() func StandardLogger() *Logger { return std diff --git a/vendor/github.com/sirupsen/logrus/logger.go b/vendor/github.com/sirupsen/logrus/logger.go index 33770445..015fbdc3 100644 --- a/vendor/github.com/sirupsen/logrus/logger.go +++ b/vendor/github.com/sirupsen/logrus/logger.go @@ -341,9 +341,9 @@ func (logger *Logger) Exit(code int) { logger.ExitFunc(code) } -//When file is opened with appending mode, it's safe to -//write concurrently to a file (within 4k message on Linux). -//In these cases user can choose to disable the lock. +// When file is opened with appending mode, it's safe to +// write concurrently to a file (within 4k message on Linux). +// In these cases user can choose to disable the lock. func (logger *Logger) SetNoLock() { logger.mu.Disable() } diff --git a/vendor/github.com/sirupsen/logrus/text_formatter.go b/vendor/github.com/sirupsen/logrus/text_formatter.go index be2c6efe..c2abb77e 100644 --- a/vendor/github.com/sirupsen/logrus/text_formatter.go +++ b/vendor/github.com/sirupsen/logrus/text_formatter.go @@ -202,7 +202,6 @@ func (f *TextFormatter) Format(entry *Entry) ([]byte, error) { if f.isColored() { f.printColored(b, entry, keys, data, timestampFormat) } else { - for _, key := range fixedKeys { var value interface{} switch { diff --git a/vendor/github.com/spf13/afero/afero.go b/vendor/github.com/spf13/afero/afero.go index 469ff7d2..bf2644d6 100644 --- a/vendor/github.com/spf13/afero/afero.go +++ b/vendor/github.com/spf13/afero/afero.go @@ -97,7 +97,7 @@ type Fs interface { // Chown changes the uid and gid of the named file. Chown(name string, uid, gid int) error - //Chtimes changes the access and modification times of the named file + // Chtimes changes the access and modification times of the named file Chtimes(name string, atime time.Time, mtime time.Time) error } diff --git a/vendor/github.com/spf13/afero/copyOnWriteFs.go b/vendor/github.com/spf13/afero/copyOnWriteFs.go index 6ff8f309..4c8efa40 100644 --- a/vendor/github.com/spf13/afero/copyOnWriteFs.go +++ b/vendor/github.com/spf13/afero/copyOnWriteFs.go @@ -223,7 +223,7 @@ func (u *CopyOnWriteFs) OpenFile(name string, flag int, perm os.FileMode) (File, return nil, err } if isaDir { - if err = u.layer.MkdirAll(dir, 0777); err != nil { + if err = u.layer.MkdirAll(dir, 0o777); err != nil { return nil, err } return u.layer.OpenFile(name, flag, perm) @@ -322,5 +322,5 @@ func (u *CopyOnWriteFs) MkdirAll(name string, perm os.FileMode) error { } func (u *CopyOnWriteFs) Create(name string) (File, error) { - return u.OpenFile(name, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0666) + return u.OpenFile(name, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0o666) } diff --git a/vendor/github.com/spf13/afero/ioutil.go b/vendor/github.com/spf13/afero/ioutil.go index a403133e..0a57086e 100644 --- a/vendor/github.com/spf13/afero/ioutil.go +++ b/vendor/github.com/spf13/afero/ioutil.go @@ -141,8 +141,10 @@ func WriteFile(fs Fs, filename string, data []byte, perm os.FileMode) error { // We generate random temporary file names so that there's a good // chance the file doesn't exist yet - keeps the number of tries in // TempFile to a minimum. -var rand uint32 -var randmu sync.Mutex +var ( + rand uint32 + randmu sync.Mutex +) func reseed() uint32 { return uint32(time.Now().UnixNano() + int64(os.Getpid())) @@ -190,7 +192,7 @@ func TempFile(fs Fs, dir, pattern string) (f File, err error) { nconflict := 0 for i := 0; i < 10000; i++ { name := filepath.Join(dir, prefix+nextRandom()+suffix) - f, err = fs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) + f, err = fs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o600) if os.IsExist(err) { if nconflict++; nconflict > 10 { randmu.Lock() @@ -214,6 +216,7 @@ func TempFile(fs Fs, dir, pattern string) (f File, err error) { func (a Afero) TempDir(dir, prefix string) (name string, err error) { return TempDir(a.Fs, dir, prefix) } + func TempDir(fs Fs, dir, prefix string) (name string, err error) { if dir == "" { dir = os.TempDir() @@ -222,7 +225,7 @@ func TempDir(fs Fs, dir, prefix string) (name string, err error) { nconflict := 0 for i := 0; i < 10000; i++ { try := filepath.Join(dir, prefix+nextRandom()) - err = fs.Mkdir(try, 0700) + err = fs.Mkdir(try, 0o700) if os.IsExist(err) { if nconflict++; nconflict > 10 { randmu.Lock() diff --git a/vendor/github.com/spf13/afero/mem/file.go b/vendor/github.com/spf13/afero/mem/file.go index 5a20730c..faf9326d 100644 --- a/vendor/github.com/spf13/afero/mem/file.go +++ b/vendor/github.com/spf13/afero/mem/file.go @@ -227,7 +227,7 @@ func (f *File) Truncate(size int64) error { defer f.fileData.Unlock() if size > int64(len(f.fileData.data)) { diff := size - int64(len(f.fileData.data)) - f.fileData.data = append(f.fileData.data, bytes.Repeat([]byte{00}, int(diff))...) + f.fileData.data = append(f.fileData.data, bytes.Repeat([]byte{0o0}, int(diff))...) } else { f.fileData.data = f.fileData.data[0:size] } @@ -267,7 +267,7 @@ func (f *File) Write(b []byte) (n int, err error) { tail = f.fileData.data[n+int(cur):] } if diff > 0 { - f.fileData.data = append(f.fileData.data, append(bytes.Repeat([]byte{00}, int(diff)), b...)...) + f.fileData.data = append(f.fileData.data, append(bytes.Repeat([]byte{0o0}, int(diff)), b...)...) f.fileData.data = append(f.fileData.data, tail...) } else { f.fileData.data = append(f.fileData.data[:cur], b...) @@ -303,16 +303,19 @@ func (s *FileInfo) Name() string { s.Unlock() return name } + func (s *FileInfo) Mode() os.FileMode { s.Lock() defer s.Unlock() return s.mode } + func (s *FileInfo) ModTime() time.Time { s.Lock() defer s.Unlock() return s.modtime } + func (s *FileInfo) IsDir() bool { s.Lock() defer s.Unlock() diff --git a/vendor/github.com/spf13/afero/memmap.go b/vendor/github.com/spf13/afero/memmap.go index 5c265f92..4422a38f 100644 --- a/vendor/github.com/spf13/afero/memmap.go +++ b/vendor/github.com/spf13/afero/memmap.go @@ -43,7 +43,7 @@ func (m *MemMapFs) getData() map[string]*mem.FileData { // Root should always exist, right? // TODO: what about windows? root := mem.CreateDir(FilePathSeparator) - mem.SetMode(root, os.ModeDir|0755) + mem.SetMode(root, os.ModeDir|0o755) m.data[FilePathSeparator] = root }) return m.data @@ -96,12 +96,12 @@ func (m *MemMapFs) registerWithParent(f *mem.FileData, perm os.FileMode) { pdir := filepath.Dir(filepath.Clean(f.Name())) err := m.lockfreeMkdir(pdir, perm) if err != nil { - //log.Println("Mkdir error:", err) + // log.Println("Mkdir error:", err) return } parent, err = m.lockfreeOpen(pdir) if err != nil { - //log.Println("Open after Mkdir error:", err) + // log.Println("Open after Mkdir error:", err) return } } diff --git a/vendor/github.com/spf13/afero/unionFile.go b/vendor/github.com/spf13/afero/unionFile.go index 985363ee..e33189e9 100644 --- a/vendor/github.com/spf13/afero/unionFile.go +++ b/vendor/github.com/spf13/afero/unionFile.go @@ -130,7 +130,7 @@ func (f *UnionFile) Name() string { type DirsMerger func(lofi, bofi []os.FileInfo) ([]os.FileInfo, error) var defaultUnionMergeDirsFn = func(lofi, bofi []os.FileInfo) ([]os.FileInfo, error) { - var files = make(map[string]os.FileInfo) + files := make(map[string]os.FileInfo) for _, fi := range lofi { files[fi.Name()] = fi @@ -151,7 +151,6 @@ var defaultUnionMergeDirsFn = func(lofi, bofi []os.FileInfo) ([]os.FileInfo, err } return rfi, nil - } // Readdir will weave the two directories together and @@ -281,7 +280,7 @@ func copyToLayer(base Fs, layer Fs, name string) error { return err } if !exists { - err = layer.MkdirAll(filepath.Dir(name), 0777) // FIXME? + err = layer.MkdirAll(filepath.Dir(name), 0o777) // FIXME? if err != nil { return err } diff --git a/vendor/github.com/spf13/afero/util.go b/vendor/github.com/spf13/afero/util.go index 4f253f48..dda8aa79 100644 --- a/vendor/github.com/spf13/afero/util.go +++ b/vendor/github.com/spf13/afero/util.go @@ -42,7 +42,7 @@ func WriteReader(fs Fs, path string, r io.Reader) (err error) { ospath := filepath.FromSlash(dir) if ospath != "" { - err = fs.MkdirAll(ospath, 0777) // rwx, rw, r + err = fs.MkdirAll(ospath, 0o777) // rwx, rw, r if err != nil { if err != os.ErrExist { return err @@ -70,7 +70,7 @@ func SafeWriteReader(fs Fs, path string, r io.Reader) (err error) { ospath := filepath.FromSlash(dir) if ospath != "" { - err = fs.MkdirAll(ospath, 0777) // rwx, rw, r + err = fs.MkdirAll(ospath, 0o777) // rwx, rw, r if err != nil { return } @@ -123,7 +123,7 @@ func GetTempDir(fs Fs, subPath string) string { return addSlash(dir) } - err := fs.MkdirAll(dir, 0777) + err := fs.MkdirAll(dir, 0o777) if err != nil { panic(err) } @@ -200,7 +200,6 @@ func FileContainsAnyBytes(fs Fs, filename string, subslices [][]byte) (bool, err // readerContains reports whether any of the subslices is within r. func readerContainsAny(r io.Reader, subslices ...[]byte) bool { - if r == nil || len(subslices) == 0 { return false } diff --git a/vendor/github.com/spf13/cast/caste.go b/vendor/github.com/spf13/cast/caste.go index 70c7291b..a275778e 100644 --- a/vendor/github.com/spf13/cast/caste.go +++ b/vendor/github.com/spf13/cast/caste.go @@ -785,8 +785,8 @@ func indirectToStringerOrError(a interface{}) interface{} { return nil } - var errorType = reflect.TypeOf((*error)(nil)).Elem() - var fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem() + errorType := reflect.TypeOf((*error)(nil)).Elem() + fmtStringerType := reflect.TypeOf((*fmt.Stringer)(nil)).Elem() v := reflect.ValueOf(a) for !v.Type().Implements(fmtStringerType) && !v.Type().Implements(errorType) && v.Kind() == reflect.Ptr && !v.IsNil() { @@ -853,7 +853,7 @@ func ToStringE(i interface{}) (string, error) { // ToStringMapStringE casts an interface to a map[string]string type. func ToStringMapStringE(i interface{}) (map[string]string, error) { - var m = map[string]string{} + m := map[string]string{} switch v := i.(type) { case map[string]string: @@ -883,7 +883,7 @@ func ToStringMapStringE(i interface{}) (map[string]string, error) { // ToStringMapStringSliceE casts an interface to a map[string][]string type. func ToStringMapStringSliceE(i interface{}) (map[string][]string, error) { - var m = map[string][]string{} + m := map[string][]string{} switch v := i.(type) { case map[string][]string: @@ -947,7 +947,7 @@ func ToStringMapStringSliceE(i interface{}) (map[string][]string, error) { // ToStringMapBoolE casts an interface to a map[string]bool type. func ToStringMapBoolE(i interface{}) (map[string]bool, error) { - var m = map[string]bool{} + m := map[string]bool{} switch v := i.(type) { case map[interface{}]interface{}: @@ -972,7 +972,7 @@ func ToStringMapBoolE(i interface{}) (map[string]bool, error) { // ToStringMapE casts an interface to a map[string]interface{} type. func ToStringMapE(i interface{}) (map[string]interface{}, error) { - var m = map[string]interface{}{} + m := map[string]interface{}{} switch v := i.(type) { case map[interface{}]interface{}: @@ -992,7 +992,7 @@ func ToStringMapE(i interface{}) (map[string]interface{}, error) { // ToStringMapIntE casts an interface to a map[string]int{} type. func ToStringMapIntE(i interface{}) (map[string]int, error) { - var m = map[string]int{} + m := map[string]int{} if i == nil { return m, fmt.Errorf("unable to cast %#v of type %T to map[string]int", i, i) } @@ -1033,7 +1033,7 @@ func ToStringMapIntE(i interface{}) (map[string]int, error) { // ToStringMapInt64E casts an interface to a map[string]int64{} type. func ToStringMapInt64E(i interface{}) (map[string]int64, error) { - var m = map[string]int64{} + m := map[string]int64{} if i == nil { return m, fmt.Errorf("unable to cast %#v of type %T to map[string]int64", i, i) } diff --git a/vendor/github.com/spf13/cobra/bash_completions.go b/vendor/github.com/spf13/cobra/bash_completions.go index 846636d7..50a6883c 100644 --- a/vendor/github.com/spf13/cobra/bash_completions.go +++ b/vendor/github.com/spf13/cobra/bash_completions.go @@ -610,6 +610,7 @@ func writeCmdAliases(buf *bytes.Buffer, cmd *Command) { buf.WriteString(` fi`) buf.WriteString("\n") } + func writeArgAliases(buf *bytes.Buffer, cmd *Command) { buf.WriteString(" noun_aliases=()\n") sort.Sort(sort.StringSlice(cmd.ArgAliases)) diff --git a/vendor/github.com/spf13/cobra/cobra.go b/vendor/github.com/spf13/cobra/cobra.go index d01becc8..30c81a75 100644 --- a/vendor/github.com/spf13/cobra/cobra.go +++ b/vendor/github.com/spf13/cobra/cobra.go @@ -192,7 +192,6 @@ func ld(s, t string, ignoreCase bool) int { d[i][j] = min + 1 } } - } return d[len(s)][len(t)] } diff --git a/vendor/github.com/spf13/cobra/custom_completions.go b/vendor/github.com/spf13/cobra/custom_completions.go index f9e88e08..821f6513 100644 --- a/vendor/github.com/spf13/cobra/custom_completions.go +++ b/vendor/github.com/spf13/cobra/custom_completions.go @@ -524,7 +524,7 @@ func CompDebug(msg string, printToStdErr bool) { // variable BASH_COMP_DEBUG_FILE to the path of some file to be used. if path := os.Getenv("BASH_COMP_DEBUG_FILE"); path != "" { f, err := os.OpenFile(path, - os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) if err == nil { defer f.Close() f.WriteString(msg) diff --git a/vendor/github.com/spf13/pflag/bool_slice.go b/vendor/github.com/spf13/pflag/bool_slice.go index 3731370d..06e0f50e 100644 --- a/vendor/github.com/spf13/pflag/bool_slice.go +++ b/vendor/github.com/spf13/pflag/bool_slice.go @@ -22,7 +22,6 @@ func newBoolSliceValue(val []bool, p *[]bool) *boolSliceValue { // Set converts, and assigns, the comma-separated boolean argument string representation as the []bool value of this flag. // If Set is called on a flag that already has a []bool assigned, the newly converted values will be appended. func (s *boolSliceValue) Set(val string) error { - // remove all quote characters rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "") @@ -60,7 +59,6 @@ func (s *boolSliceValue) Type() string { // String defines a "native" format for this boolean slice flag value. func (s *boolSliceValue) String() string { - boolStrSlice := make([]string, len(*s.value)) for i, b := range *s.value { boolStrSlice[i] = strconv.FormatBool(b) diff --git a/vendor/github.com/spf13/pflag/bytes.go b/vendor/github.com/spf13/pflag/bytes.go index 67d53045..6856088a 100644 --- a/vendor/github.com/spf13/pflag/bytes.go +++ b/vendor/github.com/spf13/pflag/bytes.go @@ -18,7 +18,6 @@ func (bytesHex bytesHexValue) String() string { // Set implements pflag.Value.Set. func (bytesHex *bytesHexValue) Set(value string) error { bin, err := hex.DecodeString(strings.TrimSpace(value)) - if err != nil { return err } @@ -39,7 +38,6 @@ func newBytesHexValue(val []byte, p *[]byte) *bytesHexValue { } func bytesHexConv(sval string) (interface{}, error) { - bin, err := hex.DecodeString(sval) if err == nil { @@ -52,7 +50,6 @@ func bytesHexConv(sval string) (interface{}, error) { // GetBytesHex return the []byte value of a flag with the given name func (f *FlagSet) GetBytesHex(name string) ([]byte, error) { val, err := f.getFlagType(name, "bytesHex", bytesHexConv) - if err != nil { return []byte{}, err } @@ -119,7 +116,6 @@ func (bytesBase64 bytesBase64Value) String() string { // Set implements pflag.Value.Set. func (bytesBase64 *bytesBase64Value) Set(value string) error { bin, err := base64.StdEncoding.DecodeString(strings.TrimSpace(value)) - if err != nil { return err } @@ -140,7 +136,6 @@ func newBytesBase64Value(val []byte, p *[]byte) *bytesBase64Value { } func bytesBase64ValueConv(sval string) (interface{}, error) { - bin, err := base64.StdEncoding.DecodeString(sval) if err == nil { return bin, nil @@ -152,7 +147,6 @@ func bytesBase64ValueConv(sval string) (interface{}, error) { // GetBytesBase64 return the []byte value of a flag with the given name func (f *FlagSet) GetBytesBase64(name string) ([]byte, error) { val, err := f.getFlagType(name, "bytesBase64", bytesBase64ValueConv) - if err != nil { return []byte{}, err } diff --git a/vendor/github.com/spf13/pflag/flag.go b/vendor/github.com/spf13/pflag/flag.go index 24a5036e..b24a6a56 100644 --- a/vendor/github.com/spf13/pflag/flag.go +++ b/vendor/github.com/spf13/pflag/flag.go @@ -668,7 +668,6 @@ func wrap(i, w int, s string) string { } return r - } // FlagUsagesWrapped returns a string containing the usage information diff --git a/vendor/github.com/spf13/pflag/golangflag.go b/vendor/github.com/spf13/pflag/golangflag.go index d3dd72b7..3e47328b 100644 --- a/vendor/github.com/spf13/pflag/golangflag.go +++ b/vendor/github.com/spf13/pflag/golangflag.go @@ -68,7 +68,7 @@ func PFlagFromGoFlag(goflag *goflag.Flag) *Flag { Usage: goflag.Usage, Value: wrapFlagValue(goflag.Value), // Looks like golang flags don't set DefValue correctly :-( - //DefValue: goflag.DefValue, + // DefValue: goflag.DefValue, DefValue: goflag.Value.String(), } // Ex: if the golang flag was -v, allow both -v and --v to work diff --git a/vendor/github.com/spf13/pflag/ip_slice.go b/vendor/github.com/spf13/pflag/ip_slice.go index 775faae4..23bc991d 100644 --- a/vendor/github.com/spf13/pflag/ip_slice.go +++ b/vendor/github.com/spf13/pflag/ip_slice.go @@ -23,7 +23,6 @@ func newIPSliceValue(val []net.IP, p *[]net.IP) *ipSliceValue { // Set converts, and assigns, the comma-separated IP argument string representation as the []net.IP value of this flag. // If Set is called on a flag that already has a []net.IP assigned, the newly converted values will be appended. func (s *ipSliceValue) Set(val string) error { - // remove all quote characters rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "") @@ -61,7 +60,6 @@ func (s *ipSliceValue) Type() string { // String defines a "native" format for this net.IP slice flag value. func (s *ipSliceValue) String() string { - ipStrSlice := make([]string, len(*s.value)) for i, ip := range *s.value { ipStrSlice[i] = ip.String() diff --git a/vendor/github.com/spf13/pflag/string.go b/vendor/github.com/spf13/pflag/string.go index 04e0a26f..c96b8020 100644 --- a/vendor/github.com/spf13/pflag/string.go +++ b/vendor/github.com/spf13/pflag/string.go @@ -12,6 +12,7 @@ func (s *stringValue) Set(val string) error { *s = stringValue(val) return nil } + func (s *stringValue) Type() string { return "string" } diff --git a/vendor/github.com/spf13/viper/viper.go b/vendor/github.com/spf13/viper/viper.go index 405dc20f..ced939d1 100644 --- a/vendor/github.com/spf13/viper/viper.go +++ b/vendor/github.com/spf13/viper/viper.go @@ -221,7 +221,7 @@ func New() *Viper { v := new(Viper) v.keyDelim = "." v.configName = "config" - v.configPermissions = os.FileMode(0644) + v.configPermissions = os.FileMode(0o644) v.fs = afero.NewOsFs() v.config = make(map[string]interface{}) v.override = make(map[string]interface{}) @@ -409,6 +409,7 @@ func (v *Viper) WatchConfig() { // SetConfigFile explicitly defines the path, name and extension of the config file. // Viper will use this and not check any of the config paths. func SetConfigFile(in string) { v.SetConfigFile(in) } + func (v *Viper) SetConfigFile(in string) { if in != "" { v.configFile = in @@ -419,6 +420,7 @@ func (v *Viper) SetConfigFile(in string) { // E.g. if your prefix is "spf", the env registry will look for env // variables that start with "SPF_". func SetEnvPrefix(in string) { v.SetEnvPrefix(in) } + func (v *Viper) SetEnvPrefix(in string) { if in != "" { v.envPrefix = in @@ -437,6 +439,7 @@ func (v *Viper) mergeWithEnvPrefix(in string) string { // but empty environment variables as valid values instead of falling back. // For backward compatibility reasons this is false by default. func AllowEmptyEnv(allowEmptyEnv bool) { v.AllowEmptyEnv(allowEmptyEnv) } + func (v *Viper) AllowEmptyEnv(allowEmptyEnv bool) { v.allowEmptyEnv = allowEmptyEnv } @@ -465,6 +468,7 @@ func (v *Viper) ConfigFileUsed() string { return v.configFile } // AddConfigPath adds a path for Viper to search for the config file in. // Can be called multiple times to define multiple search paths. func AddConfigPath(in string) { v.AddConfigPath(in) } + func (v *Viper) AddConfigPath(in string) { if in != "" { absin := absPathify(in) @@ -486,6 +490,7 @@ func (v *Viper) AddConfigPath(in string) { func AddRemoteProvider(provider, endpoint, path string) error { return v.AddRemoteProvider(provider, endpoint, path) } + func (v *Viper) AddRemoteProvider(provider, endpoint, path string) error { if !stringInSlice(provider, SupportedRemoteProviders) { return UnsupportedRemoteProviderError(provider) @@ -706,6 +711,7 @@ func (v *Viper) isPathShadowedInAutoEnv(path []string) string { // // "a b c" func SetTypeByDefaultValue(enable bool) { v.SetTypeByDefaultValue(enable) } + func (v *Viper) SetTypeByDefaultValue(enable bool) { v.typeByDefValue = enable } @@ -723,6 +729,7 @@ func GetViper() *Viper { // // Get returns an interface. For a specific value use one of the Get____ methods. func Get(key string) interface{} { return v.Get(key) } + func (v *Viper) Get(key string) interface{} { lcaseKey := strings.ToLower(key) val := v.find(lcaseKey, true) @@ -773,6 +780,7 @@ func (v *Viper) Get(key string) interface{} { // Sub returns new Viper instance representing a sub tree of this instance. // Sub is case-insensitive for a key. func Sub(key string) *Viper { return v.Sub(key) } + func (v *Viper) Sub(key string) *Viper { subv := New() data := v.Get(key) @@ -789,96 +797,112 @@ func (v *Viper) Sub(key string) *Viper { // GetString returns the value associated with the key as a string. func GetString(key string) string { return v.GetString(key) } + func (v *Viper) GetString(key string) string { return cast.ToString(v.Get(key)) } // GetBool returns the value associated with the key as a boolean. func GetBool(key string) bool { return v.GetBool(key) } + func (v *Viper) GetBool(key string) bool { return cast.ToBool(v.Get(key)) } // GetInt returns the value associated with the key as an integer. func GetInt(key string) int { return v.GetInt(key) } + func (v *Viper) GetInt(key string) int { return cast.ToInt(v.Get(key)) } // GetInt32 returns the value associated with the key as an integer. func GetInt32(key string) int32 { return v.GetInt32(key) } + func (v *Viper) GetInt32(key string) int32 { return cast.ToInt32(v.Get(key)) } // GetInt64 returns the value associated with the key as an integer. func GetInt64(key string) int64 { return v.GetInt64(key) } + func (v *Viper) GetInt64(key string) int64 { return cast.ToInt64(v.Get(key)) } // GetUint returns the value associated with the key as an unsigned integer. func GetUint(key string) uint { return v.GetUint(key) } + func (v *Viper) GetUint(key string) uint { return cast.ToUint(v.Get(key)) } // GetUint32 returns the value associated with the key as an unsigned integer. func GetUint32(key string) uint32 { return v.GetUint32(key) } + func (v *Viper) GetUint32(key string) uint32 { return cast.ToUint32(v.Get(key)) } // GetUint64 returns the value associated with the key as an unsigned integer. func GetUint64(key string) uint64 { return v.GetUint64(key) } + func (v *Viper) GetUint64(key string) uint64 { return cast.ToUint64(v.Get(key)) } // GetFloat64 returns the value associated with the key as a float64. func GetFloat64(key string) float64 { return v.GetFloat64(key) } + func (v *Viper) GetFloat64(key string) float64 { return cast.ToFloat64(v.Get(key)) } // GetTime returns the value associated with the key as time. func GetTime(key string) time.Time { return v.GetTime(key) } + func (v *Viper) GetTime(key string) time.Time { return cast.ToTime(v.Get(key)) } // GetDuration returns the value associated with the key as a duration. func GetDuration(key string) time.Duration { return v.GetDuration(key) } + func (v *Viper) GetDuration(key string) time.Duration { return cast.ToDuration(v.Get(key)) } // GetIntSlice returns the value associated with the key as a slice of int values. func GetIntSlice(key string) []int { return v.GetIntSlice(key) } + func (v *Viper) GetIntSlice(key string) []int { return cast.ToIntSlice(v.Get(key)) } // GetStringSlice returns the value associated with the key as a slice of strings. func GetStringSlice(key string) []string { return v.GetStringSlice(key) } + func (v *Viper) GetStringSlice(key string) []string { return cast.ToStringSlice(v.Get(key)) } // GetStringMap returns the value associated with the key as a map of interfaces. func GetStringMap(key string) map[string]interface{} { return v.GetStringMap(key) } + func (v *Viper) GetStringMap(key string) map[string]interface{} { return cast.ToStringMap(v.Get(key)) } // GetStringMapString returns the value associated with the key as a map of strings. func GetStringMapString(key string) map[string]string { return v.GetStringMapString(key) } + func (v *Viper) GetStringMapString(key string) map[string]string { return cast.ToStringMapString(v.Get(key)) } // GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings. func GetStringMapStringSlice(key string) map[string][]string { return v.GetStringMapStringSlice(key) } + func (v *Viper) GetStringMapStringSlice(key string) map[string][]string { return cast.ToStringMapStringSlice(v.Get(key)) } @@ -886,6 +910,7 @@ func (v *Viper) GetStringMapStringSlice(key string) map[string][]string { // GetSizeInBytes returns the size of the value associated with the given key // in bytes. func GetSizeInBytes(key string) uint { return v.GetSizeInBytes(key) } + func (v *Viper) GetSizeInBytes(key string) uint { sizeStr := cast.ToString(v.Get(key)) return parseSizeInBytes(sizeStr) @@ -895,6 +920,7 @@ func (v *Viper) GetSizeInBytes(key string) uint { func UnmarshalKey(key string, rawVal interface{}, opts ...DecoderConfigOption) error { return v.UnmarshalKey(key, rawVal, opts...) } + func (v *Viper) UnmarshalKey(key string, rawVal interface{}, opts ...DecoderConfigOption) error { return decode(v.Get(key), defaultDecoderConfig(rawVal, opts...)) } @@ -904,6 +930,7 @@ func (v *Viper) UnmarshalKey(key string, rawVal interface{}, opts ...DecoderConf func Unmarshal(rawVal interface{}, opts ...DecoderConfigOption) error { return v.Unmarshal(rawVal, opts...) } + func (v *Viper) Unmarshal(rawVal interface{}, opts ...DecoderConfigOption) error { return decode(v.AllSettings(), defaultDecoderConfig(rawVal, opts...)) } @@ -940,6 +967,7 @@ func decode(input interface{}, config *mapstructure.DecoderConfig) error { func UnmarshalExact(rawVal interface{}, opts ...DecoderConfigOption) error { return v.UnmarshalExact(rawVal, opts...) } + func (v *Viper) UnmarshalExact(rawVal interface{}, opts ...DecoderConfigOption) error { config := defaultDecoderConfig(rawVal, opts...) config.ErrorUnused = true @@ -950,6 +978,7 @@ func (v *Viper) UnmarshalExact(rawVal interface{}, opts ...DecoderConfigOption) // BindPFlags binds a full flag set to the configuration, using each flag's long // name as the config key. func BindPFlags(flags *pflag.FlagSet) error { return v.BindPFlags(flags) } + func (v *Viper) BindPFlags(flags *pflag.FlagSet) error { return v.BindFlagValues(pflagValueSet{flags}) } @@ -961,6 +990,7 @@ func (v *Viper) BindPFlags(flags *pflag.FlagSet) error { // Viper.BindPFlag("port", serverCmd.Flags().Lookup("port")) // func BindPFlag(key string, flag *pflag.Flag) error { return v.BindPFlag(key, flag) } + func (v *Viper) BindPFlag(key string, flag *pflag.Flag) error { return v.BindFlagValue(key, pflagValue{flag}) } @@ -968,6 +998,7 @@ func (v *Viper) BindPFlag(key string, flag *pflag.Flag) error { // BindFlagValues binds a full FlagValue set to the configuration, using each flag's long // name as the config key. func BindFlagValues(flags FlagValueSet) error { return v.BindFlagValues(flags) } + func (v *Viper) BindFlagValues(flags FlagValueSet) (err error) { flags.VisitAll(func(flag FlagValue) { if err = v.BindFlagValue(flag.Name(), flag); err != nil { @@ -979,6 +1010,7 @@ func (v *Viper) BindFlagValues(flags FlagValueSet) (err error) { // BindFlagValue binds a specific key to a FlagValue. func BindFlagValue(key string, flag FlagValue) error { return v.BindFlagValue(key, flag) } + func (v *Viper) BindFlagValue(key string, flag FlagValue) error { if flag == nil { return fmt.Errorf("flag for %q is nil", key) @@ -992,6 +1024,7 @@ func (v *Viper) BindFlagValue(key string, flag FlagValue) error { // If only a key is provided, it will use the env key matching the key, uppercased. // EnvPrefix will be used when set when env name is not provided. func BindEnv(input ...string) error { return v.BindEnv(input...) } + func (v *Viper) BindEnv(input ...string) error { var key, envkey string if len(input) == 0 { @@ -1190,6 +1223,7 @@ func stringToStringConv(val string) interface{} { // IsSet checks to see if the key has been set in any of the data locations. // IsSet is case-insensitive for a key. func IsSet(key string) bool { return v.IsSet(key) } + func (v *Viper) IsSet(key string) bool { lcaseKey := strings.ToLower(key) val := v.find(lcaseKey, false) @@ -1199,6 +1233,7 @@ func (v *Viper) IsSet(key string) bool { // AutomaticEnv has Viper check ENV variables for all. // keys set in config, default & flags func AutomaticEnv() { v.AutomaticEnv() } + func (v *Viper) AutomaticEnv() { v.automaticEnvApplied = true } @@ -1207,6 +1242,7 @@ func (v *Viper) AutomaticEnv() { // Useful for mapping an environmental variable to a key that does // not match it. func SetEnvKeyReplacer(r *strings.Replacer) { v.SetEnvKeyReplacer(r) } + func (v *Viper) SetEnvKeyReplacer(r *strings.Replacer) { v.envKeyReplacer = r } @@ -1214,6 +1250,7 @@ func (v *Viper) SetEnvKeyReplacer(r *strings.Replacer) { // RegisterAlias creates an alias that provides another accessor for the same key. // This enables one to change a name without breaking the application. func RegisterAlias(alias string, key string) { v.RegisterAlias(alias, key) } + func (v *Viper) RegisterAlias(alias string, key string) { v.registerAlias(alias, strings.ToLower(key)) } @@ -1261,6 +1298,7 @@ func (v *Viper) realKey(key string) string { // InConfig checks to see if the given key (or an alias) is in the config file. func InConfig(key string) bool { return v.InConfig(key) } + func (v *Viper) InConfig(key string) bool { // if the requested key is an alias, then return the proper key key = v.realKey(key) @@ -1273,6 +1311,7 @@ func (v *Viper) InConfig(key string) bool { // SetDefault is case-insensitive for a key. // Default only used when no value is provided by the user via flag, config or ENV. func SetDefault(key string, value interface{}) { v.SetDefault(key, value) } + func (v *Viper) SetDefault(key string, value interface{}) { // If alias passed in, then set the proper default key = v.realKey(strings.ToLower(key)) @@ -1291,6 +1330,7 @@ func (v *Viper) SetDefault(key string, value interface{}) { // Will be used instead of values obtained via // flags, config file, ENV, default, or key/value store. func Set(key string, value interface{}) { v.Set(key, value) } + func (v *Viper) Set(key string, value interface{}) { // If alias passed in, then set the proper override key = v.realKey(strings.ToLower(key)) @@ -1307,6 +1347,7 @@ func (v *Viper) Set(key string, value interface{}) { // ReadInConfig will discover and load the configuration file from disk // and key/value stores, searching in one of the defined paths. func ReadInConfig() error { return v.ReadInConfig() } + func (v *Viper) ReadInConfig() error { jww.INFO.Println("Attempting to read in config file") filename, err := v.getConfigFile() @@ -1337,6 +1378,7 @@ func (v *Viper) ReadInConfig() error { // MergeInConfig merges a new configuration with an existing config. func MergeInConfig() error { return v.MergeInConfig() } + func (v *Viper) MergeInConfig() error { jww.INFO.Println("Attempting to merge in config file") filename, err := v.getConfigFile() @@ -1359,6 +1401,7 @@ func (v *Viper) MergeInConfig() error { // ReadConfig will read a configuration file, setting existing keys to nil if the // key does not exist in the file. func ReadConfig(in io.Reader) error { return v.ReadConfig(in) } + func (v *Viper) ReadConfig(in io.Reader) error { v.config = make(map[string]interface{}) return v.unmarshalReader(in, v.config) @@ -1366,6 +1409,7 @@ func (v *Viper) ReadConfig(in io.Reader) error { // MergeConfig merges a new configuration with an existing config. func MergeConfig(in io.Reader) error { return v.MergeConfig(in) } + func (v *Viper) MergeConfig(in io.Reader) error { cfg := make(map[string]interface{}) if err := v.unmarshalReader(in, cfg); err != nil { @@ -1377,6 +1421,7 @@ func (v *Viper) MergeConfig(in io.Reader) error { // MergeConfigMap merges the configuration from the map given with an existing config. // Note that the map given may be modified. func MergeConfigMap(cfg map[string]interface{}) error { return v.MergeConfigMap(cfg) } + func (v *Viper) MergeConfigMap(cfg map[string]interface{}) error { if v.config == nil { v.config = make(map[string]interface{}) @@ -1388,6 +1433,7 @@ func (v *Viper) MergeConfigMap(cfg map[string]interface{}) error { // WriteConfig writes the current configuration to a file. func WriteConfig() error { return v.WriteConfig() } + func (v *Viper) WriteConfig() error { filename, err := v.getConfigFile() if err != nil { @@ -1398,6 +1444,7 @@ func (v *Viper) WriteConfig() error { // SafeWriteConfig writes current configuration to file only if the file does not exist. func SafeWriteConfig() error { return v.SafeWriteConfig() } + func (v *Viper) SafeWriteConfig() error { if len(v.configPaths) < 1 { return errors.New("missing configuration for 'configPath'") @@ -1407,12 +1454,14 @@ func (v *Viper) SafeWriteConfig() error { // WriteConfigAs writes current configuration to a given filename. func WriteConfigAs(filename string) error { return v.WriteConfigAs(filename) } + func (v *Viper) WriteConfigAs(filename string) error { return v.writeConfig(filename, true) } // SafeWriteConfigAs writes current configuration to a given filename if it does not exist. func SafeWriteConfigAs(filename string) error { return v.SafeWriteConfigAs(filename) } + func (v *Viper) SafeWriteConfigAs(filename string) error { alreadyExists, err := afero.Exists(v.fs, filename) if alreadyExists && err == nil { @@ -1463,6 +1512,7 @@ func (v *Viper) writeConfig(filename string, force bool) error { func unmarshalReader(in io.Reader, c map[string]interface{}) error { return v.unmarshalReader(in, c) } + func (v *Viper) unmarshalReader(in io.Reader, c map[string]interface{}) error { buf := new(bytes.Buffer) buf.ReadFrom(in) @@ -1737,6 +1787,7 @@ func mergeMaps( // ReadRemoteConfig attempts to get configuration from a remote source // and read it in the remote configuration registry. func ReadRemoteConfig() error { return v.ReadRemoteConfig() } + func (v *Viper) ReadRemoteConfig() error { return v.getKeyValueConfig() } @@ -1818,6 +1869,7 @@ func (v *Viper) watchRemoteConfig(provider RemoteProvider) (map[string]interface // AllKeys returns all keys holding a value, regardless of where they are set. // Nested keys are returned with a v.keyDelim separator func AllKeys() []string { return v.AllKeys() } + func (v *Viper) AllKeys() []string { m := map[string]bool{} // add all paths, by order of descending priority to ensure correct shadowing @@ -1898,6 +1950,7 @@ outer: // AllSettings merges all settings and returns them as a map[string]interface{}. func AllSettings() map[string]interface{} { return v.AllSettings() } + func (v *Viper) AllSettings() map[string]interface{} { m := map[string]interface{}{} // start from the list of keys, and construct the map one value at a time @@ -1919,6 +1972,7 @@ func (v *Viper) AllSettings() map[string]interface{} { // SetFs sets the filesystem to use to read configuration. func SetFs(fs afero.Fs) { v.SetFs(fs) } + func (v *Viper) SetFs(fs afero.Fs) { v.fs = fs } @@ -1926,6 +1980,7 @@ func (v *Viper) SetFs(fs afero.Fs) { // SetConfigName sets name for the config file. // Does not include extension. func SetConfigName(in string) { v.SetConfigName(in) } + func (v *Viper) SetConfigName(in string) { if in != "" { v.configName = in @@ -1936,6 +1991,7 @@ func (v *Viper) SetConfigName(in string) { // SetConfigType sets the type of the configuration returned by the // remote source, e.g. "json". func SetConfigType(in string) { v.SetConfigType(in) } + func (v *Viper) SetConfigType(in string) { if in != "" { v.configType = in @@ -1944,6 +2000,7 @@ func (v *Viper) SetConfigType(in string) { // SetConfigPermissions sets the permissions for the config file. func SetConfigPermissions(perm os.FileMode) { v.SetConfigPermissions(perm) } + func (v *Viper) SetConfigPermissions(perm os.FileMode) { v.configPermissions = perm.Perm() } @@ -2014,6 +2071,7 @@ func (v *Viper) findConfigFile() (string, error) { // Debug prints all configuration registries for debugging // purposes. func Debug() { v.Debug() } + func (v *Viper) Debug() { fmt.Printf("Aliases:\n%#v\n", v.aliases) fmt.Printf("Override:\n%#v\n", v.override) diff --git a/vendor/github.com/stretchr/testify/assert/assertions.go b/vendor/github.com/stretchr/testify/assert/assertions.go index bcac4401..0ba29545 100644 --- a/vendor/github.com/stretchr/testify/assert/assertions.go +++ b/vendor/github.com/stretchr/testify/assert/assertions.go @@ -103,7 +103,6 @@ the problem actually occurred in calling code.*/ // of each stack frame leading from the current test to the assert call that // failed. func CallerInfo() []string { - var pc uintptr var ok bool var file string @@ -349,7 +348,6 @@ func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) } return true - } // validateEqualArgs checks whether provided arguments can be safely used in the @@ -470,7 +468,6 @@ func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interfa } return true - } // Exactly asserts that two objects are equal in value and type. @@ -489,7 +486,6 @@ func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{} } return Equal(t, expected, actual, msgAndArgs...) - } // NotNil asserts that the specified object is not nil. @@ -528,7 +524,8 @@ func isNil(object interface{}) bool { []reflect.Kind{ reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, - reflect.Ptr, reflect.Slice}, + reflect.Ptr, reflect.Slice, + }, kind) if isNilableKind && value.IsNil() { @@ -553,7 +550,6 @@ func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { // isEmpty gets whether the specified object is considered empty or not. func isEmpty(object interface{}) bool { - // get nil case out of the way if object == nil { return true @@ -593,7 +589,6 @@ func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { } return pass - } // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either @@ -612,7 +607,6 @@ func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { } return pass - } // getLen try to get length of object. @@ -658,7 +652,6 @@ func True(t TestingT, value bool, msgAndArgs ...interface{}) bool { } return true - } // False asserts that the specified value is false. @@ -673,7 +666,6 @@ func False(t TestingT, value bool, msgAndArgs ...interface{}) bool { } return true - } // NotEqual asserts that the specified values are NOT equal. @@ -696,7 +688,6 @@ func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{ } return true - } // NotEqualValues asserts that two objects are not equal even when converted to the same type @@ -719,7 +710,6 @@ func NotEqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...inte // return (true, false) if element was not found. // return (true, true) if element was found. func includeElement(list interface{}, element interface{}) (ok, found bool) { - listValue := reflect.ValueOf(list) listKind := reflect.TypeOf(list).Kind() defer func() { @@ -750,7 +740,6 @@ func includeElement(list interface{}, element interface{}) (ok, found bool) { } } return true, false - } // Contains asserts that the specified string, list(array, slice...) or map contains the @@ -773,7 +762,6 @@ func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bo } return true - } // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the @@ -796,7 +784,6 @@ func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) } return true - } // Subset asserts that the specified list(array, slice...) contains all @@ -1001,12 +988,10 @@ type PanicTestFunc func() // didPanic returns true if the function passed to it panics. Otherwise, it returns false. func didPanic(f PanicTestFunc) (bool, interface{}, string) { - didPanic := false var message interface{} var stack string func() { - defer func() { if message = recover(); message != nil { didPanic = true @@ -1016,11 +1001,9 @@ func didPanic(f PanicTestFunc) (bool, interface{}, string) { // call the target function f() - }() return didPanic, message, stack - } // Panics asserts that the code inside the specified PanicTestFunc panics. @@ -1377,7 +1360,6 @@ func EqualError(t TestingT, theError error, errString string, msgAndArgs ...inte // matchRegexp return true if a specified regexp matches a string. func matchRegexp(rx interface{}, str interface{}) bool { - var r *regexp.Regexp if rr, ok := rx.(*regexp.Regexp); ok { r = rr @@ -1386,7 +1368,6 @@ func matchRegexp(rx interface{}, str interface{}) bool { } return (r.FindStringIndex(fmt.Sprint(str)) != nil) - } // Regexp asserts that a specified regexp matches a string. @@ -1422,7 +1403,6 @@ func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interf } return !match - } // Zero asserts that i is the zero value for its type. diff --git a/vendor/github.com/ugorji/go/codec/binc.go b/vendor/github.com/ugorji/go/codec/binc.go index d2b4ba06..787d4fcd 100644 --- a/vendor/github.com/ugorji/go/codec/binc.go +++ b/vendor/github.com/ugorji/go/codec/binc.go @@ -715,7 +715,7 @@ func (d *bincDecDriver) DecodeStringAsBytes() (bs2 []byte) { if d.advanceNil() { return } - var slen = -1 + slen := -1 switch d.vd { case bincVdString, bincVdByteArray: slen = d.decLen() @@ -943,8 +943,8 @@ func (d *bincDecDriver) nextValueBytes(v0 []byte) (v []byte) { d.readNextBd() } v = v0 - var h = decNextValueBytesHelper{d: &d.d} - var cursor = d.d.rb.c - 1 + h := decNextValueBytesHelper{d: &d.d} + cursor := d.d.rb.c - 1 h.append1(&v, d.bd) v = d.nextValueBytesBdReadR(v) d.bdRead = false @@ -955,14 +955,14 @@ func (d *bincDecDriver) nextValueBytes(v0 []byte) (v []byte) { func (d *bincDecDriver) nextValueBytesR(v0 []byte) (v []byte) { d.readNextBd() v = v0 - var h = decNextValueBytesHelper{d: &d.d} + h := decNextValueBytesHelper{d: &d.d} h.append1(&v, d.bd) return d.nextValueBytesBdReadR(v) } func (d *bincDecDriver) nextValueBytesBdReadR(v0 []byte) (v []byte) { v = v0 - var h = decNextValueBytesHelper{d: &d.d} + h := decNextValueBytesHelper{d: &d.d} fnLen := func(vs byte) uint { switch vs { @@ -1105,7 +1105,7 @@ func (h *BincHandle) Name() string { return "binc" } func (h *BincHandle) desc(bd byte) string { return bincdesc(bd>>4, bd&0x0f) } func (h *BincHandle) newEncDriver() encDriver { - var e = &bincEncDriver{h: h} + e := &bincEncDriver{h: h} e.e.e = e e.e.init(h) e.reset() @@ -1284,9 +1284,9 @@ func bincDecodeTime(bs []byte) (tt time.Time, err error) { tz = bigen.Uint16([2]byte{bs[i], bs[i+1]}) // sign extend sign bit into top 2 MSB (which were dst bits): if tz&(1<<13) == 0 { // positive - tz = tz & 0x3fff //clear 2 MSBs: dst bits + tz = tz & 0x3fff // clear 2 MSBs: dst bits } else { // negative - tz = tz | 0xc000 //set 2 MSBs: dst bits + tz = tz | 0xc000 // set 2 MSBs: dst bits } tzint := int16(tz) if tzint == 0 { @@ -1301,5 +1301,7 @@ func bincDecodeTime(bs []byte) (tt time.Time, err error) { return } -var _ decDriver = (*bincDecDriver)(nil) -var _ encDriver = (*bincEncDriver)(nil) +var ( + _ decDriver = (*bincDecDriver)(nil) + _ encDriver = (*bincEncDriver)(nil) +) diff --git a/vendor/github.com/ugorji/go/codec/cbor.go b/vendor/github.com/ugorji/go/codec/cbor.go index b18e5aff..205aa2e4 100644 --- a/vendor/github.com/ugorji/go/codec/cbor.go +++ b/vendor/github.com/ugorji/go/codec/cbor.go @@ -785,8 +785,8 @@ func (d *cborDecDriver) nextValueBytes(v0 []byte) (v []byte) { d.readNextBd() } v = v0 - var h = decNextValueBytesHelper{d: &d.d} - var cursor = d.d.rb.c - 1 + h := decNextValueBytesHelper{d: &d.d} + cursor := d.d.rb.c - 1 h.append1(&v, d.bd) v = d.nextValueBytesBdReadR(v) d.bdRead = false @@ -797,14 +797,14 @@ func (d *cborDecDriver) nextValueBytes(v0 []byte) (v []byte) { func (d *cborDecDriver) nextValueBytesR(v0 []byte) (v []byte) { d.readNextBd() v = v0 - var h = decNextValueBytesHelper{d: &d.d} + h := decNextValueBytesHelper{d: &d.d} h.append1(&v, d.bd) return d.nextValueBytesBdReadR(v) } func (d *cborDecDriver) nextValueBytesBdReadR(v0 []byte) (v []byte) { v = v0 - var h = decNextValueBytesHelper{d: &d.d} + h := decNextValueBytesHelper{d: &d.d} var bs []byte var ui uint64 @@ -930,7 +930,7 @@ func (h *CborHandle) Name() string { return "cbor" } func (h *CborHandle) desc(bd byte) string { return cbordesc(bd) } func (h *CborHandle) newEncDriver() encDriver { - var e = &cborEncDriver{h: h} + e := &cborEncDriver{h: h} e.e.e = e e.e.init(h) e.reset() @@ -955,5 +955,7 @@ func (d *cborDecDriver) reset() { d.st = d.h.SkipUnexpectedTags } -var _ decDriver = (*cborDecDriver)(nil) -var _ encDriver = (*cborEncDriver)(nil) +var ( + _ decDriver = (*cborDecDriver)(nil) + _ encDriver = (*cborEncDriver)(nil) +) diff --git a/vendor/github.com/ugorji/go/codec/decimal.go b/vendor/github.com/ugorji/go/codec/decimal.go index a6c762e1..d51d6a50 100644 --- a/vendor/github.com/ugorji/go/codec/decimal.go +++ b/vendor/github.com/ugorji/go/codec/decimal.go @@ -98,11 +98,13 @@ var uint64pow10 = [...]uint64{ 1 * quadrillion, 10 * quadrillion, 100 * quadrillion, 1 * quintillion, 10 * quintillion, } + var float64pow10 = [...]float64{ 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22, } + var float32pow10 = [...]float32{ 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, } @@ -125,11 +127,15 @@ type floatinfo struct { mantCutoff uint64 } -var fi32 = floatinfo{23, true, 10, 7, false, 1<<23 - 1} -var fi64 = floatinfo{52, false, 22, 15, false, 1<<52 - 1} +var ( + fi32 = floatinfo{23, true, 10, 7, false, 1<<23 - 1} + fi64 = floatinfo{52, false, 22, 15, false, 1<<52 - 1} +) -var fi64u = floatinfo{0, false, 19, 0, true, fUint64Cutoff} -var fi64i = floatinfo{0, false, 19, 0, true, fUint64Cutoff} +var ( + fi64u = floatinfo{0, false, 19, 0, true, fUint64Cutoff} + fi64i = floatinfo{0, false, 19, 0, true, fUint64Cutoff} +) func strconvParseErr(b []byte, fn string) error { return &strconv.NumError{ @@ -329,7 +335,7 @@ type readFloatResult struct { func readFloat(s []byte, y floatinfo) (r readFloatResult) { var i uint // uint, so that we eliminate bounds checking - var slen = uint(len(s)) + slen := uint(len(s)) if slen == 0 { // read an empty string as the zero value // r.bad = true diff --git a/vendor/github.com/ugorji/go/codec/decode.go b/vendor/github.com/ugorji/go/codec/decode.go index c0f60f4d..21c5b434 100644 --- a/vendor/github.com/ugorji/go/codec/decode.go +++ b/vendor/github.com/ugorji/go/codec/decode.go @@ -345,7 +345,7 @@ func (d *Decoder) jsonUnmarshal(f *codecFnInfo, rv reflect.Value) { func (d *Decoder) jsonUnmarshalV(tm jsonUnmarshaler) { // grab the bytes to be read, as UnmarshalJSON needs the full JSON so as to unmarshal it itself. - var bs0 = []byte{} + bs0 := []byte{} if !d.bytes { bs0 = d.blist.get(256) } @@ -502,7 +502,7 @@ func (d *Decoder) kInterfaceNaked(f *codecFnInfo) (rvn reflect.Value) { case valueTypeExt: tag, bytes := n.u, n.l // calling decode below might taint the values bfn := d.h.getExtForTag(tag) - var re = RawExt{Tag: tag} + re := RawExt{Tag: tag} if bytes == nil { // it is one of the InterfaceExt ones: json and cbor. // most likely cbor, as json decoding never reveals valueTypeExt (no tagging support) @@ -767,7 +767,7 @@ func (d *Decoder) kSlice(f *codecFnInfo, rv reflect.Value) { var rvChanged bool - var rv0 = rv + rv0 := rv var rv9 reflect.Value rvlen := rvLenSlice(rv) @@ -806,7 +806,7 @@ func (d *Decoder) kSlice(f *codecFnInfo, rv reflect.Value) { } // consider creating new element once, and just decoding into it. - var elemReset = d.h.SliceElementReset + elemReset := d.h.SliceElementReset var j int @@ -941,7 +941,7 @@ func (d *Decoder) kArray(f *codecFnInfo, rv reflect.Value) { } // consider creating new element once, and just decoding into it. - var elemReset = d.h.SliceElementReset + elemReset := d.h.SliceElementReset for j := 0; d.containerNext(j, containerLenS, hasLen); j++ { // note that you cannot expand the array if indefinite and we go past array length @@ -989,7 +989,7 @@ func (d *Decoder) kChan(f *codecFnInfo, rv reflect.Value) { return } - var rvCanset = rv.CanSet() + rvCanset := rv.CanSet() // only expects valueType(Array|Map - nil handled above) slh, containerLenS := d.decSliceHelperStart() @@ -1014,7 +1014,7 @@ func (d *Decoder) kChan(f *codecFnInfo, rv reflect.Value) { var fn *codecFn var rvChanged bool - var rv0 = rv + rv0 := rv var rv9 reflect.Value var rvlen int // := rv.Len() @@ -1051,7 +1051,6 @@ func (d *Decoder) kChan(f *codecFnInfo, rv reflect.Value) { if rvChanged { // infers rvCanset=true, so it can be reset rv0.Set(rv) } - } func (d *Decoder) kMap(f *codecFnInfo, rv reflect.Value) { @@ -1078,7 +1077,7 @@ func (d *Decoder) kMap(f *codecFnInfo, rv reflect.Value) { var vtypeElem reflect.Type var keyFn, valFn *codecFn - var ktypeLo, vtypeLo = ktype, vtype + ktypeLo, vtypeLo := ktype, vtype if ktypeKind == reflect.Ptr { for ktypeLo = ktype.Elem(); ktypeLo.Kind() == reflect.Ptr; ktypeLo = ktypeLo.Elem() { diff --git a/vendor/github.com/ugorji/go/codec/doc.go b/vendor/github.com/ugorji/go/codec/doc.go index e53f7ffd..507ad6e0 100644 --- a/vendor/github.com/ugorji/go/codec/doc.go +++ b/vendor/github.com/ugorji/go/codec/doc.go @@ -207,7 +207,7 @@ Running Benchmarks cd bench go test -bench . -benchmem -benchtime 1s - + Please see http://github.com/ugorji/go-codec-bench . Caveats diff --git a/vendor/github.com/ugorji/go/codec/encode.go b/vendor/github.com/ugorji/go/codec/encode.go index 26cf4a67..c74727c3 100644 --- a/vendor/github.com/ugorji/go/codec/encode.go +++ b/vendor/github.com/ugorji/go/codec/encode.go @@ -310,7 +310,7 @@ func (e *Encoder) kSeqFn(rtelem reflect.Type) (fn *codecFn) { } func (e *Encoder) kSliceWMbs(rv reflect.Value, ti *typeInfo) { - var l = rvLenSlice(rv) + l := rvLenSlice(rv) if l == 0 { e.mapStart(0) } else { @@ -330,7 +330,7 @@ func (e *Encoder) kSliceWMbs(rv reflect.Value, ti *typeInfo) { } func (e *Encoder) kSliceW(rv reflect.Value, ti *typeInfo) { - var l = rvLenSlice(rv) + l := rvLenSlice(rv) e.arrayStart(l) if l > 0 { fn := e.kSeqFn(ti.elem) @@ -343,7 +343,7 @@ func (e *Encoder) kSliceW(rv reflect.Value, ti *typeInfo) { } func (e *Encoder) kArrayWMbs(rv reflect.Value, ti *typeInfo) { - var l = rv.Len() + l := rv.Len() if l == 0 { e.mapStart(0) } else { @@ -363,7 +363,7 @@ func (e *Encoder) kArrayWMbs(rv reflect.Value, ti *typeInfo) { } func (e *Encoder) kArrayW(rv reflect.Value, ti *typeInfo) { - var l = rv.Len() + l := rv.Len() e.arrayStart(l) if l > 0 { fn := e.kSeqFn(ti.elem) @@ -520,7 +520,7 @@ func (e *Encoder) kStruct(f *codecFnInfo, rv reflect.Value) { } newlen += len(f.ti.sfiSrc) - var fkvs = e.slist.get(newlen)[:newlen] + fkvs := e.slist.get(newlen)[:newlen] recur := e.h.RecursiveEmptyCheck @@ -575,7 +575,7 @@ func (e *Encoder) kStruct(f *codecFnInfo, rv reflect.Value) { if si.path.omitEmpty && isEmptyValue(kv.r, e.h.TypeInfos, recur) { switch kv.r.Kind() { case reflect.Struct, reflect.Interface, reflect.Ptr, reflect.Array, reflect.Map, reflect.Slice: - kv.r = reflect.Value{} //encode as nil + kv.r = reflect.Value{} // encode as nil } } fkvs[i] = kv @@ -626,7 +626,7 @@ func (e *Encoder) kMap(f *codecFnInfo, rv reflect.Value) { valFn = e.h.fn(rtval) } - var rvv = mapAddrLoopvarRV(f.ti.elem, vtypeKind) + rvv := mapAddrLoopvarRV(f.ti.elem, vtypeKind) if e.h.Canonical { e.kMapCanonical(f.ti, rv, rvv, valFn) @@ -635,7 +635,7 @@ func (e *Encoder) kMap(f *codecFnInfo, rv reflect.Value) { } rtkey := f.ti.key - var keyTypeIsString = stringTypId == rt2id(rtkey) // rtkeyid + keyTypeIsString := stringTypId == rt2id(rtkey) // rtkeyid if !keyTypeIsString { for rtkey.Kind() == reflect.Ptr { rtkey = rtkey.Elem() @@ -645,7 +645,7 @@ func (e *Encoder) kMap(f *codecFnInfo, rv reflect.Value) { } } - var rvk = mapAddrLoopvarRV(f.ti.key, ktypeKind) + rvk := mapAddrLoopvarRV(f.ti.key, ktypeKind) var it mapIter mapRange(&it, rv, rvk, rvv, true) diff --git a/vendor/github.com/ugorji/go/codec/fast-path.generated.go b/vendor/github.com/ugorji/go/codec/fast-path.generated.go index db1e738a..e346df63 100644 --- a/vendor/github.com/ugorji/go/codec/fast-path.generated.go +++ b/vendor/github.com/ugorji/go/codec/fast-path.generated.go @@ -48,11 +48,15 @@ type fastpathE struct { decfn func(*Decoder, *codecFnInfo, reflect.Value) } -type fastpathA [56]fastpathE -type fastpathARtid [56]uintptr +type ( + fastpathA [56]fastpathE + fastpathARtid [56]uintptr +) -var fastpathAv fastpathA -var fastpathAvRtid fastpathARtid +var ( + fastpathAv fastpathA + fastpathAvRtid fastpathARtid +) type fastpathAslice struct{} @@ -60,6 +64,7 @@ func (fastpathAslice) Len() int { return 56 } func (fastpathAslice) Less(i, j int) bool { return fastpathAvRtid[uint(i)] < fastpathAvRtid[uint(j)] } + func (fastpathAslice) Swap(i, j int) { fastpathAvRtid[uint(i)], fastpathAvRtid[uint(j)] = fastpathAvRtid[uint(j)], fastpathAvRtid[uint(i)] fastpathAv[uint(i)], fastpathAv[uint(j)] = fastpathAv[uint(j)], fastpathAv[uint(i)] @@ -635,6 +640,7 @@ func (e *Encoder) fastpathEncSliceIntfR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncSliceIntfV(v, e) } } + func (fastpathT) EncSliceIntfV(v []interface{}, e *Encoder) { e.arrayStart(len(v)) for j := range v { @@ -643,6 +649,7 @@ func (fastpathT) EncSliceIntfV(v []interface{}, e *Encoder) { } e.arrayEnd() } + func (fastpathT) EncAsMapSliceIntfV(v []interface{}, e *Encoder) { e.haltOnMbsOddLen(len(v)) e.mapStart(len(v) >> 1) // e.mapStart(len(v) / 2) @@ -656,6 +663,7 @@ func (fastpathT) EncAsMapSliceIntfV(v []interface{}, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncSliceStringR(f *codecFnInfo, rv reflect.Value) { var v []string if rv.Kind() == reflect.Array { @@ -669,6 +677,7 @@ func (e *Encoder) fastpathEncSliceStringR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncSliceStringV(v, e) } } + func (fastpathT) EncSliceStringV(v []string, e *Encoder) { e.arrayStart(len(v)) for j := range v { @@ -677,6 +686,7 @@ func (fastpathT) EncSliceStringV(v []string, e *Encoder) { } e.arrayEnd() } + func (fastpathT) EncAsMapSliceStringV(v []string, e *Encoder) { e.haltOnMbsOddLen(len(v)) e.mapStart(len(v) >> 1) // e.mapStart(len(v) / 2) @@ -690,6 +700,7 @@ func (fastpathT) EncAsMapSliceStringV(v []string, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncSliceBytesR(f *codecFnInfo, rv reflect.Value) { var v [][]byte if rv.Kind() == reflect.Array { @@ -703,6 +714,7 @@ func (e *Encoder) fastpathEncSliceBytesR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncSliceBytesV(v, e) } } + func (fastpathT) EncSliceBytesV(v [][]byte, e *Encoder) { e.arrayStart(len(v)) for j := range v { @@ -711,6 +723,7 @@ func (fastpathT) EncSliceBytesV(v [][]byte, e *Encoder) { } e.arrayEnd() } + func (fastpathT) EncAsMapSliceBytesV(v [][]byte, e *Encoder) { e.haltOnMbsOddLen(len(v)) e.mapStart(len(v) >> 1) // e.mapStart(len(v) / 2) @@ -724,6 +737,7 @@ func (fastpathT) EncAsMapSliceBytesV(v [][]byte, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncSliceFloat32R(f *codecFnInfo, rv reflect.Value) { var v []float32 if rv.Kind() == reflect.Array { @@ -737,6 +751,7 @@ func (e *Encoder) fastpathEncSliceFloat32R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncSliceFloat32V(v, e) } } + func (fastpathT) EncSliceFloat32V(v []float32, e *Encoder) { e.arrayStart(len(v)) for j := range v { @@ -745,6 +760,7 @@ func (fastpathT) EncSliceFloat32V(v []float32, e *Encoder) { } e.arrayEnd() } + func (fastpathT) EncAsMapSliceFloat32V(v []float32, e *Encoder) { e.haltOnMbsOddLen(len(v)) e.mapStart(len(v) >> 1) // e.mapStart(len(v) / 2) @@ -758,6 +774,7 @@ func (fastpathT) EncAsMapSliceFloat32V(v []float32, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncSliceFloat64R(f *codecFnInfo, rv reflect.Value) { var v []float64 if rv.Kind() == reflect.Array { @@ -771,6 +788,7 @@ func (e *Encoder) fastpathEncSliceFloat64R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncSliceFloat64V(v, e) } } + func (fastpathT) EncSliceFloat64V(v []float64, e *Encoder) { e.arrayStart(len(v)) for j := range v { @@ -779,6 +797,7 @@ func (fastpathT) EncSliceFloat64V(v []float64, e *Encoder) { } e.arrayEnd() } + func (fastpathT) EncAsMapSliceFloat64V(v []float64, e *Encoder) { e.haltOnMbsOddLen(len(v)) e.mapStart(len(v) >> 1) // e.mapStart(len(v) / 2) @@ -792,6 +811,7 @@ func (fastpathT) EncAsMapSliceFloat64V(v []float64, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncSliceUint8R(f *codecFnInfo, rv reflect.Value) { var v []uint8 if rv.Kind() == reflect.Array { @@ -805,9 +825,11 @@ func (e *Encoder) fastpathEncSliceUint8R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncSliceUint8V(v, e) } } + func (fastpathT) EncSliceUint8V(v []uint8, e *Encoder) { e.e.EncodeStringBytesRaw(v) } + func (fastpathT) EncAsMapSliceUint8V(v []uint8, e *Encoder) { e.haltOnMbsOddLen(len(v)) e.mapStart(len(v) >> 1) // e.mapStart(len(v) / 2) @@ -821,6 +843,7 @@ func (fastpathT) EncAsMapSliceUint8V(v []uint8, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncSliceUint64R(f *codecFnInfo, rv reflect.Value) { var v []uint64 if rv.Kind() == reflect.Array { @@ -834,6 +857,7 @@ func (e *Encoder) fastpathEncSliceUint64R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncSliceUint64V(v, e) } } + func (fastpathT) EncSliceUint64V(v []uint64, e *Encoder) { e.arrayStart(len(v)) for j := range v { @@ -842,6 +866,7 @@ func (fastpathT) EncSliceUint64V(v []uint64, e *Encoder) { } e.arrayEnd() } + func (fastpathT) EncAsMapSliceUint64V(v []uint64, e *Encoder) { e.haltOnMbsOddLen(len(v)) e.mapStart(len(v) >> 1) // e.mapStart(len(v) / 2) @@ -855,6 +880,7 @@ func (fastpathT) EncAsMapSliceUint64V(v []uint64, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncSliceIntR(f *codecFnInfo, rv reflect.Value) { var v []int if rv.Kind() == reflect.Array { @@ -868,6 +894,7 @@ func (e *Encoder) fastpathEncSliceIntR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncSliceIntV(v, e) } } + func (fastpathT) EncSliceIntV(v []int, e *Encoder) { e.arrayStart(len(v)) for j := range v { @@ -876,6 +903,7 @@ func (fastpathT) EncSliceIntV(v []int, e *Encoder) { } e.arrayEnd() } + func (fastpathT) EncAsMapSliceIntV(v []int, e *Encoder) { e.haltOnMbsOddLen(len(v)) e.mapStart(len(v) >> 1) // e.mapStart(len(v) / 2) @@ -889,6 +917,7 @@ func (fastpathT) EncAsMapSliceIntV(v []int, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncSliceInt32R(f *codecFnInfo, rv reflect.Value) { var v []int32 if rv.Kind() == reflect.Array { @@ -902,6 +931,7 @@ func (e *Encoder) fastpathEncSliceInt32R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncSliceInt32V(v, e) } } + func (fastpathT) EncSliceInt32V(v []int32, e *Encoder) { e.arrayStart(len(v)) for j := range v { @@ -910,6 +940,7 @@ func (fastpathT) EncSliceInt32V(v []int32, e *Encoder) { } e.arrayEnd() } + func (fastpathT) EncAsMapSliceInt32V(v []int32, e *Encoder) { e.haltOnMbsOddLen(len(v)) e.mapStart(len(v) >> 1) // e.mapStart(len(v) / 2) @@ -923,6 +954,7 @@ func (fastpathT) EncAsMapSliceInt32V(v []int32, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncSliceInt64R(f *codecFnInfo, rv reflect.Value) { var v []int64 if rv.Kind() == reflect.Array { @@ -936,6 +968,7 @@ func (e *Encoder) fastpathEncSliceInt64R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncSliceInt64V(v, e) } } + func (fastpathT) EncSliceInt64V(v []int64, e *Encoder) { e.arrayStart(len(v)) for j := range v { @@ -944,6 +977,7 @@ func (fastpathT) EncSliceInt64V(v []int64, e *Encoder) { } e.arrayEnd() } + func (fastpathT) EncAsMapSliceInt64V(v []int64, e *Encoder) { e.haltOnMbsOddLen(len(v)) e.mapStart(len(v) >> 1) // e.mapStart(len(v) / 2) @@ -957,6 +991,7 @@ func (fastpathT) EncAsMapSliceInt64V(v []int64, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncSliceBoolR(f *codecFnInfo, rv reflect.Value) { var v []bool if rv.Kind() == reflect.Array { @@ -970,6 +1005,7 @@ func (e *Encoder) fastpathEncSliceBoolR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncSliceBoolV(v, e) } } + func (fastpathT) EncSliceBoolV(v []bool, e *Encoder) { e.arrayStart(len(v)) for j := range v { @@ -978,6 +1014,7 @@ func (fastpathT) EncSliceBoolV(v []bool, e *Encoder) { } e.arrayEnd() } + func (fastpathT) EncAsMapSliceBoolV(v []bool, e *Encoder) { e.haltOnMbsOddLen(len(v)) e.mapStart(len(v) >> 1) // e.mapStart(len(v) / 2) @@ -991,9 +1028,11 @@ func (fastpathT) EncAsMapSliceBoolV(v []bool, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapStringIntfR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapStringIntfV(rv2i(rv).(map[string]interface{}), e) } + func (fastpathT) EncMapStringIntfV(v map[string]interface{}, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1020,9 +1059,11 @@ func (fastpathT) EncMapStringIntfV(v map[string]interface{}, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapStringStringR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapStringStringV(rv2i(rv).(map[string]string), e) } + func (fastpathT) EncMapStringStringV(v map[string]string, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1049,9 +1090,11 @@ func (fastpathT) EncMapStringStringV(v map[string]string, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapStringBytesR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapStringBytesV(rv2i(rv).(map[string][]byte), e) } + func (fastpathT) EncMapStringBytesV(v map[string][]byte, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1078,9 +1121,11 @@ func (fastpathT) EncMapStringBytesV(v map[string][]byte, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapStringUint8R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapStringUint8V(rv2i(rv).(map[string]uint8), e) } + func (fastpathT) EncMapStringUint8V(v map[string]uint8, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1107,9 +1152,11 @@ func (fastpathT) EncMapStringUint8V(v map[string]uint8, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapStringUint64R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapStringUint64V(rv2i(rv).(map[string]uint64), e) } + func (fastpathT) EncMapStringUint64V(v map[string]uint64, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1136,9 +1183,11 @@ func (fastpathT) EncMapStringUint64V(v map[string]uint64, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapStringIntR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapStringIntV(rv2i(rv).(map[string]int), e) } + func (fastpathT) EncMapStringIntV(v map[string]int, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1165,9 +1214,11 @@ func (fastpathT) EncMapStringIntV(v map[string]int, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapStringInt32R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapStringInt32V(rv2i(rv).(map[string]int32), e) } + func (fastpathT) EncMapStringInt32V(v map[string]int32, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1194,9 +1245,11 @@ func (fastpathT) EncMapStringInt32V(v map[string]int32, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapStringFloat64R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapStringFloat64V(rv2i(rv).(map[string]float64), e) } + func (fastpathT) EncMapStringFloat64V(v map[string]float64, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1223,9 +1276,11 @@ func (fastpathT) EncMapStringFloat64V(v map[string]float64, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapStringBoolR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapStringBoolV(rv2i(rv).(map[string]bool), e) } + func (fastpathT) EncMapStringBoolV(v map[string]bool, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1252,9 +1307,11 @@ func (fastpathT) EncMapStringBoolV(v map[string]bool, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapUint8IntfR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapUint8IntfV(rv2i(rv).(map[uint8]interface{}), e) } + func (fastpathT) EncMapUint8IntfV(v map[uint8]interface{}, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1281,9 +1338,11 @@ func (fastpathT) EncMapUint8IntfV(v map[uint8]interface{}, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapUint8StringR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapUint8StringV(rv2i(rv).(map[uint8]string), e) } + func (fastpathT) EncMapUint8StringV(v map[uint8]string, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1310,9 +1369,11 @@ func (fastpathT) EncMapUint8StringV(v map[uint8]string, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapUint8BytesR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapUint8BytesV(rv2i(rv).(map[uint8][]byte), e) } + func (fastpathT) EncMapUint8BytesV(v map[uint8][]byte, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1339,9 +1400,11 @@ func (fastpathT) EncMapUint8BytesV(v map[uint8][]byte, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapUint8Uint8R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapUint8Uint8V(rv2i(rv).(map[uint8]uint8), e) } + func (fastpathT) EncMapUint8Uint8V(v map[uint8]uint8, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1368,9 +1431,11 @@ func (fastpathT) EncMapUint8Uint8V(v map[uint8]uint8, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapUint8Uint64R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapUint8Uint64V(rv2i(rv).(map[uint8]uint64), e) } + func (fastpathT) EncMapUint8Uint64V(v map[uint8]uint64, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1397,9 +1462,11 @@ func (fastpathT) EncMapUint8Uint64V(v map[uint8]uint64, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapUint8IntR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapUint8IntV(rv2i(rv).(map[uint8]int), e) } + func (fastpathT) EncMapUint8IntV(v map[uint8]int, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1426,9 +1493,11 @@ func (fastpathT) EncMapUint8IntV(v map[uint8]int, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapUint8Int32R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapUint8Int32V(rv2i(rv).(map[uint8]int32), e) } + func (fastpathT) EncMapUint8Int32V(v map[uint8]int32, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1455,9 +1524,11 @@ func (fastpathT) EncMapUint8Int32V(v map[uint8]int32, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapUint8Float64R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapUint8Float64V(rv2i(rv).(map[uint8]float64), e) } + func (fastpathT) EncMapUint8Float64V(v map[uint8]float64, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1484,9 +1555,11 @@ func (fastpathT) EncMapUint8Float64V(v map[uint8]float64, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapUint8BoolR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapUint8BoolV(rv2i(rv).(map[uint8]bool), e) } + func (fastpathT) EncMapUint8BoolV(v map[uint8]bool, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1513,9 +1586,11 @@ func (fastpathT) EncMapUint8BoolV(v map[uint8]bool, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapUint64IntfR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapUint64IntfV(rv2i(rv).(map[uint64]interface{}), e) } + func (fastpathT) EncMapUint64IntfV(v map[uint64]interface{}, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1542,9 +1617,11 @@ func (fastpathT) EncMapUint64IntfV(v map[uint64]interface{}, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapUint64StringR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapUint64StringV(rv2i(rv).(map[uint64]string), e) } + func (fastpathT) EncMapUint64StringV(v map[uint64]string, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1571,9 +1648,11 @@ func (fastpathT) EncMapUint64StringV(v map[uint64]string, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapUint64BytesR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapUint64BytesV(rv2i(rv).(map[uint64][]byte), e) } + func (fastpathT) EncMapUint64BytesV(v map[uint64][]byte, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1600,9 +1679,11 @@ func (fastpathT) EncMapUint64BytesV(v map[uint64][]byte, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapUint64Uint8R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapUint64Uint8V(rv2i(rv).(map[uint64]uint8), e) } + func (fastpathT) EncMapUint64Uint8V(v map[uint64]uint8, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1629,9 +1710,11 @@ func (fastpathT) EncMapUint64Uint8V(v map[uint64]uint8, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapUint64Uint64R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapUint64Uint64V(rv2i(rv).(map[uint64]uint64), e) } + func (fastpathT) EncMapUint64Uint64V(v map[uint64]uint64, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1658,9 +1741,11 @@ func (fastpathT) EncMapUint64Uint64V(v map[uint64]uint64, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapUint64IntR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapUint64IntV(rv2i(rv).(map[uint64]int), e) } + func (fastpathT) EncMapUint64IntV(v map[uint64]int, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1687,9 +1772,11 @@ func (fastpathT) EncMapUint64IntV(v map[uint64]int, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapUint64Int32R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapUint64Int32V(rv2i(rv).(map[uint64]int32), e) } + func (fastpathT) EncMapUint64Int32V(v map[uint64]int32, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1716,9 +1803,11 @@ func (fastpathT) EncMapUint64Int32V(v map[uint64]int32, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapUint64Float64R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapUint64Float64V(rv2i(rv).(map[uint64]float64), e) } + func (fastpathT) EncMapUint64Float64V(v map[uint64]float64, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1745,9 +1834,11 @@ func (fastpathT) EncMapUint64Float64V(v map[uint64]float64, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapUint64BoolR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapUint64BoolV(rv2i(rv).(map[uint64]bool), e) } + func (fastpathT) EncMapUint64BoolV(v map[uint64]bool, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1774,9 +1865,11 @@ func (fastpathT) EncMapUint64BoolV(v map[uint64]bool, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapIntIntfR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapIntIntfV(rv2i(rv).(map[int]interface{}), e) } + func (fastpathT) EncMapIntIntfV(v map[int]interface{}, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1803,9 +1896,11 @@ func (fastpathT) EncMapIntIntfV(v map[int]interface{}, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapIntStringR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapIntStringV(rv2i(rv).(map[int]string), e) } + func (fastpathT) EncMapIntStringV(v map[int]string, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1832,9 +1927,11 @@ func (fastpathT) EncMapIntStringV(v map[int]string, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapIntBytesR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapIntBytesV(rv2i(rv).(map[int][]byte), e) } + func (fastpathT) EncMapIntBytesV(v map[int][]byte, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1861,9 +1958,11 @@ func (fastpathT) EncMapIntBytesV(v map[int][]byte, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapIntUint8R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapIntUint8V(rv2i(rv).(map[int]uint8), e) } + func (fastpathT) EncMapIntUint8V(v map[int]uint8, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1890,9 +1989,11 @@ func (fastpathT) EncMapIntUint8V(v map[int]uint8, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapIntUint64R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapIntUint64V(rv2i(rv).(map[int]uint64), e) } + func (fastpathT) EncMapIntUint64V(v map[int]uint64, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1919,9 +2020,11 @@ func (fastpathT) EncMapIntUint64V(v map[int]uint64, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapIntIntR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapIntIntV(rv2i(rv).(map[int]int), e) } + func (fastpathT) EncMapIntIntV(v map[int]int, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1948,9 +2051,11 @@ func (fastpathT) EncMapIntIntV(v map[int]int, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapIntInt32R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapIntInt32V(rv2i(rv).(map[int]int32), e) } + func (fastpathT) EncMapIntInt32V(v map[int]int32, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -1977,9 +2082,11 @@ func (fastpathT) EncMapIntInt32V(v map[int]int32, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapIntFloat64R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapIntFloat64V(rv2i(rv).(map[int]float64), e) } + func (fastpathT) EncMapIntFloat64V(v map[int]float64, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -2006,9 +2113,11 @@ func (fastpathT) EncMapIntFloat64V(v map[int]float64, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapIntBoolR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapIntBoolV(rv2i(rv).(map[int]bool), e) } + func (fastpathT) EncMapIntBoolV(v map[int]bool, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -2035,9 +2144,11 @@ func (fastpathT) EncMapIntBoolV(v map[int]bool, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapInt32IntfR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapInt32IntfV(rv2i(rv).(map[int32]interface{}), e) } + func (fastpathT) EncMapInt32IntfV(v map[int32]interface{}, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -2064,9 +2175,11 @@ func (fastpathT) EncMapInt32IntfV(v map[int32]interface{}, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapInt32StringR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapInt32StringV(rv2i(rv).(map[int32]string), e) } + func (fastpathT) EncMapInt32StringV(v map[int32]string, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -2093,9 +2206,11 @@ func (fastpathT) EncMapInt32StringV(v map[int32]string, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapInt32BytesR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapInt32BytesV(rv2i(rv).(map[int32][]byte), e) } + func (fastpathT) EncMapInt32BytesV(v map[int32][]byte, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -2122,9 +2237,11 @@ func (fastpathT) EncMapInt32BytesV(v map[int32][]byte, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapInt32Uint8R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapInt32Uint8V(rv2i(rv).(map[int32]uint8), e) } + func (fastpathT) EncMapInt32Uint8V(v map[int32]uint8, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -2151,9 +2268,11 @@ func (fastpathT) EncMapInt32Uint8V(v map[int32]uint8, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapInt32Uint64R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapInt32Uint64V(rv2i(rv).(map[int32]uint64), e) } + func (fastpathT) EncMapInt32Uint64V(v map[int32]uint64, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -2180,9 +2299,11 @@ func (fastpathT) EncMapInt32Uint64V(v map[int32]uint64, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapInt32IntR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapInt32IntV(rv2i(rv).(map[int32]int), e) } + func (fastpathT) EncMapInt32IntV(v map[int32]int, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -2209,9 +2330,11 @@ func (fastpathT) EncMapInt32IntV(v map[int32]int, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapInt32Int32R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapInt32Int32V(rv2i(rv).(map[int32]int32), e) } + func (fastpathT) EncMapInt32Int32V(v map[int32]int32, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -2238,9 +2361,11 @@ func (fastpathT) EncMapInt32Int32V(v map[int32]int32, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapInt32Float64R(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapInt32Float64V(rv2i(rv).(map[int32]float64), e) } + func (fastpathT) EncMapInt32Float64V(v map[int32]float64, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -2267,9 +2392,11 @@ func (fastpathT) EncMapInt32Float64V(v map[int32]float64, e *Encoder) { } e.mapEnd() } + func (e *Encoder) fastpathEncMapInt32BoolR(f *codecFnInfo, rv reflect.Value) { fastpathTV.EncMapInt32BoolV(rv2i(rv).(map[int32]bool), e) } + func (fastpathT) EncMapInt32BoolV(v map[int32]bool, e *Encoder) { e.mapStart(len(v)) if e.h.Canonical { @@ -2979,11 +3106,13 @@ func (d *Decoder) fastpathDecSliceIntfR(f *codecFnInfo, rv reflect.Value) { fastpathTV.DecSliceIntfN(rv2i(rv).([]interface{}), d) } } + func (f fastpathT) DecSliceIntfX(vp *[]interface{}, d *Decoder) { if v, changed := f.DecSliceIntfY(*vp, d); changed { *vp = v } } + func (fastpathT) DecSliceIntfY(v []interface{}, d *Decoder) (v2 []interface{}, changed bool) { slh, containerLenS := d.decSliceHelperStart() if slh.IsNil { @@ -3041,6 +3170,7 @@ func (fastpathT) DecSliceIntfY(v []interface{}, d *Decoder) (v2 []interface{}, c slh.End() return v, changed } + func (fastpathT) DecSliceIntfN(v []interface{}, d *Decoder) { slh, containerLenS := d.decSliceHelperStart() if slh.IsNil { @@ -3078,11 +3208,13 @@ func (d *Decoder) fastpathDecSliceStringR(f *codecFnInfo, rv reflect.Value) { fastpathTV.DecSliceStringN(rv2i(rv).([]string), d) } } + func (f fastpathT) DecSliceStringX(vp *[]string, d *Decoder) { if v, changed := f.DecSliceStringY(*vp, d); changed { *vp = v } } + func (fastpathT) DecSliceStringY(v []string, d *Decoder) (v2 []string, changed bool) { slh, containerLenS := d.decSliceHelperStart() if slh.IsNil { @@ -3140,6 +3272,7 @@ func (fastpathT) DecSliceStringY(v []string, d *Decoder) (v2 []string, changed b slh.End() return v, changed } + func (fastpathT) DecSliceStringN(v []string, d *Decoder) { slh, containerLenS := d.decSliceHelperStart() if slh.IsNil { @@ -3177,11 +3310,13 @@ func (d *Decoder) fastpathDecSliceBytesR(f *codecFnInfo, rv reflect.Value) { fastpathTV.DecSliceBytesN(rv2i(rv).([][]byte), d) } } + func (f fastpathT) DecSliceBytesX(vp *[][]byte, d *Decoder) { if v, changed := f.DecSliceBytesY(*vp, d); changed { *vp = v } } + func (fastpathT) DecSliceBytesY(v [][]byte, d *Decoder) (v2 [][]byte, changed bool) { slh, containerLenS := d.decSliceHelperStart() if slh.IsNil { @@ -3239,6 +3374,7 @@ func (fastpathT) DecSliceBytesY(v [][]byte, d *Decoder) (v2 [][]byte, changed bo slh.End() return v, changed } + func (fastpathT) DecSliceBytesN(v [][]byte, d *Decoder) { slh, containerLenS := d.decSliceHelperStart() if slh.IsNil { @@ -3276,11 +3412,13 @@ func (d *Decoder) fastpathDecSliceFloat32R(f *codecFnInfo, rv reflect.Value) { fastpathTV.DecSliceFloat32N(rv2i(rv).([]float32), d) } } + func (f fastpathT) DecSliceFloat32X(vp *[]float32, d *Decoder) { if v, changed := f.DecSliceFloat32Y(*vp, d); changed { *vp = v } } + func (fastpathT) DecSliceFloat32Y(v []float32, d *Decoder) (v2 []float32, changed bool) { slh, containerLenS := d.decSliceHelperStart() if slh.IsNil { @@ -3338,6 +3476,7 @@ func (fastpathT) DecSliceFloat32Y(v []float32, d *Decoder) (v2 []float32, change slh.End() return v, changed } + func (fastpathT) DecSliceFloat32N(v []float32, d *Decoder) { slh, containerLenS := d.decSliceHelperStart() if slh.IsNil { @@ -3375,11 +3514,13 @@ func (d *Decoder) fastpathDecSliceFloat64R(f *codecFnInfo, rv reflect.Value) { fastpathTV.DecSliceFloat64N(rv2i(rv).([]float64), d) } } + func (f fastpathT) DecSliceFloat64X(vp *[]float64, d *Decoder) { if v, changed := f.DecSliceFloat64Y(*vp, d); changed { *vp = v } } + func (fastpathT) DecSliceFloat64Y(v []float64, d *Decoder) (v2 []float64, changed bool) { slh, containerLenS := d.decSliceHelperStart() if slh.IsNil { @@ -3437,6 +3578,7 @@ func (fastpathT) DecSliceFloat64Y(v []float64, d *Decoder) (v2 []float64, change slh.End() return v, changed } + func (fastpathT) DecSliceFloat64N(v []float64, d *Decoder) { slh, containerLenS := d.decSliceHelperStart() if slh.IsNil { @@ -3474,11 +3616,13 @@ func (d *Decoder) fastpathDecSliceUint8R(f *codecFnInfo, rv reflect.Value) { fastpathTV.DecSliceUint8N(rv2i(rv).([]uint8), d) } } + func (f fastpathT) DecSliceUint8X(vp *[]uint8, d *Decoder) { if v, changed := f.DecSliceUint8Y(*vp, d); changed { *vp = v } } + func (fastpathT) DecSliceUint8Y(v []uint8, d *Decoder) (v2 []uint8, changed bool) { switch d.d.ContainerType() { case valueTypeNil, valueTypeMap: @@ -3544,6 +3688,7 @@ func (fastpathT) DecSliceUint8Y(v []uint8, d *Decoder) (v2 []uint8, changed bool slh.End() return v, changed } + func (fastpathT) DecSliceUint8N(v []uint8, d *Decoder) { switch d.d.ContainerType() { case valueTypeNil, valueTypeMap: @@ -3591,11 +3736,13 @@ func (d *Decoder) fastpathDecSliceUint64R(f *codecFnInfo, rv reflect.Value) { fastpathTV.DecSliceUint64N(rv2i(rv).([]uint64), d) } } + func (f fastpathT) DecSliceUint64X(vp *[]uint64, d *Decoder) { if v, changed := f.DecSliceUint64Y(*vp, d); changed { *vp = v } } + func (fastpathT) DecSliceUint64Y(v []uint64, d *Decoder) (v2 []uint64, changed bool) { slh, containerLenS := d.decSliceHelperStart() if slh.IsNil { @@ -3653,6 +3800,7 @@ func (fastpathT) DecSliceUint64Y(v []uint64, d *Decoder) (v2 []uint64, changed b slh.End() return v, changed } + func (fastpathT) DecSliceUint64N(v []uint64, d *Decoder) { slh, containerLenS := d.decSliceHelperStart() if slh.IsNil { @@ -3690,11 +3838,13 @@ func (d *Decoder) fastpathDecSliceIntR(f *codecFnInfo, rv reflect.Value) { fastpathTV.DecSliceIntN(rv2i(rv).([]int), d) } } + func (f fastpathT) DecSliceIntX(vp *[]int, d *Decoder) { if v, changed := f.DecSliceIntY(*vp, d); changed { *vp = v } } + func (fastpathT) DecSliceIntY(v []int, d *Decoder) (v2 []int, changed bool) { slh, containerLenS := d.decSliceHelperStart() if slh.IsNil { @@ -3752,6 +3902,7 @@ func (fastpathT) DecSliceIntY(v []int, d *Decoder) (v2 []int, changed bool) { slh.End() return v, changed } + func (fastpathT) DecSliceIntN(v []int, d *Decoder) { slh, containerLenS := d.decSliceHelperStart() if slh.IsNil { @@ -3789,11 +3940,13 @@ func (d *Decoder) fastpathDecSliceInt32R(f *codecFnInfo, rv reflect.Value) { fastpathTV.DecSliceInt32N(rv2i(rv).([]int32), d) } } + func (f fastpathT) DecSliceInt32X(vp *[]int32, d *Decoder) { if v, changed := f.DecSliceInt32Y(*vp, d); changed { *vp = v } } + func (fastpathT) DecSliceInt32Y(v []int32, d *Decoder) (v2 []int32, changed bool) { slh, containerLenS := d.decSliceHelperStart() if slh.IsNil { @@ -3851,6 +4004,7 @@ func (fastpathT) DecSliceInt32Y(v []int32, d *Decoder) (v2 []int32, changed bool slh.End() return v, changed } + func (fastpathT) DecSliceInt32N(v []int32, d *Decoder) { slh, containerLenS := d.decSliceHelperStart() if slh.IsNil { @@ -3888,11 +4042,13 @@ func (d *Decoder) fastpathDecSliceInt64R(f *codecFnInfo, rv reflect.Value) { fastpathTV.DecSliceInt64N(rv2i(rv).([]int64), d) } } + func (f fastpathT) DecSliceInt64X(vp *[]int64, d *Decoder) { if v, changed := f.DecSliceInt64Y(*vp, d); changed { *vp = v } } + func (fastpathT) DecSliceInt64Y(v []int64, d *Decoder) (v2 []int64, changed bool) { slh, containerLenS := d.decSliceHelperStart() if slh.IsNil { @@ -3950,6 +4106,7 @@ func (fastpathT) DecSliceInt64Y(v []int64, d *Decoder) (v2 []int64, changed bool slh.End() return v, changed } + func (fastpathT) DecSliceInt64N(v []int64, d *Decoder) { slh, containerLenS := d.decSliceHelperStart() if slh.IsNil { @@ -3987,11 +4144,13 @@ func (d *Decoder) fastpathDecSliceBoolR(f *codecFnInfo, rv reflect.Value) { fastpathTV.DecSliceBoolN(rv2i(rv).([]bool), d) } } + func (f fastpathT) DecSliceBoolX(vp *[]bool, d *Decoder) { if v, changed := f.DecSliceBoolY(*vp, d); changed { *vp = v } } + func (fastpathT) DecSliceBoolY(v []bool, d *Decoder) (v2 []bool, changed bool) { slh, containerLenS := d.decSliceHelperStart() if slh.IsNil { @@ -4049,6 +4208,7 @@ func (fastpathT) DecSliceBoolY(v []bool, d *Decoder) (v2 []bool, changed bool) { slh.End() return v, changed } + func (fastpathT) DecSliceBoolN(v []bool, d *Decoder) { slh, containerLenS := d.decSliceHelperStart() if slh.IsNil { @@ -4069,6 +4229,7 @@ func (fastpathT) DecSliceBoolN(v []bool, d *Decoder) { } slh.End() } + func (d *Decoder) fastpathDecMapStringIntfR(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -4084,6 +4245,7 @@ func (d *Decoder) fastpathDecMapStringIntfR(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapStringIntfX(vp *map[string]interface{}, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -4098,6 +4260,7 @@ func (f fastpathT) DecMapStringIntfX(vp *map[string]interface{}, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapStringIntfL(v map[string]interface{}, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[string]interface{} given stream length: %v", containerLen) @@ -4120,6 +4283,7 @@ func (fastpathT) DecMapStringIntfL(v map[string]interface{}, containerLen int, d v[mk] = mv } } + func (d *Decoder) fastpathDecMapStringStringR(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -4135,6 +4299,7 @@ func (d *Decoder) fastpathDecMapStringStringR(f *codecFnInfo, rv reflect.Value) } d.mapEnd() } + func (f fastpathT) DecMapStringStringX(vp *map[string]string, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -4149,6 +4314,7 @@ func (f fastpathT) DecMapStringStringX(vp *map[string]string, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapStringStringL(v map[string]string, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[string]string given stream length: %v", containerLen) @@ -4165,6 +4331,7 @@ func (fastpathT) DecMapStringStringL(v map[string]string, containerLen int, d *D v[mk] = mv } } + func (d *Decoder) fastpathDecMapStringBytesR(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -4180,6 +4347,7 @@ func (d *Decoder) fastpathDecMapStringBytesR(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapStringBytesX(vp *map[string][]byte, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -4194,6 +4362,7 @@ func (f fastpathT) DecMapStringBytesX(vp *map[string][]byte, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapStringBytesL(v map[string][]byte, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[string][]byte given stream length: %v", containerLen) @@ -4216,6 +4385,7 @@ func (fastpathT) DecMapStringBytesL(v map[string][]byte, containerLen int, d *De v[mk] = mv } } + func (d *Decoder) fastpathDecMapStringUint8R(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -4231,6 +4401,7 @@ func (d *Decoder) fastpathDecMapStringUint8R(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapStringUint8X(vp *map[string]uint8, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -4245,6 +4416,7 @@ func (f fastpathT) DecMapStringUint8X(vp *map[string]uint8, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapStringUint8L(v map[string]uint8, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[string]uint8 given stream length: %v", containerLen) @@ -4261,6 +4433,7 @@ func (fastpathT) DecMapStringUint8L(v map[string]uint8, containerLen int, d *Dec v[mk] = mv } } + func (d *Decoder) fastpathDecMapStringUint64R(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -4276,6 +4449,7 @@ func (d *Decoder) fastpathDecMapStringUint64R(f *codecFnInfo, rv reflect.Value) } d.mapEnd() } + func (f fastpathT) DecMapStringUint64X(vp *map[string]uint64, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -4290,6 +4464,7 @@ func (f fastpathT) DecMapStringUint64X(vp *map[string]uint64, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapStringUint64L(v map[string]uint64, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[string]uint64 given stream length: %v", containerLen) @@ -4306,6 +4481,7 @@ func (fastpathT) DecMapStringUint64L(v map[string]uint64, containerLen int, d *D v[mk] = mv } } + func (d *Decoder) fastpathDecMapStringIntR(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -4321,6 +4497,7 @@ func (d *Decoder) fastpathDecMapStringIntR(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapStringIntX(vp *map[string]int, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -4335,6 +4512,7 @@ func (f fastpathT) DecMapStringIntX(vp *map[string]int, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapStringIntL(v map[string]int, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[string]int given stream length: %v", containerLen) @@ -4351,6 +4529,7 @@ func (fastpathT) DecMapStringIntL(v map[string]int, containerLen int, d *Decoder v[mk] = mv } } + func (d *Decoder) fastpathDecMapStringInt32R(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -4366,6 +4545,7 @@ func (d *Decoder) fastpathDecMapStringInt32R(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapStringInt32X(vp *map[string]int32, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -4380,6 +4560,7 @@ func (f fastpathT) DecMapStringInt32X(vp *map[string]int32, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapStringInt32L(v map[string]int32, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[string]int32 given stream length: %v", containerLen) @@ -4396,6 +4577,7 @@ func (fastpathT) DecMapStringInt32L(v map[string]int32, containerLen int, d *Dec v[mk] = mv } } + func (d *Decoder) fastpathDecMapStringFloat64R(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -4411,6 +4593,7 @@ func (d *Decoder) fastpathDecMapStringFloat64R(f *codecFnInfo, rv reflect.Value) } d.mapEnd() } + func (f fastpathT) DecMapStringFloat64X(vp *map[string]float64, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -4425,6 +4608,7 @@ func (f fastpathT) DecMapStringFloat64X(vp *map[string]float64, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapStringFloat64L(v map[string]float64, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[string]float64 given stream length: %v", containerLen) @@ -4441,6 +4625,7 @@ func (fastpathT) DecMapStringFloat64L(v map[string]float64, containerLen int, d v[mk] = mv } } + func (d *Decoder) fastpathDecMapStringBoolR(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -4456,6 +4641,7 @@ func (d *Decoder) fastpathDecMapStringBoolR(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapStringBoolX(vp *map[string]bool, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -4470,6 +4656,7 @@ func (f fastpathT) DecMapStringBoolX(vp *map[string]bool, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapStringBoolL(v map[string]bool, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[string]bool given stream length: %v", containerLen) @@ -4486,6 +4673,7 @@ func (fastpathT) DecMapStringBoolL(v map[string]bool, containerLen int, d *Decod v[mk] = mv } } + func (d *Decoder) fastpathDecMapUint8IntfR(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -4501,6 +4689,7 @@ func (d *Decoder) fastpathDecMapUint8IntfR(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapUint8IntfX(vp *map[uint8]interface{}, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -4515,6 +4704,7 @@ func (f fastpathT) DecMapUint8IntfX(vp *map[uint8]interface{}, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapUint8IntfL(v map[uint8]interface{}, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[uint8]interface{} given stream length: %v", containerLen) @@ -4537,6 +4727,7 @@ func (fastpathT) DecMapUint8IntfL(v map[uint8]interface{}, containerLen int, d * v[mk] = mv } } + func (d *Decoder) fastpathDecMapUint8StringR(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -4552,6 +4743,7 @@ func (d *Decoder) fastpathDecMapUint8StringR(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapUint8StringX(vp *map[uint8]string, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -4566,6 +4758,7 @@ func (f fastpathT) DecMapUint8StringX(vp *map[uint8]string, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapUint8StringL(v map[uint8]string, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[uint8]string given stream length: %v", containerLen) @@ -4582,6 +4775,7 @@ func (fastpathT) DecMapUint8StringL(v map[uint8]string, containerLen int, d *Dec v[mk] = mv } } + func (d *Decoder) fastpathDecMapUint8BytesR(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -4597,6 +4791,7 @@ func (d *Decoder) fastpathDecMapUint8BytesR(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapUint8BytesX(vp *map[uint8][]byte, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -4611,6 +4806,7 @@ func (f fastpathT) DecMapUint8BytesX(vp *map[uint8][]byte, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapUint8BytesL(v map[uint8][]byte, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[uint8][]byte given stream length: %v", containerLen) @@ -4633,6 +4829,7 @@ func (fastpathT) DecMapUint8BytesL(v map[uint8][]byte, containerLen int, d *Deco v[mk] = mv } } + func (d *Decoder) fastpathDecMapUint8Uint8R(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -4648,6 +4845,7 @@ func (d *Decoder) fastpathDecMapUint8Uint8R(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapUint8Uint8X(vp *map[uint8]uint8, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -4662,6 +4860,7 @@ func (f fastpathT) DecMapUint8Uint8X(vp *map[uint8]uint8, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapUint8Uint8L(v map[uint8]uint8, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[uint8]uint8 given stream length: %v", containerLen) @@ -4678,6 +4877,7 @@ func (fastpathT) DecMapUint8Uint8L(v map[uint8]uint8, containerLen int, d *Decod v[mk] = mv } } + func (d *Decoder) fastpathDecMapUint8Uint64R(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -4693,6 +4893,7 @@ func (d *Decoder) fastpathDecMapUint8Uint64R(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapUint8Uint64X(vp *map[uint8]uint64, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -4707,6 +4908,7 @@ func (f fastpathT) DecMapUint8Uint64X(vp *map[uint8]uint64, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapUint8Uint64L(v map[uint8]uint64, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[uint8]uint64 given stream length: %v", containerLen) @@ -4723,6 +4925,7 @@ func (fastpathT) DecMapUint8Uint64L(v map[uint8]uint64, containerLen int, d *Dec v[mk] = mv } } + func (d *Decoder) fastpathDecMapUint8IntR(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -4738,6 +4941,7 @@ func (d *Decoder) fastpathDecMapUint8IntR(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapUint8IntX(vp *map[uint8]int, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -4752,6 +4956,7 @@ func (f fastpathT) DecMapUint8IntX(vp *map[uint8]int, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapUint8IntL(v map[uint8]int, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[uint8]int given stream length: %v", containerLen) @@ -4768,6 +4973,7 @@ func (fastpathT) DecMapUint8IntL(v map[uint8]int, containerLen int, d *Decoder) v[mk] = mv } } + func (d *Decoder) fastpathDecMapUint8Int32R(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -4783,6 +4989,7 @@ func (d *Decoder) fastpathDecMapUint8Int32R(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapUint8Int32X(vp *map[uint8]int32, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -4797,6 +5004,7 @@ func (f fastpathT) DecMapUint8Int32X(vp *map[uint8]int32, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapUint8Int32L(v map[uint8]int32, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[uint8]int32 given stream length: %v", containerLen) @@ -4813,6 +5021,7 @@ func (fastpathT) DecMapUint8Int32L(v map[uint8]int32, containerLen int, d *Decod v[mk] = mv } } + func (d *Decoder) fastpathDecMapUint8Float64R(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -4828,6 +5037,7 @@ func (d *Decoder) fastpathDecMapUint8Float64R(f *codecFnInfo, rv reflect.Value) } d.mapEnd() } + func (f fastpathT) DecMapUint8Float64X(vp *map[uint8]float64, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -4842,6 +5052,7 @@ func (f fastpathT) DecMapUint8Float64X(vp *map[uint8]float64, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapUint8Float64L(v map[uint8]float64, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[uint8]float64 given stream length: %v", containerLen) @@ -4858,6 +5069,7 @@ func (fastpathT) DecMapUint8Float64L(v map[uint8]float64, containerLen int, d *D v[mk] = mv } } + func (d *Decoder) fastpathDecMapUint8BoolR(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -4873,6 +5085,7 @@ func (d *Decoder) fastpathDecMapUint8BoolR(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapUint8BoolX(vp *map[uint8]bool, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -4887,6 +5100,7 @@ func (f fastpathT) DecMapUint8BoolX(vp *map[uint8]bool, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapUint8BoolL(v map[uint8]bool, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[uint8]bool given stream length: %v", containerLen) @@ -4903,6 +5117,7 @@ func (fastpathT) DecMapUint8BoolL(v map[uint8]bool, containerLen int, d *Decoder v[mk] = mv } } + func (d *Decoder) fastpathDecMapUint64IntfR(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -4918,6 +5133,7 @@ func (d *Decoder) fastpathDecMapUint64IntfR(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapUint64IntfX(vp *map[uint64]interface{}, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -4932,6 +5148,7 @@ func (f fastpathT) DecMapUint64IntfX(vp *map[uint64]interface{}, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapUint64IntfL(v map[uint64]interface{}, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[uint64]interface{} given stream length: %v", containerLen) @@ -4954,6 +5171,7 @@ func (fastpathT) DecMapUint64IntfL(v map[uint64]interface{}, containerLen int, d v[mk] = mv } } + func (d *Decoder) fastpathDecMapUint64StringR(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -4969,6 +5187,7 @@ func (d *Decoder) fastpathDecMapUint64StringR(f *codecFnInfo, rv reflect.Value) } d.mapEnd() } + func (f fastpathT) DecMapUint64StringX(vp *map[uint64]string, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -4983,6 +5202,7 @@ func (f fastpathT) DecMapUint64StringX(vp *map[uint64]string, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapUint64StringL(v map[uint64]string, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[uint64]string given stream length: %v", containerLen) @@ -4999,6 +5219,7 @@ func (fastpathT) DecMapUint64StringL(v map[uint64]string, containerLen int, d *D v[mk] = mv } } + func (d *Decoder) fastpathDecMapUint64BytesR(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -5014,6 +5235,7 @@ func (d *Decoder) fastpathDecMapUint64BytesR(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapUint64BytesX(vp *map[uint64][]byte, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -5028,6 +5250,7 @@ func (f fastpathT) DecMapUint64BytesX(vp *map[uint64][]byte, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapUint64BytesL(v map[uint64][]byte, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[uint64][]byte given stream length: %v", containerLen) @@ -5050,6 +5273,7 @@ func (fastpathT) DecMapUint64BytesL(v map[uint64][]byte, containerLen int, d *De v[mk] = mv } } + func (d *Decoder) fastpathDecMapUint64Uint8R(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -5065,6 +5289,7 @@ func (d *Decoder) fastpathDecMapUint64Uint8R(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapUint64Uint8X(vp *map[uint64]uint8, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -5079,6 +5304,7 @@ func (f fastpathT) DecMapUint64Uint8X(vp *map[uint64]uint8, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapUint64Uint8L(v map[uint64]uint8, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[uint64]uint8 given stream length: %v", containerLen) @@ -5095,6 +5321,7 @@ func (fastpathT) DecMapUint64Uint8L(v map[uint64]uint8, containerLen int, d *Dec v[mk] = mv } } + func (d *Decoder) fastpathDecMapUint64Uint64R(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -5110,6 +5337,7 @@ func (d *Decoder) fastpathDecMapUint64Uint64R(f *codecFnInfo, rv reflect.Value) } d.mapEnd() } + func (f fastpathT) DecMapUint64Uint64X(vp *map[uint64]uint64, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -5124,6 +5352,7 @@ func (f fastpathT) DecMapUint64Uint64X(vp *map[uint64]uint64, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapUint64Uint64L(v map[uint64]uint64, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[uint64]uint64 given stream length: %v", containerLen) @@ -5140,6 +5369,7 @@ func (fastpathT) DecMapUint64Uint64L(v map[uint64]uint64, containerLen int, d *D v[mk] = mv } } + func (d *Decoder) fastpathDecMapUint64IntR(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -5155,6 +5385,7 @@ func (d *Decoder) fastpathDecMapUint64IntR(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapUint64IntX(vp *map[uint64]int, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -5169,6 +5400,7 @@ func (f fastpathT) DecMapUint64IntX(vp *map[uint64]int, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapUint64IntL(v map[uint64]int, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[uint64]int given stream length: %v", containerLen) @@ -5185,6 +5417,7 @@ func (fastpathT) DecMapUint64IntL(v map[uint64]int, containerLen int, d *Decoder v[mk] = mv } } + func (d *Decoder) fastpathDecMapUint64Int32R(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -5200,6 +5433,7 @@ func (d *Decoder) fastpathDecMapUint64Int32R(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapUint64Int32X(vp *map[uint64]int32, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -5214,6 +5448,7 @@ func (f fastpathT) DecMapUint64Int32X(vp *map[uint64]int32, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapUint64Int32L(v map[uint64]int32, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[uint64]int32 given stream length: %v", containerLen) @@ -5230,6 +5465,7 @@ func (fastpathT) DecMapUint64Int32L(v map[uint64]int32, containerLen int, d *Dec v[mk] = mv } } + func (d *Decoder) fastpathDecMapUint64Float64R(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -5245,6 +5481,7 @@ func (d *Decoder) fastpathDecMapUint64Float64R(f *codecFnInfo, rv reflect.Value) } d.mapEnd() } + func (f fastpathT) DecMapUint64Float64X(vp *map[uint64]float64, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -5259,6 +5496,7 @@ func (f fastpathT) DecMapUint64Float64X(vp *map[uint64]float64, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapUint64Float64L(v map[uint64]float64, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[uint64]float64 given stream length: %v", containerLen) @@ -5275,6 +5513,7 @@ func (fastpathT) DecMapUint64Float64L(v map[uint64]float64, containerLen int, d v[mk] = mv } } + func (d *Decoder) fastpathDecMapUint64BoolR(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -5290,6 +5529,7 @@ func (d *Decoder) fastpathDecMapUint64BoolR(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapUint64BoolX(vp *map[uint64]bool, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -5304,6 +5544,7 @@ func (f fastpathT) DecMapUint64BoolX(vp *map[uint64]bool, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapUint64BoolL(v map[uint64]bool, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[uint64]bool given stream length: %v", containerLen) @@ -5320,6 +5561,7 @@ func (fastpathT) DecMapUint64BoolL(v map[uint64]bool, containerLen int, d *Decod v[mk] = mv } } + func (d *Decoder) fastpathDecMapIntIntfR(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -5335,6 +5577,7 @@ func (d *Decoder) fastpathDecMapIntIntfR(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapIntIntfX(vp *map[int]interface{}, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -5349,6 +5592,7 @@ func (f fastpathT) DecMapIntIntfX(vp *map[int]interface{}, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapIntIntfL(v map[int]interface{}, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[int]interface{} given stream length: %v", containerLen) @@ -5371,6 +5615,7 @@ func (fastpathT) DecMapIntIntfL(v map[int]interface{}, containerLen int, d *Deco v[mk] = mv } } + func (d *Decoder) fastpathDecMapIntStringR(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -5386,6 +5631,7 @@ func (d *Decoder) fastpathDecMapIntStringR(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapIntStringX(vp *map[int]string, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -5400,6 +5646,7 @@ func (f fastpathT) DecMapIntStringX(vp *map[int]string, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapIntStringL(v map[int]string, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[int]string given stream length: %v", containerLen) @@ -5416,6 +5663,7 @@ func (fastpathT) DecMapIntStringL(v map[int]string, containerLen int, d *Decoder v[mk] = mv } } + func (d *Decoder) fastpathDecMapIntBytesR(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -5431,6 +5679,7 @@ func (d *Decoder) fastpathDecMapIntBytesR(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapIntBytesX(vp *map[int][]byte, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -5445,6 +5694,7 @@ func (f fastpathT) DecMapIntBytesX(vp *map[int][]byte, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapIntBytesL(v map[int][]byte, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[int][]byte given stream length: %v", containerLen) @@ -5467,6 +5717,7 @@ func (fastpathT) DecMapIntBytesL(v map[int][]byte, containerLen int, d *Decoder) v[mk] = mv } } + func (d *Decoder) fastpathDecMapIntUint8R(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -5482,6 +5733,7 @@ func (d *Decoder) fastpathDecMapIntUint8R(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapIntUint8X(vp *map[int]uint8, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -5496,6 +5748,7 @@ func (f fastpathT) DecMapIntUint8X(vp *map[int]uint8, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapIntUint8L(v map[int]uint8, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[int]uint8 given stream length: %v", containerLen) @@ -5512,6 +5765,7 @@ func (fastpathT) DecMapIntUint8L(v map[int]uint8, containerLen int, d *Decoder) v[mk] = mv } } + func (d *Decoder) fastpathDecMapIntUint64R(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -5527,6 +5781,7 @@ func (d *Decoder) fastpathDecMapIntUint64R(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapIntUint64X(vp *map[int]uint64, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -5541,6 +5796,7 @@ func (f fastpathT) DecMapIntUint64X(vp *map[int]uint64, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapIntUint64L(v map[int]uint64, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[int]uint64 given stream length: %v", containerLen) @@ -5557,6 +5813,7 @@ func (fastpathT) DecMapIntUint64L(v map[int]uint64, containerLen int, d *Decoder v[mk] = mv } } + func (d *Decoder) fastpathDecMapIntIntR(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -5572,6 +5829,7 @@ func (d *Decoder) fastpathDecMapIntIntR(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapIntIntX(vp *map[int]int, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -5586,6 +5844,7 @@ func (f fastpathT) DecMapIntIntX(vp *map[int]int, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapIntIntL(v map[int]int, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[int]int given stream length: %v", containerLen) @@ -5602,6 +5861,7 @@ func (fastpathT) DecMapIntIntL(v map[int]int, containerLen int, d *Decoder) { v[mk] = mv } } + func (d *Decoder) fastpathDecMapIntInt32R(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -5617,6 +5877,7 @@ func (d *Decoder) fastpathDecMapIntInt32R(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapIntInt32X(vp *map[int]int32, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -5631,6 +5892,7 @@ func (f fastpathT) DecMapIntInt32X(vp *map[int]int32, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapIntInt32L(v map[int]int32, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[int]int32 given stream length: %v", containerLen) @@ -5647,6 +5909,7 @@ func (fastpathT) DecMapIntInt32L(v map[int]int32, containerLen int, d *Decoder) v[mk] = mv } } + func (d *Decoder) fastpathDecMapIntFloat64R(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -5662,6 +5925,7 @@ func (d *Decoder) fastpathDecMapIntFloat64R(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapIntFloat64X(vp *map[int]float64, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -5676,6 +5940,7 @@ func (f fastpathT) DecMapIntFloat64X(vp *map[int]float64, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapIntFloat64L(v map[int]float64, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[int]float64 given stream length: %v", containerLen) @@ -5692,6 +5957,7 @@ func (fastpathT) DecMapIntFloat64L(v map[int]float64, containerLen int, d *Decod v[mk] = mv } } + func (d *Decoder) fastpathDecMapIntBoolR(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -5707,6 +5973,7 @@ func (d *Decoder) fastpathDecMapIntBoolR(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapIntBoolX(vp *map[int]bool, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -5721,6 +5988,7 @@ func (f fastpathT) DecMapIntBoolX(vp *map[int]bool, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapIntBoolL(v map[int]bool, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[int]bool given stream length: %v", containerLen) @@ -5737,6 +6005,7 @@ func (fastpathT) DecMapIntBoolL(v map[int]bool, containerLen int, d *Decoder) { v[mk] = mv } } + func (d *Decoder) fastpathDecMapInt32IntfR(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -5752,6 +6021,7 @@ func (d *Decoder) fastpathDecMapInt32IntfR(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapInt32IntfX(vp *map[int32]interface{}, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -5766,6 +6036,7 @@ func (f fastpathT) DecMapInt32IntfX(vp *map[int32]interface{}, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapInt32IntfL(v map[int32]interface{}, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[int32]interface{} given stream length: %v", containerLen) @@ -5788,6 +6059,7 @@ func (fastpathT) DecMapInt32IntfL(v map[int32]interface{}, containerLen int, d * v[mk] = mv } } + func (d *Decoder) fastpathDecMapInt32StringR(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -5803,6 +6075,7 @@ func (d *Decoder) fastpathDecMapInt32StringR(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapInt32StringX(vp *map[int32]string, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -5817,6 +6090,7 @@ func (f fastpathT) DecMapInt32StringX(vp *map[int32]string, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapInt32StringL(v map[int32]string, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[int32]string given stream length: %v", containerLen) @@ -5833,6 +6107,7 @@ func (fastpathT) DecMapInt32StringL(v map[int32]string, containerLen int, d *Dec v[mk] = mv } } + func (d *Decoder) fastpathDecMapInt32BytesR(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -5848,6 +6123,7 @@ func (d *Decoder) fastpathDecMapInt32BytesR(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapInt32BytesX(vp *map[int32][]byte, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -5862,6 +6138,7 @@ func (f fastpathT) DecMapInt32BytesX(vp *map[int32][]byte, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapInt32BytesL(v map[int32][]byte, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[int32][]byte given stream length: %v", containerLen) @@ -5884,6 +6161,7 @@ func (fastpathT) DecMapInt32BytesL(v map[int32][]byte, containerLen int, d *Deco v[mk] = mv } } + func (d *Decoder) fastpathDecMapInt32Uint8R(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -5899,6 +6177,7 @@ func (d *Decoder) fastpathDecMapInt32Uint8R(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapInt32Uint8X(vp *map[int32]uint8, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -5913,6 +6192,7 @@ func (f fastpathT) DecMapInt32Uint8X(vp *map[int32]uint8, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapInt32Uint8L(v map[int32]uint8, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[int32]uint8 given stream length: %v", containerLen) @@ -5929,6 +6209,7 @@ func (fastpathT) DecMapInt32Uint8L(v map[int32]uint8, containerLen int, d *Decod v[mk] = mv } } + func (d *Decoder) fastpathDecMapInt32Uint64R(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -5944,6 +6225,7 @@ func (d *Decoder) fastpathDecMapInt32Uint64R(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapInt32Uint64X(vp *map[int32]uint64, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -5958,6 +6240,7 @@ func (f fastpathT) DecMapInt32Uint64X(vp *map[int32]uint64, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapInt32Uint64L(v map[int32]uint64, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[int32]uint64 given stream length: %v", containerLen) @@ -5974,6 +6257,7 @@ func (fastpathT) DecMapInt32Uint64L(v map[int32]uint64, containerLen int, d *Dec v[mk] = mv } } + func (d *Decoder) fastpathDecMapInt32IntR(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -5989,6 +6273,7 @@ func (d *Decoder) fastpathDecMapInt32IntR(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapInt32IntX(vp *map[int32]int, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -6003,6 +6288,7 @@ func (f fastpathT) DecMapInt32IntX(vp *map[int32]int, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapInt32IntL(v map[int32]int, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[int32]int given stream length: %v", containerLen) @@ -6019,6 +6305,7 @@ func (fastpathT) DecMapInt32IntL(v map[int32]int, containerLen int, d *Decoder) v[mk] = mv } } + func (d *Decoder) fastpathDecMapInt32Int32R(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -6034,6 +6321,7 @@ func (d *Decoder) fastpathDecMapInt32Int32R(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapInt32Int32X(vp *map[int32]int32, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -6048,6 +6336,7 @@ func (f fastpathT) DecMapInt32Int32X(vp *map[int32]int32, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapInt32Int32L(v map[int32]int32, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[int32]int32 given stream length: %v", containerLen) @@ -6064,6 +6353,7 @@ func (fastpathT) DecMapInt32Int32L(v map[int32]int32, containerLen int, d *Decod v[mk] = mv } } + func (d *Decoder) fastpathDecMapInt32Float64R(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -6079,6 +6369,7 @@ func (d *Decoder) fastpathDecMapInt32Float64R(f *codecFnInfo, rv reflect.Value) } d.mapEnd() } + func (f fastpathT) DecMapInt32Float64X(vp *map[int32]float64, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -6093,6 +6384,7 @@ func (f fastpathT) DecMapInt32Float64X(vp *map[int32]float64, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapInt32Float64L(v map[int32]float64, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[int32]float64 given stream length: %v", containerLen) @@ -6109,6 +6401,7 @@ func (fastpathT) DecMapInt32Float64L(v map[int32]float64, containerLen int, d *D v[mk] = mv } } + func (d *Decoder) fastpathDecMapInt32BoolR(f *codecFnInfo, rv reflect.Value) { containerLen := d.mapStart(d.d.ReadMapStart()) if rv.Kind() == reflect.Ptr { @@ -6124,6 +6417,7 @@ func (d *Decoder) fastpathDecMapInt32BoolR(f *codecFnInfo, rv reflect.Value) { } d.mapEnd() } + func (f fastpathT) DecMapInt32BoolX(vp *map[int32]bool, d *Decoder) { containerLen := d.mapStart(d.d.ReadMapStart()) if containerLen == containerLenNil { @@ -6138,6 +6432,7 @@ func (f fastpathT) DecMapInt32BoolX(vp *map[int32]bool, d *Decoder) { d.mapEnd() } } + func (fastpathT) DecMapInt32BoolL(v map[int32]bool, containerLen int, d *Decoder) { if v == nil { d.errorf("cannot decode into nil map[int32]bool given stream length: %v", containerLen) diff --git a/vendor/github.com/ugorji/go/codec/fast-path.not.go b/vendor/github.com/ugorji/go/codec/fast-path.not.go index 259485d3..dc7e31ef 100644 --- a/vendor/github.com/ugorji/go/codec/fast-path.not.go +++ b/vendor/github.com/ugorji/go/codec/fast-path.not.go @@ -25,19 +25,23 @@ func fastpathEncodeTypeSwitch(iv interface{}, e *Encoder) bool { return false } func fastpathDecodeSetZeroTypeSwitch(iv interface{}) bool { return false } -type fastpathT struct{} -type fastpathE struct { - rtid uintptr - rt reflect.Type - encfn func(*Encoder, *codecFnInfo, reflect.Value) - decfn func(*Decoder, *codecFnInfo, reflect.Value) -} +type ( + fastpathT struct{} + fastpathE struct { + rtid uintptr + rt reflect.Type + encfn func(*Encoder, *codecFnInfo, reflect.Value) + decfn func(*Decoder, *codecFnInfo, reflect.Value) + } +) type fastpathA [0]fastpathE func fastpathAvIndex(rtid uintptr) int { return -1 } -var fastpathAv fastpathA -var fastpathTV fastpathT +var ( + fastpathAv fastpathA + fastpathTV fastpathT +) // ---- type TestMammoth2Wrapper struct{} // to allow testMammoth work in notfastpath mode diff --git a/vendor/github.com/ugorji/go/codec/gen.go b/vendor/github.com/ugorji/go/codec/gen.go index 5c5f925f..4e7dfd79 100644 --- a/vendor/github.com/ugorji/go/codec/gen.go +++ b/vendor/github.com/ugorji/go/codec/gen.go @@ -175,12 +175,16 @@ const ( genDecStructArrayInlineLoopCheck = true ) -type genStructMapStyle uint8 -type genStringDecAsBytes string -type genStringDecZC string +type ( + genStructMapStyle uint8 + genStringDecAsBytes string + genStringDecZC string +) -var genStringDecAsBytesTyp = reflect.TypeOf(genStringDecAsBytes("")) -var genStringDecZCTyp = reflect.TypeOf(genStringDecZC("")) +var ( + genStringDecAsBytesTyp = reflect.TypeOf(genStringDecAsBytes("")) + genStringDecZCTyp = reflect.TypeOf(genStringDecZC("")) +) const ( genStructMapStyleConsolidated genStructMapStyle = iota @@ -757,7 +761,6 @@ func (x *genRunner) selfer(encode bool) { x.decStructArray(genTopLevelVarName, "l", "return", rt2id(t0), t0) x.line("}") x.line("") - } // used for chan, array, slice, map @@ -1119,7 +1122,7 @@ func (x *genRunner) encOmitEmptyLine(t2 reflect.StructField, varname string, buf buf.s(" || ") x.encOmitEmptyLine(f, varname2, buf) } - //buf.s(")") + // buf.s(")") case reflect.Bool: buf.s("bool(").s(varname2).s(")") case reflect.Map, reflect.Slice, reflect.Array, reflect.Chan: @@ -1379,7 +1382,7 @@ func (x *genRunner) encMapFallback(varname string, t reflect.Type) { func (x *genRunner) decVarInitPtr(varname, nilvar string, t reflect.Type, si *structFieldInfo, newbuf, nilbuf *genBuf) (varname3 string, t2 reflect.StructField) { - //we must accommodate anonymous fields, where the embedded field is a nil pointer in the value. + // we must accommodate anonymous fields, where the embedded field is a nil pointer in the value. // t2 = t.FieldByIndex(si.is) varname3 = varname t2typ := t @@ -1477,7 +1480,6 @@ func (x *genRunner) decVarMain(varname, rand string, t reflect.Type, checkNotNil // decVar takes a variable called varname, of type t func (x *genRunner) decVar(varname, nilvar string, t reflect.Type, canBeNil, checkNotNil bool) { - // We only encode as nil if a nillable value. // This removes some of the wasted checks for TryDecodeAsNil. // We need to think about this more, to see what happens if omitempty, etc @@ -2174,12 +2176,14 @@ func genInternalZeroValue(s string) string { } } -var genInternalNonZeroValueIdx [6]uint64 -var genInternalNonZeroValueStrs = [...][6]string{ - {`"string-is-an-interface-1"`, "true", `"some-string-1"`, `[]byte("some-string-1")`, "11.1", "111"}, - {`"string-is-an-interface-2"`, "false", `"some-string-2"`, `[]byte("some-string-2")`, "22.2", "77"}, - {`"string-is-an-interface-3"`, "true", `"some-string-3"`, `[]byte("some-string-3")`, "33.3e3", "127"}, -} +var ( + genInternalNonZeroValueIdx [6]uint64 + genInternalNonZeroValueStrs = [...][6]string{ + {`"string-is-an-interface-1"`, "true", `"some-string-1"`, `[]byte("some-string-1")`, "11.1", "111"}, + {`"string-is-an-interface-2"`, "false", `"some-string-2"`, `[]byte("some-string-2")`, "22.2", "77"}, + {`"string-is-an-interface-3"`, "true", `"some-string-3"`, `[]byte("some-string-3")`, "33.3e3", "127"}, + } +) // Note: last numbers must be in range: 0-127 (as they may be put into a int8, uint8, etc) @@ -2330,9 +2334,11 @@ func genStripVendor(s string) string { } // var genInternalMu sync.Mutex -var genInternalV = genInternal{Version: genVersion} -var genInternalTmplFuncs template.FuncMap -var genInternalOnce sync.Once +var ( + genInternalV = genInternal{Version: genVersion} + genInternalTmplFuncs template.FuncMap + genInternalOnce sync.Once +) func genInternalInit() { wordSizeBytes := int(intBitsize) / 8 @@ -2362,7 +2368,7 @@ func genInternalInit() { // keep as slice, so it is in specific iteration order. // Initial order was uint64, string, interface{}, int, int64, ... - var types = [...]string{ + types := [...]string{ "interface{}", "string", "[]byte", @@ -2409,7 +2415,7 @@ func genInternalInit() { // } // var mapkeytypestr = string(mb) - var gt = genInternal{Version: genVersion} + gt := genInternal{Version: genVersion} // For each slice or map type, there must be a (symmetrical) Encode and Decode fast-path function diff --git a/vendor/github.com/ugorji/go/codec/helper.go b/vendor/github.com/ugorji/go/codec/helper.go index 4a886c7f..2c0df0a5 100644 --- a/vendor/github.com/ugorji/go/codec/helper.go +++ b/vendor/github.com/ugorji/go/codec/helper.go @@ -530,6 +530,7 @@ func (x *typeInfoLoad) reset() { type jsonMarshaler interface { MarshalJSON() ([]byte, error) } + type jsonUnmarshaler interface { UnmarshalJSON([]byte) error } @@ -849,7 +850,7 @@ func (x *BasicHandle) initHandle(hh Handle) { x.mu.Lock() defer x.mu.Unlock() // use defer, as halt may panic below if x.inited == 0 { - var f = initedHandleFlag + f := initedHandleFlag if hh.isBinary() { f |= binaryHandleFlag } @@ -886,7 +887,7 @@ func findRtidFn(s []codecRtidFn, rtid uintptr) (i uint, fn *codecFn) { // h, i, j := 0, 0, len(s) var h uint // var h, i uint - var j = uint(len(s)) + j := uint(len(s)) LOOP: if i < j { h = (i + j) >> 1 // avoid overflow when computing h // h = i + (j-i)/2 @@ -990,7 +991,7 @@ func (x *BasicHandle) fnLoad(rt reflect.Type, rtid uintptr, checkExt bool) (fn * } else if supportMarshalInterfaces && !x.isBe() && x.isJs() && (ti.flagJsonMarshaler || ti.flagJsonMarshalerPtr) && (ti.flagJsonUnmarshaler || ti.flagJsonUnmarshalerPtr) { - //If JSON, we should check JSONMarshal before textMarshal + // If JSON, we should check JSONMarshal before textMarshal fn.fe = (*Encoder).jsonMarshal fn.fd = (*Decoder).jsonUnmarshal fi.addrD = ti.flagJsonUnmarshalerPtr @@ -1298,6 +1299,7 @@ func (bytesExtFailer) WriteExt(v interface{}) []byte { halt.onerror(errExtFnWriteExtUnsupported) return nil } + func (bytesExtFailer) ReadExt(v interface{}, bs []byte) { halt.onerror(errExtFnReadExtUnsupported) } @@ -1308,6 +1310,7 @@ func (interfaceExtFailer) ConvertExt(v interface{}) interface{} { halt.onerror(errExtFnConvertExtUnsupported) return nil } + func (interfaceExtFailer) UpdateExt(dest interface{}, v interface{}) { halt.onerror(errExtFnUpdateExtUnsupported) } @@ -1881,7 +1884,7 @@ func findTypeInfo(s []rtid2ti, rtid uintptr) (i uint, ti *typeInfo) { // Note: we use goto (instead of for loop) so this can be inlined. var h uint - var j = uint(len(s)) + j := uint(len(s)) LOOP: if i < j { h = (i + j) >> 1 // avoid overflow when computing h // h = i + (j-i)/2 @@ -2335,12 +2338,14 @@ func (checkOverflow) Float32(v float64) (overflow bool) { } return math.MaxFloat32 < v && v <= math.MaxFloat64 } + func (checkOverflow) Uint(v uint64, bitsize uint8) (overflow bool) { if v != 0 && v != (v<<(64-bitsize))>>(64-bitsize) { overflow = true } return } + func (checkOverflow) Int(v int64, bitsize uint8) (overflow bool) { if v != 0 && v != (v<<(64-bitsize))>>(64-bitsize) { overflow = true @@ -2353,7 +2358,7 @@ func (checkOverflow) Uint2Int(v uint64, neg bool) (overflow bool) { } func (checkOverflow) SignedInt(v uint64) (overflow bool) { - //e.g. -127 to 128 for int8 + // e.g. -127 to 128 for int8 pos := (v >> 63) == 0 ui2 := v & 0x7fffffffffffffff if pos { @@ -2374,18 +2379,21 @@ func (x checkOverflow) Float32V(v float64) float64 { } return v } + func (x checkOverflow) UintV(v uint64, bitsize uint8) uint64 { if x.Uint(v, bitsize) { halt.errorf("uint64 overflow: %v", v) } return v } + func (x checkOverflow) IntV(v int64, bitsize uint8) int64 { if x.Int(v, bitsize) { halt.errorf("int64 overflow: %v", v) } return v } + func (x checkOverflow) SignedIntV(v uint64) int64 { if x.SignedInt(v) { halt.errorf("uint64 to int64 overflow: %v", v) @@ -2470,6 +2478,7 @@ func (x *bitset32) set(pos byte) *bitset32 { x[pos&31] = true // x[pos%32] = true return x } + func (x *bitset32) isset(pos byte) bool { return x[pos&31] // x[pos%32] } @@ -2490,6 +2499,7 @@ func (x *bitset256) set(pos byte) *bitset256 { x[pos] = true return x } + func (x *bitset256) isset(pos byte) bool { return x[pos] } @@ -2574,14 +2584,17 @@ func (mustHdl) String(s string, err error) string { halt.onerror(err) return s } + func (mustHdl) Int(s int64, err error) int64 { halt.onerror(err) return s } + func (mustHdl) Uint(s uint64, err error) uint64 { halt.onerror(err) return s } + func (mustHdl) Float(s float64, err error) float64 { halt.onerror(err) return s @@ -2713,7 +2726,7 @@ func (x *bytesFreelist) checkPutGet(v []byte, length int) []byte { // assume cap(v) < length, so put must happen before get y := *x - var put = cap(v) == 0 // if empty, consider it already put + put := cap(v) == 0 // if empty, consider it already put if !put { y = append(y, v) } diff --git a/vendor/github.com/ugorji/go/codec/helper_not_unsafe.go b/vendor/github.com/ugorji/go/codec/helper_not_unsafe.go index d1d8aa3e..d1843315 100644 --- a/vendor/github.com/ugorji/go/codec/helper_not_unsafe.go +++ b/vendor/github.com/ugorji/go/codec/helper_not_unsafe.go @@ -246,21 +246,27 @@ func (x *atomicRtidFnSlice) store(p []codecRtidFn) { func (n *fauxUnion) ru() reflect.Value { return reflect.ValueOf(&n.u).Elem() } + func (n *fauxUnion) ri() reflect.Value { return reflect.ValueOf(&n.i).Elem() } + func (n *fauxUnion) rf() reflect.Value { return reflect.ValueOf(&n.f).Elem() } + func (n *fauxUnion) rl() reflect.Value { return reflect.ValueOf(&n.l).Elem() } + func (n *fauxUnion) rs() reflect.Value { return reflect.ValueOf(&n.s).Elem() } + func (n *fauxUnion) rt() reflect.Value { return reflect.ValueOf(&n.t).Elem() } + func (n *fauxUnion) rb() reflect.Value { return reflect.ValueOf(&n.b).Elem() } diff --git a/vendor/github.com/ugorji/go/codec/helper_unsafe.go b/vendor/github.com/ugorji/go/codec/helper_unsafe.go index 2efb690a..c4a79a63 100644 --- a/vendor/github.com/ugorji/go/codec/helper_unsafe.go +++ b/vendor/github.com/ugorji/go/codec/helper_unsafe.go @@ -142,7 +142,7 @@ func byteSliceSameData(v1 []byte, v2 []byte) bool { // This applies to references like map/ptr/unsafepointer/chan/func, // and non-reference values like interface/slice. func isNil(v interface{}) (rv reflect.Value, isnil bool) { - var ui = (*unsafeIntf)(unsafe.Pointer(&v)) + ui := (*unsafeIntf)(unsafe.Pointer(&v)) if ui.ptr == nil { isnil = true return @@ -364,8 +364,8 @@ func i2rtid(i interface{}) uintptr { // -------------------------- func unsafeCmpZero(ptr unsafe.Pointer, size int) bool { - var s1 = unsafeString{ptr, size} - var s2 = unsafeString{unsafeZeroAddr, size} + s1 := unsafeString{ptr, size} + s2 := unsafeString{unsafeZeroAddr, size} if size > len(unsafeZeroArr) { arr := make([]byte, size) s2.Data = unsafe.Pointer(&arr[0]) @@ -394,7 +394,6 @@ func isEmptyValue(v reflect.Value, tinfos *TypeInfos, recursive bool) bool { // return unsafeCmpZero(urv.ptr, int(rtsize(rvType(v)))) return unsafeCmpZero(urv.ptr, int(rtsize2(urv.typ))) - } func isEmptyValueFallbackRecur(urv *unsafeReflectValue, v reflect.Value, tinfos *TypeInfos) bool { @@ -569,31 +568,37 @@ func (n *fauxUnion) ru() (v reflect.Value) { ((*unsafeReflectValue)(unsafe.Pointer(&v))).ptr = unsafe.Pointer(&n.u) return } + func (n *fauxUnion) ri() (v reflect.Value) { v = defUnsafeDecNakedWrapper.ri ((*unsafeReflectValue)(unsafe.Pointer(&v))).ptr = unsafe.Pointer(&n.i) return } + func (n *fauxUnion) rf() (v reflect.Value) { v = defUnsafeDecNakedWrapper.rf ((*unsafeReflectValue)(unsafe.Pointer(&v))).ptr = unsafe.Pointer(&n.f) return } + func (n *fauxUnion) rl() (v reflect.Value) { v = defUnsafeDecNakedWrapper.rl ((*unsafeReflectValue)(unsafe.Pointer(&v))).ptr = unsafe.Pointer(&n.l) return } + func (n *fauxUnion) rs() (v reflect.Value) { v = defUnsafeDecNakedWrapper.rs ((*unsafeReflectValue)(unsafe.Pointer(&v))).ptr = unsafe.Pointer(&n.s) return } + func (n *fauxUnion) rt() (v reflect.Value) { v = defUnsafeDecNakedWrapper.rt ((*unsafeReflectValue)(unsafe.Pointer(&v))).ptr = unsafe.Pointer(&n.t) return } + func (n *fauxUnion) rb() (v reflect.Value) { v = defUnsafeDecNakedWrapper.rb ((*unsafeReflectValue)(unsafe.Pointer(&v))).ptr = unsafe.Pointer(&n.b) @@ -1115,8 +1120,8 @@ func unsafeMapKVPtr(urv *unsafeReflectValue) unsafe.Pointer { } func mapGet(m, k, v reflect.Value, keyFastKind mapKeyFastKind, valIsIndirect, valIsRef bool) (_ reflect.Value) { - var urv = (*unsafeReflectValue)(unsafe.Pointer(&k)) - var kptr = unsafeMapKVPtr(urv) + urv := (*unsafeReflectValue)(unsafe.Pointer(&k)) + kptr := unsafeMapKVPtr(urv) urv = (*unsafeReflectValue)(unsafe.Pointer(&m)) mptr := rvRefPtr(urv) @@ -1155,11 +1160,11 @@ func mapGet(m, k, v reflect.Value, keyFastKind mapKeyFastKind, valIsIndirect, va } func mapSet(m, k, v reflect.Value, keyFastKind mapKeyFastKind, valIsIndirect, valIsRef bool) { - var urv = (*unsafeReflectValue)(unsafe.Pointer(&k)) - var kptr = unsafeMapKVPtr(urv) + urv := (*unsafeReflectValue)(unsafe.Pointer(&k)) + kptr := unsafeMapKVPtr(urv) urv = (*unsafeReflectValue)(unsafe.Pointer(&v)) - var vtyp = urv.typ - var vptr = unsafeMapKVPtr(urv) + vtyp := urv.typ + vptr := unsafeMapKVPtr(urv) urv = (*unsafeReflectValue)(unsafe.Pointer(&m)) mptr := rvRefPtr(urv) @@ -1282,6 +1287,7 @@ func len_map(m unsafe.Pointer) int { // return maplen(m) return len_map_chan(m) } + func len_chan(m unsafe.Pointer) int { // return chanlen(m) return len_map_chan(m) diff --git a/vendor/github.com/ugorji/go/codec/json.go b/vendor/github.com/ugorji/go/codec/json.go index 629a416d..b1371966 100644 --- a/vendor/github.com/ugorji/go/codec/json.go +++ b/vendor/github.com/ugorji/go/codec/json.go @@ -343,10 +343,10 @@ func (e *jsonEncDriver) encodeUint(neg bool, quotes bool, u uint64) { "80818283848586878889" + "90919293949596979899" - // typically, 19 or 20 bytes sufficient for decimal encoding a uint64 - // var a [24]byte - var a = e.b[0:24] - var i = uint8(len(a)) + // typically, 19 or 20 bytes sufficient for decimal encoding a uint64 + // var a [24]byte + a := e.b[0:24] + i := uint8(len(a)) if quotes { i-- @@ -354,7 +354,7 @@ func (e *jsonEncDriver) encodeUint(neg bool, quotes bool, u uint64) { } // u guaranteed to fit into a uint (as we are not 32bit OS) var is uint - var us = uint(u) + us := uint(u) for us >= 100 { is = us % 100 * 2 us /= 100 @@ -728,7 +728,7 @@ func (d *jsonDecDriver) advance() { func (d *jsonDecDriver) nextValueBytes(v0 []byte) (v []byte) { v = v0 - var h = decNextValueBytesHelper{d: &d.d} + h := decNextValueBytesHelper{d: &d.d} v, cursor := d.nextValueBytesR(v) h.bytesRdV(&v, cursor) return @@ -736,7 +736,7 @@ func (d *jsonDecDriver) nextValueBytes(v0 []byte) (v []byte) { func (d *jsonDecDriver) nextValueBytesR(v0 []byte) (v []byte, cursor uint) { v = v0 - var h = decNextValueBytesHelper{d: &d.d} + h := decNextValueBytesHelper{d: &d.d} dr := &d.d.decRd consumeString := func() { @@ -1378,7 +1378,7 @@ func (h *JsonHandle) typical() bool { } func (h *JsonHandle) newEncDriver() encDriver { - var e = &jsonEncDriver{h: h} + e := &jsonEncDriver{h: h} // var x []byte // e.buf = &x e.e.e = e @@ -1389,7 +1389,7 @@ func (h *JsonHandle) newEncDriver() encDriver { } func (h *JsonHandle) newDecDriver() decDriver { - var d = &jsonDecDriver{h: h} + d := &jsonDecDriver{h: h} var x []byte d.buf = &x d.d.d = d @@ -1465,8 +1465,10 @@ func jsonFloatStrconvFmtPrec32(f float32) (fmt byte, prec int8) { return } -var _ decDriverContainerTracker = (*jsonDecDriver)(nil) -var _ encDriverContainerTracker = (*jsonEncDriver)(nil) -var _ decDriver = (*jsonDecDriver)(nil) +var ( + _ decDriverContainerTracker = (*jsonDecDriver)(nil) + _ encDriverContainerTracker = (*jsonEncDriver)(nil) + _ decDriver = (*jsonDecDriver)(nil) +) var _ encDriver = (*jsonEncDriver)(nil) diff --git a/vendor/github.com/ugorji/go/codec/msgpack.go b/vendor/github.com/ugorji/go/codec/msgpack.go index 75477bb5..47c5f5e1 100644 --- a/vendor/github.com/ugorji/go/codec/msgpack.go +++ b/vendor/github.com/ugorji/go/codec/msgpack.go @@ -76,8 +76,10 @@ const ( mpNegFixNumMax byte = 0xff ) -var mpTimeExtTag int8 = -1 -var mpTimeExtTagU = uint8(mpTimeExtTag) +var ( + mpTimeExtTag int8 = -1 + mpTimeExtTagU = uint8(mpTimeExtTag) +) var mpdescNames = map[byte]string{ mpNil: "nil", @@ -263,7 +265,7 @@ func (e *msgpackEncDriver) EncodeTime(t time.Time) { t = t.UTC() sec, nsec := t.Unix(), uint64(t.Nanosecond()) var data64 uint64 - var l = 4 + l := 4 if sec >= 0 && sec>>34 == 0 { data64 = (nsec << 34) | uint64(sec) if data64&0xffffffff00000000 != 0 { @@ -532,8 +534,8 @@ func (d *msgpackDecDriver) nextValueBytes(v0 []byte) (v []byte) { d.readNextBd() } v = v0 - var h = decNextValueBytesHelper{d: &d.d} - var cursor = d.d.rb.c - 1 + h := decNextValueBytesHelper{d: &d.d} + cursor := d.d.rb.c - 1 h.append1(&v, d.bd) v = d.nextValueBytesBdReadR(v) d.bdRead = false @@ -544,14 +546,14 @@ func (d *msgpackDecDriver) nextValueBytes(v0 []byte) (v []byte) { func (d *msgpackDecDriver) nextValueBytesR(v0 []byte) (v []byte) { d.readNextBd() v = v0 - var h = decNextValueBytesHelper{d: &d.d} + h := decNextValueBytesHelper{d: &d.d} h.append1(&v, d.bd) return d.nextValueBytesBdReadR(v) } func (d *msgpackDecDriver) nextValueBytesBdReadR(v0 []byte) (v []byte) { v = v0 - var h = decNextValueBytesHelper{d: &d.d} + h := decNextValueBytesHelper{d: &d.d} bd := d.bd @@ -1030,7 +1032,7 @@ func (d *msgpackDecDriver) decodeExtV(verifyTag bool, tag byte) (xbs []byte, xta //-------------------------------------------------- -//MsgpackHandle is a Handle for the Msgpack Schema-Free Encoding Format. +// MsgpackHandle is a Handle for the Msgpack Schema-Free Encoding Format. type MsgpackHandle struct { binaryEncodingType BasicHandle @@ -1062,7 +1064,7 @@ func (h *MsgpackHandle) Name() string { return "msgpack" } func (h *MsgpackHandle) desc(bd byte) string { return mpdesc(bd) } func (h *MsgpackHandle) newEncDriver() encDriver { - var e = &msgpackEncDriver{h: h} + e := &msgpackEncDriver{h: h} e.e.e = e e.e.init(h) e.reset() @@ -1141,7 +1143,7 @@ func (c *msgpackSpecRpcCodec) parseCustomHeader(expectTypeByte byte, msgid *uint // We read the response header by hand // so that the body can be decoded on its own from the stream at a later time. - const fia byte = 0x94 //four item array descriptor value + const fia byte = 0x94 // four item array descriptor value var ba [1]byte var n int @@ -1155,7 +1157,7 @@ func (c *msgpackSpecRpcCodec) parseCustomHeader(expectTypeByte byte, msgid *uint } } - var b = ba[0] + b := ba[0] if b != fia { err = fmt.Errorf("not array - %s %x/%s", msgBadDesc, b, mpdesc(b)) } else { @@ -1194,5 +1196,7 @@ func (x msgpackSpecRpc) ClientCodec(conn io.ReadWriteCloser, h Handle) rpc.Clien return &msgpackSpecRpcCodec{newRPCCodec(conn, h)} } -var _ decDriver = (*msgpackDecDriver)(nil) -var _ encDriver = (*msgpackEncDriver)(nil) +var ( + _ decDriver = (*msgpackDecDriver)(nil) + _ encDriver = (*msgpackEncDriver)(nil) +) diff --git a/vendor/github.com/ugorji/go/codec/reader.go b/vendor/github.com/ugorji/go/codec/reader.go index d8e623ad..070ba853 100644 --- a/vendor/github.com/ugorji/go/codec/reader.go +++ b/vendor/github.com/ugorji/go/codec/reader.go @@ -316,7 +316,7 @@ func (z *bufioDecReader) reset(r io.Reader, bufsize int, blist *bytesFreelist) { } func (z *bufioDecReader) readb(p []byte) { - var n = uint(copy(p, z.buf[z.c:])) + n := uint(copy(p, z.buf[z.c:])) z.n += n z.c += n if len(p) != int(n) { @@ -782,6 +782,7 @@ func (z *decRd) readn1() (v uint8) { } return } + func (z *decRd) readn1IO() uint8 { if z.bufio { return z.bi.readn1() diff --git a/vendor/github.com/ugorji/go/codec/rpc.go b/vendor/github.com/ugorji/go/codec/rpc.go index e5dd1d2d..900117f1 100644 --- a/vendor/github.com/ugorji/go/codec/rpc.go +++ b/vendor/github.com/ugorji/go/codec/rpc.go @@ -104,7 +104,7 @@ func (c *rpcCodec) write(obj1, obj2 interface{}, writeObj2 bool) (err error) { func (c *rpcCodec) read(obj interface{}) (err error) { err = c.ready() if err == nil { - //If nil is passed in, we should read and discard + // If nil is passed in, we should read and discard if obj == nil { // return c.dec.Decode(&obj) err = c.dec.swallowErr() diff --git a/vendor/github.com/ugorji/go/codec/simple.go b/vendor/github.com/ugorji/go/codec/simple.go index a08b553f..1d1113dc 100644 --- a/vendor/github.com/ugorji/go/codec/simple.go +++ b/vendor/github.com/ugorji/go/codec/simple.go @@ -593,8 +593,8 @@ func (d *simpleDecDriver) nextValueBytes(v0 []byte) (v []byte) { d.readNextBd() } v = v0 - var h = decNextValueBytesHelper{d: &d.d} - var cursor = d.d.rb.c - 1 + h := decNextValueBytesHelper{d: &d.d} + cursor := d.d.rb.c - 1 h.append1(&v, d.bd) v = d.nextValueBytesBdReadR(v) d.bdRead = false @@ -605,14 +605,14 @@ func (d *simpleDecDriver) nextValueBytes(v0 []byte) (v []byte) { func (d *simpleDecDriver) nextValueBytesR(v0 []byte) (v []byte) { d.readNextBd() v = v0 - var h = decNextValueBytesHelper{d: &d.d} + h := decNextValueBytesHelper{d: &d.d} h.append1(&v, d.bd) return d.nextValueBytesBdReadR(v) } func (d *simpleDecDriver) nextValueBytesBdReadR(v0 []byte) (v []byte) { v = v0 - var h = decNextValueBytesHelper{d: &d.d} + h := decNextValueBytesHelper{d: &d.d} c := d.bd @@ -724,7 +724,7 @@ func (h *SimpleHandle) Name() string { return "simple" } func (h *SimpleHandle) desc(bd byte) string { return simpledesc(bd) } func (h *SimpleHandle) newEncDriver() encDriver { - var e = &simpleEncDriver{h: h} + e := &simpleEncDriver{h: h} e.e.e = e e.e.init(h) e.reset() @@ -746,5 +746,7 @@ func (d *simpleDecDriver) reset() { d.bd, d.bdRead = 0, false } -var _ decDriver = (*simpleDecDriver)(nil) -var _ encDriver = (*simpleEncDriver)(nil) +var ( + _ decDriver = (*simpleDecDriver)(nil) + _ encDriver = (*simpleEncDriver)(nil) +) diff --git a/vendor/github.com/ugorji/go/codec/sort-slice.generated.go b/vendor/github.com/ugorji/go/codec/sort-slice.generated.go index 92441ebf..8cabcb1c 100644 --- a/vendor/github.com/ugorji/go/codec/sort-slice.generated.go +++ b/vendor/github.com/ugorji/go/codec/sort-slice.generated.go @@ -5,9 +5,11 @@ package codec -import "time" -import "reflect" -import "bytes" +import ( + "time" + "reflect" + "bytes" +) type stringSlice []string diff --git a/vendor/github.com/ugorji/go/codec/writer.go b/vendor/github.com/ugorji/go/codec/writer.go index 5774ae02..68d40251 100644 --- a/vendor/github.com/ugorji/go/codec/writer.go +++ b/vendor/github.com/ugorji/go/codec/writer.go @@ -128,6 +128,7 @@ func (z *bufioEncWriter) writen1(b1 byte) { z.buf[z.n] = b1 z.n++ } + func (z *bufioEncWriter) writen2(b1, b2 byte) { if 2 > len(z.buf)-z.n { z.flush() @@ -136,6 +137,7 @@ func (z *bufioEncWriter) writen2(b1, b2 byte) { z.buf[z.n] = b1 z.n += 2 } + func (z *bufioEncWriter) writen4(b [4]byte) { if 4 > len(z.buf)-z.n { z.flush() @@ -170,31 +172,39 @@ type bytesEncAppender struct { func (z *bytesEncAppender) writeb(s []byte) { z.b = append(z.b, s...) } + func (z *bytesEncAppender) writestr(s string) { z.b = append(z.b, s...) } + func (z *bytesEncAppender) writeqstr(s string) { z.b = append(append(append(z.b, '"'), s...), '"') // z.b = append(z.b, '"') // z.b = append(z.b, s...) // z.b = append(z.b, '"') } + func (z *bytesEncAppender) writen1(b1 byte) { z.b = append(z.b, b1) } + func (z *bytesEncAppender) writen2(b1, b2 byte) { z.b = append(z.b, b1, b2) } + func (z *bytesEncAppender) writen4(b [4]byte) { z.b = append(z.b, b[:]...) } + func (z *bytesEncAppender) writen8(b [8]byte) { z.b = append(z.b, b[:]...) } + func (z *bytesEncAppender) endErr() error { *(z.out) = z.b return nil } + func (z *bytesEncAppender) reset(in []byte, out *[]byte) { z.b = in[:0] z.out = out @@ -227,6 +237,7 @@ func (z *encWr) writeb(s []byte) { z.wf.writeb(s) } } + func (z *encWr) writeqstr(s string) { if z.bytes { // MARKER: z.wb.writeqstr(s) @@ -235,6 +246,7 @@ func (z *encWr) writeqstr(s string) { z.wf.writeqstr(s) } } + func (z *encWr) writestr(s string) { if z.bytes { z.wb.writestr(s) @@ -242,6 +254,7 @@ func (z *encWr) writestr(s string) { z.wf.writestr(s) } } + func (z *encWr) writen1(b1 byte) { if z.bytes { z.wb.writen1(b1) @@ -258,6 +271,7 @@ func (z *encWr) writen2(b1, b2 byte) { z.wf.writen2(b1, b2) } } + func (z *encWr) writen4(b [4]byte) { if z.bytes { z.wb.writen4(b) @@ -265,6 +279,7 @@ func (z *encWr) writen4(b [4]byte) { z.wf.writen4(b) } } + func (z *encWr) writen8(b [8]byte) { if z.bytes { z.wb.writen8(b) diff --git a/vendor/go.uber.org/zap/sink.go b/vendor/go.uber.org/zap/sink.go index df46fa87..30078cb6 100644 --- a/vendor/go.uber.org/zap/sink.go +++ b/vendor/go.uber.org/zap/sink.go @@ -136,7 +136,7 @@ func newFileSink(u *url.URL) (Sink, error) { case "stderr": return nopCloserSink{os.Stderr}, nil } - return os.OpenFile(u.Path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666) + return os.OpenFile(u.Path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o666) } func normalizeScheme(s string) (string, error) { diff --git a/vendor/go.uber.org/zap/stacktrace.go b/vendor/go.uber.org/zap/stacktrace.go index 0cf8c1dd..7c67bf66 100644 --- a/vendor/go.uber.org/zap/stacktrace.go +++ b/vendor/go.uber.org/zap/stacktrace.go @@ -27,13 +27,11 @@ import ( "go.uber.org/zap/internal/bufferpool" ) -var ( - _stacktracePool = sync.Pool{ - New: func() interface{} { - return newProgramCounters(64) - }, - } -) +var _stacktracePool = sync.Pool{ + New: func() interface{} { + return newProgramCounters(64) + }, +} func takeStacktrace(skip int) string { buffer := bufferpool.Get() diff --git a/vendor/go.uber.org/zap/zapcore/entry.go b/vendor/go.uber.org/zap/zapcore/entry.go index 4aa8b4f9..d8138034 100644 --- a/vendor/go.uber.org/zap/zapcore/entry.go +++ b/vendor/go.uber.org/zap/zapcore/entry.go @@ -33,14 +33,12 @@ import ( "go.uber.org/multierr" ) -var ( - _cePool = sync.Pool{New: func() interface{} { - // Pre-allocate some space for cores. - return &CheckedEntry{ - cores: make([]Core, 4), - } - }} -) +var _cePool = sync.Pool{New: func() interface{} { + // Pre-allocate some space for cores. + return &CheckedEntry{ + cores: make([]Core, 4), + } +}} func getCheckedEntry() *CheckedEntry { ce := _cePool.Get().(*CheckedEntry) diff --git a/vendor/golang.org/x/crypto/acme/autocert/cache.go b/vendor/golang.org/x/crypto/acme/autocert/cache.go index 03f63022..a52bee84 100644 --- a/vendor/golang.org/x/crypto/acme/autocert/cache.go +++ b/vendor/golang.org/x/crypto/acme/autocert/cache.go @@ -65,7 +65,7 @@ func (d DirCache) Get(ctx context.Context, name string) ([]byte, error) { // Put writes the certificate data to the specified file name. // The file will be created with 0600 permissions. func (d DirCache) Put(ctx context.Context, name string, data []byte) error { - if err := os.MkdirAll(string(d), 0700); err != nil { + if err := os.MkdirAll(string(d), 0o700); err != nil { return err } diff --git a/vendor/golang.org/x/crypto/acme/autocert/listener.go b/vendor/golang.org/x/crypto/acme/autocert/listener.go index cb486097..8031a676 100644 --- a/vendor/golang.org/x/crypto/acme/autocert/listener.go +++ b/vendor/golang.org/x/crypto/acme/autocert/listener.go @@ -50,7 +50,7 @@ func NewListener(domains ...string) net.Listener { m.HostPolicy = HostWhitelist(domains...) } dir := cacheDir() - if err := os.MkdirAll(dir, 0700); err != nil { + if err := os.MkdirAll(dir, 0o700); err != nil { log.Printf("warning: autocert.NewListener not using a cache: %v", err) } else { m.Cache = DirCache(dir) diff --git a/vendor/golang.org/x/crypto/ssh/certs.go b/vendor/golang.org/x/crypto/ssh/certs.go index 916c840b..faf5536f 100644 --- a/vendor/golang.org/x/crypto/ssh/certs.go +++ b/vendor/golang.org/x/crypto/ssh/certs.go @@ -240,7 +240,8 @@ func NewCertSigner(cert *Certificate, signer Signer) (Signer, error) { if algorithmSigner, ok := signer.(AlgorithmSigner); ok { return &algorithmOpenSSHCertSigner{ - &openSSHCertSigner{cert, signer}, algorithmSigner}, nil + &openSSHCertSigner{cert, signer}, algorithmSigner, + }, nil } else { return &openSSHCertSigner{cert, signer}, nil } diff --git a/vendor/golang.org/x/crypto/ssh/channel.go b/vendor/golang.org/x/crypto/ssh/channel.go index c0834c00..91ad5333 100644 --- a/vendor/golang.org/x/crypto/ssh/channel.go +++ b/vendor/golang.org/x/crypto/ssh/channel.go @@ -472,8 +472,10 @@ func (m *mux) newChannel(chanType string, direction channelDirection, extraData return ch } -var errUndecided = errors.New("ssh: must Accept or Reject channel") -var errDecidedAlready = errors.New("ssh: can call Accept or Reject only once") +var ( + errUndecided = errors.New("ssh: must Accept or Reject channel") + errDecidedAlready = errors.New("ssh: can call Accept or Reject only once") +) type extChannel struct { code uint32 @@ -541,7 +543,8 @@ func (ch *channel) CloseWrite() error { } ch.sentEOF = true return ch.sendMessage(channelEOFMsg{ - PeersID: ch.remoteId}) + PeersID: ch.remoteId, + }) } func (ch *channel) Close() error { @@ -550,7 +553,8 @@ func (ch *channel) Close() error { } return ch.sendMessage(channelCloseMsg{ - PeersID: ch.remoteId}) + PeersID: ch.remoteId, + }) } // Extended returns an io.ReadWriter that sends and receives data on the given, diff --git a/vendor/golang.org/x/crypto/ssh/common.go b/vendor/golang.org/x/crypto/ssh/common.go index 290382d0..7c4a441f 100644 --- a/vendor/golang.org/x/crypto/ssh/common.go +++ b/vendor/golang.org/x/crypto/ssh/common.go @@ -139,7 +139,6 @@ func (a *directionAlgorithms) rekeyBytes() int64 { switch a.Cipher { case "aes128-ctr", "aes192-ctr", "aes256-ctr", gcmCipherID, aes128cbcID: return 16 * (1 << 32) - } // For others, stick with RFC4253 recommendation to rekey after 1 Gb of data. diff --git a/vendor/golang.org/x/crypto/ssh/handshake.go b/vendor/golang.org/x/crypto/ssh/handshake.go index 2b10b05a..9a2f2039 100644 --- a/vendor/golang.org/x/crypto/ssh/handshake.go +++ b/vendor/golang.org/x/crypto/ssh/handshake.go @@ -257,7 +257,6 @@ func (t *handshakeTransport) resetWriteThresholds() { } func (t *handshakeTransport) kexLoop() { - write: for t.getWriteError() == nil { var request *pendingKex diff --git a/vendor/golang.org/x/crypto/ssh/internal/bcrypt_pbkdf/bcrypt_pbkdf.go b/vendor/golang.org/x/crypto/ssh/internal/bcrypt_pbkdf/bcrypt_pbkdf.go index af81d266..dad2d93e 100644 --- a/vendor/golang.org/x/crypto/ssh/internal/bcrypt_pbkdf/bcrypt_pbkdf.go +++ b/vendor/golang.org/x/crypto/ssh/internal/bcrypt_pbkdf/bcrypt_pbkdf.go @@ -11,6 +11,7 @@ package bcrypt_pbkdf import ( "crypto/sha512" "errors" + "golang.org/x/crypto/blowfish" ) diff --git a/vendor/golang.org/x/crypto/ssh/kex.go b/vendor/golang.org/x/crypto/ssh/kex.go index 766e9293..d2029030 100644 --- a/vendor/golang.org/x/crypto/ssh/kex.go +++ b/vendor/golang.org/x/crypto/ssh/kex.go @@ -602,14 +602,14 @@ func (gex dhGEXSHA) Client(c packetConn, randSource io.Reader, magics *handshake // Check if g is safe by verifing that g > 1 and g < p - 1 one := big.NewInt(1) - var pMinusOne = &big.Int{} + pMinusOne := &big.Int{} pMinusOne.Sub(gex.p, one) if gex.g.Cmp(one) != 1 && gex.g.Cmp(pMinusOne) != -1 { return nil, fmt.Errorf("ssh: server provided gex g is not safe") } // Send GexInit - var pHalf = &big.Int{} + pHalf := &big.Int{} pHalf.Rsh(gex.p, 1) x, err := rand.Int(randSource, pHalf) if err != nil { @@ -723,7 +723,7 @@ func (gex dhGEXSHA) Server(c packetConn, randSource io.Reader, magics *handshake return } - var pHalf = &big.Int{} + pHalf := &big.Int{} pHalf.Rsh(gex.p, 1) y, err := rand.Int(randSource, pHalf) diff --git a/vendor/golang.org/x/crypto/ssh/messages.go b/vendor/golang.org/x/crypto/ssh/messages.go index ac41a416..e7fcbb19 100644 --- a/vendor/golang.org/x/crypto/ssh/messages.go +++ b/vendor/golang.org/x/crypto/ssh/messages.go @@ -152,8 +152,7 @@ type userAuthRequestMsg struct { } // Used for debug printouts of packets. -type userAuthSuccessMsg struct { -} +type userAuthSuccessMsg struct{} // See RFC 4252, section 5.1 const msgUserAuthFailure = 51 @@ -176,8 +175,10 @@ type userAuthBannerMsg struct { } // See RFC 4256, section 3.2 -const msgUserAuthInfoRequest = 60 -const msgUserAuthInfoResponse = 61 +const ( + msgUserAuthInfoRequest = 60 + msgUserAuthInfoResponse = 61 +) type userAuthInfoRequestMsg struct { User string `sshtype:"60"` @@ -198,8 +199,10 @@ type channelOpenMsg struct { TypeSpecificData []byte `ssh:"rest"` } -const msgChannelExtendedData = 95 -const msgChannelData = 94 +const ( + msgChannelExtendedData = 95 + msgChannelData = 94 +) // Used for debug print outs of packets. type channelDataMsg struct { diff --git a/vendor/golang.org/x/crypto/ssh/ssh_gss.go b/vendor/golang.org/x/crypto/ssh/ssh_gss.go index 24bd7c8e..4687b456 100644 --- a/vendor/golang.org/x/crypto/ssh/ssh_gss.go +++ b/vendor/golang.org/x/crypto/ssh/ssh_gss.go @@ -87,12 +87,10 @@ type GSSAPIServer interface { DeleteSecContext() error } -var ( - // OpenSSH supports Kerberos V5 mechanism only for GSS-API authentication, - // so we also support the krb5 mechanism only. - // See RFC 1964 section 1. - krb5Mesh = asn1.ObjectIdentifier{1, 2, 840, 113554, 1, 2, 2} -) +// OpenSSH supports Kerberos V5 mechanism only for GSS-API authentication, +// so we also support the krb5 mechanism only. +// See RFC 1964 section 1. +var krb5Mesh = asn1.ObjectIdentifier{1, 2, 840, 113554, 1, 2, 2} // The GSS-API authentication method is initiated when the client sends an SSH_MSG_USERAUTH_REQUEST // See RFC 4462 section 3.2. diff --git a/vendor/golang.org/x/net/idna/trieval.go b/vendor/golang.org/x/net/idna/trieval.go index 7a8cf889..19e3fd86 100644 --- a/vendor/golang.org/x/net/idna/trieval.go +++ b/vendor/golang.org/x/net/idna/trieval.go @@ -84,7 +84,7 @@ const ( joiningT joiningR - //the following types are derived during processing + // the following types are derived during processing joinZWJ joinZWNJ joinVirama diff --git a/vendor/golang.org/x/sys/cpu/byteorder.go b/vendor/golang.org/x/sys/cpu/byteorder.go index dcbb14ef..3365c0e3 100644 --- a/vendor/golang.org/x/sys/cpu/byteorder.go +++ b/vendor/golang.org/x/sys/cpu/byteorder.go @@ -14,8 +14,10 @@ type byteOrder interface { Uint64([]byte) uint64 } -type littleEndian struct{} -type bigEndian struct{} +type ( + littleEndian struct{} + bigEndian struct{} +) func (littleEndian) Uint32(b []byte) uint32 { _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808 diff --git a/vendor/golang.org/x/sys/cpu/cpu_arm.go b/vendor/golang.org/x/sys/cpu/cpu_arm.go index 301b752e..855beacd 100644 --- a/vendor/golang.org/x/sys/cpu/cpu_arm.go +++ b/vendor/golang.org/x/sys/cpu/cpu_arm.go @@ -69,5 +69,4 @@ func initOptions() { {Name: "aes", Feature: &ARM.HasAES}, {Name: "crc32", Feature: &ARM.HasCRC32}, } - } diff --git a/vendor/golang.org/x/sys/cpu/cpu_x86.go b/vendor/golang.org/x/sys/cpu/cpu_x86.go index fd380c0a..d32800ac 100644 --- a/vendor/golang.org/x/sys/cpu/cpu_x86.go +++ b/vendor/golang.org/x/sys/cpu/cpu_x86.go @@ -57,7 +57,6 @@ func initOptions() { } func archInit() { - Initialized = true maxID, _, _, _ := cpuid(0, 0) diff --git a/vendor/golang.org/x/sys/cpu/hwcap_linux.go b/vendor/golang.org/x/sys/cpu/hwcap_linux.go index f3baa379..b053a889 100644 --- a/vendor/golang.org/x/sys/cpu/hwcap_linux.go +++ b/vendor/golang.org/x/sys/cpu/hwcap_linux.go @@ -20,8 +20,10 @@ const ( // For those platforms don't have a 'cpuid' equivalent we use HWCAP/HWCAP2 // These are initialized in cpu_$GOARCH.go // and should not be changed after they are initialized. -var hwCap uint -var hwCap2 uint +var ( + hwCap uint + hwCap2 uint +) func readHWCAP() error { buf, err := ioutil.ReadFile(procAuxv) diff --git a/vendor/golang.org/x/sys/unix/aliases.go b/vendor/golang.org/x/sys/unix/aliases.go index abc89c10..21b37527 100644 --- a/vendor/golang.org/x/sys/unix/aliases.go +++ b/vendor/golang.org/x/sys/unix/aliases.go @@ -10,6 +10,8 @@ package unix import "syscall" -type Signal = syscall.Signal -type Errno = syscall.Errno -type SysProcAttr = syscall.SysProcAttr +type ( + Signal = syscall.Signal + Errno = syscall.Errno + SysProcAttr = syscall.SysProcAttr +) diff --git a/vendor/golang.org/x/sys/unix/cap_freebsd.go b/vendor/golang.org/x/sys/unix/cap_freebsd.go index 0b7c6adb..eec747cd 100644 --- a/vendor/golang.org/x/sys/unix/cap_freebsd.go +++ b/vendor/golang.org/x/sys/unix/cap_freebsd.go @@ -21,12 +21,10 @@ const ( capArSizeMax = capRightsGoVersion + 2 ) -var ( - bit2idx = []int{ - -1, 0, 1, -1, 2, -1, -1, -1, 3, -1, -1, -1, -1, -1, -1, -1, - 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - } -) +var bit2idx = []int{ + -1, 0, 1, -1, 2, -1, -1, -1, 3, -1, -1, -1, -1, -1, -1, -1, + 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, +} func capidxbit(right uint64) int { return int((right >> 57) & 0x1f) diff --git a/vendor/golang.org/x/sys/unix/epoll_zos.go b/vendor/golang.org/x/sys/unix/epoll_zos.go index cedaf7e0..37ed2ead 100644 --- a/vendor/golang.org/x/sys/unix/epoll_zos.go +++ b/vendor/golang.org/x/sys/unix/epoll_zos.go @@ -51,7 +51,7 @@ const ( // epToPollEvt converts epoll event field to poll equivalent. // In epoll, Events is a 32-bit field, while poll uses 16 bits. func epToPollEvt(events uint32) int16 { - var ep2p = map[uint32]int16{ + ep2p := map[uint32]int16{ EPOLLIN: POLLIN, EPOLLOUT: POLLOUT, EPOLLHUP: POLLHUP, @@ -71,7 +71,7 @@ func epToPollEvt(events uint32) int16 { // pToEpollEvt converts 16 bit poll event bitfields to 32-bit epoll event fields. func pToEpollEvt(revents int16) uint32 { - var p2ep = map[int16]uint32{ + p2ep := map[int16]uint32{ POLLIN: EPOLLIN, POLLOUT: EPOLLOUT, POLLHUP: EPOLLHUP, @@ -131,7 +131,6 @@ func (e *epollImpl) epollctl(epfd int, op int, fd int, event *EpollEvent) (err e ep, ok := e.epfd2ep[epfd] if !ok { - return EBADF } diff --git a/vendor/golang.org/x/sys/unix/fstatfs_zos.go b/vendor/golang.org/x/sys/unix/fstatfs_zos.go index e377cc9f..96cdaa88 100644 --- a/vendor/golang.org/x/sys/unix/fstatfs_zos.go +++ b/vendor/golang.org/x/sys/unix/fstatfs_zos.go @@ -49,7 +49,7 @@ func Fstatfs(fd int, stat *Statfs_t) (err error) { default: break } - //proceed to return if: err is nil (found), err is nonnil but not ERANGE (another error occurred) + // proceed to return if: err is nil (found), err is nonnil but not ERANGE (another error occurred) if err == nil || err != nil && err != ERANGE { break } @@ -68,7 +68,7 @@ func tryGetmntent64(stat *Statfs_t) (err error) { if err != nil { return err } - err = ERANGE //return ERANGE if no match is found in this batch + err = ERANGE // return ERANGE if no match is found in this batch for i := 0; i < fs_count; i++ { if stat.Fsid == uint64(mnt_ent_buffer.filesys_info[i].Dev) { stat.Type = uint32(mnt_ent_buffer.filesys_info[i].Fstname[0]) @@ -89,7 +89,7 @@ func tryGetmntent128(stat *Statfs_t) (err error) { if err != nil { return err } - err = ERANGE //return ERANGE if no match is found in this batch + err = ERANGE // return ERANGE if no match is found in this batch for i := 0; i < fs_count; i++ { if stat.Fsid == uint64(mnt_ent_buffer.filesys_info[i].Dev) { stat.Type = uint32(mnt_ent_buffer.filesys_info[i].Fstname[0]) @@ -110,7 +110,7 @@ func tryGetmntent256(stat *Statfs_t) (err error) { if err != nil { return err } - err = ERANGE //return ERANGE if no match is found in this batch + err = ERANGE // return ERANGE if no match is found in this batch for i := 0; i < fs_count; i++ { if stat.Fsid == uint64(mnt_ent_buffer.filesys_info[i].Dev) { stat.Type = uint32(mnt_ent_buffer.filesys_info[i].Fstname[0]) @@ -131,7 +131,7 @@ func tryGetmntent512(stat *Statfs_t) (err error) { if err != nil { return err } - err = ERANGE //return ERANGE if no match is found in this batch + err = ERANGE // return ERANGE if no match is found in this batch for i := 0; i < fs_count; i++ { if stat.Fsid == uint64(mnt_ent_buffer.filesys_info[i].Dev) { stat.Type = uint32(mnt_ent_buffer.filesys_info[i].Fstname[0]) @@ -152,7 +152,7 @@ func tryGetmntent1024(stat *Statfs_t) (err error) { if err != nil { return err } - err = ERANGE //return ERANGE if no match is found in this batch + err = ERANGE // return ERANGE if no match is found in this batch for i := 0; i < fs_count; i++ { if stat.Fsid == uint64(mnt_ent_buffer.filesys_info[i].Dev) { stat.Type = uint32(mnt_ent_buffer.filesys_info[i].Fstname[0]) diff --git a/vendor/golang.org/x/sys/unix/readdirent_getdirentries.go b/vendor/golang.org/x/sys/unix/readdirent_getdirentries.go index 2a4ba47c..1c27e2ca 100644 --- a/vendor/golang.org/x/sys/unix/readdirent_getdirentries.go +++ b/vendor/golang.org/x/sys/unix/readdirent_getdirentries.go @@ -15,6 +15,6 @@ func ReadDirent(fd int, buf []byte) (n int, err error) { // 64 bits should be enough. (32 bits isn't even on 386). Since the // actual system call is getdirentries64, 64 is a good guess. // TODO(rsc): Can we use a single global basep for all calls? - var base = (*uintptr)(unsafe.Pointer(new(uint64))) + base := (*uintptr)(unsafe.Pointer(new(uint64))) return Getdirentries(fd, buf, base) } diff --git a/vendor/golang.org/x/sys/unix/syscall_darwin.go b/vendor/golang.org/x/sys/unix/syscall_darwin.go index 1223d7ae..814d3936 100644 --- a/vendor/golang.org/x/sys/unix/syscall_darwin.go +++ b/vendor/golang.org/x/sys/unix/syscall_darwin.go @@ -372,7 +372,7 @@ func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err e if raceenabled { raceReleaseMerge(unsafe.Pointer(&ioSync)) } - var length = int64(count) + length := int64(count) err = sendfile(infd, outfd, *offset, &length, nil, 0) written = int(length) return diff --git a/vendor/golang.org/x/sys/unix/syscall_linux.go b/vendor/golang.org/x/sys/unix/syscall_linux.go index 44ea96e3..9c013372 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux.go @@ -2244,7 +2244,7 @@ func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { // Root can read and write any file. return nil } - if st.Mode&0111 != 0 { + if st.Mode&0o111 != 0 { // Root can execute any file that anybody can execute. return nil } diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_386.go b/vendor/golang.org/x/sys/unix/syscall_linux_386.go index 7b52e5d8..90ab7cde 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_386.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_386.go @@ -101,8 +101,10 @@ type rlimit32 struct { //sysnb getrlimit(resource int, rlim *rlimit32) (err error) = SYS_GETRLIMIT -const rlimInf32 = ^uint32(0) -const rlimInf64 = ^uint64(0) +const ( + rlimInf32 = ^uint32(0) + rlimInf64 = ^uint64(0) +) func Getrlimit(resource int, rlim *Rlimit) (err error) { err = prlimit(0, resource, nil, rlim) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_arm.go b/vendor/golang.org/x/sys/unix/syscall_linux_arm.go index 68877728..3f4309f6 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_arm.go @@ -180,8 +180,10 @@ type rlimit32 struct { //sysnb getrlimit(resource int, rlim *rlimit32) (err error) = SYS_UGETRLIMIT -const rlimInf32 = ^uint32(0) -const rlimInf64 = ^uint64(0) +const ( + rlimInf32 = ^uint32(0) + rlimInf64 = ^uint64(0) +) func Getrlimit(resource int, rlim *Rlimit) (err error) { err = prlimit(0, resource, nil, rlim) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go b/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go index 8f0d0a5b..03840517 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go @@ -146,8 +146,10 @@ func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int6 return mmap2(addr, length, prot, flags, fd, page) } -const rlimInf32 = ^uint32(0) -const rlimInf64 = ^uint64(0) +const ( + rlimInf32 = ^uint32(0) + rlimInf64 = ^uint64(0) +) type rlimit32 struct { Cur uint32 diff --git a/vendor/golang.org/x/sys/unix/syscall_unix.go b/vendor/golang.org/x/sys/unix/syscall_unix.go index a7618ceb..79fa0e44 100644 --- a/vendor/golang.org/x/sys/unix/syscall_unix.go +++ b/vendor/golang.org/x/sys/unix/syscall_unix.go @@ -326,7 +326,7 @@ func SetsockoptByte(fd, level, opt int, value byte) (err error) { } func SetsockoptInt(fd, level, opt int, value int) (err error) { - var n = int32(value) + n := int32(value) return setsockopt(fd, level, opt, unsafe.Pointer(&n), 4) } diff --git a/vendor/golang.org/x/sys/unix/syscall_unix_gc_ppc64x.go b/vendor/golang.org/x/sys/unix/syscall_unix_gc_ppc64x.go index f6f707ac..7c7d7993 100644 --- a/vendor/golang.org/x/sys/unix/syscall_unix_gc_ppc64x.go +++ b/vendor/golang.org/x/sys/unix/syscall_unix_gc_ppc64x.go @@ -14,12 +14,15 @@ import "syscall" func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) { return syscall.Syscall(trap, a1, a2, a3) } + func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) { return syscall.Syscall6(trap, a1, a2, a3, a4, a5, a6) } + func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) { return syscall.RawSyscall(trap, a1, a2, a3) } + func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) { return syscall.RawSyscall6(trap, a1, a2, a3, a4, a5, a6) } diff --git a/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go b/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go index 13f58d2b..dab667ad 100644 --- a/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go +++ b/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go @@ -38,11 +38,11 @@ func copyStat(stat *Stat_t, statLE *Stat_LE_t) { stat.Rdev = uint64(statLE.Rdev) stat.Size = statLE.Size stat.Atim.Sec = int64(statLE.Atim) - stat.Atim.Nsec = 0 //zos doesn't return nanoseconds + stat.Atim.Nsec = 0 // zos doesn't return nanoseconds stat.Mtim.Sec = int64(statLE.Mtim) - stat.Mtim.Nsec = 0 //zos doesn't return nanoseconds + stat.Mtim.Nsec = 0 // zos doesn't return nanoseconds stat.Ctim.Sec = int64(statLE.Ctim) - stat.Ctim.Nsec = 0 //zos doesn't return nanoseconds + stat.Ctim.Nsec = 0 // zos doesn't return nanoseconds stat.Blksize = int64(statLE.Blksize) stat.Blocks = statLE.Blocks } @@ -321,7 +321,7 @@ func Getpgrp() (pid int) { func Getrusage(who int, rusage *Rusage) (err error) { var ruz rusage_zos err = getrusage(who, &ruz) - //Only the first two fields of Rusage are set + // Only the first two fields of Rusage are set rusage.Utime.Sec = ruz.Utime.Sec rusage.Utime.Usec = int64(ruz.Utime.Usec) rusage.Stime.Sec = ruz.Stime.Sec @@ -571,7 +571,7 @@ func setTimespec(sec, nsec int64) Timespec { return Timespec{Sec: sec, Nsec: nsec} } -func setTimeval(sec, usec int64) Timeval { //fix +func setTimeval(sec, usec int64) Timeval { // fix return Timeval{Sec: sec, Usec: usec} } @@ -1219,7 +1219,7 @@ func Readdir(dir uintptr) (*Dirent, error) { // Therefore to avoid false positives we clear errno before calling it. // TODO(neeilan): Commented this out to get sys/unix compiling on z/OS. Uncomment and fix. Error: "undefined: clearsyscall" - //clearsyscall.Errno() // TODO(mundaym): check pre-emption rules. + // clearsyscall.Errno() // TODO(mundaym): check pre-emption rules. e, _, _ := syscall_syscall(SYS___READDIR_R_A, dir, uintptr(unsafe.Pointer(&ent)), uintptr(unsafe.Pointer(&res))) var err error @@ -1276,7 +1276,6 @@ func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error { } func Flock(fd int, how int) error { - var flock_type int16 var fcntl_cmd int @@ -1349,8 +1348,7 @@ func Munlockall() (err error) { } func ClockGettime(clockid int32, ts *Timespec) error { - - var ticks_per_sec uint32 = 100 //TODO(kenan): value is currently hardcoded; need sysconf() call otherwise + var ticks_per_sec uint32 = 100 // TODO(kenan): value is currently hardcoded; need sysconf() call otherwise var nsec_per_sec int64 = 1000000000 if ts == nil { @@ -1483,7 +1481,7 @@ func (m *mmapper) Mmap(fd int, offset int64, length int, prot int, flags int) (d } // Slice memory layout - var sl = struct { + sl := struct { addr uintptr len int cap int @@ -1695,7 +1693,7 @@ func SetsockoptByte(fd, level, opt int, value byte) (err error) { } func SetsockoptInt(fd, level, opt int, value int) (err error) { - var n = int32(value) + n := int32(value) return setsockopt(fd, level, opt, unsafe.Pointer(&n), 4) } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc.go b/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc.go index 91a23cc7..85521910 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc.go @@ -130,6 +130,7 @@ uintptr_t mmap(uintptr_t, uintptr_t, int, int, int, long long); */ import "C" + import ( "unsafe" ) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gc.go b/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gc.go index 8b737fa9..89357f9a 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gc.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gc.go @@ -248,8 +248,7 @@ import ( type syscallFunc uintptr -var ( - libc_utimes, +var libc_utimes, libc_utimensat, libc_getcwd, libc_accept, @@ -366,7 +365,6 @@ var ( libc_setrlimit, libc_lseek, libc_mmap64 syscallFunc -) // Implemented in runtime/syscall_aix.go. func rawSyscall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gccgo.go b/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gccgo.go index 3c260917..264df754 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gccgo.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gccgo.go @@ -129,6 +129,7 @@ uintptr_t mmap64(uintptr_t, uintptr_t, int, int, int, long long); */ import "C" + import ( "syscall" ) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_illumos_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_illumos_amd64.go index af5cb064..681127d2 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_illumos_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_illumos_amd64.go @@ -26,15 +26,13 @@ import ( //go:linkname procputmsg libc_putmsg //go:linkname procgetmsg libc_getmsg -var ( - procreadv, +var procreadv, procpreadv, procwritev, procpwritev, procaccept4, procputmsg, procgetmsg syscallFunc -) // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT diff --git a/vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go index 4e18d5c9..d6a7d421 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go @@ -273,8 +273,7 @@ import ( //go:linkname procsetsockopt libc_setsockopt //go:linkname procrecvfrom libc_recvfrom -var ( - procpipe, +var procpipe, procpipe2, procgetsockname, procGetcwd, @@ -404,7 +403,6 @@ var ( procgetpeername, procsetsockopt, procrecvfrom syscallFunc -) // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT diff --git a/vendor/golang.org/x/sys/unix/ztypes_aix_ppc.go b/vendor/golang.org/x/sys/unix/ztypes_aix_ppc.go index 7a8161c1..b9384ddb 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_aix_ppc.go +++ b/vendor/golang.org/x/sys/unix/ztypes_aix_ppc.go @@ -22,9 +22,11 @@ type ( _C_long_long int64 ) -type off64 int64 -type off int32 -type Mode_t uint32 +type ( + off64 int64 + off int32 + Mode_t uint32 +) type Timespec struct { Sec int32 @@ -326,6 +328,7 @@ type Flock_t struct { type Fsid_t struct { Val [2]uint32 } + type Fsid64_t struct { Val [2]uint64 } diff --git a/vendor/golang.org/x/sys/unix/ztypes_aix_ppc64.go b/vendor/golang.org/x/sys/unix/ztypes_aix_ppc64.go index 07ed733c..07609444 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_aix_ppc64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_aix_ppc64.go @@ -22,9 +22,11 @@ type ( _C_long_long int64 ) -type off64 int64 -type off int64 -type Mode_t uint32 +type ( + off64 int64 + off int64 + Mode_t uint32 +) type Timespec struct { Sec int64 @@ -329,6 +331,7 @@ type Flock_t struct { type Fsid_t struct { Val [2]uint32 } + type Fsid64_t struct { Val [2]uint64 } diff --git a/vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go b/vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go index 8bffde78..074a0c67 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go +++ b/vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go @@ -49,13 +49,13 @@ type Timeval struct { Usec int64 } -type timeval_zos struct { //correct (with padding and all) +type timeval_zos struct { // correct (with padding and all) Sec int64 _ [4]byte // pad Usec int32 } -type Tms struct { //clock_t is 4-byte unsigned int in zos +type Tms struct { // clock_t is 4-byte unsigned int in zos Utime uint32 Stime uint32 Cutime uint32 @@ -240,7 +240,7 @@ type PollFd struct { Revents int16 } -type Stat_t struct { //Linux Definition +type Stat_t struct { // Linux Definition Dev uint64 Ino uint64 Nlink uint64 @@ -374,7 +374,7 @@ type Winsize struct { type W_Mnth struct { Hid [4]byte Size int32 - Cur1 int32 //32bit pointer + Cur1 int32 // 32bit pointer Cur2 int32 //^ Devno uint32 _ [4]byte diff --git a/vendor/golang.org/x/sys/windows/aliases.go b/vendor/golang.org/x/sys/windows/aliases.go index af3af60d..6e7dd776 100644 --- a/vendor/golang.org/x/sys/windows/aliases.go +++ b/vendor/golang.org/x/sys/windows/aliases.go @@ -9,5 +9,7 @@ package windows import "syscall" -type Errno = syscall.Errno -type SysProcAttr = syscall.SysProcAttr +type ( + Errno = syscall.Errno + SysProcAttr = syscall.SysProcAttr +) diff --git a/vendor/golang.org/x/sys/windows/security_windows.go b/vendor/golang.org/x/sys/windows/security_windows.go index 0e428ecb..2dfe66df 100644 --- a/vendor/golang.org/x/sys/windows/security_windows.go +++ b/vendor/golang.org/x/sys/windows/security_windows.go @@ -1093,12 +1093,15 @@ type TrusteeValue uintptr func TrusteeValueFromString(str string) TrusteeValue { return TrusteeValue(unsafe.Pointer(StringToUTF16Ptr(str))) } + func TrusteeValueFromSID(sid *SID) TrusteeValue { return TrusteeValue(unsafe.Pointer(sid)) } + func TrusteeValueFromObjectsAndSid(objectsAndSid *OBJECTS_AND_SID) TrusteeValue { return TrusteeValue(unsafe.Pointer(objectsAndSid)) } + func TrusteeValueFromObjectsAndName(objectsAndName *OBJECTS_AND_NAME) TrusteeValue { return TrusteeValue(unsafe.Pointer(objectsAndName)) } diff --git a/vendor/golang.org/x/sys/windows/syscall_windows.go b/vendor/golang.org/x/sys/windows/syscall_windows.go index bb6aaf89..1e0eea97 100644 --- a/vendor/golang.org/x/sys/windows/syscall_windows.go +++ b/vendor/golang.org/x/sys/windows/syscall_windows.go @@ -19,8 +19,10 @@ import ( "golang.org/x/sys/internal/unsafeheader" ) -type Handle uintptr -type HWND uintptr +type ( + Handle uintptr + HWND uintptr +) const ( InvalidHandle = ^Handle(0) @@ -1278,9 +1280,11 @@ func SetsockoptLinger(fd Handle, level, opt int, l *Linger) (err error) { func SetsockoptInet4Addr(fd Handle, level, opt int, value [4]byte) (err error) { return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&value[0])), 4) } + func SetsockoptIPMreq(fd Handle, level, opt int, mreq *IPMreq) (err error) { return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(mreq)), int32(unsafe.Sizeof(*mreq))) } + func SetsockoptIPv6Mreq(fd Handle, level, opt int, mreq *IPv6Mreq) (err error) { return syscall.EWINDOWS } diff --git a/vendor/golang.org/x/sys/windows/types_windows.go b/vendor/golang.org/x/sys/windows/types_windows.go index 23fe18ec..a50db81c 100644 --- a/vendor/golang.org/x/sys/windows/types_windows.go +++ b/vendor/golang.org/x/sys/windows/types_windows.go @@ -1286,9 +1286,11 @@ type IpAddrString struct { Context uint32 } -const MAX_ADAPTER_NAME_LENGTH = 256 -const MAX_ADAPTER_DESCRIPTION_LENGTH = 128 -const MAX_ADAPTER_ADDRESS_LENGTH = 8 +const ( + MAX_ADAPTER_NAME_LENGTH = 256 + MAX_ADAPTER_DESCRIPTION_LENGTH = 128 + MAX_ADAPTER_ADDRESS_LENGTH = 8 +) type IpAdapterInfo struct { Next *IpAdapterInfo @@ -1311,9 +1313,11 @@ type IpAdapterInfo struct { LeaseExpires int64 } -const MAXLEN_PHYSADDR = 8 -const MAX_INTERFACE_NAME_LEN = 256 -const MAXLEN_IFDESCR = 256 +const ( + MAXLEN_PHYSADDR = 8 + MAX_INTERFACE_NAME_LEN = 256 + MAXLEN_IFDESCR = 256 +) type MibIfRow struct { Name [MAX_INTERFACE_NAME_LEN]uint16 @@ -1377,18 +1381,20 @@ type DataBlob struct { Size uint32 Data *byte } -type CryptIntegerBlob DataBlob -type CryptUintBlob DataBlob -type CryptObjidBlob DataBlob -type CertNameBlob DataBlob -type CertRdnValueBlob DataBlob -type CertBlob DataBlob -type CrlBlob DataBlob -type CryptDataBlob DataBlob -type CryptHashBlob DataBlob -type CryptDigestBlob DataBlob -type CryptDerBlob DataBlob -type CryptAttrBlob DataBlob +type ( + CryptIntegerBlob DataBlob + CryptUintBlob DataBlob + CryptObjidBlob DataBlob + CertNameBlob DataBlob + CertRdnValueBlob DataBlob + CertBlob DataBlob + CrlBlob DataBlob + CryptDataBlob DataBlob + CryptHashBlob DataBlob + CryptDigestBlob DataBlob + CryptDerBlob DataBlob + CryptAttrBlob DataBlob +) type CryptBitBlob struct { Size uint32 @@ -1415,8 +1421,7 @@ type CertChainContext struct { RevocationFreshnessTime uint32 } -type CertTrustListInfo struct { - // Not implemented +type CertTrustListInfo struct { // Not implemented } type CertSimpleChain struct { @@ -1439,8 +1444,7 @@ type CertChainElement struct { ExtendedErrorInfo *uint16 } -type CertRevocationCrlInfo struct { - // Not implemented +type CertRevocationCrlInfo struct { // Not implemented } type CertRevocationInfo struct { @@ -1510,8 +1514,7 @@ type CertPoliciesInfo struct { PolicyInfos *CertPolicyInfo } -type CertPolicyQualifierInfo struct { - // Not implemented +type CertPolicyQualifierInfo struct { // Not implemented } type CertStrongSignPara struct { diff --git a/vendor/golang.org/x/text/unicode/bidi/core.go b/vendor/golang.org/x/text/unicode/bidi/core.go index e4c08110..f7ed1ac7 100644 --- a/vendor/golang.org/x/text/unicode/bidi/core.go +++ b/vendor/golang.org/x/text/unicode/bidi/core.go @@ -461,7 +461,6 @@ func (p *paragraph) isolatingRunSequence(indexes []int) *isolatingRunSequence { // the first character after the end of run sequence limit := indexes[length-1] + 1 for ; limit < p.Len() && isRemovedByX9(p.initialTypes[limit]); limit++ { - } succLevel = p.embeddingLevel if limit < p.Len() { @@ -484,7 +483,6 @@ func (p *paragraph) isolatingRunSequence(indexes []int) *isolatingRunSequence { // Note that some weak types (EN, AN) remain after this processing is // complete. func (s *isolatingRunSequence) resolveWeakTypes() { - // on entry, only these types remain s.assertOnly(L, R, AL, EN, ES, ET, AN, CS, B, S, WS, ON, NSM, LRI, RLI, FSI, PDI) @@ -604,7 +602,6 @@ func (s *isolatingRunSequence) resolveWeakTypes() { // 6) resolving neutral types Rules N1-N2. func (s *isolatingRunSequence) resolveNeutralTypes() { - // on entry, only these types can be in resultTypes s.assertOnly(L, R, EN, AN, B, S, WS, ON, RLI, LRI, FSI, PDI) @@ -670,7 +667,6 @@ func setTypes(types []Class, newType Class) { // 7) resolving implicit embedding levels Rules I1, I2. func (s *isolatingRunSequence) resolveImplicitLevels() { - // on entry, only these types can be in resultTypes s.assertOnly(L, R, EN, AN) diff --git a/vendor/golang.org/x/text/unicode/norm/tables10.0.0.go b/vendor/golang.org/x/text/unicode/norm/tables10.0.0.go index 26fbd55a..430239ab 100644 --- a/vendor/golang.org/x/text/unicode/norm/tables10.0.0.go +++ b/vendor/golang.org/x/text/unicode/norm/tables10.0.0.go @@ -6709,8 +6709,10 @@ var nfkcSparseValues = [869]valueRange{ } // recompMap: 7520 bytes (entries only) -var recompMap map[uint32]rune -var recompMapOnce sync.Once +var ( + recompMap map[uint32]rune + recompMapOnce sync.Once +) const recompMapPacked = "" + "\x00A\x03\x00\x00\x00\x00\xc0" + // 0x00410300: 0x000000C0 diff --git a/vendor/golang.org/x/text/unicode/norm/tables11.0.0.go b/vendor/golang.org/x/text/unicode/norm/tables11.0.0.go index 2c58f09b..39a70e47 100644 --- a/vendor/golang.org/x/text/unicode/norm/tables11.0.0.go +++ b/vendor/golang.org/x/text/unicode/norm/tables11.0.0.go @@ -6745,8 +6745,10 @@ var nfkcSparseValues = [871]valueRange{ } // recompMap: 7520 bytes (entries only) -var recompMap map[uint32]rune -var recompMapOnce sync.Once +var ( + recompMap map[uint32]rune + recompMapOnce sync.Once +) const recompMapPacked = "" + "\x00A\x03\x00\x00\x00\x00\xc0" + // 0x00410300: 0x000000C0 diff --git a/vendor/golang.org/x/text/unicode/norm/tables12.0.0.go b/vendor/golang.org/x/text/unicode/norm/tables12.0.0.go index 7e1ae096..a750d679 100644 --- a/vendor/golang.org/x/text/unicode/norm/tables12.0.0.go +++ b/vendor/golang.org/x/text/unicode/norm/tables12.0.0.go @@ -6762,8 +6762,10 @@ var nfkcSparseValues = [877]valueRange{ } // recompMap: 7520 bytes (entries only) -var recompMap map[uint32]rune -var recompMapOnce sync.Once +var ( + recompMap map[uint32]rune + recompMapOnce sync.Once +) const recompMapPacked = "" + "\x00A\x03\x00\x00\x00\x00\xc0" + // 0x00410300: 0x000000C0 diff --git a/vendor/golang.org/x/text/unicode/norm/tables13.0.0.go b/vendor/golang.org/x/text/unicode/norm/tables13.0.0.go index 9ea1b421..6e52c4ab 100644 --- a/vendor/golang.org/x/text/unicode/norm/tables13.0.0.go +++ b/vendor/golang.org/x/text/unicode/norm/tables13.0.0.go @@ -6811,8 +6811,10 @@ var nfkcSparseValues = [895]valueRange{ } // recompMap: 7528 bytes (entries only) -var recompMap map[uint32]rune -var recompMapOnce sync.Once +var ( + recompMap map[uint32]rune + recompMapOnce sync.Once +) const recompMapPacked = "" + "\x00A\x03\x00\x00\x00\x00\xc0" + // 0x00410300: 0x000000C0 diff --git a/vendor/golang.org/x/text/unicode/norm/tables9.0.0.go b/vendor/golang.org/x/text/unicode/norm/tables9.0.0.go index 94290692..b3149a6f 100644 --- a/vendor/golang.org/x/text/unicode/norm/tables9.0.0.go +++ b/vendor/golang.org/x/text/unicode/norm/tables9.0.0.go @@ -6689,8 +6689,10 @@ var nfkcSparseValues = [875]valueRange{ } // recompMap: 7520 bytes (entries only) -var recompMap map[uint32]rune -var recompMapOnce sync.Once +var ( + recompMap map[uint32]rune + recompMapOnce sync.Once +) const recompMapPacked = "" + "\x00A\x03\x00\x00\x00\x00\xc0" + // 0x00410300: 0x000000C0 diff --git a/vendor/google.golang.org/protobuf/encoding/prototext/encode.go b/vendor/google.golang.org/protobuf/encoding/prototext/encode.go index dece2297..299bb33d 100644 --- a/vendor/google.golang.org/protobuf/encoding/prototext/encode.go +++ b/vendor/google.golang.org/protobuf/encoding/prototext/encode.go @@ -102,7 +102,7 @@ func (o MarshalOptions) Format(m proto.Message) string { // MarshalOptions object. Do not depend on the output being stable. It may // change over time across different versions of the program. func (o MarshalOptions) Marshal(m proto.Message) ([]byte, error) { - var delims = [2]byte{'{', '}'} + delims := [2]byte{'{', '}'} if o.Multiline && o.Indent == "" { o.Indent = defaultIndent diff --git a/vendor/google.golang.org/protobuf/internal/descfmt/stringer.go b/vendor/google.golang.org/protobuf/internal/descfmt/stringer.go index e7af0fe0..22b19cb2 100644 --- a/vendor/google.golang.org/protobuf/internal/descfmt/stringer.go +++ b/vendor/google.golang.org/protobuf/internal/descfmt/stringer.go @@ -25,6 +25,7 @@ type list interface { func FormatList(s fmt.State, r rune, vs list) { io.WriteString(s, formatListOpt(vs, true, r == 'v' && (s.Flag('+') || s.Flag('#')))) } + func formatListOpt(vs list, isRoot, allowMulti bool) string { start, end := "[", "]" if isRoot { @@ -117,6 +118,7 @@ var descriptorAccessors = map[reflect.Type][]string{ func FormatDesc(s fmt.State, r rune, t pref.Descriptor) { io.WriteString(s, formatDescOpt(t, true, r == 'v' && (s.Flag('+') || s.Flag('#')))) } + func formatDescOpt(t pref.Descriptor, isRoot, allowMulti bool) string { rv := reflect.ValueOf(t) rt := rv.MethodByName("ProtoType").Type().In(0) diff --git a/vendor/google.golang.org/protobuf/internal/filedesc/desc.go b/vendor/google.golang.org/protobuf/internal/filedesc/desc.go index 2540befd..e8de9d09 100644 --- a/vendor/google.golang.org/protobuf/internal/filedesc/desc.go +++ b/vendor/google.golang.org/protobuf/internal/filedesc/desc.go @@ -148,6 +148,7 @@ func (ed *Enum) Options() pref.ProtoMessage { } return descopts.Enum } + func (ed *Enum) Values() pref.EnumValueDescriptors { if ed.L1.eagerValues { return &ed.L2.Values @@ -281,9 +282,11 @@ func (fd *Field) JSONName() string { return fd.L1.JSONName.get(fd) func (fd *Field) HasPresence() bool { return fd.L1.Cardinality != pref.Repeated && (fd.L0.ParentFile.L1.Syntax == pref.Proto2 || fd.L1.Message != nil || fd.L1.ContainingOneof != nil) } + func (fd *Field) HasOptionalKeyword() bool { return (fd.L0.ParentFile.L1.Syntax == pref.Proto2 && fd.L1.Cardinality == pref.Optional && fd.L1.ContainingOneof == nil) || fd.L1.IsProto3Optional } + func (fd *Field) IsPacked() bool { if !fd.L1.HasPacked && fd.L0.ParentFile.L1.Syntax != pref.Proto2 && fd.L1.Cardinality == pref.Repeated { switch fd.L1.Kind { @@ -304,6 +307,7 @@ func (fd *Field) MapKey() pref.FieldDescriptor { } return fd.Message().Fields().ByNumber(1) } + func (fd *Field) MapValue() pref.FieldDescriptor { if !fd.IsMap() { return nil @@ -317,9 +321,11 @@ func (fd *Field) ContainingOneof() pref.OneofDescriptor { return fd.L1.Cont func (fd *Field) ContainingMessage() pref.MessageDescriptor { return fd.L0.Parent.(pref.MessageDescriptor) } + func (fd *Field) Enum() pref.EnumDescriptor { return fd.L1.Enum } + func (fd *Field) Message() pref.MessageDescriptor { if fd.L1.IsWeak { if d, _ := protoregistry.GlobalFiles.FindDescriptorByName(fd.L1.Message.FullName()); d != nil { @@ -348,6 +354,7 @@ func (fd *Field) EnforceUTF8() bool { func (od *Oneof) IsSynthetic() bool { return od.L0.ParentFile.L1.Syntax == pref.Proto3 && len(od.L1.Fields.List) == 1 && od.L1.Fields.List[0].HasOptionalKeyword() } + func (od *Oneof) Options() pref.ProtoMessage { if f := od.L1.Options; f != nil { return f() diff --git a/vendor/google.golang.org/protobuf/internal/filedesc/desc_init.go b/vendor/google.golang.org/protobuf/internal/filedesc/desc_init.go index c0cddf86..dce672fd 100644 --- a/vendor/google.golang.org/protobuf/internal/filedesc/desc_init.go +++ b/vendor/google.golang.org/protobuf/internal/filedesc/desc_init.go @@ -58,18 +58,21 @@ func (fd *File) allocEnums(n int) []Enum { fd.allEnums = fd.allEnums[:total+n] return es } + func (fd *File) allocMessages(n int) []Message { total := len(fd.allMessages) ms := fd.allMessages[total : total+n] fd.allMessages = fd.allMessages[:total+n] return ms } + func (fd *File) allocExtensions(n int) []Extension { total := len(fd.allExtensions) xs := fd.allExtensions[total : total+n] fd.allExtensions = fd.allExtensions[:total+n] return xs } + func (fd *File) allocServices(n int) []Service { total := len(fd.allServices) xs := fd.allServices[total : total+n] @@ -453,6 +456,7 @@ var nameBuilderPool = sync.Pool{ func getBuilder() *strs.Builder { return nameBuilderPool.Get().(*strs.Builder) } + func putBuilder(b *strs.Builder) { nameBuilderPool.Put(b) } diff --git a/vendor/google.golang.org/protobuf/internal/filedesc/desc_list_gen.go b/vendor/google.golang.org/protobuf/internal/filedesc/desc_list_gen.go index 6a8825e8..7dbfb1f0 100644 --- a/vendor/google.golang.org/protobuf/internal/filedesc/desc_list_gen.go +++ b/vendor/google.golang.org/protobuf/internal/filedesc/desc_list_gen.go @@ -24,15 +24,18 @@ type Enums struct { func (p *Enums) Len() int { return len(p.List) } + func (p *Enums) Get(i int) protoreflect.EnumDescriptor { return &p.List[i] } + func (p *Enums) ByName(s protoreflect.Name) protoreflect.EnumDescriptor { if d := p.lazyInit().byName[s]; d != nil { return d } return nil } + func (p *Enums) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } @@ -62,21 +65,25 @@ type EnumValues struct { func (p *EnumValues) Len() int { return len(p.List) } + func (p *EnumValues) Get(i int) protoreflect.EnumValueDescriptor { return &p.List[i] } + func (p *EnumValues) ByName(s protoreflect.Name) protoreflect.EnumValueDescriptor { if d := p.lazyInit().byName[s]; d != nil { return d } return nil } + func (p *EnumValues) ByNumber(n protoreflect.EnumNumber) protoreflect.EnumValueDescriptor { if d := p.lazyInit().byNum[n]; d != nil { return d } return nil } + func (p *EnumValues) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } @@ -109,15 +116,18 @@ type Messages struct { func (p *Messages) Len() int { return len(p.List) } + func (p *Messages) Get(i int) protoreflect.MessageDescriptor { return &p.List[i] } + func (p *Messages) ByName(s protoreflect.Name) protoreflect.MessageDescriptor { if d := p.lazyInit().byName[s]; d != nil { return d } return nil } + func (p *Messages) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } @@ -148,27 +158,32 @@ type Fields struct { func (p *Fields) Len() int { return len(p.List) } + func (p *Fields) Get(i int) protoreflect.FieldDescriptor { return &p.List[i] } + func (p *Fields) ByName(s protoreflect.Name) protoreflect.FieldDescriptor { if d := p.lazyInit().byName[s]; d != nil { return d } return nil } + func (p *Fields) ByJSONName(s string) protoreflect.FieldDescriptor { if d := p.lazyInit().byJSON[s]; d != nil { return d } return nil } + func (p *Fields) ByNumber(n protoreflect.FieldNumber) protoreflect.FieldDescriptor { if d := p.lazyInit().byNum[n]; d != nil { return d } return nil } + func (p *Fields) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } @@ -205,15 +220,18 @@ type Oneofs struct { func (p *Oneofs) Len() int { return len(p.List) } + func (p *Oneofs) Get(i int) protoreflect.OneofDescriptor { return &p.List[i] } + func (p *Oneofs) ByName(s protoreflect.Name) protoreflect.OneofDescriptor { if d := p.lazyInit().byName[s]; d != nil { return d } return nil } + func (p *Oneofs) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } @@ -242,15 +260,18 @@ type Extensions struct { func (p *Extensions) Len() int { return len(p.List) } + func (p *Extensions) Get(i int) protoreflect.ExtensionDescriptor { return &p.List[i] } + func (p *Extensions) ByName(s protoreflect.Name) protoreflect.ExtensionDescriptor { if d := p.lazyInit().byName[s]; d != nil { return d } return nil } + func (p *Extensions) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } @@ -279,15 +300,18 @@ type Services struct { func (p *Services) Len() int { return len(p.List) } + func (p *Services) Get(i int) protoreflect.ServiceDescriptor { return &p.List[i] } + func (p *Services) ByName(s protoreflect.Name) protoreflect.ServiceDescriptor { if d := p.lazyInit().byName[s]; d != nil { return d } return nil } + func (p *Services) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } @@ -316,15 +340,18 @@ type Methods struct { func (p *Methods) Len() int { return len(p.List) } + func (p *Methods) Get(i int) protoreflect.MethodDescriptor { return &p.List[i] } + func (p *Methods) ByName(s protoreflect.Name) protoreflect.MethodDescriptor { if d := p.lazyInit().byName[s]; d != nil { return d } return nil } + func (p *Methods) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } diff --git a/vendor/google.golang.org/protobuf/internal/impl/codec_gen.go b/vendor/google.golang.org/protobuf/internal/impl/codec_gen.go index ff198d0a..5a9e9a4c 100644 --- a/vendor/google.golang.org/protobuf/internal/impl/codec_gen.go +++ b/vendor/google.golang.org/protobuf/internal/impl/codec_gen.go @@ -3022,7 +3022,6 @@ var coderUint64PackedSliceValue = valueCoderFuncs{ // sizeSfixed32 returns the size of wire encoding a int32 pointer as a Sfixed32. func sizeSfixed32(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { - return f.tagsize + protowire.SizeFixed32() } @@ -3338,7 +3337,6 @@ var coderSfixed32PackedSliceValue = valueCoderFuncs{ // sizeFixed32 returns the size of wire encoding a uint32 pointer as a Fixed32. func sizeFixed32(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { - return f.tagsize + protowire.SizeFixed32() } @@ -3654,7 +3652,6 @@ var coderFixed32PackedSliceValue = valueCoderFuncs{ // sizeFloat returns the size of wire encoding a float32 pointer as a Float. func sizeFloat(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { - return f.tagsize + protowire.SizeFixed32() } @@ -3970,7 +3967,6 @@ var coderFloatPackedSliceValue = valueCoderFuncs{ // sizeSfixed64 returns the size of wire encoding a int64 pointer as a Sfixed64. func sizeSfixed64(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { - return f.tagsize + protowire.SizeFixed64() } @@ -4286,7 +4282,6 @@ var coderSfixed64PackedSliceValue = valueCoderFuncs{ // sizeFixed64 returns the size of wire encoding a uint64 pointer as a Fixed64. func sizeFixed64(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { - return f.tagsize + protowire.SizeFixed64() } @@ -4602,7 +4597,6 @@ var coderFixed64PackedSliceValue = valueCoderFuncs{ // sizeDouble returns the size of wire encoding a float64 pointer as a Double. func sizeDouble(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { - return f.tagsize + protowire.SizeFixed64() } diff --git a/vendor/google.golang.org/protobuf/internal/impl/convert.go b/vendor/google.golang.org/protobuf/internal/impl/convert.go index 36a90dff..f83209fc 100644 --- a/vendor/google.golang.org/protobuf/internal/impl/convert.go +++ b/vendor/google.golang.org/protobuf/internal/impl/convert.go @@ -154,13 +154,16 @@ func (c *boolConverter) PBValueOf(v reflect.Value) pref.Value { } return pref.ValueOfBool(v.Bool()) } + func (c *boolConverter) GoValueOf(v pref.Value) reflect.Value { return reflect.ValueOf(v.Bool()).Convert(c.goType) } + func (c *boolConverter) IsValidPB(v pref.Value) bool { _, ok := v.Interface().(bool) return ok } + func (c *boolConverter) IsValidGo(v reflect.Value) bool { return v.IsValid() && v.Type() == c.goType } @@ -178,13 +181,16 @@ func (c *int32Converter) PBValueOf(v reflect.Value) pref.Value { } return pref.ValueOfInt32(int32(v.Int())) } + func (c *int32Converter) GoValueOf(v pref.Value) reflect.Value { return reflect.ValueOf(int32(v.Int())).Convert(c.goType) } + func (c *int32Converter) IsValidPB(v pref.Value) bool { _, ok := v.Interface().(int32) return ok } + func (c *int32Converter) IsValidGo(v reflect.Value) bool { return v.IsValid() && v.Type() == c.goType } @@ -202,13 +208,16 @@ func (c *int64Converter) PBValueOf(v reflect.Value) pref.Value { } return pref.ValueOfInt64(int64(v.Int())) } + func (c *int64Converter) GoValueOf(v pref.Value) reflect.Value { return reflect.ValueOf(int64(v.Int())).Convert(c.goType) } + func (c *int64Converter) IsValidPB(v pref.Value) bool { _, ok := v.Interface().(int64) return ok } + func (c *int64Converter) IsValidGo(v reflect.Value) bool { return v.IsValid() && v.Type() == c.goType } @@ -226,13 +235,16 @@ func (c *uint32Converter) PBValueOf(v reflect.Value) pref.Value { } return pref.ValueOfUint32(uint32(v.Uint())) } + func (c *uint32Converter) GoValueOf(v pref.Value) reflect.Value { return reflect.ValueOf(uint32(v.Uint())).Convert(c.goType) } + func (c *uint32Converter) IsValidPB(v pref.Value) bool { _, ok := v.Interface().(uint32) return ok } + func (c *uint32Converter) IsValidGo(v reflect.Value) bool { return v.IsValid() && v.Type() == c.goType } @@ -250,13 +262,16 @@ func (c *uint64Converter) PBValueOf(v reflect.Value) pref.Value { } return pref.ValueOfUint64(uint64(v.Uint())) } + func (c *uint64Converter) GoValueOf(v pref.Value) reflect.Value { return reflect.ValueOf(uint64(v.Uint())).Convert(c.goType) } + func (c *uint64Converter) IsValidPB(v pref.Value) bool { _, ok := v.Interface().(uint64) return ok } + func (c *uint64Converter) IsValidGo(v reflect.Value) bool { return v.IsValid() && v.Type() == c.goType } @@ -274,13 +289,16 @@ func (c *float32Converter) PBValueOf(v reflect.Value) pref.Value { } return pref.ValueOfFloat32(float32(v.Float())) } + func (c *float32Converter) GoValueOf(v pref.Value) reflect.Value { return reflect.ValueOf(float32(v.Float())).Convert(c.goType) } + func (c *float32Converter) IsValidPB(v pref.Value) bool { _, ok := v.Interface().(float32) return ok } + func (c *float32Converter) IsValidGo(v reflect.Value) bool { return v.IsValid() && v.Type() == c.goType } @@ -298,13 +316,16 @@ func (c *float64Converter) PBValueOf(v reflect.Value) pref.Value { } return pref.ValueOfFloat64(float64(v.Float())) } + func (c *float64Converter) GoValueOf(v pref.Value) reflect.Value { return reflect.ValueOf(float64(v.Float())).Convert(c.goType) } + func (c *float64Converter) IsValidPB(v pref.Value) bool { _, ok := v.Interface().(float64) return ok } + func (c *float64Converter) IsValidGo(v reflect.Value) bool { return v.IsValid() && v.Type() == c.goType } @@ -322,6 +343,7 @@ func (c *stringConverter) PBValueOf(v reflect.Value) pref.Value { } return pref.ValueOfString(v.Convert(stringType).String()) } + func (c *stringConverter) GoValueOf(v pref.Value) reflect.Value { // pref.Value.String never panics, so we go through an interface // conversion here to check the type. @@ -331,10 +353,12 @@ func (c *stringConverter) GoValueOf(v pref.Value) reflect.Value { } return reflect.ValueOf(s).Convert(c.goType) } + func (c *stringConverter) IsValidPB(v pref.Value) bool { _, ok := v.Interface().(string) return ok } + func (c *stringConverter) IsValidGo(v reflect.Value) bool { return v.IsValid() && v.Type() == c.goType } @@ -355,13 +379,16 @@ func (c *bytesConverter) PBValueOf(v reflect.Value) pref.Value { } return pref.ValueOfBytes(v.Convert(bytesType).Bytes()) } + func (c *bytesConverter) GoValueOf(v pref.Value) reflect.Value { return reflect.ValueOf(v.Bytes()).Convert(c.goType) } + func (c *bytesConverter) IsValidPB(v pref.Value) bool { _, ok := v.Interface().([]byte) return ok } + func (c *bytesConverter) IsValidGo(v reflect.Value) bool { return v.IsValid() && v.Type() == c.goType } diff --git a/vendor/google.golang.org/protobuf/internal/impl/convert_list.go b/vendor/google.golang.org/protobuf/internal/impl/convert_list.go index 6fccab52..da176d97 100644 --- a/vendor/google.golang.org/protobuf/internal/impl/convert_list.go +++ b/vendor/google.golang.org/protobuf/internal/impl/convert_list.go @@ -110,15 +110,19 @@ func (ls *listReflect) Len() int { } return ls.v.Elem().Len() } + func (ls *listReflect) Get(i int) pref.Value { return ls.conv.PBValueOf(ls.v.Elem().Index(i)) } + func (ls *listReflect) Set(i int, v pref.Value) { ls.v.Elem().Index(i).Set(ls.conv.GoValueOf(v)) } + func (ls *listReflect) Append(v pref.Value) { ls.v.Elem().Set(reflect.Append(ls.v.Elem(), ls.conv.GoValueOf(v))) } + func (ls *listReflect) AppendMutable() pref.Value { if _, ok := ls.conv.(*messageConverter); !ok { panic("invalid AppendMutable on list with non-message type") @@ -127,15 +131,19 @@ func (ls *listReflect) AppendMutable() pref.Value { ls.Append(v) return v } + func (ls *listReflect) Truncate(i int) { ls.v.Elem().Set(ls.v.Elem().Slice(0, i)) } + func (ls *listReflect) NewElement() pref.Value { return ls.conv.New() } + func (ls *listReflect) IsValid() bool { return !ls.v.IsNil() } + func (ls *listReflect) protoUnwrap() interface{} { return ls.v.Interface() } diff --git a/vendor/google.golang.org/protobuf/internal/impl/convert_map.go b/vendor/google.golang.org/protobuf/internal/impl/convert_map.go index de06b259..e37d5593 100644 --- a/vendor/google.golang.org/protobuf/internal/impl/convert_map.go +++ b/vendor/google.golang.org/protobuf/internal/impl/convert_map.go @@ -67,11 +67,13 @@ type mapReflect struct { func (ms *mapReflect) Len() int { return ms.v.Len() } + func (ms *mapReflect) Has(k pref.MapKey) bool { rk := ms.keyConv.GoValueOf(k.Value()) rv := ms.v.MapIndex(rk) return rv.IsValid() } + func (ms *mapReflect) Get(k pref.MapKey) pref.Value { rk := ms.keyConv.GoValueOf(k.Value()) rv := ms.v.MapIndex(rk) @@ -80,15 +82,18 @@ func (ms *mapReflect) Get(k pref.MapKey) pref.Value { } return ms.valConv.PBValueOf(rv) } + func (ms *mapReflect) Set(k pref.MapKey, v pref.Value) { rk := ms.keyConv.GoValueOf(k.Value()) rv := ms.valConv.GoValueOf(v) ms.v.SetMapIndex(rk, rv) } + func (ms *mapReflect) Clear(k pref.MapKey) { rk := ms.keyConv.GoValueOf(k.Value()) ms.v.SetMapIndex(rk, reflect.Value{}) } + func (ms *mapReflect) Mutable(k pref.MapKey) pref.Value { if _, ok := ms.valConv.(*messageConverter); !ok { panic("invalid Mutable on map with non-message value type") @@ -100,6 +105,7 @@ func (ms *mapReflect) Mutable(k pref.MapKey) pref.Value { } return v } + func (ms *mapReflect) Range(f func(pref.MapKey, pref.Value) bool) { iter := mapRange(ms.v) for iter.Next() { @@ -110,12 +116,15 @@ func (ms *mapReflect) Range(f func(pref.MapKey, pref.Value) bool) { } } } + func (ms *mapReflect) NewValue() pref.Value { return ms.valConv.New() } + func (ms *mapReflect) IsValid() bool { return !ms.v.IsNil() } + func (ms *mapReflect) protoUnwrap() interface{} { return ms.v.Interface() } diff --git a/vendor/google.golang.org/protobuf/internal/impl/extension.go b/vendor/google.golang.org/protobuf/internal/impl/extension.go index e904fd99..fdd53c6f 100644 --- a/vendor/google.golang.org/protobuf/internal/impl/extension.go +++ b/vendor/google.golang.org/protobuf/internal/impl/extension.go @@ -92,21 +92,27 @@ func InitExtensionInfo(xi *ExtensionInfo, xd pref.ExtensionDescriptor, goType re func (xi *ExtensionInfo) New() pref.Value { return xi.lazyInit().New() } + func (xi *ExtensionInfo) Zero() pref.Value { return xi.lazyInit().Zero() } + func (xi *ExtensionInfo) ValueOf(v interface{}) pref.Value { return xi.lazyInit().PBValueOf(reflect.ValueOf(v)) } + func (xi *ExtensionInfo) InterfaceOf(v pref.Value) interface{} { return xi.lazyInit().GoValueOf(v).Interface() } + func (xi *ExtensionInfo) IsValidValue(v pref.Value) bool { return xi.lazyInit().IsValidPB(v) } + func (xi *ExtensionInfo) IsValidInterface(v interface{}) bool { return xi.lazyInit().IsValidGo(reflect.ValueOf(v)) } + func (xi *ExtensionInfo) TypeDescriptor() pref.ExtensionTypeDescriptor { if atomic.LoadUint32(&xi.init) < extensionInfoDescInit { xi.lazyInitSlow() @@ -151,6 +157,7 @@ type extensionTypeDescriptor struct { func (xtd *extensionTypeDescriptor) Type() pref.ExtensionType { return xtd.xi } + func (xtd *extensionTypeDescriptor) Descriptor() pref.ExtensionDescriptor { return xtd.ExtensionDescriptor } diff --git a/vendor/google.golang.org/protobuf/internal/impl/legacy_enum.go b/vendor/google.golang.org/protobuf/internal/impl/legacy_enum.go index f7d7ffb5..111f0fcf 100644 --- a/vendor/google.golang.org/protobuf/internal/impl/legacy_enum.go +++ b/vendor/google.golang.org/protobuf/internal/impl/legacy_enum.go @@ -76,6 +76,7 @@ func (t *legacyEnumType) New(n pref.EnumNumber) pref.Enum { t.m.Store(n, e) return e } + func (t *legacyEnumType) Descriptor() pref.EnumDescriptor { return t.desc } @@ -89,15 +90,19 @@ type legacyEnumWrapper struct { func (e *legacyEnumWrapper) Descriptor() pref.EnumDescriptor { return e.pbTyp.Descriptor() } + func (e *legacyEnumWrapper) Type() pref.EnumType { return e.pbTyp } + func (e *legacyEnumWrapper) Number() pref.EnumNumber { return e.num } + func (e *legacyEnumWrapper) ProtoReflect() pref.Enum { return e } + func (e *legacyEnumWrapper) protoUnwrap() interface{} { v := reflect.New(e.goTyp).Elem() v.SetInt(int64(e.num)) diff --git a/vendor/google.golang.org/protobuf/internal/impl/legacy_export.go b/vendor/google.golang.org/protobuf/internal/impl/legacy_export.go index c3d741c2..8f9be08e 100644 --- a/vendor/google.golang.org/protobuf/internal/impl/legacy_export.go +++ b/vendor/google.golang.org/protobuf/internal/impl/legacy_export.go @@ -60,7 +60,7 @@ func (Export) UnmarshalJSONEnum(ed pref.EnumDescriptor, b []byte) (pref.EnumNumb // The current implementation does no compression. func (Export) CompressGZIP(in []byte) (out []byte) { // RFC 1952, section 2.3.1. - var gzipHeader = [10]byte{0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff} + gzipHeader := [10]byte{0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff} // RFC 1951, section 3.2.4. var blockHeader [5]byte diff --git a/vendor/google.golang.org/protobuf/internal/impl/legacy_file.go b/vendor/google.golang.org/protobuf/internal/impl/legacy_file.go index 9ab09108..7ea40ec8 100644 --- a/vendor/google.golang.org/protobuf/internal/impl/legacy_file.go +++ b/vendor/google.golang.org/protobuf/internal/impl/legacy_file.go @@ -73,9 +73,11 @@ type resolverOnly struct { func (r resolverOnly) FindFileByPath(path string) (protoreflect.FileDescriptor, error) { return r.reg.FindFileByPath(path) } + func (r resolverOnly) FindDescriptorByName(name protoreflect.FullName) (protoreflect.Descriptor, error) { return r.reg.FindDescriptorByName(name) } + func (resolverOnly) RegisterFile(protoreflect.FileDescriptor) error { return nil } diff --git a/vendor/google.golang.org/protobuf/internal/impl/legacy_message.go b/vendor/google.golang.org/protobuf/internal/impl/legacy_message.go index 06c68e11..19e9e60c 100644 --- a/vendor/google.golang.org/protobuf/internal/impl/legacy_message.go +++ b/vendor/google.golang.org/protobuf/internal/impl/legacy_message.go @@ -81,6 +81,7 @@ var legacyMessageDescCache sync.Map // map[reflect.Type]protoreflect.MessageDesc func LegacyLoadMessageDesc(t reflect.Type) pref.MessageDescriptor { return legacyLoadMessageDesc(t, "") } + func legacyLoadMessageDesc(t reflect.Type, name pref.FullName) pref.MessageDescriptor { // Fast-path: check if a MessageDescriptor is cached for this concrete type. if mi, ok := legacyMessageDescCache.Load(t); ok { @@ -159,6 +160,7 @@ func aberrantLoadMessageDesc(t reflect.Type, name pref.FullName) pref.MessageDes } return aberrantLoadMessageDescReentrant(t, name) } + func aberrantLoadMessageDescReentrant(t reflect.Type, name pref.FullName) pref.MessageDescriptor { // Fast-path: check if an MessageDescriptor is cached for this concrete type. if md, ok := aberrantMessageDescCache[t]; ok { @@ -424,12 +426,15 @@ type aberrantMessageType struct { func (mt aberrantMessageType) New() pref.Message { return aberrantMessage{reflect.Zero(mt.t)} } + func (mt aberrantMessageType) Zero() pref.Message { return aberrantMessage{reflect.Zero(mt.t)} } + func (mt aberrantMessageType) GoType() reflect.Type { return mt.t } + func (mt aberrantMessageType) Descriptor() pref.MessageDescriptor { return LegacyLoadMessageDesc(mt.t) } @@ -450,53 +455,69 @@ func (m aberrantMessage) ProtoReflect() pref.Message { func (m aberrantMessage) Descriptor() pref.MessageDescriptor { return LegacyLoadMessageDesc(m.v.Type()) } + func (m aberrantMessage) Type() pref.MessageType { return aberrantMessageType{m.v.Type()} } + func (m aberrantMessage) New() pref.Message { return aberrantMessage{reflect.Zero(m.v.Type())} } + func (m aberrantMessage) Interface() pref.ProtoMessage { return m } + func (m aberrantMessage) Range(f func(pref.FieldDescriptor, pref.Value) bool) { } + func (m aberrantMessage) Has(pref.FieldDescriptor) bool { panic("invalid field descriptor") } + func (m aberrantMessage) Clear(pref.FieldDescriptor) { panic("invalid field descriptor") } + func (m aberrantMessage) Get(pref.FieldDescriptor) pref.Value { panic("invalid field descriptor") } + func (m aberrantMessage) Set(pref.FieldDescriptor, pref.Value) { panic("invalid field descriptor") } + func (m aberrantMessage) Mutable(pref.FieldDescriptor) pref.Value { panic("invalid field descriptor") } + func (m aberrantMessage) NewField(pref.FieldDescriptor) pref.Value { panic("invalid field descriptor") } + func (m aberrantMessage) WhichOneof(pref.OneofDescriptor) pref.FieldDescriptor { panic("invalid oneof descriptor") } + func (m aberrantMessage) GetUnknown() pref.RawFields { return nil } + func (m aberrantMessage) SetUnknown(pref.RawFields) { // SetUnknown discards its input on messages which don't support unknown field storage. } + func (m aberrantMessage) IsValid() bool { // An invalid message is a read-only, empty message. Since we don't know anything // about the alleged contents of this message, we can't say with confidence that // it is invalid in this sense. Therefore, report it as valid. return true } + func (m aberrantMessage) ProtoMethods() *piface.Methods { return legacyProtoMethods } + func (m aberrantMessage) protoUnwrap() interface{} { return m.v.Interface() } diff --git a/vendor/google.golang.org/protobuf/internal/impl/merge_gen.go b/vendor/google.golang.org/protobuf/internal/impl/merge_gen.go index 8816c274..81982688 100644 --- a/vendor/google.golang.org/protobuf/internal/impl/merge_gen.go +++ b/vendor/google.golang.org/protobuf/internal/impl/merge_gen.go @@ -6,8 +6,6 @@ package impl -import () - func mergeBool(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { *dst.Bool() = *src.Bool() } diff --git a/vendor/google.golang.org/protobuf/internal/impl/message.go b/vendor/google.golang.org/protobuf/internal/impl/message.go index 7dd994bd..cff37bbf 100644 --- a/vendor/google.golang.org/protobuf/internal/impl/message.go +++ b/vendor/google.golang.org/protobuf/internal/impl/message.go @@ -209,6 +209,7 @@ fieldLoop: func (mi *MessageInfo) New() protoreflect.Message { return mi.MessageOf(reflect.New(mi.GoReflectType.Elem()).Interface()) } + func (mi *MessageInfo) Zero() protoreflect.Message { return mi.MessageOf(reflect.Zero(mi.GoReflectType).Interface()) } diff --git a/vendor/google.golang.org/protobuf/internal/impl/message_reflect.go b/vendor/google.golang.org/protobuf/internal/impl/message_reflect.go index 0f4b8db7..c659006e 100644 --- a/vendor/google.golang.org/protobuf/internal/impl/message_reflect.go +++ b/vendor/google.golang.org/protobuf/internal/impl/message_reflect.go @@ -156,6 +156,7 @@ func (m *extensionMap) Range(f func(pref.FieldDescriptor, pref.Value) bool) { } } } + func (m *extensionMap) Has(xt pref.ExtensionType) (ok bool) { if m == nil { return false @@ -175,9 +176,11 @@ func (m *extensionMap) Has(xt pref.ExtensionType) (ok bool) { } return true } + func (m *extensionMap) Clear(xt pref.ExtensionType) { delete(*m, int32(xt.TypeDescriptor().Number())) } + func (m *extensionMap) Get(xt pref.ExtensionType) pref.Value { xd := xt.TypeDescriptor() if m != nil { @@ -187,6 +190,7 @@ func (m *extensionMap) Get(xt pref.ExtensionType) pref.Value { } return xt.Zero() } + func (m *extensionMap) Set(xt pref.ExtensionType, v pref.Value) { xd := xt.TypeDescriptor() isValid := true @@ -211,6 +215,7 @@ func (m *extensionMap) Set(xt pref.ExtensionType, v pref.Value) { x.Set(xt, v) (*m)[int32(xd.Number())] = x } + func (m *extensionMap) Mutable(xt pref.ExtensionType) pref.Value { xd := xt.TypeDescriptor() if xd.Kind() != pref.MessageKind && xd.Kind() != pref.GroupKind && !xd.IsList() && !xd.IsMap() { @@ -323,6 +328,7 @@ func (m *messageReflectWrapper) messageInfo() *MessageInfo { return m.mi } func (m *messageIfaceWrapper) ProtoReflect() pref.Message { return (*messageReflectWrapper)(m) } + func (m *messageIfaceWrapper) protoUnwrap() interface{} { return m.p.AsIfaceOf(m.mi.GoReflectType.Elem()) } diff --git a/vendor/google.golang.org/protobuf/internal/impl/message_reflect_gen.go b/vendor/google.golang.org/protobuf/internal/impl/message_reflect_gen.go index 741d6e5b..73b5b470 100644 --- a/vendor/google.golang.org/protobuf/internal/impl/message_reflect_gen.go +++ b/vendor/google.golang.org/protobuf/internal/impl/message_reflect_gen.go @@ -14,18 +14,23 @@ import ( func (m *messageState) Descriptor() protoreflect.MessageDescriptor { return m.messageInfo().Desc } + func (m *messageState) Type() protoreflect.MessageType { return m.messageInfo() } + func (m *messageState) New() protoreflect.Message { return m.messageInfo().New() } + func (m *messageState) Interface() protoreflect.ProtoMessage { return m.protoUnwrap().(protoreflect.ProtoMessage) } + func (m *messageState) protoUnwrap() interface{} { return m.pointer().AsIfaceOf(m.messageInfo().GoReflectType.Elem()) } + func (m *messageState) ProtoMethods() *protoiface.Methods { m.messageInfo().init() return &m.messageInfo().methods @@ -61,6 +66,7 @@ func (m *messageState) Range(f func(protoreflect.FieldDescriptor, protoreflect.V } m.messageInfo().extensionMap(m.pointer()).Range(f) } + func (m *messageState) Has(fd protoreflect.FieldDescriptor) bool { m.messageInfo().init() if fi, xt := m.messageInfo().checkField(fd); fi != nil { @@ -69,6 +75,7 @@ func (m *messageState) Has(fd protoreflect.FieldDescriptor) bool { return m.messageInfo().extensionMap(m.pointer()).Has(xt) } } + func (m *messageState) Clear(fd protoreflect.FieldDescriptor) { m.messageInfo().init() if fi, xt := m.messageInfo().checkField(fd); fi != nil { @@ -77,6 +84,7 @@ func (m *messageState) Clear(fd protoreflect.FieldDescriptor) { m.messageInfo().extensionMap(m.pointer()).Clear(xt) } } + func (m *messageState) Get(fd protoreflect.FieldDescriptor) protoreflect.Value { m.messageInfo().init() if fi, xt := m.messageInfo().checkField(fd); fi != nil { @@ -85,6 +93,7 @@ func (m *messageState) Get(fd protoreflect.FieldDescriptor) protoreflect.Value { return m.messageInfo().extensionMap(m.pointer()).Get(xt) } } + func (m *messageState) Set(fd protoreflect.FieldDescriptor, v protoreflect.Value) { m.messageInfo().init() if fi, xt := m.messageInfo().checkField(fd); fi != nil { @@ -93,6 +102,7 @@ func (m *messageState) Set(fd protoreflect.FieldDescriptor, v protoreflect.Value m.messageInfo().extensionMap(m.pointer()).Set(xt, v) } } + func (m *messageState) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { m.messageInfo().init() if fi, xt := m.messageInfo().checkField(fd); fi != nil { @@ -101,6 +111,7 @@ func (m *messageState) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Val return m.messageInfo().extensionMap(m.pointer()).Mutable(xt) } } + func (m *messageState) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { m.messageInfo().init() if fi, xt := m.messageInfo().checkField(fd); fi != nil { @@ -109,6 +120,7 @@ func (m *messageState) NewField(fd protoreflect.FieldDescriptor) protoreflect.Va return xt.New() } } + func (m *messageState) WhichOneof(od protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { m.messageInfo().init() if oi := m.messageInfo().oneofs[od.Name()]; oi != nil && oi.oneofDesc == od { @@ -116,14 +128,17 @@ func (m *messageState) WhichOneof(od protoreflect.OneofDescriptor) protoreflect. } panic("invalid oneof descriptor " + string(od.FullName()) + " for message " + string(m.Descriptor().FullName())) } + func (m *messageState) GetUnknown() protoreflect.RawFields { m.messageInfo().init() return m.messageInfo().getUnknown(m.pointer()) } + func (m *messageState) SetUnknown(b protoreflect.RawFields) { m.messageInfo().init() m.messageInfo().setUnknown(m.pointer(), b) } + func (m *messageState) IsValid() bool { return !m.pointer().IsNil() } @@ -131,21 +146,26 @@ func (m *messageState) IsValid() bool { func (m *messageReflectWrapper) Descriptor() protoreflect.MessageDescriptor { return m.messageInfo().Desc } + func (m *messageReflectWrapper) Type() protoreflect.MessageType { return m.messageInfo() } + func (m *messageReflectWrapper) New() protoreflect.Message { return m.messageInfo().New() } + func (m *messageReflectWrapper) Interface() protoreflect.ProtoMessage { if m, ok := m.protoUnwrap().(protoreflect.ProtoMessage); ok { return m } return (*messageIfaceWrapper)(m) } + func (m *messageReflectWrapper) protoUnwrap() interface{} { return m.pointer().AsIfaceOf(m.messageInfo().GoReflectType.Elem()) } + func (m *messageReflectWrapper) ProtoMethods() *protoiface.Methods { m.messageInfo().init() return &m.messageInfo().methods @@ -181,6 +201,7 @@ func (m *messageReflectWrapper) Range(f func(protoreflect.FieldDescriptor, proto } m.messageInfo().extensionMap(m.pointer()).Range(f) } + func (m *messageReflectWrapper) Has(fd protoreflect.FieldDescriptor) bool { m.messageInfo().init() if fi, xt := m.messageInfo().checkField(fd); fi != nil { @@ -189,6 +210,7 @@ func (m *messageReflectWrapper) Has(fd protoreflect.FieldDescriptor) bool { return m.messageInfo().extensionMap(m.pointer()).Has(xt) } } + func (m *messageReflectWrapper) Clear(fd protoreflect.FieldDescriptor) { m.messageInfo().init() if fi, xt := m.messageInfo().checkField(fd); fi != nil { @@ -197,6 +219,7 @@ func (m *messageReflectWrapper) Clear(fd protoreflect.FieldDescriptor) { m.messageInfo().extensionMap(m.pointer()).Clear(xt) } } + func (m *messageReflectWrapper) Get(fd protoreflect.FieldDescriptor) protoreflect.Value { m.messageInfo().init() if fi, xt := m.messageInfo().checkField(fd); fi != nil { @@ -205,6 +228,7 @@ func (m *messageReflectWrapper) Get(fd protoreflect.FieldDescriptor) protoreflec return m.messageInfo().extensionMap(m.pointer()).Get(xt) } } + func (m *messageReflectWrapper) Set(fd protoreflect.FieldDescriptor, v protoreflect.Value) { m.messageInfo().init() if fi, xt := m.messageInfo().checkField(fd); fi != nil { @@ -213,6 +237,7 @@ func (m *messageReflectWrapper) Set(fd protoreflect.FieldDescriptor, v protorefl m.messageInfo().extensionMap(m.pointer()).Set(xt, v) } } + func (m *messageReflectWrapper) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { m.messageInfo().init() if fi, xt := m.messageInfo().checkField(fd); fi != nil { @@ -221,6 +246,7 @@ func (m *messageReflectWrapper) Mutable(fd protoreflect.FieldDescriptor) protore return m.messageInfo().extensionMap(m.pointer()).Mutable(xt) } } + func (m *messageReflectWrapper) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { m.messageInfo().init() if fi, xt := m.messageInfo().checkField(fd); fi != nil { @@ -229,6 +255,7 @@ func (m *messageReflectWrapper) NewField(fd protoreflect.FieldDescriptor) protor return xt.New() } } + func (m *messageReflectWrapper) WhichOneof(od protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { m.messageInfo().init() if oi := m.messageInfo().oneofs[od.Name()]; oi != nil && oi.oneofDesc == od { @@ -236,14 +263,17 @@ func (m *messageReflectWrapper) WhichOneof(od protoreflect.OneofDescriptor) prot } panic("invalid oneof descriptor " + string(od.FullName()) + " for message " + string(m.Descriptor().FullName())) } + func (m *messageReflectWrapper) GetUnknown() protoreflect.RawFields { m.messageInfo().init() return m.messageInfo().getUnknown(m.pointer()) } + func (m *messageReflectWrapper) SetUnknown(b protoreflect.RawFields) { m.messageInfo().init() m.messageInfo().setUnknown(m.pointer(), b) } + func (m *messageReflectWrapper) IsValid() bool { return !m.pointer().IsNil() } diff --git a/vendor/google.golang.org/protobuf/internal/impl/pointer_unsafe.go b/vendor/google.golang.org/protobuf/internal/impl/pointer_unsafe.go index 088aa85d..76b02cb7 100644 --- a/vendor/google.golang.org/protobuf/internal/impl/pointer_unsafe.go +++ b/vendor/google.golang.org/protobuf/internal/impl/pointer_unsafe.go @@ -143,10 +143,12 @@ func (Export) MessageStateOf(p Pointer) *messageState { // Super-tricky - see documentation on MessageState. return (*messageState)(unsafe.Pointer(p)) } + func (ms *messageState) pointer() pointer { // Super-tricky - see documentation on MessageState. return pointer{p: unsafe.Pointer(ms)} } + func (ms *messageState) messageInfo() *MessageInfo { mi := ms.LoadMessageInfo() if mi == nil { @@ -154,9 +156,11 @@ func (ms *messageState) messageInfo() *MessageInfo { } return mi } + func (ms *messageState) LoadMessageInfo() *MessageInfo { return (*MessageInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&ms.atomicMessageInfo)))) } + func (ms *messageState) StoreMessageInfo(mi *MessageInfo) { atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&ms.atomicMessageInfo)), unsafe.Pointer(mi)) } diff --git a/vendor/google.golang.org/protobuf/internal/set/ints.go b/vendor/google.golang.org/protobuf/internal/set/ints.go index d3d7f89a..bed0e308 100644 --- a/vendor/google.golang.org/protobuf/internal/set/ints.go +++ b/vendor/google.golang.org/protobuf/internal/set/ints.go @@ -13,12 +13,15 @@ type int64s uint64 func (bs *int64s) Len() int { return bits.OnesCount64(uint64(*bs)) } + func (bs *int64s) Has(n uint64) bool { return uint64(*bs)&(uint64(1)< 0 } + func (bs *int64s) Set(n uint64) { *(*uint64)(bs) |= uint64(1) << n } + func (bs *int64s) Clear(n uint64) { *(*uint64)(bs) &^= uint64(1) << n } @@ -32,6 +35,7 @@ type Ints struct { func (bs *Ints) Len() int { return bs.lo.Len() + len(bs.hi) } + func (bs *Ints) Has(n uint64) bool { if n < 64 { return bs.lo.Has(n) @@ -39,6 +43,7 @@ func (bs *Ints) Has(n uint64) bool { _, ok := bs.hi[n] return ok } + func (bs *Ints) Set(n uint64) { if n < 64 { bs.lo.Set(n) @@ -49,6 +54,7 @@ func (bs *Ints) Set(n uint64) { } bs.hi[n] = struct{}{} } + func (bs *Ints) Clear(n uint64) { if n < 64 { bs.lo.Clear(n) diff --git a/vendor/google.golang.org/protobuf/internal/strs/strings.go b/vendor/google.golang.org/protobuf/internal/strs/strings.go index 0b74e765..0b802250 100644 --- a/vendor/google.golang.org/protobuf/internal/strs/strings.go +++ b/vendor/google.golang.org/protobuf/internal/strs/strings.go @@ -188,9 +188,11 @@ func TrimEnumPrefix(s, prefix string) string { func isASCIILower(c byte) bool { return 'a' <= c && c <= 'z' } + func isASCIIUpper(c byte) bool { return 'A' <= c && c <= 'Z' } + func isASCIIDigit(c byte) bool { return '0' <= c && c <= '9' } diff --git a/vendor/google.golang.org/protobuf/reflect/protoreflect/value_pure.go b/vendor/google.golang.org/protobuf/reflect/protoreflect/value_pure.go index 918e685e..b582b6c6 100644 --- a/vendor/google.golang.org/protobuf/reflect/protoreflect/value_pure.go +++ b/vendor/google.golang.org/protobuf/reflect/protoreflect/value_pure.go @@ -41,9 +41,11 @@ type value struct { func valueOfString(v string) Value { return Value{typ: stringType, str: v} } + func valueOfBytes(v []byte) Value { return Value{typ: bytesType, bin: v} } + func valueOfIface(v interface{}) Value { return Value{typ: ifaceType, iface: v} } @@ -51,9 +53,11 @@ func valueOfIface(v interface{}) Value { func (v Value) getString() string { return v.str } + func (v Value) getBytes() []byte { return v.bin } + func (v Value) getIface() interface{} { return v.iface } diff --git a/vendor/google.golang.org/protobuf/reflect/protoreflect/value_unsafe.go b/vendor/google.golang.org/protobuf/reflect/protoreflect/value_unsafe.go index c45debdc..34f2f4ab 100644 --- a/vendor/google.golang.org/protobuf/reflect/protoreflect/value_unsafe.go +++ b/vendor/google.golang.org/protobuf/reflect/protoreflect/value_unsafe.go @@ -75,10 +75,12 @@ func valueOfString(v string) Value { p := (*stringHeader)(unsafe.Pointer(&v)) return Value{typ: stringType, ptr: p.Data, num: uint64(len(v))} } + func valueOfBytes(v []byte) Value { p := (*sliceHeader)(unsafe.Pointer(&v)) return Value{typ: bytesType, ptr: p.Data, num: uint64(len(v))} } + func valueOfIface(v interface{}) Value { p := (*ifaceHeader)(unsafe.Pointer(&v)) return Value{typ: p.Type, ptr: p.Data} @@ -88,10 +90,12 @@ func (v Value) getString() (x string) { *(*stringHeader)(unsafe.Pointer(&x)) = stringHeader{Data: v.ptr, Len: int(v.num)} return x } + func (v Value) getBytes() (x []byte) { *(*sliceHeader)(unsafe.Pointer(&x)) = sliceHeader{Data: v.ptr, Len: int(v.num), Cap: int(v.num)} return x } + func (v Value) getIface() (x interface{}) { *(*ifaceHeader)(unsafe.Pointer(&x)) = ifaceHeader{Type: v.typ, Data: v.ptr} return x diff --git a/vendor/gopkg.in/go-playground/validator.v9/baked_in.go b/vendor/gopkg.in/go-playground/validator.v9/baked_in.go index cfc5686d..db81270d 100644 --- a/vendor/gopkg.in/go-playground/validator.v9/baked_in.go +++ b/vendor/gopkg.in/go-playground/validator.v9/baked_in.go @@ -169,8 +169,10 @@ var ( } ) -var oneofValsCache = map[string][]string{} -var oneofValsCacheRWLock = sync.RWMutex{} +var ( + oneofValsCache = map[string][]string{} + oneofValsCacheRWLock = sync.RWMutex{} +) func parseOneOfParam2(s string) []string { oneofValsCacheRWLock.RLock() @@ -223,7 +225,6 @@ func isOneOf(fl FieldLevel) bool { // isUnique is the validation function for validating if each array|slice|map value is unique func isUnique(fl FieldLevel) bool { - field := fl.Field() param := fl.Param() v := reflect.ValueOf(struct{}{}) @@ -263,7 +264,6 @@ func isUnique(fl FieldLevel) bool { // IsMAC is the validation function for validating if the field's value is a valid MAC address. func isMAC(fl FieldLevel) bool { - _, err := net.ParseMAC(fl.Field().String()) return err == nil @@ -271,7 +271,6 @@ func isMAC(fl FieldLevel) bool { // IsCIDRv4 is the validation function for validating if the field's value is a valid v4 CIDR address. func isCIDRv4(fl FieldLevel) bool { - ip, _, err := net.ParseCIDR(fl.Field().String()) return err == nil && ip.To4() != nil @@ -279,7 +278,6 @@ func isCIDRv4(fl FieldLevel) bool { // IsCIDRv6 is the validation function for validating if the field's value is a valid v6 CIDR address. func isCIDRv6(fl FieldLevel) bool { - ip, _, err := net.ParseCIDR(fl.Field().String()) return err == nil && ip.To4() == nil @@ -287,7 +285,6 @@ func isCIDRv6(fl FieldLevel) bool { // IsCIDR is the validation function for validating if the field's value is a valid v4 or v6 CIDR address. func isCIDR(fl FieldLevel) bool { - _, _, err := net.ParseCIDR(fl.Field().String()) return err == nil @@ -295,7 +292,6 @@ func isCIDR(fl FieldLevel) bool { // IsIPv4 is the validation function for validating if a value is a valid v4 IP address. func isIPv4(fl FieldLevel) bool { - ip := net.ParseIP(fl.Field().String()) return ip != nil && ip.To4() != nil @@ -303,7 +299,6 @@ func isIPv4(fl FieldLevel) bool { // IsIPv6 is the validation function for validating if the field's value is a valid v6 IP address. func isIPv6(fl FieldLevel) bool { - ip := net.ParseIP(fl.Field().String()) return ip != nil && ip.To4() == nil @@ -311,7 +306,6 @@ func isIPv6(fl FieldLevel) bool { // IsIP is the validation function for validating if the field's value is a valid v4 or v6 IP address. func isIP(fl FieldLevel) bool { - ip := net.ParseIP(fl.Field().String()) return ip != nil @@ -319,7 +313,6 @@ func isIP(fl FieldLevel) bool { // IsSSN is the validation function for validating if the field's value is a valid SSN. func isSSN(fl FieldLevel) bool { - field := fl.Field() if field.Len() != 11 { @@ -377,7 +370,6 @@ func isLatitude(fl FieldLevel) bool { // IsDataURI is the validation function for validating if the field's value is a valid data URI. func isDataURI(fl FieldLevel) bool { - uri := strings.SplitN(fl.Field().String(), ",", 2) if len(uri) != 2 { @@ -393,7 +385,6 @@ func isDataURI(fl FieldLevel) bool { // HasMultiByteCharacter is the validation function for validating if the field's value has a multi byte character. func hasMultiByteCharacter(fl FieldLevel) bool { - field := fl.Field() if field.Len() == 0 { @@ -460,7 +451,6 @@ func isISBN(fl FieldLevel) bool { // IsISBN13 is the validation function for validating if the field's value is a valid v13 ISBN. func isISBN13(fl FieldLevel) bool { - s := strings.Replace(strings.Replace(fl.Field().String(), "-", "", 4), " ", "", 4) if !iSBN13Regex.MatchString(s) { @@ -481,7 +471,6 @@ func isISBN13(fl FieldLevel) bool { // IsISBN10 is the validation function for validating if the field's value is a valid v10 ISBN. func isISBN10(fl FieldLevel) bool { - s := strings.Replace(strings.Replace(fl.Field().String(), "-", "", 3), " ", "", 3) if !iSBN10Regex.MatchString(s) { @@ -655,7 +644,6 @@ func excludes(fl FieldLevel) bool { // ContainsRune is the validation function for validating that the field's value contains the rune specified within the param. func containsRune(fl FieldLevel) bool { - r, _ := utf8.DecodeRuneInString(fl.Param()) return strings.ContainsRune(fl.Field().String(), r) @@ -708,7 +696,6 @@ func fieldExcludes(fl FieldLevel) bool { // IsNeField is the validation function for validating if the current field's value is not equal to the field specified by the param's value. func isNeField(fl FieldLevel) bool { - field := fl.Field() kind := field.Kind() @@ -762,7 +749,6 @@ func isNe(fl FieldLevel) bool { // IsLteCrossStructField is the validation function for validating if the current field's value is less than or equal to the field, within a separate struct, specified by the param's value. func isLteCrossStructField(fl FieldLevel) bool { - field := fl.Field() kind := field.Kind() @@ -810,7 +796,6 @@ func isLteCrossStructField(fl FieldLevel) bool { // IsLtCrossStructField is the validation function for validating if the current field's value is less than the field, within a separate struct, specified by the param's value. // NOTE: This is exposed for use within your own custom functions and not intended to be called directly. func isLtCrossStructField(fl FieldLevel) bool { - field := fl.Field() kind := field.Kind() @@ -857,7 +842,6 @@ func isLtCrossStructField(fl FieldLevel) bool { // IsGteCrossStructField is the validation function for validating if the current field's value is greater than or equal to the field, within a separate struct, specified by the param's value. func isGteCrossStructField(fl FieldLevel) bool { - field := fl.Field() kind := field.Kind() @@ -904,7 +888,6 @@ func isGteCrossStructField(fl FieldLevel) bool { // IsGtCrossStructField is the validation function for validating if the current field's value is greater than the field, within a separate struct, specified by the param's value. func isGtCrossStructField(fl FieldLevel) bool { - field := fl.Field() kind := field.Kind() @@ -951,7 +934,6 @@ func isGtCrossStructField(fl FieldLevel) bool { // IsNeCrossStructField is the validation function for validating that the current field's value is not equal to the field, within a separate struct, specified by the param's value. func isNeCrossStructField(fl FieldLevel) bool { - field := fl.Field() kind := field.Kind() @@ -998,7 +980,6 @@ func isNeCrossStructField(fl FieldLevel) bool { // IsEqCrossStructField is the validation function for validating that the current field's value is equal to the field, within a separate struct, specified by the param's value. func isEqCrossStructField(fl FieldLevel) bool { - field := fl.Field() kind := field.Kind() @@ -1045,7 +1026,6 @@ func isEqCrossStructField(fl FieldLevel) bool { // IsEqField is the validation function for validating if the current field's value is equal to the field specified by the param's value. func isEqField(fl FieldLevel) bool { - field := fl.Field() kind := field.Kind() @@ -1093,7 +1073,6 @@ func isEqField(fl FieldLevel) bool { // IsEq is the validation function for validating if the current field's value is equal to the param's value. func isEq(fl FieldLevel) bool { - field := fl.Field() param := fl.Param() @@ -1138,11 +1117,9 @@ func isBase64URL(fl FieldLevel) bool { // IsURI is the validation function for validating if the current field's value is a valid URI. func isURI(fl FieldLevel) bool { - field := fl.Field() switch field.Kind() { - case reflect.String: s := field.String() @@ -1167,11 +1144,9 @@ func isURI(fl FieldLevel) bool { // IsURL is the validation function for validating if the current field's value is a valid URL. func isURL(fl FieldLevel) bool { - field := fl.Field() switch field.Kind() { - case reflect.String: var i int @@ -1204,7 +1179,6 @@ func isUrnRFC2141(fl FieldLevel) bool { field := fl.Field() switch field.Kind() { - case reflect.String: str := field.String() @@ -1404,7 +1378,6 @@ func requiredWithoutAll(fl FieldLevel) bool { // IsGteField is the validation function for validating if the current field's value is greater than or equal to the field specified by the param's value. func isGteField(fl FieldLevel) bool { - field := fl.Field() kind := field.Kind() @@ -1451,7 +1424,6 @@ func isGteField(fl FieldLevel) bool { // IsGtField is the validation function for validating if the current field's value is greater than the field specified by the param's value. func isGtField(fl FieldLevel) bool { - field := fl.Field() kind := field.Kind() @@ -1498,7 +1470,6 @@ func isGtField(fl FieldLevel) bool { // IsGte is the validation function for validating if the current field's value is greater than or equal to the param's value. func isGte(fl FieldLevel) bool { - field := fl.Field() param := fl.Param() @@ -1545,7 +1516,6 @@ func isGte(fl FieldLevel) bool { // IsGt is the validation function for validating if the current field's value is greater than the param's value. func isGt(fl FieldLevel) bool { - field := fl.Field() param := fl.Param() @@ -1578,7 +1548,6 @@ func isGt(fl FieldLevel) bool { case reflect.Struct: if field.Type() == timeType { - return field.Interface().(time.Time).After(time.Now().UTC()) } } @@ -1588,7 +1557,6 @@ func isGt(fl FieldLevel) bool { // HasLengthOf is the validation function for validating if the current field's value is equal to the param's value. func hasLengthOf(fl FieldLevel) bool { - field := fl.Field() param := fl.Param() @@ -1630,7 +1598,6 @@ func hasMinOf(fl FieldLevel) bool { // IsLteField is the validation function for validating if the current field's value is less than or equal to the field specified by the param's value. func isLteField(fl FieldLevel) bool { - field := fl.Field() kind := field.Kind() @@ -1677,7 +1644,6 @@ func isLteField(fl FieldLevel) bool { // IsLtField is the validation function for validating if the current field's value is less than the field specified by the param's value. func isLtField(fl FieldLevel) bool { - field := fl.Field() kind := field.Kind() @@ -1724,7 +1690,6 @@ func isLtField(fl FieldLevel) bool { // IsLte is the validation function for validating if the current field's value is less than or equal to the param's value. func isLte(fl FieldLevel) bool { - field := fl.Field() param := fl.Param() @@ -1771,7 +1736,6 @@ func isLte(fl FieldLevel) bool { // IsLt is the validation function for validating if the current field's value is less than the param's value. func isLt(fl FieldLevel) bool { - field := fl.Field() param := fl.Param() @@ -1805,7 +1769,6 @@ func isLt(fl FieldLevel) bool { case reflect.Struct: if field.Type() == timeType { - return field.Interface().(time.Time).Before(time.Now().UTC()) } } @@ -1820,7 +1783,6 @@ func hasMaxOf(fl FieldLevel) bool { // IsTCP4AddrResolvable is the validation function for validating if the field's value is a resolvable tcp4 address. func isTCP4AddrResolvable(fl FieldLevel) bool { - if !isIP4Addr(fl) { return false } @@ -1831,7 +1793,6 @@ func isTCP4AddrResolvable(fl FieldLevel) bool { // IsTCP6AddrResolvable is the validation function for validating if the field's value is a resolvable tcp6 address. func isTCP6AddrResolvable(fl FieldLevel) bool { - if !isIP6Addr(fl) { return false } @@ -1843,7 +1804,6 @@ func isTCP6AddrResolvable(fl FieldLevel) bool { // IsTCPAddrResolvable is the validation function for validating if the field's value is a resolvable tcp address. func isTCPAddrResolvable(fl FieldLevel) bool { - if !isIP4Addr(fl) && !isIP6Addr(fl) { return false } @@ -1855,7 +1815,6 @@ func isTCPAddrResolvable(fl FieldLevel) bool { // IsUDP4AddrResolvable is the validation function for validating if the field's value is a resolvable udp4 address. func isUDP4AddrResolvable(fl FieldLevel) bool { - if !isIP4Addr(fl) { return false } @@ -1867,7 +1826,6 @@ func isUDP4AddrResolvable(fl FieldLevel) bool { // IsUDP6AddrResolvable is the validation function for validating if the field's value is a resolvable udp6 address. func isUDP6AddrResolvable(fl FieldLevel) bool { - if !isIP6Addr(fl) { return false } @@ -1879,7 +1837,6 @@ func isUDP6AddrResolvable(fl FieldLevel) bool { // IsUDPAddrResolvable is the validation function for validating if the field's value is a resolvable udp address. func isUDPAddrResolvable(fl FieldLevel) bool { - if !isIP4Addr(fl) && !isIP6Addr(fl) { return false } @@ -1891,7 +1848,6 @@ func isUDPAddrResolvable(fl FieldLevel) bool { // IsIP4AddrResolvable is the validation function for validating if the field's value is a resolvable ip4 address. func isIP4AddrResolvable(fl FieldLevel) bool { - if !isIPv4(fl) { return false } @@ -1903,7 +1859,6 @@ func isIP4AddrResolvable(fl FieldLevel) bool { // IsIP6AddrResolvable is the validation function for validating if the field's value is a resolvable ip6 address. func isIP6AddrResolvable(fl FieldLevel) bool { - if !isIPv6(fl) { return false } @@ -1915,7 +1870,6 @@ func isIP6AddrResolvable(fl FieldLevel) bool { // IsIPAddrResolvable is the validation function for validating if the field's value is a resolvable ip address. func isIPAddrResolvable(fl FieldLevel) bool { - if !isIP(fl) { return false } @@ -1927,14 +1881,12 @@ func isIPAddrResolvable(fl FieldLevel) bool { // IsUnixAddrResolvable is the validation function for validating if the field's value is a resolvable unix address. func isUnixAddrResolvable(fl FieldLevel) bool { - _, err := net.ResolveUnixAddr("unix", fl.Field().String()) return err == nil } func isIP4Addr(fl FieldLevel) bool { - val := fl.Field().String() if idx := strings.LastIndex(val, ":"); idx != -1 { @@ -1947,7 +1899,6 @@ func isIP4Addr(fl FieldLevel) bool { } func isIP6Addr(fl FieldLevel) bool { - val := fl.Field().String() if idx := strings.LastIndex(val, ":"); idx != -1 { diff --git a/vendor/gopkg.in/go-playground/validator.v9/errors.go b/vendor/gopkg.in/go-playground/validator.v9/errors.go index 46c24c9b..9f2d2538 100644 --- a/vendor/gopkg.in/go-playground/validator.v9/errors.go +++ b/vendor/gopkg.in/go-playground/validator.v9/errors.go @@ -24,7 +24,6 @@ type InvalidValidationError struct { // Error returns InvalidValidationError message func (e *InvalidValidationError) Error() string { - if e.Type == nil { return "validator: (nil)" } @@ -41,7 +40,6 @@ type ValidationErrors []FieldError // All information to create an error message specific to your application is contained within // the FieldError found within the ValidationErrors array func (ve ValidationErrors) Error() string { - buff := bytes.NewBufferString("") var fe *fieldError @@ -58,7 +56,6 @@ func (ve ValidationErrors) Error() string { // Translate translates all of the ValidationErrors func (ve ValidationErrors) Translate(ut ut.Translator) ValidationErrorsTranslations { - trans := make(ValidationErrorsTranslations) var fe *fieldError @@ -158,8 +155,10 @@ type FieldError interface { } // compile time interface checks -var _ FieldError = new(fieldError) -var _ error = new(fieldError) +var ( + _ FieldError = new(fieldError) + _ error = new(fieldError) +) // fieldError contains a single field's validation error along // with other properties that may be needed for error message creation @@ -204,7 +203,6 @@ func (fe *fieldError) StructNamespace() string { // Field returns the fields name with the tag name taking precedence over the // fields actual name. func (fe *fieldError) Field() string { - return fe.ns[len(fe.ns)-int(fe.fieldLen):] // // return fe.field // fld := fe.ns[len(fe.ns)-int(fe.fieldLen):] @@ -257,7 +255,6 @@ func (fe *fieldError) Error() string { // NOTE: is not registered translation can be found it returns the same // as calling fe.Error() func (fe *fieldError) Translate(ut ut.Translator) string { - m, ok := fe.v.transTagFunc[ut] if !ok { return fe.Error() diff --git a/vendor/gopkg.in/go-playground/validator.v9/struct_level.go b/vendor/gopkg.in/go-playground/validator.v9/struct_level.go index 57691ee3..5f555973 100644 --- a/vendor/gopkg.in/go-playground/validator.v9/struct_level.go +++ b/vendor/gopkg.in/go-playground/validator.v9/struct_level.go @@ -107,7 +107,6 @@ func (v *validate) ExtractType(field reflect.Value) (reflect.Value, reflect.Kind // ReportError reports an error just by passing the field and tag information func (v *validate) ReportError(field interface{}, fieldName, structFieldName, tag, param string) { - fv, kind, _ := v.extractTypeInternal(reflect.ValueOf(field), false) if len(structFieldName) == 0 { @@ -161,7 +160,6 @@ func (v *validate) ReportError(field interface{}, fieldName, structFieldName, ta // // NOTE: this function prepends the current namespace to the relative ones. func (v *validate) ReportValidationErrors(relativeNamespace, relativeStructNamespace string, errs ValidationErrors) { - var err *fieldError for i := 0; i < len(errs); i++ { diff --git a/vendor/gopkg.in/go-playground/validator.v9/util.go b/vendor/gopkg.in/go-playground/validator.v9/util.go index 71acbdc4..8951c747 100644 --- a/vendor/gopkg.in/go-playground/validator.v9/util.go +++ b/vendor/gopkg.in/go-playground/validator.v9/util.go @@ -10,7 +10,6 @@ import ( // It will dive into pointers, customTypes and return you the // underlying value and it's kind. func (v *validate) extractTypeInternal(current reflect.Value, nullable bool) (reflect.Value, reflect.Kind, bool) { - BEGIN: switch current.Kind() { case reflect.Ptr: @@ -41,7 +40,6 @@ BEGIN: default: if v.v.hasCustomFuncs { - if fn, ok := v.v.customFuncs[current.Type()]; ok { current = reflect.ValueOf(fn(current)) goto BEGIN @@ -58,7 +56,6 @@ BEGIN: // NOTE: when not successful ok will be false, this can happen when a nested struct is nil and so the field // could not be retrieved because it didn't exist. func (v *validate) getStructFieldOKInternal(val reflect.Value, namespace string) (current reflect.Value, kind reflect.Kind, nullable bool, found bool) { - BEGIN: current, kind, nullable = v.ExtractType(val) if kind == reflect.Invalid { @@ -222,7 +219,6 @@ BEGIN: // asInt returns the parameter as a int64 // or panics if it can't convert func asInt(param string) int64 { - i, err := strconv.ParseInt(param, 0, 64) panicIf(err) @@ -232,7 +228,6 @@ func asInt(param string) int64 { // asUint returns the parameter as a uint64 // or panics if it can't convert func asUint(param string) uint64 { - i, err := strconv.ParseUint(param, 0, 64) panicIf(err) @@ -242,7 +237,6 @@ func asUint(param string) uint64 { // asFloat returns the parameter as a float64 // or panics if it can't convert func asFloat(param string) float64 { - i, err := strconv.ParseFloat(param, 64) panicIf(err) diff --git a/vendor/gopkg.in/go-playground/validator.v9/validator.go b/vendor/gopkg.in/go-playground/validator.v9/validator.go index 342e72e3..6e704837 100644 --- a/vendor/gopkg.in/go-playground/validator.v9/validator.go +++ b/vendor/gopkg.in/go-playground/validator.v9/validator.go @@ -31,7 +31,6 @@ type validate struct { // parent and current will be the same the first run of validateStruct func (v *validate) validateStruct(ctx context.Context, parent reflect.Value, current reflect.Value, typ reflect.Type, ns []byte, structNs []byte, ct *cTag) { - cs, ok := v.v.structCache.Get(typ) if !ok { cs = v.v.extractStructCache(current, typ.Name()) @@ -57,13 +56,11 @@ func (v *validate) validateStruct(ctx context.Context, parent reflect.Value, cur f = cs.fields[i] if v.isPartial { - if v.ffn != nil { // used with StructFiltered if v.ffn(append(structNs, f.name...)) { continue } - } else { // used with StructPartial & StructExcept _, ok = v.includeExclude[string(append(structNs, f.name...))] @@ -355,7 +352,6 @@ OUTER: v.ct = ct if ct.fn(ctx, v) { - // drain rest of the 'or' values, then continue or leave for { @@ -390,7 +386,6 @@ OUTER: } if ct.hasAlias { - v.errs = append(v.errs, &fieldError{ v: v.v, @@ -406,7 +401,6 @@ OUTER: typ: typ, }, ) - } else { tVal := string(v.misc)[1:] @@ -473,5 +467,4 @@ OUTER: ct = ct.next } } - } diff --git a/vendor/gopkg.in/go-playground/validator.v9/validator_instance.go b/vendor/gopkg.in/go-playground/validator.v9/validator_instance.go index 4a89d406..7cba54d2 100644 --- a/vendor/gopkg.in/go-playground/validator.v9/validator_instance.go +++ b/vendor/gopkg.in/go-playground/validator.v9/validator_instance.go @@ -82,7 +82,6 @@ type Validate struct { // New returns a new instance of 'validate' with sane defaults. func New() *Validate { - tc := new(tagCache) tc.m.Store(make(map[string]*cTag)) @@ -104,7 +103,6 @@ func New() *Validate { // must copy validators for separate validations to be used in each instance for k, val := range bakedInValidators { - switch k { // these require that even if the value is nil that the validation should run, omitempty still overrides this behaviour case requiredWithTag, requiredWithAllTag, requiredWithoutTag, requiredWithoutAllTag: @@ -192,7 +190,6 @@ func (v *Validate) registerValidation(tag string, fn FuncCtx, bakedIn bool, nilC // // NOTE: this function is not thread-safe it is intended that these all be registered prior to any validation func (v *Validate) RegisterAlias(alias, tags string) { - _, ok := restrictedTags[alias] if ok || strings.ContainsAny(alias, restrictedTagChars) { @@ -216,7 +213,6 @@ func (v *Validate) RegisterStructValidation(fn StructLevelFunc, types ...interfa // NOTE: // - this method is not thread-safe it is intended that these all be registered prior to any validation func (v *Validate) RegisterStructValidationCtx(fn StructLevelFuncCtx, types ...interface{}) { - if v.structLevelFuncs == nil { v.structLevelFuncs = make(map[reflect.Type]StructLevelFuncCtx) } @@ -235,7 +231,6 @@ func (v *Validate) RegisterStructValidationCtx(fn StructLevelFuncCtx, types ...i // // NOTE: this method is not thread-safe it is intended that these all be registered prior to any validation func (v *Validate) RegisterCustomTypeFunc(fn CustomTypeFunc, types ...interface{}) { - if v.customFuncs == nil { v.customFuncs = make(map[reflect.Type]CustomTypeFunc) } @@ -249,7 +244,6 @@ func (v *Validate) RegisterCustomTypeFunc(fn CustomTypeFunc, types ...interface{ // RegisterTranslation registers translations against the provided tag. func (v *Validate) RegisterTranslation(tag string, trans ut.Translator, registerFn RegisterTranslationsFunc, translationFn TranslationFunc) (err error) { - if v.transTagFunc == nil { v.transTagFunc = make(map[ut.Translator]map[string]TranslationFunc) } @@ -283,7 +277,6 @@ func (v *Validate) Struct(s interface{}) error { // It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. // You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. func (v *Validate) StructCtx(ctx context.Context, s interface{}) (err error) { - val := reflect.ValueOf(s) top := val diff --git a/vendor/gopkg.in/ini.v1/deprecated.go b/vendor/gopkg.in/ini.v1/deprecated.go index e8bda06e..eda71f28 100644 --- a/vendor/gopkg.in/ini.v1/deprecated.go +++ b/vendor/gopkg.in/ini.v1/deprecated.go @@ -19,7 +19,5 @@ const ( DEFAULT_SECTION = DefaultSection ) -var ( - // Deprecated: AllCapsUnderscore converts to format ALL_CAPS_UNDERSCORE. - AllCapsUnderscore = SnackCase -) +// Deprecated: AllCapsUnderscore converts to format ALL_CAPS_UNDERSCORE. +var AllCapsUnderscore = SnackCase diff --git a/vendor/gopkg.in/ini.v1/file.go b/vendor/gopkg.in/ini.v1/file.go index b96d172c..b63a1f49 100644 --- a/vendor/gopkg.in/ini.v1/file.go +++ b/vendor/gopkg.in/ini.v1/file.go @@ -508,7 +508,7 @@ func (f *File) SaveToIndent(filename, indent string) error { return err } - return ioutil.WriteFile(filename, buf.Bytes(), 0666) + return ioutil.WriteFile(filename, buf.Bytes(), 0o666) } // SaveTo writes content to file system. diff --git a/vendor/gopkg.in/ini.v1/key.go b/vendor/gopkg.in/ini.v1/key.go index 8baafd9e..83a7f86e 100644 --- a/vendor/gopkg.in/ini.v1/key.go +++ b/vendor/gopkg.in/ini.v1/key.go @@ -781,10 +781,8 @@ func (k *Key) parseUint64s(strs []string, addInvalid, returnOnInvalid bool) ([]u return vals, err } - type Parser func(str string) (interface{}, error) - // parseTimesFormat transforms strings to times in given format. func (k *Key) parseTimesFormat(format string, strs []string, addInvalid, returnOnInvalid bool) ([]time.Time, error) { vals := make([]time.Time, 0, len(strs)) @@ -801,7 +799,6 @@ func (k *Key) parseTimesFormat(format string, strs []string, addInvalid, returnO return vals, err } - // doParse transforms strings to different types func (k *Key) doParse(strs []string, addInvalid, returnOnInvalid bool, parser Parser) ([]interface{}, error) { vals := make([]interface{}, 0, len(strs)) diff --git a/vendor/gopkg.in/ini.v1/parser.go b/vendor/gopkg.in/ini.v1/parser.go index 65147166..c112bdda 100644 --- a/vendor/gopkg.in/ini.v1/parser.go +++ b/vendor/gopkg.in/ini.v1/parser.go @@ -222,7 +222,6 @@ func hasSurroundedQuote(in string, quote byte) bool { } func (p *parser) readValue(in []byte, bufferSize int) (string, error) { - line := strings.TrimLeftFunc(string(in), unicode.IsSpace) if len(line) == 0 { if p.options.AllowPythonMultilineValues && len(in) > 0 && in[len(in)-1] == '\n' { diff --git a/vendor/gopkg.in/ini.v1/section.go b/vendor/gopkg.in/ini.v1/section.go index afaa97c9..ec4d2c88 100644 --- a/vendor/gopkg.in/ini.v1/section.go +++ b/vendor/gopkg.in/ini.v1/section.go @@ -198,7 +198,6 @@ func (s *Section) ParentKeys() []*Key { } else { break } - } return parentKeys } diff --git a/vendor/gopkg.in/yaml.v2/apic.go b/vendor/gopkg.in/yaml.v2/apic.go index acf71402..5022f21c 100644 --- a/vendor/gopkg.in/yaml.v2/apic.go +++ b/vendor/gopkg.in/yaml.v2/apic.go @@ -5,7 +5,7 @@ import ( ) func yaml_insert_token(parser *yaml_parser_t, pos int, token *yaml_token_t) { - //fmt.Println("yaml_insert_token", "pos:", pos, "typ:", token.typ, "head:", parser.tokens_head, "len:", len(parser.tokens)) + // fmt.Println("yaml_insert_token", "pos:", pos, "typ:", token.typ, "head:", parser.tokens_head, "len:", len(parser.tokens)) // Check if we can move the queue at the beginning of the buffer. if parser.tokens_head > 0 && len(parser.tokens) == cap(parser.tokens) { diff --git a/vendor/gopkg.in/yaml.v2/decode.go b/vendor/gopkg.in/yaml.v2/decode.go index 129bc2a9..3da2269c 100644 --- a/vendor/gopkg.in/yaml.v2/decode.go +++ b/vendor/gopkg.in/yaml.v2/decode.go @@ -701,7 +701,7 @@ func (d *decoder) mappingSlice(n *node, out reflect.Value) (good bool) { d.mapType = outt var slice []MapItem - var l = len(n.children) + l := len(n.children) for i := 0; i < l; i += 2 { if isMerge(n.children[i]) { d.merge(n.children[i+1], out) diff --git a/vendor/gopkg.in/yaml.v2/emitterc.go b/vendor/gopkg.in/yaml.v2/emitterc.go index a1c2cc52..b243ae13 100644 --- a/vendor/gopkg.in/yaml.v2/emitterc.go +++ b/vendor/gopkg.in/yaml.v2/emitterc.go @@ -310,7 +310,6 @@ func yaml_emitter_emit_stream_start(emitter *yaml_emitter_t, event *yaml_event_t // Expect DOCUMENT-START or STREAM-END. func yaml_emitter_emit_document_start(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { - if event.typ == yaml_DOCUMENT_START_EVENT { if event.version_directive != nil { @@ -796,7 +795,6 @@ func yaml_emitter_check_simple_key(emitter *yaml_emitter_t) bool { // Determine an acceptable scalar style. func yaml_emitter_select_scalar_style(emitter *yaml_emitter_t, event *yaml_event_t) bool { - no_tag := len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 if no_tag && !event.implicit && !event.quoted_implicit { return yaml_emitter_set_emitter_error(emitter, "neither tag nor implicit flags are specified") @@ -1131,7 +1129,6 @@ func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool { // Check if the event data is valid. func yaml_emitter_analyze_event(emitter *yaml_emitter_t, event *yaml_event_t) bool { - emitter.anchor_data.anchor = nil emitter.tag_data.handle = nil emitter.tag_data.suffix = nil @@ -1368,7 +1365,6 @@ func yaml_emitter_write_plain_scalar(emitter *yaml_emitter_t, value []byte, allo } func yaml_emitter_write_single_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { - if !yaml_emitter_write_indicator(emitter, []byte{'\''}, true, false, false) { return false } diff --git a/vendor/gopkg.in/yaml.v2/parserc.go b/vendor/gopkg.in/yaml.v2/parserc.go index 81d05dfe..3017aa9f 100644 --- a/vendor/gopkg.in/yaml.v2/parserc.go +++ b/vendor/gopkg.in/yaml.v2/parserc.go @@ -91,7 +91,7 @@ func yaml_parser_set_parser_error_context(parser *yaml_parser_t, context string, // State dispatcher. func yaml_parser_state_machine(parser *yaml_parser_t, event *yaml_event_t) bool { - //trace("yaml_parser_state_machine", "state:", parser.state.String()) + // trace("yaml_parser_state_machine", "state:", parser.state.String()) switch parser.state { case yaml_PARSE_STREAM_START_STATE: @@ -196,7 +196,6 @@ func yaml_parser_parse_stream_start(parser *yaml_parser_t, event *yaml_event_t) // explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* // ************************* func yaml_parser_parse_document_start(parser *yaml_parser_t, event *yaml_event_t, implicit bool) bool { - token := peek_token(parser) if token == nil { return false @@ -357,7 +356,7 @@ func yaml_parser_parse_document_end(parser *yaml_parser_t, event *yaml_event_t) // flow_content ::= flow_collection | SCALAR // ****** func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, indentless_sequence bool) bool { - //defer trace("yaml_parser_parse_node", "block:", block, "indentless_sequence:", indentless_sequence)() + // defer trace("yaml_parser_parse_node", "block:", block, "indentless_sequence:", indentless_sequence)() token := peek_token(parser) if token == nil { diff --git a/vendor/gopkg.in/yaml.v2/readerc.go b/vendor/gopkg.in/yaml.v2/readerc.go index 7c1f5fac..1092a587 100644 --- a/vendor/gopkg.in/yaml.v2/readerc.go +++ b/vendor/gopkg.in/yaml.v2/readerc.go @@ -95,7 +95,7 @@ func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool { // [Go] This function was changed to guarantee the requested length size at EOF. // The fact we need to do this is pretty awful, but the description above implies - // for that to be the case, and there are tests + // for that to be the case, and there are tests // If the EOF flag is set and the raw buffer is empty, do nothing. if parser.eof && parser.raw_buffer_pos == len(parser.raw_buffer) { @@ -104,7 +104,7 @@ func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool { // given length in the buffer. Not doing that means every single // check that calls this function to make sure the buffer has a // given length is Go) panicking; or C) accessing invalid memory. - //return true + // return true } // Return if the buffer contains enough characters. diff --git a/vendor/gopkg.in/yaml.v2/resolve.go b/vendor/gopkg.in/yaml.v2/resolve.go index 4120e0c9..1a53a63e 100644 --- a/vendor/gopkg.in/yaml.v2/resolve.go +++ b/vendor/gopkg.in/yaml.v2/resolve.go @@ -14,8 +14,10 @@ type resolveMapItem struct { tag string } -var resolveTable = make([]byte, 256) -var resolveMap = make(map[string]resolveMapItem) +var ( + resolveTable = make([]byte, 256) + resolveMap = make(map[string]resolveMapItem) +) func init() { t := resolveTable @@ -29,7 +31,7 @@ func init() { } t[int('.')] = '.' // Float (potentially in map) - var resolveMapList = []struct { + resolveMapList := []struct { v interface{} tag string l []string @@ -180,7 +182,7 @@ func resolve(tag string, in string) (rtag string, out interface{}) { return yaml_INT_TAG, uintv } } else if strings.HasPrefix(plain, "-0b") { - intv, err := strconv.ParseInt("-" + plain[3:], 2, 64) + intv, err := strconv.ParseInt("-"+plain[3:], 2, 64) if err == nil { if true || intv == int64(int(intv)) { return yaml_INT_TAG, int(intv) diff --git a/vendor/gopkg.in/yaml.v2/scannerc.go b/vendor/gopkg.in/yaml.v2/scannerc.go index 0b9bb603..62e4e335 100644 --- a/vendor/gopkg.in/yaml.v2/scannerc.go +++ b/vendor/gopkg.in/yaml.v2/scannerc.go @@ -990,7 +990,6 @@ func yaml_parser_unroll_indent(parser *yaml_parser_t, column int) bool { // Initialize the scanner and produce the STREAM-START token. func yaml_parser_fetch_stream_start(parser *yaml_parser_t) bool { - // Set the initial indentation. parser.indent = -1 @@ -1018,7 +1017,6 @@ func yaml_parser_fetch_stream_start(parser *yaml_parser_t) bool { // Produce the STREAM-END token and shut down the scanner. func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool { - // Force new line. if parser.mark.column != 0 { parser.mark.column = 0 @@ -1237,7 +1235,6 @@ func yaml_parser_fetch_block_entry(parser *yaml_parser_t) bool { // Produce the KEY token. func yaml_parser_fetch_key(parser *yaml_parser_t) bool { - // In the block context, additional checks are required. if parser.flow_level == 0 { // Check if we are allowed to start a new key (not nessesary simple). @@ -1276,13 +1273,11 @@ func yaml_parser_fetch_key(parser *yaml_parser_t) bool { // Produce the VALUE token. func yaml_parser_fetch_value(parser *yaml_parser_t) bool { - simple_key := &parser.simple_keys[len(parser.simple_keys)-1] // Have we found a simple key? if valid, ok := yaml_simple_key_is_valid(parser, simple_key); !ok { return false - } else if valid { // Create the KEY token and insert it into the queue. @@ -1441,7 +1436,6 @@ func yaml_parser_fetch_plain_scalar(parser *yaml_parser_t) bool { // Eat whitespaces and comments until the next token is found. func yaml_parser_scan_to_next_token(parser *yaml_parser_t) bool { - // Until the next token is not found. for { // Allow the BOM mark to start a line. @@ -1684,7 +1678,6 @@ const max_number_length = 2 // %YAML 1.1 # a comment \n // ^ func yaml_parser_scan_version_directive_number(parser *yaml_parser_t, start_mark yaml_mark_t, number *int8) bool { - // Repeat while the next character is digit. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false @@ -1966,7 +1959,7 @@ func yaml_parser_scan_tag_handle(parser *yaml_parser_t, directive bool, start_ma // Scan a tag. func yaml_parser_scan_tag_uri(parser *yaml_parser_t, directive bool, head []byte, start_mark yaml_mark_t, uri *[]byte) bool { - //size_t length = head ? strlen((char *)head) : 0 + // size_t length = head ? strlen((char *)head) : 0 var s []byte hasTag := len(head) > 0 @@ -2024,7 +2017,6 @@ func yaml_parser_scan_tag_uri(parser *yaml_parser_t, directive bool, head []byte // Decode an URI-escape sequence corresponding to a single UTF-8 character. func yaml_parser_scan_uri_escapes(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, s *[]byte) bool { - // Decode the required number of characters. w := 1024 for w > 0 { @@ -2359,7 +2351,6 @@ func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, si } else if !single && parser.buffer[parser.buffer_pos] == '"' { // It is a right double quote. break - } else if !single && parser.buffer[parser.buffer_pos] == '\\' && is_break(parser.buffer, parser.buffer_pos+1) { // It is an escaped line break. if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { @@ -2568,10 +2559,9 @@ func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, si // Scan a plain scalar. func yaml_parser_scan_plain_scalar(parser *yaml_parser_t, token *yaml_token_t) bool { - var s, leading_break, trailing_breaks, whitespaces []byte var leading_blanks bool - var indent = parser.indent + 1 + indent := parser.indent + 1 start_mark := parser.mark end_mark := parser.mark diff --git a/vendor/gopkg.in/yaml.v2/sorter.go b/vendor/gopkg.in/yaml.v2/sorter.go index 4c45e660..2edd7340 100644 --- a/vendor/gopkg.in/yaml.v2/sorter.go +++ b/vendor/gopkg.in/yaml.v2/sorter.go @@ -52,7 +52,7 @@ func (l keyList) Less(i, j int) bool { var ai, bi int var an, bn int64 if ar[i] == '0' || br[i] == '0' { - for j := i-1; j >= 0 && unicode.IsDigit(ar[j]); j-- { + for j := i - 1; j >= 0 && unicode.IsDigit(ar[j]); j-- { if ar[j] != '0' { an = 1 bn = 1 diff --git a/vendor/gopkg.in/yaml.v2/yaml.go b/vendor/gopkg.in/yaml.v2/yaml.go index 30813884..8f7bd424 100644 --- a/vendor/gopkg.in/yaml.v2/yaml.go +++ b/vendor/gopkg.in/yaml.v2/yaml.go @@ -304,8 +304,10 @@ type fieldInfo struct { Inline []int } -var structMap = make(map[reflect.Type]*structInfo) -var fieldMapMutex sync.RWMutex +var ( + structMap = make(map[reflect.Type]*structInfo) + fieldMapMutex sync.RWMutex +) func getStructInfo(st reflect.Type) (*structInfo, error) { fieldMapMutex.RLock() @@ -383,7 +385,7 @@ func getStructInfo(st reflect.Type) (*structInfo, error) { fieldsList = append(fieldsList, finfo) } default: - //return nil, errors.New("Option ,inline needs a struct value or map field") + // return nil, errors.New("Option ,inline needs a struct value or map field") return nil, errors.New("Option ,inline needs a struct value field") } continue diff --git a/vendor/gopkg.in/yaml.v2/yamlprivateh.go b/vendor/gopkg.in/yaml.v2/yamlprivateh.go index 8110ce3c..c97ca60b 100644 --- a/vendor/gopkg.in/yaml.v2/yamlprivateh.go +++ b/vendor/gopkg.in/yaml.v2/yamlprivateh.go @@ -94,7 +94,7 @@ func is_tab(b []byte, i int) bool { // Check if the character at the specified position is blank (space or tab). func is_blank(b []byte, i int) bool { - //return is_space(b, i) || is_tab(b, i) + // return is_space(b, i) || is_tab(b, i) return b[i] == ' ' || b[i] == '\t' } @@ -113,7 +113,7 @@ func is_crlf(b []byte, i int) bool { // Check if the character is a line break or NUL. func is_breakz(b []byte, i int) bool { - //return is_break(b, i) || is_z(b, i) + // return is_break(b, i) || is_z(b, i) return ( // is_break: b[i] == '\r' || // CR (#xD) b[i] == '\n' || // LF (#xA) @@ -126,7 +126,7 @@ func is_breakz(b []byte, i int) bool { // Check if the character is a line break, space, or NUL. func is_spacez(b []byte, i int) bool { - //return is_space(b, i) || is_breakz(b, i) + // return is_space(b, i) || is_breakz(b, i) return ( // is_space: b[i] == ' ' || // is_breakz: @@ -140,7 +140,7 @@ func is_spacez(b []byte, i int) bool { // Check if the character is a line break, space, tab, or NUL. func is_blankz(b []byte, i int) bool { - //return is_blank(b, i) || is_breakz(b, i) + // return is_blank(b, i) || is_breakz(b, i) return ( // is_blank: b[i] == ' ' || b[i] == '\t' || // is_breakz: @@ -169,5 +169,4 @@ func width(b byte) int { return 4 } return 0 - } diff --git a/vendor/gopkg.in/yaml.v3/apic.go b/vendor/gopkg.in/yaml.v3/apic.go index 65846e67..49f5d973 100644 --- a/vendor/gopkg.in/yaml.v3/apic.go +++ b/vendor/gopkg.in/yaml.v3/apic.go @@ -1,17 +1,17 @@ -// +// // Copyright (c) 2011-2019 Canonical Ltd // Copyright (c) 2006-2010 Kirill Simonov -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -27,7 +27,7 @@ import ( ) func yaml_insert_token(parser *yaml_parser_t, pos int, token *yaml_token_t) { - //fmt.Println("yaml_insert_token", "pos:", pos, "typ:", token.typ, "head:", parser.tokens_head, "len:", len(parser.tokens)) + // fmt.Println("yaml_insert_token", "pos:", pos, "typ:", token.typ, "head:", parser.tokens_head, "len:", len(parser.tokens)) // Check if we can move the queue at the beginning of the buffer. if parser.tokens_head > 0 && len(parser.tokens) == cap(parser.tokens) { diff --git a/vendor/gopkg.in/yaml.v3/decode.go b/vendor/gopkg.in/yaml.v3/decode.go index be63169b..c6c38bd0 100644 --- a/vendor/gopkg.in/yaml.v3/decode.go +++ b/vendor/gopkg.in/yaml.v3/decode.go @@ -211,7 +211,7 @@ func (p *parser) alias() *Node { } func (p *parser) scalar() *Node { - var parsedStyle = p.event.scalar_style() + parsedStyle := p.event.scalar_style() var nodeStyle Style switch { case parsedStyle&yaml_DOUBLE_QUOTED_SCALAR_STYLE != 0: @@ -223,8 +223,8 @@ func (p *parser) scalar() *Node { case parsedStyle&yaml_FOLDED_SCALAR_STYLE != 0: nodeStyle = FoldedStyle } - var nodeValue = string(p.event.value) - var nodeTag = string(p.event.tag) + nodeValue := string(p.event.value) + nodeTag := string(p.event.tag) var defaultTag string if nodeStyle == 0 { if nodeValue == "<<" { diff --git a/vendor/gopkg.in/yaml.v3/emitterc.go b/vendor/gopkg.in/yaml.v3/emitterc.go index ab2a0661..2f0a5133 100644 --- a/vendor/gopkg.in/yaml.v3/emitterc.go +++ b/vendor/gopkg.in/yaml.v3/emitterc.go @@ -354,7 +354,6 @@ func yaml_emitter_emit_stream_start(emitter *yaml_emitter_t, event *yaml_event_t // Expect DOCUMENT-START or STREAM-END. func yaml_emitter_emit_document_start(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { - if event.typ == yaml_DOCUMENT_START_EVENT { if event.version_directive != nil { @@ -974,7 +973,6 @@ func yaml_emitter_check_simple_key(emitter *yaml_emitter_t) bool { // Determine an acceptable scalar style. func yaml_emitter_select_scalar_style(emitter *yaml_emitter_t, event *yaml_event_t) bool { - no_tag := len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 if no_tag && !event.implicit && !event.quoted_implicit { return yaml_emitter_set_emitter_error(emitter, "neither tag nor implicit flags are specified") @@ -1379,7 +1377,6 @@ func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool { // Check if the event data is valid. func yaml_emitter_analyze_event(emitter *yaml_emitter_t, event *yaml_event_t) bool { - emitter.anchor_data.anchor = nil emitter.tag_data.handle = nil emitter.tag_data.suffix = nil @@ -1480,7 +1477,7 @@ func yaml_emitter_write_indent(emitter *yaml_emitter_t) bool { } } emitter.whitespace = true - //emitter.indention = true + // emitter.indention = true emitter.space_above = false emitter.foot_indent = -1 return true @@ -1609,7 +1606,7 @@ func yaml_emitter_write_plain_scalar(emitter *yaml_emitter_t, value []byte, allo if !write_break(emitter, value, &i) { return false } - //emitter.indention = true + // emitter.indention = true breaks = true } else { if breaks { @@ -1638,7 +1635,6 @@ func yaml_emitter_write_plain_scalar(emitter *yaml_emitter_t, value []byte, allo } func yaml_emitter_write_single_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { - if !yaml_emitter_write_indicator(emitter, []byte{'\''}, true, false, false) { return false } @@ -1667,7 +1663,7 @@ func yaml_emitter_write_single_quoted_scalar(emitter *yaml_emitter_t, value []by if !write_break(emitter, value, &i) { return false } - //emitter.indention = true + // emitter.indention = true breaks = true } else { if breaks { @@ -1869,7 +1865,7 @@ func yaml_emitter_write_literal_scalar(emitter *yaml_emitter_t, value []byte) bo if !put_break(emitter) { return false } - //emitter.indention = true + // emitter.indention = true emitter.whitespace = true breaks := true for i := 0; i < len(value); { @@ -1877,7 +1873,7 @@ func yaml_emitter_write_literal_scalar(emitter *yaml_emitter_t, value []byte) bo if !write_break(emitter, value, &i) { return false } - //emitter.indention = true + // emitter.indention = true breaks = true } else { if breaks { @@ -1907,7 +1903,7 @@ func yaml_emitter_write_folded_scalar(emitter *yaml_emitter_t, value []byte) boo if !put_break(emitter) { return false } - //emitter.indention = true + // emitter.indention = true emitter.whitespace = true breaks := true @@ -1928,7 +1924,7 @@ func yaml_emitter_write_folded_scalar(emitter *yaml_emitter_t, value []byte) boo if !write_break(emitter, value, &i) { return false } - //emitter.indention = true + // emitter.indention = true breaks = true } else { if breaks { @@ -1962,7 +1958,7 @@ func yaml_emitter_write_comment(emitter *yaml_emitter_t, comment []byte) bool { if !write_break(emitter, comment, &i) { return false } - //emitter.indention = true + // emitter.indention = true breaks = true pound = false } else { @@ -1987,6 +1983,6 @@ func yaml_emitter_write_comment(emitter *yaml_emitter_t, comment []byte) bool { } emitter.whitespace = true - //emitter.indention = true + // emitter.indention = true return true } diff --git a/vendor/gopkg.in/yaml.v3/encode.go b/vendor/gopkg.in/yaml.v3/encode.go index 1f37271c..33bb9d47 100644 --- a/vendor/gopkg.in/yaml.v3/encode.go +++ b/vendor/gopkg.in/yaml.v3/encode.go @@ -424,8 +424,8 @@ func (e *encoder) nodev(in reflect.Value) { func (e *encoder) node(node *Node, tail string) { // If the tag was not explicitly requested, and dropping it won't change the // implicit tag of the value, don't include it in the presentation. - var tag = node.Tag - var stag = shortTag(tag) + tag := node.Tag + stag := shortTag(tag) var rtag string var forceQuoting bool if tag != "" && node.Style&TaggedStyle == 0 { diff --git a/vendor/gopkg.in/yaml.v3/parserc.go b/vendor/gopkg.in/yaml.v3/parserc.go index aea9050b..fe47e047 100644 --- a/vendor/gopkg.in/yaml.v3/parserc.go +++ b/vendor/gopkg.in/yaml.v3/parserc.go @@ -148,7 +148,7 @@ func yaml_parser_set_parser_error_context(parser *yaml_parser_t, context string, // State dispatcher. func yaml_parser_state_machine(parser *yaml_parser_t, event *yaml_event_t) bool { - //trace("yaml_parser_state_machine", "state:", parser.state.String()) + // trace("yaml_parser_state_machine", "state:", parser.state.String()) switch parser.state { case yaml_PARSE_STREAM_START_STATE: @@ -253,7 +253,6 @@ func yaml_parser_parse_stream_start(parser *yaml_parser_t, event *yaml_event_t) // explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* // ************************* func yaml_parser_parse_document_start(parser *yaml_parser_t, event *yaml_event_t, implicit bool) bool { - token := peek_token(parser) if token == nil { return false @@ -453,7 +452,7 @@ func yaml_parser_set_event_comments(parser *yaml_parser_t, event *yaml_event_t) // flow_content ::= flow_collection | SCALAR // ****** func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, indentless_sequence bool) bool { - //defer trace("yaml_parser_parse_node", "block:", block, "indentless_sequence:", indentless_sequence)() + // defer trace("yaml_parser_parse_node", "block:", block, "indentless_sequence:", indentless_sequence)() token := peek_token(parser) if token == nil { diff --git a/vendor/gopkg.in/yaml.v3/readerc.go b/vendor/gopkg.in/yaml.v3/readerc.go index b7de0a89..b9ea25ef 100644 --- a/vendor/gopkg.in/yaml.v3/readerc.go +++ b/vendor/gopkg.in/yaml.v3/readerc.go @@ -1,17 +1,17 @@ -// +// // Copyright (c) 2011-2019 Canonical Ltd // Copyright (c) 2006-2010 Kirill Simonov -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -126,7 +126,7 @@ func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool { // given length in the buffer. Not doing that means every single // check that calls this function to make sure the buffer has a // given length is Go) panicking; or C) accessing invalid memory. - //return true + // return true } // Return if the buffer contains enough characters. diff --git a/vendor/gopkg.in/yaml.v3/resolve.go b/vendor/gopkg.in/yaml.v3/resolve.go index 64ae8880..0c81f414 100644 --- a/vendor/gopkg.in/yaml.v3/resolve.go +++ b/vendor/gopkg.in/yaml.v3/resolve.go @@ -29,8 +29,10 @@ type resolveMapItem struct { tag string } -var resolveTable = make([]byte, 256) -var resolveMap = make(map[string]resolveMapItem) +var ( + resolveTable = make([]byte, 256) + resolveMap = make(map[string]resolveMapItem) +) func init() { t := resolveTable @@ -44,7 +46,7 @@ func init() { } t[int('.')] = '.' // Float (potentially in map) - var resolveMapList = []struct { + resolveMapList := []struct { v interface{} tag string l []string @@ -80,8 +82,10 @@ const ( mergeTag = "!!merge" ) -var longTags = make(map[string]string) -var shortTags = make(map[string]string) +var ( + longTags = make(map[string]string) + shortTags = make(map[string]string) +) func init() { for _, stag := range []string{nullTag, boolTag, strTag, intTag, floatTag, timestampTag, seqTag, mapTag, binaryTag, mergeTag} { diff --git a/vendor/gopkg.in/yaml.v3/scannerc.go b/vendor/gopkg.in/yaml.v3/scannerc.go index 57e954ca..1dd3d2b8 100644 --- a/vendor/gopkg.in/yaml.v3/scannerc.go +++ b/vendor/gopkg.in/yaml.v3/scannerc.go @@ -1076,7 +1076,6 @@ func yaml_parser_unroll_indent(parser *yaml_parser_t, column int, scan_mark yaml // Initialize the scanner and produce the STREAM-START token. func yaml_parser_fetch_stream_start(parser *yaml_parser_t) bool { - // Set the initial indentation. parser.indent = -1 @@ -1104,7 +1103,6 @@ func yaml_parser_fetch_stream_start(parser *yaml_parser_t) bool { // Produce the STREAM-END token and shut down the scanner. func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool { - // Force new line. if parser.mark.column != 0 { parser.mark.column = 0 @@ -1193,7 +1191,6 @@ func yaml_parser_fetch_document_indicator(parser *yaml_parser_t, typ yaml_token_ // Produce the FLOW-SEQUENCE-START or FLOW-MAPPING-START token. func yaml_parser_fetch_flow_collection_start(parser *yaml_parser_t, typ yaml_token_type_t) bool { - // The indicators '[' and '{' may start a simple key. if !yaml_parser_save_simple_key(parser) { return false @@ -1324,7 +1321,6 @@ func yaml_parser_fetch_block_entry(parser *yaml_parser_t) bool { // Produce the KEY token. func yaml_parser_fetch_key(parser *yaml_parser_t) bool { - // In the block context, additional checks are required. if parser.flow_level == 0 { // Check if we are allowed to start a new key (not nessesary simple). @@ -1363,13 +1359,11 @@ func yaml_parser_fetch_key(parser *yaml_parser_t) bool { // Produce the VALUE token. func yaml_parser_fetch_value(parser *yaml_parser_t) bool { - simple_key := &parser.simple_keys[len(parser.simple_keys)-1] // Have we found a simple key? if valid, ok := yaml_simple_key_is_valid(parser, simple_key); !ok { return false - } else if valid { // Create the KEY token and insert it into the queue. @@ -1528,7 +1522,6 @@ func yaml_parser_fetch_plain_scalar(parser *yaml_parser_t) bool { // Eat whitespaces and comments until the next token is found. func yaml_parser_scan_to_next_token(parser *yaml_parser_t) bool { - scan_mark := parser.mark // Until the next token is not found. @@ -1797,7 +1790,6 @@ const max_number_length = 2 // %YAML 1.1 # a comment \n // ^ func yaml_parser_scan_version_directive_number(parser *yaml_parser_t, start_mark yaml_mark_t, number *int8) bool { - // Repeat while the next character is digit. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false @@ -2079,7 +2071,7 @@ func yaml_parser_scan_tag_handle(parser *yaml_parser_t, directive bool, start_ma // Scan a tag. func yaml_parser_scan_tag_uri(parser *yaml_parser_t, directive bool, head []byte, start_mark yaml_mark_t, uri *[]byte) bool { - //size_t length = head ? strlen((char *)head) : 0 + // size_t length = head ? strlen((char *)head) : 0 var s []byte hasTag := len(head) > 0 @@ -2137,7 +2129,6 @@ func yaml_parser_scan_tag_uri(parser *yaml_parser_t, directive bool, head []byte // Decode an URI-escape sequence corresponding to a single UTF-8 character. func yaml_parser_scan_uri_escapes(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, s *[]byte) bool { - // Decode the required number of characters. w := 1024 for w > 0 { @@ -2476,7 +2467,6 @@ func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, si } else if !single && parser.buffer[parser.buffer_pos] == '"' { // It is a right double quote. break - } else if !single && parser.buffer[parser.buffer_pos] == '\\' && is_break(parser.buffer, parser.buffer_pos+1) { // It is an escaped line break. if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { @@ -2685,10 +2675,9 @@ func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, si // Scan a plain scalar. func yaml_parser_scan_plain_scalar(parser *yaml_parser_t, token *yaml_token_t) bool { - var s, leading_break, trailing_breaks, whitespaces []byte var leading_blanks bool - var indent = parser.indent + 1 + indent := parser.indent + 1 start_mark := parser.mark end_mark := parser.mark @@ -2843,7 +2832,7 @@ func yaml_parser_scan_line_comment(parser *yaml_parser_t, token_mark yaml_mark_t continue } if parser.buffer[parser.buffer_pos+peek] == '#' { - seen := parser.mark.index+peek + seen := parser.mark.index + peek for { if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false @@ -2873,7 +2862,7 @@ func yaml_parser_scan_line_comment(parser *yaml_parser_t, token_mark yaml_mark_t parser.comments = append(parser.comments, yaml_comment_t{ token_mark: token_mark, start_mark: start_mark, - line: text, + line: text, }) } return true @@ -2886,14 +2875,14 @@ func yaml_parser_scan_comments(parser *yaml_parser_t, scan_mark yaml_mark_t) boo token = parser.tokens[len(parser.tokens)-2] } - var token_mark = token.start_mark + token_mark := token.start_mark var start_mark yaml_mark_t - var recent_empty = false - var first_empty = parser.newlines <= 1 + recent_empty := false + first_empty := parser.newlines <= 1 - var line = parser.mark.line - var column = parser.mark.column + line := parser.mark.line + column := parser.mark.column var text []byte @@ -2901,15 +2890,15 @@ func yaml_parser_scan_comments(parser *yaml_parser_t, scan_mark yaml_mark_t) boo // still be considered as a foot of the prior content. // If there's some content in the currently parsed line, then // the foot is the line below it. - var foot_line = -1 + foot_line := -1 if scan_mark.line > 0 { - foot_line = parser.mark.line-parser.newlines+1 + foot_line = parser.mark.line - parser.newlines + 1 if parser.newlines == 0 && parser.mark.column > 1 { foot_line++ } } - var peek = 0 + peek := 0 for ; peek < 512; peek++ { if parser.unread < peek+1 && !yaml_parser_update_buffer(parser, peek+1) { break @@ -2986,7 +2975,7 @@ func yaml_parser_scan_comments(parser *yaml_parser_t, scan_mark yaml_mark_t) boo recent_empty = false // Consume until after the consumed comment line. - seen := parser.mark.index+peek + seen := parser.mark.index + peek for { if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false diff --git a/vendor/gopkg.in/yaml.v3/writerc.go b/vendor/gopkg.in/yaml.v3/writerc.go index b8a116bf..266d0b09 100644 --- a/vendor/gopkg.in/yaml.v3/writerc.go +++ b/vendor/gopkg.in/yaml.v3/writerc.go @@ -1,17 +1,17 @@ -// +// // Copyright (c) 2011-2019 Canonical Ltd // Copyright (c) 2006-2010 Kirill Simonov -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE diff --git a/vendor/gopkg.in/yaml.v3/yaml.go b/vendor/gopkg.in/yaml.v3/yaml.go index b5d35a50..1d16ba0b 100644 --- a/vendor/gopkg.in/yaml.v3/yaml.go +++ b/vendor/gopkg.in/yaml.v3/yaml.go @@ -339,7 +339,7 @@ const ( // Address yaml.Node // } // err := yaml.Unmarshal(data, &person) -// +// // Or by itself: // // var person Node @@ -349,7 +349,7 @@ type Node struct { // Kind defines whether the node is a document, a mapping, a sequence, // a scalar value, or an alias to another node. The specific data type of // scalar nodes may be obtained via the ShortTag and LongTag methods. - Kind Kind + Kind Kind // Style allows customizing the apperance of the node in the tree. Style Style @@ -479,9 +479,11 @@ type fieldInfo struct { Inline []int } -var structMap = make(map[reflect.Type]*structInfo) -var fieldMapMutex sync.RWMutex -var unmarshalerType reflect.Type +var ( + structMap = make(map[reflect.Type]*structInfo) + fieldMapMutex sync.RWMutex + unmarshalerType reflect.Type +) func init() { var v Unmarshaler diff --git a/vendor/gopkg.in/yaml.v3/yamlh.go b/vendor/gopkg.in/yaml.v3/yamlh.go index 2719cfbb..42266b69 100644 --- a/vendor/gopkg.in/yaml.v3/yamlh.go +++ b/vendor/gopkg.in/yaml.v3/yamlh.go @@ -639,7 +639,6 @@ type yaml_parser_t struct { } type yaml_comment_t struct { - scan_mark yaml_mark_t // Position where scanning for comments started token_mark yaml_mark_t // Position after which tokens will be associated with this comment start_mark yaml_mark_t // Position of '#' comment mark diff --git a/vendor/gopkg.in/yaml.v3/yamlprivateh.go b/vendor/gopkg.in/yaml.v3/yamlprivateh.go index e88f9c54..96a859ea 100644 --- a/vendor/gopkg.in/yaml.v3/yamlprivateh.go +++ b/vendor/gopkg.in/yaml.v3/yamlprivateh.go @@ -1,17 +1,17 @@ -// +// // Copyright (c) 2011-2019 Canonical Ltd // Copyright (c) 2006-2010 Kirill Simonov -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -116,7 +116,7 @@ func is_tab(b []byte, i int) bool { // Check if the character at the specified position is blank (space or tab). func is_blank(b []byte, i int) bool { - //return is_space(b, i) || is_tab(b, i) + // return is_space(b, i) || is_tab(b, i) return b[i] == ' ' || b[i] == '\t' } @@ -135,10 +135,10 @@ func is_crlf(b []byte, i int) bool { // Check if the character is a line break or NUL. func is_breakz(b []byte, i int) bool { - //return is_break(b, i) || is_z(b, i) + // return is_break(b, i) || is_z(b, i) return ( - // is_break: - b[i] == '\r' || // CR (#xD) + // is_break: + b[i] == '\r' || // CR (#xD) b[i] == '\n' || // LF (#xA) b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) @@ -149,10 +149,10 @@ func is_breakz(b []byte, i int) bool { // Check if the character is a line break, space, or NUL. func is_spacez(b []byte, i int) bool { - //return is_space(b, i) || is_breakz(b, i) + // return is_space(b, i) || is_breakz(b, i) return ( - // is_space: - b[i] == ' ' || + // is_space: + b[i] == ' ' || // is_breakz: b[i] == '\r' || // CR (#xD) b[i] == '\n' || // LF (#xA) @@ -164,10 +164,10 @@ func is_spacez(b []byte, i int) bool { // Check if the character is a line break, space, tab, or NUL. func is_blankz(b []byte, i int) bool { - //return is_blank(b, i) || is_breakz(b, i) + // return is_blank(b, i) || is_breakz(b, i) return ( - // is_blank: - b[i] == ' ' || b[i] == '\t' || + // is_blank: + b[i] == ' ' || b[i] == '\t' || // is_breakz: b[i] == '\r' || // CR (#xD) b[i] == '\n' || // LF (#xA) @@ -194,5 +194,4 @@ func width(b byte) int { return 4 } return 0 - } diff --git a/vendor/modules.txt b/vendor/modules.txt index cfdae3d4..f8574058 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -3,7 +3,7 @@ github.com/DATA-DOG/go-sqlmock # github.com/GeertJohan/go.rice v1.0.2 github.com/GeertJohan/go.rice github.com/GeertJohan/go.rice/embedded -# github.com/bmc-toolbox/bmclib v0.4.13 +# github.com/bmc-toolbox/bmclib v0.4.14 github.com/bmc-toolbox/bmclib/cfgresources github.com/bmc-toolbox/bmclib/devices github.com/bmc-toolbox/bmclib/discover diff --git a/web/rice-box.go b/web/rice-box.go index d2ce9afb..6fc7fa45 100644 --- a/web/rice-box.go +++ b/web/rice-box.go @@ -7,7 +7,6 @@ import ( ) func init() { - // define files file2 := &embedded.EmbeddedFile{ Filename: "bootstrap.min.css", @@ -67,7 +66,6 @@ func init() { } func init() { - // define files file7 := &embedded.EmbeddedFile{ Filename: "doc.tmpl",