From e263525d69b53e329f447dd85cf40ccd95c0552e Mon Sep 17 00:00:00 2001 From: aram price Date: Mon, 28 Mar 2022 10:51:43 -0700 Subject: [PATCH 1/3] `golangci-lint` passes on production code - removed unused code in `jobsupervisor/` --- .golangci.yml | 67 ++++++ agent/action/add_persistent_disk.go | 1 + agent/action/compile_package.go | 9 +- agent/action/concrete_factory.go | 5 +- agent/action/drain.go | 5 +- agent/action/fetch_logs.go | 17 +- agent/action/list_disk.go | 6 +- agent/action/mount_disk.go | 19 +- agent/action/release_apply_spec.go | 2 +- agent/action/run_script.go | 2 +- agent/action/runner.go | 16 +- agent/action/shutdown.go | 4 +- agent/action/upload_blob.go | 1 - agent/agent.go | 8 +- agent/alert/monit_adapter.go | 168 ++++++------- .../applier/applyspec/concrete_v1_service.go | 2 +- .../rendered_templates_archive_spec.go | 1 - .../bundle_collection_interface.go | 2 +- .../file_bundle_collection.go | 5 +- agent/applier/concrete_applier.go | 3 +- agent/applier/models/job.go | 5 +- agent/bootstrap.go | 2 +- agent/compiler/concrete_compiler.go | 3 +- agent/heartbeat.go | 40 ++-- .../blobstore_delegator.go | 7 +- .../blobstore_delegator_interface.go | 2 +- agent/httpblobprovider/http_blob_provider.go | 20 +- agent/script/drain/concrete_script.go | 4 +- agent/script/parallel_script.go | 22 +- agent/task/concrete_manager.go | 2 +- agent/utils/agent_killer.go | 2 - agentclient/http/agent_client.go | 2 +- agentclient/ping_retryable.go | 2 +- ci/pipeline.yml | 9 + .../iscsi_device_path_resolver.go | 7 +- .../mapped_device_path_resolver.go | 2 +- .../scsi_volume_id_device_path_resolver.go | 22 +- infrastructure/dig_dns_resolver.go | 2 - infrastructure/file_metadata_service.go | 12 +- infrastructure/file_registry.go | 2 +- infrastructure/http_metadata_service.go | 9 +- infrastructure/settings_source_factory.go | 6 +- integration/utils/blobstore.go | 3 +- integration/utils/nats_client.go | 3 +- .../templates/execution-lock/hibernate.go | 2 +- integration/windows/utils/agent.go | 11 +- jobsupervisor/alert_envelope.go | 6 +- jobsupervisor/monit/http_client.go | 2 +- jobsupervisor/monit/monit_retry_strategy.go | 8 +- jobsupervisor/monitor/disk.go | 69 ------ jobsupervisor/monitor/disk_test.go | 28 --- jobsupervisor/monitor/memory.go | 126 ---------- jobsupervisor/monitor/memory_test.go | 98 -------- jobsupervisor/monitor/monitor.go | 223 ------------------ jobsupervisor/monitor/monitor_suite_test.go | 13 - jobsupervisor/monitor/monitor_test.go | 58 ----- jobsupervisor/pipe/main.go | 34 ++- jobsupervisor/pipe/syslog/syslog.go | 66 +++--- jobsupervisor/provider.go | 14 +- jobsupervisor/windows_job_supervisor.go | 45 ++-- jobsupervisor/winsvc/cpu.go | 132 ----------- jobsupervisor/winsvc/winsvc.go | 32 +-- jobsupervisor/wrapper_job_supervisor.go | 20 +- main/agent.go | 7 +- matchers/one_of_matcher.go | 2 +- mbus/handler_provider.go | 21 +- mbus/https_handler.go | 8 +- platform/cdrom/cdutil.go | 2 +- platform/cert/windows_cert_manager.go | 8 +- platform/delayed_audit_logger_unix.go | 5 +- platform/disk/cmd_mounts_searcher.go | 10 +- platform/disk/ephemeral_device_partitioner.go | 6 +- platform/disk/linux_formatter.go | 24 +- platform/disk/parted_partitioner.go | 21 +- platform/disk/proc_mounts_searcher.go | 8 +- platform/disk/root_device_partitioner.go | 11 - platform/disk/sfdisk_partitioner.go | 45 ++-- platform/dummy_platform.go | 23 +- platform/linux_platform.go | 111 ++++----- platform/net/custom_network.go | 36 --- platform/net/default_network_resolver.go | 1 - platform/net/firewall_provider_windows.go | 8 +- platform/net/interface_manager_windows.go | 9 +- .../net/ip/interface_addresses_validator.go | 6 +- platform/net/kernel_ipv6.go | 2 +- platform/net/routes_searcher_unix.go | 8 +- platform/net/routes_searcher_windows.go | 13 +- platform/net/ubuntu_net_manager.go | 119 +++------- platform/net/windows_net_manager.go | 2 - .../openiscsi/concrete_open_iscsi_admin.go | 30 +-- platform/syscall_unix.go | 4 - platform/syscall_windows.go | 34 +-- platform/udevdevice/concrete_udev_device.go | 26 +- platform/vitals/service.go | 60 ++--- platform/windows_platform.go | 42 ++-- settings/settings.go | 12 +- sigar/sigar_stats_collector.go | 1 - tools/tools.go | 5 +- 98 files changed, 723 insertions(+), 1527 deletions(-) create mode 100644 .golangci.yml delete mode 100644 jobsupervisor/monitor/disk.go delete mode 100644 jobsupervisor/monitor/disk_test.go delete mode 100644 jobsupervisor/monitor/memory.go delete mode 100644 jobsupervisor/monitor/memory_test.go delete mode 100644 jobsupervisor/monitor/monitor.go delete mode 100644 jobsupervisor/monitor/monitor_suite_test.go delete mode 100644 jobsupervisor/monitor/monitor_test.go delete mode 100644 jobsupervisor/winsvc/cpu.go delete mode 100644 platform/net/custom_network.go diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 000000000..354e1430a --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,67 @@ +# https://github.com/golangci/golangci-lint#config-file +run: + deadline: 5m + skip-dirs: + - tmp + - integration + skip-files: + - ".*/fake-.*\\.go$" + +linters: + disable-all: true + enable: &LINTERS + # default linters + - deadcode + - errcheck + - gosimple + - govet + - ineffassign + - staticcheck + - structcheck + - typecheck + - unused + - varcheck + + # additional linters for this project (we should disable these if they get annoying). + - asciicheck + - bodyclose + - depguard + - dogsled + - exhaustive + - exportloopref + - funlen + - gochecknoglobals + - gochecknoinits + - gocritic + - gocyclo + - goheader + - goimports + - revive + - goprintffuncname + - gosec + - misspell + - nakedret + - nestif + - noctx + - nolintlint + - prealloc + - rowserrcheck + - exportloopref + - sqlclosecheck + - unconvert + - whitespace + +issues: + exclude-rules: + - path: _test\.go + linters: *LINTERS + +linters-settings: + dogsled: + max-blank-identifiers: 5 + funlen: + lines: 200 + statements: 90 + +output: + sort-results: true diff --git a/agent/action/add_persistent_disk.go b/agent/action/add_persistent_disk.go index de9818c68..10f0c582b 100644 --- a/agent/action/add_persistent_disk.go +++ b/agent/action/add_persistent_disk.go @@ -2,6 +2,7 @@ package action import ( "errors" + boshsettings "github.com/cloudfoundry/bosh-agent/settings" bosherr "github.com/cloudfoundry/bosh-utils/errors" ) diff --git a/agent/action/compile_package.go b/agent/action/compile_package.go index 0d7426f0c..1a7c40f2a 100644 --- a/agent/action/compile_package.go +++ b/agent/action/compile_package.go @@ -30,7 +30,9 @@ func (a CompilePackageAction) IsLoggable() bool { return true } -func (a CompilePackageAction) Run(blobID string, multiDigest boshcrypto.MultipleDigest, name, version string, deps boshcomp.Dependencies) (val map[string]interface{}, err error) { +func (a CompilePackageAction) Run(blobID string, multiDigest boshcrypto.MultipleDigest, name, version string, deps boshcomp.Dependencies) (map[string]interface{}, error) { + val := map[string]interface{}{} + pkg := boshcomp.Package{ BlobstoreID: blobID, Name: name, @@ -53,8 +55,7 @@ func (a CompilePackageAction) Run(blobID string, multiDigest boshcrypto.Multiple uploadedBlobID, uploadedDigest, err := a.compiler.Compile(pkg, modelsDeps) if err != nil { - err = bosherr.WrapErrorf(err, "Compiling package %s", pkg.Name) - return + return val, bosherr.WrapErrorf(err, "Compiling package %s", pkg.Name) } result := map[string]string{ @@ -65,7 +66,7 @@ func (a CompilePackageAction) Run(blobID string, multiDigest boshcrypto.Multiple val = map[string]interface{}{ "result": result, } - return + return val, nil } func (a CompilePackageAction) Resume() (interface{}, error) { diff --git a/agent/action/concrete_factory.go b/agent/action/concrete_factory.go index 86ac3b914..33708002c 100644 --- a/agent/action/concrete_factory.go +++ b/agent/action/concrete_factory.go @@ -35,14 +35,14 @@ func NewFactory( specService boshas.V1Service, jobScriptProvider boshscript.JobScriptProvider, logger boshlog.Logger, - blobstoreDelegator blobdelegator.BlobstoreDelegator) (factory Factory) { + blobstoreDelegator blobdelegator.BlobstoreDelegator) Factory { compressor := platform.GetCompressor() copier := platform.GetCopier() dirProvider := platform.GetDirProvider() vitalsService := platform.GetVitalsService() certManager := platform.GetCertManager() - factory = concreteFactory{ + return concreteFactory{ availableActions: map[string]Action{ // API "ping": NewPing(), @@ -92,7 +92,6 @@ func NewFactory( "sync_dns_with_signed_url": NewSyncDNSWithSignedURL(settingsService, platform, logger, blobstoreDelegator), }, } - return } func (f concreteFactory) Create(method string) (Action, error) { diff --git a/agent/action/drain.go b/agent/action/drain.go index dca7e52f8..9f595c0a3 100644 --- a/agent/action/drain.go +++ b/agent/action/drain.go @@ -79,10 +79,9 @@ func (a DrainAction) Run(drainType DrainType, newSpecs ...boshas.V1ApplySpec) (i if err != nil { return 0, bosherr.WrapError(err, "Unmonitoring services") } - //TODO write health.json - - var scripts []boshscript.Script + // TODO write health.json + scripts := make([]boshscript.Script, 0, len(currentSpec.Jobs())) for _, job := range currentSpec.Jobs() { script := a.jobScriptProvider.NewDrainScript(job.BundleName(), params) scripts = append(scripts, script) diff --git a/agent/action/fetch_logs.go b/agent/action/fetch_logs.go index 921ba7675..830028a81 100644 --- a/agent/action/fetch_logs.go +++ b/agent/action/fetch_logs.go @@ -41,7 +41,8 @@ func (a FetchLogsAction) IsLoggable() bool { return true } -func (a FetchLogsAction) Run(logType string, filters []string) (value map[string]string, err error) { +func (a FetchLogsAction) Run(logType string, filters []string) (map[string]string, error) { + value := map[string]string{} var logsDir string switch logType { @@ -56,22 +57,19 @@ func (a FetchLogsAction) Run(logType string, filters []string) (value map[string } logsDir = a.settingsDir.AgentLogsDir() default: - err = bosherr.Error("Invalid log type") - return + return value, bosherr.Error("Invalid log type") } tmpDir, err := a.copier.FilteredCopyToTemp(logsDir, filters) if err != nil { - err = bosherr.WrapError(err, "Copying filtered files to temp directory") - return + return value, bosherr.WrapError(err, "Copying filtered files to temp directory") } defer a.copier.CleanUp(tmpDir) tarball, err := a.compressor.CompressFilesInDir(tmpDir) if err != nil { - err = bosherr.WrapError(err, "Making logs tarball") - return + return value, bosherr.WrapError(err, "Making logs tarball") } defer func() { @@ -80,12 +78,11 @@ func (a FetchLogsAction) Run(logType string, filters []string) (value map[string blobID, multidigestSha, err := a.blobstore.Write("", tarball, nil) if err != nil { - err = bosherr.WrapError(err, "Create file on blobstore") - return + return value, bosherr.WrapError(err, "Create file on blobstore") } value = map[string]string{"blobstore_id": blobID, "sha1": multidigestSha.String()} - return + return value, nil } func (a FetchLogsAction) Resume() (interface{}, error) { diff --git a/agent/action/list_disk.go b/agent/action/list_disk.go index bd5ab0e23..db7b35177 100644 --- a/agent/action/list_disk.go +++ b/agent/action/list_disk.go @@ -27,11 +27,7 @@ func NewListDisk( } func (a ListDiskAction) IsAsynchronous(version ProtocolVersion) bool { - if version >= 3 { - return true - } - - return false + return version >= 3 } func (a ListDiskAction) IsPersistent() bool { diff --git a/agent/action/mount_disk.go b/agent/action/mount_disk.go index 62d295908..0e2202efd 100644 --- a/agent/action/mount_disk.go +++ b/agent/action/mount_disk.go @@ -3,7 +3,6 @@ package action import ( "errors" - boshdpresolv "github.com/cloudfoundry/bosh-agent/infrastructure/devicepathresolver" boshsettings "github.com/cloudfoundry/bosh-agent/settings" boshdirs "github.com/cloudfoundry/bosh-agent/settings/directories" bosherr "github.com/cloudfoundry/bosh-utils/errors" @@ -16,11 +15,10 @@ type diskMounter interface { } type MountDiskAction struct { - settingsService boshsettings.Service - diskMounter diskMounter - devicePathResolver boshdpresolv.DevicePathResolver - dirProvider boshdirs.Provider - logger boshlog.Logger + settingsService boshsettings.Service + diskMounter diskMounter + dirProvider boshdirs.Provider + logger boshlog.Logger } func NewMountDisk( @@ -81,12 +79,3 @@ func (a MountDiskAction) Resume() (interface{}, error) { func (a MountDiskAction) Cancel() error { return errors.New("not supported") } - -func (a MountDiskAction) pruneNil(hints []interface{}) []interface{} { - for i := len(hints) - 1; i >= 0; i-- { - if hints[i] == nil { - hints = append(hints[:i], hints[i+1:]...) - } - } - return hints -} diff --git a/agent/action/release_apply_spec.go b/agent/action/release_apply_spec.go index 8354088ca..1c1e1dc31 100644 --- a/agent/action/release_apply_spec.go +++ b/agent/action/release_apply_spec.go @@ -37,7 +37,7 @@ func (a ReleaseApplySpecAction) Run() (value interface{}, err error) { return } - err = json.Unmarshal([]byte(specBytes), &value) + err = json.Unmarshal(specBytes, &value) if err != nil { err = bosherr.WrapError(err, "Unmarshalling release apply spec") return diff --git a/agent/action/run_script.go b/agent/action/run_script.go index 96326a4f9..7a398b05d 100644 --- a/agent/action/run_script.go +++ b/agent/action/run_script.go @@ -56,7 +56,7 @@ func (a RunScriptAction) Run(scriptName string, options RunScriptOptions) (map[s return emptyResults, bosherr.WrapError(err, "Getting current spec") } - var scripts []boshscript.Script + scripts := make([]boshscript.Script, 0, len(currentSpec.Jobs())) for _, job := range currentSpec.Jobs() { script := a.scriptProvider.NewScript(job.BundleName(), scriptName, options.Env) scripts = append(scripts, script) diff --git a/agent/action/runner.go b/agent/action/runner.go index ef3e1d30a..9b5f7ac2a 100644 --- a/agent/action/runner.go +++ b/agent/action/runner.go @@ -88,7 +88,8 @@ func (r concreteRunner) invalidReturnTypes(methodType reflect.Type) (valid bool) return } -func (r concreteRunner) extractMethodArgs(runMethodType reflect.Type, protocolVersion ProtocolVersion, args []interface{}) (methodArgs []reflect.Value, err error) { +func (r concreteRunner) extractMethodArgs(runMethodType reflect.Type, protocolVersion ProtocolVersion, args []interface{}) ([]reflect.Value, error) { + methodArgs := []reflect.Value{} numberOfArgs := runMethodType.NumIn() numberOfReqArgs := numberOfArgs @@ -109,16 +110,14 @@ func (r concreteRunner) extractMethodArgs(runMethodType reflect.Type, protocolVe } if len(args) < numberOfReqArgs { - err = bosherr.Errorf("Not enough arguments, expected %d, got %d", numberOfReqArgs, len(args)) - return + return methodArgs, bosherr.Errorf("Not enough arguments, expected %d, got %d", numberOfReqArgs, len(args)) } for i, argFromPayload := range args { var rawArgBytes []byte - rawArgBytes, err = json.Marshal(argFromPayload) + rawArgBytes, err := json.Marshal(argFromPayload) if err != nil { - err = bosherr.WrapError(err, "Marshalling action argument") - return + return methodArgs, bosherr.WrapError(err, "Marshalling action argument") } argType, typeFound := r.getMethodArgType(runMethodType, i+argsOffset) @@ -130,14 +129,13 @@ func (r concreteRunner) extractMethodArgs(runMethodType reflect.Type, protocolVe err = json.Unmarshal(rawArgBytes, argValuePtr.Interface()) if err != nil { - err = bosherr.WrapError(err, "Unmarshalling action argument") - return + return methodArgs, bosherr.WrapError(err, "Unmarshalling action argument") } methodArgs = append(methodArgs, reflect.Indirect(argValuePtr)) } - return + return methodArgs, nil } func (r concreteRunner) getMethodArgType(methodType reflect.Type, index int) (argType reflect.Type, found bool) { diff --git a/agent/action/shutdown.go b/agent/action/shutdown.go index 1a8f778ef..b432a5bd4 100644 --- a/agent/action/shutdown.go +++ b/agent/action/shutdown.go @@ -29,8 +29,8 @@ func (a ShutdownAction) IsLoggable() bool { } func (a ShutdownAction) Run() (string, error) { - a.platform.Shutdown() - return "", nil + err := a.platform.Shutdown() + return "", err } func (a ShutdownAction) Resume() (interface{}, error) { diff --git a/agent/action/upload_blob.go b/agent/action/upload_blob.go index 1c233451e..3852a193c 100644 --- a/agent/action/upload_blob.go +++ b/agent/action/upload_blob.go @@ -38,7 +38,6 @@ func (a UploadBlobAction) IsLoggable() bool { } func (a UploadBlobAction) Run(content UploadBlobSpec) (string, error) { - decodedPayload, err := base64.StdEncoding.DecodeString(content.Payload) if err != nil { return content.BlobID, err diff --git a/agent/agent.go b/agent/agent.go index 904b7556c..46327ef34 100644 --- a/agent/agent.go +++ b/agent/agent.go @@ -23,7 +23,8 @@ const ( ) var ( - HeartbeatRetryInterval = 1 * time.Second + // HeartbeatRetryInterval TODO: remove 'nolint:gochecknoglobals' - should be passed in rather than re-defined in agent_test.go + HeartbeatRetryInterval = 1 * time.Second //nolint:gochecknoglobals ) //go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 . StartManager @@ -119,9 +120,10 @@ func (a Agent) generateHeartbeats(errCh chan error) { // Send initial heartbeat a.sendAndRecordHeartbeat(errCh, false) - tickChan := time.Tick(a.heartbeatInterval) + // Violates staticcheck SA1015 - probably fine since heartbeats are endless + tickChan := time.Tick(a.heartbeatInterval) //nolint:staticcheck - for { + for { //nolint:gosimple select { case <-tickChan: a.sendAndRecordHeartbeat(errCh, true) diff --git a/agent/alert/monit_adapter.go b/agent/alert/monit_adapter.go index bd196328e..55767974a 100644 --- a/agent/alert/monit_adapter.go +++ b/agent/alert/monit_adapter.go @@ -71,93 +71,93 @@ func (m *monitAdapter) createdAt() int64 { } func (m *monitAdapter) Severity() (severity SeverityLevel, found bool) { + var eventToSeverity = map[string]SeverityLevel{ // located inside Severity() so as not to create a global + "action done": SeverityIgnored, + "checksum failed": SeverityCritical, + "checksum changed": SeverityWarning, + "checksum succeeded": SeverityIgnored, + "checksum not changed": SeverityIgnored, + "connection failed": SeverityAlert, + "connection succeeded": SeverityIgnored, + "connection changed": SeverityError, + "connection not changed": SeverityIgnored, + "content failed": SeverityError, + "content succeeded": SeverityIgnored, + "content match": SeverityIgnored, + "content doesn't match": SeverityError, + "data access error": SeverityError, + "data access succeeded": SeverityIgnored, + "data access changed": SeverityWarning, + "data access not changed": SeverityIgnored, + "execution failed": SeverityAlert, + "execution succeeded": SeverityIgnored, + "execution changed": SeverityWarning, + "execution not changed": SeverityIgnored, + "filesystem flags failed": SeverityError, + "filesystem flags succeeded": SeverityIgnored, + "filesystem flags changed": SeverityWarning, + "filesystem flags not changed": SeverityIgnored, + "gid failed": SeverityError, + "gid succeeded": SeverityIgnored, + "gid changed": SeverityWarning, + "gid not changed": SeverityIgnored, + "heartbeat failed": SeverityError, + "heartbeat succeeded": SeverityIgnored, + "heartbeat changed": SeverityWarning, + "heartbeat not changed": SeverityIgnored, + "icmp failed": SeverityCritical, + "icmp succeeded": SeverityIgnored, + "icmp changed": SeverityWarning, + "icmp not changed": SeverityIgnored, + "monit instance failed": SeverityAlert, + "monit instance succeeded": SeverityIgnored, + "monit instance changed": SeverityIgnored, + "monit instance not changed": SeverityIgnored, + "invalid type": SeverityError, + "type succeeded": SeverityIgnored, + "type changed": SeverityWarning, + "type not changed": SeverityIgnored, + "does not exist": SeverityAlert, + "exists": SeverityIgnored, + "existence changed": SeverityWarning, + "existence not changed": SeverityIgnored, + "permission failed": SeverityError, + "permission succeeded": SeverityIgnored, + "permission changed": SeverityWarning, + "permission not changed": SeverityIgnored, + "pid failed": SeverityCritical, + "pid succeeded": SeverityIgnored, + "pid changed": SeverityWarning, + "pid not changed": SeverityIgnored, + "ppid failed": SeverityCritical, + "ppid succeeded": SeverityIgnored, + "ppid changed": SeverityWarning, + "ppid not changed": SeverityIgnored, + "resource limit matched": SeverityError, + "resource limit succeeded": SeverityIgnored, + "resource limit changed": SeverityWarning, + "resource limit not changed": SeverityIgnored, + "size failed": SeverityError, + "size succeeded": SeverityIgnored, + "size changed": SeverityError, + "size not changed": SeverityIgnored, + "timeout": SeverityCritical, + "timeout recovery": SeverityIgnored, + "timeout changed": SeverityWarning, + "timeout not changed": SeverityIgnored, + "timestamp failed": SeverityError, + "timestamp succeeded": SeverityIgnored, + "timestamp changed": SeverityWarning, + "timestamp not changed": SeverityIgnored, + "uid failed": SeverityCritical, + "uid succeeded": SeverityIgnored, + "uid changed": SeverityWarning, + "uid not changed": SeverityIgnored, + } + severity, found = eventToSeverity[strings.ToLower(m.monitAlert.Event)] if !found { severity = SeverityDefault } return severity, found } - -var eventToSeverity = map[string]SeverityLevel{ - "action done": SeverityIgnored, - "checksum failed": SeverityCritical, - "checksum changed": SeverityWarning, - "checksum succeeded": SeverityIgnored, - "checksum not changed": SeverityIgnored, - "connection failed": SeverityAlert, - "connection succeeded": SeverityIgnored, - "connection changed": SeverityError, - "connection not changed": SeverityIgnored, - "content failed": SeverityError, - "content succeeded": SeverityIgnored, - "content match": SeverityIgnored, - "content doesn't match": SeverityError, - "data access error": SeverityError, - "data access succeeded": SeverityIgnored, - "data access changed": SeverityWarning, - "data access not changed": SeverityIgnored, - "execution failed": SeverityAlert, - "execution succeeded": SeverityIgnored, - "execution changed": SeverityWarning, - "execution not changed": SeverityIgnored, - "filesystem flags failed": SeverityError, - "filesystem flags succeeded": SeverityIgnored, - "filesystem flags changed": SeverityWarning, - "filesystem flags not changed": SeverityIgnored, - "gid failed": SeverityError, - "gid succeeded": SeverityIgnored, - "gid changed": SeverityWarning, - "gid not changed": SeverityIgnored, - "heartbeat failed": SeverityError, - "heartbeat succeeded": SeverityIgnored, - "heartbeat changed": SeverityWarning, - "heartbeat not changed": SeverityIgnored, - "icmp failed": SeverityCritical, - "icmp succeeded": SeverityIgnored, - "icmp changed": SeverityWarning, - "icmp not changed": SeverityIgnored, - "monit instance failed": SeverityAlert, - "monit instance succeeded": SeverityIgnored, - "monit instance changed": SeverityIgnored, - "monit instance not changed": SeverityIgnored, - "invalid type": SeverityError, - "type succeeded": SeverityIgnored, - "type changed": SeverityWarning, - "type not changed": SeverityIgnored, - "does not exist": SeverityAlert, - "exists": SeverityIgnored, - "existence changed": SeverityWarning, - "existence not changed": SeverityIgnored, - "permission failed": SeverityError, - "permission succeeded": SeverityIgnored, - "permission changed": SeverityWarning, - "permission not changed": SeverityIgnored, - "pid failed": SeverityCritical, - "pid succeeded": SeverityIgnored, - "pid changed": SeverityWarning, - "pid not changed": SeverityIgnored, - "ppid failed": SeverityCritical, - "ppid succeeded": SeverityIgnored, - "ppid changed": SeverityWarning, - "ppid not changed": SeverityIgnored, - "resource limit matched": SeverityError, - "resource limit succeeded": SeverityIgnored, - "resource limit changed": SeverityWarning, - "resource limit not changed": SeverityIgnored, - "size failed": SeverityError, - "size succeeded": SeverityIgnored, - "size changed": SeverityError, - "size not changed": SeverityIgnored, - "timeout": SeverityCritical, - "timeout recovery": SeverityIgnored, - "timeout changed": SeverityWarning, - "timeout not changed": SeverityIgnored, - "timestamp failed": SeverityError, - "timestamp succeeded": SeverityIgnored, - "timestamp changed": SeverityWarning, - "timestamp not changed": SeverityIgnored, - "uid failed": SeverityCritical, - "uid succeeded": SeverityIgnored, - "uid changed": SeverityWarning, - "uid not changed": SeverityIgnored, -} diff --git a/agent/applier/applyspec/concrete_v1_service.go b/agent/applier/applyspec/concrete_v1_service.go index 546fd9063..b146da1dd 100644 --- a/agent/applier/applyspec/concrete_v1_service.go +++ b/agent/applier/applyspec/concrete_v1_service.go @@ -30,7 +30,7 @@ func (s concreteV1Service) Get() (V1ApplySpec, error) { return spec, bosherr.WrapError(err, "Reading json spec file") } - err = json.Unmarshal([]byte(contents), &spec) + err = json.Unmarshal(contents, &spec) if err != nil { return spec, bosherr.WrapError(err, "Unmarshalling json spec file") } diff --git a/agent/applier/applyspec/rendered_templates_archive_spec.go b/agent/applier/applyspec/rendered_templates_archive_spec.go index fcd477614..c4eb79050 100644 --- a/agent/applier/applyspec/rendered_templates_archive_spec.go +++ b/agent/applier/applyspec/rendered_templates_archive_spec.go @@ -37,7 +37,6 @@ func (s *RenderedTemplatesArchiveSpec) UnmarshalJSON(data []byte) error { } if jsonStruct.BlobstoreID == "" && jsonStruct.Sha1 == "" { - s = nil return nil } diff --git a/agent/applier/bundlecollection/bundle_collection_interface.go b/agent/applier/bundlecollection/bundle_collection_interface.go index b244975f8..107c74fb5 100644 --- a/agent/applier/bundlecollection/bundle_collection_interface.go +++ b/agent/applier/bundlecollection/bundle_collection_interface.go @@ -7,7 +7,7 @@ type BundleDefinition interface { } type BundleCollection interface { - Get(defintion BundleDefinition) (bundle Bundle, err error) + Get(definition BundleDefinition) (bundle Bundle, err error) List() ([]Bundle, error) } diff --git a/agent/applier/bundlecollection/file_bundle_collection.go b/agent/applier/bundlecollection/file_bundle_collection.go index cf76170cb..97fe80097 100644 --- a/agent/applier/bundlecollection/file_bundle_collection.go +++ b/agent/applier/bundlecollection/file_bundle_collection.go @@ -111,13 +111,12 @@ func (bc FileBundleCollection) getDigested(definition BundleDefinition) (Bundle, } func (bc FileBundleCollection) List() ([]Bundle, error) { - var bundles []Bundle - bundleInstallPaths, err := bc.fs.Glob(path.Join(bc.installPath, bc.name, "*", "*")) if err != nil { - return bundles, bosherr.WrapError(err, "Globbing bundles") + return []Bundle{}, bosherr.WrapError(err, "Globbing bundles") } + bundles := make([]Bundle, 0, len(bundleInstallPaths)) for _, path := range bundleInstallPaths { bundle, err := bc.getDigested(newFileBundleDefinition(path)) if err != nil { diff --git a/agent/applier/concrete_applier.go b/agent/applier/concrete_applier.go index c134efb7b..816e3dfb9 100644 --- a/agent/applier/concrete_applier.go +++ b/agent/applier/concrete_applier.go @@ -39,7 +39,8 @@ func NewConcreteApplier( } func (a *concreteApplier) Prepare(desiredApplySpec as.ApplySpec) error { - var tasks []func() error + tasks := make([]func() error, 0, len(desiredApplySpec.Jobs())+len(desiredApplySpec.Packages())) + pool := work.Pool{ Count: *a.settings.Env.GetParallel(), } diff --git a/agent/applier/models/job.go b/agent/applier/models/job.go index 9a10669b2..9552f561c 100644 --- a/agent/applier/models/job.go +++ b/agent/applier/models/job.go @@ -1,8 +1,9 @@ package models import ( - bosherr "github.com/cloudfoundry/bosh-utils/errors" "os" + + bosherr "github.com/cloudfoundry/bosh-utils/errors" ) type Job struct { @@ -45,7 +46,7 @@ type JobDirectoryProvider interface { func (s Job) CreateDirectories(jobDirectoryCreator JobDirectoryCreator, jobDirProvider JobDirectoryProvider) error { if len(s.Name) < 1 { - return bosherr.Error("Job name cannot be emtpy") + return bosherr.Error("Job name cannot be empty") } dirs := []string{ diff --git a/agent/bootstrap.go b/agent/bootstrap.go index ca2a24483..556d24a1e 100644 --- a/agent/bootstrap.go +++ b/agent/bootstrap.go @@ -47,7 +47,7 @@ func NewBootstrap( } } -func (boot bootstrap) Run() (err error) { +func (boot bootstrap) Run() (err error) { //nolint:gocyclo if err = boot.platform.SetupRuntimeConfiguration(); err != nil { return bosherr.WrapError(err, "Setting up runtime configuration") } diff --git a/agent/compiler/concrete_compiler.go b/agent/compiler/concrete_compiler.go index f49ae690c..327e7a86f 100644 --- a/agent/compiler/concrete_compiler.go +++ b/agent/compiler/concrete_compiler.go @@ -1,11 +1,12 @@ package compiler import ( - "code.cloudfoundry.org/clock" "fmt" "os" "path" + "code.cloudfoundry.org/clock" + boshbc "github.com/cloudfoundry/bosh-agent/agent/applier/bundlecollection" boshmodels "github.com/cloudfoundry/bosh-agent/agent/applier/models" "github.com/cloudfoundry/bosh-agent/agent/applier/packages" diff --git a/agent/heartbeat.go b/agent/heartbeat.go index ee0d32e2a..223da39cb 100644 --- a/agent/heartbeat.go +++ b/agent/heartbeat.go @@ -16,23 +16,23 @@ type Heartbeat struct { NodeID string `json:"node_id"` } -//Heartbeat payload example: -//{ -// "job": "cloud_controller", -// "index": 3, -// "job_state":"running", -// "vitals": { -// "load": ["0.09","0.04","0.01"], -// "cpu": {"user":"0.0","sys":"0.0","wait":"0.4"}, -// "mem": {"percent":"3.5","kb":"145996"}, -// "swap": {"percent":"0.0","kb":"0"}, -// "disk": { -// "system": {"percent" => "82"}, -// "ephemeral": {"percent" => "5"}, -// "persistent": {"percent" => "94"} -// }, -// "ntp": { -// "offset": "-0.06423", -// "timestamp": "14 Oct 11:13:19" -// } -//} +// Heartbeat payload example: +// { +// "job": "cloud_controller", +// "index": 3, +// "job_state":"running", +// "vitals": { +// "load": ["0.09","0.04","0.01"], +// "cpu": {"user":"0.0","sys":"0.0","wait":"0.4"}, +// "mem": {"percent":"3.5","kb":"145996"}, +// "swap": {"percent":"0.0","kb":"0"}, +// "disk": { +// "system": {"percent" => "82"}, +// "ephemeral": {"percent" => "5"}, +// "persistent": {"percent" => "94"} +// }, +// "ntp": { +// "offset": "-0.06423", +// "timestamp": "14 Oct 11:13:19" +// } +// } diff --git a/agent/httpblobprovider/blobstore_delegator/blobstore_delegator.go b/agent/httpblobprovider/blobstore_delegator/blobstore_delegator.go index f13ac1b88..a92b23c6b 100644 --- a/agent/httpblobprovider/blobstore_delegator/blobstore_delegator.go +++ b/agent/httpblobprovider/blobstore_delegator/blobstore_delegator.go @@ -1,13 +1,14 @@ -package blobstore_delegator +package blobstore_delegator //nolint:revive import ( "fmt" + "time" + bosherr "github.com/cloudfoundry/bosh-utils/errors" boshlog "github.com/cloudfoundry/bosh-utils/logger" boshretry "github.com/cloudfoundry/bosh-utils/retrystrategy" - "time" - httpblobprovider "github.com/cloudfoundry/bosh-agent/agent/httpblobprovider" + "github.com/cloudfoundry/bosh-agent/agent/httpblobprovider" "github.com/cloudfoundry/bosh-utils/blobstore" boshcrypto "github.com/cloudfoundry/bosh-utils/crypto" ) diff --git a/agent/httpblobprovider/blobstore_delegator/blobstore_delegator_interface.go b/agent/httpblobprovider/blobstore_delegator/blobstore_delegator_interface.go index e35b905e3..04ba03f80 100644 --- a/agent/httpblobprovider/blobstore_delegator/blobstore_delegator_interface.go +++ b/agent/httpblobprovider/blobstore_delegator/blobstore_delegator_interface.go @@ -1,4 +1,4 @@ -package blobstore_delegator +package blobstore_delegator //nolint:revive import ( boshcrypto "github.com/cloudfoundry/bosh-utils/crypto" diff --git a/agent/httpblobprovider/http_blob_provider.go b/agent/httpblobprovider/http_blob_provider.go index c7fae4dff..6b1a63c9c 100644 --- a/agent/httpblobprovider/http_blob_provider.go +++ b/agent/httpblobprovider/http_blob_provider.go @@ -12,8 +12,6 @@ import ( boshsys "github.com/cloudfoundry/bosh-utils/system" ) -var DefaultCryptoAlgorithms = []boshcrypto.Algorithm{boshcrypto.DigestAlgorithmSHA1, boshcrypto.DigestAlgorithmSHA512} - type HTTPBlobImpl struct { fs boshsys.FileSystem createAlgorithms []boshcrypto.Algorithm @@ -21,6 +19,8 @@ type HTTPBlobImpl struct { } func NewHTTPBlobImpl(fs boshsys.FileSystem, httpClient *http.Client) *HTTPBlobImpl { + var DefaultCryptoAlgorithms = []boshcrypto.Algorithm{boshcrypto.DigestAlgorithmSHA1, boshcrypto.DigestAlgorithmSHA512} + return NewHTTPBlobImplWithDigestAlgorithms(fs, httpClient, DefaultCryptoAlgorithms) } @@ -50,7 +50,7 @@ func (h *HTTPBlobImpl) Upload(signedURL, filepath string, headers map[string]str return boshcrypto.MultipleDigest{}, err } - req, err := http.NewRequest("PUT", signedURL, file) + req, err := http.NewRequest("PUT", signedURL, file) //nolint:noctx if err != nil { defer file.Close() return boshcrypto.MultipleDigest{}, err @@ -59,10 +59,8 @@ func (h *HTTPBlobImpl) Upload(signedURL, filepath string, headers map[string]str req.Header.Set("Accept", "*/*") req.Header.Set("Expect", "100-continue") - if headers != nil { - for k, v := range headers { - req.Header.Set(k, v) - } + for k, v := range headers { + req.Header.Set(k, v) } req.ContentLength = stat.Size() @@ -84,16 +82,14 @@ func (h *HTTPBlobImpl) Get(signedURL string, digest boshcrypto.Digest, headers m return "", bosherr.WrapError(err, "Creating temporary file") } - req, err := http.NewRequest("GET", signedURL, strings.NewReader("")) + req, err := http.NewRequest("GET", signedURL, strings.NewReader("")) //nolint:noctx if err != nil { defer file.Close() return "", bosherr.WrapError(err, "Creating Get Request") } - if headers != nil { - for k, v := range headers { - req.Header.Set(k, v) - } + for k, v := range headers { + req.Header.Set(k, v) } resp, err := h.httpClient.Do(req) diff --git a/agent/script/drain/concrete_script.go b/agent/script/drain/concrete_script.go index 46c65bab4..cc029ff28 100644 --- a/agent/script/drain/concrete_script.go +++ b/agent/script/drain/concrete_script.go @@ -65,7 +65,9 @@ func (s ConcreteScript) Run() error { value, err := s.runOnce(params) if err != nil { return err - } else if value < 0 { + } + + if value < 0 { s.timeService.Sleep(time.Duration(-value) * time.Second) params = params.ToStatusParams() } else { diff --git a/agent/script/parallel_script.go b/agent/script/parallel_script.go index d341b7b1b..a72c96f28 100644 --- a/agent/script/parallel_script.go +++ b/agent/script/parallel_script.go @@ -49,17 +49,15 @@ func (s ParallelScript) Run() error { var failedScripts, passedScripts []string for i := 0; i < len(existingScripts); i++ { - select { - case r := <-resultsChan: - jobName := r.Script.Tag() - - if r.Error == nil { - passedScripts = append(passedScripts, jobName) - s.logger.Info(s.logTag, "'%s' script has successfully executed", r.Script.Path()) - } else { - failedScripts = append(failedScripts, jobName) - s.logger.Error(s.logTag, "'%s' script has failed with error: %s", r.Script.Path(), r.Error) - } + r := <-resultsChan + jobName := r.Script.Tag() + + if r.Error == nil { + passedScripts = append(passedScripts, jobName) + s.logger.Info(s.logTag, "'%s' script has successfully executed", r.Script.Path()) + } else { + failedScripts = append(failedScripts, jobName) + s.logger.Error(s.logTag, "'%s' script has failed with error: %s", r.Script.Path(), r.Error) } } @@ -73,7 +71,7 @@ func (s ParallelScript) Cancel() error { if script, ok := script.(CancellableScript); ok { err := script.Cancel() if err != nil { - bosherr.WrapErrorf(err, "'%s' script did not cancel", s.name) + return bosherr.WrapErrorf(err, "'%s' script did not cancel", s.name) } } else { return bosherr.Errorf("Script %s is not cancellable", s.name) diff --git a/agent/task/concrete_manager.go b/agent/task/concrete_manager.go index f167263a4..70a1b8e9f 100644 --- a/agent/task/concrete_manager.go +++ b/agent/task/concrete_manager.go @@ -66,7 +66,7 @@ func (m *concreteManager) GetInfos() ([]Info, error) { return nil, err } - var r []Info + r := make([]Info, 0, len(taskInfos)) for _, taskInfo := range taskInfos { r = append(r, taskInfo) } diff --git a/agent/utils/agent_killer.go b/agent/utils/agent_killer.go index ea09e339f..f001c2ccf 100644 --- a/agent/utils/agent_killer.go +++ b/agent/utils/agent_killer.go @@ -23,6 +23,4 @@ func (a AgentKiller) KillAgent() { // this gives a bit of time for the director to learn about the task time.Sleep(1 * time.Second) os.Exit(0) - - return } diff --git a/agentclient/http/agent_client.go b/agentclient/http/agent_client.go index 78afb89e8..01c3e2ccb 100644 --- a/agentclient/http/agent_client.go +++ b/agentclient/http/agent_client.go @@ -239,7 +239,7 @@ func (c *AgentClient) SendAsyncTaskMessage(method string, arguments []interface{ sendErrors++ shouldRetry := sendErrors <= c.toleratedErrorCount err = bosherr.WrapError(err, "Sending 'get_task' to the agent") - c.logger.Debug(c.logTag, "Error occured sending get_task. Error retry %d of %d: %s", sendErrors, c.toleratedErrorCount, err.Error()) + c.logger.Debug(c.logTag, "Error occurred sending get_task. Error retry %d of %d: %s", sendErrors, c.toleratedErrorCount, err.Error()) return shouldRetry, err } sendErrors = 0 diff --git a/agentclient/ping_retryable.go b/agentclient/ping_retryable.go index aff46ee4a..bc02409d7 100644 --- a/agentclient/ping_retryable.go +++ b/agentclient/ping_retryable.go @@ -28,7 +28,7 @@ func (r *pingRetryable) Attempt() (bool, error) { break } } - r, _ := regexp.Compile("x509: ") + r := regexp.MustCompile("x509: ") if r.MatchString(err.Error()) { return false, err } diff --git a/ci/pipeline.yml b/ci/pipeline.yml index f994068ee..1062e7fb9 100644 --- a/ci/pipeline.yml +++ b/ci/pipeline.yml @@ -228,6 +228,15 @@ jobs: - task: test-unit file: bosh-agent/ci/tasks/test-unit.yml + - name: golangci-lint + plan: + - get: bosh-agent + trigger: true + - task: golangci-lint + file: bosh-agent/ci/tasks/golangci-lint.yml + params: + GOLANGCI_LINT_VERSION: v1.45.0 + - name: test-unit-windows serial: true plan: diff --git a/infrastructure/devicepathresolver/iscsi_device_path_resolver.go b/infrastructure/devicepathresolver/iscsi_device_path_resolver.go index edaa5f99f..cbf6f10d0 100644 --- a/infrastructure/devicepathresolver/iscsi_device_path_resolver.go +++ b/infrastructure/devicepathresolver/iscsi_device_path_resolver.go @@ -139,12 +139,11 @@ func (ispr iscsiDevicePathResolver) getMappedDevices() ([]string, error) { // a "–part1" suffix device based on origin multipath device // last mounted disk already have this device, new disk doesn't have this device yet func (ispr iscsiDevicePathResolver) getDevicePaths(devices []string, shouldExist bool) ([]string, error) { + var partitionRegexp = regexp.MustCompile("-part1") var paths []string + for _, device := range devices { - exist, err := regexp.MatchString("-part1", device) - if err != nil { - return paths, bosherr.WrapError(err, "There is a problem with your regexp: '-part1'. That is used to find existing device") - } + exist := partitionRegexp.MatchString(device) if exist == shouldExist { matchedPath := path.Join("/dev/mapper", strings.Split(strings.Fields(device)[0], "-")[0]) ispr.logger.Debug(ispr.logTag, "path in device list: '%+v'", matchedPath) diff --git a/infrastructure/devicepathresolver/mapped_device_path_resolver.go b/infrastructure/devicepathresolver/mapped_device_path_resolver.go index 3376f77c2..b1a55ba4e 100644 --- a/infrastructure/devicepathresolver/mapped_device_path_resolver.go +++ b/infrastructure/devicepathresolver/mapped_device_path_resolver.go @@ -55,7 +55,7 @@ func (dpr mappedDevicePathResolver) GetRealDevicePath(diskSettings boshsettings. func (dpr mappedDevicePathResolver) findPossibleDevice(devicePath string) (string, bool, error) { needsMapping := strings.HasPrefix(devicePath, "/dev/sd") - if needsMapping { + if needsMapping { //nolint:nestif pathSuffix := strings.Split(devicePath, "/dev/sd")[1] possiblePrefixes := []string{ diff --git a/infrastructure/devicepathresolver/scsi_volume_id_device_path_resolver.go b/infrastructure/devicepathresolver/scsi_volume_id_device_path_resolver.go index f444480a4..f04640e21 100644 --- a/infrastructure/devicepathresolver/scsi_volume_id_device_path_resolver.go +++ b/infrastructure/devicepathresolver/scsi_volume_id_device_path_resolver.go @@ -6,6 +6,8 @@ import ( "strings" "time" + bosherr "github.com/cloudfoundry/bosh-utils/errors" + boshsettings "github.com/cloudfoundry/bosh-agent/settings" boshsys "github.com/cloudfoundry/bosh-utils/system" ) @@ -27,10 +29,10 @@ func NewSCSIVolumeIDDevicePathResolver( } } -func (devicePathResolver SCSIVolumeIDDevicePathResolver) GetRealDevicePath(diskSettings boshsettings.DiskSettings) (realPath string, timedOut bool, err error) { +func (devicePathResolver SCSIVolumeIDDevicePathResolver) GetRealDevicePath(diskSettings boshsettings.DiskSettings) (string, bool, error) { devicePaths, err := devicePathResolver.fs.Glob("/sys/bus/scsi/devices/*:0:0:0/block/*") if err != nil { - return + return "", false, err } var hostID string @@ -51,13 +53,13 @@ func (devicePathResolver SCSIVolumeIDDevicePathResolver) GetRealDevicePath(diskS } if len(hostID) == 0 { - return + return "", false, bosherr.Error("Zero length hostID") } scanPath := fmt.Sprintf("/sys/class/scsi_host/host%s/scan", hostID) err = devicePathResolver.fs.WriteFileString(scanPath, "- - -") if err != nil { - return + return "", false, err } deviceGlobPath := fmt.Sprintf("/sys/bus/scsi/devices/%s:0:%s:0/block/*", hostID, volumeID) @@ -72,12 +74,16 @@ func (devicePathResolver SCSIVolumeIDDevicePathResolver) GetRealDevicePath(diskS } } - if err != nil || len(devicePaths) == 0 { - return + if err != nil { + return "", false, err + } + + if len(devicePaths) == 0 { + return "", false, nil // see infrastructure/devicepathresolver/scsi_volume_id_device_path_resolver_test.go:102 } basename := path.Base(devicePaths[0]) - realPath = path.Join("/dev/", basename) + realPath := path.Join("/dev/", basename) - return + return realPath, false, nil } diff --git a/infrastructure/dig_dns_resolver.go b/infrastructure/dig_dns_resolver.go index f03c76c5a..b4a44596b 100644 --- a/infrastructure/dig_dns_resolver.go +++ b/infrastructure/dig_dns_resolver.go @@ -11,8 +11,6 @@ import ( boshsys "github.com/cloudfoundry/bosh-utils/system" ) -const digDNSResolverLogTag = "Dig DNS Resolver" - type DigDNSResolver struct { runner boshsys.CmdRunner logger boshlog.Logger diff --git a/infrastructure/file_metadata_service.go b/infrastructure/file_metadata_service.go index b909e07b4..cb9702e8c 100644 --- a/infrastructure/file_metadata_service.go +++ b/infrastructure/file_metadata_service.go @@ -52,7 +52,7 @@ func (ms fileMetadataService) GetPublicKey() (string, error) { return "", bosherr.WrapError(err, "Reading metadata file") } - err = json.Unmarshal([]byte(contents), &p) + err = json.Unmarshal(contents, &p) if err != nil { return "", bosherr.WrapError(err, "Unmarshalling metadata") } @@ -68,7 +68,7 @@ func (ms fileMetadataService) GetInstanceID() (string, error) { return "", bosherr.WrapError(err, "Reading metadata file") } - err = json.Unmarshal([]byte(contents), &metadata) + err = json.Unmarshal(contents, &metadata) if err != nil { return "", bosherr.WrapError(err, "Unmarshalling metadata") } @@ -86,7 +86,7 @@ func (ms fileMetadataService) GetServerName() (string, error) { return "", bosherr.WrapError(err, "Reading user data") } - err = json.Unmarshal([]byte(contents), &userData) + err = json.Unmarshal(contents, &userData) if err != nil { return "", bosherr.WrapError(err, "Unmarshalling user data") } @@ -106,7 +106,7 @@ func (ms fileMetadataService) GetRegistryEndpoint() (string, error) { return ms.settingsFilePath, nil } - err = json.Unmarshal([]byte(contents), &userData) + err = json.Unmarshal(contents, &userData) if err != nil { return "", bosherr.WrapError(err, "Unmarshalling user data") } @@ -124,7 +124,7 @@ func (ms fileMetadataService) GetNetworks() (boshsettings.Networks, error) { return nil, bosherr.WrapError(err, "Reading user data") } - err = json.Unmarshal([]byte(contents), &userData) + err = json.Unmarshal(contents, &userData) if err != nil { return nil, bosherr.WrapError(err, "Unmarshalling user data") } @@ -142,7 +142,7 @@ func (ms fileMetadataService) GetSettings() (boshsettings.Settings, error) { return boshsettings.Settings{}, bosherr.WrapError(err, "Reading user data") } - err = json.Unmarshal([]byte(contents), &userData) + err = json.Unmarshal(contents, &userData) if err != nil { return boshsettings.Settings{}, bosherr.WrapError(err, "Unmarshalling user data") } diff --git a/infrastructure/file_registry.go b/infrastructure/file_registry.go index 7eda2cae0..6aa5091b0 100644 --- a/infrastructure/file_registry.go +++ b/infrastructure/file_registry.go @@ -28,7 +28,7 @@ func (r *fileRegistry) GetSettings() (boshsettings.Settings, error) { return settings, bosherr.WrapError(err, "Read settings file") } - err = json.Unmarshal([]byte(contents), &settings) + err = json.Unmarshal(contents, &settings) if err != nil { return settings, bosherr.WrapError(err, "Unmarshal json settings") } diff --git a/infrastructure/http_metadata_service.go b/infrastructure/http_metadata_service.go index 2ec0e4d3a..b2784dac5 100644 --- a/infrastructure/http_metadata_service.go +++ b/infrastructure/http_metadata_service.go @@ -279,13 +279,13 @@ func (ms HTTPMetadataService) getUserData() (UserDataContentsType, error) { err = json.Unmarshal(userDataBytes, &userData) if err != nil { - userDataBytesWithoutQuotes := strings.Replace(string(userDataBytes), `"`, ``, -1) + userDataBytesWithoutQuotes := strings.ReplaceAll(string(userDataBytes), `"`, ``) decodedUserData, err := base64.RawURLEncoding.DecodeString(userDataBytesWithoutQuotes) if err != nil { return userData, bosherr.WrapError(err, "Decoding url encoded user data") } - err = json.Unmarshal([]byte(decodedUserData), &userData) + err = json.Unmarshal(decodedUserData, &userData) if err != nil { return userData, bosherr.WrapErrorf(err, "Unmarshalling url decoded user data '%s'", decodedUserData) } @@ -318,10 +318,6 @@ func (ms HTTPMetadataService) ensureMinimalNetworkSetup() error { return nil } -func (ms HTTPMetadataService) addHeaders() func(*http.Request) { - return ms.addHeadersWithToken("") -} - func (ms HTTPMetadataService) addHeadersWithToken(imdsToken string) func(*http.Request) { return func(req *http.Request) { for key, value := range ms.metadataHeaders { @@ -367,7 +363,6 @@ func (ms HTTPMetadataService) getToken() (token string, err error) { } return string(bytes), nil - } func createRetryClient(delay time.Duration, logger boshlog.Logger) *httpclient.HTTPClient { diff --git a/infrastructure/settings_source_factory.go b/infrastructure/settings_source_factory.go index 4ed9e2ff2..5eb8f66d0 100644 --- a/infrastructure/settings_source_factory.go +++ b/infrastructure/settings_source_factory.go @@ -100,11 +100,10 @@ func (f SettingsSourceFactory) New() (boshsettings.Source, error) { } func (f SettingsSourceFactory) buildWithRegistry() (boshsettings.Source, error) { - var metadataServices []MetadataService - digDNSResolver := NewDigDNSResolver(f.platform.GetRunner(), f.logger) resolver := NewRegistryEndpointResolver(digDNSResolver) + metadataServices := make([]MetadataService, 0, len(f.options.Sources)) for _, opts := range f.options.Sources { var metadataService MetadataService @@ -158,8 +157,7 @@ func (f SettingsSourceFactory) buildWithRegistry() (boshsettings.Source, error) } func (f SettingsSourceFactory) buildWithoutRegistry() (boshsettings.Source, error) { - var settingsSources []boshsettings.Source - + settingsSources := make([]boshsettings.Source, 0, len(f.options.Sources)) for _, opts := range f.options.Sources { var settingsSource boshsettings.Source diff --git a/integration/utils/blobstore.go b/integration/utils/blobstore.go index 494d22404..92907add5 100644 --- a/integration/utils/blobstore.go +++ b/integration/utils/blobstore.go @@ -1,12 +1,13 @@ package utils import ( - "github.com/cloudfoundry/bosh-agent/integration/windows/utils" "io" "net/http" "os" "time" + "github.com/cloudfoundry/bosh-agent/integration/windows/utils" + davclient "github.com/cloudfoundry/bosh-davcli/client" davconfig "github.com/cloudfoundry/bosh-davcli/config" boshlog "github.com/cloudfoundry/bosh-utils/logger" diff --git a/integration/utils/nats_client.go b/integration/utils/nats_client.go index b546a6889..979c05e72 100644 --- a/integration/utils/nats_client.go +++ b/integration/utils/nats_client.go @@ -9,7 +9,6 @@ import ( "encoding/json" "encoding/pem" "fmt" - "github.com/cloudfoundry/bosh-agent/integration/windows/utils" "io/ioutil" "os" "path/filepath" @@ -17,6 +16,8 @@ import ( "text/template" "time" + "github.com/cloudfoundry/bosh-agent/integration/windows/utils" + "golang.org/x/crypto/ssh" "github.com/cloudfoundry/bosh-agent/agent/action" diff --git a/integration/windows/fixtures/templates/execution-lock/hibernate.go b/integration/windows/fixtures/templates/execution-lock/hibernate.go index 43f72f3ed..677fe8c19 100644 --- a/integration/windows/fixtures/templates/execution-lock/hibernate.go +++ b/integration/windows/fixtures/templates/execution-lock/hibernate.go @@ -29,7 +29,7 @@ func main() { // Many pointless ways to achieve the same thing, while adding more and more dependencies if err != nil && strings.Contains(message, strconv.Itoa(i)) && matcher.Match(messageBytes) { - fmt.Printf(message) + fmt.Print(message) } else { failedMatchErr := errors.New("this is bad") fmt.Println(failedMatchErr.Error()) diff --git a/integration/windows/utils/agent.go b/integration/windows/utils/agent.go index 7548b4ab4..6030b58db 100644 --- a/integration/windows/utils/agent.go +++ b/integration/windows/utils/agent.go @@ -2,13 +2,14 @@ package utils import ( "fmt" - "golang.org/x/crypto/ssh" "io/ioutil" "os" "os/exec" "path/filepath" "time" + "golang.org/x/crypto/ssh" + "bytes" "regexp" @@ -52,7 +53,7 @@ func RetrievePrivateIP(vmName string) (string, error) { } gomega.Eventually(session, 20*time.Second).Should(gexec.Exit(0)) - privateIPMatcher, err := regexp.Compile(`^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}`) + privateIPMatcher := regexp.MustCompile(`^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}`) return privateIPMatcher.FindString(stdout.String()), nil } @@ -65,7 +66,7 @@ func RetrievePublicIP(vmName string) (string, error) { } gomega.Eventually(session, 20*time.Second).Should(gexec.Exit(0)) - hostnameMatcher, err := regexp.Compile(`HostName\s([a-zA-Z0-9\.-]*)\n`) + hostnameMatcher := regexp.MustCompile(`HostName\s([a-zA-Z0-9\.-]*)\n`) return hostnameMatcher.FindStringSubmatch(stdout.String())[1], nil } @@ -143,5 +144,9 @@ func GetSSHTunnelClient() (*ssh.Client, error) { Auth: []ssh.AuthMethod{ssh.PublicKeys(signer)}, HostKeyCallback: ssh.InsecureIgnoreHostKey(), }) + if err != nil { + return nil, err + } + return sshClient, nil } diff --git a/jobsupervisor/alert_envelope.go b/jobsupervisor/alert_envelope.go index d4c975e5a..37146d588 100644 --- a/jobsupervisor/alert_envelope.go +++ b/jobsupervisor/alert_envelope.go @@ -19,11 +19,7 @@ type alertEnvelope struct { func (e *alertEnvelope) Write(lineBytes []byte) (err error) { line := strings.TrimSpace(string(lineBytes)) - idRegexp, err := regexp.Compile("^Message-id: <([^>]+)>$") - if err != nil { - return - } - + idRegexp := regexp.MustCompile("^Message-id: <([^>]+)>$") idMatches := idRegexp.FindStringSubmatch(line) switch { diff --git a/jobsupervisor/monit/http_client.go b/jobsupervisor/monit/http_client.go index ee0905bf5..d07d79a93 100644 --- a/jobsupervisor/monit/http_client.go +++ b/jobsupervisor/monit/http_client.go @@ -182,7 +182,7 @@ func (c httpClient) validateResponse(response *http.Response) error { func (c httpClient) makeRequest(client HTTPClient, target url.URL, method, requestBody string) (*http.Response, error) { c.logger.Debug("http-client", "Monit request: url='%s' body='%s'", target.String(), requestBody) - request, err := http.NewRequest(method, target.String(), strings.NewReader(requestBody)) + request, err := http.NewRequest(method, target.String(), strings.NewReader(requestBody)) //nolint:noctx if err != nil { return nil, err } diff --git a/jobsupervisor/monit/monit_retry_strategy.go b/jobsupervisor/monit/monit_retry_strategy.go index bdfca01ae..2ffdfef2a 100644 --- a/jobsupervisor/monit/monit_retry_strategy.go +++ b/jobsupervisor/monit/monit_retry_strategy.go @@ -57,21 +57,21 @@ func (m *monitRetryStrategy) Try() error { break } - is503 := m.retryable.Response() != nil && m.retryable.Response().StatusCode == 503 + is503 := m.retryable.Response() != nil && m.retryable.Response().StatusCode == 503 //nolint:bodyclose isCanceled := err != nil && strings.Contains(err.Error(), "request canceled") if (is503 || isCanceled) && m.unavailableAttempts < m.maxUnavailableAttempts { - m.unavailableAttempts = m.unavailableAttempts + 1 + m.unavailableAttempts++ } else { // once a non-503 error is received, all errors count as 'other' errors m.unavailableAttempts = m.maxUnavailableAttempts + 1 - m.otherAttempts = m.otherAttempts + 1 + m.otherAttempts++ } m.timeService.Sleep(m.delay) } - if err != nil && m.retryable.Response() != nil { + if err != nil && m.retryable.Response() != nil { //nolint:bodyclose _ = m.retryable.Response().Body.Close() } diff --git a/jobsupervisor/monitor/disk.go b/jobsupervisor/monitor/disk.go deleted file mode 100644 index 5ad2c0041..000000000 --- a/jobsupervisor/monitor/disk.go +++ /dev/null @@ -1,69 +0,0 @@ -//go:build windows -// +build windows - -package monitor - -import ( - "fmt" - "syscall" - "unsafe" -) - -var ( - // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364935(v=vs.85).aspx - procGetDiskFreeSpace = kernel32DLL.MustFindProc("GetDiskFreeSpaceW") -) - -type DiskUsage struct { - Total Byte - Used Byte -} - -func (d *DiskUsage) Percent() float64 { - if d.Total > 0 { - return float64(d.Used) / float64(d.Total) - } - return 0 -} - -func newDiskUsage(u diskUsage) DiskUsage { - m := uint64(u.SectorsPerCluster * u.BytesPerSector) - total := uint64(u.TotalNumberOfClusters) * m - used := total - (uint64(u.NumberOfFreeClusters) * m) - return DiskUsage{ - Total: Byte(total), - Used: Byte(used), - } -} - -type diskUsage struct { - SectorsPerCluster uint32 - BytesPerSector uint32 - NumberOfFreeClusters uint32 - TotalNumberOfClusters uint32 -} - -func UsedDiskSpace(name string) (DiskUsage, error) { - u, err := getDiskFreeSpace(name) - return newDiskUsage(u), err -} - -func getDiskFreeSpace(name string) (diskUsage, error) { - var u diskUsage - root, err := syscall.UTF16PtrFromString(name) - if err != nil { - return u, fmt.Errorf("UsedDiskSpace (%s): %s", name, err) - } - r1, _, e1 := syscall.Syscall6(procGetDiskFreeSpace.Addr(), 5, - uintptr(unsafe.Pointer(root)), - uintptr(unsafe.Pointer(&u.SectorsPerCluster)), - uintptr(unsafe.Pointer(&u.BytesPerSector)), - uintptr(unsafe.Pointer(&u.NumberOfFreeClusters)), - uintptr(unsafe.Pointer(&u.TotalNumberOfClusters)), - 0, - ) - if err := checkErrno(r1, e1); err != nil { - return u, fmt.Errorf("UsedDiskSpace (%s): %s", name, err) - } - return u, nil -} diff --git a/jobsupervisor/monitor/disk_test.go b/jobsupervisor/monitor/disk_test.go deleted file mode 100644 index cfe6a58d7..000000000 --- a/jobsupervisor/monitor/disk_test.go +++ /dev/null @@ -1,28 +0,0 @@ -//go:build windows -// +build windows - -package monitor - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Disk", func() { - It("should report the percent used", func() { - du := diskUsage{ - SectorsPerCluster: 8, - BytesPerSector: 512, - NumberOfFreeClusters: 6948117, - TotalNumberOfClusters: 15638527, - } - expPer := 0.55570515049148 - exp := DiskUsage{ - Total: 64055406592, - Used: 35595919360, - } - u := newDiskUsage(du) - Expect(u).To(Equal(exp)) - Expect(matchFloat(u.Percent(), expPer)).To(Succeed()) - }) -}) diff --git a/jobsupervisor/monitor/memory.go b/jobsupervisor/monitor/memory.go deleted file mode 100644 index 28a89e150..000000000 --- a/jobsupervisor/monitor/memory.go +++ /dev/null @@ -1,126 +0,0 @@ -//go:build windows -// +build windows - -package monitor - -import ( - "bytes" - "errors" - "fmt" - "os/exec" - "strconv" - "syscall" - "unsafe" -) - -// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366589(v=vs.85).aspx -var procGlobalMemoryStatusEx = kernel32DLL.MustFindProc("GlobalMemoryStatusEx") - -type Byte uint64 - -const ( - KB Byte = 1 << (10 * (iota + 1)) - MB - GB -) - -func (b Byte) Uint64() uint64 { return uint64(b) } - -func (b Byte) String() string { - switch { - case b < KB: - return fmt.Sprintf("%d", b) - case b < MB: - return fmt.Sprintf("%.1fK", float64(b)/float64(KB)) - case b < GB: - return fmt.Sprintf("%.1fM", float64(b)/float64(MB)) - } - return fmt.Sprintf("%.1fG", float64(b)/float64(GB)) -} - -type MemStat struct { - Total Byte - Avail Byte -} - -func (m MemStat) Used() float64 { - if m.Avail == 0 { - if m.Total == 0 { - return 0 - } - return 1 - } - return 1 - float64(m.Avail)/float64(m.Total) -} - -type memorystatusex struct { - Length uint32 - MemoryLoad uint32 - TotalPhys uint64 - AvailPhys uint64 - TotalPageFile uint64 - AvailPageFile uint64 - TotalVirtual uint64 - AvailVirtual uint64 - AvailExtendedVirtual uint64 -} - -func getGlobalMemoryStatusEx() (*memorystatusex, error) { - var m memorystatusex - m.Length = uint32(unsafe.Sizeof(m)) - r1, _, e1 := syscall.Syscall(procGlobalMemoryStatusEx.Addr(), 1, uintptr(unsafe.Pointer(&m)), 0, 0) - if err := checkErrno(r1, e1); err != nil { - return nil, fmt.Errorf("GlobalMemoryStatusEx: %s", err) - } - return &m, nil -} - -func SystemMemStats() (MemStat, error) { - m, err := getGlobalMemoryStatusEx() - if err != nil { - return MemStat{}, err - } - mem := MemStat{ - Total: Byte(m.TotalPhys), - Avail: Byte(m.AvailPhys), - } - return mem, nil -} - -func SystemPageStats() (MemStat, error) { - const MB = 1024 * 1024 - out, err := exec.Command("wmic", "pagefile", "list", "full").Output() - if err != nil { - return MemStat{}, err - } - total, err := parseWmicOutput(out, []byte("AllocatedBaseSize")) - if err != nil { - return MemStat{}, err - } - used, err := parseWmicOutput(out, []byte("CurrentUsage")) - if err != nil { - return MemStat{}, err - } - total *= MB - used *= MB - mem := MemStat{ - Total: Byte(total), - Avail: Byte(total - used), - } - return mem, nil -} - -func parseWmicOutput(s, sep []byte) (uint64, error) { - bb := bytes.Split(s, []byte("\n")) - for i := 0; i < len(bb); i++ { - b := bytes.TrimSpace(bb[i]) - if bytes.HasPrefix(b, sep) { - n := bytes.IndexByte(b, '=') - if n == -1 || n == len(s)-1 { - return 0, errors.New("parseWmicOutput: parsing field: " + string(sep)) - } - return strconv.ParseUint(string(b[n+1:]), 10, 64) - } - } - return 0, errors.New("parseWmicOutput: missing field: " + string(sep)) -} diff --git a/jobsupervisor/monitor/memory_test.go b/jobsupervisor/monitor/memory_test.go deleted file mode 100644 index b0a80f512..000000000 --- a/jobsupervisor/monitor/memory_test.go +++ /dev/null @@ -1,98 +0,0 @@ -//go:build windows -// +build windows - -package monitor - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Memory", func() { - Context("when create a new memstat", func() { - It("should report the percent used", func() { - var tests = []struct { - Avail Byte - Total Byte - Exp float64 - }{ - {Avail: 1024, Total: 2048, Exp: 0.5}, - {Avail: 0, Total: 0, Exp: 0}, - {Avail: 0, Total: 1024, Exp: 1}, - {Avail: 9216, Total: 10240, Exp: 0.10}, - } - for _, x := range tests { - m := MemStat{Avail: x.Avail, Total: x.Total} - Expect(matchFloat(m.Used(), x.Exp)).To(Succeed()) - } - }) - - It("should report system usage", func() { - m, err := SystemMemStats() - Expect(err).To(Succeed()) - Expect(m.Avail).ToNot(Equal(0)) - Expect(m.Total).ToNot(Equal(0)) - }) - }) - - Context("when defining Byte", func() { - It("should print correctly", func() { - var tests = []struct { - Input Byte - Exp string - }{ - {Input: 300, Exp: "300"}, - {Input: 1024, Exp: "1.0K"}, - {Input: 2000, Exp: "2.0K"}, - {Input: 1 * MB, Exp: "1.0M"}, - {Input: (14 * GB) / 10, Exp: "1.4G"}, - } - for _, x := range tests { - Expect(x.Input.String()).To(Equal(x.Exp)) - } - }) - }) - - Context("when parsing wmic output", func() { - It("should parse the output", func() { - res := ` - -AllocatedBaseSize=4791 - -CurrentUsage=393 - -Description=C:\pagefile.sys - -InstallDate=20151221103329.285091-480 - -Name=C:\pagefile.sys - -PeakUsage=2916 - -Status= - -TempPageFile=FALSE - - -` - out := []byte(res) - num, err := parseWmicOutput(out, []byte("CurrentUsage")) - Expect(err).To(BeNil()) - Expect(num).To(Equal(uint64(393))) - - num, err = parseWmicOutput(out, []byte("AllocatedBaseSize")) - Expect(err).To(BeNil()) - Expect(num).To(Equal(uint64(4791))) - - num, err = parseWmicOutput(out, []byte("Status")) - Expect(err).To(HaveOccurred()) - Expect(num).To(Equal(uint64(0))) - - num, err = parseWmicOutput(out, []byte("SOMETHINGELSE")) - Expect(err).To(HaveOccurred()) - Expect(num).To(Equal(uint64(0))) - }) - - }) - -}) diff --git a/jobsupervisor/monitor/monitor.go b/jobsupervisor/monitor/monitor.go deleted file mode 100644 index 487638578..000000000 --- a/jobsupervisor/monitor/monitor.go +++ /dev/null @@ -1,223 +0,0 @@ -//go:build windows -// +build windows - -package monitor - -import ( - "errors" - "fmt" - "math" - "sync" - "sync/atomic" - "syscall" - "time" - "unsafe" -) - -var ( - // Global kernel32 DLL - kernel32DLL = syscall.MustLoadDLL("kernel32") - - // https://msdn.microsoft.com/en-us/library/windows/desktop/ms724400(v=vs.85).aspx - procGetSystemTimes = kernel32DLL.MustFindProc("GetSystemTimes") -) - -type CPU struct { - User float64 - Kernel float64 - Idle float64 -} - -// Total returns the sum of user and kernel CPU time. -func (c CPU) Total() float64 { - return c.User + c.Kernel -} - -type CPUTime struct { - previous uint64 - delta uint64 - load float64 -} - -func (c CPUTime) CPU() float64 { return c.load } - -type monitorState int32 - -const ( - stateStopped monitorState = iota - stateRunning - stateExited -) - -type state struct { - val monitorState -} - -func (s *state) Set(n monitorState) { - atomic.StoreInt32((*int32)(&s.val), int32(n)) -} - -func (s *state) Is(n monitorState) bool { - return atomic.LoadInt32((*int32)(&s.val)) == int32(n) -} - -type Monitor struct { - user CPUTime - kernel CPUTime - idle CPUTime - mem MemStat // system memory - tick *time.Ticker // use tick.Stop() to stop monitoring - err error // system error, if any - inited bool // monitor initialized - mu sync.RWMutex // pids mutex - state state - cond *sync.Cond // Optional sync conditional for StatsCollector -} - -func New(freq time.Duration) (*Monitor, error) { - if freq < time.Millisecond*10 { - freq = time.Millisecond * 500 - } - m := &Monitor{ - tick: time.NewTicker(freq), - inited: true, - } - if err := m.monitorLoop(); err != nil { - return nil, err - } - return m, nil -} - -// condMonitor, returns a Monitor that broadcasts on cond on each update. -func condMonitor(freq time.Duration, cond *sync.Cond) (*Monitor, error) { - m := &Monitor{ - tick: time.NewTicker(freq), - inited: true, - cond: cond, - } - m.state.Set(stateRunning) - if err := m.monitorLoop(); err != nil { - return nil, err - } - return m, nil -} - -func (m *Monitor) MemStat() MemStat { - m.mu.RLock() - mem := m.mem - m.mu.RUnlock() - return mem -} - -func (m *Monitor) CPU() (cpu CPU, err error) { - m.mu.RLock() - if !m.inited { - err = errors.New("monitor: not initialized") - } - if m.err != nil { - err = m.err - } - cpu = CPU{ - Kernel: m.kernel.load, - User: m.user.load, - Idle: m.idle.load, - } - m.mu.RUnlock() - return -} - -func (m *Monitor) monitorLoop() error { - m.state.Set(stateRunning) - if err := m.updateSystemCPU(); err != nil { - m.err = err - return m.err - } - go func() { - defer m.state.Set(stateExited) - for range m.tick.C { - // Hard error - if err := m.updateSystemCPU(); err != nil { - m.err = err - return - } - // TODO: FIX ME - if !m.state.Is(stateRunning) { - continue - } - } - }() - return nil -} - -func (m *Monitor) updateSystemCPU() error { - if m.err != nil { - return m.err - } - var ( - idleTime filetime - kernelTime filetime - userTime filetime - ) - r1, _, e1 := syscall.Syscall(procGetSystemTimes.Addr(), 3, - uintptr(unsafe.Pointer(&idleTime)), - uintptr(unsafe.Pointer(&kernelTime)), - uintptr(unsafe.Pointer(&userTime)), - ) - if err := checkErrno(r1, e1); err != nil { - m.err = fmt.Errorf("GetSystemTimes: %s", error(e1)) - return m.err - } - - m.calculateSystemCPU(kernelTime.Uint64(), userTime.Uint64(), idleTime.Uint64()) - - return nil -} - -func (m *Monitor) calculateSystemCPU(kernelTicks, userTicks, idleTicks uint64) { - m.mu.Lock() - - kernel := kernelTicks - m.kernel.previous - user := userTicks - m.user.previous - idle := idleTicks - m.idle.previous - - total := kernel + user - if total > 0 { - m.idle.load = float64(idle) / float64(total) - m.idle.previous = idleTicks - m.idle.delta = idle - - m.kernel.load = math.Max(float64(kernel-idle)/float64(total), 0) - m.kernel.previous = kernelTicks - m.kernel.delta = kernel - - m.user.load = math.Max(1-m.idle.load-m.kernel.load, 0) - m.user.previous = userTicks - m.user.delta = user - } else { - m.idle.load = 0 - m.kernel.load = 0 - m.user.load = 0 - } - - m.mu.Unlock() -} - -func checkErrno(r1 uintptr, err error) error { - if r1 == 0 { - if e, ok := err.(syscall.Errno); ok && e != 0 { - return err - } - return syscall.EINVAL - } - return nil -} - -// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724284(v=vs.85).aspx -type filetime struct { - LowDateTime uint32 - HighDateTime uint32 -} - -func (f filetime) Uint64() uint64 { - return uint64(f.HighDateTime)<<32 | uint64(f.LowDateTime) -} diff --git a/jobsupervisor/monitor/monitor_suite_test.go b/jobsupervisor/monitor/monitor_suite_test.go deleted file mode 100644 index ff1a0aab0..000000000 --- a/jobsupervisor/monitor/monitor_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package monitor - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestMonitor(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Monitor Suite") -} diff --git a/jobsupervisor/monitor/monitor_test.go b/jobsupervisor/monitor/monitor_test.go deleted file mode 100644 index 62d207d9e..000000000 --- a/jobsupervisor/monitor/monitor_test.go +++ /dev/null @@ -1,58 +0,0 @@ -//go:build windows -// +build windows - -package monitor - -import ( - "fmt" - "math" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var cpuTestCases = []struct { - prevKernel, prevUser, prevIdle uint64 - currKernel, currUser, currIdle uint64 - loadKernel, loadUser, loadIdle float64 -}{ - { - 0, 0, 0, - 300, 500, 200, - 0.125, 0.625, 0.25, - }, - { - 300, 500, 200, - 600, 1000, 400, - 0.125, 0.625, 0.25, - }, - { - 300, 500, 200, - 300, 500, 100, // Regression - 0, 0, 0, - }, -} - -func matchFloat(val, exp float64) error { - if math.Abs(val-exp) < 0.000001 { - return nil - } - return fmt.Errorf("Expected %.6f to Equal %.6f", val, exp) -} - -var _ = Describe("CPU", func() { - Context("when calculating CPU usage", func() { - It("should correctly report SystemLevel User, Kernel and Idle", func() { - for _, x := range cpuTestCases { - m := Monitor{} - m.kernel.previous = x.prevKernel - m.user.previous = x.prevUser - m.idle.previous = x.prevIdle - m.calculateSystemCPU(x.currKernel, x.currUser, x.currIdle) - Expect(matchFloat(m.kernel.load, x.loadKernel)).To(Succeed()) - Expect(matchFloat(m.user.load, x.loadUser)).To(Succeed()) - Expect(matchFloat(m.idle.load, x.loadIdle)).To(Succeed()) - } - }) - }) -}) diff --git a/jobsupervisor/pipe/main.go b/jobsupervisor/pipe/main.go index 138b23eab..c77a9421d 100644 --- a/jobsupervisor/pipe/main.go +++ b/jobsupervisor/pipe/main.go @@ -24,11 +24,6 @@ type noopWriter struct{} func (n noopWriter) Write(p []byte) (int, error) { return len(p), nil } -// set log output to noop writer on program initialization. We do not -// want to write any logs to stderr - only the underlying program should -// write to stderr and stdout. -func init() { log.SetOutput(noopWriter{}) } - const EnvPrefix = "__PIPE_" type Config struct { @@ -127,7 +122,7 @@ func (c *Config) SendEvent(code int) error { if err != nil { return err } - res, err := http.Post(c.NotifyHTTP, "application/json", bytes.NewReader(body)) + res, err := http.Post(c.NotifyHTTP, "application/json", bytes.NewReader(body)) //nolint:noctx if err != nil { return err } @@ -207,7 +202,10 @@ func (c *Config) Run(path string, args []string, stdout, stderr io.Writer) (exit return 1, fmt.Errorf("starting command (%s): %s", path, err) } go func() { - cmd.Wait() + err = cmd.Wait() + if err != nil { + log.Printf("Waiting for command (%s) returned an error: %s", path, err) + } closeChannel(haltCh) }() @@ -246,7 +244,10 @@ func (c *Config) Run(path string, args []string, stdout, stderr io.Writer) (exit for { select { case sig := <-sigCh: - cmd.Process.Signal(sig) + err = cmd.Process.Signal(sig) + if err != nil { + log.Printf("Unable to signal process: %s", err) + } case <-haltCh: return } @@ -305,10 +306,11 @@ func ExitCode(cmd *exec.Cmd) (int, error) { func FindProcess(pid int) error { p, err := os.FindProcess(pid) - if err == nil { - p.Release() // Close process handle + if err != nil { + return err } - return err + + return p.Release() // Close process handle } type BulletproofWriter struct { @@ -317,7 +319,10 @@ type BulletproofWriter struct { func (w *BulletproofWriter) Write(p []byte) (int, error) { if w.w != nil { - w.w.Write(p) + _, err := w.w.Write(p) + if err != nil { + log.Printf("BulletproofWriter.Write failed: %s", err) + } } return len(p), nil } @@ -336,6 +341,11 @@ func ParseArgs() (path string, args []string, err error) { } func main() { + // set log output to noop writer on program initialization. We do not + // want to write any logs to stderr - only the underlying program should + // write to stderr and stdout. + log.SetOutput(noopWriter{}) + conf := ParseConfig() conf.InitLog() log.Printf("pipe: configuration: %+v", conf) diff --git a/jobsupervisor/pipe/syslog/syslog.go b/jobsupervisor/pipe/syslog/syslog.go index bbf9608db..7d8b2bb9a 100644 --- a/jobsupervisor/pipe/syslog/syslog.go +++ b/jobsupervisor/pipe/syslog/syslog.go @@ -26,14 +26,15 @@ const ( // From /usr/include/sys/syslog.h. // These are the same on Linux, BSD, and OS X. - LOG_EMERG Priority = iota - LOG_ALERT - LOG_CRIT - LOG_ERR - LOG_WARNING - LOG_NOTICE - LOG_INFO - LOG_DEBUG + + LOG_EMERG Priority = iota //nolint:revive + LOG_ALERT //nolint:revive + LOG_CRIT //nolint:revive + LOG_ERR //nolint:revive + LOG_WARNING //nolint:revive + LOG_NOTICE //nolint:revive + LOG_INFO //nolint:revive + LOG_DEBUG //nolint:revive ) const ( @@ -41,30 +42,31 @@ const ( // From /usr/include/sys/syslog.h. // These are the same up to LOG_FTP on Linux, BSD, and OS X. - LOG_KERN Priority = iota << 3 - LOG_USER - LOG_MAIL - LOG_DAEMON - LOG_AUTH - LOG_SYSLOG - LOG_LPR - LOG_NEWS - LOG_UUCP - LOG_CRON - LOG_AUTHPRIV - LOG_FTP - _ // unused - _ // unused - _ // unused - _ // unused - LOG_LOCAL0 - LOG_LOCAL1 - LOG_LOCAL2 - LOG_LOCAL3 - LOG_LOCAL4 - LOG_LOCAL5 - LOG_LOCAL6 - LOG_LOCAL7 + + LOG_KERN Priority = iota << 3 //nolint:revive + LOG_USER //nolint:revive + LOG_MAIL //nolint:revive + LOG_DAEMON //nolint:revive + LOG_AUTH //nolint:revive + LOG_SYSLOG //nolint:revive + LOG_LPR //nolint:revive + LOG_NEWS //nolint:revive + LOG_UUCP //nolint:revive + LOG_CRON //nolint:revive + LOG_AUTHPRIV //nolint:revive + LOG_FTP //nolint:revive + _ // unused + _ // unused + _ // unused + _ // unused + LOG_LOCAL0 //nolint:revive + LOG_LOCAL1 //nolint:revive + LOG_LOCAL2 //nolint:revive + LOG_LOCAL3 //nolint:revive + LOG_LOCAL4 //nolint:revive + LOG_LOCAL5 //nolint:revive + LOG_LOCAL6 //nolint:revive + LOG_LOCAL7 //nolint:revive ) const maxBufSize = 1024 * 1024 * 20 // 20MB diff --git a/jobsupervisor/provider.go b/jobsupervisor/provider.go index e3480fde2..6a2920864 100644 --- a/jobsupervisor/provider.go +++ b/jobsupervisor/provider.go @@ -28,7 +28,7 @@ func NewProvider( logger boshlog.Logger, dirProvider boshdir.Provider, handler boshhandler.Handler, -) (p Provider) { +) Provider { timeService := clock.NewClock() fs := platform.GetFs() runner := platform.GetRunner() @@ -47,13 +47,13 @@ func NewProvider( timeService, ) - p.supervisors = map[string]JobSupervisor{ - "monit": NewWrapperJobSupervisor(monitJobSupervisor, fs, dirProvider, logger), - "dummy": NewDummyJobSupervisor(), - "dummy-nats": NewDummyNatsJobSupervisor(handler), + return Provider{ + supervisors: map[string]JobSupervisor{ + "monit": NewWrapperJobSupervisor(monitJobSupervisor, fs, dirProvider, logger), + "dummy": NewDummyJobSupervisor(), + "dummy-nats": NewDummyNatsJobSupervisor(handler), + }, } - - return } func (p Provider) Get(name string) (supervisor JobSupervisor, err error) { diff --git a/jobsupervisor/windows_job_supervisor.go b/jobsupervisor/windows_job_supervisor.go index bbb14beec..46638b7b5 100644 --- a/jobsupervisor/windows_job_supervisor.go +++ b/jobsupervisor/windows_job_supervisor.go @@ -22,7 +22,6 @@ import ( "golang.org/x/sys/windows/svc" - "github.com/cloudfoundry/bosh-agent/jobsupervisor/monitor" "github.com/cloudfoundry/bosh-agent/jobsupervisor/winsvc" boshalert "github.com/cloudfoundry/bosh-agent/agent/alert" @@ -32,14 +31,15 @@ import ( boshsys "github.com/cloudfoundry/bosh-utils/system" ) -var pipeExePath = "C:\\var\\vcap\\bosh\\bin\\pipe.exe" -var serviceDescription = "vcap" +// TODO: stop creating globals and then overriding in tests, +// see jobsupervisor/windows_job_supervisor_export_test.go:14, :21 +var pipeExePath = "C:\\var\\vcap\\bosh\\bin\\pipe.exe" //nolint:gochecknoglobals +var serviceDescription = "vcap" //nolint:gochecknoglobals const ( serviceWrapperExeFileName = "job-service-wrapper.exe" serviceWrapperConfigFileName = "job-service-wrapper.xml" serviceWrapperAppConfigFileName = "job-service-wrapper.exe.config" - serviceWrapperEventJSONFileName = "job-service-wrapper.wrapper.log.json" serviceWrapperAppConfigBody = ` @@ -172,11 +172,9 @@ type windowsJobSupervisor struct { logTag string machineIP string msgCh chan *windowsServiceEvent - monitor *monitor.Monitor jobFailuresServerPort int cancelServer chan bool - // state *state.State state supervisorState mgr *winsvc.Mgr } @@ -213,11 +211,7 @@ func NewWindowsJobSupervisor( jobFailuresServerPort: jobFailuresServerPort, cancelServer: cancelChan, } - m, err := monitor.New(-1) - if err != nil { - s.logger.Error(s.logTag, "Initializing monitor.Monitor: %s", err) - } - s.monitor = m + s.stateSet(stateEnabled) mgr, err := winsvc.Connect(matchService) @@ -239,7 +233,9 @@ func (w *windowsJobSupervisor) Start() error { // // Do this here, as we know the agent has successfully connected // with the director and is healthy. - w.mgr.DisableAgentAutoStart() + if err := w.mgr.DisableAgentAutoStart(); err != nil { + w.logger.Error(w.logTag, "Running DisableAgentAutoStart %s", err) + } if err := w.mgr.Start(); err != nil { return bosherr.WrapError(err, "Starting windows job process") @@ -294,18 +290,16 @@ func (w *windowsJobSupervisor) Status() (status string) { return "running" } -var windowsSvcStateMap = map[svc.State]string{ - svc.Stopped: "stopped", - svc.StartPending: "starting", - svc.StopPending: "stop_pending", - svc.Running: "running", - svc.ContinuePending: "continue_pending", - svc.PausePending: "pause_pending", - svc.Paused: "paused", -} - func SvcStateString(s svc.State) string { - return windowsSvcStateMap[s] + return map[svc.State]string{ + svc.Stopped: "stopped", + svc.StartPending: "starting", + svc.StopPending: "stop_pending", + svc.Running: "running", + svc.ContinuePending: "continue_pending", + svc.PausePending: "pause_pending", + svc.Paused: "paused", + }[s] } func (w *windowsJobSupervisor) Processes() ([]Process, error) { @@ -459,7 +453,10 @@ func (w *windowsJobSupervisor) handleJobFailure(hn JobFailureHandler, wr http.Re Service: event.ProcessName, Description: fmt.Sprintf("exited with code %d", event.ExitCode), } - hn(alert) + err = hn(alert) + if err != nil { + w.logger.Error(w.logTag, "JobFailureHandler: generated an error: %s", err) + } } func (w *windowsJobSupervisor) MonitorJobFailures(handler JobFailureHandler) error { diff --git a/jobsupervisor/winsvc/cpu.go b/jobsupervisor/winsvc/cpu.go deleted file mode 100644 index 2d59dbb39..000000000 --- a/jobsupervisor/winsvc/cpu.go +++ /dev/null @@ -1,132 +0,0 @@ -//go:build windows -// +build windows - -package winsvc - -import ( - "math" - "sync" - "syscall" - "time" - "unsafe" - - "golang.org/x/sys/windows" -) - -var ( - // Global kernel32 DLL - kernel32DLL = windows.NewLazySystemDLL("kernel32") - - // https://msdn.microsoft.com/en-us/library/windows/desktop/ms724400(v=vs.85).aspx - procGetSystemTimes = kernel32DLL.NewProc("GetSystemTimes") -) - -var cpu = newMonitor(time.Second * 5) - -type monitor struct { - user cpuTime - kernel cpuTime - idle cpuTime - mu sync.RWMutex - tick *time.Ticker -} - -func newMonitor(tick time.Duration) *monitor { - if tick < time.Second { - tick = time.Second - } - m := &monitor{ - tick: time.NewTicker(tick), - } - go m.monitorLoop() - return m -} - -func (m *monitor) CPU() (usage float64) { - m.mu.RLock() - usage = (m.user.load + m.kernel.load) * 100 - m.mu.RUnlock() - return -} - -func (m *monitor) Stop() error { - if m.tick != nil { - m.tick.Stop() - } - return nil -} - -func (m *monitor) monitorLoop() { - m.updateSystemCPU() - for range m.tick.C { - m.updateSystemCPU() - } -} - -func (m *monitor) updateSystemCPU() { - if procGetSystemTimes.Find() != nil { - return - } - var ( - idleTime filetime - kernelTime filetime - userTime filetime - ) - r1, _, e1 := syscall.Syscall(procGetSystemTimes.Addr(), 3, - uintptr(unsafe.Pointer(&idleTime)), - uintptr(unsafe.Pointer(&kernelTime)), - uintptr(unsafe.Pointer(&userTime)), - ) - if r1 == 0 { - _ = e1 // unused for now - return - } - m.calculateSystemCPU(kernelTime.Uint64(), userTime.Uint64(), idleTime.Uint64()) -} - -func (m *monitor) calculateSystemCPU(kernelTicks, userTicks, idleTicks uint64) { - m.mu.Lock() - - kernel := kernelTicks - m.kernel.previous - user := userTicks - m.user.previous - idle := idleTicks - m.idle.previous - - total := kernel + user - if total > 0 { - m.idle.load = float64(idle) / float64(total) - m.idle.previous = idleTicks - m.idle.delta = idle - - m.kernel.load = math.Max(float64(kernel-idle)/float64(total), 0) - m.kernel.previous = kernelTicks - m.kernel.delta = kernel - - m.user.load = math.Max(1-m.idle.load-m.kernel.load, 0) - m.user.previous = userTicks - m.user.delta = user - } else { - m.idle.load = 0 - m.kernel.load = 0 - m.user.load = 0 - } - - m.mu.Unlock() -} - -type cpuTime struct { - previous uint64 - delta uint64 - load float64 -} - -func (c cpuTime) CPU() float64 { return c.load } - -// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724284(v=vs.85).aspx -type filetime struct { - LowDateTime uint32 - HighDateTime uint32 -} - -func (f filetime) Uint64() uint64 { - return uint64(f.HighDateTime)<<32 | uint64(f.LowDateTime) -} diff --git a/jobsupervisor/winsvc/winsvc.go b/jobsupervisor/winsvc/winsvc.go index 50ee94f68..4cb3d25fd 100644 --- a/jobsupervisor/winsvc/winsvc.go +++ b/jobsupervisor/winsvc/winsvc.go @@ -124,18 +124,6 @@ func (m *Mgr) iter(fn func(*mgr.Service) error) (first error) { return } -func svcStartTypeString(startType uint32) string { - switch startType { - case mgr.StartManual: - return "StartManual" - case mgr.StartAutomatic: - return "StartAutomatic" - case mgr.StartDisabled: - return "StartDisabled" - } - return fmt.Sprintf("Invalid Service StartType: %d", startType) -} - func SetStartType(s *mgr.Service, startType uint32) error { conf, err := s.Config() if err != nil { @@ -168,7 +156,7 @@ func querySvc(s *mgr.Service) (svc.Status, error) { // If no WaitHint is provided the default of 10 seconds is returned. As per // Microsoft's recommendations he returned interval will be between 1 and 10 // seconds. -func calculateWaitHint(status svc.Status) (waitHint, interval time.Duration) { +func calculateWaitHint(status svc.Status) (time.Duration, time.Duration) { // // This is all a little confusing, so I included the definition of WaitHint // and Microsoft's guidelines on how to use below: @@ -200,18 +188,20 @@ func calculateWaitHint(status svc.Status) (waitHint, interval time.Duration) { // // https://msdn.microsoft.com/en-us/library/windows/desktop/ms686315(v=vs.85).aspx // - waitHint = time.Duration(status.WaitHint) * time.Millisecond + waitHint := time.Duration(status.WaitHint) * time.Millisecond if waitHint == 0 { waitHint = time.Second * 10 } - interval = waitHint / 10 + interval := waitHint / 10 + switch { case interval < time.Second: interval = time.Second case interval > time.Second*10: interval = time.Second * 10 } - return + + return waitHint, interval } // waitPending, waits for service s to transition out of pendingState, which @@ -250,9 +240,7 @@ func waitPending(s *mgr.Service, pendingState svc.State) (svc.Status, error) { break } - switch { - // Exceeded our timeout - case time.Since(start) > Timeout: + if time.Since(start) > Timeout { err := &TransitionError{ Msg: "timeout waiting for state transition", Name: s.Name, @@ -279,7 +267,7 @@ func waitPending(s *mgr.Service, pendingState svc.State) (svc.Status, error) { func doStart(s *mgr.Service) error { // https://msdn.microsoft.com/en-us/library/windows/desktop/ms681383(v=vs.85).aspx - const ERROR_SERVICE_ALREADY_RUNNING = syscall.Errno(0x420) + const ERROR_SERVICE_ALREADY_RUNNING = syscall.Errno(0x420) //nolint:revive // Set start type to manual to enable starting the service. if err := SetStartType(s, mgr.StartManual); err != nil { @@ -513,13 +501,13 @@ func (s *ServiceStatus) StateString() string { return svcStateString(s.State) } -// Status returns the name and status for all of the services monitored. +// Status returns the name and status for all services monitored. func (m *Mgr) Status() ([]ServiceStatus, error) { svcs, err := m.services() if err != nil { return nil, err } - defer closeServices(svcs) + defer closeServices(svcs) //nolint:errcheck sts := make([]ServiceStatus, len(svcs)) for i, s := range svcs { diff --git a/jobsupervisor/wrapper_job_supervisor.go b/jobsupervisor/wrapper_job_supervisor.go index c9d34222a..592a89e98 100644 --- a/jobsupervisor/wrapper_job_supervisor.go +++ b/jobsupervisor/wrapper_job_supervisor.go @@ -1,27 +1,21 @@ package jobsupervisor import ( - - //boshmonit "github.com/cloudfoundry/bosh-agent/jobsupervisor/monit" - //boshdir "github.com/cloudfoundry/bosh-agent/settings/directories" - //boshlog "github.com/cloudfoundry/bosh-utils/logger" - //boshsys "github.com/cloudfoundry/bosh-utils/system" "encoding/json" + "path/filepath" + "github.com/cloudfoundry/bosh-agent/settings/directories" boshlog "github.com/cloudfoundry/bosh-utils/logger" "github.com/cloudfoundry/bosh-utils/system" - "path/filepath" ) const wrapperJobSupervisorLogTag = "wrapperJobSupervisor" type wrapperJobSupervisor struct { - delegate JobSupervisor - fs system.FileSystem - dirProvider directories.Provider - logger boshlog.Logger - pollRunning bool - pollUnmonitor bool + delegate JobSupervisor + fs system.FileSystem + dirProvider directories.Provider + logger boshlog.Logger } func NewWrapperJobSupervisor(delegate JobSupervisor, fs system.FileSystem, dirProvider directories.Provider, logger boshlog.Logger) JobSupervisor { @@ -37,7 +31,6 @@ func (w *wrapperJobSupervisor) Reload() error { return w.delegate.Reload() } func (w *wrapperJobSupervisor) Start() error { - err := w.delegate.Start() w.HealthRecorder(w.delegate.Status()) @@ -78,7 +71,6 @@ func (w *wrapperJobSupervisor) MonitorJobFailures(handler JobFailureHandler) err } func (w *wrapperJobSupervisor) HealthRecorder(status string) { - healthRaw, err := json.Marshal(Health{State: status}) if err != nil { w.logger.Error(wrapperJobSupervisorLogTag, err.Error()) diff --git a/main/agent.go b/main/agent.go index 0eb757a88..9ec5afef2 100644 --- a/main/agent.go +++ b/main/agent.go @@ -62,7 +62,8 @@ func startAgent(logger logger.Logger) error { } sigCh := make(chan os.Signal, 8) - signal.Notify(sigCh, syscall.SIGTERM, os.Interrupt, os.Kill) + // `os.Kill` can not be intercepted on UNIX OS's, possibly necessary for Windows? + signal.Notify(sigCh, syscall.SIGTERM, os.Interrupt, os.Kill) //nolint:staticcheck errCh := runAgent(opts, logger) for { select { @@ -83,7 +84,9 @@ func main() { logger.Error(mainLogTag, "Agent exited with error: %s", err) exitCode = 1 } - logger.FlushTimeout(time.Minute) + if err := logger.FlushTimeout(time.Minute); err != nil { + logger.Error(mainLogTag, "Setting logger flush timeout failed: %s", err) + } os.Exit(exitCode) } diff --git a/matchers/one_of_matcher.go b/matchers/one_of_matcher.go index ec4971df3..a2313edc1 100644 --- a/matchers/one_of_matcher.go +++ b/matchers/one_of_matcher.go @@ -37,7 +37,7 @@ func (m *OneOfMatcher) NegatedFailureMessage(actual interface{}) (message string } func (m *OneOfMatcher) expectedValues() string { - expectedValues := make([]string, len(m.Elements), len(m.Elements)) + expectedValues := make([]string, len(m.Elements)) for i, matcher := range m.Elements { expectedValues[i] = format.Object(matcher, 1) } diff --git a/mbus/handler_provider.go b/mbus/handler_provider.go index 5c4964021..ed973511e 100644 --- a/mbus/handler_provider.go +++ b/mbus/handler_provider.go @@ -1,6 +1,8 @@ package mbus import ( + "net/url" + boshagentblobstore "github.com/cloudfoundry/bosh-agent/agent/blobstore" boshhandler "github.com/cloudfoundry/bosh-agent/handler" boshplatform "github.com/cloudfoundry/bosh-agent/platform" @@ -8,7 +10,6 @@ import ( bosherr "github.com/cloudfoundry/bosh-utils/errors" boshlog "github.com/cloudfoundry/bosh-utils/logger" "github.com/nats-io/nats.go" - "net/url" ) type HandlerProvider struct { @@ -32,16 +33,14 @@ func NewHandlerProvider( func (p HandlerProvider) Get( platform boshplatform.Platform, blobManager boshagentblobstore.BlobManagerInterface, -) (handler boshhandler.Handler, err error) { +) (boshhandler.Handler, error) { if p.handler != nil { - handler = p.handler - return + return p.handler, nil } mbusURL, err := url.Parse(p.settingsService.GetSettings().GetMbusURL()) if err != nil { - err = bosherr.WrapError(err, "Parsing handler URL") - return + return nil, bosherr.WrapError(err, "Parsing handler URL") } switch mbusURL.Scheme { @@ -49,15 +48,11 @@ func (p HandlerProvider) Get( f := func(url string, options ...nats.Option) (NatsConnection, error) { return nats.Connect(url, options...) } - handler = NewNatsHandler(p.settingsService, f, p.logger, platform, natsConnectRetryInterval, natsConnectMaxRetryInterval) + return NewNatsHandler(p.settingsService, f, p.logger, platform, natsConnectRetryInterval, natsConnectMaxRetryInterval), nil case "https": mbusKeyPair := p.settingsService.GetSettings().GetMbusCerts() - handler = NewHTTPSHandler(mbusURL, mbusKeyPair, blobManager, p.logger, p.auditLogger) + return NewHTTPSHandler(mbusURL, mbusKeyPair, blobManager, p.logger, p.auditLogger), nil default: - err = bosherr.Errorf("Message Bus Handler with scheme %s could not be found", mbusURL.Scheme) + return nil, bosherr.Errorf("Message Bus Handler with scheme %s could not be found", mbusURL.Scheme) } - - p.handler = handler - - return } diff --git a/mbus/https_handler.go b/mbus/https_handler.go index 45e9bce84..eedb1bde2 100644 --- a/mbus/https_handler.go +++ b/mbus/https_handler.go @@ -113,8 +113,8 @@ func (h HTTPSHandler) agentHandler(handlerFunc boshhandler.Func) func(http.Respo } } -func (h HTTPSHandler) blobsHandler() (blobsHandler func(http.ResponseWriter, *http.Request)) { - blobsHandler = func(w http.ResponseWriter, r *http.Request) { +func (h HTTPSHandler) blobsHandler() func(http.ResponseWriter, *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { switch r.Method { case "GET": h.getBlob(w, r) @@ -124,9 +124,7 @@ func (h HTTPSHandler) blobsHandler() (blobsHandler func(http.ResponseWriter, *ht w.WriteHeader(404) h.generateCEFLog(r, 404, "") } - return } - return } func (h HTTPSHandler) putBlob(w http.ResponseWriter, r *http.Request) { @@ -152,9 +150,7 @@ func (h HTTPSHandler) getBlob(w http.ResponseWriter, r *http.Request) { file, statusCode, err := h.blobManager.Fetch(blobID) if err != nil { h.logger.Error(httpsHandlerLogTag, "Failed to fetch blob: %s", err.Error()) - w.WriteHeader(statusCode) - } else { defer func() { _ = file.Close() diff --git a/platform/cdrom/cdutil.go b/platform/cdrom/cdutil.go index de694ae8f..2d3a699b7 100644 --- a/platform/cdrom/cdutil.go +++ b/platform/cdrom/cdutil.go @@ -61,7 +61,7 @@ func (util cdUtil) GetFilesContents(fileNames []string) ([][]byte, error) { return [][]byte{}, bosherr.WrapError(err, "Reading from CDROM") } - contents = append(contents, []byte(stringContents)) + contents = append(contents, stringContents) } util.logger.Debug(util.logTag, "Umounting CDROM") diff --git a/platform/cert/windows_cert_manager.go b/platform/cert/windows_cert_manager.go index c5230a7fd..f8af7a688 100644 --- a/platform/cert/windows_cert_manager.go +++ b/platform/cert/windows_cert_manager.go @@ -2,6 +2,7 @@ package cert import ( "fmt" + "log" "os" "path" "strconv" @@ -83,7 +84,12 @@ func (c *windowsCertManager) UpdateCertificates(rawCerts string) error { if err != nil { return err } - defer c.fs.RemoveAll(tempCertDir) + defer func() { + err = c.fs.RemoveAll(tempCertDir) + if err != nil { + log.Printf("Unable to remove %s directory: %s", tempCertDir, err) + } + }() for i, cert := range certs { filename := path.Join(tempCertDir, strconv.Itoa(i)) diff --git a/platform/delayed_audit_logger_unix.go b/platform/delayed_audit_logger_unix.go index 6ee3fd761..50083cd21 100644 --- a/platform/delayed_audit_logger_unix.go +++ b/platform/delayed_audit_logger_unix.go @@ -5,10 +5,11 @@ package platform import ( "fmt" - boshlog "github.com/cloudfoundry/bosh-utils/logger" - boshretry "github.com/cloudfoundry/bosh-utils/retrystrategy" "log" "time" + + boshlog "github.com/cloudfoundry/bosh-utils/logger" + boshretry "github.com/cloudfoundry/bosh-utils/retrystrategy" ) type DelayedAuditLogger struct { diff --git a/platform/disk/cmd_mounts_searcher.go b/platform/disk/cmd_mounts_searcher.go index 0e3777747..ac86b4b4a 100644 --- a/platform/disk/cmd_mounts_searcher.go +++ b/platform/disk/cmd_mounts_searcher.go @@ -16,19 +16,19 @@ func NewCmdMountsSearcher(runner boshsys.CmdRunner) MountsSearcher { } func (s cmdMountsSearcher) SearchMounts() ([]Mount, error) { - var mounts []Mount - stdout, _, _, err := s.runner.RunCommand("mount") if err != nil { - return mounts, bosherr.WrapError(err, "Running mount") + return []Mount{}, bosherr.WrapError(err, "Running mount") } - // e.g. '/dev/sda on /boot type ext2 (rw)' - for _, mountEntry := range strings.Split(stdout, "\n") { + mountEntries := strings.Split(stdout, "\n") + mounts := make([]Mount, 0, len(mountEntries)) + for _, mountEntry := range mountEntries { if mountEntry == "" { continue } + // e.g. '/dev/sda on /boot type ext2 (rw)' mountFields := strings.Fields(mountEntry) mounts = append(mounts, Mount{ diff --git a/platform/disk/ephemeral_device_partitioner.go b/platform/disk/ephemeral_device_partitioner.go index 172156a0d..72f520cc0 100644 --- a/platform/disk/ephemeral_device_partitioner.go +++ b/platform/disk/ephemeral_device_partitioner.go @@ -76,7 +76,6 @@ func (p *EphemeralDevicePartitioner) matchPartitionNames(existingPartitions []Ex if !strings.HasPrefix(existingPartition.Name, partition.NamePrefix) { return false } - } return true @@ -88,10 +87,13 @@ func (p EphemeralDevicePartitioner) RemovePartitions(partitions []ExistingPartit func (p EphemeralDevicePartitioner) ensureGPTPartition(devicePath string) (err error) { stdout, _, _, err := p.cmdRunner.RunCommand("parted", "-m", devicePath, "unit", "B", "print") + if err != nil { + return bosherr.WrapErrorf(err, "Running 'parted'") + } if !strings.Contains(stdout, "gpt") { p.logger.Debug(p.logTag, "Creating gpt table") - stdout, _, _, err = p.cmdRunner.RunCommand( + _, _, _, err = p.cmdRunner.RunCommand( "parted", "-s", devicePath, diff --git a/platform/disk/linux_formatter.go b/platform/disk/linux_formatter.go index 845556f29..551f0071d 100644 --- a/platform/disk/linux_formatter.go +++ b/platform/disk/linux_formatter.go @@ -1,10 +1,11 @@ package disk import ( - bosherr "github.com/cloudfoundry/bosh-utils/errors" - boshsys "github.com/cloudfoundry/bosh-utils/system" "regexp" "strings" + + bosherr "github.com/cloudfoundry/bosh-utils/errors" + boshsys "github.com/cloudfoundry/bosh-utils/system" ) type linuxFormatter struct { @@ -19,7 +20,7 @@ func NewLinuxFormatter(runner boshsys.CmdRunner, fs boshsys.FileSystem) Formatte } } -func (f linuxFormatter) Format(partitionPath string, fsType FileSystemType) (err error) { +func (f linuxFormatter) Format(partitionPath string, fsType FileSystemType) error { existingFsType, err := f.getPartitionFormatType(partitionPath) if err != nil { return bosherr.WrapError(err, "Checking filesystem format of partition") @@ -27,19 +28,19 @@ func (f linuxFormatter) Format(partitionPath string, fsType FileSystemType) (err if fsType == FileSystemSwap { if existingFsType == FileSystemSwap { - return + return err } // swap is not user-configured, so we're not concerned about reformatting } else if existingFsType == FileSystemExt4 || existingFsType == FileSystemXFS { // never reformat if it is already formatted in a supported format - return + return err } switch fsType { case FileSystemSwap: _, _, _, err = f.runner.RunCommand("mkswap", partitionPath) if err != nil { - err = bosherr.WrapError(err, "Shelling out to mkswap") + return bosherr.WrapError(err, "Shelling out to mkswap") } case FileSystemExt4: @@ -50,16 +51,19 @@ func (f linuxFormatter) Format(partitionPath string, fsType FileSystemType) (err } } if err != nil { - err = bosherr.WrapError(err, "Shelling out to mke2fs") + return bosherr.WrapError(err, "Shelling out to mke2fs") } case FileSystemXFS: _, _, _, err = f.runner.RunCommand("mkfs.xfs", partitionPath) if err != nil { - err = bosherr.WrapError(err, "Shelling out to mkfs.xfs") + return bosherr.WrapError(err, "Shelling out to mkfs.xfs") } + case FileSystemDefault: + return nil } - return + + return nil } func (f linuxFormatter) GrowFilesystem(partitionPath string) error { @@ -87,6 +91,8 @@ func (f linuxFormatter) GrowFilesystem(partitionPath string) error { if err != nil { return bosherr.WrapError(err, "Failed to grow XFS filesystem") } + case FileSystemDefault, FileSystemSwap: + return nil } return nil } diff --git a/platform/disk/parted_partitioner.go b/platform/disk/parted_partitioner.go index a46ecc12d..da97beb9f 100644 --- a/platform/disk/parted_partitioner.go +++ b/platform/disk/parted_partitioner.go @@ -100,7 +100,7 @@ func (p partedPartitioner) partitionsMatch(existingPartitions []ExistingPartitio return false } - remainingDiskSpace = remainingDiskSpace - partition.SizeInBytes + remainingDiskSpace -= partition.SizeInBytes } return true @@ -215,16 +215,15 @@ func (p partedPartitioner) RemovePartitions(partitions []ExistingPartition, devi func (p partedPartitioner) runPartedPrint(devicePath string) (stdout, stderr string, exitStatus int, err error) { stdout, stderr, exitStatus, err = p.cmdRunner.RunCommand("parted", "-m", devicePath, "unit", "B", "print") - defer p.cmdRunner.RunCommand("udevadm", "settle") + defer p.cmdRunner.RunCommand("udevadm", "settle") // nolint:errcheck - printFields := strings.SplitN(string(stdout), ":", 7) + printFields := strings.SplitN(stdout, ":", 7) // Create a new partition table if // - there is none, or // - a "loop" partition table is shown (which can mean a valid one was not found) - if strings.Contains(fmt.Sprintf("%s\n%s", stdout, stderr), "unrecognised disk label") || - (len(printFields) > 5 && printFields[5] == "loop") { - + containsUnrecognizedDiskLabel := strings.Contains(fmt.Sprintf("%s\n%s", stdout, stderr), "unrecognised disk label") + if containsUnrecognizedDiskLabel || (len(printFields) > 5 && printFields[5] == "loop") { stdout, stderr, exitStatus, err = p.getPartitionTable(devicePath) if err != nil { return stdout, stderr, exitStatus, bosherr.WrapErrorf(err, "Parted making label") @@ -304,7 +303,7 @@ func (p partedPartitioner) createEachPartition(partitions []Partition, deviceFul ) if err != nil { p.logger.Error(p.logTag, "Failed with an error: %s", err) - //TODO: double check the output here. Does it make sense? + // TODO: double check the output here. Does it make sense? return true, bosherr.WrapError(err, "Creating partition using parted") } @@ -314,7 +313,10 @@ func (p partedPartitioner) createEachPartition(partitions []Partition, deviceFul return true, bosherr.WrapError(err, "Creating partition using parted") } - p.cmdRunner.RunCommand("udevadm", "settle") + _, _, _, err = p.cmdRunner.RunCommand("udevadm", "settle") + if err != nil { + p.logger.Error(p.logTag, "Failed to run udevadm settle: %s", err) + } p.logger.Info(p.logTag, "Successfully created partition %d on %s", index, devicePath) return false, nil @@ -353,10 +355,11 @@ func (p partedPartitioner) createMapperPartition(devicePath string) error { return true, bosherr.Errorf("No devices found") } + part1Regexp := regexp.MustCompile("-part1") device := strings.TrimPrefix(devicePath, "/dev/mapper/") lines := strings.Split(strings.Trim(output, "\n"), "\n") for i := 0; i < len(lines); i++ { - if match, _ := regexp.MatchString("-part1", lines[i]); match { + if part1Regexp.MatchString(lines[i]) { if strings.Contains(lines[i], device) { p.logger.Info(p.logTag, "Succeeded in detecting partition %s", devicePath+"-part1") return false, nil diff --git a/platform/disk/proc_mounts_searcher.go b/platform/disk/proc_mounts_searcher.go index 1a2b4cccb..dba8d17a9 100644 --- a/platform/disk/proc_mounts_searcher.go +++ b/platform/disk/proc_mounts_searcher.go @@ -16,14 +16,14 @@ func NewProcMountsSearcher(fs boshsys.FileSystem) MountsSearcher { } func (s procMountsSearcher) SearchMounts() ([]Mount, error) { - var mounts []Mount - mountInfo, err := s.fs.ReadFileString("/proc/mounts") if err != nil { - return mounts, bosherr.WrapError(err, "Reading /proc/mounts") + return []Mount{}, bosherr.WrapError(err, "Reading /proc/mounts") } - for _, mountEntry := range strings.Split(mountInfo, "\n") { + mountEntries := strings.Split(mountInfo, "\n") + mounts := make([]Mount, 0, len(mountEntries)) + for _, mountEntry := range mountEntries { if mountEntry == "" { continue } diff --git a/platform/disk/root_device_partitioner.go b/platform/disk/root_device_partitioner.go index e9d7a4158..ac1fc36aa 100644 --- a/platform/disk/root_device_partitioner.go +++ b/platform/disk/root_device_partitioner.go @@ -215,17 +215,6 @@ func (p rootDevicePartitioner) roundUp(numToRound, multiple uint64) uint64 { return numToRound + multiple - remainder } -func (p rootDevicePartitioner) roundDown(numToRound, multiple uint64) uint64 { - if multiple == 0 { - return numToRound - } - remainder := numToRound % multiple - if remainder == 0 { - return numToRound - } - return numToRound - remainder -} - func (p rootDevicePartitioner) SinglePartitionNeedsResize(devicePath string, expectedPartitionType PartitionType) (needsResize bool, err error) { return false, bosherr.WrapError(err, "Resizing the system disk is not supported") } diff --git a/platform/disk/sfdisk_partitioner.go b/platform/disk/sfdisk_partitioner.go index 63e70272d..d065a445d 100644 --- a/platform/disk/sfdisk_partitioner.go +++ b/platform/disk/sfdisk_partitioner.go @@ -52,7 +52,7 @@ func (p sfdiskPartitioner) Partition(devicePath string, partitions []Partition) partitionSize = "" } - sfdiskInput = sfdiskInput + fmt.Sprintf(",%s,%s\n", partitionSize, sfdiskPartitionType) + sfdiskInput += fmt.Sprintf(",%s,%s\n", partitionSize, sfdiskPartitionType) } partitionRetryable := boshretry.NewRetryable(func() (bool, error) { @@ -70,7 +70,7 @@ func (p sfdiskPartitioner) Partition(devicePath string, partitions []Partition) if err != nil { return err } - if strings.Contains(devicePath, "/dev/mapper/") { + if strings.Contains(devicePath, "/dev/mapper/") { //nolint:nestif _, _, _, err = p.cmdRunner.RunCommand("/etc/init.d/open-iscsi", "restart") if err != nil { return bosherr.WrapError(err, "Shelling out to restart open-iscsi") @@ -91,14 +91,13 @@ func (p sfdiskPartitioner) Partition(devicePath string, partitions []Partition) return true, bosherr.Errorf("No devices found") } + part1Regexp := regexp.MustCompile("-part1") device := strings.TrimPrefix(devicePath, "/dev/mapper/") lines := strings.Split(strings.Trim(output, "\n"), "\n") for i := 0; i < len(lines); i++ { - if match, _ := regexp.MatchString("-part1", lines[i]); match { - if strings.Contains(lines[i], device) { - p.logger.Info(p.logTag, "Succeeded in detecting partition %s", devicePath+"-part1") - return false, nil - } + if part1Regexp.MatchString(lines[i]) && strings.Contains(lines[i], device) { + p.logger.Info(p.logTag, "Succeeded in detecting partition %s", devicePath+"-part1") + return false, nil } } @@ -206,34 +205,34 @@ func (p sfdiskPartitioner) diskMatchesPartitions(devicePath string, partitionsTo return false, nil } - remainingDiskSpace = remainingDiskSpace - partitionToMatch.SizeInBytes + remainingDiskSpace -= partitionToMatch.SizeInBytes } return true, nil } -var partitionTypesMap = map[string]PartitionType{ - "82": PartitionTypeSwap, - "83": PartitionTypeLinux, - "0": PartitionTypeEmpty, - "ee": PartitionTypeGPT, -} +func extractPartitionPathAndType(line string) (string, PartitionType) { + var partitionTypesMap = map[string]PartitionType{ + "82": PartitionTypeSwap, + "83": PartitionTypeLinux, + "0": PartitionTypeEmpty, + "ee": PartitionTypeGPT, + } -func extractPartitionPathAndType(line string) (partitionPath string, partitionType PartitionType) { partitionFields := strings.Fields(line) - lastField := partitionFields[len(partitionFields)-1] + lastField := partitionFields[len(partitionFields)-1] sfdiskPartitionType := strings.Replace(lastField, "Id=", "", 1) - partitionPath = partitionFields[0] - partitionType = partitionTypesMap[sfdiskPartitionType] - return + partitionPath := partitionFields[0] + + return partitionPath, partitionTypesMap[sfdiskPartitionType] } -func (p sfdiskPartitioner) SinglePartitionNeedsResize(devicePath string, expectedPartitionType PartitionType) (needsResize bool, err error) { - return false, bosherr.WrapError(err, "Resizing partition using sfdisk is not supported") +func (p sfdiskPartitioner) SinglePartitionNeedsResize(devicePath string, expectedPartitionType PartitionType) (bool, error) { + return false, bosherr.WrapError(nil, "Resizing partition using sfdisk is not supported") } -func (p sfdiskPartitioner) ResizeSinglePartition(devicePath string) (err error) { - return bosherr.WrapError(err, "Resizing partition using sfdisk is not supported") +func (p sfdiskPartitioner) ResizeSinglePartition(devicePath string) error { + return bosherr.WrapError(nil, "Resizing partition using sfdisk is not supported") } diff --git a/platform/dummy_platform.go b/platform/dummy_platform.go index 17e39c044..9a2ff13f7 100644 --- a/platform/dummy_platform.go +++ b/platform/dummy_platform.go @@ -253,7 +253,6 @@ func (p dummyPlatform) SetupSharedMemory() error { } func (p dummyPlatform) SetupBlobsDir() error { - blobsDir := p.dirProvider.BlobsDir() if err := p.fs.MkdirAll(blobsDir, blobsDirPermissions); err != nil { return bosherr.WrapErrorf(err, "Making %s dir", blobsDir) @@ -302,7 +301,10 @@ func (p dummyPlatform) MountPersistentDisk(diskSettings boshsettings.DiskSetting return err } - p.fs.WriteFile(filepath.Join(p.dirProvider.BoshDir(), "formatted_disks.json"), diskJSON) + err = p.fs.WriteFile(filepath.Join(p.dirProvider.BoshDir(), "formatted_disks.json"), diskJSON) + if err != nil { + return err + } mounts = append(mounts, mount{ MountDir: mountPoint, @@ -314,7 +316,10 @@ func (p dummyPlatform) MountPersistentDisk(diskSettings boshsettings.DiskSetting return err } - p.fs.WriteFileString(managedSettingsPath, diskSettings.ID) + err = p.fs.WriteFileString(managedSettingsPath, diskSettings.ID) + if err != nil { + return err + } return p.fs.WriteFile(p.mountsPath(), mountsJSON) } @@ -415,7 +420,10 @@ func (p dummyPlatform) IsPersistentDiskMountable(diskSettings boshsettings.DiskS if err != nil { return false, err } - json.Unmarshal(bytes, &formattedDisks) + err = json.Unmarshal(bytes, &formattedDisks) + if err != nil { + return false, err + } for _, disk := range formattedDisks { if diskSettings.ID == disk.DiskCid { @@ -441,7 +449,10 @@ func (p dummyPlatform) AssociateDisk(name string, settings boshsettings.DiskSett return bosherr.WrapError(err, "Associating Disk: ") } } else if err == nil { - json.Unmarshal(bytes, &diskNames) + err = json.Unmarshal(bytes, &diskNames) + if err != nil { + return err + } } diskNames = append(diskNames, name) @@ -483,7 +494,7 @@ func (p dummyPlatform) GetDefaultNetwork() (boshsettings.Network, error) { return network, nil } - err = json.Unmarshal([]byte(contents), &network) + err = json.Unmarshal(contents, &network) if err != nil { return network, bosherr.WrapError(err, "Unmarshal json settings") } diff --git a/platform/linux_platform.go b/platform/linux_platform.go index 7d90939c9..8f8bc5661 100644 --- a/platform/linux_platform.go +++ b/platform/linux_platform.go @@ -151,7 +151,7 @@ func (p linux) AssociateDisk(name string, settings boshsettings.DiskSettings) er disksDir := p.dirProvider.DisksDir() err := p.fs.MkdirAll(disksDir, disksDirPermissions) if err != nil { - bosherr.WrapError(err, "Associating disk: ") + return bosherr.WrapError(err, "Associating disk: ") } linkPath := path.Join(disksDir, name) @@ -317,14 +317,14 @@ func (p linux) findEphemeralUsersMatching(reg *regexp.Regexp) (matchingUsers []s } func (p linux) SetupBoshSettingsDisk() (err error) { - path := filepath.Dir(p.GetAgentSettingsPath(true)) + agentSettingsTmpfsDir := filepath.Dir(p.GetAgentSettingsPath(true)) - err = p.fs.MkdirAll(path, 0700) + err = p.fs.MkdirAll(agentSettingsTmpfsDir, 0700) if err != nil { err = bosherr.WrapError(err, "Setting up Bosh Settings Disk") return } - return p.diskManager.GetMounter().MountTmpfs(path, "16m") + return p.diskManager.GetMounter().MountTmpfs(agentSettingsTmpfsDir, "16m") } func (p linux) GetAgentSettingsPath(tmpfs bool) string { @@ -353,15 +353,15 @@ func (p linux) SetupRootDisk(ephemeralDiskPath string) error { return nil } - //if there is ephemeral disk we can safely autogrow, if not we should not. - if (ephemeralDiskPath == "") && (p.options.CreatePartitionIfNoEphemeralDisk == true) { + // if there is ephemeral disk we can safely autogrow, if not we should not. + if (ephemeralDiskPath == "") && p.options.CreatePartitionIfNoEphemeralDisk { p.logger.Info(logTag, "No Ephemeral Disk provided, Skipping growing of the Root Filesystem") return nil } // in case growpart is not available for another flavour of linux, don't stop the agent from running, // without this integration-test would not run since the bosh-lite vm doesn't have it - if p.cmdRunner.CommandExists("growpart") == false { + if !p.cmdRunner.CommandExists("growpart") { p.logger.Info(logTag, "The program 'growpart' is not installed, Root Filesystem cannot be grown") return nil } @@ -378,7 +378,7 @@ func (p linux) SetupRootDisk(ephemeralDiskPath string) error { ) if err != nil { - if strings.Contains(stdout, "NOCHANGE") == false { + if !strings.Contains(stdout, "NOCHANGE") { return bosherr.WrapError(err, "growpart") } } @@ -495,31 +495,33 @@ func (p linux) SetupIPv6(config boshsettings.IPv6) error { } func (p linux) SetupHostname(hostname string) error { - if !p.state.Linux.HostsConfigured { - _, _, _, err := p.cmdRunner.RunCommand("hostname", hostname) - if err != nil { - return bosherr.WrapError(err, "Setting hostname") - } + if p.state.Linux.HostsConfigured { + return nil + } - err = p.fs.WriteFileString("/etc/hostname", hostname) - if err != nil { - return bosherr.WrapError(err, "Writing to /etc/hostname") - } + _, _, _, err := p.cmdRunner.RunCommand("hostname", hostname) + if err != nil { + return bosherr.WrapError(err, "Setting hostname") + } - buffer, err := p.generateDefaultEtcHosts(hostname) - if err != nil { - return err - } - err = p.fs.WriteFile("/etc/hosts", buffer.Bytes()) - if err != nil { - return bosherr.WrapError(err, "Writing to /etc/hosts") - } + err = p.fs.WriteFileString("/etc/hostname", hostname) + if err != nil { + return bosherr.WrapError(err, "Writing to /etc/hostname") + } - p.state.Linux.HostsConfigured = true - err = p.state.SaveState() - if err != nil { - return bosherr.WrapError(err, "Setting up hostname") - } + buffer, err := p.generateDefaultEtcHosts(hostname) + if err != nil { + return err + } + err = p.fs.WriteFile("/etc/hosts", buffer.Bytes()) + if err != nil { + return bosherr.WrapError(err, "Writing to /etc/hosts") + } + + p.state.Linux.HostsConfigured = true + err = p.state.SaveState() + if err != nil { + return bosherr.WrapError(err, "Setting up hostname") } return nil @@ -591,7 +593,7 @@ func (p linux) SetupEphemeralDiskWithPath(realPath string, desiredSwapSizeInByte return bosherr.WrapErrorf(err, "Globbing ephemeral disk mount point `%s'", mountPointGlob) } - if contents != nil && len(contents) > 0 { + if len(contents) > 0 { // When agent bootstraps for the first time data directory should be empty. // It might be non-empty on subsequent agent restarts. The ephemeral disk setup // should be idempotent and partitioning will be skipped if disk is already @@ -694,13 +696,14 @@ func (p linux) SetupRawEphemeralDisks(devices []boshsettings.DiskSettings) (err if err != nil { // "unrecognised disk label" is acceptable, since the disk may not have been partitioned - if strings.Contains(stdout, "unrecognised disk label") == false && - strings.Contains(stderr, "unrecognised disk label") == false { + if !strings.Contains(stdout, "unrecognised disk label") && + !strings.Contains(stderr, "unrecognised disk label") { return bosherr.WrapError(err, "Setting up raw ephemeral disks") } } - if strings.Contains(stdout, "Partition Table: gpt") && strings.Contains(stdout, "raw-ephemeral-") { + if strings.Contains(stdout, "Partition Table: gpt") && + strings.Contains(stdout, "raw-ephemeral-") { continue } @@ -1082,8 +1085,8 @@ func (p linux) SetupOptDir() error { return bosherr.WrapError(err, "Chowning root var opt dir") } - //Mount our /var/opt bind mount without the 'noexec' option. Binaries are - //often in subdirectories of /var/opt, and folks expect to be able to execute them. + // Mount our /var/opt bind mount without the 'noexec' option. Binaries are + // often in subdirectories of /var/opt, and folks expect to be able to execute them. err = p.bindMountDir(boshRootVarOptDirPath, varOptDir, true) if err != nil { return err @@ -1102,8 +1105,8 @@ func (p linux) SetupOptDir() error { return bosherr.WrapError(err, "Chowning root opt dir") } - //Mount our /opt bind mount without the 'noexec' option. Binaries are - //often in subdirectories of /opt, and folks expect to be able to execute them. + // Mount our /opt bind mount without the 'noexec' option. Binaries are + // often in subdirectories of /opt, and folks expect to be able to execute them. err = p.bindMountDir(boshRootOptDirPath, optDir, true) if err != nil { return err @@ -1174,7 +1177,6 @@ func (p linux) changeTmpDirPermissions(path string) error { } func (p linux) AdjustPersistentDiskPartitioning(diskSetting boshsettings.DiskSettings, mountPoint string) error { - if p.options.UsePreformattedPersistentDisk { return nil } @@ -1198,7 +1200,7 @@ func (p linux) AdjustPersistentDiskPartitioning(diskSetting boshsettings.DiskSet } p.logger.Debug(logTag, "Persistent disk single partition needs resize: %+v", singlePartNeedsResize) - if singlePartNeedsResize { + if singlePartNeedsResize { //nolint:nestif err = partitioner.ResizeSinglePartition(devicePath) if err != nil { return bosherr.WrapError(err, "Resizing disk partition") @@ -1232,6 +1234,8 @@ func (p linux) AdjustPersistentDiskPartitioning(diskSetting boshsettings.DiskSet case boshdisk.FileSystemExt4, boshdisk.FileSystemXFS: case boshdisk.FileSystemDefault: persistentDiskFS = boshdisk.FileSystemExt4 + case boshdisk.FileSystemSwap: + fallthrough default: return bosherr.Error(fmt.Sprintf(`The filesystem type "%s" is not supported`, diskSetting.FileSystemType)) } @@ -1342,13 +1346,12 @@ func (p linux) IsMountPoint(path string) (string, bool, error) { return p.diskManager.GetMounter().IsMountPoint(path) } -func (p linux) MigratePersistentDisk(fromMountPoint, toMountPoint string) (err error) { +func (p linux) MigratePersistentDisk(fromMountPoint, toMountPoint string) error { p.logger.Debug(logTag, "Migrating persistent disk %v to %v", fromMountPoint, toMountPoint) - err = p.diskManager.GetMounter().RemountAsReadonly(fromMountPoint) + err := p.diskManager.GetMounter().RemountAsReadonly(fromMountPoint) if err != nil { - err = bosherr.WrapError(err, "Remounting persistent disk as readonly") - return + return bosherr.WrapError(err, "Remounting persistent disk as readonly") } // Golang does not implement a file copy that would allow us to preserve dates... @@ -1356,8 +1359,7 @@ func (p linux) MigratePersistentDisk(fromMountPoint, toMountPoint string) (err e tarCopy := fmt.Sprintf("(tar -C %s --xattrs -cf - .) | (tar -C %s --xattrs -xpf -)", fromMountPoint, toMountPoint) _, _, _, err = p.cmdRunner.RunCommand("sh", "-c", tarCopy) if err != nil { - err = bosherr.WrapError(err, "Copying files from old disk to new disk") - return + return bosherr.WrapError(err, "Copying files from old disk to new disk") } // Find iSCSI device id of fromMountPoint @@ -1365,14 +1367,13 @@ func (p linux) MigratePersistentDisk(fromMountPoint, toMountPoint string) (err e if p.options.DevicePathResolutionType == "iscsi" { mounts, err := p.diskManager.GetMountsSearcher().SearchMounts() if err != nil { - err = bosherr.WrapError(err, "Search persistent disk as readonly") - return err + return bosherr.WrapError(err, "Search persistent disk as readonly") } + devMapperPart1Regexp := regexp.MustCompile(`/dev/mapper/(.*?)-part1`) for _, mount := range mounts { if mount.MountPoint == fromMountPoint { - r := regexp.MustCompile(`\/dev\/mapper\/(.*?)-part1`) - matches := r.FindStringSubmatch(mount.PartitionPath) + matches := devMapperPart1Regexp.FindStringSubmatch(mount.PartitionPath) if len(matches) > 1 { iscsiID = matches[1] } @@ -1382,8 +1383,7 @@ func (p linux) MigratePersistentDisk(fromMountPoint, toMountPoint string) (err e _, err = p.diskManager.GetMounter().Unmount(fromMountPoint) if err != nil { - err = bosherr.WrapError(err, "Unmounting old persistent disk") - return + return bosherr.WrapError(err, "Unmounting old persistent disk") } err = p.diskManager.GetMounter().Remount(toMountPoint, fromMountPoint) @@ -1392,10 +1392,13 @@ func (p linux) MigratePersistentDisk(fromMountPoint, toMountPoint string) (err e } if p.options.DevicePathResolutionType == "iscsi" && iscsiID != "" { - p.flushMultipathDevice(iscsiID) + err = p.flushMultipathDevice(iscsiID) + if err != nil { + return err + } } - return + return err } func (p linux) IsPersistentDiskMounted(diskSettings boshsettings.DiskSettings) (bool, error) { diff --git a/platform/net/custom_network.go b/platform/net/custom_network.go deleted file mode 100644 index a02f47167..000000000 --- a/platform/net/custom_network.go +++ /dev/null @@ -1,36 +0,0 @@ -package net - -import ( - boship "github.com/cloudfoundry/bosh-agent/platform/net/ip" - boshsettings "github.com/cloudfoundry/bosh-agent/settings" -) - -type dnsConfigArg struct { - DNSServers []string -} - -type customNetwork struct { - boshsettings.Network - Interface string - NetworkIP string - Broadcast string - HasDefaultGateway bool -} - -type networkInterfaceConfigArg struct { - DNSServers []string - Networks []customNetwork - HasDNSNameServers bool -} - -func (c customNetwork) ToInterfaceAddress() boship.InterfaceAddress { - return boship.NewSimpleInterfaceAddress(c.Interface, c.IP) -} - -// toInterfaceAddresses bulk converts customNetworks to InterfaceAddresses -func toInterfaceAddresses(networks []customNetwork) (addresses []boship.InterfaceAddress) { - for _, network := range networks { - addresses = append(addresses, network.ToInterfaceAddress()) - } - return -} diff --git a/platform/net/default_network_resolver.go b/platform/net/default_network_resolver.go index 58f781dfa..a251ebab5 100644 --- a/platform/net/default_network_resolver.go +++ b/platform/net/default_network_resolver.go @@ -50,7 +50,6 @@ func (r defaultNetworkResolver) GetDefaultNetwork() (boshsettings.Network, error Netmask: gonet.IP(ip.Mask).String(), Gateway: route.Gateway, }, nil - } return network, bosherr.Error("Failed to find default route") diff --git a/platform/net/firewall_provider_windows.go b/platform/net/firewall_provider_windows.go index b22a263f9..d15bbc4a1 100644 --- a/platform/net/firewall_provider_windows.go +++ b/platform/net/firewall_provider_windows.go @@ -26,7 +26,7 @@ func SetupNatsFirewall(mbus string) error { } session, err := wf.New(&wf.Options{ Name: "Windows Firewall Session for Bosh Agent", - Dynamic: true, //setting this to true will create an ephemeral FW Rule that lasts as long as the Agent Process runs. + Dynamic: true, // setting this to true will create an ephemeral FW Rule that lasts as long as the Agent Process runs. }) if err != nil { return bosherr.WrapError(err, "Getting windows firewall session") @@ -54,8 +54,8 @@ func SetupNatsFirewall(mbus string) error { // wf.LayerALEAuthConnectV6, //#TODO: Do we need v6? } - // The windows app id will be used to create a conditional exception for the block outgoing nats rule. - appID, err := wf.AppID("C:\\bosh\\bosh-agent.exe") //Could this ever be somewhere else? + // The Windows app id will be used to create a conditional exception for the block outgoing nats rule. + appID, err := wf.AppID("C:\\bosh\\bosh-agent.exe") // Could this ever be somewhere else? if err != nil { return bosherr.WrapError(err, "Getting the windows app id for bosh-agent.exe") } @@ -93,7 +93,7 @@ func SetupNatsFirewall(mbus string) error { Sublayer: sublayerID, Weight: 1000, Conditions: []*wf.Match{ - // Block trafic to natsIp:natsPort + // Block traffic to natsIp:natsPort { Field: wf.FieldIPRemoteAddress, Op: wf.MatchTypePrefix, diff --git a/platform/net/interface_manager_windows.go b/platform/net/interface_manager_windows.go index 8910de59a..f720b5374 100644 --- a/platform/net/interface_manager_windows.go +++ b/platform/net/interface_manager_windows.go @@ -10,6 +10,10 @@ import ( "golang.org/x/sys/windows" ) +var ( + procGetAdaptersInfo = syscall.MustLoadDLL("iphlpapi.dll").MustFindProc("GetAdaptersInfo") //nolint:gochecknoglobals +) + type windowsInterfaceManager struct{} func NewInterfaceManager() InterfaceManager { @@ -17,12 +21,12 @@ func NewInterfaceManager() InterfaceManager { } func (windowsInterfaceManager) GetInterfaces() ([]Interface, error) { - var interfaces []Interface ifs, err := goNet.Interfaces() if err != nil { return nil, err } + interfaces := make([]Interface, 0, len(ifs)) for _, fs := range ifs { gateway, err := getGateway(fs.Index) if err != nil { @@ -34,6 +38,7 @@ func (windowsInterfaceManager) GetInterfaces() ([]Interface, error) { } interfaces = append(interfaces, netInterface) } + return interfaces, nil } @@ -69,7 +74,7 @@ func getAdaptersInfo() (*windows.IpAdapterInfo, error) { uintptr(unsafe.Pointer(&bufLen)), 0, ) - switch syscall.Errno(r0) { + switch syscall.Errno(r0) { //nolint:exhaustive case 0: return (*windows.IpAdapterInfo)(unsafe.Pointer(&buf[0])), nil case windows.ERROR_BUFFER_OVERFLOW: diff --git a/platform/net/ip/interface_addresses_validator.go b/platform/net/ip/interface_addresses_validator.go index e91ead34d..f31b882fb 100644 --- a/platform/net/ip/interface_addresses_validator.go +++ b/platform/net/ip/interface_addresses_validator.go @@ -32,7 +32,7 @@ func (i InterfaceAddressesValidator) Attempt() (bool, error) { return true, bosherr.Errorf("Validating network interface '%s' IP addresses, no interface configured with that name", ifaceName) } - actualIPs := []string{} + var actualIPs []string desiredIP, _ := desiredInterfaceAddress.GetIP() for _, iface := range ifaces { actualIP, _ := iface.GetIP() @@ -43,14 +43,14 @@ func (i InterfaceAddressesValidator) Attempt() (bool, error) { actualIPs = append(actualIPs, actualIP) } - return true, bosherr.Errorf("Validating network interface '%s' IP addresses, expected: '%s', actual: [%s]", ifaceName, desiredIP, strings.Join(actualIPs, ", ")) + return true, bosherr.Errorf("Validating network interface '%s' IP addresses, expected: '%s', actual: [%s]", ifaceName, desiredIP, strings.Join(actualIPs, ", ")) //nolint:staticcheck } return false, nil } func (i InterfaceAddressesValidator) findInterfaceByName(ifaceName string, ifaces []InterfaceAddress) []InterfaceAddress { - result := []InterfaceAddress{} + result := make([]InterfaceAddress, 0, len(ifaces)) for _, iface := range ifaces { if iface.GetInterfaceName() == ifaceName { result = append(result, iface) diff --git a/platform/net/kernel_ipv6.go b/platform/net/kernel_ipv6.go index bd840582f..ba3e9bfb2 100644 --- a/platform/net/kernel_ipv6.go +++ b/platform/net/kernel_ipv6.go @@ -34,7 +34,7 @@ func (net KernelIPv6Impl) Enable(stopCh <-chan struct{}) error { } if strings.Contains(grubConf, grubIPv6DisableOpt) { - grubConf = strings.Replace(grubConf, grubIPv6DisableOpt, "", -1) + grubConf = strings.ReplaceAll(grubConf, grubIPv6DisableOpt, "") err = net.fs.WriteFileString(grubConfPath, grubConf) if err != nil { diff --git a/platform/net/routes_searcher_unix.go b/platform/net/routes_searcher_unix.go index c61c336d9..4794a56dc 100644 --- a/platform/net/routes_searcher_unix.go +++ b/platform/net/routes_searcher_unix.go @@ -55,14 +55,14 @@ func parseRoute(ipString string) (Route, error) { } func (s cmdRoutesSearcher) SearchRoutes() ([]Route, error) { - var routes []Route - stdout, _, _, err := s.runner.RunCommandQuietly("ip", "r") if err != nil { - return routes, bosherr.WrapError(err, "Running route") + return []Route{}, bosherr.WrapError(err, "Running route") } - for _, routeEntry := range strings.Split(stdout, "\n") { + routeEntries := strings.Split(stdout, "\n") + routes := make([]Route, 0, len(routeEntries)) + for _, routeEntry := range routeEntries { if len(routeEntry) == 0 { continue } diff --git a/platform/net/routes_searcher_windows.go b/platform/net/routes_searcher_windows.go index 47a948379..2bf46dd51 100644 --- a/platform/net/routes_searcher_windows.go +++ b/platform/net/routes_searcher_windows.go @@ -1,18 +1,11 @@ package net import ( - "syscall" - bosherr "github.com/cloudfoundry/bosh-utils/errors" boshlog "github.com/cloudfoundry/bosh-utils/logger" boshsys "github.com/cloudfoundry/bosh-utils/system" ) -var ( - modiphlpapi = syscall.MustLoadDLL("iphlpapi.dll") - procGetAdaptersInfo = modiphlpapi.MustFindProc("GetAdaptersInfo") -) - type windowsRoutesSearcher struct { interfaceManager InterfaceManager cmdRunner boshsys.CmdRunner @@ -27,11 +20,13 @@ func (s windowsRoutesSearcher) SearchRoutes() ([]Route, error) { if err != nil { return nil, bosherr.WrapError(err, "Running route") } - var routes []Route + defaultGateway, _, _, err := s.cmdRunner.RunCommandQuietly("(Get-NetRoute -DestinationPrefix '0.0.0.0/0').NextHop") if err != nil { return nil, bosherr.WrapError(err, "Running route") } + + routes := make([]Route, 0, len(ifs)) for _, fs := range ifs { route := Route{ InterfaceName: fs.Name, @@ -42,8 +37,10 @@ func (s windowsRoutesSearcher) SearchRoutes() ([]Route, error) { } routes = append(routes, route) } + if len(routes) == 0 { return nil, bosherr.Error("no routes") } + return routes, nil } diff --git a/platform/net/ubuntu_net_manager.go b/platform/net/ubuntu_net_manager.go index b2f1efd4e..782d61913 100644 --- a/platform/net/ubuntu_net_manager.go +++ b/platform/net/ubuntu_net_manager.go @@ -22,7 +22,31 @@ import ( ini "github.com/cloudfoundry/bosh-agent/ini" ) -const UbuntuNetManagerLogTag = "UbuntuNetManager" +const ( + UbuntuNetManagerLogTag = "UbuntuNetManager" + + systemdNetworkFolder = "/etc/systemd/network" + + // DHCP Config file - /etc/dhcp/dhclient.conf + // Ubuntu 14.04 accepts several DNS as a list in a single prepend directive + dhclientConfTemplate = `# Generated by bosh-agent + +option rfc3442-classless-static-routes code 121 = array of unsigned integer 8; + +send host-name = gethostname(); + +request subnet-mask, broadcast-address, time-offset, routers, + domain-name, domain-name-servers, domain-search, host-name, + netbios-name-servers, netbios-scope, interface-mtu, + rfc3442-classless-static-routes, ntp-servers; +{{ if . }} +prepend domain-name-servers {{ . }};{{ end }} +` + + resolvConfTemplate = `# Generated by bosh-agent +{{ range .DNSServers }}nameserver {{ . }} +{{ end }}` +) type UbuntuNetManager struct { cmdRunner boshsys.CmdRunner @@ -64,13 +88,12 @@ func NewUbuntuNetManager( } func (net UbuntuNetManager) GetConfiguredNetworkInterfaces() ([]string, error) { - interfaces := []string{} - interfacesByMacAddress, err := net.macAddressDetector.DetectMacAddresses() if err != nil { - return interfaces, bosherr.WrapError(err, "Getting network interfaces") + return []string{}, bosherr.WrapError(err, "Getting network interfaces") } + interfaces := make([]string, 0, len(interfacesByMacAddress)) for _, iface := range interfacesByMacAddress { if net.fs.FileExists(interfaceConfigurationFile(iface)) { interfaces = append(interfaces, iface) @@ -89,7 +112,6 @@ func (net UbuntuNetManager) SetupIPv6(config boshsettings.IPv6, stopCh <-chan st func (net UbuntuNetManager) SetupNetworking(networks boshsettings.Networks, mbus string, errCh chan error) error { if networks.IsPreconfigured() { - // Note in this case IPs are not broadcast dnsNetwork, _ := networks.DefaultNetworkFor("dns") err := net.writeResolvConf(dnsNetwork.DNS) @@ -132,12 +154,9 @@ func (net UbuntuNetManager) SetupNetworking(networks boshsettings.Networks, mbus staticAddresses, dynamicAddresses := net.ifaceAddresses(staticConfigs, dhcpConfigs) var staticAddressesWithoutVirtual []boship.InterfaceAddress - r, err := regexp.Compile(`:\d+`) - if err != nil { - return bosherr.WrapError(err, "There is a problem with your regexp: ':\\d+'. That is used to skip validation of virtual interfaces(e.g., eth0:0, eth0:1)") - } + r := regexp.MustCompile(`:\d+`) for _, addr := range staticAddresses { - if r.MatchString(addr.GetInterfaceName()) == true { + if r.MatchString(addr.GetInterfaceName()) { continue } else { staticAddressesWithoutVirtual = append(staticAddressesWithoutVirtual, addr) @@ -199,8 +218,6 @@ func (net UbuntuNetManager) ComputeNetworkConfig(networks boshsettings.Networks) } func (net UbuntuNetManager) collapseVirtualInterfaces(staticConfigs []StaticInterfaceConfiguration) ([]StaticInterfaceConfiguration, error) { - configs := []StaticInterfaceConfiguration{} - // collect any virtual interfaces virtualInterfacesByDevice := map[string][]VirtualInterface{} for _, config := range staticConfigs { @@ -222,6 +239,7 @@ func (net UbuntuNetManager) collapseVirtualInterfaces(staticConfigs []StaticInte } } + configs := make([]StaticInterfaceConfiguration, 0, len(staticConfigs)) // keep non-virtual interfaces, and append if found for _, config := range staticConfigs { if !strings.Contains(config.Name, ":") { @@ -241,7 +259,6 @@ func (net UbuntuNetManager) writeNetConfigs( staticConfigs StaticInterfaceConfigurations, dnsServers []string, opts boshsys.ConvergeFileContentsOpts) (bool, error) { - interfacesChanged, err := net.writeNetworkInterfaces(dhcpConfigs, staticConfigs, dnsServers, opts) if err != nil { return false, bosherr.WrapError(err, "Writing network configuration") @@ -256,7 +273,7 @@ func (net UbuntuNetManager) writeNetConfigs( } } - return (interfacesChanged || dhcpChanged), nil + return interfacesChanged || dhcpChanged, nil } func (net UbuntuNetManager) removeDhcpDNSConfiguration() error { @@ -292,10 +309,6 @@ func (net UbuntuNetManager) buildInterfaces(networks boshsettings.Networks) ([]S return nil, nil, bosherr.WrapError(err, "Getting network interfaces") } - // if len(interfacesByMacAddress) == 0 { - // return nil, nil, bosherr.Error("No network interfaces found") - // } - staticConfigs, dhcpConfigs, err := net.interfaceConfigurationCreator.CreateInterfaceConfigurations(networks, interfacesByMacAddress) if err != nil { return nil, nil, bosherr.WrapError(err, "Creating interface configurations") @@ -305,11 +318,12 @@ func (net UbuntuNetManager) buildInterfaces(networks boshsettings.Networks) ([]S } func (net UbuntuNetManager) ifaceAddresses(staticConfigs []StaticInterfaceConfiguration, dhcpConfigs []DHCPInterfaceConfiguration) ([]boship.InterfaceAddress, []boship.InterfaceAddress) { - staticAddresses := []boship.InterfaceAddress{} + staticAddresses := make([]boship.InterfaceAddress, 0, len(staticConfigs)) for _, iface := range staticConfigs { staticAddresses = append(staticAddresses, boship.NewSimpleInterfaceAddress(iface.Name, iface.Address)) } - dynamicAddresses := []boship.InterfaceAddress{} + + dynamicAddresses := make([]boship.InterfaceAddress, 0, len(dhcpConfigs)) for _, iface := range dhcpConfigs { dynamicAddresses = append(dynamicAddresses, boship.NewResolvingInterfaceAddress(iface.Name, net.ipResolver)) } @@ -347,30 +361,6 @@ func (net UbuntuNetManager) writeDHCPConfiguration(dnsServers []string, opts bos return changed, nil } -func (net UbuntuNetManager) updateConfiguration(name, templateDefinition string, templateConfiguration interface{}, opts boshsys.ConvergeFileContentsOpts) (bool, error) { - interfaceFile := interfaceConfigurationFile(name) - buffer := bytes.NewBuffer([]byte{}) - templateFuncs := template.FuncMap{ - "NetmaskToCIDR": boshsettings.NetmaskToCIDR, - } - - t := template.Must(template.New(name).Funcs(templateFuncs).Parse(templateDefinition)) - - err := t.Execute(buffer, templateConfiguration) - if err != nil { - return false, bosherr.WrapError(err, fmt.Sprintf("Generating config from template %s", name)) - } - - net.logger.Error(UbuntuNetManagerLogTag, "Updating %s configuration with contents: %s", name, buffer.Bytes()) - return net.fs.ConvergeFileContents( - interfaceFile, - buffer.Bytes(), - opts, - ) -} - -const systemdNetworkFolder = "/etc/systemd/network" - func interfaceConfigurationFile(name string) string { interfaceBasename := fmt.Sprintf("10_%s.network", name) return filepath.Join(systemdNetworkFolder, interfaceBasename) @@ -381,18 +371,11 @@ func (net UbuntuNetManager) writeNetworkInterfaces( staticConfigs StaticInterfaceConfigurations, dnsServers []string, opts boshsys.ConvergeFileContentsOpts) (bool, error) { - - type networkInterfaceConfig struct { - DNSServers []string - InterfaceConfig interface{} - HasDNSNameServers bool - } - sort.Stable(dhcpConfigs) sort.Stable(staticConfigs) staleNetworkConfigFiles := make(map[string]bool) - err := net.fs.Walk(filepath.Join(systemdNetworkFolder), func(match string, _ os.FileInfo, err error) error { + err := net.fs.Walk(systemdNetworkFolder, func(match string, _ os.FileInfo, err error) error { if err != nil { return err } @@ -448,17 +431,6 @@ func (net UbuntuNetManager) writeNetworkInterfaces( return anyChanged, nil } -func (net UbuntuNetManager) ifaceNames(dhcpConfigs DHCPInterfaceConfigurations, staticConfigs StaticInterfaceConfigurations) []string { - ifaceNames := []string{} - for _, config := range dhcpConfigs { - ifaceNames = append(ifaceNames, config.Name) - } - for _, config := range staticConfigs { - ifaceNames = append(ifaceNames, config.Name) - } - return ifaceNames -} - func (net UbuntuNetManager) writeResolvConf(dnsServers []string) error { buffer := bytes.NewBuffer([]byte{}) @@ -475,7 +447,7 @@ func (net UbuntuNetManager) writeResolvConf(dnsServers []string) error { return bosherr.WrapError(err, "Generating DNS config from template") } - if len(dnsServers) > 0 { + if len(dnsServers) > 0 { //nolint:nestif // Write out base so that releases may overwrite head err = net.fs.WriteFile("/etc/resolvconf/resolv.conf.d/base", buffer.Bytes()) if err != nil { @@ -638,22 +610,3 @@ func (net UbuntuNetManager) writeDynamicInterfaceConfiguration(config DHCPInterf return net.fs.ConvergeFileContents(configPath, buffer.Bytes(), opts) } - -// DHCP Config file - /etc/dhcp/dhclient.conf -// Ubuntu 14.04 accepts several DNS as a list in a single prepend directive -const dhclientConfTemplate = `# Generated by bosh-agent - -option rfc3442-classless-static-routes code 121 = array of unsigned integer 8; - -send host-name = gethostname(); - -request subnet-mask, broadcast-address, time-offset, routers, - domain-name, domain-name-servers, domain-search, host-name, - netbios-name-servers, netbios-scope, interface-mtu, - rfc3442-classless-static-routes, ntp-servers; -{{ if . }} -prepend domain-name-servers {{ . }};{{ end }} -` -const resolvConfTemplate = `# Generated by bosh-agent -{{ range .DNSServers }}nameserver {{ . }} -{{ end }}` diff --git a/platform/net/windows_net_manager.go b/platform/net/windows_net_manager.go index 8f608eebc..09b852684 100644 --- a/platform/net/windows_net_manager.go +++ b/platform/net/windows_net_manager.go @@ -188,7 +188,6 @@ func (net WindowsNetManager) ComputeNetworkConfig(networks boshsettings.Networks dnsNetwork, _ := nonVipNetworks.DefaultNetworkFor("dns") dnsServers := dnsNetwork.DNS return staticConfigs, dhcpConfigs, dnsServers, nil - } func (net WindowsNetManager) SetupIPv6(_ boshsettings.IPv6, _ <-chan struct{}) error { return nil } @@ -215,7 +214,6 @@ func (net WindowsNetManager) buildInterfaces(networks boshsettings.Networks) ( []DHCPInterfaceConfiguration, error, ) { - interfacesByMacAddress, err := net.macAddressDetector.DetectMacAddresses() if err != nil { return nil, nil, bosherr.WrapError(err, "Getting network interfaces") diff --git a/platform/openiscsi/concrete_open_iscsi_admin.go b/platform/openiscsi/concrete_open_iscsi_admin.go index 84a1335c0..cb4ed2d61 100644 --- a/platform/openiscsi/concrete_open_iscsi_admin.go +++ b/platform/openiscsi/concrete_open_iscsi_admin.go @@ -28,7 +28,7 @@ func NewConcreteOpenIscsiAdmin(fs boshsys.FileSystem, runner boshsys.CmdRunner, } } -func (iscsi concreteOpenIscsiAdmin) Setup(iqn, username, password string) (err error) { +func (iscsi concreteOpenIscsiAdmin) Setup(iqn, username, password string) error { iscsi.logger.Info(iscsi.logtag, "Setup Open-iscsi, initializing /etc/iscsi/initiatorname.iscsi,iscsid.conf") buffer := bytes.NewBuffer([]byte{}) t := template.Must(template.New("Open-iscsi-initiator").Parse(initiatorNameIscsiTemplate)) @@ -37,16 +37,14 @@ func (iscsi concreteOpenIscsiAdmin) Setup(iqn, username, password string) (err e Iqn string } - err = t.Execute(buffer, initiatorNameArgs{iqn}) + err := t.Execute(buffer, initiatorNameArgs{iqn}) if err != nil { - err = bosherr.WrapError(err, "Generating initiatorname.iscsi of Open-iscsi") - return + return bosherr.WrapError(err, "Generating initiatorname.iscsi of Open-iscsi") } err = iscsi.fs.WriteFile(path.Join("/etc/iscsi", "initiatorname.iscsi"), buffer.Bytes()) if err != nil { - err = bosherr.WrapError(err, "Writing to /etc/iscsi/initiatorname.iscsi") - return + return bosherr.WrapError(err, "Writing to /etc/iscsi/initiatorname.iscsi") } buffer.Reset() @@ -59,30 +57,27 @@ func (iscsi concreteOpenIscsiAdmin) Setup(iqn, username, password string) (err e t = template.Must(template.New("Open-iscsi-conf").Parse(iscsidConfTemplate)) err = t.Execute(buffer, iscsidConfArgs{username, password}) if err != nil { - err = bosherr.WrapError(err, "Generating iscsid.conf of Open-iscsi") - return + return bosherr.WrapError(err, "Generating iscsid.conf of Open-iscsi") } err = iscsi.fs.WriteFile(path.Join("/etc/iscsi", "iscsid.conf"), buffer.Bytes()) if err != nil { - err = bosherr.WrapError(err, "Writing to /etc/iscsi/iscsid.conf") - return + return bosherr.WrapError(err, "Writing to /etc/iscsi/iscsid.conf") } buffer.Reset() err = iscsi.Restart() if err != nil { - err = bosherr.WrapError(err, "Restarting iscsi after modifying the /etc/iscsi/iscsid.conf file") - return + return bosherr.WrapError(err, "Restarting iscsi after modifying the /etc/iscsi/iscsid.conf file") } _, _, _, err = iscsi.runner.RunCommand("/etc/init.d/multipath-tools", "restart") if err != nil { - err = bosherr.WrapError(err, "Restarting multipath after restarting open-iscsi") - return + return bosherr.WrapError(err, "Restarting multipath after restarting open-iscsi") } - return + + return nil } // Open-iscsi initiator file - /etc/iscsi/initiatorname.iscsi @@ -165,10 +160,7 @@ func (iscsi concreteOpenIscsiAdmin) IsLoggedin() (bool, error) { return false, bosherr.WrapError(err, "Checking all current sessions logged in") } - r, err := regexp.Compile(`^tcp: \[\d+\]`) - if err != nil { - return false, bosherr.WrapError(err, "There is a problem with your regexp: '^tcp: \\[\\d+\\]'. That is used to check iscsi session(e.g., tcp: [sid] portal target)") - } + r := regexp.MustCompile(`^tcp: \[\d+\]`) if r.MatchString(stdout) { return true, nil } diff --git a/platform/syscall_unix.go b/platform/syscall_unix.go index 8b0c1e412..1b92779f5 100644 --- a/platform/syscall_unix.go +++ b/platform/syscall_unix.go @@ -27,10 +27,6 @@ func localAccountNames() ([]string, error) { return nil, ErrNotImplemented } -func isServiceRunning(_ string) error { - return ErrNotImplemented -} - func sshEnabled() error { return ErrNotImplemented } diff --git a/platform/syscall_windows.go b/platform/syscall_windows.go index f4afd19b3..ff218d7f1 100644 --- a/platform/syscall_windows.go +++ b/platform/syscall_windows.go @@ -24,19 +24,19 @@ import ( ) var ( - userenv = windows.NewLazySystemDLL("userenv.dll") - netapi32 = windows.NewLazySystemDLL("Netapi32.dll") + userenv = windows.NewLazySystemDLL("userenv.dll") //nolint:gochecknoglobals + netapi32 = windows.NewLazySystemDLL("Netapi32.dll") //nolint:gochecknoglobals - procCreateProfile = userenv.NewProc("CreateProfile") - procDeleteProfile = userenv.NewProc("DeleteProfileW") - procGetProfilesDirectory = userenv.NewProc("GetProfilesDirectoryW") - procNetUserEnum = netapi32.NewProc("NetUserEnum") + procCreateProfile = userenv.NewProc("CreateProfile") //nolint:gochecknoglobals + procDeleteProfile = userenv.NewProc("DeleteProfileW") //nolint:gochecknoglobals,unused + procGetProfilesDirectory = userenv.NewProc("GetProfilesDirectoryW") //nolint:gochecknoglobals + procNetUserEnum = netapi32.NewProc("NetUserEnum") //nolint:gochecknoglobals ) // createProfile, creates the profile and home directory of the user identified // by Security Identifier sid. func createProfile(sid, username string) (string, error) { - const S_OK = 0x00000000 + const S_OK = 0x00000000 //nolint:revive if err := procCreateProfile.Find(); err != nil { return "", err } @@ -69,7 +69,7 @@ func createProfile(sid, username string) (string, error) { // deleteProfile, deletes the profile and home directory of the user identified // by Security Identifier sid. -func deleteProfile(sid string) error { +func deleteProfile(sid string) error { //nolint:deadcode,unused if err := procDeleteProfile.Find(); err != nil { return err } @@ -292,8 +292,8 @@ func deleteLocalUser(username string) error { } func localAccountNames() ([]string, error) { - const MAX_PREFERRED_LENGTH = 0xffffffff - const FILTER_NORMAL_ACCOUNT = 2 + const MAX_PREFERRED_LENGTH = 0xffffffff //nolint:revive + const FILTER_NORMAL_ACCOUNT = 2 //nolint:revive if err := procNetUserEnum.Find(); err != nil { return nil, err @@ -319,16 +319,16 @@ func localAccountNames() ([]string, error) { if e1 == syscall.ERROR_MORE_DATA { // This shouldn't happen, but in case // it does we need to free the buffer - windows.NetApiBufferFree(buf) + windows.NetApiBufferFree(buf) //nolint:errcheck } if e1 == 0 { return nil, os.NewSyscallError("NetUserEnum", syscall.EINVAL) } return nil, os.NewSyscallError("NetUserEnum", e1) } - defer windows.NetApiBufferFree(buf) + defer windows.NetApiBufferFree(buf) //nolint:errcheck - type USER_INFO_0 struct { + type USER_INFO_0 struct { //nolint:revive Name *uint16 } type sliceHeader struct { @@ -361,14 +361,14 @@ func serviceDisabled(s *mgr.Service) bool { } // Make the function called by GetHostPublicKey configurable for testing. -var sshEnabled func() error = checkSSH +var sshEnabled func() error = checkSSH //nolint:gochecknoglobals,revive // checkSSH checks if the sshd service is installed and running. // // The services are installed during stemcell creation, but are disabled. The // job windows-utilities-release/enable_ssh job is used to enable ssh. func checkSSH() error { - const ERROR_SERVICE_DOES_NOT_EXIST syscall.Errno = 0x424 + const ERROR_SERVICE_DOES_NOT_EXIST syscall.Errno = 0x424 //nolint:revive const msgFmt = "%s service not running and start type is disabled. " + "To enable ssh on Windows you must run the enable_ssh job from the " + @@ -378,7 +378,7 @@ func checkSSH() error { if err != nil { return fmt.Errorf("opening service control manager: %s", err) } - defer m.Disconnect() + defer m.Disconnect() //nolint:errcheck sshd, err := m.OpenService("sshd") if err != nil { @@ -413,7 +413,7 @@ func disableWindowsUpdates() error { if err != nil { return fmt.Errorf("opening service control manager: %s", err) } - defer m.Disconnect() + defer m.Disconnect() //nolint:errcheck s, err := m.OpenService("wuauserv") if err != nil { diff --git a/platform/udevdevice/concrete_udev_device.go b/platform/udevdevice/concrete_udev_device.go index 7c031d279..2bfe80fb6 100644 --- a/platform/udevdevice/concrete_udev_device.go +++ b/platform/udevdevice/concrete_udev_device.go @@ -37,34 +37,34 @@ func (udev ConcreteUdevDevice) KickDevice(filePath string) { if err := udev.readByte(filePath); err != nil { udev.logger.Error(udev.logtag, "Failed to read byte from device: %s", err.Error()) } - - return } -func (udev ConcreteUdevDevice) Settle() (err error) { +func (udev ConcreteUdevDevice) Settle() error { udev.logger.Debug(udev.logtag, "Settling UdevDevice") switch { case udev.runner.CommandExists("udevadm"): - _, _, _, err = udev.runner.RunCommand("udevadm", "settle") + _, _, _, err := udev.runner.RunCommand("udevadm", "settle") + return err case udev.runner.CommandExists("udevsettle"): - _, _, _, err = udev.runner.RunCommand("udevsettle") + _, _, _, err := udev.runner.RunCommand("udevsettle") + return err default: - err = bosherr.Error("can not find udevadm or udevsettle commands") + return bosherr.Error("can not find udevadm or udevsettle commands") } - return } -func (udev ConcreteUdevDevice) Trigger() (err error) { +func (udev ConcreteUdevDevice) Trigger() error { udev.logger.Debug(udev.logtag, "Triggering UdevDevice") switch { case udev.runner.CommandExists("udevadm"): - _, _, _, err = udev.runner.RunCommand("udevadm", "trigger") + _, _, _, err := udev.runner.RunCommand("udevadm", "trigger") + return err case udev.runner.CommandExists("udevtrigger"): - _, _, _, err = udev.runner.RunCommand("udevtrigger") + _, _, _, err := udev.runner.RunCommand("udevtrigger") + return err default: - err = bosherr.Error("can not find udevadm or udevtrigger commands") + return bosherr.Error("can not find udevadm or udevtrigger commands") } - return } func (udev ConcreteUdevDevice) EnsureDeviceReadable(filePath string) error { @@ -100,7 +100,7 @@ func (udev ConcreteUdevDevice) readByte(filePath string) error { }() udev.logger.Debug(udev.logtag, "Successfully open file: %s", filePath) - bytes := make([]byte, 1, 1) + bytes := make([]byte, 1) read, err := device.Read(bytes) if err != nil { return err diff --git a/platform/vitals/service.go b/platform/vitals/service.go index 55d038dd5..dd243af9d 100644 --- a/platform/vitals/service.go +++ b/platform/vitals/service.go @@ -3,7 +3,7 @@ package vitals import ( "fmt" - "github.com/cloudfoundry/gosigar" + sigar "github.com/cloudfoundry/gosigar" boshdisk "github.com/cloudfoundry/bosh-agent/platform/disk" boshstats "github.com/cloudfoundry/bosh-agent/platform/stats" @@ -35,7 +35,7 @@ func NewService( } } -func (s concreteService) Get() (vitals Vitals, err error) { +func (s concreteService) Get() (Vitals, error) { var ( loadStats boshstats.CPULoad cpuStats boshstats.CPUStats @@ -45,43 +45,39 @@ func (s concreteService) Get() (vitals Vitals, err error) { diskStats DiskVitals ) - loadStats, err = s.statsCollector.GetCPULoad() + vitals := Vitals{} + + loadStats, err := s.statsCollector.GetCPULoad() if err != nil && err != sigar.ErrNotImplemented { - err = bosherr.WrapError(err, "Getting CPU Load") - return + return vitals, bosherr.WrapError(err, "Getting CPU Load") } cpuStats, err = s.statsCollector.GetCPUStats() if err != nil { - err = bosherr.WrapError(err, "Getting CPU Stats") - return + return vitals, bosherr.WrapError(err, "Getting CPU Stats") } memStats, err = s.statsCollector.GetMemStats() if err != nil { - err = bosherr.WrapError(err, "Getting Memory Stats") - return + return vitals, bosherr.WrapError(err, "Getting Memory Stats") } swapStats, err = s.statsCollector.GetSwapStats() if err != nil { - err = bosherr.WrapError(err, "Getting Swap Stats") - return + return vitals, bosherr.WrapError(err, "Getting Swap Stats") } diskStats, err = s.getDiskStats() if err != nil { - err = bosherr.WrapError(err, "Getting Disk Stats") - return + return vitals, bosherr.WrapError(err, "Getting Disk Stats") } uptimeStats, err = s.statsCollector.GetUptimeStats() if err != nil { - err = bosherr.WrapError(err, "Getting Uptime Stats") - return + return vitals, bosherr.WrapError(err, "Getting Uptime Stats") } - vitals = Vitals{ + return Vitals{ Load: createLoadVitals(loadStats), CPU: CPUVitals{ User: cpuStats.UserPercent().FormatFractionOf100(1), @@ -92,56 +88,52 @@ func (s concreteService) Get() (vitals Vitals, err error) { Swap: createMemVitals(swapStats), Disk: diskStats, Uptime: UptimeVitals{Secs: uptimeStats.Secs}, - } - return + }, nil } -func (s concreteService) getDiskStats() (diskStats DiskVitals, err error) { +func (s concreteService) getDiskStats() (DiskVitals, error) { disks := map[string]string{ "/": "system", s.dirProvider.DataDir(): "ephemeral", s.dirProvider.StoreDir(): "persistent", } - diskStats = make(DiskVitals, len(disks)) + diskStats := make(DiskVitals, len(disks)) for path, name := range disks { - diskStats, err = s.addDiskStats(diskStats, path, name) + diskStats, err := s.addDiskStats(diskStats, path, name) if err != nil { - return + return diskStats, err } } - return + return diskStats, nil } -func (s concreteService) addDiskStats(diskStats DiskVitals, path, name string) (updated DiskVitals, err error) { - updated = diskStats - +func (s concreteService) addDiskStats(diskStats DiskVitals, path, name string) (DiskVitals, error) { if s.diskMounter != nil { var isMountPoint bool - _, isMountPoint, err = s.diskMounter.IsMountPoint(path) + _, isMountPoint, err := s.diskMounter.IsMountPoint(path) if err != nil { - err = bosherr.WrapError(err, fmt.Sprintf("Verifying if '%s' is a mount point", path)) - return + return diskStats, bosherr.WrapError(err, fmt.Sprintf("Verifying if '%s' is a mount point", path)) } if !isMountPoint { - return + return diskStats, nil } } stat, diskErr := s.statsCollector.GetDiskStats(path) if diskErr != nil { if path == "/" { - err = bosherr.WrapError(diskErr, "Getting Disk Stats for /") + return diskStats, bosherr.WrapError(diskErr, "Getting Disk Stats for /") } - return + return diskStats, nil } - updated[name] = SpecificDiskVitals{ + diskStats[name] = SpecificDiskVitals{ Percent: stat.DiskUsage.Percent().FormatFractionOf100(0), InodePercent: stat.InodeUsage.Percent().FormatFractionOf100(0), } - return + return diskStats, nil } func createMemVitals(memUsage boshstats.Usage) MemoryVitals { diff --git a/platform/windows_platform.go b/platform/windows_platform.go index 61ad6fd48..3ad213dc9 100644 --- a/platform/windows_platform.go +++ b/platform/windows_platform.go @@ -39,7 +39,7 @@ type WindowsDiskManager interface { // Administrator user name, this currently exists for testing, but may be useful // if we ever change the Admin user name for security reasons. -var administratorUserName = "Administrator" +var administratorUserName = "Administrator" //nolint:gochecknoglobals type WindowsOptions struct { // Feature flag during ephemeral disk support rollout @@ -293,7 +293,6 @@ func (p WindowsPlatform) GetUpdateSettingsPath(tmpfs bool) string { } func (p WindowsPlatform) SetupSSH(publicKey []string, username string) error { - if username == boshsettings.VCAPUsername { if !userExists(username) { err := p.CreateUser(username, "") @@ -342,7 +341,7 @@ func (p WindowsPlatform) SetUserPassword(user, encryptedPwd string) (err error) return } -func (p WindowsPlatform) SaveDNSRecords(dnsRecords boshsettings.DNSRecords, hostname string) (err error) { +func (p WindowsPlatform) SaveDNSRecords(dnsRecords boshsettings.DNSRecords, hostname string) error { windir := os.Getenv("windir") if windir == "" { return bosherr.Error("SaveDNSRecords: missing %WINDIR% env variable") @@ -378,7 +377,7 @@ func (p WindowsPlatform) SaveDNSRecords(dnsRecords boshsettings.DNSRecords, host if err := p.fs.Rename(tmpfile, hostfile); err != nil { return bosherr.WrapErrorf(err, "SaveDNSRecords: renaming %s to %s", tmpfile, hostfile) } - return + return nil } func (p WindowsPlatform) SetupIPv6(config boshsettings.IPv6) error { @@ -401,19 +400,17 @@ func (p WindowsPlatform) GetCertManager() (certManager boshcert.Manager) { return p.certManager } -func (p WindowsPlatform) SetupLogrotate(groupName, basePath, size string) (err error) { - return +func (p WindowsPlatform) SetupLogrotate(groupName, basePath, size string) error { + return nil } -func (p WindowsPlatform) SetTimeWithNtpServers(servers []string) (err error) { +func (p WindowsPlatform) SetTimeWithNtpServers(servers []string) error { if len(servers) == 0 { - return + return nil } - var ( - stderr string - ) + ntpServers := strings.Join(servers, " ") - _, stderr, _, err = p.cmdRunner.RunCommand("powershell.exe", + _, stderr, _, err := p.cmdRunner.RunCommand("powershell.exe", "new-netfirewallrule", "-displayname", "NTP", "-direction", "outbound", @@ -421,8 +418,7 @@ func (p WindowsPlatform) SetTimeWithNtpServers(servers []string) (err error) { "-protocol", "udp", "-RemotePort", "123") if err != nil { - err = bosherr.WrapErrorf(err, "SetTimeWithNtpServers %s", stderr) - return + return bosherr.WrapErrorf(err, "SetTimeWithNtpServers %s", stderr) } _, _, _, _ = p.cmdRunner.RunCommand("net", "stop", "w32time") @@ -434,21 +430,18 @@ func (p WindowsPlatform) SetTimeWithNtpServers(servers []string) (err error) { "/syncfromflags:manual", manualPeerList) if err != nil { - err = bosherr.WrapErrorf(err, "SetTimeWithNtpServers %s", stderr) - return + return bosherr.WrapErrorf(err, "SetTimeWithNtpServers %s", stderr) } _, _, _, _ = p.cmdRunner.RunCommand("net", "start", "w32time") _, stderr, _, err = p.cmdRunner.RunCommand("w32tm", "/config", "/update") if err != nil { - err = bosherr.WrapErrorf(err, "SetTimeWithNtpServers %s", stderr) - return + return bosherr.WrapErrorf(err, "SetTimeWithNtpServers %s", stderr) } _, stderr, _, err = p.cmdRunner.RunCommand("w32tm", "/resync", "/rediscover") if err != nil { - err = bosherr.WrapErrorf(err, "SetTimeWithNtpServers %s", stderr) - return + return bosherr.WrapErrorf(err, "SetTimeWithNtpServers %s", stderr) } - return + return nil } func (p WindowsPlatform) SetupEphemeralDiskWithPath(devicePath string, desiredSwapSizeInBytes *uint64, labelPrefix string) error { @@ -463,7 +456,7 @@ func (p WindowsPlatform) SetupEphemeralDiskWithPath(devicePath string, desiredSw protector := p.diskManager.GetProtector() if !protector.CommandExists() { - return fmt.Errorf("cannot protect %s. %s cmd does not exist.", dataPath, disk.ProtectCmdlet) + return fmt.Errorf("cannot protect %s. %s cmd does not exist", dataPath, disk.ProtectCmdlet) } partitioner := p.diskManager.GetPartitioner() @@ -629,7 +622,7 @@ func (p WindowsPlatform) GetEphemeralDiskPath(diskSettings boshsettings.DiskSett diskPath = "0" } - if diskSettings.Path != "" { + if diskSettings.Path != "" { //nolint:nestif matchInt, _ := regexp.MatchString(`\d`, diskSettings.Path) if matchInt { diskPath = diskSettings.Path @@ -637,7 +630,7 @@ func (p WindowsPlatform) GetEphemeralDiskPath(diskSettings boshsettings.DiskSett alphs := []byte("abcdefghijklmnopq") lastChar := diskSettings.Path[len(diskSettings.Path)-1:] - diskPath = fmt.Sprintf("%d", bytes.IndexByte(alphs, byte(lastChar[0]))) + diskPath = fmt.Sprintf("%d", bytes.IndexByte(alphs, lastChar[0])) } } else if diskSettings.DeviceID != "" { stdout, stderr, _, err := p.cmdRunner.RunCommand("powershell", "-Command", fmt.Sprintf("Get-Disk -UniqueId %s | Select Number | ConvertTo-Json", strings.ReplaceAll(diskSettings.DeviceID, "-", ""))) @@ -716,7 +709,6 @@ func (p WindowsPlatform) GetDefaultNetwork() (boshsettings.Network, error) { } func (p WindowsPlatform) GetHostPublicKey() (string, error) { - if err := sshEnabled(); err != nil { return "", bosherr.WrapError(err, "OpenSSH is not running") } diff --git a/settings/settings.go b/settings/settings.go index 4cdb24a51..23337dbed 100644 --- a/settings/settings.go +++ b/settings/settings.go @@ -118,7 +118,7 @@ func (s Settings) PersistentDiskSettingsFromHint(diskID string, diskHint interfa func (s Settings) EphemeralDiskSettings() DiskSettings { diskSettings := DiskSettings{} - if s.Disks.Ephemeral != nil { + if s.Disks.Ephemeral != nil { //nolint:nestif if hashSettings, ok := s.Disks.Ephemeral.(map[string]interface{}); ok { if path, ok := hashSettings["path"]; ok { diskSettings.Path = path.(string) @@ -189,7 +189,7 @@ func (s Settings) populatePersistentDiskSettings(diskID string, settingsInfo int ID: diskID, } - if hashSettings, ok := settingsInfo.(map[string]interface{}); ok { + if hashSettings, ok := settingsInfo.(map[string]interface{}); ok { //nolint:nestif if path, ok := hashSettings["path"]; ok { diskSettings.Path = path.(string) } @@ -266,14 +266,14 @@ func (e Env) GetSwapSizeInBytes() *uint64 { return nil } - result := uint64(*e.Bosh.SwapSizeInMB * 1024 * 1024) + result := *e.Bosh.SwapSizeInMB * 1024 * 1024 return &result } func (e Env) GetParallel() *int { result := 5 if e.Bosh.Parallel != nil { - result = int(*e.Bosh.Parallel) + result = *e.Bosh.Parallel } return &result } @@ -520,7 +520,7 @@ func NetmaskToCIDR(netmask string, ipv6 bool) (string, error) { return strconv.Itoa(ones), nil } -//{ +// { // "agent_id": "bm-xxxxxxxx", // "blobstore": { // "options": { @@ -579,4 +579,4 @@ func NetmaskToCIDR(netmask string, ipv6 bool) (string, error) { // "vm": { // "name": "vm-xxxxxxxx" // } -//} +// } diff --git a/sigar/sigar_stats_collector.go b/sigar/sigar_stats_collector.go index 33a5d3c02..df506b06c 100644 --- a/sigar/sigar_stats_collector.go +++ b/sigar/sigar_stats_collector.go @@ -110,7 +110,6 @@ func (s *sigarStatsCollector) GetDiskStats(mountedPath string) (stats boshstats. } func (s *sigarStatsCollector) GetUptimeStats() (stats boshstats.UptimeStats, err error) { - uptime := sigar.Uptime{} err = uptime.Get() diff --git a/tools/tools.go b/tools/tools.go index 1cd5281bb..2e1a6b27f 100644 --- a/tools/tools.go +++ b/tools/tools.go @@ -1,11 +1,12 @@ +//go:build tools // +build tools package tools import ( - _ "github.com/onsi/ginkgo/ginkgo" // comment to make golint happy - _ "golang.org/x/lint/golint" // comment to make golint happy _ "github.com/maxbrunsfeld/counterfeiter/v6" + _ "github.com/onsi/ginkgo/ginkgo" // comment to make golint happy + _ "golang.org/x/lint/golint" // comment to make golint happy ) // This file imports packages that are used when running go generate, or used From edfed12fe7063571725313847f634343ec30ed98 Mon Sep 17 00:00:00 2001 From: aram price Date: Mon, 28 Mar 2022 10:55:31 -0700 Subject: [PATCH 2/3] Clean up `bin/` - address shellcheck issues - create generic `bin/lint` and `bin/format` helpers (not named after specific formatter / linter tools) - add TODO's around making tests more modular --- bin/build | 18 ++++++------- bin/build-linux-amd64 | 10 ++++--- bin/build-linux-ppc64le | 21 ++++++++------- bin/ci | 11 ++++---- bin/env | 20 +++++--------- bin/format | 10 +++++++ bin/ginkgo | 17 ++++++++++++ bin/go | 9 +++---- bin/godirs | 16 ----------- bin/gofiles | 12 +++++---- bin/golint | 28 -------------------- bin/linenumber | 7 ----- bin/{golangci-lint => lint} | 0 bin/test | 19 +++++++------ bin/test-bosh-integration | 23 ++++++++-------- bin/test-unhandled-errors | 41 ---------------------------- bin/test-unit | 53 ++++++++----------------------------- 17 files changed, 108 insertions(+), 207 deletions(-) create mode 100755 bin/format create mode 100755 bin/ginkgo delete mode 100755 bin/godirs delete mode 100755 bin/golint delete mode 100755 bin/linenumber rename bin/{golangci-lint => lint} (100%) delete mode 100755 bin/test-unhandled-errors diff --git a/bin/build b/bin/build index 23aa015b0..814ec155a 100755 --- a/bin/build +++ b/bin/build @@ -1,16 +1,14 @@ -#!/bin/bash +#!/usr/bin/env bash +set -eu -o pipefail -set -e +ROOT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )" -agent_dir="$(cd "$(dirname "$0")" && cd .. && pwd)" -bin=$agent_dir/bin - -pushd $agent_dir/main - $bin/go build -o $agent_dir/out/bosh-agent +pushd "${ROOT_DIR}/main" + "${ROOT_DIR}/bin/go" build -o "${ROOT_DIR}/out/bosh-agent" popd -if [[ $GOOS = 'windows' ]]; then - pushd $agent_dir/jobsupervisor/pipe - $bin/go build -o $agent_dir/out/bosh-agent-pipe +if [[ "${GOOS}" = 'windows' ]]; then + pushd "${ROOT_DIR}/jobsupervisor/pipe" + "${ROOT_DIR}/bin/go" build -o "${ROOT_DIR}/out/bosh-agent-pipe" popd fi diff --git a/bin/build-linux-amd64 b/bin/build-linux-amd64 index 8d08f985f..7846c4d79 100755 --- a/bin/build-linux-amd64 +++ b/bin/build-linux-amd64 @@ -1,9 +1,11 @@ -#!/bin/bash +#!/usr/bin/env bash +set -eu -o pipefail -set -e -o pipefail +ROOT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )" export GOARCH=amd64 export GOOS=linux -export GOTOOLDIR=$(go env GOROOT)/pkg/linux_amd64 +export GOTOOLDIR +GOTOOLDIR=$(go env GOROOT)/pkg/linux_amd64 -$(dirname $0)/build +"${ROOT_DIR}/bin/build" diff --git a/bin/build-linux-ppc64le b/bin/build-linux-ppc64le index f29998413..c948f5c82 100755 --- a/bin/build-linux-ppc64le +++ b/bin/build-linux-ppc64le @@ -1,15 +1,18 @@ -#!/bin/bash +#!/usr/bin/env bash +set -eu -o pipefail -set -e -o pipefail - -bin=$(dirname $0) +ROOT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )" export GOROOT=/usr/local/gccgo -export PATH=$GOROOT/bin:$PATH -export LD_LIBRARY_PATH=$GOROOT/lib64 -export build_options="-compiler gccgo -gccgoflags '-static-libgo'" + +export PATH=${GOROOT}/bin:${PATH} + +export LD_LIBRARY_PATH=${GOROOT}/lib64 # we need following steps to make gccgo work -cp -f $GOROOT/lib64/libgo.so.7 /lib/powerpc64le-linux-gnu +cp -f "${LD_LIBRARY_PATH}/libgo.so.7" /lib/powerpc64le-linux-gnu -$bin/go build $build_options -o $bin/../out/bosh-agent github.com/cloudfoundry/bosh-agent/main +"${ROOT_DIR}/bin/go" build \ + -compiler gccgo -gccgoflags '-static-libgo' \ + -o "${ROOT_DIR}/out/bosh-agent" \ + github.com/cloudfoundry/bosh-agent/main diff --git a/bin/ci b/bin/ci index dfe7dcf51..ab24c2ac0 100755 --- a/bin/ci +++ b/bin/ci @@ -1,9 +1,8 @@ -#!/bin/bash +#!/usr/bin/env bash +set -eu -o pipefail -set -e -o pipefail +ROOT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )" -bin=$(dirname $0) +"${ROOT_DIR}/bin/lint" # TODO: this should be called in parallel via Concourse -$bin/go get github.com/golang/lint/golint - -exec $bin/test-unit +exec "${ROOT_DIR}/bin/test-unit" diff --git a/bin/env b/bin/env index efd2b29b9..60ebb2746 100755 --- a/bin/env +++ b/bin/env @@ -1,18 +1,12 @@ -#!/bin/bash +#!/usr/bin/env bash +set -eu -o pipefail -set -e -o pipefail +ROOT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )" -base=$( cd "$( dirname "$( dirname "$0" )")" && pwd ) -base_gopath=$( cd $base/../../../.. && pwd ) +base_gopath=$( cd ${ROOT_DIR}/../../../.. && pwd ) -export GOPATH=$base_gopath -export GOBIN=$base_gopath/gobin -export PATH=$PATH:$GOBIN:$base_gopath/bin -export GO15VENDOREXPERIMENT=1 - -#Travis only has 2 'boosted' cores, recommends 4-6 threads max -if [ "$TRAVIS" == "true" ]; then - export GOMAXPROCS=4 -fi +export GOPATH="${base_gopath}" +export GOBIN="${base_gopath}/gobin" +export PATH=${PATH}:${GOBIN}:"${base_gopath}/bin" exec $@ diff --git a/bin/format b/bin/format new file mode 100755 index 000000000..b2d670f21 --- /dev/null +++ b/bin/format @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +set -eu -o pipefail + +ROOT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )" + +export GOIMPORTS_VERSION="${GOIMPORTS_VERSION:-latest}" + +go install -v "golang.org/x/tools/cmd/goimports@${GOIMPORTS_VERSION}" + +"${ROOT_DIR}/bin/gofiles" | xargs goimports -w diff --git a/bin/ginkgo b/bin/ginkgo new file mode 100755 index 000000000..1cb8e121a --- /dev/null +++ b/bin/ginkgo @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +set -eu -o pipefail + +export ROOT_DIR +ROOT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )" + +SLOW_SPEC_THRESHOLD="${SLOW_SPEC_THRESHOLD:-20}" + +# shellcheck disable=SC2068 +"${ROOT_DIR}/bin/env" \ + go run github.com/onsi/ginkgo/ginkgo \ + -keepGoing \ + -skipPackage=vendor \ + -slowSpecThreshold="${SLOW_SPEC_THRESHOLD}" \ + -race \ + -r \ + ${@} diff --git a/bin/go b/bin/go index 51c2ba89a..3ed3cff69 100755 --- a/bin/go +++ b/bin/go @@ -1,7 +1,6 @@ -#!/bin/bash +#!/usr/bin/env bash +set -eu -o pipefail -set -e -o pipefail +ROOT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )" -bin=$(dirname $0) - -exec $bin/env go $@ +exec ${ROOT_DIR}/bin/env go $@ diff --git a/bin/godirs b/bin/godirs deleted file mode 100755 index 39ee8256e..000000000 --- a/bin/godirs +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/bash - -set -e -o pipefail - -cd $(dirname $0)/.. - -find * -maxdepth 0 -type d -and \( \ - -not -path 'Godeps' \ - -not -path 'bin' \ - -not -path 'ci' \ - -not -path 'out' \ - -not -path 'tmp' \ - -not -path 'gobin' \ - -not -path 'vendor' \ - \) \ - | xargs $@ diff --git a/bin/gofiles b/bin/gofiles index 1f809286a..815cdfb5e 100755 --- a/bin/gofiles +++ b/bin/gofiles @@ -1,7 +1,9 @@ -#!/bin/bash +#!/usr/bin/env bash +set -eu -o pipefail -set -e -o pipefail +ROOT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )" -cd $(dirname $0)/.. - -printf "$(find * -maxdepth 0 -type f -name '*.go')\n$(find $(bin/godirs) -type f -name '*.go')" | xargs -L 1 $@ +pushd "${ROOT_DIR}" > /dev/null 2>&1 + # shellcheck disable=SC2035 + find * -name '*.go' -and \( -not -path 'vendor/*' \) +popd > /dev/null 2>&1 \ No newline at end of file diff --git a/bin/golint b/bin/golint deleted file mode 100755 index 5743c4b7d..000000000 --- a/bin/golint +++ /dev/null @@ -1,28 +0,0 @@ -#!/bin/bash - -set -e -o pipefail - -bin=$(dirname $0) - -set +e # golint will fail on the issues we filter out -errors=$( - $bin/gofiles $bin/env go run golang.org/x/lint/golint \ - | grep -v \ - -e 'should have comment.* or be unexported' \ - -e '/mocks/' \ - -e '/fakes/' \ - -e '/jobsfakes/' \ - -e 'should not be capitalized' \ - -e 'underscore in package name' \ - -e 'bootstrapper/spec/' \ - -e 'jobsupervisor/pipe/syslog/syslog.go' \ - -e 'platform/windows_platform_test.go' \ - -e 'platform/syscall_windows.go' \ - -e 'jobsupervisor/winsvc' -) -set -e - -if [ "$(echo -n "$errors")" != "" ]; then - echo "$errors" - exit 1 -fi diff --git a/bin/linenumber b/bin/linenumber deleted file mode 100755 index cde8e6385..000000000 --- a/bin/linenumber +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/bash -# prepend line numbers to all lines, starting at 1 -# usage: bin/golint | bin/linenumber - -set -e -o pipefail - -awk '{print NR "\t" $0}' \ No newline at end of file diff --git a/bin/golangci-lint b/bin/lint similarity index 100% rename from bin/golangci-lint rename to bin/lint diff --git a/bin/test b/bin/test index 4e0e6d0a0..b136d402c 100755 --- a/bin/test +++ b/bin/test @@ -1,21 +1,20 @@ -#!/bin/bash +#!/usr/bin/env bash +set -eu -o pipefail -set -e -o pipefail +ROOT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )" result=0 -bin=$(dirname $0) +"${ROOT_DIR}/bin/test-unit" +(( result+=$? )) || true -$bin/test-unit -q -let "result+=$?" || true +"${ROOT_DIR}/bin/test-integration" # TODO this file does not exist +(( result+=$? )) || true -$bin/test-integration -let "result+=$?" || true - -if [ $result -eq 0 ]; then +if [ "${result}" -eq 0 ]; then echo -e "\n\033[0;32mSUITE SUCCESS\033[0m" else echo -e "\n\033[0;31mSUITE FAILURE\033[0m" fi -exit $result +exit "${result}" diff --git a/bin/test-bosh-integration b/bin/test-bosh-integration index bca8b6457..160a5f13f 100755 --- a/bin/test-bosh-integration +++ b/bin/test-bosh-integration @@ -1,32 +1,33 @@ -#!/bin/bash +#!/usr/bin/env bash +set -eu -o pipefail -set -e -o pipefail +ROOT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )" -base=$( cd $(dirname $0)/.. && pwd ) +bosh_dir="${ROOT_DIR}/tmp/bosh" -if [ ! -d $base/tmp/bosh ]; then +if [ ! -d "${bosh_dir}" ]; then echo -e "\n Cloning BOSH..." - rm -rf $base/tmp - mkdir -p $base/tmp - git clone --recursive --depth 1 --branch master https://github.com/cloudfoundry/bosh.git $base/tmp/bosh + rm -rf "${bosh_dir}" + mkdir -p "${bosh_dir}" + git clone --recursive --depth 1 --branch main https://github.com/cloudfoundry/bosh.git "${bosh_dir}" else echo -e "\n Updating BOSH to origin/master..." ( - cd $base/tmp/bosh + cd "${bosh_dir}" git clean -dfx - git fetch https://github.com/cloudfoundry/bosh.git master + git fetch https://github.com/cloudfoundry/bosh.git main git reset --hard FETCH_HEAD ) fi -cd $base/tmp/bosh +cd "${bosh_dir}" echo -e "\n Installing BOSH dependencies..." bundle install echo -e "\n Linking bosh agent..." rm -rf go/src/github.com/cloudfoundry/bosh-agent -ln -s $base go/src/github.com/cloudfoundry/bosh-agent +ln -s "${ROOT_DIR}" go/src/github.com/cloudfoundry/bosh-agent echo -e "\n Running integration tests..." bundle exec rake spec:integration diff --git a/bin/test-unhandled-errors b/bin/test-unhandled-errors deleted file mode 100755 index ed9e4f6fb..000000000 --- a/bin/test-unhandled-errors +++ /dev/null @@ -1,41 +0,0 @@ -#!/bin/bash - -set -e -o pipefail - -bin=$(dirname $0) - -$bin/go get github.com/kisielk/errcheck - -packages_to_check=$($bin/go list ./... \ - | grep -v "github.com/cloudfoundry/bosh-agent/vendor" \ - | grep -v "github.com/cloudfoundry/bosh-agent/integration" \ - | xargs -) - -set +e -all_errors=$($bin/env errcheck $packages_to_check) - -# exits 0 if no unhandled errors, 1 if there are unhandled errors, 2 if checking failed -if [ "$?" -eq 2 ] -then - echo "" - echo "Failed." - exit 1 -fi -set -e - -set +e -errors=$(echo "$all_errors" | grep -v "_test.go") # hopefully errcheck will add a flag to ignore tests and we won't have to do this: https://github.com/kisielk/errcheck/issues/66 -# exits 0 if any lines weren't excluded, 1 if all lines were excluded -if [ "$?" -eq 1 ] -then - echo "All good." - exit 0 -fi -set -e - -num_errors=$(echo "$errors" | wc -l | awk {'print $1'}) -echo "$errors" -echo "" -echo "$num_errors unhandled errors found." -exit 1 diff --git a/bin/test-unit b/bin/test-unit index 394aeef54..c95504f20 100755 --- a/bin/test-unit +++ b/bin/test-unit @@ -1,52 +1,21 @@ -#!/bin/bash +#!/usr/bin/env bash +set -eu -o pipefail -set -e -o pipefail - -while getopts ":q:w" opt; do - case "$opt" in - q) QUIET=true ;; - w) WATCH="watch" ;; - esac -done -shift $(( OPTIND - 1 )) - -bin=$(dirname $0) - -dir=$bin/.. -if [ -n "$1" ] ; then - dir=$1 -fi +ROOT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )" echo 'Note: if you want to quickly run tests for just one package, do it like this:' -echo ' % ginkgo path/to/package' - +echo ' % bin/ginkgo path/to/package' -# Travis randomly kills go builds when using -race -race=$([ "$TRAVIS" != "true" ] && echo "-race") +"${ROOT_DIR}/bin/format" # TODO: this should be called in parallel via Concourse -ignored=(vendor,Tools,bin,ci,docs,gobin,out,test,tmp) -echo -e "\n Formatting packages, other than: ${ignored[*]}..." -for i in `ls -1` ; do - if [ -d "$i" ] && [[ ! ${ignored[*]} =~ "$i" ]] ; then - $bin/go fmt github.com/cloudfoundry/bosh-agent/${i}/... - fi +for os in windows linux; do + echo -e "\n lint-ing with GOOS=${os}..." + GOOS="${os}" "${ROOT_DIR}/bin/lint" # TODO: this should be called in parallel via Concourse + echo -e "\n build-ing with GOOS=${os} to confirm everything compiles..." + GOOS="${os}" "${ROOT_DIR}/bin/build" # TODO: this should be called in parallel via Concourse done -echo -e "\n Skipping check for unhandled errors until https://github.com/kisielk/errcheck/issues/75 is resolved" -# $bin/test-unhandled-errors - -echo -e "\n Running build script for windows to confirm everything compiles..." -GOOS=windows $bin/build - -echo -e "\n Running build script to confirm everything compiles..." -$bin/build - echo -e "\n Testing packages..." -$bin/env go run github.com/onsi/ginkgo/ginkgo $WATCH -r $race -skipPackage="integration,vendor" $dir - -if [[ ! "$(go version)" =~ go1.8 ]]; then - echo -e "\n Checking with golint..." - $bin/golint -fi +"${ROOT_DIR}/bin/ginkgo" -skipPackage="integration" "${ROOT_DIR}" echo -e "\n\033[0;32mSUCCESS\033[0m" From 9f03a0d86db103dbf92a1ee029fd0a61b7292b14 Mon Sep 17 00:00:00 2001 From: aram price Date: Mon, 28 Mar 2022 10:58:14 -0700 Subject: [PATCH 3/3] `golangci-lint` passes on test code --- .golangci.yml | 90 +++++----- agent/action/apply_test.go | 52 +++--- agent/action/cancel_task_test.go | 6 +- agent/action/compile_package_test.go | 6 +- .../compile_package_with_signed_url_test.go | 10 +- agent/action/concrete_factory_test.go | 62 +++---- agent/action/delete_arp_entries_test.go | 28 +-- agent/action/drain_test.go | 30 ++-- agent/action/fetch_logs_test.go | 30 ++-- .../action/fetch_logs_with_signed_url_test.go | 34 ++-- agent/action/get_state_test.go | 38 ++-- agent/action/get_task_test.go | 26 +-- agent/action/info_test.go | 20 +-- agent/action/list_disk_test.go | 30 ++-- agent/action/migrate_disk_test.go | 22 +-- agent/action/mount_disk_test.go | 30 ++-- agent/action/ping_test.go | 18 +- .../action/prepare_configure_networks_test.go | 31 ++-- agent/action/prepare_test.go | 24 +-- agent/action/release_apply_spec_test.go | 23 ++- agent/action/run_errand_test.go | 83 +++++---- agent/action/run_script_test.go | 22 +-- agent/action/runner_test.go | 107 ++++++------ agent/action/shared_test.go | 47 ++--- agent/action/shutdown_test.go | 22 +-- agent/action/ssh_test.go | 36 ++-- agent/action/start_test.go | 28 +-- agent/action/state/sync_dns_state_test.go | 16 +- agent/action/stop_test.go | 24 +-- agent/action/sync_dns_test.go | 65 ++++--- agent/action/sync_dns_with_signed_url_test.go | 66 +++---- agent/action/unmount_disk_test.go | 33 ++-- agent/action/update_settings_test.go | 75 ++++---- agent/action/upload_blob_test.go | 43 ++--- agent/action_dispatcher_test.go | 14 +- agent/agent_test.go | 40 ++--- .../applyspec/concrete_v1_service_test.go | 6 +- .../rendered_templates_archive_spec_test.go | 4 +- agent/applier/applyspec/v1_apply_spec_test.go | 10 +- .../file_bundle_setup_unix_test.go | 3 +- .../bundlecollection/file_bundle_test.go | 25 +-- .../file_bundle_windows_test.go | 3 +- agent/applier/concrete_applier_test.go | 71 ++++---- .../applier/jobs/rendered_job_applier_test.go | 22 +-- agent/applier/models/job_test.go | 3 +- .../packages/compiled_package_applier_test.go | 3 +- agent/blobstore/cascading_blobstore_test.go | 6 +- agent/bootonce/start_manager.go | 4 - agent/bootonce/start_manager_test.go | 3 +- agent/bootstrap_test.go | 76 ++++---- agent/compiler/concrete_compiler_test.go | 11 +- .../concrete_compiler_windows_test.go | 5 +- agent/heartbeat_test.go | 2 +- .../blobstore_delegator_test.go | 1 + .../blobstore_http_client_test.go | 12 +- agent/script/drain/concrete_script_test.go | 3 +- agent/script/generic_script_test.go | 6 +- agent/tarpath/detector_test.go | 3 +- agent/task/async_task_service_test.go | 14 +- agent/task/concrete_manager_test.go | 2 +- agent/task/fakes/fake_manager.go | 2 +- agentclient/applyspec/apply_spec_test.go | 2 +- app/app_test.go | 47 ++--- app/config_test.go | 51 +++--- handler/common_event_format_test.go | 5 +- .../agentlogger/signalable_logger_test.go | 4 +- .../config_drive_metadata_service_test.go | 4 +- .../id_device_path_resolver_test.go | 2 +- .../iscsi_device_path_resolver_test.go | 3 +- .../mapped_device_path_resolver_test.go | 24 ++- .../scsi_id_device_path_resolver.go | 2 +- .../scsi_id_device_path_resolver_test.go | 2 +- ...csi_volume_id_device_path_resolver_test.go | 3 +- infrastructure/file_metadata_service_test.go | 39 +++-- infrastructure/file_registry_test.go | 10 +- infrastructure/file_settings_source_test.go | 18 +- infrastructure/http_metadata_service_test.go | 46 ++--- infrastructure/http_registry_test.go | 15 +- .../instance_metadata_settings_source_test.go | 18 +- infrastructure/multi_settings_source_test.go | 6 +- .../multi_source_metadata_service_test.go | 12 +- integration/integration_suite_test.go | 2 +- integration/test_environment.go | 42 ++++- integration/windows/ephemeral_disk_test.go | 6 +- integration/windows/windows_suite_test.go | 10 +- .../dummy_nats_job_supervisor_test.go | 16 +- jobsupervisor/fakes/fake_job_supervisor.go | 5 +- .../monit/monit_retry_strategy_test.go | 2 +- jobsupervisor/monit_job_supervisor.go | 2 - jobsupervisor/monit_job_supervisor_test.go | 50 ++++-- jobsupervisor/pipe/main_test.go | 36 ++-- jobsupervisor/pipe/syslog/syslog_test.go | 99 +++++------ jobsupervisor/pipe/winsw_pipe_suite_test.go | 12 +- jobsupervisor/provider_test.go | 3 +- .../windows_job_supervisor_export_test.go | 2 +- jobsupervisor/windows_job_supervisor_test.go | 104 ++++++----- jobsupervisor/wrapper_job_supervisor_test.go | 46 ++--- mbus/handler_provider_test.go | 6 +- mbus/https_dispatcher_test.go | 22 +-- mbus/https_handler_test.go | 12 +- mbus/nats_handler.go | 17 +- mbus/nats_handler_test.go | 42 +++-- platform/bootstrap_state_test.go | 12 +- platform/cert/cert_manager_test.go | 52 ++++-- platform/delayed_audit_logger_unix_test.go | 8 +- platform/disk/diskutil_test.go | 9 +- .../disk/ephemeral_device_partitioner_test.go | 6 +- platform/disk/linux_formatter_test.go | 46 +++-- platform/disk/linux_mounter_test.go | 9 +- platform/disk/parted_partitioner_test.go | 2 - platform/disk/proc_mounts_searcher_test.go | 9 +- platform/disk/sfdisk_partitioner_test.go | 32 ++-- platform/dummy_platform_test.go | 15 +- platform/fakes/fake_audit_logger_provider.go | 4 +- platform/linux_platform_test.go | 163 ++++++++++++------ platform/net/arp/arping_test.go | 6 +- platform/net/dns_validator_test.go | 6 +- platform/net/firewall_provider_linux_test.go | 6 +- .../interface_configuration_creator_test.go | 8 +- platform/net/mac_address_detector_test.go | 12 +- platform/net/ubuntu_net_manager_test.go | 39 +++-- platform/net/windows_net_manager_test.go | 2 +- platform/stats/percentage_test.go | 5 +- platform/syscall_windows_test.go | 10 +- platform/udevdevice/fakes/fake_udev_device.go | 6 +- platform/vitals/service_test.go | 2 +- platform/windows/disk/partitioner_test.go | 10 -- platform/windows/powershell/runner_test.go | 12 +- platform/windows_platform_test.go | 69 ++++---- settings/service_test.go | 36 ++-- 130 files changed, 1652 insertions(+), 1424 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 354e1430a..aa20403d9 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,60 +1,47 @@ # https://github.com/golangci/golangci-lint#config-file run: - deadline: 5m + timeout: 5m skip-dirs: - tmp - integration skip-files: - - ".*/fake-.*\\.go$" - -linters: - disable-all: true - enable: &LINTERS - # default linters - - deadcode - - errcheck - - gosimple - - govet - - ineffassign - - staticcheck - - structcheck - - typecheck - - unused - - varcheck - - # additional linters for this project (we should disable these if they get annoying). - - asciicheck - - bodyclose - - depguard - - dogsled - - exhaustive - - exportloopref - - funlen - - gochecknoglobals - - gochecknoinits - - gocritic - - gocyclo - - goheader - - goimports - - revive - - goprintffuncname - - gosec - - misspell - - nakedret - - nestif - - noctx - - nolintlint - - prealloc - - rowserrcheck - - exportloopref - - sqlclosecheck - - unconvert - - whitespace - -issues: - exclude-rules: - - path: _test\.go - linters: *LINTERS + # explicitly skip files containing '// Code generated by counterfeiter. DO NOT EDIT.' + - agent/action/fakes/fake_clock.go + - agent/action/fakes/fake_clock.go + - agent/agentfakes/fake_start_manager.go + - agent/applier/bundlecollection/fakes/fake_clock.go + - agent/applier/jobs/jobsfakes/fake_applier.go + - agent/blobstore/blobstorefakes/fake_blob_manager_interface.go + - agent/httpblobprovider/blobstore_delegator/blobstore_delegatorfakes/fake_blobstore_delegator.go + - agent/httpblobprovider/httpblobproviderfakes/fake_httpblob_provider.go + - agent/script/drain/drainfakes/fake_script_params.go + - agent/script/scriptfakes/fake_cancellable_script.go + - agent/script/scriptfakes/fake_job_script_provider.go + - agent/script/scriptfakes/fake_script.go + - agent/tarpath/tarpathfakes/fake_detector.go + - agent/utils/utilsfakes/fake_killer.go + - agentclient/fakes/fake_agent_client.go + - jobsupervisor/monit/monitfakes/fake_httpclient.go + - jobsupervisor/monit/monitfakes/fake_request_retryable.go + - mbus/mbusfakes/fake_nats_connection.go + - platform/cert/certfakes/fake_manager.go + - platform/disk/diskfakes/fake_manager.go + - platform/disk/diskfakes/fake_mounter.go + - platform/fakes/fake_windows_disk_manager.go + - platform/net/netfakes/fake_macaddress_detector.go + - platform/openiscsi/openiscsifakes/fake_open_iscsi.go + - platform/platformfakes/fake_audit_logger.go + - platform/platformfakes/fake_platform.go + - platform/vitals/vitalsfakes/fake_service.go + - platform/windows/disk/fakes/fake_windows_disk_formatter.go + - platform/windows/disk/fakes/fake_windows_disk_linker.go + - platform/windows/disk/fakes/fake_windows_disk_partitioner.go + - platform/windows/disk/fakes/fake_windows_disk_protector.go + - settings/settingsfakes/fake_platform_settings_getter.go + - vendor/github.com/cloudfoundry/bosh-utils/logger/loggerfakes/fake_logger.go + - vendor/github.com/maxbrunsfeld/counterfeiter/v6/generator/function_template.go + - vendor/github.com/maxbrunsfeld/counterfeiter/v6/generator/interface_template.go + - vendor/github.com/maxbrunsfeld/counterfeiter/v6/generator/package_template.go linters-settings: dogsled: @@ -64,4 +51,5 @@ linters-settings: statements: 90 output: + # Sort results by: filepath, line and column. sort-results: true diff --git a/agent/action/apply_test.go b/agent/action/apply_test.go index c73d54e54..341b06c93 100644 --- a/agent/action/apply_test.go +++ b/agent/action/apply_test.go @@ -7,7 +7,7 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - . "github.com/cloudfoundry/bosh-agent/agent/action" + "github.com/cloudfoundry/bosh-agent/agent/action" boshas "github.com/cloudfoundry/bosh-agent/agent/applier/applyspec" fakeas "github.com/cloudfoundry/bosh-agent/agent/applier/applyspec/fakes" fakeappl "github.com/cloudfoundry/bosh-agent/agent/applier/fakes" @@ -24,7 +24,7 @@ var _ = Describe("ApplyAction", func() { specService *fakeas.FakeV1Service settingsService *fakesettings.FakeSettingsService dirProvider boshdir.Provider - action ApplyAction + applyAction action.ApplyAction fs boshsys.FileSystem ) @@ -34,14 +34,14 @@ var _ = Describe("ApplyAction", func() { settingsService = &fakesettings.FakeSettingsService{} dirProvider = boshdir.NewProvider("/var/vcap") fs = fakesys.NewFakeFileSystem() - action = NewApply(applier, specService, settingsService, dirProvider, fs) + applyAction = action.NewApply(applier, specService, settingsService, dirProvider, fs) }) - AssertActionIsAsynchronous(action) - AssertActionIsNotPersistent(action) - AssertActionIsLoggable(action) - AssertActionIsNotCancelable(action) - AssertActionIsNotResumable(action) + AssertActionIsAsynchronous(applyAction) + AssertActionIsNotPersistent(applyAction) + AssertActionIsLoggable(applyAction) + AssertActionIsNotCancelable(applyAction) + AssertActionIsNotResumable(applyAction) Describe("Run", func() { settings := boshsettings.Settings{AgentID: "fake-agent-id"} @@ -63,7 +63,7 @@ var _ = Describe("ApplyAction", func() { }) It("populates dynamic networks in desired spec", func() { - _, err := action.Run(desiredApplySpec) + _, err := applyAction.Run(desiredApplySpec) Expect(err).ToNot(HaveOccurred()) Expect(specService.PopulateDHCPNetworksSpec).To(Equal(desiredApplySpec)) Expect(specService.PopulateDHCPNetworksSettings).To(Equal(settings)) @@ -75,7 +75,7 @@ var _ = Describe("ApplyAction", func() { }) It("runs applier with populated desired spec", func() { - _, err := action.Run(desiredApplySpec) + _, err := applyAction.Run(desiredApplySpec) Expect(err).ToNot(HaveOccurred()) Expect(applier.Applied).To(BeTrue()) Expect(applier.ApplyDesiredApplySpec).To(Equal(populatedDesiredApplySpec)) @@ -84,7 +84,7 @@ var _ = Describe("ApplyAction", func() { Context("when applier succeeds applying desired spec", func() { Context("when saving desires spec as current spec succeeds", func() { It("returns 'applied' after setting populated desired spec as current spec", func() { - value, err := action.Run(desiredApplySpec) + value, err := applyAction.Run(desiredApplySpec) Expect(err).ToNot(HaveOccurred()) Expect(value).To(Equal("applied")) @@ -99,7 +99,7 @@ var _ = Describe("ApplyAction", func() { }) It("returns 'applied' and writes the id, instance name, deployment name, and az to files in the instance directory", func() { - value, err := action.Run(desiredApplySpec) + value, err := applyAction.Run(desiredApplySpec) Expect(err).ToNot(HaveOccurred()) Expect(value).To(Equal("applied")) @@ -128,7 +128,7 @@ var _ = Describe("ApplyAction", func() { It("returns error because agent was not able to remember that is converged to desired spec", func() { specService.SetErr = errors.New("fake-set-error") - _, err := action.Run(desiredApplySpec) + _, err := applyAction.Run(desiredApplySpec) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-set-error")) }) @@ -141,13 +141,13 @@ var _ = Describe("ApplyAction", func() { }) It("returns error", func() { - _, err := action.Run(desiredApplySpec) + _, err := applyAction.Run(desiredApplySpec) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-apply-error")) }) It("does not save desired spec as current spec", func() { - _, err := action.Run(desiredApplySpec) + _, err := applyAction.Run(desiredApplySpec) Expect(err).To(HaveOccurred()) Expect(specService.Spec).To(Equal(currentApplySpec)) }) @@ -160,19 +160,19 @@ var _ = Describe("ApplyAction", func() { }) It("returns error", func() { - _, err := action.Run(desiredApplySpec) + _, err := applyAction.Run(desiredApplySpec) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-populate-dynamic-networks-err")) }) It("does not apply desired spec as current spec", func() { - _, err := action.Run(desiredApplySpec) + _, err := applyAction.Run(desiredApplySpec) Expect(err).To(HaveOccurred()) Expect(applier.Applied).To(BeFalse()) }) It("does not save desired spec as current spec", func() { - _, err := action.Run(desiredApplySpec) + _, err := applyAction.Run(desiredApplySpec) Expect(err).To(HaveOccurred()) Expect(specService.Spec).To(Equal(currentApplySpec)) }) @@ -194,7 +194,7 @@ var _ = Describe("ApplyAction", func() { } It("populates dynamic networks in desired spec", func() { - _, err := action.Run(desiredApplySpec) + _, err := applyAction.Run(desiredApplySpec) Expect(err).ToNot(HaveOccurred()) Expect(specService.PopulateDHCPNetworksSpec).To(Equal(desiredApplySpec)) Expect(specService.PopulateDHCPNetworksSettings).To(Equal(settings)) @@ -207,7 +207,7 @@ var _ = Describe("ApplyAction", func() { Context("when saving desires spec as current spec succeeds", func() { It("returns 'applied' after setting desired spec as current spec", func() { - value, err := action.Run(desiredApplySpec) + value, err := applyAction.Run(desiredApplySpec) Expect(err).ToNot(HaveOccurred()) Expect(value).To(Equal("applied")) @@ -215,7 +215,7 @@ var _ = Describe("ApplyAction", func() { }) It("does not try to apply desired spec since it does not have jobs and packages", func() { - _, err := action.Run(desiredApplySpec) + _, err := applyAction.Run(desiredApplySpec) Expect(err).ToNot(HaveOccurred()) Expect(applier.Applied).To(BeFalse()) }) @@ -227,13 +227,13 @@ var _ = Describe("ApplyAction", func() { }) It("returns error because agent was not able to remember that is converged to desired spec", func() { - _, err := action.Run(desiredApplySpec) + _, err := applyAction.Run(desiredApplySpec) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-set-error")) }) It("does not try to apply desired spec since it does not have jobs and packages", func() { - _, err := action.Run(desiredApplySpec) + _, err := applyAction.Run(desiredApplySpec) Expect(err).To(HaveOccurred()) Expect(applier.Applied).To(BeFalse()) }) @@ -246,19 +246,19 @@ var _ = Describe("ApplyAction", func() { }) It("returns error", func() { - _, err := action.Run(desiredApplySpec) + _, err := applyAction.Run(desiredApplySpec) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-populate-dynamic-networks-err")) }) It("does not apply desired spec as current spec", func() { - _, err := action.Run(desiredApplySpec) + _, err := applyAction.Run(desiredApplySpec) Expect(err).To(HaveOccurred()) Expect(applier.Applied).To(BeFalse()) }) It("does not save desired spec as current spec", func() { - _, err := action.Run(desiredApplySpec) + _, err := applyAction.Run(desiredApplySpec) Expect(err).To(HaveOccurred()) Expect(specService.Spec).ToNot(Equal(desiredApplySpec)) }) diff --git a/agent/action/cancel_task_test.go b/agent/action/cancel_task_test.go index 3097cfa88..88643b961 100644 --- a/agent/action/cancel_task_test.go +++ b/agent/action/cancel_task_test.go @@ -6,7 +6,7 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - . "github.com/cloudfoundry/bosh-agent/agent/action" + boshaction "github.com/cloudfoundry/bosh-agent/agent/action" boshtask "github.com/cloudfoundry/bosh-agent/agent/task" faketask "github.com/cloudfoundry/bosh-agent/agent/task/fakes" ) @@ -14,12 +14,12 @@ import ( var _ = Describe("CancelTaskAction", func() { var ( taskService *faketask.FakeService - action CancelTaskAction + action boshaction.CancelTaskAction ) BeforeEach(func() { taskService = faketask.NewFakeService() - action = NewCancelTask(taskService) + action = boshaction.NewCancelTask(taskService) }) AssertActionIsNotAsynchronous(action) diff --git a/agent/action/compile_package_test.go b/agent/action/compile_package_test.go index 2afc7b423..d55582161 100644 --- a/agent/action/compile_package_test.go +++ b/agent/action/compile_package_test.go @@ -7,7 +7,7 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - . "github.com/cloudfoundry/bosh-agent/agent/action" + boshaction "github.com/cloudfoundry/bosh-agent/agent/action" boshmodels "github.com/cloudfoundry/bosh-agent/agent/applier/models" boshcomp "github.com/cloudfoundry/bosh-agent/agent/compiler" fakecomp "github.com/cloudfoundry/bosh-agent/agent/compiler/fakes" @@ -39,12 +39,12 @@ func getCompileActionArguments() (blobID string, multiDigest boshcrypto.Multiple var _ = Describe("CompilePackageAction", func() { var ( compiler *fakecomp.FakeCompiler - action CompilePackageAction + action boshaction.CompilePackageAction ) BeforeEach(func() { compiler = fakecomp.NewFakeCompiler() - action = NewCompilePackage(compiler) + action = boshaction.NewCompilePackage(compiler) }) AssertActionIsAsynchronous(action) diff --git a/agent/action/compile_package_with_signed_url_test.go b/agent/action/compile_package_with_signed_url_test.go index ada364dbf..fa09cf07d 100644 --- a/agent/action/compile_package_with_signed_url_test.go +++ b/agent/action/compile_package_with_signed_url_test.go @@ -7,15 +7,15 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - . "github.com/cloudfoundry/bosh-agent/agent/action" + boshaction "github.com/cloudfoundry/bosh-agent/agent/action" boshmodels "github.com/cloudfoundry/bosh-agent/agent/applier/models" boshcomp "github.com/cloudfoundry/bosh-agent/agent/compiler" fakecomp "github.com/cloudfoundry/bosh-agent/agent/compiler/fakes" boshcrypto "github.com/cloudfoundry/bosh-utils/crypto" ) -func getCompileWithSignedURLActionArguments() CompilePackageWithSignedURLRequest { - return CompilePackageWithSignedURLRequest{ +func getCompileWithSignedURLActionArguments() boshaction.CompilePackageWithSignedURLRequest { + return boshaction.CompilePackageWithSignedURLRequest{ PackageGetSignedURL: "fake/get/url", UploadSignedURL: "fake/upload/url", Name: "fake-package-name", @@ -46,12 +46,12 @@ func getCompileWithSignedURLActionArguments() CompilePackageWithSignedURLRequest var _ = Describe("CompilePackageWithSignedURL", func() { var ( compiler *fakecomp.FakeCompiler - action CompilePackageWithSignedURL + action boshaction.CompilePackageWithSignedURL ) BeforeEach(func() { compiler = fakecomp.NewFakeCompiler() - action = NewCompilePackageWithSignedURL(compiler) + action = boshaction.NewCompilePackageWithSignedURL(compiler) }) AssertActionIsAsynchronous(action) diff --git a/agent/action/concrete_factory_test.go b/agent/action/concrete_factory_test.go index 86b6789b8..b20b94758 100644 --- a/agent/action/concrete_factory_test.go +++ b/agent/action/concrete_factory_test.go @@ -1,13 +1,13 @@ package action_test import ( - . "github.com/cloudfoundry/bosh-agent/agent/action" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/cloudfoundry/bosh-agent/agent/script/scriptfakes" "github.com/cloudfoundry/bosh-agent/platform/platformfakes" + boshaction "github.com/cloudfoundry/bosh-agent/agent/action" boshscript "github.com/cloudfoundry/bosh-agent/agent/script" boshdir "github.com/cloudfoundry/bosh-agent/settings/directories" boshlog "github.com/cloudfoundry/bosh-utils/logger" @@ -38,7 +38,7 @@ var _ = Describe("concreteFactory", func() { jobSupervisor *fakejobsuper.FakeJobSupervisor specService *fakeas.FakeV1Service jobScriptProvider boshscript.JobScriptProvider - factory Factory + factory boshaction.Factory logger boshlog.Logger fileSystem *fakesys.FakeFileSystem blobDelegator *fakeblobdelegator.FakeBlobstoreDelegator @@ -63,7 +63,7 @@ var _ = Describe("concreteFactory", func() { logger = boshlog.NewLogger(boshlog.LevelNone) blobDelegator = &fakeblobdelegator.FakeBlobstoreDelegator{} - factory = NewFactory( + factory = boshaction.NewFactory( settingsService, platform, blobManager, @@ -79,8 +79,8 @@ var _ = Describe("concreteFactory", func() { ) }) - It("returns error if action cannot be created", func() { - action, err := factory.Create("fake-unknown-action") + It("returns error if boshaction cannot be created", func() { + action, err := factory.Create("fake-unknown-boshaction") Expect(err).To(HaveOccurred()) Expect(action).To(BeNil()) }) @@ -88,7 +88,7 @@ var _ = Describe("concreteFactory", func() { It("apply", func() { action, err := factory.Create("apply") Expect(err).ToNot(HaveOccurred()) - Expect(action).To(BeEquivalentTo(NewApply( + Expect(action).To(BeEquivalentTo(boshaction.NewApply( applier, specService, settingsService, @@ -101,110 +101,110 @@ var _ = Describe("concreteFactory", func() { action, err := factory.Create("drain") Expect(err).ToNot(HaveOccurred()) // Cannot do equality check since channel is used in initializer - Expect(action).To(BeAssignableToTypeOf(DrainAction{})) + Expect(action).To(BeAssignableToTypeOf(boshaction.DrainAction{})) }) It("fetch_logs", func() { action, err := factory.Create("fetch_logs") Expect(err).ToNot(HaveOccurred()) - Expect(action).To(Equal(NewFetchLogs(platform.GetCompressor(), platform.GetCopier(), blobDelegator, platform.GetDirProvider()))) + Expect(action).To(Equal(boshaction.NewFetchLogs(platform.GetCompressor(), platform.GetCopier(), blobDelegator, platform.GetDirProvider()))) }) It("fetch_logs_with_signed_url", func() { ac, err := factory.Create("fetch_logs_with_signed_url") Expect(err).ToNot(HaveOccurred()) - Expect(ac).To(Equal(NewFetchLogsWithSignedURLAction(platform.GetCompressor(), platform.GetCopier(), platform.GetDirProvider(), blobDelegator))) + Expect(ac).To(Equal(boshaction.NewFetchLogsWithSignedURLAction(platform.GetCompressor(), platform.GetCopier(), platform.GetDirProvider(), blobDelegator))) }) It("get_task", func() { action, err := factory.Create("get_task") Expect(err).ToNot(HaveOccurred()) - Expect(action).To(Equal(NewGetTask(taskService))) + Expect(action).To(Equal(boshaction.NewGetTask(taskService))) }) It("cancel_task", func() { action, err := factory.Create("cancel_task") Expect(err).ToNot(HaveOccurred()) - Expect(action).To(Equal(NewCancelTask(taskService))) + Expect(action).To(Equal(boshaction.NewCancelTask(taskService))) }) It("get_state", func() { action, err := factory.Create("get_state") Expect(err).ToNot(HaveOccurred()) - Expect(action).To(Equal(NewGetState(settingsService, specService, jobSupervisor, platform.GetVitalsService()))) + Expect(action).To(Equal(boshaction.NewGetState(settingsService, specService, jobSupervisor, platform.GetVitalsService()))) }) It("list_disk", func() { action, err := factory.Create("list_disk") Expect(err).ToNot(HaveOccurred()) - Expect(action).To(Equal(NewListDisk(settingsService, platform, logger))) + Expect(action).To(Equal(boshaction.NewListDisk(settingsService, platform, logger))) }) It("migrate_disk", func() { action, err := factory.Create("migrate_disk") Expect(err).ToNot(HaveOccurred()) - Expect(action).To(Equal(NewMigrateDisk(platform, platform.GetDirProvider()))) + Expect(action).To(Equal(boshaction.NewMigrateDisk(platform, platform.GetDirProvider()))) }) It("mount_disk", func() { action, err := factory.Create("mount_disk") Expect(err).ToNot(HaveOccurred()) - Expect(action).To(Equal(NewMountDisk(settingsService, platform, platform.GetDirProvider(), logger))) + Expect(action).To(Equal(boshaction.NewMountDisk(settingsService, platform, platform.GetDirProvider(), logger))) }) It("ping", func() { action, err := factory.Create("ping") Expect(err).ToNot(HaveOccurred()) - Expect(action).To(Equal(NewPing())) + Expect(action).To(Equal(boshaction.NewPing())) }) It("info", func() { action, err := factory.Create("info") Expect(err).ToNot(HaveOccurred()) - Expect(action).To(Equal(NewInfo())) + Expect(action).To(Equal(boshaction.NewInfo())) }) It("ssh", func() { action, err := factory.Create("ssh") Expect(err).ToNot(HaveOccurred()) - Expect(action).To(Equal(NewSSH(settingsService, platform, platform.GetDirProvider(), logger))) + Expect(action).To(Equal(boshaction.NewSSH(settingsService, platform, platform.GetDirProvider(), logger))) }) It("start", func() { action, err := factory.Create("start") Expect(err).ToNot(HaveOccurred()) - Expect(action).To(Equal(NewStart(jobSupervisor, applier, specService))) + Expect(action).To(Equal(boshaction.NewStart(jobSupervisor, applier, specService))) }) It("stop", func() { action, err := factory.Create("stop") Expect(err).ToNot(HaveOccurred()) - Expect(action).To(Equal(NewStop(jobSupervisor))) + Expect(action).To(Equal(boshaction.NewStop(jobSupervisor))) }) It("remove_persistent_disk", func() { action, err := factory.Create("remove_persistent_disk") Expect(err).ToNot(HaveOccurred()) - Expect(action).To(Equal(NewRemovePersistentDiskAction(settingsService))) + Expect(action).To(Equal(boshaction.NewRemovePersistentDiskAction(settingsService))) }) It("unmount_disk", func() { action, err := factory.Create("unmount_disk") Expect(err).ToNot(HaveOccurred()) - Expect(action).To(Equal(NewUnmountDisk(settingsService, platform))) + Expect(action).To(Equal(boshaction.NewUnmountDisk(settingsService, platform))) }) It("compile_package", func() { action, err := factory.Create("compile_package") Expect(err).ToNot(HaveOccurred()) - Expect(action).To(Equal(NewCompilePackage(compiler))) + Expect(action).To(Equal(boshaction.NewCompilePackage(compiler))) }) It("compile_package_with_signed_url", func() { action, err := factory.Create("compile_package_with_signed_url") Expect(err).ToNot(HaveOccurred()) - Expect(action).To(Equal(NewCompilePackageWithSignedURL(compiler))) + Expect(action).To(Equal(boshaction.NewCompilePackageWithSignedURL(compiler))) }) It("run_errand", func() { @@ -212,43 +212,43 @@ var _ = Describe("concreteFactory", func() { Expect(err).ToNot(HaveOccurred()) // Cannot do equality check since channel is used in initializer - Expect(action).To(BeAssignableToTypeOf(RunErrandAction{})) + Expect(action).To(BeAssignableToTypeOf(boshaction.RunErrandAction{})) }) It("run_script", func() { action, err := factory.Create("run_script") Expect(err).ToNot(HaveOccurred()) - Expect(action).To(Equal(NewRunScript(jobScriptProvider, specService, logger))) + Expect(action).To(Equal(boshaction.NewRunScript(jobScriptProvider, specService, logger))) }) It("prepare", func() { action, err := factory.Create("prepare") Expect(err).ToNot(HaveOccurred()) - Expect(action).To(Equal(NewPrepare(applier))) + Expect(action).To(Equal(boshaction.NewPrepare(applier))) }) It("delete_arp_entries", func() { action, err := factory.Create("delete_arp_entries") Expect(err).ToNot(HaveOccurred()) - Expect(action).To(Equal(NewDeleteARPEntries(platform))) + Expect(action).To(Equal(boshaction.NewDeleteARPEntries(platform))) }) It("shutdown", func() { action, err := factory.Create("shutdown") Expect(err).ToNot(HaveOccurred()) - Expect(action).To(Equal(NewShutdown(platform))) + Expect(action).To(Equal(boshaction.NewShutdown(platform))) }) It("sync_dns", func() { action, err := factory.Create("sync_dns") Expect(err).ToNot(HaveOccurred()) - Expect(action).To(Equal(NewSyncDNS(blobDelegator, settingsService, platform, logger))) + Expect(action).To(Equal(boshaction.NewSyncDNS(blobDelegator, settingsService, platform, logger))) }) It("upload_blob", func() { action, err := factory.Create("upload_blob") Expect(err).ToNot(HaveOccurred()) - Expect(action).To(Equal(NewUploadBlobAction(blobManager))) + Expect(action).To(Equal(boshaction.NewUploadBlobAction(blobManager))) }) }) diff --git a/agent/action/delete_arp_entries_test.go b/agent/action/delete_arp_entries_test.go index 3e1c3aa3f..c83c1529a 100644 --- a/agent/action/delete_arp_entries_test.go +++ b/agent/action/delete_arp_entries_test.go @@ -4,36 +4,36 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - . "github.com/cloudfoundry/bosh-agent/agent/action" + "github.com/cloudfoundry/bosh-agent/agent/action" "github.com/cloudfoundry/bosh-agent/platform/platformfakes" ) var _ = Describe("Delete ARP Entries", func() { var ( - platform *platformfakes.FakePlatform - action DeleteARPEntriesAction - addresses []string - args DeleteARPEntriesActionArgs + platform *platformfakes.FakePlatform + deleteARPEntriesAction action.DeleteARPEntriesAction + addresses []string + args action.DeleteARPEntriesActionArgs ) BeforeEach(func() { platform = &platformfakes.FakePlatform{} - action = NewDeleteARPEntries(platform) + deleteARPEntriesAction = action.NewDeleteARPEntries(platform) addresses = []string{"10.0.0.1", "10.0.0.2"} - args = DeleteARPEntriesActionArgs{ + args = action.DeleteARPEntriesActionArgs{ Ips: addresses, } }) - AssertActionIsNotAsynchronous(action) - AssertActionIsNotPersistent(action) - AssertActionIsLoggable(action) + AssertActionIsNotAsynchronous(deleteARPEntriesAction) + AssertActionIsNotPersistent(deleteARPEntriesAction) + AssertActionIsLoggable(deleteARPEntriesAction) - AssertActionIsNotCancelable(action) - AssertActionIsNotResumable(action) + AssertActionIsNotCancelable(deleteARPEntriesAction) + AssertActionIsNotResumable(deleteARPEntriesAction) It("requests deletion of all provided IPs from the ARP cache", func() { - _, err := action.Run(args) + _, err := deleteARPEntriesAction.Run(args) Expect(err).ToNot(HaveOccurred()) Expect(platform.DeleteARPEntryWithIPCallCount()).To(Equal(2)) Expect(platform.DeleteARPEntryWithIPArgsForCall(0)).To(Equal("10.0.0.1")) @@ -41,7 +41,7 @@ var _ = Describe("Delete ARP Entries", func() { }) It("returns an empty map", func() { - response, err := action.Run(args) + response, err := deleteARPEntriesAction.Run(args) Expect(err).ToNot(HaveOccurred()) Expect(response).To(Equal(map[string]interface{}{})) diff --git a/agent/action/drain_test.go b/agent/action/drain_test.go index 40f1f27ec..f9be7a107 100644 --- a/agent/action/drain_test.go +++ b/agent/action/drain_test.go @@ -6,7 +6,7 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - . "github.com/cloudfoundry/bosh-agent/agent/action" + "github.com/cloudfoundry/bosh-agent/agent/action" "github.com/cloudfoundry/bosh-agent/agent/applier/applyspec" boshas "github.com/cloudfoundry/bosh-agent/agent/applier/applyspec" fakeas "github.com/cloudfoundry/bosh-agent/agent/applier/applyspec/fakes" @@ -26,7 +26,7 @@ var _ = Describe("DrainAction", func() { jobScriptProvider *scriptfakes.FakeJobScriptProvider fakeScripts map[string]*scriptfakes.FakeCancellableScript jobSupervisor *fakejobsuper.FakeJobSupervisor - action DrainAction + drainAction action.DrainAction logger boshlog.Logger ) @@ -37,7 +37,7 @@ var _ = Describe("DrainAction", func() { specService = fakeas.NewFakeV1Service() jobScriptProvider = &scriptfakes.FakeJobScriptProvider{} jobSupervisor = fakejobsuper.NewFakeJobSupervisor() - action = NewDrain(notifier, specService, jobScriptProvider, jobSupervisor, logger) + drainAction = action.NewDrain(notifier, specService, jobScriptProvider, jobSupervisor, logger) }) BeforeEach(func() { @@ -50,11 +50,11 @@ var _ = Describe("DrainAction", func() { } }) - AssertActionIsAsynchronous(action) - AssertActionIsNotPersistent(action) - AssertActionIsLoggable(action) + AssertActionIsAsynchronous(drainAction) + AssertActionIsNotPersistent(drainAction) + AssertActionIsLoggable(drainAction) - AssertActionIsNotResumable(action) + AssertActionIsNotResumable(drainAction) Describe("Run", func() { var ( @@ -87,7 +87,7 @@ var _ = Describe("DrainAction", func() { }) act := func() (int, error) { - return action.Run(DrainTypeUpdate, newSpec) + return drainAction.Run(action.DrainTypeUpdate, newSpec) } Context("when current agent has a job spec template", func() { @@ -167,7 +167,7 @@ var _ = Describe("DrainAction", func() { Context("when apply spec is not provided", func() { It("returns error", func() { - value, err := action.Run(DrainTypeUpdate) + value, err := drainAction.Run(action.DrainTypeUpdate) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("Drain update requires new spec")) Expect(value).To(Equal(0)) @@ -201,7 +201,7 @@ var _ = Describe("DrainAction", func() { }) Context("when drain shutdown is requested", func() { - act := func() (int, error) { return action.Run(DrainTypeShutdown) } + act := func() (int, error) { return drainAction.Run(action.DrainTypeShutdown) } Context("when current agent has a job spec template", func() { var ( @@ -316,7 +316,7 @@ var _ = Describe("DrainAction", func() { }) Context("when drain status is requested", func() { - act := func() (int, error) { return action.Run(DrainTypeStatus) } + act := func() (int, error) { return drainAction.Run(action.DrainTypeStatus) } It("returns an error", func() { value, err := act() @@ -360,12 +360,12 @@ var _ = Describe("DrainAction", func() { specService.Spec = currentSpec }) - Context("when action was not canceled yet", func() { - It("cancel action", func() { - _, err := action.Run(DrainTypeShutdown, newSpec) + Context("when drainAction was not canceled yet", func() { + It("cancel drainAction", func() { + _, err := drainAction.Run(action.DrainTypeShutdown, newSpec) Expect(err).ToNot(HaveOccurred()) - err = action.Cancel() + err = drainAction.Cancel() Expect(err).ToNot(HaveOccurred()) }) }) diff --git a/agent/action/fetch_logs_test.go b/agent/action/fetch_logs_test.go index 98dfa4563..708fdf5b5 100644 --- a/agent/action/fetch_logs_test.go +++ b/agent/action/fetch_logs_test.go @@ -6,7 +6,7 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - . "github.com/cloudfoundry/bosh-agent/agent/action" + "github.com/cloudfoundry/bosh-agent/agent/action" fakeblobdelegator "github.com/cloudfoundry/bosh-agent/agent/httpblobprovider/blobstore_delegator/blobstore_delegatorfakes" boshdirs "github.com/cloudfoundry/bosh-agent/settings/directories" boshassert "github.com/cloudfoundry/bosh-utils/assert" @@ -16,11 +16,11 @@ import ( var _ = Describe("FetchLogsAction", func() { var ( - compressor *fakecmd.FakeCompressor - copier *fakecmd.FakeCopier - blobstore *fakeblobdelegator.FakeBlobstoreDelegator - dirProvider boshdirs.Provider - action FetchLogsAction + compressor *fakecmd.FakeCompressor + copier *fakecmd.FakeCopier + blobstore *fakeblobdelegator.FakeBlobstoreDelegator + dirProvider boshdirs.Provider + fetchLogsAction action.FetchLogsAction ) BeforeEach(func() { @@ -28,15 +28,15 @@ var _ = Describe("FetchLogsAction", func() { blobstore = &fakeblobdelegator.FakeBlobstoreDelegator{} dirProvider = boshdirs.NewProvider("/fake/dir") copier = fakecmd.NewFakeCopier() - action = NewFetchLogs(compressor, copier, blobstore, dirProvider) + fetchLogsAction = action.NewFetchLogs(compressor, copier, blobstore, dirProvider) }) - AssertActionIsAsynchronous(action) - AssertActionIsNotPersistent(action) - AssertActionIsLoggable(action) + AssertActionIsAsynchronous(fetchLogsAction) + AssertActionIsNotPersistent(fetchLogsAction) + AssertActionIsLoggable(fetchLogsAction) - AssertActionIsNotResumable(action) - AssertActionIsNotCancelable(action) + AssertActionIsNotResumable(fetchLogsAction) + AssertActionIsNotCancelable(fetchLogsAction) Describe("Run", func() { testLogs := func(logType string, filters []string, expectedFilters []string) { @@ -48,7 +48,7 @@ var _ = Describe("FetchLogsAction", func() { return "my-blob-id", multidigestSha, nil } - logs, err := action.Run(logType, filters) + logs, err := fetchLogsAction.Run(logType, filters) Expect(err).ToNot(HaveOccurred()) var expectedPath string @@ -72,7 +72,7 @@ var _ = Describe("FetchLogsAction", func() { } It("logs errs if given invalid log type", func() { - _, err := action.Run("other-logs", []string{}) + _, err := fetchLogsAction.Run("other-logs", []string{}) Expect(err).To(HaveOccurred()) }) @@ -111,7 +111,7 @@ var _ = Describe("FetchLogsAction", func() { return "my-blob-id", boshcrypto.MultipleDigest{}, nil } - _, err := action.Run("job", []string{}) + _, err := fetchLogsAction.Run("job", []string{}) Expect(err).ToNot(HaveOccurred()) // Logs are not cleaned up before blobstore upload diff --git a/agent/action/fetch_logs_with_signed_url_test.go b/agent/action/fetch_logs_with_signed_url_test.go index c8b0714e2..5820d384a 100644 --- a/agent/action/fetch_logs_with_signed_url_test.go +++ b/agent/action/fetch_logs_with_signed_url_test.go @@ -6,23 +6,21 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - . "github.com/cloudfoundry/bosh-agent/agent/action" - + "github.com/cloudfoundry/bosh-agent/agent/action" fakeblobdelegator "github.com/cloudfoundry/bosh-agent/agent/httpblobprovider/blobstore_delegator/blobstore_delegatorfakes" - fakecmd "github.com/cloudfoundry/bosh-utils/fileutil/fakes" - boshdirs "github.com/cloudfoundry/bosh-agent/settings/directories" boshassert "github.com/cloudfoundry/bosh-utils/assert" boshcrypto "github.com/cloudfoundry/bosh-utils/crypto" + fakecmd "github.com/cloudfoundry/bosh-utils/fileutil/fakes" ) var _ = Describe("FetchLogsWithSignedURLAction", func() { var ( - compressor *fakecmd.FakeCompressor - copier *fakecmd.FakeCopier - dirProvider boshdirs.Provider - action FetchLogsWithSignedURLAction - blobDelegator *fakeblobdelegator.FakeBlobstoreDelegator + compressor *fakecmd.FakeCompressor + copier *fakecmd.FakeCopier + dirProvider boshdirs.Provider + fetchLogsWithSignedURLAction action.FetchLogsWithSignedURLAction + blobDelegator *fakeblobdelegator.FakeBlobstoreDelegator ) BeforeEach(func() { @@ -31,15 +29,15 @@ var _ = Describe("FetchLogsWithSignedURLAction", func() { copier = fakecmd.NewFakeCopier() blobDelegator = &fakeblobdelegator.FakeBlobstoreDelegator{} - action = NewFetchLogsWithSignedURLAction(compressor, copier, dirProvider, blobDelegator) + fetchLogsWithSignedURLAction = action.NewFetchLogsWithSignedURLAction(compressor, copier, dirProvider, blobDelegator) }) - AssertActionIsAsynchronous(action) - AssertActionIsNotPersistent(action) - AssertActionIsLoggable(action) + AssertActionIsAsynchronous(fetchLogsWithSignedURLAction) + AssertActionIsNotPersistent(fetchLogsWithSignedURLAction) + AssertActionIsLoggable(fetchLogsWithSignedURLAction) - AssertActionIsNotResumable(action) - AssertActionIsNotCancelable(action) + AssertActionIsNotResumable(fetchLogsWithSignedURLAction) + AssertActionIsNotCancelable(fetchLogsWithSignedURLAction) Describe("Run", func() { testLogs := func(logType string, filters []string, expectedFilters []string) { @@ -50,7 +48,7 @@ var _ = Describe("FetchLogsWithSignedURLAction", func() { sha1 := multidigestSha.String() blobDelegator.WriteReturns("", multidigestSha, nil) - logs, err := action.Run(FetchLogsWithSignedURLRequest{SignedURL: "foobar", LogType: logType, Filters: filters, BlobstoreHeaders: map[string]string{"key": "value"}}) + logs, err := fetchLogsWithSignedURLAction.Run(action.FetchLogsWithSignedURLRequest{SignedURL: "foobar", LogType: logType, Filters: filters, BlobstoreHeaders: map[string]string{"key": "value"}}) Expect(err).ToNot(HaveOccurred()) var expectedPath string @@ -76,7 +74,7 @@ var _ = Describe("FetchLogsWithSignedURLAction", func() { } It("logs errs if given invalid log type", func() { - _, err := action.Run(FetchLogsWithSignedURLRequest{LogType: "other-logs", Filters: []string{}}) + _, err := fetchLogsWithSignedURLAction.Run(action.FetchLogsWithSignedURLRequest{LogType: "other-logs", Filters: []string{}}) Expect(err).To(HaveOccurred()) }) @@ -109,7 +107,7 @@ var _ = Describe("FetchLogsWithSignedURLAction", func() { compressor.CompressFilesInDirTarballPath = "/fake-compressed-logs.tar" - _, err := action.Run(FetchLogsWithSignedURLRequest{LogType: "job", Filters: []string{}}) + _, err := fetchLogsWithSignedURLAction.Run(action.FetchLogsWithSignedURLRequest{LogType: "job", Filters: []string{}}) Expect(err).ToNot(HaveOccurred()) // Logs are not cleaned up before blobstore upload diff --git a/agent/action/get_state_test.go b/agent/action/get_state_test.go index 9c8aa840f..53035aa06 100644 --- a/agent/action/get_state_test.go +++ b/agent/action/get_state_test.go @@ -6,7 +6,7 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - . "github.com/cloudfoundry/bosh-agent/agent/action" + "github.com/cloudfoundry/bosh-agent/agent/action" boshas "github.com/cloudfoundry/bosh-agent/agent/applier/applyspec" fakeas "github.com/cloudfoundry/bosh-agent/agent/applier/applyspec/fakes" boshjobsuper "github.com/cloudfoundry/bosh-agent/jobsupervisor" @@ -24,7 +24,7 @@ var _ = Describe("GetState", func() { specService *fakeas.FakeV1Service jobSupervisor *fakejobsuper.FakeJobSupervisor vitalsService *vitalsfakes.FakeService - action GetStateAction + getStateAction action.GetStateAction ) BeforeEach(func() { @@ -32,15 +32,15 @@ var _ = Describe("GetState", func() { jobSupervisor = fakejobsuper.NewFakeJobSupervisor() specService = fakeas.NewFakeV1Service() vitalsService = &vitalsfakes.FakeService{} - action = NewGetState(settingsService, specService, jobSupervisor, vitalsService) + getStateAction = action.NewGetState(settingsService, specService, jobSupervisor, vitalsService) }) - AssertActionIsNotAsynchronous(action) - AssertActionIsNotPersistent(action) - AssertActionIsLoggable(action) + AssertActionIsNotAsynchronous(getStateAction) + AssertActionIsNotPersistent(getStateAction) + AssertActionIsLoggable(getStateAction) - AssertActionIsNotResumable(action) - AssertActionIsNotCancelable(action) + AssertActionIsNotResumable(getStateAction) + AssertActionIsNotCancelable(getStateAction) Describe("Run", func() { Context("when current spec can be retrieved", func() { @@ -55,7 +55,7 @@ var _ = Describe("GetState", func() { Deployment: "fake-deployment", } - expectedSpec := GetStateV1ApplySpec{ + expectedSpec := action.GetStateV1ApplySpec{ V1ApplySpec: boshas.V1ApplySpec{ NetworkSpecs: map[string]boshas.NetworkSpec{}, ResourcePoolSpecs: map[string]interface{}{}, @@ -67,7 +67,7 @@ var _ = Describe("GetState", func() { } expectedSpec.Deployment = "fake-deployment" - state, err := action.Run() + state, err := getStateAction.Run() Expect(err).ToNot(HaveOccurred()) Expect(state.AgentID).To(Equal(expectedSpec.AgentID)) @@ -116,7 +116,7 @@ var _ = Describe("GetState", func() { }, } - state, err := action.Run("full") + state, err := getStateAction.Run("full") Expect(err).ToNot(HaveOccurred()) boshassert.MatchesJSONString(GinkgoT(), state.AgentID, `"my-agent-id"`) @@ -130,7 +130,7 @@ var _ = Describe("GetState", func() { Describe("non-populated field formatting", func() { It("returns network as empty hash if not set", func() { specService.Spec = boshas.V1ApplySpec{NetworkSpecs: nil} - state, err := action.Run("full") + state, err := getStateAction.Run("full") Expect(err).ToNot(HaveOccurred()) boshassert.MatchesJSONString(GinkgoT(), state.NetworkSpecs, `{}`) @@ -142,33 +142,33 @@ var _ = Describe("GetState", func() { }, }, } - state, err = action.Run("full") + state, err = getStateAction.Run("full") Expect(err).ToNot(HaveOccurred()) boshassert.MatchesJSONString(GinkgoT(), state.NetworkSpecs, `{"fake-net-name":{"ip":"fake-ip"}}`) }) It("returns resource_pool as empty hash if not set", func() { specService.Spec = boshas.V1ApplySpec{ResourcePoolSpecs: nil} - state, err := action.Run("full") + state, err := getStateAction.Run("full") Expect(err).ToNot(HaveOccurred()) boshassert.MatchesJSONString(GinkgoT(), state.ResourcePoolSpecs, `{}`) // Non-empty ResourcePoolSpecs specService.Spec = boshas.V1ApplySpec{ResourcePoolSpecs: "fake-resource-pool"} - state, err = action.Run("full") + state, err = getStateAction.Run("full") Expect(err).ToNot(HaveOccurred()) boshassert.MatchesJSONString(GinkgoT(), state.ResourcePoolSpecs, `"fake-resource-pool"`) }) It("returns packages as empty hash if not set", func() { specService.Spec = boshas.V1ApplySpec{PackageSpecs: nil} - state, err := action.Run("full") + state, err := getStateAction.Run("full") Expect(err).ToNot(HaveOccurred()) boshassert.MatchesJSONString(GinkgoT(), state.PackageSpecs, `{}`) // Non-empty PackageSpecs specService.Spec = boshas.V1ApplySpec{PackageSpecs: map[string]boshas.PackageSpec{}} - state, err = action.Run("full") + state, err = getStateAction.Run("full") Expect(err).ToNot(HaveOccurred()) boshassert.MatchesJSONString(GinkgoT(), state.PackageSpecs, `{}`) }) @@ -181,7 +181,7 @@ var _ = Describe("GetState", func() { }) It("returns error", func() { - _, err := action.Run("full") + _, err := getStateAction.Run("full") Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-vitals-get-error")) }) @@ -192,7 +192,7 @@ var _ = Describe("GetState", func() { It("without current spec", func() { specService.GetErr = errors.New("fake-spec-get-error") - _, err := action.Run() + _, err := getStateAction.Run() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-spec-get-error")) }) diff --git a/agent/action/get_task_test.go b/agent/action/get_task_test.go index b26880b10..8239f892f 100644 --- a/agent/action/get_task_test.go +++ b/agent/action/get_task_test.go @@ -6,7 +6,7 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - . "github.com/cloudfoundry/bosh-agent/agent/action" + "github.com/cloudfoundry/bosh-agent/agent/action" boshtask "github.com/cloudfoundry/bosh-agent/agent/task" faketask "github.com/cloudfoundry/bosh-agent/agent/task/fakes" boshassert "github.com/cloudfoundry/bosh-utils/assert" @@ -14,21 +14,21 @@ import ( var _ = Describe("GetTask", func() { var ( - taskService *faketask.FakeService - action GetTaskAction + taskService *faketask.FakeService + getTaskAction action.GetTaskAction ) BeforeEach(func() { taskService = faketask.NewFakeService() - action = NewGetTask(taskService) + getTaskAction = action.NewGetTask(taskService) }) - AssertActionIsNotAsynchronous(action) - AssertActionIsNotPersistent(action) - AssertActionIsLoggable(action) + AssertActionIsNotAsynchronous(getTaskAction) + AssertActionIsNotPersistent(getTaskAction) + AssertActionIsLoggable(getTaskAction) - AssertActionIsNotResumable(action) - AssertActionIsNotCancelable(action) + AssertActionIsNotResumable(getTaskAction) + AssertActionIsNotCancelable(getTaskAction) It("returns a running task", func() { taskService.StartedTasks["fake-task-id"] = boshtask.Task{ @@ -36,7 +36,7 @@ var _ = Describe("GetTask", func() { State: boshtask.StateRunning, } - taskValue, err := action.Run("fake-task-id") + taskValue, err := getTaskAction.Run("fake-task-id") Expect(err).ToNot(HaveOccurred()) // Check JSON key casing @@ -51,7 +51,7 @@ var _ = Describe("GetTask", func() { Error: errors.New("fake-task-error"), } - taskValue, err := action.Run("fake-task-id") + taskValue, err := getTaskAction.Run("fake-task-id") Expect(err).To(HaveOccurred()) Expect(err.Error()).To(Equal("Task fake-task-id result: fake-task-error")) Expect(taskValue).To(BeNil()) @@ -64,7 +64,7 @@ var _ = Describe("GetTask", func() { Value: "some-task-value", } - taskValue, err := action.Run("fake-task-id") + taskValue, err := getTaskAction.Run("fake-task-id") Expect(err).ToNot(HaveOccurred()) Expect(taskValue).To(Equal("some-task-value")) }) @@ -72,7 +72,7 @@ var _ = Describe("GetTask", func() { It("returns error when task is not found", func() { taskService.StartedTasks = map[string]boshtask.Task{} - _, err := action.Run("fake-task-id") + _, err := getTaskAction.Run("fake-task-id") Expect(err).To(HaveOccurred()) Expect(err.Error()).To(Equal("Task with id fake-task-id could not be found")) }) diff --git a/agent/action/info_test.go b/agent/action/info_test.go index 5707c2f74..af4d5b500 100644 --- a/agent/action/info_test.go +++ b/agent/action/info_test.go @@ -1,30 +1,30 @@ package action_test import ( - . "github.com/cloudfoundry/bosh-agent/agent/action" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + + "github.com/cloudfoundry/bosh-agent/agent/action" ) var _ = Describe("Info", func() { var ( - action InfoAction + infoAction action.InfoAction ) BeforeEach(func() { - action = NewInfo() + infoAction = action.NewInfo() }) - AssertActionIsNotAsynchronous(action) - AssertActionIsNotPersistent(action) - AssertActionIsLoggable(action) + AssertActionIsNotAsynchronous(infoAction) + AssertActionIsNotPersistent(infoAction) + AssertActionIsLoggable(infoAction) - AssertActionIsNotResumable(action) - AssertActionIsNotCancelable(action) + AssertActionIsNotResumable(infoAction) + AssertActionIsNotCancelable(infoAction) It("returns the api version", func() { - infoResponse, err := action.Run() + infoResponse, err := infoAction.Run() Expect(err).ToNot(HaveOccurred()) Expect(infoResponse.APIVersion).To(Equal(1)) }) diff --git a/agent/action/list_disk_test.go b/agent/action/list_disk_test.go index 404f8b25f..12aca98ca 100644 --- a/agent/action/list_disk_test.go +++ b/agent/action/list_disk_test.go @@ -4,7 +4,7 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - . "github.com/cloudfoundry/bosh-agent/agent/action" + "github.com/cloudfoundry/bosh-agent/agent/action" "github.com/cloudfoundry/bosh-agent/platform/platformfakes" boshsettings "github.com/cloudfoundry/bosh-agent/settings" fakesettings "github.com/cloudfoundry/bosh-agent/settings/fakes" @@ -17,14 +17,14 @@ var _ = Describe("ListDisk", func() { settingsService *fakesettings.FakeSettingsService platform *platformfakes.FakePlatform logger boshlog.Logger - action ListDiskAction + listDiskAction action.ListDiskAction ) BeforeEach(func() { settingsService = &fakesettings.FakeSettingsService{} platform = &platformfakes.FakePlatform{} logger = boshlog.NewLogger(boshlog.LevelNone) - action = NewListDisk(settingsService, platform, logger) + listDiskAction = action.NewListDisk(settingsService, platform, logger) platform.IsPersistentDiskMountedStub = func(settings boshsettings.DiskSettings) (bool, error) { if settings.Path == "/dev/sdb" || settings.Path == "/dev/sdc" { @@ -35,15 +35,15 @@ var _ = Describe("ListDisk", func() { } }) - AssertActionIsSynchronousForVersion(action, 1) - AssertActionIsSynchronousForVersion(action, 2) - AssertActionIsAsynchronousForVersion(action, 3) + AssertActionIsSynchronousForVersion(listDiskAction, 1) + AssertActionIsSynchronousForVersion(listDiskAction, 2) + AssertActionIsAsynchronousForVersion(listDiskAction, 3) - AssertActionIsNotPersistent(action) - AssertActionIsLoggable(action) + AssertActionIsNotPersistent(listDiskAction) + AssertActionIsLoggable(listDiskAction) - AssertActionIsNotResumable(action) - AssertActionIsNotCancelable(action) + AssertActionIsNotResumable(listDiskAction) + AssertActionIsNotCancelable(listDiskAction) Context("list disk run", func() { Context("persistent disks defined", func() { @@ -69,7 +69,7 @@ var _ = Describe("ListDisk", func() { }) It("returns list of mounted disks", func() { - value, err := action.Run() + value, err := listDiskAction.Run() Expect(err).ToNot(HaveOccurred()) values, ok := value.([]string) Expect(ok).To(BeTrue()) @@ -83,7 +83,7 @@ var _ = Describe("ListDisk", func() { Context("there are no disks", func() { It("returns an empty array", func() { - result, err := action.Run() + result, err := listDiskAction.Run() Expect(err).ToNot(HaveOccurred()) Expect(result).ToNot(BeNil()) Expect(result).To(Equal(make([]string, 0))) @@ -96,7 +96,7 @@ var _ = Describe("ListDisk", func() { It("should return an error", func() { settingsService.LoadSettingsError = bosherrors.Error("fake loadsettings error") - _, err := action.Run() + _, err := listDiskAction.Run() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("Refreshing the settings: fake loadsettings error")) }) @@ -105,7 +105,7 @@ var _ = Describe("ListDisk", func() { Context("when unable to load persistent disk hints", func() { Context("when persistent disk settings file does not exist", func() { It("should not return an error", func() { - _, err := action.Run() + _, err := listDiskAction.Run() Expect(err).ToNot(HaveOccurred()) }) }) @@ -114,7 +114,7 @@ var _ = Describe("ListDisk", func() { It("should return an error", func() { settingsService.GetAllPersistentDiskSettingsError = bosherrors.Error("fake get persistent disk hints error") - _, err := action.Run() + _, err := listDiskAction.Run() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("Getting persistent disk settings: fake get persistent disk hints error")) }) diff --git a/agent/action/migrate_disk_test.go b/agent/action/migrate_disk_test.go index a63d6d0e2..ca61ad189 100644 --- a/agent/action/migrate_disk_test.go +++ b/agent/action/migrate_disk_test.go @@ -4,7 +4,7 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - . "github.com/cloudfoundry/bosh-agent/agent/action" + "github.com/cloudfoundry/bosh-agent/agent/action" "github.com/cloudfoundry/bosh-agent/platform/platformfakes" boshdirs "github.com/cloudfoundry/bosh-agent/settings/directories" boshassert "github.com/cloudfoundry/bosh-utils/assert" @@ -12,25 +12,25 @@ import ( var _ = Describe("Testing with Ginkgo", func() { var ( - action MigrateDiskAction - platform *platformfakes.FakePlatform + migrateDiskAction action.MigrateDiskAction + platform *platformfakes.FakePlatform ) BeforeEach(func() { platform = &platformfakes.FakePlatform{} dirProvider := boshdirs.NewProvider("/foo") - action = NewMigrateDisk(platform, dirProvider) + migrateDiskAction = action.NewMigrateDisk(platform, dirProvider) }) - AssertActionIsAsynchronous(action) - AssertActionIsNotPersistent(action) - AssertActionIsLoggable(action) + AssertActionIsAsynchronous(migrateDiskAction) + AssertActionIsNotPersistent(migrateDiskAction) + AssertActionIsLoggable(migrateDiskAction) - AssertActionIsNotResumable(action) - AssertActionIsNotCancelable(action) + AssertActionIsNotResumable(migrateDiskAction) + AssertActionIsNotCancelable(migrateDiskAction) - It("migrate disk action run", func() { - value, err := action.Run() + It("migrate disk migrateDiskAction run", func() { + value, err := migrateDiskAction.Run() Expect(err).ToNot(HaveOccurred()) boshassert.MatchesJSONString(GinkgoT(), value, "{}") diff --git a/agent/action/mount_disk_test.go b/agent/action/mount_disk_test.go index 00816664e..0db69b557 100644 --- a/agent/action/mount_disk_test.go +++ b/agent/action/mount_disk_test.go @@ -6,7 +6,7 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - . "github.com/cloudfoundry/bosh-agent/agent/action" + "github.com/cloudfoundry/bosh-agent/agent/action" "github.com/cloudfoundry/bosh-agent/platform/platformfakes" boshsettings "github.com/cloudfoundry/bosh-agent/settings" boshdirs "github.com/cloudfoundry/bosh-agent/settings/directories" @@ -19,7 +19,7 @@ var _ = Describe("MountDiskAction", func() { var ( settingsService *fakesettings.FakeSettingsService platform *platformfakes.FakePlatform - action MountDiskAction + mountDiskAction action.MountDiskAction logger boshlog.Logger ) @@ -28,19 +28,19 @@ var _ = Describe("MountDiskAction", func() { platform = &platformfakes.FakePlatform{} dirProvider := boshdirs.NewProvider("/fake-base-dir") logger = boshlog.NewLogger(boshlog.LevelNone) - action = NewMountDisk(settingsService, platform, dirProvider, logger) + mountDiskAction = action.NewMountDisk(settingsService, platform, dirProvider, logger) }) - AssertActionIsAsynchronous(action) - AssertActionIsNotPersistent(action) - AssertActionIsLoggable(action) + AssertActionIsAsynchronous(mountDiskAction) + AssertActionIsNotPersistent(mountDiskAction) + AssertActionIsLoggable(mountDiskAction) - AssertActionIsNotResumable(action) - AssertActionIsNotCancelable(action) + AssertActionIsNotResumable(mountDiskAction) + AssertActionIsNotCancelable(mountDiskAction) Describe("Run", func() { Context("when settings can be loaded", func() { - Context("when a disk hint is NOT passed in the action arguments", func() { + Context("when a disk hint is NOT passed in the mountDiskAction arguments", func() { Context("when disk cid can be resolved to a device path from infrastructure settings", func() { BeforeEach(func() { settingsService.PersistentDiskSettings = map[string]boshsettings.DiskSettings{ @@ -58,7 +58,7 @@ var _ = Describe("MountDiskAction", func() { }) It("returns error after trying to adjust partitioning", func() { - _, err := action.Run("fake-disk-cid") + _, err := mountDiskAction.Run("fake-disk-cid") Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-adjust-persistent-disk-partitioning-err")) Expect(platform.AdjustPersistentDiskPartitioningCallCount()).To(Equal(1)) @@ -77,7 +77,7 @@ var _ = Describe("MountDiskAction", func() { Context("when mounting succeeds", func() { It("returns without an error after mounting store directory", func() { - result, err := action.Run("fake-disk-cid") + result, err := mountDiskAction.Run("fake-disk-cid") Expect(err).NotTo(HaveOccurred()) Expect(result).To(Equal(map[string]string{})) @@ -94,7 +94,7 @@ var _ = Describe("MountDiskAction", func() { }) It("does not save disk hint", func() { - result, err := action.Run("fake-disk-cid") + result, err := mountDiskAction.Run("fake-disk-cid") Expect(err).NotTo(HaveOccurred()) Expect(result).To(Equal(map[string]string{})) Expect(settingsService.SavePersistentDiskSettingsCallCount).To(Equal(0)) @@ -107,7 +107,7 @@ var _ = Describe("MountDiskAction", func() { }) It("returns error after trying to mount store directory", func() { - _, err := action.Run("fake-disk-cid") + _, err := mountDiskAction.Run("fake-disk-cid") Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-mount-persistent-disk-err")) Expect(settingsService.SavePersistentDiskSettingsCallCount).To(Equal(0)) @@ -121,7 +121,7 @@ var _ = Describe("MountDiskAction", func() { }) It("returns error", func() { - _, err := action.Run("fake-unknown-disk-cid") + _, err := mountDiskAction.Run("fake-unknown-disk-cid") Expect(err).To(HaveOccurred()) Expect(err.Error()).To(Equal("Reading persistent disk settings: Persistent disk with volume id 'fake-unknown-disk-cid' could not be found")) }) @@ -133,7 +133,7 @@ var _ = Describe("MountDiskAction", func() { It("returns error", func() { settingsService.LoadSettingsError = errors.New("fake-load-settings-err") - _, err := action.Run("fake-disk-cid") + _, err := mountDiskAction.Run("fake-disk-cid") Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-load-settings-err")) }) diff --git a/agent/action/ping_test.go b/agent/action/ping_test.go index 04621af4d..80e7b89c3 100644 --- a/agent/action/ping_test.go +++ b/agent/action/ping_test.go @@ -4,28 +4,28 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - . "github.com/cloudfoundry/bosh-agent/agent/action" + "github.com/cloudfoundry/bosh-agent/agent/action" ) var _ = Describe("Ping", func() { var ( - action PingAction + pingAction action.PingAction ) BeforeEach(func() { - action = NewPing() + pingAction = action.NewPing() }) - AssertActionIsNotAsynchronous(action) - AssertActionIsNotPersistent(action) - AssertActionIsLoggable(action) + AssertActionIsNotAsynchronous(pingAction) + AssertActionIsNotPersistent(pingAction) + AssertActionIsLoggable(pingAction) - AssertActionIsNotResumable(action) - AssertActionIsNotCancelable(action) + AssertActionIsNotResumable(pingAction) + AssertActionIsNotCancelable(pingAction) It("ping run returns pong", func() { - pong, err := action.Run() + pong, err := pingAction.Run() Expect(err).ToNot(HaveOccurred()) Expect(pong).To(Equal("pong")) }) diff --git a/agent/action/prepare_configure_networks_test.go b/agent/action/prepare_configure_networks_test.go index 3c13748d4..c9082dcf0 100644 --- a/agent/action/prepare_configure_networks_test.go +++ b/agent/action/prepare_configure_networks_test.go @@ -3,38 +3,37 @@ package action_test import ( "errors" - . "github.com/cloudfoundry/bosh-agent/agent/action" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "github.com/cloudfoundry/bosh-agent/agent/action" "github.com/cloudfoundry/bosh-agent/platform/platformfakes" - fakesettings "github.com/cloudfoundry/bosh-agent/settings/fakes" ) var _ = Describe("prepareConfigureNetworks", func() { var ( - action PrepareConfigureNetworksAction - platform *platformfakes.FakePlatform - settingsService *fakesettings.FakeSettingsService + prepareConfigureNetworksAction action.PrepareConfigureNetworksAction + platform *platformfakes.FakePlatform + settingsService *fakesettings.FakeSettingsService ) BeforeEach(func() { platform = &platformfakes.FakePlatform{} settingsService = &fakesettings.FakeSettingsService{} - action = NewPrepareConfigureNetworks(platform, settingsService) + prepareConfigureNetworksAction = action.NewPrepareConfigureNetworks(platform, settingsService) }) - AssertActionIsNotAsynchronous(action) - AssertActionIsNotPersistent(action) - AssertActionIsLoggable(action) + AssertActionIsNotAsynchronous(prepareConfigureNetworksAction) + AssertActionIsNotPersistent(prepareConfigureNetworksAction) + AssertActionIsLoggable(prepareConfigureNetworksAction) - AssertActionIsNotResumable(action) - AssertActionIsNotCancelable(action) + AssertActionIsNotResumable(prepareConfigureNetworksAction) + AssertActionIsNotCancelable(prepareConfigureNetworksAction) Describe("Run", func() { It("invalidates settings so that load settings cannot fall back on old settings", func() { - resp, err := action.Run() + resp, err := prepareConfigureNetworksAction.Run() Expect(err).NotTo(HaveOccurred()) Expect(resp).To(Equal("ok")) @@ -43,7 +42,7 @@ var _ = Describe("prepareConfigureNetworks", func() { Context("when settings invalidation succeeds", func() { It("prepares platform for networking change", func() { - resp, err := action.Run() + resp, err := prepareConfigureNetworksAction.Run() Expect(err).NotTo(HaveOccurred()) Expect(resp).To(Equal("ok")) @@ -56,7 +55,7 @@ var _ = Describe("prepareConfigureNetworks", func() { }) It("returns error if preparing for networking change fails", func() { - resp, err := action.Run() + resp, err := prepareConfigureNetworksAction.Run() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-prepare-error")) Expect(resp).To(Equal("")) @@ -70,7 +69,7 @@ var _ = Describe("prepareConfigureNetworks", func() { }) It("returns error early if settings err invalidating", func() { - resp, err := action.Run() + resp, err := prepareConfigureNetworksAction.Run() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-invalidate-error")) @@ -78,7 +77,7 @@ var _ = Describe("prepareConfigureNetworks", func() { }) It("does not prepare platform for networking change", func() { - _, err := action.Run() + _, err := prepareConfigureNetworksAction.Run() Expect(err).To(HaveOccurred()) Expect(platform.PrepareForNetworkingChangeCallCount()).To(Equal(0)) diff --git a/agent/action/prepare_test.go b/agent/action/prepare_test.go index 325653593..4c1e77297 100644 --- a/agent/action/prepare_test.go +++ b/agent/action/prepare_test.go @@ -6,34 +6,34 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - . "github.com/cloudfoundry/bosh-agent/agent/action" + "github.com/cloudfoundry/bosh-agent/agent/action" boshas "github.com/cloudfoundry/bosh-agent/agent/applier/applyspec" fakeappl "github.com/cloudfoundry/bosh-agent/agent/applier/fakes" ) var _ = Describe("PrepareAction", func() { var ( - applier *fakeappl.FakeApplier - action PrepareAction + applier *fakeappl.FakeApplier + prepareAction action.PrepareAction ) BeforeEach(func() { applier = fakeappl.NewFakeApplier() - action = NewPrepare(applier) + prepareAction = action.NewPrepare(applier) }) - AssertActionIsAsynchronous(action) - AssertActionIsNotPersistent(action) - AssertActionIsLoggable(action) + AssertActionIsAsynchronous(prepareAction) + AssertActionIsNotPersistent(prepareAction) + AssertActionIsLoggable(prepareAction) - AssertActionIsNotResumable(action) - AssertActionIsNotCancelable(action) + AssertActionIsNotResumable(prepareAction) + AssertActionIsNotCancelable(prepareAction) Describe("Run", func() { desiredApplySpec := boshas.V1ApplySpec{ConfigurationHash: "fake-desired-config-hash"} It("runs applier to prepare vm for future configuration with desired apply spec", func() { - _, err := action.Run(desiredApplySpec) + _, err := prepareAction.Run(desiredApplySpec) Expect(err).ToNot(HaveOccurred()) Expect(applier.Prepared).To(BeTrue()) Expect(applier.PrepareDesiredApplySpec).To(Equal(desiredApplySpec)) @@ -41,7 +41,7 @@ var _ = Describe("PrepareAction", func() { Context("when applier succeeds preparing vm", func() { It("returns 'applied' after setting desired spec as current spec", func() { - value, err := action.Run(desiredApplySpec) + value, err := prepareAction.Run(desiredApplySpec) Expect(err).ToNot(HaveOccurred()) Expect(value).To(Equal("prepared")) }) @@ -51,7 +51,7 @@ var _ = Describe("PrepareAction", func() { It("returns error", func() { applier.PrepareError = errors.New("fake-prepare-error") - _, err := action.Run(desiredApplySpec) + _, err := prepareAction.Run(desiredApplySpec) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-prepare-error")) }) diff --git a/agent/action/release_apply_spec_test.go b/agent/action/release_apply_spec_test.go index 156b0b674..cba4a3aa2 100644 --- a/agent/action/release_apply_spec_test.go +++ b/agent/action/release_apply_spec_test.go @@ -1,41 +1,40 @@ package action_test import ( - . "github.com/cloudfoundry/bosh-agent/agent/action" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "github.com/cloudfoundry/bosh-agent/agent/action" "github.com/cloudfoundry/bosh-agent/platform/platformfakes" - fakesys "github.com/cloudfoundry/bosh-utils/system/fakes" ) var _ = Describe("ReleaseApplySpec", func() { var ( - platform *platformfakes.FakePlatform - action ReleaseApplySpecAction - fileSystem *fakesys.FakeFileSystem + platform *platformfakes.FakePlatform + releaseApplySpecAction action.ReleaseApplySpecAction + fileSystem *fakesys.FakeFileSystem ) BeforeEach(func() { platform = &platformfakes.FakePlatform{} fileSystem = fakesys.NewFakeFileSystem() platform.GetFsReturns(fileSystem) - action = NewReleaseApplySpec(platform) + releaseApplySpecAction = action.NewReleaseApplySpec(platform) }) - AssertActionIsNotAsynchronous(action) - AssertActionIsNotPersistent(action) - AssertActionIsLoggable(action) + AssertActionIsNotAsynchronous(releaseApplySpecAction) + AssertActionIsNotPersistent(releaseApplySpecAction) + AssertActionIsLoggable(releaseApplySpecAction) - AssertActionIsNotResumable(action) - AssertActionIsNotCancelable(action) + AssertActionIsNotResumable(releaseApplySpecAction) + AssertActionIsNotCancelable(releaseApplySpecAction) It("run", func() { err := fileSystem.WriteFileString("/var/vcap/micro/apply_spec.json", `{"json":["objects"]}`) Expect(err).ToNot(HaveOccurred()) - value, err := action.Run() + value, err := releaseApplySpecAction.Run() Expect(err).ToNot(HaveOccurred()) Expect(value).To(Equal(map[string]interface{}{"json": []interface{}{"objects"}})) diff --git a/agent/action/run_errand_test.go b/agent/action/run_errand_test.go index cb7fa91b5..b1ae5ce99 100644 --- a/agent/action/run_errand_test.go +++ b/agent/action/run_errand_test.go @@ -2,36 +2,35 @@ package action_test import ( "errors" + "runtime" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - . "github.com/cloudfoundry/bosh-agent/agent/action" - + "github.com/cloudfoundry/bosh-agent/agent/action" boshas "github.com/cloudfoundry/bosh-agent/agent/applier/applyspec" fakeas "github.com/cloudfoundry/bosh-agent/agent/applier/applyspec/fakes" boshenv "github.com/cloudfoundry/bosh-agent/agent/script/pathenv" boshlog "github.com/cloudfoundry/bosh-utils/logger" boshsys "github.com/cloudfoundry/bosh-utils/system" fakesys "github.com/cloudfoundry/bosh-utils/system/fakes" - "runtime" ) var _ = Describe("RunErrand", func() { var ( - specService *fakeas.FakeV1Service - cmdRunner *fakesys.FakeCmdRunner - action RunErrandAction - errandName string - fullCommand string + specService *fakeas.FakeV1Service + cmdRunner *fakesys.FakeCmdRunner + runErrandAction action.RunErrandAction + errandName string + fullCommand string ) BeforeEach(func() { specService = fakeas.NewFakeV1Service() cmdRunner = fakesys.NewFakeCmdRunner() logger := boshlog.NewLogger(boshlog.LevelNone) - action = NewRunErrand(specService, "/fake-jobs-dir", cmdRunner, logger) + runErrandAction = action.NewRunErrand(specService, "/fake-jobs-dir", cmdRunner, logger) errandName = "fake-job-name" if runtime.GOOS == "windows" { fullCommand = "powershell /fake-jobs-dir/fake-job-name/bin/run" @@ -40,11 +39,11 @@ var _ = Describe("RunErrand", func() { } }) - AssertActionIsAsynchronous(action) - AssertActionIsNotPersistent(action) - AssertActionIsLoggable(action) + AssertActionIsAsynchronous(runErrandAction) + AssertActionIsNotPersistent(runErrandAction) + AssertActionIsLoggable(runErrandAction) - AssertActionIsNotResumable(action) + AssertActionIsNotResumable(runErrandAction) Describe("Run", func() { Context("when apply spec is successfully retrieved", func() { @@ -63,10 +62,10 @@ var _ = Describe("RunErrand", func() { }) It("returns errand result without error after running an errand", func() { - result, err := action.Run() + result, err := runErrandAction.Run() Expect(err).ToNot(HaveOccurred()) Expect(result).To(Equal( - ErrandResult{ + action.ErrandResult{ Stdout: "fake-stdout", Stderr: "fake-stderr", ExitStatus: 0, @@ -101,10 +100,10 @@ var _ = Describe("RunErrand", func() { }) It("returns errand result without error after running an errand", func() { - result, err := action.Run(errandName) + result, err := runErrandAction.Run(errandName) Expect(err).ToNot(HaveOccurred()) Expect(result).To(Equal( - ErrandResult{ + action.ErrandResult{ Stdout: "fake-stdout", Stderr: "fake-stderr", ExitStatus: 0, @@ -113,7 +112,7 @@ var _ = Describe("RunErrand", func() { }) It("runs errand script with properly configured environment", func() { - _, err := action.Run(errandName) + _, err := runErrandAction.Run(errandName) Expect(err).ToNot(HaveOccurred()) cmd := cmdRunner.RunComplexCommands[0] env := map[string]string{"PATH": boshenv.Path()} @@ -134,10 +133,10 @@ var _ = Describe("RunErrand", func() { }) It("returns errand result without an error", func() { - result, err := action.Run(errandName) + result, err := runErrandAction.Run(errandName) Expect(err).ToNot(HaveOccurred()) Expect(result).To(Equal( - ErrandResult{ + action.ErrandResult{ Stdout: "fake-stdout", Stderr: "fake-stderr", ExitStatus: 123, @@ -157,10 +156,10 @@ var _ = Describe("RunErrand", func() { }) It("returns error because script failed to execute", func() { - result, err := action.Run(errandName) + result, err := runErrandAction.Run(errandName) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-bosh-error")) - Expect(result).To(Equal(ErrandResult{})) + Expect(result).To(Equal(action.ErrandResult{})) }) }) }) @@ -171,13 +170,13 @@ var _ = Describe("RunErrand", func() { }) It("returns error stating the errand cannot be found", func() { - _, err := action.Run(errandName) + _, err := runErrandAction.Run(errandName) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(Equal("Could not find errand fake-job-name")) }) It("does not run errand script", func() { - _, err := action.Run(errandName) + _, err := runErrandAction.Run(errandName) Expect(err).To(HaveOccurred()) Expect(len(cmdRunner.RunComplexCommands)).To(Equal(0)) }) @@ -190,13 +189,13 @@ var _ = Describe("RunErrand", func() { }) It("returns error stating that job template is required", func() { - _, err := action.Run(errandName) + _, err := runErrandAction.Run(errandName) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-get-error")) }) It("does not run errand script", func() { - _, err := action.Run(errandName) + _, err := runErrandAction.Run(errandName) Expect(err).To(HaveOccurred()) Expect(len(cmdRunner.RunComplexCommands)).To(Equal(0)) }) @@ -220,7 +219,7 @@ var _ = Describe("RunErrand", func() { specService.Spec = currentSpec }) - Context("when action was not cancelled yet", func() { + Context("when runErrandAction was not cancelled yet", func() { It("terminates errand nicely giving it 10 secs to exit on its own", func() { process := &fakesys.FakeProcess{ TerminatedNicelyCallBack: func(p *fakesys.FakeProcess) { @@ -234,10 +233,10 @@ var _ = Describe("RunErrand", func() { cmdRunner.AddProcess(fullCommand, process) - err := action.Cancel() + err := runErrandAction.Cancel() Expect(err).ToNot(HaveOccurred()) - _, err = action.Run(errandName) + _, err = runErrandAction.Run(errandName) Expect(err).ToNot(HaveOccurred()) Expect(process.TerminateNicelyKillGracePeriod).To(Equal(10 * time.Second)) @@ -257,13 +256,13 @@ var _ = Describe("RunErrand", func() { }) It("returns errand result without error after running an errand", func() { - err := action.Cancel() + err := runErrandAction.Cancel() Expect(err).ToNot(HaveOccurred()) - result, err := action.Run(errandName) + result, err := runErrandAction.Run(errandName) Expect(err).ToNot(HaveOccurred()) Expect(result).To(Equal( - ErrandResult{ + action.ErrandResult{ Stdout: "fake-stdout", Stderr: "fake-stderr", ExitStatus: 0, @@ -287,13 +286,13 @@ var _ = Describe("RunErrand", func() { }) It("returns errand result without an error", func() { - err := action.Cancel() + err := runErrandAction.Cancel() Expect(err).ToNot(HaveOccurred()) - result, err := action.Run(errandName) + result, err := runErrandAction.Run(errandName) Expect(err).ToNot(HaveOccurred()) Expect(result).To(Equal( - ErrandResult{ + action.ErrandResult{ Stdout: "fake-stdout", Stderr: "fake-stderr", ExitStatus: 123, @@ -315,18 +314,18 @@ var _ = Describe("RunErrand", func() { }) It("returns error because script failed to execute", func() { - err := action.Cancel() + err := runErrandAction.Cancel() Expect(err).ToNot(HaveOccurred()) - result, err := action.Run(errandName) + result, err := runErrandAction.Run(errandName) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-bosh-error")) - Expect(result).To(Equal(ErrandResult{})) + Expect(result).To(Equal(action.ErrandResult{})) }) }) }) - Context("when action was cancelled already", func() { + Context("when runErrandAction was cancelled already", func() { BeforeEach(func() { cmdRunner.AddProcess(fullCommand, &fakesys.FakeProcess{ TerminatedNicelyCallBack: func(p *fakesys.FakeProcess) { @@ -338,11 +337,11 @@ var _ = Describe("RunErrand", func() { }) }) - It("allows to cancel action second time without returning an error", func() { - err := action.Cancel() + It("allows to cancel runErrandAction second time without returning an error", func() { + err := runErrandAction.Cancel() Expect(err).ToNot(HaveOccurred()) - err = action.Cancel() + err = runErrandAction.Cancel() Expect(err).ToNot(HaveOccurred()) // returns without waiting }) }) diff --git a/agent/action/run_script_test.go b/agent/action/run_script_test.go index 6a0e4c435..c7d9a38c1 100644 --- a/agent/action/run_script_test.go +++ b/agent/action/run_script_test.go @@ -6,7 +6,7 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - . "github.com/cloudfoundry/bosh-agent/agent/action" + "github.com/cloudfoundry/bosh-agent/agent/action" "github.com/cloudfoundry/bosh-agent/agent/applier/applyspec" fakeapplyspec "github.com/cloudfoundry/bosh-agent/agent/applier/applyspec/fakes" boshscript "github.com/cloudfoundry/bosh-agent/agent/script" @@ -18,8 +18,8 @@ var _ = Describe("RunScript", func() { var ( fakeJobScriptProvider *scriptfakes.FakeJobScriptProvider specService *fakeapplyspec.FakeV1Service - action RunScriptAction - options RunScriptOptions + runScriptAction action.RunScriptAction + options action.RunScriptOptions ) BeforeEach(func() { @@ -27,23 +27,23 @@ var _ = Describe("RunScript", func() { specService = fakeapplyspec.NewFakeV1Service() specService.Spec.RenderedTemplatesArchiveSpec = &applyspec.RenderedTemplatesArchiveSpec{} logger := boshlog.NewLogger(boshlog.LevelNone) - action = NewRunScript(fakeJobScriptProvider, specService, logger) - options = RunScriptOptions{ + runScriptAction = action.NewRunScript(fakeJobScriptProvider, specService, logger) + options = action.RunScriptOptions{ Env: map[string]string{ "FOO": "foo", }, } }) - AssertActionIsAsynchronous(action) - AssertActionIsNotPersistent(action) - AssertActionIsLoggable(action) + AssertActionIsAsynchronous(runScriptAction) + AssertActionIsNotPersistent(runScriptAction) + AssertActionIsLoggable(runScriptAction) - AssertActionIsNotResumable(action) - AssertActionIsNotCancelable(action) + AssertActionIsNotResumable(runScriptAction) + AssertActionIsNotCancelable(runScriptAction) Describe("Run", func() { - act := func() (map[string]string, error) { return action.Run("run-me", options) } + act := func() (map[string]string, error) { return runScriptAction.Run("run-me", options) } Context("when current spec can be retrieved", func() { var parallelScript *scriptfakes.FakeCancellableScript diff --git a/agent/action/runner_test.go b/agent/action/runner_test.go index 679d10359..77385ad1d 100644 --- a/agent/action/runner_test.go +++ b/agent/action/runner_test.go @@ -3,13 +3,12 @@ package action_test import ( "errors" - "github.com/stretchr/testify/assert" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - . "github.com/cloudfoundry/bosh-agent/agent/action" + "github.com/cloudfoundry/bosh-agent/agent/action" fakeaction "github.com/cloudfoundry/bosh-agent/agent/action/fakes" + "github.com/stretchr/testify/assert" ) type valueType struct { @@ -41,11 +40,10 @@ type argumentWithTypes struct { type actionWithTypes struct { Value valueType Err error - - Arg argumentWithTypes + Arg argumentWithTypes } -func (a *actionWithTypes) IsAsynchronous(_ ProtocolVersion) bool { +func (a *actionWithTypes) IsAsynchronous(_ action.ProtocolVersion) bool { return false } @@ -77,7 +75,7 @@ type actionWithSingleStringArgument struct { Arg string } -func (a *actionWithSingleStringArgument) IsAsynchronous(_ ProtocolVersion) bool { +func (a *actionWithSingleStringArgument) IsAsynchronous(_ action.ProtocolVersion) bool { return false } @@ -112,7 +110,7 @@ type actionWithGoodRunMethod struct { SliceArgs []string } -func (a *actionWithGoodRunMethod) IsAsynchronous(_ ProtocolVersion) bool { +func (a *actionWithGoodRunMethod) IsAsynchronous(_ action.ProtocolVersion) bool { return false } @@ -148,7 +146,7 @@ type actionWithOptionalRunArgument struct { Err error } -func (a *actionWithOptionalRunArgument) IsAsynchronous(_ ProtocolVersion) bool { +func (a *actionWithOptionalRunArgument) IsAsynchronous(_ action.ProtocolVersion) bool { return false } @@ -176,7 +174,7 @@ func (a *actionWithOptionalRunArgument) Cancel() error { type actionWithoutRunMethod struct{} -func (a *actionWithoutRunMethod) IsAsynchronous(_ ProtocolVersion) bool { +func (a *actionWithoutRunMethod) IsAsynchronous(_ action.ProtocolVersion) bool { return false } @@ -198,7 +196,7 @@ func (a *actionWithoutRunMethod) Cancel() error { type actionWithOneRunReturnValue struct{} -func (a *actionWithOneRunReturnValue) IsAsynchronous(_ ProtocolVersion) bool { +func (a *actionWithOneRunReturnValue) IsAsynchronous(_ action.ProtocolVersion) bool { return false } @@ -224,7 +222,7 @@ func (a *actionWithOneRunReturnValue) Cancel() error { type actionWithSecondReturnValueNotError struct{} -func (a *actionWithSecondReturnValueNotError) IsAsynchronous(_ ProtocolVersion) bool { +func (a *actionWithSecondReturnValueNotError) IsAsynchronous(_ action.ProtocolVersion) bool { return false } @@ -249,11 +247,11 @@ func (a *actionWithSecondReturnValueNotError) Cancel() error { } type actionWithProtocolVersion struct { - ProtocolVersion ProtocolVersion + ProtocolVersion action.ProtocolVersion SubAction string } -func (a *actionWithProtocolVersion) IsAsynchronous(_ ProtocolVersion) bool { +func (a *actionWithProtocolVersion) IsAsynchronous(_ action.ProtocolVersion) bool { return false } @@ -265,7 +263,7 @@ func (a *actionWithProtocolVersion) IsLoggable() bool { return true } -func (a *actionWithProtocolVersion) Run(protocolVersion ProtocolVersion, subAction string) (valueType, error) { +func (a *actionWithProtocolVersion) Run(protocolVersion action.ProtocolVersion, subAction string) (valueType, error) { a.ProtocolVersion = protocolVersion a.SubAction = subAction @@ -282,7 +280,7 @@ func (a *actionWithProtocolVersion) Cancel() error { var _ = Describe("concreteRunner", func() { It("runner run parses the payload", func() { - runner := NewRunner() + runner := action.NewRunner() expectedValue := valueType{ID: 13, Success: true} expectedErr := errors.New("fake-run-error") @@ -312,7 +310,7 @@ var _ = Describe("concreteRunner", func() { }) It("runner run errs when actions not enough arguments", func() { - runner := NewRunner() + runner := action.NewRunner() expectedValue := valueType{ID: 13, Success: true} @@ -324,7 +322,7 @@ var _ = Describe("concreteRunner", func() { }) It("runner runs successfully when action is passed more arguments than required", func() { - runner := NewRunner() + runner := action.NewRunner() expectedValue := valueType{ID: 13, Success: true} @@ -336,7 +334,7 @@ var _ = Describe("concreteRunner", func() { }) It("runner run errs when action arguments types do not match", func() { - runner := NewRunner() + runner := action.NewRunner() expectedValue := valueType{ID: 13, Success: true} @@ -348,9 +346,9 @@ var _ = Describe("concreteRunner", func() { }) It("extracts argument types correctly", func() { - runner := NewRunner() + runner := action.NewRunner() - action := &actionWithTypes{} + actionWithTypes := &actionWithTypes{} payload := `{ "arguments":[{ @@ -364,72 +362,73 @@ var _ = Describe("concreteRunner", func() { "bool_type":false }] }` - _, err := runner.Run(action, []byte(payload), 0) + _, err := runner.Run(actionWithTypes, []byte(payload), 0) Expect(err).ToNot(HaveOccurred()) - Expect(action.Arg.IntType).To(Equal(int(-1024000))) - Expect(action.Arg.Int32Type).To(Equal(int32(-1024000))) - Expect(action.Arg.Int64Type).To(Equal(int64(-1024000))) - Expect(action.Arg.Float32Type).To(Equal(float32(100))) - Expect(action.Arg.Float64Type).To(Equal(float64(1.024e+06))) - Expect(action.Arg.UintType).To(Equal(uint(1024000))) - Expect(action.Arg.StringType).To(Equal("fake-string")) - Expect(action.Arg.BoolType).To(Equal(false)) + Expect(actionWithTypes.Arg.IntType).To(Equal(int(-1024000))) + Expect(actionWithTypes.Arg.Int32Type).To(Equal(int32(-1024000))) + Expect(actionWithTypes.Arg.Int64Type).To(Equal(int64(-1024000))) + Expect(actionWithTypes.Arg.Float32Type).To(Equal(float32(100))) + Expect(actionWithTypes.Arg.Float64Type).To(Equal(float64(1.024e+06))) + Expect(actionWithTypes.Arg.UintType).To(Equal(uint(1024000))) + Expect(actionWithTypes.Arg.StringType).To(Equal("fake-string")) + Expect(actionWithTypes.Arg.BoolType).To(Equal(false)) }) It("runner handles optional arguments being passed in", func() { - runner := NewRunner() + runner := action.NewRunner() expectedValue := valueType{ID: 13, Success: true} expectedErr := errors.New("fake-run-error") - action := &actionWithOptionalRunArgument{Value: expectedValue, Err: expectedErr} + actionWithOptionalRunArgument := &actionWithOptionalRunArgument{Value: expectedValue, Err: expectedErr} payload := `{"arguments":["setup", {"user":"rob","pwd":"rob123","id":12}, {"user":"bob","pwd":"bob123","id":13}]}` - value, err := runner.Run(action, []byte(payload), 0) + value, err := runner.Run(actionWithOptionalRunArgument, []byte(payload), 0) Expect(value).To(Equal(expectedValue)) Expect(err).To(Equal(expectedErr)) - Expect(action.SubAction).To(Equal("setup")) - assert.Equal(GinkgoT(), action.OptionalArgs, []argsType{ + Expect(actionWithOptionalRunArgument.SubAction).To(Equal("setup")) + assert.Equal(GinkgoT(), actionWithOptionalRunArgument.OptionalArgs, []argsType{ {User: "rob", Password: "rob123", ID: 12}, {User: "bob", Password: "bob123", ID: 13}, }) }) It("runner handles optional arguments when not passed in", func() { - runner := NewRunner() - action := &actionWithOptionalRunArgument{} + runner := action.NewRunner() + actionWithOptionalRunArgument := &actionWithOptionalRunArgument{} payload := `{"arguments":["setup"]}` - runner.Run(action, []byte(payload), 0) + _, err := runner.Run(actionWithOptionalRunArgument, []byte(payload), 0) + Expect(err).NotTo(HaveOccurred()) - Expect(action.SubAction).To(Equal("setup")) - Expect(action.OptionalArgs).To(Equal([]argsType{})) + Expect(actionWithOptionalRunArgument.SubAction).To(Equal("setup")) + Expect(actionWithOptionalRunArgument.OptionalArgs).To(Equal([]argsType{})) }) It("runner run errs when action does not implement run", func() { - runner := NewRunner() + runner := action.NewRunner() _, err := runner.Run(&actionWithoutRunMethod{}, []byte(`{"arguments":[]}`), 0) Expect(err).To(HaveOccurred()) }) It("runner run errs when actions run does not return two values", func() { - runner := NewRunner() + runner := action.NewRunner() _, err := runner.Run(&actionWithOneRunReturnValue{}, []byte(`{"arguments":[]}`), 0) Expect(err).To(HaveOccurred()) }) It("runner run errs when actions run second return type is not error", func() { - runner := NewRunner() + runner := action.NewRunner() _, err := runner.Run(&actionWithSecondReturnValueNotError{}, []byte(`{"arguments":[]}`), 0) Expect(err).To(HaveOccurred()) }) Describe("Resume", func() { It("calls Resume() on action", func() { - runner := NewRunner() + runner := action.NewRunner() testAction := &fakeaction.TestAction{ ResumeErr: errors.New("fake-action-error"), ResumeValue: "fake-action-resume-value", @@ -444,28 +443,28 @@ var _ = Describe("concreteRunner", func() { }) It("passes protocol version to run method", func() { - runner := NewRunner() + runner := action.NewRunner() - action := &actionWithProtocolVersion{} + actionWithProtocolVersion := &actionWithProtocolVersion{} payload := `{"arguments":["setup"]}` - _, err := runner.Run(action, []byte(payload), 1) + _, err := runner.Run(actionWithProtocolVersion, []byte(payload), 1) Expect(err).ToNot(HaveOccurred()) - Expect(action.ProtocolVersion).To(Equal(ProtocolVersion(1))) - Expect(action.SubAction).To(Equal("setup")) + Expect(actionWithProtocolVersion.ProtocolVersion).To(Equal(action.ProtocolVersion(1))) + Expect(actionWithProtocolVersion.SubAction).To(Equal("setup")) }) It("passes protocol version to run method from request ProtocolVersion not the payload", func() { - runner := NewRunner() + runner := action.NewRunner() - action := &actionWithProtocolVersion{} + actionWithProtocolVersion := &actionWithProtocolVersion{} payload := `{"protocol":98,"arguments":["setup"]}` - _, err := runner.Run(action, []byte(payload), 1) + _, err := runner.Run(actionWithProtocolVersion, []byte(payload), 1) Expect(err).ToNot(HaveOccurred()) - Expect(action.ProtocolVersion).To(Equal(ProtocolVersion(1))) - Expect(action.SubAction).To(Equal("setup")) + Expect(actionWithProtocolVersion.ProtocolVersion).To(Equal(action.ProtocolVersion(1))) + Expect(actionWithProtocolVersion.SubAction).To(Equal("setup")) }) }) diff --git a/agent/action/shared_test.go b/agent/action/shared_test.go index e70949dbf..ff4767e65 100644 --- a/agent/action/shared_test.go +++ b/agent/action/shared_test.go @@ -1,78 +1,79 @@ package action_test import ( - . "github.com/cloudfoundry/bosh-agent/agent/action" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + + "github.com/cloudfoundry/bosh-agent/agent/action" ) -func AssertActionIsSynchronousForVersion(action Action, version ProtocolVersion) { +func AssertActionIsSynchronousForVersion(a action.Action, version action.ProtocolVersion) { It("is synchronous for version", func() { - Expect(action.IsAsynchronous(version)).To(BeFalse()) + Expect(a.IsAsynchronous(version)).To(BeFalse()) }) } -func AssertActionIsAsynchronousForVersion(action Action, version ProtocolVersion) { +func AssertActionIsAsynchronousForVersion(a action.Action, version action.ProtocolVersion) { It("is synchronous for version", func() { - Expect(action.IsAsynchronous(version)).To(BeTrue()) + Expect(a.IsAsynchronous(version)).To(BeTrue()) }) } -func AssertActionIsAsynchronous(action Action) { +func AssertActionIsAsynchronous(a action.Action) { It("is asynchronous", func() { - Expect(action.IsAsynchronous(ProtocolVersion(1))).To(BeTrue()) + Expect(a.IsAsynchronous(action.ProtocolVersion(1))).To(BeTrue()) }) } -func AssertActionIsNotAsynchronous(action Action) { +func AssertActionIsNotAsynchronous(a action.Action) { It("is not asynchronous", func() { - Expect(action.IsAsynchronous(ProtocolVersion(1))).To(BeFalse()) + Expect(a.IsAsynchronous(action.ProtocolVersion(1))).To(BeFalse()) }) } -func AssertActionIsPersistent(action Action) { +func AssertActionIsPersistent(a action.Action) { It("is persistent", func() { - Expect(action.IsPersistent()).To(BeTrue()) + Expect(a.IsPersistent()).To(BeTrue()) }) } -func AssertActionIsNotPersistent(action Action) { +func AssertActionIsNotPersistent(a action.Action) { It("is not persistent", func() { - Expect(action.IsPersistent()).To(BeFalse()) + Expect(a.IsPersistent()).To(BeFalse()) }) } -func AssertActionIsLoggable(action Action) { +func AssertActionIsLoggable(a action.Action) { It("is loggable", func() { - Expect(action.IsLoggable()).To(BeTrue()) + Expect(a.IsLoggable()).To(BeTrue()) }) } -func AssertActionIsNotLoggable(action Action) { +func AssertActionIsNotLoggable(a action.Action) { It("is not loggable", func() { - Expect(action.IsLoggable()).To(BeFalse()) + Expect(a.IsLoggable()).To(BeFalse()) }) } -func AssertActionIsNotCancelable(action Action) { +func AssertActionIsNotCancelable(a action.Action) { It("cannot be cancelled", func() { - err := action.Cancel() + err := a.Cancel() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(Equal("not supported")) }) } -func AssertActionIsResumable(action Action) { +func AssertActionIsResumable(a action.Action) { It("can be resumed", func() { - value, err := action.Resume() + value, err := a.Resume() Expect(value).To(Equal("ok")) Expect(err).ToNot(HaveOccurred()) }) } -func AssertActionIsNotResumable(action Action) { +func AssertActionIsNotResumable(a action.Action) { It("cannot be resumed", func() { - _, err := action.Resume() + _, err := a.Resume() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(Equal("not supported")) }) diff --git a/agent/action/shutdown_test.go b/agent/action/shutdown_test.go index 2a989e55d..7467013e1 100644 --- a/agent/action/shutdown_test.go +++ b/agent/action/shutdown_test.go @@ -1,39 +1,39 @@ package action_test import ( - . "github.com/cloudfoundry/bosh-agent/agent/action" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "github.com/cloudfoundry/bosh-agent/agent/action" "github.com/cloudfoundry/bosh-agent/platform/platformfakes" ) var _ = Describe("Shutdown", func() { var ( - platform *platformfakes.FakePlatform - action ShutdownAction + platform *platformfakes.FakePlatform + shutdownAction action.ShutdownAction ) BeforeEach(func() { platform = &platformfakes.FakePlatform{} - action = NewShutdown(platform) + shutdownAction = action.NewShutdown(platform) }) - AssertActionIsNotAsynchronous(action) - AssertActionIsNotPersistent(action) - AssertActionIsLoggable(action) + AssertActionIsNotAsynchronous(shutdownAction) + AssertActionIsNotPersistent(shutdownAction) + AssertActionIsLoggable(shutdownAction) - AssertActionIsNotCancelable(action) - AssertActionIsNotResumable(action) + AssertActionIsNotCancelable(shutdownAction) + AssertActionIsNotResumable(shutdownAction) It("shuts the VM down", func() { - _, err := action.Run() + _, err := shutdownAction.Run() Expect(err).ToNot(HaveOccurred()) Expect(platform.ShutdownCallCount()).To(Equal(1)) }) It("returns an empty string", func() { - response, err := action.Run() + response, err := shutdownAction.Run() Expect(err).ToNot(HaveOccurred()) Expect(response).To(Equal("")) }) diff --git a/agent/action/ssh_test.go b/agent/action/ssh_test.go index 20cdaec93..e46a5c877 100644 --- a/agent/action/ssh_test.go +++ b/agent/action/ssh_test.go @@ -3,16 +3,14 @@ package action_test import ( "errors" - . "github.com/cloudfoundry/bosh-agent/agent/action" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "github.com/cloudfoundry/bosh-agent/agent/action" "github.com/cloudfoundry/bosh-agent/platform/platformfakes" - - fakesettings "github.com/cloudfoundry/bosh-agent/settings/fakes" - boshsettings "github.com/cloudfoundry/bosh-agent/settings" boshdirs "github.com/cloudfoundry/bosh-agent/settings/directories" + fakesettings "github.com/cloudfoundry/bosh-agent/settings/fakes" boshassert "github.com/cloudfoundry/bosh-utils/assert" boshlog "github.com/cloudfoundry/bosh-utils/logger" ) @@ -21,7 +19,7 @@ var _ = Describe("SSHAction", func() { var ( platform *platformfakes.FakePlatform settingsService boshsettings.Service - action SSHAction + sshAction action.SSHAction ) BeforeEach(func() { @@ -30,21 +28,21 @@ var _ = Describe("SSHAction", func() { platform = &platformfakes.FakePlatform{} dirProvider := boshdirs.NewProvider("/foo") logger := boshlog.NewLogger(boshlog.LevelNone) - action = NewSSH(settingsService, platform, dirProvider, logger) + sshAction = action.NewSSH(settingsService, platform, dirProvider, logger) }) - AssertActionIsNotAsynchronous(action) - AssertActionIsNotPersistent(action) - AssertActionIsLoggable(action) + AssertActionIsNotAsynchronous(sshAction) + AssertActionIsNotPersistent(sshAction) + AssertActionIsLoggable(sshAction) - AssertActionIsNotResumable(action) - AssertActionIsNotCancelable(action) + AssertActionIsNotResumable(sshAction) + AssertActionIsNotCancelable(sshAction) Describe("Run", func() { Context("setupSSH", func() { var ( - response SSHResult - params SSHParams + response action.SSHResult + params action.SSHParams err error defaultIP string @@ -68,15 +66,15 @@ var _ = Describe("SSHAction", func() { platform.GetHostPublicKeyReturns(platformPublicKeyValue, platformPublicKeyErr) - params = SSHParams{ + params = action.SSHParams{ User: "fake-user", PublicKey: "fake-public-key", } dirProvider := boshdirs.NewProvider("/foo") logger := boshlog.NewLogger(boshlog.LevelNone) - action = NewSSH(settingsService, platform, dirProvider, logger) - response, err = action.Run("setup", params) + sshAction = action.NewSSH(settingsService, platform, dirProvider, logger) + response, err = sshAction.Run("setup", params) }) Context("without default ip", func() { @@ -116,7 +114,7 @@ var _ = Describe("SSHAction", func() { Context("with a host public key available", func() { It("should return SSH Result with HostPublicKey", func() { hostPublicKey, _ := platform.GetHostPublicKey() - Expect(response).To(Equal(SSHResult{ + Expect(response).To(Equal(action.SSHResult{ Command: "setup", Status: "success", IP: defaultIP, @@ -132,7 +130,7 @@ var _ = Describe("SSHAction", func() { }) It("should return an error", func() { - Expect(response).To(Equal(SSHResult{})) + Expect(response).To(Equal(action.SSHResult{})) Expect(err).ToNot(BeNil()) }) }) @@ -140,7 +138,7 @@ var _ = Describe("SSHAction", func() { Context("cleanupSSH", func() { It("should delete ephemeral user", func() { - response, err := action.Run("cleanup", SSHParams{UserRegex: "^foobar.*"}) + response, err := sshAction.Run("cleanup", action.SSHParams{UserRegex: "^foobar.*"}) Expect(err).ToNot(HaveOccurred()) Expect(platform.DeleteEphemeralUsersMatchingCallCount()).To(Equal(1)) diff --git a/agent/action/start_test.go b/agent/action/start_test.go index d6807a0da..f85078885 100644 --- a/agent/action/start_test.go +++ b/agent/action/start_test.go @@ -1,12 +1,12 @@ package action_test import ( + "errors" + . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "errors" - - . "github.com/cloudfoundry/bosh-agent/agent/action" + "github.com/cloudfoundry/bosh-agent/agent/action" fakeas "github.com/cloudfoundry/bosh-agent/agent/applier/applyspec/fakes" fakeappl "github.com/cloudfoundry/bosh-agent/agent/applier/fakes" fakejobsuper "github.com/cloudfoundry/bosh-agent/jobsupervisor/fakes" @@ -17,44 +17,44 @@ var _ = Describe("Start", func() { jobSupervisor *fakejobsuper.FakeJobSupervisor applier *fakeappl.FakeApplier specService *fakeas.FakeV1Service - action StartAction + startAction action.StartAction ) BeforeEach(func() { jobSupervisor = fakejobsuper.NewFakeJobSupervisor() applier = fakeappl.NewFakeApplier() specService = fakeas.NewFakeV1Service() - action = NewStart(jobSupervisor, applier, specService) + startAction = action.NewStart(jobSupervisor, applier, specService) }) - AssertActionIsNotAsynchronous(action) - AssertActionIsNotPersistent(action) - AssertActionIsLoggable(action) + AssertActionIsNotAsynchronous(startAction) + AssertActionIsNotPersistent(startAction) + AssertActionIsLoggable(startAction) - AssertActionIsNotResumable(action) - AssertActionIsNotCancelable(action) + AssertActionIsNotResumable(startAction) + AssertActionIsNotCancelable(startAction) It("returns started", func() { - started, err := action.Run() + started, err := startAction.Run() Expect(err).ToNot(HaveOccurred()) Expect(started).To(Equal("started")) }) It("starts monitor services", func() { - _, err := action.Run() + _, err := startAction.Run() Expect(err).ToNot(HaveOccurred()) Expect(jobSupervisor.Started).To(BeTrue()) }) It("configures jobs", func() { - _, err := action.Run() + _, err := startAction.Run() Expect(err).ToNot(HaveOccurred()) Expect(applier.Configured).To(BeTrue()) }) It("apply errs if a job fails configuring", func() { applier.ConfiguredError = errors.New("fake error") - _, err := action.Run() + _, err := startAction.Run() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("Configuring jobs")) diff --git a/agent/action/state/sync_dns_state_test.go b/agent/action/state/sync_dns_state_test.go index f15d3762e..e66756fc4 100644 --- a/agent/action/state/sync_dns_state_test.go +++ b/agent/action/state/sync_dns_state_test.go @@ -3,12 +3,11 @@ package state_test import ( "errors" - . "github.com/cloudfoundry/bosh-agent/agent/action/state" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "github.com/cloudfoundry/bosh-agent/agent/action/state" "github.com/cloudfoundry/bosh-agent/platform/platformfakes" - fakesys "github.com/cloudfoundry/bosh-utils/system/fakes" fakeuuidgen "github.com/cloudfoundry/bosh-utils/uuid/fakes" ) @@ -16,7 +15,7 @@ import ( var _ = Describe("SyncDNSState", func() { var ( localDNSState []byte - syncDNSState SyncDNSState + syncDNSState state.SyncDNSState fakeFileSystem *fakesys.FakeFileSystem fakeUUIDGenerator *fakeuuidgen.FakeGenerator fakePlatform *platformfakes.FakePlatform @@ -32,7 +31,7 @@ var _ = Describe("SyncDNSState", func() { fakeUUIDGenerator = fakeuuidgen.NewFakeGenerator() path = "/blobstore-dns-records.json" - syncDNSState = NewSyncDNSState(fakePlatform, path, fakeUUIDGenerator) + syncDNSState = state.NewSyncDNSState(fakePlatform, path, fakeUUIDGenerator) err = nil localDNSState = []byte(`{ "version": 1234, @@ -61,7 +60,8 @@ var _ = Describe("SyncDNSState", func() { Context("when writing to a temp file fails", func() { It("does not override the existing records.json", func() { - fakeFileSystem.WriteFile(path, []byte("{}")) + err := fakeFileSystem.WriteFile(path, []byte("{}")) + Expect(err).ToNot(HaveOccurred()) fakeUUIDGenerator.GeneratedUUID = "fake-generated-uuid" fakeFileSystem.WriteFileErrors[path+"fake-generated-uuid"] = errors.New("failed to write tmp file") @@ -151,7 +151,8 @@ var _ = Describe("SyncDNSState", func() { Context("when state file exists", func() { BeforeEach(func() { - fakeFileSystem.WriteFile(path, []byte(`{"version":1}`)) + err := fakeFileSystem.WriteFile(path, []byte(`{"version":1}`)) + Expect(err).ToNot(HaveOccurred()) }) It("returns true when the state file version is less than the supplied version", func() { @@ -173,7 +174,8 @@ var _ = Describe("SyncDNSState", func() { }) It("returns true when unmarshalling the version fails", func() { - fakeFileSystem.WriteFile(path, []byte(`garbage`)) + err := fakeFileSystem.WriteFile(path, []byte(`garbage`)) + Expect(err).ToNot(HaveOccurred()) Expect(syncDNSState.NeedsUpdate(2)).To(BeTrue()) }) diff --git a/agent/action/stop_test.go b/agent/action/stop_test.go index 1367eccc1..6444f2e8c 100644 --- a/agent/action/stop_test.go +++ b/agent/action/stop_test.go @@ -4,48 +4,48 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - . "github.com/cloudfoundry/bosh-agent/agent/action" + "github.com/cloudfoundry/bosh-agent/agent/action" fakejobsuper "github.com/cloudfoundry/bosh-agent/jobsupervisor/fakes" ) var _ = Describe("Stop", func() { var ( jobSupervisor *fakejobsuper.FakeJobSupervisor - action StopAction + stopAction action.StopAction ) BeforeEach(func() { jobSupervisor = fakejobsuper.NewFakeJobSupervisor() - action = NewStop(jobSupervisor) + stopAction = action.NewStop(jobSupervisor) }) - AssertActionIsAsynchronous(action) - AssertActionIsNotPersistent(action) - AssertActionIsLoggable(action) + AssertActionIsAsynchronous(stopAction) + AssertActionIsNotPersistent(stopAction) + AssertActionIsLoggable(stopAction) - AssertActionIsNotResumable(action) - AssertActionIsNotCancelable(action) + AssertActionIsNotResumable(stopAction) + AssertActionIsNotCancelable(stopAction) It("returns stopped", func() { - stopped, err := action.Run(ProtocolVersion(2)) + stopped, err := stopAction.Run(action.ProtocolVersion(2)) Expect(err).ToNot(HaveOccurred()) Expect(stopped).To(Equal("stopped")) }) It("stops job supervisor services", func() { - _, err := action.Run(ProtocolVersion(2)) + _, err := stopAction.Run(action.ProtocolVersion(2)) Expect(err).ToNot(HaveOccurred()) Expect(jobSupervisor.Stopped).To(BeTrue()) }) It("stops when protocol version is 2", func() { - _, err := action.Run(ProtocolVersion(2)) + _, err := stopAction.Run(action.ProtocolVersion(2)) Expect(err).ToNot(HaveOccurred()) Expect(jobSupervisor.StoppedAndWaited).ToNot(BeTrue()) }) It("stops and waits when protocol version is greater than 2", func() { - _, err := action.Run(ProtocolVersion(3)) + _, err := stopAction.Run(action.ProtocolVersion(3)) Expect(err).ToNot(HaveOccurred()) Expect(jobSupervisor.StoppedAndWaited).To(BeTrue()) }) diff --git a/agent/action/sync_dns_test.go b/agent/action/sync_dns_test.go index 3ba3021e6..18e0a92fd 100644 --- a/agent/action/sync_dns_test.go +++ b/agent/action/sync_dns_test.go @@ -4,25 +4,22 @@ import ( "errors" "path/filepath" - . "github.com/cloudfoundry/bosh-agent/agent/action" - fakeblobdelegator "github.com/cloudfoundry/bosh-agent/agent/httpblobprovider/blobstore_delegator/blobstore_delegatorfakes" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "github.com/cloudfoundry/bosh-agent/agent/action" + fakeblobdelegator "github.com/cloudfoundry/bosh-agent/agent/httpblobprovider/blobstore_delegator/blobstore_delegatorfakes" "github.com/cloudfoundry/bosh-agent/platform/platformfakes" - - fakelogger "github.com/cloudfoundry/bosh-utils/logger/loggerfakes" - - fakesettings "github.com/cloudfoundry/bosh-agent/settings/fakes" - fakesys "github.com/cloudfoundry/bosh-utils/system/fakes" - boshsettings "github.com/cloudfoundry/bosh-agent/settings" + fakesettings "github.com/cloudfoundry/bosh-agent/settings/fakes" boshcrypto "github.com/cloudfoundry/bosh-utils/crypto" + fakelogger "github.com/cloudfoundry/bosh-utils/logger/loggerfakes" + fakesys "github.com/cloudfoundry/bosh-utils/system/fakes" ) var _ = Describe("SyncDNS", func() { var ( - action SyncDNS + syncDNSAction action.SyncDNS fakeBlobstore *fakeblobdelegator.FakeBlobstoreDelegator fakeSettingsService *fakesettings.FakeSettingsService fakePlatform *platformfakes.FakePlatform @@ -39,15 +36,15 @@ var _ = Describe("SyncDNS", func() { fakeFileSystem = fakesys.NewFakeFileSystem() fakePlatform.GetFsReturns(fakeFileSystem) - action = NewSyncDNS(fakeBlobstore, fakeSettingsService, fakePlatform, logger) + syncDNSAction = action.NewSyncDNS(fakeBlobstore, fakeSettingsService, fakePlatform, logger) }) - AssertActionIsNotAsynchronous(action) - AssertActionIsNotPersistent(action) - AssertActionIsLoggable(action) + AssertActionIsNotAsynchronous(syncDNSAction) + AssertActionIsNotPersistent(syncDNSAction) + AssertActionIsLoggable(syncDNSAction) - AssertActionIsNotResumable(action) - AssertActionIsNotCancelable(action) + AssertActionIsNotResumable(syncDNSAction) + AssertActionIsNotCancelable(syncDNSAction) Context("#Run", func() { var ( @@ -90,7 +87,7 @@ var _ = Describe("SyncDNS", func() { }) It("returns with no error and does no writes and no gets to blobstore", func() { - _, err := action.Run("fake-blobstore-id", multiDigest, 2) + _, err := syncDNSAction.Run("fake-blobstore-id", multiDigest, 2) Expect(err).ToNot(HaveOccurred()) }) }) @@ -104,7 +101,7 @@ var _ = Describe("SyncDNS", func() { }) It("returns error", func() { - _, err := action.Run("fake-blobstore-id", multiDigest, 2) + _, err := syncDNSAction.Run("fake-blobstore-id", multiDigest, 2) Expect(err).ToNot(HaveOccurred()) }) }) @@ -112,7 +109,7 @@ var _ = Describe("SyncDNS", func() { Context("when the version in the blob does not match the version director supplied", func() { It("returns an error", func() { - _, err := action.Run("fake-blobstore-id", multiDigest, 3) + _, err := syncDNSAction.Run("fake-blobstore-id", multiDigest, 3) Expect(err).To(MatchError("version from unpacked dns blob does not match version supplied by director")) }) }) @@ -125,7 +122,7 @@ var _ = Describe("SyncDNS", func() { Context("when blobstore contains DNS records", func() { It("accesses the blobstore and fetches DNS records", func() { - response, err := action.Run("fake-blobstore-id", multiDigest, 2) + response, err := syncDNSAction.Run("fake-blobstore-id", multiDigest, 2) Expect(err).ToNot(HaveOccurred()) Expect(response).To(Equal("synced")) @@ -136,7 +133,7 @@ var _ = Describe("SyncDNS", func() { }) It("reads the DNS records from the blobstore file", func() { - response, err := action.Run("fake-blobstore-id", multiDigest, 2) + response, err := syncDNSAction.Run("fake-blobstore-id", multiDigest, 2) Expect(err).ToNot(HaveOccurred()) Expect(response).To(Equal("synced")) @@ -146,7 +143,7 @@ var _ = Describe("SyncDNS", func() { It("fails reading the DNS records from the blobstore file", func() { fakeFileSystem.RegisterReadFileError("fake-blobstore-file-path", errors.New("fake-error")) - response, err := action.Run("fake-blobstore-id", multiDigest, 2) + response, err := syncDNSAction.Run("fake-blobstore-id", multiDigest, 2) Expect(err).To(HaveOccurred()) Expect(response).To(Equal("")) Expect(err.Error()).To(ContainSubstring("reading fake-blobstore-file-path from blobstore")) @@ -154,7 +151,7 @@ var _ = Describe("SyncDNS", func() { }) It("deletes the file once read", func() { - _, err := action.Run("fake-blobstore-id", multiDigest, 2) + _, err := syncDNSAction.Run("fake-blobstore-id", multiDigest, 2) Expect(err).ToNot(HaveOccurred()) Expect(fakeFileSystem.FileExists("fake-blobstore-file-path")).To(BeFalse()) @@ -167,7 +164,7 @@ var _ = Describe("SyncDNS", func() { } return nil } - _, err := action.Run("fake-blobstore-id", multiDigest, 2) + _, err := syncDNSAction.Run("fake-blobstore-id", multiDigest, 2) Expect(err).ToNot(HaveOccurred()) tag, message, _ := logger.ErrorArgsForCall(0) @@ -176,7 +173,7 @@ var _ = Describe("SyncDNS", func() { }) It("saves DNS records to the platform", func() { - response, err := action.Run("fake-blobstore-id", multiDigest, 2) + response, err := syncDNSAction.Run("fake-blobstore-id", multiDigest, 2) Expect(err).ToNot(HaveOccurred()) Expect(response).To(Equal("synced")) @@ -201,7 +198,7 @@ var _ = Describe("SyncDNS", func() { It("saves DNS records to the platform", func() { Expect(fakeFileSystem.FileExists(stateFilePath)).To(BeFalse()) - response, err := action.Run("fake-blobstore-id", multiDigest, 2) + response, err := syncDNSAction.Run("fake-blobstore-id", multiDigest, 2) Expect(err).ToNot(HaveOccurred()) Expect(response).To(Equal("synced")) @@ -227,7 +224,7 @@ var _ = Describe("SyncDNS", func() { }) It("saves DNS records to the platform", func() { - response, err := action.Run("fake-blobstore-id", multiDigest, 2) + response, err := syncDNSAction.Run("fake-blobstore-id", multiDigest, 2) Expect(err).ToNot(HaveOccurred()) Expect(response).To(Equal("synced")) @@ -251,7 +248,7 @@ var _ = Describe("SyncDNS", func() { }) It("saves DNS records to the platform", func() { - response, err := action.Run("fake-blobstore-id", multiDigest, 2) + response, err := syncDNSAction.Run("fake-blobstore-id", multiDigest, 2) Expect(err).ToNot(HaveOccurred()) Expect(response).To(Equal("synced")) @@ -278,7 +275,7 @@ var _ = Describe("SyncDNS", func() { It("runs successfully and creates a new state file", func() { Expect(fakeFileSystem.FileExists(stateFilePath)).To(BeFalse()) - response, err := action.Run("fake-blobstore-id", multiDigest, 2) + response, err := syncDNSAction.Run("fake-blobstore-id", multiDigest, 2) Expect(err).ToNot(HaveOccurred()) Expect(response).To(Equal("synced")) @@ -305,7 +302,7 @@ var _ = Describe("SyncDNS", func() { }) It("returns an error", func() { - _, err := action.Run("fake-blobstore-id", multiDigest, 2) + _, err := syncDNSAction.Run("fake-blobstore-id", multiDigest, 2) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("saving local DNS state")) }) @@ -319,7 +316,7 @@ var _ = Describe("SyncDNS", func() { }) It("fails unmarshalling the DNS records from the file", func() { - _, err := action.Run("fake-blobstore-id", multiDigest, 2) + _, err := syncDNSAction.Run("fake-blobstore-id", multiDigest, 2) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("unmarshalling DNS records")) }) @@ -333,13 +330,13 @@ var _ = Describe("SyncDNS", func() { }) It("fails to save DNS records on the platform", func() { - _, err := action.Run("fake-blobstore-id", multiDigest, 2) + _, err := syncDNSAction.Run("fake-blobstore-id", multiDigest, 2) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("saving DNS records")) }) It("should not update the records.json", func() { - _, err := action.Run("fake-blobstore-id", multiDigest, 2) + _, err := syncDNSAction.Run("fake-blobstore-id", multiDigest, 2) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("saving DNS records")) @@ -357,7 +354,7 @@ var _ = Describe("SyncDNS", func() { Context("when blobstore returns an error", func() { It("fails with an wrapped error", func() { - _, err := action.Run("fake-blobstore-id", multiDigest, 2) + _, err := syncDNSAction.Run("fake-blobstore-id", multiDigest, 2) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("reading fake-blobstore-file-path-does-not-exist from blobstore")) }) @@ -377,7 +374,7 @@ var _ = Describe("SyncDNS", func() { Context("when file removal failed", func() { It("logs error", func() { - _, _ = action.Run("fake-blobstore-id", multiDigest, 2) + _, _ = syncDNSAction.Run("fake-blobstore-id", multiDigest, 2) tag, message, _ := logger.ErrorArgsForCall(0) Expect(tag).To(Equal("Sync DNS action")) Expect(message).To(Equal("Failed to remove dns blob file at path 'fake-blobstore-file-path'")) diff --git a/agent/action/sync_dns_with_signed_url_test.go b/agent/action/sync_dns_with_signed_url_test.go index da32050ba..af1a7d56e 100644 --- a/agent/action/sync_dns_with_signed_url_test.go +++ b/agent/action/sync_dns_with_signed_url_test.go @@ -4,13 +4,12 @@ import ( "errors" "path/filepath" - . "github.com/cloudfoundry/bosh-agent/agent/action" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "github.com/cloudfoundry/bosh-agent/platform/platformfakes" - + "github.com/cloudfoundry/bosh-agent/agent/action" fakeblobdelegator "github.com/cloudfoundry/bosh-agent/agent/httpblobprovider/blobstore_delegator/blobstore_delegatorfakes" + "github.com/cloudfoundry/bosh-agent/platform/platformfakes" fakesettings "github.com/cloudfoundry/bosh-agent/settings/fakes" fakelogger "github.com/cloudfoundry/bosh-utils/logger/loggerfakes" fakesys "github.com/cloudfoundry/bosh-utils/system/fakes" @@ -19,15 +18,15 @@ import ( boshcrypto "github.com/cloudfoundry/bosh-utils/crypto" ) -var _ = Describe("SyncDNSWithSignedURL", func() { +var _ = Describe("action.SyncDNSWithSignedURL", func() { var ( - action SyncDNSWithSignedURL - fakeSettingsService *fakesettings.FakeSettingsService - fakePlatform *platformfakes.FakePlatform - fakeFileSystem *fakesys.FakeFileSystem - logger *fakelogger.FakeLogger - fakeDNSRecordsString string - blobDelegator *fakeblobdelegator.FakeBlobstoreDelegator + syncDNSWithSignedURLAction action.SyncDNSWithSignedURL + fakeSettingsService *fakesettings.FakeSettingsService + fakePlatform *platformfakes.FakePlatform + fakeFileSystem *fakesys.FakeFileSystem + logger *fakelogger.FakeLogger + fakeDNSRecordsString string + blobDelegator *fakeblobdelegator.FakeBlobstoreDelegator ) BeforeEach(func() { @@ -38,15 +37,15 @@ var _ = Describe("SyncDNSWithSignedURL", func() { fakeFileSystem = fakesys.NewFakeFileSystem() fakePlatform.GetFsReturns(fakeFileSystem) - action = NewSyncDNSWithSignedURL(fakeSettingsService, fakePlatform, logger, blobDelegator) + syncDNSWithSignedURLAction = action.NewSyncDNSWithSignedURL(fakeSettingsService, fakePlatform, logger, blobDelegator) }) - AssertActionIsNotAsynchronous(action) - AssertActionIsNotPersistent(action) - AssertActionIsLoggable(action) + AssertActionIsNotAsynchronous(syncDNSWithSignedURLAction) + AssertActionIsNotPersistent(syncDNSWithSignedURLAction) + AssertActionIsLoggable(syncDNSWithSignedURLAction) - AssertActionIsNotResumable(action) - AssertActionIsNotCancelable(action) + AssertActionIsNotResumable(syncDNSWithSignedURLAction) + AssertActionIsNotCancelable(syncDNSWithSignedURLAction) Context("#Run", func() { var ( @@ -89,7 +88,7 @@ var _ = Describe("SyncDNSWithSignedURL", func() { }) It("returns with no error and does no writes and no gets to blobstore", func() { - _, err := action.Run(SyncDNSWithSignedURLRequest{ + _, err := syncDNSWithSignedURLAction.Run(action.SyncDNSWithSignedURLRequest{ SignedURL: "fake-signed-url", MultiDigest: multiDigest, Version: 2, @@ -107,7 +106,7 @@ var _ = Describe("SyncDNSWithSignedURL", func() { }) It("returns error", func() { - _, err := action.Run(SyncDNSWithSignedURLRequest{ + _, err := syncDNSWithSignedURLAction.Run(action.SyncDNSWithSignedURLRequest{ SignedURL: "fake-signed-url", MultiDigest: multiDigest, Version: 2, @@ -119,7 +118,7 @@ var _ = Describe("SyncDNSWithSignedURL", func() { Context("when the version in the blob does not match the version director supplied", func() { It("returns an error", func() { - _, err := action.Run(SyncDNSWithSignedURLRequest{ + _, err := syncDNSWithSignedURLAction.Run(action.SyncDNSWithSignedURLRequest{ SignedURL: "fake-signed-url", MultiDigest: multiDigest, Version: 3, @@ -139,7 +138,7 @@ var _ = Describe("SyncDNSWithSignedURL", func() { headers := map[string]string{ "key": "value", } - response, err := action.Run(SyncDNSWithSignedURLRequest{ + response, err := syncDNSWithSignedURLAction.Run(action.SyncDNSWithSignedURLRequest{ SignedURL: "fake-signed-url", MultiDigest: multiDigest, Version: 2, @@ -156,7 +155,7 @@ var _ = Describe("SyncDNSWithSignedURL", func() { }) It("reads the DNS records from the blobstore file", func() { - response, err := action.Run(SyncDNSWithSignedURLRequest{ + response, err := syncDNSWithSignedURLAction.Run(action.SyncDNSWithSignedURLRequest{ SignedURL: "fake-signed-url", MultiDigest: multiDigest, Version: 2, @@ -168,7 +167,7 @@ var _ = Describe("SyncDNSWithSignedURL", func() { }) It("saves DNS records to the platform", func() { - response, err := action.Run(SyncDNSWithSignedURLRequest{ + response, err := syncDNSWithSignedURLAction.Run(action.SyncDNSWithSignedURLRequest{ SignedURL: "fake-signed-url", MultiDigest: multiDigest, Version: 2, @@ -197,7 +196,7 @@ var _ = Describe("SyncDNSWithSignedURL", func() { It("saves DNS records to the platform", func() { Expect(fakeFileSystem.FileExists(stateFilePath)).To(BeFalse()) - response, err := action.Run(SyncDNSWithSignedURLRequest{ + response, err := syncDNSWithSignedURLAction.Run(action.SyncDNSWithSignedURLRequest{ SignedURL: "fake-signed-url", MultiDigest: multiDigest, Version: 2, @@ -227,7 +226,7 @@ var _ = Describe("SyncDNSWithSignedURL", func() { }) It("saves DNS records to the platform", func() { - response, err := action.Run(SyncDNSWithSignedURLRequest{ + response, err := syncDNSWithSignedURLAction.Run(action.SyncDNSWithSignedURLRequest{ SignedURL: "fake-signed-url", MultiDigest: multiDigest, Version: 2, @@ -255,7 +254,7 @@ var _ = Describe("SyncDNSWithSignedURL", func() { }) It("saves DNS records to the platform", func() { - response, err := action.Run(SyncDNSWithSignedURLRequest{ + response, err := syncDNSWithSignedURLAction.Run(action.SyncDNSWithSignedURLRequest{ SignedURL: "fake-signed-url", MultiDigest: multiDigest, Version: 2, @@ -286,7 +285,7 @@ var _ = Describe("SyncDNSWithSignedURL", func() { It("runs successfully and creates a new state file", func() { Expect(fakeFileSystem.FileExists(stateFilePath)).To(BeFalse()) - response, err := action.Run(SyncDNSWithSignedURLRequest{ + response, err := syncDNSWithSignedURLAction.Run(action.SyncDNSWithSignedURLRequest{ SignedURL: "fake-signed-url", MultiDigest: multiDigest, Version: 2, @@ -317,7 +316,7 @@ var _ = Describe("SyncDNSWithSignedURL", func() { }) It("returns an error", func() { - _, err := action.Run(SyncDNSWithSignedURLRequest{ + _, err := syncDNSWithSignedURLAction.Run(action.SyncDNSWithSignedURLRequest{ SignedURL: "fake-signed-url", MultiDigest: multiDigest, Version: 2, @@ -330,11 +329,12 @@ var _ = Describe("SyncDNSWithSignedURL", func() { Context("when DNS records is invalid", func() { BeforeEach(func() { - fakeFileSystem.WriteFileString("fake-blobstore-file-path", "") + err := fakeFileSystem.WriteFileString("fake-blobstore-file-path", "") + Expect(err).NotTo(HaveOccurred()) }) It("fails unmarshalling the DNS records from the file", func() { - _, err := action.Run(SyncDNSWithSignedURLRequest{ + _, err := syncDNSWithSignedURLAction.Run(action.SyncDNSWithSignedURLRequest{ SignedURL: "fake-signed-url", MultiDigest: multiDigest, Version: 2, @@ -352,7 +352,7 @@ var _ = Describe("SyncDNSWithSignedURL", func() { }) It("fails to save DNS records on the platform", func() { - _, err := action.Run(SyncDNSWithSignedURLRequest{ + _, err := syncDNSWithSignedURLAction.Run(action.SyncDNSWithSignedURLRequest{ SignedURL: "fake-signed-url", MultiDigest: multiDigest, Version: 2, @@ -362,7 +362,7 @@ var _ = Describe("SyncDNSWithSignedURL", func() { }) It("should not update the records.json", func() { - _, err := action.Run(SyncDNSWithSignedURLRequest{ + _, err := syncDNSWithSignedURLAction.Run(action.SyncDNSWithSignedURLRequest{ SignedURL: "fake-signed-url", MultiDigest: multiDigest, Version: 2, @@ -384,7 +384,7 @@ var _ = Describe("SyncDNSWithSignedURL", func() { Context("when blobstore returns an error", func() { It("fails with an wrapped error", func() { - _, err := action.Run(SyncDNSWithSignedURLRequest{ + _, err := syncDNSWithSignedURLAction.Run(action.SyncDNSWithSignedURLRequest{ SignedURL: "fake-signed-url", MultiDigest: multiDigest, Version: 2, diff --git a/agent/action/unmount_disk_test.go b/agent/action/unmount_disk_test.go index c7cfd1839..4660b0308 100644 --- a/agent/action/unmount_disk_test.go +++ b/agent/action/unmount_disk_test.go @@ -1,24 +1,23 @@ package action_test import ( - . "github.com/cloudfoundry/bosh-agent/agent/action" + "errors" + . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "github.com/cloudfoundry/bosh-agent/platform/platformfakes" - - fakesettings "github.com/cloudfoundry/bosh-agent/settings/fakes" - - "errors" + "github.com/cloudfoundry/bosh-agent/agent/action" "github.com/cloudfoundry/bosh-agent/platform/disk" + "github.com/cloudfoundry/bosh-agent/platform/platformfakes" boshsettings "github.com/cloudfoundry/bosh-agent/settings" + fakesettings "github.com/cloudfoundry/bosh-agent/settings/fakes" boshassert "github.com/cloudfoundry/bosh-utils/assert" ) var _ = Describe("UnmountDiskAction", func() { var ( - platform *platformfakes.FakePlatform - action UnmountDiskAction + platform *platformfakes.FakePlatform + unmountDiskAction action.UnmountDiskAction expectedDiskSettings boshsettings.DiskSettings settingsService *fakesettings.FakeSettingsService @@ -46,7 +45,7 @@ var _ = Describe("UnmountDiskAction", func() { }, } - action = NewUnmountDisk(settingsService, platform) + unmountDiskAction = action.NewUnmountDisk(settingsService, platform) expectedDiskSettings = boshsettings.DiskSettings{ ID: "vol-123", @@ -64,17 +63,17 @@ var _ = Describe("UnmountDiskAction", func() { } }) - AssertActionIsAsynchronous(action) - AssertActionIsNotPersistent(action) - AssertActionIsLoggable(action) + AssertActionIsAsynchronous(unmountDiskAction) + AssertActionIsNotPersistent(unmountDiskAction) + AssertActionIsLoggable(unmountDiskAction) - AssertActionIsNotResumable(action) - AssertActionIsNotCancelable(action) + AssertActionIsNotResumable(unmountDiskAction) + AssertActionIsNotCancelable(unmountDiskAction) It("unmount disk when the disk is mounted", func() { platform.UnmountPersistentDiskReturns(true, nil) - result, err := action.Run("vol-123") + result, err := unmountDiskAction.Run("vol-123") Expect(err).ToNot(HaveOccurred()) boshassert.MatchesJSONString(GinkgoT(), result, `{"message":"Unmounted partition of {ID:vol-123 DeviceID: VolumeID:2 Lun:0 HostDeviceID:fake-host-device-id Path:/dev/sdf ISCSISettings:{InitiatorName:fake-initiator-name Username:fake-username Target:fake-target Password:fake-password} FileSystemType:ext4 MountOptions:[] Partitioner:}"}`) @@ -85,7 +84,7 @@ var _ = Describe("UnmountDiskAction", func() { It("unmount disk when the disk is not mounted", func() { platform.UnmountPersistentDiskReturns(false, nil) - result, err := action.Run("vol-123") + result, err := unmountDiskAction.Run("vol-123") Expect(err).ToNot(HaveOccurred()) boshassert.MatchesJSONString(GinkgoT(), result, `{"message":"Partition of {ID:vol-123 DeviceID: VolumeID:2 Lun:0 HostDeviceID:fake-host-device-id Path:/dev/sdf ISCSISettings:{InitiatorName:fake-initiator-name Username:fake-username Target:fake-target Password:fake-password} FileSystemType:ext4 MountOptions:[] Partitioner:} is not mounted"}`) @@ -99,7 +98,7 @@ var _ = Describe("UnmountDiskAction", func() { }) It("returns error", func() { - _, err := action.Run("vol-456") + _, err := unmountDiskAction.Run("vol-456") Expect(err).To(HaveOccurred()) }) }) diff --git a/agent/action/update_settings_test.go b/agent/action/update_settings_test.go index 04f9ae1af..1a33de4bc 100644 --- a/agent/action/update_settings_test.go +++ b/agent/action/update_settings_test.go @@ -1,33 +1,31 @@ package action_test import ( - "github.com/cloudfoundry/bosh-agent/agent/utils/utilsfakes" + "errors" + . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "errors" - - . "github.com/cloudfoundry/bosh-agent/agent/action" + "github.com/cloudfoundry/bosh-agent/agent/action" + "github.com/cloudfoundry/bosh-agent/agent/utils/utilsfakes" "github.com/cloudfoundry/bosh-agent/platform/cert/certfakes" "github.com/cloudfoundry/bosh-agent/platform/platformfakes" - "github.com/cloudfoundry/bosh-utils/logger" - + boshsettings "github.com/cloudfoundry/bosh-agent/settings" fakesettings "github.com/cloudfoundry/bosh-agent/settings/fakes" + "github.com/cloudfoundry/bosh-utils/logger" fakesys "github.com/cloudfoundry/bosh-utils/system/fakes" - - boshsettings "github.com/cloudfoundry/bosh-agent/settings" ) var _ = Describe("UpdateSettings", func() { var ( - action UpdateSettingsAction - agentKiller utilsfakes.FakeKiller - certManager *certfakes.FakeManager - settingsService *fakesettings.FakeSettingsService - log logger.Logger - platform *platformfakes.FakePlatform - newUpdateSettings boshsettings.UpdateSettings - fileSystem *fakesys.FakeFileSystem + updateSettingsAction action.UpdateSettingsAction + agentKiller utilsfakes.FakeKiller + certManager *certfakes.FakeManager + settingsService *fakesettings.FakeSettingsService + log logger.Logger + platform *platformfakes.FakePlatform + newUpdateSettings boshsettings.UpdateSettings + fileSystem *fakesys.FakeFileSystem ) BeforeEach(func() { @@ -40,39 +38,40 @@ var _ = Describe("UpdateSettings", func() { fileSystem = fakesys.NewFakeFileSystem() platform.GetFsReturns(fileSystem) - action = NewUpdateSettings(settingsService, platform, certManager, log, &agentKiller) + updateSettingsAction = action.NewUpdateSettings(settingsService, platform, certManager, log, &agentKiller) newUpdateSettings = boshsettings.UpdateSettings{} }) - AssertActionIsAsynchronous(action) - AssertActionIsPersistent(action) - AssertActionIsLoggable(action) + AssertActionIsAsynchronous(updateSettingsAction) + AssertActionIsPersistent(updateSettingsAction) + AssertActionIsLoggable(updateSettingsAction) - AssertActionIsResumable(action) - AssertActionIsNotCancelable(action) + AssertActionIsResumable(updateSettingsAction) + AssertActionIsNotCancelable(updateSettingsAction) Context("on success", func() { It("returns 'ok'", func() { - result, err := action.Run(newUpdateSettings) + result, err := updateSettingsAction.Run(newUpdateSettings) Expect(err).ToNot(HaveOccurred()) Expect(result).To(Equal("ok")) }) It("writes the updated settings to a file", func() { - action.Run(newUpdateSettings) + _, err := updateSettingsAction.Run(newUpdateSettings) + Expect(err).NotTo(HaveOccurred()) Expect(settingsService.SaveUpdateSettingsCallCount).To(Equal(1)) }) }) Context("when it fails to save the UpdateSettings", func() { BeforeEach(func() { - settingsService.SaveUpdateSettingsErr = errors.New("Fake write error") + settingsService.SaveUpdateSettingsErr = errors.New("fake write error") }) It("returns an error", func() { - _, err := action.Run(newUpdateSettings) + _, err := updateSettingsAction.Run(newUpdateSettings) Expect(err).To(HaveOccurred()) - Expect(err.Error()).To(ContainSubstring("Fake write error")) + Expect(err.Error()).To(ContainSubstring("fake write error")) }) }) @@ -80,19 +79,19 @@ var _ = Describe("UpdateSettings", func() { BeforeEach(func() { log = logger.NewLogger(logger.LevelNone) certManager = new(certfakes.FakeManager) - certManager.UpdateCertificatesReturns(errors.New("Error")) - action = NewUpdateSettings(settingsService, platform, certManager, log, &agentKiller) + certManager.UpdateCertificatesReturns(errors.New("fake error")) + updateSettingsAction = action.NewUpdateSettings(settingsService, platform, certManager, log, &agentKiller) }) It("returns the error", func() { - result, err := action.Run(newUpdateSettings) + result, err := updateSettingsAction.Run(newUpdateSettings) Expect(err).To(HaveOccurred()) Expect(result).To(BeEmpty()) }) }) It("loads settings", func() { - _, err := action.Run(newUpdateSettings) + _, err := updateSettingsAction.Run(newUpdateSettings) Expect(err).ToNot(HaveOccurred()) Expect(settingsService.SettingsWereLoaded).To(BeTrue()) }) @@ -100,7 +99,7 @@ var _ = Describe("UpdateSettings", func() { Context("when loading the settings fails", func() { It("returns an error", func() { settingsService.LoadSettingsError = errors.New("nope") - _, err := action.Run(newUpdateSettings) + _, err := updateSettingsAction.Run(newUpdateSettings) Expect(err).To(HaveOccurred()) }) }) @@ -119,14 +118,14 @@ var _ = Describe("UpdateSettings", func() { newUpdateSettings = boshsettings.UpdateSettings{ DiskAssociations: []boshsettings.DiskAssociation{diskAssociation}, } - settingsService.GetPersistentDiskSettingsError = errors.New("Disk DNE") + settingsService.GetPersistentDiskSettingsError = errors.New("disk DNE") }) It("returns the error", func() { - _, err := action.Run(newUpdateSettings) + _, err := updateSettingsAction.Run(newUpdateSettings) Expect(err).To(HaveOccurred()) - Expect(err.Error()).To(Equal("Fetching disk settings: Disk DNE")) + Expect(err.Error()).To(Equal("Fetching disk settings: disk DNE")) }) }) @@ -160,7 +159,7 @@ var _ = Describe("UpdateSettings", func() { DiskCID: "fake-disk-id-2", } - _, err := action.Run(boshsettings.UpdateSettings{ + _, err := updateSettingsAction.Run(boshsettings.UpdateSettings{ DiskAssociations: []boshsettings.DiskAssociation{ diskAssociation, diskAssociation2, @@ -204,14 +203,14 @@ var _ = Describe("UpdateSettings", func() { It("kills the agent", func() { Expect(func() { - action.Run(newUpdateSettings) + updateSettingsAction.Run(newUpdateSettings) //nolint:errcheck }).To(Panic()) Expect(agentKiller.KillAgentCallCount()).To(Equal(1)) }) It("persists the new settings", func() { Expect(func() { - action.Run(newUpdateSettings) + updateSettingsAction.Run(newUpdateSettings) //nolint:errcheck }).To(Panic()) updateSettings := settingsService.SaveUpdateSettingsLastArg diff --git a/agent/action/upload_blob_test.go b/agent/action/upload_blob_test.go index cc2f800c8..d54715166 100644 --- a/agent/action/upload_blob_test.go +++ b/agent/action/upload_blob_test.go @@ -3,37 +3,37 @@ package action_test import ( "errors" - . "github.com/cloudfoundry/bosh-agent/agent/blobstore/blobstorefakes" - "github.com/cloudfoundry/bosh-utils/crypto" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - . "github.com/cloudfoundry/bosh-agent/agent/action" + "github.com/cloudfoundry/bosh-agent/agent/action" + "github.com/cloudfoundry/bosh-agent/agent/blobstore/blobstorefakes" + "github.com/cloudfoundry/bosh-utils/crypto" ) var _ = Describe("UploadBlobAction", func() { var ( - action UploadBlobAction - fakeBlobManager *FakeBlobManagerInterface + uploadBlobAction action.UploadBlobAction + fakeBlobManager *blobstorefakes.FakeBlobManagerInterface ) BeforeEach(func() { - fakeBlobManager = &FakeBlobManagerInterface{} - action = NewUploadBlobAction(fakeBlobManager) + fakeBlobManager = &blobstorefakes.FakeBlobManagerInterface{} + uploadBlobAction = action.NewUploadBlobAction(fakeBlobManager) }) - AssertActionIsAsynchronous(action) - AssertActionIsNotPersistent(action) - AssertActionIsNotLoggable(action) + AssertActionIsAsynchronous(uploadBlobAction) + AssertActionIsNotPersistent(uploadBlobAction) + AssertActionIsNotLoggable(uploadBlobAction) - AssertActionIsNotResumable(action) - AssertActionIsNotCancelable(action) + AssertActionIsNotResumable(uploadBlobAction) + AssertActionIsNotCancelable(uploadBlobAction) Describe("Run", func() { Context("Payload Validation", func() { It("validates the payload using provided Checksum", func() { - _, err := action.Run(UploadBlobSpec{ + _, err := uploadBlobAction.Run(action.UploadBlobSpec{ Payload: "Y2xvdWRmb3VuZHJ5", Checksum: crypto.MustParseMultipleDigest("sha1:e578935e2f0613d68ba6a4fcc0d32754b52d334d"), BlobID: "id", @@ -42,17 +42,18 @@ var _ = Describe("UploadBlobAction", func() { }) It("validates the payload using provided sha256 Checksum", func() { - //echo -n 'cloudfoundry' | shasum -a 256 - _, err := action.Run(UploadBlobSpec{ - Payload: "Y2xvdWRmb3VuZHJ5", - Checksum: crypto.MustNewMultipleDigest(crypto.NewDigest(crypto.DigestAlgorithmSHA256, "2ad453a5a20f9e110c40100c7f8eeb929070dd5abea32d7401ab74779b695e73")), - BlobID: "id", + _, err := uploadBlobAction.Run(action.UploadBlobSpec{ + Payload: "Y2xvdWRmb3VuZHJ5", + Checksum: crypto.MustNewMultipleDigest(crypto.NewDigest(crypto.DigestAlgorithmSHA256, + // echo -n 'cloudfoundry' | shasum -a 256 + "2ad453a5a20f9e110c40100c7f8eeb929070dd5abea32d7401ab74779b695e73")), + BlobID: "id", }) Expect(err).ToNot(HaveOccurred()) }) It("does not validate the payload when the Checksum is incorrect", func() { - _, err := action.Run(UploadBlobSpec{ + _, err := uploadBlobAction.Run(action.UploadBlobSpec{ Payload: "Y2xvdWRmb3VuZHJ5", Checksum: crypto.MustParseMultipleDigest("sha1:badChecksum"), BlobID: "id", @@ -63,7 +64,7 @@ var _ = Describe("UploadBlobAction", func() { }) It("should call the blob manager", func() { - _, err := action.Run(UploadBlobSpec{ + _, err := uploadBlobAction.Run(action.UploadBlobSpec{ Payload: "Y2xvdWRmb3VuZHJ5", Checksum: crypto.MustParseMultipleDigest("sha1:e578935e2f0613d68ba6a4fcc0d32754b52d334d"), BlobID: "id", @@ -74,7 +75,7 @@ var _ = Describe("UploadBlobAction", func() { It("should return an error if the blob manager fails", func() { fakeBlobManager.WriteReturns(errors.New("blob write error")) - _, err := action.Run(UploadBlobSpec{ + _, err := uploadBlobAction.Run(action.UploadBlobSpec{ Payload: "Y2xvdWRmb3VuZHJ5", Checksum: crypto.MustParseMultipleDigest("sha1:e578935e2f0613d68ba6a4fcc0d32754b52d334d"), BlobID: "id", diff --git a/agent/action_dispatcher_test.go b/agent/action_dispatcher_test.go index 7fba37545..3ae728f5e 100644 --- a/agent/action_dispatcher_test.go +++ b/agent/action_dispatcher_test.go @@ -8,7 +8,7 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - . "github.com/cloudfoundry/bosh-agent/agent" + "github.com/cloudfoundry/bosh-agent/agent" "github.com/cloudfoundry/bosh-agent/agent/action" fakeaction "github.com/cloudfoundry/bosh-agent/agent/action/fakes" boshtask "github.com/cloudfoundry/bosh-agent/agent/task" @@ -18,7 +18,7 @@ import ( fakes "github.com/cloudfoundry/bosh-utils/logger/loggerfakes" ) -func init() { +func init() { //nolint:funlen,gochecknoinits Describe("actionDispatcher", func() { var ( logger *fakes.FakeLogger @@ -26,7 +26,7 @@ func init() { taskManager *faketask.FakeManager actionFactory *fakeaction.FakeFactory actionRunner *fakeaction.FakeRunner - dispatcher ActionDispatcher + dispatcher agent.ActionDispatcher ) BeforeEach(func() { @@ -35,7 +35,7 @@ func init() { taskManager = faketask.NewFakeManager() actionFactory = fakeaction.NewFakeFactory() actionRunner = &fakeaction.FakeRunner{} - dispatcher = NewActionDispatcher(logger, taskService, taskManager, actionFactory, actionRunner) + dispatcher = agent.NewActionDispatcher(logger, taskService, taskManager, actionFactory, actionRunner) }) It("responds with exception when the method is unknown", func() { @@ -91,7 +91,6 @@ func init() { BeforeEach(func() { runAction = &fakeaction.TestAction{Asynchronous: true} actionFactory.RegisterAction("fake-action", runAction) - }) It("passes protocol version zero to IsSynchronous", func() { @@ -122,7 +121,6 @@ func init() { Expect(runAction.ProtocolVersion).To(Equal(action.ProtocolVersion(99))) Expect(actionRunner.RunProtocolVersion).To(Equal(action.ProtocolVersion(99))) }) - }) Context("when request contains protocol version and action is Synchronous", func() { @@ -151,7 +149,6 @@ func init() { Expect(runAction.ProtocolVersion).To(Equal(action.ProtocolVersion(99))) Expect(actionRunner.RunProtocolVersion).To(Equal(action.ProtocolVersion(99))) }) - }) Context("when action is synchronous", func() { @@ -473,7 +470,8 @@ func init() { } { // Check that second task executes second action - taskService.StartedTasks["fake-task-id-2"].Func() + _, err := taskService.StartedTasks["fake-task-id-2"].Func() + Expect(err).NotTo(HaveOccurred()) Expect(actionRunner.ResumeAction).To(Equal(secondAction)) Expect(string(actionRunner.ResumePayload)).To(Equal("fake-task-payload-2")) } diff --git a/agent/agent_test.go b/agent/agent_test.go index b6ce9523b..58507db75 100644 --- a/agent/agent_test.go +++ b/agent/agent_test.go @@ -7,9 +7,8 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - . "github.com/cloudfoundry/bosh-agent/agent" - "code.cloudfoundry.org/clock/fakeclock" + "github.com/cloudfoundry/bosh-agent/agent" "github.com/cloudfoundry/bosh-agent/agent/agentfakes" boshalert "github.com/cloudfoundry/bosh-agent/agent/alert" boshas "github.com/cloudfoundry/bosh-agent/agent/applier/applyspec" @@ -26,7 +25,7 @@ import ( fakeuuid "github.com/cloudfoundry/bosh-utils/uuid/fakes" ) -func init() { +func init() { //nolint:funlen,gochecknoinits Describe("Agent", func() { var ( logger boshlog.Logger @@ -41,11 +40,11 @@ func init() { vitalService *vitalsfakes.FakeService startManager *agentfakes.FakeStartManager - agent Agent + boshAgent agent.Agent ) BeforeSuite(func() { - HeartbeatRetryInterval = 1 * time.Millisecond + agent.HeartbeatRetryInterval = 1 * time.Millisecond }) BeforeEach(func() { @@ -64,7 +63,7 @@ func init() { platform.GetVitalsServiceReturns(vitalService) - agent = New( + boshAgent = agent.New( logger, handler, platform, @@ -77,19 +76,18 @@ func init() { timeService, startManager, ) - }) Describe("Run", func() { It("Registers a start with the startManager", func() { - err := agent.Run() + err := boshAgent.Run() Expect(err).ToNot(HaveOccurred()) Expect(startManager.RegisterStartCallCount()).To(Equal(1)) }) It("lets dispatcher handle requests arriving via handler", func() { - err := agent.Run() + err := boshAgent.Run() Expect(err).ToNot(HaveOccurred()) expectedResp := boshhandler.NewValueResponse("pong") @@ -108,7 +106,7 @@ func init() { resumedBeforeStartingToDispatch = actionDispatcher.ResumedPreviouslyDispatchedTasks } - err := agent.Run() + err := boshAgent.Run() Expect(err).ToNot(HaveOccurred()) Expect(resumedBeforeStartingToDispatch).To(BeTrue()) }) @@ -139,7 +137,7 @@ func init() { expectedJobName := "fake-job" expectedJobIndex := 1 expectedNodeID := "node-id" - expectedHb := Heartbeat{ + expectedHb := agent.Heartbeat{ Deployment: "FakeDeployment", Job: &expectedJobName, Index: &expectedJobIndex, @@ -151,7 +149,7 @@ func init() { It("sends initial heartbeat", func() { // Configure periodic heartbeat every 5 hours // so that we are sure that we will not receive it - agent = New( + boshAgent = agent.New( logger, handler, platform, @@ -168,7 +166,7 @@ func init() { // Immediately exit after sending initial heartbeat handler.SendErr = errors.New("stop") - err := agent.Run() + err := boshAgent.Run() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("stop")) @@ -198,7 +196,7 @@ func init() { } } - err := agent.Run() + err := boshAgent.Run() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("stop")) @@ -214,39 +212,39 @@ func init() { Expect(jobSupervisor.GetHealthRecorded()).To(BeNumerically(">=", 3)) }) - Context("when the agent may not be rebooted", func() { + Context("when the boshAgent may not be rebooted", func() { BeforeEach(func() { startManager.CanStartReturns(false) }) It("stops the boot process and returns an error", func() { - err := agent.Run() + err := boshAgent.Run() Expect(err).To(HaveOccurred()) }) }) }) - Context("when the agent fails to get job spec for a heartbeat", func() { + Context("when the boshAgent fails to get job spec for a heartbeat", func() { BeforeEach(func() { specService.GetErr = errors.New("fake-spec-service-error") handler.KeepOnRunning() }) It("returns the error", func() { - err := agent.Run() + err := boshAgent.Run() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-spec-service-error")) }) }) - Context("when the agent fails to get vitals for a heartbeat", func() { + Context("when the boshAgent fails to get vitals for a heartbeat", func() { BeforeEach(func() { vitalService.GetReturns(boshvitals.Vitals{}, errors.New("fake-vitals-service-error")) handler.KeepOnRunning() }) It("returns the error", func() { - err := agent.Run() + err := boshAgent.Run() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-vitals-service-error")) }) @@ -272,7 +270,7 @@ func init() { } } - err := agent.Run() + err := boshAgent.Run() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("stop")) diff --git a/agent/applier/applyspec/concrete_v1_service_test.go b/agent/applier/applyspec/concrete_v1_service_test.go index 10815302d..f4eb1a9af 100644 --- a/agent/applier/applyspec/concrete_v1_service_test.go +++ b/agent/applier/applyspec/concrete_v1_service_test.go @@ -12,7 +12,7 @@ import ( fakesys "github.com/cloudfoundry/bosh-utils/system/fakes" ) -func init() { +func init() { //nolint:gochecknoinits Describe("concreteV1Service", func() { var ( fs *fakesys.FakeFileSystem @@ -28,7 +28,8 @@ func init() { Describe("Get", func() { Context("when filesystem has a spec file", func() { BeforeEach(func() { - fs.WriteFileString(specPath, `{"deployment":"fake-deployment-name"}`) + err := fs.WriteFileString(specPath, `{"deployment":"fake-deployment-name"}`) + Expect(err).ToNot(HaveOccurred()) }) It("reads spec from filesystem", func() { @@ -123,7 +124,6 @@ func init() { "gateway": "fake-net2-gateway", }, } - }) Context("when associated network is in settings", func() { diff --git a/agent/applier/applyspec/rendered_templates_archive_spec_test.go b/agent/applier/applyspec/rendered_templates_archive_spec_test.go index c63b26adf..144f1718c 100644 --- a/agent/applier/applyspec/rendered_templates_archive_spec_test.go +++ b/agent/applier/applyspec/rendered_templates_archive_spec_test.go @@ -52,8 +52,8 @@ var _ = Describe("RenderedTemplatesArchive", func() { Context("unmarshalling JSON", func() { DescribeTable("unmarshalling", func(blobstoreID, sha1, errorMsg string, expected *RenderedTemplatesArchiveSpec) { data := []byte(fmt.Sprintf(`{"blobstore_id": "%s", "sha1": "%s"}`, blobstoreID, sha1)) - var rendered *RenderedTemplatesArchiveSpec - rendered = &RenderedTemplatesArchiveSpec{} + + rendered := &RenderedTemplatesArchiveSpec{} err := json.Unmarshal(data, rendered) if errorMsg == "" { Expect(err).NotTo(HaveOccurred()) diff --git a/agent/applier/applyspec/v1_apply_spec_test.go b/agent/applier/applyspec/v1_apply_spec_test.go index 0faf45a8e..22e3d12e4 100644 --- a/agent/applier/applyspec/v1_apply_spec_test.go +++ b/agent/applier/applyspec/v1_apply_spec_test.go @@ -128,7 +128,7 @@ var _ = Describe("V1ApplySpec", func() { Expect(err).ToNot(HaveOccurred()) reloadedSpec := V1ApplySpec{} - err = json.Unmarshal([]byte(specBytes), &reloadedSpec) + err = json.Unmarshal(specBytes, &reloadedSpec) Expect(err).ToNot(HaveOccurred()) Expect(reloadedSpec).To(Equal(spec)) @@ -170,7 +170,7 @@ var _ = Describe("V1ApplySpec", func() { specBytes, err := json.Marshal(spec) Expect(err).ToNot(HaveOccurred()) reloadedSpec := V1ApplySpec{} - err = json.Unmarshal([]byte(specBytes), &reloadedSpec) + err = json.Unmarshal(specBytes, &reloadedSpec) Expect(err).ToNot(HaveOccurred()) Expect(reloadedSpec).To(Equal(spec)) @@ -274,7 +274,7 @@ var _ = Describe("V1ApplySpec", func() { }) Describe("Packages", func() { - It("retuns packages", func() { + It("returns packages", func() { spec := V1ApplySpec{ PackageSpecs: map[string]PackageSpec{ "fake-package1-name-key": { @@ -320,7 +320,7 @@ var _ = Describe("V1ApplySpec", func() { var _ = Describe("NetworkSpec", func() { Describe("PopulateIPInfo", func() { - It("populates network spec with ip, netmask and gateway addressess", func() { + It("populates network spec with ip, netmask and gateway addresses", func() { networkSpec := NetworkSpec{} networkSpec = networkSpec.PopulateIPInfo("fake-ip", "fake-netmask", "fake-gateway") @@ -334,7 +334,7 @@ var _ = Describe("NetworkSpec", func() { })) }) - It("overwrites network spec with ip, netmask and gateway addressess", func() { + It("overwrites network spec with ip, netmask and gateway addresses", func() { networkSpec := NetworkSpec{ Fields: map[string]interface{}{ "ip": "fake-old-ip", diff --git a/agent/applier/bundlecollection/file_bundle_setup_unix_test.go b/agent/applier/bundlecollection/file_bundle_setup_unix_test.go index 54223a43b..7abbed24f 100644 --- a/agent/applier/bundlecollection/file_bundle_setup_unix_test.go +++ b/agent/applier/bundlecollection/file_bundle_setup_unix_test.go @@ -72,7 +72,8 @@ var _ = Describe("FileBundle", func() { decompressPath := fakeCompressor.DecompressFileToDirDirs[len(fakeCompressor.DecompressFileToDirDirs)-1] contents, err := fs.ReadFileString(filepath.Join(sourcePath, "config.go")) Expect(err).NotTo(HaveOccurred()) - fs.WriteFileString(filepath.Join(decompressPath, "config.go"), contents) + err = fs.WriteFileString(filepath.Join(decompressPath, "config.go"), contents) + Expect(err).ToNot(HaveOccurred()) } path, err := fileBundle.Install(sourcePath, "") diff --git a/agent/applier/bundlecollection/file_bundle_test.go b/agent/applier/bundlecollection/file_bundle_test.go index 763d67584..bfa852dc7 100644 --- a/agent/applier/bundlecollection/file_bundle_test.go +++ b/agent/applier/bundlecollection/file_bundle_test.go @@ -74,7 +74,7 @@ var _ = Describe("FileBundle", func() { fileStats := fs.GetFileTestStat(installPath) Expect(fileStats).ToNot(BeNil()) - Expect(fileStats.FileType).To(Equal(fakesys.FakeFileType(fakesys.FakeFileTypeDir))) + Expect(fileStats.FileType).To(Equal(fakesys.FakeFileTypeDir)) Expect(fileStats.FileMode).To(Equal(os.FileMode(0750))) Expect(fileStats.Username).To(Equal("root")) Expect(fileStats.Groupname).To(Equal("vcap")) @@ -109,14 +109,15 @@ var _ = Describe("FileBundle", func() { }) It("sets correct permissions on install path", func() { - fs.Chmod(sourcePath, os.FileMode(0700)) + err := fs.Chmod(sourcePath, os.FileMode(0700)) + Expect(err).ToNot(HaveOccurred()) - _, err := fileBundle.Install(sourcePath, "") + _, err = fileBundle.Install(sourcePath, "") Expect(err).NotTo(HaveOccurred()) fileStats := fs.GetFileTestStat(installPath) Expect(fileStats).ToNot(BeNil()) - Expect(fileStats.FileType).To(Equal(fakesys.FakeFileType(fakesys.FakeFileTypeDir))) + Expect(fileStats.FileType).To(Equal(fakesys.FakeFileTypeDir)) Expect(fileStats.FileMode).To(Equal(os.FileMode(0750))) Expect(fileStats.Username).To(Equal("root")) Expect(fileStats.Groupname).To(Equal("vcap")) @@ -138,7 +139,8 @@ var _ = Describe("FileBundle", func() { decompressPath := fakeCompressor.DecompressFileToDirDirs[len(fakeCompressor.DecompressFileToDirDirs)-1] contents, err := fs.ReadFileString(filepath.Join(sourcePath, "config.go")) Expect(err).NotTo(HaveOccurred()) - fs.WriteFileString(filepath.Join(decompressPath, "config.go"), contents) + err = fs.WriteFileString(filepath.Join(decompressPath, "config.go"), contents) + Expect(err).ToNot(HaveOccurred()) } path, err := fileBundle.Install(sourcePath, "") @@ -203,14 +205,15 @@ var _ = Describe("FileBundle", func() { }) It("sets correct permissions on install path", func() { - fs.Chmod(sourcePath, os.FileMode(0700)) + err := fs.Chmod(sourcePath, os.FileMode(0700)) + Expect(err).NotTo(HaveOccurred()) - _, err := fileBundle.Install(sourcePath, "") + _, err = fileBundle.Install(sourcePath, "") Expect(err).NotTo(HaveOccurred()) fileStats := fs.GetFileTestStat(installPath) Expect(fileStats).ToNot(BeNil()) - Expect(fileStats.FileType).To(Equal(fakesys.FakeFileType(fakesys.FakeFileTypeDir))) + Expect(fileStats.FileType).To(Equal(fakesys.FakeFileTypeDir)) Expect(fileStats.FileMode).To(Equal(os.FileMode(0750))) Expect(fileStats.Username).To(Equal("root")) Expect(fileStats.Groupname).To(Equal("vcap")) @@ -279,12 +282,12 @@ var _ = Describe("FileBundle", func() { fileStats := fs.GetFileTestStat(enablePath) Expect(fileStats).NotTo(BeNil()) - Expect(fileStats.FileType).To(Equal(fakesys.FakeFileType(fakesys.FakeFileTypeSymlink))) + Expect(fileStats.FileType).To(Equal(fakesys.FakeFileTypeSymlink)) Expect(installPath).To(Equal(fileStats.SymlinkTarget)) fileStats = fs.GetFileTestStat("/") // dir holding symlink Expect(fileStats).NotTo(BeNil()) - Expect(fileStats.FileType).To(Equal(fakesys.FakeFileType(fakesys.FakeFileTypeDir))) + Expect(fileStats.FileType).To(Equal(fakesys.FakeFileTypeDir)) Expect(fileStats.FileMode).To(Equal(os.FileMode(0750))) Expect(fileStats.Username).To(Equal("root")) Expect(fileStats.Groupname).To(Equal("vcap")) @@ -412,7 +415,7 @@ var _ = Describe("FileBundle", func() { fileStats := fs.GetFileTestStat(enablePath) Expect(fileStats).NotTo(BeNil()) - Expect(fileStats.FileType).To(Equal(fakesys.FakeFileType(fakesys.FakeFileTypeSymlink))) + Expect(fileStats.FileType).To(Equal(fakesys.FakeFileTypeSymlink)) Expect(newerInstallPath).To(Equal(fileStats.SymlinkTarget)) }) }) diff --git a/agent/applier/bundlecollection/file_bundle_windows_test.go b/agent/applier/bundlecollection/file_bundle_windows_test.go index 942c0722f..3ff4e1602 100644 --- a/agent/applier/bundlecollection/file_bundle_windows_test.go +++ b/agent/applier/bundlecollection/file_bundle_windows_test.go @@ -4,10 +4,11 @@ package bundlecollection_test import ( + "os" + "github.com/cloudfoundry/bosh-agent/agent/tarpath/tarpathfakes" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "os" . "github.com/cloudfoundry/bosh-agent/agent/applier/bundlecollection" "github.com/cloudfoundry/bosh-agent/agent/applier/bundlecollection/fakes" diff --git a/agent/applier/concrete_applier_test.go b/agent/applier/concrete_applier_test.go index e78c90c78..685d4d857 100644 --- a/agent/applier/concrete_applier_test.go +++ b/agent/applier/concrete_applier_test.go @@ -4,21 +4,20 @@ import ( "errors" "path/filepath" - "github.com/stretchr/testify/assert" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - . "github.com/cloudfoundry/bosh-agent/agent/applier" + "github.com/cloudfoundry/bosh-agent/agent/applier" fakeas "github.com/cloudfoundry/bosh-agent/agent/applier/applyspec/fakes" fakejobs "github.com/cloudfoundry/bosh-agent/agent/applier/jobs/jobsfakes" - models "github.com/cloudfoundry/bosh-agent/agent/applier/models" + "github.com/cloudfoundry/bosh-agent/agent/applier/models" fakepackages "github.com/cloudfoundry/bosh-agent/agent/applier/packages/fakes" fakejobsuper "github.com/cloudfoundry/bosh-agent/jobsupervisor/fakes" boshsettings "github.com/cloudfoundry/bosh-agent/settings" boshdirs "github.com/cloudfoundry/bosh-agent/settings/directories" fakesettings "github.com/cloudfoundry/bosh-agent/settings/fakes" boshuuid "github.com/cloudfoundry/bosh-utils/uuid" + "github.com/stretchr/testify/assert" ) type FakeLogRotateDelegate struct { @@ -57,7 +56,7 @@ var _ = Describe("concreteApplier", func() { packageApplier *fakepackages.FakeApplier logRotateDelegate *FakeLogRotateDelegate jobSupervisor *fakejobsuper.FakeJobSupervisor - applier Applier + agentApplier applier.Applier settingsService boshsettings.Service ) @@ -67,7 +66,7 @@ var _ = Describe("concreteApplier", func() { logRotateDelegate = &FakeLogRotateDelegate{} jobSupervisor = fakejobsuper.NewFakeJobSupervisor() settingsService = &fakesettings.FakeSettingsService{} - applier = NewConcreteApplier( + agentApplier = applier.NewConcreteApplier( jobApplier, packageApplier, logRotateDelegate, @@ -81,7 +80,7 @@ var _ = Describe("concreteApplier", func() { It("prepares each jobs", func() { job := buildJob() - err := applier.Prepare( + err := agentApplier.Prepare( &fakeas.FakeApplySpec{JobResults: []models.Job{job}}, ) Expect(err).ToNot(HaveOccurred()) @@ -94,7 +93,7 @@ var _ = Describe("concreteApplier", func() { jobApplier.PrepareReturns(errors.New("fake-prepare-job-error")) - err := applier.Prepare( + err := agentApplier.Prepare( &fakeas.FakeApplySpec{JobResults: []models.Job{job}}, ) Expect(err).To(HaveOccurred()) @@ -105,7 +104,7 @@ var _ = Describe("concreteApplier", func() { pkg1 := buildPackage() pkg2 := buildPackage() - err := applier.Prepare( + err := agentApplier.Prepare( &fakeas.FakeApplySpec{PackageResults: []models.Package{pkg1, pkg2}}, ) Expect(err).ToNot(HaveOccurred()) @@ -117,7 +116,7 @@ var _ = Describe("concreteApplier", func() { packageApplier.PrepareError = errors.New("fake-prepare-package-error") - err := applier.Prepare( + err := agentApplier.Prepare( &fakeas.FakeApplySpec{PackageResults: []models.Package{pkg}}, ) Expect(err).To(HaveOccurred()) @@ -127,7 +126,7 @@ var _ = Describe("concreteApplier", func() { It("deletes the job source from the blobstore after preparing", func() { job := buildJob() - err := applier.Prepare(&fakeas.FakeApplySpec{JobResults: []models.Job{job}}) + err := agentApplier.Prepare(&fakeas.FakeApplySpec{JobResults: []models.Job{job}}) Expect(err).ToNot(HaveOccurred()) Expect(jobApplier.DeleteSourceBlobsCallCount()).To(Equal(1)) @@ -136,9 +135,9 @@ var _ = Describe("concreteApplier", func() { It("returns an error when deleting the source blobs fails", func() { job := buildJob() - jobApplier.DeleteSourceBlobsReturns(errors.New("boom!")) + jobApplier.DeleteSourceBlobsReturns(errors.New("boom")) - err := applier.Apply(&fakeas.FakeApplySpec{JobResults: []models.Job{job}}) + err := agentApplier.Apply(&fakeas.FakeApplySpec{JobResults: []models.Job{job}}) Expect(err).To(HaveOccurred()) Expect(jobApplier.DeleteSourceBlobsCallCount()).To(Equal(1)) @@ -152,7 +151,7 @@ var _ = Describe("concreteApplier", func() { job2 := models.Job{Name: "fake-job-name-2", Version: "fake-version-name-2"} jobs := []models.Job{job1, job2} - err := applier.ConfigureJobs(&fakeas.FakeApplySpec{JobResults: jobs}) + err := agentApplier.ConfigureJobs(&fakeas.FakeApplySpec{JobResults: jobs}) Expect(err).ToNot(HaveOccurred()) Expect(jobSupervisor.Reloaded).To(BeTrue()) @@ -163,7 +162,7 @@ var _ = Describe("concreteApplier", func() { job2 := models.Job{Name: "fake-job-name-2", Version: "fake-version-name-2"} jobs := []models.Job{job1, job2} - err := applier.ConfigureJobs(&fakeas.FakeApplySpec{JobResults: jobs}) + err := agentApplier.ConfigureJobs(&fakeas.FakeApplySpec{JobResults: jobs}) Expect(err).ToNot(HaveOccurred()) Expect(jobApplier.ConfigureCallCount()).To(Equal(2)) @@ -176,7 +175,7 @@ var _ = Describe("concreteApplier", func() { Describe("Apply", func() { It("removes all jobs from job supervisor", func() { - err := applier.Apply(&fakeas.FakeApplySpec{}) + err := agentApplier.Apply(&fakeas.FakeApplySpec{}) Expect(err).ToNot(HaveOccurred()) Expect(jobSupervisor.RemovedAllJobs).To(BeTrue()) @@ -187,18 +186,16 @@ var _ = Describe("concreteApplier", func() { jobSupervisor.RemovedAllJobsErr = errors.New("fake-remove-all-jobs-error") job := buildJob() - applier.Apply(&fakeas.FakeApplySpec{JobResults: []models.Job{job}}) - - // check that jobs were not applied before removing all other jobs + agentApplier.Apply(&fakeas.FakeApplySpec{JobResults: []models.Job{job}}) //nolint:errcheck + // check that jobs were not applied before removing other jobs Expect(jobApplier.ApplyCallCount()).To(Equal(0)) - }) It("returns error if removing all jobs from job supervisor fails", func() { jobSupervisor.RemovedAllJobsErr = errors.New("fake-remove-all-jobs-error") - err := applier.Apply(&fakeas.FakeApplySpec{}) + err := agentApplier.Apply(&fakeas.FakeApplySpec{}) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-remove-all-jobs-error")) }) @@ -206,7 +203,7 @@ var _ = Describe("concreteApplier", func() { It("apply applies jobs", func() { job := buildJob() - err := applier.Apply(&fakeas.FakeApplySpec{JobResults: []models.Job{job}}) + err := agentApplier.Apply(&fakeas.FakeApplySpec{JobResults: []models.Job{job}}) Expect(err).ToNot(HaveOccurred()) Expect(jobApplier.ApplyCallCount()).To(Equal(1)) @@ -218,7 +215,7 @@ var _ = Describe("concreteApplier", func() { jobApplier.ApplyReturns(errors.New("fake-apply-job-error")) - err := applier.Apply(&fakeas.FakeApplySpec{JobResults: []models.Job{job}}) + err := agentApplier.Apply(&fakeas.FakeApplySpec{JobResults: []models.Job{job}}) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-apply-job-error")) @@ -227,7 +224,7 @@ var _ = Describe("concreteApplier", func() { It("asked jobApplier to keep only the jobs in the desired specs", func() { desiredJob := buildJob() - err := applier.Apply(&fakeas.FakeApplySpec{JobResults: []models.Job{desiredJob}}) + err := agentApplier.Apply(&fakeas.FakeApplySpec{JobResults: []models.Job{desiredJob}}) Expect(err).ToNot(HaveOccurred()) @@ -240,7 +237,7 @@ var _ = Describe("concreteApplier", func() { desiredJob := buildJob() - err := applier.Apply(&fakeas.FakeApplySpec{JobResults: []models.Job{desiredJob}}) + err := agentApplier.Apply(&fakeas.FakeApplySpec{JobResults: []models.Job{desiredJob}}) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-keep-only-error")) }) @@ -249,7 +246,7 @@ var _ = Describe("concreteApplier", func() { pkg1 := buildPackage() pkg2 := buildPackage() - err := applier.Apply(&fakeas.FakeApplySpec{PackageResults: []models.Package{pkg1, pkg2}}) + err := agentApplier.Apply(&fakeas.FakeApplySpec{PackageResults: []models.Package{pkg1, pkg2}}) Expect(err).ToNot(HaveOccurred()) Expect(packageApplier.AppliedPackages).To(Equal([]models.Package{pkg1, pkg2})) }) @@ -259,7 +256,7 @@ var _ = Describe("concreteApplier", func() { packageApplier.ApplyError = errors.New("fake-apply-package-error") - err := applier.Apply(&fakeas.FakeApplySpec{PackageResults: []models.Package{pkg}}) + err := agentApplier.Apply(&fakeas.FakeApplySpec{PackageResults: []models.Package{pkg}}) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-apply-package-error")) }) @@ -267,7 +264,7 @@ var _ = Describe("concreteApplier", func() { It("asked packageApplier to keep only the packages in the desired specs", func() { desiredPkg := buildPackage() - err := applier.Apply(&fakeas.FakeApplySpec{PackageResults: []models.Package{desiredPkg}}) + err := agentApplier.Apply(&fakeas.FakeApplySpec{PackageResults: []models.Package{desiredPkg}}) Expect(err).ToNot(HaveOccurred()) Expect(packageApplier.KeptOnlyPackages).To(Equal([]models.Package{desiredPkg})) }) @@ -277,7 +274,7 @@ var _ = Describe("concreteApplier", func() { desiredPkg := buildPackage() - err := applier.Apply(&fakeas.FakeApplySpec{PackageResults: []models.Package{desiredPkg}}) + err := agentApplier.Apply(&fakeas.FakeApplySpec{PackageResults: []models.Package{desiredPkg}}) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-keep-only-error")) }) @@ -287,7 +284,7 @@ var _ = Describe("concreteApplier", func() { job2 := models.Job{Name: "fake-job-name-2", Version: "fake-version-name-2"} jobs := []models.Job{job1, job2} - err := applier.Apply(&fakeas.FakeApplySpec{JobResults: jobs}) + err := agentApplier.Apply(&fakeas.FakeApplySpec{JobResults: jobs}) Expect(err).ToNot(HaveOccurred()) Expect(jobApplier.ConfigureCallCount()).To(Equal(0)) @@ -296,16 +293,16 @@ var _ = Describe("concreteApplier", func() { }) It("apply errs if monitor fails reload", func() { - jobs := []models.Job{} + var jobs []models.Job jobSupervisor.ReloadErr = errors.New("error reloading monit") - err := applier.Apply(&fakeas.FakeApplySpec{JobResults: jobs}) + err := agentApplier.Apply(&fakeas.FakeApplySpec{JobResults: jobs}) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("error reloading monit")) }) It("apply sets up logrotation", func() { - err := applier.Apply(&fakeas.FakeApplySpec{MaxLogFileSizeResult: "fake-size"}) + err := agentApplier.Apply(&fakeas.FakeApplySpec{MaxLogFileSizeResult: "fake-size"}) Expect(err).ToNot(HaveOccurred()) assert.Equal(GinkgoT(), logRotateDelegate.SetupLogrotateArgs, SetupLogrotateArgs{ @@ -318,7 +315,7 @@ var _ = Describe("concreteApplier", func() { It("apply errs if setup logrotate fails", func() { logRotateDelegate.SetupLogrotateErr = errors.New("fake-set-up-logrotate-error") - err := applier.Apply(&fakeas.FakeApplySpec{}) + err := agentApplier.Apply(&fakeas.FakeApplySpec{}) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-set-up-logrotate-error")) }) @@ -326,7 +323,7 @@ var _ = Describe("concreteApplier", func() { It("deletes the job source from the blobstore after applying", func() { job := buildJob() - err := applier.Apply(&fakeas.FakeApplySpec{JobResults: []models.Job{job}}) + err := agentApplier.Apply(&fakeas.FakeApplySpec{JobResults: []models.Job{job}}) Expect(err).ToNot(HaveOccurred()) Expect(jobApplier.DeleteSourceBlobsCallCount()).To(Equal(1)) @@ -335,9 +332,9 @@ var _ = Describe("concreteApplier", func() { It("returns an error when deleting the source blobs fails", func() { job := buildJob() - jobApplier.DeleteSourceBlobsReturns(errors.New("boom!")) + jobApplier.DeleteSourceBlobsReturns(errors.New("boom")) - err := applier.Apply(&fakeas.FakeApplySpec{JobResults: []models.Job{job}}) + err := agentApplier.Apply(&fakeas.FakeApplySpec{JobResults: []models.Job{job}}) Expect(err).To(HaveOccurred()) Expect(jobApplier.DeleteSourceBlobsCallCount()).To(Equal(1)) diff --git a/agent/applier/jobs/rendered_job_applier_test.go b/agent/applier/jobs/rendered_job_applier_test.go index 38a1cd940..edde59738 100644 --- a/agent/applier/jobs/rendered_job_applier_test.go +++ b/agent/applier/jobs/rendered_job_applier_test.go @@ -2,13 +2,12 @@ package jobs_test import ( "errors" - "io" "os" - . "github.com/cloudfoundry/bosh-agent/agent/applier/jobs" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "github.com/cloudfoundry/bosh-agent/agent/applier/jobs" "github.com/cloudfoundry/bosh-agent/agent/applier/models" "github.com/cloudfoundry/bosh-agent/settings/directories" @@ -32,7 +31,7 @@ var _ = Describe("renderedJobApplier", func() { packageApplierProvider *fakepackages.FakeApplierProvider blobstore *fakeblobdelegator.FakeBlobstoreDelegator fs *fakesys.FakeFileSystem - applier Applier + applier jobs.Applier fixPermissions *fakeFixer ) @@ -46,7 +45,7 @@ var _ = Describe("renderedJobApplier", func() { dirProvider := directories.NewProvider("/fakebasedir") fixPermissions = &fakeFixer{} - applier = NewRenderedJobApplier( + applier = jobs.NewRenderedJobApplier( blobstore, dirProvider, jobsBc, @@ -378,12 +377,13 @@ var _ = Describe("renderedJobApplier", func() { It("adds job to the job supervisor", func() { job, bundle := buildJob(jobsBc) - fs.WriteFileString("/path/to/job/monit", "some conf") + err := fs.WriteFileString("/path/to/job/monit", "some conf") + Expect(err).NotTo(HaveOccurred()) fs.SetGlob("/path/to/job/*.monit", []string{"/path/to/job/subjob.monit"}) bundle.GetDirPath = "/path/to/job" - err := applier.Configure(job, 0) + err = applier.Configure(job, 0) Expect(err).ToNot(HaveOccurred()) Expect(len(jobSupervisor.AddJobArgs)).To(Equal(2)) @@ -535,16 +535,6 @@ func (f *fakeFixer) Fix(fs boshsys.FileSystem, path, user, group string) error { return f.fakeFixError } -type unsupportedAlgo struct{} - -func (unsupportedAlgo) Compare(algo boshcrypto.Algorithm) int { - return -1 -} - -func (unsupportedAlgo) CreateDigest(reader io.Reader) (boshcrypto.Digest, error) { - return boshcrypto.MultipleDigest{}, nil -} - func buildJob(bc *fakebc.FakeBundleCollection) (models.Job, *fakebc.FakeBundle) { uuidGen := boshuuid.NewGenerator() uuid, err := uuidGen.Generate() diff --git a/agent/applier/models/job_test.go b/agent/applier/models/job_test.go index 9bfc1091f..61d9fd1ff 100644 --- a/agent/applier/models/job_test.go +++ b/agent/applier/models/job_test.go @@ -4,12 +4,13 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "os" + . "github.com/cloudfoundry/bosh-agent/agent/applier/models" "github.com/cloudfoundry/bosh-agent/settings/directories" "github.com/cloudfoundry/bosh-utils/crypto" "github.com/cloudfoundry/bosh-utils/system/fakes" fakesys "github.com/cloudfoundry/bosh-utils/system/fakes" - "os" "errors" ) diff --git a/agent/applier/packages/compiled_package_applier_test.go b/agent/applier/packages/compiled_package_applier_test.go index 18ca23b91..078bf3669 100644 --- a/agent/applier/packages/compiled_package_applier_test.go +++ b/agent/applier/packages/compiled_package_applier_test.go @@ -38,7 +38,7 @@ func buildPkg(bc *fakebc.FakeBundleCollection) (models.Package, *fakebc.FakeBund return pkg, bundle } -func init() { +func init() { //nolint:funlen,gochecknoinits Describe("compiledPackageApplier", func() { var ( packagesBc *fakebc.FakeBundleCollection @@ -350,7 +350,6 @@ func init() { ItReturnsErrors() }) - }) }) } diff --git a/agent/blobstore/cascading_blobstore_test.go b/agent/blobstore/cascading_blobstore_test.go index a9e6db81f..1c0749090 100644 --- a/agent/blobstore/cascading_blobstore_test.go +++ b/agent/blobstore/cascading_blobstore_test.go @@ -275,7 +275,7 @@ var _ = Describe("cascadingBlobstore", func() { blobManagers = append(blobManagers, blobManager) } - index := rand.Intn(10) + index := rand.Intn(10) //nolint:gosec blobManagers[index].BlobExistsReturns(true) blobManagers[index].GetPathReturns("/path/to-copy/of-blob", nil) }) @@ -295,7 +295,7 @@ var _ = Describe("cascadingBlobstore", func() { blobManagers = append(blobManagers, blobManager) } - index := rand.Intn(10) + index := rand.Intn(10) //nolint:gosec blobManagers[index].BlobExistsReturns(true) blobManagers[index].GetPathReturns("", errors.New("disaster")) }) @@ -359,7 +359,7 @@ var _ = Describe("cascadingBlobstore", func() { blobManagers = append(blobManagers, blobManager) } - blobManager = blobManagers[rand.Intn(10)] + blobManager = blobManagers[rand.Intn(10)] //nolint:gosec blobManager.BlobExistsReturns(true) }) diff --git a/agent/bootonce/start_manager.go b/agent/bootonce/start_manager.go index 3d064514c..5c4a910df 100644 --- a/agent/bootonce/start_manager.go +++ b/agent/bootonce/start_manager.go @@ -60,7 +60,3 @@ func (r *StartManager) persistentBootoncePath() string { func (r *StartManager) tmpfsBootoncePath() string { return filepath.Join(r.dirProvider.CanRestartDir(), BootonceFileName) } - -func touch(fs boshsys.FileSystem, path string) error { - return fs.WriteFile(path, nil) -} diff --git a/agent/bootonce/start_manager_test.go b/agent/bootonce/start_manager_test.go index 769510739..0ad3f7e51 100644 --- a/agent/bootonce/start_manager_test.go +++ b/agent/bootonce/start_manager_test.go @@ -51,7 +51,8 @@ var _ = Describe("checking if the agent can be booted", func() { Context("when it is booting subsequent times", func() { BeforeEach(func() { - startManager.RegisterStart() + err := startManager.RegisterStart() + Expect(err).NotTo(HaveOccurred()) }) It("allows the agent to boot", func() { diff --git a/agent/bootstrap_test.go b/agent/bootstrap_test.go index e6b36115b..ee9ea7077 100644 --- a/agent/bootstrap_test.go +++ b/agent/bootstrap_test.go @@ -9,10 +9,10 @@ import ( "path/filepath" "time" - . "github.com/cloudfoundry/bosh-agent/agent" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "github.com/cloudfoundry/bosh-agent/agent" "github.com/cloudfoundry/bosh-agent/agent/applier/applyspec" "github.com/cloudfoundry/bosh-agent/agent/applier/applyspec/fakes" fakedevicepathresolver "github.com/cloudfoundry/bosh-agent/infrastructure/devicepathresolver/fakes" @@ -90,7 +90,7 @@ var _ = Describe("bootstrap", func() { }) bootstrap := func() error { - return NewBootstrap(platform, dirProvider, settingsService, specService, logger).Run() + return agent.NewBootstrap(platform, dirProvider, settingsService, specService, logger).Run() } It("sets up runtime configuration", func() { @@ -268,8 +268,7 @@ var _ = Describe("bootstrap", func() { }) It("sets up ephemeral disk", func() { - var swapSize uint64 - swapSize = 2048 + var swapSize uint64 = 2048 settingsService.Settings.Env.Bosh.SwapSizeInMB = &swapSize settingsService.Settings.Disks = boshsettings.Disks{ Ephemeral: "fake-ephemeral-disk-setting", @@ -553,9 +552,10 @@ var _ = Describe("bootstrap", func() { }) It("removes development tools", func() { - platform.GetFs().WriteFileString(path.Join(dirProvider.EtcDir(), "dev_tools_file_list"), "/usr/bin/gfortran") + err := platform.GetFs().WriteFileString(path.Join(dirProvider.EtcDir(), "dev_tools_file_list"), "/usr/bin/gfortran") + Expect(err).NotTo(HaveOccurred()) - err := bootstrap() + err = bootstrap() Expect(err).NotTo(HaveOccurred()) Expect(platform.RemoveDevToolsCallCount()).To(Equal(1)) Expect(platform.RemoveDevToolsArgsForCall(0)).To(Equal( @@ -579,7 +579,8 @@ var _ = Describe("bootstrap", func() { Context("and the static libraries path exists", func() { BeforeEach(func() { - platform.GetFs().WriteFileString(path.Join(dirProvider.EtcDir(), "static_libraries_list"), "/usr/lib/libsupp.a") + err := platform.GetFs().WriteFileString(path.Join(dirProvider.EtcDir(), "static_libraries_list"), "/usr/lib/libsupp.a") + Expect(err).NotTo(HaveOccurred()) }) It("removes static libraries", func() { @@ -691,7 +692,7 @@ var _ = Describe("bootstrap", func() { Context("when the disk associations are not provided as attached disks", func() { BeforeEach(func() { settingsService.PersistentDiskSettings = map[string]boshsettings.DiskSettings{} - settingsService.GetPersistentDiskSettingsError = errors.New("Disk not found") + settingsService.GetPersistentDiskSettingsError = errors.New("disk not found") }) It("returns an error", func() { @@ -778,7 +779,8 @@ var _ = Describe("bootstrap", func() { diskCid := "i-am-a-disk-cid" managedDiskSettingsPath = filepath.Join(platform.GetDirProvider().BoshDir(), "managed_disk_settings.json") - fileSystem.WriteFile(managedDiskSettingsPath, []byte(diskCid)) + err := fileSystem.WriteFile(managedDiskSettingsPath, []byte(diskCid)) + Expect(err).NotTo(HaveOccurred()) updateSettings := boshsettings.UpdateSettings{ DiskAssociations: []boshsettings.DiskAssociation{ @@ -792,7 +794,8 @@ var _ = Describe("bootstrap", func() { Expect(err).ToNot(HaveOccurred()) updateSettingsPath := filepath.Join(platform.GetDirProvider().BoshDir(), "update_settings.json") - fileSystem.WriteFile(updateSettingsPath, updateSettingsBytes) + err = fileSystem.WriteFile(updateSettingsPath, updateSettingsBytes) + Expect(err).NotTo(HaveOccurred()) }) Context("and the provided disk CID is the same", func() { @@ -819,14 +822,14 @@ var _ = Describe("bootstrap", func() { ID: "i-am-a-disk-cid", }, } - settingsService.GetPersistentDiskSettingsError = errors.New("Disk not found") + settingsService.GetPersistentDiskSettingsError = errors.New("disk not found") }) It("returns an error", func() { err := bootstrap() Expect(err).To(HaveOccurred()) - Expect(err.Error()).To(ContainSubstring("Attached disk disagrees with previous mount: Disk not found")) + Expect(err.Error()).To(ContainSubstring("Attached disk disagrees with previous mount: disk not found")) }) }) @@ -839,7 +842,7 @@ var _ = Describe("bootstrap", func() { Context("when reading the managed_disk_settings.json errors", func() { BeforeEach(func() { - fileSystem.RegisterReadFileError(managedDiskSettingsPath, errors.New("Oh noes!")) + fileSystem.RegisterReadFileError(managedDiskSettingsPath, errors.New("oh noes")) }) It("returns an error", func() { @@ -891,7 +894,8 @@ var _ = Describe("bootstrap", func() { Expect(err).ToNot(HaveOccurred()) updateSettingsPath := filepath.Join(platform.GetDirProvider().BoshDir(), "update_settings.json") - fileSystem.WriteFile(updateSettingsPath, updateSettingsBytes) + err = fileSystem.WriteFile(updateSettingsPath, updateSettingsBytes) + Expect(err).NotTo(HaveOccurred()) settingsService.PersistentDiskSettings = map[string]boshsettings.DiskSettings{ "vol-123": { @@ -907,16 +911,17 @@ var _ = Describe("bootstrap", func() { BeforeEach(func() { diskCid := "vol-123" managedDiskSettingsPath := filepath.Join(platform.GetDirProvider().BoshDir(), "managed_disk_settings.json") - fileSystem.WriteFile(managedDiskSettingsPath, []byte(diskCid)) + err := fileSystem.WriteFile(managedDiskSettingsPath, []byte(diskCid)) + Expect(err).NotTo(HaveOccurred()) - platform.AdjustPersistentDiskPartitioningReturns(errors.New("Grow partition fail")) + platform.AdjustPersistentDiskPartitioningReturns(errors.New("grow partition fail")) }) It("should return error", func() { err := bootstrap() Expect(err).To(HaveOccurred()) Expect(platform.AdjustPersistentDiskPartitioningCallCount()).To(Equal(1)) Expect(platform.MountPersistentDiskCallCount()).To(Equal(0)) - Expect(err.Error()).To(Equal("Mounting last mounted disk: Adjusting persistent disk partitioning: Grow partition fail")) + Expect(err.Error()).To(Equal("Mounting last mounted disk: Adjusting persistent disk partitioning: grow partition fail")) }) }) @@ -924,15 +929,16 @@ var _ = Describe("bootstrap", func() { BeforeEach(func() { diskCid := "vol-123" managedDiskSettingsPath := filepath.Join(platform.GetDirProvider().BoshDir(), "managed_disk_settings.json") - fileSystem.WriteFile(managedDiskSettingsPath, []byte(diskCid)) + err := fileSystem.WriteFile(managedDiskSettingsPath, []byte(diskCid)) + Expect(err).NotTo(HaveOccurred()) - platform.MountPersistentDiskReturns(errors.New("Mount fail")) + platform.MountPersistentDiskReturns(errors.New("mount fail")) }) It("should return error", func() { err := bootstrap() Expect(err).To(HaveOccurred()) Expect(platform.MountPersistentDiskCallCount()).To(Equal(1)) - Expect(err.Error()).To(Equal("Mounting last mounted disk: Mounting persistent disk: Mount fail")) + Expect(err.Error()).To(Equal("Mounting last mounted disk: Mounting persistent disk: mount fail")) }) }) @@ -940,7 +946,8 @@ var _ = Describe("bootstrap", func() { BeforeEach(func() { diskCid := "vol-123" managedDiskSettingsPath := filepath.Join(platform.GetDirProvider().BoshDir(), "managed_disk_settings.json") - fileSystem.WriteFile(managedDiskSettingsPath, []byte(diskCid)) + err := fileSystem.WriteFile(managedDiskSettingsPath, []byte(diskCid)) + Expect(err).NotTo(HaveOccurred()) platform.IsPersistentDiskMountableReturns(false, errors.New("boom")) }) @@ -978,7 +985,8 @@ var _ = Describe("bootstrap", func() { BeforeEach(func() { diskCid := "vol-123" managedDiskSettingsPath := filepath.Join(platform.GetDirProvider().BoshDir(), "managed_disk_settings.json") - fileSystem.WriteFile(managedDiskSettingsPath, []byte(diskCid)) + err := fileSystem.WriteFile(managedDiskSettingsPath, []byte(diskCid)) + Expect(err).NotTo(HaveOccurred()) }) It("mounts persistent disk", func() { @@ -1008,7 +1016,7 @@ var _ = Describe("bootstrap", func() { Context("and cannot find persistent disk", func() { BeforeEach(func() { - settingsService.GetPersistentDiskSettingsError = errors.New("Disk not found") + settingsService.GetPersistentDiskSettingsError = errors.New("disk not found") }) It("returns and error", func() { @@ -1025,7 +1033,7 @@ var _ = Describe("bootstrap", func() { fs *fakesys.FakeFileSystem platform boshplatform.Platform - boot Bootstrap + boot agent.Bootstrap defaultNetworkResolver boshsettings.DefaultNetworkResolver logger boshlog.Logger dirProvider boshdirs.Provider @@ -1105,7 +1113,8 @@ var _ = Describe("bootstrap", func() { logger = boshlog.NewLogger(boshlog.LevelNone) kernelIPv6 := boshnet.NewKernelIPv6Impl(fs, runner, logger) fakeMACAddressDetector = &netfakes.FakeMACAddressDetector{} - fs.WriteFileString("/etc/resolv.conf", "8.8.8.8 4.4.4.4") + err := fs.WriteFileString("/etc/resolv.conf", "8.8.8.8 4.4.4.4") + Expect(err).NotTo(HaveOccurred()) ubuntuNetManager := boshnet.NewUbuntuNetManager(fs, runner, ipResolver, fakeMACAddressDetector, interfaceConfigurationCreator, interfaceAddrsProvider, dnsValidator, arping, kernelIPv6, logger) ubuntuCertManager := boshcert.NewUbuntuCertManager(fs, runner, 1, logger) @@ -1146,7 +1155,8 @@ var _ = Describe("bootstrap", func() { JustBeforeEach(func() { var settings boshsettings.Settings - json.Unmarshal([]byte(settingsJSON), &settings) + err := json.Unmarshal([]byte(settingsJSON), &settings) + Expect(err).NotTo(HaveOccurred()) settingsSource := fakeinf.FakeSettingsSource{ PublicKey: "123", @@ -1160,7 +1170,7 @@ var _ = Describe("bootstrap", func() { logger, ) - boot = NewBootstrap( + boot = agent.NewBootstrap( platform, dirProvider, settingsService, @@ -1198,7 +1208,7 @@ var _ = Describe("bootstrap", func() { Context("and a single physical network interface exists", func() { BeforeEach(func() { - stubInterfaces([][]string{[]string{"eth0", "aa:bb:cc"}}) + stubInterfaces([][]string{{"eth0", "aa:bb:cc"}}) interfaceAddrsProvider.GetInterfaceAddresses = []boship.InterfaceAddress{ boship.NewSimpleInterfaceAddress("eth0", "2.2.2.2"), } @@ -1212,7 +1222,7 @@ var _ = Describe("bootstrap", func() { Context("and extra physical network interfaces exist", func() { BeforeEach(func() { - stubInterfaces([][]string{[]string{"eth0", "aa:bb:cc"}, []string{"eth1", "aa:bb:dd"}}) + stubInterfaces([][]string{{"eth0", "aa:bb:cc"}, {"eth1", "aa:bb:dd"}}) interfaceAddrsProvider.GetInterfaceAddresses = []boship.InterfaceAddress{ boship.NewSimpleInterfaceAddress("eth0", "2.2.2.2"), } @@ -1253,7 +1263,7 @@ var _ = Describe("bootstrap", func() { Context("and a single physical network interface exists", func() { BeforeEach(func() { - stubInterfaces([][]string{[]string{"eth0", "aa:bb:cc"}}) + stubInterfaces([][]string{{"eth0", "aa:bb:cc"}}) interfaceAddrsProvider.GetInterfaceAddresses = []boship.InterfaceAddress{ boship.NewSimpleInterfaceAddress("eth0", "2.2.2.2"), } @@ -1267,7 +1277,7 @@ var _ = Describe("bootstrap", func() { Context("and extra physical network interfaces exist", func() { BeforeEach(func() { - stubInterfaces([][]string{[]string{"eth0", "aa:bb:cc"}, []string{"eth1", "aa:bb:dd"}}) + stubInterfaces([][]string{{"eth0", "aa:bb:cc"}, {"eth1", "aa:bb:dd"}}) interfaceAddrsProvider.GetInterfaceAddresses = []boship.InterfaceAddress{ boship.NewSimpleInterfaceAddress("eth0", "2.2.2.2"), } @@ -1312,7 +1322,7 @@ var _ = Describe("bootstrap", func() { Context("and a single physical network interface exists", func() { BeforeEach(func() { - stubInterfaces([][]string{[]string{"eth0", "aa:bb:cc"}}) + stubInterfaces([][]string{{"eth0", "aa:bb:cc"}}) }) It("raises an error", func() { @@ -1324,7 +1334,7 @@ var _ = Describe("bootstrap", func() { Context("and two physical network interfaces with matching MAC addresses exist", func() { BeforeEach(func() { - stubInterfaces([][]string{[]string{"eth0", "aa:bb:cc"}, []string{"eth1", "aa:bb:dd"}}) + stubInterfaces([][]string{{"eth0", "aa:bb:cc"}, {"eth1", "aa:bb:dd"}}) interfaceAddrsProvider.GetInterfaceAddresses = []boship.InterfaceAddress{ boship.NewSimpleInterfaceAddress("eth0", "2.2.2.2"), boship.NewSimpleInterfaceAddress("eth1", "3.3.3.3"), diff --git a/agent/compiler/concrete_compiler_test.go b/agent/compiler/concrete_compiler_test.go index 7dad8863b..45d4cc519 100644 --- a/agent/compiler/concrete_compiler_test.go +++ b/agent/compiler/concrete_compiler_test.go @@ -64,7 +64,7 @@ func getCompileArgs() (Package, []boshmodels.Package) { return pkg, pkgDeps } -func init() { +func init() { //nolint:funlen,gochecknoinits Describe("concreteCompiler", func() { var ( compiler Compiler @@ -95,8 +95,10 @@ func init() { new(fakebc.FakeClock), ) - fs.MkdirAll("/real-compile-dir", os.ModePerm) - fs.Symlink("/real-compile-dir", "/fake-compile-dir") + err := fs.MkdirAll("/real-compile-dir", os.ModePerm) + Expect(err).NotTo(HaveOccurred()) + err = fs.Symlink("/real-compile-dir", "/fake-compile-dir") + Expect(err).NotTo(HaveOccurred()) Expect(fs.WriteFileString("/tmp/compressed-compiled-package", "fake-contents")).ToNot(HaveOccurred()) }) @@ -276,7 +278,8 @@ func init() { BeforeEach(func() { compressor.DecompressFileToDirCallBack = func() { filename := "/fake-compile-dir/pkg_name/" + PackagingScriptName - fs.WriteFileString(filename, packagingScriptContents) + err := fs.WriteFileString(filename, packagingScriptContents) + Expect(err).NotTo(HaveOccurred()) } }) diff --git a/agent/compiler/concrete_compiler_windows_test.go b/agent/compiler/concrete_compiler_windows_test.go index e43d2910d..912b0fcac 100644 --- a/agent/compiler/concrete_compiler_windows_test.go +++ b/agent/compiler/concrete_compiler_windows_test.go @@ -19,7 +19,7 @@ import ( fakesys "github.com/cloudfoundry/bosh-utils/system/fakes" ) -func init() { +func init() { //nolint:gochecknoinits Describe("concreteCompiler", func() { var ( compiler Compiler @@ -52,7 +52,8 @@ func init() { fakeClock, ) - fs.MkdirAll("/fake-compile-dir", os.ModePerm) + err := fs.MkdirAll("/fake-compile-dir", os.ModePerm) + Expect(err).NotTo(HaveOccurred()) Expect(fs.WriteFileString("/tmp/compressed-compiled-package", "fake-contents")).ToNot(HaveOccurred()) }) diff --git a/agent/heartbeat_test.go b/agent/heartbeat_test.go index c78b7b738..ae70f152f 100644 --- a/agent/heartbeat_test.go +++ b/agent/heartbeat_test.go @@ -10,7 +10,7 @@ import ( boshvitals "github.com/cloudfoundry/bosh-agent/platform/vitals" ) -func init() { +func init() { //nolint:gochecknoinits Describe("Heartbeat", func() { Context("when all information is available to the heartbeat", func() { It("serializes heartbeat with all fields", func() { diff --git a/agent/httpblobprovider/blobstore_delegator/blobstore_delegator_test.go b/agent/httpblobprovider/blobstore_delegator/blobstore_delegator_test.go index 611fac8a3..7008afdce 100644 --- a/agent/httpblobprovider/blobstore_delegator/blobstore_delegator_test.go +++ b/agent/httpblobprovider/blobstore_delegator/blobstore_delegator_test.go @@ -2,6 +2,7 @@ package blobstore_delegator_test import ( "errors" + boshlog "github.com/cloudfoundry/bosh-utils/logger" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" diff --git a/agent/httpblobprovider/blobstore_http_client_test.go b/agent/httpblobprovider/blobstore_http_client_test.go index 290ff1643..9694ea5bd 100644 --- a/agent/httpblobprovider/blobstore_http_client_test.go +++ b/agent/httpblobprovider/blobstore_http_client_test.go @@ -1,16 +1,20 @@ package httpblobprovider_test import ( + "net/http" + . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "net/http" httpblobprovider "github.com/cloudfoundry/bosh-agent/agent/httpblobprovider" "github.com/cloudfoundry/bosh-agent/settings" boshcrypto "github.com/cloudfoundry/bosh-utils/crypto" ) -var certificate = `-----BEGIN CERTIFICATE----- +var _ = Describe("NewBlobstoreHTTPClient", func() { + var ( + options settings.Blobstore + certificate = `-----BEGIN CERTIFICATE----- MIIEOjCCAqKgAwIBAgIRALcJj7JFUaQ2sd4gwuIqILcwDQYJKoZIhvcNAQELBQAw JjEMMAoGA1UEBhMDVVNBMRYwFAYDVQQKEw1DbG91ZCBGb3VuZHJ5MB4XDTIxMDky OTE0MzM0NVoXDTIyMDkyOTE0MzM0NVowJjEMMAoGA1UEBhMDVVNBMRYwFAYDVQQK @@ -35,10 +39,6 @@ fJo3Mli9ryp1/HRECrSkEDE5zK2SsGbtuciYhA4ALVQB02EQSlhRYL9zXtfnq6d5 aMaUJX87g3h6U88UGBrIQZE9frYi97wpasdJqrZ8XuROhws3xznrPlM0Debv69/h Ia61hX5ccGHhfw1oXlPCqF8jPZgVJpSAv5nsthy9 -----END CERTIFICATE-----` - -var _ = Describe("NewBlobstoreHTTPClient", func() { - var ( - options settings.Blobstore ) BeforeEach(func() { diff --git a/agent/script/drain/concrete_script_test.go b/agent/script/drain/concrete_script_test.go index 708705341..4d8294245 100644 --- a/agent/script/drain/concrete_script_test.go +++ b/agent/script/drain/concrete_script_test.go @@ -76,7 +76,8 @@ var _ = Describe("ConcreteScript", func() { It("returns bool", func() { Expect(script.Exists()).To(BeFalse()) - fs.WriteFile("/fake/script", []byte{}) + err := fs.WriteFile("/fake/script", []byte{}) + Expect(err).NotTo(HaveOccurred()) Expect(script.Exists()).To(BeTrue()) }) }) diff --git a/agent/script/generic_script_test.go b/agent/script/generic_script_test.go index 8e9ee409c..b97696e95 100644 --- a/agent/script/generic_script_test.go +++ b/agent/script/generic_script_test.go @@ -7,10 +7,11 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "runtime" + boshscript "github.com/cloudfoundry/bosh-agent/agent/script" boshenv "github.com/cloudfoundry/bosh-agent/agent/script/pathenv" fakesys "github.com/cloudfoundry/bosh-utils/system/fakes" - "runtime" ) var _ = Describe("GenericScript", func() { @@ -66,7 +67,8 @@ var _ = Describe("GenericScript", func() { It("returns bool", func() { Expect(genericScript.Exists()).To(BeFalse()) - fs.WriteFile("/path-to-script", []byte{}) + err := fs.WriteFile("/path-to-script", []byte{}) + Expect(err).NotTo(HaveOccurred()) Expect(genericScript.Exists()).To(BeTrue()) }) }) diff --git a/agent/tarpath/detector_test.go b/agent/tarpath/detector_test.go index 6e29a8e8b..33a88be41 100644 --- a/agent/tarpath/detector_test.go +++ b/agent/tarpath/detector_test.go @@ -110,8 +110,9 @@ func writeTgz(path string, files []string) { defer tw.Close() for _, file := range files { - tw.WriteHeader(&tar.Header{ + err := tw.WriteHeader(&tar.Header{ Name: file, }) + Expect(err).NotTo(HaveOccurred()) } } diff --git a/agent/task/async_task_service_test.go b/agent/task/async_task_service_test.go index 533b1c894..42ac077e5 100644 --- a/agent/task/async_task_service_test.go +++ b/agent/task/async_task_service_test.go @@ -13,7 +13,7 @@ import ( fakeuuid "github.com/cloudfoundry/bosh-utils/uuid/fakes" ) -func init() { +func init() { //nolint:funlen,gochecknoinits Describe("asyncTaskService", func() { var ( uuidGen *fakeuuid.FakeGenerator @@ -210,10 +210,12 @@ func init() { Expect(task.ID).To(Equal("fake-uuid")) Expect(task.State).To(Equal(StateRunning)) - task.Func() + _, err = task.Func() + Expect(err).NotTo(HaveOccurred()) Expect(runFuncCalled).To(BeTrue()) - task.CancelFunc(task) + err = task.CancelFunc(task) + Expect(err).NotTo(HaveOccurred()) Expect(cancelFuncCalled).To(BeTrue()) task.EndFunc(task) @@ -244,10 +246,12 @@ func init() { Expect(task.ID).To(Equal("fake-task-id")) Expect(task.State).To(Equal(StateRunning)) - task.Func() + _, err := task.Func() + Expect(err).NotTo(HaveOccurred()) Expect(runFuncCalled).To(BeTrue()) - task.CancelFunc(task) + err = task.CancelFunc(task) + Expect(err).NotTo(HaveOccurred()) Expect(cancelFuncCalled).To(BeTrue()) task.EndFunc(task) diff --git a/agent/task/concrete_manager_test.go b/agent/task/concrete_manager_test.go index f28d39c64..154a417c3 100644 --- a/agent/task/concrete_manager_test.go +++ b/agent/task/concrete_manager_test.go @@ -12,7 +12,7 @@ import ( fakesys "github.com/cloudfoundry/bosh-utils/system/fakes" ) -func init() { +func init() { //nolint:gochecknoinits Describe("concreteManagerProvider", func() { Describe("NewManager", func() { It("returns manager with tasks.json as its tasks path", func() { diff --git a/agent/task/fakes/fake_manager.go b/agent/task/fakes/fake_manager.go index 8c24081aa..1d8a122cc 100644 --- a/agent/task/fakes/fake_manager.go +++ b/agent/task/fakes/fake_manager.go @@ -13,7 +13,7 @@ func NewFakeManager() *FakeManager { } func (m *FakeManager) GetInfos() ([]boshtask.Info, error) { - var taskInfos []boshtask.Info + taskInfos := make([]boshtask.Info, 0, len(m.taskIDToTaskInfo)) for _, taskInfo := range m.taskIDToTaskInfo { taskInfos = append(taskInfos, taskInfo) } diff --git a/agentclient/applyspec/apply_spec_test.go b/agentclient/applyspec/apply_spec_test.go index c21662e7b..aca8daa68 100644 --- a/agentclient/applyspec/apply_spec_test.go +++ b/agentclient/applyspec/apply_spec_test.go @@ -64,7 +64,7 @@ var _ = Describe("ApplySpec", func() { Expect(applySpecMap).To(Equal(map[string]interface{}{ "deployment": "fake-deployment-name", "name": "fake-instance-name", - "index": 0.0, //json.Unmarshal ultimately converts all ints to floats. type must be float for comparisons to work + "index": 0.0, // json.Unmarshal ultimately converts all ints to floats. type must be a float for comparisons to work "id": "this-is-a-node-id", "az": "this-is-an-availability-zone", "packages": map[string]interface{}{ diff --git a/app/app_test.go b/app/app_test.go index e280a51f4..3dba4ceb2 100644 --- a/app/app_test.go +++ b/app/app_test.go @@ -16,7 +16,7 @@ import ( fakesys "github.com/cloudfoundry/bosh-utils/system/fakes" ) -func init() { +func init() { //nolint:funlen,gochecknoinits Describe("App", func() { var ( baseDir string @@ -109,12 +109,12 @@ func init() { } }` - err = ioutil.WriteFile(settingsPath, []byte(settingsJSON), 0640) + err = ioutil.WriteFile(settingsPath, []byte(settingsJSON), 0640) //nolint:gosec Expect(err).ToNot(HaveOccurred()) }) JustBeforeEach(func() { - err := ioutil.WriteFile(agentConfPath, []byte(agentConfJSON), 0640) + err := ioutil.WriteFile(agentConfPath, []byte(agentConfJSON), 0640) //nolint:gosec Expect(err).ToNot(HaveOccurred()) logger := boshlog.NewLogger(boshlog.LevelNone) @@ -126,7 +126,8 @@ func init() { }) AfterEach(func() { - os.RemoveAll(baseDir) + err := os.RemoveAll(baseDir) + Expect(err).NotTo(HaveOccurred()) }) It("Sets up device path resolver on platform specific to infrastructure", func() { @@ -191,9 +192,11 @@ func init() { Context("when stemcell version and sha files are present", func() { It("should print out the stemcell version and sha in the logs", func() { - fakeFs.WriteFileString(stemcellVersionFilePath, "version-blah") - fakeFs.WriteFileString(stemcellSha1FilePath, "sha1-blah") - app.Setup(opts) + err := fakeFs.WriteFileString(stemcellVersionFilePath, "version-blah") + Expect(err).NotTo(HaveOccurred()) + err = fakeFs.WriteFileString(stemcellSha1FilePath, "sha1-blah") + Expect(err).NotTo(HaveOccurred()) + app.Setup(opts) //nolint:errcheck _, loggedString, _ := logger.InfoArgsForCall(0) Expect(loggedString).To(ContainSubstring("Running on stemcell version 'version-blah' (git: sha1-blah)")) }) @@ -201,8 +204,9 @@ func init() { Context("when stemcell version file is NOT present", func() { It("should print out the sha in the logs", func() { - fakeFs.WriteFileString(stemcellSha1FilePath, "sha1-blah") - app.Setup(opts) + err := fakeFs.WriteFileString(stemcellSha1FilePath, "sha1-blah") + Expect(err).NotTo(HaveOccurred()) + app.Setup(opts) //nolint:errcheck _, loggedString, _ := logger.InfoArgsForCall(0) Expect(loggedString).To(ContainSubstring("Running on stemcell version '?' (git: sha1-blah)")) }) @@ -210,9 +214,9 @@ func init() { Context("when sha version file is NOT present", func() { It("should print out the stemcell version in the logs", func() { - fakeFs.WriteFileString(stemcellVersionFilePath, "version-blah") - app.Setup(opts) - + err := fakeFs.WriteFileString(stemcellVersionFilePath, "version-blah") + Expect(err).NotTo(HaveOccurred()) + app.Setup(opts) //nolint:errcheck _, loggedString, _ := logger.InfoArgsForCall(0) Expect(loggedString).To(ContainSubstring("Running on stemcell version 'version-blah' (git: ?)")) }) @@ -220,10 +224,11 @@ func init() { Context("when stemcell version file is empty", func() { It("should print out the sha in the logs", func() { - fakeFs.WriteFileString(stemcellVersionFilePath, "") - fakeFs.WriteFileString(stemcellSha1FilePath, "sha1-blah") - - app.Setup(opts) + err := fakeFs.WriteFileString(stemcellVersionFilePath, "") + Expect(err).NotTo(HaveOccurred()) + err = fakeFs.WriteFileString(stemcellSha1FilePath, "sha1-blah") + Expect(err).NotTo(HaveOccurred()) + app.Setup(opts) //nolint:errcheck _, loggedString, _ := logger.InfoArgsForCall(0) Expect(loggedString).To(ContainSubstring("Running on stemcell version '?' (git: sha1-blah)")) }) @@ -231,9 +236,11 @@ func init() { Context("when sha version file is empty", func() { It("should print out the stemcell version in the logs", func() { - fakeFs.WriteFileString(stemcellVersionFilePath, "version-blah") - fakeFs.WriteFileString(stemcellSha1FilePath, "") - app.Setup(opts) + err := fakeFs.WriteFileString(stemcellVersionFilePath, "version-blah") + Expect(err).NotTo(HaveOccurred()) + err = fakeFs.WriteFileString(stemcellSha1FilePath, "") + Expect(err).NotTo(HaveOccurred()) + app.Setup(opts) //nolint:errcheck _, loggedString, _ := logger.InfoArgsForCall(0) Expect(loggedString).To(ContainSubstring("Running on stemcell version 'version-blah' (git: ?)")) }) @@ -241,7 +248,7 @@ func init() { Context("when stemcell version and sha files are NOT present", func() { It("should print unknown version and sha in the logs", func() { - app.Setup(opts) + app.Setup(opts) //nolint:errcheck _, loggedString, _ := logger.InfoArgsForCall(0) Expect(loggedString).To(ContainSubstring("Running on stemcell version '?' (git: ?)")) }) diff --git a/app/config_test.go b/app/config_test.go index d2ffaacde..2ee84c690 100644 --- a/app/config_test.go +++ b/app/config_test.go @@ -19,7 +19,7 @@ var _ = Describe("LoadConfigFromPath", func() { }) It("returns populates config", func() { - fs.WriteFileString("/fake-config.conf", `{ + err := fs.WriteFileString("/fake-config.conf", `{ "Platform": { "Linux": { "UseDefaultTmpDir": true, @@ -65,6 +65,7 @@ var _ = Describe("LoadConfigFromPath", func() { } } }`) + Expect(err).NotTo(HaveOccurred()) config, err := LoadConfigFromPath(fs, "/fake-config.conf") Expect(err).ToNot(HaveOccurred()) @@ -124,49 +125,53 @@ var _ = Describe("LoadConfigFromPath", func() { }) It("returns error if file cannot be parsed", func() { - fs.WriteFileString("/fake-config.conf", `fake-invalid-json`) + err := fs.WriteFileString("/fake-config.conf", `fake-invalid-json`) + Expect(err).NotTo(HaveOccurred()) - _, err := LoadConfigFromPath(fs, "/fake-config.conf") + _, err = LoadConfigFromPath(fs, "/fake-config.conf") Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("invalid character")) }) It("returns an error when the source options type is unknown", func() { - fs.WriteFileString("/fake-config.conf", `{ + err := fs.WriteFileString("/fake-config.conf", `{ "Infrastructure": { "Settings": { "Sources": [{ "Type": "fake-type" }] } } }`) + Expect(err).NotTo(HaveOccurred()) - _, err := LoadConfigFromPath(fs, "/fake-config.conf") + _, err = LoadConfigFromPath(fs, "/fake-config.conf") Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("Unknown source type 'fake-type'")) }) It("returns an error when the source options do not have type", func() { - fs.WriteFileString("/fake-config.conf", `{ + err := fs.WriteFileString("/fake-config.conf", `{ "Infrastructure": { "Settings": { "Sources": [{ }] } } }`) + Expect(err).NotTo(HaveOccurred()) - _, err := LoadConfigFromPath(fs, "/fake-config.conf") + _, err = LoadConfigFromPath(fs, "/fake-config.conf") Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("Missing source type")) }) It("returns empty settings sources if no sources are defined", func() { - fs.WriteFileString("/fake-config.conf", `{ + err := fs.WriteFileString("/fake-config.conf", `{ "Infrastructure": { "Settings": { "Sources": [] } } }`) + Expect(err).NotTo(HaveOccurred()) config, err := LoadConfigFromPath(fs, "/fake-config.conf") Expect(err).ToNot(HaveOccurred()) @@ -178,19 +183,20 @@ var _ = Describe("LoadConfigFromPath", func() { }) It("returns an error when the source options do not have type", func() { - fs.WriteFileString("/fake-config.conf", `{ + err := fs.WriteFileString("/fake-config.conf", `{ "Infrastructure": { "Settings": { "Sources": 1 } } }`) + Expect(err).NotTo(HaveOccurred()) - _, err := LoadConfigFromPath(fs, "/fake-config.conf") + _, err = LoadConfigFromPath(fs, "/fake-config.conf") Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("Unmarshalling sources")) }) It("returns errors if failed to decode HTTP source options", func() { - fs.WriteFileString("/fake-config.conf", `{ + err := fs.WriteFileString("/fake-config.conf", `{ "Infrastructure": { "Settings": { "Sources": [{ @@ -200,14 +206,15 @@ var _ = Describe("LoadConfigFromPath", func() { } } }`) + Expect(err).NotTo(HaveOccurred()) - _, err := LoadConfigFromPath(fs, "/fake-config.conf") + _, err = LoadConfigFromPath(fs, "/fake-config.conf") Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("Unmarshalling source type 'HTTP'")) }) It("returns errors if failed to decode InstanceMetadata source options", func() { - fs.WriteFileString("/fake-config.conf", `{ + err := fs.WriteFileString("/fake-config.conf", `{ "Infrastructure": { "Settings": { "Sources": [{ @@ -217,14 +224,15 @@ var _ = Describe("LoadConfigFromPath", func() { } } }`) + Expect(err).NotTo(HaveOccurred()) - _, err := LoadConfigFromPath(fs, "/fake-config.conf") + _, err = LoadConfigFromPath(fs, "/fake-config.conf") Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("Unmarshalling source type 'InstanceMetadata'")) }) It("returns errors if failed to decode ConfigDrive source options", func() { - fs.WriteFileString("/fake-config.conf", `{ + err := fs.WriteFileString("/fake-config.conf", `{ "Infrastructure": { "Settings": { "Sources": [{ @@ -234,14 +242,15 @@ var _ = Describe("LoadConfigFromPath", func() { } } }`) + Expect(err).NotTo(HaveOccurred()) - _, err := LoadConfigFromPath(fs, "/fake-config.conf") + _, err = LoadConfigFromPath(fs, "/fake-config.conf") Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("Unmarshalling source type 'ConfigDrive'")) }) It("returns errors if failed to decode File source options", func() { - fs.WriteFileString("/fake-config.conf", `{ + err := fs.WriteFileString("/fake-config.conf", `{ "Infrastructure": { "Settings": { "Sources": [{ @@ -251,14 +260,15 @@ var _ = Describe("LoadConfigFromPath", func() { } } }`) + Expect(err).NotTo(HaveOccurred()) - _, err := LoadConfigFromPath(fs, "/fake-config.conf") + _, err = LoadConfigFromPath(fs, "/fake-config.conf") Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("Unmarshalling source type 'File'")) }) It("returns errors if failed to decode CDROM source options", func() { - fs.WriteFileString("/fake-config.conf", `{ + err := fs.WriteFileString("/fake-config.conf", `{ "Infrastructure": { "Settings": { "Sources": [{ @@ -268,8 +278,9 @@ var _ = Describe("LoadConfigFromPath", func() { } } }`) + Expect(err).NotTo(HaveOccurred()) - _, err := LoadConfigFromPath(fs, "/fake-config.conf") + _, err = LoadConfigFromPath(fs, "/fake-config.conf") Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("Unmarshalling source type 'CDROM'")) }) diff --git a/handler/common_event_format_test.go b/handler/common_event_format_test.go index db9eff5b5..531ae391b 100644 --- a/handler/common_event_format_test.go +++ b/handler/common_event_format_test.go @@ -1,11 +1,12 @@ package handler_test import ( + "net/http" + "net/http/httptest" + "github.com/cloudfoundry/bosh-agent/handler" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "net/http" - "net/http/httptest" ) var _ = Describe("CommonEventFormat", func() { diff --git a/infrastructure/agentlogger/signalable_logger_test.go b/infrastructure/agentlogger/signalable_logger_test.go index 3882b6330..396df4066 100644 --- a/infrastructure/agentlogger/signalable_logger_test.go +++ b/infrastructure/agentlogger/signalable_logger_test.go @@ -11,8 +11,8 @@ import ( . "github.com/onsi/gomega" ) -var _ = Describe("Signalable logger debug", func() { - Describe("when SIGSEGV is recieved", func() { +var _ = Describe("Signal-able logger debug", func() { + Describe("when SIGSEGV is received", func() { It("it dumps all goroutines to the given buffer", func() { outBuf := new(bytes.Buffer) signalChannel := make(chan os.Signal, 1) diff --git a/infrastructure/config_drive_metadata_service_test.go b/infrastructure/config_drive_metadata_service_test.go index 710609486..71b1d505d 100644 --- a/infrastructure/config_drive_metadata_service_test.go +++ b/infrastructure/config_drive_metadata_service_test.go @@ -19,7 +19,7 @@ import ( var _ = Describe("ConfigDriveMetadataService", describeConfigDriveMetadataService) -func describeConfigDriveMetadataService() { +func describeConfigDriveMetadataService() { //nolint:funlen var ( metadataService MetadataService resolver *fakeinf.FakeDNSResolver @@ -65,7 +65,7 @@ func describeConfigDriveMetadataService() { logger, ) - userdataContents := fmt.Sprintf(`{"server":{"name":"fake-server-name"},"registry":{"endpoint":"fake-registry-endpoint"}}`) + userdataContents := `{"server":{"name":"fake-server-name"},"registry":{"endpoint":"fake-registry-endpoint"}}` metadataServiceFileContents[1] = []byte(userdataContents) metadata := MetadataContentsType{ diff --git a/infrastructure/devicepathresolver/id_device_path_resolver_test.go b/infrastructure/devicepathresolver/id_device_path_resolver_test.go index 825aeb6e9..fdd377ba8 100644 --- a/infrastructure/devicepathresolver/id_device_path_resolver_test.go +++ b/infrastructure/devicepathresolver/id_device_path_resolver_test.go @@ -38,7 +38,7 @@ var _ = Describe("IDDevicePathResolver", func() { Describe("GetRealDevicePath", func() { It("refreshes udev", func() { - pathResolver.GetRealDevicePath(diskSettings) + pathResolver.GetRealDevicePath(diskSettings) //nolint:errcheck Expect(udev.Triggered).To(Equal(true)) Expect(udev.Settled).To(Equal(true)) }) diff --git a/infrastructure/devicepathresolver/iscsi_device_path_resolver_test.go b/infrastructure/devicepathresolver/iscsi_device_path_resolver_test.go index 567feccbf..70b747bc1 100644 --- a/infrastructure/devicepathresolver/iscsi_device_path_resolver_test.go +++ b/infrastructure/devicepathresolver/iscsi_device_path_resolver_test.go @@ -55,7 +55,8 @@ var _ = Describe("iscsiDevicePathResolver", func() { // Setup the managed_disk_settings.json managedDiskSettingsPath = filepath.Join(dirProvider.BoshDir(), "managed_disk_settings.json") - fs.WriteFileString(managedDiskSettingsPath, "12345678") + err := fs.WriteFileString(managedDiskSettingsPath, "12345678") + Expect(err).NotTo(HaveOccurred()) }) Describe("GetRealDevicePath", func() { diff --git a/infrastructure/devicepathresolver/mapped_device_path_resolver_test.go b/infrastructure/devicepathresolver/mapped_device_path_resolver_test.go index cf18fba16..f5945b070 100644 --- a/infrastructure/devicepathresolver/mapped_device_path_resolver_test.go +++ b/infrastructure/devicepathresolver/mapped_device_path_resolver_test.go @@ -44,9 +44,12 @@ var _ = Describe("mappedDevicePathResolver", func() { Context("when a matching /dev/xvdX device is found", func() { BeforeEach(func() { - fs.WriteFile("/dev/xvda", []byte{}) - fs.WriteFile("/dev/vda", []byte{}) - fs.WriteFile("/dev/sda", []byte{}) + err := fs.WriteFile("/dev/xvda", []byte{}) + Expect(err).NotTo(HaveOccurred()) + err = fs.WriteFile("/dev/vda", []byte{}) + Expect(err).NotTo(HaveOccurred()) + err = fs.WriteFile("/dev/sda", []byte{}) + Expect(err).NotTo(HaveOccurred()) }) It("returns the match", func() { @@ -59,8 +62,10 @@ var _ = Describe("mappedDevicePathResolver", func() { Context("when a matching /dev/vdX device is found", func() { BeforeEach(func() { - fs.WriteFile("/dev/vda", []byte{}) - fs.WriteFile("/dev/sda", []byte{}) + err := fs.WriteFile("/dev/vda", []byte{}) + Expect(err).NotTo(HaveOccurred()) + err = fs.WriteFile("/dev/sda", []byte{}) + Expect(err).NotTo(HaveOccurred()) }) It("returns the match", func() { @@ -73,7 +78,8 @@ var _ = Describe("mappedDevicePathResolver", func() { Context("when a matching /dev/sdX device is found", func() { BeforeEach(func() { - fs.WriteFile("/dev/sda", []byte{}) + err := fs.WriteFile("/dev/sda", []byte{}) + Expect(err).NotTo(HaveOccurred()) }) It("returns the match", func() { @@ -88,7 +94,8 @@ var _ = Describe("mappedDevicePathResolver", func() { Context("when the timeout has not expired", func() { BeforeEach(func() { time.AfterFunc(time.Second, func() { - fs.WriteFile("/dev/xvda", []byte{}) + err := fs.WriteFile("/dev/xvda", []byte{}) + Expect(err).NotTo(HaveOccurred()) }) }) @@ -113,7 +120,8 @@ var _ = Describe("mappedDevicePathResolver", func() { Context("when a path that never needs remapping is passed in", func() { Context("when path exists", func() { BeforeEach(func() { - fs.WriteFile("/dev/xvdba", []byte{}) + err := fs.WriteFile("/dev/xvdba", []byte{}) + Expect(err).NotTo(HaveOccurred()) diskSettings = boshsettings.DiskSettings{ Path: "/dev/xvdba", } diff --git a/infrastructure/devicepathresolver/scsi_id_device_path_resolver.go b/infrastructure/devicepathresolver/scsi_id_device_path_resolver.go index c30105709..4f4f8c6c1 100644 --- a/infrastructure/devicepathresolver/scsi_id_device_path_resolver.go +++ b/infrastructure/devicepathresolver/scsi_id_device_path_resolver.go @@ -67,7 +67,7 @@ func (idpr SCSIIDDevicePathResolver) GetRealDevicePath(diskSettings boshsettings time.Sleep(100 * time.Millisecond) - uuid := strings.Replace(diskSettings.DeviceID, "-", "", -1) + uuid := strings.ReplaceAll(diskSettings.DeviceID, "-", "") disks, err := idpr.fs.Glob("/dev/disk/by-id/*" + uuid) if err != nil { return "", false, bosherr.WrapError(err, "Could not list disks by id") diff --git a/infrastructure/devicepathresolver/scsi_id_device_path_resolver_test.go b/infrastructure/devicepathresolver/scsi_id_device_path_resolver_test.go index 243ed56ce..f76adf6b3 100644 --- a/infrastructure/devicepathresolver/scsi_id_device_path_resolver_test.go +++ b/infrastructure/devicepathresolver/scsi_id_device_path_resolver_test.go @@ -27,7 +27,7 @@ var _ = Describe("ScsiIDDevicePathResolver", func() { BeforeEach(func() { deviceID := "ab1b46b5-bf22-4332-bddd-12a05ea1a5fc" - id = strings.Replace(deviceID, "-", "", -1) + id = strings.ReplaceAll(deviceID, "-", "") fs = fakesys.NewFakeFileSystem() pathResolver = NewSCSIIDDevicePathResolver(500*time.Millisecond, fs, boshlog.NewLogger(boshlog.LevelNone)) diskSettings = boshsettings.DiskSettings{ diff --git a/infrastructure/devicepathresolver/scsi_volume_id_device_path_resolver_test.go b/infrastructure/devicepathresolver/scsi_volume_id_device_path_resolver_test.go index f48a32d93..348476488 100644 --- a/infrastructure/devicepathresolver/scsi_volume_id_device_path_resolver_test.go +++ b/infrastructure/devicepathresolver/scsi_volume_id_device_path_resolver_test.go @@ -42,7 +42,8 @@ var _ = Describe("SCSIVolumeIDDevicePathResolver", func() { Describe("GetRealDevicePath", func() { It("rescans the devices attached to the root disks scsi controller", func() { - resolver.GetRealDevicePath(diskSettings) + _, _, err := resolver.GetRealDevicePath(diskSettings) + Expect(err).NotTo(HaveOccurred()) scanContents, err := fs.ReadFileString("/sys/class/scsi_host/hostfake-host-id/scan") Expect(err).NotTo(HaveOccurred()) diff --git a/infrastructure/file_metadata_service_test.go b/infrastructure/file_metadata_service_test.go index fb0b6c84f..9a16d6bb0 100644 --- a/infrastructure/file_metadata_service_test.go +++ b/infrastructure/file_metadata_service_test.go @@ -34,8 +34,8 @@ var _ = Describe("FileMetadataService", func() { Describe("GetInstanceID", func() { Context("when metadata service file exists", func() { BeforeEach(func() { - metadataContents := `{"instance-id":"fake-instance-id"}` - fs.WriteFileString("fake-metadata-file-path", metadataContents) + err := fs.WriteFileString("fake-metadata-file-path", `{"instance-id":"fake-instance-id"}`) + Expect(err).NotTo(HaveOccurred()) }) It("returns instance id", func() { @@ -54,7 +54,8 @@ var _ = Describe("FileMetadataService", func() { Context("when metadata service file has invalid format", func() { BeforeEach(func() { - fs.WriteFileString("fake-metadata-file-path", "bad-json") + err := fs.WriteFileString("fake-metadata-file-path", "bad-json") + Expect(err).NotTo(HaveOccurred()) }) It("returns an error", func() { @@ -67,8 +68,8 @@ var _ = Describe("FileMetadataService", func() { Describe("GetServerName", func() { Context("when userdata file exists", func() { BeforeEach(func() { - userDataContents := `{"server":{"name":"fake-server-name"}}` - fs.WriteFileString("fake-userdata-file-path", userDataContents) + err := fs.WriteFileString("fake-userdata-file-path", `{"server":{"name":"fake-server-name"}}`) + Expect(err).NotTo(HaveOccurred()) }) It("returns server name", func() { @@ -96,7 +97,8 @@ var _ = Describe("FileMetadataService", func() { "network_2": {"type": "dynamic", "default": ["dns"], "dns": ["8.8.8.8"], "mac": "fake-mac-address-2"} } }` - fs.WriteFileString("fake-userdata-file-path", userDataContents) + err := fs.WriteFileString("fake-userdata-file-path", userDataContents) + Expect(err).NotTo(HaveOccurred()) networks, err := metadataService.GetNetworks() Expect(err).ToNot(HaveOccurred()) @@ -121,7 +123,8 @@ var _ = Describe("FileMetadataService", func() { It("returns a nil Networks if the settings are missing (from an old CPI version)", func() { userDataContents := `{}` - fs.WriteFileString("fake-userdata-file-path", userDataContents) + err := fs.WriteFileString("fake-userdata-file-path", userDataContents) + Expect(err).NotTo(HaveOccurred()) networks, err := metadataService.GetNetworks() Expect(err).ToNot(HaveOccurred()) @@ -146,8 +149,11 @@ var _ = Describe("FileMetadataService", func() { Describe("GetRegistryEndpoint", func() { Context("when metadata service file exists", func() { BeforeEach(func() { - userDataContents := `{"registry":{"endpoint":"fake-registry-endpoint"}}` - fs.WriteFileString("fake-userdata-file-path", userDataContents) + err := fs.WriteFileString( + "fake-userdata-file-path", + `{"registry":{"endpoint":"fake-registry-endpoint"}}`, + ) + Expect(err).NotTo(HaveOccurred()) }) It("returns registry endpoint", func() { @@ -176,7 +182,8 @@ var _ = Describe("FileMetadataService", func() { "mbus": "Agent-Mbus" }` - fs.WriteFileString("fake-userdata-file-path", userDataContents) + err := fs.WriteFileString("fake-userdata-file-path", userDataContents) + Expect(err).NotTo(HaveOccurred()) }) It("returns settings", func() { @@ -193,7 +200,8 @@ var _ = Describe("FileMetadataService", func() { "mbus": "Agent-Mbus" }` - fs.WriteFileString("fake-userdata-file-path", userDataContents) + err := fs.WriteFileString("fake-userdata-file-path", userDataContents) + Expect(err).NotTo(HaveOccurred()) }) It("returns error", func() { @@ -206,7 +214,8 @@ var _ = Describe("FileMetadataService", func() { Context("when metadata service file does not exist", func() { BeforeEach(func() { - fs.RemoveAll("fake-settings-file-path") + err := fs.RemoveAll("fake-settings-file-path") + Expect(err).NotTo(HaveOccurred()) }) It("returns error", func() { @@ -226,7 +235,8 @@ var _ = Describe("FileMetadataService", func() { "mbus": "Agent-Mbus" }` - fs.WriteFileString("fake-userdata-file-path", userDataContents) + err := fs.WriteFileString("fake-userdata-file-path", userDataContents) + Expect(err).NotTo(HaveOccurred()) }) It("returns error", func() { @@ -246,7 +256,8 @@ var _ = Describe("FileMetadataService", func() { Context("when file exists", func() { BeforeEach(func() { - fs.WriteFileString("fake-settings-file-path", ``) + err := fs.WriteFileString("fake-settings-file-path", ``) + Expect(err).NotTo(HaveOccurred()) }) It("returns true", func() { diff --git a/infrastructure/file_registry_test.go b/infrastructure/file_registry_test.go index bd92fbc05..645abced8 100644 --- a/infrastructure/file_registry_test.go +++ b/infrastructure/file_registry_test.go @@ -6,21 +6,20 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "github.com/cloudfoundry/bosh-agent/infrastructure" boshsettings "github.com/cloudfoundry/bosh-agent/settings" fakesys "github.com/cloudfoundry/bosh-utils/system/fakes" - - . "github.com/cloudfoundry/bosh-agent/infrastructure" ) var _ = Describe("FileRegistry", func() { var ( fs *fakesys.FakeFileSystem - fileRegistry Registry + fileRegistry infrastructure.Registry ) BeforeEach(func() { fs = fakesys.NewFakeFileSystem() - fileRegistry = NewFileRegistry("/fake-registry-file-path", fs) + fileRegistry = infrastructure.NewFileRegistry("/fake-registry-file-path", fs) }) Describe("GetSettings", func() { @@ -36,7 +35,8 @@ var _ = Describe("FileRegistry", func() { settingsJSON, err := json.Marshal(expectedSettings) Expect(err).ToNot(HaveOccurred()) - fs.WriteFile("/fake-registry-file-path", settingsJSON) + err = fs.WriteFile("/fake-registry-file-path", settingsJSON) + Expect(err).NotTo(HaveOccurred()) }) It("returns the settings", func() { diff --git a/infrastructure/file_settings_source_test.go b/infrastructure/file_settings_source_test.go index c869f99b6..07bec1d32 100644 --- a/infrastructure/file_settings_source_test.go +++ b/infrastructure/file_settings_source_test.go @@ -3,19 +3,19 @@ package infrastructure_test import ( "encoding/json" - boshlog "github.com/cloudfoundry/bosh-utils/logger" - fakesys "github.com/cloudfoundry/bosh-utils/system/fakes" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - . "github.com/cloudfoundry/bosh-agent/infrastructure" + "github.com/cloudfoundry/bosh-agent/infrastructure" boshsettings "github.com/cloudfoundry/bosh-agent/settings" + boshlog "github.com/cloudfoundry/bosh-utils/logger" + fakesys "github.com/cloudfoundry/bosh-utils/system/fakes" ) var _ = Describe("FileSettingsSource", func() { var ( fs *fakesys.FakeFileSystem - source *FileSettingsSource + source *infrastructure.FileSettingsSource logger boshlog.Logger ) @@ -39,7 +39,7 @@ var _ = Describe("FileSettingsSource", func() { ) BeforeEach(func() { settingsFileName = "/fake-settings-file-path" - source = NewFileSettingsSource(settingsFileName, fs, logger) + source = infrastructure.NewFileSettingsSource(settingsFileName, fs, logger) }) Context("settings have valid format", func() { @@ -54,7 +54,8 @@ var _ = Describe("FileSettingsSource", func() { settingsJSON, err := json.Marshal(expectedSettings) Expect(err).ToNot(HaveOccurred()) - fs.WriteFile(settingsFileName, settingsJSON) + err = fs.WriteFile(settingsFileName, settingsJSON) + Expect(err).NotTo(HaveOccurred()) }) It("returns settings read from the file", func() { @@ -72,7 +73,8 @@ var _ = Describe("FileSettingsSource", func() { Context("settings have invalid format", func() { BeforeEach(func() { - fs.WriteFileString(settingsFileName, "bad-json") + err := fs.WriteFileString(settingsFileName, "bad-json") + Expect(err).NotTo(HaveOccurred()) }) It("returns settings read from the file", func() { _, err := source.Settings() @@ -84,7 +86,7 @@ var _ = Describe("FileSettingsSource", func() { Context("when the registry file does not exist", func() { BeforeEach(func() { - source = NewFileSettingsSource( + source = infrastructure.NewFileSettingsSource( "/missing-settings-file-path", fs, logger) }) diff --git a/infrastructure/http_metadata_service_test.go b/infrastructure/http_metadata_service_test.go index 43ba81ebc..67df87770 100644 --- a/infrastructure/http_metadata_service_test.go +++ b/infrastructure/http_metadata_service_test.go @@ -22,7 +22,7 @@ import ( var _ = Describe("HTTPMetadataService", describeHTTPMetadataService) -func describeHTTPMetadataService() { +func describeHTTPMetadataService() { //nolint:funlen var ( metadataHeaders map[string]string dnsResolver *fakeinf.FakeDNSResolver @@ -94,7 +94,8 @@ func describeHTTPMetadataService() { Expect(r.URL.Path).To(Equal("/ssh-keys")) Expect(r.Header.Get("key")).To(Equal("value")) - w.Write([]byte("fake-public-key")) + _, err := w.Write([]byte("fake-public-key")) + Expect(err).NotTo(HaveOccurred()) }) ts = httptest.NewServer(handler) }) @@ -137,7 +138,6 @@ func describeHTTPMetadataService() { Context("when IMDSv2 is required", func() { var tokenCalls int BeforeEach(func() { - handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer GinkgoRecover() @@ -147,7 +147,8 @@ func describeHTTPMetadataService() { Expect(r.Header.Get("X-aws-ec2-metadata-token-ttl-seconds")).To(Equal("300")) tokenCalls++ - w.Write([]byte("this-is-a-token")) + _, err := w.Write([]byte("this-is-a-token")) + Expect(err).NotTo(HaveOccurred()) return } @@ -156,7 +157,8 @@ func describeHTTPMetadataService() { Expect(r.Header.Get("key")).To(Equal("value")) Expect(r.Header.Get("X-aws-ec2-metadata-token")).To(Equal("this-is-a-token")) - w.Write([]byte("fake-public-key")) + _, err := w.Write([]byte("fake-public-key")) + Expect(err).NotTo(HaveOccurred()) }) ts = httptest.NewServer(handler) @@ -173,7 +175,6 @@ func describeHTTPMetadataService() { Expect(publicKey).To(Equal("fake-public-key")) }) }) - }) Describe("GetEmptyPublicKey", func() { @@ -230,7 +231,8 @@ func describeHTTPMetadataService() { Expect(r.URL.Path).To(Equal("/instanceid")) Expect(r.Header.Get("key")).To(Equal("value")) - w.Write([]byte("fake-instance-id")) + _, err := w.Write([]byte("fake-instance-id")) + Expect(err).NotTo(HaveOccurred()) }) ts = httptest.NewServer(handler) }) @@ -268,13 +270,11 @@ func describeHTTPMetadataService() { Expect(instanceID).To(BeEmpty()) }) }) - }) Context("when IMDSv2 is required", func() { var tokenCalls int BeforeEach(func() { - handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer GinkgoRecover() @@ -284,7 +284,8 @@ func describeHTTPMetadataService() { Expect(r.Header.Get("X-aws-ec2-metadata-token-ttl-seconds")).To(Equal("300")) tokenCalls++ - w.Write([]byte("this-is-a-token")) + _, err := w.Write([]byte("this-is-a-token")) + Expect(err).NotTo(HaveOccurred()) return } @@ -293,7 +294,8 @@ func describeHTTPMetadataService() { Expect(r.Header.Get("key")).To(Equal("value")) Expect(r.Header.Get("X-aws-ec2-metadata-token")).To(Equal("this-is-a-token")) - w.Write([]byte("fake-instance-id")) + _, err := w.Write([]byte("fake-instance-id")) + Expect(err).NotTo(HaveOccurred()) }) ts = httptest.NewServer(handler) @@ -309,13 +311,11 @@ func describeHTTPMetadataService() { Expect(tokenCalls).NotTo(BeZero()) Expect(instanceID).To(Equal("fake-instance-id")) }) - }) Context("when a tokenPath is set, but the region does not support IMDSv2 (which could be a thing that could happen, we don't know we can't verify)", func() { var tokenCalls int BeforeEach(func() { - handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer GinkgoRecover() @@ -326,7 +326,8 @@ func describeHTTPMetadataService() { tokenCalls++ w.WriteHeader(500) - w.Write([]byte("ceci-nest-pas-une-token")) + _, err := w.Write([]byte("ceci-nest-pas-une-token")) + Expect(err).NotTo(HaveOccurred()) return } @@ -335,7 +336,8 @@ func describeHTTPMetadataService() { Expect(r.Header.Get("key")).To(Equal("value")) Expect(r.Header.Get("X-aws-ec2-metadata-token")).To(Equal("")) - w.Write([]byte("fake-instance-id")) + _, err := w.Write([]byte("fake-instance-id")) + Expect(err).NotTo(HaveOccurred()) }) ts = httptest.NewServer(handler) @@ -351,7 +353,6 @@ func describeHTTPMetadataService() { Expect(tokenCalls).NotTo(BeZero()) Expect(instanceID).To(Equal("fake-instance-id")) }) - }) }) @@ -376,7 +377,8 @@ func describeHTTPMetadataService() { jsonStr = fmt.Sprintf(`{"server":{"name":"%s"}}`, *serverName) } - w.Write([]byte(jsonStr)) + _, err := w.Write([]byte(jsonStr)) + Expect(err).NotTo(HaveOccurred()) } BeforeEach(func() { @@ -446,7 +448,8 @@ func describeHTTPMetadataService() { }`, *registryURL, *dnsServer) } - w.Write([]byte(jsonStr)) + _, err := w.Write([]byte(jsonStr)) + Expect(err).NotTo(HaveOccurred()) } BeforeEach(func() { @@ -543,7 +546,8 @@ func describeHTTPMetadataService() { "dns":{"nameserver":["%s"]} }`, *registryURL, *dnsServer) } - w.Write([]byte(jsonStr)) + _, err := w.Write([]byte(jsonStr)) + Expect(err).NotTo(HaveOccurred()) } } @@ -558,7 +562,6 @@ func describeHTTPMetadataService() { }) Context("when server returns an HTTP Response with status code ==2xx (as defined by the request retryable) within 10 retries", func() { - BeforeEach(func() { dnsResolver.RegisterRecord(fakeinf.FakeDNSRecord{ DNSServers: []string{"fake-dns-server-ip"}, @@ -602,7 +605,8 @@ func describeHTTPMetadataService() { Expect(r.Method).To(Equal("GET")) Expect(r.URL.Path).To(Equal("/user-data")) Expect(r.Header.Get("key")).To(Equal("value")) - w.Write([]byte(*jsonStr)) + _, err := w.Write([]byte(*jsonStr)) + Expect(err).NotTo(HaveOccurred()) } BeforeEach(func() { diff --git a/infrastructure/http_registry_test.go b/infrastructure/http_registry_test.go index 23dcdaea9..ec8a7488d 100644 --- a/infrastructure/http_registry_test.go +++ b/infrastructure/http_registry_test.go @@ -22,7 +22,7 @@ import ( var _ = Describe("httpRegistry", describeHTTPRegistry) -func describeHTTPRegistry() { +func describeHTTPRegistry() { //nolint:funlen logger := boshlog.NewLogger(boshlog.LevelNone) var ( @@ -51,7 +51,8 @@ func describeHTTPRegistry() { Expect(r.Method).To(Equal("GET")) Expect(r.URL.Path).To(Equal("/instances/fake-identifier/settings")) - w.Write([]byte(settingsJSON)) + _, err := w.Write([]byte(settingsJSON)) + Expect(err).NotTo(HaveOccurred()) }) ts = httptest.NewServer(boshRegistryHandler) @@ -231,9 +232,9 @@ func describeHTTPRegistry() { "name": "vm-abc-def" } }` - settingsJSON = strings.Replace(settingsJSON, `"`, `\"`, -1) - settingsJSON = strings.Replace(settingsJSON, "\n", "", -1) - settingsJSON = strings.Replace(settingsJSON, "\t", "", -1) + settingsJSON = strings.ReplaceAll(settingsJSON, `"`, `\"`) + settingsJSON = strings.ReplaceAll(settingsJSON, "\n", "") + settingsJSON = strings.ReplaceAll(settingsJSON, "\t", "") settingsJSON = fmt.Sprintf(`{"settings": "%s"}`, settingsJSON) expectedSettings := boshsettings.Settings{ @@ -358,7 +359,8 @@ func describeHTTPRegistry() { GinkgoRecover() - w.Write([]byte(settingsJSON)) + _, err := w.Write([]byte(settingsJSON)) + Expect(err).NotTo(HaveOccurred()) } } @@ -399,7 +401,6 @@ func describeHTTPRegistry() { Expect(err.Error()).To(ContainSubstring("invalid status: 500")) }) }) - }) }) } diff --git a/infrastructure/instance_metadata_settings_source_test.go b/infrastructure/instance_metadata_settings_source_test.go index d4861d846..a040234b4 100644 --- a/infrastructure/instance_metadata_settings_source_test.go +++ b/infrastructure/instance_metadata_settings_source_test.go @@ -4,10 +4,10 @@ import ( "net/http" "net/http/httptest" - . "github.com/cloudfoundry/bosh-agent/infrastructure" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "github.com/cloudfoundry/bosh-agent/infrastructure" "github.com/cloudfoundry/bosh-agent/platform/platformfakes" boshlog "github.com/cloudfoundry/bosh-utils/logger" @@ -21,7 +21,7 @@ func describeInstanceMetadataSettingsSource() { settingsPath string platform *platformfakes.FakePlatform logger boshlog.Logger - metadataSource *InstanceMetadataSettingsSource + metadataSource *infrastructure.InstanceMetadataSettingsSource ) BeforeEach(func() { @@ -30,7 +30,7 @@ func describeInstanceMetadataSettingsSource() { settingsPath = "/computeMetadata/v1/instance/attributes/bosh_settings" platform = &platformfakes.FakePlatform{} logger = boshlog.NewLogger(boshlog.LevelNone) - metadataSource = NewInstanceMetadataSettingsSource("http://fake-metadata-host", metadataHeaders, settingsPath, platform, logger) + metadataSource = infrastructure.NewInstanceMetadataSettingsSource("http://fake-metadata-host", metadataHeaders, settingsPath, platform, logger) }) Describe("PublicSSHKeyForUsername", func() { @@ -53,17 +53,14 @@ func describeInstanceMetadataSettingsSource() { Expect(r.URL.Path).To(Equal(settingsPath)) Expect(r.Header.Get("key")).To(Equal("value")) - var jsonStr string - - jsonStr = `{"agent_id": "123"}` - - w.Write([]byte(jsonStr)) + _, err := w.Write([]byte(`{"agent_id": "123"}`)) + Expect(err).NotTo(HaveOccurred()) } BeforeEach(func() { handler := http.HandlerFunc(handlerFunc) ts = httptest.NewServer(handler) - metadataSource = NewInstanceMetadataSettingsSource(ts.URL, metadataHeaders, settingsPath, platform, logger) + metadataSource = infrastructure.NewInstanceMetadataSettingsSource(ts.URL, metadataHeaders, settingsPath, platform, logger) }) AfterEach(func() { @@ -77,10 +74,9 @@ func describeInstanceMetadataSettingsSource() { }) It("returns an error if reading from the instance metadata endpoint fails", func() { - metadataSource = NewInstanceMetadataSettingsSourceWithoutRetryDelay("bad-registry-endpoint", metadataHeaders, settingsPath, platform, logger) + metadataSource = infrastructure.NewInstanceMetadataSettingsSourceWithoutRetryDelay("bad-registry-endpoint", metadataHeaders, settingsPath, platform, logger) _, err := metadataSource.Settings() Expect(err).To(HaveOccurred()) }) - }) } diff --git a/infrastructure/multi_settings_source_test.go b/infrastructure/multi_settings_source_test.go index c30495b0d..956363f13 100644 --- a/infrastructure/multi_settings_source_test.go +++ b/infrastructure/multi_settings_source_test.go @@ -6,7 +6,7 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - . "github.com/cloudfoundry/bosh-agent/infrastructure" + "github.com/cloudfoundry/bosh-agent/infrastructure" fakeinf "github.com/cloudfoundry/bosh-agent/infrastructure/fakes" boshsettings "github.com/cloudfoundry/bosh-agent/settings" ) @@ -18,7 +18,7 @@ var _ = Describe("MultiSettingsSource", func() { Context("when there are no sources", func() { It("returns an error when there are no sources", func() { - _, err := NewMultiSettingsSource([]boshsettings.Source{}...) + _, err := infrastructure.NewMultiSettingsSource([]boshsettings.Source{}...) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("MultiSettingsSource requires to have at least one source")) }) @@ -50,7 +50,7 @@ var _ = Describe("MultiSettingsSource", func() { JustBeforeEach(func() { var err error - source, err = NewMultiSettingsSource(source1, source2) + source, err = infrastructure.NewMultiSettingsSource(source1, source2) Expect(err).ToNot(HaveOccurred()) }) diff --git a/infrastructure/multi_source_metadata_service_test.go b/infrastructure/multi_source_metadata_service_test.go index 7ae82e7df..a52dace98 100644 --- a/infrastructure/multi_source_metadata_service_test.go +++ b/infrastructure/multi_source_metadata_service_test.go @@ -12,7 +12,7 @@ import ( var _ = Describe("MultiSourceMetadataService", describeMultiSourceMetadataService) -func describeMultiSourceMetadataService() { +func describeMultiSourceMetadataService() { //nolint:funlen var ( metadataService MetadataService service1 fakeinf.FakeMetadataService @@ -51,8 +51,8 @@ func describeMultiSourceMetadataService() { Describe("IsAvailable", func() { It("is true", func() { - availablity := metadataService.IsAvailable() - Expect(availablity).To(BeTrue()) + availability := metadataService.IsAvailable() + Expect(availability).To(BeTrue()) }) }) @@ -129,8 +129,7 @@ func describeMultiSourceMetadataService() { Describe("IsAvailable", func() { It("is true", func() { - availablity := metadataService.IsAvailable() - Expect(availablity).To(BeTrue()) + Expect(metadataService.IsAvailable()).To(BeTrue()) }) }) @@ -183,8 +182,7 @@ func describeMultiSourceMetadataService() { Describe("IsAvailable", func() { It("is false", func() { - availablity := metadataService.IsAvailable() - Expect(availablity).To(BeFalse()) + Expect(metadataService.IsAvailable()).To(BeFalse()) }) }) diff --git a/integration/integration_suite_test.go b/integration/integration_suite_test.go index 43018e153..c73d12f80 100644 --- a/integration/integration_suite_test.go +++ b/integration/integration_suite_test.go @@ -29,7 +29,7 @@ func TestIntegration(t *testing.T) { err = testEnvironment.StopAgent() Expect(err).ToNot(HaveOccurred()) - //create a backup of original settings for nats FW tests + // create a backup of original settings for nats FW tests _, err = testEnvironment.RunCommand("sudo sh -c \"mkdir -p /settings-backup && cp /var/vcap/bosh/*.json /settings-backup/ \" ") Expect(err).ToNot(HaveOccurred()) diff --git a/integration/test_environment.go b/integration/test_environment.go index e54312089..30a8017d7 100644 --- a/integration/test_environment.go +++ b/integration/test_environment.go @@ -126,7 +126,10 @@ sudo mkdir -p /tmp/config-drive/ec2/latest return err } - t.RunCommand("sudo fuser -km /tmp/config-drive") + _, err = t.RunCommand("sudo fuser -km /tmp/config-drive") + if err != nil { + return err + } _, err = t.RunCommand("sudo umount -l /tmp/config-drive") return err } @@ -147,8 +150,14 @@ func (t *TestEnvironment) DetachDevice(dir string) error { sort.Sort(byLen(mountPointsSlice)) for _, mountPoint := range mountPointsSlice { if mountPoint != "" { - t.RunCommand(fmt.Sprintf("sudo fuser -km %s", mountPoint)) - t.RunCommand(fmt.Sprintf("sudo umount %s", mountPoint)) + _, err = t.RunCommand(fmt.Sprintf("sudo fuser -km %s", mountPoint)) + if err != nil { + return err + } + _, err = t.RunCommand(fmt.Sprintf("sudo umount %s", mountPoint)) + if err != nil { + return err + } } } @@ -254,8 +263,11 @@ func (t *TestEnvironment) CleanupDataDir() error { func (t *TestEnvironment) ResetDeviceMap() error { for n, loopDevice := range t.deviceMap { - t.DetachLoopDevice(loopDevice) - _, err := t.RunCommand(fmt.Sprintf("sudo rm -f %s", fmt.Sprintf("/virtualfs-%d", n))) + err := t.DetachLoopDevice(loopDevice) + if err != nil { + return err + } + _, err = t.RunCommand(fmt.Sprintf("sudo rm -f %s", fmt.Sprintf("/virtualfs-%d", n))) if err != nil { return err } @@ -293,7 +305,10 @@ func (t *TestEnvironment) EnsureRootDeviceIsLargeEnough() error { // Ensure we have enough space to create the fake loopback devices used in tests if sizeInBytes < 10000000000 { - t.RunCommand("sudo swapoff /dev/sda2") + _, err = t.RunCommand("sudo swapoff /dev/sda2") + if err != nil { + return err + } for i := len(outputLines); i > 1; i-- { _, err = t.RunCommand(fmt.Sprintf("sudo parted /dev/sda rm %d", i)) @@ -302,7 +317,10 @@ func (t *TestEnvironment) EnsureRootDeviceIsLargeEnough() error { } } - t.RunCommand("sudo udevadm settle") + _, err = t.RunCommand("sudo udevadm settle") + if err != nil { + return err + } _, err = t.RunCommand("sudo parted /dev/sda ---pretend-input-tty resizepart 1 yes 10000M") if err != nil { @@ -408,7 +426,10 @@ func (t *TestEnvironment) DetachPartitionedRootDevice(rootLink string, devicePat if _, err := t.RunCommand(fmt.Sprintf("losetup %s", partitionPath)); err == nil { if output, _ := t.RunCommand(fmt.Sprintf("sudo mount | grep '%s ' | awk '{print $3}'", partitionPath)); output != "" { - t.RunCommand(fmt.Sprintf("sudo umount -l %s", output)) + _, err = t.RunCommand(fmt.Sprintf("sudo umount -l %s", output)) + if err != nil { + return err + } } if i > 0 { @@ -600,7 +621,10 @@ func (t *TestEnvironment) StopAgentTunnel() error { return fmt.Errorf("Not running") } t.sshTunnelProc.Wait() - t.sshTunnelProc.TerminateNicely(5 * time.Second) + err := t.sshTunnelProc.TerminateNicely(5 * time.Second) + if err != nil { + return err + } t.sshTunnelProc = nil return nil } diff --git a/integration/windows/ephemeral_disk_test.go b/integration/windows/ephemeral_disk_test.go index e295f8dcb..5f9cbb895 100644 --- a/integration/windows/ephemeral_disk_test.go +++ b/integration/windows/ephemeral_disk_test.go @@ -74,9 +74,9 @@ var _ = Describe("EphemeralDisk", func() { agent.RunPowershellCommand("cp c:\\bosh\\agent-configuration\\root-partition-agent.json c:\\bosh\\agent.json") agent.StartAgent() - expectedLogMessage := fmt.Sprintf( - "WARN - Unable to create ephemeral partition on disk 0, as there isn't enough free space", - ) + expectedLogMessage := + "WARN - Unable to create ephemeral partition on disk 0, as there isn't enough free space" + Eventually(func() bool { matchingLogOutput := agent.RunPowershellCommand(fmt.Sprintf( `Select-String -Path C:\var\vcap\bosh\log\service_wrapper.err.log -Pattern "%s"`, diff --git a/integration/windows/windows_suite_test.go b/integration/windows/windows_suite_test.go index cd13a755b..8c6f986eb 100644 --- a/integration/windows/windows_suite_test.go +++ b/integration/windows/windows_suite_test.go @@ -2,7 +2,6 @@ package windows_test import ( "fmt" - "github.com/onsi/gomega/gexec" "io" "io/ioutil" "os" @@ -11,6 +10,8 @@ import ( "strings" "time" + "github.com/onsi/gomega/gexec" + "net/http" "github.com/cloudfoundry/bosh-agent/integration/windows/utils" @@ -79,9 +80,10 @@ var _ = BeforeSuite(func() { agent.CleanUpExtraDisks() goSourcePath := filepath.Join(utils.AgentDir(), "integration", "windows", "fixtures", "templates", "go", "go1.7.1.windows-amd64.zip") - os.RemoveAll(goSourcePath) - downloadFile(goSourcePath, "https://dl.google.com/go/go1.7.1.windows-amd64.zip") - //agent.RunPowershellCommand("add-content \\ProgramData\\ssh\\sshd_config \"AllowUsers bosh_testuser\"") + err = os.RemoveAll(goSourcePath) + Expect(err).NotTo(HaveOccurred()) + err = downloadFile(goSourcePath, "https://dl.google.com/go/go1.7.1.windows-amd64.zip") + Expect(err).NotTo(HaveOccurred()) }) func templateEphemeralDiskSettings(natsPrivateIP, ephemeralDiskConfig, filename string) { diff --git a/jobsupervisor/dummy_nats_job_supervisor_test.go b/jobsupervisor/dummy_nats_job_supervisor_test.go index d8612043a..5d83b6b07 100644 --- a/jobsupervisor/dummy_nats_job_supervisor_test.go +++ b/jobsupervisor/dummy_nats_job_supervisor_test.go @@ -23,14 +23,16 @@ var _ = Describe("dummyNatsJobSupervisor", func() { Describe("MonitorJobFailures", func() { It("monitors job status", func() { - dummyNats.MonitorJobFailures(func(boshalert.MonitAlert) error { return nil }) + err := dummyNats.MonitorJobFailures(func(boshalert.MonitAlert) error { return nil }) + Expect(err).NotTo(HaveOccurred()) Expect(handler.RegisteredAdditionalFunc).ToNot(BeNil()) }) }) Describe("Status", func() { BeforeEach(func() { - dummyNats.MonitorJobFailures(func(boshalert.MonitAlert) error { return nil }) + err := dummyNats.MonitorJobFailures(func(boshalert.MonitAlert) error { return nil }) + Expect(err).NotTo(HaveOccurred()) }) It("returns the received status", func() { @@ -52,7 +54,8 @@ var _ = Describe("dummyNatsJobSupervisor", func() { Describe("Start", func() { BeforeEach(func() { - dummyNats.MonitorJobFailures(func(boshalert.MonitAlert) error { return nil }) + err := dummyNats.MonitorJobFailures(func(boshalert.MonitAlert) error { return nil }) + Expect(err).NotTo(HaveOccurred()) }) Context("When set_task_fail flag is sent in messagae", func() { @@ -84,7 +87,8 @@ var _ = Describe("dummyNatsJobSupervisor", func() { Context("when a job is failing", func() { BeforeEach(func() { - dummyNats.MonitorJobFailures(func(boshalert.MonitAlert) error { return nil }) + err := dummyNats.MonitorJobFailures(func(boshalert.MonitAlert) error { return nil }) + Expect(err).NotTo(HaveOccurred()) }) Context("with 'fail_task'", func() { @@ -118,7 +122,8 @@ var _ = Describe("dummyNatsJobSupervisor", func() { Context("when a job is failing", func() { BeforeEach(func() { - dummyNats.MonitorJobFailures(func(boshalert.MonitAlert) error { return nil }) + err := dummyNats.MonitorJobFailures(func(boshalert.MonitAlert) error { return nil }) + Expect(err).NotTo(HaveOccurred()) }) Context("with 'fail_task'", func() { @@ -142,5 +147,4 @@ var _ = Describe("dummyNatsJobSupervisor", func() { }) }) }) - }) diff --git a/jobsupervisor/fakes/fake_job_supervisor.go b/jobsupervisor/fakes/fake_job_supervisor.go index 7f9386e6a..bb80880cc 100644 --- a/jobsupervisor/fakes/fake_job_supervisor.go +++ b/jobsupervisor/fakes/fake_job_supervisor.go @@ -1,9 +1,10 @@ package fakes import ( + "sync" + boshalert "github.com/cloudfoundry/bosh-agent/agent/alert" boshjobsuper "github.com/cloudfoundry/bosh-agent/jobsupervisor" - "sync" ) type FakeJobSupervisor struct { @@ -107,7 +108,7 @@ func (m *FakeJobSupervisor) MonitorJobFailures(handler boshjobsuper.JobFailureHa func (m *FakeJobSupervisor) HealthRecorder(status string) { m.HealthRecordedMutex.Lock() - m.HealthRecorded += 1 + m.HealthRecorded++ m.HealthRecordedMutex.Unlock() } diff --git a/jobsupervisor/monit/monit_retry_strategy_test.go b/jobsupervisor/monit/monit_retry_strategy_test.go index 36f58a6a2..66f7e44e5 100644 --- a/jobsupervisor/monit/monit_retry_strategy_test.go +++ b/jobsupervisor/monit/monit_retry_strategy_test.go @@ -189,7 +189,7 @@ var _ = Describe("MonitRetryStrategy", func() { Expect(retryable.AttemptCallCount()).To(Equal(maxOtherAttempts)) }) - Context("when other attempts are all unavailble", func() { + Context("when other attempts are all unavailable", func() { It("retries for maxOtherAttempts", func() { retryable.AttemptStub = func() (bool, error) { if retryable.AttemptCallCount() == 1 { diff --git a/jobsupervisor/monit_job_supervisor.go b/jobsupervisor/monit_job_supervisor.go index 9ebe9a0a6..c036521ce 100644 --- a/jobsupervisor/monit_job_supervisor.go +++ b/jobsupervisor/monit_job_supervisor.go @@ -279,7 +279,6 @@ func (m monitJobSupervisor) Status() (status string) { if m.fs.FileExists(m.stoppedFilePath()) { status = "stopped" - } else { services := monitStatus.ServicesInGroup("vcap") for _, service := range services { @@ -392,7 +391,6 @@ func (m monitJobSupervisor) filterServices(services []boshmonit.Service, fn func } func (m monitJobSupervisor) checkServices() ([]boshmonit.Service, error) { - monitStatus, err := m.client.Status() if err != nil { return nil, bosherr.WrapErrorf(err, "Getting monit status") diff --git a/jobsupervisor/monit_job_supervisor_test.go b/jobsupervisor/monit_job_supervisor_test.go index c201a6c90..fb4d87842 100644 --- a/jobsupervisor/monit_job_supervisor_test.go +++ b/jobsupervisor/monit_job_supervisor_test.go @@ -78,8 +78,10 @@ var _ = Describe("monitJobSupervisor", func() { conn, err = smtp.Dial(fmt.Sprintf("localhost:%d", port)) } - conn.Mail("sender@example.org") - conn.Rcpt("recipient@example.net") + err = conn.Mail("sender@example.org") + Expect(err).NotTo(HaveOccurred()) + err = conn.Rcpt("recipient@example.net") + Expect(err).NotTo(HaveOccurred()) writeCloser, err := conn.Data() if err != nil { return err @@ -221,10 +223,12 @@ var _ = Describe("monitJobSupervisor", func() { }) It("deletes stopped file", func() { - fs.MkdirAll("/var/vcap/monit/stopped", os.FileMode(0755)) - fs.WriteFileString("/var/vcap/monit/stopped", "") + err := fs.MkdirAll("/var/vcap/monit/stopped", os.FileMode(0755)) + Expect(err).NotTo(HaveOccurred()) + err = fs.WriteFileString("/var/vcap/monit/stopped", "") + Expect(err).NotTo(HaveOccurred()) - err := monit.Start() + err = monit.Start() Expect(err).ToNot(HaveOccurred()) Expect(fs.FileExists("/var/vcap/monit/stopped")).ToNot(BeTrue()) }) @@ -268,7 +272,8 @@ var _ = Describe("monitJobSupervisor", func() { resBody := readFixture("monit/test_assets/monit_status_stopped.xml") if r.URL.Path == "/_status2" { - w.Write(resBody) + _, err := w.Write(resBody) + Expect(err).NotTo(HaveOccurred()) } else { Expect(r.Method).To(Equal("POST")) requestData["action"] = r.PostFormValue("action") @@ -472,7 +477,8 @@ var _ = Describe("monitJobSupervisor", func() { resBody := readFixture("monit/test_assets/monit_status_errored.xml") if r.URL.Path == "/_status2" { - w.Write(resBody) + _, err := w.Write(resBody) + Expect(err).NotTo(HaveOccurred()) } else { Expect(r.Method).To(Equal("POST")) requestData["action"] = r.PostFormValue("action") @@ -522,9 +528,11 @@ var _ = Describe("monitJobSupervisor", func() { if r.URL.Path == "/_status2" { statusRequests++ if statusRequests == 1 { - w.Write(readFixture("monit/test_assets/monit_status_running.xml")) + _, err := w.Write(readFixture("monit/test_assets/monit_status_running.xml")) + Expect(err).NotTo(HaveOccurred()) } else { - w.Write(readFixture("monit/test_assets/monit_status_multiple.xml")) + _, err := w.Write(readFixture("monit/test_assets/monit_status_multiple.xml")) + Expect(err).NotTo(HaveOccurred()) } } else { Expect(r.Method).To(Equal("POST")) @@ -648,8 +656,10 @@ var _ = Describe("monitJobSupervisor", func() { Services: []boshmonit.Service{}, } - fs.MkdirAll("/var/vcap/monit/stopped", os.FileMode(0755)) - fs.WriteFileString("/var/vcap/monit/stopped", "") + err := fs.MkdirAll("/var/vcap/monit/stopped", os.FileMode(0755)) + Expect(err).NotTo(HaveOccurred()) + err = fs.WriteFileString("/var/vcap/monit/stopped", "") + Expect(err).NotTo(HaveOccurred()) status := monit.Status() Expect(status).To(Equal("stopped")) @@ -733,7 +743,10 @@ var _ = Describe("monitJobSupervisor", func() { return } - go monit.MonitorJobFailures(failureHandler) + go func() { + err := monit.MonitorJobFailures(failureHandler) + Expect(err).NotTo(HaveOccurred()) + }() msg := `Message-id: <1304319946.0@localhost> Service: nats @@ -763,7 +776,10 @@ var _ = Describe("monitJobSupervisor", func() { return } - go monit.MonitorJobFailures(failureHandler) + go func() { + err := monit.MonitorJobFailures(failureHandler) + Expect(err).NotTo(HaveOccurred()) + }() err := doJobFailureEmail(`fake-other-email`, jobFailuresServerPort) Expect(err).ToNot(HaveOccurred()) @@ -773,7 +789,8 @@ var _ = Describe("monitJobSupervisor", func() { Describe("AddJob", func() { BeforeEach(func() { - fs.WriteFileString("/some/config/path", "fake-config") + err := fs.WriteFileString("/some/config/path", "fake-config") + Expect(err).NotTo(HaveOccurred()) }) Context("when reading configuration from config path succeeds", func() { @@ -816,9 +833,10 @@ var _ = Describe("monitJobSupervisor", func() { It("does not return error because all jobs are removed from monit", func() { jobsDir := dirProvider.MonitJobsDir() jobBasename := "/0000_router.monitrc" - fs.WriteFileString(jobsDir+jobBasename, "fake-added-job") + err := fs.WriteFileString(jobsDir+jobBasename, "fake-added-job") + Expect(err).NotTo(HaveOccurred()) - err := monit.RemoveAllJobs() + err = monit.RemoveAllJobs() Expect(err).ToNot(HaveOccurred()) Expect(fs.FileExists(jobsDir)).To(BeFalse()) diff --git a/jobsupervisor/pipe/main_test.go b/jobsupervisor/pipe/main_test.go index 026e5a1d7..d03137b57 100644 --- a/jobsupervisor/pipe/main_test.go +++ b/jobsupervisor/pipe/main_test.go @@ -26,7 +26,7 @@ import ( "github.com/cloudfoundry/bosh-agent/jobsupervisor/pipe/syslog" ) -const ServiceName = "jimbob" +const ServiceName = "jim-bob" const MachineIP = "1.2.3.4" func FindOpenPort() (int, error) { @@ -34,7 +34,7 @@ func FindOpenPort() (int, error) { rand.Seed(time.Now().UnixNano()) for i := 0; i < 50; i++ { - port := Base + rand.Intn(10000) + port := Base + rand.Intn(10000) //nolint:gosec addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("localhost:%d", port)) if err != nil { return 0, err @@ -77,7 +77,8 @@ var _ = Describe("Main", func() { server.RouteToHandler("POST", "/", func(w http.ResponseWriter, r *http.Request) { b, err := ioutil.ReadAll(r.Body) Expect(err).To(Succeed()) - r.Body.Close() + err = r.Body.Close() + Expect(err).NotTo(HaveOccurred()) bodyCh <- b }) }) @@ -107,8 +108,8 @@ var _ = Describe("Main", func() { Expect(event.ProcessName).To(Equal("foo")) } - // On Concourse tests on Windows may be ran in a Pipe, which - // will already have it's env vars set. Make sure we don't + // On Concourse tests on Windows may be run in a Pipe, which + // will already have its env vars set. Make sure we don't // pass those env vars to the Pipe we are testing. It("overwrites Pipe specific NOTIFY_HTTP env vars during testing", func() { defer invalidatePipeEnvVars()() @@ -146,7 +147,8 @@ var _ = Describe("Main", func() { Expect(err).To(Succeed()) }) AfterEach(func() { - os.RemoveAll(tempDir) + err := os.RemoveAll(tempDir) + Expect(err).NotTo(HaveOccurred()) }) It("never logs own behaviour to stdout/err", func() { @@ -196,7 +198,7 @@ var _ = Describe("Main", func() { var invalidLogDir string randString := func() string { b := make([]byte, 8) - n, _ := rand.Read(b) + n, _ := rand.Read(b) //nolint:gosec return fmt.Sprintf("%X", b[:n]) } for i := 0; i < 1000; i++ { @@ -232,7 +234,7 @@ var _ = Describe("Main", func() { var ServerConn *net.UDPConn var ServerAddr *net.UDPAddr var syslogPort string - var syslogReceived chan (string) + var syslogReceived chan string var done chan struct{} var wg *sync.WaitGroup @@ -294,7 +296,7 @@ var _ = Describe("Main", func() { } It("ignores errors writing to syslog, allowing the app to continue functioning", func() { - cmd := exec.Command(pathToPipeCLI, GoSequencePath, + cmd := exec.Command(pathToPipeCLI, GoSequencePath, //nolint:gosec "-start", strconv.Itoa(Start), "-end", strconv.Itoa(End), "-int", Interval.String(), @@ -311,15 +313,17 @@ var _ = Describe("Main", func() { Expect(cmd.Start()).To(Succeed()) go func() { time.Sleep((Interval / 2) * 3) // * 1.5 - ServerConn.Close() + err := ServerConn.Close() + Expect(err).NotTo(HaveOccurred()) }() Expect(cmd.Wait()).To(Succeed()) - checkSequenceOutput(&stdout, Start, End) + err := checkSequenceOutput(&stdout, Start, End) + Expect(err).NotTo(HaveOccurred()) }) testStdoutToSyslog := func() { - cmd := exec.Command(pathToPipeCLI, GoSequencePath, + cmd := exec.Command(pathToPipeCLI, GoSequencePath, //nolint:gosec "-start", strconv.Itoa(Start), "-end", strconv.Itoa(End), "-int", Interval.String(), @@ -359,7 +363,7 @@ var _ = Describe("Main", func() { }) It("logs stderr output to syslog", func() { - cmd := exec.Command(pathToPipeCLI, GoSequencePath, + cmd := exec.Command(pathToPipeCLI, GoSequencePath, //nolint:gosec "-start", strconv.Itoa(Start), "-end", strconv.Itoa(End), "-int", Interval.String(), @@ -401,7 +405,7 @@ func check(p syslog.Priority, in, out string) error { n, err := fmt.Sscanf(out, tmpl, ×tamp, &parsedHostname, &pid) if n != 3 || err != nil || parsedHostname != MachineIP { - return fmt.Errorf("Got %q, does not match template %q (%d %s)", out, tmpl, n, err) + return fmt.Errorf("got %q, does not match template %q (%d %s)", out, tmpl, n, err) } return nil } @@ -429,7 +433,7 @@ func cmdEnv(envVars ...string) []string { // invalidatePipeEnvVars stores invalid values in the Pipe specific variables // of the current environment and returns a function to the reset any modified -// varaibles. +// variables. // // Example: // @@ -458,7 +462,7 @@ func invalidatePipeEnvVars() (restore func()) { for k := range envVars { os.Setenv(k, "") } - // function to reset restore environemnt + // function to reset restore environment return func() { for k, v := range envVars { if v.ok { diff --git a/jobsupervisor/pipe/syslog/syslog_test.go b/jobsupervisor/pipe/syslog/syslog_test.go index 278fd9a98..1b4d99a4e 100644 --- a/jobsupervisor/pipe/syslog/syslog_test.go +++ b/jobsupervisor/pipe/syslog/syslog_test.go @@ -27,7 +27,7 @@ func runPktSyslog(c net.PacketConn, done chan<- string) { var n int var err error - c.SetReadDeadline(time.Now().Add(100 * time.Millisecond)) + c.SetReadDeadline(time.Now().Add(100 * time.Millisecond)) //nolint:errcheck n, _, err = c.ReadFrom(buf[:]) rcvd += string(buf[:n]) if err != nil { @@ -44,7 +44,7 @@ func runPktSyslog(c net.PacketConn, done chan<- string) { done <- rcvd } -var crashy = false +var crashy = false //nolint:gochecknoglobals func testableNetwork(network string) bool { return network == "tcp" || network == "udp" @@ -60,7 +60,7 @@ func runStreamSyslog(l net.Listener, done chan<- string, wg *sync.WaitGroup) { wg.Add(1) go func(c net.Conn) { defer wg.Done() - c.SetReadDeadline(time.Now().Add(time.Second)) + c.SetReadDeadline(time.Now().Add(time.Second)) //nolint:errcheck b := bufio.NewReader(c) for ct := 1; !crashy || ct&7 != 0; ct++ { s, err := b.ReadString('\n') @@ -74,38 +74,40 @@ func runStreamSyslog(l net.Listener, done chan<- string, wg *sync.WaitGroup) { } } -func startServer(n, la string, done chan<- string) (addr string, sock io.Closer, wg *sync.WaitGroup) { - if la == "" { - la = "127.0.0.1:0" +func startServer(n, listenAddr string, done chan<- string) (string, io.Closer, *sync.WaitGroup) { + if listenAddr == "" { + listenAddr = "127.0.0.1:0" } + var addr string + var closerSocket io.Closer - wg = new(sync.WaitGroup) - if n == "udp" { - l, e := net.ListenPacket(n, la) - if e != nil { - log.Fatalf("startServer failed: %v", e) + wg := new(sync.WaitGroup) + if n == "udp" { // TODO: can likely be simplified + listener, err := net.ListenPacket(n, listenAddr) + if err != nil { + log.Fatalf("startServer failed: %v", err) } - addr = l.LocalAddr().String() - sock = l + addr = listener.LocalAddr().String() + closerSocket = listener wg.Add(1) go func() { defer wg.Done() - runPktSyslog(l, done) + runPktSyslog(listener, done) }() } else { - l, e := net.Listen(n, la) - if e != nil { - log.Fatalf("startServer failed: %v", e) + listener, err := net.Listen(n, listenAddr) + if err != nil { + log.Fatalf("startServer failed: %v", err) } - addr = l.Addr().String() - sock = l + addr = listener.Addr().String() + closerSocket = listener wg.Add(1) go func() { defer wg.Done() - runStreamSyslog(l, done, wg) + runStreamSyslog(listener, done, wg) }() } - return + return addr, closerSocket, wg } type dialFunc func(tr, addr string) (*Writer, error) @@ -162,18 +164,18 @@ func TestWithSimulated(t *testing.T) { } func TestFlapTCP(t *testing.T) { - const net = "tcp" - if !testableNetwork(net) { - t.Skipf("skipping on %s/%s; '%s' is not supported", runtime.GOOS, runtime.GOARCH, net) + const tcpNetwork = "tcp" + if !testableNetwork(tcpNetwork) { + t.Skipf("skipping on %s/%s; '%s' is not supported", runtime.GOOS, runtime.GOARCH, tcpNetwork) } done := make(chan string) // Start server - addr, sock, srvWG := startServer(net, "", done) + addr, sock, srvWG := startServer(tcpNetwork, "", done) defer sock.Close() - s, err := Dial(net, addr, LOG_INFO|LOG_USER, "syslog_test") + s, err := Dial(tcpNetwork, addr, LOG_INFO|LOG_USER, "syslog_test") if err != nil { t.Fatalf("Dial() failed: %v", err) } @@ -198,7 +200,7 @@ func TestFlapTCP(t *testing.T) { } // restart server - addr2, sock2, srvWG2 := startServer(net, addr, done) + addr2, sock2, srvWG2 := startServer(tcpNetwork, addr, done) defer srvWG2.Wait() defer sock2.Close() if addr2 != addr { @@ -217,27 +219,27 @@ func TestFlapTCP(t *testing.T) { } func TestDialHostname(t *testing.T) { - net := "tcp" - if !testableNetwork(net) { - t.Skipf("skipping on %s/%s; '%s' is not supported", runtime.GOOS, runtime.GOARCH, net) + tcpNetwork := "tcp" + if !testableNetwork(tcpNetwork) { + t.Skipf("skipping on %s/%s; '%s' is not supported", runtime.GOOS, runtime.GOARCH, tcpNetwork) } done := make(chan string) - addr, sock, srvWG := startServer(net, "", done) + addr, sock, srvWG := startServer(tcpNetwork, "", done) defer srvWG.Wait() defer os.Remove(addr) defer sock.Close() if testing.Short() { t.Skip("skipping syslog test during -short") } - f, err := DialHostname(net, addr, (LOG_LOCAL7|LOG_DEBUG)+1, "syslog_test", TestHostname) + f, err := DialHostname(tcpNetwork, addr, (LOG_LOCAL7|LOG_DEBUG)+1, "syslog_test", TestHostname) //nolint:staticcheck,ineffassign if f != nil { t.Fatalf("Should have trapped bad priority") } - f, err = DialHostname(net, addr, -1, "syslog_test", TestHostname) + f, err = DialHostname(tcpNetwork, addr, -1, "syslog_test", TestHostname) //nolint:staticcheck,ineffassign if f != nil { t.Fatalf("Should have trapped bad priority") } - l, err := DialHostname(net, addr, LOG_USER|LOG_ERR, "syslog_test", TestHostname) + l, err := DialHostname(tcpNetwork, addr, LOG_USER|LOG_ERR, "syslog_test", TestHostname) if err != nil { t.Fatalf("Dial() failed: %s", err) } @@ -249,27 +251,27 @@ func TestDialHostname(t *testing.T) { } func TestDial(t *testing.T) { - net := "tcp" - if !testableNetwork(net) { - t.Skipf("skipping on %s/%s; '%s' is not supported", runtime.GOOS, runtime.GOARCH, net) + tcpNetwork := "tcp" + if !testableNetwork(tcpNetwork) { + t.Skipf("skipping on %s/%s; '%s' is not supported", runtime.GOOS, runtime.GOARCH, tcpNetwork) } done := make(chan string) - addr, sock, srvWG := startServer(net, "", done) + addr, sock, srvWG := startServer(tcpNetwork, "", done) defer srvWG.Wait() defer os.Remove(addr) defer sock.Close() if testing.Short() { t.Skip("skipping syslog test during -short") } - f, err := Dial(net, addr, (LOG_LOCAL7|LOG_DEBUG)+1, "syslog_test") + f, err := Dial(tcpNetwork, addr, (LOG_LOCAL7|LOG_DEBUG)+1, "syslog_test") //nolint:ineffassign,staticcheck if f != nil { t.Fatalf("Should have trapped bad priority") } - f, err = Dial(net, addr, -1, "syslog_test") + f, err = Dial(tcpNetwork, addr, -1, "syslog_test") //nolint:ineffassign,staticcheck if f != nil { t.Fatalf("Should have trapped bad priority") } - l, err := Dial(net, addr, LOG_USER|LOG_ERR, "syslog_test") + l, err := Dial(tcpNetwork, addr, LOG_USER|LOG_ERR, "syslog_test") if err != nil { t.Fatalf("Dial() failed: %s", err) } @@ -340,7 +342,6 @@ func TestWrite(t *testing.T) { t.Errorf("s.Info() = '%q', didn't match '%q' (%d %s)", rcvd, test.exp, n, err) } } - } func TestConcurrentWrite(t *testing.T) { @@ -372,12 +373,12 @@ func TestConcurrentReconnect(t *testing.T) { const N = 10 const M = 100 - net := "tcp" - if !testableNetwork(net) { + tcpNetwork := "tcp" + if !testableNetwork(tcpNetwork) { t.Skipf("skipping on %s/%s; 'tcp' is not supported", runtime.GOOS, runtime.GOARCH) } done := make(chan string, N*M) - addr, sock, srvWG := startServer(net, "", done) + addr, sock, srvWG := startServer(tcpNetwork, "", done) // count all the messages arriving count := make(chan int) @@ -398,11 +399,11 @@ func TestConcurrentReconnect(t *testing.T) { var wg sync.WaitGroup wg.Add(N) for i := 0; i < N; i++ { - go func() { + go func() { //nolint:staticcheck defer wg.Done() - w, err := Dial(net, addr, LOG_USER|LOG_ERR, "tag") + w, err := Dial(tcpNetwork, addr, LOG_USER|LOG_ERR, "tag") if err != nil { - t.Fatalf("syslog.Dial() failed: %v", err) + t.Fatalf("syslog.Dial() failed: %v", err) //nolint:govet,staticcheck } defer w.Close() for i := 0; i < M; i++ { @@ -455,6 +456,6 @@ func BenchmarkWrite(b *testing.B) { priority: LOG_INFO, } for i := 0; i < b.N; i++ { - w.Write(testString) + w.Write(testString) //nolint:errcheck } } diff --git a/jobsupervisor/pipe/winsw_pipe_suite_test.go b/jobsupervisor/pipe/winsw_pipe_suite_test.go index ae88ba84b..8bd3ed595 100644 --- a/jobsupervisor/pipe/winsw_pipe_suite_test.go +++ b/jobsupervisor/pipe/winsw_pipe_suite_test.go @@ -11,12 +11,12 @@ import ( "testing" ) -var pathToPipeCLI string -var GoSequencePath string -var PrintPidsPath string -var ExitRunnerPath string -var ExitCodePath string -var echoCmdArgs []string +var pathToPipeCLI string //nolint:gochecknoglobals +var GoSequencePath string //nolint:gochecknoglobals +var PrintPidsPath string //nolint:gochecknoglobals +var ExitRunnerPath string //nolint:gochecknoglobals +var ExitCodePath string //nolint:gochecknoglobals +var echoCmdArgs []string //nolint:gochecknoglobals const echoOutput = "hello" diff --git a/jobsupervisor/provider_test.go b/jobsupervisor/provider_test.go index e0a43fd10..8ce354633 100644 --- a/jobsupervisor/provider_test.go +++ b/jobsupervisor/provider_test.go @@ -19,7 +19,7 @@ import ( boshlog "github.com/cloudfoundry/bosh-utils/logger" ) -func init() { +func init() { //nolint:gochecknoinits Describe("provider", func() { var ( platform *platformfakes.FakePlatform @@ -62,7 +62,6 @@ func init() { } else { jobSupervisorName = "monit" } - }) It("provides a monit/windows job supervisor", func() { diff --git a/jobsupervisor/windows_job_supervisor_export_test.go b/jobsupervisor/windows_job_supervisor_export_test.go index 8705435ae..4d0527b12 100644 --- a/jobsupervisor/windows_job_supervisor_export_test.go +++ b/jobsupervisor/windows_job_supervisor_export_test.go @@ -8,7 +8,7 @@ import ( "time" ) -func init() { +func init() { //nolint:gochecknoinits // Change constant for unit test process labels to prevent collisions with // bosh deployed Job Supervisor serviceDescription = fmt.Sprintf("vcap_test_%d", time.Now().UnixNano()) diff --git a/jobsupervisor/windows_job_supervisor_test.go b/jobsupervisor/windows_job_supervisor_test.go index 160af08e4..3fb876534 100755 --- a/jobsupervisor/windows_job_supervisor_test.go +++ b/jobsupervisor/windows_job_supervisor_test.go @@ -37,7 +37,7 @@ import ( "github.com/onsi/gomega/gexec" ) -func init() { +func init() { //nolint:gochecknoinits // Make sure we don't use 'vcap' as the service description, // otherwise we may destroy BOSH deployed Concourse workers. // @@ -52,21 +52,21 @@ const ( DefaultMachineIP = "127.0.0.1" DefaultTimeout = time.Second * 15 DefaultInterval = time.Millisecond * 500 - DefaultEventPort = 2825 ) var ( - StartStopExe string - HelloExe string - WaitSvcExe string - FlapStartExe string - TempDir string + StartStopExe string //nolint:gochecknoglobals + HelloExe string //nolint:gochecknoglobals + WaitSvcExe string //nolint:gochecknoglobals + FlapStartExe string //nolint:gochecknoglobals + TempDir string //nolint:gochecknoglobals - ServiceDescription = GetServiceDescription() + ServiceDescription = GetServiceDescription() //nolint:gochecknoglobals ) var _ = AfterSuite(func() { - os.RemoveAll(TempDir) + err := os.RemoveAll(TempDir) + Expect(err).NotTo(HaveOccurred()) gexec.CleanupBuildArtifacts() match := func(s string) bool { @@ -74,7 +74,7 @@ var _ = AfterSuite(func() { } m, err := winsvc.Connect(match) Expect(err).To(Succeed()) - defer m.Disconnect() + defer m.Disconnect() //nolint:errcheck Expect(m.Delete()).To(Succeed()) }) @@ -162,7 +162,8 @@ func testWindowsConfigs(jobName string) (WindowsProcessConfig, error) { f, err := ioutil.TempFile(TempDir, "stopfile-") Expect(err).ToNot(HaveOccurred()) tmpFileName := f.Name() - f.Close() + err = f.Close() + Expect(err).NotTo(HaveOccurred()) procs = []WindowsProcess{ { Name: fmt.Sprintf("stop-executable-1-%d", time.Now().UnixNano()), @@ -175,7 +176,7 @@ func testWindowsConfigs(jobName string) (WindowsProcessConfig, error) { }, } default: - return WindowsProcessConfig{}, fmt.Errorf("Invalid Windows Config Process name: %s", jobName) + return WindowsProcessConfig{}, fmt.Errorf("invalid Windows Config Process name: %s", jobName) } return WindowsProcessConfig{Processes: procs}, nil @@ -206,9 +207,10 @@ func concurrentStopConfig() WindowsProcessConfig { createStopFile := func() string { f, err := ioutil.TempFile(TempDir, "stopfile-") Expect(err).ToNot(HaveOccurred()) - path := f.Name() - f.Close() - return path + stopFilePathName := f.Name() + err = f.Close() + Expect(err).NotTo(HaveOccurred()) + return stopFilePathName } for i := 0; i < WaitCount; i++ { @@ -298,12 +300,13 @@ func addFlappingJob(jobSupervisor JobSupervisor, jobDir string, fs boshsys.FileS if err != nil { return nil, err } - defer m.Disconnect() + defer m.Disconnect() //nolint:errcheck - var svcs []*mgr.Service + var svcs []*mgr.Service //nolint:prealloc defer func() { for _, s := range svcs { - s.Close() + err := s.Close() + Expect(err).NotTo(HaveOccurred()) } }() @@ -412,13 +415,16 @@ var _ = Describe("WindowsJobSupervisor", func() { var err error basePath, err = ioutil.TempDir(TempDir, "") Expect(err).ToNot(HaveOccurred()) - fs.MkdirAll(basePath, 0755) + err = fs.MkdirAll(basePath, 0755) + Expect(err).NotTo(HaveOccurred()) binPath := filepath.Join(basePath, "bosh", "bin") - fs.MkdirAll(binPath, 0755) + err = fs.MkdirAll(binPath, 0755) + Expect(err).NotTo(HaveOccurred()) logDir = path.Join(basePath, "sys", "log") - fs.MkdirAll(binPath, 0755) + err = fs.MkdirAll(binPath, 0755) + Expect(err).NotTo(HaveOccurred()) exePath = filepath.Join(binPath, "job-service-wrapper.exe") @@ -439,7 +445,7 @@ var _ = Describe("WindowsJobSupervisor", func() { if err != nil { return 0, err } - defer m.Disconnect() + defer m.Disconnect() //nolint:errcheck s, err := m.OpenService(serviceName) if err != nil { return 0, err @@ -457,7 +463,7 @@ var _ = Describe("WindowsJobSupervisor", func() { if err != nil { return svc.Status{}, mgr.Config{}, err } - defer m.Disconnect() + defer m.Disconnect() //nolint:errcheck s, err := m.OpenService(svcName) if err != nil { @@ -604,7 +610,7 @@ var _ = Describe("WindowsJobSupervisor", func() { Expect(p.State).To(Equal("stopped")) Expect(int(p.CPU.Total)).To(Equal(0)) Expect(int(p.CPU.Total)).To(Equal(0)) - Expect(int(p.Memory.Kb)).To(Equal(0)) + Expect(p.Memory.Kb).To(Equal(0)) } }) }) @@ -809,7 +815,7 @@ var _ = Describe("WindowsJobSupervisor", func() { Context("when the WindowsProcess has syslog environment variables", func() { var ServerConn *net.UDPConn - var syslogReceived chan (string) + var syslogReceived chan string BeforeEach(func() { ServerAddr, err := net.ResolveUDPAddr("udp", ":10202") @@ -817,7 +823,7 @@ var _ = Describe("WindowsJobSupervisor", func() { ServerConn, err = net.ListenUDP("udp", ServerAddr) Expect(err).To(Succeed()) - syslogReceived = make(chan (string), 1) + syslogReceived = make(chan string, 1) go func() { buf := make([]byte, 1024) for { @@ -834,7 +840,8 @@ var _ = Describe("WindowsJobSupervisor", func() { }) AfterEach(func() { - ServerConn.Close() + err := ServerConn.Close() + Expect(err).NotTo(HaveOccurred()) }) // Test that the syslog message s matches pattern: @@ -850,7 +857,7 @@ var _ = Describe("WindowsJobSupervisor", func() { s = strings.TrimSpace(s) n, err := fmt.Sscanf(s, tmpl, &timeStamp, &ipAddr, &id, &pid) if n != 4 || err != nil { - Expect(fmt.Errorf("Got %q, does not match template %q (%d %s)", + Expect(fmt.Errorf("got %q, does not match template %q (%d %s)", s, tmpl, n, err)).To(Succeed()) } @@ -887,7 +894,8 @@ var _ = Describe("WindowsJobSupervisor", func() { // notification causes WinSW to think the process is actually // running when it is not. That is because WinSW monitors // pipe.exe - not the underlying process. - os.Setenv("__PIPE_DISABLE_NOTIFY", strconv.FormatBool(true)) + err := os.Setenv("__PIPE_DISABLE_NOTIFY", strconv.FormatBool(true)) + Expect(err).NotTo(HaveOccurred()) defer os.Unsetenv("__PIPE_DISABLE_NOTIFY") conf, err := flappingStartConfig(flapCount, jobCount) @@ -1024,12 +1032,12 @@ var _ = Describe("WindowsJobSupervisor", func() { doJobFailureRequest := func(payload string, port int) error { url := fmt.Sprintf("http://localhost:%d", port) - _, err := http.Post(url, "application/json", strings.NewReader(payload)) + _, err := http.Post(url, "application/json", strings.NewReader(payload)) //nolint:gosec return err } - expectedMonitAlert := func(recieved boshalert.MonitAlert) interface{} { - date, err := time.Parse(time.RFC1123Z, recieved.Date) + expectedMonitAlert := func(received boshalert.MonitAlert) interface{} { + date, err := time.Parse(time.RFC1123Z, received.Date) if err != nil { return err } @@ -1053,7 +1061,10 @@ var _ = Describe("WindowsJobSupervisor", func() { return } - go jobSupervisor.MonitorJobFailures(failureHandler) + go func() { + err := jobSupervisor.MonitorJobFailures(failureHandler) + Expect(err).NotTo(HaveOccurred()) + }() _, err := addFlappingJob(jobSupervisor, jobDir, fs) Expect(err).To(Succeed()) @@ -1070,7 +1081,10 @@ var _ = Describe("WindowsJobSupervisor", func() { return } - go jobSupervisor.MonitorJobFailures(failureHandler) + go func() { + err := jobSupervisor.MonitorJobFailures(failureHandler) + Expect(err).NotTo(HaveOccurred()) + }() err := doJobFailureRequest(failureRequest, jobFailuresServerPort) Expect(err).ToNot(HaveOccurred()) @@ -1085,7 +1099,10 @@ var _ = Describe("WindowsJobSupervisor", func() { handledAlert.Set(alert) return } - go jobSupervisor.MonitorJobFailures(failureHandler) + go func() { + err := jobSupervisor.MonitorJobFailures(failureHandler) + Expect(err).NotTo(HaveOccurred()) + }() // Unmonitor jobs Expect(jobSupervisor.Unmonitor()).To(Succeed()) @@ -1103,7 +1120,10 @@ var _ = Describe("WindowsJobSupervisor", func() { handledAlert.Set(alert) return } - go jobSupervisor.MonitorJobFailures(failureHandler) + go func() { + err := jobSupervisor.MonitorJobFailures(failureHandler) + Expect(err).NotTo(HaveOccurred()) + }() // Unmonitor jobs Expect(jobSupervisor.Unmonitor()).To(Succeed()) @@ -1130,7 +1150,10 @@ var _ = Describe("WindowsJobSupervisor", func() { atomic.StoreInt32(&didHandleAlert, 1) return } - go jobSupervisor.MonitorJobFailures(failureHandler) + go func() { + err := jobSupervisor.MonitorJobFailures(failureHandler) + Expect(err).NotTo(HaveOccurred()) + }() err := doJobFailureRequest(`some bad request`, jobFailuresServerPort) Expect(err).ToNot(HaveOccurred()) @@ -1141,7 +1164,10 @@ var _ = Describe("WindowsJobSupervisor", func() { It("returns an error when it fails to bind", func() { failureHandler := func(alert boshalert.MonitAlert) (err error) { return } - go jobSupervisor.MonitorJobFailures(failureHandler) + go func() { + err := jobSupervisor.MonitorJobFailures(failureHandler) + Expect(err).NotTo(HaveOccurred()) + }() time.Sleep(50 * time.Millisecond) err := jobSupervisor.MonitorJobFailures(failureHandler) Expect(err).To(HaveOccurred()) @@ -1201,7 +1227,7 @@ var _ = Describe("WindowsJobSupervisor", func() { } }) - It("uses 'startargument' instead of 'argment'", func() { + It("uses 'startargument' instead of 'arguments'", func() { proc.Stop = &StopCommand{ Executable: "STOPPER", Args: []string{"Stop_1", "Stop_2"}, diff --git a/jobsupervisor/wrapper_job_supervisor_test.go b/jobsupervisor/wrapper_job_supervisor_test.go index 84fa3fae3..acc8ab1aa 100644 --- a/jobsupervisor/wrapper_job_supervisor_test.go +++ b/jobsupervisor/wrapper_job_supervisor_test.go @@ -28,7 +28,8 @@ var _ = Describe("WrapperJobSupervisor", func() { BeforeEach(func() { fs = fakesys.NewFakeFileSystem() - fs.MkdirAll("/var/vcap/instance", 666) + err := fs.MkdirAll("/var/vcap/instance", 0666) + Expect(err).NotTo(HaveOccurred()) logger = boshlog.NewLogger(boshlog.LevelNone) dirProvider = boshdir.NewProvider("/var/vcap") @@ -43,58 +44,60 @@ var _ = Describe("WrapperJobSupervisor", func() { }) It("Reload should delegate to the underlying job supervisor", func() { - error := errors.New("BOOM") - fakeSupervisor.ReloadErr = error + boomError := errors.New("BOOM") + fakeSupervisor.ReloadErr = boomError err := wrapper.Reload() Expect(fakeSupervisor.Reloaded).To(BeTrue()) - Expect(err).To(Equal(error)) + Expect(err).To(Equal(boomError)) }) Describe("Start", func() { It("should delegate to the underlying job supervisor", func() { - error := errors.New("BOOM") - fakeSupervisor.StartErr = error + boomError := errors.New("BOOM") + fakeSupervisor.StartErr = boomError err := wrapper.Start() Expect(fakeSupervisor.Started).To(BeTrue()) - Expect(err).To(Equal(error)) + Expect(err).To(Equal(boomError)) }) It("write the health json asynchronously", func() { fakeSupervisor.StatusStatus = "running" - wrapper.Start() + err := wrapper.Start() + Expect(err).NotTo(HaveOccurred()) healthFile := filepath.Join(dirProvider.InstanceDir(), "health.json") healthRaw, err := fs.ReadFile(healthFile) Expect(err).ToNot(HaveOccurred()) health := &Health{} - json.Unmarshal(healthRaw, health) + err = json.Unmarshal(healthRaw, health) + Expect(err).NotTo(HaveOccurred()) Expect(health.State).To(Equal("running")) }) }) It("Stop should delegate to the underlying job supervisor", func() { - error := errors.New("BOOM") - fakeSupervisor.StopErr = error + boomError := errors.New("BOOM") + fakeSupervisor.StopErr = boomError err := wrapper.Stop() Expect(fakeSupervisor.Stopped).To(BeTrue()) - Expect(err).To(Equal(error)) + Expect(err).To(Equal(boomError)) }) It("StopAndWait should delegate to the underlying job supervisor", func() { - error := errors.New("BOOM") - fakeSupervisor.StopErr = error + boomError := errors.New("BOOM") + fakeSupervisor.StopErr = boomError err := wrapper.StopAndWait() Expect(fakeSupervisor.StoppedAndWaited).To(BeTrue()) - Expect(err).To(Equal(error)) + Expect(err).To(Equal(boomError)) }) Describe("Unmointor", func() { It("Unmonitor should delegate to the underlying job supervisor", func() { - error := errors.New("BOOM") - fakeSupervisor.UnmonitorErr = error + boomError := errors.New("BOOM") + fakeSupervisor.UnmonitorErr = boomError err := wrapper.Unmonitor() Expect(fakeSupervisor.Unmonitored).To(BeTrue()) - Expect(err).To(Equal(error)) + Expect(err).To(Equal(boomError)) }) It("write the health json asynchronously", func() { @@ -105,7 +108,8 @@ var _ = Describe("WrapperJobSupervisor", func() { healthRaw, err := fs.ReadFile(healthFile) Expect(err).ToNot(HaveOccurred()) health := &Health{} - json.Unmarshal(healthRaw, health) + err = json.Unmarshal(healthRaw, health) + Expect(err).NotTo(HaveOccurred()) Expect(health.State).To(Equal("stopped")) }) @@ -128,8 +132,8 @@ var _ = Describe("WrapperJobSupervisor", func() { }) It("AddJob should delegate to the underlying job supervisor", func() { - error := errors.New("BOOM") - fakeSupervisor.StartErr = error + boomError := errors.New("BOOM") + fakeSupervisor.StartErr = boomError _ = wrapper.AddJob("name", 0, "path") Expect(fakeSupervisor.AddJobArgs).To(Equal([]fakes.AddJobArgs{ { diff --git a/mbus/handler_provider_test.go b/mbus/handler_provider_test.go index faef9de77..41abba594 100644 --- a/mbus/handler_provider_test.go +++ b/mbus/handler_provider_test.go @@ -1,12 +1,13 @@ package mbus_test import ( - "github.com/cloudfoundry/bosh-agent/mbus/mbusfakes" - "github.com/nats-io/nats.go" gourl "net/url" "reflect" "time" + "github.com/cloudfoundry/bosh-agent/mbus/mbusfakes" + "github.com/nats-io/nats.go" + . "github.com/cloudfoundry/bosh-agent/mbus" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" @@ -80,6 +81,7 @@ var _ = Describe("HandlerProvider", func() { logger, auditLogger, ) + Expect(err).NotTo(HaveOccurred()) httpsHandler, ok := handler.(HTTPSHandler) Expect(ok).To(BeTrue()) Expect(reflect.DeepEqual(httpsHandler, expectedHandler)).To(BeTrue()) diff --git a/mbus/https_dispatcher_test.go b/mbus/https_dispatcher_test.go index e342adbe0..3bfef68c0 100644 --- a/mbus/https_dispatcher_test.go +++ b/mbus/https_dispatcher_test.go @@ -66,7 +66,7 @@ QgK94NXJDoDd1OZjpUBMPLVa8d20/RdGNW8OMolJpzEPhg0r7Ac= -----END RSA PRIVATE KEY-----` // Confirm the targetURL is valid and can be listened on before running tests. -func init() { +func init() { //nolint:gochecknoinits u, err := url.Parse(targetURL) if err != nil { panic(fmt.Sprintf("Invalid target URL: %s", err)) @@ -141,9 +141,9 @@ var _ = Describe("HTTPSDispatcher", func() { dispatcher.AddRoute("/example", handler) tlsConfig := &tls.Config{ - InsecureSkipVerify: true, - MinVersion: tls.VersionSSL30, - MaxVersion: tls.VersionSSL30, + InsecureSkipVerify: true, //nolint:gosec + MinVersion: tls.VersionSSL30, //nolint:staticcheck + MaxVersion: tls.VersionSSL30, //nolint:staticcheck } client := getHTTPClientWithConfig(tlsConfig) _, err := client.Get(targetURL + "/example") @@ -155,7 +155,7 @@ var _ = Describe("HTTPSDispatcher", func() { dispatcher.AddRoute("/example", handler) tlsConfig := &tls.Config{ - InsecureSkipVerify: true, + InsecureSkipVerify: true, //nolint:gosec MinVersion: tls.VersionTLS10, MaxVersion: tls.VersionTLS10, } @@ -169,7 +169,7 @@ var _ = Describe("HTTPSDispatcher", func() { dispatcher.AddRoute("/example", handler) tlsConfig := &tls.Config{ - InsecureSkipVerify: true, + InsecureSkipVerify: true, //nolint:gosec MinVersion: tls.VersionTLS11, MaxVersion: tls.VersionTLS11, } @@ -183,7 +183,7 @@ var _ = Describe("HTTPSDispatcher", func() { dispatcher.AddRoute("/example", handler) tlsConfig := &tls.Config{ - InsecureSkipVerify: true, + InsecureSkipVerify: true, //nolint:gosec MinVersion: tls.VersionTLS12, MaxVersion: tls.VersionTLS12, } @@ -197,7 +197,7 @@ var _ = Describe("HTTPSDispatcher", func() { dispatcher.AddRoute("/example", handler) tlsConfig := &tls.Config{ - InsecureSkipVerify: true, + InsecureSkipVerify: true, //nolint:gosec MinVersion: tls.VersionTLS12, MaxVersion: tls.VersionTLS12, CipherSuites: []uint16{ @@ -215,7 +215,7 @@ var _ = Describe("HTTPSDispatcher", func() { dispatcher.AddRoute("/example", handler) tlsConfig := &tls.Config{ - InsecureSkipVerify: true, + InsecureSkipVerify: true, //nolint:gosec MinVersion: tls.VersionTLS12, MaxVersion: tls.VersionTLS12, CipherSuites: []uint16{ @@ -234,7 +234,7 @@ var _ = Describe("HTTPSDispatcher", func() { dispatcher.AddRoute("/example", handler) tlsConfig := &tls.Config{ - InsecureSkipVerify: true, + InsecureSkipVerify: true, //nolint:gosec CipherSuites: []uint16{ tls.TLS_RSA_WITH_AES_128_CBC_SHA, tls.TLS_RSA_WITH_AES_256_CBC_SHA, @@ -281,7 +281,7 @@ var _ = Describe("HTTPSDispatcher", func() { func getHTTPClient() http.Client { tlsConfig := &tls.Config{ - InsecureSkipVerify: true, + InsecureSkipVerify: true, //nolint:gosec // Both CBC & RC4 ciphers can be exploited // Mozilla's "Modern" recommended settings only overlap with the golang TLS client on these two ciphers CipherSuites: []uint16{ diff --git a/mbus/https_handler_test.go b/mbus/https_handler_test.go index 414600eef..bf3ef7c82 100644 --- a/mbus/https_handler_test.go +++ b/mbus/https_handler_test.go @@ -67,7 +67,7 @@ var _ = Describe("HTTPSHandler", func() { logger := boshlog.NewWriterLogger(boshlog.LevelDebug, GinkgoWriter) handler = NewHTTPSHandler(mbusURL, mbusKeyPair, blobManager, logger, fakes.NewFakeAuditLogger()) - go handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) { + go handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) { //nolint:errcheck receivedRequest = req return boshhandler.NewValueResponse("expected value") }) @@ -77,7 +77,7 @@ var _ = Describe("HTTPSHandler", func() { authority := x509.NewCertPool() Expect(authority.AppendCertsFromPEM(caCert)).To(BeTrue()) - httpTransport := &http.Transport{TLSClientConfig: &tls.Config{RootCAs: authority}} + httpTransport := &http.Transport{TLSClientConfig: &tls.Config{RootCAs: authority}} //nolint:gosec httpClient = http.Client{Timeout: 5 * time.Second, Transport: httpTransport} waitForServerToStart(serverURL, httpClient) @@ -208,7 +208,7 @@ var _ = Describe("HTTPSHandler", func() { putBody := `Updated data` putPayload := strings.NewReader(putBody) - httpRequest, err := http.NewRequest("PUT", strings.Replace(serverURL, "pass", "wrong", -1)+"/blobs/a5/123-456-789", putPayload) + httpRequest, err := http.NewRequest("PUT", strings.ReplaceAll(serverURL, "pass", "wrong")+"/blobs/a5/123-456-789", putPayload) Expect(err).NotTo(HaveOccurred()) httpResponse, err := httpClient.Do(httpRequest) Expect(err).ToNot(HaveOccurred()) @@ -223,7 +223,7 @@ var _ = Describe("HTTPSHandler", func() { }) Describe("routing and auth", func() { - Context("when an incorrect uri is specificed", func() { + Context("when an incorrect uri is specified", func() { It("returns a 404", func() { postBody := `{"method":"ping","arguments":["foo","bar"], "reply_to": "reply to me!"}` postPayload := strings.NewReader(postBody) @@ -241,7 +241,7 @@ var _ = Describe("HTTPSHandler", func() { postBody := `{"method":"ping","arguments":["foo","bar"], "reply_to": "reply to me!"}` postPayload := strings.NewReader(postBody) - httpResponse, err := httpClient.Post(strings.Replace(serverURL, "pass", "wrong", -1)+"/agent", "application/json", postPayload) + httpResponse, err := httpClient.Post(strings.ReplaceAll(serverURL, "pass", "wrong")+"/agent", "application/json", postPayload) Expect(err).ToNot(HaveOccurred()) defer httpResponse.Body.Close() @@ -256,7 +256,7 @@ var _ = Describe("HTTPSHandler", func() { func waitForServerToStart(serverURL string, httpClient http.Client) { Eventually(func() error { - httpResponse, err := httpClient.Get(serverURL + "/healthz") + httpResponse, err := httpClient.Get(serverURL + "/healthz") //nolint:noctx if err == nil { httpResponse.Body.Close() } diff --git a/mbus/nats_handler.go b/mbus/nats_handler.go index e794bc551..566f5ce1f 100644 --- a/mbus/nats_handler.go +++ b/mbus/nats_handler.go @@ -4,7 +4,6 @@ import ( "encoding/json" "errors" "fmt" - "github.com/nats-io/nats.go" "net" "net/url" "os" @@ -13,6 +12,8 @@ import ( "sync" "syscall" + "github.com/nats-io/nats.go" + "crypto/x509" "time" @@ -53,7 +54,6 @@ type NatsConnection interface { Close() Publish(subj string, data []byte) error Subscribe(subj string, cb nats.MsgHandler) (*nats.Subscription, error) - //Subscribe(subject string, f func(natsMsg *nats.Msg)) (interface{}, error) } type natsHandler struct { @@ -206,13 +206,13 @@ func (h *natsHandler) Stop() { } func (h *natsHandler) VerifyPeerCertificate(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error { + natsBoshInternalsRegexp := regexp.MustCompile(`^[a-zA-Z0-9*\-]*.nats.bosh-internal$`) for _, chain := range verifiedChains { if len(chain) == 0 { continue } commonName := chain[0].Subject.CommonName - match, _ := regexp.MatchString("^[a-zA-Z0-9*\\-]*.nats.bosh-internal$", commonName) - if match { + if natsBoshInternalsRegexp.MatchString(commonName) { return nil } } @@ -248,16 +248,13 @@ func (h *natsHandler) handleNatsMsg(natsMsg *nats.Msg, handlerFunc boshhandler.F func (h *natsHandler) runUntilInterrupted() { defer h.connection.Close() - keepRunning := true - c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, syscall.SIGTERM) + keepRunning := true for keepRunning { - select { - case <-c: - keepRunning = false - } + <-c + keepRunning = false } } diff --git a/mbus/nats_handler_test.go b/mbus/nats_handler_test.go index 6cf86dc73..0ba364bb1 100644 --- a/mbus/nats_handler_test.go +++ b/mbus/nats_handler_test.go @@ -6,11 +6,12 @@ import ( "crypto/x509" "encoding/pem" "errors" - "github.com/cloudfoundry/bosh-agent/mbus/mbusfakes" - "github.com/nats-io/nats.go" "io/ioutil" "time" + "github.com/cloudfoundry/bosh-agent/mbus/mbusfakes" + "github.com/nats-io/nats.go" + . "github.com/cloudfoundry/bosh-agent/mbus" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" @@ -24,7 +25,7 @@ import ( boshlog "github.com/cloudfoundry/bosh-utils/logger" ) -func init() { +func init() { //nolint:funlen,gochecknoinits Describe("natsHandler", func() { var ( settingsService *fakesettings.FakeSettingsService @@ -83,10 +84,11 @@ func init() { It("starts", func() { var receivedRequest boshhandler.Request - handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) { + err := handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) { receivedRequest = req return boshhandler.NewValueResponse("expected value") }) + Expect(err).NotTo(HaveOccurred()) defer handler.Stop() Expect(connection.SubscribeCallCount()).To(Equal(1)) @@ -112,9 +114,10 @@ func init() { }) It("cleans up ip-mac address cache for nats configured with ip address", func() { - handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) { + err := handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) { return nil }) + Expect(err).NotTo(HaveOccurred()) defer handler.Stop() Expect(platform.DeleteARPEntryWithIPArgsForCall(0)).To(Equal("127.0.0.1")) @@ -122,9 +125,10 @@ func init() { It("does not try to clean up ip-mac address cache for nats configured with hostname", func() { settingsService.Settings.Mbus = "nats://fake-username:fake-password@fake-hostname.com:1234" - handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) { + err := handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) { return nil }) + Expect(err).NotTo(HaveOccurred()) defer handler.Stop() Expect(platform.DeleteARPEntryWithIPCallCount()).To(Equal(0)) @@ -132,9 +136,10 @@ func init() { It("logs error and proceeds if it fails to clean up ip-mac address cache for nats", func() { platform.DeleteARPEntryWithIPReturns(errors.New("failed to run")) - handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) { + err := handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) { return nil }) + Expect(err).NotTo(HaveOccurred()) defer handler.Stop() Expect(platform.DeleteARPEntryWithIPArgsForCall(0)).To(Equal("127.0.0.1")) @@ -184,10 +189,11 @@ func init() { It("can add additional handler funcs to receive requests", func() { var firstHandlerReq, secondHandlerRequest boshhandler.Request - handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) { + err := handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) { firstHandlerReq = req return boshhandler.NewValueResponse("first-handler-resp") }) + Expect(err).NotTo(HaveOccurred()) defer handler.Stop() handler.RegisterAdditionalFunc(func(req boshhandler.Request) (resp boshhandler.Response) { @@ -284,7 +290,7 @@ func init() { Context("when NATs handler fails to publish", func() { It("logs to syslog error", func() { - connection.PublishReturns(errors.New("Oh noes!")) + connection.PublishReturns(errors.New("oh noes")) err := handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) { return boshhandler.NewValueResponse("responding") @@ -300,7 +306,7 @@ func init() { Expect(auditLogger.DebugCallCount()).To(Equal(0)) Expect(auditLogger.ErrCallCount()).To(Equal(1)) - msg := `cs1=Oh noes! cs1Label=statusReason` + msg := `cs1=oh noes cs1Label=statusReason` Expect(auditLogger.ErrArgsForCall(0)).To(ContainSubstring(msg)) }) }) @@ -321,7 +327,8 @@ func init() { options := nats.Options{} for _, option := range connectorOptionsArg { - option(&options) + err := option(&options) + Expect(err).NotTo(HaveOccurred()) } Expect(options.TLSConfig.RootCAs.Subjects()).To(BeEquivalentTo(certPool.Subjects())) @@ -393,7 +400,8 @@ func init() { options := nats.Options{} for _, option := range connectorOptionsArg { - option(&options) + err := option(&options) + Expect(err).NotTo(HaveOccurred()) } Expect(options.TLSConfig.RootCAs).To(BeNil()) @@ -423,7 +431,6 @@ func init() { }) }) }) - } func VerifyPeerCertificateCallback(handler boshhandler.Handler, connectorOptionsArg []nats.Option, certPath string, caPath string) error { @@ -434,10 +441,12 @@ func VerifyPeerCertificateCallback(handler boshhandler.Handler, connectorOptions correctCa, err := ioutil.ReadFile(caPath) Expect(err).NotTo(HaveOccurred()) - certPemBlock, _ := pem.Decode([]byte(correctCnCert)) + certPemBlock, _ := pem.Decode(correctCnCert) cert, err := x509.ParseCertificate(certPemBlock.Bytes) - caPemBlock, _ := pem.Decode([]byte(correctCa)) + Expect(err).NotTo(HaveOccurred()) + caPemBlock, _ := pem.Decode(correctCa) ca, err := x509.ParseCertificate(caPemBlock.Bytes) + Expect(err).NotTo(HaveOccurred()) errHandler := handler.Start(func(req boshhandler.Request) (res boshhandler.Response) { return }) Expect(errHandler).ToNot(HaveOccurred()) @@ -445,7 +454,8 @@ func VerifyPeerCertificateCallback(handler boshhandler.Handler, connectorOptions options := nats.Options{} for _, option := range connectorOptionsArg { - option(&options) + err := option(&options) + Expect(err).NotTo(HaveOccurred()) } certPool := x509.NewCertPool() diff --git a/platform/bootstrap_state_test.go b/platform/bootstrap_state_test.go index 9da0db226..a24e0ec21 100644 --- a/platform/bootstrap_state_test.go +++ b/platform/bootstrap_state_test.go @@ -28,7 +28,8 @@ var _ = Describe("State", func() { Describe("SaveState", func() { It("saves the state file with the appropriate properties", func() { s.Linux = platform.LinuxState{HostsConfigured: true} - s.SaveState() + err := s.SaveState() + Expect(err).NotTo(HaveOccurred()) contents, readerr := fs.ReadFile(path) @@ -38,7 +39,8 @@ var _ = Describe("State", func() { It("saves the state file with the properties passed in", func() { s.Linux = platform.LinuxState{HostsConfigured: true} - s.SaveState() + err := s.SaveState() + Expect(err).NotTo(HaveOccurred()) contents, readerr := fs.ReadFile(path) @@ -82,10 +84,11 @@ var _ = Describe("State", func() { Context("When the agent cannot read the state file due to a failed disk", func() { It("returns an error and a state object with false properties", func() { - fs.WriteFileString(path, `{ + err := fs.WriteFileString(path, `{ "hosts_configured": true, "hostname_configured": true }`) + Expect(err).NotTo(HaveOccurred()) fs.RegisterReadFileError(path, errors.New("ENXIO: disk failed")) @@ -97,7 +100,8 @@ var _ = Describe("State", func() { Context("When the agent cannot parse the state file due to malformed JSON", func() { It("returns an error and a state object with false properties", func() { - fs.WriteFileString(path, "malformed-JSON") + err := fs.WriteFileString(path, "malformed-JSON") + Expect(err).NotTo(HaveOccurred()) _, readerr := platform.NewBootstrapState(fs, path) diff --git a/platform/cert/cert_manager_test.go b/platform/cert/cert_manager_test.go index a05597477..4e7f8c571 100644 --- a/platform/cert/cert_manager_test.go +++ b/platform/cert/cert_manager_test.go @@ -116,9 +116,12 @@ var _ = Describe("Certificate Management", func() { }) It("only deletes the files with the given prefix", func() { - fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_1.foo", "goodbye") - fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_2.foo", "goodbye") - fakeFs.WriteFileString("/path/to/delete/stuff/in/different_file_1.bar", "goodbye") + err := fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_1.foo", "goodbye") + Expect(err).NotTo(HaveOccurred()) + err = fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_2.foo", "goodbye") + Expect(err).NotTo(HaveOccurred()) + err = fakeFs.WriteFileString("/path/to/delete/stuff/in/different_file_1.bar", "goodbye") + Expect(err).NotTo(HaveOccurred()) fakeFs.SetGlob("/path/to/delete/stuff/in/delete_me_*", []string{ "/path/to/delete/stuff/in/delete_me_1.foo", "/path/to/delete/stuff/in/delete_me_2.foo", @@ -130,9 +133,12 @@ var _ = Describe("Certificate Management", func() { }) It("only deletes the files in the given path", func() { - fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_1.foo", "goodbye") - fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_2.foo", "goodbye") - fakeFs.WriteFileString("/path/to/other/things/in/delete_me_3.foo", "goodbye") + err := fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_1.foo", "goodbye") + Expect(err).NotTo(HaveOccurred()) + err = fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_2.foo", "goodbye") + Expect(err).NotTo(HaveOccurred()) + err = fakeFs.WriteFileString("/path/to/other/things/in/delete_me_3.foo", "goodbye") + Expect(err).NotTo(HaveOccurred()) fakeFs.SetGlob("/path/to/delete/stuff/in/delete_me_*", []string{ "/path/to/delete/stuff/in/delete_me_1.foo", "/path/to/delete/stuff/in/delete_me_2.foo", @@ -146,8 +152,10 @@ var _ = Describe("Certificate Management", func() { It("returns an error when glob fails", func() { fakeFs.GlobErr = errors.New("couldn't walk") - fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_1.foo", "goodbye") - fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_2.bar", "goodbye") + err := fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_1.foo", "goodbye") + Expect(err).NotTo(HaveOccurred()) + err = fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_2.bar", "goodbye") + Expect(err).NotTo(HaveOccurred()) count, err := cert.DeleteFiles(fakeFs, "/path/to/delete/stuff/in/", "delete_me_") Expect(err).To(HaveOccurred()) Expect(count).To(Equal(0)) @@ -157,8 +165,10 @@ var _ = Describe("Certificate Management", func() { fakeFs.RemoveAllStub = func(_ string) error { return errors.New("couldn't delete") } - fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_1.foo", "goodbye") - fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_2.bar", "goodbye") + err := fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_1.foo", "goodbye") + Expect(err).NotTo(HaveOccurred()) + err = fakeFs.WriteFileString("/path/to/delete/stuff/in/delete_me_2.bar", "goodbye") + Expect(err).NotTo(HaveOccurred()) fakeFs.SetGlob("/path/to/delete/stuff/in/delete_me_*", []string{ "/path/to/delete/stuff/in/delete_me_1.foo", "/path/to/delete/stuff/in/delete_me_2.bar", @@ -194,16 +204,17 @@ var _ = Describe("Certificate Management", func() { }) It("deletes all certs when passed an empty string", func() { - fakeFs.WriteFileString(fmt.Sprintf("%s/bosh-trusted-cert-1.crt", certBasePath), "goodbye") + err := fakeFs.WriteFileString(fmt.Sprintf("%s/bosh-trusted-cert-1.crt", certBasePath), "goodbye") + Expect(err).NotTo(HaveOccurred()) fakeFs.SetGlob(fmt.Sprintf("%s/bosh-trusted-cert-*", certBasePath), []string{ fmt.Sprintf("%s/bosh-trusted-cert-1.crt", certBasePath), }) - err := certManager.UpdateCertificates("") + err = certManager.UpdateCertificates("") Expect(err).NotTo(HaveOccurred()) Expect(fakeFs.FileExists(fmt.Sprintf("%s/bosh-trusted-cert-1.crt", certBasePath))).To(BeFalse()) }) - It("deletes exisitng cert files before writing new ones", func() { + It("deletes existing cert files before writing new ones", func() { certs := fmt.Sprintf("%s\n%s\n", cert1, cert1) err := certManager.UpdateCertificates(certs) Expect(err).NotTo(HaveOccurred()) @@ -215,7 +226,8 @@ var _ = Describe("Certificate Management", func() { fmt.Sprintf("%s/bosh-trusted-cert-1.crt", certBasePath), fmt.Sprintf("%s/bosh-trusted-cert-2.crt", certBasePath), }) - certManager.UpdateCertificates(cert1) + err = certManager.UpdateCertificates(cert1) + Expect(err).NotTo(HaveOccurred()) Expect(fakeFs.FileExists(fmt.Sprintf("%s/bosh-trusted-cert-1.crt", certBasePath))).To(BeTrue()) Expect(countFiles(fakeFs, certBasePath)).To(Equal(1)) }) @@ -230,12 +242,13 @@ var _ = Describe("Certificate Management", func() { fakeFs.RemoveAllStub = func(_ string) error { return errors.New("NOT ALLOW") } - fakeFs.WriteFileString(fmt.Sprintf("%s/bosh-trusted-cert-1.crt", certBasePath), "goodbye") + err := fakeFs.WriteFileString(fmt.Sprintf("%s/bosh-trusted-cert-1.crt", certBasePath), "goodbye") + Expect(err).NotTo(HaveOccurred()) fakeFs.SetGlob(fmt.Sprintf("%s/bosh-trusted-cert-*", certBasePath), []string{ fmt.Sprintf("%s/bosh-trusted-cert-1.crt", certBasePath), }) - err := certManager.UpdateCertificates("") + err = certManager.UpdateCertificates("") Expect(err).To(HaveOccurred()) }) } @@ -396,7 +409,7 @@ if (Test-Path %[1]s) { AfterEach(func() { for _, thumbprint := range certThumbprints { - cmd := exec.Command("powershell", "-Command", fmt.Sprintf(removeCertScript, `Cert:\LocalMachine\Root\`+thumbprint)) + cmd := exec.Command("powershell", "-Command", fmt.Sprintf(removeCertScript, `Cert:\LocalMachine\Root\`+thumbprint)) //nolint:gosec session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter) Expect(err).To(BeNil()) Eventually(session).Should(gexec.Exit(0)) @@ -458,12 +471,13 @@ if (Test-Path %[1]s) { }) func countFiles(fs system.FileSystem, dir string) (count int) { - fs.Walk(dir, func(path string, info os.FileInfo, err error) error { - if filepath.Join(path) == filepath.Join(dir) { + err := fs.Walk(dir, func(path string, info os.FileInfo, err error) error { + if filepath.Join(path) == filepath.Join(dir) { //nolint:gocritic return nil } count++ return nil }) + Expect(err).NotTo(HaveOccurred()) return } diff --git a/platform/delayed_audit_logger_unix_test.go b/platform/delayed_audit_logger_unix_test.go index 76572dd57..8e474e5ad 100644 --- a/platform/delayed_audit_logger_unix_test.go +++ b/platform/delayed_audit_logger_unix_test.go @@ -90,7 +90,7 @@ var _ = Describe("Delayed Audit Logger", func() { Context("when there is no debug audit logger available", func() { It("should retry until audit logger is available", func() { - auditLoggerProvider.SetDebugLoggerError(errors.New("Problems!")) + auditLoggerProvider.SetDebugLoggerError(errors.New("fake error")) delayedAuditLogger.StartLogging() Eventually(func() int { @@ -98,13 +98,13 @@ var _ = Describe("Delayed Audit Logger", func() { }).Should(Equal(1)) _, err, _ := logger.ErrorArgsForCall(0) - Expect(err).To(ContainSubstring("Problems!")) + Expect(err).To(ContainSubstring("fake error")) }) }) Context("when there is no error audit logger available", func() { It("should retry until audit logger is available", func() { - auditLoggerProvider.SetErrorLoggerError(errors.New("Problems!")) + auditLoggerProvider.SetErrorLoggerError(errors.New("fake error")) delayedAuditLogger.StartLogging() Eventually(func() int { @@ -112,7 +112,7 @@ var _ = Describe("Delayed Audit Logger", func() { }).Should(Equal(1)) _, err, _ := logger.ErrorArgsForCall(0) - Expect(err).To(ContainSubstring("Problems!")) + Expect(err).To(ContainSubstring("fake error")) }) }) }) diff --git a/platform/disk/diskutil_test.go b/platform/disk/diskutil_test.go index a438c9633..0f6a00d74 100644 --- a/platform/disk/diskutil_test.go +++ b/platform/disk/diskutil_test.go @@ -39,10 +39,13 @@ var _ = Describe("Diskutil", func() { Context("when disk path does not exist", func() { BeforeEach(func() { - fs.MkdirAll("fake-disk-path", 0700) + err := fs.MkdirAll("fake-disk-path", 0700) + Expect(err).NotTo(HaveOccurred()) fs.TempDirDir = "fake-tempdir" - fs.WriteFileString("fake-tempdir/fake-file-path-1", "fake-contents-1") - fs.WriteFileString("fake-tempdir/fake-file-path-2", "fake-contents-2") + err = fs.WriteFileString("fake-tempdir/fake-file-path-1", "fake-contents-1") + Expect(err).NotTo(HaveOccurred()) + err = fs.WriteFileString("fake-tempdir/fake-file-path-2", "fake-contents-2") + Expect(err).NotTo(HaveOccurred()) }) It("mounts disk path to temporary directory", func() { diff --git a/platform/disk/ephemeral_device_partitioner_test.go b/platform/disk/ephemeral_device_partitioner_test.go index 8835fbed4..2bfd94c40 100644 --- a/platform/disk/ephemeral_device_partitioner_test.go +++ b/platform/disk/ephemeral_device_partitioner_test.go @@ -2,6 +2,7 @@ package disk_test import ( "errors" + . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" @@ -42,9 +43,10 @@ var _ = Describe("EphemeralDevicePartitioner", func() { fakeCmdRunner = fakesys.NewFakeCmdRunner() fakefs = fakesys.NewFakeFileSystem() - fakefs.WriteFile("/setting/path.json", []byte(`{ + err := fakefs.WriteFile("/setting/path.json", []byte(`{ "agent_id":"fake-agent-id" }`)) + Expect(err).NotTo(HaveOccurred()) logger = boshlog.NewLogger(boshlog.LevelNone) fakeCmdRunner = fakesys.NewFakeCmdRunner() @@ -299,7 +301,7 @@ var _ = Describe("EphemeralDevicePartitioner", func() { fakeCmdRunner.AddCmdResult( "parted -m /dev/edx unit B print", fakesys.FakeCmdResult{ - Stdout: "Some weird error", ExitStatus: 1, Error: errors.New("Some weird error")}, + Stdout: "some weird error", ExitStatus: 1, Error: errors.New("some weird error")}, ) }) diff --git a/platform/disk/linux_formatter_test.go b/platform/disk/linux_formatter_test.go index 1b53354a3..8115c805d 100644 --- a/platform/disk/linux_formatter_test.go +++ b/platform/disk/linux_formatter_test.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" + . "github.com/cloudfoundry/bosh-agent/platform/disk" fakesys "github.com/cloudfoundry/bosh-utils/system/fakes" ) @@ -19,7 +20,8 @@ var _ = Describe("Linux Formatter", func() { fakeRunner.AddCmdResult("blkid -p /dev/xvda2", fakesys.FakeCmdResult{ExitStatus: 2, Error: errors.New("Exit code 2")}) formatter := NewLinuxFormatter(fakeRunner, fakeFs) - formatter.Format("/dev/xvda2", FileSystemSwap) + err := formatter.Format("/dev/xvda2", FileSystemSwap) + Expect(err).NotTo(HaveOccurred()) Expect(2).To(Equal(len(fakeRunner.RunCommands))) Expect(fakeRunner.RunCommands[1]).To(Equal([]string{"mkswap", "/dev/xvda2"})) @@ -31,7 +33,8 @@ var _ = Describe("Linux Formatter", func() { fakeRunner.AddCmdResult("blkid -p /dev/xvda1", fakesys.FakeCmdResult{Stdout: `xxxxx TYPE="ext4" yyyy zzzz`}) formatter := NewLinuxFormatter(fakeRunner, fakeFs) - formatter.Format("/dev/xvda1", FileSystemSwap) + err := formatter.Format("/dev/xvda1", FileSystemSwap) + Expect(err).NotTo(HaveOccurred()) Expect(2).To(Equal(len(fakeRunner.RunCommands))) Expect(fakeRunner.RunCommands[1]).To(Equal([]string{"mkswap", "/dev/xvda1"})) @@ -43,7 +46,8 @@ var _ = Describe("Linux Formatter", func() { fakeRunner.AddCmdResult("blkid -p /dev/xvda1", fakesys.FakeCmdResult{Stdout: `xxxxx TYPE="swap" yyyy zzzz`}) formatter := NewLinuxFormatter(fakeRunner, fakeFs) - formatter.Format("/dev/xvda1", FileSystemSwap) + err := formatter.Format("/dev/xvda1", FileSystemSwap) + Expect(err).NotTo(HaveOccurred()) Expect(1).To(Equal(len(fakeRunner.RunCommands))) Expect(fakeRunner.RunCommands[0]).To(Equal([]string{"blkid", "-p", "/dev/xvda1"})) @@ -54,11 +58,13 @@ var _ = Describe("Linux Formatter", func() { It("allows lazy itable support", func() { fakeRunner := fakesys.NewFakeCmdRunner() fakeFs := fakesys.NewFakeFileSystem() - fakeFs.WriteFile("/sys/fs/ext4/features/lazy_itable_init", []byte{}) + err := fakeFs.WriteFile("/sys/fs/ext4/features/lazy_itable_init", []byte{}) + Expect(err).NotTo(HaveOccurred()) fakeRunner.AddCmdResult("blkid -p /dev/xvda2", fakesys.FakeCmdResult{Stdout: `xxxxx TYPE="ext2" yyyy zzzz`}) formatter := NewLinuxFormatter(fakeRunner, fakeFs) - formatter.Format("/dev/xvda2", FileSystemExt4) + err = formatter.Format("/dev/xvda2", FileSystemExt4) + Expect(err).NotTo(HaveOccurred()) Expect(2).To(Equal(len(fakeRunner.RunCommands))) Expect(fakeRunner.RunCommands[1]).To(Equal([]string{"mke2fs", "-t", "ext4", "-j", "-E", "lazy_itable_init=1", "/dev/xvda2"})) @@ -72,7 +78,8 @@ var _ = Describe("Linux Formatter", func() { BeforeEach(func() { fakeRunner = fakesys.NewFakeCmdRunner() fakeFs = fakesys.NewFakeFileSystem() - fakeFs.WriteFile("/sys/fs/ext4/features/lazy_itable_init", []byte{}) + err := fakeFs.WriteFile("/sys/fs/ext4/features/lazy_itable_init", []byte{}) + Expect(err).NotTo(HaveOccurred()) fakeRunner.AddCmdResult("blkid -p /dev/xvda2", fakesys.FakeCmdResult{Stdout: `xxxxx TYPE="ext2" yyyy zzzz`}) mkeCmd = fmt.Sprintf("mke2fs -t %s -j -E lazy_itable_init=1 %s", FileSystemExt4, "/dev/xvda2") @@ -87,7 +94,8 @@ var _ = Describe("Linux Formatter", func() { ExitStatus: 0, }) formatter := NewLinuxFormatter(fakeRunner, fakeFs) - formatter.Format("/dev/xvda2", FileSystemExt4) + err := formatter.Format("/dev/xvda2", FileSystemExt4) + Expect(err).NotTo(HaveOccurred()) Expect(3).To(Equal(len(fakeRunner.RunCommands))) Expect(fakeRunner.RunCommands[1]).To(Equal([]string{"mke2fs", "-t", "ext4", "-j", "-E", "lazy_itable_init=1", "/dev/xvda2"})) @@ -99,7 +107,8 @@ var _ = Describe("Linux Formatter", func() { Error: errors.New(`some other error`), }) formatter := NewLinuxFormatter(fakeRunner, fakeFs) - formatter.Format("/dev/xvda2", FileSystemExt4) + err := formatter.Format("/dev/xvda2", FileSystemExt4) + Expect(err).To(HaveOccurred()) Expect(2).To(Equal(len(fakeRunner.RunCommands))) Expect(fakeRunner.RunCommands[1]).To(Equal([]string{"mke2fs", "-t", "ext4", "-j", "-E", "lazy_itable_init=1", "/dev/xvda2"})) @@ -112,7 +121,8 @@ var _ = Describe("Linux Formatter", func() { fakeRunner.AddCmdResult("blkid -p /dev/xvda2", fakesys.FakeCmdResult{Stdout: `xxxxx TYPE="ext2" yyyy zzzz`}) formatter := NewLinuxFormatter(fakeRunner, fakeFs) - formatter.Format("/dev/xvda2", FileSystemExt4) + err := formatter.Format("/dev/xvda2", FileSystemExt4) + Expect(err).NotTo(HaveOccurred()) Expect(2).To(Equal(len(fakeRunner.RunCommands))) Expect(fakeRunner.RunCommands[1]).To(Equal([]string{"mke2fs", "-t", "ext4", "-j", "/dev/xvda2"})) @@ -124,7 +134,8 @@ var _ = Describe("Linux Formatter", func() { fakeRunner.AddCmdResult("blkid -p /dev/xvda1", fakesys.FakeCmdResult{Stdout: `xxxxx TYPE="ext4" yyyy zzzz`}) formatter := NewLinuxFormatter(fakeRunner, fakeFs) - formatter.Format("/dev/xvda1", FileSystemExt4) + err := formatter.Format("/dev/xvda1", FileSystemExt4) + Expect(err).NotTo(HaveOccurred()) Expect(1).To(Equal(len(fakeRunner.RunCommands))) Expect(fakeRunner.RunCommands[0]).To(Equal([]string{"blkid", "-p", "/dev/xvda1"})) @@ -136,7 +147,8 @@ var _ = Describe("Linux Formatter", func() { fakeRunner.AddCmdResult("blkid -p /dev/xvda2", fakesys.FakeCmdResult{Stdout: `xxxxx TYPE="xfs" yyyy zzzz`}) formatter := NewLinuxFormatter(fakeRunner, fakeFs) - formatter.Format("/dev/xvda2", FileSystemExt4) + err := formatter.Format("/dev/xvda2", FileSystemExt4) + Expect(err).NotTo(HaveOccurred()) Expect(1).To(Equal(len(fakeRunner.RunCommands))) Expect(fakeRunner.RunCommands[0]).To(Equal([]string{"blkid", "-p", "/dev/xvda2"})) @@ -148,7 +160,8 @@ var _ = Describe("Linux Formatter", func() { fakeRunner.AddCmdResult("blkid -p /dev/xvda2", fakesys.FakeCmdResult{Stdout: `xxxxx TYPE="somethingelse" yyyy zzzz`}) formatter := NewLinuxFormatter(fakeRunner, fakeFs) - formatter.Format("/dev/xvda2", FileSystemExt4) + err := formatter.Format("/dev/xvda2", FileSystemExt4) + Expect(err).NotTo(HaveOccurred()) Expect(2).To(Equal(len(fakeRunner.RunCommands))) Expect(fakeRunner.RunCommands[0]).To(Equal([]string{"blkid", "-p", "/dev/xvda2"})) @@ -162,7 +175,8 @@ var _ = Describe("Linux Formatter", func() { fakeRunner.AddCmdResult("blkid -p /dev/xvda2", fakesys.FakeCmdResult{ExitStatus: 2, Error: errors.New("Exit code 2")}) formatter := NewLinuxFormatter(fakeRunner, fakeFs) - formatter.Format("/dev/xvda2", FileSystemXFS) + err := formatter.Format("/dev/xvda2", FileSystemXFS) + Expect(err).NotTo(HaveOccurred()) Expect(2).To(Equal(len(fakeRunner.RunCommands))) Expect(fakeRunner.RunCommands[1]).To(Equal([]string{"mkfs.xfs", "/dev/xvda2"})) @@ -174,7 +188,8 @@ var _ = Describe("Linux Formatter", func() { fakeRunner.AddCmdResult("blkid -p /dev/xvda1", fakesys.FakeCmdResult{Stdout: `xxxxx TYPE="ext4" yyyy zzzz`}) formatter := NewLinuxFormatter(fakeRunner, fakeFs) - formatter.Format("/dev/xvda1", FileSystemXFS) + err := formatter.Format("/dev/xvda1", FileSystemXFS) + Expect(err).NotTo(HaveOccurred()) Expect(1).To(Equal(len(fakeRunner.RunCommands))) Expect(fakeRunner.RunCommands[0]).To(Equal([]string{"blkid", "-p", "/dev/xvda1"})) @@ -186,7 +201,8 @@ var _ = Describe("Linux Formatter", func() { fakeRunner.AddCmdResult("blkid -p /dev/xvda1", fakesys.FakeCmdResult{Stdout: `xxxxx TYPE="xfs" yyyy zzzz`}) formatter := NewLinuxFormatter(fakeRunner, fakeFs) - formatter.Format("/dev/xvda1", FileSystemXFS) + err := formatter.Format("/dev/xvda1", FileSystemXFS) + Expect(err).NotTo(HaveOccurred()) Expect(1).To(Equal(len(fakeRunner.RunCommands))) Expect(fakeRunner.RunCommands[0]).To(Equal([]string{"blkid", "-p", "/dev/xvda1"})) diff --git a/platform/disk/linux_mounter_test.go b/platform/disk/linux_mounter_test.go index 75973894a..076aa8711 100644 --- a/platform/disk/linux_mounter_test.go +++ b/platform/disk/linux_mounter_test.go @@ -279,7 +279,8 @@ var _ = Describe("linuxMounter", func() { It("linux swap on", func() { runner.AddCmdResult("swapon -s", fakesys.FakeCmdResult{Stdout: "Filename Type Size Used Priority\n"}) - mounter.SwapOn("/dev/swap") + err := mounter.SwapOn("/dev/swap") + Expect(err).NotTo(HaveOccurred()) Expect(2).To(Equal(len(runner.RunCommands))) Expect(runner.RunCommands[1]).To(Equal([]string{"swapon", "/dev/swap"})) }) @@ -287,7 +288,8 @@ var _ = Describe("linuxMounter", func() { It("linux swap on when already on", func() { runner.AddCmdResult("swapon -s", fakesys.FakeCmdResult{Stdout: swaponUsageOutput}) - mounter.SwapOn("/dev/swap") + err := mounter.SwapOn("/dev/swap") + Expect(err).NotTo(HaveOccurred()) Expect(1).To(Equal(len(runner.RunCommands))) Expect(runner.RunCommands[0]).To(Equal([]string{"swapon", "-s"})) }) @@ -295,7 +297,8 @@ var _ = Describe("linuxMounter", func() { It("linux swap on when already on other device", func() { runner.AddCmdResult("swapon -s", fakesys.FakeCmdResult{Stdout: swaponUsageOutputWithOtherDevice}) - mounter.SwapOn("/dev/swap") + err := mounter.SwapOn("/dev/swap") + Expect(err).NotTo(HaveOccurred()) Expect(2).To(Equal(len(runner.RunCommands))) Expect(runner.RunCommands[0]).To(Equal([]string{"swapon", "-s"})) Expect(runner.RunCommands[1]).To(Equal([]string{"swapon", "/dev/swap"})) diff --git a/platform/disk/parted_partitioner_test.go b/platform/disk/parted_partitioner_test.go index e4a046b6d..4edf44691 100644 --- a/platform/disk/parted_partitioner_test.go +++ b/platform/disk/parted_partitioner_test.go @@ -13,8 +13,6 @@ import ( fakesys "github.com/cloudfoundry/bosh-utils/system/fakes" ) -const partitionNamePrefix = "bosh-partition" - func bytesOfMiB(sizeInMiB uint64) uint64 { return sizeInMiB * 1024 * 1024 } diff --git a/platform/disk/proc_mounts_searcher_test.go b/platform/disk/proc_mounts_searcher_test.go index e278b18df..f66ab7663 100644 --- a/platform/disk/proc_mounts_searcher_test.go +++ b/platform/disk/proc_mounts_searcher_test.go @@ -24,13 +24,14 @@ var _ = Describe("procMountsSearcher", func() { Describe("SearchMounts", func() { Context("when reading /proc/mounts succeeds", func() { It("returns parsed mount information", func() { - fs.WriteFileString( + err := fs.WriteFileString( "/proc/mounts", `none /run/lock tmpfs rw,nosuid,nodev,noexec,relatime,size=5120k 0 0 none /run/shm tmpfs rw,nosuid,nodev,relatime 0 0 /dev/sda1 /boot ext2 rw,relatime,errors=continue 0 0 none /tmp/warden/cgroup tmpfs rw,relatime 0 0`, ) + Expect(err).NotTo(HaveOccurred()) mounts, err := searcher.SearchMounts() Expect(err).ToNot(HaveOccurred()) @@ -43,13 +44,14 @@ none /tmp/warden/cgroup tmpfs rw,relatime 0 0`, }) It("ignores empty lines", func() { - fs.WriteFileString("/proc/mounts", ` + err := fs.WriteFileString("/proc/mounts", ` none /run/shm tmpfs rw,nosuid,nodev,relatime 0 0 /dev/sda1 /boot ext2 rw,relatime,errors=continue 0 0 `, ) + Expect(err).NotTo(HaveOccurred()) mounts, err := searcher.SearchMounts() Expect(err).ToNot(HaveOccurred()) @@ -62,7 +64,8 @@ none /run/shm tmpfs rw,nosuid,nodev,relatime 0 0 Context("when reading /proc/mounts fails", func() { It("returns error", func() { - fs.WriteFileString("/proc/mounts", "") + err := fs.WriteFileString("/proc/mounts", "") + Expect(err).NotTo(HaveOccurred()) fs.ReadFileError = errors.New("fake-read-err") mounts, err := searcher.SearchMounts() diff --git a/platform/disk/sfdisk_partitioner_test.go b/platform/disk/sfdisk_partitioner_test.go index 7fecc4909..9ff20fdc6 100644 --- a/platform/disk/sfdisk_partitioner_test.go +++ b/platform/disk/sfdisk_partitioner_test.go @@ -22,6 +22,7 @@ unit: sectors /dev/sda4 : start= 0, size= 0, Id= 0 ` +//nolint:gosec const devSdaSfdiskEmptyDumpWhitespace = `# partition table of /dev/sda unit: sectors @@ -107,7 +108,8 @@ var _ = Describe("sfdiskPartitioner", func() { {Type: PartitionTypeLinux, SizeInBytes: 512 * 1024 * 1024}, } - partitioner.Partition("/dev/sda", partitions) + err := partitioner.Partition("/dev/sda", partitions) + Expect(err).NotTo(HaveOccurred()) Expect(1).To(Equal(len(runner.RunCommandsWithInput))) Expect(runner.RunCommandsWithInput[0]).To(Equal([]string{",512MiB,S\n,1024MiB,L\n,,L\n", "sfdisk", "/dev/sda"})) @@ -125,7 +127,8 @@ var _ = Describe("sfdiskPartitioner", func() { {Type: PartitionTypeLinux, SizeInBytes: 512 * 1024 * 1024}, } - partitioner.Partition("/dev/sda", partitions) + err := partitioner.Partition("/dev/sda", partitions) + Expect(err).NotTo(HaveOccurred()) Expect(1).To(Equal(len(runner.RunCommandsWithInput))) Expect(runner.RunCommandsWithInput[0]).To(Equal([]string{",512MiB,S\n,1024MiB,L\n,,L\n", "sfdisk", "/dev/sda"})) @@ -155,7 +158,7 @@ var _ = Describe("sfdiskPartitioner", func() { Context("during get partitions", func() { It("raises error", func() { runner.AddCmdResult("sfdisk -s /dev/sda", fakesys.FakeCmdResult{Stdout: fmt.Sprintf("%d\n", 2048*1024)}) - runner.AddCmdResult("sfdisk -d /dev/sda", fakesys.FakeCmdResult{Error: errors.New("Some weird error")}) + runner.AddCmdResult("sfdisk -d /dev/sda", fakesys.FakeCmdResult{Error: errors.New("some weird error")}) partitions := []Partition{ {Type: PartitionTypeSwap, SizeInBytes: 512 * 1024 * 1024}, @@ -165,13 +168,13 @@ var _ = Describe("sfdiskPartitioner", func() { err := partitioner.Partition("/dev/sda", partitions) Expect(err).To(HaveOccurred()) - Expect(err.Error()).To(ContainSubstring("Some weird error")) + Expect(err.Error()).To(ContainSubstring("some weird error")) }) }) Context("when getting device size", func() { It("raises error", func() { - runner.AddCmdResult("sfdisk -s /dev/sda", fakesys.FakeCmdResult{Error: errors.New("Another weird error")}) + runner.AddCmdResult("sfdisk -s /dev/sda", fakesys.FakeCmdResult{Error: errors.New("another weird error")}) partitions := []Partition{ {Type: PartitionTypeSwap, SizeInBytes: 512 * 1024 * 1024}, @@ -179,7 +182,7 @@ var _ = Describe("sfdiskPartitioner", func() { err := partitioner.Partition("/dev/sda", partitions) Expect(err).To(HaveOccurred()) - Expect(err.Error()).To(ContainSubstring("Another weird error")) + Expect(err.Error()).To(ContainSubstring("another weird error")) }) }) }) @@ -194,7 +197,8 @@ var _ = Describe("sfdiskPartitioner", func() { {Type: PartitionTypeLinux, SizeInBytes: 512 * 1024 * 1024}, } - partitioner.Partition("/dev/sda", partitions) + err := partitioner.Partition("/dev/sda", partitions) + Expect(err).NotTo(HaveOccurred()) Expect(1).To(Equal(len(runner.RunCommandsWithInput))) Expect(runner.RunCommandsWithInput[0]).To(Equal([]string{",512MiB,S\n,1024MiB,L\n,,L\n", "sfdisk", "/dev/sda"})) @@ -209,7 +213,7 @@ var _ = Describe("sfdiskPartitioner", func() { {Type: PartitionTypeLinux, SizeInBytes: 512 * 1024 * 1024}, } - partitioner.Partition("/dev/mapper/xxxxxx", partitions) + partitioner.Partition("/dev/mapper/xxxxxx", partitions) //nolint:errcheck Expect(1).To(Equal(len(runner.RunCommandsWithInput))) Expect(runner.RunCommandsWithInput[0]).To(Equal([]string{",512MiB,S\n,1024MiB,L\n,,L\n", "sfdisk", "/dev/mapper/xxxxxx"})) @@ -240,7 +244,8 @@ var _ = Describe("sfdiskPartitioner", func() { {Type: PartitionTypeLinux, SizeInBytes: 512 * 1024 * 1024}, } - partitioner.Partition("/dev/sda", partitions) + err := partitioner.Partition("/dev/sda", partitions) + Expect(err).NotTo(HaveOccurred()) Expect(len(runner.RunCommandsWithInput)).To(Equal(0)) }) @@ -255,7 +260,8 @@ var _ = Describe("sfdiskPartitioner", func() { {Type: PartitionTypeLinux, SizeInBytes: 1024 * 1024 * 1024}, } - partitioner.Partition("/dev/mapper/xxxxxx", partitions) + err := partitioner.Partition("/dev/mapper/xxxxxx", partitions) + Expect(err).NotTo(HaveOccurred()) Expect(len(runner.RunCommandsWithInput)).To(Equal(0)) }) @@ -272,7 +278,8 @@ var _ = Describe("sfdiskPartitioner", func() { {Type: PartitionTypeLinux}, } - partitioner.Partition("/dev/sda", partitions) + err := partitioner.Partition("/dev/sda", partitions) + Expect(err).NotTo(HaveOccurred()) Expect(len(runner.RunCommandsWithInput)).To(Equal(1)) Expect(runner.RunCommandsWithInput[0]).To(Equal([]string{",1024MiB,L\n,,L\n", "sfdisk", "/dev/sda"})) @@ -290,7 +297,8 @@ var _ = Describe("sfdiskPartitioner", func() { {Type: PartitionTypeLinux}, } - partitioner.Partition("/dev/sda", partitions) + err := partitioner.Partition("/dev/sda", partitions) + Expect(err).NotTo(HaveOccurred()) Expect(0).To(Equal(len(runner.RunCommandsWithInput))) }) diff --git a/platform/dummy_platform_test.go b/platform/dummy_platform_test.go index 151db029f..ed420b0e3 100644 --- a/platform/dummy_platform_test.go +++ b/platform/dummy_platform_test.go @@ -66,7 +66,8 @@ var _ = Describe("DummyPlatform", func() { Describe("GetDefaultNetwork", func() { It("returns the contents of dummy-defaults-network-settings.json since that's what the dummy cpi writes", func() { settingsFilePath := "/fake-dir/bosh/dummy-default-network-settings.json" - fs.WriteFileString(settingsFilePath, `{"IP": "1.2.3.4"}`) + err := fs.WriteFileString(settingsFilePath, `{"IP": "1.2.3.4"}`) + Expect(err).NotTo(HaveOccurred()) network, err := platform.GetDefaultNetwork() Expect(err).NotTo(HaveOccurred()) @@ -129,8 +130,10 @@ var _ = Describe("DummyPlatform", func() { Context("Device has already been mounted as expected", func() { BeforeEach(func() { - fs.WriteFileString(managedSettingsPath, "somediskid") - fs.WriteFileString(mountsPath, `[{"MountDir":"/dev/potato","DiskCid":"somediskid"}]`) + err := fs.WriteFileString(managedSettingsPath, "somediskid") + Expect(err).NotTo(HaveOccurred()) + err = fs.WriteFileString(mountsPath, `[{"MountDir":"/dev/potato","DiskCid":"somediskid"}]`) + Expect(err).NotTo(HaveOccurred()) }) It("Does not mount in new location", func() { @@ -153,7 +156,8 @@ var _ = Describe("DummyPlatform", func() { Expect(err).NotTo(HaveOccurred()) mountsPath := filepath.Join(dirProvider.BoshDir(), "mounts.json") - fs.WriteFile(mountsPath, mountsJSON) + err = fs.WriteFile(mountsPath, mountsJSON) + Expect(err).NotTo(HaveOccurred()) }) It("removes one of the disks from the mounts json", func() { @@ -201,7 +205,8 @@ var _ = Describe("DummyPlatform", func() { Describe("IsPersistentDiskMountable", func() { BeforeEach(func() { formattedDisksPath := filepath.Join(dirProvider.BoshDir(), "formatted_disks.json") - fs.WriteFileString(formattedDisksPath, `[{"DiskCid": "my-disk-id"}]`) + err := fs.WriteFileString(formattedDisksPath, `[{"DiskCid": "my-disk-id"}]`) + Expect(err).NotTo(HaveOccurred()) }) Context("when disk has been formatted", func() { diff --git a/platform/fakes/fake_audit_logger_provider.go b/platform/fakes/fake_audit_logger_provider.go index f5898b22f..79e9479fa 100644 --- a/platform/fakes/fake_audit_logger_provider.go +++ b/platform/fakes/fake_audit_logger_provider.go @@ -65,7 +65,7 @@ func (p *FakeAuditLoggerProvider) SetErrorLoggerError(err error) { func (p *FakeAuditLoggerProvider) GetDebugLogsAt(index int) string { p.debugBufferLock.RLock() - debugString := string(p.debugBuffer.Bytes()) + debugString := p.debugBuffer.String() p.debugBufferLock.RUnlock() return debugString } @@ -88,7 +88,7 @@ func (p *FakeAuditLoggerProvider) ProvideErrorLogger() (*log.Logger, error) { func (p *FakeAuditLoggerProvider) GetErrorLogsAt(index int) string { p.errorBufferLock.RLock() - errorString := string(p.errorBuffer.Bytes()) + errorString := p.errorBuffer.String() p.errorBufferLock.RUnlock() return errorString } diff --git a/platform/linux_platform_test.go b/platform/linux_platform_test.go index 668fe318f..a8d357f39 100644 --- a/platform/linux_platform_test.go +++ b/platform/linux_platform_test.go @@ -211,6 +211,7 @@ var _ = Describe("LinuxPlatform", func() { Describe("DeleteEphemeralUsersMatching", func() { It("deletes users with prefix and regex", func() { + //nolint:gosec passwdFile := `bosh_foo:... bosh_bar:... foo:... @@ -218,9 +219,10 @@ bar:... foobar:... bosh_foobar:...` - fs.WriteFileString("/etc/passwd", passwdFile) + err := fs.WriteFileString("/etc/passwd", passwdFile) + Expect(err).NotTo(HaveOccurred()) - err := platform.DeleteEphemeralUsersMatching("bar$") + err = platform.DeleteEphemeralUsersMatching("bar$") Expect(err).NotTo(HaveOccurred()) Expect(len(cmdRunner.RunCommands)).To(Equal(2)) Expect(cmdRunner.RunCommands[0]).To(Equal([]string{"userdel", "-rf", "bosh_bar"})) @@ -252,12 +254,12 @@ bosh_foobar:...` }) It("returns error if mounting tmpfs fails", func() { - mounter.MountTmpfsReturns(errors.New("explosion!")) + mounter.MountTmpfsReturns(errors.New("fake error")) err := platform.SetupBoshSettingsDisk() Expect(err).To(HaveOccurred()) - Expect(err.Error()).To(ContainSubstring("explosion!")) + Expect(err.Error()).To(ContainSubstring("fake error")) }) }) @@ -595,7 +597,8 @@ bosh_foobar:...` It("setup ssh with a single key", func() { fs.HomeDirHomePath = "/some/home/dir" - platform.SetupSSH([]string{"some public key"}, "vcap") + err := platform.SetupSSH([]string{"some public key"}, "vcap") + Expect(err).NotTo(HaveOccurred()) sshDirPath := "/some/home/dir/.ssh" sshDirStat := fs.GetFileTestStat(sshDirPath) @@ -619,7 +622,8 @@ bosh_foobar:...` It("setup ssh with multiple keys", func() { fs.HomeDirHomePath = "/some/home/dir" - platform.SetupSSH([]string{"some public key", "some other public key"}, "vcap") + err := platform.SetupSSH([]string{"some public key", "some other public key"}, "vcap") + Expect(err).NotTo(HaveOccurred()) sshDirPath := "/some/home/dir/.ssh" sshDirStat := fs.GetFileTestStat(sshDirPath) @@ -644,14 +648,16 @@ bosh_foobar:...` Describe("SetUserPassword", func() { It("set user password", func() { - platform.SetUserPassword("my-user", "my-encrypted-password") + err := platform.SetUserPassword("my-user", "my-encrypted-password") + Expect(err).NotTo(HaveOccurred()) Expect(len(cmdRunner.RunCommands)).To(Equal(1)) Expect(cmdRunner.RunCommands[0]).To(Equal([]string{"usermod", "-p", "my-encrypted-password", "my-user"})) }) Context("password is empty string", func() { It("sets password to *", func() { - platform.SetUserPassword("my-user", "") + err := platform.SetUserPassword("my-user", "") + Expect(err).NotTo(HaveOccurred()) Expect(len(cmdRunner.RunCommands)).To(Equal(1)) Expect(cmdRunner.RunCommands[0]).To(Equal([]string{"usermod", "-p", "*", "my-user"})) }) @@ -671,12 +677,12 @@ ff02::3 ip6-allhosts ` Context("When running command to get hostname fails", func() { It("returns an error", func() { - result := fakesys.FakeCmdResult{Error: errors.New("Oops!")} + result := fakesys.FakeCmdResult{Error: errors.New("fake error")} cmdRunner.AddCmdResult("hostname foobar.local", result) err := platform.SetupHostname("foobar.local") Expect(err).To(HaveOccurred()) - Expect(err.Error()).To(ContainSubstring("Setting hostname: Oops!")) + Expect(err.Error()).To(ContainSubstring("Setting hostname: fake error")) }) }) @@ -712,7 +718,8 @@ ff02::3 ip6-allhosts Context("When host files have not yet been configured", func() { It("sets up hostname", func() { - platform.SetupHostname("foobar.local") + err := platform.SetupHostname("foobar.local") + Expect(err).NotTo(HaveOccurred()) Expect(len(cmdRunner.RunCommands)).To(Equal(1)) Expect(cmdRunner.RunCommands[0]).To(Equal([]string{"hostname", "foobar.local"})) @@ -728,8 +735,10 @@ ff02::3 ip6-allhosts Context("When host files have already been configured", func() { It("skips setting up hostname to prevent overriding changes made by the release author", func() { - platform.SetupHostname("foobar.local") - platform.SetupHostname("newfoo.local") + err := platform.SetupHostname("foobar.local") + Expect(err).NotTo(HaveOccurred()) + err = platform.SetupHostname("newfoo.local") + Expect(err).NotTo(HaveOccurred()) Expect(len(cmdRunner.RunCommands)).To(Equal(1)) Expect(cmdRunner.RunCommands[0]).To(Equal([]string{"hostname", "foobar.local"})) @@ -758,7 +767,8 @@ fake-base-path/data/sys/log/*.log fake-base-path/data/sys/log/.*.log fake-base-p ` It("sets up logrotate", func() { - platform.SetupLogrotate("fake-group-name", "fake-base-path", "fake-size") + err := platform.SetupLogrotate("fake-group-name", "fake-base-path", "fake-size") + Expect(err).NotTo(HaveOccurred()) logrotateFileContent, err := fs.ReadFileString("/etc/logrotate.d/fake-group-name") Expect(err).NotTo(HaveOccurred()) @@ -771,7 +781,8 @@ fake-base-path/data/sys/log/*.log fake-base-path/data/sys/log/.*.log fake-base-p Describe("SetTimeWithNtpServers", func() { It("sets time with ntp servers", func() { - platform.SetTimeWithNtpServers([]string{"0.north-america.pool.ntp.org", "1.north-america.pool.ntp.org"}) + err := platform.SetTimeWithNtpServers([]string{"0.north-america.pool.ntp.org", "1.north-america.pool.ntp.org"}) + Expect(err).NotTo(HaveOccurred()) ntpConfig := fs.GetFileTestStat("/fake-dir/bosh/etc/ntpserver") Expect(ntpConfig.StringContents()).To(Equal("0.north-america.pool.ntp.org 1.north-america.pool.ntp.org")) @@ -782,7 +793,8 @@ fake-base-path/data/sys/log/*.log fake-base-path/data/sys/log/.*.log fake-base-p }) It("sets time with ntp servers is noop when no ntp server provided", func() { - platform.SetTimeWithNtpServers([]string{}) + err := platform.SetTimeWithNtpServers([]string{}) + Expect(err).NotTo(HaveOccurred()) Expect(len(cmdRunner.RunCommands)).To(Equal(0)) ntpConfig := fs.GetFileTestStat("/fake-dir/bosh/etc/ntpserver") @@ -1122,7 +1134,7 @@ fake-base-path/data/sys/log/*.log fake-base-path/data/sys/log/.*.log fake-base-p }) }) - Context("when getting absolute path suceeds", func() { + Context("when getting absolute path succeeds", func() { BeforeEach(func() { cmdRunner.AddCmdResult( "readlink -f /dev/vda1", @@ -1337,7 +1349,7 @@ fake-base-path/data/sys/log/*.log fake-base-path/data/sys/log/.*.log fake-base-p } }) - Context("when getting absolute path suceeds", func() { + Context("when getting absolute path succeeds", func() { BeforeEach(func() { cmdRunner.AddCmdResult( "readlink -f /dev/vda2", @@ -2006,7 +2018,7 @@ Number Start End Size File system Name Flags fileStats := fs.GetFileTestStat("/fake-dir/data/tmp") Expect(fileStats).NotTo(BeNil()) - Expect(fileStats.FileType).To(Equal(fakesys.FakeFileType(fakesys.FakeFileTypeDir))) + Expect(fileStats.FileType).To(Equal(fakesys.FakeFileTypeDir)) Expect(fileStats.FileMode).To(Equal(os.FileMode(0755))) }) @@ -2100,7 +2112,8 @@ Number Start End Size File system Name Flags }) It("does not create new tmp filesystem", func() { - platform.SetupTmpDir() + err := platform.SetupTmpDir() + Expect(err).NotTo(HaveOccurred()) for _, cmd := range cmdRunner.RunCommands { Expect(cmd[0]).ToNot(Equal("truncate")) Expect(cmd[0]).ToNot(Equal("mke2fs")) @@ -2130,7 +2143,8 @@ Number Start End Size File system Name Flags }) It("does not create new tmp filesystem", func() { - platform.SetupTmpDir() + err := platform.SetupTmpDir() + Expect(err).To(HaveOccurred()) for _, cmd := range cmdRunner.RunCommands { Expect(cmd[0]).ToNot(Equal("truncate")) Expect(cmd[0]).ToNot(Equal("mke2fs")) @@ -2138,7 +2152,8 @@ Number Start End Size File system Name Flags }) It("does not try to mount /tmp", func() { - platform.SetupTmpDir() + err := platform.SetupTmpDir() + Expect(err).To(HaveOccurred()) Expect(mounter.MountCallCount()).To(Equal(0)) }) }) @@ -2193,7 +2208,8 @@ Number Start End Size File system Name Flags }) It("does not create new tmp filesystem", func() { - platform.SetupTmpDir() + err := platform.SetupTmpDir() + Expect(err).NotTo(HaveOccurred()) for _, cmd := range cmdRunner.RunCommands { Expect(cmd[0]).ToNot(Equal("truncate")) Expect(cmd[0]).ToNot(Equal("mke2fs")) @@ -2201,7 +2217,8 @@ Number Start End Size File system Name Flags }) It("does not try to mount root_tmp into /var/tmp", func() { - platform.SetupTmpDir() + err := platform.SetupTmpDir() + Expect(err).NotTo(HaveOccurred()) Expect(mounter.MountCallCount()).To(Equal(0)) }) }) @@ -2223,7 +2240,8 @@ Number Start End Size File system Name Flags }) It("does not create new tmp filesystem", func() { - platform.SetupTmpDir() + err := platform.SetupTmpDir() + Expect(err).To(HaveOccurred()) for _, cmd := range cmdRunner.RunCommands { Expect(cmd[0]).ToNot(Equal("truncate")) Expect(cmd[0]).ToNot(Equal("mke2fs")) @@ -2231,7 +2249,8 @@ Number Start End Size File system Name Flags }) It("does not try to mount /var/tmp", func() { - platform.SetupTmpDir() + err := platform.SetupTmpDir() + Expect(err).To(HaveOccurred()) Expect(mounter.MountCallCount()).To(Equal(0)) }) }) @@ -2268,7 +2287,8 @@ Number Start End Size File system Name Flags }) It("does not create new tmp filesystem", func() { - platform.SetupTmpDir() + err := platform.SetupTmpDir() + Expect(err).NotTo(HaveOccurred()) for _, cmd := range cmdRunner.RunCommands { Expect(cmd[0]).ToNot(Equal("truncate")) Expect(cmd[0]).ToNot(Equal("mke2fs")) @@ -2276,7 +2296,8 @@ Number Start End Size File system Name Flags }) It("does not try to mount anything", func() { - platform.SetupTmpDir() + err := platform.SetupTmpDir() + Expect(err).NotTo(HaveOccurred()) Expect(mounter.MountCallCount()).To(Equal(0)) }) }) @@ -2451,9 +2472,10 @@ Number Start End Size File system Name Flags Context("when the chrony user exists", func() { BeforeEach(func() { - fs.WriteFileString("/etc/passwd", `bob:fakeuser + err := fs.WriteFileString("/etc/passwd", `bob:fakeuser _chrony:somethingfake sam:fakeanotheruser`) + Expect(err).NotTo(HaveOccurred()) }) It("creates the /var/log/chrony directory", func() { @@ -2468,10 +2490,11 @@ sam:fakeanotheruser`) Context("when there is an error reading /etc/passwd", func() { It("acts like there is no chrony user", func() { - fs.WriteFileString("/etc/passwd", `_notchrony:somethingfake`) + err := fs.WriteFileString("/etc/passwd", `_notchrony:somethingfake`) + Expect(err).NotTo(HaveOccurred()) fs.RegisterReadFileError("/etc/passwd", fmt.Errorf("boom")) - err := act() + err = act() Expect(err).ToNot(HaveOccurred()) Expect(cmdRunner.RunCommands).ToNot(ContainElement([]string{"mkdir", "-p", "/fake-dir/data/root_log/chrony"})) @@ -2517,7 +2540,8 @@ sam:fakeanotheruser`) }) It("does not try to mount root_log into /var/log", func() { - act() + err := act() + Expect(err).NotTo(HaveOccurred()) Expect(mounter.MountCallCount()).To(Equal(0)) }) }) @@ -2539,7 +2563,8 @@ sam:fakeanotheruser`) }) It("does not try to mount /var/log", func() { - act() + err := act() + Expect(err).To(HaveOccurred()) Expect(mounter.MountCallCount()).To(Equal(0)) }) }) @@ -2604,7 +2629,8 @@ sam:fakeanotheruser`) }) It("does not try to mount root_var_opt into /var/opt", func() { - platform.SetupOptDir() + err := platform.SetupOptDir() + Expect(err).NotTo(HaveOccurred()) Expect(mounter.MountCallCount()).To(Equal(0)) }) }) @@ -2626,7 +2652,8 @@ sam:fakeanotheruser`) }) It("does not try to mount /var/opt", func() { - platform.SetupOptDir() + err := platform.SetupOptDir() + Expect(err).To(HaveOccurred()) Expect(mounter.MountCallCount()).To(Equal(0)) }) }) @@ -2671,7 +2698,8 @@ sam:fakeanotheruser`) }) It("does not try to mount root_opt into /opt", func() { - platform.SetupOptDir() + err := platform.SetupOptDir() + Expect(err).NotTo(HaveOccurred()) Expect(mounter.MountCallCount()).To(Equal(0)) }) }) @@ -2693,7 +2721,8 @@ sam:fakeanotheruser`) }) It("does not try to mount /opt", func() { - platform.SetupOptDir() + err := platform.SetupOptDir() + Expect(err).To(HaveOccurred()) Expect(mounter.MountCallCount()).To(Equal(0)) }) }) @@ -2941,7 +2970,7 @@ sam:fakeanotheruser`) }) }) - Context("when settings specify an unsupported filesysem", func() { + Context("when settings specify an unsupported filesystem", func() { BeforeEach(func() { diskSettings.FileSystemType = boshdisk.FileSystemType("blahblah") }) @@ -2954,9 +2983,22 @@ sam:fakeanotheruser`) }) }) + Context(`when settings specify a "swap" filesystem`, func() { + BeforeEach(func() { + diskSettings.FileSystemType = boshdisk.FileSystemSwap + }) + + It("it errors", func() { + err := platform.AdjustPersistentDiskPartitioning(diskSettings, mntPoint) + + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(Equal(`The filesystem type "swap" is not supported`)) + }) + }) + Context("when disk could not be formatted", func() { BeforeEach(func() { - formatter.FormatError = errors.New("Oh noes!") + formatter.FormatError = errors.New("oh noes") }) It("returns an error", func() { @@ -2966,7 +3008,7 @@ sam:fakeanotheruser`) ) Expect(err).To(HaveOccurred()) - Expect(err.Error()).To(Equal("Formatting partition with xfs: Oh noes!")) + Expect(err.Error()).To(Equal("Formatting partition with xfs: oh noes")) }) }) }) @@ -3201,7 +3243,7 @@ sam:fakeanotheruser`) }) It("returns an error when updating managed_disk_settings.json fails", func() { - fs.WriteFileError = errors.New("Oh noes!") + fs.WriteFileError = errors.New("fake error") err := platform.MountPersistentDisk( boshsettings.DiskSettings{Path: "fake-volume-id", FileSystemType: boshdisk.FileSystemXFS}, @@ -3209,7 +3251,7 @@ sam:fakeanotheruser`) ) Expect(err).To(HaveOccurred()) - Expect(err.Error()).To(Equal("Writing managed_disk_settings.json: Oh noes!")) + Expect(err.Error()).To(Equal("Writing managed_disk_settings.json: fake error")) }) It("mounts the disk", func() { @@ -3852,7 +3894,8 @@ unit: sectors Describe("GetMonitCredentials", func() { It("get monit credentials reads monit file from disk", func() { - fs.WriteFileString("/fake-dir/monit/monit.user", "fake-user:fake-random-password") + err := fs.WriteFileString("/fake-dir/monit/monit.user", "fake-user:fake-random-password") + Expect(err).NotTo(HaveOccurred()) username, password, err := platform.GetMonitCredentials() Expect(err).NotTo(HaveOccurred()) @@ -3862,14 +3905,16 @@ unit: sectors }) It("get monit credentials errs when invalid file format", func() { - fs.WriteFileString("/fake-dir/monit/monit.user", "fake-user") + err := fs.WriteFileString("/fake-dir/monit/monit.user", "fake-user") + Expect(err).NotTo(HaveOccurred()) - _, _, err := platform.GetMonitCredentials() + _, _, err = platform.GetMonitCredentials() Expect(err).To(HaveOccurred()) }) It("get monit credentials leaves colons in password intact", func() { - fs.WriteFileString("/fake-dir/monit/monit.user", "fake-user:fake:random:password") + err := fs.WriteFileString("/fake-dir/monit/monit.user", "fake-user:fake:random:password") + Expect(err).NotTo(HaveOccurred()) username, password, err := platform.GetMonitCredentials() Expect(err).NotTo(HaveOccurred()) @@ -3881,9 +3926,10 @@ unit: sectors Describe("PrepareForNetworkingChange", func() { It("removes the network persistent rules file", func() { - fs.WriteFile("/etc/udev/rules.d/70-persistent-net.rules", []byte{}) + err := fs.WriteFile("/etc/udev/rules.d/70-persistent-net.rules", []byte{}) + Expect(err).NotTo(HaveOccurred()) - err := platform.PrepareForNetworkingChange() + err = platform.PrepareForNetworkingChange() Expect(err).NotTo(HaveOccurred()) Expect(fs.FileExists("/etc/udev/rules.d/70-persistent-net.rules")).To(BeFalse()) @@ -3949,7 +3995,9 @@ unit: sectors Describe("GetHostPublicKey", func() { It("gets host public key if file exists", func() { - fs.WriteFileString("/etc/ssh/ssh_host_rsa_key.pub", "public-key") + err := fs.WriteFileString("/etc/ssh/ssh_host_rsa_key.pub", "public-key") + Expect(err).NotTo(HaveOccurred()) + hostPublicKey, err := platform.GetHostPublicKey() Expect(err).ToNot(HaveOccurred()) Expect(hostPublicKey).To(Equal("public-key")) @@ -4007,8 +4055,9 @@ unit: sectors Describe("RemoveDevTools", func() { It("removes listed packages", func() { devToolsListPath := path.Join(dirProvider.EtcDir(), "dev_tools_file_list") - fs.WriteFileString(devToolsListPath, "dummy-compiler") - err := platform.RemoveDevTools(devToolsListPath) + err := fs.WriteFileString(devToolsListPath, "dummy-compiler") + Expect(err).NotTo(HaveOccurred()) + err = platform.RemoveDevTools(devToolsListPath) Expect(err).ToNot(HaveOccurred()) Expect(len(cmdRunner.RunCommands)).To(Equal(1)) Expect(cmdRunner.RunCommands[0]).To(Equal([]string{"rm", "-rf", "dummy-compiler"})) @@ -4018,8 +4067,9 @@ unit: sectors Describe("RemoveStaticLibraries", func() { It("removes listed static libraries", func() { staticLibrariesListPath := path.Join(dirProvider.EtcDir(), "static_libraries_list") - fs.WriteFileString(staticLibrariesListPath, "static.a\nlibrary.a") - err := platform.RemoveStaticLibraries(staticLibrariesListPath) + err := fs.WriteFileString(staticLibrariesListPath, "static.a\nlibrary.a") + Expect(err).NotTo(HaveOccurred()) + err = platform.RemoveStaticLibraries(staticLibrariesListPath) Expect(err).ToNot(HaveOccurred()) Expect(cmdRunner.RunCommands).To(HaveLen(2)) Expect(cmdRunner.RunCommands[0]).To(Equal([]string{"rm", "-rf", "static.a"})) @@ -4038,8 +4088,9 @@ unit: sectors It("should return an error", func() { cmdRunner.AddCmdResult("rm -rf library.a", fakesys.FakeCmdResult{Error: errors.New("oh noes")}) staticLibrariesListPath := path.Join(dirProvider.EtcDir(), "static_libraries_list") - fs.WriteFileString(staticLibrariesListPath, "static.a\nlibrary.a") - err := platform.RemoveStaticLibraries(staticLibrariesListPath) + err := fs.WriteFileString(staticLibrariesListPath, "static.a\nlibrary.a") + Expect(err).NotTo(HaveOccurred()) + err = platform.RemoveStaticLibraries(staticLibrariesListPath) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("oh noes")) Expect(cmdRunner.RunCommands).To(HaveLen(2)) @@ -4062,7 +4113,7 @@ unit: sectors }, } - defaultEtcHosts = strings.Replace(EtcHostsTemplate, "{{ . }}", "fake-hostname", -1) + defaultEtcHosts = strings.ReplaceAll(EtcHostsTemplate, "{{ . }}", "fake-hostname") }) It("fails generating a UUID", func() { diff --git a/platform/net/arp/arping_test.go b/platform/net/arp/arping_test.go index 3d23f21a2..8339a7164 100644 --- a/platform/net/arp/arping_test.go +++ b/platform/net/arp/arping_test.go @@ -40,8 +40,10 @@ var _ = Describe("arping", func() { Describe("BroadcastMACAddresses", func() { BeforeEach(func() { - fs.WriteFile("/sys/class/net/eth0", []byte{}) - fs.WriteFile("/sys/class/net/eth1", []byte{}) + err := fs.WriteFile("/sys/class/net/eth0", []byte{}) + Expect(err).NotTo(HaveOccurred()) + err = fs.WriteFile("/sys/class/net/eth1", []byte{}) + Expect(err).NotTo(HaveOccurred()) }) It("runs arping commands for each interface", func() { diff --git a/platform/net/dns_validator_test.go b/platform/net/dns_validator_test.go index 1dd98d711..d3783cc86 100644 --- a/platform/net/dns_validator_test.go +++ b/platform/net/dns_validator_test.go @@ -22,9 +22,10 @@ var _ = Describe("DNSValidator", func() { Context("when /etc/resolv.conf contains at least one dns server", func() { BeforeEach(func() { - fs.WriteFileString("/etc/resolv.conf", ` + err := fs.WriteFileString("/etc/resolv.conf", ` nameserver 8.8.8.8 nameserver 9.9.9.9`) + Expect(err).NotTo(HaveOccurred()) }) It("returns nil", func() { @@ -43,7 +44,8 @@ var _ = Describe("DNSValidator", func() { Context("when /etc/resolv.conf does not contain any of the dns servers specified in the manifest", func() { BeforeEach(func() { - fs.WriteFileString("/etc/resolv.conf", `nameserver 6.6.6.6`) + err := fs.WriteFileString("/etc/resolv.conf", `nameserver 6.6.6.6`) + Expect(err).NotTo(HaveOccurred()) }) It("returns error", func() { diff --git a/platform/net/firewall_provider_linux_test.go b/platform/net/firewall_provider_linux_test.go index 0614b478e..bfea18fe7 100644 --- a/platform/net/firewall_provider_linux_test.go +++ b/platform/net/firewall_provider_linux_test.go @@ -6,15 +6,15 @@ import ( ) var _ = Describe("SetupFirewall Linux", func() { - //covers the case for http_metadata_service where on some IaaSs we cannot yet know the contents of agent-settings.json \ - //since http_metadata_service is responsible for pulling the data. + // covers the case for http_metadata_service where on some IaaSs we cannot yet know the contents of + // agent-settings.json since http_metadata_service is responsible for pulling the data. When("mbus url is empty", func() { It("returns early without an error", func() { err := SetupNatsFirewall("") Expect(err).ToNot(HaveOccurred()) }) }) - //create no rule on a create-env + // create no rule on a create-env When("mbus url starts with https://", func() { It("returns early without an error", func() { err := SetupNatsFirewall("https://") diff --git a/platform/net/interface_configuration_creator_test.go b/platform/net/interface_configuration_creator_test.go index 87936da0d..2d5979088 100644 --- a/platform/net/interface_configuration_creator_test.go +++ b/platform/net/interface_configuration_creator_test.go @@ -95,7 +95,7 @@ var _ = Describe("InterfaceConfigurationCreator", func() { interfacesByMAC["some-other-mac"] = "static-interface-name" }) - It("retuns an error", func() { + It("returns an error", func() { _, _, err := interfaceConfigurationCreator.CreateInterfaceConfigurations(networks, interfacesByMAC) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("No device found")) @@ -142,7 +142,7 @@ var _ = Describe("InterfaceConfigurationCreator", func() { interfacesByMAC = map[string]string{} }) - It("retuns an error", func() { + It("returns an error", func() { _, _, err := interfaceConfigurationCreator.CreateInterfaceConfigurations(networks, interfacesByMAC) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("Number of network settings '1' is greater than the number of network devices '0'")) @@ -310,7 +310,7 @@ var _ = Describe("InterfaceConfigurationCreator", func() { interfacesByMAC[dhcpNetwork.Mac] = "dhcp-interface-name" }) - It("retuns an error", func() { + It("returns an error", func() { _, _, err := interfaceConfigurationCreator.CreateInterfaceConfigurations(networks, interfacesByMAC) Expect(err).To(HaveOccurred()) }) @@ -456,7 +456,7 @@ var _ = Describe("InterfaceConfigurationCreator", func() { interfacesByMAC[dhcpNetwork.Mac] = "dhcp-interface-name" }) - It("retuns an error", func() { + It("returns an error", func() { _, _, err := interfaceConfigurationCreator.CreateInterfaceConfigurations(networks, interfacesByMAC) Expect(err).To(HaveOccurred()) }) diff --git a/platform/net/mac_address_detector_test.go b/platform/net/mac_address_detector_test.go index 0b24f49ae..e6c4ca941 100644 --- a/platform/net/mac_address_detector_test.go +++ b/platform/net/mac_address_detector_test.go @@ -28,12 +28,16 @@ var _ = Describe("MacAddressDetector", func() { writeNetworkDevice := func(iface string, macAddress string, isPhysical bool, ifalias string) string { interfacePath := fmt.Sprintf("/sys/class/net/%s", iface) - fs.WriteFile(interfacePath, []byte{}) + err := fs.WriteFile(interfacePath, []byte{}) + Expect(err).NotTo(HaveOccurred()) if isPhysical { - fs.WriteFile(fmt.Sprintf("/sys/class/net/%s/device", iface), []byte{}) + err = fs.WriteFile(fmt.Sprintf("/sys/class/net/%s/device", iface), []byte{}) + Expect(err).NotTo(HaveOccurred()) } - fs.WriteFileString(fmt.Sprintf("/sys/class/net/%s/address", iface), fmt.Sprintf("%s\n", macAddress)) - fs.WriteFileString(fmt.Sprintf("/sys/class/net/%s/ifalias", iface), fmt.Sprintf("%s\n", ifalias)) + err = fs.WriteFileString(fmt.Sprintf("/sys/class/net/%s/address", iface), fmt.Sprintf("%s\n", macAddress)) + Expect(err).NotTo(HaveOccurred()) + err = fs.WriteFileString(fmt.Sprintf("/sys/class/net/%s/ifalias", iface), fmt.Sprintf("%s\n", ifalias)) + Expect(err).NotTo(HaveOccurred()) return interfacePath } diff --git a/platform/net/ubuntu_net_manager_test.go b/platform/net/ubuntu_net_manager_test.go index ffa10331a..f3db35311 100644 --- a/platform/net/ubuntu_net_manager_test.go +++ b/platform/net/ubuntu_net_manager_test.go @@ -145,7 +145,7 @@ var _ = Describe("ubuntuNetManager", func() { }) Context("when interface alias exists in network settings", func() { - It("static interface configuration should be construted by alias name", func() { + It("static interface configuration should be constructed by alias name", func() { networks := boshsettings.Networks{ "default": factory.Network{ IP: "10.10.0.32", @@ -257,10 +257,11 @@ var _ = Describe("ubuntuNetManager", func() { interfaceAddrsProvider.GetInterfaceAddresses = []boship.InterfaceAddress{ boship.NewSimpleInterfaceAddress("ethstatic", "1.2.3.4"), } - fs.WriteFileString("/etc/resolv.conf", ` + err := fs.WriteFileString("/etc/resolv.conf", ` nameserver 8.8.8.8 nameserver 9.9.9.9 `) + Expect(err).NotTo(HaveOccurred()) expectedNetworkConfigurationForStaticAndDhcp = `# Generated by bosh-agent auto lo iface lo inet loopback @@ -809,7 +810,7 @@ Gateway=3.4.5.6 "ethdhcp": dhcpNetwork, "ethstatic": staticNetwork, }) - staticNetwork.Netmask = "not an ip" //will cause InterfaceConfigurationCreator to fail + staticNetwork.Netmask = "not an ip" // will cause InterfaceConfigurationCreator to fail err := netManager.SetupNetworking(boshsettings.Networks{"static-network": staticNetwork}, "", nil) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("Creating interface configurations")) @@ -941,7 +942,8 @@ prepend domain-name-servers 8.8.8.8, 9.9.9.9; "ethstatic": staticNetwork, }) - fs.WriteFileString("/etc/dhcp/dhclient.conf", initialDhcpConfig) + err := fs.WriteFileString("/etc/dhcp/dhclient.conf", initialDhcpConfig) + Expect(err).NotTo(HaveOccurred()) // check that config files change after stop and before start cmdRunner.SetCmdCallback("ip --force link set ethdhcp down", func() { @@ -959,7 +961,7 @@ prepend domain-name-servers 8.8.8.8, 9.9.9.9; Expect(fs.ReadFileString("/etc/dhcp/dhclient.conf")).To(Equal(initialDhcpConfig)) }) - err := netManager.SetupNetworking(boshsettings.Networks{"dhcp-network": dhcpNetwork, "static-network": staticNetwork}, "", nil) + err = netManager.SetupNetworking(boshsettings.Networks{"dhcp-network": dhcpNetwork, "static-network": staticNetwork}, "", nil) Expect(err).ToNot(HaveOccurred()) Expect(len(cmdRunner.RunCommands)).To(Equal(5)) @@ -999,10 +1001,12 @@ prepend domain-name-servers 8.8.8.8, 9.9.9.9; "ethstatic": staticNetwork, }) - fs.WriteFileString("/etc/network/interfaces", expectedNetworkConfigurationForStaticAndDhcp) - fs.WriteFileString("/etc/dhcp/dhclient.conf", initialDhcpConfig) + err := fs.WriteFileString("/etc/network/interfaces", expectedNetworkConfigurationForStaticAndDhcp) + Expect(err).NotTo(HaveOccurred()) + err = fs.WriteFileString("/etc/dhcp/dhclient.conf", initialDhcpConfig) + Expect(err).NotTo(HaveOccurred()) - err := netManager.SetupNetworking(boshsettings.Networks{"dhcp-network": dhcpNetwork, "static-network": staticNetwork}, "", nil) + err = netManager.SetupNetworking(boshsettings.Networks{"dhcp-network": dhcpNetwork, "static-network": staticNetwork}, "", nil) Expect(err).ToNot(HaveOccurred()) networkConfig := fs.GetFileTestStat("/etc/network/interfaces") @@ -1026,7 +1030,8 @@ prepend domain-name-servers 8.8.8.8, 9.9.9.9; "ethstatic": staticNetwork, }) - fs.WriteFileString("/etc/dhcp/dhclient.conf", initialDhcpConfig) + err := fs.WriteFileString("/etc/dhcp/dhclient.conf", initialDhcpConfig) + Expect(err).NotTo(HaveOccurred()) // check that config files change after stop and before start cmdRunner.SetCmdCallback("ip --force link set ethdhcp down", func() { @@ -1044,7 +1049,7 @@ prepend domain-name-servers 8.8.8.8, 9.9.9.9; Expect(fs.ReadFileString("/etc/dhcp/dhclient.conf")).To(Equal(initialDhcpConfig)) }) - err := netManager.SetupNetworking(boshsettings.Networks{"dhcp-network": dhcpNetwork, "static-network": staticNetwork}, "", nil) + err = netManager.SetupNetworking(boshsettings.Networks{"dhcp-network": dhcpNetwork, "static-network": staticNetwork}, "", nil) Expect(err).ToNot(HaveOccurred()) Expect(len(cmdRunner.RunCommands)).To(Equal(5)) @@ -1158,7 +1163,8 @@ DNS=9.9.9.9 Context("when dns is not properly configured", func() { BeforeEach(func() { - fs.WriteFileString("/etc/resolv.conf", "") + err := fs.WriteFileString("/etc/resolv.conf", "") + Expect(err).NotTo(HaveOccurred()) }) It("fails", func() { @@ -1272,15 +1278,16 @@ Gateway=3.4.5.6 boship.NewSimpleInterfaceAddress("eth0", "10.112.39.113"), boship.NewSimpleInterfaceAddress("eth1", "169.50.68.75"), } - fs.WriteFileString("/etc/resolv.conf", ` + err := fs.WriteFileString("/etc/resolv.conf", ` nameserver 8.8.8.8 nameserver 10.0.80.11 nameserver 10.0.80.12 `) + Expect(err).NotTo(HaveOccurred()) }) scrubMultipleLines := func(in string) string { - return strings.Replace(in, "\n\n\n", "\n\n", -1) + return strings.ReplaceAll(in, "\n\n\n", "\n\n") } It("succeeds", func() { @@ -1360,8 +1367,10 @@ DNS=10.0.80.12 }) It("returns networks that are defined in /etc/network/interfaces", func() { - fs.WriteFileString("/etc/systemd/network/10_fake-eth0.network", ``) - fs.WriteFileString("/etc/systemd/network/10_fake-eth2.network", ``) + err := fs.WriteFileString("/etc/systemd/network/10_fake-eth0.network", ``) + Expect(err).NotTo(HaveOccurred()) + err = fs.WriteFileString("/etc/systemd/network/10_fake-eth2.network", ``) + Expect(err).NotTo(HaveOccurred()) interfaces, err := netManager.GetConfiguredNetworkInterfaces() Expect(err).ToNot(HaveOccurred()) diff --git a/platform/net/windows_net_manager_test.go b/platform/net/windows_net_manager_test.go index 0d3f76aa8..8579d8827 100644 --- a/platform/net/windows_net_manager_test.go +++ b/platform/net/windows_net_manager_test.go @@ -57,7 +57,7 @@ var _ = Describe("WindowsNetManager", func() { tmpDir, err = ioutil.TempDir("", "bosh-tests-") Expect(err).ToNot(HaveOccurred()) dirProvider = boshdirs.NewProvider(tmpDir) - err = fs.MkdirAll(filepath.Join(dirProvider.BoshDir()), 0755) + err = fs.MkdirAll(filepath.Join(dirProvider.BoshDir()), 0755) //nolint:gocritic Expect(err).ToNot(HaveOccurred()) netManager = NewWindowsNetManager( diff --git a/platform/stats/percentage_test.go b/platform/stats/percentage_test.go index e7ccc2056..94c7824ca 100644 --- a/platform/stats/percentage_test.go +++ b/platform/stats/percentage_test.go @@ -7,10 +7,9 @@ import ( . "github.com/cloudfoundry/bosh-agent/platform/stats" ) -func init() { +func init() { // nolint:gochecknoinits Describe("Testing with Ginkgo", func() { It("fraction of100", func() { - p := NewPercentage(50, 100) Expect(p.FractionOf100()).To(Equal(float64(50))) @@ -20,8 +19,8 @@ func init() { p = NewPercentage(0, 0) Expect(p.FractionOf100()).To(Equal(float64(0))) }) - It("format fraction of100", func() { + It("format fraction of100", func() { p := NewPercentage(50, 100) Expect(p.FormatFractionOf100(2)).To(Equal("50.00")) Expect(p.FormatFractionOf100(0)).To(Equal("50")) diff --git a/platform/syscall_windows_test.go b/platform/syscall_windows_test.go index 870c89ddd..0d5ca91eb 100644 --- a/platform/syscall_windows_test.go +++ b/platform/syscall_windows_test.go @@ -16,13 +16,13 @@ import ( var ( // Export for testing - UserHomeDirectory = userHomeDirectory - RandomPassword = randomPassword - ValidWindowsPassword = validPassword - LocalAccountNames = localAccountNames + UserHomeDirectory = userHomeDirectory //nolint:gochecknoglobals + RandomPassword = randomPassword //nolint:gochecknoglobals + ValidWindowsPassword = validPassword //nolint:gochecknoglobals + LocalAccountNames = localAccountNames //nolint:gochecknoglobals // Export for test cleanup - DeleteLocalUser = deleteLocalUser + DeleteLocalUser = deleteLocalUser //nolint:gochecknoglobals ) // SetSSHEnabled sets the function called by GetHostPublicKey to determine if diff --git a/platform/udevdevice/fakes/fake_udev_device.go b/platform/udevdevice/fakes/fake_udev_device.go index 139d60b41..9399660b1 100644 --- a/platform/udevdevice/fakes/fake_udev_device.go +++ b/platform/udevdevice/fakes/fake_udev_device.go @@ -13,14 +13,12 @@ type FakeUdevDevice struct { EnsureDeviceReadableError error } -func NewFakeUdevDevice() (lowlevel *FakeUdevDevice) { - lowlevel = &FakeUdevDevice{} - return +func NewFakeUdevDevice() *FakeUdevDevice { + return &FakeUdevDevice{} } func (l *FakeUdevDevice) KickDevice(filePath string) { l.KickDeviceFile = filePath - return } func (l *FakeUdevDevice) Settle() (err error) { diff --git a/platform/vitals/service_test.go b/platform/vitals/service_test.go index 40bf088b5..08a442ddb 100644 --- a/platform/vitals/service_test.go +++ b/platform/vitals/service_test.go @@ -122,7 +122,7 @@ var _ = Describe("Vitals service", func() { boshassert.MatchesJSONMap(GinkgoT(), vitals, expectedVitals) }) - Context("when missing stats for ephemeral and peristent disk", func() { + Context("when missing stats for ephemeral and persistent disk", func() { BeforeEach(func() { statsCollector.DiskStats = map[string]boshstats.DiskStats{ "/": { diff --git a/platform/windows/disk/partitioner_test.go b/platform/windows/disk/partitioner_test.go index ebcd24978..6093cc2e6 100644 --- a/platform/windows/disk/partitioner_test.go +++ b/platform/windows/disk/partitioner_test.go @@ -13,16 +13,6 @@ import ( ) var _ = Describe("Partitioner", func() { - const cmdStandardError = `Get-Disk : No MSFT_Disk objects found with property 'Number' equal to '0'. -Verify the value of the property and retry. -At line:1 char:1 -+ Get-Disk 0 -+ ~~~~~~~~~~ - + CategoryInfo : ObjectNotFound: (0:UInt32) [Get-Disk], CimJobExc - eption - + FullyQualifiedErrorId : CmdletizationQuery_NotFound_Number,Get-Disk -` - var ( cmdRunner *fakes.FakeCmdRunner partitioner *disk.Partitioner diff --git a/platform/windows/powershell/runner_test.go b/platform/windows/powershell/runner_test.go index 573dcc179..43ee1c369 100644 --- a/platform/windows/powershell/runner_test.go +++ b/platform/windows/powershell/runner_test.go @@ -125,7 +125,8 @@ Missing statement body in do loop. BaseCmdRunner: baseCmdRunner, } - powershellRunner.RunCommandQuietly(powershellCommandArgs[0], powershellCommandArgs[1:]...) + _, _, _, err := powershellRunner.RunCommandQuietly(powershellCommandArgs[0], powershellCommandArgs[1:]...) + Expect(err).NotTo(HaveOccurred()) Expect(baseCmdRunner.RunCommandsQuietly).To(Equal([][]string{strings.Split(expectedCommand, " ")})) }) @@ -139,7 +140,8 @@ Missing statement body in do loop. } input := "Some stdin" - powershellRunner.RunCommandWithInput(input, powershellCommandArgs[0], powershellCommandArgs[1:]...) + _, _, _, err := powershellRunner.RunCommandWithInput(input, powershellCommandArgs[0], powershellCommandArgs[1:]...) + Expect(err).NotTo(HaveOccurred()) Expect(baseCmdRunner.RunCommandsWithInput).To(Equal( [][]string{append([]string{input}, strings.Split(expectedCommand, " ")...)}, )) @@ -160,7 +162,8 @@ Missing statement body in do loop. BaseCmdRunner: baseCmdRunner, } - powershellRunner.RunComplexCommand(complexCommand) + _, _, _, err := powershellRunner.RunComplexCommand(complexCommand) + Expect(err).NotTo(HaveOccurred()) Expect(baseCmdRunner.RunComplexCommands).To(Equal([]system.Command{expectedCommand})) }) @@ -184,7 +187,8 @@ Missing statement body in do loop. &fakes.FakeProcess{}, ) - powershellRunner.RunComplexCommandAsync(complexCommand) + _, err := powershellRunner.RunComplexCommandAsync(complexCommand) + Expect(err).NotTo(HaveOccurred()) Expect(baseCmdRunner.RunComplexCommands).To(Equal([]system.Command{expectedCommand})) }) diff --git a/platform/windows_platform_test.go b/platform/windows_platform_test.go index be43e8159..1c23fc20b 100644 --- a/platform/windows_platform_test.go +++ b/platform/windows_platform_test.go @@ -44,19 +44,19 @@ import ( ) var ( - modadvapi32 = windows.NewLazySystemDLL("Advapi32.dll") - procLogonUser = modadvapi32.NewProc("LogonUserW") + modadvapi32 = windows.NewLazySystemDLL("Advapi32.dll") //nolint:gochecknoglobals + procLogonUser = modadvapi32.NewProc("LogonUserW") //nolint:gochecknoglobals ) -const ERROR_LOGON_FAILURE = syscall.Errno(0x52E) +const ERROR_LOGON_FAILURE = syscall.Errno(0x52E) //nolint:revive // Use LogonUser to check if the provided password is correct. // // https://msdn.microsoft.com/en-us/library/windows/desktop/aa378184(v=vs.85).aspx // func ValidUserPassword(username, password string) error { - const LOGON32_LOGON_NETWORK = 3 - const LOGON32_PROVIDER_DEFAULT = 0 + const LOGON32_LOGON_NETWORK = 3 //nolint:revive + const LOGON32_PROVIDER_DEFAULT = 0 //nolint:revive if err := procLogonUser.Find(); err != nil { return err @@ -84,7 +84,7 @@ func ValidUserPassword(username, password string) error { } return e1 } - windows.CloseHandle(token) + windows.CloseHandle(token) //nolint:errcheck return nil } @@ -159,7 +159,7 @@ var _ = Describe("WindowsPlatform", func() { Describe("GetFileContentsFromCDROM", func() { It("reads file from D drive", func() { - fs.WriteFileString("D:/env", "fake-contents") + fs.WriteFileString("D:/env", "fake-contents") //nolint:errcheck contents, err := platform.GetFileContentsFromCDROM("env") Expect(err).NotTo(HaveOccurred()) Expect(contents).To(Equal([]byte("fake-contents"))) @@ -182,7 +182,7 @@ var _ = Describe("WindowsPlatform", func() { fileStats := fs.GetFileTestStat("/fake-dir/data/tmp") Expect(fileStats).NotTo(BeNil()) - Expect(fileStats.FileType).To(Equal(fakesys.FakeFileType(fakesys.FakeFileTypeDir))) + Expect(fileStats.FileType).To(Equal(fakesys.FakeFileTypeDir)) }) It("returns error if creating new temp dir errs", func() { @@ -218,7 +218,7 @@ var _ = Describe("WindowsPlatform", func() { fileStats := fs.GetFileTestStat("/fake-dir/data/blobs") Expect(fileStats).NotTo(BeNil()) - Expect(fileStats.FileType).To(Equal(fakesys.FakeFileType(fakesys.FakeFileTypeDir))) + Expect(fileStats.FileType).To(Equal(fakesys.FakeFileTypeDir)) }) It("returns error if creating new temp dir errs", func() { @@ -237,11 +237,11 @@ var _ = Describe("WindowsPlatform", func() { fileStats := fs.GetFileTestStat("/fake-dir/data/sys/log") Expect(fileStats).NotTo(BeNil()) - Expect(fileStats.FileType).To(Equal(fakesys.FakeFileType(fakesys.FakeFileTypeDir))) + Expect(fileStats.FileType).To(Equal(fakesys.FakeFileTypeDir)) fileStats = fs.GetFileTestStat("/fake-dir/sys") Expect(fileStats).NotTo(BeNil()) - Expect(fileStats.FileType).To(Equal(fakesys.FakeFileType(fakesys.FakeFileTypeSymlink))) + Expect(fileStats.FileType).To(Equal(fakesys.FakeFileTypeSymlink)) }) It("returns error if creating new temp dir errs", func() { @@ -279,7 +279,7 @@ var _ = Describe("WindowsPlatform", func() { Describe("SetTimeWithNtpServers", func() { It("sets time with ntp servers", func() { servers := []string{"0.north-america.pool.ntp.org", "1.north-america.pool.ntp.org"} - platform.SetTimeWithNtpServers(servers) + platform.SetTimeWithNtpServers(servers) //nolint:errcheck Expect(len(cmdRunner.RunCommands)).To(Equal(6)) Expect(cmdRunner.RunCommands[0]).To(ContainElement(ContainSubstring("new-netfirewallrule"))) @@ -293,7 +293,7 @@ var _ = Describe("WindowsPlatform", func() { }) It("sets time with ntp servers is noop when no ntp server provided", func() { - platform.SetTimeWithNtpServers([]string{}) + platform.SetTimeWithNtpServers([]string{}) //nolint:errcheck Expect(len(cmdRunner.RunCommands)).To(Equal(0)) }) }) @@ -380,7 +380,7 @@ var _ = Describe("WindowsPlatform", func() { drive += "\\" dirname := filepath.Join(drive, "ProgramData", "ssh") - fs.MkdirAll(dirname, 0744) + fs.MkdirAll(dirname, 0744) //nolint:errcheck var keyTypes = []string{ "dsa", "ecdsa", @@ -391,9 +391,9 @@ var _ = Describe("WindowsPlatform", func() { name := fmt.Sprintf("ssh_host_%s_key", s) path := filepath.Join(dirname, name) - fs.WriteFileString(path, fmt.Sprintf("PRIVATE %s KEY", strings.ToUpper(s))) + fs.WriteFileString(path, fmt.Sprintf("PRIVATE %s KEY", strings.ToUpper(s))) //nolint:errcheck path += ".pub" - fs.WriteFileString(path, fmt.Sprintf("PUBLIC %s KEY", strings.ToUpper(s))) + fs.WriteFileString(path, fmt.Sprintf("PUBLIC %s KEY", strings.ToUpper(s))) //nolint:errcheck } } @@ -696,7 +696,7 @@ var _ = Describe("WindowsPlatform", func() { }) It("returns an error when getting free disk space command fails", func() { - expectedError := errors.New("It went wrong") + expectedError := errors.New("it went wrong") partitioner.GetFreeSpaceOnDiskReturns(0, expectedError) err := platform.SetupEphemeralDiskWithPath(diskNumber, nil, labelPrefix) @@ -708,7 +708,7 @@ var _ = Describe("WindowsPlatform", func() { diskNumber = "1" partitionNumber = "1" - partitionCountError := errors.New("Something failed") + partitionCountError := errors.New("something failed") partitioner.GetCountOnDiskReturns("", partitionCountError) err := platform.SetupEphemeralDiskWithPath(diskNumber, nil, labelPrefix) @@ -720,7 +720,7 @@ var _ = Describe("WindowsPlatform", func() { diskNumber = "1" partitionNumber = "1" - initializeDiskError := errors.New("It went wrong") + initializeDiskError := errors.New("it went wrong") partitioner.InitializeDiskReturns(initializeDiskError) err := platform.SetupEphemeralDiskWithPath(diskNumber, nil, labelPrefix) @@ -738,7 +738,7 @@ var _ = Describe("WindowsPlatform", func() { }) It("returns an error when partition disk command fails", func() { - partitionDiskError := errors.New("It went wrong") + partitionDiskError := errors.New("it went wrong") partitioner.PartitionDiskReturns("", partitionDiskError) err := platform.SetupEphemeralDiskWithPath(diskNumber, nil, labelPrefix) @@ -765,7 +765,7 @@ var _ = Describe("WindowsPlatform", func() { }) It("returns an error when creating a symlink fails", func() { - LinkError := errors.New("It went wrong") + LinkError := errors.New("it went wrong") linker.LinkReturns(LinkError) err := platform.SetupEphemeralDiskWithPath(diskNumber, nil, labelPrefix) @@ -774,7 +774,7 @@ var _ = Describe("WindowsPlatform", func() { }) It("returns an error protecting path command fails", func() { - protectPathError := errors.New("Failure") + protectPathError := errors.New("failure") protector.ProtectPathReturns(protectPathError) err := platform.SetupEphemeralDiskWithPath(diskNumber, nil, labelPrefix) @@ -876,7 +876,6 @@ func expectFormatterCalledWithArgs( expectedDiskNumber, expectedPartitionNumber string, ) { - ExpectWithOffset(1, formatter.FormatCallCount()).To(Equal(1)) diskNumber, partitionNumber := formatter.FormatArgsForCall(0) ExpectWithOffset(1, diskNumber).To(Equal(expectedDiskNumber)) @@ -895,7 +894,6 @@ func expectAssignDriveLetterCalledWithArgs( expectedDiskNumber, expectedPartitionNumber string, ) { - ExpectWithOffset(1, partitioner.AssignDriveLetterCallCount()).To(Equal(1)) diskNumber, partitionNumber := partitioner.AssignDriveLetterArgsForCall(0) Expect(diskNumber).To(Equal(expectedDiskNumber)) @@ -915,11 +913,11 @@ var _ = Describe("BOSH User Commands", func() { ) BeforeEach(func() { - testUsername = fmt.Sprintf("%stest_%s", boshsettings.EphemeralUserPrefix, fmt.Sprintf("%s", uuid.New())[0:8]) + testUsername = fmt.Sprintf("%stest_%s", boshsettings.EphemeralUserPrefix, uuid.New().String()[0:8]) deleteUserOnce.Do(func() { - DeleteLocalUser(testUsername) - DeleteLocalUser("vcap") + DeleteLocalUser(testUsername) //nolint:errcheck + DeleteLocalUser("vcap") //nolint:errcheck }) }) @@ -935,16 +933,15 @@ var _ = Describe("BOSH User Commands", func() { } AfterEach(func() { - DeleteLocalUser(testUsername) - DeleteLocalUser("vcap") + DeleteLocalUser(testUsername) //nolint:errcheck + DeleteLocalUser("vcap") //nolint:errcheck Expect(userExists(testUsername)).ToNot(Succeed()) - cmdRunner.RunCommand(powershell.Executable, "-Command", `get-wmiobject -class win32_userprofile | where { $_.LocalPath -like 'C:\Users\bosh*' } | remove-wmiobject`) - cmdRunner.RunCommand(powershell.Executable, "-Command", fmt.Sprintf(`Remove-Item C:\Users\%s* -Force -Recurse`, testUsername)) + cmdRunner.RunCommand(powershell.Executable, "-Command", `get-wmiobject -class win32_userprofile | where { $_.LocalPath -like 'C:\Users\bosh*' } | remove-wmiobject`) //nolint:errcheck + cmdRunner.RunCommand(powershell.Executable, "-Command", fmt.Sprintf(`Remove-Item C:\Users\%s* -Force -Recurse`, testUsername)) //nolint:errcheck }) Describe("SSH", func() { - var platform Platform BeforeEach(func() { @@ -991,7 +988,7 @@ var _ = Describe("BOSH User Commands", func() { if err != nil { return false } - defer m.Disconnect() + defer m.Disconnect() //nolint:errcheck s, err := m.OpenService("sshd") if err != nil { return false @@ -1166,11 +1163,11 @@ var _ = Describe("BOSH User Commands", func() { Expect(platform.SetUserPassword(boshsettings.VCAPUsername, testPassword)).To(Succeed()) Expect(lockFile).To(BeAnExistingFile()) - fs.RemoveAll(lockFile) + fs.RemoveAll(lockFile) //nolint:errcheck Expect(platform.SetUserPassword(boshsettings.RootUsername, testPassword)).To(Succeed()) Expect(lockFile).To(BeAnExistingFile()) - fs.RemoveAll(lockFile) + fs.RemoveAll(lockFile) //nolint:errcheck }) It("sets a random password on the Administrator user if it exists", func() { @@ -1197,7 +1194,7 @@ var _ = Describe("BOSH User Commands", func() { fmt.Sprintf("Testing with Root user: %s", root)) Expect(lockFile).To(BeAnExistingFile()) - fs.RemoveAll(lockFile) + fs.RemoveAll(lockFile) //nolint:errcheck } }) diff --git a/settings/service_test.go b/settings/service_test.go index 9047389f3..d5d967596 100644 --- a/settings/service_test.go +++ b/settings/service_test.go @@ -82,7 +82,8 @@ var _ = Describe("settingsService", func() { go func() { for i := 0; i < 100000; i++ { - service.LoadSettings() + err := service.LoadSettings() + Expect(err).NotTo(HaveOccurred()) } done <- true }() @@ -162,10 +163,11 @@ var _ = Describe("settingsService", func() { Context("when a settings file exists", func() { Context("when settings contain at most one dynamic network", func() { BeforeEach(func() { - fs.WriteFile("/setting/path.json", []byte(`{ + err := fs.WriteFile("/setting/path.json", []byte(`{ "agent_id":"some-agent-id", "networks": {"fake-net-1": {"type": "dynamic"}} }`)) + Expect(err).NotTo(HaveOccurred()) fakePlatformSettingsGetter.GetDefaultNetworkReturns(Network{ IP: "fake-resolved-ip", @@ -199,9 +201,10 @@ var _ = Describe("settingsService", func() { }) It("fetches UpdateSettings", func() { - fs.WriteFile(fakePlatformSettingsGetter.GetUpdateSettingsPath(false), []byte(`{"trusted_certs": "a trusted cert"}`)) + err := fs.WriteFile(fakePlatformSettingsGetter.GetUpdateSettingsPath(false), []byte(`{"trusted_certs": "a trusted cert"}`)) + Expect(err).NotTo(HaveOccurred()) - err := service.LoadSettings() + err = service.LoadSettings() Expect(err).NotTo(HaveOccurred()) settings := service.GetSettings() @@ -212,9 +215,10 @@ var _ = Describe("settingsService", func() { Context("when non-unmarshallable settings file exists", func() { It("returns any error from the fetcher", func() { - fs.WriteFile("/setting/path.json", []byte(`$%^&*(`)) + err := fs.WriteFile("/setting/path.json", []byte(`$%^&*(`)) + Expect(err).NotTo(HaveOccurred()) - err := service.LoadSettings() + err = service.LoadSettings() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("fake-fetch-error")) @@ -236,7 +240,8 @@ var _ = Describe("settingsService", func() { Describe("UpdateSettings", func() { Context("when the update_settings.json exists", func() { BeforeEach(func() { - fs.WriteFile(fakePlatformSettingsGetter.GetUpdateSettingsPath(false), []byte(`{"trusted_certs": "a trusted cert"}`)) + err := fs.WriteFile(fakePlatformSettingsGetter.GetUpdateSettingsPath(false), []byte(`{"trusted_certs": "a trusted cert"}`)) + Expect(err).NotTo(HaveOccurred()) }) It("populates settings with an UpdateSettings read from the update settings file", func() { @@ -289,16 +294,6 @@ var _ = Describe("settingsService", func() { }) Context("disk settings file exists", func() { - BeforeEach(func() { - err := fs.WriteFileQuietly("/setting/persistent_settings.json", []byte("{}")) - Expect(err).ToNot(HaveOccurred()) - }) - - It("loads persistent settings from disk", func() { - service.GetPersistentDiskSettings("fake-disk-cid") - Expect(fs.ReadFileWithOptsCallCount).To(Equal(1)) - }) - Context("has invalid settings saved on disk", func() { var existingSettingsOnDisk []DiskSettings // The correct format is map[string]DiskSettings but we want to write out an incorrect format. @@ -359,6 +354,7 @@ var _ = Describe("settingsService", func() { }, } }) + It("returns disk settings", func() { settings, err := service.GetPersistentDiskSettings("disk-cid") Expect(err).ToNot(HaveOccurred()) @@ -608,9 +604,10 @@ var _ = Describe("settingsService", func() { fakeSettingsSource.SettingsErr = nil service, fs := buildService() - fs.WriteFile("/setting/path.json", []byte(`{}`)) + err := fs.WriteFile("/setting/path.json", []byte(`{}`)) + Expect(err).NotTo(HaveOccurred()) - err := service.InvalidateSettings() + err = service.InvalidateSettings() Expect(err).ToNot(HaveOccurred()) Expect(fs.FileExists("/setting/path.json")).To(BeFalse()) @@ -737,6 +734,7 @@ var _ = Describe("settingsService", func() { err := service.SaveUpdateSettings(updateSettings) Expect(err).NotTo(HaveOccurred()) jsonString, err := json.Marshal(updateSettings) + Expect(err).NotTo(HaveOccurred()) fileContent, err := fs.ReadFile(fakePlatformSettingsGetter.GetUpdateSettingsPath(false)) Expect(err).NotTo(HaveOccurred())