From 27157bb8e092b2119d158ed12b613d3c2e2eccfb Mon Sep 17 00:00:00 2001 From: Thomas Stromberg Date: Thu, 2 Sep 2021 20:11:27 -0700 Subject: [PATCH 1/9] Run 'lint-install', integrate with verify rule Signed-off-by: Thomas Stromberg --- .golangci.yml | 204 ++++++++++++++++++++++++++++++++++++++++++++++++++ Makefile | 50 ++++++++++++- 2 files changed, 251 insertions(+), 3 deletions(-) create mode 100644 .golangci.yml diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 000000000..9b3a5722e --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,204 @@ +# NOTE: This file is populated by the lint-install tool. Local adjustments may be overwritten. +linters-settings: + cyclop: + # NOTE: This is a very high transitional threshold + max-complexity: 37 + package-average: 34.0 + skip-tests: true + + gocognit: + # NOTE: This is a very high transitional threshold + min-complexity: 98 + + dupl: + threshold: 200 + + goconst: + min-len: 4 + min-occurrences: 5 + ignore-tests: true + + gosec: + excludes: + - G107 # Potential HTTP request made with variable url + - G204 # Subprocess launched with function call as argument or cmd arguments + - G404 # Use of weak random number generator (math/rand instead of crypto/rand + + errorlint: + # these are still common in Go: for instance, exit errors. + asserts: false + + exhaustive: + default-signifies-exhaustive: true + + nestif: + min-complexity: 8 + + nolintlint: + require-explanation: true + allow-unused: false + require-specific: true + + revive: + ignore-generated-header: true + severity: warning + rules: + - name: atomic + - name: blank-imports + - name: bool-literal-in-expr + - name: confusing-naming + - name: constant-logical-expr + - name: context-as-argument + - name: context-keys-type + - name: deep-exit + - name: defer + - name: range-val-in-closure + - name: range-val-address + - name: dot-imports + - name: error-naming + - name: error-return + - name: error-strings + - name: errorf + - name: exported + - name: identical-branches + - name: if-return + - name: import-shadowing + - name: increment-decrement + - name: indent-error-flow + - name: indent-error-flow + - name: package-comments + - name: range + - name: receiver-naming + - name: redefines-builtin-id + - name: superfluous-else + - name: struct-tag + - name: time-naming + - name: unexported-naming + - name: unexported-return + - name: unnecessary-stmt + - name: unreachable-code + - name: unused-parameter + - name: var-declaration + - name: var-naming + - name: unconditional-recursion + - name: waitgroup-by-value + + staticcheck: + go: "1.16" + + unused: + go: "1.16" + +output: + sort-results: true + +linters: + disable-all: true + enable: + - asciicheck + - bodyclose + - cyclop + - deadcode + - dogsled + - dupl + - durationcheck + - errcheck + # errname is only available in golangci-lint v1.42.0+ - wait until v1.43 is available to settle + #- errname + - errorlint + - exhaustive + - exportloopref + - forcetypeassert + - gocognit + - goconst + - gocritic + - godot + - gofmt + - gofumpt + - gosec + - goheader + - goimports + - goprintffuncname + - gosimple + - govet + - ifshort + - importas + - ineffassign + - makezero + - misspell + - nakedret + - nestif + - nilerr + - noctx + - nolintlint + - predeclared + # disabling for the initial iteration of the linting tool + #- promlinter + - revive + - rowserrcheck + - sqlclosecheck + - staticcheck + - structcheck + - stylecheck + - thelper + - tparallel + - typecheck + - unconvert + - unparam + - unused + - varcheck + - wastedassign + - whitespace + + # Disabled linters, due to being misaligned with Go practices + # - exhaustivestruct + # - gochecknoglobals + # - gochecknoinits + # - goconst + # - godox + # - goerr113 + # - gomnd + # - lll + # - nlreturn + # - testpackage + # - wsl + # Disabled linters, due to not being relevant to our code base: + # - maligned + # - prealloc "For most programs usage of prealloc will be a premature optimization." + # Disabled linters due to bad error messages or bugs + # - tagliatelle + +issues: + # Excluding configuration per-path, per-linter, per-text and per-source + exclude-rules: + - path: _test\.go + linters: + - dupl + - errcheck + - forcetypeassert + - gocyclo + - gosec + - noctx + + - path: cmd.* + linters: + - noctx + + - path: main\.go + linters: + - noctx + + - path: cmd.* + text: "deep-exit" + + - path: main\.go + text: "deep-exit" + + # This check is of questionable value + - linters: + - tparallel + text: "call t.Parallel on the top level as well as its subtests" + + # Don't hide lint issues just because there are many of them + max-same-issues: 0 + max-issues-per-linter: 0 diff --git a/Makefile b/Makefile index 2f64973c9..e60c0b98d 100644 --- a/Makefile +++ b/Makefile @@ -10,9 +10,53 @@ test: ## Run tests go clean -testcache go test ./... -v -verify: ## Run lint like checkers - goimports -d . - golint ./... +verify: lint help: ## Print this help @grep --no-filename -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sed 's/:.*##/·/' | sort | column -ts '·' -c 120 + +# BEGIN: lint-install ../tink +# http://github.com/tinkerbell/lint-install + +GOLINT_VERSION ?= v1.42.0 +HADOLINT_VERSION ?= v2.7.0 +SHELLCHECK_VERSION ?= v0.7.2 +LINT_OS := $(shell uname) +LINT_ARCH := $(shell uname -m) +LINT_ROOT := $(shell dirname $(realpath $(firstword $(MAKEFILE_LIST)))) + +# shellcheck and hadolint lack arm64 native binaries: rely on x86-64 emulation +ifeq ($(LINT_OS),Darwin) + ifeq ($(LINT_ARCH),arm64) + LINT_ARCH=x86_64 + endif +endif + +LINT_LOWER_OS = $(shell echo $(LINT_OS) | tr '[:upper:]' '[:lower:]') +GOLINT_CONFIG:=$(LINT_ROOT)/.golangci.yml + +lint: out/linters/shellcheck-$(SHELLCHECK_VERSION)-$(LINT_ARCH)/shellcheck out/linters/hadolint-$(HADOLINT_VERSION)-$(LINT_ARCH) out/linters/golangci-lint-$(GOLINT_VERSION)-$(LINT_ARCH) + out/linters/golangci-lint-$(GOLINT_VERSION)-$(LINT_ARCH) run + out/linters/hadolint-$(HADOLINT_VERSION)-$(LINT_ARCH) $(shell find . -name "*Dockerfile") + out/linters/shellcheck-$(SHELLCHECK_VERSION)-$(LINT_ARCH)/shellcheck $(shell find . -name "*.sh") + +fix: out/linters/shellcheck-$(SHELLCHECK_VERSION)-$(LINT_ARCH)/shellcheck out/linters/golangci-lint-$(GOLINT_VERSION)-$(LINT_ARCH) + out/linters/golangci-lint-$(GOLINT_VERSION)-$(LINT_ARCH) run --fix + out/linters/shellcheck-$(SHELLCHECK_VERSION)-$(LINT_ARCH)/shellcheck $(shell find . -name "*.sh") -f diff | git apply -p2 - + +out/linters/shellcheck-$(SHELLCHECK_VERSION)-$(LINT_ARCH)/shellcheck: + mkdir -p out/linters + curl -sSfL https://github.com/koalaman/shellcheck/releases/download/$(SHELLCHECK_VERSION)/shellcheck-$(SHELLCHECK_VERSION).$(LINT_LOWER_OS).$(LINT_ARCH).tar.xz | tar -C out/linters -xJf - + mv out/linters/shellcheck-$(SHELLCHECK_VERSION) out/linters/shellcheck-$(SHELLCHECK_VERSION)-$(LINT_ARCH) + +out/linters/hadolint-$(HADOLINT_VERSION)-$(LINT_ARCH): + mkdir -p out/linters + curl -sfL https://github.com/hadolint/hadolint/releases/download/v2.6.1/hadolint-$(LINT_OS)-$(LINT_ARCH) > out/linters/hadolint-$(HADOLINT_VERSION)-$(LINT_ARCH) + chmod u+x out/linters/hadolint-$(HADOLINT_VERSION)-$(LINT_ARCH) + +out/linters/golangci-lint-$(GOLINT_VERSION)-$(LINT_ARCH): + mkdir -p out/linters + curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b out/linters $(GOLINT_VERSION) + mv out/linters/golangci-lint out/linters/golangci-lint-$(GOLINT_VERSION)-$(LINT_ARCH) + +# END: lint-install ../tink From 6a9086a58f96d8c8e3d0029bcfc7270e1ab48199 Mon Sep 17 00:00:00 2001 From: Thomas Stromberg Date: Thu, 2 Sep 2021 20:12:24 -0700 Subject: [PATCH 2/9] Automated fixes from 'make fix' Signed-off-by: Thomas Stromberg --- client/main.go | 14 ++++---- cmd/tink-cli/cmd/completion.go | 2 +- cmd/tink-cli/cmd/docs.go | 6 ++-- cmd/tink-cli/cmd/hardware/commands.go | 2 +- cmd/tink-cli/cmd/hardware/get.go | 6 ++-- cmd/tink-cli/cmd/hardware/id.go | 2 +- cmd/tink-cli/cmd/hardware/ip.go | 2 +- cmd/tink-cli/cmd/hardware/push.go | 2 +- cmd/tink-cli/cmd/root.go | 2 +- cmd/tink-cli/cmd/template/get.go | 8 +++-- cmd/tink-cli/cmd/template/list.go | 4 +-- cmd/tink-cli/cmd/template/update.go | 2 +- cmd/tink-cli/cmd/workflow/data.go | 2 +- cmd/tink-cli/cmd/workflow/events.go | 3 +- cmd/tink-cli/cmd/workflow/get.go | 8 +++-- cmd/tink-cli/cmd/workflow/list.go | 2 +- cmd/tink-cli/cmd/workflow/state.go | 1 - cmd/tink-cli/main.go | 2 +- cmd/tink-server/main.go | 7 ++-- cmd/tink-worker/cmd/root.go | 4 +-- cmd/tink-worker/internal/registry.go | 11 +++---- cmd/tink-worker/internal/worker.go | 12 +++---- cmd/tink-worker/main.go | 6 ++-- db/db.go | 10 +++--- db/db_test.go | 2 +- db/hardware.go | 15 ++++----- db/migration/migration_test.go | 2 -- db/mock/hardware.go | 12 +++---- db/mock/mock.go | 2 +- db/mock/template.go | 12 +++---- db/mock/workflow.go | 30 ++++++++--------- db/template.go | 11 +++---- db/workflow.go | 47 +++++++++++++-------------- grpc-server/grpc_server.go | 4 +-- grpc-server/hardware.go | 8 ++--- grpc-server/template.go | 11 +++---- grpc-server/tinkerbell.go | 19 +++++------ grpc-server/workflow.go | 13 +++----- grpc-server/workflow_test.go | 6 ++-- http-server/http_handlers.go | 8 ++--- http-server/http_handlers_test.go | 1 - http-server/http_server.go | 4 +-- metrics/metrics.go | 4 +-- pkg/hardware_wrapper.go | 4 +-- test/framework/hardware.go | 2 +- test/framework/setup.go | 11 +++---- test/framework/tearDown.go | 2 +- test/framework/template.go | 2 +- test/framework/utils.go | 10 +++--- test/framework/worker.go | 11 ++++--- test/framework/workflow.go | 4 +-- workflow/template_validator.go | 8 ++--- workflow/types.go | 6 ++-- 53 files changed, 188 insertions(+), 203 deletions(-) diff --git a/client/main.go b/client/main.go index 0e3e083fc..97dea1b32 100644 --- a/client/main.go +++ b/client/main.go @@ -16,14 +16,14 @@ import ( "google.golang.org/grpc/credentials" ) -// gRPC clients +// gRPC clients. var ( TemplateClient template.TemplateServiceClient WorkflowClient workflow.WorkflowServiceClient HardwareClient hardware.HardwareServiceClient ) -// FullClient aggregates all the gRPC clients available from Tinkerbell Server +// FullClient aggregates all the gRPC clients available from Tinkerbell Server. type FullClient struct { TemplateClient template.TemplateServiceClient WorkflowClient workflow.WorkflowServiceClient @@ -52,7 +52,7 @@ func NewFullClientFromGlobal() (*FullClient, error) { // NewFullClient returns a FullClient. A structure that contains all the // clients made available from tink-server. This is the function you should use -// instead of NewFullClientFromGlobal that will be deprecated soon +// instead of NewFullClientFromGlobal that will be deprecated soon. func NewFullClient(conn grpc.ClientConnInterface) *FullClient { return &FullClient{ TemplateClient: template.NewTemplateServiceClient(conn), @@ -97,7 +97,7 @@ func NewClientConn(opt *ConnOptions) (*grpc.ClientConn, error) { return conn, nil } -// GetConnection returns a gRPC client connection +// GetConnection returns a gRPC client connection. func GetConnection() (*grpc.ClientConn, error) { certURL := os.Getenv("TINKERBELL_CERT_URL") if certURL == "" { @@ -132,7 +132,7 @@ func GetConnection() (*grpc.ClientConn, error) { return conn, nil } -// Setup : create a connection to server +// Setup : create a connection to server. func Setup() error { conn, err := GetConnection() if err != nil { @@ -144,7 +144,7 @@ func Setup() error { return nil } -// TinkHardwareClient creates a new hardware client +// TinkHardwareClient creates a new hardware client. func TinkHardwareClient() (hardware.HardwareServiceClient, error) { conn, err := GetConnection() if err != nil { @@ -153,7 +153,7 @@ func TinkHardwareClient() (hardware.HardwareServiceClient, error) { return hardware.NewHardwareServiceClient(conn), nil } -// TinkWorkflowClient creates a new workflow client +// TinkWorkflowClient creates a new workflow client. func TinkWorkflowClient() (workflow.WorkflowServiceClient, error) { conn, err := GetConnection() if err != nil { diff --git a/cmd/tink-cli/cmd/completion.go b/cmd/tink-cli/cmd/completion.go index 3cf73649b..24544624f 100644 --- a/cmd/tink-cli/cmd/completion.go +++ b/cmd/tink-cli/cmd/completion.go @@ -8,7 +8,7 @@ import ( ) // completionCmd returns the completion command that, when run, generates a -// bash or zsh completion script for the CLI +// bash or zsh completion script for the CLI. func completionCmd(name string) *cobra.Command { return &cobra.Command{ Use: "completion [bash|zsh|fish|powershell]", diff --git a/cmd/tink-cli/cmd/docs.go b/cmd/tink-cli/cmd/docs.go index cd5adb0b5..0504396be 100644 --- a/cmd/tink-cli/cmd/docs.go +++ b/cmd/tink-cli/cmd/docs.go @@ -7,12 +7,10 @@ import ( "github.com/spf13/cobra/doc" ) -var ( - docsPath string -) +var docsPath string // docsCmd returns the generate command that, when run, generates -// documentation +// documentation. func docsCmd(name string) *cobra.Command { cmd := &cobra.Command{ Use: "docs [markdown|man]", diff --git a/cmd/tink-cli/cmd/hardware/commands.go b/cmd/tink-cli/cmd/hardware/commands.go index 17630dad3..ed6e6f963 100644 --- a/cmd/tink-cli/cmd/hardware/commands.go +++ b/cmd/tink-cli/cmd/hardware/commands.go @@ -15,7 +15,7 @@ import ( ) // SubCommands holds the sub commands for template command -// Example: tinkerbell template [subcommand] +// Example: tinkerbell template [subcommand]. var SubCommands []*cobra.Command func verifyUUIDs(args []string) error { diff --git a/cmd/tink-cli/cmd/hardware/get.go b/cmd/tink-cli/cmd/hardware/get.go index 70b5b26db..35441958a 100644 --- a/cmd/tink-cli/cmd/hardware/get.go +++ b/cmd/tink-cli/cmd/hardware/get.go @@ -53,10 +53,12 @@ func (h *getHardware) PopulateTable(data []interface{}, t table.Writer) error { // even if if has more than one // interface. for _, iface := range hw.GetNetwork().GetInterfaces() { - t.AppendRow(table.Row{hw.Id, + t.AppendRow(table.Row{ + hw.Id, iface.Dhcp.Mac, iface.Dhcp.Ip.Address, - iface.Dhcp.Hostname}) + iface.Dhcp.Hostname, + }) } } } diff --git a/cmd/tink-cli/cmd/hardware/id.go b/cmd/tink-cli/cmd/hardware/id.go index 728be5243..a8d85653e 100644 --- a/cmd/tink-cli/cmd/hardware/id.go +++ b/cmd/tink-cli/cmd/hardware/id.go @@ -14,7 +14,7 @@ import ( "github.com/tinkerbell/tink/protos/hardware" ) -// idCmd represents the id command +// idCmd represents the id command. func NewGetByIDCmd() *cobra.Command { return &cobra.Command{ Use: "id", diff --git a/cmd/tink-cli/cmd/hardware/ip.go b/cmd/tink-cli/cmd/hardware/ip.go index 36cf05698..1c4cc2804 100644 --- a/cmd/tink-cli/cmd/hardware/ip.go +++ b/cmd/tink-cli/cmd/hardware/ip.go @@ -15,7 +15,7 @@ import ( var data bool -// ipCmd represents the ip command +// ipCmd represents the ip command. func NewGetByIPCmd() *cobra.Command { cmd := &cobra.Command{ Use: "ip", diff --git a/cmd/tink-cli/cmd/hardware/push.go b/cmd/tink-cli/cmd/hardware/push.go index 78ab0858d..5e219af3b 100644 --- a/cmd/tink-cli/cmd/hardware/push.go +++ b/cmd/tink-cli/cmd/hardware/push.go @@ -23,7 +23,7 @@ var ( sFile = "file" ) -// pushCmd represents the push command +// pushCmd represents the push command. func NewPushCmd() *cobra.Command { cmd := &cobra.Command{ Use: "push", diff --git a/cmd/tink-cli/cmd/root.go b/cmd/tink-cli/cmd/root.go index 0103322d5..1fb24ae82 100644 --- a/cmd/tink-cli/cmd/root.go +++ b/cmd/tink-cli/cmd/root.go @@ -10,7 +10,7 @@ import ( var cfgFile string -// rootCmd represents the base command when called without any subcommands +// rootCmd represents the base command when called without any subcommands. var rootCmd = &cobra.Command{ Use: "tink", Short: "tinkerbell CLI", diff --git a/cmd/tink-cli/cmd/template/get.go b/cmd/tink-cli/cmd/template/get.go index 3b7f5bec7..250358f25 100644 --- a/cmd/tink-cli/cmd/template/get.go +++ b/cmd/tink-cli/cmd/template/get.go @@ -15,7 +15,7 @@ import ( "github.com/tinkerbell/tink/protos/template" ) -// getCmd represents the get subcommand for template command +// getCmd represents the get subcommand for template command. var GetCmd = &cobra.Command{ Use: "get [id]", Short: "get a template", @@ -84,9 +84,11 @@ func (h *getTemplate) RetrieveData(ctx context.Context, cl *client.FullClient) ( func (h *getTemplate) PopulateTable(data []interface{}, t table.Writer) error { for _, v := range data { if tmp, ok := v.(*template.WorkflowTemplate); ok { - t.AppendRow(table.Row{tmp.Id, tmp.Name, + t.AppendRow(table.Row{ + tmp.Id, tmp.Name, tmp.CreatedAt.AsTime().Format(time.RFC3339), - tmp.UpdatedAt.AsTime().Format(time.RFC3339)}) + tmp.UpdatedAt.AsTime().Format(time.RFC3339), + }) } } return nil diff --git a/cmd/tink-cli/cmd/template/list.go b/cmd/tink-cli/cmd/template/list.go index adaa7d306..ffe5a9bd5 100644 --- a/cmd/tink-cli/cmd/template/list.go +++ b/cmd/tink-cli/cmd/template/list.go @@ -14,7 +14,7 @@ import ( "github.com/tinkerbell/tink/protos/template" ) -// table headers +// table headers. var ( id = "Template ID" name = "Template Name" @@ -27,7 +27,7 @@ var ( t table.Writer ) -// listCmd represents the list subcommand for template command +// listCmd represents the list subcommand for template command. func NewListCommand() *cobra.Command { cmd := &cobra.Command{ Use: "list", diff --git a/cmd/tink-cli/cmd/template/update.go b/cmd/tink-cli/cmd/template/update.go index 252ccd557..e4cff1999 100644 --- a/cmd/tink-cli/cmd/template/update.go +++ b/cmd/tink-cli/cmd/template/update.go @@ -14,7 +14,7 @@ import ( "github.com/tinkerbell/tink/workflow" ) -// updateCmd represents the get subcommand for template command +// updateCmd represents the get subcommand for template command. func NewUpdateCommand() *cobra.Command { cmd := &cobra.Command{ Use: "update [id] [flags]", diff --git a/cmd/tink-cli/cmd/workflow/data.go b/cmd/tink-cli/cmd/workflow/data.go index f9b7a1ed5..20b72e807 100644 --- a/cmd/tink-cli/cmd/workflow/data.go +++ b/cmd/tink-cli/cmd/workflow/data.go @@ -17,7 +17,7 @@ var ( versionOnly bool ) -// dataCmd represents the data subcommand for workflow command +// dataCmd represents the data subcommand for workflow command. func NewDataCommand() *cobra.Command { cmd := &cobra.Command{ Use: "data [id]", diff --git a/cmd/tink-cli/cmd/workflow/events.go b/cmd/tink-cli/cmd/workflow/events.go index 6af1163bd..95eaac26d 100644 --- a/cmd/tink-cli/cmd/workflow/events.go +++ b/cmd/tink-cli/cmd/workflow/events.go @@ -40,7 +40,6 @@ func NewShowCommand() *cobra.Command { t.AppendHeader(table.Row{hWorkerID, hTaskName, hActionName, hExecutionTime, hMessage, hStatus}) listEvents(t, args) t.Render() - }, } return cmd @@ -53,7 +52,7 @@ func listEvents(t table.Writer, args []string) { if err != nil { log.Fatal(err) } - //var wf *workflow.Workflow + // var wf *workflow.Workflow err = nil for event, err := events.Recv(); err == nil && event != nil; event, err = events.Recv() { t.AppendRows([]table.Row{ diff --git a/cmd/tink-cli/cmd/workflow/get.go b/cmd/tink-cli/cmd/workflow/get.go index 96727e3f6..55a0baf0f 100644 --- a/cmd/tink-cli/cmd/workflow/get.go +++ b/cmd/tink-cli/cmd/workflow/get.go @@ -20,7 +20,7 @@ var ( hDevice = "Hardware device" ) -// getCmd represents the get subcommand for workflow command +// getCmd represents the get subcommand for workflow command. var GetCmd = &cobra.Command{ Use: "get [id]", Short: "get a workflow", @@ -85,10 +85,12 @@ func (h *getWorkflow) RetrieveData(ctx context.Context, cl *client.FullClient) ( func (h *getWorkflow) PopulateTable(data []interface{}, t table.Writer) error { for _, v := range data { if w, ok := v.(*workflow.Workflow); ok { - t.AppendRow(table.Row{w.Id, w.Template, + t.AppendRow(table.Row{ + w.Id, w.Template, w.State.String(), w.CreatedAt.AsTime().UTC().Format(time.RFC3339), - w.UpdatedAt.AsTime().UTC().Format(time.RFC3339)}) + w.UpdatedAt.AsTime().UTC().Format(time.RFC3339), + }) } } return nil diff --git a/cmd/tink-cli/cmd/workflow/list.go b/cmd/tink-cli/cmd/workflow/list.go index 6f45abc81..e96458429 100644 --- a/cmd/tink-cli/cmd/workflow/list.go +++ b/cmd/tink-cli/cmd/workflow/list.go @@ -22,7 +22,7 @@ var ( hUpdatedAt = "Updated At" ) -// listCmd represents the list subcommand for workflow command +// listCmd represents the list subcommand for workflow command. func NewListCommand() *cobra.Command { cmd := &cobra.Command{ Use: "list", diff --git a/cmd/tink-cli/cmd/workflow/state.go b/cmd/tink-cli/cmd/workflow/state.go index 28f640bb0..e09aee32c 100644 --- a/cmd/tink-cli/cmd/workflow/state.go +++ b/cmd/tink-cli/cmd/workflow/state.go @@ -43,7 +43,6 @@ func NewStateCommand() *cobra.Command { t.AppendRow(table.Row{"Current Action State", wf.CurrentActionState}) t.Render() - } }, } diff --git a/cmd/tink-cli/main.go b/cmd/tink-cli/main.go index d6d35cec3..84fc73a3c 100644 --- a/cmd/tink-cli/main.go +++ b/cmd/tink-cli/main.go @@ -7,7 +7,7 @@ import ( "github.com/tinkerbell/tink/cmd/tink-cli/cmd" ) -// version is set at build time +// version is set at build time. var version = "devel" func main() { diff --git a/cmd/tink-server/main.go b/cmd/tink-server/main.go index 00e456d27..6c90e157c 100644 --- a/cmd/tink-server/main.go +++ b/cmd/tink-server/main.go @@ -19,10 +19,8 @@ import ( httpServer "github.com/tinkerbell/tink/http-server" ) -var ( - // version is set at build time - version = "devel" -) +// version is set at build time. +var version = "devel" // DaemonConfig represents all the values you can configure as part of the tink-server. // You can change the configuration via environment variable, or file, or command flags. @@ -108,7 +106,6 @@ func main() { if err := cmd.ExecuteContext(context.Background()); err != nil { os.Exit(1) } - } func NewRootCommand(config *DaemonConfig, logger log.Logger) *cobra.Command { diff --git a/cmd/tink-worker/cmd/root.go b/cmd/tink-worker/cmd/root.go index 679b13f07..c68c71c40 100644 --- a/cmd/tink-worker/cmd/root.go +++ b/cmd/tink-worker/cmd/root.go @@ -20,11 +20,11 @@ import ( const ( defaultRetryInterval = 3 defaultRetryCount = 3 - defaultMaxFileSize int64 = 10 * 1024 * 1024 //10MB + defaultMaxFileSize int64 = 10 * 1024 * 1024 // 10MB defaultTimeoutMinutes = 60 ) -// NewRootCommand creates a new Tink Worker Cobra root command +// NewRootCommand creates a new Tink Worker Cobra root command. func NewRootCommand(version string, logger log.Logger) *cobra.Command { rootCmd := &cobra.Command{ Use: "tink-worker", diff --git a/cmd/tink-worker/internal/registry.go b/cmd/tink-worker/internal/registry.go index 97bc13ad5..fe378f809 100644 --- a/cmd/tink-worker/internal/registry.go +++ b/cmd/tink-worker/internal/registry.go @@ -13,7 +13,7 @@ import ( ) // RegistryConnDetails are the connection details for accessing a Docker -// registry and logging activities +// registry and logging activities. type RegistryConnDetails struct { registry, user, @@ -21,7 +21,7 @@ type RegistryConnDetails struct { logger log.Logger } -// ImagePullStatus is the status of the downloaded Image chunk +// ImagePullStatus is the status of the downloaded Image chunk. type ImagePullStatus struct { Status string `json:"status"` Error string `json:"error"` @@ -32,7 +32,7 @@ type ImagePullStatus struct { } `json:"progressDetail"` } -// NewRegistryConnDetails creates a new RegistryConnDetails +// NewRegistryConnDetails creates a new RegistryConnDetails. func NewRegistryConnDetails(registry, user, pwd string, logger log.Logger) *RegistryConnDetails { return &RegistryConnDetails{ registry: registry, @@ -42,13 +42,12 @@ func NewRegistryConnDetails(registry, user, pwd string, logger log.Logger) *Regi } } -// NewClient uses the RegistryConnDetails to create a new Docker Client +// NewClient uses the RegistryConnDetails to create a new Docker Client. func (r *RegistryConnDetails) NewClient() (*client.Client, error) { if r.registry == "" { return nil, errors.New("required DOCKER_REGISTRY") } c, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation()) - if err != nil { return nil, errors.Wrap(err, "DOCKER CLIENT") } @@ -60,7 +59,7 @@ type imagePuller interface { ImagePull(context.Context, string, types.ImagePullOptions) (io.ReadCloser, error) } -// pullImage outputs to stdout the contents of the requested image (relative to the registry) +// pullImage outputs to stdout the contents of the requested image (relative to the registry). func (r *RegistryConnDetails) pullImage(ctx context.Context, cli imagePuller, image string) error { authConfig := types.AuthConfig{ Username: r.user, diff --git a/cmd/tink-worker/internal/worker.go b/cmd/tink-worker/internal/worker.go index 55dfb0e6e..8845eaf78 100644 --- a/cmd/tink-worker/internal/worker.go +++ b/cmd/tink-worker/internal/worker.go @@ -38,7 +38,7 @@ var ( workflowDataSHA = map[string]string{} ) -// WorkflowMetadata is the metadata related to workflow data +// WorkflowMetadata is the metadata related to workflow data. type WorkflowMetadata struct { WorkerID string `json:"workerID"` Action string `json:"actionName"` @@ -47,7 +47,7 @@ type WorkflowMetadata struct { SHA string `json:"sha256"` } -// Worker details provide all the context needed to run a +// Worker details provide all the context needed to run a. type Worker struct { client pb.WorkflowServiceClient regConn *RegistryConnDetails @@ -59,7 +59,7 @@ type Worker struct { maxSize int64 } -// NewWorker creates a new Worker, creating a new Docker registry client +// NewWorker creates a new Worker, creating a new Docker registry client. func NewWorker(client pb.WorkflowServiceClient, regConn *RegistryConnDetails, logger log.Logger, registry string, retries int, retryInterval time.Duration, maxFileSize int64) *Worker { registryClient, err := regConn.NewClient() if err != nil { @@ -188,7 +188,7 @@ func (w *Worker) execute(ctx context.Context, wfID string, action *pb.WorkflowAc return status, nil } -// ProcessWorkflowActions gets all Workflow contexts and processes their actions +// ProcessWorkflowActions gets all Workflow contexts and processes their actions. func (w *Worker) ProcessWorkflowActions(ctx context.Context, workerID string, captureActionLogs bool) error { l := w.logger.With("workerID", workerID) @@ -249,7 +249,7 @@ func (w *Worker) ProcessWorkflowActions(ctx context.Context, workerID string, ca "taskName", actions.GetActionList()[actionIndex].GetTaskName(), ) if _, err := os.Stat(wfDir); os.IsNotExist(err) { - err := os.Mkdir(wfDir, os.FileMode(0755)) + err := os.Mkdir(wfDir, os.FileMode(0o755)) if err != nil { l.Error(err) os.Exit(1) @@ -474,7 +474,7 @@ func sendUpdate(ctx context.Context, logger log.Logger, client pb.WorkflowServic } func openDataFile(wfDir string, l log.Logger) *os.File { - f, err := os.OpenFile(filepath.Clean(wfDir+string(os.PathSeparator)+dataFile), os.O_RDWR|os.O_CREATE, 0600) + f, err := os.OpenFile(filepath.Clean(wfDir+string(os.PathSeparator)+dataFile), os.O_RDWR|os.O_CREATE, 0o600) if err != nil { l.Error(err) os.Exit(1) diff --git a/cmd/tink-worker/main.go b/cmd/tink-worker/main.go index 8a8c0cea0..4e590ef29 100644 --- a/cmd/tink-worker/main.go +++ b/cmd/tink-worker/main.go @@ -11,10 +11,8 @@ const ( serviceKey = "github.com/tinkerbell/tink" ) -var ( - // version is set at build time - version = "devel" -) +// version is set at build time. +var version = "devel" func main() { logger, err := log.Init(serviceKey) diff --git a/db/db.go b/db/db.go index e4107bca8..c58daaadd 100644 --- a/db/db.go +++ b/db/db.go @@ -17,7 +17,7 @@ import ( pb "github.com/tinkerbell/tink/protos/workflow" ) -// Database interface for tinkerbell database operations +// Database interface for tinkerbell database operations. type Database interface { hardware template @@ -59,13 +59,13 @@ type workflow interface { ShowWorkflowEvents(wfID string, fn func(wfs *pb.WorkflowActionStatus) error) error } -// TinkDB implements the Database interface +// TinkDB implements the Database interface. type TinkDB struct { instance *sql.DB logger log.Logger } -// Connect returns a connection to postgres database +// Connect returns a connection to postgres database. func Connect(db *sql.DB, lg log.Logger) *TinkDB { return &TinkDB{instance: db, logger: lg} } @@ -83,7 +83,7 @@ func (t *TinkDB) CheckRequiredMigrations() (int, error) { return len(migrations) - len(records), nil } -// Error returns the underlying cause for error +// Error returns the underlying cause for error. func Error(err error) *pq.Error { if pqErr, ok := errors.Cause(err).(*pq.Error); ok { return pqErr @@ -103,7 +103,7 @@ func get(ctx context.Context, db *sql.DB, query string, args ...interface{}) (st } // buildGetCondition builds a where condition string in the format "column_name = 'field_value' AND" -// takes in a map[string]string with keys being the column name and the values being the field values +// takes in a map[string]string with keys being the column name and the values being the field values. func buildGetCondition(fields map[string]string) (string, error) { for column, field := range fields { if field != "" { diff --git a/db/db_test.go b/db/db_test.go index cc3ed4d84..97fe6ff15 100644 --- a/db/db_test.go +++ b/db/db_test.go @@ -20,7 +20,7 @@ type NewPostgresDatabaseRequest struct { // NewPostgresDatabaseClient returns a SQL client ready to be used. Behind the // scene it is starting a Docker container that will get cleaned up when the -// test is over. Tests using this function are safe to run in parallel +// test is over. Tests using this function are safe to run in parallel. func NewPostgresDatabaseClient(t *testing.T, ctx context.Context, req NewPostgresDatabaseRequest) (*sql.DB, *db.TinkDB, func() error) { testcontainers.SkipIfProviderIsNotHealthy(t) postgresC, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ diff --git a/db/hardware.go b/db/hardware.go index 19b49ab43..ec70e01cc 100644 --- a/db/hardware.go +++ b/db/hardware.go @@ -11,7 +11,7 @@ import ( "google.golang.org/grpc/status" ) -// DeleteFromDB : delete data from hardware table +// DeleteFromDB : delete data from hardware table. func (d TinkDB) DeleteFromDB(ctx context.Context, id string) error { tx, err := d.instance.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable}) if err != nil { @@ -25,7 +25,6 @@ func (d TinkDB) DeleteFromDB(ctx context.Context, id string) error { WHERE id = $1; `, id) - if err != nil { return errors.Wrap(err, "DELETE") } @@ -41,7 +40,7 @@ func (d TinkDB) DeleteFromDB(ctx context.Context, id string) error { return nil } -// InsertIntoDB : insert data into hardware table +// InsertIntoDB : insert data into hardware table. func (d TinkDB) InsertIntoDB(ctx context.Context, data string) error { tx, err := d.instance.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable}) if err != nil { @@ -69,7 +68,7 @@ func (d TinkDB) InsertIntoDB(ctx context.Context, data string) error { return nil } -// GetByMAC : get data by machine mac +// GetByMAC : get data by machine mac. func (d TinkDB) GetByMAC(ctx context.Context, mac string) (string, error) { arg := ` { @@ -96,7 +95,7 @@ func (d TinkDB) GetByMAC(ctx context.Context, mac string) (string, error) { return get(ctx, d.instance, query, arg) } -// GetByIP : get data by machine ip +// GetByIP : get data by machine ip. func (d TinkDB) GetByIP(ctx context.Context, ip string) (string, error) { instance := ` { @@ -140,7 +139,7 @@ func (d TinkDB) GetByIP(ctx context.Context, ip string) (string, error) { return get(ctx, d.instance, query, instance, hardwareOrManagement) } -// GetByID : get data by machine id +// GetByID : get data by machine id. func (d TinkDB) GetByID(ctx context.Context, id string) (string, error) { arg := id @@ -155,7 +154,7 @@ func (d TinkDB) GetByID(ctx context.Context, id string) (string, error) { return get(ctx, d.instance, query, arg) } -// GetAll : get data for all machine +// GetAll : get data for all machine. func (d TinkDB) GetAll(fn func([]byte) error) error { rows, err := d.instance.Query(` SELECT data @@ -163,7 +162,6 @@ func (d TinkDB) GetAll(fn func([]byte) error) error { WHERE deleted_at IS NULL `) - if err != nil { return err } @@ -182,7 +180,6 @@ func (d TinkDB) GetAll(fn func([]byte) error) error { if err != nil { return err } - } err = rows.Err() diff --git a/db/migration/migration_test.go b/db/migration/migration_test.go index dc7b43eb4..f06ba317b 100644 --- a/db/migration/migration_test.go +++ b/db/migration/migration_test.go @@ -42,7 +42,6 @@ func TestMigrationsAreOrderendInTheWayWeDeclaredThem(t *testing.T) { t.Errorf("Expected migration \"%s\" but got \"%s\"", dm.Id, orderedMigration[ii].Id) } } - } func TestMigrationFuncNamesMatchIDs(t *testing.T) { @@ -65,7 +64,6 @@ func TestMigrationFuncNamesMatchIDs(t *testing.T) { assert.NotContains(t, timestamps, mid) } - } func TestGetMigrations(t *testing.T) { diff --git a/db/mock/hardware.go b/db/mock/hardware.go index f01054502..acd56ec72 100644 --- a/db/mock/hardware.go +++ b/db/mock/hardware.go @@ -4,32 +4,32 @@ import ( "context" ) -// DeleteFromDB : delete data from hardware table +// DeleteFromDB : delete data from hardware table. func (d DB) DeleteFromDB(ctx context.Context, id string) error { return nil } -// InsertIntoDB : insert data into hardware table +// InsertIntoDB : insert data into hardware table. func (d DB) InsertIntoDB(ctx context.Context, data string) error { return nil } -// GetByMAC : get data by machine mac +// GetByMAC : get data by machine mac. func (d DB) GetByMAC(ctx context.Context, mac string) (string, error) { return "", nil } -// GetByIP : get data by machine ip +// GetByIP : get data by machine ip. func (d DB) GetByIP(ctx context.Context, ip string) (string, error) { return "", nil } -// GetByID : get data by machine id +// GetByID : get data by machine id. func (d DB) GetByID(ctx context.Context, id string) (string, error) { return "", nil } -// GetAll : get data for all machine +// GetAll : get data for all machine. func (d DB) GetAll(fn func([]byte) error) error { return nil } diff --git a/db/mock/mock.go b/db/mock/mock.go index bccd3976f..57cfb14a9 100644 --- a/db/mock/mock.go +++ b/db/mock/mock.go @@ -10,7 +10,7 @@ import ( pb "github.com/tinkerbell/tink/protos/workflow" ) -// DB is the mocked implementation of Database interface +// DB is the mocked implementation of Database interface. type DB struct { // workflow CreateWorkflowFunc func(ctx context.Context, wf db.Workflow, data string, id uuid.UUID) error diff --git a/db/mock/template.go b/db/mock/template.go index 533fea17f..5bdd2a6e0 100644 --- a/db/mock/template.go +++ b/db/mock/template.go @@ -15,7 +15,7 @@ type Template struct { Deleted bool } -// CreateTemplate creates a new workflow template +// CreateTemplate creates a new workflow template. func (d *DB) CreateTemplate(ctx context.Context, name string, data string, id uuid.UUID) error { if d.TemplateDB == nil { d.TemplateDB = make(map[string]interface{}) @@ -41,12 +41,12 @@ func (d *DB) CreateTemplate(ctx context.Context, name string, data string, id uu return nil } -// GetTemplate returns a workflow template +// GetTemplate returns a workflow template. func (d DB) GetTemplate(ctx context.Context, fields map[string]string, deleted bool) (*tb.WorkflowTemplate, error) { return d.GetTemplateFunc(ctx, fields, deleted) } -// DeleteTemplate deletes a workflow template +// DeleteTemplate deletes a workflow template. func (d DB) DeleteTemplate(ctx context.Context, name string) error { if d.TemplateDB != nil { delete(d.TemplateDB, name) @@ -55,17 +55,17 @@ func (d DB) DeleteTemplate(ctx context.Context, name string) error { return nil } -// ListTemplates returns all saved templates +// ListTemplates returns all saved templates. func (d DB) ListTemplates(in string, fn func(id, n string, in, del *timestamp.Timestamp) error) error { return nil } -// UpdateTemplate update a given template +// UpdateTemplate update a given template. func (d DB) UpdateTemplate(ctx context.Context, name string, data string, id uuid.UUID) error { return nil } -// ClearTemplateDB clear all the templates +// ClearTemplateDB clear all the templates. func (d *DB) ClearTemplateDB() { d.TemplateDB = make(map[string]interface{}) } diff --git a/db/mock/workflow.go b/db/mock/workflow.go index 4a845802f..7a6f85ef1 100644 --- a/db/mock/workflow.go +++ b/db/mock/workflow.go @@ -9,77 +9,77 @@ import ( pb "github.com/tinkerbell/tink/protos/workflow" ) -// CreateWorkflow creates a new workflow +// CreateWorkflow creates a new workflow. func (d DB) CreateWorkflow(ctx context.Context, wf db.Workflow, data string, id uuid.UUID) error { return d.CreateWorkflowFunc(ctx, wf, data, id) } -// InsertIntoWfDataTable : Insert ephemeral data in workflow_data table +// InsertIntoWfDataTable : Insert ephemeral data in workflow_data table. func (d DB) InsertIntoWfDataTable(ctx context.Context, req *pb.UpdateWorkflowDataRequest) error { return d.InsertIntoWfDataTableFunc(ctx, req) } -// GetfromWfDataTable : Give you the ephemeral data from workflow_data table +// GetfromWfDataTable : Give you the ephemeral data from workflow_data table. func (d DB) GetfromWfDataTable(ctx context.Context, req *pb.GetWorkflowDataRequest) ([]byte, error) { return d.GetfromWfDataTableFunc(ctx, req) } -// GetWorkflowMetadata returns metadata wrt to the ephemeral data of a workflow +// GetWorkflowMetadata returns metadata wrt to the ephemeral data of a workflow. func (d DB) GetWorkflowMetadata(ctx context.Context, req *pb.GetWorkflowDataRequest) ([]byte, error) { return d.GetWorkflowMetadataFunc(ctx, req) } -// GetWorkflowDataVersion returns the latest version of data for a workflow +// GetWorkflowDataVersion returns the latest version of data for a workflow. func (d DB) GetWorkflowDataVersion(ctx context.Context, workflowID string) (int32, error) { return d.GetWorkflowDataVersionFunc(ctx, workflowID) } -// GetWorkflowsForWorker : returns the list of workflows for a particular worker +// GetWorkflowsForWorker : returns the list of workflows for a particular worker. func (d DB) GetWorkflowsForWorker(id string) ([]string, error) { return d.GetWorkflowsForWorkerFunc(id) } -// GetWorkflow returns a workflow +// GetWorkflow returns a workflow. func (d DB) GetWorkflow(ctx context.Context, id string) (db.Workflow, error) { return d.GetWorkflowFunc(ctx, id) } -// DeleteWorkflow deletes a workflow +// DeleteWorkflow deletes a workflow. func (d DB) DeleteWorkflow(ctx context.Context, id string, state int32) error { return nil } -// ListWorkflows returns all workflows +// ListWorkflows returns all workflows. func (d DB) ListWorkflows(fn func(wf db.Workflow) error) error { return nil } -// UpdateWorkflow updates a given workflow +// UpdateWorkflow updates a given workflow. func (d DB) UpdateWorkflow(ctx context.Context, wf db.Workflow, state int32) error { return nil } -// UpdateWorkflowState : update the current workflow state +// UpdateWorkflowState : update the current workflow state. func (d DB) UpdateWorkflowState(ctx context.Context, wfContext *pb.WorkflowContext) error { return d.UpdateWorkflowStateFunc(ctx, wfContext) } -// GetWorkflowContexts : gives you the current workflow context +// GetWorkflowContexts : gives you the current workflow context. func (d DB) GetWorkflowContexts(ctx context.Context, wfID string) (*pb.WorkflowContext, error) { return d.GetWorkflowContextsFunc(ctx, wfID) } -// GetWorkflowActions : gives you the action list of workflow +// GetWorkflowActions : gives you the action list of workflow. func (d DB) GetWorkflowActions(ctx context.Context, wfID string) (*pb.WorkflowActionList, error) { return d.GetWorkflowActionsFunc(ctx, wfID) } -// InsertIntoWorkflowEventTable : insert workflow event table +// InsertIntoWorkflowEventTable : insert workflow event table. func (d DB) InsertIntoWorkflowEventTable(ctx context.Context, wfEvent *pb.WorkflowActionStatus, time time.Time) error { return d.InsertIntoWorkflowEventTableFunc(ctx, wfEvent, time) } -// ShowWorkflowEvents returns all workflows +// ShowWorkflowEvents returns all workflows. func (d DB) ShowWorkflowEvents(wfID string, fn func(wfs *pb.WorkflowActionStatus) error) error { return nil } diff --git a/db/template.go b/db/template.go index 043a8f067..569c09ef4 100644 --- a/db/template.go +++ b/db/template.go @@ -16,7 +16,7 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" ) -// CreateTemplate creates a new workflow template +// CreateTemplate creates a new workflow template. func (d TinkDB) CreateTemplate(ctx context.Context, name string, data string, id uuid.UUID) error { _, err := wflow.Parse([]byte(data)) if err != nil { @@ -48,7 +48,7 @@ func (d TinkDB) CreateTemplate(ctx context.Context, name string, data string, id return nil } -// GetTemplate returns template which is not deleted +// GetTemplate returns template which is not deleted. func (d TinkDB) GetTemplate(ctx context.Context, fields map[string]string, deleted bool) (*tb.WorkflowTemplate, error) { getCondition, err := buildGetCondition(fields) if err != nil { @@ -100,7 +100,7 @@ func (d TinkDB) GetTemplate(ctx context.Context, fields map[string]string, delet return &tb.WorkflowTemplate{}, err } -// DeleteTemplate deletes a workflow template by id +// DeleteTemplate deletes a workflow template by id. func (d TinkDB) DeleteTemplate(ctx context.Context, id string) error { tx, err := d.instance.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable}) if err != nil { @@ -129,7 +129,7 @@ func (d TinkDB) DeleteTemplate(ctx context.Context, id string) error { return nil } -// ListTemplates returns all saved templates +// ListTemplates returns all saved templates. func (d TinkDB) ListTemplates(filter string, fn func(id, n string, in, del *timestamp.Timestamp) error) error { rows, err := d.instance.Query(` SELECT id, name, created_at, updated_at @@ -139,7 +139,6 @@ func (d TinkDB) ListTemplates(filter string, fn func(id, n string, in, del *time AND deleted_at IS NULL; `, filter) - if err != nil { return err } @@ -175,7 +174,7 @@ func (d TinkDB) ListTemplates(filter string, fn func(id, n string, in, del *time return err } -// UpdateTemplate update a given template +// UpdateTemplate update a given template. func (d TinkDB) UpdateTemplate(ctx context.Context, name string, data string, id uuid.UUID) error { tx, err := d.instance.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable}) if err != nil { diff --git a/db/workflow.go b/db/workflow.go index fa470cd5a..0cad04eb0 100644 --- a/db/workflow.go +++ b/db/workflow.go @@ -21,7 +21,7 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" ) -// Workflow represents a workflow instance in database +// Workflow represents a workflow instance in database. type Workflow struct { State int32 ID, Hardware, Template string @@ -33,7 +33,7 @@ var ( maxVersions = defaultMaxVersions // maximum number of workflow data versions to be kept in database ) -// CreateWorkflow creates a new workflow +// CreateWorkflow creates a new workflow. func (d TinkDB) CreateWorkflow(ctx context.Context, wf Workflow, data string, id uuid.UUID) error { tx, err := d.instance.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable}) if err != nil { @@ -43,12 +43,10 @@ func (d TinkDB) CreateWorkflow(ctx context.Context, wf Workflow, data string, id err = insertActionList(ctx, d.instance, data, id, tx) if err != nil { return errors.Wrap(err, "failed to create workflow") - } err = insertInWorkflow(ctx, d.instance, wf, tx) if err != nil { return errors.Wrap(err, "failed to create workflow") - } err = tx.Commit() if err != nil { @@ -89,7 +87,7 @@ func insertIntoWfWorkerTable(ctx context.Context, db *sql.DB, wfID uuid.UUID, wo return nil } -// Insert actions in the workflow_state table +// Insert actions in the workflow_state table. func insertActionList(ctx context.Context, db *sql.DB, yamlData string, id uuid.UUID, tx *sql.Tx) error { wf, err := wflow.Parse([]byte(yamlData)) if err != nil { @@ -191,14 +189,14 @@ func insertActionList(ctx context.Context, db *sql.DB, yamlData string, id uuid. return nil } -// InsertIntoWfDataTable : Insert ephemeral data in workflow_data table +// InsertIntoWfDataTable : Insert ephemeral data in workflow_data table. func (d TinkDB) InsertIntoWfDataTable(ctx context.Context, req *pb.UpdateWorkflowDataRequest) error { version, err := getLatestVersionWfData(ctx, d.instance, req.GetWorkflowId()) if err != nil { return err } - //increment version + // increment version version = version + 1 tx, err := d.instance.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable}) if err != nil { @@ -236,7 +234,7 @@ func (d TinkDB) InsertIntoWfDataTable(ctx context.Context, req *pb.UpdateWorkflo return nil } -// GetfromWfDataTable : Give you the ephemeral data from workflow_data table +// GetfromWfDataTable : Give you the ephemeral data from workflow_data table. func (d TinkDB) GetfromWfDataTable(ctx context.Context, req *pb.GetWorkflowDataRequest) ([]byte, error) { version := req.GetVersion() if req.Version == 0 { @@ -267,7 +265,7 @@ func (d TinkDB) GetfromWfDataTable(ctx context.Context, req *pb.GetWorkflowDataR return []byte{}, nil } -// GetWorkflowMetadata returns metadata wrt to the ephemeral data of a workflow +// GetWorkflowMetadata returns metadata wrt to the ephemeral data of a workflow. func (d TinkDB) GetWorkflowMetadata(ctx context.Context, req *pb.GetWorkflowDataRequest) ([]byte, error) { version := req.GetVersion() if req.Version == 0 { @@ -298,12 +296,12 @@ func (d TinkDB) GetWorkflowMetadata(ctx context.Context, req *pb.GetWorkflowData return []byte{}, nil } -// GetWorkflowDataVersion returns the latest version of data for a workflow +// GetWorkflowDataVersion returns the latest version of data for a workflow. func (d TinkDB) GetWorkflowDataVersion(ctx context.Context, workflowID string) (int32, error) { return getLatestVersionWfData(ctx, d.instance, workflowID) } -// GetWorkflowsForWorker : returns the list of workflows for a particular worker +// GetWorkflowsForWorker : returns the list of workflows for a particular worker. func (d TinkDB) GetWorkflowsForWorker(id string) ([]string, error) { rows, err := d.instance.Query(` SELECT workflow_id @@ -334,7 +332,7 @@ func (d TinkDB) GetWorkflowsForWorker(id string) ([]string, error) { return wfID, err } -// GetWorkflow returns a workflow +// GetWorkflow returns a workflow. func (d TinkDB) GetWorkflow(ctx context.Context, id string) (Workflow, error) { query := ` SELECT template, devices, created_at, updated_at @@ -370,7 +368,7 @@ func (d TinkDB) GetWorkflow(ctx context.Context, id string) (Workflow, error) { return Workflow{}, errors.New("Workflow with id " + id + " does not exist") } -// DeleteWorkflow deletes a workflow +// DeleteWorkflow deletes a workflow. func (d TinkDB) DeleteWorkflow(ctx context.Context, id string, state int32) error { tx, err := d.instance.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable}) if err != nil { @@ -417,7 +415,7 @@ func (d TinkDB) DeleteWorkflow(ctx context.Context, id string, state int32) erro return nil } -// ListWorkflows returns all workflows +// ListWorkflows returns all workflows. func (d TinkDB) ListWorkflows(fn func(wf Workflow) error) error { rows, err := d.instance.Query(` SELECT id, template, devices, created_at, updated_at @@ -425,7 +423,6 @@ func (d TinkDB) ListWorkflows(fn func(wf Workflow) error) error { WHERE deleted_at IS NULL; `) - if err != nil { return err } @@ -463,7 +460,7 @@ func (d TinkDB) ListWorkflows(fn func(wf Workflow) error) error { return err } -// UpdateWorkflow updates a given workflow +// UpdateWorkflow updates a given workflow. func (d TinkDB) UpdateWorkflow(ctx context.Context, wf Workflow, state int32) error { tx, err := d.instance.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable}) if err != nil { @@ -507,7 +504,7 @@ func (d TinkDB) UpdateWorkflow(ctx context.Context, wf Workflow, state int32) er return nil } -// UpdateWorkflowState : update the current workflow state +// UpdateWorkflowState : update the current workflow state. func (d TinkDB) UpdateWorkflowState(ctx context.Context, wfContext *pb.WorkflowContext) error { tx, err := d.instance.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable}) if err != nil { @@ -534,7 +531,7 @@ func (d TinkDB) UpdateWorkflowState(ctx context.Context, wfContext *pb.WorkflowC return nil } -// GetWorkflowContexts : gives you the current workflow context +// GetWorkflowContexts : gives you the current workflow context. func (d TinkDB) GetWorkflowContexts(ctx context.Context, wfID string) (*pb.WorkflowContext, error) { query := ` SELECT current_worker, current_task_name, current_action_name, current_action_index, current_action_state, total_number_of_actions @@ -555,7 +552,8 @@ func (d TinkDB) GetWorkflowContexts(ctx context.Context, wfID string) (*pb.Workf CurrentAction: ca, CurrentActionIndex: cai, CurrentActionState: cas, - TotalNumberOfActions: tact}, nil + TotalNumberOfActions: tact, + }, nil } if err != sql.ErrNoRows { err = errors.Wrap(err, "SELECT from worflow_state") @@ -565,7 +563,7 @@ func (d TinkDB) GetWorkflowContexts(ctx context.Context, wfID string) (*pb.Workf return &pb.WorkflowContext{}, errors.New("Workflow with id " + wfID + " does not exist") } -// GetWorkflowActions : gives you the action list of workflow +// GetWorkflowActions : gives you the action list of workflow. func (d TinkDB) GetWorkflowActions(ctx context.Context, wfID string) (*pb.WorkflowActionList, error) { query := ` SELECT action_list @@ -582,7 +580,8 @@ func (d TinkDB) GetWorkflowActions(ctx context.Context, wfID string) (*pb.Workfl return nil, err } return &pb.WorkflowActionList{ - ActionList: actions}, nil + ActionList: actions, + }, nil } if err != sql.ErrNoRows { err = errors.Wrap(err, "SELECT from worflow_state") @@ -591,7 +590,7 @@ func (d TinkDB) GetWorkflowActions(ctx context.Context, wfID string) (*pb.Workfl return &pb.WorkflowActionList{}, nil } -// InsertIntoWorkflowEventTable : insert workflow event table +// InsertIntoWorkflowEventTable : insert workflow event table. func (d TinkDB) InsertIntoWorkflowEventTable(ctx context.Context, wfEvent *pb.WorkflowActionStatus, time time.Time) error { tx, err := d.instance.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable}) if err != nil { @@ -615,7 +614,7 @@ func (d TinkDB) InsertIntoWorkflowEventTable(ctx context.Context, wfEvent *pb.Wo return nil } -// ShowWorkflowEvents returns all workflows +// ShowWorkflowEvents returns all workflows. func (d TinkDB) ShowWorkflowEvents(wfID string, fn func(wfs *pb.WorkflowActionStatus) error) error { rows, err := d.instance.Query(` SELECT worker_id, task_name, action_name, execution_time, message, status, created_at @@ -625,7 +624,6 @@ func (d TinkDB) ShowWorkflowEvents(wfID string, fn func(wfs *pb.WorkflowActionSt ORDER BY created_at ASC; `, wfID) - if err != nil { return err } @@ -770,7 +768,6 @@ func getWorkerID(ctx context.Context, db *sql.DB, addr string) (string, error) { } id, err := getWorkerIDbyIP(ctx, db, addr) return id, errors.WithMessage(err, "no worker found") - } id, err := getWorkerIDbyMac(ctx, db, parsedMAC.String()) return id, errors.WithMessage(err, "no worker found") diff --git a/grpc-server/grpc_server.go b/grpc-server/grpc_server.go index e971d5066..b3fe4aad9 100644 --- a/grpc-server/grpc_server.go +++ b/grpc-server/grpc_server.go @@ -24,7 +24,7 @@ import ( "google.golang.org/grpc/reflection" ) -// Server is the gRPC server for tinkerbell +// Server is the gRPC server for tinkerbell. type server struct { cert []byte modT time.Time @@ -48,7 +48,7 @@ type ConfigGRPCServer struct { DB *db.TinkDB } -// SetupGRPC setup and return a gRPC server +// SetupGRPC setup and return a gRPC server. func SetupGRPC(ctx context.Context, logger log.Logger, config *ConfigGRPCServer, errCh chan<- error) ([]byte, time.Time) { params := []grpc.ServerOption{ grpc.UnaryInterceptor(grpc_prometheus.UnaryServerInterceptor), diff --git a/grpc-server/hardware.go b/grpc-server/hardware.go index ee6428c62..1d8100c12 100644 --- a/grpc-server/hardware.go +++ b/grpc-server/hardware.go @@ -140,14 +140,14 @@ func (s *server) ByIP(ctx context.Context, in *hardware.GetRequest) (*hardware.H }) } -// ByID implements hardware.ByID +// ByID implements hardware.ByID. func (s *server) ByID(ctx context.Context, in *hardware.GetRequest) (*hardware.Hardware, error) { return s.by("ByID", func() (string, error) { return s.db.GetByID(ctx, in.Id) }) } -// ALL implements hardware.All +// ALL implements hardware.All. func (s *server) All(_ *hardware.Empty, stream hardware.HardwareService_AllServer) error { labels := prometheus.Labels{"method": "All", "op": "get"} @@ -241,12 +241,12 @@ func (s *server) DeprecatedWatch(in *hardware.GetRequest, stream hardware.Hardwa } } -// Cert returns the public cert that can be served to clients +// Cert returns the public cert that can be served to clients. func (s *server) Cert() []byte { return s.cert } -// ModTime returns the modified-time of the grpc cert +// ModTime returns the modified-time of the grpc cert. func (s *server) ModTime() time.Time { return s.modT } diff --git a/grpc-server/template.go b/grpc-server/template.go index b8bc44ddb..0dc2cd53c 100644 --- a/grpc-server/template.go +++ b/grpc-server/template.go @@ -13,7 +13,7 @@ import ( "github.com/tinkerbell/tink/protos/template" ) -// CreateTemplate implements template.CreateTemplate +// CreateTemplate implements template.CreateTemplate. func (s *server) CreateTemplate(ctx context.Context, in *template.WorkflowTemplate) (*template.CreateResponse, error) { s.logger.Info("createtemplate") labels := prometheus.Labels{"method": "CreateTemplate", "op": ""} @@ -43,7 +43,7 @@ func (s *server) CreateTemplate(ctx context.Context, in *template.WorkflowTempla return &template.CreateResponse{Id: id.String()}, err } -// GetTemplate implements template.GetTemplate +// GetTemplate implements template.GetTemplate. func (s *server) GetTemplate(ctx context.Context, in *template.GetRequest) (*template.WorkflowTemplate, error) { s.logger.Info("gettemplate") labels := prometheus.Labels{"method": "GetTemplate", "op": ""} @@ -75,7 +75,7 @@ func (s *server) GetTemplate(ctx context.Context, in *template.GetRequest) (*tem return wtmpl, err } -// DeleteTemplate implements template.DeleteTemplate +// DeleteTemplate implements template.DeleteTemplate. func (s *server) DeleteTemplate(ctx context.Context, in *template.GetRequest) (*template.Empty, error) { s.logger.Info("deletetemplate") labels := prometheus.Labels{"method": "DeleteTemplate", "op": ""} @@ -103,7 +103,7 @@ func (s *server) DeleteTemplate(ctx context.Context, in *template.GetRequest) (* return &template.Empty{}, err } -// ListTemplates implements template.ListTemplates +// ListTemplates implements template.ListTemplates. func (s *server) ListTemplates(in *template.ListRequest, stream template.TemplateService_ListTemplatesServer) error { s.logger.Info("listtemplates") labels := prometheus.Labels{"method": "ListTemplates", "op": "list"} @@ -129,7 +129,6 @@ func (s *server) ListTemplates(in *template.ListRequest, stream template.Templat err := s.db.ListTemplates(filter, func(id, n string, crTime, upTime *timestamp.Timestamp) error { return stream.Send(&template.WorkflowTemplate{Id: id, Name: n, CreatedAt: crTime, UpdatedAt: upTime}) }) - if err != nil { metrics.CacheErrors.With(labels).Inc() return err @@ -139,7 +138,7 @@ func (s *server) ListTemplates(in *template.ListRequest, stream template.Templat return nil } -// UpdateTemplate implements template.UpdateTemplate +// UpdateTemplate implements template.UpdateTemplate. func (s *server) UpdateTemplate(ctx context.Context, in *template.WorkflowTemplate) (*template.Empty, error) { s.logger.Info("updatetemplate") labels := prometheus.Labels{"method": "UpdateTemplate", "op": ""} diff --git a/grpc-server/tinkerbell.go b/grpc-server/tinkerbell.go index 14ed269a0..c8e048d11 100644 --- a/grpc-server/tinkerbell.go +++ b/grpc-server/tinkerbell.go @@ -28,7 +28,7 @@ const ( msgSendWfContext = "send workflow context: %s" ) -// GetWorkflowContexts implements tinkerbell.GetWorkflowContexts +// GetWorkflowContexts implements tinkerbell.GetWorkflowContexts. func (s *server) GetWorkflowContexts(req *pb.WorkflowContextRequest, stream pb.WorkflowService_GetWorkflowContextsServer) error { wfs, err := getWorkflowsForWorker(s.db, req.WorkerId) if err != nil { @@ -48,7 +48,7 @@ func (s *server) GetWorkflowContexts(req *pb.WorkflowContextRequest, stream pb.W return nil } -// GetWorkflowContextList implements tinkerbell.GetWorkflowContextList +// GetWorkflowContextList implements tinkerbell.GetWorkflowContextList. func (s *server) GetWorkflowContextList(context context.Context, req *pb.WorkflowContextRequest) (*pb.WorkflowContextList, error) { wfs, err := getWorkflowsForWorker(s.db, req.WorkerId) if err != nil { @@ -71,7 +71,7 @@ func (s *server) GetWorkflowContextList(context context.Context, req *pb.Workflo return nil, nil } -// GetWorkflowActions implements tinkerbell.GetWorkflowActions +// GetWorkflowActions implements tinkerbell.GetWorkflowActions. func (s *server) GetWorkflowActions(context context.Context, req *pb.WorkflowActionsRequest) (*pb.WorkflowActionList, error) { wfID := req.GetWorkflowId() if wfID == "" { @@ -80,7 +80,7 @@ func (s *server) GetWorkflowActions(context context.Context, req *pb.WorkflowAct return getWorkflowActions(context, s.db, wfID) } -// ReportActionStatus implements tinkerbell.ReportActionStatus +// ReportActionStatus implements tinkerbell.ReportActionStatus. func (s *server) ReportActionStatus(context context.Context, req *pb.WorkflowActionStatus) (*pb.Empty, error) { wfID := req.GetWorkflowId() if wfID == "" { @@ -148,7 +148,7 @@ func (s *server) ReportActionStatus(context context.Context, req *pb.WorkflowAct return &pb.Empty{}, nil } -// UpdateWorkflowData updates workflow ephemeral data +// UpdateWorkflowData updates workflow ephemeral data. func (s *server) UpdateWorkflowData(context context.Context, req *pb.UpdateWorkflowDataRequest) (*pb.Empty, error) { wfID := req.GetWorkflowId() if wfID == "" { @@ -165,7 +165,7 @@ func (s *server) UpdateWorkflowData(context context.Context, req *pb.UpdateWorkf return &pb.Empty{}, nil } -// GetWorkflowData gets the ephemeral data for a workflow +// GetWorkflowData gets the ephemeral data for a workflow. func (s *server) GetWorkflowData(context context.Context, req *pb.GetWorkflowDataRequest) (*pb.GetWorkflowDataResponse, error) { wfID := req.GetWorkflowId() if wfID == "" { @@ -178,7 +178,7 @@ func (s *server) GetWorkflowData(context context.Context, req *pb.GetWorkflowDat return &pb.GetWorkflowDataResponse{Data: data}, nil } -// GetWorkflowMetadata returns metadata wrt to the ephemeral data of a workflow +// GetWorkflowMetadata returns metadata wrt to the ephemeral data of a workflow. func (s *server) GetWorkflowMetadata(context context.Context, req *pb.GetWorkflowDataRequest) (*pb.GetWorkflowDataResponse, error) { data, err := s.db.GetWorkflowMetadata(context, req) if err != nil { @@ -187,7 +187,7 @@ func (s *server) GetWorkflowMetadata(context context.Context, req *pb.GetWorkflo return &pb.GetWorkflowDataResponse{Data: data}, nil } -// GetWorkflowDataVersion returns the latest version of data for a workflow +// GetWorkflowDataVersion returns the latest version of data for a workflow. func (s *server) GetWorkflowDataVersion(context context.Context, req *pb.GetWorkflowDataRequest) (*pb.GetWorkflowDataResponse, error) { version, err := s.db.GetWorkflowDataVersion(context, req.WorkflowId) if err != nil { @@ -216,7 +216,7 @@ func getWorkflowActions(context context.Context, db db.Database, wfID string) (* } // isApplicableToSend checks if a particular workflow context is applicable or if it is needed to -// be sent to a worker based on the state of the current action and the targeted workerID +// be sent to a worker based on the state of the current action and the targeted workerID. func isApplicableToSend(context context.Context, logger log.Logger, wfContext *pb.WorkflowContext, workerID string, db db.Database) bool { if wfContext.GetCurrentActionState() == pb.State_STATE_FAILED || wfContext.GetCurrentActionState() == pb.State_STATE_TIMEOUT { @@ -239,7 +239,6 @@ func isApplicableToSend(context context.Context, logger log.Logger, wfContext *p } else if actions.ActionList[wfContext.GetCurrentActionIndex()].GetWorkerId() == workerID { logger.Info(fmt.Sprintf(msgSendWfContext, wfContext.GetWorkflowId())) return true - } return false } diff --git a/grpc-server/workflow.go b/grpc-server/workflow.go index 44c96a044..5ec578453 100644 --- a/grpc-server/workflow.go +++ b/grpc-server/workflow.go @@ -15,7 +15,7 @@ import ( const errFailedToGetTemplate = "failed to get template with ID %s" -// CreateWorkflow implements workflow.CreateWorkflow +// CreateWorkflow implements workflow.CreateWorkflow. func (s *server) CreateWorkflow(ctx context.Context, in *workflow.CreateRequest) (*workflow.CreateResponse, error) { s.logger.Info("createworkflow") labels := prometheus.Labels{"method": "CreateWorkflow", "op": ""} @@ -42,7 +42,6 @@ func (s *server) CreateWorkflow(ctx context.Context, in *workflow.CreateRequest) return &workflow.CreateResponse{}, errors.Wrapf(err, errFailedToGetTemplate, in.GetTemplate()) } data, err := wkf.RenderTemplate(in.GetTemplate(), wtmpl.GetData(), []byte(in.Hardware)) - if err != nil { metrics.CacheErrors.With(labels).Inc() s.logger.Error(err) @@ -71,7 +70,7 @@ func (s *server) CreateWorkflow(ctx context.Context, in *workflow.CreateRequest) return &workflow.CreateResponse{Id: id.String()}, err } -// GetWorkflow implements workflow.GetWorkflow +// GetWorkflow implements workflow.GetWorkflow. func (s *server) GetWorkflow(ctx context.Context, in *workflow.GetRequest) (*workflow.Workflow, error) { s.logger.Info("getworkflow") labels := prometheus.Labels{"method": "GetWorkflow", "op": ""} @@ -122,7 +121,7 @@ func (s *server) GetWorkflow(ctx context.Context, in *workflow.GetRequest) (*wor return wf, err } -// DeleteWorkflow implements workflow.DeleteWorkflow +// DeleteWorkflow implements workflow.DeleteWorkflow. func (s *server) DeleteWorkflow(ctx context.Context, in *workflow.GetRequest) (*workflow.Empty, error) { s.logger.Info("deleteworkflow") labels := prometheus.Labels{"method": "DeleteWorkflow", "op": ""} @@ -151,7 +150,7 @@ func (s *server) DeleteWorkflow(ctx context.Context, in *workflow.GetRequest) (* return &workflow.Empty{}, err } -// ListWorkflows implements workflow.ListWorkflows +// ListWorkflows implements workflow.ListWorkflows. func (s *server) ListWorkflows(_ *workflow.Empty, stream workflow.WorkflowService_ListWorkflowsServer) error { s.logger.Info("listworkflows") labels := prometheus.Labels{"method": "ListWorkflows", "op": "list"} @@ -180,7 +179,6 @@ func (s *server) ListWorkflows(_ *workflow.Empty, stream workflow.WorkflowServic } return stream.Send(wf) }) - if err != nil { metrics.CacheErrors.With(labels).Inc() return err @@ -236,7 +234,7 @@ func (s *server) GetWorkflowContext(ctx context.Context, in *workflow.GetRequest return wf, err } -// ShowWorflowevents implements workflow.ShowWorflowEvents +// ShowWorflowevents implements workflow.ShowWorflowEvents. func (s *server) ShowWorkflowEvents(req *workflow.GetRequest, stream workflow.WorkflowService_ShowWorkflowEventsServer) error { s.logger.Info("List workflows Events") labels := prometheus.Labels{"method": "ShowWorkflowEvents", "op": "list"} @@ -266,7 +264,6 @@ func (s *server) ShowWorkflowEvents(req *workflow.GetRequest, stream workflow.Wo } return stream.Send(wfs) }) - if err != nil { metrics.CacheErrors.With(labels).Inc() return err diff --git a/grpc-server/workflow_test.go b/grpc-server/workflow_test.go index 62b9c460b..75d0b7b7a 100644 --- a/grpc-server/workflow_test.go +++ b/grpc-server/workflow_test.go @@ -148,7 +148,8 @@ func TestGetWorkflow(t *testing.T) { return db.Workflow{ ID: workflowID, Template: templateID, - Hardware: hw}, nil + Hardware: hw, + }, nil }, GetWorkflowContextsFunc: func(ctx context.Context, wfID string) (*workflow.WorkflowContext, error) { return &workflow.WorkflowContext{ @@ -193,7 +194,8 @@ func TestGetWorkflow(t *testing.T) { return db.Workflow{ ID: workflowID, Template: templateID, - Hardware: hw}, nil + Hardware: hw, + }, nil }, GetWorkflowContextsFunc: func(ctx context.Context, wfID string) (*workflow.WorkflowContext, error) { return &workflow.WorkflowContext{ diff --git a/http-server/http_handlers.go b/http-server/http_handlers.go index 6fa6a0ff0..cbf198d28 100644 --- a/http-server/http_handlers.go +++ b/http-server/http_handlers.go @@ -21,7 +21,7 @@ import ( ) // RegisterHardwareServiceHandlerFromEndpoint serves Hardware requests at the -// given endpoint over GRPC +// given endpoint over GRPC. func RegisterHardwareServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) error { conn, err := grpc.Dial(endpoint, opts...) if err != nil { @@ -214,7 +214,7 @@ func RegisterHardwareServiceHandlerFromEndpoint(ctx context.Context, mux *runtim } // RegisterTemplateHandlerFromEndpoint serves Template requests at the given -// endpoint over GRPC +// endpoint over GRPC. func RegisterTemplateHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) error { conn, err := grpc.Dial(endpoint, opts...) if err != nil { @@ -384,7 +384,7 @@ func RegisterTemplateHandlerFromEndpoint(ctx context.Context, mux *runtime.Serve } // RegisterWorkflowSvcHandlerFromEndpoint serves Workflow requests at the given -// endpoint over GRPC +// endpoint over GRPC. func RegisterWorkflowSvcHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) error { conn, err := grpc.Dial(endpoint, opts...) if err != nil { @@ -588,7 +588,7 @@ func tryParseTemplate(data string) error { return nil } -// writeResponse appends a new line after res +// writeResponse appends a new line after res. func writeResponse(w http.ResponseWriter, status int, res string) { w.WriteHeader(status) if _, err := w.Write([]byte(fmt.Sprintln(res))); err != nil { diff --git a/http-server/http_handlers_test.go b/http-server/http_handlers_test.go index 20646271f..002d82412 100644 --- a/http-server/http_handlers_test.go +++ b/http-server/http_handlers_test.go @@ -62,7 +62,6 @@ func TestMain(m *testing.M) { } func TestHardwarePushHandler(t *testing.T) { - for name, test := range handlerTests { t.Log(name) diff --git a/http-server/http_server.go b/http-server/http_server.go index 260559994..a17688381 100644 --- a/http-server/http_server.go +++ b/http-server/http_server.go @@ -35,7 +35,7 @@ type HTTPServerConfig struct { HTTPBasicAuthPassword string } -// SetupHTTP setup and return an HTTP server +// SetupHTTP setup and return an HTTP server. func SetupHTTP(ctx context.Context, lg log.Logger, config *HTTPServerConfig, errCh chan<- error) { logger = lg @@ -143,7 +143,7 @@ func setupGitRevJSON() { } // BasicAuth adds authentication to the routes handled by handler -// skips authentication if both authUsername and authPassword aren't set +// skips authentication if both authUsername and authPassword aren't set. func BasicAuth(authUsername, authPassword string, handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if authUsername != "" || authPassword != "" { diff --git a/metrics/metrics.go b/metrics/metrics.go index e3426b039..75b88689f 100644 --- a/metrics/metrics.go +++ b/metrics/metrics.go @@ -6,7 +6,7 @@ import ( "github.com/prometheus/client_golang/prometheus/promauto" ) -// Prometheus Metrics +// Prometheus Metrics. var ( CacheDuration prometheus.ObserverVec CacheErrors *prometheus.CounterVec @@ -22,7 +22,7 @@ var ( WatchMissTotal prometheus.Counter ) -// SetupMetrics sets the defaults for metrics +// SetupMetrics sets the defaults for metrics. func SetupMetrics(facility string, logger log.Logger) { curryLabels := prometheus.Labels{ "service": "tink", diff --git a/pkg/hardware_wrapper.go b/pkg/hardware_wrapper.go index 8e3f10736..85d3bb461 100644 --- a/pkg/hardware_wrapper.go +++ b/pkg/hardware_wrapper.go @@ -31,7 +31,7 @@ type HardwareWrapper struct { // 2. Marshal Hardware object to then be unmarshaled into map A // 3. Create another empty map B to unmarshal metadata string into // 4. Set map B as map A's metadata field -// 5. Marshal map A +// 5. Marshal map A. func (h HardwareWrapper) MarshalJSON() ([]byte, error) { tmp := make(map[string]interface{}) // map (A) to hold metadata as a map (as opposed to string) hwByte, err := json.Marshal(h.Hardware) // marshal hardware object @@ -67,7 +67,7 @@ func (h HardwareWrapper) MarshalJSON() ([]byte, error) { // 2. Unmarshal []byte b into map // 3. Marshal metadata field // 4. Set metadata string as map's metadata field -// 5. Marshal map to then be unmarshaled into Hardware object +// 5. Marshal map to then be unmarshaled into Hardware object. func (h *HardwareWrapper) UnmarshalJSON(b []byte) error { type hwWrapper HardwareWrapper // intermediary type to avoid infinite recursion tmp := make(map[string]interface{}) // map to hold metadata as a string (as well as all the hardware data) diff --git a/test/framework/hardware.go b/test/framework/hardware.go index dcc006295..74dee9f1f 100644 --- a/test/framework/hardware.go +++ b/test/framework/hardware.go @@ -25,7 +25,7 @@ func readHwData(file string) ([]byte, error) { return data, nil } -// PushHardwareData : push hardware data +// PushHardwareData : push hardware data. func PushHardwareData(hwDataFiles []string) error { for _, hwFile := range hwDataFiles { filepath := "data/hardware/" + hwFile diff --git a/test/framework/setup.go b/test/framework/setup.go index a8a9cbc7f..ab3c7d462 100644 --- a/test/framework/setup.go +++ b/test/framework/setup.go @@ -55,7 +55,6 @@ func removeWorkerImage() error { cmd.Stderr = os.Stderr err := cmd.Run() return err - } func createWorkerImage() error { @@ -99,7 +98,7 @@ func initializeLogger() { logger.SetFormatter(&logrus.JSONFormatter{}) } -// StartStack : Starting stack +// StartStack : Starting stack. func StartStack() error { // Docker compose file for starting the containers filepath := "../test-docker-compose.yml" @@ -125,25 +124,25 @@ func StartStack() error { return err } - //Build default images + // Build default images err = buildActionImages() if err != nil { return err } - //Push Images into registry + // Push Images into registry err = pushImages() if err != nil { return err } - //Remove older worker image + // Remove older worker image err = removeWorkerImage() if err != nil { return err } - //Create new Worker image locally + // Create new Worker image locally err = createWorkerImage() if err != nil { logger.Errorln("failed to create worker Image") diff --git a/test/framework/tearDown.go b/test/framework/tearDown.go index 8132d98c9..180a65e43 100644 --- a/test/framework/tearDown.go +++ b/test/framework/tearDown.go @@ -5,7 +5,7 @@ import ( "os/exec" ) -// TearDown : remove the setup +// TearDown : remove the setup. func TearDown() error { cmd := exec.Command("/bin/sh", "-c", "docker-compose rm -svf") cmd.Stdout = os.Stdout diff --git a/test/framework/template.go b/test/framework/template.go index d1c9d3343..485970fa9 100644 --- a/test/framework/template.go +++ b/test/framework/template.go @@ -24,7 +24,7 @@ func readTemplateData(file string) (string, error) { return string(data), nil } -// CreateTemplate : create template in the database +// CreateTemplate : create template in the database. func CreateTemplate(tmpl string) (string, error) { filePath := "data/template/" + tmpl // Read Content of template diff --git a/test/framework/utils.go b/test/framework/utils.go index 4390fdd7d..69bd9114a 100644 --- a/test/framework/utils.go +++ b/test/framework/utils.go @@ -4,16 +4,18 @@ import ( "github.com/sirupsen/logrus" ) -var logger = logrus.New() -var log *logrus.Entry +var ( + logger = logrus.New() + log *logrus.Entry +) // Log : This Log will be used in test cases. var Log = logger -// SetupWorkflow ... Set up workflow +// SetupWorkflow ... Set up workflow. func SetupWorkflow(tar string, tmpl string) (string, error) { hardwareID := "c9d6faa4-08a2-4285-ae6c-f3401211bd56" - //Add template in template table + // Add template in template table templateID, err := CreateTemplate(tmpl) if err != nil { return "", err diff --git a/test/framework/worker.go b/test/framework/worker.go index 38e6d7d94..a9113c074 100644 --- a/test/framework/worker.go +++ b/test/framework/worker.go @@ -60,11 +60,11 @@ func waitContainer(ctx context.Context, cli *dc.Client, id string, wg *sync.Wait case status := <-wait: statusChannel <- status.StatusCode fmt.Println("Worker with id ", id, "finished successfully with status code ", status.StatusCode) - //stopLogs <- true + // stopLogs <- true case err := <-errC: log.Println("Worker with id ", id, "failed : ", err) failedWorkers <- id - //stopLogs <- true + // stopLogs <- true } wg.Done() } @@ -84,6 +84,7 @@ func removeContainer(ctx context.Context, cli *dc.Client, id string) error { log.Println("Worker Container removed : ", id) return nil } + func checkCurrentStatus(ctx context.Context, wfID string, workflowStatus chan workflow.State) { for len(workflowStatus) == 0 { GetCurrentStatus(ctx, wfID, workflowStatus) @@ -109,7 +110,7 @@ func captureLogs(ctx context.Context, cli *dc.Client, id string) { fmt.Println("Logging Finished for container ", id) } -// StartWorkers starts the dummy workers +// StartWorkers starts the dummy workers. func StartWorkers(workers int64, workerStatus chan<- int64, wfID string) (workflow.State, error) { log = logger.WithField("workflow_id", wfID) var wg sync.WaitGroup @@ -131,7 +132,7 @@ func StartWorkers(workers int64, workerStatus chan<- int64, wfID string) (workfl workerContainer[i] = cID log.Debugln("Worker container created with ID : ", cID) // Run container - //startedAt := time.Now() + // startedAt := time.Now() err = runContainer(ctx, cli, cID) if err != nil { @@ -140,7 +141,7 @@ func StartWorkers(workers int64, workerStatus chan<- int64, wfID string) (workfl } else { fmt.Println("Worker started with ID : ", cID) wg.Add(1) - //capturing logs of action container in a go-routine + // capturing logs of action container in a go-routine stopLogs := make(chan bool) go captureLogs(ctx, cli, cID) diff --git a/test/framework/workflow.go b/test/framework/workflow.go index 0cdfd0044..b22ae6c86 100644 --- a/test/framework/workflow.go +++ b/test/framework/workflow.go @@ -7,7 +7,7 @@ import ( "github.com/tinkerbell/tink/protos/workflow" ) -// CreateWorkflow : create workflow +// CreateWorkflow : create workflow. func CreateWorkflow(template string, hardware string) (string, error) { req := workflow.CreateRequest{Template: template, Hardware: hardware} res, err := client.WorkflowClient.CreateWorkflow(context.Background(), &req) @@ -17,7 +17,7 @@ func CreateWorkflow(template string, hardware string) (string, error) { return res.Id, nil } -// GetCurrentStatus : get the current status of workflow from server +// GetCurrentStatus : get the current status of workflow from server. func GetCurrentStatus(ctx context.Context, wfID string, status chan workflow.State) { req := workflow.GetRequest{Id: wfID} wf, err := client.WorkflowClient.GetWorkflowContext(ctx, &req) diff --git a/workflow/template_validator.go b/workflow/template_validator.go index 851ca626f..01671476d 100644 --- a/workflow/template_validator.go +++ b/workflow/template_validator.go @@ -24,7 +24,7 @@ const ( errInvalidHardwareAddress = "failed to render template, invalid hardware address: %s" ) -// Parse parses the template yaml content into a Workflow +// Parse parses the template yaml content into a Workflow. func Parse(yamlContent []byte) (*Workflow, error) { var workflow Workflow @@ -41,7 +41,7 @@ func Parse(yamlContent []byte) (*Workflow, error) { } // MustParse parse a slice of bytes to a template. It an error occurs the -// function triggers a panic. Common utility for testing purpose +// function triggers a panic. Common utility for testing purpose. func MustParse(yamlContent []byte) *Workflow { w, err := Parse(yamlContent) if err != nil { @@ -60,7 +60,7 @@ func MustParseFromFile(path string) *Workflow { return MustParse(content) } -// RenderTemplate renders the workflow template wrt given hardware details +// RenderTemplate renders the workflow template wrt given hardware details. func RenderTemplate(templateID, templateData string, devices []byte) (string, error) { var hardware map[string]interface{} err := json.Unmarshal(devices, &hardware) @@ -92,7 +92,7 @@ func RenderTemplate(templateID, templateData string, devices []byte) (string, er return buf.String(), nil } -// validate validates a workflow template against certain requirements +// validate validates a workflow template against certain requirements. func validate(wf *Workflow) error { if hasEmptyName(wf.Name) { return errors.New(errEmptyName) diff --git a/workflow/types.go b/workflow/types.go index 22dabb4eb..9e0395fa3 100644 --- a/workflow/types.go +++ b/workflow/types.go @@ -1,6 +1,6 @@ package workflow -// Workflow represents a workflow to be executed +// Workflow represents a workflow to be executed. type Workflow struct { Version string `yaml:"version"` Name string `yaml:"name"` @@ -9,7 +9,7 @@ type Workflow struct { Tasks []Task `yaml:"tasks"` } -// Task represents a task to be executed as part of a workflow +// Task represents a task to be executed as part of a workflow. type Task struct { Name string `yaml:"name"` WorkerAddr string `yaml:"worker"` @@ -18,7 +18,7 @@ type Task struct { Environment map[string]string `yaml:"environment,omitempty"` } -// Action is the basic executional unit for a workflow +// Action is the basic executional unit for a workflow. type Action struct { Name string `yaml:"name"` Image string `yaml:"image"` From 8988f45a39c30c28dc4bb4e8e7c913c240e19354 Mon Sep 17 00:00:00 2001 From: Thomas Stromberg Date: Fri, 3 Sep 2021 12:07:05 -0700 Subject: [PATCH 3/9] This is Lint-a-geddon coming to your doorstep Signed-off-by: Thomas Stromberg --- .golangci.yml | 4 +- Makefile | 6 +- cmd/tink-cli/cmd/completion.go | 2 +- cmd/tink-cli/cmd/delete/delete.go | 7 +- cmd/tink-cli/cmd/delete/delete_test.go | 2 +- cmd/tink-cli/cmd/delete/doc.go | 2 +- cmd/tink-cli/cmd/docs_test.go | 7 ++ cmd/tink-cli/cmd/get/get.go | 2 +- cmd/tink-cli/cmd/get/get_test.go | 4 +- cmd/tink-cli/cmd/hardware/commands.go | 4 +- cmd/tink-cli/cmd/hardware/delete.go | 4 +- cmd/tink-cli/cmd/hardware/get.go | 13 +- cmd/tink-cli/cmd/hardware/get_test.go | 2 +- cmd/tink-cli/cmd/hardware/id.go | 4 +- cmd/tink-cli/cmd/hardware/ip.go | 4 +- cmd/tink-cli/cmd/hardware/list.go | 9 +- cmd/tink-cli/cmd/hardware/mac.go | 4 +- cmd/tink-cli/cmd/hardware/push.go | 21 ++-- cmd/tink-cli/cmd/hardware_test.go | 2 + cmd/tink-cli/cmd/template/create.go | 1 + cmd/tink-cli/cmd/template/get.go | 9 +- cmd/tink-cli/cmd/template/get_test.go | 2 +- cmd/tink-cli/cmd/template/list.go | 3 +- cmd/tink-cli/cmd/template/update.go | 14 ++- cmd/tink-cli/cmd/template_test.go | 1 + cmd/tink-cli/cmd/workflow/create.go | 4 +- cmd/tink-cli/cmd/workflow/data.go | 8 +- cmd/tink-cli/cmd/workflow/events.go | 3 +- cmd/tink-cli/cmd/workflow/get.go | 5 +- cmd/tink-cli/cmd/workflow/list.go | 3 +- cmd/tink-cli/cmd/workflow_test.go | 1 + cmd/tink-server/main.go | 5 +- cmd/tink-worker/cmd/root.go | 18 +-- cmd/tink-worker/internal/action.go | 11 +- cmd/tink-worker/internal/registry.go | 2 +- cmd/tink-worker/internal/registry_test.go | 4 +- cmd/tink-worker/internal/worker.go | 142 +++++++++++----------- cmd/tink-worker/main.go | 4 +- db/db.go | 13 +- db/db_test.go | 4 +- db/hardware.go | 2 +- db/hardware_test.go | 35 +++--- db/mock/hardware.go | 12 +- db/mock/template.go | 14 +-- db/mock/workflow.go | 12 +- db/template.go | 33 ++--- db/template_test.go | 18 +-- db/workflow.go | 73 +++++------ db/workflow_test.go | 18 +-- grpc-server/template_test.go | 10 +- grpc-server/tinkerbell.go | 66 +++++----- grpc-server/tinkerbell_test.go | 13 +- grpc-server/workflow.go | 27 ++-- http-server/http_handlers.go | 31 ++--- http-server/http_handlers_test.go | 2 +- http-server/http_server.go | 10 +- test/e2e_test.go | 72 ----------- test/framework/hardware.go | 3 +- test/framework/setup.go | 29 ++--- test/framework/utils.go | 2 +- test/framework/worker.go | 18 +-- test/test_wf_timeout.go | 49 -------- test/test_wf_with_multi_workers.go | 52 -------- test/test_wf_with_worker.go | 54 -------- workflow/template_validator.go | 2 +- workflow/template_validator_test.go | 75 ++++++------ 66 files changed, 439 insertions(+), 653 deletions(-) delete mode 100644 test/e2e_test.go delete mode 100644 test/test_wf_timeout.go delete mode 100644 test/test_wf_with_multi_workers.go delete mode 100644 test/test_wf_with_worker.go diff --git a/.golangci.yml b/.golangci.yml index 9b3a5722e..a90a568ac 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -180,7 +180,7 @@ issues: - gosec - noctx - - path: cmd.* + - path: .*cmd.* linters: - noctx @@ -188,7 +188,7 @@ issues: linters: - noctx - - path: cmd.* + - path: .*cmd.* text: "deep-exit" - path: main\.go diff --git a/Makefile b/Makefile index e60c0b98d..5845ef8c6 100644 --- a/Makefile +++ b/Makefile @@ -15,7 +15,7 @@ verify: lint help: ## Print this help @grep --no-filename -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sed 's/:.*##/·/' | sort | column -ts '·' -c 120 -# BEGIN: lint-install ../tink +# BEGIN: lint-install --dockerfile=warn ../tink # http://github.com/tinkerbell/lint-install GOLINT_VERSION ?= v1.42.0 @@ -37,7 +37,7 @@ GOLINT_CONFIG:=$(LINT_ROOT)/.golangci.yml lint: out/linters/shellcheck-$(SHELLCHECK_VERSION)-$(LINT_ARCH)/shellcheck out/linters/hadolint-$(HADOLINT_VERSION)-$(LINT_ARCH) out/linters/golangci-lint-$(GOLINT_VERSION)-$(LINT_ARCH) out/linters/golangci-lint-$(GOLINT_VERSION)-$(LINT_ARCH) run - out/linters/hadolint-$(HADOLINT_VERSION)-$(LINT_ARCH) $(shell find . -name "*Dockerfile") + out/linters/hadolint-$(HADOLINT_VERSION)-$(LINT_ARCH) --no-fail $(shell find . -name "*Dockerfile") out/linters/shellcheck-$(SHELLCHECK_VERSION)-$(LINT_ARCH)/shellcheck $(shell find . -name "*.sh") fix: out/linters/shellcheck-$(SHELLCHECK_VERSION)-$(LINT_ARCH)/shellcheck out/linters/golangci-lint-$(GOLINT_VERSION)-$(LINT_ARCH) @@ -59,4 +59,4 @@ out/linters/golangci-lint-$(GOLINT_VERSION)-$(LINT_ARCH): curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b out/linters $(GOLINT_VERSION) mv out/linters/golangci-lint out/linters/golangci-lint-$(GOLINT_VERSION)-$(LINT_ARCH) -# END: lint-install ../tink +# END: lint-install --dockerfile=warn ../tink diff --git a/cmd/tink-cli/cmd/completion.go b/cmd/tink-cli/cmd/completion.go index 24544624f..5e8356b7d 100644 --- a/cmd/tink-cli/cmd/completion.go +++ b/cmd/tink-cli/cmd/completion.go @@ -9,7 +9,7 @@ import ( // completionCmd returns the completion command that, when run, generates a // bash or zsh completion script for the CLI. -func completionCmd(name string) *cobra.Command { +func completionCmd(_ string) *cobra.Command { return &cobra.Command{ Use: "completion [bash|zsh|fish|powershell]", Short: "Generate completion script", diff --git a/cmd/tink-cli/cmd/delete/delete.go b/cmd/tink-cli/cmd/delete/delete.go index da885a00c..57e4581bb 100644 --- a/cmd/tink-cli/cmd/delete/delete.go +++ b/cmd/tink-cli/cmd/delete/delete.go @@ -1,4 +1,4 @@ -package delete +package delete // nolint:predeclared // package name delete has same name as predeclared identifier import ( "context" @@ -98,7 +98,7 @@ func NewDeleteCommand(opt Options) *cobra.Command { }, RunE: func(cmd *cobra.Command, args []string) error { if opt.DeleteByID == nil { - return errors.New("DeleteByID is not implemented for this resource yet. Please have a look at the issue in GitHub or open a new one.") + return errors.New("option DeleteByID is not implemented for this resource yet. Please have a look at the issue in GitHub or open a new one") } for _, requestedID := range args { _, err := opt.DeleteByID(cmd.Context(), opt.fullClient, requestedID) @@ -106,9 +106,8 @@ func NewDeleteCommand(opt Options) *cobra.Command { if s, ok := status.FromError(err); ok && s.Code() == codes.NotFound { fmt.Fprintf(cmd.ErrOrStderr(), "Error\t%s\tnot found\n", requestedID) continue - } else { - return err } + return err } fmt.Fprintf(cmd.OutOrStdout(), "Deleted\t%s\n", requestedID) } diff --git a/cmd/tink-cli/cmd/delete/delete_test.go b/cmd/tink-cli/cmd/delete/delete_test.go index 0b99f057e..9310d3bf6 100644 --- a/cmd/tink-cli/cmd/delete/delete_test.go +++ b/cmd/tink-cli/cmd/delete/delete_test.go @@ -1,4 +1,4 @@ -package delete +package delete // nolint:predeclared // package name delete has same name as predeclared identifier import ( "bytes" diff --git a/cmd/tink-cli/cmd/delete/doc.go b/cmd/tink-cli/cmd/delete/doc.go index d50da3537..0469f5a7d 100644 --- a/cmd/tink-cli/cmd/delete/doc.go +++ b/cmd/tink-cli/cmd/delete/doc.go @@ -1,4 +1,4 @@ // Package delete provides a reusable implementation of the Delete command // for the tink cli. The Delete command deletes resources. It is designed // to be extendible and usable across resources. -package delete +package delete // nolint:predeclared // package name delete has same name as predeclared identifier diff --git a/cmd/tink-cli/cmd/docs_test.go b/cmd/tink-cli/cmd/docs_test.go index b3f37937b..c3f68809e 100644 --- a/cmd/tink-cli/cmd/docs_test.go +++ b/cmd/tink-cli/cmd/docs_test.go @@ -1,3 +1,4 @@ +//nolint:thelper // misuse of test helpers requires a large refactor into subtests package cmd import ( @@ -60,6 +61,8 @@ func Test_docsCmd(t *testing.T) { args: args{name: testCommand}, want: &cobra.Command{}, cmdFunc: func(t *testing.T, c *cobra.Command) { + t.Helper() + dir, err := ioutil.TempDir("", "tink-test-*") if err != nil { t.Fatal(err) @@ -90,6 +93,8 @@ func Test_docsCmd(t *testing.T) { args: args{name: testCommand}, want: &cobra.Command{}, cmdFunc: func(t *testing.T, c *cobra.Command) { + t.Helper() + dir, err := ioutil.TempDir("", "tink-test-*") if err != nil { t.Fatal(err) @@ -120,6 +125,8 @@ func Test_docsCmd(t *testing.T) { args: args{name: testCommand}, want: &cobra.Command{}, cmdFunc: func(t *testing.T, c *cobra.Command) { + t.Helper() + root := c.Root() root.SetArgs([]string{subCommand, "invalid"}) if err := root.Execute(); err == nil { diff --git a/cmd/tink-cli/cmd/get/get.go b/cmd/tink-cli/cmd/get/get.go index 68ef63d24..9bb0a8016 100644 --- a/cmd/tink-cli/cmd/get/get.go +++ b/cmd/tink-cli/cmd/get/get.go @@ -97,7 +97,7 @@ func NewGetCommand(opt Options) *cobra.Command { if len(args) != 0 { if opt.RetrieveByID == nil { - return errors.New("Get by ID is not implemented for this resource yet. Please have a look at the issue in GitHub or open a new one.") + return errors.New("option RetrieveByID is not implemented for this resource yet. Please have a look at the issue in GitHub or open a new one") } for _, requestedID := range args { s, err := opt.RetrieveByID(cmd.Context(), opt.fullClient, requestedID) diff --git a/cmd/tink-cli/cmd/get/get_test.go b/cmd/tink-cli/cmd/get/get_test.go index e6632a685..3e9eb561c 100644 --- a/cmd/tink-cli/cmd/get/get_test.go +++ b/cmd/tink-cli/cmd/get/get_test.go @@ -14,7 +14,7 @@ import ( ) func TestNewGetCommand(t *testing.T) { - table := []struct { + tests := []struct { Name string ExpectStdout string Args []string @@ -175,7 +175,7 @@ func TestNewGetCommand(t *testing.T) { }, } - for _, s := range table { + for _, s := range tests { t.Run(s.Name, func(t *testing.T) { if s.Skip != "" { t.Skip(s.Skip) diff --git a/cmd/tink-cli/cmd/hardware/commands.go b/cmd/tink-cli/cmd/hardware/commands.go index ed6e6f963..5d8f3101a 100644 --- a/cmd/tink-cli/cmd/hardware/commands.go +++ b/cmd/tink-cli/cmd/hardware/commands.go @@ -11,7 +11,7 @@ import ( "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/tinkerbell/tink/pkg" - "github.com/tinkerbell/tink/protos/hardware" + hwpb "github.com/tinkerbell/tink/protos/hardware" ) // SubCommands holds the sub commands for template command @@ -30,7 +30,7 @@ func verifyUUIDs(args []string) error { return nil } -func printOutput(data bool, hw *hardware.Hardware, input string) { +func printOutput(data bool, hw *hwpb.Hardware, input string) { t := table.NewWriter() t.SetOutputMirror(os.Stdout) t.AppendHeader(table.Row{"Field Name", "Value"}) diff --git a/cmd/tink-cli/cmd/hardware/delete.go b/cmd/tink-cli/cmd/hardware/delete.go index 3376bb5aa..083b63049 100644 --- a/cmd/tink-cli/cmd/hardware/delete.go +++ b/cmd/tink-cli/cmd/hardware/delete.go @@ -7,7 +7,7 @@ import ( "github.com/tinkerbell/tink/client" "github.com/tinkerbell/tink/cmd/tink-cli/cmd/delete" - "github.com/tinkerbell/tink/protos/hardware" + hwpb "github.com/tinkerbell/tink/protos/hardware" ) type deleteHardware struct { @@ -15,7 +15,7 @@ type deleteHardware struct { } func (h *deleteHardware) DeleteByID(ctx context.Context, cl *client.FullClient, requestedID string) (interface{}, error) { - return cl.HardwareClient.Delete(ctx, &hardware.DeleteRequest{Id: requestedID}) + return cl.HardwareClient.Delete(ctx, &hwpb.DeleteRequest{Id: requestedID}) } func NewDeleteOptions() delete.Options { diff --git a/cmd/tink-cli/cmd/hardware/get.go b/cmd/tink-cli/cmd/hardware/get.go index 35441958a..c3db3b24e 100644 --- a/cmd/tink-cli/cmd/hardware/get.go +++ b/cmd/tink-cli/cmd/hardware/get.go @@ -2,12 +2,13 @@ package hardware import ( "context" + "errors" "io" "github.com/jedib0t/go-pretty/table" "github.com/tinkerbell/tink/client" "github.com/tinkerbell/tink/cmd/tink-cli/cmd/get" - "github.com/tinkerbell/tink/protos/hardware" + hwpb "github.com/tinkerbell/tink/protos/hardware" ) type getHardware struct { @@ -26,20 +27,20 @@ func NewGetOptions() get.Options { } func (h *getHardware) RetrieveByID(ctx context.Context, cl *client.FullClient, requiredID string) (interface{}, error) { - return cl.HardwareClient.ByID(ctx, &hardware.GetRequest{Id: requiredID}) + return cl.HardwareClient.ByID(ctx, &hwpb.GetRequest{Id: requiredID}) } func (h *getHardware) RetrieveData(ctx context.Context, cl *client.FullClient) ([]interface{}, error) { - list, err := cl.HardwareClient.All(ctx, &hardware.Empty{}) + list, err := cl.HardwareClient.All(ctx, &hwpb.Empty{}) if err != nil { return nil, err } data := []interface{}{} - var hw *hardware.Hardware + var hw *hwpb.Hardware for hw, err = list.Recv(); err == nil && hw != nil; hw, err = list.Recv() { data = append(data, hw) } - if err != nil && err != io.EOF { + if err != nil && !errors.Is(err, io.EOF) { return nil, err } return data, nil @@ -47,7 +48,7 @@ func (h *getHardware) RetrieveData(ctx context.Context, cl *client.FullClient) ( func (h *getHardware) PopulateTable(data []interface{}, t table.Writer) error { for _, v := range data { - if hw, ok := v.(*hardware.Hardware); ok { + if hw, ok := v.(*hwpb.Hardware); ok { // TODO(gianarb): I think we should // print it better. The hardware is one // even if if has more than one diff --git a/cmd/tink-cli/cmd/hardware/get_test.go b/cmd/tink-cli/cmd/hardware/get_test.go index 527019aff..4239a639e 100644 --- a/cmd/tink-cli/cmd/hardware/get_test.go +++ b/cmd/tink-cli/cmd/hardware/get_test.go @@ -81,7 +81,7 @@ func TestGetHardware(t *testing.T) { AllFunc: func(ctx context.Context, in *hardware_proto.Empty, opts ...grpc.CallOption) (hardware_proto.HardwareService_AllClient, error) { return &hardware_proto.HardwareService_AllClientMock{ RecvFunc: func() (*hardware_proto.Hardware, error) { - s.counter = s.counter + 1 + s.counter++ if s.counter > len(s.ReturnedHardwares) { return nil, io.EOF } diff --git a/cmd/tink-cli/cmd/hardware/id.go b/cmd/tink-cli/cmd/hardware/id.go index a8d85653e..b84a7ca9d 100644 --- a/cmd/tink-cli/cmd/hardware/id.go +++ b/cmd/tink-cli/cmd/hardware/id.go @@ -11,7 +11,7 @@ import ( "github.com/spf13/cobra" "github.com/tinkerbell/tink/client" "github.com/tinkerbell/tink/pkg" - "github.com/tinkerbell/tink/protos/hardware" + hwpb "github.com/tinkerbell/tink/protos/hardware" ) // idCmd represents the id command. @@ -25,7 +25,7 @@ func NewGetByIDCmd() *cobra.Command { }, Run: func(cmd *cobra.Command, args []string) { for _, id := range args { - hw, err := client.HardwareClient.ByID(context.Background(), &hardware.GetRequest{Id: id}) + hw, err := client.HardwareClient.ByID(context.Background(), &hwpb.GetRequest{Id: id}) if err != nil { log.Fatal(err) } diff --git a/cmd/tink-cli/cmd/hardware/ip.go b/cmd/tink-cli/cmd/hardware/ip.go index 1c4cc2804..8ba480ecc 100644 --- a/cmd/tink-cli/cmd/hardware/ip.go +++ b/cmd/tink-cli/cmd/hardware/ip.go @@ -10,7 +10,7 @@ import ( "github.com/spf13/cobra" "github.com/tinkerbell/tink/client" - "github.com/tinkerbell/tink/protos/hardware" + hwpb "github.com/tinkerbell/tink/protos/hardware" ) var data bool @@ -31,7 +31,7 @@ func NewGetByIPCmd() *cobra.Command { }, Run: func(cmd *cobra.Command, args []string) { for _, ip := range args { - hw, err := client.HardwareClient.ByIP(context.Background(), &hardware.GetRequest{Ip: ip}) + hw, err := client.HardwareClient.ByIP(context.Background(), &hwpb.GetRequest{Ip: ip}) if err != nil { log.Fatal(err) } diff --git a/cmd/tink-cli/cmd/hardware/list.go b/cmd/tink-cli/cmd/hardware/list.go index 418f84327..0fca67c1f 100644 --- a/cmd/tink-cli/cmd/hardware/list.go +++ b/cmd/tink-cli/cmd/hardware/list.go @@ -2,6 +2,7 @@ package hardware import ( "context" + "errors" "fmt" "io" "log" @@ -10,7 +11,7 @@ import ( "github.com/jedib0t/go-pretty/table" "github.com/spf13/cobra" "github.com/tinkerbell/tink/client" - "github.com/tinkerbell/tink/protos/hardware" + hwpb "github.com/tinkerbell/tink/protos/hardware" ) var ( @@ -40,12 +41,12 @@ func NewListCmd() *cobra.Command { } func listHardware() { - list, err := client.HardwareClient.All(context.Background(), &hardware.Empty{}) + list, err := client.HardwareClient.All(context.Background(), &hwpb.Empty{}) if err != nil { log.Fatal(err) } - var hw *hardware.Hardware + var hw *hwpb.Hardware for hw, err = list.Recv(); err == nil && hw != nil; hw, err = list.Recv() { for _, iface := range hw.GetNetwork().GetInterfaces() { if quiet { @@ -55,7 +56,7 @@ func listHardware() { } } } - if err != nil && err != io.EOF { + if err != nil && !errors.Is(err, io.EOF) { log.Fatal(err) } } diff --git a/cmd/tink-cli/cmd/hardware/mac.go b/cmd/tink-cli/cmd/hardware/mac.go index 7adfa34a9..00a49663f 100644 --- a/cmd/tink-cli/cmd/hardware/mac.go +++ b/cmd/tink-cli/cmd/hardware/mac.go @@ -10,7 +10,7 @@ import ( "github.com/spf13/cobra" "github.com/tinkerbell/tink/client" - "github.com/tinkerbell/tink/protos/hardware" + hwpb "github.com/tinkerbell/tink/protos/hardware" ) func NewGetByMACCmd() *cobra.Command { @@ -28,7 +28,7 @@ func NewGetByMACCmd() *cobra.Command { }, Run: func(cmd *cobra.Command, args []string) { for _, mac := range args { - hw, err := client.HardwareClient.ByMAC(context.Background(), &hardware.GetRequest{Mac: mac}) + hw, err := client.HardwareClient.ByMAC(context.Background(), &hwpb.GetRequest{Mac: mac}) if err != nil { log.Fatal(err) } diff --git a/cmd/tink-cli/cmd/hardware/push.go b/cmd/tink-cli/cmd/hardware/push.go index 5e219af3b..f1abf5206 100644 --- a/cmd/tink-cli/cmd/hardware/push.go +++ b/cmd/tink-cli/cmd/hardware/push.go @@ -15,7 +15,7 @@ import ( "github.com/spf13/cobra" "github.com/tinkerbell/tink/client" "github.com/tinkerbell/tink/pkg" - "github.com/tinkerbell/tink/protos/hardware" + hwpb "github.com/tinkerbell/tink/protos/hardware" ) var ( @@ -41,10 +41,15 @@ tink hardware push --file /tmp/data.json`, }, Run: func(cmd *cobra.Command, args []string) { var data string + var err error + if isInputFromPipe() { data = readDataFromStdin() } else { - data = readDataFromFile() + data, err = readDataFromFile() + if err != nil { + log.Fatalf("read data from file failed: %v", err) + } } s := struct { ID string @@ -56,11 +61,11 @@ tink hardware push --file /tmp/data.json`, } var hw pkg.HardwareWrapper - err := json.Unmarshal([]byte(data), &hw) + err = json.Unmarshal([]byte(data), &hw) if err != nil { log.Fatal(err) } - if _, err := client.HardwareClient.Push(context.Background(), &hardware.PushRequest{Data: hw.Hardware}); err != nil { + if _, err := client.HardwareClient.Push(context.Background(), &hwpb.PushRequest{Data: hw.Hardware}); err != nil { log.Fatal(err) } log.Println("Hardware data pushed successfully") @@ -84,16 +89,16 @@ func readDataFromStdin() string { return string(data) } -func readDataFromFile() string { +func readDataFromFile() (string, error) { f, err := os.Open(filepath.Clean(file)) if err != nil { - log.Fatal(err) + return "", err } defer f.Close() data, err := ioutil.ReadAll(f) if err != nil { - log.Fatal(err) + return "", err } - return string(data) + return string(data), nil } diff --git a/cmd/tink-cli/cmd/hardware_test.go b/cmd/tink-cli/cmd/hardware_test.go index 9d3c229bb..b4db321d2 100644 --- a/cmd/tink-cli/cmd/hardware_test.go +++ b/cmd/tink-cli/cmd/hardware_test.go @@ -1,3 +1,4 @@ +//nolint:thelper // misuse of test helpers requires a large refactor into subtests package cmd import ( @@ -25,6 +26,7 @@ func Test_NewHardwareCommand(t *testing.T) { args: args{name: testCommand}, want: &cobra.Command{}, cmdFunc: func(t *testing.T, c *cobra.Command) { + t.Helper() root := c.Root() root.SetArgs([]string{subCommand}) if err := root.Execute(); err != nil { diff --git a/cmd/tink-cli/cmd/template/create.go b/cmd/tink-cli/cmd/template/create.go index 19d3b2fd6..2c4273479 100644 --- a/cmd/tink-cli/cmd/template/create.go +++ b/cmd/tink-cli/cmd/template/create.go @@ -1,3 +1,4 @@ +//nolint:import-shadowing // The name 'template' shadows an import name package template import ( diff --git a/cmd/tink-cli/cmd/template/get.go b/cmd/tink-cli/cmd/template/get.go index 250358f25..fdfb6b535 100644 --- a/cmd/tink-cli/cmd/template/get.go +++ b/cmd/tink-cli/cmd/template/get.go @@ -2,6 +2,7 @@ package template import ( "context" + "errors" "fmt" "io" "log" @@ -15,7 +16,7 @@ import ( "github.com/tinkerbell/tink/protos/template" ) -// getCmd represents the get subcommand for template command. +// GetCmd represents the get subcommand for template command. var GetCmd = &cobra.Command{ Use: "get [id]", Short: "get a template", @@ -43,7 +44,7 @@ var GetCmd = &cobra.Command{ if err != nil { log.Fatal(err) } - fmt.Println(string(t.Data)) + fmt.Println(t.Data) } }, } @@ -53,7 +54,7 @@ type getTemplate struct { } func (h *getTemplate) RetrieveByID(ctx context.Context, cl *client.FullClient, requestedID string) (interface{}, error) { - return cl.TemplateClient.GetTemplate(context.Background(), &template.GetRequest{ + return cl.TemplateClient.GetTemplate(ctx, &template.GetRequest{ GetBy: &template.GetRequest_Id{ Id: requestedID, }, @@ -75,7 +76,7 @@ func (h *getTemplate) RetrieveData(ctx context.Context, cl *client.FullClient) ( for tmp, err = list.Recv(); err == nil && tmp.Name != ""; tmp, err = list.Recv() { data = append(data, tmp) } - if err != nil && err != io.EOF { + if err != nil && !errors.Is(err, io.EOF) { return nil, err } return data, nil diff --git a/cmd/tink-cli/cmd/template/get_test.go b/cmd/tink-cli/cmd/template/get_test.go index e6e225f1d..72c4f4ed4 100644 --- a/cmd/tink-cli/cmd/template/get_test.go +++ b/cmd/tink-cli/cmd/template/get_test.go @@ -56,7 +56,7 @@ func TestGetTemplate(t *testing.T) { ListTemplatesFunc: func(ctx context.Context, in *template.ListRequest, opts ...grpc.CallOption) (template.TemplateService_ListTemplatesClient, error) { return &template.TemplateService_ListTemplatesClientMock{ RecvFunc: func() (*template.WorkflowTemplate, error) { - s.counter = s.counter + 1 + s.counter++ if s.counter > len(s.ReturnedTemplate) { return nil, io.EOF } diff --git a/cmd/tink-cli/cmd/template/list.go b/cmd/tink-cli/cmd/template/list.go index ffe5a9bd5..7ac1cb139 100644 --- a/cmd/tink-cli/cmd/template/list.go +++ b/cmd/tink-cli/cmd/template/list.go @@ -2,6 +2,7 @@ package template import ( "context" + "errors" "fmt" "io" "log" @@ -75,7 +76,7 @@ func listTemplates() { printOutput(tmp) } - if err != nil && err != io.EOF { + if err != nil && !errors.Is(err, io.EOF) { log.Fatal(err) } } diff --git a/cmd/tink-cli/cmd/template/update.go b/cmd/tink-cli/cmd/template/update.go index e4cff1999..fe7dadc7b 100644 --- a/cmd/tink-cli/cmd/template/update.go +++ b/cmd/tink-cli/cmd/template/update.go @@ -54,7 +54,11 @@ $ tink template update 614168df-45a5-11eb-b13d-0242ac120003 --file /tmp/example. func updateTemplate(id string) { req := template.WorkflowTemplate{Id: id} if filePath != "" { - data := readTemplateData() + data, err := readTemplateData() + if err != nil { + log.Fatalf("readTemplateData: %v", err) + } + if data != "" { wf, err := workflow.Parse([]byte(data)) if err != nil { @@ -74,16 +78,16 @@ func updateTemplate(id string) { fmt.Println("Updated Template: ", id) } -func readTemplateData() string { +func readTemplateData() (string, error) { f, err := os.Open(filePath) if err != nil { - log.Fatal(err) + return "", err } defer f.Close() data, err := ioutil.ReadAll(f) if err != nil { - log.Fatal(err) + return "", err } - return string(data) + return string(data), nil } diff --git a/cmd/tink-cli/cmd/template_test.go b/cmd/tink-cli/cmd/template_test.go index 39d1c8f60..c5daa7127 100644 --- a/cmd/tink-cli/cmd/template_test.go +++ b/cmd/tink-cli/cmd/template_test.go @@ -1,3 +1,4 @@ +//nolint:thelper // misuse of test helpers requires a large refactor into subtests package cmd import ( diff --git a/cmd/tink-cli/cmd/workflow/create.go b/cmd/tink-cli/cmd/workflow/create.go index b8d6da18c..7ab18954d 100644 --- a/cmd/tink-cli/cmd/workflow/create.go +++ b/cmd/tink-cli/cmd/workflow/create.go @@ -28,7 +28,7 @@ func NewCreateCommand() *cobra.Command { return err }, Run: func(c *cobra.Command, args []string) { - createWorkflow(args) + createWorkflow() }, } flags := cmd.PersistentFlags() @@ -40,7 +40,7 @@ func NewCreateCommand() *cobra.Command { return cmd } -func createWorkflow(args []string) { +func createWorkflow() { req := workflow.CreateRequest{Template: template, Hardware: hardware} res, err := client.WorkflowClient.CreateWorkflow(context.Background(), &req) if err != nil { diff --git a/cmd/tink-cli/cmd/workflow/data.go b/cmd/tink-cli/cmd/workflow/data.go index 20b72e807..77d691475 100644 --- a/cmd/tink-cli/cmd/workflow/data.go +++ b/cmd/tink-cli/cmd/workflow/data.go @@ -39,11 +39,13 @@ func NewDataCommand() *cobra.Command { req := &workflow.GetWorkflowDataRequest{WorkflowId: arg, Version: version} var res *workflow.GetWorkflowDataResponse var err error - if needsMetadata { + + switch { + case needsMetadata: res, err = client.WorkflowClient.GetWorkflowMetadata(context.Background(), req) - } else if versionOnly { + case versionOnly: res, err = client.WorkflowClient.GetWorkflowDataVersion(context.Background(), req) - } else { + default: res, err = client.WorkflowClient.GetWorkflowData(context.Background(), req) } diff --git a/cmd/tink-cli/cmd/workflow/events.go b/cmd/tink-cli/cmd/workflow/events.go index 95eaac26d..ea054a5a1 100644 --- a/cmd/tink-cli/cmd/workflow/events.go +++ b/cmd/tink-cli/cmd/workflow/events.go @@ -2,6 +2,7 @@ package workflow import ( "context" + "errors" "fmt" "io" "log" @@ -59,7 +60,7 @@ func listEvents(t table.Writer, args []string) { {event.WorkerId, event.TaskName, event.ActionName, event.Seconds, event.Message, event.ActionStatus}, }) } - if err != nil && err != io.EOF { + if err != nil && !errors.Is(err, io.EOF) { log.Fatal(err) } } diff --git a/cmd/tink-cli/cmd/workflow/get.go b/cmd/tink-cli/cmd/workflow/get.go index 55a0baf0f..0998cd997 100644 --- a/cmd/tink-cli/cmd/workflow/get.go +++ b/cmd/tink-cli/cmd/workflow/get.go @@ -2,6 +2,7 @@ package workflow import ( "context" + "errors" "fmt" "io" "log" @@ -20,7 +21,7 @@ var ( hDevice = "Hardware device" ) -// getCmd represents the get subcommand for workflow command. +// GetCmd represents the get subcommand for workflow command. var GetCmd = &cobra.Command{ Use: "get [id]", Short: "get a workflow", @@ -76,7 +77,7 @@ func (h *getWorkflow) RetrieveData(ctx context.Context, cl *client.FullClient) ( for w, err = list.Recv(); err == nil && w.Id != ""; w, err = list.Recv() { data = append(data, w) } - if err != nil && err != io.EOF { + if err != nil && !errors.Is(err, io.EOF) { return nil, err } return data, nil diff --git a/cmd/tink-cli/cmd/workflow/list.go b/cmd/tink-cli/cmd/workflow/list.go index e96458429..8e560f543 100644 --- a/cmd/tink-cli/cmd/workflow/list.go +++ b/cmd/tink-cli/cmd/workflow/list.go @@ -2,6 +2,7 @@ package workflow import ( "context" + "errors" "fmt" "io" "log" @@ -73,7 +74,7 @@ func listWorkflows() { printOutput(wf) } - if err != nil && err != io.EOF { + if err != nil && !errors.Is(err, io.EOF) { log.Fatal(err) } } diff --git a/cmd/tink-cli/cmd/workflow_test.go b/cmd/tink-cli/cmd/workflow_test.go index 3752f4b9e..1629cd03c 100644 --- a/cmd/tink-cli/cmd/workflow_test.go +++ b/cmd/tink-cli/cmd/workflow_test.go @@ -1,3 +1,4 @@ +//nolint:thelper // misuse of test helpers requires a large refactor into subtests package cmd import ( diff --git a/cmd/tink-server/main.go b/cmd/tink-server/main.go index 6c90e157c..4bab14627 100644 --- a/cmd/tink-server/main.go +++ b/cmd/tink-server/main.go @@ -98,7 +98,6 @@ func main() { if err != nil { panic(err) } - defer logger.Close() config := &DaemonConfig{} @@ -106,6 +105,8 @@ func main() { if err := cmd.ExecuteContext(context.Background()); err != nil { os.Exit(1) } + + logger.Close() } func NewRootCommand(config *DaemonConfig, logger log.Logger) *cobra.Command { @@ -179,7 +180,7 @@ func NewRootCommand(config *DaemonConfig, logger log.Logger) *cobra.Command { DB: tinkDB, }, errCh) - httpServer.SetupHTTP(ctx, logger, &httpServer.HTTPServerConfig{ + httpServer.SetupHTTP(ctx, logger, &httpServer.Config{ CertPEM: cert, ModTime: modT, GRPCAuthority: config.GRPCAuthority, diff --git a/cmd/tink-worker/cmd/root.go b/cmd/tink-worker/cmd/root.go index c68c71c40..1340fe6d4 100644 --- a/cmd/tink-worker/cmd/root.go +++ b/cmd/tink-worker/cmd/root.go @@ -81,7 +81,7 @@ func NewRootCommand(version string, logger log.Logger) *cobra.Command { rootCmd.Flags().Duration("retry-interval", defaultRetryInterval, "Retry interval in seconds (RETRY_INTERVAL)") - rootCmd.Flags().Duration("timeout", time.Duration(defaultTimeoutMinutes*time.Minute), "Max duration to wait for worker to complete (TIMEOUT)") + rootCmd.Flags().Duration("timeout", defaultTimeoutMinutes*time.Minute, "Max duration to wait for worker to complete (TIMEOUT)") rootCmd.Flags().Int("max-retry", defaultRetryCount, "Maximum number of retries to attempt (MAX_RETRY)") @@ -138,24 +138,24 @@ func createViper(logger log.Logger) (*viper.Viper, error) { } func applyViper(v *viper.Viper, cmd *cobra.Command) error { - errors := []error{} + errs := []error{} cmd.Flags().VisitAll(func(f *pflag.Flag) { if !f.Changed && v.IsSet(f.Name) { val := v.Get(f.Name) if err := cmd.Flags().Set(f.Name, fmt.Sprintf("%v", val)); err != nil { - errors = append(errors, err) + errs = append(errs, err) return } } }) - if len(errors) > 0 { - errs := []string{} - for _, err := range errors { - errs = append(errs, err.Error()) + if len(errs) > 0 { + es := []string{} + for _, err := range errs { + es = append(es, err.Error()) } - return fmt.Errorf(strings.Join(errs, ", ")) + return fmt.Errorf(strings.Join(es, ", ")) } return nil @@ -166,7 +166,7 @@ func tryClientConnection(logger log.Logger, retryInterval time.Duration, retries c, err := client.GetConnection() if err != nil { logger.With("error", err, "duration", retryInterval).Info("failed to connect, sleeping before retrying") - <-time.After(retryInterval * time.Second) + <-time.After(retryInterval) continue } diff --git a/cmd/tink-worker/internal/action.go b/cmd/tink-worker/internal/action.go index 4bcf9ed42..f78ef74f1 100644 --- a/cmd/tink-worker/internal/action.go +++ b/cmd/tink-worker/internal/action.go @@ -14,9 +14,8 @@ import ( ) const ( - errCreateContainer = "failed to create container" - errFailedToWait = "failed to wait for completion of action" - errFailedToRunCmd = "failed to run on-timeout command" + errFailedToWait = "failed to wait for completion of action" + errFailedToRunCmd = "failed to run on-timeout command" infoWaitFinished = "wait finished for failed or timeout container" ) @@ -43,9 +42,7 @@ func (w *Worker) createContainer(ctx context.Context, cmd []string, wfID string, Binds: []string{wfDir + ":/workflow"}, } - // Retrieve the PID configuration - pidConfig := action.GetPid() - if pidConfig != "" { + if pidConfig := action.GetPid(); pidConfig != "" { w.logger.With("pid", pidConfig).Info("creating container") hostConfig.PidMode = container.PidMode(pidConfig) } @@ -67,7 +64,7 @@ func startContainer(ctx context.Context, l log.Logger, cli *client.Client, id st func waitContainer(ctx context.Context, cli *client.Client, id string) (pb.State, error) { // Inspect whether the container is in running state if _, err := cli.ContainerInspect(ctx, id); err != nil { - return pb.State_STATE_FAILED, nil + return pb.State_STATE_FAILED, nil // nolint:nilerr // error is not nil, but it returns nil } // send API call to wait for the container completion diff --git a/cmd/tink-worker/internal/registry.go b/cmd/tink-worker/internal/registry.go index fe378f809..a85ddc81f 100644 --- a/cmd/tink-worker/internal/registry.go +++ b/cmd/tink-worker/internal/registry.go @@ -81,7 +81,7 @@ func (r *RegistryConnDetails) pullImage(ctx context.Context, cli imagePuller, im var status *ImagePullStatus for { if err := fd.Decode(&status); err != nil { - if err == io.EOF { + if errors.Is(err, io.EOF) { break } return errors.Wrap(err, "DOCKER PULL") diff --git a/cmd/tink-worker/internal/registry_test.go b/cmd/tink-worker/internal/registry_test.go index e4e863aa4..063facdc9 100644 --- a/cmd/tink-worker/internal/registry_test.go +++ b/cmd/tink-worker/internal/registry_test.go @@ -14,6 +14,8 @@ import ( ) func setupTestLogger(t *testing.T) log.Logger { + t.Helper() + service := "github.com/tinkerbell/tink" logger, err := log.Init(service) if err != nil { @@ -27,7 +29,7 @@ type imagePullerMock struct { imagePullErr error } -func (d *imagePullerMock) ImagePull(ctx context.Context, str string, op types.ImagePullOptions) (io.ReadCloser, error) { +func (d *imagePullerMock) ImagePull(_ context.Context, _ string, _ types.ImagePullOptions) (io.ReadCloser, error) { return d.stringReadCloser, d.imagePullErr } diff --git a/cmd/tink-worker/internal/worker.go b/cmd/tink-worker/internal/worker.go index 8845eaf78..3d358eee3 100644 --- a/cmd/tink-worker/internal/worker.go +++ b/cmd/tink-worker/internal/worker.go @@ -60,13 +60,13 @@ type Worker struct { } // NewWorker creates a new Worker, creating a new Docker registry client. -func NewWorker(client pb.WorkflowServiceClient, regConn *RegistryConnDetails, logger log.Logger, registry string, retries int, retryInterval time.Duration, maxFileSize int64) *Worker { +func NewWorker(c pb.WorkflowServiceClient, regConn *RegistryConnDetails, logger log.Logger, registry string, retries int, retryInterval time.Duration, maxFileSize int64) *Worker { registryClient, err := regConn.NewClient() if err != nil { panic(err) } return &Worker{ - client: client, + client: c, regConn: regConn, registryClient: registryClient, logger: logger, @@ -95,17 +95,20 @@ func (w *Worker) captureLogs(ctx context.Context, id string) { } } +// execute executes a workflow action, optionally capturing logs. func (w *Worker) execute(ctx context.Context, wfID string, action *pb.WorkflowAction, captureLogs bool) (pb.State, error) { l := w.logger.With("workflowID", wfID, "workerID", action.GetWorkerId(), "actionName", action.GetName(), "actionImage", action.GetImage()) cli := w.registryClient if err := w.regConn.pullImage(ctx, cli, action.GetImage()); err != nil { - return pb.State_STATE_RUNNING, errors.Wrap(err, "DOCKER PULL") + return pb.State_STATE_RUNNING, errors.Wrap(err, "pull image") } + id, err := w.createContainer(ctx, action.Command, wfID, action, captureLogs) if err != nil { - return pb.State_STATE_RUNNING, errors.Wrap(err, "DOCKER CREATE") + return pb.State_STATE_RUNNING, errors.Wrap(err, "create container") } + l.With("containerID", id, "command", action.GetOnTimeout()).Info("container created") var timeCtx context.Context @@ -120,72 +123,74 @@ func (w *Worker) execute(ctx context.Context, wfID string, action *pb.WorkflowAc err = startContainer(timeCtx, l, cli, id) if err != nil { - return pb.State_STATE_RUNNING, errors.Wrap(err, "DOCKER RUN") + return pb.State_STATE_RUNNING, errors.Wrap(err, "start container") } - failedActionStatus := make(chan pb.State) - if captureLogs { - // capturing logs of action container in a go-routine go w.captureLogs(ctx, id) } - status, waitErr := waitContainer(timeCtx, cli, id) + st, err := waitContainer(timeCtx, cli, id) + l.With("status", st.String()).Info("wait container completed") + + // If we've made it this far, the container has successfully completed. + // Everything after this is just cleanup. + defer func() { - if removalErr := removeContainer(ctx, l, cli, id); removalErr != nil { - l.With("containerID", id).Error(removalErr) + if err := removeContainer(ctx, l, cli, id); err != nil { + l.With("containerID", id).Error(err) } + l.With("status", st.String()).Info("container removed") }() - if waitErr != nil { - return status, errors.Wrap(waitErr, "DOCKER_WAIT") + if err != nil { + return st, errors.Wrap(err, "wait container") } - l.With("status", status.String()).Info("container removed") - if status != pb.State_STATE_SUCCESS { - if status == pb.State_STATE_TIMEOUT && action.OnTimeout != nil { - id, err = w.createContainer(ctx, action.OnTimeout, wfID, action, captureLogs) - if err != nil { - l.Error(errors.Wrap(err, errCreateContainer)) - } - l.With("containerID", id, "status", status.String(), "command", action.GetOnTimeout()).Info("container created") - failedActionStatus := make(chan pb.State) - if captureLogs { - go w.captureLogs(ctx, id) - } - go waitFailedContainer(ctx, l, cli, id, failedActionStatus) - err = startContainer(ctx, l, cli, id) - if err != nil { - l.Error(errors.Wrap(err, errFailedToRunCmd)) - } - onTimeoutStatus := <-failedActionStatus - l.With("status", onTimeoutStatus).Info("action timeout") - } else { - if action.OnFailure != nil { - id, err = w.createContainer(ctx, action.OnFailure, wfID, action, captureLogs) - if err != nil { - l.Error(errors.Wrap(err, errFailedToRunCmd)) - } - l.With("containerID", id, "actionStatus", status.String(), "command", action.GetOnFailure()).Info("container created") - if captureLogs { - go w.captureLogs(ctx, id) - } - go waitFailedContainer(ctx, l, cli, id, failedActionStatus) - err = startContainer(ctx, l, cli, id) - if err != nil { - l.Error(errors.Wrap(err, errFailedToRunCmd)) - } - onFailureStatus := <-failedActionStatus - l.With("status", onFailureStatus).Info("action failed") - } - } - l.Info(infoWaitFinished) - if err != nil { - l.Error(errors.Wrap(err, errFailedToWait)) - } + l.With("status", st.String()).Info("container removed") + + if st == pb.State_STATE_SUCCESS { + l.With("status", st).Info("action container exited with success", st) + return st, nil + } + + if st == pb.State_STATE_TIMEOUT && action.OnTimeout != nil { + rst := w.executeReaction(ctx, st.String(), action.OnTimeout, wfID, action, captureLogs, l) + l.With("status", rst).Info("action timeout") + } else if action.OnFailure != nil { + rst := w.executeReaction(ctx, st.String(), action.OnFailure, wfID, action, captureLogs, l) + l.With("status", rst).Info("action failed") + } + + l.Info(infoWaitFinished) + if err != nil { + l.Error(errors.Wrap(err, errFailedToWait)) } - l.With("status", status).Info("action container exited") - return status, nil + + l.With("status", st).Info("action container exited") + return st, nil +} + +// executeReaction executes special case OnTimeout/OnFailure actions. +func (w *Worker) executeReaction(ctx context.Context, reaction string, cmd []string, wfID string, action *pb.WorkflowAction, captureLogs bool, l log.Logger) pb.State { + id, err := w.createContainer(ctx, cmd, wfID, action, captureLogs) + if err != nil { + l.Error(errors.Wrap(err, errFailedToRunCmd)) + } + l.With("containerID", id, "actionStatus", reaction, "command", cmd).Info("container created") + if captureLogs { + go w.captureLogs(ctx, id) + } + + st := make(chan pb.State) + + go waitFailedContainer(ctx, l, w.registryClient, id, st) + err = startContainer(ctx, l, w.registryClient, id) + if err != nil { + l.Error(errors.Wrap(err, errFailedToRunCmd)) + } + + return <-st } // ProcessWorkflowActions gets all Workflow contexts and processes their actions. @@ -299,7 +304,7 @@ func (w *Worker) ProcessWorkflowActions(ctx context.Context, workerID string, ca // start executing the action start := time.Now() - status, err := w.execute(ctx, wfID, action, captureActionLogs) + st, err := w.execute(ctx, wfID, action, captureActionLogs) elapsed := time.Since(start) actionStatus := &pb.WorkflowActionStatus{ @@ -310,8 +315,8 @@ func (w *Worker) ProcessWorkflowActions(ctx context.Context, workerID string, ca WorkerId: action.GetWorkerId(), } - if err != nil || status != pb.State_STATE_SUCCESS { - if status == pb.State_STATE_TIMEOUT { + if err != nil || st != pb.State_STATE_SUCCESS { + if st == pb.State_STATE_TIMEOUT { actionStatus.ActionStatus = pb.State_STATE_TIMEOUT } else { actionStatus.ActionStatus = pb.State_STATE_FAILED @@ -340,20 +345,21 @@ func (w *Worker) ProcessWorkflowActions(ctx context.Context, workerID string, ca if len(actions.GetActionList()) == actionIndex+1 { l.Info("reached to end of workflow") delete(workflowcontexts, wfID) - turn = false + turn = false // nolint:wastedassign // assigned to turn, but reassigned without using the value break } + nextAction := actions.GetActionList()[actionIndex+1] if nextAction.GetWorkerId() != workerID { l.Debug(fmt.Sprintf(msgTurn, nextAction.GetWorkerId())) turn = false } else { - actionIndex = actionIndex + 1 + actionIndex++ } } } // sleep before asking for new workflows - <-time.After(w.retryInterval * time.Second) + <-time.After(w.retryInterval) } } @@ -380,7 +386,7 @@ func (w *Worker) reportActionStatus(ctx context.Context, actionStatus *pb.Workfl _, err = w.client.ReportActionStatus(ctx, actionStatus) if err != nil { l.Error(errors.Wrap(err, errReportActionStatus)) - <-time.After(w.retryInterval * time.Second) + <-time.After(w.retryInterval) continue } @@ -389,11 +395,11 @@ func (w *Worker) reportActionStatus(ctx context.Context, actionStatus *pb.Workfl return err } -func getWorkflowData(ctx context.Context, logger log.Logger, client pb.WorkflowServiceClient, workerID, workflowID string) { +func getWorkflowData(ctx context.Context, logger log.Logger, c pb.WorkflowServiceClient, workerID, workflowID string) { l := logger.With("workflowID", workflowID, "workerID", workerID, ) - res, err := client.GetWorkflowData(ctx, &pb.GetWorkflowDataRequest{WorkflowId: workflowID}) + res, err := c.GetWorkflowData(ctx, &pb.GetWorkflowDataRequest{WorkflowId: workflowID}) if err != nil { l.Error(err) } @@ -443,7 +449,7 @@ func (w *Worker) updateWorkflowData(ctx context.Context, actionStatus *pb.Workfl } } -func sendUpdate(ctx context.Context, logger log.Logger, client pb.WorkflowServiceClient, st *pb.WorkflowActionStatus, data []byte, checksum string) { +func sendUpdate(ctx context.Context, logger log.Logger, c pb.WorkflowServiceClient, st *pb.WorkflowActionStatus, data []byte, checksum string) { l := logger.With("workflowID", st.GetWorkflowId, "workerID", st.GetWorkerId(), "actionName", st.GetActionName(), @@ -462,7 +468,7 @@ func sendUpdate(ctx context.Context, logger log.Logger, client pb.WorkflowServic os.Exit(1) } - _, err = client.UpdateWorkflowData(ctx, &pb.UpdateWorkflowDataRequest{ + _, err = c.UpdateWorkflowData(ctx, &pb.UpdateWorkflowDataRequest{ WorkflowId: st.GetWorkflowId(), Data: data, Metadata: metadata, diff --git a/cmd/tink-worker/main.go b/cmd/tink-worker/main.go index 4e590ef29..cbf073c7c 100644 --- a/cmd/tink-worker/main.go +++ b/cmd/tink-worker/main.go @@ -20,11 +20,11 @@ func main() { panic(err) } - defer logger.Close() - rootCmd := cmd.NewRootCommand(version, logger) if err := rootCmd.Execute(); err != nil { os.Exit(1) } + + logger.Close() } diff --git a/db/db.go b/db/db.go index c58daaadd..bb627dd2b 100644 --- a/db/db.go +++ b/db/db.go @@ -55,7 +55,7 @@ type workflow interface { UpdateWorkflowState(ctx context.Context, wfContext *pb.WorkflowContext) error GetWorkflowContexts(ctx context.Context, wfID string) (*pb.WorkflowContext, error) GetWorkflowActions(ctx context.Context, wfID string) (*pb.WorkflowActionList, error) - InsertIntoWorkflowEventTable(ctx context.Context, wfEvent *pb.WorkflowActionStatus, time time.Time) error + InsertIntoWorkflowEventTable(ctx context.Context, wfEvent *pb.WorkflowActionStatus, t time.Time) error ShowWorkflowEvents(wfID string, fn func(wfs *pb.WorkflowActionStatus) error) error } @@ -70,13 +70,13 @@ func Connect(db *sql.DB, lg log.Logger) *TinkDB { return &TinkDB{instance: db, logger: lg} } -func (t *TinkDB) Migrate() (int, error) { - return migrate.Exec(t.instance, "postgres", migration.GetMigrations(), migrate.Up) +func (d *TinkDB) Migrate() (int, error) { + return migrate.Exec(d.instance, "postgres", migration.GetMigrations(), migrate.Up) } -func (t *TinkDB) CheckRequiredMigrations() (int, error) { +func (d *TinkDB) CheckRequiredMigrations() (int, error) { migrations := migration.GetMigrations().Migrations - records, err := migrate.GetMigrationRecords(t.instance, "postgres") + records, err := migrate.GetMigrationRecords(d.instance, "postgres") if err != nil { return 0, err } @@ -95,8 +95,7 @@ func get(ctx context.Context, db *sql.DB, query string, args ...interface{}) (st row := db.QueryRowContext(ctx, query, args...) buf := []byte{} - err := row.Scan(&buf) - if err != nil { + if err := row.Scan(&buf); err != nil { return "", errors.Wrap(err, "SELECT") } return string(buf), nil diff --git a/db/db_test.go b/db/db_test.go index 97fe6ff15..14f910277 100644 --- a/db/db_test.go +++ b/db/db_test.go @@ -21,7 +21,9 @@ type NewPostgresDatabaseRequest struct { // NewPostgresDatabaseClient returns a SQL client ready to be used. Behind the // scene it is starting a Docker container that will get cleaned up when the // test is over. Tests using this function are safe to run in parallel. -func NewPostgresDatabaseClient(t *testing.T, ctx context.Context, req NewPostgresDatabaseRequest) (*sql.DB, *db.TinkDB, func() error) { +func NewPostgresDatabaseClient(ctx context.Context, t *testing.T, req NewPostgresDatabaseRequest) (*sql.DB, *db.TinkDB, func() error) { + t.Helper() + testcontainers.SkipIfProviderIsNotHealthy(t) postgresC, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ ContainerRequest: testcontainers.ContainerRequest{ diff --git a/db/hardware.go b/db/hardware.go index ec70e01cc..b57bff221 100644 --- a/db/hardware.go +++ b/db/hardware.go @@ -183,7 +183,7 @@ func (d TinkDB) GetAll(fn func([]byte) error) error { } err = rows.Err() - if err == sql.ErrNoRows { + if errors.Is(err, sql.ErrNoRows) { err = nil } return err diff --git a/db/hardware_test.go b/db/hardware_test.go index eb5994161..cf878e603 100644 --- a/db/hardware_test.go +++ b/db/hardware_test.go @@ -1,3 +1,4 @@ +//nolint:thelper // misuse of test helpers requires a large refactor into subtests package db_test import ( @@ -119,7 +120,7 @@ func TestCreateHardware(t *testing.T) { Expectation: func(t *testing.T, input []*hardware.Hardware, tinkDB *db.TinkDB) { count := 0 err := tinkDB.GetAll(func(b []byte) error { - count = count + 1 + count++ return nil }) if err != nil { @@ -140,7 +141,7 @@ func TestCreateHardware(t *testing.T) { for _, s := range tests { t.Run(s.Name, func(t *testing.T) { t.Parallel() - _, tinkDB, cl := NewPostgresDatabaseClient(t, ctx, NewPostgresDatabaseRequest{ + _, tinkDB, cl := NewPostgresDatabaseClient(ctx, t, NewPostgresDatabaseRequest{ ApplyMigration: true, }) defer func() { @@ -178,7 +179,7 @@ func TestCreateHardware(t *testing.T) { func TestDeleteHardware(t *testing.T) { t.Parallel() ctx := context.Background() - _, tinkDB, cl := NewPostgresDatabaseClient(t, ctx, NewPostgresDatabaseRequest{ + _, tinkDB, cl := NewPostgresDatabaseClient(ctx, t, NewPostgresDatabaseRequest{ ApplyMigration: true, }) defer func() { @@ -200,7 +201,7 @@ func TestDeleteHardware(t *testing.T) { count := 0 err = tinkDB.GetAll(func(b []byte) error { - count = count + 1 + count++ return nil }) if err != nil { @@ -262,7 +263,7 @@ func TestGetByID(t *testing.T) { for _, s := range tests { t.Run(s.Name, func(t *testing.T) { t.Parallel() - _, tinkDB, cl := NewPostgresDatabaseClient(t, ctx, NewPostgresDatabaseRequest{ + _, tinkDB, cl := NewPostgresDatabaseClient(ctx, t, NewPostgresDatabaseRequest{ ApplyMigration: true, }) defer func() { @@ -300,7 +301,7 @@ func TestGetByID(t *testing.T) { func TestGetByID_WithNonExistingID(t *testing.T) { t.Parallel() ctx := context.Background() - _, tinkDB, cl := NewPostgresDatabaseClient(t, ctx, NewPostgresDatabaseRequest{ + _, tinkDB, cl := NewPostgresDatabaseClient(ctx, t, NewPostgresDatabaseRequest{ ApplyMigration: true, }) defer func() { @@ -316,8 +317,10 @@ func TestGetByID_WithNonExistingID(t *testing.T) { } want := "no rows in result set" + + // TODO: use errors.Is here if !strings.Contains(err.Error(), want) { - t.Error(fmt.Errorf("unexpected output, looking for %q as a substring in %q", want, err.Error())) + t.Error(fmt.Errorf("unexpected output, looking for %q as a substring in %q", want, err.Error())) //nolint:errorlint // non-wrapping format verb for fmt.Errorf } } @@ -375,7 +378,7 @@ func TestGetByIP(t *testing.T) { for _, s := range tests { t.Run(s.Name, func(t *testing.T) { t.Parallel() - _, tinkDB, cl := NewPostgresDatabaseClient(t, ctx, NewPostgresDatabaseRequest{ + _, tinkDB, cl := NewPostgresDatabaseClient(ctx, t, NewPostgresDatabaseRequest{ ApplyMigration: true, }) defer func() { @@ -413,7 +416,7 @@ func TestGetByIP(t *testing.T) { func TestGetByIP_WithNonExistingIP(t *testing.T) { t.Parallel() ctx := context.Background() - _, tinkDB, cl := NewPostgresDatabaseClient(t, ctx, NewPostgresDatabaseRequest{ + _, tinkDB, cl := NewPostgresDatabaseClient(ctx, t, NewPostgresDatabaseRequest{ ApplyMigration: true, }) defer func() { @@ -430,7 +433,7 @@ func TestGetByIP_WithNonExistingIP(t *testing.T) { want := "no rows in result set" if !strings.Contains(err.Error(), want) { - t.Error(fmt.Errorf("unexpected output, looking for %q as a substring in %q", want, err.Error())) + t.Error(fmt.Errorf("unexpected output, looking for %q as a substring in %q", want, err.Error())) //nolint:errorlint // non-wrapping format verb for fmt.Errorf } } @@ -486,7 +489,7 @@ func TestGetByMAC(t *testing.T) { for _, s := range tests { t.Run(s.Name, func(t *testing.T) { t.Parallel() - _, tinkDB, cl := NewPostgresDatabaseClient(t, ctx, NewPostgresDatabaseRequest{ + _, tinkDB, cl := NewPostgresDatabaseClient(ctx, t, NewPostgresDatabaseRequest{ ApplyMigration: true, }) defer func() { @@ -524,7 +527,7 @@ func TestGetByMAC(t *testing.T) { func TestGetByMAC_WithNonExistingMAC(t *testing.T) { t.Parallel() ctx := context.Background() - _, tinkDB, cl := NewPostgresDatabaseClient(t, ctx, NewPostgresDatabaseRequest{ + _, tinkDB, cl := NewPostgresDatabaseClient(ctx, t, NewPostgresDatabaseRequest{ ApplyMigration: true, }) defer func() { @@ -541,7 +544,7 @@ func TestGetByMAC_WithNonExistingMAC(t *testing.T) { want := "no rows in result set" if !strings.Contains(err.Error(), want) { - t.Error(fmt.Errorf("unexpected output, looking for %q as a substring in %q", want, err.Error())) + t.Error(fmt.Errorf("unexpected output, looking for %q as a substring in %q", want, err.Error())) //nolint:errorlint // non-wrapping format verb for fmt.Errorf } } @@ -551,19 +554,19 @@ func readHardwareData(file string) *hardware.Hardware { panic(err) } var hw pkg.HardwareWrapper - err = json.Unmarshal([]byte(data), &hw) + err = json.Unmarshal(data, &hw) if err != nil { panic(err) } return hw.Hardware } -func createHardware(ctx context.Context, db *db.TinkDB, hw *hardware.Hardware) error { +func createHardware(ctx context.Context, d *db.TinkDB, hw *hardware.Hardware) error { data, err := json.Marshal(hw) if err != nil { return err } - return db.InsertIntoDB(ctx, string(data)) + return d.InsertIntoDB(ctx, string(data)) } func hardwareComparer(in *hardware.Hardware, hw *hardware.Hardware) bool { diff --git a/db/mock/hardware.go b/db/mock/hardware.go index acd56ec72..b68665b11 100644 --- a/db/mock/hardware.go +++ b/db/mock/hardware.go @@ -5,31 +5,31 @@ import ( ) // DeleteFromDB : delete data from hardware table. -func (d DB) DeleteFromDB(ctx context.Context, id string) error { +func (d DB) DeleteFromDB(_ context.Context, _ string) error { return nil } // InsertIntoDB : insert data into hardware table. -func (d DB) InsertIntoDB(ctx context.Context, data string) error { +func (d DB) InsertIntoDB(_ context.Context, _ string) error { return nil } // GetByMAC : get data by machine mac. -func (d DB) GetByMAC(ctx context.Context, mac string) (string, error) { +func (d DB) GetByMAC(_ context.Context, _ string) (string, error) { return "", nil } // GetByIP : get data by machine ip. -func (d DB) GetByIP(ctx context.Context, ip string) (string, error) { +func (d DB) GetByIP(_ context.Context, _ string) (string, error) { return "", nil } // GetByID : get data by machine id. -func (d DB) GetByID(ctx context.Context, id string) (string, error) { +func (d DB) GetByID(_ context.Context, _ string) (string, error) { return "", nil } // GetAll : get data for all machine. -func (d DB) GetAll(fn func([]byte) error) error { +func (d DB) GetAll(_ func([]byte) error) error { return nil } diff --git a/db/mock/template.go b/db/mock/template.go index 5bdd2a6e0..c9cfa4f60 100644 --- a/db/mock/template.go +++ b/db/mock/template.go @@ -2,7 +2,7 @@ package mock import ( "context" - "errors" + "fmt" "github.com/golang/protobuf/ptypes/timestamp" "github.com/google/uuid" @@ -16,7 +16,7 @@ type Template struct { } // CreateTemplate creates a new workflow template. -func (d *DB) CreateTemplate(ctx context.Context, name string, data string, id uuid.UUID) error { +func (d *DB) CreateTemplate(_ context.Context, name string, data string, id uuid.UUID) error { if d.TemplateDB == nil { d.TemplateDB = make(map[string]interface{}) } @@ -26,10 +26,10 @@ func (d *DB) CreateTemplate(ctx context.Context, name string, data string, id uu switch stmpl := tmpl.(type) { case Template: if !stmpl.Deleted { - return errors.New("Template name already exist in the database") + return fmt.Errorf("template name %q already exists in the database", name) } default: - return errors.New("Not a Template type in the database") + return fmt.Errorf("template %q not a Template type in the database", name) } } d.TemplateDB[name] = Template{ @@ -47,7 +47,7 @@ func (d DB) GetTemplate(ctx context.Context, fields map[string]string, deleted b } // DeleteTemplate deletes a workflow template. -func (d DB) DeleteTemplate(ctx context.Context, name string) error { +func (d DB) DeleteTemplate(_ context.Context, name string) error { if d.TemplateDB != nil { delete(d.TemplateDB, name) } @@ -56,12 +56,12 @@ func (d DB) DeleteTemplate(ctx context.Context, name string) error { } // ListTemplates returns all saved templates. -func (d DB) ListTemplates(in string, fn func(id, n string, in, del *timestamp.Timestamp) error) error { +func (d DB) ListTemplates(_ string, _ func(id, n string, in, del *timestamp.Timestamp) error) error { return nil } // UpdateTemplate update a given template. -func (d DB) UpdateTemplate(ctx context.Context, name string, data string, id uuid.UUID) error { +func (d DB) UpdateTemplate(_ context.Context, _ string, _ string, _ uuid.UUID) error { return nil } diff --git a/db/mock/workflow.go b/db/mock/workflow.go index 7a6f85ef1..31b113f91 100644 --- a/db/mock/workflow.go +++ b/db/mock/workflow.go @@ -45,17 +45,17 @@ func (d DB) GetWorkflow(ctx context.Context, id string) (db.Workflow, error) { } // DeleteWorkflow deletes a workflow. -func (d DB) DeleteWorkflow(ctx context.Context, id string, state int32) error { +func (d DB) DeleteWorkflow(_ context.Context, _ string, _ int32) error { return nil } // ListWorkflows returns all workflows. -func (d DB) ListWorkflows(fn func(wf db.Workflow) error) error { +func (d DB) ListWorkflows(_ func(wf db.Workflow) error) error { return nil } // UpdateWorkflow updates a given workflow. -func (d DB) UpdateWorkflow(ctx context.Context, wf db.Workflow, state int32) error { +func (d DB) UpdateWorkflow(_ context.Context, _ db.Workflow, _ int32) error { return nil } @@ -75,11 +75,11 @@ func (d DB) GetWorkflowActions(ctx context.Context, wfID string) (*pb.WorkflowAc } // InsertIntoWorkflowEventTable : insert workflow event table. -func (d DB) InsertIntoWorkflowEventTable(ctx context.Context, wfEvent *pb.WorkflowActionStatus, time time.Time) error { - return d.InsertIntoWorkflowEventTableFunc(ctx, wfEvent, time) +func (d DB) InsertIntoWorkflowEventTable(ctx context.Context, wfEvent *pb.WorkflowActionStatus, t time.Time) error { + return d.InsertIntoWorkflowEventTableFunc(ctx, wfEvent, t) } // ShowWorkflowEvents returns all workflows. -func (d DB) ShowWorkflowEvents(wfID string, fn func(wfs *pb.WorkflowActionStatus) error) error { +func (d DB) ShowWorkflowEvents(_ string, _ func(wfs *pb.WorkflowActionStatus) error) error { return nil } diff --git a/db/template.go b/db/template.go index 569c09ef4..6f049414d 100644 --- a/db/template.go +++ b/db/template.go @@ -93,7 +93,7 @@ func (d TinkDB) GetTemplate(ctx context.Context, fields map[string]string, delet UpdatedAt: upAt, }, nil } - if err != sql.ErrNoRows { + if !errors.Is(err, sql.ErrNoRows) { err = errors.Wrap(err, "SELECT") d.logger.Error(err) } @@ -168,7 +168,7 @@ func (d TinkDB) ListTemplates(filter string, fn func(id, n string, in, del *time } err = rows.Err() - if err == sql.ErrNoRows { + if errors.Is(err, sql.ErrNoRows) { err = nil } return err @@ -181,28 +181,13 @@ func (d TinkDB) UpdateTemplate(ctx context.Context, name string, data string, id return errors.Wrap(err, "BEGIN transaction") } - if data == "" && name != "" { - _, err = tx.Exec(` - UPDATE template - SET - updated_at = NOW(), name = $2 - WHERE - id = $1;`, id, name) - } else if data != "" && name == "" { - _, err = tx.Exec(` - UPDATE template - SET - updated_at = NOW(), data = $2 - WHERE - id = $1;`, id, data) - } else { - _, err = tx.Exec(` - UPDATE template - SET - updated_at = NOW(), name = $2, data = $3 - WHERE - id = $1; - `, id, name, data) + switch { + case data == "" && name != "": + _, err = tx.Exec(`UPDATE template SET updated_at = NOW(), name = $2 WHERE id = $1;`, id, name) + case data != "" && name == "": + _, err = tx.Exec(`UPDATE template SET updated_at = NOW(), data = $2 WHERE id = $1;`, id, data) + default: + _, err = tx.Exec(`UPDATE template SET updated_at = NOW(), name = $2, data = $3 WHERE id = $1;`, id, name, data) } if err != nil { diff --git a/db/template_test.go b/db/template_test.go index 4e003c626..28184ba08 100644 --- a/db/template_test.go +++ b/db/template_test.go @@ -1,3 +1,4 @@ +//nolint:thelper // misuse of test helpers requires a large refactor into subtests package db_test import ( @@ -127,7 +128,7 @@ func TestCreateTemplate(t *testing.T) { Expectation: func(t *testing.T, input []*workflow.Workflow, tinkDB *db.TinkDB) { count := 0 err := tinkDB.ListTemplates("%", func(id, n string, in, del *timestamp.Timestamp) error { - count = count + 1 + count++ return nil }) if err != nil { @@ -143,7 +144,7 @@ func TestCreateTemplate(t *testing.T) { for _, s := range table { t.Run(s.Name, func(t *testing.T) { t.Parallel() - _, tinkDB, cl := NewPostgresDatabaseClient(t, ctx, NewPostgresDatabaseRequest{ + _, tinkDB, cl := NewPostgresDatabaseClient(ctx, t, NewPostgresDatabaseRequest{ ApplyMigration: true, }) defer func() { @@ -180,7 +181,7 @@ func TestCreateTemplate(t *testing.T) { func TestCreateTemplate_TwoTemplateWithSameNameButFirstOneIsDeleted(t *testing.T) { t.Parallel() ctx := context.Background() - _, tinkDB, cl := NewPostgresDatabaseClient(t, ctx, NewPostgresDatabaseRequest{ + _, tinkDB, cl := NewPostgresDatabaseClient(ctx, t, NewPostgresDatabaseRequest{ ApplyMigration: true, }) defer func() { @@ -212,7 +213,7 @@ func TestCreateTemplate_TwoTemplateWithSameNameButFirstOneIsDeleted(t *testing.T func TestDeleteTemplate(t *testing.T) { t.Parallel() ctx := context.Background() - _, tinkDB, cl := NewPostgresDatabaseClient(t, ctx, NewPostgresDatabaseRequest{ + _, tinkDB, cl := NewPostgresDatabaseClient(ctx, t, NewPostgresDatabaseRequest{ ApplyMigration: true, }) defer func() { @@ -237,7 +238,7 @@ func TestDeleteTemplate(t *testing.T) { count := 0 err = tinkDB.ListTemplates("%", func(id, n string, in, del *timestamp.Timestamp) error { - count = count + 1 + count++ return nil }) if err != nil { @@ -304,7 +305,7 @@ func TestGetTemplate(t *testing.T) { for _, s := range tests { t.Run(s.Name, func(t *testing.T) { t.Parallel() - _, tinkDB, cl := NewPostgresDatabaseClient(t, ctx, NewPostgresDatabaseRequest{ + _, tinkDB, cl := NewPostgresDatabaseClient(ctx, t, NewPostgresDatabaseRequest{ ApplyMigration: true, }) defer func() { @@ -342,7 +343,7 @@ func TestGetTemplate(t *testing.T) { func TestGetTemplateWithInvalidID(t *testing.T) { t.Parallel() ctx := context.Background() - _, tinkDB, cl := NewPostgresDatabaseClient(t, ctx, NewPostgresDatabaseRequest{ + _, tinkDB, cl := NewPostgresDatabaseClient(ctx, t, NewPostgresDatabaseRequest{ ApplyMigration: true, }) defer func() { @@ -359,8 +360,9 @@ func TestGetTemplateWithInvalidID(t *testing.T) { } want := "no rows in result set" + // TODO: replace with errors.Is if !strings.Contains(err.Error(), want) { - t.Error(fmt.Errorf("unexpected output, looking for %q as a substring in %q", want, err.Error())) + t.Error(fmt.Errorf("unexpected output, looking for %q as a substring in %q", want, err.Error())) // nolint:errorlint // non-wrapping format verb for fmt.Errorf } } diff --git a/db/workflow.go b/db/workflow.go index 0cad04eb0..6a9ce8132 100644 --- a/db/workflow.go +++ b/db/workflow.go @@ -44,7 +44,7 @@ func (d TinkDB) CreateWorkflow(ctx context.Context, wf Workflow, data string, id if err != nil { return errors.Wrap(err, "failed to create workflow") } - err = insertInWorkflow(ctx, d.instance, wf, tx) + err = insertInWorkflow(wf, tx) if err != nil { return errors.Wrap(err, "failed to create workflow") } @@ -55,7 +55,7 @@ func (d TinkDB) CreateWorkflow(ctx context.Context, wf Workflow, data string, id return nil } -func insertInWorkflow(ctx context.Context, db *sql.DB, wf Workflow, tx *sql.Tx) error { +func insertInWorkflow(wf Workflow, tx *sql.Tx) error { _, err := tx.Exec(` INSERT INTO workflow (created_at, updated_at, template, devices, id) @@ -72,7 +72,7 @@ func insertInWorkflow(ctx context.Context, db *sql.DB, wf Workflow, tx *sql.Tx) return nil } -func insertIntoWfWorkerTable(ctx context.Context, db *sql.DB, wfID uuid.UUID, workerID uuid.UUID, tx *sql.Tx) error { +func insertIntoWfWorkerTable(wfID uuid.UUID, workerID uuid.UUID, tx *sql.Tx) error { _, err := tx.Exec(` INSERT INTO workflow_worker_map (workflow_id, worker_id) @@ -116,7 +116,7 @@ func insertActionList(ctx context.Context, db *sql.DB, yamlData string, id uuid. return err } if uniqueWorkerID != workerUID { - err = insertIntoWfWorkerTable(ctx, db, id, workerUID, tx) + err = insertIntoWfWorkerTable(id, workerUID, tx) if err != nil { return err } @@ -197,7 +197,7 @@ func (d TinkDB) InsertIntoWfDataTable(ctx context.Context, req *pb.UpdateWorkflo } // increment version - version = version + 1 + version++ tx, err := d.instance.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable}) if err != nil { return errors.Wrap(err, "BEGIN transaction") @@ -254,7 +254,7 @@ func (d TinkDB) GetfromWfDataTable(ctx context.Context, req *pb.GetWorkflowDataR buf := []byte{} err := row.Scan(&buf) if err == nil { - return []byte(buf), nil + return buf, nil } if err != sql.ErrNoRows { @@ -285,7 +285,7 @@ func (d TinkDB) GetWorkflowMetadata(ctx context.Context, req *pb.GetWorkflowData buf := []byte{} err := row.Scan(&buf) if err == nil { - return []byte(buf), nil + return buf, nil } if err != sql.ErrNoRows { @@ -326,7 +326,7 @@ func (d TinkDB) GetWorkflowsForWorker(id string) ([]string, error) { wfID = append(wfID, workerID) } err = rows.Err() - if err == sql.ErrNoRows { + if errors.Is(err, sql.ErrNoRows) { return nil, nil } return wfID, err @@ -369,7 +369,7 @@ func (d TinkDB) GetWorkflow(ctx context.Context, id string) (Workflow, error) { } // DeleteWorkflow deletes a workflow. -func (d TinkDB) DeleteWorkflow(ctx context.Context, id string, state int32) error { +func (d TinkDB) DeleteWorkflow(ctx context.Context, id string, _ int32) error { tx, err := d.instance.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable}) if err != nil { return errors.Wrap(err, "BEGIN transaction") @@ -454,43 +454,26 @@ func (d TinkDB) ListWorkflows(fn func(wf Workflow) error) error { } } err = rows.Err() - if err == sql.ErrNoRows { + if errors.Is(err, sql.ErrNoRows) { err = nil } return err } // UpdateWorkflow updates a given workflow. -func (d TinkDB) UpdateWorkflow(ctx context.Context, wf Workflow, state int32) error { +func (d TinkDB) UpdateWorkflow(ctx context.Context, wf Workflow, _ int32) error { tx, err := d.instance.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable}) if err != nil { return errors.Wrap(err, "BEGIN transaction") } - if wf.Hardware == "" && wf.Template != "" { - _, err = tx.Exec(` - UPDATE workflow - SET - updated_at = NOW(), template = $2 - WHERE - id = $1; - `, wf.ID, wf.Template) - } else if wf.Hardware != "" && wf.Template == "" { - _, err = tx.Exec(` - UPDATE workflow - SET - updated_at = NOW(), devices = $2 - WHERE - id = $1; - `, wf.ID, wf.Hardware) - } else { - _, err = tx.Exec(` - UPDATE workflow - SET - updated_at = NOW(), template = $2, devices = $3 - WHERE - id = $1; - `, wf.ID, wf.Template, wf.Hardware) + switch { + case wf.Hardware == "" && wf.Template != "": + _, err = tx.Exec(`UPDATE workflow SET updated_at = NOW(), template = $2 WHERE id = $1;`, wf.ID, wf.Template) + case wf.Hardware != "" && wf.Template == "": + _, err = tx.Exec(`UPDATE workflow SET updated_at = NOW(), devices = $2 WHERE id = $1;`, wf.ID, wf.Hardware) + default: + _, err = tx.Exec(`UPDATE workflow SET updated_at = NOW(), template = $2, devices = $3 WHERE id = $1;`, wf.ID, wf.Template, wf.Hardware) } if err != nil { @@ -591,7 +574,7 @@ func (d TinkDB) GetWorkflowActions(ctx context.Context, wfID string) (*pb.Workfl } // InsertIntoWorkflowEventTable : insert workflow event table. -func (d TinkDB) InsertIntoWorkflowEventTable(ctx context.Context, wfEvent *pb.WorkflowActionStatus, time time.Time) error { +func (d TinkDB) InsertIntoWorkflowEventTable(ctx context.Context, wfEvent *pb.WorkflowActionStatus, t time.Time) error { tx, err := d.instance.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable}) if err != nil { return errors.Wrap(err, "BEGIN transaction") @@ -603,7 +586,7 @@ func (d TinkDB) InsertIntoWorkflowEventTable(ctx context.Context, wfEvent *pb.Wo workflow_event (workflow_id, worker_id, task_name, action_name, execution_time, message, status, created_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8); - `, wfEvent.WorkflowId, wfEvent.WorkerId, wfEvent.TaskName, wfEvent.ActionName, wfEvent.Seconds, wfEvent.Message, wfEvent.ActionStatus, time) + `, wfEvent.WorkflowId, wfEvent.WorkerId, wfEvent.TaskName, wfEvent.ActionName, wfEvent.Seconds, wfEvent.Message, wfEvent.ActionStatus, t) if err != nil { return errors.Wrap(err, "INSERT in to workflow_event") } @@ -630,14 +613,14 @@ func (d TinkDB) ShowWorkflowEvents(wfID string, fn func(wfs *pb.WorkflowActionSt defer rows.Close() var ( - status int32 + st int32 secs int64 id, tName, aName, msg string evTime time.Time ) for rows.Next() { - err = rows.Scan(&id, &tName, &aName, &secs, &msg, &status, &evTime) + err = rows.Scan(&id, &tName, &aName, &secs, &msg, &st, &evTime) if err != nil { err = errors.Wrap(err, "SELECT") d.logger.Error(err) @@ -650,7 +633,7 @@ func (d TinkDB) ShowWorkflowEvents(wfID string, fn func(wfs *pb.WorkflowActionSt ActionName: aName, Seconds: secs, Message: msg, - ActionStatus: pb.State(status), + ActionStatus: pb.State(st), CreatedAt: createdAt, } err = fn(wfs) @@ -659,7 +642,7 @@ func (d TinkDB) ShowWorkflowEvents(wfID string, fn func(wfs *pb.WorkflowActionSt } } err = rows.Err() - if err == sql.ErrNoRows { + if errors.Is(err, sql.ErrNoRows) { err = nil } return err @@ -674,8 +657,8 @@ func getLatestVersionWfData(ctx context.Context, db *sql.DB, wfID string) (int32 ` row := db.QueryRowContext(ctx, query, wfID) var version int32 - err := row.Scan(&version) - if err != nil { + + if err := row.Scan(&version); err != nil { return -1, err } return version, nil @@ -705,7 +688,7 @@ func getWorkerIDbyMac(ctx context.Context, db *sql.DB, mac string) (string, erro ` id, err := get(ctx, db, query, arg) - if errors.Cause(err) == sql.ErrNoRows { + if errors.Is(err, sql.ErrNoRows) { err = errors.WithMessage(errors.New(mac), "mac") } return id, err @@ -753,7 +736,7 @@ func getWorkerIDbyIP(ctx context.Context, db *sql.DB, ip string) (string, error) ` id, err := get(ctx, db, query, instance, hardwareOrManagement) - if errors.Cause(err) == sql.ErrNoRows { + if errors.Is(err, sql.ErrNoRows) { err = errors.WithMessage(errors.New(ip), "ip") } return id, err diff --git a/db/workflow_test.go b/db/workflow_test.go index ca042a164..26d1493d2 100644 --- a/db/workflow_test.go +++ b/db/workflow_test.go @@ -1,3 +1,4 @@ +//nolint:thelper // misuse of test helpers requires a large refactor into subtests package db_test import ( @@ -55,7 +56,7 @@ func TestCreateWorkflow(t *testing.T) { Expectation: func(t *testing.T, in *input, tinkDB *db.TinkDB) { count := 0 err := tinkDB.ListWorkflows(func(wf db.Workflow) error { - count = count + 1 + count++ return nil }) if err != nil { @@ -82,7 +83,7 @@ func TestCreateWorkflow(t *testing.T) { Expectation: func(t *testing.T, in *input, tinkDB *db.TinkDB) { count := 0 err := tinkDB.ListWorkflows(func(wf db.Workflow) error { - count = count + 1 + count++ return nil }) if err != nil { @@ -109,7 +110,7 @@ func TestCreateWorkflow(t *testing.T) { Expectation: func(t *testing.T, in *input, tinkDB *db.TinkDB) { count := 0 err := tinkDB.ListWorkflows(func(wf db.Workflow) error { - count = count + 1 + count++ return nil }) if err != nil { @@ -137,7 +138,7 @@ func TestCreateWorkflow(t *testing.T) { Expectation: func(t *testing.T, in *input, tinkDB *db.TinkDB) { count := 0 err := tinkDB.ListWorkflows(func(wf db.Workflow) error { - count = count + 1 + count++ return nil }) if err != nil { @@ -154,7 +155,7 @@ func TestCreateWorkflow(t *testing.T) { for _, s := range tests { t.Run(s.Name, func(t *testing.T) { t.Parallel() - _, tinkDB, cl := NewPostgresDatabaseClient(t, ctx, NewPostgresDatabaseRequest{ + _, tinkDB, cl := NewPostgresDatabaseClient(ctx, t, NewPostgresDatabaseRequest{ ApplyMigration: true, }) defer func() { @@ -201,7 +202,7 @@ func TestCreateWorkflow(t *testing.T) { func TestDeleteWorkflow(t *testing.T) { t.Parallel() ctx := context.Background() - _, tinkDB, cl := NewPostgresDatabaseClient(t, ctx, NewPostgresDatabaseRequest{ + _, tinkDB, cl := NewPostgresDatabaseClient(ctx, t, NewPostgresDatabaseRequest{ ApplyMigration: true, }) defer func() { @@ -235,6 +236,7 @@ func TestDeleteWorkflow(t *testing.T) { t.Error(err) } + // TODO: Investigate why we bother with passing an unused status value err = tinkDB.DeleteWorkflow(ctx, wfID, pb.State_value[pb.State_STATE_PENDING.String()]) if err != nil { t.Error(err) @@ -242,7 +244,7 @@ func TestDeleteWorkflow(t *testing.T) { count := 0 err = tinkDB.ListWorkflows(func(wf db.Workflow) error { - count = count + 1 + count++ return nil }) if err != nil { @@ -332,7 +334,7 @@ func TestGetWorkflow(t *testing.T) { for _, s := range tests { t.Run(s.Name, func(t *testing.T) { t.Parallel() - _, tinkDB, cl := NewPostgresDatabaseClient(t, ctx, NewPostgresDatabaseRequest{ + _, tinkDB, cl := NewPostgresDatabaseClient(ctx, t, NewPostgresDatabaseRequest{ ApplyMigration: true, }) defer func() { diff --git a/grpc-server/template_test.go b/grpc-server/template_test.go index 8cb0fe00e..ca9a6569d 100644 --- a/grpc-server/template_test.go +++ b/grpc-server/template_test.go @@ -135,7 +135,10 @@ func TestCreateTemplate(t *testing.T) { } ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout) - defer cancel() + t.Cleanup(func() { + cancel() + }) + for name := range testCases { tc := testCases[name] t.Run(name, func(t *testing.T) { @@ -354,7 +357,10 @@ func TestGetTemplate(t *testing.T) { } ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout) - defer cancel() + t.Cleanup(func() { + cancel() + }) + for name := range testCases { tc := testCases[name] t.Run(name, func(t *testing.T) { diff --git a/grpc-server/tinkerbell.go b/grpc-server/tinkerbell.go index c8e048d11..798010ad6 100644 --- a/grpc-server/tinkerbell.go +++ b/grpc-server/tinkerbell.go @@ -17,7 +17,7 @@ var workflowData = make(map[string]int) const ( errInvalidWorkerID = "invalid worker id" - errInvalidWorkflowId = "invalid workflow id" + errInvalidWorkflowID = "invalid workflow id" errInvalidTaskName = "invalid task name" errInvalidActionName = "invalid action name" errInvalidTaskReported = "reported task name does not match the current action details" @@ -49,7 +49,7 @@ func (s *server) GetWorkflowContexts(req *pb.WorkflowContextRequest, stream pb.W } // GetWorkflowContextList implements tinkerbell.GetWorkflowContextList. -func (s *server) GetWorkflowContextList(context context.Context, req *pb.WorkflowContextRequest) (*pb.WorkflowContextList, error) { +func (s *server) GetWorkflowContextList(ctx context.Context, req *pb.WorkflowContextRequest) (*pb.WorkflowContextList, error) { wfs, err := getWorkflowsForWorker(s.db, req.WorkerId) if err != nil { return nil, err @@ -58,7 +58,7 @@ func (s *server) GetWorkflowContextList(context context.Context, req *pb.Workflo if wfs != nil { wfContexts := []*pb.WorkflowContext{} for _, wf := range wfs { - wfContext, err := s.db.GetWorkflowContexts(context, wf) + wfContext, err := s.db.GetWorkflowContexts(ctx, wf) if err != nil { return nil, status.Errorf(codes.Aborted, err.Error()) } @@ -72,19 +72,19 @@ func (s *server) GetWorkflowContextList(context context.Context, req *pb.Workflo } // GetWorkflowActions implements tinkerbell.GetWorkflowActions. -func (s *server) GetWorkflowActions(context context.Context, req *pb.WorkflowActionsRequest) (*pb.WorkflowActionList, error) { +func (s *server) GetWorkflowActions(ctx context.Context, req *pb.WorkflowActionsRequest) (*pb.WorkflowActionList, error) { wfID := req.GetWorkflowId() if wfID == "" { - return nil, status.Errorf(codes.InvalidArgument, errInvalidWorkflowId) + return nil, status.Errorf(codes.InvalidArgument, errInvalidWorkflowID) } - return getWorkflowActions(context, s.db, wfID) + return getWorkflowActions(ctx, s.db, wfID) } // ReportActionStatus implements tinkerbell.ReportActionStatus. -func (s *server) ReportActionStatus(context context.Context, req *pb.WorkflowActionStatus) (*pb.Empty, error) { +func (s *server) ReportActionStatus(ctx context.Context, req *pb.WorkflowActionStatus) (*pb.Empty, error) { wfID := req.GetWorkflowId() if wfID == "" { - return nil, status.Errorf(codes.InvalidArgument, errInvalidWorkflowId) + return nil, status.Errorf(codes.InvalidArgument, errInvalidWorkflowID) } if req.GetTaskName() == "" { return nil, status.Errorf(codes.InvalidArgument, errInvalidTaskName) @@ -96,11 +96,11 @@ func (s *server) ReportActionStatus(context context.Context, req *pb.WorkflowAct l := s.logger.With("actionName", req.GetActionName(), "workflowID", req.GetWorkflowId()) l.Info(fmt.Sprintf(msgReceivedStatus, req.GetActionStatus())) - wfContext, err := s.db.GetWorkflowContexts(context, wfID) + wfContext, err := s.db.GetWorkflowContexts(ctx, wfID) if err != nil { return nil, status.Errorf(codes.Aborted, err.Error()) } - wfActions, err := s.db.GetWorkflowActions(context, wfID) + wfActions, err := s.db.GetWorkflowActions(ctx, wfID) if err != nil { return nil, status.Errorf(codes.Aborted, err.Error()) } @@ -108,7 +108,7 @@ func (s *server) ReportActionStatus(context context.Context, req *pb.WorkflowAct actionIndex := wfContext.GetCurrentActionIndex() if req.GetActionStatus() == pb.State_STATE_RUNNING { if wfContext.GetCurrentAction() != "" { - actionIndex = actionIndex + 1 + actionIndex++ } } action := wfActions.ActionList[actionIndex] @@ -123,14 +123,14 @@ func (s *server) ReportActionStatus(context context.Context, req *pb.WorkflowAct wfContext.CurrentAction = req.GetActionName() wfContext.CurrentActionState = req.GetActionStatus() wfContext.CurrentActionIndex = actionIndex - err = s.db.UpdateWorkflowState(context, wfContext) + err = s.db.UpdateWorkflowState(ctx, wfContext) if err != nil { return &pb.Empty{}, status.Errorf(codes.Aborted, err.Error()) } // TODO the below "time" would be a part of the request which is coming form worker. - time := time.Now() - err = s.db.InsertIntoWorkflowEventTable(context, req, time) + t := time.Now() + err = s.db.InsertIntoWorkflowEventTable(ctx, req, t) if err != nil { return &pb.Empty{}, status.Error(codes.Aborted, err.Error()) } @@ -149,16 +149,16 @@ func (s *server) ReportActionStatus(context context.Context, req *pb.WorkflowAct } // UpdateWorkflowData updates workflow ephemeral data. -func (s *server) UpdateWorkflowData(context context.Context, req *pb.UpdateWorkflowDataRequest) (*pb.Empty, error) { +func (s *server) UpdateWorkflowData(ctx context.Context, req *pb.UpdateWorkflowDataRequest) (*pb.Empty, error) { wfID := req.GetWorkflowId() if wfID == "" { - return &pb.Empty{}, status.Errorf(codes.InvalidArgument, errInvalidWorkflowId) + return &pb.Empty{}, status.Errorf(codes.InvalidArgument, errInvalidWorkflowID) } _, ok := workflowData[wfID] if !ok { workflowData[wfID] = 1 } - err := s.db.InsertIntoWfDataTable(context, req) + err := s.db.InsertIntoWfDataTable(ctx, req) if err != nil { return &pb.Empty{}, status.Errorf(codes.Aborted, err.Error()) } @@ -166,12 +166,12 @@ func (s *server) UpdateWorkflowData(context context.Context, req *pb.UpdateWorkf } // GetWorkflowData gets the ephemeral data for a workflow. -func (s *server) GetWorkflowData(context context.Context, req *pb.GetWorkflowDataRequest) (*pb.GetWorkflowDataResponse, error) { - wfID := req.GetWorkflowId() - if wfID == "" { - return &pb.GetWorkflowDataResponse{Data: []byte("")}, status.Errorf(codes.InvalidArgument, errInvalidWorkflowId) +func (s *server) GetWorkflowData(ctx context.Context, req *pb.GetWorkflowDataRequest) (*pb.GetWorkflowDataResponse, error) { + if wfID := req.GetWorkflowId(); wfID == "" { + return &pb.GetWorkflowDataResponse{Data: []byte("")}, status.Errorf(codes.InvalidArgument, errInvalidWorkflowID) } - data, err := s.db.GetfromWfDataTable(context, req) + + data, err := s.db.GetfromWfDataTable(ctx, req) if err != nil { return &pb.GetWorkflowDataResponse{Data: []byte("")}, status.Errorf(codes.Aborted, err.Error()) } @@ -179,8 +179,8 @@ func (s *server) GetWorkflowData(context context.Context, req *pb.GetWorkflowDat } // GetWorkflowMetadata returns metadata wrt to the ephemeral data of a workflow. -func (s *server) GetWorkflowMetadata(context context.Context, req *pb.GetWorkflowDataRequest) (*pb.GetWorkflowDataResponse, error) { - data, err := s.db.GetWorkflowMetadata(context, req) +func (s *server) GetWorkflowMetadata(ctx context.Context, req *pb.GetWorkflowDataRequest) (*pb.GetWorkflowDataResponse, error) { + data, err := s.db.GetWorkflowMetadata(ctx, req) if err != nil { return &pb.GetWorkflowDataResponse{Data: []byte("")}, status.Errorf(codes.Aborted, err.Error()) } @@ -188,41 +188,41 @@ func (s *server) GetWorkflowMetadata(context context.Context, req *pb.GetWorkflo } // GetWorkflowDataVersion returns the latest version of data for a workflow. -func (s *server) GetWorkflowDataVersion(context context.Context, req *pb.GetWorkflowDataRequest) (*pb.GetWorkflowDataResponse, error) { - version, err := s.db.GetWorkflowDataVersion(context, req.WorkflowId) +func (s *server) GetWorkflowDataVersion(ctx context.Context, req *pb.GetWorkflowDataRequest) (*pb.GetWorkflowDataResponse, error) { + version, err := s.db.GetWorkflowDataVersion(ctx, req.WorkflowId) if err != nil { return &pb.GetWorkflowDataResponse{Version: version}, status.Errorf(codes.Aborted, err.Error()) } return &pb.GetWorkflowDataResponse{Version: version}, nil } -func getWorkflowsForWorker(db db.Database, id string) ([]string, error) { +func getWorkflowsForWorker(d db.Database, id string) ([]string, error) { if id == "" { return nil, status.Errorf(codes.InvalidArgument, errInvalidWorkerID) } - wfs, err := db.GetWorkflowsForWorker(id) + wfs, err := d.GetWorkflowsForWorker(id) if err != nil { return nil, status.Errorf(codes.Aborted, err.Error()) } return wfs, nil } -func getWorkflowActions(context context.Context, db db.Database, wfID string) (*pb.WorkflowActionList, error) { - actions, err := db.GetWorkflowActions(context, wfID) +func getWorkflowActions(ctx context.Context, d db.Database, wfID string) (*pb.WorkflowActionList, error) { + actions, err := d.GetWorkflowActions(ctx, wfID) if err != nil { - return nil, status.Errorf(codes.Aborted, errInvalidWorkflowId) + return nil, status.Errorf(codes.Aborted, errInvalidWorkflowID) } return actions, nil } // isApplicableToSend checks if a particular workflow context is applicable or if it is needed to // be sent to a worker based on the state of the current action and the targeted workerID. -func isApplicableToSend(context context.Context, logger log.Logger, wfContext *pb.WorkflowContext, workerID string, db db.Database) bool { +func isApplicableToSend(ctx context.Context, logger log.Logger, wfContext *pb.WorkflowContext, workerID string, d db.Database) bool { if wfContext.GetCurrentActionState() == pb.State_STATE_FAILED || wfContext.GetCurrentActionState() == pb.State_STATE_TIMEOUT { return false } - actions, err := getWorkflowActions(context, db, wfContext.GetWorkflowId()) + actions, err := getWorkflowActions(ctx, d, wfContext.GetWorkflowId()) if err != nil { return false } diff --git a/grpc-server/tinkerbell_test.go b/grpc-server/tinkerbell_test.go index d30fe7425..6de6c8512 100644 --- a/grpc-server/tinkerbell_test.go +++ b/grpc-server/tinkerbell_test.go @@ -28,11 +28,16 @@ const ( var wfData = []byte("{'os': 'ubuntu', 'base_url': 'http://192.168.1.1/'}") -func testServer(t *testing.T, db db.Database) *server { - l, _ := log.Init("github.com/tinkerbell/tink") +func testServer(t *testing.T, d db.Database) *server { + t.Helper() + l, err := log.Init("github.com/tinkerbell/tink") + if err != nil { + t.Errorf("log init failed: %v", err) + } + return &server{ logger: l, - db: db, + db: d, } } @@ -871,7 +876,7 @@ func TestGetWorkflowMetadata(t *testing.T) { UpdatedAt: time.Now(), SHA: "fcbf74596047b6d3e746702ccc2c697d87817371918a5042805c8c7c75b2cb5f", }) - return []byte(meta), nil + return meta, nil }, }, workflowID: workflowID, diff --git a/grpc-server/workflow.go b/grpc-server/workflow.go index 5ec578453..f37ec4339 100644 --- a/grpc-server/workflow.go +++ b/grpc-server/workflow.go @@ -5,6 +5,7 @@ import ( "strconv" "github.com/google/uuid" + "github.com/packethost/pkg/log" "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/tinkerbell/tink/db" @@ -111,7 +112,7 @@ func (s *server) GetWorkflow(ctx context.Context, in *workflow.GetRequest) (*wor Id: w.ID, Template: w.Template, Hardware: w.Hardware, - State: getWorkflowState(s.db, ctx, in.Id), + State: getWorkflowState(ctx, s.db, s.logger, in.Id), CreatedAt: w.CreatedAt, UpdatedAt: w.UpdatedAt, Data: data, @@ -175,7 +176,7 @@ func (s *server) ListWorkflows(_ *workflow.Empty, stream workflow.WorkflowServic Hardware: w.Hardware, CreatedAt: w.CreatedAt, UpdatedAt: w.UpdatedAt, - State: getWorkflowState(s.db, stream.Context(), w.ID), + State: getWorkflowState(stream.Context(), s.db, s.logger, w.ID), } return stream.Send(wf) }) @@ -218,7 +219,7 @@ func (s *server) GetWorkflowContext(ctx context.Context, in *workflow.GetRequest CurrentTask: w.CurrentTask, CurrentAction: w.CurrentAction, CurrentActionIndex: w.CurrentActionIndex, - CurrentActionState: workflow.State(w.CurrentActionState), + CurrentActionState: w.CurrentActionState, TotalNumberOfActions: w.TotalNumberOfActions, } l := s.logger.With( @@ -257,7 +258,7 @@ func (s *server) ShowWorkflowEvents(req *workflow.GetRequest, stream workflow.Wo WorkerId: w.WorkerId, TaskName: w.TaskName, ActionName: w.ActionName, - ActionStatus: workflow.State(w.ActionStatus), + ActionStatus: w.ActionStatus, Seconds: w.Seconds, Message: w.Message, CreatedAt: w.CreatedAt, @@ -278,15 +279,17 @@ func (s *server) ShowWorkflowEvents(req *workflow.GetRequest, stream workflow.Wo // considered as Failed/Timeout. And If an action is successful then the workflow state // will be considered as Running until the last action of the workflow is executed successfully. -func getWorkflowState(db db.Database, ctx context.Context, id string) workflow.State { - wfCtx, _ := db.GetWorkflowContexts(ctx, id) +func getWorkflowState(ctx context.Context, d db.Database, l log.Logger, id string) workflow.State { + wfCtx, err := d.GetWorkflowContexts(ctx, id) + if err != nil { + l.Error(err) + } + if wfCtx.CurrentActionState != workflow.State_STATE_SUCCESS { return wfCtx.CurrentActionState - } else { - if wfCtx.GetCurrentActionIndex() == wfCtx.GetTotalNumberOfActions()-1 { - return workflow.State_STATE_SUCCESS - } else { - return workflow.State_STATE_RUNNING - } } + if wfCtx.GetCurrentActionIndex() == wfCtx.GetTotalNumberOfActions()-1 { + return workflow.State_STATE_SUCCESS + } + return workflow.State_STATE_RUNNING } diff --git a/http-server/http_handlers.go b/http-server/http_handlers.go index cbf198d28..7ef9f7310 100644 --- a/http-server/http_handlers.go +++ b/http-server/http_handlers.go @@ -3,6 +3,7 @@ package httpserver import ( "context" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -53,7 +54,7 @@ func RegisterHardwareServiceHandlerFromEndpoint(ctx context.Context, mux *runtim return } - if err := json.NewDecoder(newReader()).Decode(&hw); err != nil && err != io.EOF { + if err := json.NewDecoder(newReader()).Decode(&hw); err != nil && !errors.Is(err, io.EOF) { writeResponse(w, http.StatusBadRequest, status.Errorf(codes.InvalidArgument, "%v", err).Error()) return } @@ -81,7 +82,7 @@ func RegisterHardwareServiceHandlerFromEndpoint(ctx context.Context, mux *runtim return } - if err := json.NewDecoder(newReader()).Decode(&gr); err != nil && err != io.EOF { + if err := json.NewDecoder(newReader()).Decode(&gr); err != nil && !errors.Is(err, io.EOF) { writeResponse(w, http.StatusBadRequest, status.Errorf(codes.InvalidArgument, "%v", err).Error()) return } @@ -109,7 +110,7 @@ func RegisterHardwareServiceHandlerFromEndpoint(ctx context.Context, mux *runtim return } - if err := json.NewDecoder(newReader()).Decode(&gr); err != nil && err != io.EOF { + if err := json.NewDecoder(newReader()).Decode(&gr); err != nil && !errors.Is(err, io.EOF) { writeResponse(w, http.StatusBadRequest, status.Errorf(codes.InvalidArgument, "%v", err).Error()) return } @@ -170,7 +171,7 @@ func RegisterHardwareServiceHandlerFromEndpoint(ctx context.Context, mux *runtim } var hw *hardware.Hardware - err = nil + for hw, err = alls.Recv(); err == nil && hw != nil; hw, err = alls.Recv() { b, err := json.Marshal(pkg.HardwareWrapper{Hardware: hw}) if err != nil { @@ -179,7 +180,7 @@ func RegisterHardwareServiceHandlerFromEndpoint(ctx context.Context, mux *runtim } writeResponse(w, http.StatusOK, string(b)) } - if err != nil && err != io.EOF { + if err != nil && !errors.Is(err, io.EOF) { writeResponse(w, http.StatusInternalServerError, err.Error()) return } @@ -246,7 +247,7 @@ func RegisterTemplateHandlerFromEndpoint(ctx context.Context, mux *runtime.Serve return } - if err := json.NewDecoder(newReader()).Decode(&tmpl); err != nil && err != io.EOF { + if err := json.NewDecoder(newReader()).Decode(&tmpl); err != nil && !errors.Is(err, io.EOF) { writeResponse(w, http.StatusBadRequest, status.Errorf(codes.InvalidArgument, "%v", err).Error()) return } @@ -364,7 +365,7 @@ func RegisterTemplateHandlerFromEndpoint(ctx context.Context, mux *runtime.Serve } var tmp *template.WorkflowTemplate - err = nil + for tmp, err = list.Recv(); err == nil && tmp.Name != ""; tmp, err = list.Recv() { m := protojson.MarshalOptions{UseProtoNames: true} s, err := m.Marshal(tmp) @@ -375,7 +376,7 @@ func RegisterTemplateHandlerFromEndpoint(ctx context.Context, mux *runtime.Serve writeResponse(w, http.StatusOK, string(s)) } - if err != nil && err != io.EOF { + if err != nil && !errors.Is(err, io.EOF) { writeResponse(w, http.StatusInternalServerError, err.Error()) } }) @@ -416,7 +417,7 @@ func RegisterWorkflowSvcHandlerFromEndpoint(ctx context.Context, mux *runtime.Se return } - if err := json.NewDecoder(newReader()).Decode(&cr); err != nil && err != io.EOF { + if err := json.NewDecoder(newReader()).Decode(&cr); err != nil && !errors.Is(err, io.EOF) { writeResponse(w, http.StatusBadRequest, status.Errorf(codes.InvalidArgument, "%v", err).Error()) return } @@ -488,7 +489,7 @@ func RegisterWorkflowSvcHandlerFromEndpoint(ctx context.Context, mux *runtime.Se } var wf *workflow.Workflow - err = nil + for wf, err = list.Recv(); err == nil && wf.Id != ""; wf, err = list.Recv() { m := protojson.MarshalOptions{UseProtoNames: true} s, err := m.Marshal(wf) @@ -499,7 +500,7 @@ func RegisterWorkflowSvcHandlerFromEndpoint(ctx context.Context, mux *runtime.Se writeResponse(w, http.StatusOK, string(s)) } - if err != nil && err != io.EOF { + if err != nil && !errors.Is(err, io.EOF) { writeResponse(w, http.StatusInternalServerError, err.Error()) return } @@ -561,7 +562,7 @@ func RegisterWorkflowSvcHandlerFromEndpoint(ctx context.Context, mux *runtime.Se return } var event *workflow.WorkflowActionStatus - err = nil + for event, err = events.Recv(); err == nil && event != nil; event, err = events.Recv() { m := protojson.MarshalOptions{UseProtoNames: true, EmitUnpopulated: true} s, err := m.Marshal(event) @@ -571,7 +572,7 @@ func RegisterWorkflowSvcHandlerFromEndpoint(ctx context.Context, mux *runtime.Se } writeResponse(w, http.StatusOK, string(s)) } - if err != nil && err != io.EOF { + if err != nil && !errors.Is(err, io.EOF) { writeResponse(w, http.StatusInternalServerError, err.Error()) return } @@ -589,8 +590,8 @@ func tryParseTemplate(data string) error { } // writeResponse appends a new line after res. -func writeResponse(w http.ResponseWriter, status int, res string) { - w.WriteHeader(status) +func writeResponse(w http.ResponseWriter, st int, res string) { + w.WriteHeader(st) if _, err := w.Write([]byte(fmt.Sprintln(res))); err != nil { logger.Info(err) } diff --git a/http-server/http_handlers_test.go b/http-server/http_handlers_test.go index 002d82412..b1534d604 100644 --- a/http-server/http_handlers_test.go +++ b/http-server/http_handlers_test.go @@ -31,7 +31,7 @@ type server struct { hardware.UnimplementedHardwareServiceServer } -func (s *server) Push(ctx context.Context, in *hardware.PushRequest) (*hardware.Empty, error) { +func (s *server) Push(_ context.Context, in *hardware.PushRequest) (*hardware.Empty, error) { hw := in.Data if hw.Id == "" { err := errors.New("id must be set to a UUID, got id: " + hw.Id) diff --git a/http-server/http_server.go b/http-server/http_server.go index a17688381..1b60451a8 100644 --- a/http-server/http_server.go +++ b/http-server/http_server.go @@ -26,7 +26,7 @@ var ( logger log.Logger ) -type HTTPServerConfig struct { +type Config struct { CertPEM []byte ModTime time.Time GRPCAuthority string @@ -36,7 +36,7 @@ type HTTPServerConfig struct { } // SetupHTTP setup and return an HTTP server. -func SetupHTTP(ctx context.Context, lg log.Logger, config *HTTPServerConfig, errCh chan<- error) { +func SetupHTTP(ctx context.Context, lg log.Logger, config *Config, errCh chan<- error) { logger = lg cp := x509.NewCertPool() @@ -87,7 +87,7 @@ func SetupHTTP(ctx context.Context, lg log.Logger, config *HTTPServerConfig, err go func() { logger.Info("serving http") err := srv.ListenAndServe() - if err == http.ErrServerClosed { + if errors.Is(err, http.ErrServerClosed) { err = nil } errCh <- err @@ -100,12 +100,12 @@ func SetupHTTP(ctx context.Context, lg log.Logger, config *HTTPServerConfig, err }() } -func versionHandler(w http.ResponseWriter, r *http.Request) { +func versionHandler(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "application/json") _, _ = w.Write(gitRevJSON) } -func healthCheckHandler(w http.ResponseWriter, r *http.Request) { +func healthCheckHandler(w http.ResponseWriter, _ *http.Request) { res := struct { GitRev string `json:"git_rev"` Uptime float64 `json:"uptime"` diff --git a/test/e2e_test.go b/test/e2e_test.go deleted file mode 100644 index 680dea12d..000000000 --- a/test/e2e_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package e2e - -//import ( -// "os" -// "time" -// "testing" -// -// "github.com/tinkerbell/tink/client" -// "github.com/tinkerbell/tink/protos/workflow" -// "github.com/tinkerbell/tink/test/framework" -// "github.com/sirupsen/logrus" -//) -// -//var log *logrus.Logger = framework.Log -// -//func TestMain(m *testing.M) { -// log.Infoln("########Creating Setup########") -// time.Sleep(10 * time.Second) -// err := framework.StartStack() -// if err != nil { -// os.Exit(1) -// } -// os.Setenv("TINKERBELL_GRPC_AUTHORITY", "127.0.0.1:42113") -// os.Setenv("TINKERBELL_CERT_URL", "http://127.0.0.1:42114/cert") -// client.Setup() -// log.Infoln("########Setup Created########") -// -// log.Infoln("Creating hardware inventory") -// //push hardware data into hardware table -// hwData := []string{"hardware_1.json", "hardware_2.json"} -// err = framework.PushHardwareData(hwData) -// if err != nil { -// log.Errorln("Failed to push hardware inventory : ", err) -// os.Exit(2) -// } -// log.Infoln("Hardware inventory created") -// -// log.Infoln("########Starting Tests########") -// status := m.Run() -// log.Infoln("########Finished Tests########") -// log.Infoln("########Removing setup########") -// //err = framework.TearDown() -// if err != nil { -// os.Exit(3) -// } -// log.Infoln("########Setup removed########") -// os.Exit(status) -//} -// -//var testCases = map[string]struct { -// hardware string -// template string -// workers int64 -// expected workflow.ActionState -// ephData string -//}{ -// "testWfWithWorker": {"hardware_1.json", "sample_1", 1, workflow.ActionState_ACTION_STATE_SUCCESS, `{"action_02": "data_02"}`}, -// "testWfTimeout": {"hardware_1.json", "sample_2", 1, workflow.ActionState_ACTION_STATE_TIMEOUT, `{"action_01": "data_01"}`}, -// //"testWfWithMultiWorkers": {"hardware_1.json", "sample_3", 2, workflow.ActionState_ACTION_STATE_SUCCESS, `{"action_01": "data_01"}`}, -//} -// -//var runTestMap = map[string]func(t *testing.T){ -// "testWfWithWorker": TestWfWithWorker, -// "testWfTimeout": TestWfTimeout, -// //"testWfWithMultiWorkers": TestWfWithMultiWorkers, -//} -// -//func TestE2E(t *testing.T) { -// for key, val := range runTestMap { -// t.Run(key, val) -// } -//} diff --git a/test/framework/hardware.go b/test/framework/hardware.go index 74dee9f1f..b30ef8010 100644 --- a/test/framework/hardware.go +++ b/test/framework/hardware.go @@ -28,8 +28,7 @@ func readHwData(file string) ([]byte, error) { // PushHardwareData : push hardware data. func PushHardwareData(hwDataFiles []string) error { for _, hwFile := range hwDataFiles { - filepath := "data/hardware/" + hwFile - data, err := readHwData(filepath) + data, err := readHwData(filepath.Join("data/hardware", hwFile)) if err != nil { return err } diff --git a/test/framework/setup.go b/test/framework/setup.go index ab3c7d462..f9a48ecb5 100644 --- a/test/framework/setup.go +++ b/test/framework/setup.go @@ -41,7 +41,7 @@ func pushImages() error { return err } -func startDb(filepath string) error { +func startDB(filepath string) error { cmd := exec.Command("/bin/sh", "-c", "docker-compose -f "+filepath+" up --build -d db") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr @@ -107,44 +107,37 @@ func StartStack() error { initializeLogger() // Start Db and logging components - err := startDb(filepath) - if err != nil { + if err := startDB(filepath); err != nil { return err } // Building certs - err = buildCerts(filepath) - if err != nil { + if err := buildCerts(filepath); err != nil { return err } // Building registry - err = buildLocalDockerRegistry(filepath) - if err != nil { + if err := buildLocalDockerRegistry(filepath); err != nil { return err } // Build default images - err = buildActionImages() - if err != nil { + if err := buildActionImages(); err != nil { return err } // Push Images into registry - err = pushImages() - if err != nil { + if err := pushImages(); err != nil { return err } // Remove older worker image - err = removeWorkerImage() - if err != nil { + if err := removeWorkerImage(); err != nil { return err } // Create new Worker image locally - err = createWorkerImage() - if err != nil { + if err := createWorkerImage(); err != nil { logger.Errorln("failed to create worker Image") return errors.Wrap(err, "worker image creation failed") } @@ -155,9 +148,9 @@ func StartStack() error { cmd := exec.Command("/bin/sh", "-c", "docker-compose -f "+filepath+" up --build -d") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr - err = cmd.Run() - if err != nil { - logger.Errorln("failed to create worker Image") + + if err := cmd.Run(); err != nil { + logger.Errorf("failed to create worker image: %v", err) return errors.Wrap(err, "worker image creation failed") } return nil diff --git a/test/framework/utils.go b/test/framework/utils.go index 69bd9114a..ac1e9ed96 100644 --- a/test/framework/utils.go +++ b/test/framework/utils.go @@ -13,7 +13,7 @@ var ( var Log = logger // SetupWorkflow ... Set up workflow. -func SetupWorkflow(tar string, tmpl string) (string, error) { +func SetupWorkflow(tmpl string) (string, error) { hardwareID := "c9d6faa4-08a2-4285-ae6c-f3401211bd56" // Add template in template table templateID, err := CreateTemplate(tmpl) diff --git a/test/framework/worker.go b/test/framework/worker.go index a9113c074..9a1deda80 100644 --- a/test/framework/worker.go +++ b/test/framework/worker.go @@ -24,7 +24,7 @@ func initializeDockerClient() (*dc.Client, error) { return c, nil } -func createWorkerContainer(ctx context.Context, cli *dc.Client, workerID string, wfID string) (string, error) { +func createWorkerContainer(ctx context.Context, cli *dc.Client, workerID string) (string, error) { volume := map[string]struct{}{"/var/run/docker.sock": {}} config := &container.Config{ Image: "worker", @@ -53,18 +53,16 @@ func runContainer(ctx context.Context, cli *dc.Client, id string) error { return nil } -func waitContainer(ctx context.Context, cli *dc.Client, id string, wg *sync.WaitGroup, failedWorkers chan<- string, statusChannel chan<- int64, stopLogs chan<- bool) { +func waitContainer(ctx context.Context, cli *dc.Client, id string, wg *sync.WaitGroup, failedWorkers chan<- string, statusChannel chan<- int64) { // send API call to wait for the container completion wait, errC := cli.ContainerWait(ctx, id, container.WaitConditionNotRunning) select { case status := <-wait: statusChannel <- status.StatusCode fmt.Println("Worker with id ", id, "finished successfully with status code ", status.StatusCode) - // stopLogs <- true case err := <-errC: log.Println("Worker with id ", id, "failed : ", err) failedWorkers <- id - // stopLogs <- true } wg.Done() } @@ -91,7 +89,7 @@ func checkCurrentStatus(ctx context.Context, wfID string, workflowStatus chan wo } } -func captureLogs(ctx context.Context, cli *dc.Client, id string) { +func captureLogs(cli *dc.Client, id string) { reader, err := cli.ContainerLogs(context.Background(), id, types.ContainerLogsOptions{ ShowStdout: true, ShowStderr: true, @@ -124,7 +122,7 @@ func StartWorkers(workers int64, workerStatus chan<- int64, wfID string) (workfl var i int64 for i = 0; i < workers; i++ { ctx := context.Background() - cID, err := createWorkerContainer(ctx, cli, workerID[i], wfID) + cID, err := createWorkerContainer(ctx, cli, workerID[i]) log = logger.WithFields(logrus.Fields{"workflow_id": wfID, "worker_id": workerID[i]}) if err != nil { log.Errorln("Failed to create worker container : ", err) @@ -141,11 +139,9 @@ func StartWorkers(workers int64, workerStatus chan<- int64, wfID string) (workfl } else { fmt.Println("Worker started with ID : ", cID) wg.Add(1) - // capturing logs of action container in a go-routine - stopLogs := make(chan bool) - go captureLogs(ctx, cli, cID) - go waitContainer(ctx, cli, cID, &wg, failedWorkers, workerStatus, stopLogs) + go captureLogs(cli, cID) + go waitContainer(ctx, cli, cID, &wg, failedWorkers, workerStatus) go checkCurrentStatus(ctx, wfID, workflowStatus) } } @@ -176,8 +172,6 @@ func StartWorkers(workers int64, workerStatus chan<- int64, wfID string) (workfl if len(failedContainer) > 0 { continue - } else { - break } } } diff --git a/test/test_wf_timeout.go b/test/test_wf_timeout.go deleted file mode 100644 index 0b5283f22..000000000 --- a/test/test_wf_timeout.go +++ /dev/null @@ -1,49 +0,0 @@ -package e2e - -//import ( -// "context" -// "testing" -// -// "github.com/tinkerbell/tink/client" -// "github.com/tinkerbell/tink/protos/workflow" -// "github.com/tinkerbell/tink/test/framework" -// "github.com/stretchr/testify/assert" -//) -// -//// TestWfTimeout : Timeout Test -//func TestWfTimeout(t *testing.T) { -// // Start test only if the test case exist in the table -// if test, ok := testCases["testWfTimeout"]; ok { -// wfID, err := framework.SetupWorkflow(test.hardware, test.template) -// -// if err != nil { -// t.Error(err) -// } -// assert.NoError(t, err, "Create Workflow") -// -// // Start the Worker -// workerStatus := make(chan int64, test.workers) -// wfStatus, err := framework.StartWorkers(test.workers, workerStatus, wfID) -// if err != nil { -// log.Errorf("Test Failed\n") -// t.Error(err) -// } -// assert.Equal(t, test.expected, wfStatus) -// assert.NoError(t, err, "Workers Failed") -// -// for i := int64(0); i < test.workers; i++ { -// if len(workerStatus) > 0 { -// // Check for worker exit status -// status := <-workerStatus -// expected := 0 -// assert.Equal(t, int64(expected), status) -// -// //checking for ephemeral data validation -// resp, err := client.WorkflowClient.GetWorkflowData(context.Background(), &workflow.GetWorkflowDataRequest{WorkflowID: wfID, Version: 0}) -// if err != nil { -// assert.Equal(t, test.ephData, string(resp.GetData())) -// } -// } -// } -// } -//} diff --git a/test/test_wf_with_multi_workers.go b/test/test_wf_with_multi_workers.go deleted file mode 100644 index ba43d00db..000000000 --- a/test/test_wf_with_multi_workers.go +++ /dev/null @@ -1,52 +0,0 @@ -package e2e - -//import ( -// "context" -// "testing" -// -// "github.com/tinkerbell/tink/client" -// "github.com/tinkerbell/tink/protos/workflow" -// "github.com/tinkerbell/tink/test/framework" -// "github.com/stretchr/testify/assert" -//) -// -//// TestWfWithMultiWorkers : Two Worker Test -//func TestWfWithMultiWorkers(t *testing.T) { -// // Start test only if the test case exist in the table -// if test, ok := testCases["testWfWithMultiWorkers"]; ok { -// wfID, err := framework.SetupWorkflow(test.hardware, test.template) -// -// if err != nil { -// t.Error(err) -// } -// assert.NoError(t, err, "Create Workflow") -// -// // Start the Worker -// workerStatus := make(chan int64, test.workers) -// wfStatus, err := framework.StartWorkers(test.workers, workerStatus, wfID) -// if err != nil { -// log.Errorf("Test Failed\n") -// t.Error(err) -// } -// assert.Equal(t, test.expected, wfStatus) -// assert.NoError(t, err, "Workers Failed") -// -// for i := int64(0); i < test.workers; i++ { -// if len(workerStatus) > 0 { -// // Check for worker exit status -// status := <-workerStatus -// expected := 0 -// if test.expected != workflow.ActionState_ACTION_STATE_SUCCESS { -// expected = 1 -// } -// assert.Equal(t, int64(expected), status) -// -// //checking for ephemeral data validation -// resp, err := client.WorkflowClient.GetWorkflowData(context.Background(), &workflow.GetWorkflowDataRequest{WorkflowID: wfID, Version: 0}) -// if err != nil { -// assert.Equal(t, test.ephData, string(resp.GetData())) -// } -// } -// } -// } -//} diff --git a/test/test_wf_with_worker.go b/test/test_wf_with_worker.go deleted file mode 100644 index 8ebe8f6e9..000000000 --- a/test/test_wf_with_worker.go +++ /dev/null @@ -1,54 +0,0 @@ -package e2e - -//import ( -// "context" -// "testing" -// -// "github.com/tinkerbell/tink/client" -// "github.com/tinkerbell/tink/protos/workflow" -// "github.com/tinkerbell/tink/test/framework" -// "github.com/stretchr/testify/assert" -//) -// -//// TestWfWithWorker : One Worker Test -//func TestWfWithWorker(t *testing.T) { -// -// // Start test only if the test case exist in the table -// if test, ok := testCases["testWfWithWorker"]; ok { -// wfID, err := framework.SetupWorkflow(test.hardware, test.template) -// -// if err != nil { -// t.Error(err) -// } -// if !assert.NoError(t, err, "Create Workflow") { -// t.Fatal(err) -// } -// -// // Start the Worker -// workerStatus := make(chan int64, test.workers) -// wfStatus, err := framework.StartWorkers(test.workers, workerStatus, wfID) -// if err != nil { -// log.Errorf("Test Failed\n") -// t.Error(err) -// } -// assert.Equal(t, test.expected, wfStatus) -// assert.NoError(t, err, "Workers Failed") -// -// for i := int64(0); i < test.workers; i++ { -// if len(workerStatus) > 0 { -// //Check for worker exit status -// status := <-workerStatus -// expected := 0 -// if test.expected != workflow.ActionState_ACTION_STATE_SUCCESS { -// expected = 1 -// } -// assert.Equal(t, int64(expected), status) -// //checking for ephemeral data validation -// resp, err := client.WorkflowClient.GetWorkflowData(context.Background(), &workflow.GetWorkflowDataRequest{WorkflowID: wfID, Version: 0}) -// if err != nil { -// assert.Equal(t, test.ephData, string(resp.GetData())) -// } -// } -// } -// } -//} diff --git a/workflow/template_validator.go b/workflow/template_validator.go index 01671476d..342a7261b 100644 --- a/workflow/template_validator.go +++ b/workflow/template_validator.go @@ -70,7 +70,7 @@ func RenderTemplate(templateID, templateData string, devices []byte) (string, er } t := template.New("workflow-template").Option("missingkey=error") - _, err = t.Parse(string(templateData)) + _, err = t.Parse(templateData) if err != nil { err = errors.Wrapf(err, errTemplateParsing, templateID) return "", err diff --git a/workflow/template_validator_test.go b/workflow/template_validator_test.go index c371f86bb..ee93221b8 100644 --- a/workflow/template_validator_test.go +++ b/workflow/template_validator_test.go @@ -42,32 +42,32 @@ tasks: func TestMustParse(t *testing.T) { table := []struct { - Name string - Input string - Recover func(t *testing.T) + Name string + Input string + WantPanic bool }{ { - Name: "parse-valid-template", - Input: validTemplate, - Recover: func(t *testing.T) { - if r := recover(); r != nil { - t.Errorf("panic not expected: %s", r) - } - }, + Name: "parse-valid-template", + Input: validTemplate, + WantPanic: false, }, { - Name: "parse-invalid-template", - Input: invalidTemplate, - Recover: func(t *testing.T) { - if r := recover(); r == nil { - t.Errorf("panic expected but we didn't got one: %s", r) - } - }, + Name: "parse-invalid-template", + Input: invalidTemplate, + WantPanic: true, }, } for _, s := range table { t.Run(s.Name, func(t *testing.T) { - defer s.Recover(t) + defer func() { + r := recover() + if r == nil && s.WantPanic { + t.Errorf("panic expected but we didn't got one: %s", r) + } else if r != nil && !s.WantPanic { + t.Errorf("unexpected panic: %s", r) + } + }() + _ = MustParse([]byte(s.Input)) }) } @@ -75,32 +75,32 @@ func TestMustParse(t *testing.T) { func TestMustParseFromFile(t *testing.T) { table := []struct { - Name string - Input string - Recover func(t *testing.T) + Name string + Input string + WantPanic bool }{ { - Name: "parse-valid-template", - Input: validTemplate, - Recover: func(t *testing.T) { - if r := recover(); r != nil { - t.Errorf("panic not expected: %s", r) - } - }, + Name: "parse-valid-template", + Input: validTemplate, + WantPanic: false, }, { - Name: "parse-invalid-template", - Input: invalidTemplate, - Recover: func(t *testing.T) { - if r := recover(); r == nil { - t.Errorf("panic expected but we didn't got one: %s", r) - } - }, + Name: "parse-invalid-template", + Input: invalidTemplate, + WantPanic: true, }, } for _, s := range table { t.Run(s.Name, func(t *testing.T) { - defer s.Recover(t) + defer func() { + r := recover() + if r == nil && s.WantPanic { + t.Errorf("panic expected but we didn't got one: %s", r) + } else if r != nil && !s.WantPanic { + t.Errorf("unexpected panic: %s", r) + } + }() + file, err := ioutil.TempFile(os.TempDir(), "tinktest") if err != nil { t.Error(err) @@ -136,7 +136,7 @@ func TestParse(t *testing.T) { for _, test := range testcases { t.Run(test.name, func(t *testing.T) { - res, err := Parse([]byte(test.content)) + res, err := Parse(test.content) if err != nil { assert.Error(t, err) assert.Empty(t, res) @@ -263,6 +263,7 @@ tasks: templateData: validTemplate, hwAddress: []byte("{\"invalid_device\":\"08:00:27:00:00:01\"}"), expectedError: func(t *testing.T, err error) { + t.Helper() if err == nil { t.Error("expected error, got nil") } From 09a2cc9f6516becb088df2042470877241c1ffbe Mon Sep 17 00:00:00 2001 From: Thomas Stromberg Date: Fri, 3 Sep 2021 12:18:16 -0700 Subject: [PATCH 4/9] Reformat Signed-off-by: Thomas Stromberg --- .github/workflows/ci.yaml | 172 +++++++++++++----------------- cmd/tink-cli/main.go | 3 +- cmd/tink-server/main.go | 2 +- protos/hardware/hardware.pb.go | 48 +++++---- protos/hardware/hardware.pb.gw.go | 44 ++------ protos/hardware/mock.go | 60 ++++------- protos/packet/packet.pb.go | 39 +++---- protos/template/mock.go | 60 ++++------- protos/template/template.pb.go | 34 +++--- protos/template/template.pb.gw.go | 44 +++----- protos/workflow/mock.go | 60 ++++------- protos/workflow/workflow.pb.go | 67 +++++++----- protos/workflow/workflow.pb.gw.go | 38 ++----- 13 files changed, 281 insertions(+), 390 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 293990852..e8993f6f7 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -6,97 +6,73 @@ env: CGO_ENABLED: 0 jobs: - golangci-lint: + lint: runs-on: ubuntu-latest steps: - - name: Checkout code - uses: actions/checkout@v2 - - name: Install Go - uses: actions/setup-go@v2 - with: - go-version: '1.14.6' - - name: golangci-lint - uses: golangci/golangci-lint-action@v2 - goimports: - runs-on: ubuntu-latest - steps: - - name: Checkout code - uses: actions/checkout@v2 - - name: Install Go - uses: actions/setup-go@v2 - with: - go-version: '1.14.6' - - name: goimports - run: go get golang.org/x/tools/cmd/goimports && goimports -d . | (! grep .) - vet: - runs-on: ubuntu-latest - steps: - - name: Checkout code - uses: actions/checkout@v2 - - name: Install Go - uses: actions/setup-go@v2 - with: - go-version: '1.14.6' - - name: go vet - run: go vet ./... + - name: Checkout code + uses: actions/checkout@v2 + - name: Install Go + uses: actions/setup-go@v2 + with: + go-version: "1.17.0" + - name: make lint + run: make lint test: runs-on: ubuntu-latest steps: - - name: Checkout code - uses: actions/checkout@v2 - - name: Install Go - uses: actions/setup-go@v2 - with: - go-version: '1.14.6' - - name: go test - run: go test -coverprofile=coverage.txt ./... - - name: upload codecov - run: bash <(curl -s https://codecov.io/bash) + - name: Checkout code + uses: actions/checkout@v2 + - name: Install Go + uses: actions/setup-go@v2 + with: + go-version: "1.14.6" + - name: go test + run: go test -coverprofile=coverage.txt ./... + - name: upload codecov + run: bash <(curl -s https://codecov.io/bash) ci-checks: runs-on: ubuntu-latest steps: - - name: Checkout code - uses: actions/checkout@v2 - - uses: cachix/install-nix-action@v12 - with: - nix_path: nixpkgs=channel:nixos-unstable - - run: ./ci-checks.sh + - name: Checkout code + uses: actions/checkout@v2 + - uses: cachix/install-nix-action@v12 + with: + nix_path: nixpkgs=channel:nixos-unstable + - run: ./ci-checks.sh validation: runs-on: ubuntu-latest needs: - ci-checks - - goimports - - golangci-lint + - lint - test - - vet steps: - - name: fake - run: echo ":+1:" + - name: fake + run: echo ":+1:" crosscompile: runs-on: ubuntu-latest needs: - validation steps: - - name: Checkout code - uses: actions/checkout@v2 - - name: Install Go - uses: actions/setup-go@v2 - with: - go-version: '1.14.6' - - run: make crosscompile -j$(nproc) - - name: Upload tink-cli binaries - uses: actions/upload-artifact@v2 - with: + - name: Checkout code + uses: actions/checkout@v2 + - name: Install Go + uses: actions/setup-go@v2 + with: + go-version: "1.14.6" + - run: make crosscompile -j$(nproc) + - name: Upload tink-cli binaries + uses: actions/upload-artifact@v2 + with: name: tink-cli path: cmd/tink-cli/tink-cli-* - - name: Upload tink-server binaries - uses: actions/upload-artifact@v2 - with: + - name: Upload tink-server binaries + uses: actions/upload-artifact@v2 + with: name: tink-server path: cmd/tink-server/tink-server-* - - name: Upload tink-worker binaries - uses: actions/upload-artifact@v2 - with: + - name: Upload tink-worker binaries + uses: actions/upload-artifact@v2 + with: name: tink-worker path: cmd/tink-worker/tink-worker-* docker-images: @@ -113,35 +89,35 @@ jobs: - repository: quay.io/tinkerbell/tink-worker binary: tink-worker steps: - - name: Docker Image Tag for Sha - id: docker-image-tag - run: | - echo ::set-output name=tags::${{ matrix.repository }}:latest,${{ matrix.repository }}:sha-${GITHUB_SHA::8} - - name: Checkout code - uses: actions/checkout@v2 - - name: Login to quay.io - uses: docker/login-action@v1 - if: ${{ startsWith(github.ref, 'refs/heads/master') }} - with: - registry: quay.io - username: ${{ secrets.QUAY_USERNAME }} - password: ${{ secrets.QUAY_PASSWORD }} - - name: Set up QEMU - uses: docker/setup-qemu-action@v1 - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v1 - - name: Download ${{ matrix.binary }} artifacts - uses: actions/download-artifact@v2 - with: + - name: Docker Image Tag for Sha + id: docker-image-tag + run: | + echo ::set-output name=tags::${{ matrix.repository }}:latest,${{ matrix.repository }}:sha-${GITHUB_SHA::8} + - name: Checkout code + uses: actions/checkout@v2 + - name: Login to quay.io + uses: docker/login-action@v1 + if: ${{ startsWith(github.ref, 'refs/heads/master') }} + with: + registry: quay.io + username: ${{ secrets.QUAY_USERNAME }} + password: ${{ secrets.QUAY_PASSWORD }} + - name: Set up QEMU + uses: docker/setup-qemu-action@v1 + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v1 + - name: Download ${{ matrix.binary }} artifacts + uses: actions/download-artifact@v2 + with: name: ${{ matrix.binary}} path: cmd/${{ matrix.binary }} - - name: Fix Permissions - run: chmod +x cmd/${{ matrix.binary }}/${{ matrix.binary }}* - - name: ${{ matrix.repository }} - uses: docker/build-push-action@v2 - with: - context: cmd/${{ matrix.binary }}/ - cache-from: type=registry,ref=${{ matrix.repository }}:latest - push: ${{ startsWith(github.ref, 'refs/heads/master') }} - tags: ${{ steps.docker-image-tag.outputs.tags }} - platforms: linux/386,linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64 + - name: Fix Permissions + run: chmod +x cmd/${{ matrix.binary }}/${{ matrix.binary }}* + - name: ${{ matrix.repository }} + uses: docker/build-push-action@v2 + with: + context: cmd/${{ matrix.binary }}/ + cache-from: type=registry,ref=${{ matrix.repository }}:latest + push: ${{ startsWith(github.ref, 'refs/heads/master') }} + tags: ${{ steps.docker-image-tag.outputs.tags }} + platforms: linux/386,linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64 diff --git a/cmd/tink-cli/main.go b/cmd/tink-cli/main.go index 36a5c469f..20804664d 100644 --- a/cmd/tink-cli/main.go +++ b/cmd/tink-cli/main.go @@ -14,10 +14,11 @@ var version = "devel" func main() { ctx, otelShutdown := otelinit.InitOpenTelemetry(context.Background(), "github.com/tinkerbell/tink") - defer otelShutdown(ctx) if err := cmd.Execute(version); err != nil { fmt.Fprintln(os.Stderr, err.Error()) os.Exit(1) } + + otelShutdown(ctx) } diff --git a/cmd/tink-server/main.go b/cmd/tink-server/main.go index 65da61f8b..e4af976d1 100644 --- a/cmd/tink-server/main.go +++ b/cmd/tink-server/main.go @@ -102,7 +102,6 @@ func main() { ctx := context.Background() ctx, otelShutdown := otelinit.InitOpenTelemetry(ctx, "github.com/tinkerbell/tink") - defer otelShutdown(ctx) config := &DaemonConfig{} @@ -112,6 +111,7 @@ func main() { } logger.Close() + otelShutdown(ctx) } func NewRootCommand(config *DaemonConfig, logger log.Logger) *cobra.Command { diff --git a/protos/hardware/hardware.pb.go b/protos/hardware/hardware.pb.go index 3937bd463..4e1992b50 100644 --- a/protos/hardware/hardware.pb.go +++ b/protos/hardware/hardware.pb.go @@ -1047,21 +1047,24 @@ func file_hardware_hardware_proto_rawDescGZIP() []byte { return file_hardware_hardware_proto_rawDescData } -var file_hardware_hardware_proto_msgTypes = make([]protoimpl.MessageInfo, 12) -var file_hardware_hardware_proto_goTypes = []interface{}{ - (*PushRequest)(nil), // 0: github.com.tinkerbell.tink.protos.hardware.PushRequest - (*Empty)(nil), // 1: github.com.tinkerbell.tink.protos.hardware.Empty - (*GetRequest)(nil), // 2: github.com.tinkerbell.tink.protos.hardware.GetRequest - (*Hardware)(nil), // 3: github.com.tinkerbell.tink.protos.hardware.Hardware - (*DeleteRequest)(nil), // 4: github.com.tinkerbell.tink.protos.hardware.DeleteRequest - (*Hardware_DHCP)(nil), // 5: github.com.tinkerbell.tink.protos.hardware.Hardware.DHCP - (*Hardware_Netboot)(nil), // 6: github.com.tinkerbell.tink.protos.hardware.Hardware.Netboot - (*Hardware_Network)(nil), // 7: github.com.tinkerbell.tink.protos.hardware.Hardware.Network - (*Hardware_DHCP_IP)(nil), // 8: github.com.tinkerbell.tink.protos.hardware.Hardware.DHCP.IP - (*Hardware_Netboot_IPXE)(nil), // 9: github.com.tinkerbell.tink.protos.hardware.Hardware.Netboot.IPXE - (*Hardware_Netboot_Osie)(nil), // 10: github.com.tinkerbell.tink.protos.hardware.Hardware.Netboot.Osie - (*Hardware_Network_Interface)(nil), // 11: github.com.tinkerbell.tink.protos.hardware.Hardware.Network.Interface -} +var ( + file_hardware_hardware_proto_msgTypes = make([]protoimpl.MessageInfo, 12) + file_hardware_hardware_proto_goTypes = []interface{}{ + (*PushRequest)(nil), // 0: github.com.tinkerbell.tink.protos.hardware.PushRequest + (*Empty)(nil), // 1: github.com.tinkerbell.tink.protos.hardware.Empty + (*GetRequest)(nil), // 2: github.com.tinkerbell.tink.protos.hardware.GetRequest + (*Hardware)(nil), // 3: github.com.tinkerbell.tink.protos.hardware.Hardware + (*DeleteRequest)(nil), // 4: github.com.tinkerbell.tink.protos.hardware.DeleteRequest + (*Hardware_DHCP)(nil), // 5: github.com.tinkerbell.tink.protos.hardware.Hardware.DHCP + (*Hardware_Netboot)(nil), // 6: github.com.tinkerbell.tink.protos.hardware.Hardware.Netboot + (*Hardware_Network)(nil), // 7: github.com.tinkerbell.tink.protos.hardware.Hardware.Network + (*Hardware_DHCP_IP)(nil), // 8: github.com.tinkerbell.tink.protos.hardware.Hardware.DHCP.IP + (*Hardware_Netboot_IPXE)(nil), // 9: github.com.tinkerbell.tink.protos.hardware.Hardware.Netboot.IPXE + (*Hardware_Netboot_Osie)(nil), // 10: github.com.tinkerbell.tink.protos.hardware.Hardware.Netboot.Osie + (*Hardware_Network_Interface)(nil), // 11: github.com.tinkerbell.tink.protos.hardware.Hardware.Network.Interface + } +) + var file_hardware_hardware_proto_depIdxs = []int32{ 3, // 0: github.com.tinkerbell.tink.protos.hardware.PushRequest.data:type_name -> github.com.tinkerbell.tink.protos.hardware.Hardware 7, // 1: github.com.tinkerbell.tink.protos.hardware.Hardware.network:type_name -> github.com.tinkerbell.tink.protos.hardware.Hardware.Network @@ -1264,8 +1267,10 @@ func file_hardware_hardware_proto_init() { } // Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConnInterface +var ( + _ context.Context + _ grpc.ClientConnInterface +) // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. @@ -1431,27 +1436,32 @@ type HardwareServiceServer interface { } // UnimplementedHardwareServiceServer can be embedded to have forward compatible implementations. -type UnimplementedHardwareServiceServer struct { -} +type UnimplementedHardwareServiceServer struct{} func (*UnimplementedHardwareServiceServer) Push(context.Context, *PushRequest) (*Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method Push not implemented") } + func (*UnimplementedHardwareServiceServer) ByMAC(context.Context, *GetRequest) (*Hardware, error) { return nil, status.Errorf(codes.Unimplemented, "method ByMAC not implemented") } + func (*UnimplementedHardwareServiceServer) ByIP(context.Context, *GetRequest) (*Hardware, error) { return nil, status.Errorf(codes.Unimplemented, "method ByIP not implemented") } + func (*UnimplementedHardwareServiceServer) ByID(context.Context, *GetRequest) (*Hardware, error) { return nil, status.Errorf(codes.Unimplemented, "method ByID not implemented") } + func (*UnimplementedHardwareServiceServer) All(*Empty, HardwareService_AllServer) error { return status.Errorf(codes.Unimplemented, "method All not implemented") } + func (*UnimplementedHardwareServiceServer) DeprecatedWatch(*GetRequest, HardwareService_DeprecatedWatchServer) error { return status.Errorf(codes.Unimplemented, "method DeprecatedWatch not implemented") } + func (*UnimplementedHardwareServiceServer) Delete(context.Context, *DeleteRequest) (*Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method Delete not implemented") } diff --git a/protos/hardware/hardware.pb.gw.go b/protos/hardware/hardware.pb.gw.go index d33c623d9..3d6ca1f72 100644 --- a/protos/hardware/hardware.pb.gw.go +++ b/protos/hardware/hardware.pb.gw.go @@ -25,13 +25,15 @@ import ( ) // Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage -var _ = metadata.Join +var ( + _ codes.Code + _ io.Reader + _ status.Status + _ = runtime.String + _ = utilities.NewDoubleArray + _ = descriptor.ForMessage + _ = metadata.Join +) func request_HardwareService_Push_0(ctx context.Context, marshaler runtime.Marshaler, client HardwareServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq PushRequest @@ -47,7 +49,6 @@ func request_HardwareService_Push_0(ctx context.Context, marshaler runtime.Marsh msg, err := client.Push(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_HardwareService_Push_0(ctx context.Context, marshaler runtime.Marshaler, server HardwareServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { @@ -64,7 +65,6 @@ func local_request_HardwareService_Push_0(ctx context.Context, marshaler runtime msg, err := server.Push(ctx, &protoReq) return msg, metadata, err - } func request_HardwareService_ByMAC_0(ctx context.Context, marshaler runtime.Marshaler, client HardwareServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { @@ -81,7 +81,6 @@ func request_HardwareService_ByMAC_0(ctx context.Context, marshaler runtime.Mars msg, err := client.ByMAC(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_HardwareService_ByMAC_0(ctx context.Context, marshaler runtime.Marshaler, server HardwareServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { @@ -98,7 +97,6 @@ func local_request_HardwareService_ByMAC_0(ctx context.Context, marshaler runtim msg, err := server.ByMAC(ctx, &protoReq) return msg, metadata, err - } func request_HardwareService_ByIP_0(ctx context.Context, marshaler runtime.Marshaler, client HardwareServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { @@ -115,7 +113,6 @@ func request_HardwareService_ByIP_0(ctx context.Context, marshaler runtime.Marsh msg, err := client.ByIP(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_HardwareService_ByIP_0(ctx context.Context, marshaler runtime.Marshaler, server HardwareServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { @@ -132,12 +129,9 @@ func local_request_HardwareService_ByIP_0(ctx context.Context, marshaler runtime msg, err := server.ByIP(ctx, &protoReq) return msg, metadata, err - } -var ( - filter_HardwareService_ByID_0 = &utilities.DoubleArray{Encoding: map[string]int{"id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) +var filter_HardwareService_ByID_0 = &utilities.DoubleArray{Encoding: map[string]int{"id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} func request_HardwareService_ByID_0(ctx context.Context, marshaler runtime.Marshaler, client HardwareServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq GetRequest @@ -170,7 +164,6 @@ func request_HardwareService_ByID_0(ctx context.Context, marshaler runtime.Marsh msg, err := client.ByID(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_HardwareService_ByID_0(ctx context.Context, marshaler runtime.Marshaler, server HardwareServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { @@ -204,7 +197,6 @@ func local_request_HardwareService_ByID_0(ctx context.Context, marshaler runtime msg, err := server.ByID(ctx, &protoReq) return msg, metadata, err - } func request_HardwareService_All_0(ctx context.Context, marshaler runtime.Marshaler, client HardwareServiceClient, req *http.Request, pathParams map[string]string) (HardwareService_AllClient, runtime.ServerMetadata, error) { @@ -221,7 +213,6 @@ func request_HardwareService_All_0(ctx context.Context, marshaler runtime.Marsha } metadata.HeaderMD = header return stream, metadata, nil - } func request_HardwareService_Delete_0(ctx context.Context, marshaler runtime.Marshaler, client HardwareServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { @@ -248,7 +239,6 @@ func request_HardwareService_Delete_0(ctx context.Context, marshaler runtime.Mar msg, err := client.Delete(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_HardwareService_Delete_0(ctx context.Context, marshaler runtime.Marshaler, server HardwareServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { @@ -275,7 +265,6 @@ func local_request_HardwareService_Delete_0(ctx context.Context, marshaler runti msg, err := server.Delete(ctx, &protoReq) return msg, metadata, err - } // RegisterHardwareServiceHandlerServer registers the http handlers for service HardwareService to "mux". @@ -283,7 +272,6 @@ func local_request_HardwareService_Delete_0(ctx context.Context, marshaler runti // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterHardwareServiceHandlerFromEndpoint instead. func RegisterHardwareServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server HardwareServiceServer) error { - mux.Handle("POST", pattern_HardwareService_Push_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() @@ -304,7 +292,6 @@ func RegisterHardwareServiceHandlerServer(ctx context.Context, mux *runtime.Serv } forward_HardwareService_Push_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) mux.Handle("POST", pattern_HardwareService_ByMAC_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -327,7 +314,6 @@ func RegisterHardwareServiceHandlerServer(ctx context.Context, mux *runtime.Serv } forward_HardwareService_ByMAC_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) mux.Handle("POST", pattern_HardwareService_ByIP_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -350,7 +336,6 @@ func RegisterHardwareServiceHandlerServer(ctx context.Context, mux *runtime.Serv } forward_HardwareService_ByIP_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) mux.Handle("GET", pattern_HardwareService_ByID_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -373,7 +358,6 @@ func RegisterHardwareServiceHandlerServer(ctx context.Context, mux *runtime.Serv } forward_HardwareService_ByID_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) mux.Handle("GET", pattern_HardwareService_All_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -403,7 +387,6 @@ func RegisterHardwareServiceHandlerServer(ctx context.Context, mux *runtime.Serv } forward_HardwareService_Delete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) return nil @@ -446,7 +429,6 @@ func RegisterHardwareServiceHandler(ctx context.Context, mux *runtime.ServeMux, // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in // "HardwareServiceClient" to call the correct interceptors. func RegisterHardwareServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client HardwareServiceClient) error { - mux.Handle("POST", pattern_HardwareService_Push_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() @@ -464,7 +446,6 @@ func RegisterHardwareServiceHandlerClient(ctx context.Context, mux *runtime.Serv } forward_HardwareService_Push_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) mux.Handle("POST", pattern_HardwareService_ByMAC_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -484,7 +465,6 @@ func RegisterHardwareServiceHandlerClient(ctx context.Context, mux *runtime.Serv } forward_HardwareService_ByMAC_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) mux.Handle("POST", pattern_HardwareService_ByIP_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -504,7 +484,6 @@ func RegisterHardwareServiceHandlerClient(ctx context.Context, mux *runtime.Serv } forward_HardwareService_ByIP_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) mux.Handle("GET", pattern_HardwareService_ByID_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -524,7 +503,6 @@ func RegisterHardwareServiceHandlerClient(ctx context.Context, mux *runtime.Serv } forward_HardwareService_ByID_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) mux.Handle("GET", pattern_HardwareService_All_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -544,7 +522,6 @@ func RegisterHardwareServiceHandlerClient(ctx context.Context, mux *runtime.Serv } forward_HardwareService_All_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) - }) mux.Handle("DELETE", pattern_HardwareService_Delete_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -564,7 +541,6 @@ func RegisterHardwareServiceHandlerClient(ctx context.Context, mux *runtime.Serv } forward_HardwareService_Delete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) return nil diff --git a/protos/hardware/mock.go b/protos/hardware/mock.go index 760e17842..4253f2f3a 100644 --- a/protos/hardware/mock.go +++ b/protos/hardware/mock.go @@ -480,17 +480,13 @@ type HardwareService_AllClientMock struct { // calls tracks calls to the methods. calls struct { // CloseSend holds details about calls to the CloseSend method. - CloseSend []struct { - } + CloseSend []struct{} // Context holds details about calls to the Context method. - Context []struct { - } + Context []struct{} // Header holds details about calls to the Header method. - Header []struct { - } + Header []struct{} // Recv holds details about calls to the Recv method. - Recv []struct { - } + Recv []struct{} // RecvMsg holds details about calls to the RecvMsg method. RecvMsg []struct { // M is the m argument value. @@ -502,8 +498,7 @@ type HardwareService_AllClientMock struct { M interface{} } // Trailer holds details about calls to the Trailer method. - Trailer []struct { - } + Trailer []struct{} } lockCloseSend sync.RWMutex lockContext sync.RWMutex @@ -519,8 +514,7 @@ func (mock *HardwareService_AllClientMock) CloseSend() error { if mock.CloseSendFunc == nil { panic("HardwareService_AllClientMock.CloseSendFunc: method is nil but HardwareService_AllClient.CloseSend was just called") } - callInfo := struct { - }{} + callInfo := struct{}{} mock.lockCloseSend.Lock() mock.calls.CloseSend = append(mock.calls.CloseSend, callInfo) mock.lockCloseSend.Unlock() @@ -530,10 +524,8 @@ func (mock *HardwareService_AllClientMock) CloseSend() error { // CloseSendCalls gets all the calls that were made to CloseSend. // Check the length with: // len(mockedHardwareService_AllClient.CloseSendCalls()) -func (mock *HardwareService_AllClientMock) CloseSendCalls() []struct { -} { - var calls []struct { - } +func (mock *HardwareService_AllClientMock) CloseSendCalls() []struct{} { + var calls []struct{} mock.lockCloseSend.RLock() calls = mock.calls.CloseSend mock.lockCloseSend.RUnlock() @@ -545,8 +537,7 @@ func (mock *HardwareService_AllClientMock) Context() context.Context { if mock.ContextFunc == nil { panic("HardwareService_AllClientMock.ContextFunc: method is nil but HardwareService_AllClient.Context was just called") } - callInfo := struct { - }{} + callInfo := struct{}{} mock.lockContext.Lock() mock.calls.Context = append(mock.calls.Context, callInfo) mock.lockContext.Unlock() @@ -556,10 +547,8 @@ func (mock *HardwareService_AllClientMock) Context() context.Context { // ContextCalls gets all the calls that were made to Context. // Check the length with: // len(mockedHardwareService_AllClient.ContextCalls()) -func (mock *HardwareService_AllClientMock) ContextCalls() []struct { -} { - var calls []struct { - } +func (mock *HardwareService_AllClientMock) ContextCalls() []struct{} { + var calls []struct{} mock.lockContext.RLock() calls = mock.calls.Context mock.lockContext.RUnlock() @@ -571,8 +560,7 @@ func (mock *HardwareService_AllClientMock) Header() (metadata.MD, error) { if mock.HeaderFunc == nil { panic("HardwareService_AllClientMock.HeaderFunc: method is nil but HardwareService_AllClient.Header was just called") } - callInfo := struct { - }{} + callInfo := struct{}{} mock.lockHeader.Lock() mock.calls.Header = append(mock.calls.Header, callInfo) mock.lockHeader.Unlock() @@ -582,10 +570,8 @@ func (mock *HardwareService_AllClientMock) Header() (metadata.MD, error) { // HeaderCalls gets all the calls that were made to Header. // Check the length with: // len(mockedHardwareService_AllClient.HeaderCalls()) -func (mock *HardwareService_AllClientMock) HeaderCalls() []struct { -} { - var calls []struct { - } +func (mock *HardwareService_AllClientMock) HeaderCalls() []struct{} { + var calls []struct{} mock.lockHeader.RLock() calls = mock.calls.Header mock.lockHeader.RUnlock() @@ -597,8 +583,7 @@ func (mock *HardwareService_AllClientMock) Recv() (*Hardware, error) { if mock.RecvFunc == nil { panic("HardwareService_AllClientMock.RecvFunc: method is nil but HardwareService_AllClient.Recv was just called") } - callInfo := struct { - }{} + callInfo := struct{}{} mock.lockRecv.Lock() mock.calls.Recv = append(mock.calls.Recv, callInfo) mock.lockRecv.Unlock() @@ -608,10 +593,8 @@ func (mock *HardwareService_AllClientMock) Recv() (*Hardware, error) { // RecvCalls gets all the calls that were made to Recv. // Check the length with: // len(mockedHardwareService_AllClient.RecvCalls()) -func (mock *HardwareService_AllClientMock) RecvCalls() []struct { -} { - var calls []struct { - } +func (mock *HardwareService_AllClientMock) RecvCalls() []struct{} { + var calls []struct{} mock.lockRecv.RLock() calls = mock.calls.Recv mock.lockRecv.RUnlock() @@ -685,8 +668,7 @@ func (mock *HardwareService_AllClientMock) Trailer() metadata.MD { if mock.TrailerFunc == nil { panic("HardwareService_AllClientMock.TrailerFunc: method is nil but HardwareService_AllClient.Trailer was just called") } - callInfo := struct { - }{} + callInfo := struct{}{} mock.lockTrailer.Lock() mock.calls.Trailer = append(mock.calls.Trailer, callInfo) mock.lockTrailer.Unlock() @@ -696,10 +678,8 @@ func (mock *HardwareService_AllClientMock) Trailer() metadata.MD { // TrailerCalls gets all the calls that were made to Trailer. // Check the length with: // len(mockedHardwareService_AllClient.TrailerCalls()) -func (mock *HardwareService_AllClientMock) TrailerCalls() []struct { -} { - var calls []struct { - } +func (mock *HardwareService_AllClientMock) TrailerCalls() []struct{} { + var calls []struct{} mock.lockTrailer.RLock() calls = mock.calls.Trailer mock.lockTrailer.RUnlock() diff --git a/protos/packet/packet.pb.go b/protos/packet/packet.pb.go index 380d4b94a..d92e802f8 100644 --- a/protos/packet/packet.pb.go +++ b/protos/packet/packet.pb.go @@ -1366,24 +1366,27 @@ func file_packet_packet_proto_rawDescGZIP() []byte { return file_packet_packet_proto_rawDescData } -var file_packet_packet_proto_msgTypes = make([]protoimpl.MessageInfo, 15) -var file_packet_packet_proto_goTypes = []interface{}{ - (*Metadata)(nil), // 0: github.com.tinkerbell.tink.protos.packet.Metadata - (*Metadata_Manufacturer)(nil), // 1: github.com.tinkerbell.tink.protos.packet.Metadata.Manufacturer - (*Metadata_Instance)(nil), // 2: github.com.tinkerbell.tink.protos.packet.Metadata.Instance - (*Metadata_Custom)(nil), // 3: github.com.tinkerbell.tink.protos.packet.Metadata.Custom - (*Metadata_Facility)(nil), // 4: github.com.tinkerbell.tink.protos.packet.Metadata.Facility - (*Metadata_Instance_OperatingSystem)(nil), // 5: github.com.tinkerbell.tink.protos.packet.Metadata.Instance.OperatingSystem - (*Metadata_Instance_IP)(nil), // 6: github.com.tinkerbell.tink.protos.packet.Metadata.Instance.IP - (*Metadata_Instance_Storage)(nil), // 7: github.com.tinkerbell.tink.protos.packet.Metadata.Instance.Storage - (*Metadata_Instance_Storage_Disk)(nil), // 8: github.com.tinkerbell.tink.protos.packet.Metadata.Instance.Storage.Disk - (*Metadata_Instance_Storage_File)(nil), // 9: github.com.tinkerbell.tink.protos.packet.Metadata.Instance.Storage.File - (*Metadata_Instance_Storage_Mount)(nil), // 10: github.com.tinkerbell.tink.protos.packet.Metadata.Instance.Storage.Mount - (*Metadata_Instance_Storage_Filesystem)(nil), // 11: github.com.tinkerbell.tink.protos.packet.Metadata.Instance.Storage.Filesystem - (*Metadata_Instance_Storage_RAID)(nil), // 12: github.com.tinkerbell.tink.protos.packet.Metadata.Instance.Storage.RAID - (*Metadata_Instance_Storage_Disk_Partition)(nil), // 13: github.com.tinkerbell.tink.protos.packet.Metadata.Instance.Storage.Disk.Partition - (*Metadata_Instance_Storage_Mount_FilesystemOptions)(nil), // 14: github.com.tinkerbell.tink.protos.packet.Metadata.Instance.Storage.Mount.FilesystemOptions -} +var ( + file_packet_packet_proto_msgTypes = make([]protoimpl.MessageInfo, 15) + file_packet_packet_proto_goTypes = []interface{}{ + (*Metadata)(nil), // 0: github.com.tinkerbell.tink.protos.packet.Metadata + (*Metadata_Manufacturer)(nil), // 1: github.com.tinkerbell.tink.protos.packet.Metadata.Manufacturer + (*Metadata_Instance)(nil), // 2: github.com.tinkerbell.tink.protos.packet.Metadata.Instance + (*Metadata_Custom)(nil), // 3: github.com.tinkerbell.tink.protos.packet.Metadata.Custom + (*Metadata_Facility)(nil), // 4: github.com.tinkerbell.tink.protos.packet.Metadata.Facility + (*Metadata_Instance_OperatingSystem)(nil), // 5: github.com.tinkerbell.tink.protos.packet.Metadata.Instance.OperatingSystem + (*Metadata_Instance_IP)(nil), // 6: github.com.tinkerbell.tink.protos.packet.Metadata.Instance.IP + (*Metadata_Instance_Storage)(nil), // 7: github.com.tinkerbell.tink.protos.packet.Metadata.Instance.Storage + (*Metadata_Instance_Storage_Disk)(nil), // 8: github.com.tinkerbell.tink.protos.packet.Metadata.Instance.Storage.Disk + (*Metadata_Instance_Storage_File)(nil), // 9: github.com.tinkerbell.tink.protos.packet.Metadata.Instance.Storage.File + (*Metadata_Instance_Storage_Mount)(nil), // 10: github.com.tinkerbell.tink.protos.packet.Metadata.Instance.Storage.Mount + (*Metadata_Instance_Storage_Filesystem)(nil), // 11: github.com.tinkerbell.tink.protos.packet.Metadata.Instance.Storage.Filesystem + (*Metadata_Instance_Storage_RAID)(nil), // 12: github.com.tinkerbell.tink.protos.packet.Metadata.Instance.Storage.RAID + (*Metadata_Instance_Storage_Disk_Partition)(nil), // 13: github.com.tinkerbell.tink.protos.packet.Metadata.Instance.Storage.Disk.Partition + (*Metadata_Instance_Storage_Mount_FilesystemOptions)(nil), // 14: github.com.tinkerbell.tink.protos.packet.Metadata.Instance.Storage.Mount.FilesystemOptions + } +) + var file_packet_packet_proto_depIdxs = []int32{ 1, // 0: github.com.tinkerbell.tink.protos.packet.Metadata.manufacturer:type_name -> github.com.tinkerbell.tink.protos.packet.Metadata.Manufacturer 2, // 1: github.com.tinkerbell.tink.protos.packet.Metadata.instance:type_name -> github.com.tinkerbell.tink.protos.packet.Metadata.Instance diff --git a/protos/template/mock.go b/protos/template/mock.go index a44d26e73..d0b4371a6 100644 --- a/protos/template/mock.go +++ b/protos/template/mock.go @@ -370,17 +370,13 @@ type TemplateService_ListTemplatesClientMock struct { // calls tracks calls to the methods. calls struct { // CloseSend holds details about calls to the CloseSend method. - CloseSend []struct { - } + CloseSend []struct{} // Context holds details about calls to the Context method. - Context []struct { - } + Context []struct{} // Header holds details about calls to the Header method. - Header []struct { - } + Header []struct{} // Recv holds details about calls to the Recv method. - Recv []struct { - } + Recv []struct{} // RecvMsg holds details about calls to the RecvMsg method. RecvMsg []struct { // M is the m argument value. @@ -392,8 +388,7 @@ type TemplateService_ListTemplatesClientMock struct { M interface{} } // Trailer holds details about calls to the Trailer method. - Trailer []struct { - } + Trailer []struct{} } lockCloseSend sync.RWMutex lockContext sync.RWMutex @@ -409,8 +404,7 @@ func (mock *TemplateService_ListTemplatesClientMock) CloseSend() error { if mock.CloseSendFunc == nil { panic("TemplateService_ListTemplatesClientMock.CloseSendFunc: method is nil but TemplateService_ListTemplatesClient.CloseSend was just called") } - callInfo := struct { - }{} + callInfo := struct{}{} mock.lockCloseSend.Lock() mock.calls.CloseSend = append(mock.calls.CloseSend, callInfo) mock.lockCloseSend.Unlock() @@ -420,10 +414,8 @@ func (mock *TemplateService_ListTemplatesClientMock) CloseSend() error { // CloseSendCalls gets all the calls that were made to CloseSend. // Check the length with: // len(mockedTemplateService_ListTemplatesClient.CloseSendCalls()) -func (mock *TemplateService_ListTemplatesClientMock) CloseSendCalls() []struct { -} { - var calls []struct { - } +func (mock *TemplateService_ListTemplatesClientMock) CloseSendCalls() []struct{} { + var calls []struct{} mock.lockCloseSend.RLock() calls = mock.calls.CloseSend mock.lockCloseSend.RUnlock() @@ -435,8 +427,7 @@ func (mock *TemplateService_ListTemplatesClientMock) Context() context.Context { if mock.ContextFunc == nil { panic("TemplateService_ListTemplatesClientMock.ContextFunc: method is nil but TemplateService_ListTemplatesClient.Context was just called") } - callInfo := struct { - }{} + callInfo := struct{}{} mock.lockContext.Lock() mock.calls.Context = append(mock.calls.Context, callInfo) mock.lockContext.Unlock() @@ -446,10 +437,8 @@ func (mock *TemplateService_ListTemplatesClientMock) Context() context.Context { // ContextCalls gets all the calls that were made to Context. // Check the length with: // len(mockedTemplateService_ListTemplatesClient.ContextCalls()) -func (mock *TemplateService_ListTemplatesClientMock) ContextCalls() []struct { -} { - var calls []struct { - } +func (mock *TemplateService_ListTemplatesClientMock) ContextCalls() []struct{} { + var calls []struct{} mock.lockContext.RLock() calls = mock.calls.Context mock.lockContext.RUnlock() @@ -461,8 +450,7 @@ func (mock *TemplateService_ListTemplatesClientMock) Header() (metadata.MD, erro if mock.HeaderFunc == nil { panic("TemplateService_ListTemplatesClientMock.HeaderFunc: method is nil but TemplateService_ListTemplatesClient.Header was just called") } - callInfo := struct { - }{} + callInfo := struct{}{} mock.lockHeader.Lock() mock.calls.Header = append(mock.calls.Header, callInfo) mock.lockHeader.Unlock() @@ -472,10 +460,8 @@ func (mock *TemplateService_ListTemplatesClientMock) Header() (metadata.MD, erro // HeaderCalls gets all the calls that were made to Header. // Check the length with: // len(mockedTemplateService_ListTemplatesClient.HeaderCalls()) -func (mock *TemplateService_ListTemplatesClientMock) HeaderCalls() []struct { -} { - var calls []struct { - } +func (mock *TemplateService_ListTemplatesClientMock) HeaderCalls() []struct{} { + var calls []struct{} mock.lockHeader.RLock() calls = mock.calls.Header mock.lockHeader.RUnlock() @@ -487,8 +473,7 @@ func (mock *TemplateService_ListTemplatesClientMock) Recv() (*WorkflowTemplate, if mock.RecvFunc == nil { panic("TemplateService_ListTemplatesClientMock.RecvFunc: method is nil but TemplateService_ListTemplatesClient.Recv was just called") } - callInfo := struct { - }{} + callInfo := struct{}{} mock.lockRecv.Lock() mock.calls.Recv = append(mock.calls.Recv, callInfo) mock.lockRecv.Unlock() @@ -498,10 +483,8 @@ func (mock *TemplateService_ListTemplatesClientMock) Recv() (*WorkflowTemplate, // RecvCalls gets all the calls that were made to Recv. // Check the length with: // len(mockedTemplateService_ListTemplatesClient.RecvCalls()) -func (mock *TemplateService_ListTemplatesClientMock) RecvCalls() []struct { -} { - var calls []struct { - } +func (mock *TemplateService_ListTemplatesClientMock) RecvCalls() []struct{} { + var calls []struct{} mock.lockRecv.RLock() calls = mock.calls.Recv mock.lockRecv.RUnlock() @@ -575,8 +558,7 @@ func (mock *TemplateService_ListTemplatesClientMock) Trailer() metadata.MD { if mock.TrailerFunc == nil { panic("TemplateService_ListTemplatesClientMock.TrailerFunc: method is nil but TemplateService_ListTemplatesClient.Trailer was just called") } - callInfo := struct { - }{} + callInfo := struct{}{} mock.lockTrailer.Lock() mock.calls.Trailer = append(mock.calls.Trailer, callInfo) mock.lockTrailer.Unlock() @@ -586,10 +568,8 @@ func (mock *TemplateService_ListTemplatesClientMock) Trailer() metadata.MD { // TrailerCalls gets all the calls that were made to Trailer. // Check the length with: // len(mockedTemplateService_ListTemplatesClient.TrailerCalls()) -func (mock *TemplateService_ListTemplatesClientMock) TrailerCalls() []struct { -} { - var calls []struct { - } +func (mock *TemplateService_ListTemplatesClientMock) TrailerCalls() []struct{} { + var calls []struct{} mock.lockTrailer.RLock() calls = mock.calls.Trailer mock.lockTrailer.RUnlock() diff --git a/protos/template/template.pb.go b/protos/template/template.pb.go index c13f9c4e4..85581430d 100644 --- a/protos/template/template.pb.go +++ b/protos/template/template.pb.go @@ -493,15 +493,18 @@ func file_template_template_proto_rawDescGZIP() []byte { return file_template_template_proto_rawDescData } -var file_template_template_proto_msgTypes = make([]protoimpl.MessageInfo, 5) -var file_template_template_proto_goTypes = []interface{}{ - (*Empty)(nil), // 0: github.com.tinkerbell.tink.protos.template.Empty - (*WorkflowTemplate)(nil), // 1: github.com.tinkerbell.tink.protos.template.WorkflowTemplate - (*CreateResponse)(nil), // 2: github.com.tinkerbell.tink.protos.template.CreateResponse - (*GetRequest)(nil), // 3: github.com.tinkerbell.tink.protos.template.GetRequest - (*ListRequest)(nil), // 4: github.com.tinkerbell.tink.protos.template.ListRequest - (*timestamppb.Timestamp)(nil), // 5: google.protobuf.Timestamp -} +var ( + file_template_template_proto_msgTypes = make([]protoimpl.MessageInfo, 5) + file_template_template_proto_goTypes = []interface{}{ + (*Empty)(nil), // 0: github.com.tinkerbell.tink.protos.template.Empty + (*WorkflowTemplate)(nil), // 1: github.com.tinkerbell.tink.protos.template.WorkflowTemplate + (*CreateResponse)(nil), // 2: github.com.tinkerbell.tink.protos.template.CreateResponse + (*GetRequest)(nil), // 3: github.com.tinkerbell.tink.protos.template.GetRequest + (*ListRequest)(nil), // 4: github.com.tinkerbell.tink.protos.template.ListRequest + (*timestamppb.Timestamp)(nil), // 5: google.protobuf.Timestamp + } +) + var file_template_template_proto_depIdxs = []int32{ 5, // 0: github.com.tinkerbell.tink.protos.template.WorkflowTemplate.created_at:type_name -> google.protobuf.Timestamp 5, // 1: github.com.tinkerbell.tink.protos.template.WorkflowTemplate.updated_at:type_name -> google.protobuf.Timestamp @@ -618,8 +621,10 @@ func file_template_template_proto_init() { } // Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConnInterface +var ( + _ context.Context + _ grpc.ClientConnInterface +) // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. @@ -744,21 +749,24 @@ type TemplateServiceServer interface { } // UnimplementedTemplateServiceServer can be embedded to have forward compatible implementations. -type UnimplementedTemplateServiceServer struct { -} +type UnimplementedTemplateServiceServer struct{} func (*UnimplementedTemplateServiceServer) CreateTemplate(context.Context, *WorkflowTemplate) (*CreateResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method CreateTemplate not implemented") } + func (*UnimplementedTemplateServiceServer) GetTemplate(context.Context, *GetRequest) (*WorkflowTemplate, error) { return nil, status.Errorf(codes.Unimplemented, "method GetTemplate not implemented") } + func (*UnimplementedTemplateServiceServer) DeleteTemplate(context.Context, *GetRequest) (*Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method DeleteTemplate not implemented") } + func (*UnimplementedTemplateServiceServer) ListTemplates(*ListRequest, TemplateService_ListTemplatesServer) error { return status.Errorf(codes.Unimplemented, "method ListTemplates not implemented") } + func (*UnimplementedTemplateServiceServer) UpdateTemplate(context.Context, *WorkflowTemplate) (*Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method UpdateTemplate not implemented") } diff --git a/protos/template/template.pb.gw.go b/protos/template/template.pb.gw.go index dd507d00e..ce9eaec92 100644 --- a/protos/template/template.pb.gw.go +++ b/protos/template/template.pb.gw.go @@ -25,13 +25,15 @@ import ( ) // Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage -var _ = metadata.Join +var ( + _ codes.Code + _ io.Reader + _ status.Status + _ = runtime.String + _ = utilities.NewDoubleArray + _ = descriptor.ForMessage + _ = metadata.Join +) func request_TemplateService_CreateTemplate_0(ctx context.Context, marshaler runtime.Marshaler, client TemplateServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq WorkflowTemplate @@ -47,7 +49,6 @@ func request_TemplateService_CreateTemplate_0(ctx context.Context, marshaler run msg, err := client.CreateTemplate(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_TemplateService_CreateTemplate_0(ctx context.Context, marshaler runtime.Marshaler, server TemplateServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { @@ -64,12 +65,9 @@ func local_request_TemplateService_CreateTemplate_0(ctx context.Context, marshal msg, err := server.CreateTemplate(ctx, &protoReq) return msg, metadata, err - } -var ( - filter_TemplateService_GetTemplate_0 = &utilities.DoubleArray{Encoding: map[string]int{"id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) +var filter_TemplateService_GetTemplate_0 = &utilities.DoubleArray{Encoding: map[string]int{"id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} func request_TemplateService_GetTemplate_0(ctx context.Context, marshaler runtime.Marshaler, client TemplateServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq GetRequest @@ -107,7 +105,6 @@ func request_TemplateService_GetTemplate_0(ctx context.Context, marshaler runtim msg, err := client.GetTemplate(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_TemplateService_GetTemplate_0(ctx context.Context, marshaler runtime.Marshaler, server TemplateServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { @@ -146,12 +143,9 @@ func local_request_TemplateService_GetTemplate_0(ctx context.Context, marshaler msg, err := server.GetTemplate(ctx, &protoReq) return msg, metadata, err - } -var ( - filter_TemplateService_DeleteTemplate_0 = &utilities.DoubleArray{Encoding: map[string]int{"id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) +var filter_TemplateService_DeleteTemplate_0 = &utilities.DoubleArray{Encoding: map[string]int{"id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} func request_TemplateService_DeleteTemplate_0(ctx context.Context, marshaler runtime.Marshaler, client TemplateServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq GetRequest @@ -189,7 +183,6 @@ func request_TemplateService_DeleteTemplate_0(ctx context.Context, marshaler run msg, err := client.DeleteTemplate(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_TemplateService_DeleteTemplate_0(ctx context.Context, marshaler runtime.Marshaler, server TemplateServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { @@ -228,12 +221,9 @@ func local_request_TemplateService_DeleteTemplate_0(ctx context.Context, marshal msg, err := server.DeleteTemplate(ctx, &protoReq) return msg, metadata, err - } -var ( - filter_TemplateService_ListTemplates_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) +var filter_TemplateService_ListTemplates_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} func request_TemplateService_ListTemplates_0(ctx context.Context, marshaler runtime.Marshaler, client TemplateServiceClient, req *http.Request, pathParams map[string]string) (TemplateService_ListTemplatesClient, runtime.ServerMetadata, error) { var protoReq ListRequest @@ -256,7 +246,6 @@ func request_TemplateService_ListTemplates_0(ctx context.Context, marshaler runt } metadata.HeaderMD = header return stream, metadata, nil - } // RegisterTemplateServiceHandlerServer registers the http handlers for service TemplateService to "mux". @@ -264,7 +253,6 @@ func request_TemplateService_ListTemplates_0(ctx context.Context, marshaler runt // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterTemplateServiceHandlerFromEndpoint instead. func RegisterTemplateServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server TemplateServiceServer) error { - mux.Handle("POST", pattern_TemplateService_CreateTemplate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() @@ -285,7 +273,6 @@ func RegisterTemplateServiceHandlerServer(ctx context.Context, mux *runtime.Serv } forward_TemplateService_CreateTemplate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) mux.Handle("GET", pattern_TemplateService_GetTemplate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -308,7 +295,6 @@ func RegisterTemplateServiceHandlerServer(ctx context.Context, mux *runtime.Serv } forward_TemplateService_GetTemplate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) mux.Handle("DELETE", pattern_TemplateService_DeleteTemplate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -331,7 +317,6 @@ func RegisterTemplateServiceHandlerServer(ctx context.Context, mux *runtime.Serv } forward_TemplateService_DeleteTemplate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) mux.Handle("GET", pattern_TemplateService_ListTemplates_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -381,7 +366,6 @@ func RegisterTemplateServiceHandler(ctx context.Context, mux *runtime.ServeMux, // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in // "TemplateServiceClient" to call the correct interceptors. func RegisterTemplateServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client TemplateServiceClient) error { - mux.Handle("POST", pattern_TemplateService_CreateTemplate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() @@ -399,7 +383,6 @@ func RegisterTemplateServiceHandlerClient(ctx context.Context, mux *runtime.Serv } forward_TemplateService_CreateTemplate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) mux.Handle("GET", pattern_TemplateService_GetTemplate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -419,7 +402,6 @@ func RegisterTemplateServiceHandlerClient(ctx context.Context, mux *runtime.Serv } forward_TemplateService_GetTemplate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) mux.Handle("DELETE", pattern_TemplateService_DeleteTemplate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -439,7 +421,6 @@ func RegisterTemplateServiceHandlerClient(ctx context.Context, mux *runtime.Serv } forward_TemplateService_DeleteTemplate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) mux.Handle("GET", pattern_TemplateService_ListTemplates_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -459,7 +440,6 @@ func RegisterTemplateServiceHandlerClient(ctx context.Context, mux *runtime.Serv } forward_TemplateService_ListTemplates_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) - }) return nil diff --git a/protos/workflow/mock.go b/protos/workflow/mock.go index 7481db188..441a145c7 100644 --- a/protos/workflow/mock.go +++ b/protos/workflow/mock.go @@ -865,17 +865,13 @@ type WorkflowService_ListWorkflowsClientMock struct { // calls tracks calls to the methods. calls struct { // CloseSend holds details about calls to the CloseSend method. - CloseSend []struct { - } + CloseSend []struct{} // Context holds details about calls to the Context method. - Context []struct { - } + Context []struct{} // Header holds details about calls to the Header method. - Header []struct { - } + Header []struct{} // Recv holds details about calls to the Recv method. - Recv []struct { - } + Recv []struct{} // RecvMsg holds details about calls to the RecvMsg method. RecvMsg []struct { // M is the m argument value. @@ -887,8 +883,7 @@ type WorkflowService_ListWorkflowsClientMock struct { M interface{} } // Trailer holds details about calls to the Trailer method. - Trailer []struct { - } + Trailer []struct{} } lockCloseSend sync.RWMutex lockContext sync.RWMutex @@ -904,8 +899,7 @@ func (mock *WorkflowService_ListWorkflowsClientMock) CloseSend() error { if mock.CloseSendFunc == nil { panic("WorkflowService_ListWorkflowsClientMock.CloseSendFunc: method is nil but WorkflowService_ListWorkflowsClient.CloseSend was just called") } - callInfo := struct { - }{} + callInfo := struct{}{} mock.lockCloseSend.Lock() mock.calls.CloseSend = append(mock.calls.CloseSend, callInfo) mock.lockCloseSend.Unlock() @@ -915,10 +909,8 @@ func (mock *WorkflowService_ListWorkflowsClientMock) CloseSend() error { // CloseSendCalls gets all the calls that were made to CloseSend. // Check the length with: // len(mockedWorkflowService_ListWorkflowsClient.CloseSendCalls()) -func (mock *WorkflowService_ListWorkflowsClientMock) CloseSendCalls() []struct { -} { - var calls []struct { - } +func (mock *WorkflowService_ListWorkflowsClientMock) CloseSendCalls() []struct{} { + var calls []struct{} mock.lockCloseSend.RLock() calls = mock.calls.CloseSend mock.lockCloseSend.RUnlock() @@ -930,8 +922,7 @@ func (mock *WorkflowService_ListWorkflowsClientMock) Context() context.Context { if mock.ContextFunc == nil { panic("WorkflowService_ListWorkflowsClientMock.ContextFunc: method is nil but WorkflowService_ListWorkflowsClient.Context was just called") } - callInfo := struct { - }{} + callInfo := struct{}{} mock.lockContext.Lock() mock.calls.Context = append(mock.calls.Context, callInfo) mock.lockContext.Unlock() @@ -941,10 +932,8 @@ func (mock *WorkflowService_ListWorkflowsClientMock) Context() context.Context { // ContextCalls gets all the calls that were made to Context. // Check the length with: // len(mockedWorkflowService_ListWorkflowsClient.ContextCalls()) -func (mock *WorkflowService_ListWorkflowsClientMock) ContextCalls() []struct { -} { - var calls []struct { - } +func (mock *WorkflowService_ListWorkflowsClientMock) ContextCalls() []struct{} { + var calls []struct{} mock.lockContext.RLock() calls = mock.calls.Context mock.lockContext.RUnlock() @@ -956,8 +945,7 @@ func (mock *WorkflowService_ListWorkflowsClientMock) Header() (metadata.MD, erro if mock.HeaderFunc == nil { panic("WorkflowService_ListWorkflowsClientMock.HeaderFunc: method is nil but WorkflowService_ListWorkflowsClient.Header was just called") } - callInfo := struct { - }{} + callInfo := struct{}{} mock.lockHeader.Lock() mock.calls.Header = append(mock.calls.Header, callInfo) mock.lockHeader.Unlock() @@ -967,10 +955,8 @@ func (mock *WorkflowService_ListWorkflowsClientMock) Header() (metadata.MD, erro // HeaderCalls gets all the calls that were made to Header. // Check the length with: // len(mockedWorkflowService_ListWorkflowsClient.HeaderCalls()) -func (mock *WorkflowService_ListWorkflowsClientMock) HeaderCalls() []struct { -} { - var calls []struct { - } +func (mock *WorkflowService_ListWorkflowsClientMock) HeaderCalls() []struct{} { + var calls []struct{} mock.lockHeader.RLock() calls = mock.calls.Header mock.lockHeader.RUnlock() @@ -982,8 +968,7 @@ func (mock *WorkflowService_ListWorkflowsClientMock) Recv() (*Workflow, error) { if mock.RecvFunc == nil { panic("WorkflowService_ListWorkflowsClientMock.RecvFunc: method is nil but WorkflowService_ListWorkflowsClient.Recv was just called") } - callInfo := struct { - }{} + callInfo := struct{}{} mock.lockRecv.Lock() mock.calls.Recv = append(mock.calls.Recv, callInfo) mock.lockRecv.Unlock() @@ -993,10 +978,8 @@ func (mock *WorkflowService_ListWorkflowsClientMock) Recv() (*Workflow, error) { // RecvCalls gets all the calls that were made to Recv. // Check the length with: // len(mockedWorkflowService_ListWorkflowsClient.RecvCalls()) -func (mock *WorkflowService_ListWorkflowsClientMock) RecvCalls() []struct { -} { - var calls []struct { - } +func (mock *WorkflowService_ListWorkflowsClientMock) RecvCalls() []struct{} { + var calls []struct{} mock.lockRecv.RLock() calls = mock.calls.Recv mock.lockRecv.RUnlock() @@ -1070,8 +1053,7 @@ func (mock *WorkflowService_ListWorkflowsClientMock) Trailer() metadata.MD { if mock.TrailerFunc == nil { panic("WorkflowService_ListWorkflowsClientMock.TrailerFunc: method is nil but WorkflowService_ListWorkflowsClient.Trailer was just called") } - callInfo := struct { - }{} + callInfo := struct{}{} mock.lockTrailer.Lock() mock.calls.Trailer = append(mock.calls.Trailer, callInfo) mock.lockTrailer.Unlock() @@ -1081,10 +1063,8 @@ func (mock *WorkflowService_ListWorkflowsClientMock) Trailer() metadata.MD { // TrailerCalls gets all the calls that were made to Trailer. // Check the length with: // len(mockedWorkflowService_ListWorkflowsClient.TrailerCalls()) -func (mock *WorkflowService_ListWorkflowsClientMock) TrailerCalls() []struct { -} { - var calls []struct { - } +func (mock *WorkflowService_ListWorkflowsClientMock) TrailerCalls() []struct{} { + var calls []struct{} mock.lockTrailer.RLock() calls = mock.calls.Trailer mock.lockTrailer.RUnlock() diff --git a/protos/workflow/workflow.pb.go b/protos/workflow/workflow.pb.go index 8c718339e..aa814f0c0 100644 --- a/protos/workflow/workflow.pb.go +++ b/protos/workflow/workflow.pb.go @@ -1504,27 +1504,30 @@ func file_workflow_workflow_proto_rawDescGZIP() []byte { return file_workflow_workflow_proto_rawDescData } -var file_workflow_workflow_proto_enumTypes = make([]protoimpl.EnumInfo, 1) -var file_workflow_workflow_proto_msgTypes = make([]protoimpl.MessageInfo, 15) -var file_workflow_workflow_proto_goTypes = []interface{}{ - (State)(0), // 0: github.com.tinkerbell.tink.protos.workflow.State - (*Empty)(nil), // 1: github.com.tinkerbell.tink.protos.workflow.Empty - (*Workflow)(nil), // 2: github.com.tinkerbell.tink.protos.workflow.Workflow - (*CreateRequest)(nil), // 3: github.com.tinkerbell.tink.protos.workflow.CreateRequest - (*CreateResponse)(nil), // 4: github.com.tinkerbell.tink.protos.workflow.CreateResponse - (*GetRequest)(nil), // 5: github.com.tinkerbell.tink.protos.workflow.GetRequest - (*WorkflowContext)(nil), // 6: github.com.tinkerbell.tink.protos.workflow.WorkflowContext - (*WorkflowActionStatus)(nil), // 7: github.com.tinkerbell.tink.protos.workflow.WorkflowActionStatus - (*WorkflowContextRequest)(nil), // 8: github.com.tinkerbell.tink.protos.workflow.WorkflowContextRequest - (*WorkflowContextList)(nil), // 9: github.com.tinkerbell.tink.protos.workflow.WorkflowContextList - (*WorkflowActionsRequest)(nil), // 10: github.com.tinkerbell.tink.protos.workflow.WorkflowActionsRequest - (*WorkflowAction)(nil), // 11: github.com.tinkerbell.tink.protos.workflow.WorkflowAction - (*WorkflowActionList)(nil), // 12: github.com.tinkerbell.tink.protos.workflow.WorkflowActionList - (*GetWorkflowDataRequest)(nil), // 13: github.com.tinkerbell.tink.protos.workflow.GetWorkflowDataRequest - (*GetWorkflowDataResponse)(nil), // 14: github.com.tinkerbell.tink.protos.workflow.GetWorkflowDataResponse - (*UpdateWorkflowDataRequest)(nil), // 15: github.com.tinkerbell.tink.protos.workflow.UpdateWorkflowDataRequest - (*timestamppb.Timestamp)(nil), // 16: google.protobuf.Timestamp -} +var ( + file_workflow_workflow_proto_enumTypes = make([]protoimpl.EnumInfo, 1) + file_workflow_workflow_proto_msgTypes = make([]protoimpl.MessageInfo, 15) + file_workflow_workflow_proto_goTypes = []interface{}{ + (State)(0), // 0: github.com.tinkerbell.tink.protos.workflow.State + (*Empty)(nil), // 1: github.com.tinkerbell.tink.protos.workflow.Empty + (*Workflow)(nil), // 2: github.com.tinkerbell.tink.protos.workflow.Workflow + (*CreateRequest)(nil), // 3: github.com.tinkerbell.tink.protos.workflow.CreateRequest + (*CreateResponse)(nil), // 4: github.com.tinkerbell.tink.protos.workflow.CreateResponse + (*GetRequest)(nil), // 5: github.com.tinkerbell.tink.protos.workflow.GetRequest + (*WorkflowContext)(nil), // 6: github.com.tinkerbell.tink.protos.workflow.WorkflowContext + (*WorkflowActionStatus)(nil), // 7: github.com.tinkerbell.tink.protos.workflow.WorkflowActionStatus + (*WorkflowContextRequest)(nil), // 8: github.com.tinkerbell.tink.protos.workflow.WorkflowContextRequest + (*WorkflowContextList)(nil), // 9: github.com.tinkerbell.tink.protos.workflow.WorkflowContextList + (*WorkflowActionsRequest)(nil), // 10: github.com.tinkerbell.tink.protos.workflow.WorkflowActionsRequest + (*WorkflowAction)(nil), // 11: github.com.tinkerbell.tink.protos.workflow.WorkflowAction + (*WorkflowActionList)(nil), // 12: github.com.tinkerbell.tink.protos.workflow.WorkflowActionList + (*GetWorkflowDataRequest)(nil), // 13: github.com.tinkerbell.tink.protos.workflow.GetWorkflowDataRequest + (*GetWorkflowDataResponse)(nil), // 14: github.com.tinkerbell.tink.protos.workflow.GetWorkflowDataResponse + (*UpdateWorkflowDataRequest)(nil), // 15: github.com.tinkerbell.tink.protos.workflow.UpdateWorkflowDataRequest + (*timestamppb.Timestamp)(nil), // 16: google.protobuf.Timestamp + } +) + var file_workflow_workflow_proto_depIdxs = []int32{ 0, // 0: github.com.tinkerbell.tink.protos.workflow.Workflow.state:type_name -> github.com.tinkerbell.tink.protos.workflow.State 16, // 1: github.com.tinkerbell.tink.protos.workflow.Workflow.created_at:type_name -> google.protobuf.Timestamp @@ -1779,8 +1782,10 @@ func file_workflow_workflow_proto_init() { } // Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConnInterface +var ( + _ context.Context + _ grpc.ClientConnInterface +) // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. @@ -2062,48 +2067,60 @@ type WorkflowServiceServer interface { } // UnimplementedWorkflowServiceServer can be embedded to have forward compatible implementations. -type UnimplementedWorkflowServiceServer struct { -} +type UnimplementedWorkflowServiceServer struct{} func (*UnimplementedWorkflowServiceServer) CreateWorkflow(context.Context, *CreateRequest) (*CreateResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method CreateWorkflow not implemented") } + func (*UnimplementedWorkflowServiceServer) GetWorkflow(context.Context, *GetRequest) (*Workflow, error) { return nil, status.Errorf(codes.Unimplemented, "method GetWorkflow not implemented") } + func (*UnimplementedWorkflowServiceServer) DeleteWorkflow(context.Context, *GetRequest) (*Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method DeleteWorkflow not implemented") } + func (*UnimplementedWorkflowServiceServer) ListWorkflows(*Empty, WorkflowService_ListWorkflowsServer) error { return status.Errorf(codes.Unimplemented, "method ListWorkflows not implemented") } + func (*UnimplementedWorkflowServiceServer) GetWorkflowContext(context.Context, *GetRequest) (*WorkflowContext, error) { return nil, status.Errorf(codes.Unimplemented, "method GetWorkflowContext not implemented") } + func (*UnimplementedWorkflowServiceServer) ShowWorkflowEvents(*GetRequest, WorkflowService_ShowWorkflowEventsServer) error { return status.Errorf(codes.Unimplemented, "method ShowWorkflowEvents not implemented") } + func (*UnimplementedWorkflowServiceServer) GetWorkflowContextList(context.Context, *WorkflowContextRequest) (*WorkflowContextList, error) { return nil, status.Errorf(codes.Unimplemented, "method GetWorkflowContextList not implemented") } + func (*UnimplementedWorkflowServiceServer) GetWorkflowContexts(*WorkflowContextRequest, WorkflowService_GetWorkflowContextsServer) error { return status.Errorf(codes.Unimplemented, "method GetWorkflowContexts not implemented") } + func (*UnimplementedWorkflowServiceServer) GetWorkflowActions(context.Context, *WorkflowActionsRequest) (*WorkflowActionList, error) { return nil, status.Errorf(codes.Unimplemented, "method GetWorkflowActions not implemented") } + func (*UnimplementedWorkflowServiceServer) ReportActionStatus(context.Context, *WorkflowActionStatus) (*Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method ReportActionStatus not implemented") } + func (*UnimplementedWorkflowServiceServer) GetWorkflowData(context.Context, *GetWorkflowDataRequest) (*GetWorkflowDataResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method GetWorkflowData not implemented") } + func (*UnimplementedWorkflowServiceServer) GetWorkflowMetadata(context.Context, *GetWorkflowDataRequest) (*GetWorkflowDataResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method GetWorkflowMetadata not implemented") } + func (*UnimplementedWorkflowServiceServer) GetWorkflowDataVersion(context.Context, *GetWorkflowDataRequest) (*GetWorkflowDataResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method GetWorkflowDataVersion not implemented") } + func (*UnimplementedWorkflowServiceServer) UpdateWorkflowData(context.Context, *UpdateWorkflowDataRequest) (*Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method UpdateWorkflowData not implemented") } diff --git a/protos/workflow/workflow.pb.gw.go b/protos/workflow/workflow.pb.gw.go index 6c4827882..2c94215c2 100644 --- a/protos/workflow/workflow.pb.gw.go +++ b/protos/workflow/workflow.pb.gw.go @@ -25,13 +25,15 @@ import ( ) // Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage -var _ = metadata.Join +var ( + _ codes.Code + _ io.Reader + _ status.Status + _ = runtime.String + _ = utilities.NewDoubleArray + _ = descriptor.ForMessage + _ = metadata.Join +) func request_WorkflowService_CreateWorkflow_0(ctx context.Context, marshaler runtime.Marshaler, client WorkflowServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var protoReq CreateRequest @@ -47,7 +49,6 @@ func request_WorkflowService_CreateWorkflow_0(ctx context.Context, marshaler run msg, err := client.CreateWorkflow(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_WorkflowService_CreateWorkflow_0(ctx context.Context, marshaler runtime.Marshaler, server WorkflowServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { @@ -64,7 +65,6 @@ func local_request_WorkflowService_CreateWorkflow_0(ctx context.Context, marshal msg, err := server.CreateWorkflow(ctx, &protoReq) return msg, metadata, err - } func request_WorkflowService_GetWorkflow_0(ctx context.Context, marshaler runtime.Marshaler, client WorkflowServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { @@ -91,7 +91,6 @@ func request_WorkflowService_GetWorkflow_0(ctx context.Context, marshaler runtim msg, err := client.GetWorkflow(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_WorkflowService_GetWorkflow_0(ctx context.Context, marshaler runtime.Marshaler, server WorkflowServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { @@ -118,7 +117,6 @@ func local_request_WorkflowService_GetWorkflow_0(ctx context.Context, marshaler msg, err := server.GetWorkflow(ctx, &protoReq) return msg, metadata, err - } func request_WorkflowService_DeleteWorkflow_0(ctx context.Context, marshaler runtime.Marshaler, client WorkflowServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { @@ -145,7 +143,6 @@ func request_WorkflowService_DeleteWorkflow_0(ctx context.Context, marshaler run msg, err := client.DeleteWorkflow(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_WorkflowService_DeleteWorkflow_0(ctx context.Context, marshaler runtime.Marshaler, server WorkflowServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { @@ -172,7 +169,6 @@ func local_request_WorkflowService_DeleteWorkflow_0(ctx context.Context, marshal msg, err := server.DeleteWorkflow(ctx, &protoReq) return msg, metadata, err - } func request_WorkflowService_ListWorkflows_0(ctx context.Context, marshaler runtime.Marshaler, client WorkflowServiceClient, req *http.Request, pathParams map[string]string) (WorkflowService_ListWorkflowsClient, runtime.ServerMetadata, error) { @@ -189,7 +185,6 @@ func request_WorkflowService_ListWorkflows_0(ctx context.Context, marshaler runt } metadata.HeaderMD = header return stream, metadata, nil - } func request_WorkflowService_GetWorkflowContext_0(ctx context.Context, marshaler runtime.Marshaler, client WorkflowServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { @@ -216,7 +211,6 @@ func request_WorkflowService_GetWorkflowContext_0(ctx context.Context, marshaler msg, err := client.GetWorkflowContext(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_WorkflowService_GetWorkflowContext_0(ctx context.Context, marshaler runtime.Marshaler, server WorkflowServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { @@ -243,7 +237,6 @@ func local_request_WorkflowService_GetWorkflowContext_0(ctx context.Context, mar msg, err := server.GetWorkflowContext(ctx, &protoReq) return msg, metadata, err - } func request_WorkflowService_ShowWorkflowEvents_0(ctx context.Context, marshaler runtime.Marshaler, client WorkflowServiceClient, req *http.Request, pathParams map[string]string) (WorkflowService_ShowWorkflowEventsClient, runtime.ServerMetadata, error) { @@ -278,7 +271,6 @@ func request_WorkflowService_ShowWorkflowEvents_0(ctx context.Context, marshaler } metadata.HeaderMD = header return stream, metadata, nil - } // RegisterWorkflowServiceHandlerServer registers the http handlers for service WorkflowService to "mux". @@ -286,7 +278,6 @@ func request_WorkflowService_ShowWorkflowEvents_0(ctx context.Context, marshaler // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterWorkflowServiceHandlerFromEndpoint instead. func RegisterWorkflowServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server WorkflowServiceServer) error { - mux.Handle("POST", pattern_WorkflowService_CreateWorkflow_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() @@ -307,7 +298,6 @@ func RegisterWorkflowServiceHandlerServer(ctx context.Context, mux *runtime.Serv } forward_WorkflowService_CreateWorkflow_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) mux.Handle("GET", pattern_WorkflowService_GetWorkflow_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -330,7 +320,6 @@ func RegisterWorkflowServiceHandlerServer(ctx context.Context, mux *runtime.Serv } forward_WorkflowService_GetWorkflow_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) mux.Handle("DELETE", pattern_WorkflowService_DeleteWorkflow_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -353,7 +342,6 @@ func RegisterWorkflowServiceHandlerServer(ctx context.Context, mux *runtime.Serv } forward_WorkflowService_DeleteWorkflow_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) mux.Handle("GET", pattern_WorkflowService_ListWorkflows_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -383,7 +371,6 @@ func RegisterWorkflowServiceHandlerServer(ctx context.Context, mux *runtime.Serv } forward_WorkflowService_GetWorkflowContext_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) mux.Handle("GET", pattern_WorkflowService_ShowWorkflowEvents_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -433,7 +420,6 @@ func RegisterWorkflowServiceHandler(ctx context.Context, mux *runtime.ServeMux, // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in // "WorkflowServiceClient" to call the correct interceptors. func RegisterWorkflowServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client WorkflowServiceClient) error { - mux.Handle("POST", pattern_WorkflowService_CreateWorkflow_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() @@ -451,7 +437,6 @@ func RegisterWorkflowServiceHandlerClient(ctx context.Context, mux *runtime.Serv } forward_WorkflowService_CreateWorkflow_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) mux.Handle("GET", pattern_WorkflowService_GetWorkflow_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -471,7 +456,6 @@ func RegisterWorkflowServiceHandlerClient(ctx context.Context, mux *runtime.Serv } forward_WorkflowService_GetWorkflow_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) mux.Handle("DELETE", pattern_WorkflowService_DeleteWorkflow_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -491,7 +475,6 @@ func RegisterWorkflowServiceHandlerClient(ctx context.Context, mux *runtime.Serv } forward_WorkflowService_DeleteWorkflow_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) mux.Handle("GET", pattern_WorkflowService_ListWorkflows_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -511,7 +494,6 @@ func RegisterWorkflowServiceHandlerClient(ctx context.Context, mux *runtime.Serv } forward_WorkflowService_ListWorkflows_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) - }) mux.Handle("GET", pattern_WorkflowService_GetWorkflowContext_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -531,7 +513,6 @@ func RegisterWorkflowServiceHandlerClient(ctx context.Context, mux *runtime.Serv } forward_WorkflowService_GetWorkflowContext_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) mux.Handle("GET", pattern_WorkflowService_ShowWorkflowEvents_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -551,7 +532,6 @@ func RegisterWorkflowServiceHandlerClient(ctx context.Context, mux *runtime.Serv } forward_WorkflowService_ShowWorkflowEvents_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) - }) return nil From e8cce101548d92ce4da34ec9a40b5a896c160e39 Mon Sep 17 00:00:00 2001 From: Thomas Stromberg Date: Wed, 22 Sep 2021 10:43:52 -0700 Subject: [PATCH 5/9] Write prettier results to disks so that we can find the required change more easily Signed-off-by: Thomas Stromberg --- ci-checks.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ci-checks.sh b/ci-checks.sh index d61d4d519..710a63061 100755 --- a/ci-checks.sh +++ b/ci-checks.sh @@ -11,7 +11,8 @@ if ! git ls-files '*.sh' '*.go' '*.md' | xargs codespell -q 3 -I .codespell-whit failed=1 fi -if ! git ls-files '*.yml' '*.json' '*.md' | xargs prettier --check; then +# --check doesn't show what line number fails, so write the result to disk for the diff to catch +if ! git ls-files '*.yml' '*.json' '*.md' | xargs prettier --list-different --write;; then failed=1 fi From e94f138f6765c3e965f0ab60dfceb7b481f367c6 Mon Sep 17 00:00:00 2001 From: Thomas Stromberg Date: Wed, 22 Sep 2021 11:16:15 -0700 Subject: [PATCH 6/9] Remove extraneous semi-colon Signed-off-by: Thomas Stromberg --- ci-checks.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ci-checks.sh b/ci-checks.sh index 710a63061..826964aeb 100755 --- a/ci-checks.sh +++ b/ci-checks.sh @@ -12,7 +12,7 @@ if ! git ls-files '*.sh' '*.go' '*.md' | xargs codespell -q 3 -I .codespell-whit fi # --check doesn't show what line number fails, so write the result to disk for the diff to catch -if ! git ls-files '*.yml' '*.json' '*.md' | xargs prettier --list-different --write;; then +if ! git ls-files '*.yml' '*.json' '*.md' | xargs prettier --list-different --write; then failed=1 fi From 4dd91151552975942cefdc1f0ca63562a2ab9e09 Mon Sep 17 00:00:00 2001 From: Thomas Stromberg Date: Wed, 22 Sep 2021 12:05:33 -0700 Subject: [PATCH 7/9] Extend golangci-lint timeout from 1m to 4m (new lint-install) Signed-off-by: Thomas Stromberg --- .golangci.yml | 4 ++++ Makefile | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index a90a568ac..1b06c90a9 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,3 +1,7 @@ +run: + # The default runtime timeout is 1m, which doesn't work well on Github Actions. + timeout: 4m + # NOTE: This file is populated by the lint-install tool. Local adjustments may be overwritten. linters-settings: cyclop: diff --git a/Makefile b/Makefile index 5845ef8c6..82921d14b 100644 --- a/Makefile +++ b/Makefile @@ -15,7 +15,7 @@ verify: lint help: ## Print this help @grep --no-filename -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sed 's/:.*##/·/' | sort | column -ts '·' -c 120 -# BEGIN: lint-install --dockerfile=warn ../tink +# BEGIN: lint-install --dockerfile=warn . # http://github.com/tinkerbell/lint-install GOLINT_VERSION ?= v1.42.0 @@ -59,4 +59,4 @@ out/linters/golangci-lint-$(GOLINT_VERSION)-$(LINT_ARCH): curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b out/linters $(GOLINT_VERSION) mv out/linters/golangci-lint out/linters/golangci-lint-$(GOLINT_VERSION)-$(LINT_ARCH) -# END: lint-install --dockerfile=warn ../tink +# END: lint-install --dockerfile=warn . From 6a7f85d619fd3125b4e5d1ab0e46137ef0e225c5 Mon Sep 17 00:00:00 2001 From: Thomas Stromberg Date: Wed, 22 Sep 2021 12:09:45 -0700 Subject: [PATCH 8/9] Add bullshit empty line Signed-off-by: Thomas Stromberg --- .golangci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.golangci.yml b/.golangci.yml index 1b06c90a9..32928c100 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -154,6 +154,7 @@ linters: - wastedassign - whitespace + # Disabled linters, due to being misaligned with Go practices # - exhaustivestruct # - gochecknoglobals From cd512b934dc27893fcc22ae752bce89b52cb3134 Mon Sep 17 00:00:00 2001 From: Thomas Stromberg Date: Thu, 30 Sep 2021 16:16:32 -0700 Subject: [PATCH 9/9] Replace uses of tx.Exec with tx.ExecContext Signed-off-by: Thomas Stromberg --- db/hardware.go | 4 ++-- db/template.go | 10 +++++----- db/workflow.go | 34 +++++++++++++++++----------------- 3 files changed, 24 insertions(+), 24 deletions(-) diff --git a/db/hardware.go b/db/hardware.go index b57bff221..97a6475fc 100644 --- a/db/hardware.go +++ b/db/hardware.go @@ -18,7 +18,7 @@ func (d TinkDB) DeleteFromDB(ctx context.Context, id string) error { return errors.Wrap(err, "BEGIN transaction") } - res, err := tx.Exec(` + res, err := tx.ExecContext(ctx, ` UPDATE hardware SET deleted_at = NOW() @@ -47,7 +47,7 @@ func (d TinkDB) InsertIntoDB(ctx context.Context, data string) error { return errors.Wrap(err, "BEGIN transaction") } - _, err = tx.Exec(` + _, err = tx.ExecContext(ctx, ` INSERT INTO hardware (inserted_at, id, data) VALUES diff --git a/db/template.go b/db/template.go index 6f049414d..6fd31bffc 100644 --- a/db/template.go +++ b/db/template.go @@ -27,7 +27,7 @@ func (d TinkDB) CreateTemplate(ctx context.Context, name string, data string, id if err != nil { return errors.Wrap(err, "BEGIN transaction") } - _, err = tx.Exec(` + _, err = tx.ExecContext(ctx, ` INSERT INTO template (created_at, updated_at, name, data, id) VALUES @@ -107,7 +107,7 @@ func (d TinkDB) DeleteTemplate(ctx context.Context, id string) error { return errors.Wrap(err, "BEGIN transaction") } - res, err := tx.Exec(` + res, err := tx.ExecContext(ctx, ` UPDATE template SET deleted_at = NOW() @@ -183,11 +183,11 @@ func (d TinkDB) UpdateTemplate(ctx context.Context, name string, data string, id switch { case data == "" && name != "": - _, err = tx.Exec(`UPDATE template SET updated_at = NOW(), name = $2 WHERE id = $1;`, id, name) + _, err = tx.ExecContext(ctx, `UPDATE template SET updated_at = NOW(), name = $2 WHERE id = $1;`, id, name) case data != "" && name == "": - _, err = tx.Exec(`UPDATE template SET updated_at = NOW(), data = $2 WHERE id = $1;`, id, data) + _, err = tx.ExecContext(ctx, `UPDATE template SET updated_at = NOW(), data = $2 WHERE id = $1;`, id, data) default: - _, err = tx.Exec(`UPDATE template SET updated_at = NOW(), name = $2, data = $3 WHERE id = $1;`, id, name, data) + _, err = tx.ExecContext(ctx, `UPDATE template SET updated_at = NOW(), name = $2, data = $3 WHERE id = $1;`, id, name, data) } if err != nil { diff --git a/db/workflow.go b/db/workflow.go index 6a9ce8132..cc8556560 100644 --- a/db/workflow.go +++ b/db/workflow.go @@ -44,7 +44,7 @@ func (d TinkDB) CreateWorkflow(ctx context.Context, wf Workflow, data string, id if err != nil { return errors.Wrap(err, "failed to create workflow") } - err = insertInWorkflow(wf, tx) + err = insertInWorkflow(ctx, wf, tx) if err != nil { return errors.Wrap(err, "failed to create workflow") } @@ -55,8 +55,8 @@ func (d TinkDB) CreateWorkflow(ctx context.Context, wf Workflow, data string, id return nil } -func insertInWorkflow(wf Workflow, tx *sql.Tx) error { - _, err := tx.Exec(` +func insertInWorkflow(ctx context.Context, wf Workflow, tx *sql.Tx) error { + _, err := tx.ExecContext(ctx, ` INSERT INTO workflow (created_at, updated_at, template, devices, id) VALUES @@ -72,8 +72,8 @@ func insertInWorkflow(wf Workflow, tx *sql.Tx) error { return nil } -func insertIntoWfWorkerTable(wfID uuid.UUID, workerID uuid.UUID, tx *sql.Tx) error { - _, err := tx.Exec(` +func insertIntoWfWorkerTable(ctx context.Context, wfID uuid.UUID, workerID uuid.UUID, tx *sql.Tx) error { + _, err := tx.ExecContext(ctx, ` INSERT INTO workflow_worker_map (workflow_id, worker_id) VALUES @@ -116,7 +116,7 @@ func insertActionList(ctx context.Context, db *sql.DB, yamlData string, id uuid. return err } if uniqueWorkerID != workerUID { - err = insertIntoWfWorkerTable(id, workerUID, tx) + err = insertIntoWfWorkerTable(ctx, id, workerUID, tx) if err != nil { return err } @@ -173,7 +173,7 @@ func insertActionList(ctx context.Context, db *sql.DB, yamlData string, id uuid. return err } - _, err = tx.Exec(` + _, err = tx.ExecContext(ctx, ` INSERT INTO workflow_state (workflow_id, current_worker, current_task_name, current_action_name, current_action_state, action_list, current_action_index, total_number_of_actions) VALUES @@ -203,7 +203,7 @@ func (d TinkDB) InsertIntoWfDataTable(ctx context.Context, req *pb.UpdateWorkflo return errors.Wrap(err, "BEGIN transaction") } - _, err = tx.Exec(` + _, err = tx.ExecContext(ctx, ` INSERT INTO workflow_data (workflow_id, version, metadata, data) VALUES @@ -215,7 +215,7 @@ func (d TinkDB) InsertIntoWfDataTable(ctx context.Context, req *pb.UpdateWorkflo if version > int32(maxVersions) { cleanVersion := version - int32(maxVersions) - _, err = tx.Exec(` + _, err = tx.ExecContext(ctx, ` UPDATE workflow_data SET data = NULL @@ -375,7 +375,7 @@ func (d TinkDB) DeleteWorkflow(ctx context.Context, id string, _ int32) error { return errors.Wrap(err, "BEGIN transaction") } - _, err = tx.Exec(` + _, err = tx.ExecContext(ctx, ` DELETE FROM workflow_worker_map WHERE workflow_id = $1; @@ -384,7 +384,7 @@ func (d TinkDB) DeleteWorkflow(ctx context.Context, id string, _ int32) error { return errors.Wrap(err, "Delete Workflow Error") } - _, err = tx.Exec(` + _, err = tx.ExecContext(ctx, ` DELETE FROM workflow_state WHERE workflow_id = $1; @@ -393,7 +393,7 @@ func (d TinkDB) DeleteWorkflow(ctx context.Context, id string, _ int32) error { return errors.Wrap(err, "Delete Workflow Error") } - res, err := tx.Exec(` + res, err := tx.ExecContext(ctx, ` UPDATE workflow SET deleted_at = NOW() @@ -469,11 +469,11 @@ func (d TinkDB) UpdateWorkflow(ctx context.Context, wf Workflow, _ int32) error switch { case wf.Hardware == "" && wf.Template != "": - _, err = tx.Exec(`UPDATE workflow SET updated_at = NOW(), template = $2 WHERE id = $1;`, wf.ID, wf.Template) + _, err = tx.ExecContext(ctx, `UPDATE workflow SET updated_at = NOW(), template = $2 WHERE id = $1;`, wf.ID, wf.Template) case wf.Hardware != "" && wf.Template == "": - _, err = tx.Exec(`UPDATE workflow SET updated_at = NOW(), devices = $2 WHERE id = $1;`, wf.ID, wf.Hardware) + _, err = tx.ExecContext(ctx, `UPDATE workflow SET updated_at = NOW(), devices = $2 WHERE id = $1;`, wf.ID, wf.Hardware) default: - _, err = tx.Exec(`UPDATE workflow SET updated_at = NOW(), template = $2, devices = $3 WHERE id = $1;`, wf.ID, wf.Template, wf.Hardware) + _, err = tx.ExecContext(ctx, `UPDATE workflow SET updated_at = NOW(), template = $2, devices = $3 WHERE id = $1;`, wf.ID, wf.Template, wf.Hardware) } if err != nil { @@ -494,7 +494,7 @@ func (d TinkDB) UpdateWorkflowState(ctx context.Context, wfContext *pb.WorkflowC return errors.Wrap(err, "BEGIN transaction") } - _, err = tx.Exec(` + _, err = tx.ExecContext(ctx, ` UPDATE workflow_state SET current_task_name = $2, current_action_name = $3, @@ -581,7 +581,7 @@ func (d TinkDB) InsertIntoWorkflowEventTable(ctx context.Context, wfEvent *pb.Wo } // TODO "created_at" field should be set in worker and come in the request - _, err = tx.Exec(` + _, err = tx.ExecContext(ctx, ` INSERT INTO workflow_event (workflow_id, worker_id, task_name, action_name, execution_time, message, status, created_at) VALUES