diff --git a/client/acl_test.go b/client/acl_test.go index 91bd4427510..91303ef7959 100644 --- a/client/acl_test.go +++ b/client/acl_test.go @@ -11,7 +11,6 @@ import ( "github.com/hashicorp/nomad/acl" "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/client/config" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" @@ -261,7 +260,7 @@ func TestClient_ACL_ResolveToken_Expired(t *testing.T) { // Create and upsert a token which has just expired. mockExpiredToken := mock.ACLToken() - mockExpiredToken.ExpirationTime = pointer.Of(time.Now().Add(-5 * time.Minute)) + mockExpiredToken.ExpirationTime = new(time.Now().Add(-5 * time.Minute)) err := s1.State().UpsertACLTokens(structs.MsgTypeTestSetup, 120, []*structs.ACLToken{mockExpiredToken}) must.NoError(t, err) diff --git a/client/agent_endpoint.go b/client/agent_endpoint.go index 8b89ae37523..e7b5eb91a65 100644 --- a/client/agent_endpoint.go +++ b/client/agent_endpoint.go @@ -18,7 +18,6 @@ import ( "github.com/hashicorp/nomad/command/agent/host" "github.com/hashicorp/nomad/command/agent/monitor" "github.com/hashicorp/nomad/command/agent/pprof" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/structs" ) @@ -88,16 +87,16 @@ func (a *Agent) monitor(conn io.ReadWriteCloser) { encoder := codec.NewEncoder(conn, structs.MsgpackHandle) if err := decoder.Decode(&args); err != nil { - handleStreamResultError(err, pointer.Of(int64(500)), encoder) + handleStreamResultError(err, new(int64(500)), encoder) return } // Check acl if aclObj, err := a.c.ResolveToken(args.AuthToken); err != nil { - handleStreamResultError(err, pointer.Of(int64(403)), encoder) + handleStreamResultError(err, new(int64(403)), encoder) return } else if !aclObj.AllowAgentRead() { - handleStreamResultError(structs.ErrPermissionDenied, pointer.Of(int64(403)), encoder) + handleStreamResultError(structs.ErrPermissionDenied, new(int64(403)), encoder) return } @@ -107,7 +106,7 @@ func (a *Agent) monitor(conn io.ReadWriteCloser) { } if logLevel == log.NoLevel { - handleStreamResultError(errors.New("Unknown log level"), pointer.Of(int64(400)), encoder) + handleStreamResultError(errors.New("Unknown log level"), new(int64(400)), encoder) return } @@ -168,7 +167,7 @@ func (a *Agent) monitor(conn io.ReadWriteCloser) { streamErr := streamEncoder.EncodeStream(frames, errCh, ctx, framer, false) if streamErr != nil { - handleStreamResultError(streamErr, pointer.Of(int64(500)), encoder) + handleStreamResultError(streamErr, new(int64(500)), encoder) return } } @@ -203,22 +202,22 @@ func (a *Agent) monitorExport(conn io.ReadWriteCloser) { encoder := codec.NewEncoder(conn, structs.MsgpackHandle) if err := decoder.Decode(&args); err != nil { - handleStreamResultError(err, pointer.Of(int64(500)), encoder) + handleStreamResultError(err, new(int64(500)), encoder) return } // Check acl if aclObj, err := a.c.ResolveToken(args.AuthToken); err != nil { - handleStreamResultError(err, pointer.Of(int64(403)), encoder) + handleStreamResultError(err, new(int64(403)), encoder) return } else if !aclObj.AllowAgentRead() { - handleStreamResultError(structs.ErrPermissionDenied, pointer.Of(int64(403)), encoder) + handleStreamResultError(structs.ErrPermissionDenied, new(int64(403)), encoder) return } nomadLogPath := a.c.GetConfig().LogFile if args.OnDisk && nomadLogPath == "" { - handleStreamResultError(errors.New("No nomad log file defined"), pointer.Of(int64(400)), encoder) + handleStreamResultError(errors.New("No nomad log file defined"), new(int64(400)), encoder) } ctx, cancel := context.WithCancel(context.Background()) @@ -255,7 +254,7 @@ func (a *Agent) monitorExport(conn io.ReadWriteCloser) { m, err := monitor.NewExportMonitor(opts) if err != nil { - handleStreamResultError(err, pointer.Of(int64(500)), encoder) + handleStreamResultError(err, new(int64(500)), encoder) return } var eofCancelCh chan error @@ -279,7 +278,7 @@ func (a *Agent) monitorExport(conn io.ReadWriteCloser) { streamErr := streamEncoder.EncodeStream(frames, errCh, ctx, framer, true) if streamErr != nil { - handleStreamResultError(streamErr, pointer.Of(int64(500)), encoder) + handleStreamResultError(streamErr, new(int64(500)), encoder) return } } diff --git a/client/alloc_endpoint.go b/client/alloc_endpoint.go index 4b82ad606dd..70ee46a8ac2 100644 --- a/client/alloc_endpoint.go +++ b/client/alloc_endpoint.go @@ -16,7 +16,6 @@ import ( "github.com/hashicorp/go-msgpack/v2/codec" "github.com/hashicorp/nomad/acl" cstructs "github.com/hashicorp/nomad/client/structs" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" nstructs "github.com/hashicorp/nomad/nomad/structs" "github.com/hashicorp/nomad/plugins/drivers" @@ -233,7 +232,7 @@ func (a *Allocations) execImpl(encoder *codec.Encoder, decoder *codec.Decoder, e // Decode the arguments var req cstructs.AllocExecRequest if err := decoder.Decode(&req); err != nil { - return pointer.Of(int64(500)), err + return new(int64(500)), err } if a.c.GetConfig().DisableRemoteExec { @@ -241,13 +240,13 @@ func (a *Allocations) execImpl(encoder *codec.Encoder, decoder *codec.Decoder, e } if req.AllocID == "" { - return pointer.Of(int64(400)), allocIDNotPresentErr + return new(int64(400)), allocIDNotPresentErr } ar, err := a.c.getAllocRunner(req.AllocID) if err != nil { - code := pointer.Of(int64(500)) + code := new(int64(500)) if nstructs.IsErrUnknownAllocation(err) { - code = pointer.Of(int64(404)) + code = new(int64(404)) } return code, err @@ -286,18 +285,18 @@ func (a *Allocations) execImpl(encoder *codec.Encoder, decoder *codec.Decoder, e // Check alloc-exec permission. if err != nil { - return pointer.Of(int64(400)), err + return new(int64(400)), err } else if !aclObj.AllowNsOp(alloc.Namespace, acl.NamespaceCapabilityAllocExec) { return nil, nstructs.ErrPermissionDenied } // Validate the arguments if req.Task == "" { - return pointer.Of(int64(400)), taskNotPresentErr + return new(int64(400)), taskNotPresentErr } if req.JobID != "" && req.JobID != alloc.JobID { - return pointer.Of(int64(http.StatusBadRequest)), + return new(int64(http.StatusBadRequest)), fmt.Errorf("job %s does not have allocation %s", req.JobID, req.AllocID) } @@ -305,12 +304,12 @@ func (a *Allocations) execImpl(encoder *codec.Encoder, decoder *codec.Decoder, e if req.Action != "" { task := alloc.LookupTask(req.Task) if task == nil { - return pointer.Of(int64(http.StatusBadRequest)), + return new(int64(http.StatusBadRequest)), fmt.Errorf("task %s not found in allocation %s", req.Task, alloc.ID) } jobAction := task.GetAction(req.Action) if jobAction == nil { - return pointer.Of(int64(http.StatusBadRequest)), + return new(int64(http.StatusBadRequest)), fmt.Errorf("action %s not found in task %s", req.Action, req.Task) } @@ -319,14 +318,14 @@ func (a *Allocations) execImpl(encoder *codec.Encoder, decoder *codec.Decoder, e } if len(req.Cmd) == 0 { - return pointer.Of(int64(400)), errors.New("command is not present") + return new(int64(400)), errors.New("command is not present") } capabilities, err := ar.GetTaskDriverCapabilities(req.Task) if err != nil { - code := pointer.Of(int64(500)) + code := new(int64(500)) if nstructs.IsErrUnknownAllocation(err) { - code = pointer.Of(int64(404)) + code = new(int64(404)) } return code, err @@ -342,9 +341,9 @@ func (a *Allocations) execImpl(encoder *codec.Encoder, decoder *codec.Decoder, e allocState, err := a.c.GetAllocState(req.AllocID) if err != nil { - code := pointer.Of(int64(500)) + code := new(int64(500)) if nstructs.IsErrUnknownAllocation(err) { - code = pointer.Of(int64(404)) + code = new(int64(404)) } return code, err @@ -353,11 +352,11 @@ func (a *Allocations) execImpl(encoder *codec.Encoder, decoder *codec.Decoder, e // Check that the task is there taskState := allocState.TaskStates[req.Task] if taskState == nil { - return pointer.Of(int64(400)), fmt.Errorf("unknown task name %q", req.Task) + return new(int64(400)), fmt.Errorf("unknown task name %q", req.Task) } if taskState.StartedAt.IsZero() { - return pointer.Of(int64(404)), fmt.Errorf("task %q not started yet.", req.Task) + return new(int64(404)), fmt.Errorf("task %q not started yet.", req.Task) } ctx, cancel := context.WithCancel(context.Background()) @@ -365,12 +364,12 @@ func (a *Allocations) execImpl(encoder *codec.Encoder, decoder *codec.Decoder, e h := ar.GetTaskExecHandler(req.Task) if h == nil { - return pointer.Of(int64(404)), fmt.Errorf("task %q is not running.", req.Task) + return new(int64(404)), fmt.Errorf("task %q is not running.", req.Task) } err = h(ctx, req.Cmd, req.Tty, newExecStream(decoder, encoder)) if err != nil { - code := pointer.Of(int64(500)) + code := new(int64(500)) return code, err } diff --git a/client/allocrunner/alloc_runner.go b/client/allocrunner/alloc_runner.go index e0cb0d7daa8..1c706af9c1f 100644 --- a/client/allocrunner/alloc_runner.go +++ b/client/allocrunner/alloc_runner.go @@ -37,7 +37,6 @@ import ( "github.com/hashicorp/nomad/client/taskenv" "github.com/hashicorp/nomad/client/vaultclient" "github.com/hashicorp/nomad/client/widmgr" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/users/dynamic" "github.com/hashicorp/nomad/nomad/structs" "github.com/hashicorp/nomad/plugins/device" @@ -863,7 +862,7 @@ func (ar *allocRunner) clientAlloc(taskStates map[string]*structs.TaskState) *st if a.ClientStatus == structs.AllocClientStatusFailed && alloc.DeploymentID != "" && !a.DeploymentStatus.HasHealth() { a.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(false), + Healthy: new(false), } } diff --git a/client/allocrunner/csi_hook_test.go b/client/allocrunner/csi_hook_test.go index 8d488cba7d4..49cebdfc321 100644 --- a/client/allocrunner/csi_hook_test.go +++ b/client/allocrunner/csi_hook_test.go @@ -14,7 +14,6 @@ import ( "github.com/hashicorp/nomad/client/allocrunner/state" "github.com/hashicorp/nomad/client/pluginmanager/csimanager" cstructs "github.com/hashicorp/nomad/client/structs" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/testlog" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" @@ -317,8 +316,8 @@ func TestCSIHook(t *testing.T) { alloc: alloc, ns: tc.rpcNS, callCounts: callCounts, - hasExistingClaim: pointer.Of(tc.startsWithClaims), - schedulable: pointer.Of(!tc.startsUnschedulable), + hasExistingClaim: new(tc.startsWithClaims), + schedulable: new(!tc.startsUnschedulable), } ar := mockAllocRunner{ res: &cstructs.AllocHookResources{}, @@ -460,8 +459,8 @@ func TestCSIHook_Prerun_Validation(t *testing.T) { rpcer := mockRPCer{ alloc: alloc, callCounts: testutil.NewCallCounter(), - hasExistingClaim: pointer.Of(false), - schedulable: pointer.Of(true), + hasExistingClaim: new(false), + schedulable: new(true), } ar := mockAllocRunner{ diff --git a/client/allocrunner/group_service_hook_test.go b/client/allocrunner/group_service_hook_test.go index 630bdf75a38..3d13b46a8ef 100644 --- a/client/allocrunner/group_service_hook_test.go +++ b/client/allocrunner/group_service_hook_test.go @@ -15,7 +15,6 @@ import ( cstructs "github.com/hashicorp/nomad/client/structs" "github.com/hashicorp/nomad/client/taskenv" agentconsul "github.com/hashicorp/nomad/command/agent/consul" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/testlog" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" @@ -73,7 +72,7 @@ func TestGroupServiceHook_ShutdownDelayUpdate(t *testing.T) { ci.Parallel(t) alloc := mock.Alloc() - alloc.Job.TaskGroups[0].ShutdownDelay = pointer.Of(10 * time.Second) + alloc.Job.TaskGroups[0].ShutdownDelay = new(10 * time.Second) logger := testlog.HCLogger(t) consulMockClient := regMock.NewServiceRegistrationHandler(logger) @@ -95,7 +94,7 @@ func TestGroupServiceHook_ShutdownDelayUpdate(t *testing.T) { must.NoError(t, h.Prerun(env)) // Incease shutdown Delay - alloc.Job.TaskGroups[0].ShutdownDelay = pointer.Of(15 * time.Second) + alloc.Job.TaskGroups[0].ShutdownDelay = new(15 * time.Second) req := &interfaces.RunnerUpdateRequest{Alloc: alloc, AllocEnv: env} must.NoError(t, h.Update(req)) diff --git a/client/allocrunner/taskrunner/connect_native_hook_test.go b/client/allocrunner/taskrunner/connect_native_hook_test.go index 2020b5d2db1..4b269a7c5bb 100644 --- a/client/allocrunner/taskrunner/connect_native_hook_test.go +++ b/client/allocrunner/taskrunner/connect_native_hook_test.go @@ -18,7 +18,6 @@ import ( "github.com/hashicorp/nomad/client/taskenv" "github.com/hashicorp/nomad/client/testutil" agentconsul "github.com/hashicorp/nomad/command/agent/consul" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/testlog" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" @@ -475,8 +474,8 @@ func TestTaskRunner_ConnectNativeHook_shareTLS(t *testing.T) { // TLS config consumed by native application ShareSSL: shareSSL, - EnableSSL: pointer.Of(true), - VerifySSL: pointer.Of(true), + EnableSSL: new(true), + VerifySSL: new(true), CAFile: fakeCert, CertFile: fakeCert, KeyFile: fakeCert, @@ -522,7 +521,7 @@ func TestTaskRunner_ConnectNativeHook_shareTLS(t *testing.T) { // so make sure an unset value turns the feature on. t.Run("share_ssl is true", func(t *testing.T) { - try(t, pointer.Of(true)) + try(t, new(true)) }) t.Run("share_ssl is nil", func(t *testing.T) { @@ -590,9 +589,9 @@ func TestTaskRunner_ConnectNativeHook_shareTLS_override(t *testing.T) { Addr: consulConfig.Address, // TLS config consumed by native application - ShareSSL: pointer.Of(true), - EnableSSL: pointer.Of(true), - VerifySSL: pointer.Of(true), + ShareSSL: new(true), + EnableSSL: new(true), + VerifySSL: new(true), CAFile: fakeCert, CertFile: fakeCert, KeyFile: fakeCert, diff --git a/client/allocrunner/taskrunner/envoy_bootstrap_hook_test.go b/client/allocrunner/taskrunner/envoy_bootstrap_hook_test.go index c0242216d4c..3bbb459c102 100644 --- a/client/allocrunner/taskrunner/envoy_bootstrap_hook_test.go +++ b/client/allocrunner/taskrunner/envoy_bootstrap_hook_test.go @@ -28,7 +28,6 @@ import ( "github.com/hashicorp/nomad/client/testutil" agentconsul "github.com/hashicorp/nomad/command/agent/consul" "github.com/hashicorp/nomad/helper/args" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/testlog" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" @@ -104,8 +103,8 @@ func TestEnvoyBootstrapHook_decodeTriState(t *testing.T) { ci.Parallel(t) require.Equal(t, "", decodeTriState(nil)) - require.Equal(t, "true", decodeTriState(pointer.Of(true))) - require.Equal(t, "false", decodeTriState(pointer.Of(false))) + require.Equal(t, "true", decodeTriState(new(true))) + require.Equal(t, "false", decodeTriState(new(false))) } var ( diff --git a/client/allocrunner/taskrunner/getter/testing.go b/client/allocrunner/taskrunner/getter/testing.go index b5c702dde5d..a730537d2fd 100644 --- a/client/allocrunner/taskrunner/getter/testing.go +++ b/client/allocrunner/taskrunner/getter/testing.go @@ -9,7 +9,6 @@ import ( "testing" cconfig "github.com/hashicorp/nomad/client/config" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/testlog" sconfig "github.com/hashicorp/nomad/nomad/structs/config" "github.com/shoenig/test/must" @@ -19,8 +18,8 @@ import ( // artifact config. It is good enough for tests so no mock implementation exists. func TestSandbox(t *testing.T) *Sandbox { defaultConfig := sconfig.DefaultArtifactConfig() - defaultConfig.DecompressionSizeLimit = pointer.Of("1MB") - defaultConfig.DecompressionFileCountLimit = pointer.Of(10) + defaultConfig.DecompressionSizeLimit = new("1MB") + defaultConfig.DecompressionFileCountLimit = new(10) ac, err := cconfig.ArtifactConfigFromAgent(defaultConfig) must.NoError(t, err) return New(ac, testlog.HCLogger(t)) diff --git a/client/allocrunner/taskrunner/secrets_hook_test.go b/client/allocrunner/taskrunner/secrets_hook_test.go index 27dd2be02b1..074e52b6757 100644 --- a/client/allocrunner/taskrunner/secrets_hook_test.go +++ b/client/allocrunner/taskrunner/secrets_hook_test.go @@ -21,7 +21,6 @@ import ( "github.com/hashicorp/nomad/client/config" "github.com/hashicorp/nomad/client/taskenv" "github.com/hashicorp/nomad/helper/bufconndialer" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/testlog" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" @@ -263,7 +262,7 @@ func TestSecretsHook_Prestart_Vault(t *testing.T) { clientConfig.VaultConfigs = map[string]*structsc.VaultConfig{ structs.VaultDefaultCluster: { Name: structs.VaultDefaultCluster, - Enabled: pointer.Of(true), + Enabled: new(true), Addr: defaultVaultServer.URL, }, } diff --git a/client/allocrunner/taskrunner/task_runner_linux_test.go b/client/allocrunner/taskrunner/task_runner_linux_test.go index 1343e81d4de..64f49cefab6 100644 --- a/client/allocrunner/taskrunner/task_runner_linux_test.go +++ b/client/allocrunner/taskrunner/task_runner_linux_test.go @@ -39,19 +39,17 @@ import ( cstate "github.com/hashicorp/nomad/client/state" cstructs "github.com/hashicorp/nomad/client/structs" "github.com/hashicorp/nomad/client/taskenv" - "github.com/hashicorp/nomad/helper" - structsc "github.com/hashicorp/nomad/nomad/structs/config" - ctestutil "github.com/hashicorp/nomad/client/testutil" "github.com/hashicorp/nomad/client/vaultclient" "github.com/hashicorp/nomad/client/widmgr" agentconsul "github.com/hashicorp/nomad/command/agent/consul" mockdriver "github.com/hashicorp/nomad/drivers/mock" "github.com/hashicorp/nomad/drivers/rawexec" - "github.com/hashicorp/nomad/helper/pointer" + "github.com/hashicorp/nomad/helper" "github.com/hashicorp/nomad/helper/testlog" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" + structsc "github.com/hashicorp/nomad/nomad/structs/config" "github.com/hashicorp/nomad/plugins/device" "github.com/hashicorp/nomad/plugins/drivers" "github.com/hashicorp/nomad/plugins/drivers/fsisolation" @@ -126,7 +124,7 @@ func testTaskRunnerConfig(t *testing.T, alloc *structs.Allocation, taskName stri db := cstate.NewMemDB(logger) if thisTask.Vault != nil { - clientConf.GetDefaultVault().Enabled = pointer.Of(true) + clientConf.GetDefaultVault().Enabled = new(true) } var vaultFunc vaultclient.VaultClientFunc @@ -1120,7 +1118,7 @@ func TestTaskRunner_NoShutdownDelay(t *testing.T) { maxTimeToFailDuration := time.Duration(testutil.TestMultiplier()) * time.Second alloc := mock.Alloc() - alloc.DesiredTransition = structs.DesiredTransition{NoShutdownDelay: pointer.Of(true)} + alloc.DesiredTransition = structs.DesiredTransition{NoShutdownDelay: new(true)} task := alloc.Job.TaskGroups[0].Tasks[0] task.Services[0].Tags = []string{"tag1"} task.Services = task.Services[:1] // only need 1 for this test @@ -2399,7 +2397,7 @@ func TestTaskRunner_TemplateWorkloadIdentity(t *testing.T) { } conf.ClientConfig.VaultConfigs = map[string]*structsc.VaultConfig{ structs.VaultDefaultCluster: { - Enabled: pointer.Of(true), + Enabled: new(true), Addr: vaultServer.URL, }, } diff --git a/client/allocrunner/taskrunner/template/template.go b/client/allocrunner/taskrunner/template/template.go index a7af2d5b8c9..846a377740f 100644 --- a/client/allocrunner/taskrunner/template/template.go +++ b/client/allocrunner/taskrunner/template/template.go @@ -26,7 +26,6 @@ import ( "github.com/hashicorp/nomad/client/allocrunner/taskrunner/interfaces" "github.com/hashicorp/nomad/client/config" "github.com/hashicorp/nomad/client/taskenv" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/structs" structsc "github.com/hashicorp/nomad/nomad/structs/config" ) @@ -751,7 +750,7 @@ func parseTemplateConfigs(config *TaskTemplateManagerConfig) (map[*ctconf.Templa } ct.Wait = &ctconf.WaitConfig{ - Enabled: pointer.Of(true), + Enabled: new(true), Min: tmpl.Wait.Min, Max: tmpl.Wait.Max, } @@ -869,7 +868,7 @@ func newRunnerConfig(config *TaskTemplateManagerConfig, if config.ConsulConfig.EnableSSL != nil && *config.ConsulConfig.EnableSSL { verify := config.ConsulConfig.VerifySSL != nil && *config.ConsulConfig.VerifySSL conf.Consul.SSL = &ctconf.SSLConfig{ - Enabled: pointer.Of(true), + Enabled: new(true), Verify: &verify, Cert: &config.ConsulConfig.CertFile, Key: &config.ConsulConfig.KeyFile, @@ -884,7 +883,7 @@ func newRunnerConfig(config *TaskTemplateManagerConfig, } conf.Consul.Auth = &ctconf.AuthConfig{ - Enabled: pointer.Of(true), + Enabled: new(true), Username: &parts[0], Password: &parts[1], } @@ -913,7 +912,7 @@ func newRunnerConfig(config *TaskTemplateManagerConfig, // Set up the Vault config // Always set these to ensure nothing is picked up from the environment emptyStr := "" - conf.Vault.RenewToken = pointer.Of(false) + conf.Vault.RenewToken = new(false) conf.Vault.Token = &emptyStr if config.VaultConfig != nil && config.VaultConfig.IsEnabled() { conf.Vault.Address = &config.VaultConfig.Addr @@ -932,7 +931,7 @@ func newRunnerConfig(config *TaskTemplateManagerConfig, skipVerify := config.VaultConfig.TLSSkipVerify != nil && *config.VaultConfig.TLSSkipVerify verify := !skipVerify conf.Vault.SSL = &ctconf.SSLConfig{ - Enabled: pointer.Of(true), + Enabled: new(true), Verify: &verify, Cert: &config.VaultConfig.TLSCertFile, Key: &config.VaultConfig.TLSKeyFile, @@ -942,8 +941,8 @@ func newRunnerConfig(config *TaskTemplateManagerConfig, } } else { conf.Vault.SSL = &ctconf.SSLConfig{ - Enabled: pointer.Of(false), - Verify: pointer.Of(false), + Enabled: new(false), + Verify: new(false), Cert: &emptyStr, Key: &emptyStr, CaCert: &emptyStr, diff --git a/client/allocrunner/taskrunner/template/template_default_test.go b/client/allocrunner/taskrunner/template/template_default_test.go index bd390931aae..8cc1e283949 100644 --- a/client/allocrunner/taskrunner/template/template_default_test.go +++ b/client/allocrunner/taskrunner/template/template_default_test.go @@ -16,7 +16,6 @@ import ( "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/client/taskenv" clienttestutil "github.com/hashicorp/nomad/client/testutil" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" "github.com/hashicorp/nomad/testutil" @@ -37,8 +36,8 @@ func TestTaskTemplateManager_Permissions(t *testing.T) { DestPath: file, ChangeMode: structs.TemplateChangeModeNoop, Perms: "777", - Uid: pointer.Of(503), - Gid: pointer.Of(20), + Uid: new(503), + Gid: new(20), } harness := newTestHarness(t, []*structs.Template{template}, false, false) @@ -59,8 +58,8 @@ func TestTaskTemplateManager_Permissions(t *testing.T) { must.Eq(t, os.ModePerm, fi.Mode()) sys := fi.Sys() - uid := pointer.Of(int(sys.(*syscall.Stat_t).Uid)) - gid := pointer.Of(int(sys.(*syscall.Stat_t).Gid)) + uid := new(int(sys.(*syscall.Stat_t).Uid)) + gid := new(int(sys.(*syscall.Stat_t).Gid)) must.Eq(t, template.Uid, uid) must.Eq(t, template.Gid, gid) diff --git a/client/allocrunner/taskrunner/template/template_test.go b/client/allocrunner/taskrunner/template/template_test.go index cfd7c35885d..9eebf3de084 100644 --- a/client/allocrunner/taskrunner/template/template_test.go +++ b/client/allocrunner/taskrunner/template/template_test.go @@ -28,7 +28,6 @@ import ( "github.com/hashicorp/nomad/client/config" "github.com/hashicorp/nomad/client/taskenv" clienttestutil "github.com/hashicorp/nomad/client/testutil" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/testlog" "github.com/hashicorp/nomad/helper/users" "github.com/hashicorp/nomad/helper/uuid" @@ -94,7 +93,7 @@ func newTestHarness(t *testing.T, templates []*structs.Template, consul, vault b TemplateConfig: &config.ClientTemplateConfig{ FunctionDenylist: config.DefaultTemplateFunctionDenylist, DisableSandbox: false, - ConsulRetry: &config.RetryConfig{Backoff: pointer.Of(10 * time.Millisecond)}, + ConsulRetry: &config.RetryConfig{Backoff: new(10 * time.Millisecond)}, }}, emitRate: DefaultMaxTemplateEventRate, } @@ -359,20 +358,20 @@ func TestTaskTemplateManager_InvalidConfig(t *testing.T) { func TestNewRunnerConfig_Retries(t *testing.T) { tcfg := config.DefaultTemplateConfig() tcfg.ConsulRetry = &config.RetryConfig{ - Attempts: pointer.Of(0), // unlimited - Backoff: pointer.Of(100 * time.Millisecond), - MaxBackoff: pointer.Of(300 * time.Millisecond), + Attempts: new(0), // unlimited + Backoff: new(100 * time.Millisecond), + MaxBackoff: new(300 * time.Millisecond), } tcfg.VaultRetry = &config.RetryConfig{ - Attempts: pointer.Of(5), // limited non-default - Backoff: pointer.Of(200 * time.Millisecond), - MaxBackoff: pointer.Of(500 * time.Millisecond), + Attempts: new(5), // limited non-default + Backoff: new(200 * time.Millisecond), + MaxBackoff: new(500 * time.Millisecond), } managerCfg := &TaskTemplateManagerConfig{ ClientConfig: &config.Config{TemplateConfig: tcfg}, ConsulConfig: &sconfig.ConsulConfig{}, - VaultConfig: &sconfig.VaultConfig{Enabled: pointer.Of(true)}, + VaultConfig: &sconfig.VaultConfig{Enabled: new(true)}, } ct := ctconf.DefaultTemplateConfig() mapping := map[*ctconf.TemplateConfig]*structs.Template{ct: {}} @@ -380,22 +379,22 @@ func TestNewRunnerConfig_Retries(t *testing.T) { must.NoError(t, err) must.Eq(t, &ctconf.RetryConfig{ - Attempts: pointer.Of(0), - Backoff: pointer.Of(100 * time.Millisecond), - MaxBackoff: pointer.Of(300 * time.Millisecond), - Enabled: pointer.Of(true), + Attempts: new(0), + Backoff: new(100 * time.Millisecond), + MaxBackoff: new(300 * time.Millisecond), + Enabled: new(true), }, tconfig.Consul.Retry) must.Eq(t, &ctconf.RetryConfig{ - Attempts: pointer.Of(5), - Backoff: pointer.Of(200 * time.Millisecond), - MaxBackoff: pointer.Of(500 * time.Millisecond), - Enabled: pointer.Of(true), + Attempts: new(5), + Backoff: new(200 * time.Millisecond), + MaxBackoff: new(500 * time.Millisecond), + Enabled: new(true), }, tconfig.Vault.Retry) must.Eq(t, &ctconf.RetryConfig{ - Attempts: pointer.Of(12), - Backoff: pointer.Of(250 * time.Millisecond), - MaxBackoff: pointer.Of(time.Minute), - Enabled: pointer.Of(true), + Attempts: new(12), + Backoff: new(250 * time.Millisecond), + MaxBackoff: new(time.Minute), + Enabled: new(true), }, tconfig.Nomad.Retry) } @@ -1843,7 +1842,7 @@ func TestTaskTemplateManager_Config_ServerName(t *testing.T) { c.Node = mock.Node() c.VaultConfigs = map[string]*sconfig.VaultConfig{ structs.VaultDefaultCluster: { - Enabled: pointer.Of(true), + Enabled: new(true), Addr: "https://localhost/", TLSServerName: "notlocalhost", }, @@ -1875,7 +1874,7 @@ func TestTaskTemplateManager_Config_VaultNamespace(t *testing.T) { c.Node = mock.Node() c.VaultConfigs = map[string]*sconfig.VaultConfig{ structs.VaultDefaultCluster: { - Enabled: pointer.Of(true), + Enabled: new(true), Addr: "https://localhost/", TLSServerName: "notlocalhost", Namespace: testNS, @@ -1909,7 +1908,7 @@ func TestTaskTemplateManager_Config_VaultNamespace_TaskOverride(t *testing.T) { c.Node = mock.Node() c.VaultConfigs = map[string]*sconfig.VaultConfig{ structs.VaultDefaultCluster: { - Enabled: pointer.Of(true), + Enabled: new(true), Addr: "https://localhost/", TLSServerName: "notlocalhost", Namespace: testNS, @@ -2304,7 +2303,7 @@ func TestTaskTemplateManager_ClientTemplateConfig_Set(t *testing.T) { clientConfig.VaultConfigs = map[string]*sconfig.VaultConfig{ structs.VaultDefaultCluster: { - Enabled: pointer.Of(true), + Enabled: new(true), Namespace: testNS, }, } @@ -2315,18 +2314,18 @@ func TestTaskTemplateManager_ClientTemplateConfig_Set(t *testing.T) { // helper to reduce boilerplate waitConfig := &config.WaitConfig{ - Min: pointer.Of(5 * time.Second), - Max: pointer.Of(10 * time.Second), + Min: new(5 * time.Second), + Max: new(10 * time.Second), } // helper to reduce boilerplate retryConfig := &config.RetryConfig{ - Attempts: pointer.Of(5), - Backoff: pointer.Of(5 * time.Second), - MaxBackoff: pointer.Of(20 * time.Second), + Attempts: new(5), + Backoff: new(5 * time.Second), + MaxBackoff: new(20 * time.Second), } - clientConfig.TemplateConfig.MaxStale = pointer.Of(5 * time.Second) - clientConfig.TemplateConfig.BlockQueryWaitTime = pointer.Of(60 * time.Second) + clientConfig.TemplateConfig.MaxStale = new(5 * time.Second) + clientConfig.TemplateConfig.BlockQueryWaitTime = new(60 * time.Second) clientConfig.TemplateConfig.Wait = waitConfig.Copy() clientConfig.TemplateConfig.ConsulRetry = retryConfig.Copy() clientConfig.TemplateConfig.VaultRetry = retryConfig.Copy() @@ -2337,8 +2336,8 @@ func TestTaskTemplateManager_ClientTemplateConfig_Set(t *testing.T) { allocWithOverride.Job.TaskGroups[0].Tasks[0].Templates = []*structs.Template{ { Wait: &structs.WaitConfig{ - Min: pointer.Of(2 * time.Second), - Max: pointer.Of(12 * time.Second), + Min: new(2 * time.Second), + Max: new(12 * time.Second), }, }, } @@ -2353,8 +2352,8 @@ func TestTaskTemplateManager_ClientTemplateConfig_Set(t *testing.T) { { "basic-wait-config", &config.ClientTemplateConfig{ - MaxStale: pointer.Of(5 * time.Second), - BlockQueryWaitTime: pointer.Of(60 * time.Second), + MaxStale: new(5 * time.Second), + BlockQueryWaitTime: new(60 * time.Second), Wait: waitConfig.Copy(), ConsulRetry: retryConfig.Copy(), VaultRetry: retryConfig.Copy(), @@ -2369,8 +2368,8 @@ func TestTaskTemplateManager_ClientTemplateConfig_Set(t *testing.T) { }, &config.Config{ TemplateConfig: &config.ClientTemplateConfig{ - MaxStale: pointer.Of(5 * time.Second), - BlockQueryWaitTime: pointer.Of(60 * time.Second), + MaxStale: new(5 * time.Second), + BlockQueryWaitTime: new(60 * time.Second), Wait: waitConfig.Copy(), ConsulRetry: retryConfig.Copy(), VaultRetry: retryConfig.Copy(), @@ -2379,17 +2378,17 @@ func TestTaskTemplateManager_ClientTemplateConfig_Set(t *testing.T) { }, &templateconfig.TemplateConfig{ Wait: &templateconfig.WaitConfig{ - Enabled: pointer.Of(true), - Min: pointer.Of(5 * time.Second), - Max: pointer.Of(10 * time.Second), + Enabled: new(true), + Min: new(5 * time.Second), + Max: new(10 * time.Second), }, }, }, { "template-override", &config.ClientTemplateConfig{ - MaxStale: pointer.Of(5 * time.Second), - BlockQueryWaitTime: pointer.Of(60 * time.Second), + MaxStale: new(5 * time.Second), + BlockQueryWaitTime: new(60 * time.Second), Wait: waitConfig.Copy(), ConsulRetry: retryConfig.Copy(), VaultRetry: retryConfig.Copy(), @@ -2404,8 +2403,8 @@ func TestTaskTemplateManager_ClientTemplateConfig_Set(t *testing.T) { }, &config.Config{ TemplateConfig: &config.ClientTemplateConfig{ - MaxStale: pointer.Of(5 * time.Second), - BlockQueryWaitTime: pointer.Of(60 * time.Second), + MaxStale: new(5 * time.Second), + BlockQueryWaitTime: new(60 * time.Second), Wait: waitConfig.Copy(), ConsulRetry: retryConfig.Copy(), VaultRetry: retryConfig.Copy(), @@ -2414,21 +2413,21 @@ func TestTaskTemplateManager_ClientTemplateConfig_Set(t *testing.T) { }, &templateconfig.TemplateConfig{ Wait: &templateconfig.WaitConfig{ - Enabled: pointer.Of(true), - Min: pointer.Of(2 * time.Second), - Max: pointer.Of(12 * time.Second), + Enabled: new(true), + Min: new(2 * time.Second), + Max: new(12 * time.Second), }, }, }, { "bounds-override", &config.ClientTemplateConfig{ - MaxStale: pointer.Of(5 * time.Second), - BlockQueryWaitTime: pointer.Of(60 * time.Second), + MaxStale: new(5 * time.Second), + BlockQueryWaitTime: new(60 * time.Second), Wait: waitConfig.Copy(), WaitBounds: &config.WaitConfig{ - Min: pointer.Of(3 * time.Second), - Max: pointer.Of(11 * time.Second), + Min: new(3 * time.Second), + Max: new(11 * time.Second), }, ConsulRetry: retryConfig.Copy(), VaultRetry: retryConfig.Copy(), @@ -2443,20 +2442,20 @@ func TestTaskTemplateManager_ClientTemplateConfig_Set(t *testing.T) { Templates: []*structs.Template{ { Wait: &structs.WaitConfig{ - Min: pointer.Of(2 * time.Second), - Max: pointer.Of(12 * time.Second), + Min: new(2 * time.Second), + Max: new(12 * time.Second), }, }, }, }, &config.Config{ TemplateConfig: &config.ClientTemplateConfig{ - MaxStale: pointer.Of(5 * time.Second), - BlockQueryWaitTime: pointer.Of(60 * time.Second), + MaxStale: new(5 * time.Second), + BlockQueryWaitTime: new(60 * time.Second), Wait: waitConfig.Copy(), WaitBounds: &config.WaitConfig{ - Min: pointer.Of(3 * time.Second), - Max: pointer.Of(11 * time.Second), + Min: new(3 * time.Second), + Max: new(11 * time.Second), }, ConsulRetry: retryConfig.Copy(), VaultRetry: retryConfig.Copy(), @@ -2465,9 +2464,9 @@ func TestTaskTemplateManager_ClientTemplateConfig_Set(t *testing.T) { }, &templateconfig.TemplateConfig{ Wait: &templateconfig.WaitConfig{ - Enabled: pointer.Of(true), - Min: pointer.Of(3 * time.Second), - Max: pointer.Of(11 * time.Second), + Enabled: new(true), + Min: new(3 * time.Second), + Max: new(11 * time.Second), }, }, }, @@ -2537,8 +2536,8 @@ func TestTaskTemplateManager_Template_Wait_Set(t *testing.T) { Templates: []*structs.Template{ { Wait: &structs.WaitConfig{ - Min: pointer.Of(5 * time.Second), - Max: pointer.Of(10 * time.Second), + Min: new(5 * time.Second), + Max: new(10 * time.Second), }, }, }, @@ -2571,13 +2570,13 @@ func Test_newRunnerConfig_consul(t *testing.T) { ClientConfig: config.DefaultConfig(), }, expectedOutputConfig: &ctconf.ConsulConfig{ - Address: pointer.Of("localhost:8500"), - Namespace: pointer.Of(""), + Address: new("localhost:8500"), + Namespace: new(""), Auth: ctconf.DefaultAuthConfig(), Retry: ctconf.DefaultRetryConfig(), SSL: ctconf.DefaultSSLConfig(), - Token: pointer.Of("token"), - TokenFile: pointer.Of(""), + Token: new("token"), + TokenFile: new(""), Transport: ctconf.DefaultTransportConfig(), }, }, @@ -2588,13 +2587,13 @@ func Test_newRunnerConfig_consul(t *testing.T) { ClientConfig: config.DefaultConfig(), }, expectedOutputConfig: &ctconf.ConsulConfig{ - Address: pointer.Of("localhost:8500"), - Namespace: pointer.Of(""), + Address: new("localhost:8500"), + Namespace: new(""), Auth: ctconf.DefaultAuthConfig(), Retry: ctconf.DefaultRetryConfig(), SSL: ctconf.DefaultSSLConfig(), - Token: pointer.Of(""), - TokenFile: pointer.Of(""), + Token: new(""), + TokenFile: new(""), Transport: ctconf.DefaultTransportConfig(), }, }, diff --git a/client/allocrunner/taskrunner/template_hook_test.go b/client/allocrunner/taskrunner/template_hook_test.go index d7d85dc3ed5..7dc2720e66a 100644 --- a/client/allocrunner/taskrunner/template_hook_test.go +++ b/client/allocrunner/taskrunner/template_hook_test.go @@ -23,7 +23,6 @@ import ( "github.com/hashicorp/nomad/client/config" cstructs "github.com/hashicorp/nomad/client/structs" "github.com/hashicorp/nomad/client/taskenv" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/testlog" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" @@ -177,7 +176,7 @@ func TestTemplateHook_Prestart_Vault(t *testing.T) { clientConfig.VaultConfigs = map[string]*structsc.VaultConfig{ structs.VaultDefaultCluster: { Name: structs.VaultDefaultCluster, - Enabled: pointer.Of(true), + Enabled: new(true), Addr: defaultVaultServer.URL, }, } diff --git a/client/client.go b/client/client.go index 0aba249f472..bee62ed591c 100644 --- a/client/client.go +++ b/client/client.go @@ -57,7 +57,6 @@ import ( "github.com/hashicorp/nomad/helper/escapingfs" "github.com/hashicorp/nomad/helper/goruntime" "github.com/hashicorp/nomad/helper/group" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/pool" "github.com/hashicorp/nomad/helper/tlsutil" "github.com/hashicorp/nomad/helper/users/dynamic" @@ -2836,7 +2835,7 @@ func makeFailedAlloc(add *structs.Allocation, err error) *structs.Allocation { stripped.DeploymentStatus = add.DeploymentStatus.Copy() } else { stripped.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(false), + Healthy: new(false), Timestamp: failTime, } } diff --git a/client/client_test.go b/client/client_test.go index cf2ccf52a2d..b59982c4aeb 100644 --- a/client/client_test.go +++ b/client/client_test.go @@ -32,7 +32,6 @@ import ( "github.com/hashicorp/nomad/command/agent/consul" "github.com/hashicorp/nomad/helper/pluginutils/catalog" "github.com/hashicorp/nomad/helper/pluginutils/singleton" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/testlog" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad" @@ -1560,7 +1559,7 @@ func TestClient_handleNodeUpdateResponse(t *testing.T) { {RPCAdvertiseAddr: "10.0.0.2:4647", Datacenter: "dc1"}, {RPCAdvertiseAddr: "10.0.0.3:4647", Datacenter: "dc1"}, }, - SignedIdentity: pointer.Of("node-identity"), + SignedIdentity: new("node-identity"), } // Perform the update and test the outcome. diff --git a/client/config/artifact_test.go b/client/config/artifact_test.go index 0e6bc9153ce..15d06816cfc 100644 --- a/client/config/artifact_test.go +++ b/client/config/artifact_test.go @@ -8,7 +8,6 @@ import ( "time" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/structs/config" "github.com/shoenig/test/must" ) @@ -39,72 +38,72 @@ func TestArtifactConfigFromAgent(t *testing.T) { { name: "invalid http read timeout", config: &config.ArtifactConfig{ - HTTPReadTimeout: pointer.Of("invalid"), - HTTPMaxSize: pointer.Of("100GB"), - GCSTimeout: pointer.Of("30m"), - GitTimeout: pointer.Of("30m"), - HgTimeout: pointer.Of("30m"), - S3Timeout: pointer.Of("30m"), + HTTPReadTimeout: new("invalid"), + HTTPMaxSize: new("100GB"), + GCSTimeout: new("30m"), + GitTimeout: new("30m"), + HgTimeout: new("30m"), + S3Timeout: new("30m"), }, expErr: "error parsing HTTPReadTimeout", }, { name: "invalid http max size", config: &config.ArtifactConfig{ - HTTPReadTimeout: pointer.Of("30m"), - HTTPMaxSize: pointer.Of("invalid"), - GCSTimeout: pointer.Of("30m"), - GitTimeout: pointer.Of("30m"), - HgTimeout: pointer.Of("30m"), - S3Timeout: pointer.Of("30m"), + HTTPReadTimeout: new("30m"), + HTTPMaxSize: new("invalid"), + GCSTimeout: new("30m"), + GitTimeout: new("30m"), + HgTimeout: new("30m"), + S3Timeout: new("30m"), }, expErr: "error parsing HTTPMaxSize", }, { name: "invalid gcs timeout", config: &config.ArtifactConfig{ - HTTPReadTimeout: pointer.Of("30m"), - HTTPMaxSize: pointer.Of("100GB"), - GCSTimeout: pointer.Of("invalid"), - GitTimeout: pointer.Of("30m"), - HgTimeout: pointer.Of("30m"), - S3Timeout: pointer.Of("30m"), + HTTPReadTimeout: new("30m"), + HTTPMaxSize: new("100GB"), + GCSTimeout: new("invalid"), + GitTimeout: new("30m"), + HgTimeout: new("30m"), + S3Timeout: new("30m"), }, expErr: "error parsing GCSTimeout", }, { name: "invalid git timeout", config: &config.ArtifactConfig{ - HTTPReadTimeout: pointer.Of("30m"), - HTTPMaxSize: pointer.Of("100GB"), - GCSTimeout: pointer.Of("30m"), - GitTimeout: pointer.Of("invalid"), - HgTimeout: pointer.Of("30m"), - S3Timeout: pointer.Of("30m"), + HTTPReadTimeout: new("30m"), + HTTPMaxSize: new("100GB"), + GCSTimeout: new("30m"), + GitTimeout: new("invalid"), + HgTimeout: new("30m"), + S3Timeout: new("30m"), }, expErr: "error parsing GitTimeout", }, { name: "invalid hg timeout", config: &config.ArtifactConfig{ - HTTPReadTimeout: pointer.Of("30m"), - HTTPMaxSize: pointer.Of("100GB"), - GCSTimeout: pointer.Of("30m"), - GitTimeout: pointer.Of("30m"), - HgTimeout: pointer.Of("invalid"), - S3Timeout: pointer.Of("30m"), + HTTPReadTimeout: new("30m"), + HTTPMaxSize: new("100GB"), + GCSTimeout: new("30m"), + GitTimeout: new("30m"), + HgTimeout: new("invalid"), + S3Timeout: new("30m"), }, expErr: "error parsing HgTimeout", }, { name: "invalid s3 timeout", config: &config.ArtifactConfig{ - HTTPReadTimeout: pointer.Of("30m"), - HTTPMaxSize: pointer.Of("100GB"), - GCSTimeout: pointer.Of("30m"), - GitTimeout: pointer.Of("30m"), - HgTimeout: pointer.Of("30m"), - S3Timeout: pointer.Of("invalid"), + HTTPReadTimeout: new("30m"), + HTTPMaxSize: new("100GB"), + GCSTimeout: new("30m"), + GitTimeout: new("30m"), + HgTimeout: new("30m"), + S3Timeout: new("invalid"), }, expErr: "error parsing S3Timeout", }, diff --git a/client/config/config.go b/client/config/config.go index 370a0426be2..e17acb36ff0 100644 --- a/client/config/config.go +++ b/client/config/config.go @@ -491,26 +491,26 @@ func DefaultTemplateConfig() *ClientTemplateConfig { return &ClientTemplateConfig{ FunctionDenylist: DefaultTemplateFunctionDenylist, DisableSandbox: false, - BlockQueryWaitTime: pointer.Of(5 * time.Minute), // match Consul default - MaxStale: pointer.Of(DefaultTemplateMaxStale), // match Consul default + BlockQueryWaitTime: new(5 * time.Minute), // match Consul default + MaxStale: new(DefaultTemplateMaxStale), // match Consul default Wait: &WaitConfig{ - Min: pointer.Of(5 * time.Second), - Max: pointer.Of(4 * time.Minute), + Min: new(5 * time.Second), + Max: new(4 * time.Minute), }, ConsulRetry: &RetryConfig{ - Attempts: pointer.Of(12), - Backoff: pointer.Of(time.Millisecond * 250), - MaxBackoff: pointer.Of(time.Minute), + Attempts: new(12), + Backoff: new(time.Millisecond * 250), + MaxBackoff: new(time.Minute), }, VaultRetry: &RetryConfig{ - Attempts: pointer.Of(12), - Backoff: pointer.Of(time.Millisecond * 250), - MaxBackoff: pointer.Of(time.Minute), + Attempts: new(12), + Backoff: new(time.Millisecond * 250), + MaxBackoff: new(time.Minute), }, NomadRetry: &RetryConfig{ - Attempts: pointer.Of(12), - Backoff: pointer.Of(time.Millisecond * 250), - MaxBackoff: pointer.Of(time.Minute), + Attempts: new(12), + Backoff: new(time.Millisecond * 250), + MaxBackoff: new(time.Minute), }, } } @@ -729,7 +729,7 @@ func (wc *WaitConfig) ToConsulTemplate() (*config.WaitConfig, error) { } enabled := wc.Min == nil || *wc.Min != 0 || wc.Max == nil || *wc.Max != 0 - result := &config.WaitConfig{Enabled: pointer.Of(enabled)} + result := &config.WaitConfig{Enabled: new(enabled)} if wc.Min != nil { result.Min = wc.Min @@ -872,7 +872,7 @@ func (rc *RetryConfig) ToConsulTemplate() (*config.RetryConfig, error) { return nil, err } - result := &config.RetryConfig{Enabled: pointer.Of(true)} + result := &config.RetryConfig{Enabled: new(true)} if rc.Attempts != nil { result.Attempts = rc.Attempts diff --git a/client/config/config_test.go b/client/config/config_test.go index 3261a4cc62f..6b881f7cb21 100644 --- a/client/config/config_test.go +++ b/client/config/config_test.go @@ -9,7 +9,6 @@ import ( "github.com/hashicorp/consul-template/config" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/shoenig/test/must" ) @@ -44,8 +43,8 @@ func TestConfigReadDefault(t *testing.T) { func mockWaitConfig() *WaitConfig { return &WaitConfig{ - Min: pointer.Of(5 * time.Second), - Max: pointer.Of(10 * time.Second), + Min: new(5 * time.Second), + Max: new(10 * time.Second), } } @@ -61,26 +60,26 @@ func TestWaitConfig_Copy(t *testing.T) { "fully-populated", mockWaitConfig(), &WaitConfig{ - Min: pointer.Of(5 * time.Second), - Max: pointer.Of(10 * time.Second), + Min: new(5 * time.Second), + Max: new(10 * time.Second), }, }, { "min-only", &WaitConfig{ - Min: pointer.Of(5 * time.Second), + Min: new(5 * time.Second), }, &WaitConfig{ - Min: pointer.Of(5 * time.Second), + Min: new(5 * time.Second), }, }, { "max-only", &WaitConfig{ - Max: pointer.Of(5 * time.Second), + Max: new(5 * time.Second), }, &WaitConfig{ - Max: pointer.Of(5 * time.Second), + Max: new(5 * time.Second), }, }, } @@ -113,7 +112,7 @@ func TestWaitConfig_IsEmpty(t *testing.T) { { "is-not-empty", &WaitConfig{ - Min: pointer.Of(10 * time.Second), + Min: new(10 * time.Second), }, false, }, @@ -139,8 +138,8 @@ func TestWaitConfig_IsEqual(t *testing.T) { "are-equal", mockWaitConfig(), &WaitConfig{ - Min: pointer.Of(5 * time.Second), - Max: pointer.Of(10 * time.Second), + Min: new(5 * time.Second), + Max: new(10 * time.Second), }, true, }, @@ -148,8 +147,8 @@ func TestWaitConfig_IsEqual(t *testing.T) { "min-different", mockWaitConfig(), &WaitConfig{ - Min: pointer.Of(4 * time.Second), - Max: pointer.Of(10 * time.Second), + Min: new(4 * time.Second), + Max: new(10 * time.Second), }, false, }, @@ -157,8 +156,8 @@ func TestWaitConfig_IsEqual(t *testing.T) { "max-different", mockWaitConfig(), &WaitConfig{ - Min: pointer.Of(5 * time.Second), - Max: pointer.Of(9 * time.Second), + Min: new(5 * time.Second), + Max: new(9 * time.Second), }, false, }, @@ -182,8 +181,8 @@ func TestWaitConfig_IsValid(t *testing.T) { { "is-valid", &WaitConfig{ - Min: pointer.Of(5 * time.Second), - Max: pointer.Of(10 * time.Second), + Min: new(5 * time.Second), + Max: new(10 * time.Second), }, "", }, @@ -200,15 +199,15 @@ func TestWaitConfig_IsValid(t *testing.T) { { "min-greater-than-max", &WaitConfig{ - Min: pointer.Of(10 * time.Second), - Max: pointer.Of(5 * time.Second), + Min: new(10 * time.Second), + Max: new(5 * time.Second), }, "greater than", }, { "max-not-set", &WaitConfig{ - Min: pointer.Of(10 * time.Second), + Min: new(10 * time.Second), }, "", }, @@ -239,36 +238,36 @@ func TestWaitConfig_Merge(t *testing.T) { "all-fields", mockWaitConfig(), &WaitConfig{ - Min: pointer.Of(4 * time.Second), - Max: pointer.Of(9 * time.Second), + Min: new(4 * time.Second), + Max: new(9 * time.Second), }, &WaitConfig{ - Min: pointer.Of(4 * time.Second), - Max: pointer.Of(9 * time.Second), + Min: new(4 * time.Second), + Max: new(9 * time.Second), }, }, { "min-only", mockWaitConfig(), &WaitConfig{ - Min: pointer.Of(4 * time.Second), - Max: pointer.Of(10 * time.Second), + Min: new(4 * time.Second), + Max: new(10 * time.Second), }, &WaitConfig{ - Min: pointer.Of(4 * time.Second), - Max: pointer.Of(10 * time.Second), + Min: new(4 * time.Second), + Max: new(10 * time.Second), }, }, { "max-only", mockWaitConfig(), &WaitConfig{ - Min: pointer.Of(5 * time.Second), - Max: pointer.Of(9 * time.Second), + Min: new(5 * time.Second), + Max: new(9 * time.Second), }, &WaitConfig{ - Min: pointer.Of(5 * time.Second), - Max: pointer.Of(9 * time.Second), + Min: new(5 * time.Second), + Max: new(9 * time.Second), }, }, } @@ -285,14 +284,14 @@ func TestWaitConfig_ToConsulTemplate(t *testing.T) { ci.Parallel(t) expected := config.WaitConfig{ - Enabled: pointer.Of(true), - Min: pointer.Of(5 * time.Second), - Max: pointer.Of(10 * time.Second), + Enabled: new(true), + Min: new(5 * time.Second), + Max: new(10 * time.Second), } clientWaitConfig := &WaitConfig{ - Min: pointer.Of(5 * time.Second), - Max: pointer.Of(10 * time.Second), + Min: new(5 * time.Second), + Max: new(10 * time.Second), } actual, err := clientWaitConfig.ToConsulTemplate() @@ -302,14 +301,14 @@ func TestWaitConfig_ToConsulTemplate(t *testing.T) { must.Eq(t, *expected.Max, *actual.Max) expected = config.WaitConfig{ - Enabled: pointer.Of(false), - Min: pointer.Of(0 * time.Second), - Max: pointer.Of(0 * time.Second), + Enabled: new(false), + Min: new(0 * time.Second), + Max: new(0 * time.Second), } clientWaitConfig = &WaitConfig{ - Min: pointer.Of(0 * time.Second), - Max: pointer.Of(0 * time.Second), + Min: new(0 * time.Second), + Max: new(0 * time.Second), } actual, err = clientWaitConfig.ToConsulTemplate() @@ -320,10 +319,10 @@ func TestWaitConfig_ToConsulTemplate(t *testing.T) { func mockRetryConfig() *RetryConfig { return &RetryConfig{ - Attempts: pointer.Of(5), - Backoff: pointer.Of(5 * time.Second), + Attempts: new(5), + Backoff: new(5 * time.Second), BackoffHCL: "5s", - MaxBackoff: pointer.Of(10 * time.Second), + MaxBackoff: new(10 * time.Second), MaxBackoffHCL: "10s", } } @@ -339,29 +338,29 @@ func TestRetryConfig_Copy(t *testing.T) { "fully-populated", mockRetryConfig(), &RetryConfig{ - Attempts: pointer.Of(5), - Backoff: pointer.Of(5 * time.Second), + Attempts: new(5), + Backoff: new(5 * time.Second), BackoffHCL: "5s", - MaxBackoff: pointer.Of(10 * time.Second), + MaxBackoff: new(10 * time.Second), MaxBackoffHCL: "10s", }, }, { "attempts-only", &RetryConfig{ - Attempts: pointer.Of(5), + Attempts: new(5), }, &RetryConfig{ - Attempts: pointer.Of(5), + Attempts: new(5), }, }, { "backoff-only", &RetryConfig{ - Backoff: pointer.Of(5 * time.Second), + Backoff: new(5 * time.Second), }, &RetryConfig{ - Backoff: pointer.Of(5 * time.Second), + Backoff: new(5 * time.Second), }, }, { @@ -376,10 +375,10 @@ func TestRetryConfig_Copy(t *testing.T) { { "max-backoff-only", &RetryConfig{ - MaxBackoff: pointer.Of(10 * time.Second), + MaxBackoff: new(10 * time.Second), }, &RetryConfig{ - MaxBackoff: pointer.Of(10 * time.Second), + MaxBackoff: new(10 * time.Second), }, }, { @@ -421,7 +420,7 @@ func TestRetryConfig_IsEmpty(t *testing.T) { { "is-not-empty", &RetryConfig{ - Attempts: pointer.Of(12), + Attempts: new(12), }, false, }, @@ -447,10 +446,10 @@ func TestRetryConfig_IsEqual(t *testing.T) { "are-equal", mockRetryConfig(), &RetryConfig{ - Attempts: pointer.Of(5), - Backoff: pointer.Of(5 * time.Second), + Attempts: new(5), + Backoff: new(5 * time.Second), BackoffHCL: "5s", - MaxBackoff: pointer.Of(10 * time.Second), + MaxBackoff: new(10 * time.Second), MaxBackoffHCL: "10s", }, true, @@ -459,10 +458,10 @@ func TestRetryConfig_IsEqual(t *testing.T) { "attempts-different", mockRetryConfig(), &RetryConfig{ - Attempts: pointer.Of(4), - Backoff: pointer.Of(5 * time.Second), + Attempts: new(4), + Backoff: new(5 * time.Second), BackoffHCL: "5s", - MaxBackoff: pointer.Of(10 * time.Second), + MaxBackoff: new(10 * time.Second), MaxBackoffHCL: "10s", }, false, @@ -471,10 +470,10 @@ func TestRetryConfig_IsEqual(t *testing.T) { "backoff-different", mockRetryConfig(), &RetryConfig{ - Attempts: pointer.Of(5), - Backoff: pointer.Of(4 * time.Second), + Attempts: new(5), + Backoff: new(4 * time.Second), BackoffHCL: "5s", - MaxBackoff: pointer.Of(10 * time.Second), + MaxBackoff: new(10 * time.Second), MaxBackoffHCL: "10s", }, false, @@ -483,10 +482,10 @@ func TestRetryConfig_IsEqual(t *testing.T) { "backoff-hcl-different", mockRetryConfig(), &RetryConfig{ - Attempts: pointer.Of(5), - Backoff: pointer.Of(5 * time.Second), + Attempts: new(5), + Backoff: new(5 * time.Second), BackoffHCL: "4s", - MaxBackoff: pointer.Of(10 * time.Second), + MaxBackoff: new(10 * time.Second), MaxBackoffHCL: "10s", }, false, @@ -495,10 +494,10 @@ func TestRetryConfig_IsEqual(t *testing.T) { "max-backoff-different", mockRetryConfig(), &RetryConfig{ - Attempts: pointer.Of(5), - Backoff: pointer.Of(5 * time.Second), + Attempts: new(5), + Backoff: new(5 * time.Second), BackoffHCL: "5s", - MaxBackoff: pointer.Of(9 * time.Second), + MaxBackoff: new(9 * time.Second), MaxBackoffHCL: "10s", }, false, @@ -507,10 +506,10 @@ func TestRetryConfig_IsEqual(t *testing.T) { "max-backoff-hcl-different", mockRetryConfig(), &RetryConfig{ - Attempts: pointer.Of(5), - Backoff: pointer.Of(5 * time.Second), + Attempts: new(5), + Backoff: new(5 * time.Second), BackoffHCL: "5s", - MaxBackoff: pointer.Of(10 * time.Second), + MaxBackoff: new(10 * time.Second), MaxBackoffHCL: "9s", }, false, @@ -535,8 +534,8 @@ func TestRetryConfig_IsValid(t *testing.T) { { "is-valid", &RetryConfig{ - Backoff: pointer.Of(5 * time.Second), - MaxBackoff: pointer.Of(10 * time.Second), + Backoff: new(5 * time.Second), + MaxBackoff: new(10 * time.Second), }, "", }, @@ -553,30 +552,30 @@ func TestRetryConfig_IsValid(t *testing.T) { { "backoff-greater-than-max-backoff", &RetryConfig{ - Backoff: pointer.Of(10 * time.Second), - MaxBackoff: pointer.Of(5 * time.Second), + Backoff: new(10 * time.Second), + MaxBackoff: new(5 * time.Second), }, "greater than max_backoff", }, { "backoff-not-set", &RetryConfig{ - MaxBackoff: pointer.Of(10 * time.Second), + MaxBackoff: new(10 * time.Second), }, "", }, { "max-backoff-not-set", &RetryConfig{ - Backoff: pointer.Of(2 * time.Minute), + Backoff: new(2 * time.Minute), }, "greater than default", }, { "max-backoff-unbounded", &RetryConfig{ - Backoff: pointer.Of(10 * time.Second), - MaxBackoff: pointer.Of(0 * time.Second), + Backoff: new(10 * time.Second), + MaxBackoff: new(0 * time.Second), }, "", }, @@ -607,17 +606,17 @@ func TestRetryConfig_Merge(t *testing.T) { "all-fields", mockRetryConfig(), &RetryConfig{ - Attempts: pointer.Of(4), - Backoff: pointer.Of(4 * time.Second), + Attempts: new(4), + Backoff: new(4 * time.Second), BackoffHCL: "4s", - MaxBackoff: pointer.Of(9 * time.Second), + MaxBackoff: new(9 * time.Second), MaxBackoffHCL: "9s", }, &RetryConfig{ - Attempts: pointer.Of(4), - Backoff: pointer.Of(4 * time.Second), + Attempts: new(4), + Backoff: new(4 * time.Second), BackoffHCL: "4s", - MaxBackoff: pointer.Of(9 * time.Second), + MaxBackoff: new(9 * time.Second), MaxBackoffHCL: "9s", }, }, @@ -625,17 +624,17 @@ func TestRetryConfig_Merge(t *testing.T) { "attempts-only", mockRetryConfig(), &RetryConfig{ - Attempts: pointer.Of(4), - Backoff: pointer.Of(5 * time.Second), + Attempts: new(4), + Backoff: new(5 * time.Second), BackoffHCL: "5s", - MaxBackoff: pointer.Of(10 * time.Second), + MaxBackoff: new(10 * time.Second), MaxBackoffHCL: "10s", }, &RetryConfig{ - Attempts: pointer.Of(4), - Backoff: pointer.Of(5 * time.Second), + Attempts: new(4), + Backoff: new(5 * time.Second), BackoffHCL: "5s", - MaxBackoff: pointer.Of(10 * time.Second), + MaxBackoff: new(10 * time.Second), MaxBackoffHCL: "10s", }, }, @@ -643,17 +642,17 @@ func TestRetryConfig_Merge(t *testing.T) { "multi-field", mockRetryConfig(), &RetryConfig{ - Attempts: pointer.Of(5), - Backoff: pointer.Of(4 * time.Second), + Attempts: new(5), + Backoff: new(4 * time.Second), BackoffHCL: "4s", - MaxBackoff: pointer.Of(9 * time.Second), + MaxBackoff: new(9 * time.Second), MaxBackoffHCL: "9s", }, &RetryConfig{ - Attempts: pointer.Of(5), - Backoff: pointer.Of(4 * time.Second), + Attempts: new(5), + Backoff: new(4 * time.Second), BackoffHCL: "4s", - MaxBackoff: pointer.Of(9 * time.Second), + MaxBackoff: new(9 * time.Second), MaxBackoffHCL: "9s", }, }, @@ -671,10 +670,10 @@ func TestRetryConfig_ToConsulTemplate(t *testing.T) { ci.Parallel(t) expected := config.RetryConfig{ - Enabled: pointer.Of(true), - Attempts: pointer.Of(5), - Backoff: pointer.Of(5 * time.Second), - MaxBackoff: pointer.Of(10 * time.Second), + Enabled: new(true), + Attempts: new(5), + Backoff: new(5 * time.Second), + MaxBackoff: new(10 * time.Second), } actual := mockRetryConfig() diff --git a/client/config/testing.go b/client/config/testing.go index db86db58db8..6d24935bc85 100644 --- a/client/config/testing.go +++ b/client/config/testing.go @@ -12,7 +12,6 @@ import ( "time" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/testlog" "github.com/hashicorp/nomad/nomad/mock" ) @@ -68,7 +67,7 @@ func TestClientConfig(t testing.TB) (*Config, func()) { // Helps make sure we are respecting configured parent conf.CgroupParent = "testing.slice" - conf.GetDefaultVault().Enabled = pointer.Of(false) + conf.GetDefaultVault().Enabled = new(false) conf.DevMode = true // Loosen GC threshold diff --git a/client/devicemanager/manager_test.go b/client/devicemanager/manager_test.go index b5917035eca..315f4e8485d 100644 --- a/client/devicemanager/manager_test.go +++ b/client/devicemanager/manager_test.go @@ -15,7 +15,6 @@ import ( "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/client/state" "github.com/hashicorp/nomad/helper/pluginutils/loader" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/testlog" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/structs" @@ -45,7 +44,7 @@ var ( }, Attributes: map[string]*psstructs.Attribute{ "memory": { - Int: pointer.Of(int64(4)), + Int: new(int64(4)), Unit: "GB", }, }, @@ -64,7 +63,7 @@ var ( }, Attributes: map[string]*psstructs.Attribute{ "memory": { - Int: pointer.Of(int64(2)), + Int: new(int64(2)), Unit: "GB", }, }, @@ -77,14 +76,14 @@ var ( InstanceStats: map[string]*device.DeviceStats{ nvidiaDevice0ID: { Summary: &psstructs.StatValue{ - IntNumeratorVal: pointer.Of(int64(212)), + IntNumeratorVal: new(int64(212)), Unit: "F", Desc: "Temperature", }, }, nvidiaDevice1ID: { Summary: &psstructs.StatValue{ - IntNumeratorVal: pointer.Of(int64(218)), + IntNumeratorVal: new(int64(218)), Unit: "F", Desc: "Temperature", }, @@ -99,7 +98,7 @@ var ( InstanceStats: map[string]*device.DeviceStats{ intelDeviceID: { Summary: &psstructs.StatValue{ - IntNumeratorVal: pointer.Of(int64(220)), + IntNumeratorVal: new(int64(220)), Unit: "F", Desc: "Temperature", }, diff --git a/client/fingerprint/fingerprint_retry_test.go b/client/fingerprint/fingerprint_retry_test.go index fad3c29355d..b0c4b03006d 100644 --- a/client/fingerprint/fingerprint_retry_test.go +++ b/client/fingerprint/fingerprint_retry_test.go @@ -11,7 +11,6 @@ import ( "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/client/config" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/testlog" "github.com/hashicorp/nomad/nomad/structs" "github.com/shoenig/test/must" @@ -79,7 +78,7 @@ func TestRetryWrapper_Fingerprint(t *testing.T) { errorSequence: []error{probeError}, fpConfig: &config.Fingerprint{ Name: "test", - ExitOnFailure: pointer.Of(true), + ExitOnFailure: new(true), }, expectedErr: probeError, expectedCallCount: 1, @@ -89,7 +88,7 @@ func TestRetryWrapper_Fingerprint(t *testing.T) { errorSequence: []error{probeError}, fpConfig: &config.Fingerprint{ Name: "test", - ExitOnFailure: pointer.Of(false), + ExitOnFailure: new(false), }, expectedErr: nil, expectedCallCount: 1, @@ -291,7 +290,7 @@ func Test_shouldSkipEnvFingerprinter(t *testing.T) { { name: "exit on failure false and initial error", inputCfg: &config.Fingerprint{ - ExitOnFailure: pointer.Of(false), + ExitOnFailure: new(false), }, inputError: wrapProbeError(errors.New("initial error")), expectedOutput: true, @@ -299,7 +298,7 @@ func Test_shouldSkipEnvFingerprinter(t *testing.T) { { name: "exit on failure true and initial error", inputCfg: &config.Fingerprint{ - ExitOnFailure: pointer.Of(true), + ExitOnFailure: new(true), }, inputError: wrapProbeError(errors.New("initial error")), expectedOutput: false, @@ -307,7 +306,7 @@ func Test_shouldSkipEnvFingerprinter(t *testing.T) { { name: "exit on failure false and non-initial error", inputCfg: &config.Fingerprint{ - ExitOnFailure: pointer.Of(false), + ExitOnFailure: new(false), }, inputError: errors.New("initial error"), expectedOutput: true, @@ -315,7 +314,7 @@ func Test_shouldSkipEnvFingerprinter(t *testing.T) { { name: "exit on failure true and non-initial error", inputCfg: &config.Fingerprint{ - ExitOnFailure: pointer.Of(true), + ExitOnFailure: new(true), }, inputError: errors.New("initial error"), expectedOutput: false, diff --git a/client/fs_endpoint.go b/client/fs_endpoint.go index 534a07734fb..2f320965512 100644 --- a/client/fs_endpoint.go +++ b/client/fs_endpoint.go @@ -26,7 +26,6 @@ import ( "github.com/hashicorp/nomad/client/allocdir" sframer "github.com/hashicorp/nomad/client/lib/streamframer" cstructs "github.com/hashicorp/nomad/client/structs" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/structs" ) @@ -169,24 +168,24 @@ func (f *FileSystem) stream(conn io.ReadWriteCloser) { encoder := codec.NewEncoder(conn, structs.MsgpackHandle) if err := decoder.Decode(&req); err != nil { - handleStreamResultError(err, pointer.Of(int64(http.StatusInternalServerError)), encoder) + handleStreamResultError(err, new(int64(http.StatusInternalServerError)), encoder) return } if req.AllocID == "" { - handleStreamResultError(allocIDNotPresentErr, pointer.Of(int64(http.StatusBadRequest)), encoder) + handleStreamResultError(allocIDNotPresentErr, new(int64(http.StatusBadRequest)), encoder) return } ar, err := f.c.getAllocRunner(req.AllocID) if err != nil { - handleStreamResultError(structs.NewErrUnknownAllocation(req.AllocID), pointer.Of(int64(http.StatusNotFound)), encoder) + handleStreamResultError(structs.NewErrUnknownAllocation(req.AllocID), new(int64(http.StatusNotFound)), encoder) return } if ar.IsDestroyed() { handleStreamResultError( fmt.Errorf("state for allocation %s not found on client", req.AllocID), - pointer.Of(int64(http.StatusNotFound)), + new(int64(http.StatusNotFound)), encoder, ) return @@ -195,16 +194,16 @@ func (f *FileSystem) stream(conn io.ReadWriteCloser) { // Check read permissions if aclObj, err := f.c.ResolveToken(req.QueryOptions.AuthToken); err != nil { - handleStreamResultError(err, pointer.Of(int64(http.StatusForbidden)), encoder) + handleStreamResultError(err, new(int64(http.StatusForbidden)), encoder) return } else if !aclObj.AllowNsOp(alloc.Namespace, acl.NamespaceCapabilityReadFS) { - handleStreamResultError(structs.ErrPermissionDenied, pointer.Of(int64(http.StatusForbidden)), encoder) + handleStreamResultError(structs.ErrPermissionDenied, new(int64(http.StatusForbidden)), encoder) return } // Validate the arguments if req.Path == "" { - handleStreamResultError(pathNotPresentErr, pointer.Of(int64(http.StatusBadRequest)), encoder) + handleStreamResultError(pathNotPresentErr, new(int64(http.StatusBadRequest)), encoder) return } switch req.Origin { @@ -212,15 +211,15 @@ func (f *FileSystem) stream(conn io.ReadWriteCloser) { case "": req.Origin = "start" default: - handleStreamResultError(invalidOrigin, pointer.Of(int64(http.StatusBadRequest)), encoder) + handleStreamResultError(invalidOrigin, new(int64(http.StatusBadRequest)), encoder) return } fs, err := f.c.GetAllocFS(req.AllocID) if err != nil { - code := pointer.Of(int64(http.StatusInternalServerError)) + code := new(int64(http.StatusInternalServerError)) if structs.IsErrUnknownAllocation(err) { - code = pointer.Of(int64(http.StatusNotFound)) + code = new(int64(http.StatusNotFound)) } handleStreamResultError(err, code, encoder) @@ -230,13 +229,13 @@ func (f *FileSystem) stream(conn io.ReadWriteCloser) { // Calculate the offset fileInfo, err := fs.Stat(req.Path) if err != nil { - handleStreamResultError(err, pointer.Of(int64(http.StatusBadRequest)), encoder) + handleStreamResultError(err, new(int64(http.StatusBadRequest)), encoder) return } if fileInfo.IsDir { handleStreamResultError( fmt.Errorf("file %q is a directory", req.Path), - pointer.Of(int64(http.StatusBadRequest)), encoder) + new(int64(http.StatusBadRequest)), encoder) return } @@ -338,7 +337,7 @@ OUTER: } if streamErr != nil { - handleStreamResultError(streamErr, pointer.Of(int64(http.StatusInternalServerError)), encoder) + handleStreamResultError(streamErr, new(int64(http.StatusInternalServerError)), encoder) return } } @@ -354,24 +353,24 @@ func (f *FileSystem) logs(conn io.ReadWriteCloser) { encoder := codec.NewEncoder(conn, structs.MsgpackHandle) if err := decoder.Decode(&req); err != nil { - handleStreamResultError(err, pointer.Of(int64(http.StatusInternalServerError)), encoder) + handleStreamResultError(err, new(int64(http.StatusInternalServerError)), encoder) return } if req.AllocID == "" { - handleStreamResultError(allocIDNotPresentErr, pointer.Of(int64(http.StatusBadRequest)), encoder) + handleStreamResultError(allocIDNotPresentErr, new(int64(http.StatusBadRequest)), encoder) return } ar, err := f.c.getAllocRunner(req.AllocID) if err != nil { - handleStreamResultError(structs.NewErrUnknownAllocation(req.AllocID), pointer.Of(int64(http.StatusNotFound)), encoder) + handleStreamResultError(structs.NewErrUnknownAllocation(req.AllocID), new(int64(http.StatusNotFound)), encoder) return } if ar.IsDestroyed() { handleStreamResultError( fmt.Errorf("state for allocation %s not found on client", req.AllocID), - pointer.Of(int64(http.StatusNotFound)), + new(int64(http.StatusNotFound)), encoder, ) return @@ -388,19 +387,19 @@ func (f *FileSystem) logs(conn io.ReadWriteCloser) { readfs := aclObj.AllowNsOp(alloc.Namespace, acl.NamespaceCapabilityReadFS) logs := aclObj.AllowNsOp(alloc.Namespace, acl.NamespaceCapabilityReadLogs) if !readfs && !logs { - handleStreamResultError(structs.ErrPermissionDenied, pointer.Of(int64(http.StatusForbidden)), encoder) + handleStreamResultError(structs.ErrPermissionDenied, new(int64(http.StatusForbidden)), encoder) return } // Validate the arguments if req.Task == "" { - handleStreamResultError(taskNotPresentErr, pointer.Of(int64(http.StatusBadRequest)), encoder) + handleStreamResultError(taskNotPresentErr, new(int64(http.StatusBadRequest)), encoder) return } switch req.LogType { case "stdout", "stderr": default: - handleStreamResultError(logTypeNotPresentErr, pointer.Of(int64(http.StatusBadRequest)), encoder) + handleStreamResultError(logTypeNotPresentErr, new(int64(http.StatusBadRequest)), encoder) return } switch req.Origin { @@ -408,15 +407,15 @@ func (f *FileSystem) logs(conn io.ReadWriteCloser) { case "": req.Origin = "start" default: - handleStreamResultError(invalidOrigin, pointer.Of(int64(http.StatusBadRequest)), encoder) + handleStreamResultError(invalidOrigin, new(int64(http.StatusBadRequest)), encoder) return } fs, err := f.c.GetAllocFS(req.AllocID) if err != nil { - code := pointer.Of(int64(http.StatusInternalServerError)) + code := new(int64(http.StatusInternalServerError)) if structs.IsErrUnknownAllocation(err) { - code = pointer.Of(int64(http.StatusNotFound)) + code = new(int64(http.StatusNotFound)) } handleStreamResultError(err, code, encoder) @@ -425,9 +424,9 @@ func (f *FileSystem) logs(conn io.ReadWriteCloser) { allocState, err := f.c.GetAllocState(req.AllocID) if err != nil { - code := pointer.Of(int64(http.StatusInternalServerError)) + code := new(int64(http.StatusInternalServerError)) if structs.IsErrUnknownAllocation(err) { - code = pointer.Of(int64(http.StatusNotFound)) + code = new(int64(http.StatusNotFound)) } handleStreamResultError(err, code, encoder) @@ -439,7 +438,7 @@ func (f *FileSystem) logs(conn io.ReadWriteCloser) { if taskState == nil { handleStreamResultError( fmt.Errorf("unknown task name %q", req.Task), - pointer.Of(int64(http.StatusBadRequest)), + new(int64(http.StatusBadRequest)), encoder) return } @@ -447,7 +446,7 @@ func (f *FileSystem) logs(conn io.ReadWriteCloser) { if taskState.StartedAt.IsZero() { handleStreamResultError( fmt.Errorf("task %q not started yet. No logs available", req.Task), - pointer.Of(int64(http.StatusNotFound)), + new(int64(http.StatusNotFound)), encoder) return } diff --git a/client/heartbeatstop_test.go b/client/heartbeatstop_test.go index 932504c2eae..2039e064720 100644 --- a/client/heartbeatstop_test.go +++ b/client/heartbeatstop_test.go @@ -11,7 +11,6 @@ import ( "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/client/allocrunner/interfaces" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/testlog" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/structs" @@ -43,7 +42,7 @@ func TestHeartbeatStop(t *testing.T) { { Name: "foo", Disconnect: &structs.DisconnectStrategy{ - StopOnClientAfter: pointer.Of(time.Microsecond), + StopOnClientAfter: new(time.Microsecond), }, }, }, @@ -53,7 +52,7 @@ func TestHeartbeatStop(t *testing.T) { // an alloc with a longer lease alloc2 := alloc1.Copy() alloc2.ID = uuid.Generate() - alloc2.Job.TaskGroups[0].Disconnect.StopOnClientAfter = pointer.Of(500 * time.Millisecond) + alloc2.Job.TaskGroups[0].Disconnect.StopOnClientAfter = new(500 * time.Millisecond) // an alloc with no disconnect config alloc3 := alloc1.Copy() diff --git a/client/lib/cgroupslib/memory.go b/client/lib/cgroupslib/memory.go index ac95b05e7e3..c48c1ccdbae 100644 --- a/client/lib/cgroupslib/memory.go +++ b/client/lib/cgroupslib/memory.go @@ -7,8 +7,6 @@ package cgroupslib import ( "sync" - - "github.com/hashicorp/nomad/helper/pointer" ) var ( @@ -31,10 +29,10 @@ func detectMemorySwap() *uint64 { case CG1: err := WriteNomadCG1("memory", "memory.swappiness", "0") if err == nil { - return pointer.Of[uint64](0) + return new(uint64(0)) } return nil default: - return pointer.Of[uint64](0) + return new(uint64(0)) } } diff --git a/client/meta_endpoint_test.go b/client/meta_endpoint_test.go index e97eff613c6..3d862829dc6 100644 --- a/client/meta_endpoint_test.go +++ b/client/meta_endpoint_test.go @@ -9,7 +9,6 @@ import ( "github.com/hashicorp/nomad/acl" "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/client/config" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" @@ -34,7 +33,7 @@ func TestNodeMeta_ACL(t *testing.T) { applyReq := &structs.NodeMetaApplyRequest{ NodeID: c1.NodeID(), Meta: map[string]*string{ - "foo": pointer.Of("bar"), + "foo": new("bar"), }, } @@ -86,13 +85,13 @@ func TestNodeMeta_Validation(t *testing.T) { must.ErrorContains(t, err, "missing required Meta") // empty keys are prohibited - applyReq.Meta[""] = pointer.Of("bad") + applyReq.Meta[""] = new("bad") err = c1.ClientRPC("NodeMeta.Apply", applyReq, &resp) must.ErrorContains(t, err, "empty") // * is prohibited in keys delete(applyReq.Meta, "") - applyReq.Meta["*"] = pointer.Of("bad") + applyReq.Meta["*"] = new("bad") err = c1.ClientRPC("NodeMeta.Apply", applyReq, &resp) must.ErrorContains(t, err, "*") } @@ -114,7 +113,7 @@ func TestNodeMeta_unset(t *testing.T) { applyReq := &structs.NodeMetaApplyRequest{ NodeID: c1.NodeID(), Meta: map[string]*string{ - "dynamic_meta": pointer.Of("true"), + "dynamic_meta": new("true"), }, } var resp structs.NodeMetaResponse diff --git a/client/taskenv/services_test.go b/client/taskenv/services_test.go index d50de8ec1b1..df807705762 100644 --- a/client/taskenv/services_test.go +++ b/client/taskenv/services_test.go @@ -8,7 +8,6 @@ import ( "time" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/structs" "github.com/stretchr/testify/require" ) @@ -290,17 +289,17 @@ func TestInterpolate_interpolateConnect(t *testing.T) { }}, }, Meta: map[string]string{"${meta1}": "${meta2}"}, - KillTimeout: pointer.Of(1 * time.Second), + KillTimeout: new(1 * time.Second), LogConfig: &structs.LogConfig{ MaxFiles: 1, MaxFileSizeMB: 2, }, - ShutdownDelay: pointer.Of(2 * time.Second), + ShutdownDelay: new(2 * time.Second), KillSignal: "${signal1}", }, Gateway: &structs.ConsulGateway{ Proxy: &structs.ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(3 * time.Second), + ConnectTimeout: new(3 * time.Second), EnvoyGatewayBindTaggedAddresses: true, EnvoyGatewayBindAddresses: map[string]*structs.ConsulGatewayBindAddress{ "${bind1}": { @@ -400,17 +399,17 @@ func TestInterpolate_interpolateConnect(t *testing.T) { }}, }, Meta: map[string]string{"_meta1": "_meta2"}, - KillTimeout: pointer.Of(1 * time.Second), + KillTimeout: new(1 * time.Second), LogConfig: &structs.LogConfig{ MaxFiles: 1, MaxFileSizeMB: 2, }, - ShutdownDelay: pointer.Of(2 * time.Second), + ShutdownDelay: new(2 * time.Second), KillSignal: "_signal1", }, Gateway: &structs.ConsulGateway{ Proxy: &structs.ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(3 * time.Second), + ConnectTimeout: new(3 * time.Second), EnvoyGatewayBindTaggedAddresses: true, EnvoyGatewayBindAddresses: map[string]*structs.ConsulGatewayBindAddress{ "_bind1": { diff --git a/client/vaultclient/vaultclient_test.go b/client/vaultclient/vaultclient_test.go index 2244423b4a2..a85b17d7044 100644 --- a/client/vaultclient/vaultclient_test.go +++ b/client/vaultclient/vaultclient_test.go @@ -20,7 +20,6 @@ import ( "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/client/widmgr" "github.com/hashicorp/nomad/helper" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/testlog" "github.com/hashicorp/nomad/helper/useragent" "github.com/hashicorp/nomad/helper/uuid" @@ -443,7 +442,7 @@ func TestVaultClient_SetUserAgent(t *testing.T) { ci.Parallel(t) conf := structsc.DefaultVaultConfig() - conf.Enabled = pointer.Of(true) + conf.Enabled = new(true) logger := testlog.HCLogger(t) c, err := NewVaultClient(conf, logger) must.NoError(t, err) @@ -488,7 +487,7 @@ func TestVaultClient_RenewalConcurrent(t *testing.T) { // Start Vault client. conf := structsc.DefaultVaultConfig() conf.Addr = ts.URL - conf.Enabled = pointer.Of(true) + conf.Enabled = new(true) vc, err := NewVaultClient(conf, testlog.HCLogger(t)) must.NoError(t, err) @@ -544,7 +543,7 @@ func TestVaultClient_NamespaceReset(t *testing.T) { conf := structsc.DefaultVaultConfig() conf.Addr = ts.URL - conf.Enabled = pointer.Of(true) + conf.Enabled = new(true) for _, ns := range []string{"", "foo"} { conf.Namespace = ns diff --git a/client/widmgr/widmgr_int_test.go b/client/widmgr/widmgr_int_test.go index c2ffe1602a4..92fa854a918 100644 --- a/client/widmgr/widmgr_int_test.go +++ b/client/widmgr/widmgr_int_test.go @@ -10,7 +10,6 @@ import ( "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/client/widmgr" "github.com/hashicorp/nomad/command/agent" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" @@ -24,7 +23,7 @@ func TestWIDMgr(t *testing.T) { // Create a mixed ta ta := agent.NewTestAgent(t, "widtest", func(c *agent.Config) { c.Server.Enabled = true - c.Server.NumSchedulers = pointer.Of(1) + c.Server.NumSchedulers = new(1) c.Client.Enabled = true }) t.Cleanup(ta.Shutdown) diff --git a/command/agent/agent.go b/command/agent/agent.go index b99d60b12e5..f3f9bb7deea 100644 --- a/command/agent/agent.go +++ b/command/agent/agent.go @@ -33,7 +33,6 @@ import ( "github.com/hashicorp/nomad/helper/bufconndialer" "github.com/hashicorp/nomad/helper/escapingfs" "github.com/hashicorp/nomad/helper/pluginutils/loader" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad" "github.com/hashicorp/nomad/nomad/deploymentwatcher" @@ -693,7 +692,7 @@ func convertServerConfig(agentConfig *Config) (*nomad.Config, error) { // Interpret job_max_source_size as bytes from string value if agentConfig.Server.JobMaxSourceSize == nil { - agentConfig.Server.JobMaxSourceSize = pointer.Of("1M") + agentConfig.Server.JobMaxSourceSize = new("1M") } jobMaxSourceBytes, err := humanize.ParseBytes(*agentConfig.Server.JobMaxSourceSize) if err != nil { diff --git a/command/agent/agent_endpoint_test.go b/command/agent/agent_endpoint_test.go index 8b9c63a8974..8f1291fcf4c 100644 --- a/command/agent/agent_endpoint_test.go +++ b/command/agent/agent_endpoint_test.go @@ -28,7 +28,6 @@ import ( "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/ci" sframer "github.com/hashicorp/nomad/client/lib/streamframer" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/pool" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" @@ -661,7 +660,7 @@ func TestHTTP_AgentMonitorExport(t *testing.T) { func TestAgent_PprofRequest_Permissions(t *testing.T) { ci.Parallel(t) - trueP, falseP := pointer.Of(true), pointer.Of(false) + trueP, falseP := new(true), new(false) cases := []struct { acl *bool debug *bool @@ -669,7 +668,7 @@ func TestAgent_PprofRequest_Permissions(t *testing.T) { }{ // manually set to false because test helpers // enable to true by default - // enableDebug: pointer.Of(false), + // enableDebug: new(false), {debug: nil, ok: false}, {debug: trueP, ok: true}, {debug: falseP, ok: false}, @@ -1792,7 +1791,7 @@ func TestHTTP_AgentSchedulerWorkerInfoRequest(t *testing.T) { ci.Parallel(t) configFn := func(c *Config) { - c.Server.NumSchedulers = pointer.Of(runtime.NumCPU()) + c.Server.NumSchedulers = new(runtime.NumCPU()) c.Server.EnabledSchedulers = []string{"_core", "batch"} c.Client.Enabled = false } @@ -2112,7 +2111,7 @@ func TestHTTP_AgentSchedulerWorkerConfigRequest_NoACL(t *testing.T) { ci.Parallel(t) configFn := func(c *Config) { - c.Server.NumSchedulers = pointer.Of(runtime.NumCPU()) + c.Server.NumSchedulers = new(runtime.NumCPU()) c.Server.EnabledSchedulers = []string{"_core", "batch"} c.Client.Enabled = false } @@ -2144,7 +2143,7 @@ func TestHTTP_AgentSchedulerWorkerConfigRequest_ACL(t *testing.T) { ci.Parallel(t) configFn := func(c *Config) { - c.Server.NumSchedulers = pointer.Of(runtime.NumCPU()) + c.Server.NumSchedulers = new(runtime.NumCPU()) c.Server.EnabledSchedulers = []string{"_core", "batch"} c.Client.Enabled = false } diff --git a/command/agent/agent_test.go b/command/agent/agent_test.go index 20a57e107d6..bf02a6d069c 100644 --- a/command/agent/agent_test.go +++ b/command/agent/agent_test.go @@ -16,7 +16,6 @@ import ( "github.com/hashicorp/nomad/ci" clientconfig "github.com/hashicorp/nomad/client/config" cstructs "github.com/hashicorp/nomad/client/structs" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/testlog" "github.com/hashicorp/nomad/nomad" "github.com/hashicorp/nomad/nomad/structs" @@ -267,7 +266,7 @@ func TestAgent_ServerConfig_Limits_Error(t *testing.T) { expectedErr: "rpc_handshake_timeout must be >= 0", limits: config.Limits{ RPCHandshakeTimeout: "-5s", - RPCMaxConnsPerClient: pointer.Of(100), + RPCMaxConnsPerClient: new(100), }, }, { @@ -275,7 +274,7 @@ func TestAgent_ServerConfig_Limits_Error(t *testing.T) { expectedErr: "error parsing rpc_handshake_timeout", limits: config.Limits{ RPCHandshakeTimeout: "s", - RPCMaxConnsPerClient: pointer.Of(100), + RPCMaxConnsPerClient: new(100), }, }, { @@ -283,7 +282,7 @@ func TestAgent_ServerConfig_Limits_Error(t *testing.T) { expectedErr: "error parsing rpc_handshake_timeout", limits: config.Limits{ RPCHandshakeTimeout: "", - RPCMaxConnsPerClient: pointer.Of(100), + RPCMaxConnsPerClient: new(100), }, }, { @@ -291,7 +290,7 @@ func TestAgent_ServerConfig_Limits_Error(t *testing.T) { expectedErr: "rpc_max_conns_per_client must be > 25; found: -100", limits: config.Limits{ RPCHandshakeTimeout: "5s", - RPCMaxConnsPerClient: pointer.Of(-100), + RPCMaxConnsPerClient: new(-100), }, }, { @@ -299,7 +298,7 @@ func TestAgent_ServerConfig_Limits_Error(t *testing.T) { expectedErr: "rpc_max_conns_per_client must be > 25; found: 20", limits: config.Limits{ RPCHandshakeTimeout: "5s", - RPCMaxConnsPerClient: pointer.Of(config.LimitsNonStreamingConnsPerClient), + RPCMaxConnsPerClient: new(config.LimitsNonStreamingConnsPerClient), }, }, } @@ -343,21 +342,21 @@ func TestAgent_ServerConfig_Limits_OK(t *testing.T) { name: "Zeros are valid", limits: config.Limits{ RPCHandshakeTimeout: "0s", - RPCMaxConnsPerClient: pointer.Of(0), + RPCMaxConnsPerClient: new(0), }, }, { name: "Low limits are valid", limits: config.Limits{ RPCHandshakeTimeout: "1ms", - RPCMaxConnsPerClient: pointer.Of(26), + RPCMaxConnsPerClient: new(26), }, }, { name: "High limits are valid", limits: config.Limits{ RPCHandshakeTimeout: "5h", - RPCMaxConnsPerClient: pointer.Of(100000), + RPCMaxConnsPerClient: new(100000), }, }, } @@ -397,12 +396,12 @@ func TestAgent_ServerConfig_PlanRejectionTracker(t *testing.T) { { name: "valid config", trackerConfig: &PlanRejectionTracker{ - Enabled: pointer.Of(true), + Enabled: new(true), NodeThreshold: 123, NodeWindow: 17 * time.Minute, }, expectedConfig: &PlanRejectionTracker{ - Enabled: pointer.Of(true), + Enabled: new(true), NodeThreshold: 123, NodeWindow: 17 * time.Minute, }, @@ -474,7 +473,7 @@ func TestAgent_ServerConfig_RaftMultiplier_Ok(t *testing.T) { }, { - multiplier: pointer.Of(0), + multiplier: new(0), electionTimout: 1 * time.Second, heartbeatTimeout: 1 * time.Second, @@ -482,7 +481,7 @@ func TestAgent_ServerConfig_RaftMultiplier_Ok(t *testing.T) { commitTimeout: 50 * time.Millisecond, }, { - multiplier: pointer.Of(1), + multiplier: new(1), electionTimout: 1 * time.Second, heartbeatTimeout: 1 * time.Second, @@ -490,7 +489,7 @@ func TestAgent_ServerConfig_RaftMultiplier_Ok(t *testing.T) { commitTimeout: 50 * time.Millisecond, }, { - multiplier: pointer.Of(5), + multiplier: new(5), electionTimout: 5 * time.Second, heartbeatTimeout: 5 * time.Second, @@ -498,7 +497,7 @@ func TestAgent_ServerConfig_RaftMultiplier_Ok(t *testing.T) { commitTimeout: 250 * time.Millisecond, }, { - multiplier: pointer.Of(6), + multiplier: new(6), electionTimout: 6 * time.Second, heartbeatTimeout: 6 * time.Second, @@ -506,7 +505,7 @@ func TestAgent_ServerConfig_RaftMultiplier_Ok(t *testing.T) { commitTimeout: 300 * time.Millisecond, }, { - multiplier: pointer.Of(10), + multiplier: new(10), electionTimout: 10 * time.Second, heartbeatTimeout: 10 * time.Second, @@ -570,13 +569,13 @@ func TestAgent_ServerConfig_RaftTrailingLogs(t *testing.T) { }{ { name: "bad", - value: pointer.Of(int(-1)), + value: new(int(-1)), isErr: true, expect: "raft_trailing_logs must be non-negative", }, { name: "good", - value: pointer.Of(int(10)), + value: new(int(10)), expect: uint64(10), }, { @@ -619,13 +618,13 @@ func TestAgent_ServerConfig_RaftSnapshotThreshold(t *testing.T) { }{ { name: "bad", - value: pointer.Of(int(-1)), + value: new(int(-1)), isErr: true, expect: "raft_snapshot_threshold must be non-negative", }, { name: "good", - value: pointer.Of(int(10)), + value: new(int(10)), expect: uint64(10), }, { @@ -705,21 +704,21 @@ func Test_convertServerConfig_errors(t *testing.T) { { name: "num schedulers too big", inputConfig: overlayDefaultFunc(func(config *Config) { - config.Server.NumSchedulers = pointer.Of(1<<63 - 1) + config.Server.NumSchedulers = new(1<<63 - 1) }), expectErr: true, }, { name: "num schedulers negative", inputConfig: overlayDefaultFunc(func(config *Config) { - config.Server.NumSchedulers = pointer.Of(-100) + config.Server.NumSchedulers = new(-100) }), expectErr: true, }, { name: "valid", inputConfig: overlayDefaultFunc(func(config *Config) { - config.Server.NumSchedulers = pointer.Of(runtime.NumCPU()) + config.Server.NumSchedulers = new(runtime.NumCPU()) }), expectErr: false, }, @@ -802,7 +801,7 @@ func TestConvertClientConfig(t *testing.T) { { name: "hook metrics enabled (default value)", modConfig: func(c *Config) { - c.Telemetry.DisableAllocationHookMetrics = pointer.Of(false) + c.Telemetry.DisableAllocationHookMetrics = new(false) }, assert: func(t *testing.T, cc *clientconfig.Config) { must.False(t, cc.DisableAllocationHookMetrics) @@ -811,7 +810,7 @@ func TestConvertClientConfig(t *testing.T) { { name: "hook metrics disabled", modConfig: func(c *Config) { - c.Telemetry.DisableAllocationHookMetrics = pointer.Of(true) + c.Telemetry.DisableAllocationHookMetrics = new(true) }, assert: func(t *testing.T, cc *clientconfig.Config) { must.True(t, cc.DisableAllocationHookMetrics) @@ -943,7 +942,7 @@ func TestAgent_ClientConfig_discovery(t *testing.T) { // Test the default, and then custom setting of the client service // discovery boolean. require.True(t, c.NomadServiceDiscovery) - conf.Client.NomadServiceDiscovery = pointer.Of(false) + conf.Client.NomadServiceDiscovery = new(false) c, err = a.clientConfig() require.NoError(t, err) require.False(t, c.NomadServiceDiscovery) @@ -953,7 +952,7 @@ func TestAgent_ClientConfig_JobMaxSourceSize(t *testing.T) { ci.Parallel(t) conf := DevConfig(nil) - must.Eq(t, conf.Server.JobMaxSourceSize, pointer.Of("1M")) + must.Eq(t, conf.Server.JobMaxSourceSize, new("1M")) must.NoError(t, conf.normalizeAddrs()) // config conversion ensures value is set @@ -996,7 +995,7 @@ func TestAgent_HTTPCheck(t *testing.T) { normalizedAddrs: &NormalizedAddrs{HTTP: []string{"normalized:4646"}}, Consuls: []*config.ConsulConfig{{ Name: "default", - ChecksUseAdvertise: pointer.Of(false), + ChecksUseAdvertise: new(false), ClientFailuresBeforeCritical: 2, ClientFailuresBeforeWarning: 1, }}, @@ -1033,7 +1032,7 @@ func TestAgent_HTTPCheck(t *testing.T) { t.Run("Plain HTTP + ChecksUseAdvertise", func(t *testing.T) { a := agent() - a.config.Consuls[0].ChecksUseAdvertise = pointer.Of(true) + a.config.Consuls[0].ChecksUseAdvertise = new(true) check := a.agentHTTPCheck(false) if check == nil { t.Fatalf("expected non-nil check") @@ -1457,10 +1456,10 @@ func TestServer_Reload_VaultConfig(t *testing.T) { ci.Parallel(t) agent := NewTestAgent(t, t.Name(), func(c *Config) { - c.Server.NumSchedulers = pointer.Of(0) + c.Server.NumSchedulers = new(0) c.Vaults[0] = &config.VaultConfig{ Name: "default", - Enabled: pointer.Of(true), + Enabled: new(true), Namespace: "vault-namespace", Addr: "https://vault.consul:8200", } @@ -1470,7 +1469,7 @@ func TestServer_Reload_VaultConfig(t *testing.T) { newConfig := agent.GetConfig().Copy() newConfig.Vaults[0] = &config.VaultConfig{ Name: "default", - Enabled: pointer.Of(true), + Enabled: new(true), Namespace: "another-namespace", Addr: "https://vault.consul:8200", } @@ -1908,19 +1907,19 @@ func TestAgent_ServerConfig_JobMaxPriority_Ok(t *testing.T) { }, { - maxPriority: pointer.Of(0), + maxPriority: new(0), jobMaxPriority: 100, }, { - maxPriority: pointer.Of(100), + maxPriority: new(100), jobMaxPriority: 100, }, { - maxPriority: pointer.Of(200), + maxPriority: new(200), jobMaxPriority: 200, }, { - maxPriority: pointer.Of(32766), + maxPriority: new(32766), jobMaxPriority: 32766, }, } @@ -1978,19 +1977,19 @@ func TestAgent_ServerConfig_JobDefaultPriority_Ok(t *testing.T) { }, { - defaultPriority: pointer.Of(0), + defaultPriority: new(0), jobDefaultPriority: 50, }, { - defaultPriority: pointer.Of(50), + defaultPriority: new(50), jobDefaultPriority: 50, }, { - defaultPriority: pointer.Of(60), + defaultPriority: new(60), jobDefaultPriority: 60, }, { - defaultPriority: pointer.Of(99), + defaultPriority: new(99), jobDefaultPriority: 99, }, } @@ -2050,32 +2049,32 @@ func TestAgent_ServerConfig_JobMaxCount(t *testing.T) { expectedErr: "", }, { - configured: pointer.Of(1), + configured: new(1), expected: 1, expectedErr: "", }, { - configured: pointer.Of(0), + configured: new(0), expected: 0, expectedErr: "", }, { - configured: pointer.Of(structs.JobDefaultMaxCount), + configured: new(structs.JobDefaultMaxCount), expected: structs.JobDefaultMaxCount, expectedErr: "", }, { - configured: pointer.Of(2 * structs.JobDefaultMaxCount), + configured: new(2 * structs.JobDefaultMaxCount), expected: 2 * structs.JobDefaultMaxCount, expectedErr: "", }, { - configured: pointer.Of(-1), + configured: new(-1), expected: 0, expectedErr: "job_max_count (-1) cannot be negative", }, { - configured: pointer.Of(-3), + configured: new(-3), expected: 0, expectedErr: "job_max_count (-3) cannot be negative", }, diff --git a/command/agent/alloc_endpoint.go b/command/agent/alloc_endpoint.go index f2ca881774e..c2fd6717c59 100644 --- a/command/agent/alloc_endpoint.go +++ b/command/agent/alloc_endpoint.go @@ -19,7 +19,6 @@ import ( "github.com/gorilla/websocket" "github.com/hashicorp/go-msgpack/v2/codec" cstructs "github.com/hashicorp/nomad/client/structs" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/structs" "github.com/hashicorp/nomad/plugins/drivers" ) @@ -152,14 +151,14 @@ func (s *HTTPServer) allocStop(allocID string, resp http.ResponseWriter, req *ht if err != nil { return nil, err } else if noShutdownDelay == nil { - noShutdownDelay = pointer.Of(false) + noShutdownDelay = new(false) } reschedule, err := parseBool(req, "reschedule") if err != nil { return nil, err } else if reschedule == nil { - reschedule = pointer.Of(false) + reschedule = new(false) } sr := &structs.AllocStopRequest{ diff --git a/command/agent/alloc_endpoint_test.go b/command/agent/alloc_endpoint_test.go index 6f359e84742..23f8b304372 100644 --- a/command/agent/alloc_endpoint_test.go +++ b/command/agent/alloc_endpoint_test.go @@ -25,7 +25,6 @@ import ( "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/client/allocdir" cstructs "github.com/hashicorp/nomad/client/structs" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" @@ -731,7 +730,7 @@ func TestHTTP_AllocSnapshot_Atomic(t *testing.T) { ci.Parallel(t) httpTest(t, func(c *Config) { // Disable the schedulers - c.Server.NumSchedulers = pointer.Of(0) + c.Server.NumSchedulers = new(0) }, func(s *TestAgent) { // Create an alloc state := s.server.State() @@ -1133,7 +1132,7 @@ func TestHTTP_ReadWsHandshake(t *testing.T) { // websocket that can cause a panic func TestHTTP_AllocsExecStream_SafeClose(t *testing.T) { httpTest(t, - func(c *Config) { c.Server.NumSchedulers = pointer.Of(0) }, + func(c *Config) { c.Server.NumSchedulers = new(0) }, func(s *TestAgent) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) diff --git a/command/agent/command_test.go b/command/agent/command_test.go index 9a4f322d088..88657f99033 100644 --- a/command/agent/command_test.go +++ b/command/agent/command_test.go @@ -14,7 +14,6 @@ import ( "github.com/hashicorp/cli" "github.com/hashicorp/go-hclog" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/structs" "github.com/hashicorp/nomad/nomad/structs/config" "github.com/hashicorp/nomad/version" @@ -430,7 +429,7 @@ func TestIsValidConfig(t *testing.T) { Client: &ClientConfig{ Enabled: true, Artifact: &config.ArtifactConfig{ - HTTPReadTimeout: pointer.Of("-10m"), + HTTPReadTimeout: new("-10m"), }, }, }, diff --git a/command/agent/config.go b/command/agent/config.go index 6cef762b304..94546cb83ce 100644 --- a/command/agent/config.go +++ b/command/agent/config.go @@ -1764,7 +1764,7 @@ func DevConfig(mode *devModeConfig) *Config { conf.Server.BootstrapExpect = 1 conf.EnableDebug = true conf.DisableAnonymousSignature = true - conf.defaultConsul().AutoAdvertise = pointer.Of(true) + conf.defaultConsul().AutoAdvertise = new(true) conf.Client.NetworkInterface = mode.iface conf.Client.Options = map[string]string{ "driver.raw_exec.enable": "true", @@ -1776,7 +1776,7 @@ func DevConfig(mode *devModeConfig) *Config { conf.Client.GCMaxAllocs = 50 conf.Client.Options[fingerprint.TightenNetworkTimeoutsConfig] = "true" conf.Client.BindWildcardDefaultHostNetwork = true - conf.Client.NomadServiceDiscovery = pointer.Of(true) + conf.Client.NomadServiceDiscovery = new(true) conf.Client.ReservableCores = "" // inherit all the cores conf.Telemetry.PrometheusMetrics = true conf.Telemetry.PublishAllocationMetrics = true @@ -1787,20 +1787,20 @@ func DevConfig(mode *devModeConfig) *Config { if mode.consulMode { conf.Consuls[0].ServiceIdentity = &config.WorkloadIdentityConfig{ Audience: []string{"consul.io"}, - TTL: pointer.Of(time.Hour), + TTL: new(time.Hour), } conf.Consuls[0].TaskIdentity = &config.WorkloadIdentityConfig{ Audience: []string{"consul.io"}, - TTL: pointer.Of(time.Hour), + TTL: new(time.Hour), } } if mode.vaultMode { - conf.Vaults[0].Enabled = pointer.Of(true) + conf.Vaults[0].Enabled = new(true) conf.Vaults[0].Addr = "http://localhost:8200" conf.Vaults[0].DefaultIdentity = &config.WorkloadIdentityConfig{ Audience: []string{"vault.io"}, - TTL: pointer.Of(time.Hour), + TTL: new(time.Hour), } } return conf @@ -1850,7 +1850,7 @@ func DefaultConfig() *Config { GCDiskUsageThreshold: 80, GCInodeUsageThreshold: 70, GCMaxAllocs: 50, - NoHostUUID: pointer.Of(true), + NoHostUUID: new(true), DisableRemoteExec: false, ServerJoin: &ServerJoin{ RetryJoin: []string{}, @@ -1861,7 +1861,7 @@ func DefaultConfig() *Config { BindWildcardDefaultHostNetwork: true, CNIPath: client.DefaultCNIPath, CNIConfigDir: "/opt/cni/config", - NomadServiceDiscovery: pointer.Of(true), + NomadServiceDiscovery: new(true), Artifact: config.DefaultArtifactConfig(), Drain: nil, Users: config.DefaultUsersConfig(), @@ -1869,12 +1869,12 @@ func DefaultConfig() *Config { }, Server: &ServerConfig{ Enabled: false, - EnableEventBroker: pointer.Of(true), - EventBufferSize: pointer.Of(100), + EnableEventBroker: new(true), + EventBufferSize: new(100), RaftProtocol: 3, StartJoin: []string{}, PlanRejectionTracker: &PlanRejectionTracker{ - Enabled: pointer.Of(false), + Enabled: new(false), NodeThreshold: 100, NodeWindow: 5 * time.Minute, }, @@ -1889,8 +1889,8 @@ func DefaultConfig() *Config { LimitResults: 100, MinTermLength: 2, }, - JobMaxSourceSize: pointer.Of("1M"), - JobTrackedVersions: pointer.Of(structs.JobDefaultTrackedVersions), + JobMaxSourceSize: new("1M"), + JobTrackedVersions: new(structs.JobDefaultTrackedVersions), }, ACL: &ACLConfig{ Enabled: false, @@ -1906,7 +1906,7 @@ func DefaultConfig() *Config { inMemoryRetentionPeriod: 1 * time.Minute, CollectionInterval: "1s", collectionInterval: 1 * time.Second, - DisableAllocationHookMetrics: pointer.Of(false), + DisableAllocationHookMetrics: new(false), }, Eventlog: &Eventlog{ Enabled: false, @@ -1917,7 +1917,7 @@ func DefaultConfig() *Config { Version: version.GetVersion(), Autopilot: config.DefaultAutopilotConfig(), Audit: &config.AuditConfig{}, - DisableUpdateCheck: pointer.Of(false), + DisableUpdateCheck: new(false), Limits: config.DefaultLimits(), Reporting: config.DefaultReporting(), KEKProviders: []*structs.KEKProviderConfig{}, @@ -2010,7 +2010,7 @@ func (c *Config) Merge(b *Config) *Config { result.SyslogFacility = b.SyslogFacility } if b.DisableUpdateCheck != nil { - result.DisableUpdateCheck = pointer.Of(*b.DisableUpdateCheck) + result.DisableUpdateCheck = new(*b.DisableUpdateCheck) } if b.DisableAnonymousSignature { result.DisableAnonymousSignature = true @@ -2634,7 +2634,7 @@ func (s *ServerConfig) Merge(b *ServerConfig) *ServerConfig { result.RaftMultiplier = &c } if b.NumSchedulers != nil { - result.NumSchedulers = pointer.Of(*b.NumSchedulers) + result.NumSchedulers = new(*b.NumSchedulers) } if b.NodeGCThreshold != "" { result.NodeGCThreshold = b.NodeGCThreshold @@ -2646,13 +2646,13 @@ func (s *ServerConfig) Merge(b *ServerConfig) *ServerConfig { result.JobGCThreshold = b.JobGCThreshold } if b.JobDefaultPriority != nil { - result.JobDefaultPriority = pointer.Of(*b.JobDefaultPriority) + result.JobDefaultPriority = new(*b.JobDefaultPriority) } if b.JobMaxPriority != nil { - result.JobMaxPriority = pointer.Of(*b.JobMaxPriority) + result.JobMaxPriority = new(*b.JobMaxPriority) } if b.JobMaxCount != nil { - result.JobMaxCount = pointer.Of(*b.JobMaxCount) + result.JobMaxCount = new(*b.JobMaxCount) } if b.EvalGCThreshold != "" { result.EvalGCThreshold = b.EvalGCThreshold @@ -2783,15 +2783,15 @@ func (s *ServerConfig) Merge(b *ServerConfig) *ServerConfig { } if b.RaftSnapshotThreshold != nil { - result.RaftSnapshotThreshold = pointer.Of(*b.RaftSnapshotThreshold) + result.RaftSnapshotThreshold = new(*b.RaftSnapshotThreshold) } if b.RaftSnapshotInterval != nil { - result.RaftSnapshotInterval = pointer.Of(*b.RaftSnapshotInterval) + result.RaftSnapshotInterval = new(*b.RaftSnapshotInterval) } if b.RaftTrailingLogs != nil { - result.RaftTrailingLogs = pointer.Of(*b.RaftTrailingLogs) + result.RaftTrailingLogs = new(*b.RaftTrailingLogs) } if b.JobTrackedVersions != nil { diff --git a/command/agent/config_parse_test.go b/command/agent/config_parse_test.go index 95b79d367c0..bded5ba73c4 100644 --- a/command/agent/config_parse_test.go +++ b/command/agent/config_parse_test.go @@ -12,7 +12,6 @@ import ( "github.com/hashicorp/nomad/ci" client "github.com/hashicorp/nomad/client/config" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/structs" "github.com/hashicorp/nomad/nomad/structs/config" "github.com/shoenig/test/must" @@ -90,7 +89,7 @@ var basicConfig = &Config{ GCInodeUsageThreshold: 91, GCMaxAllocs: 50, GCVolumesOnNodeGC: true, - NoHostUUID: pointer.Of(false), + NoHostUUID: new(false), DisableRemoteExec: true, HostVolumes: []*structs.ClientHostVolumeConfig{ {Name: "tmp", Path: "/tmp"}, @@ -105,7 +104,7 @@ var basicConfig = &Config{ RetryInterval: 1 * time.Second, RetryIntervalHCL: "1s", RetryAttempts: 3, - ExitOnFailure: pointer.Of(true), + ExitOnFailure: new(true), }, }, }, @@ -115,8 +114,8 @@ var basicConfig = &Config{ BootstrapExpect: 5, DataDir: "/tmp/data", RaftProtocol: 3, - RaftMultiplier: pointer.Of(4), - NumSchedulers: pointer.Of(2), + RaftMultiplier: new(4), + NumSchedulers: new(2), EnabledSchedulers: []string{"test"}, NodeGCThreshold: "12h", EvalGCThreshold: "12h", @@ -144,10 +143,10 @@ var basicConfig = &Config{ RedundancyZone: "foo", UpgradeVersion: "0.8.0", EncryptKey: "abc", - EnableEventBroker: pointer.Of(false), - EventBufferSize: pointer.Of(200), + EnableEventBroker: new(false), + EventBufferSize: new(200), PlanRejectionTracker: &PlanRejectionTracker{ - Enabled: pointer.Of(true), + Enabled: new(true), NodeThreshold: 100, NodeWindow: 41 * time.Minute, NodeWindowHCL: "41m", @@ -167,9 +166,9 @@ var basicConfig = &Config{ }, }, LicensePath: "/tmp/nomad.hclic", - JobDefaultPriority: pointer.Of(100), - JobMaxPriority: pointer.Of(200), - JobMaxCount: pointer.Of(1000), + JobDefaultPriority: new(100), + JobMaxPriority: new(200), + JobMaxCount: new(1000), StartTimeout: "1m", ClientIntroduction: &ClientIntroduction{ Enforcement: "warn", @@ -195,7 +194,7 @@ var basicConfig = &Config{ ReplicationToken: "foobar", }, Audit: &config.AuditConfig{ - Enabled: pointer.Of(true), + Enabled: new(true), Sinks: []*config.AuditSink{ { DeliveryGuarantee: "enforced", @@ -220,7 +219,7 @@ var basicConfig = &Config{ }, }, Telemetry: &Telemetry{ - DisableAllocationHookMetrics: pointer.Of(true), + DisableAllocationHookMetrics: new(true), StatsiteAddr: "127.0.0.1:1234", StatsdAddr: "127.0.0.1:2345", PrometheusMetrics: true, @@ -239,7 +238,7 @@ var basicConfig = &Config{ LeaveOnTerm: true, EnableSyslog: true, SyslogFacility: "LOCAL1", - DisableUpdateCheck: pointer.Of(true), + DisableUpdateCheck: new(true), DisableAnonymousSignature: true, Consuls: []*config.ConsulConfig{{ Name: structs.ConsulDefaultCluster, @@ -266,17 +265,17 @@ var basicConfig = &Config{ ServiceIdentityAuthMethod: "nomad-services", ServiceIdentity: &config.WorkloadIdentityConfig{ Audience: []string{"consul.io", "nomad.dev"}, - Env: pointer.Of(false), - File: pointer.Of(true), - TTL: pointer.Of(1 * time.Hour), + Env: new(false), + File: new(true), + TTL: new(1 * time.Hour), TTLHCL: "1h", }, TaskIdentityAuthMethod: "nomad-tasks", TaskIdentity: &config.WorkloadIdentityConfig{ Audience: []string{"consul.io"}, - Env: pointer.Of(true), - File: pointer.Of(false), - TTL: pointer.Of(2 * time.Hour), + Env: new(true), + File: new(false), + TTL: new(2 * time.Hour), TTLHCL: "2h", }, }}, @@ -295,9 +294,9 @@ var basicConfig = &Config{ TLSSkipVerify: &trueValue, DefaultIdentity: &config.WorkloadIdentityConfig{ Audience: []string{"vault.io", "nomad.io"}, - Env: pointer.Of(false), - File: pointer.Of(true), - TTL: pointer.Of(3 * time.Hour), + Env: new(false), + File: new(true), + TTL: new(3 * time.Hour), TTLHCL: "3h", }, }}, @@ -369,7 +368,7 @@ var basicConfig = &Config{ SnapshotRetentionTime: time.Hour * 24, SnapshotRetentionTimeHCL: "24h", License: &config.LicenseReportingConfig{ - Enabled: pointer.Of(true), + Enabled: new(true), }, }, KEKProviders: []*structs.KEKProviderConfig{ @@ -654,7 +653,7 @@ func (c *Config) addDefaults() { if c.Reporting == nil { c.Reporting = &config.ReportingConfig{ License: &config.LicenseReportingConfig{ - Enabled: pointer.Of(false), + Enabled: new(false), }, } } @@ -750,7 +749,7 @@ var sample0 = &Config{ }, RPC: &RPCConfig{}, Audit: &config.AuditConfig{ - Enabled: pointer.Of(true), + Enabled: new(true), Sinks: []*config.AuditSink{ { DeliveryGuarantee: "enforced", @@ -789,12 +788,12 @@ var sample0 = &Config{ Consuls: []*config.ConsulConfig{{ Name: structs.ConsulDefaultCluster, Token: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", - ServerAutoJoin: pointer.Of(false), - ClientAutoJoin: pointer.Of(false), + ServerAutoJoin: new(false), + ClientAutoJoin: new(false), }}, Vaults: []*config.VaultConfig{{ Name: structs.VaultDefaultCluster, - Enabled: pointer.Of(true), + Enabled: new(true), Role: "nomad-cluster", Addr: "http://host.example.com:8200", }}, @@ -807,7 +806,7 @@ var sample0 = &Config{ KeyFile: "/opt/data/nomad/certs/server-key.pem", }, Autopilot: &config.AutopilotConfig{ - CleanupDeadServers: pointer.Of(true), + CleanupDeadServers: new(true), }, Reporting: config.DefaultReporting(), KEKProviders: []*structs.KEKProviderConfig{ @@ -872,7 +871,7 @@ var sample1 = &Config{ DialTimeoutHCL: "15s", }, Audit: &config.AuditConfig{ - Enabled: pointer.Of(true), + Enabled: new(true), Sinks: []*config.AuditSink{ { Name: "file", @@ -910,27 +909,27 @@ var sample1 = &Config{ SyslogFacility: "LOCAL0", Consuls: []*config.ConsulConfig{{ Name: structs.ConsulDefaultCluster, - EnableSSL: pointer.Of(true), + EnableSSL: new(true), Token: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", - ServerAutoJoin: pointer.Of(false), - ClientAutoJoin: pointer.Of(false), + ServerAutoJoin: new(false), + ClientAutoJoin: new(false), ServerServiceName: "nomad", ServerHTTPCheckName: "Nomad Server HTTP Check", ServerSerfCheckName: "Nomad Server Serf Check", ServerRPCCheckName: "Nomad Server RPC Check", ClientServiceName: "nomad-client", ClientHTTPCheckName: "Nomad Client HTTP Check", - AutoAdvertise: pointer.Of(true), - ChecksUseAdvertise: pointer.Of(false), + AutoAdvertise: new(true), + ChecksUseAdvertise: new(false), Timeout: 5 * time.Second, ServiceIdentityAuthMethod: structs.ConsulWorkloadsDefaultAuthMethodName, TaskIdentityAuthMethod: structs.ConsulWorkloadsDefaultAuthMethodName, Addr: "localhost:8500", - VerifySSL: pointer.Of(true), + VerifySSL: new(true), }}, Vaults: []*config.VaultConfig{{ Name: structs.VaultDefaultCluster, - Enabled: pointer.Of(true), + Enabled: new(true), Role: "nomad-cluster", Addr: "http://host.example.com:8200", JWTAuthBackendPath: "jwt-nomad", @@ -945,7 +944,7 @@ var sample1 = &Config{ KeyFile: "/opt/data/nomad/certs/server-key.pem", }, Autopilot: &config.AutopilotConfig{ - CleanupDeadServers: pointer.Of(true), + CleanupDeadServers: new(true), }, Reporting: &config.ReportingConfig{ License: &config.LicenseReportingConfig{}, @@ -1111,7 +1110,7 @@ func TestConfig_MultipleVault(t *testing.T) { must.Eq(t, "other", cfg.Vaults[2].Name) must.Nil(t, cfg.Vaults[2].Enabled) must.Eq(t, "127.0.0.1:9502", cfg.Vaults[2].Addr) - must.Eq(t, pointer.Of(4*time.Hour), cfg.Vaults[2].DefaultIdentity.TTL) + must.Eq(t, new(4*time.Hour), cfg.Vaults[2].DefaultIdentity.TTL) // check that extra Vault clusters have the defaults applied when not // overridden @@ -1162,8 +1161,8 @@ func TestConfig_MultipleConsul(t *testing.T) { must.Eq(t, "xyzzy", cfg.Consuls[1].Token) must.Eq(t, "other", cfg.Consuls[2].Name) - must.Eq(t, pointer.Of(3*time.Hour), cfg.Consuls[2].ServiceIdentity.TTL) - must.Eq(t, pointer.Of(5*time.Hour), cfg.Consuls[2].TaskIdentity.TTL) + must.Eq(t, new(3*time.Hour), cfg.Consuls[2].ServiceIdentity.TTL) + must.Eq(t, new(5*time.Hour), cfg.Consuls[2].TaskIdentity.TTL) // check that extra Consul clusters have the defaults applied when // not overridden @@ -1186,7 +1185,7 @@ func TestConfig_Telemetry(t *testing.T) { inputTelemetry2 := &Telemetry{ inMemoryCollectionInterval: 1 * time.Second, inMemoryRetentionPeriod: 10 * time.Second, - DisableAllocationHookMetrics: pointer.Of(true), + DisableAllocationHookMetrics: new(true), } mergedTelemetry2 := mergedTelemetry1.Merge(inputTelemetry2) must.Eq(t, mergedTelemetry2.inMemoryCollectionInterval, 1*time.Second) @@ -1206,31 +1205,31 @@ func TestConfig_Template(t *testing.T) { must.Eq(t, []string{"plugin"}, cfg.Client.TemplateConfig.FunctionDenylist) must.True(t, cfg.Client.TemplateConfig.DisableSandbox) - must.Eq(t, pointer.Of(7600*time.Hour), cfg.Client.TemplateConfig.MaxStale) - must.Eq(t, pointer.Of(10*time.Minute), cfg.Client.TemplateConfig.BlockQueryWaitTime) + must.Eq(t, new(7600*time.Hour), cfg.Client.TemplateConfig.MaxStale) + must.Eq(t, new(10*time.Minute), cfg.Client.TemplateConfig.BlockQueryWaitTime) must.NotNil(t, cfg.Client.TemplateConfig.Wait) - must.Eq(t, pointer.Of(10*time.Second), cfg.Client.TemplateConfig.Wait.Min) - must.Eq(t, pointer.Of(10*time.Minute), cfg.Client.TemplateConfig.Wait.Max) + must.Eq(t, new(10*time.Second), cfg.Client.TemplateConfig.Wait.Min) + must.Eq(t, new(10*time.Minute), cfg.Client.TemplateConfig.Wait.Max) must.NotNil(t, cfg.Client.TemplateConfig.WaitBounds) - must.Eq(t, pointer.Of(1*time.Second), cfg.Client.TemplateConfig.WaitBounds.Min) - must.Eq(t, pointer.Of(10*time.Hour), cfg.Client.TemplateConfig.WaitBounds.Max) + must.Eq(t, new(1*time.Second), cfg.Client.TemplateConfig.WaitBounds.Min) + must.Eq(t, new(10*time.Hour), cfg.Client.TemplateConfig.WaitBounds.Max) must.NotNil(t, cfg.Client.TemplateConfig.ConsulRetry) must.Eq(t, 6, *cfg.Client.TemplateConfig.ConsulRetry.Attempts) - must.Eq(t, pointer.Of(550*time.Millisecond), cfg.Client.TemplateConfig.ConsulRetry.Backoff) - must.Eq(t, pointer.Of(10*time.Minute), cfg.Client.TemplateConfig.ConsulRetry.MaxBackoff) + must.Eq(t, new(550*time.Millisecond), cfg.Client.TemplateConfig.ConsulRetry.Backoff) + must.Eq(t, new(10*time.Minute), cfg.Client.TemplateConfig.ConsulRetry.MaxBackoff) must.NotNil(t, cfg.Client.TemplateConfig.VaultRetry) must.Eq(t, 6, *cfg.Client.TemplateConfig.VaultRetry.Attempts) - must.Eq(t, pointer.Of(550*time.Millisecond), cfg.Client.TemplateConfig.VaultRetry.Backoff) - must.Eq(t, pointer.Of(10*time.Minute), cfg.Client.TemplateConfig.VaultRetry.MaxBackoff) + must.Eq(t, new(550*time.Millisecond), cfg.Client.TemplateConfig.VaultRetry.Backoff) + must.Eq(t, new(10*time.Minute), cfg.Client.TemplateConfig.VaultRetry.MaxBackoff) must.NotNil(t, cfg.Client.TemplateConfig.NomadRetry) must.Eq(t, 6, *cfg.Client.TemplateConfig.NomadRetry.Attempts) - must.Eq(t, pointer.Of(550*time.Millisecond), cfg.Client.TemplateConfig.NomadRetry.Backoff) - must.Eq(t, pointer.Of(10*time.Minute), cfg.Client.TemplateConfig.NomadRetry.MaxBackoff) + must.Eq(t, new(550*time.Millisecond), cfg.Client.TemplateConfig.NomadRetry.Backoff) + must.Eq(t, new(10*time.Minute), cfg.Client.TemplateConfig.NomadRetry.MaxBackoff) }) } } diff --git a/command/agent/config_test.go b/command/agent/config_test.go index cf81ccef918..311e49623ad 100644 --- a/command/agent/config_test.go +++ b/command/agent/config_test.go @@ -18,7 +18,6 @@ import ( "github.com/hashicorp/nomad/ci" client "github.com/hashicorp/nomad/client/config" "github.com/hashicorp/nomad/client/testutil" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/structs" "github.com/hashicorp/nomad/nomad/structs/config" "github.com/shoenig/test" @@ -65,7 +64,7 @@ func TestConfig_Merge(t *testing.T) { LeaveOnTerm: false, EnableSyslog: false, SyslogFacility: "local0.info", - DisableUpdateCheck: pointer.Of(false), + DisableUpdateCheck: new(false), DisableAnonymousSignature: false, BindAddr: "127.0.0.1", Telemetry: &Telemetry{ @@ -75,7 +74,7 @@ func TestConfig_Merge(t *testing.T) { DataDogTags: []string{"cat1:tag1", "cat2:tag2"}, PrometheusMetrics: true, DisableHostname: false, - DisableAllocationHookMetrics: pointer.Of(false), + DisableAllocationHookMetrics: new(false), CirconusAPIToken: "0", CirconusAPIApp: "nomadic", CirconusAPIURL: "http://api.circonus.com/v2", @@ -92,7 +91,7 @@ func TestConfig_Merge(t *testing.T) { PrefixFilter: []string{"filter1", "filter2"}, }, Audit: &config.AuditConfig{ - Enabled: pointer.Of(true), + Enabled: new(true), Sinks: []*config.AuditSink{ { DeliveryGuarantee: "enforced", @@ -134,7 +133,7 @@ func TestConfig_Merge(t *testing.T) { DiskMB: 10, ReservedPorts: "1,10-30,55", }, - NomadServiceDiscovery: pointer.Of(false), + NomadServiceDiscovery: new(false), }, Server: &ServerConfig{ Enabled: false, @@ -143,11 +142,11 @@ func TestConfig_Merge(t *testing.T) { DataDir: "/tmp/data1", ProtocolVersion: 1, RaftProtocol: 1, - RaftMultiplier: pointer.Of(5), - RaftSnapshotThreshold: pointer.Of(100), - RaftSnapshotInterval: pointer.Of("30m"), - RaftTrailingLogs: pointer.Of(200), - NumSchedulers: pointer.Of(1), + RaftMultiplier: new(5), + RaftSnapshotThreshold: new(100), + RaftSnapshotInterval: new("30m"), + RaftTrailingLogs: new(200), + NumSchedulers: new(1), NodeGCThreshold: "1h", BatchEvalGCThreshold: "4h", HeartbeatGrace: 30 * time.Second, @@ -155,10 +154,10 @@ func TestConfig_Merge(t *testing.T) { MaxHeartbeatsPerSecond: 30.0, RedundancyZone: "foo", UpgradeVersion: "foo", - EnableEventBroker: pointer.Of(false), - EventBufferSize: pointer.Of(0), + EnableEventBroker: new(false), + EventBufferSize: new(0), PlanRejectionTracker: &PlanRejectionTracker{ - Enabled: pointer.Of(true), + Enabled: new(true), NodeThreshold: 100, NodeWindow: 11 * time.Minute, }, @@ -257,11 +256,11 @@ func TestConfig_Merge(t *testing.T) { LeaveOnTerm: true, EnableSyslog: true, SyslogFacility: "local0.debug", - DisableUpdateCheck: pointer.Of(true), + DisableUpdateCheck: new(true), DisableAnonymousSignature: true, BindAddr: "127.0.0.2", Audit: &config.AuditConfig{ - Enabled: pointer.Of(true), + Enabled: new(true), Sinks: []*config.AuditSink{ { DeliveryGuarantee: "enforced", @@ -283,7 +282,7 @@ func TestConfig_Merge(t *testing.T) { DataDogTags: []string{"cat1:tag1", "cat2:tag2"}, PrometheusMetrics: true, DisableHostname: true, - DisableAllocationHookMetrics: pointer.Of(true), + DisableAllocationHookMetrics: new(true), PublishNodeMetrics: true, PublishAllocationMetrics: true, CirconusAPIToken: "1", @@ -303,7 +302,7 @@ func TestConfig_Merge(t *testing.T) { DisableDispatchedJobSummaryMetrics: true, DisableQuotaUtilizationMetrics: false, DisableRPCRateMetricsLabels: true, - FilterDefault: pointer.Of(false), + FilterDefault: new(false), }, Client: &ClientConfig{ Enabled: true, @@ -332,15 +331,15 @@ func TestConfig_Merge(t *testing.T) { TemplateConfig: &client.ClientTemplateConfig{ FunctionDenylist: client.DefaultTemplateFunctionDenylist, DisableSandbox: false, - BlockQueryWaitTime: pointer.Of(5 * time.Minute), - MaxStale: pointer.Of(client.DefaultTemplateMaxStale), + BlockQueryWaitTime: new(5 * time.Minute), + MaxStale: new(client.DefaultTemplateMaxStale), Wait: &client.WaitConfig{ - Min: pointer.Of(5 * time.Second), - Max: pointer.Of(4 * time.Minute), + Min: new(5 * time.Second), + Max: new(4 * time.Minute), }, - ConsulRetry: &client.RetryConfig{Attempts: pointer.Of(0)}, - VaultRetry: &client.RetryConfig{Attempts: pointer.Of(0)}, - NomadRetry: &client.RetryConfig{Attempts: pointer.Of(0)}, + ConsulRetry: &client.RetryConfig{Attempts: new(0)}, + VaultRetry: &client.RetryConfig{Attempts: new(0)}, + NomadRetry: &client.RetryConfig{Attempts: new(0)}, }, Reserved: &Resources{ CPU: 15, @@ -352,7 +351,7 @@ func TestConfig_Merge(t *testing.T) { GCParallelDestroys: 6, GCDiskUsageThreshold: 71, GCInodeUsageThreshold: 86, - NomadServiceDiscovery: pointer.Of(false), + NomadServiceDiscovery: new(false), }, Server: &ServerConfig{ Enabled: true, @@ -361,11 +360,11 @@ func TestConfig_Merge(t *testing.T) { DataDir: "/tmp/data2", ProtocolVersion: 2, RaftProtocol: 2, - RaftMultiplier: pointer.Of(6), - RaftSnapshotThreshold: pointer.Of(100), - RaftSnapshotInterval: pointer.Of("30m"), - RaftTrailingLogs: pointer.Of(200), - NumSchedulers: pointer.Of(2), + RaftMultiplier: new(6), + RaftSnapshotThreshold: new(100), + RaftSnapshotInterval: new("30m"), + RaftTrailingLogs: new(200), + NumSchedulers: new(2), EnabledSchedulers: []string{structs.JobTypeBatch}, NodeGCThreshold: "12h", BatchEvalGCThreshold: "4h", @@ -379,16 +378,16 @@ func TestConfig_Merge(t *testing.T) { NonVotingServer: true, RedundancyZone: "bar", UpgradeVersion: "bar", - EnableEventBroker: pointer.Of(true), - EventBufferSize: pointer.Of(100), + EnableEventBroker: new(true), + EventBufferSize: new(100), PlanRejectionTracker: &PlanRejectionTracker{ - Enabled: pointer.Of(true), + Enabled: new(true), NodeThreshold: 100, NodeWindow: 11 * time.Minute, }, - JobMaxPriority: pointer.Of(200), - JobDefaultPriority: pointer.Of(100), - JobMaxCount: pointer.Of(1000), + JobMaxPriority: new(200), + JobDefaultPriority: new(100), + JobMaxCount: new(1000), OIDCIssuer: "https://oidc.test.nomadproject.io", StartTimeout: "1m", }, @@ -492,7 +491,7 @@ func TestConfig_Merge(t *testing.T) { }, Reporting: &config.ReportingConfig{ License: &config.LicenseReportingConfig{ - Enabled: pointer.Of(true), + Enabled: new(true), }, }, Eventlog: &Eventlog{ @@ -1627,8 +1626,8 @@ func TestEventBroker_Parse(t *testing.T) { require := require.New(t) { a := &ServerConfig{ - EnableEventBroker: pointer.Of(false), - EventBufferSize: pointer.Of(0), + EnableEventBroker: new(false), + EventBufferSize: new(0), } b := DefaultConfig().Server b.EnableEventBroker = nil @@ -1641,8 +1640,8 @@ func TestEventBroker_Parse(t *testing.T) { { a := &ServerConfig{ - EnableEventBroker: pointer.Of(true), - EventBufferSize: pointer.Of(5000), + EnableEventBroker: new(true), + EventBufferSize: new(5000), } b := DefaultConfig().Server b.EnableEventBroker = nil @@ -1655,12 +1654,12 @@ func TestEventBroker_Parse(t *testing.T) { { a := &ServerConfig{ - EnableEventBroker: pointer.Of(false), - EventBufferSize: pointer.Of(0), + EnableEventBroker: new(false), + EventBufferSize: new(0), } b := DefaultConfig().Server - b.EnableEventBroker = pointer.Of(true) - b.EventBufferSize = pointer.Of(20000) + b.EnableEventBroker = new(true) + b.EventBufferSize = new(20000) result := a.Merge(b) require.Equal(true, *result.EnableEventBroker) @@ -1912,11 +1911,11 @@ func Test_mergeConsulConfigs(t *testing.T) { { ServiceIdentity: &config.WorkloadIdentityConfig{ Audience: []string{"consul.io"}, - TTL: pointer.Of(time.Hour), + TTL: new(time.Hour), }, TaskIdentity: &config.WorkloadIdentityConfig{ Audience: []string{"consul.io"}, - TTL: pointer.Of(time.Hour), + TTL: new(time.Hour), }, }, }, @@ -2010,7 +2009,7 @@ func Test_mergeClientFingerprinterConfigs(t *testing.T) { }, { Name: "env_gce", - ExitOnFailure: pointer.Of(false), + ExitOnFailure: new(false), }, } right := []*client.Fingerprint{ @@ -2022,11 +2021,11 @@ func Test_mergeClientFingerprinterConfigs(t *testing.T) { Name: "env_gce", RetryAttempts: 10, RetryInterval: 10 * time.Second, - ExitOnFailure: pointer.Of(true), + ExitOnFailure: new(true), }, { Name: "env_azure", - ExitOnFailure: pointer.Of(true), + ExitOnFailure: new(true), }, } @@ -2040,11 +2039,11 @@ func Test_mergeClientFingerprinterConfigs(t *testing.T) { Name: "env_gce", RetryAttempts: 10, RetryInterval: 10 * time.Second, - ExitOnFailure: pointer.Of(true), + ExitOnFailure: new(true), }, { Name: "env_azure", - ExitOnFailure: pointer.Of(true), + ExitOnFailure: new(true), }, }, mergeClientFingerprinterConfigs(left, right)) } diff --git a/command/agent/consul/connect_test.go b/command/agent/consul/connect_test.go index e829a8e2341..9a02c5b110d 100644 --- a/command/agent/consul/connect_test.go +++ b/command/agent/consul/connect_test.go @@ -9,7 +9,6 @@ import ( "github.com/hashicorp/consul/api" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/structs" "github.com/shoenig/test/must" @@ -546,7 +545,7 @@ func TestConnect_newConnectGateway(t *testing.T) { result := newConnectGateway(&structs.ConsulConnect{ Gateway: &structs.ConsulGateway{ Proxy: &structs.ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(1 * time.Second), + ConnectTimeout: new(1 * time.Second), EnvoyGatewayBindTaggedAddresses: false, EnvoyGatewayBindAddresses: nil, EnvoyGatewayNoDefaultBind: false, @@ -576,7 +575,7 @@ func TestConnect_newConnectGateway(t *testing.T) { result := newConnectGateway(&structs.ConsulConnect{ Gateway: &structs.ConsulGateway{ Proxy: &structs.ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(1 * time.Second), + ConnectTimeout: new(1 * time.Second), EnvoyGatewayBindTaggedAddresses: true, EnvoyGatewayBindAddresses: map[string]*structs.ConsulGatewayBindAddress{ "service1": { diff --git a/command/agent/http_test.go b/command/agent/http_test.go index dd9090e0279..0ce3ba8712a 100644 --- a/command/agent/http_test.go +++ b/command/agent/http_test.go @@ -26,7 +26,6 @@ import ( "github.com/hashicorp/nomad/acl" "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/testlog" "github.com/hashicorp/nomad/nomad" "github.com/hashicorp/nomad/nomad/mock" @@ -600,11 +599,11 @@ func TestParseBool(t *testing.T) { }, { Input: "true", - Expected: pointer.Of(true), + Expected: new(true), }, { Input: "false", - Expected: pointer.Of(false), + Expected: new(false), }, { Input: "1234", @@ -647,11 +646,11 @@ func Test_parseInt(t *testing.T) { }, { Input: "13", - Expected: pointer.Of(13), + Expected: new(13), }, { Input: "99", - Expected: pointer.Of(99), + Expected: new(99), }, { Input: "ten", @@ -1089,13 +1088,13 @@ func TestHTTPServer_Limits_Error(t *testing.T) { { tls: true, timeout: "5s", - limit: pointer.Of(-1), + limit: new(-1), expectedErr: "http_max_conns_per_client must be >= 0", }, { tls: false, timeout: "5s", - limit: pointer.Of(-1), + limit: new(-1), expectedErr: "http_max_conns_per_client must be >= 0", }, } @@ -1192,28 +1191,28 @@ func TestHTTPServer_Limits_OK(t *testing.T) { { tls: false, timeout: "0", - limit: pointer.Of(2), + limit: new(2), assertTimeout: false, assertLimit: true, }, { tls: true, timeout: "0", - limit: pointer.Of(2), + limit: new(2), assertTimeout: false, assertLimit: true, }, { tls: false, timeout: "5s", - limit: pointer.Of(2), + limit: new(2), assertTimeout: false, assertLimit: true, }, { tls: true, timeout: "5s", - limit: pointer.Of(2), + limit: new(2), assertTimeout: true, assertLimit: true, }, diff --git a/command/agent/job_endpoint.go b/command/agent/job_endpoint.go index d4baeb9f360..db1f61ae2bd 100644 --- a/command/agent/job_endpoint.go +++ b/command/agent/job_endpoint.go @@ -18,7 +18,6 @@ import ( "github.com/hashicorp/nomad/acl" api "github.com/hashicorp/nomad/api" cstructs "github.com/hashicorp/nomad/client/structs" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/jobspec2" "github.com/hashicorp/nomad/nomad/structs" ) @@ -1051,7 +1050,7 @@ func (s *HTTPServer) apiJobAndRequestToStructs(job *api.Job, req *http.Request, // the namespace to be correct queryNamespace := req.URL.Query().Get("namespace") namespace := namespaceForJob(job.Namespace, queryNamespace, writeReq.Namespace) - job.Namespace = pointer.Of(namespace) + job.Namespace = new(namespace) writeReq.Namespace = namespace sJob := ApiJobToStructJob(job) diff --git a/command/agent/job_endpoint_test.go b/command/agent/job_endpoint_test.go index 740126988c1..4f8e843bc98 100644 --- a/command/agent/job_endpoint_test.go +++ b/command/agent/job_endpoint_test.go @@ -17,7 +17,6 @@ import ( "github.com/hashicorp/nomad/acl" api "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" "github.com/shoenig/test/must" @@ -659,8 +658,8 @@ func TestHTTP_jobUpdate_systemScaling(t *testing.T) { httpTest(t, nil, func(s *TestAgent) { // Create the job job := MockJob() - job.Type = pointer.Of("system") - job.TaskGroups[0].Scaling = &api.ScalingPolicy{Enabled: pointer.Of(true)} + job.Type = new("system") + job.TaskGroups[0].Scaling = &api.ScalingPolicy{Enabled: new(true)} args := api.JobRegisterRequest{ Job: job, WriteRequest: api.WriteRequest{ @@ -1168,7 +1167,7 @@ func TestHTTP_Job_ScaleTaskGroup(t *testing.T) { newCount := job.TaskGroups[0].Count + 1 scaleReq := &api.ScalingRequest{ - Count: pointer.Of(int64(newCount)), + Count: new(int64(newCount)), Message: "testing", Target: map[string]string{ "Job": job.ID, @@ -2374,7 +2373,7 @@ func TestJobs_ParsingWriteRequest(t *testing.T) { srv.agent = &Agent{config: &Config{Region: agentRegion}} job := &api.Job{ - Region: pointer.Of(tc.jobRegion), + Region: new(tc.jobRegion), Multiregion: tc.multiregion, } @@ -2498,7 +2497,7 @@ func TestJobs_RegionForJob(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { job := &api.Job{ - Region: pointer.Of(tc.jobRegion), + Region: new(tc.jobRegion), Multiregion: tc.multiregion, } requestRegion, jobRegion := regionForJob( @@ -2692,15 +2691,15 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { ci.Parallel(t) apiJob := &api.Job{ - Stop: pointer.Of(true), - Region: pointer.Of("global"), - Namespace: pointer.Of("foo"), - ID: pointer.Of("foo"), - ParentID: pointer.Of("lol"), - Name: pointer.Of("name"), - Type: pointer.Of("service"), - Priority: pointer.Of(50), - AllAtOnce: pointer.Of(true), + Stop: new(true), + Region: new("global"), + Namespace: new("foo"), + ID: new("foo"), + ParentID: new("lol"), + Name: new("name"), + Type: new("service"), + Priority: new(50), + AllAtOnce: new(true), Datacenters: []string{"dc1", "dc2"}, Constraints: []*api.Constraint{ { @@ -2714,23 +2713,23 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { LTarget: "a", RTarget: "b", Operand: "c", - Weight: pointer.Of(int8(50)), + Weight: new(int8(50)), }, }, Update: &api.UpdateStrategy{ - Stagger: pointer.Of(1 * time.Second), - MaxParallel: pointer.Of(5), - HealthCheck: pointer.Of(structs.UpdateStrategyHealthCheck_Manual), - MinHealthyTime: pointer.Of(1 * time.Minute), - HealthyDeadline: pointer.Of(3 * time.Minute), - ProgressDeadline: pointer.Of(3 * time.Minute), - AutoRevert: pointer.Of(false), - Canary: pointer.Of(1), + Stagger: new(1 * time.Second), + MaxParallel: new(5), + HealthCheck: new(structs.UpdateStrategyHealthCheck_Manual), + MinHealthyTime: new(1 * time.Minute), + HealthyDeadline: new(3 * time.Minute), + ProgressDeadline: new(3 * time.Minute), + AutoRevert: new(false), + Canary: new(1), }, Spreads: []*api.Spread{ { Attribute: "${meta.rack}", - Weight: pointer.Of(int8(100)), + Weight: new(int8(100)), SpreadTarget: []*api.SpreadTarget{ { Value: "r1", @@ -2740,12 +2739,12 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { }, }, Periodic: &api.PeriodicConfig{ - Enabled: pointer.Of(true), - Spec: pointer.Of("spec"), + Enabled: new(true), + Spec: new("spec"), Specs: []string{"spec"}, - SpecType: pointer.Of("cron"), - ProhibitOverlap: pointer.Of(true), - TimeZone: pointer.Of("test zone"), + SpecType: new("cron"), + ProhibitOverlap: new(true), + TimeZone: new("test zone"), }, ParameterizedJob: &api.ParameterizedJobConfig{ Payload: "payload", @@ -2758,13 +2757,13 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { }, Multiregion: &api.Multiregion{ Strategy: &api.MultiregionStrategy{ - MaxParallel: pointer.Of(2), - OnFailure: pointer.Of("fail_all"), + MaxParallel: new(2), + OnFailure: new("fail_all"), }, Regions: []*api.MultiregionRegion{ { Name: "west", - Count: pointer.Of(1), + Count: new(1), Datacenters: []string{"dc1", "dc2"}, Meta: map[string]string{"region_code": "W"}, }, @@ -2772,8 +2771,8 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { }, TaskGroups: []*api.TaskGroup{ { - Name: pointer.Of("group1"), - Count: pointer.Of(5), + Name: new("group1"), + Count: new(5), Constraints: []*api.Constraint{ { LTarget: "x", @@ -2786,34 +2785,34 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { LTarget: "x", RTarget: "y", Operand: "z", - Weight: pointer.Of(int8(100)), + Weight: new(int8(100)), }, }, RestartPolicy: &api.RestartPolicy{ - Interval: pointer.Of(1 * time.Second), - Attempts: pointer.Of(5), - Delay: pointer.Of(10 * time.Second), - Mode: pointer.Of("delay"), - RenderTemplates: pointer.Of(false), + Interval: new(1 * time.Second), + Attempts: new(5), + Delay: new(10 * time.Second), + Mode: new("delay"), + RenderTemplates: new(false), }, ReschedulePolicy: &api.ReschedulePolicy{ - Interval: pointer.Of(12 * time.Hour), - Attempts: pointer.Of(5), - DelayFunction: pointer.Of("constant"), - Delay: pointer.Of(30 * time.Second), - Unlimited: pointer.Of(true), - MaxDelay: pointer.Of(20 * time.Minute), + Interval: new(12 * time.Hour), + Attempts: new(5), + DelayFunction: new("constant"), + Delay: new(30 * time.Second), + Unlimited: new(true), + MaxDelay: new(20 * time.Minute), }, Migrate: &api.MigrateStrategy{ - MaxParallel: pointer.Of(12), - HealthCheck: pointer.Of("task_events"), - MinHealthyTime: pointer.Of(12 * time.Hour), - HealthyDeadline: pointer.Of(12 * time.Hour), + MaxParallel: new(12), + HealthCheck: new("task_events"), + MinHealthyTime: new(12 * time.Hour), + HealthyDeadline: new(12 * time.Hour), }, Spreads: []*api.Spread{ { Attribute: "${node.datacenter}", - Weight: pointer.Of(int8(100)), + Weight: new(int8(100)), SpreadTarget: []*api.SpreadTarget{ { Value: "dc1", @@ -2823,16 +2822,16 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { }, }, EphemeralDisk: &api.EphemeralDisk{ - SizeMB: pointer.Of(100), - Sticky: pointer.Of(true), - Migrate: pointer.Of(true), + SizeMB: new(100), + Sticky: new(true), + Migrate: new(true), }, Update: &api.UpdateStrategy{ - HealthCheck: pointer.Of(structs.UpdateStrategyHealthCheck_Checks), - MinHealthyTime: pointer.Of(2 * time.Minute), - HealthyDeadline: pointer.Of(5 * time.Minute), - ProgressDeadline: pointer.Of(5 * time.Minute), - AutoRevert: pointer.Of(true), + HealthCheck: new(structs.UpdateStrategyHealthCheck_Checks), + MinHealthyTime: new(2 * time.Minute), + HealthyDeadline: new(5 * time.Minute), + ProgressDeadline: new(5 * time.Minute), + AutoRevert: new(true), }, Meta: map[string]string{ "key": "value", @@ -2860,7 +2859,7 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { }, CheckRestart: &api.CheckRestart{ Limit: 4, - Grace: pointer.Of(11 * time.Second), + Grace: new(11 * time.Second), }, Checks: []api.ServiceCheck{ { @@ -2905,7 +2904,7 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { }, }, Disconnect: &api.DisconnectStrategy{ - LostAfter: pointer.Of(30 * time.Second), + LostAfter: new(30 * time.Second), }, Tasks: []*api.Task{ { @@ -2931,7 +2930,7 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { LTarget: "a", RTarget: "b", Operand: "c", - Weight: pointer.Of(int8(50)), + Weight: new(int8(50)), }, }, Identities: []*api.WorkloadIdentity{ @@ -2946,18 +2945,18 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { }, VolumeMounts: []*api.VolumeMount{ { - Volume: pointer.Of("vol"), - Destination: pointer.Of("dest"), - ReadOnly: pointer.Of(false), - PropagationMode: pointer.Of("a"), + Volume: new("vol"), + Destination: new("dest"), + ReadOnly: new(false), + PropagationMode: new("a"), }, }, RestartPolicy: &api.RestartPolicy{ - Interval: pointer.Of(2 * time.Second), - Attempts: pointer.Of(10), - Delay: pointer.Of(20 * time.Second), - Mode: pointer.Of("delay"), - RenderTemplates: pointer.Of(false), + Interval: new(2 * time.Second), + Attempts: new(10), + Delay: new(20 * time.Second), + Mode: new("delay"), + RenderTemplates: new(false), }, Services: []*api.Service{ { @@ -2976,7 +2975,7 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { }, CheckRestart: &api.CheckRestart{ Limit: 4, - Grace: pointer.Of(11 * time.Second), + Grace: new(11 * time.Second), }, Checks: []api.ServiceCheck{ { @@ -3013,12 +3012,12 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { }, }, Resources: &api.Resources{ - CPU: pointer.Of(100), - MemoryMB: pointer.Of(10), + CPU: new(100), + MemoryMB: new(10), Networks: []*api.NetworkResource{ { IP: "10.10.11.1", - MBits: pointer.Of(10), + MBits: new(10), Hostname: "foobar", ReservedPorts: []api.Port{ { @@ -3037,7 +3036,7 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { Devices: []*api.RequestedDevice{ { Name: "nvidia/gpu", - Count: pointer.Of(uint64(4)), + Count: new(uint64(4)), Constraints: []*api.Constraint{ { LTarget: "x", @@ -3050,7 +3049,7 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { LTarget: "a", RTarget: "b", Operand: "c", - Weight: pointer.Of(int8(50)), + Weight: new(int8(50)), }, }, }, @@ -3063,58 +3062,58 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { Meta: map[string]string{ "lol": "code", }, - KillTimeout: pointer.Of(10 * time.Second), + KillTimeout: new(10 * time.Second), KillSignal: "SIGQUIT", LogConfig: &api.LogConfig{ - Disabled: pointer.Of(true), - MaxFiles: pointer.Of(10), - MaxFileSizeMB: pointer.Of(100), + Disabled: new(true), + MaxFiles: new(10), + MaxFileSizeMB: new(100), }, Artifacts: []*api.TaskArtifact{ { - GetterSource: pointer.Of("source"), + GetterSource: new("source"), GetterOptions: map[string]string{ "a": "b", }, - GetterMode: pointer.Of("dir"), - RelativeDest: pointer.Of("dest"), + GetterMode: new("dir"), + RelativeDest: new("dest"), Chown: true, }, }, Vault: &api.Vault{ Role: "nomad-task", - Namespace: pointer.Of("ns1"), + Namespace: new("ns1"), Policies: []string{"a", "b", "c"}, - Env: pointer.Of(true), - DisableFile: pointer.Of(false), - ChangeMode: pointer.Of("c"), - ChangeSignal: pointer.Of("sighup"), + Env: new(true), + DisableFile: new(false), + ChangeMode: new("c"), + ChangeSignal: new("sighup"), }, Templates: []*api.Template{ { - SourcePath: pointer.Of("source"), - DestPath: pointer.Of("dest"), - EmbeddedTmpl: pointer.Of("embedded"), - ChangeMode: pointer.Of("change"), - ChangeSignal: pointer.Of("signal"), + SourcePath: new("source"), + DestPath: new("dest"), + EmbeddedTmpl: new("embedded"), + ChangeMode: new("change"), + ChangeSignal: new("signal"), ChangeScript: &api.ChangeScript{ - Command: pointer.Of("/bin/foo"), + Command: new("/bin/foo"), Args: []string{"-h"}, - Timeout: pointer.Of(5 * time.Second), - FailOnError: pointer.Of(false), + Timeout: new(5 * time.Second), + FailOnError: new(false), }, - Splay: pointer.Of(1 * time.Minute), - Perms: pointer.Of("666"), - Uid: pointer.Of(1000), - Gid: pointer.Of(1000), - LeftDelim: pointer.Of("abc"), - RightDelim: pointer.Of("def"), - Envvars: pointer.Of(true), + Splay: new(1 * time.Minute), + Perms: new("666"), + Uid: new(1000), + Gid: new(1000), + LeftDelim: new("abc"), + RightDelim: new("def"), + Envvars: new(true), Wait: &api.WaitConfig{ - Min: pointer.Of(5 * time.Second), - Max: pointer.Of(10 * time.Second), + Min: new(5 * time.Second), + Max: new(10 * time.Second), }, - ErrMissingKey: pointer.Of(true), + ErrMissingKey: new(true), }, }, DispatchPayload: &api.DispatchPayloadConfig{ @@ -3124,13 +3123,13 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { }, }, }, - VaultNamespace: pointer.Of("ghi789"), - Status: pointer.Of("status"), - StatusDescription: pointer.Of("status_desc"), - Version: pointer.Of(uint64(10)), - CreateIndex: pointer.Of(uint64(1)), - ModifyIndex: pointer.Of(uint64(3)), - JobModifyIndex: pointer.Of(uint64(5)), + VaultNamespace: new("ghi789"), + Status: new("status"), + StatusDescription: new("status_desc"), + Version: new(uint64(10)), + CreateIndex: new(uint64(1)), + ModifyIndex: new(uint64(3)), + JobModifyIndex: new(uint64(5)), } expected := &structs.Job{ @@ -3350,7 +3349,7 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { }, Disconnect: &structs.DisconnectStrategy{ LostAfter: 30 * time.Second, - Replace: pointer.Of(true), + Replace: new(true), Reconcile: structs.ReconcileOptionBestScore, }, Tasks: []*structs.Task{ @@ -3559,14 +3558,14 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { }, Splay: 1 * time.Minute, Perms: "666", - Uid: pointer.Of(1000), - Gid: pointer.Of(1000), + Uid: new(1000), + Gid: new(1000), LeftDelim: "abc", RightDelim: "def", Envvars: true, Wait: &structs.WaitConfig{ - Min: pointer.Of(5 * time.Second), - Max: pointer.Of(10 * time.Second), + Min: new(5 * time.Second), + Max: new(10 * time.Second), }, ErrMissingKey: true, }, @@ -3586,17 +3585,17 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { must.Eq(t, expected, structsJob) systemAPIJob := &api.Job{ - Stop: pointer.Of(true), - Region: pointer.Of("global"), - Namespace: pointer.Of("foo"), - ID: pointer.Of("foo"), - ParentID: pointer.Of("lol"), - Name: pointer.Of("name"), - Type: pointer.Of("system"), - Priority: pointer.Of(50), - AllAtOnce: pointer.Of(true), + Stop: new(true), + Region: new("global"), + Namespace: new("foo"), + ID: new("foo"), + ParentID: new("lol"), + Name: new("name"), + Type: new("system"), + Priority: new(50), + AllAtOnce: new(true), Datacenters: []string{"dc1", "dc2"}, - NodePool: pointer.Of("default"), + NodePool: new("default"), Constraints: []*api.Constraint{ { LTarget: "a", @@ -3606,8 +3605,8 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { }, TaskGroups: []*api.TaskGroup{ { - Name: pointer.Of("group1"), - Count: pointer.Of(5), + Name: new("group1"), + Count: new(5), Constraints: []*api.Constraint{ { LTarget: "x", @@ -3616,16 +3615,16 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { }, }, RestartPolicy: &api.RestartPolicy{ - Interval: pointer.Of(1 * time.Second), - Attempts: pointer.Of(5), - Delay: pointer.Of(10 * time.Second), - Mode: pointer.Of("delay"), - RenderTemplates: pointer.Of(false), + Interval: new(1 * time.Second), + Attempts: new(5), + Delay: new(10 * time.Second), + Mode: new("delay"), + RenderTemplates: new(false), }, EphemeralDisk: &api.EphemeralDisk{ - SizeMB: pointer.Of(100), - Sticky: pointer.Of(true), - Migrate: pointer.Of(true), + SizeMB: new(100), + Sticky: new(true), + Migrate: new(true), }, Meta: map[string]string{ "key": "value", @@ -3653,12 +3652,12 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { }, }, Resources: &api.Resources{ - CPU: pointer.Of(100), - MemoryMB: pointer.Of(10), + CPU: new(100), + MemoryMB: new(10), Networks: []*api.NetworkResource{ { IP: "10.10.11.1", - MBits: pointer.Of(10), + MBits: new(10), ReservedPorts: []api.Port{ { Label: "http", @@ -3677,20 +3676,20 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { Meta: map[string]string{ "lol": "code", }, - KillTimeout: pointer.Of(10 * time.Second), + KillTimeout: new(10 * time.Second), KillSignal: "SIGQUIT", LogConfig: &api.LogConfig{ - Disabled: pointer.Of(true), - MaxFiles: pointer.Of(10), - MaxFileSizeMB: pointer.Of(100), + Disabled: new(true), + MaxFiles: new(10), + MaxFileSizeMB: new(100), }, Artifacts: []*api.TaskArtifact{ { - GetterSource: pointer.Of("source"), + GetterSource: new("source"), GetterOptions: map[string]string{"a": "b"}, GetterHeaders: map[string]string{"User-Agent": "nomad"}, - GetterMode: pointer.Of("dir"), - RelativeDest: pointer.Of("dest"), + GetterMode: new("dir"), + RelativeDest: new("dest"), }, }, DispatchPayload: &api.DispatchPayloadConfig{ @@ -3700,12 +3699,12 @@ func TestJobs_ApiJobToStructsJob(t *testing.T) { }, }, }, - Status: pointer.Of("status"), - StatusDescription: pointer.Of("status_desc"), - Version: pointer.Of(uint64(10)), - CreateIndex: pointer.Of(uint64(1)), - ModifyIndex: pointer.Of(uint64(3)), - JobModifyIndex: pointer.Of(uint64(5)), + Status: new("status"), + StatusDescription: new("status_desc"), + Version: new(uint64(10)), + CreateIndex: new(uint64(1)), + ModifyIndex: new(uint64(3)), + JobModifyIndex: new(uint64(5)), } expectedSystemJob := &structs.Job{ @@ -3857,26 +3856,26 @@ func TestJobs_ApiJobToStructsJobUpdate(t *testing.T) { apiJob := &api.Job{ Update: &api.UpdateStrategy{ - Stagger: pointer.Of(1 * time.Second), - MaxParallel: pointer.Of(5), - HealthCheck: pointer.Of(structs.UpdateStrategyHealthCheck_Manual), - MinHealthyTime: pointer.Of(1 * time.Minute), - HealthyDeadline: pointer.Of(3 * time.Minute), - ProgressDeadline: pointer.Of(3 * time.Minute), - AutoRevert: pointer.Of(false), + Stagger: new(1 * time.Second), + MaxParallel: new(5), + HealthCheck: new(structs.UpdateStrategyHealthCheck_Manual), + MinHealthyTime: new(1 * time.Minute), + HealthyDeadline: new(3 * time.Minute), + ProgressDeadline: new(3 * time.Minute), + AutoRevert: new(false), AutoPromote: nil, - Canary: pointer.Of(1), + Canary: new(1), }, TaskGroups: []*api.TaskGroup{ { Update: &api.UpdateStrategy{ - Canary: pointer.Of(2), - AutoRevert: pointer.Of(true), + Canary: new(2), + AutoRevert: new(true), }, }, { Update: &api.UpdateStrategy{ - Canary: pointer.Of(3), - AutoPromote: pointer.Of(true), + Canary: new(3), + AutoPromote: new(true), }, }, }, @@ -3952,16 +3951,16 @@ func TestHTTP_JobValidate_SystemMigrate(t *testing.T) { httpTest(t, nil, func(s *TestAgent) { // Create the job job := &api.Job{ - Region: pointer.Of("global"), + Region: new("global"), Datacenters: []string{"dc1"}, - ID: pointer.Of("systemmigrate"), - Name: pointer.Of("systemmigrate"), + ID: new("systemmigrate"), + Name: new("systemmigrate"), TaskGroups: []*api.TaskGroup{ - {Name: pointer.Of("web")}, + {Name: new("web")}, }, // System job... - Type: pointer.Of("system"), + Type: new("system"), // ...with an empty migrate block Migrate: &api.MigrateStrategy{}, @@ -3992,7 +3991,7 @@ func TestHTTP_JobValidate_SystemMigrate(t *testing.T) { func TestConversion_dereferenceInt(t *testing.T) { ci.Parallel(t) require.Equal(t, 0, dereferenceInt(nil)) - require.Equal(t, 42, dereferenceInt(pointer.Of(42))) + require.Equal(t, 42, dereferenceInt(new(42))) } func TestConversion_apiLogConfigToStructs(t *testing.T) { @@ -4003,31 +4002,31 @@ func TestConversion_apiLogConfigToStructs(t *testing.T) { MaxFiles: 2, MaxFileSizeMB: 8, }, apiLogConfigToStructs(&api.LogConfig{ - Disabled: pointer.Of(true), - MaxFiles: pointer.Of(2), - MaxFileSizeMB: pointer.Of(8), + Disabled: new(true), + MaxFiles: new(2), + MaxFileSizeMB: new(8), })) // COMPAT(1.6.0): verify backwards compatibility fixes // Note: we're intentionally ignoring the Enabled: false case must.Eq(t, &structs.LogConfig{Disabled: false}, apiLogConfigToStructs(&api.LogConfig{ - Enabled: pointer.Of(false), + Enabled: new(false), })) must.Eq(t, &structs.LogConfig{Disabled: false}, apiLogConfigToStructs(&api.LogConfig{ - Enabled: pointer.Of(true), + Enabled: new(true), })) must.Eq(t, &structs.LogConfig{Disabled: false}, apiLogConfigToStructs(&api.LogConfig{})) must.Eq(t, &structs.LogConfig{Disabled: false}, apiLogConfigToStructs(&api.LogConfig{ - Disabled: pointer.Of(false), + Disabled: new(false), })) must.Eq(t, &structs.LogConfig{Disabled: false}, apiLogConfigToStructs(&api.LogConfig{ - Enabled: pointer.Of(false), - Disabled: pointer.Of(false), + Enabled: new(false), + Disabled: new(false), })) } @@ -4048,8 +4047,8 @@ func TestConversion_apiResourcesToStructs(t *testing.T) { { "plain", &api.Resources{ - CPU: pointer.Of(100), - MemoryMB: pointer.Of(200), + CPU: new(100), + MemoryMB: new(200), }, &structs.Resources{ CPU: 100, @@ -4059,9 +4058,9 @@ func TestConversion_apiResourcesToStructs(t *testing.T) { { "with memory max", &api.Resources{ - CPU: pointer.Of(100), - MemoryMB: pointer.Of(200), - MemoryMaxMB: pointer.Of(300), + CPU: new(100), + MemoryMB: new(200), + MemoryMaxMB: new(300), }, &structs.Resources{ CPU: 100, @@ -4072,8 +4071,8 @@ func TestConversion_apiResourcesToStructs(t *testing.T) { { "with numa", &api.Resources{ - CPU: pointer.Of(100), - MemoryMB: pointer.Of(200), + CPU: new(100), + MemoryMB: new(200), NUMA: &api.NUMAResource{ Affinity: "prefer", }, @@ -4174,8 +4173,8 @@ func TestConversion_apiConnectSidecarTaskToStructs(t *testing.T) { Config: config, Env: env, Resources: &api.Resources{ - CPU: pointer.Of(1), - MemoryMB: pointer.Of(128), + CPU: new(1), + MemoryMB: new(128), }, Identities: []*api.WorkloadIdentity{{ Name: "myname", @@ -4191,19 +4190,19 @@ func TestConversion_apiConnectSidecarTaskToStructs(t *testing.T) { Meta: meta, KillTimeout: &timeout, LogConfig: &api.LogConfig{ - Disabled: pointer.Of(true), - MaxFiles: pointer.Of(2), - MaxFileSizeMB: pointer.Of(8), + Disabled: new(true), + MaxFiles: new(2), + MaxFileSizeMB: new(8), }, ShutdownDelay: &delay, KillSignal: "SIGTERM", VolumeMounts: []*api.VolumeMount{ { - Volume: pointer.Of("vol0"), - Destination: pointer.Of("/local/foo"), - ReadOnly: pointer.Of(true), - PropagationMode: pointer.Of("private"), - SELinuxLabel: pointer.Of("Z"), + Volume: new("vol0"), + Destination: new("/local/foo"), + ReadOnly: new(true), + PropagationMode: new("private"), + SELinuxLabel: new("Z"), }, }, })) @@ -4222,11 +4221,11 @@ func TestConversion_apiVolumeMountsToStructs(t *testing.T) { }, }, apiVolumeMountsToStructs([]*api.VolumeMount{ { - Volume: pointer.Of("vol0"), - Destination: pointer.Of("/local/foo"), - ReadOnly: pointer.Of(true), - PropagationMode: pointer.Of("private"), - SELinuxLabel: pointer.Of("Z"), + Volume: new("vol0"), + Destination: new("/local/foo"), + ReadOnly: new(true), + PropagationMode: new("private"), + SELinuxLabel: new("Z"), }, })) } @@ -4372,7 +4371,7 @@ func TestConversion_ApiConsulConnectToStructs(t *testing.T) { require.Equal(t, &structs.ConsulConnect{ Gateway: &structs.ConsulGateway{ Proxy: &structs.ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(3 * time.Second), + ConnectTimeout: new(3 * time.Second), EnvoyGatewayBindTaggedAddresses: true, EnvoyGatewayBindAddresses: map[string]*structs.ConsulGatewayBindAddress{ "service": { @@ -4389,7 +4388,7 @@ func TestConversion_ApiConsulConnectToStructs(t *testing.T) { }, ApiConsulConnectToStructs(&api.ConsulConnect{ Gateway: &api.ConsulGateway{ Proxy: &api.ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(3 * time.Second), + ConnectTimeout: new(3 * time.Second), EnvoyGatewayBindTaggedAddresses: true, EnvoyGatewayBindAddresses: map[string]*api.ConsulGatewayBindAddress{ "service": { @@ -4447,9 +4446,9 @@ func TestConversion_ApiConsulConnectToStructs(t *testing.T) { }, Remove: []string{"test2"}, }, - MaxConnections: pointer.Of(uint32(5120)), - MaxPendingRequests: pointer.Of(uint32(512)), - MaxConcurrentRequests: pointer.Of(uint32(2048)), + MaxConnections: new(uint32(5120)), + MaxPendingRequests: new(uint32(512)), + MaxConcurrentRequests: new(uint32(2048)), }}, }}, }, @@ -4494,9 +4493,9 @@ func TestConversion_ApiConsulConnectToStructs(t *testing.T) { }, Remove: []string{"test2"}, }, - MaxConnections: pointer.Of(uint32(5120)), - MaxPendingRequests: pointer.Of(uint32(512)), - MaxConcurrentRequests: pointer.Of(uint32(2048)), + MaxConnections: new(uint32(5120)), + MaxPendingRequests: new(uint32(512)), + MaxConcurrentRequests: new(uint32(2048)), }}, }}, }, diff --git a/command/agent/operator_endpoint_test.go b/command/agent/operator_endpoint_test.go index 8e76c61c256..8882e1b8080 100644 --- a/command/agent/operator_endpoint_test.go +++ b/command/agent/operator_endpoint_test.go @@ -19,7 +19,6 @@ import ( "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" @@ -78,7 +77,7 @@ func TestHTTP_OperatorRaftTransferLeadership(t *testing.T) { ci.Parallel(t) configCB := func(c *Config) { c.Client.Enabled = false - c.Server.NumSchedulers = pointer.Of(0) + c.Server.NumSchedulers = new(0) } httpTest(t, configCB, func(s *TestAgent) { @@ -702,7 +701,7 @@ func TestOperator_SnapshotRequests(t *testing.T) { func TestOperator_UpgradeCheckRequest_VaultWorkloadIdentity(t *testing.T) { ci.Parallel(t) httpTest(t, func(c *Config) { - c.Vaults[0].Enabled = pointer.Of(true) + c.Vaults[0].Enabled = new(true) c.Vaults[0].Name = "default" }, func(s *TestAgent) { // Create a test job with a Vault block but without an identity. diff --git a/command/agent/testingutils_test.go b/command/agent/testingutils_test.go index 6482134dbf1..26b9ae6e776 100644 --- a/command/agent/testingutils_test.go +++ b/command/agent/testingutils_test.go @@ -7,18 +7,17 @@ import ( "time" "github.com/hashicorp/nomad/api" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" ) func MockJob() *api.Job { job := &api.Job{ - Region: pointer.Of("global"), - ID: pointer.Of(uuid.Generate()), - Name: pointer.Of("my-job"), - Type: pointer.Of("service"), - Priority: pointer.Of(50), - AllAtOnce: pointer.Of(false), + Region: new("global"), + ID: new(uuid.Generate()), + Name: new("my-job"), + Type: new("service"), + Priority: new(50), + AllAtOnce: new(false), Datacenters: []string{"dc1"}, Constraints: []*api.Constraint{ { @@ -29,17 +28,17 @@ func MockJob() *api.Job { }, TaskGroups: []*api.TaskGroup{ { - Name: pointer.Of("web"), - Count: pointer.Of(10), + Name: new("web"), + Count: new(10), EphemeralDisk: &api.EphemeralDisk{ - SizeMB: pointer.Of(150), + SizeMB: new(150), }, RestartPolicy: &api.RestartPolicy{ - Attempts: pointer.Of(3), - Interval: pointer.Of(10 * time.Minute), - Delay: pointer.Of(1 * time.Minute), - Mode: pointer.Of("delay"), - RenderTemplates: pointer.Of(false), + Attempts: new(3), + Interval: new(10 * time.Minute), + Delay: new(1 * time.Minute), + Mode: new("delay"), + RenderTemplates: new(false), }, Networks: []*api.NetworkResource{ { @@ -93,8 +92,8 @@ func MockJob() *api.Job { }, LogConfig: api.DefaultLogConfig(), Resources: &api.Resources{ - CPU: pointer.Of(500), - MemoryMB: pointer.Of(256), + CPU: new(500), + MemoryMB: new(256), }, Meta: map[string]string{ "foo": "bar", @@ -118,7 +117,7 @@ func MockJob() *api.Job { func MockRegionalJob() *api.Job { j := MockJob() - j.Region = pointer.Of("north-america") + j.Region = new("north-america") return j } @@ -130,7 +129,7 @@ func MockRunnableJob() *api.Job { // Configure job so it can be run on a TestAgent job.Constraints = nil job.TaskGroups[0].Constraints = nil - job.TaskGroups[0].Count = pointer.Of(1) + job.TaskGroups[0].Count = new(1) job.TaskGroups[0].Tasks[0].Driver = "mock_driver" job.TaskGroups[0].Tasks[0].Services = nil job.TaskGroups[0].Tasks[0].Config = map[string]interface{}{ diff --git a/command/alloc_stop_test.go b/command/alloc_stop_test.go index 73d35efa8a0..b3f9cdd9a29 100644 --- a/command/alloc_stop_test.go +++ b/command/alloc_stop_test.go @@ -9,7 +9,6 @@ import ( "github.com/hashicorp/cli" "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/shoenig/test/must" ) @@ -79,7 +78,7 @@ func TestAllocStop_Run(t *testing.T) { jobID := "job1_sfx" job1 := testJob(jobID) - job1.Type = pointer.Of("sysbatch") + job1.Type = new("sysbatch") resp, _, err := client.Jobs().Register(job1, nil) must.NoError(t, err) diff --git a/command/eval_status_test.go b/command/eval_status_test.go index d36ac3d1feb..7922e166193 100644 --- a/command/eval_status_test.go +++ b/command/eval_status_test.go @@ -11,7 +11,6 @@ import ( "github.com/hashicorp/cli" "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" @@ -143,7 +142,7 @@ func TestEvalStatusCommand_Format(t *testing.T) { DimensionExhausted: map[string]int{"memory": 2}, QuotaExhausted: []string{}, ResourcesExhausted: map[string]*api.Resources{"web": { - Cores: pointer.Of(3), + Cores: new(3), }}, Scores: map[string]float64{}, AllocationTime: 0, diff --git a/command/helper_devices_test.go b/command/helper_devices_test.go index ad083e44a20..66d19261200 100644 --- a/command/helper_devices_test.go +++ b/command/helper_devices_test.go @@ -8,7 +8,6 @@ import ( "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/shoenig/test/must" ) @@ -31,12 +30,12 @@ func TestBuildDeviceStatsSummaryMap(t *testing.T) { InstanceStats: map[string]*api.DeviceStats{ "id1": { Summary: &api.StatValue{ - StringVal: pointer.Of("stat1"), + StringVal: new("stat1"), }, }, "id2": { Summary: &api.StatValue{ - IntNumeratorVal: pointer.Of(int64(2)), + IntNumeratorVal: new(int64(2)), }, }, }, @@ -47,12 +46,12 @@ func TestBuildDeviceStatsSummaryMap(t *testing.T) { InstanceStats: map[string]*api.DeviceStats{ "id1": { Summary: &api.StatValue{ - StringVal: pointer.Of("stat3"), + StringVal: new("stat3"), }, }, "id2": { Summary: &api.StatValue{ - IntNumeratorVal: pointer.Of(int64(4)), + IntNumeratorVal: new(int64(4)), }, }, }, @@ -61,16 +60,16 @@ func TestBuildDeviceStatsSummaryMap(t *testing.T) { expected := map[string]*api.StatValue{ "vendor1/type1/name1[id1]": { - StringVal: pointer.Of("stat1"), + StringVal: new("stat1"), }, "vendor1/type1/name1[id2]": { - IntNumeratorVal: pointer.Of(int64(2)), + IntNumeratorVal: new(int64(2)), }, "vendor2/type2[id1]": { - StringVal: pointer.Of("stat3"), + StringVal: new("stat3"), }, "vendor2/type2[id2]": { - IntNumeratorVal: pointer.Of(int64(4)), + IntNumeratorVal: new(int64(4)), }, } @@ -84,7 +83,7 @@ func TestFormatDeviceStats(t *testing.T) { statValue := func(v string) *api.StatValue { return &api.StatValue{ - StringVal: pointer.Of(v), + StringVal: new(v), } } @@ -147,12 +146,12 @@ func TestNodeStatusCommand_GetDeviceResourcesForNode(t *testing.T) { InstanceStats: map[string]*api.DeviceStats{ "id1": { Summary: &api.StatValue{ - StringVal: pointer.Of("stat1"), + StringVal: new("stat1"), }, }, "id2": { Summary: &api.StatValue{ - IntNumeratorVal: pointer.Of(int64(2)), + IntNumeratorVal: new(int64(2)), }, }, }, @@ -163,12 +162,12 @@ func TestNodeStatusCommand_GetDeviceResourcesForNode(t *testing.T) { InstanceStats: map[string]*api.DeviceStats{ "id1": { Summary: &api.StatValue{ - StringVal: pointer.Of("stat3"), + StringVal: new("stat3"), }, }, "id2": { Summary: &api.StatValue{ - IntNumeratorVal: pointer.Of(int64(4)), + IntNumeratorVal: new(int64(4)), }, }, }, @@ -221,12 +220,12 @@ func TestNodeStatusCommand_GetDeviceResources(t *testing.T) { InstanceStats: map[string]*api.DeviceStats{ "id1": { Summary: &api.StatValue{ - StringVal: pointer.Of("stat1"), + StringVal: new("stat1"), }, }, "id2": { Summary: &api.StatValue{ - IntNumeratorVal: pointer.Of(int64(2)), + IntNumeratorVal: new(int64(2)), }, }, }, @@ -237,12 +236,12 @@ func TestNodeStatusCommand_GetDeviceResources(t *testing.T) { InstanceStats: map[string]*api.DeviceStats{ "id1": { Summary: &api.StatValue{ - StringVal: pointer.Of("stat3"), + StringVal: new("stat3"), }, }, "id2": { Summary: &api.StatValue{ - IntNumeratorVal: pointer.Of(int64(4)), + IntNumeratorVal: new(int64(4)), }, }, }, @@ -269,11 +268,11 @@ func TestGetDeviceAttributes(t *testing.T) { Attributes: map[string]*api.Attribute{ "utilization": { - FloatVal: pointer.Of(float64(0.78)), + FloatVal: new(float64(0.78)), Unit: "%", }, "filesystem": { - StringVal: pointer.Of("ext4"), + StringVal: new("ext4"), }, }, } diff --git a/command/helpers_test.go b/command/helpers_test.go index b9acb5d42c8..dd942122357 100644 --- a/command/helpers_test.go +++ b/command/helpers_test.go @@ -21,7 +21,6 @@ import ( "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/client/testutil" "github.com/hashicorp/nomad/helper/flatmap" - "github.com/hashicorp/nomad/helper/pointer" "github.com/kr/pretty" "github.com/shoenig/test/must" ) @@ -235,19 +234,19 @@ const ( var ( expectedApiJob = &api.Job{ - ID: pointer.Of("job1"), - Name: pointer.Of("job1"), - Type: pointer.Of("service"), + ID: new("job1"), + Name: new("job1"), + Type: new("service"), Datacenters: []string{"dc1"}, TaskGroups: []*api.TaskGroup{ { - Name: pointer.Of("group1"), - Count: pointer.Of(1), + Name: new("group1"), + Count: new(1), RestartPolicy: &api.RestartPolicy{ - Attempts: pointer.Of(10), - Interval: pointer.Of(15 * time.Second), - Mode: pointer.Of("delay"), - RenderTemplates: pointer.Of(false), + Attempts: new(10), + Interval: new(15 * time.Second), + Mode: new("delay"), + RenderTemplates: new(false), }, Tasks: []*api.Task{ diff --git a/command/job_periodic_force_test.go b/command/job_periodic_force_test.go index 6776e49e361..64dd7110ce2 100644 --- a/command/job_periodic_force_test.go +++ b/command/job_periodic_force_test.go @@ -11,7 +11,6 @@ import ( "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/command/agent" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" "github.com/hashicorp/nomad/testutil" @@ -140,10 +139,10 @@ func TestJobPeriodicForceCommand_SuccessfulPeriodicForceDetach(t *testing.T) { // Register a job j := testJob("job1_is_periodic") j.Periodic = &api.PeriodicConfig{ - SpecType: pointer.Of(api.PeriodicSpecCron), - Spec: pointer.Of("*/15 * * * * *"), - ProhibitOverlap: pointer.Of(true), - TimeZone: pointer.Of("Europe/Minsk"), + SpecType: new(api.PeriodicSpecCron), + Spec: new("*/15 * * * * *"), + ProhibitOverlap: new(true), + TimeZone: new("Europe/Minsk"), } ui := cli.NewMockUi() @@ -182,10 +181,10 @@ func TestJobPeriodicForceCommand_SuccessfulPeriodicForce(t *testing.T) { // Register a job j := testJob("job2_is_periodic") j.Periodic = &api.PeriodicConfig{ - SpecType: pointer.Of(api.PeriodicSpecCron), - Spec: pointer.Of("*/15 * * * * *"), - ProhibitOverlap: pointer.Of(true), - TimeZone: pointer.Of("Europe/Minsk"), + SpecType: new(api.PeriodicSpecCron), + Spec: new("*/15 * * * * *"), + ProhibitOverlap: new(true), + TimeZone: new("Europe/Minsk"), } ui := cli.NewMockUi() @@ -223,17 +222,17 @@ func TestJobPeriodicForceCommand_SuccessfulIfJobIDEqualsPrefix(t *testing.T) { j1 := testJob("periodic-prefix") j1.Periodic = &api.PeriodicConfig{ - SpecType: pointer.Of(api.PeriodicSpecCron), - Spec: pointer.Of("*/15 * * * * *"), - ProhibitOverlap: pointer.Of(true), - TimeZone: pointer.Of("Europe/Minsk"), + SpecType: new(api.PeriodicSpecCron), + Spec: new("*/15 * * * * *"), + ProhibitOverlap: new(true), + TimeZone: new("Europe/Minsk"), } j2 := testJob("periodic-prefix-another-job") j2.Periodic = &api.PeriodicConfig{ - SpecType: pointer.Of(api.PeriodicSpecCron), - Spec: pointer.Of("*/15 * * * * *"), - ProhibitOverlap: pointer.Of(true), - TimeZone: pointer.Of("Europe/Minsk"), + SpecType: new(api.PeriodicSpecCron), + Spec: new("*/15 * * * * *"), + ProhibitOverlap: new(true), + TimeZone: new("Europe/Minsk"), } ui := cli.NewMockUi() @@ -265,8 +264,8 @@ func TestJobPeriodicForceCommand_ACL(t *testing.T) { jobID := "test_job_periodic_force_acl" job := testJob(jobID) job.Periodic = &api.PeriodicConfig{ - SpecType: pointer.Of(api.PeriodicSpecCron), - Spec: pointer.Of("*/15 * * * * *"), + SpecType: new(api.PeriodicSpecCron), + Spec: new("*/15 * * * * *"), } rootTokenOpts := &api.WriteOptions{ diff --git a/command/job_plan.go b/command/job_plan.go index 607d463355d..7c30359ee3e 100644 --- a/command/job_plan.go +++ b/command/job_plan.go @@ -10,7 +10,6 @@ import ( "time" "github.com/hashicorp/nomad/api" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/scheduler" "github.com/mitchellh/colorstring" "github.com/posener/complete" @@ -195,7 +194,7 @@ func (c *JobPlanCommand) Run(args []string) int { // Set the vault namespace. if vaultNamespace != "" { - job.VaultNamespace = pointer.Of(vaultNamespace) + job.VaultNamespace = new(vaultNamespace) } // Setup the options diff --git a/command/job_plan_test.go b/command/job_plan_test.go index cfaeae592b8..b1695b438fb 100644 --- a/command/job_plan_test.go +++ b/command/job_plan_test.go @@ -12,7 +12,6 @@ import ( "github.com/hashicorp/cli" "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/testutil" "github.com/shoenig/test/must" ) @@ -169,7 +168,7 @@ func TestPlanCommand_From_Files(t *testing.T) { s := testutil.NewTestServer(t, func(c *testutil.TestServerConfig) { c.Vaults[0].Address = v.HTTPAddr c.Vaults[0].Enabled = true - c.Vaults[0].AllowUnauthenticated = pointer.Of(false) + c.Vaults[0].AllowUnauthenticated = new(false) c.Vaults[0].Token = v.RootToken }) defer s.Stop() diff --git a/command/job_restart_test.go b/command/job_restart_test.go index ac8c192e1bc..dac6dba3a71 100644 --- a/command/job_restart_test.go +++ b/command/job_restart_test.go @@ -23,7 +23,6 @@ import ( "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/command/agent" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/testutil" "github.com/shoenig/test/must" "github.com/shoenig/test/wait" @@ -840,13 +839,13 @@ func TestJobRestartCommand_jobPrefixAndNamespace(t *testing.T) { evalIDs = append(evalIDs, resp.EvalID) jobProd := testJob("test_job_restart") - jobProd.Namespace = pointer.Of("prod") + jobProd.Namespace = new("prod") resp, _, err = client.Jobs().Register(jobProd, nil) must.NoError(t, err) evalIDs = append(evalIDs, resp.EvalID) jobUniqueProd := testJob("test_job_restart_prod_ns") - jobUniqueProd.Namespace = pointer.Of("prod") + jobUniqueProd.Namespace = new("prod") resp, _, err = client.Jobs().Register(jobUniqueProd, nil) must.NoError(t, err) evalIDs = append(evalIDs, resp.EvalID) @@ -972,8 +971,8 @@ func TestJobRestartCommand_rescheduleFail(t *testing.T) { // Register test job with 3 allocs. jobID := "test_job_restart_reschedule_fail" job := testJob(jobID) - job.Type = pointer.Of(api.JobTypeService) - job.TaskGroups[0].Count = pointer.Of(3) + job.Type = new(api.JobTypeService) + job.TaskGroups[0].Count = new(3) job.TaskGroups[0].Tasks[0].Config = map[string]any{"run_for": "10m"} resp, _, err := client.Jobs().Register(job, nil) @@ -1086,10 +1085,10 @@ func TestJobRestartCommand_activeDeployment(t *testing.T) { // Register test job and update it once to trigger a deployment. jobID := "test_job_restart_deployment" job := testJob(jobID) - job.Type = pointer.Of(api.JobTypeService) + job.Type = new(api.JobTypeService) job.Update = &api.UpdateStrategy{ - Canary: pointer.Of(1), - AutoPromote: pointer.Of(false), + Canary: new(1), + AutoPromote: new(false), } _, _, err := client.Jobs().Register(job, nil) @@ -1301,8 +1300,8 @@ func TestJobRestartCommand_shutdownDelay_reschedule(t *testing.T) { jobID := nonAlphaNum.ReplaceAllString(tc.name, "-") job := testJob(jobID) - job.Type = pointer.Of(api.JobTypeService) - job.TaskGroups[0].Count = pointer.Of(2) + job.Type = new(api.JobTypeService) + job.TaskGroups[0].Count = new(2) job.TaskGroups[0].Tasks[0].Config = map[string]any{"run_for": "10m"} job.TaskGroups[0].Tasks[0].ShutdownDelay = shutdownDelay job.TaskGroups[0].Tasks[0].Services = []*api.Service{{ @@ -1399,7 +1398,7 @@ func TestJobRestartCommand_filterAllocs(t *testing.T) { api.NewTaskGroup("group_3", 1). AddTask(task3), ) - jobV1.Version = pointer.Of(uint64(1)) + jobV1.Version = new(uint64(1)) jobV2 := api.NewServiceJob("example", "example", "global", 1). AddTaskGroup( @@ -1410,7 +1409,7 @@ func TestJobRestartCommand_filterAllocs(t *testing.T) { api.NewTaskGroup("group_2", 1). AddTask(task2), ) - jobV2.Version = pointer.Of(uint64(2)) + jobV2.Version = new(uint64(2)) allAllocs := []AllocationListStubWithJob{} allocs := map[string]AllocationListStubWithJob{} @@ -1607,7 +1606,7 @@ func TestJobRestartCommand_onErrorFail(t *testing.T) { // Register a job with 3 allocations. jobID := "test_job_restart_command_fail_on_error" job := testJob(jobID) - job.TaskGroups[0].Count = pointer.Of(3) + job.TaskGroups[0].Count = new(3) resp, _, err := client.Jobs().Register(job, nil) must.NoError(t, err) diff --git a/command/job_run.go b/command/job_run.go index 0aaeac3e4a2..83d2d99cec3 100644 --- a/command/job_run.go +++ b/command/job_run.go @@ -12,7 +12,6 @@ import ( "time" "github.com/hashicorp/nomad/api" - "github.com/hashicorp/nomad/helper/pointer" "github.com/posener/complete" ) @@ -59,7 +58,7 @@ Alias: nomad run mount CSI volumes require a token with the 'csi-mount-volume' capability for the volume's namespace. Jobs that mount host volumes require a token with the 'host_volume' capability for that volume. - + General Options: ` + generalOptionsUsage(usageOptsDefault) + ` @@ -244,11 +243,11 @@ func (c *JobRunCommand) Run(args []string) int { multiregion := job.IsMultiregion() if consulNamespace != "" { - job.ConsulNamespace = pointer.Of(consulNamespace) + job.ConsulNamespace = new(consulNamespace) } if vaultNamespace != "" { - job.VaultNamespace = pointer.Of(vaultNamespace) + job.VaultNamespace = new(vaultNamespace) } if output { diff --git a/command/job_scale.go b/command/job_scale.go index dd16b3a48a8..af73720c9cf 100644 --- a/command/job_scale.go +++ b/command/job_scale.go @@ -12,7 +12,6 @@ import ( "github.com/hashicorp/cli" "github.com/hashicorp/nomad/api" - "github.com/hashicorp/nomad/helper/pointer" "github.com/posener/complete" ) @@ -154,7 +153,7 @@ func (j *JobScaleCommand) Run(args []string) int { // Perform the scaling action. w := &api.WriteOptions{Namespace: namespace} req := &api.ScalingRequest{ - Count: pointer.Of(int64(count)), + Count: new(int64(count)), Target: map[string]string{ "Job": jobID, "Group": groupString, diff --git a/command/job_scale_test.go b/command/job_scale_test.go index 3f3c019c60a..e334a0cc94d 100644 --- a/command/job_scale_test.go +++ b/command/job_scale_test.go @@ -12,7 +12,6 @@ import ( "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/command/agent" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" "github.com/hashicorp/nomad/testutil" @@ -90,17 +89,17 @@ func TestJobScaleCommand_MultiGroup(t *testing.T) { SetConfig("run_for", "5s"). SetConfig("exit_code", 0). Require(&api.Resources{ - MemoryMB: pointer.Of(256), - CPU: pointer.Of(100), + MemoryMB: new(256), + CPU: new(100), }). SetLogConfig(&api.LogConfig{ - MaxFiles: pointer.Of(1), - MaxFileSizeMB: pointer.Of(2), + MaxFiles: new(1), + MaxFileSizeMB: new(2), }) group2 := api.NewTaskGroup("group2", 1). AddTask(task). RequireDisk(&api.EphemeralDisk{ - SizeMB: pointer.Of(20), + SizeMB: new(20), }) job.AddTaskGroup(group2) diff --git a/command/job_scaling_events_test.go b/command/job_scaling_events_test.go index 27d86353a52..079a7405118 100644 --- a/command/job_scaling_events_test.go +++ b/command/job_scaling_events_test.go @@ -12,7 +12,6 @@ import ( "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/command/agent" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" "github.com/hashicorp/nomad/testutil" @@ -70,7 +69,7 @@ func TestJobScalingEventsCommand_Run(t *testing.T) { // Perform a scaling action to generate an event. _, _, err = client.Jobs().Scale( "scale_events_test_job", - "group1", pointer.Of(2), + "group1", new(2), "searchable custom test message", false, nil, nil) if err != nil { t.Fatalf("err: %s", err) diff --git a/command/job_start_test.go b/command/job_start_test.go index f108241f059..05dbd645fb7 100644 --- a/command/job_start_test.go +++ b/command/job_start_test.go @@ -11,7 +11,6 @@ import ( "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/command/agent" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" @@ -84,7 +83,7 @@ func TestStartCommand(t *testing.T) { client, err := cmd.Meta.Client() must.NoError(t, err) - job.TaskGroups[0].Scaling.Enabled = pointer.Of(false) + job.TaskGroups[0].Scaling.Enabled = new(false) _, _, err = client.Jobs().RegisterOpts(job, &api.RegisterOptions{}, nil) must.NoError(t, err) @@ -115,7 +114,7 @@ func TestStartCommand(t *testing.T) { client, err := cmd.Meta.Client() must.NoError(t, err) - job.TaskGroups[0].Scaling.Enabled = pointer.Of(true) + job.TaskGroups[0].Scaling.Enabled = new(true) jsonBytes, err := json.Marshal(job) must.NoError(t, err) diff --git a/command/job_stop_test.go b/command/job_stop_test.go index 7a6bff606e1..af0a137ba9d 100644 --- a/command/job_stop_test.go +++ b/command/job_stop_test.go @@ -13,7 +13,6 @@ import ( "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/command/agent" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" @@ -57,9 +56,9 @@ func TestStopCommand_multi(t *testing.T) { for _, jobID := range jobIDs { job := testJob(jobID) - job.TaskGroups[0].Tasks[0].Resources.MemoryMB = pointer.Of(16) - job.TaskGroups[0].Tasks[0].Resources.DiskMB = pointer.Of(32) - job.TaskGroups[0].Tasks[0].Resources.CPU = pointer.Of(10) + job.TaskGroups[0].Tasks[0].Resources.MemoryMB = new(16) + job.TaskGroups[0].Tasks[0].Resources.DiskMB = new(32) + job.TaskGroups[0].Tasks[0].Resources.CPU = new(10) job.TaskGroups[0].Tasks[0].Config = map[string]interface{}{ "run_for": "30s", } diff --git a/command/job_validate.go b/command/job_validate.go index 361d2369052..2e84c970767 100644 --- a/command/job_validate.go +++ b/command/job_validate.go @@ -11,7 +11,6 @@ import ( "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/command/agent" "github.com/hashicorp/nomad/helper" - "github.com/hashicorp/nomad/helper/pointer" "github.com/posener/complete" ) @@ -135,7 +134,7 @@ func (c *JobValidateCommand) Run(args []string) int { } if vaultNamespace != "" { - job.VaultNamespace = pointer.Of(vaultNamespace) + job.VaultNamespace = new(vaultNamespace) } // Check that the job is valid diff --git a/command/job_validate_test.go b/command/job_validate_test.go index 39203f38215..a5feb56acd1 100644 --- a/command/job_validate_test.go +++ b/command/job_validate_test.go @@ -10,7 +10,6 @@ import ( "github.com/hashicorp/cli" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/testutil" "github.com/shoenig/test/must" ) @@ -30,7 +29,7 @@ func TestValidateCommand_Files(t *testing.T) { s := testutil.NewTestServer(t, func(c *testutil.TestServerConfig) { c.Vaults[0].Address = v.HTTPAddr c.Vaults[0].Enabled = true - c.Vaults[0].AllowUnauthenticated = pointer.Of(false) + c.Vaults[0].AllowUnauthenticated = new(false) c.Vaults[0].Token = v.RootToken }) defer s.Stop() diff --git a/command/meta.go b/command/meta.go index b9e51cb2907..8a8e8cf099a 100644 --- a/command/meta.go +++ b/command/meta.go @@ -14,7 +14,6 @@ import ( "github.com/hashicorp/cap/util" "github.com/hashicorp/cli" "github.com/hashicorp/nomad/api" - "github.com/hashicorp/nomad/helper/pointer" colorable "github.com/mattn/go-colorable" "github.com/mitchellh/colorstring" "github.com/posener/complete" @@ -295,7 +294,7 @@ func (m *Meta) SetupUi(args []string) { showCLIHints := os.Getenv(EnvNomadCLIShowHints) if showCLIHints != "" { if show, err := strconv.ParseBool(showCLIHints); err == nil { - m.showCLIHints = pointer.Of(show) + m.showCLIHints = new(show) } else { m.Ui.Warn(fmt.Sprintf("Invalid value %q for %s: %v", showCLIHints, EnvNomadCLIShowHints, err)) } @@ -335,7 +334,7 @@ func (m *Meta) JobByPrefix(client *api.Client, prefix string, filter string) (*a if err != nil { return nil, fmt.Errorf("Error querying job %q: %s", jobID, err) } - job.Namespace = pointer.Of(namespace) + job.Namespace = new(namespace) return job, nil } diff --git a/command/meta_test.go b/command/meta_test.go index 7bc6e0b1bc6..e9a1bb4c14f 100644 --- a/command/meta_test.go +++ b/command/meta_test.go @@ -16,7 +16,6 @@ import ( "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/command/agent" - "github.com/hashicorp/nomad/helper/pointer" "github.com/shoenig/test/must" ) @@ -186,7 +185,7 @@ func TestMeta_JobByPrefix(t *testing.T) { } for _, j := range jobs { job := testJob(j.id) - job.Namespace = pointer.Of(j.namespace) + job.Namespace = new(j.namespace) _, err := client.Namespaces().Register(&api.Namespace{Name: j.namespace}, nil) must.NoError(t, err) @@ -256,7 +255,7 @@ func TestMeta_ShowUIPath(t *testing.T) { // Create a test server with UI enabled but CLI URL links disabled server, client, url := testServer(t, true, func(c *agent.Config) { - c.UI.ShowCLIHints = pointer.Of(true) + c.UI.ShowCLIHints = new(true) }) defer server.Shutdown() waitForNodes(t, client) @@ -454,7 +453,7 @@ func TestMeta_ShowUIPath_ShowCLIHintsEnabled(t *testing.T) { // Create a test server with UI enabled and CLI URL links enabled server, client, url := testServer(t, true, func(c *agent.Config) { - c.UI.ShowCLIHints = pointer.Of(true) + c.UI.ShowCLIHints = new(true) }) defer server.Shutdown() waitForNodes(t, client) @@ -477,7 +476,7 @@ func TestMeta_ShowUIPath_ShowCLIHintsDisabled(t *testing.T) { // Create a test server with UI enabled and CLI URL links disabled server, client, url := testServer(t, true, func(c *agent.Config) { - c.UI.ShowCLIHints = pointer.Of(false) + c.UI.ShowCLIHints = new(false) }) defer server.Shutdown() waitForNodes(t, client) @@ -540,7 +539,7 @@ func TestMeta_ShowUIPath_EnvVarOverride(t *testing.T) { // Create a test server with UI enabled and CLI hints as per test case server, client, url := testServer(t, true, func(c *agent.Config) { - c.UI.ShowCLIHints = pointer.Of(tc.serverEnabled) + c.UI.ShowCLIHints = new(tc.serverEnabled) }) defer server.Shutdown() waitForNodes(t, client) @@ -569,7 +568,7 @@ func TestMeta_ShowUIPath_BrowserOpening(t *testing.T) { ci.Parallel(t) server, client, url := testServer(t, true, func(c *agent.Config) { - c.UI.ShowCLIHints = pointer.Of(true) + c.UI.ShowCLIHints = new(true) }) defer server.Shutdown() waitForNodes(t, client) diff --git a/command/monitor_test.go b/command/monitor_test.go index 9e209c41ff5..baed9c6a033 100644 --- a/command/monitor_test.go +++ b/command/monitor_test.go @@ -12,7 +12,6 @@ import ( "github.com/hashicorp/cli" "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/structs" "github.com/shoenig/test/must" "github.com/shoenig/test/wait" @@ -238,7 +237,7 @@ func TestMonitor_MonitorBlockedEval(t *testing.T) { // Submit a service job. // Since there are no clients this will create a blocked eval. job := testJob("job1") - job.Type = pointer.Of("service") + job.Type = new("service") job.TaskGroups[0].Tasks[0].Config["run_for"] = "300s" resp, _, err := client.Jobs().Register(job, nil) diff --git a/command/node_drain_test.go b/command/node_drain_test.go index 07250617a1c..64d51cde3f1 100644 --- a/command/node_drain_test.go +++ b/command/node_drain_test.go @@ -14,7 +14,6 @@ import ( "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/command/agent" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/testutil" "github.com/posener/complete" "github.com/shoenig/test/must" @@ -51,12 +50,12 @@ func TestNodeDrainCommand_Detach(t *testing.T) { // Register a job to create an alloc to drain that will block draining job := &api.Job{ - ID: pointer.Of("mock_service"), - Name: pointer.Of("mock_service"), + ID: new("mock_service"), + Name: new("mock_service"), Datacenters: []string{"dc1"}, TaskGroups: []*api.TaskGroup{ { - Name: pointer.Of("mock_group"), + Name: new("mock_group"), Tasks: []*api.Task{ { Name: "mock_task", @@ -128,19 +127,19 @@ func TestNodeDrainCommand_Monitor(t *testing.T) { // Register a service job to create allocs to drain serviceCount := 3 job := &api.Job{ - ID: pointer.Of("mock_service"), - Name: pointer.Of("mock_service"), + ID: new("mock_service"), + Name: new("mock_service"), Datacenters: []string{"dc1"}, - Type: pointer.Of("service"), + Type: new("service"), TaskGroups: []*api.TaskGroup{ { - Name: pointer.Of("mock_group"), + Name: new("mock_group"), Count: &serviceCount, Migrate: &api.MigrateStrategy{ - MaxParallel: pointer.Of(1), - HealthCheck: pointer.Of("task_states"), - MinHealthyTime: pointer.Of(10 * time.Millisecond), - HealthyDeadline: pointer.Of(5 * time.Minute), + MaxParallel: new(1), + HealthCheck: new("task_states"), + MinHealthyTime: new(10 * time.Millisecond), + HealthyDeadline: new(5 * time.Minute), }, Tasks: []*api.Task{ { @@ -150,8 +149,8 @@ func TestNodeDrainCommand_Monitor(t *testing.T) { "run_for": "10m", }, Resources: &api.Resources{ - CPU: pointer.Of(50), - MemoryMB: pointer.Of(50), + CPU: new(50), + MemoryMB: new(50), }, }, }, @@ -164,14 +163,14 @@ func TestNodeDrainCommand_Monitor(t *testing.T) { // Register a system job to ensure it is ignored during draining sysjob := &api.Job{ - ID: pointer.Of("mock_system"), - Name: pointer.Of("mock_system"), + ID: new("mock_system"), + Name: new("mock_system"), Datacenters: []string{"dc1"}, - Type: pointer.Of("system"), + Type: new("system"), TaskGroups: []*api.TaskGroup{ { - Name: pointer.Of("mock_sysgroup"), - Count: pointer.Of(1), + Name: new("mock_sysgroup"), + Count: new(1), Tasks: []*api.Task{ { Name: "mock_systask", @@ -180,8 +179,8 @@ func TestNodeDrainCommand_Monitor(t *testing.T) { "run_for": "10m", }, Resources: &api.Resources{ - CPU: pointer.Of(50), - MemoryMB: pointer.Of(50), + CPU: new(50), + MemoryMB: new(50), }, }, }, diff --git a/command/node_meta_apply.go b/command/node_meta_apply.go index 7d28a6acce4..e8ab0c6c1ff 100644 --- a/command/node_meta_apply.go +++ b/command/node_meta_apply.go @@ -8,7 +8,6 @@ import ( "strings" "github.com/hashicorp/nomad/api" - "github.com/hashicorp/nomad/helper/pointer" "github.com/posener/complete" ) @@ -123,7 +122,7 @@ func parseMapFromArgs(args []string) map[string]*string { case 0: // Nothing to do case 1: - m[kv[0]] = pointer.Of("") + m[kv[0]] = new("") default: m[kv[0]] = &kv[1] } diff --git a/command/node_meta_apply_test.go b/command/node_meta_apply_test.go index 7c7b43337bd..3ae6193cad4 100644 --- a/command/node_meta_apply_test.go +++ b/command/node_meta_apply_test.go @@ -7,7 +7,6 @@ import ( "testing" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/shoenig/test/must" ) @@ -23,18 +22,18 @@ func TestNodeMeta_parseMapFromArgs(t *testing.T) { name: "EmptyEquals", input: []string{"key1=val1", "key2=val2", "key3="}, exp: map[string]*string{ - "key1": pointer.Of("val1"), - "key2": pointer.Of("val2"), - "key3": pointer.Of(""), + "key1": new("val1"), + "key2": new("val2"), + "key3": new(""), }, }, { name: "EmptyNoEquals", input: []string{"key1=val1", "key2=val2", "key4"}, exp: map[string]*string{ - "key1": pointer.Of("val1"), - "key2": pointer.Of("val2"), - "key4": pointer.Of(""), + "key1": new("val1"), + "key2": new("val2"), + "key4": new(""), }, }, { @@ -51,23 +50,23 @@ func TestNodeMeta_parseMapFromArgs(t *testing.T) { name: "EmptyArg", input: []string{""}, exp: map[string]*string{ - "": pointer.Of(""), + "": new(""), }, }, { name: "WeirdArgs", input: []string{"=", "foo==bar"}, exp: map[string]*string{ - "": pointer.Of(""), - "foo": pointer.Of("=bar"), + "": new(""), + "foo": new("=bar"), }, }, { name: "WeirderArgs", input: []string{"=foo=bar", "\x00=\x01"}, exp: map[string]*string{ - "": pointer.Of("foo=bar"), - "\x00": pointer.Of("\x01"), + "": new("foo=bar"), + "\x00": new("\x01"), }, }, } @@ -93,30 +92,30 @@ func TestNodeMeta_applyNodeMetaUnset(t *testing.T) { name: "CommaParty", unset: ",,,", meta: map[string]*string{ - "foo": pointer.Of("bar"), + "foo": new("bar"), }, exp: map[string]*string{ - "foo": pointer.Of("bar"), + "foo": new("bar"), }, }, { name: "Empty", unset: "", meta: map[string]*string{ - "foo": pointer.Of("bar"), + "foo": new("bar"), }, exp: map[string]*string{ - "foo": pointer.Of("bar"), + "foo": new("bar"), }, }, { name: "UnsetNew", unset: "unset", meta: map[string]*string{ - "foo": pointer.Of("bar"), + "foo": new("bar"), }, exp: map[string]*string{ - "foo": pointer.Of("bar"), + "foo": new("bar"), "unset": nil, }, }, @@ -124,7 +123,7 @@ func TestNodeMeta_applyNodeMetaUnset(t *testing.T) { name: "UnsetExisting", unset: "foo", meta: map[string]*string{ - "foo": pointer.Of("bar"), + "foo": new("bar"), }, exp: map[string]*string{ "foo": nil, @@ -134,7 +133,7 @@ func TestNodeMeta_applyNodeMetaUnset(t *testing.T) { name: "UnsetBoth", unset: ",foo,unset,", meta: map[string]*string{ - "foo": pointer.Of("bar"), + "foo": new("bar"), }, exp: map[string]*string{ "foo": nil, diff --git a/command/node_pool_jobs_test.go b/command/node_pool_jobs_test.go index 6caaea7c961..13c11fd6349 100644 --- a/command/node_pool_jobs_test.go +++ b/command/node_pool_jobs_test.go @@ -12,7 +12,6 @@ import ( "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/helper" - "github.com/hashicorp/nomad/helper/pointer" "github.com/shoenig/test" "github.com/shoenig/test/must" ) @@ -39,8 +38,8 @@ func TestNodePoolJobsListCommand_Run(t *testing.T) { // Register some jobs registerJob := func(np, ns, id string) { job := testJob(id) - job.Namespace = pointer.Of(ns) - job.NodePool = pointer.Of(np) + job.Namespace = new(ns) + job.NodePool = new(np) _, _, err := client.Jobs().Register(job, nil) must.NoError(t, err) } diff --git a/command/node_status.go b/command/node_status.go index 93a52a6ee91..f0109c49383 100644 --- a/command/node_status.go +++ b/command/node_status.go @@ -16,7 +16,6 @@ import ( "github.com/hashicorp/go-set/v3" "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/api/contexts" - "github.com/hashicorp/nomad/helper/pointer" "github.com/posener/complete" ) @@ -981,9 +980,9 @@ func computeNodeTotalResources(node *api.Node) api.Resources { r := node.NodeResources res := node.ReservedResources - total.CPU = pointer.Of[int](int(r.Cpu.CpuShares) - int(res.Cpu.CpuShares)) - total.MemoryMB = pointer.Of[int](int(r.Memory.MemoryMB) - int(res.Memory.MemoryMB)) - total.DiskMB = pointer.Of[int](int(r.Disk.DiskMB) - int(res.Disk.DiskMB)) + total.CPU = new(int(r.Cpu.CpuShares) - int(res.Cpu.CpuShares)) + total.MemoryMB = new(int(r.Memory.MemoryMB) - int(res.Memory.MemoryMB)) + total.DiskMB = new(int(r.Disk.DiskMB) - int(res.Disk.DiskMB)) return total } diff --git a/command/operator_debug_test.go b/command/operator_debug_test.go index 62f38c293a4..815137a5e9b 100644 --- a/command/operator_debug_test.go +++ b/command/operator_debug_test.go @@ -24,7 +24,6 @@ import ( "github.com/hashicorp/nomad/command/agent" mon "github.com/hashicorp/nomad/command/agent/monitor" "github.com/hashicorp/nomad/helper" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/state" "github.com/hashicorp/nomad/testutil" "github.com/shoenig/test/must" @@ -891,7 +890,7 @@ func testServerWithoutLeader(t *testing.T, runClient bool, cb func(*agent.Config a := agent.NewTestAgent(t, t.Name(), func(config *agent.Config) { config.Client.Enabled = runClient config.Server.Enabled = true - config.Server.NumSchedulers = pointer.Of(0) + config.Server.NumSchedulers = new(0) config.Server.BootstrapExpect = 3 if cb != nil { diff --git a/command/quota_apply_test.go b/command/quota_apply_test.go index 078d03a2f66..cda285380b6 100644 --- a/command/quota_apply_test.go +++ b/command/quota_apply_test.go @@ -10,7 +10,6 @@ import ( "github.com/hashicorp/cli" "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/shoenig/test/must" ) @@ -81,13 +80,13 @@ limit { Limits: []*api.QuotaLimit{{ Region: "global", RegionLimit: &api.QuotaResources{ - CPU: pointer.Of(2500), - Cores: pointer.Of(0), - MemoryMB: pointer.Of(1000), - MemoryMaxMB: pointer.Of(1000), + CPU: new(2500), + Cores: new(0), + MemoryMB: new(1000), + MemoryMaxMB: new(1000), Devices: []*api.RequestedDevice{{ Name: "nvidia/gpu/1080ti", - Count: pointer.Of(uint64(1)), + Count: new(uint64(1)), }}, Storage: &api.QuotaStorageResources{ VariablesMB: 1000, @@ -95,10 +94,10 @@ limit { }, NodePools: []*api.NodePoolLimit{{ NodePool: "us1", - CPU: pointer.Of(1500), - Cores: pointer.Of(1), - MemoryMB: pointer.Of(1000), - MemoryMaxMB: pointer.Of(1000), + CPU: new(1500), + Cores: new(1), + MemoryMB: new(1000), + MemoryMaxMB: new(1000), }}, }, }}, diff --git a/command/quota_delete_test.go b/command/quota_delete_test.go index 4b3ecc93cc7..2b20cc76a1a 100644 --- a/command/quota_delete_test.go +++ b/command/quota_delete_test.go @@ -102,7 +102,7 @@ func testQuotaSpec() *api.QuotaSpec { { Region: "global", RegionLimit: &api.QuotaResources{ - CPU: pointer.Of(100), + CPU: new(100), }, }, }, diff --git a/command/scaling_policy_info_test.go b/command/scaling_policy_info_test.go index a92a7afb39e..30da864aac3 100644 --- a/command/scaling_policy_info_test.go +++ b/command/scaling_policy_info_test.go @@ -11,7 +11,6 @@ import ( "github.com/hashicorp/cli" "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/testutil" ) @@ -67,9 +66,9 @@ func TestScalingPolicyInfoCommand_Run(t *testing.T) { // Generate an example scaling policy. job.TaskGroups[0].Scaling = &api.ScalingPolicy{ - Enabled: pointer.Of(true), - Min: pointer.Of(int64(1)), - Max: pointer.Of(int64(1)), + Enabled: new(true), + Min: new(int64(1)), + Max: new(int64(1)), } // Register the job. diff --git a/command/scaling_policy_list_test.go b/command/scaling_policy_list_test.go index ed7329c7d6c..2c4b4c2c29c 100644 --- a/command/scaling_policy_list_test.go +++ b/command/scaling_policy_list_test.go @@ -9,7 +9,6 @@ import ( "github.com/hashicorp/cli" "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/shoenig/test/must" ) @@ -34,9 +33,9 @@ func TestScalingPolicyListCommand_Run(t *testing.T) { // Generate an example scaling policy. scalingPolicy := api.ScalingPolicy{ Type: api.ScalingPolicyTypeHorizontal, - Enabled: pointer.Of(true), - Min: pointer.Of(int64(1)), - Max: pointer.Of(int64(1)), + Enabled: new(true), + Min: new(int64(1)), + Max: new(int64(1)), } // Iterate the jobs, add the scaling policy and register. diff --git a/command/setup_vault_test.go b/command/setup_vault_test.go index 12a8d5fab44..1559af29204 100644 --- a/command/setup_vault_test.go +++ b/command/setup_vault_test.go @@ -11,7 +11,6 @@ import ( "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/command/agent" - "github.com/hashicorp/nomad/helper/pointer" "github.com/shoenig/test/must" ) @@ -22,7 +21,7 @@ func TestSetupVaultCommand_Run(t *testing.T) { srv, client, url := testServer(t, true, func(c *agent.Config) { c.DevMode = true c.Vaults[0].Name = "default" - c.Vaults[0].Enabled = pointer.Of(true) + c.Vaults[0].Enabled = new(true) }) defer srv.Shutdown() diff --git a/command/testing_test.go b/command/testing_test.go index 087c6e0867f..8aa034cecd0 100644 --- a/command/testing_test.go +++ b/command/testing_test.go @@ -12,7 +12,6 @@ import ( "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/command/agent" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/structs" "github.com/hashicorp/nomad/testutil" "github.com/shoenig/test/must" @@ -26,7 +25,7 @@ func testServer(t *testing.T, runClient bool, cb func(*agent.Config)) (*agent.Te config.Client.Enabled = runClient // Disable UI hints in test by default - config.UI.ShowCLIHints = pointer.Of(false) + config.UI.ShowCLIHints = new(false) if cb != nil { cb(config) @@ -62,22 +61,22 @@ func testJob(jobID string) *api.Job { SetConfig("run_for", "5s"). SetConfig("exit_code", 0). Require(&api.Resources{ - MemoryMB: pointer.Of(256), - CPU: pointer.Of(100), + MemoryMB: new(256), + CPU: new(100), }). SetLogConfig(&api.LogConfig{ - MaxFiles: pointer.Of(1), - MaxFileSizeMB: pointer.Of(2), + MaxFiles: new(1), + MaxFileSizeMB: new(2), }) group := api.NewTaskGroup("group1", 1). AddTask(task). RequireDisk(&api.EphemeralDisk{ - SizeMB: pointer.Of(20), + SizeMB: new(20), }).ScalingPolicy(&api.ScalingPolicy{ - Min: pointer.Of(int64(1)), - Max: pointer.Of(int64(5)), - Enabled: pointer.Of(true), + Min: new(int64(1)), + Max: new(int64(5)), + Enabled: new(true), }) job := api.NewBatchJob(jobID, jobID, "global", 1). @@ -109,18 +108,18 @@ func testServiceJob(jobID string) *api.Job { task := api.NewTask("task1", "mock_driver"). SetConfig("exit_code", 0). Require(&api.Resources{ - MemoryMB: pointer.Of(256), - CPU: pointer.Of(100), + MemoryMB: new(256), + CPU: new(100), }). SetLogConfig(&api.LogConfig{ - MaxFiles: pointer.Of(1), - MaxFileSizeMB: pointer.Of(2), + MaxFiles: new(1), + MaxFileSizeMB: new(2), }) group := api.NewTaskGroup("group1", 1). AddTask(task). RequireDisk(&api.EphemeralDisk{ - SizeMB: pointer.Of(20), + SizeMB: new(20), }) job := api.NewServiceJob(jobID, jobID, "global", 1). @@ -135,18 +134,18 @@ func testMultiRegionJob(jobID, region, datacenter string) *api.Job { SetConfig("run_for", "15s"). SetConfig("exit_code", 0). Require(&api.Resources{ - MemoryMB: pointer.Of(256), - CPU: pointer.Of(100), + MemoryMB: new(256), + CPU: new(100), }). SetLogConfig(&api.LogConfig{ - MaxFiles: pointer.Of(1), - MaxFileSizeMB: pointer.Of(2), + MaxFiles: new(1), + MaxFileSizeMB: new(2), }) group := api.NewTaskGroup("group1", 1). AddTask(task). RequireDisk(&api.EphemeralDisk{ - SizeMB: pointer.Of(20), + SizeMB: new(20), }) job := api.NewServiceJob(jobID, jobID, region, 1).AddDatacenter(datacenter).AddTaskGroup(group) diff --git a/drivers/docker/driver.go b/drivers/docker/driver.go index 0cda35ead97..34dd6063b4a 100644 --- a/drivers/docker/driver.go +++ b/drivers/docker/driver.go @@ -43,7 +43,6 @@ import ( "github.com/hashicorp/nomad/drivers/shared/hostnames" "github.com/hashicorp/nomad/drivers/shared/resolvconf" "github.com/hashicorp/nomad/helper" - "github.com/hashicorp/nomad/helper/pointer" nstructs "github.com/hashicorp/nomad/nomad/structs" "github.com/hashicorp/nomad/plugins/base" "github.com/hashicorp/nomad/plugins/drivers" @@ -1131,7 +1130,7 @@ func (d *Driver) createContainerConfig(task *drivers.TaskConfig, driverConfig *T // disable swap explicitly in non-Windows environments if cgroupslib.MaybeDisableMemorySwappiness() != nil { - hostConfig.MemorySwappiness = pointer.Of(int64(*(cgroupslib.MaybeDisableMemorySwappiness()))) + hostConfig.MemorySwappiness = new(int64(*(cgroupslib.MaybeDisableMemorySwappiness()))) } else { hostConfig.MemorySwappiness = nil } @@ -1700,7 +1699,7 @@ func (d *Driver) DestroyTask(taskID string, force bool) error { if !force { return fmt.Errorf("must call StopTask for the given task before Destroy or set force to true") } - if err := dockerClient.ContainerStop(d.ctx, h.containerID, containerapi.StopOptions{Timeout: pointer.Of(0)}); err != nil { + if err := dockerClient.ContainerStop(d.ctx, h.containerID, containerapi.StopOptions{Timeout: new(0)}); err != nil { h.logger.Warn("failed to stop container during destroy", "error", err) } } @@ -2059,5 +2058,5 @@ func isDockerTransientError(err error) bool { } func stopWithZeroTimeout() containerapi.StopOptions { - return containerapi.StopOptions{Timeout: pointer.Of(0)} + return containerapi.StopOptions{Timeout: new(0)} } diff --git a/drivers/docker/driver_linux_test.go b/drivers/docker/driver_linux_test.go index 5943c304911..a08ca1c33cd 100644 --- a/drivers/docker/driver_linux_test.go +++ b/drivers/docker/driver_linux_test.go @@ -16,7 +16,6 @@ import ( "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/client/testutil" - "github.com/hashicorp/nomad/helper/pointer" "github.com/shoenig/test/must" "github.com/shoenig/test/wait" ) @@ -70,7 +69,7 @@ func TestDockerDriver_PluginConfig_PidsLimit(t *testing.T) { cfg.PidsLimit = 3 opts, err := driver.createContainerConfig(task, cfg, "org/repo:0.1") must.NoError(t, err) - must.Eq(t, pointer.Of(int64(3)), opts.Host.PidsLimit) + must.Eq(t, new(int64(3)), opts.Host.PidsLimit) } func TestDockerDriver_PidsLimit(t *testing.T) { diff --git a/drivers/docker/fingerprint.go b/drivers/docker/fingerprint.go index 450a6fa8316..8be4bf7e040 100644 --- a/drivers/docker/fingerprint.go +++ b/drivers/docker/fingerprint.go @@ -11,7 +11,6 @@ import ( "time" "github.com/docker/docker/api/types/network" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/plugins/drivers" "github.com/hashicorp/nomad/plugins/drivers/utils" pstructs "github.com/hashicorp/nomad/plugins/shared/structs" @@ -44,14 +43,14 @@ func (d *Driver) setDetected(detected bool) { // setFingerprintSuccess marks the driver as having fingerprinted successfully func (d *Driver) setFingerprintSuccess() { d.fingerprintLock.Lock() - d.fingerprintSuccess = pointer.Of(true) + d.fingerprintSuccess = new(true) d.fingerprintLock.Unlock() } // setFingerprintFailure marks the driver as having failed fingerprinting func (d *Driver) setFingerprintFailure() { d.fingerprintLock.Lock() - d.fingerprintSuccess = pointer.Of(false) + d.fingerprintSuccess = new(false) d.fingerprintLock.Unlock() } diff --git a/drivers/docker/handle.go b/drivers/docker/handle.go index 82d3c50e7f1..ff5c51bc017 100644 --- a/drivers/docker/handle.go +++ b/drivers/docker/handle.go @@ -21,7 +21,6 @@ import ( "github.com/hashicorp/go-plugin" "github.com/hashicorp/nomad/client/lib/cgroupslib" "github.com/hashicorp/nomad/drivers/docker/docklog" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/plugins/drivers" pstructs "github.com/hashicorp/nomad/plugins/shared/structs" ) @@ -174,7 +173,7 @@ func (h *taskHandle) Kill(killTimeout time.Duration, signal string) error { ctx, cancel := context.WithTimeout(context.Background(), graciousTimeout) defer cancel() apiTimeout := int(killTimeout.Seconds()) - err = h.infinityClient.ContainerStop(ctx, h.containerID, containerapi.StopOptions{Timeout: pointer.Of(apiTimeout)}) + err = h.infinityClient.ContainerStop(ctx, h.containerID, containerapi.StopOptions{Timeout: new(apiTimeout)}) } else { _, parseErr := parseSignal(runtime.GOOS, signal) if parseErr != nil { @@ -207,7 +206,7 @@ func (h *taskHandle) Kill(killTimeout time.Duration, signal string) error { } // Stop the container forcefully. - err = h.dockerClient.ContainerStop(context.Background(), h.containerID, containerapi.StopOptions{Timeout: pointer.Of(0)}) + err = h.dockerClient.ContainerStop(context.Background(), h.containerID, containerapi.StopOptions{Timeout: new(0)}) } if err != nil { @@ -333,7 +332,7 @@ func (h *taskHandle) run() { ctx, stopCancel := context.WithTimeout(context.Background(), 10*time.Second) defer stopCancel() if err := h.dockerClient.ContainerStop(ctx, h.containerID, containerapi.StopOptions{ - Timeout: pointer.Of(0), + Timeout: new(0), }); err != nil { if !errdefs.IsNotModified(err) && !errdefs.IsNotFound(err) { h.logger.Error("error stopping container", "error", err) diff --git a/drivers/docker/network.go b/drivers/docker/network.go index 6145252402f..aa3cf0c3037 100644 --- a/drivers/docker/network.go +++ b/drivers/docker/network.go @@ -8,7 +8,6 @@ import ( "github.com/docker/docker/api/types" containerapi "github.com/docker/docker/api/types/container" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/plugins/drivers" ) @@ -128,7 +127,7 @@ func (d *Driver) DestroyNetwork(allocID string, spec *drivers.NetworkIsolationSp } // this is the pause container, just kill it fast - if err := dockerClient.ContainerStop(d.ctx, id, containerapi.StopOptions{Timeout: pointer.Of(1)}); err != nil { + if err := dockerClient.ContainerStop(d.ctx, id, containerapi.StopOptions{Timeout: new(1)}); err != nil { d.logger.Warn("failed to stop pause container", "id", id, "error", err) } diff --git a/drivers/docker/reconcile_dangling_test.go b/drivers/docker/reconcile_dangling_test.go index 1cef80ffdc9..084277a7a31 100644 --- a/drivers/docker/reconcile_dangling_test.go +++ b/drivers/docker/reconcile_dangling_test.go @@ -20,7 +20,6 @@ import ( "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/client/testutil" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/plugins/drivers" ) @@ -229,7 +228,7 @@ func TestDanglingContainerRemoval_Stopped(t *testing.T) { err = dockerClient.ContainerStart(ctx, cont.ID, container.StartOptions{}) must.NoError(t, err) - err = dockerClient.ContainerStop(ctx, cont.ID, container.StopOptions{Timeout: pointer.Of(60)}) + err = dockerClient.ContainerStop(ctx, cont.ID, container.StopOptions{Timeout: new(60)}) must.NoError(t, err) dd := dockerDriverHarness(t, nil).Impl().(*Driver) diff --git a/drivers/exec/driver.go b/drivers/exec/driver.go index 94c4ca5fba8..25b335294f1 100644 --- a/drivers/exec/driver.go +++ b/drivers/exec/driver.go @@ -22,7 +22,6 @@ import ( "github.com/hashicorp/nomad/drivers/shared/resolvconf" "github.com/hashicorp/nomad/drivers/shared/validators" "github.com/hashicorp/nomad/helper/pluginutils/loader" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/plugins/base" "github.com/hashicorp/nomad/plugins/drivers" "github.com/hashicorp/nomad/plugins/drivers/fsisolation" @@ -276,14 +275,14 @@ func NewExecDriver(ctx context.Context, logger hclog.Logger) drivers.DriverPlugi // setFingerprintSuccess marks the driver as having fingerprinted successfully func (d *Driver) setFingerprintSuccess() { d.fingerprintLock.Lock() - d.fingerprintSuccess = pointer.Of(true) + d.fingerprintSuccess = new(true) d.fingerprintLock.Unlock() } // setFingerprintFailure marks the driver as having failed fingerprinting func (d *Driver) setFingerprintFailure() { d.fingerprintLock.Lock() - d.fingerprintSuccess = pointer.Of(false) + d.fingerprintSuccess = new(false) d.fingerprintLock.Unlock() } diff --git a/e2e/e2eutil/utils.go b/e2e/e2eutil/utils.go index 281da5ca1bf..e9f7340bd5f 100644 --- a/e2e/e2eutil/utils.go +++ b/e2e/e2eutil/utils.go @@ -12,7 +12,6 @@ import ( "time" api "github.com/hashicorp/nomad/api" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/jobspec2" "github.com/hashicorp/nomad/nomad/structs" "github.com/hashicorp/nomad/testutil" @@ -63,7 +62,7 @@ func stringToPtrOrNil(s string) *string { if s == "" { return nil } - return pointer.Of(s) + return new(s) } func Parse2(t *testing.T, jobFile string) (*api.Job, error) { @@ -79,7 +78,7 @@ func RegisterAllocs(t *testing.T, nomadClient *api.Client, jobFile, jobID, cToke require.NoError(t, err) // Set custom job ID (distinguish among tests) - job.ID = pointer.Of(jobID) + job.ID = new(jobID) // Register job var idx uint64 diff --git a/e2e/scaling/scaling_test.go b/e2e/scaling/scaling_test.go index 9588a174279..214bc68a4f3 100644 --- a/e2e/scaling/scaling_test.go +++ b/e2e/scaling/scaling_test.go @@ -10,7 +10,6 @@ import ( "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/e2e/e2eutil" "github.com/hashicorp/nomad/e2e/v3/cluster3" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/structs" "github.com/shoenig/test/must" @@ -50,7 +49,7 @@ func testScalingBasic(t *testing.T) { // Simple scaling action. testMeta := map[string]any{"scaling-e2e-test": "value"} scaleResp, _, err := nomad.Jobs().Scale( - jobID, "horizontally_scalable", pointer.Of(3), + jobID, "horizontally_scalable", new(3), "Nomad e2e testing", false, testMeta, nil) must.NoError(t, err) must.NotEq(t, "", scaleResp.EvalID) @@ -63,11 +62,11 @@ func testScalingBasic(t *testing.T) { // Attempt break break the policy min/max parameters. _, _, err = nomad.Jobs().Scale( - jobID, "horizontally_scalable", pointer.Of(4), + jobID, "horizontally_scalable", new(4), "Nomad e2e testing", false, nil, nil) must.ErrorContains(t, err, "group count was greater than scaling policy maximum") _, _, err = nomad.Jobs().Scale( - jobID, "horizontally_scalable", pointer.Of(1), + jobID, "horizontally_scalable", new(1), "Nomad e2e testing", false, nil, nil) must.ErrorContains(t, err, "group count was less than scaling policy minimum") @@ -116,22 +115,22 @@ func testScalingNamespaces(t *testing.T) { // We shouldn't be able to trigger scaling across the namespace boundary. _, _, err = nomad.Jobs().Scale( - defaultJobID, "horizontally_scalable", pointer.Of(3), + defaultJobID, "horizontally_scalable", new(3), "Nomad e2e testing", false, nil, &aWriteOpts) must.ErrorContains(t, err, "not found") _, _, err = nomad.Jobs().Scale( - aJobID, "horizontally_scalable", pointer.Of(3), + aJobID, "horizontally_scalable", new(3), "Nomad e2e testing", false, nil, &defaultWriteOpts) must.ErrorContains(t, err, "not found") // We should be able to trigger scaling when using the correct namespace, // duh. _, _, err = nomad.Jobs().Scale( - defaultJobID, "horizontally_scalable", pointer.Of(3), + defaultJobID, "horizontally_scalable", new(3), "Nomad e2e testing", false, nil, &defaultWriteOpts) must.NoError(t, err) _, _, err = nomad.Jobs().Scale( - aJobID, "horizontally_scalable", pointer.Of(3), + aJobID, "horizontally_scalable", new(3), "Nomad e2e testing", false, nil, &aWriteOpts) must.NoError(t, err) } @@ -171,7 +170,7 @@ func testScalingSystemJob(t *testing.T) { // Try to scale beyond 1 testMeta := map[string]any{"scaling-e2e-test": "value"} - scaleResp, _, err := nomad.Jobs().Scale(jobID, "system_job_group", pointer.Of(3), + scaleResp, _, err := nomad.Jobs().Scale(jobID, "system_job_group", new(3), "Nomad e2e testing", false, testMeta, nil) must.ErrorContains(t, err, "can only be scaled between 0 and 1") @@ -192,7 +191,7 @@ func testScalingSystemJob(t *testing.T) { // Scale down to 0 testMeta = map[string]any{"scaling-e2e-test": "value"} - scaleResp, _, err = nomad.Jobs().Scale(jobID, "system_job_group", pointer.Of(0), + scaleResp, _, err = nomad.Jobs().Scale(jobID, "system_job_group", new(0), "Nomad e2e testing", false, testMeta, nil) must.NoError(t, err) must.NotEq(t, "", scaleResp.EvalID) @@ -212,7 +211,7 @@ func testScalingSystemJob(t *testing.T) { // Scale up to 1 again testMeta = map[string]any{"scaling-e2e-test": "value"} - scaleResp, _, err = nomad.Jobs().Scale(jobID, "system_job_group", pointer.Of(1), + scaleResp, _, err = nomad.Jobs().Scale(jobID, "system_job_group", new(1), "Nomad e2e testing", false, testMeta, nil) must.NoError(t, err) must.NotEq(t, "", scaleResp.EvalID) diff --git a/e2e/v3/jobs3/jobs3.go b/e2e/v3/jobs3/jobs3.go index 2cf9fd76dda..0a3699a4dc5 100644 --- a/e2e/v3/jobs3/jobs3.go +++ b/e2e/v3/jobs3/jobs3.go @@ -17,7 +17,6 @@ import ( "github.com/hashicorp/go-set/v3" nomadapi "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/e2e/v3/util3" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/jobspec2" "github.com/shoenig/test" "github.com/shoenig/test/must" @@ -333,7 +332,7 @@ func (sub *Submission) run() { must.NotNil(sub.t, job) if job.Type == nil { - job.Type = pointer.Of("service") + job.Type = new("service") } registerOpts := &nomadapi.RegisterOptions{ diff --git a/e2e/workload_id/nodemeta_test.go b/e2e/workload_id/nodemeta_test.go index 6ad5ed865ee..90668d16abb 100644 --- a/e2e/workload_id/nodemeta_test.go +++ b/e2e/workload_id/nodemeta_test.go @@ -10,7 +10,6 @@ import ( "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/e2e/e2eutil" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/jobspec2" "github.com/shoenig/test/must" @@ -72,7 +71,7 @@ func testDynamicNodeMetadata(t *testing.T) { Strict: true, }) must.NoError(t, err) - job.ID = pointer.Of(jobID) + job.ID = new(jobID) // Setup ACLs for _, task := range job.TaskGroups[0].Tasks { @@ -94,8 +93,8 @@ func testDynamicNodeMetadata(t *testing.T) { req := &api.NodeMetaApplyRequest{ NodeID: node.ID, Meta: map[string]*string{ - keyFoo: pointer.Of("bar"), - keyEmpty: pointer.Of(""), + keyFoo: new("bar"), + keyEmpty: new(""), keyUnset: nil, }, } diff --git a/helper/pluginutils/loader/testing.go b/helper/pluginutils/loader/testing.go index 5d471e7fa07..8a8b5dcc1e8 100644 --- a/helper/pluginutils/loader/testing.go +++ b/helper/pluginutils/loader/testing.go @@ -9,7 +9,6 @@ import ( log "github.com/hashicorp/go-hclog" plugin "github.com/hashicorp/go-plugin" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/plugins/base" ) @@ -54,7 +53,7 @@ func (m *MockInstance) ApiVersion() string { return // passed inst as the plugin func MockBasicExternalPlugin(inst interface{}, apiVersion string) *MockInstance { var killedLock sync.Mutex - killed := pointer.Of(false) + killed := new(false) return &MockInstance{ InternalPlugin: false, KillF: func() { diff --git a/helper/pointer/pointer.go b/helper/pointer/pointer.go index c9498be6b05..56901c860d3 100644 --- a/helper/pointer/pointer.go +++ b/helper/pointer/pointer.go @@ -12,11 +12,6 @@ type Primitive interface { cmp.Ordered | bool } -// Of returns a pointer to a. -func Of[A any](a A) *A { - return &a -} - // Copy returns a new pointer to a. func Copy[A any](a *A) *A { if a == nil { diff --git a/helper/pointer/pointer_test.go b/helper/pointer/pointer_test.go index 47f1fc85b5a..ea49cbf655e 100644 --- a/helper/pointer/pointer_test.go +++ b/helper/pointer/pointer_test.go @@ -15,7 +15,7 @@ func Test_Of(t *testing.T) { ci.Parallel(t) s := "hello" - sPtr := Of(s) + sPtr := new(s) must.Eq(t, s, *sPtr) @@ -27,9 +27,9 @@ func Test_Of(t *testing.T) { func Test_Copy(t *testing.T) { ci.Parallel(t) - orig := Of(1) + orig := new(1) dup := Copy(orig) - orig = Of(7) + orig = new(7) must.EqOp(t, 7, *orig) must.EqOp(t, 1, *dup) } diff --git a/internal/testing/apitests/tasks_test.go b/internal/testing/apitests/tasks_test.go index d211f22ca3b..3a8a1ecad51 100644 --- a/internal/testing/apitests/tasks_test.go +++ b/internal/testing/apitests/tasks_test.go @@ -9,7 +9,6 @@ import ( "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/structs" "github.com/stretchr/testify/assert" ) @@ -31,130 +30,130 @@ func TestTaskGroup_Canonicalize_ReschedulePolicy(t *testing.T) { jobReschedulePolicy: nil, taskReschedulePolicy: nil, expected: &api.ReschedulePolicy{ - Attempts: pointer.Of(structs.DefaultBatchJobReschedulePolicy.Attempts), - Interval: pointer.Of(structs.DefaultBatchJobReschedulePolicy.Interval), - Delay: pointer.Of(structs.DefaultBatchJobReschedulePolicy.Delay), - DelayFunction: pointer.Of(structs.DefaultBatchJobReschedulePolicy.DelayFunction), - MaxDelay: pointer.Of(structs.DefaultBatchJobReschedulePolicy.MaxDelay), - Unlimited: pointer.Of(structs.DefaultBatchJobReschedulePolicy.Unlimited), + Attempts: new(structs.DefaultBatchJobReschedulePolicy.Attempts), + Interval: new(structs.DefaultBatchJobReschedulePolicy.Interval), + Delay: new(structs.DefaultBatchJobReschedulePolicy.Delay), + DelayFunction: new(structs.DefaultBatchJobReschedulePolicy.DelayFunction), + MaxDelay: new(structs.DefaultBatchJobReschedulePolicy.MaxDelay), + Unlimited: new(structs.DefaultBatchJobReschedulePolicy.Unlimited), }, }, { desc: "Empty job reschedule policy", jobReschedulePolicy: &api.ReschedulePolicy{ - Attempts: pointer.Of(0), - Interval: pointer.Of(time.Duration(0)), - Delay: pointer.Of(time.Duration(0)), - MaxDelay: pointer.Of(time.Duration(0)), - DelayFunction: pointer.Of(""), - Unlimited: pointer.Of(false), + Attempts: new(0), + Interval: new(time.Duration(0)), + Delay: new(time.Duration(0)), + MaxDelay: new(time.Duration(0)), + DelayFunction: new(""), + Unlimited: new(false), }, taskReschedulePolicy: nil, expected: &api.ReschedulePolicy{ - Attempts: pointer.Of(0), - Interval: pointer.Of(time.Duration(0)), - Delay: pointer.Of(time.Duration(0)), - MaxDelay: pointer.Of(time.Duration(0)), - DelayFunction: pointer.Of(""), - Unlimited: pointer.Of(false), + Attempts: new(0), + Interval: new(time.Duration(0)), + Delay: new(time.Duration(0)), + MaxDelay: new(time.Duration(0)), + DelayFunction: new(""), + Unlimited: new(false), }, }, { desc: "Inherit from job", jobReschedulePolicy: &api.ReschedulePolicy{ - Attempts: pointer.Of(1), - Interval: pointer.Of(20 * time.Second), - Delay: pointer.Of(20 * time.Second), - MaxDelay: pointer.Of(10 * time.Minute), - DelayFunction: pointer.Of("constant"), - Unlimited: pointer.Of(false), + Attempts: new(1), + Interval: new(20 * time.Second), + Delay: new(20 * time.Second), + MaxDelay: new(10 * time.Minute), + DelayFunction: new("constant"), + Unlimited: new(false), }, taskReschedulePolicy: nil, expected: &api.ReschedulePolicy{ - Attempts: pointer.Of(1), - Interval: pointer.Of(20 * time.Second), - Delay: pointer.Of(20 * time.Second), - MaxDelay: pointer.Of(10 * time.Minute), - DelayFunction: pointer.Of("constant"), - Unlimited: pointer.Of(false), + Attempts: new(1), + Interval: new(20 * time.Second), + Delay: new(20 * time.Second), + MaxDelay: new(10 * time.Minute), + DelayFunction: new("constant"), + Unlimited: new(false), }, }, { desc: "Set in task", jobReschedulePolicy: nil, taskReschedulePolicy: &api.ReschedulePolicy{ - Attempts: pointer.Of(5), - Interval: pointer.Of(2 * time.Minute), - Delay: pointer.Of(20 * time.Second), - MaxDelay: pointer.Of(10 * time.Minute), - DelayFunction: pointer.Of("constant"), - Unlimited: pointer.Of(false), + Attempts: new(5), + Interval: new(2 * time.Minute), + Delay: new(20 * time.Second), + MaxDelay: new(10 * time.Minute), + DelayFunction: new("constant"), + Unlimited: new(false), }, expected: &api.ReschedulePolicy{ - Attempts: pointer.Of(5), - Interval: pointer.Of(2 * time.Minute), - Delay: pointer.Of(20 * time.Second), - MaxDelay: pointer.Of(10 * time.Minute), - DelayFunction: pointer.Of("constant"), - Unlimited: pointer.Of(false), + Attempts: new(5), + Interval: new(2 * time.Minute), + Delay: new(20 * time.Second), + MaxDelay: new(10 * time.Minute), + DelayFunction: new("constant"), + Unlimited: new(false), }, }, { desc: "Merge from job", jobReschedulePolicy: &api.ReschedulePolicy{ - Attempts: pointer.Of(1), - Delay: pointer.Of(20 * time.Second), - MaxDelay: pointer.Of(10 * time.Minute), + Attempts: new(1), + Delay: new(20 * time.Second), + MaxDelay: new(10 * time.Minute), }, taskReschedulePolicy: &api.ReschedulePolicy{ - Interval: pointer.Of(5 * time.Minute), - DelayFunction: pointer.Of("constant"), - Unlimited: pointer.Of(false), + Interval: new(5 * time.Minute), + DelayFunction: new("constant"), + Unlimited: new(false), }, expected: &api.ReschedulePolicy{ - Attempts: pointer.Of(1), - Interval: pointer.Of(5 * time.Minute), - Delay: pointer.Of(20 * time.Second), - MaxDelay: pointer.Of(10 * time.Minute), - DelayFunction: pointer.Of("constant"), - Unlimited: pointer.Of(false), + Attempts: new(1), + Interval: new(5 * time.Minute), + Delay: new(20 * time.Second), + MaxDelay: new(10 * time.Minute), + DelayFunction: new("constant"), + Unlimited: new(false), }, }, { desc: "Override from group", jobReschedulePolicy: &api.ReschedulePolicy{ - Attempts: pointer.Of(1), - MaxDelay: pointer.Of(10 * time.Second), + Attempts: new(1), + MaxDelay: new(10 * time.Second), }, taskReschedulePolicy: &api.ReschedulePolicy{ - Attempts: pointer.Of(5), - Delay: pointer.Of(20 * time.Second), - MaxDelay: pointer.Of(20 * time.Minute), - DelayFunction: pointer.Of("constant"), - Unlimited: pointer.Of(false), + Attempts: new(5), + Delay: new(20 * time.Second), + MaxDelay: new(20 * time.Minute), + DelayFunction: new("constant"), + Unlimited: new(false), }, expected: &api.ReschedulePolicy{ - Attempts: pointer.Of(5), - Interval: pointer.Of(structs.DefaultBatchJobReschedulePolicy.Interval), - Delay: pointer.Of(20 * time.Second), - MaxDelay: pointer.Of(20 * time.Minute), - DelayFunction: pointer.Of("constant"), - Unlimited: pointer.Of(false), + Attempts: new(5), + Interval: new(structs.DefaultBatchJobReschedulePolicy.Interval), + Delay: new(20 * time.Second), + MaxDelay: new(20 * time.Minute), + DelayFunction: new("constant"), + Unlimited: new(false), }, }, { desc: "Attempts from job, default interval", jobReschedulePolicy: &api.ReschedulePolicy{ - Attempts: pointer.Of(1), + Attempts: new(1), }, taskReschedulePolicy: nil, expected: &api.ReschedulePolicy{ - Attempts: pointer.Of(1), - Interval: pointer.Of(structs.DefaultBatchJobReschedulePolicy.Interval), - Delay: pointer.Of(structs.DefaultBatchJobReschedulePolicy.Delay), - DelayFunction: pointer.Of(structs.DefaultBatchJobReschedulePolicy.DelayFunction), - MaxDelay: pointer.Of(structs.DefaultBatchJobReschedulePolicy.MaxDelay), - Unlimited: pointer.Of(structs.DefaultBatchJobReschedulePolicy.Unlimited), + Attempts: new(1), + Interval: new(structs.DefaultBatchJobReschedulePolicy.Interval), + Delay: new(structs.DefaultBatchJobReschedulePolicy.Delay), + DelayFunction: new(structs.DefaultBatchJobReschedulePolicy.DelayFunction), + MaxDelay: new(structs.DefaultBatchJobReschedulePolicy.MaxDelay), + Unlimited: new(structs.DefaultBatchJobReschedulePolicy.Unlimited), }, }, } @@ -162,13 +161,13 @@ func TestTaskGroup_Canonicalize_ReschedulePolicy(t *testing.T) { for _, tc := range testCases { t.Run(tc.desc, func(t *testing.T) { job := &api.Job{ - ID: pointer.Of("test"), + ID: new("test"), Reschedule: tc.jobReschedulePolicy, - Type: pointer.Of(api.JobTypeBatch), + Type: new(api.JobTypeBatch), } job.Canonicalize() tg := &api.TaskGroup{ - Name: pointer.Of("foo"), + Name: new("foo"), ReschedulePolicy: tc.taskReschedulePolicy, } tg.Canonicalize(job) diff --git a/internal/testing/apitests/util_test.go b/internal/testing/apitests/util_test.go index 71a67293ea9..30274b9c124 100644 --- a/internal/testing/apitests/util_test.go +++ b/internal/testing/apitests/util_test.go @@ -7,7 +7,6 @@ import ( "testing" "github.com/hashicorp/nomad/api" - "github.com/hashicorp/nomad/helper/pointer" ) func assertQueryMeta(t *testing.T, qm *api.QueryMeta) { @@ -31,18 +30,18 @@ func testJob() *api.Job { task := api.NewTask("task1", "exec"). SetConfig("command", "/bin/sleep"). Require(&api.Resources{ - CPU: pointer.Of(100), - MemoryMB: pointer.Of(256), + CPU: new(100), + MemoryMB: new(256), }). SetLogConfig(&api.LogConfig{ - MaxFiles: pointer.Of(1), - MaxFileSizeMB: pointer.Of(2), + MaxFiles: new(1), + MaxFileSizeMB: new(2), }) group := api.NewTaskGroup("group1", 1). AddTask(task). RequireDisk(&api.EphemeralDisk{ - SizeMB: pointer.Of(25), + SizeMB: new(25), }) job := api.NewBatchJob("job1", "redis", "global", 1). diff --git a/nomad/alloc_endpoint.go b/nomad/alloc_endpoint.go index 1f9ad3d3cc2..7d7557326c6 100644 --- a/nomad/alloc_endpoint.go +++ b/nomad/alloc_endpoint.go @@ -13,7 +13,6 @@ import ( metrics "github.com/hashicorp/go-metrics/compat" "github.com/hashicorp/nomad/acl" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/state" "github.com/hashicorp/nomad/nomad/state/paginator" @@ -315,9 +314,9 @@ func (a *Alloc) Stop(args *structs.AllocStopRequest, reply *structs.AllocStopRes Evals: []*structs.Evaluation{eval}, Allocs: map[string]*structs.DesiredTransition{ args.AllocID: { - Migrate: pointer.Of(true), - NoShutdownDelay: pointer.Of(args.NoShutdownDelay), - Reschedule: pointer.Of(args.Reschedule), + Migrate: new(true), + NoShutdownDelay: new(args.NoShutdownDelay), + Reschedule: new(args.Reschedule), }, }, } diff --git a/nomad/alloc_endpoint_test.go b/nomad/alloc_endpoint_test.go index 032d4bb7ee3..1ed1a580892 100644 --- a/nomad/alloc_endpoint_test.go +++ b/nomad/alloc_endpoint_test.go @@ -11,7 +11,6 @@ import ( msgpackrpc "github.com/hashicorp/net-rpc-msgpackrpc/v2" "github.com/hashicorp/nomad/acl" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" @@ -1064,7 +1063,7 @@ func TestAllocEndpoint_UpdateDesiredTransition(t *testing.T) { require.Nil(state.UpsertAllocs(structs.MsgTypeTestSetup, 1001, []*structs.Allocation{alloc, alloc2})) t1 := &structs.DesiredTransition{ - Migrate: pointer.Of(true), + Migrate: new(true), } // Update the allocs desired status diff --git a/nomad/auth/auth_test.go b/nomad/auth/auth_test.go index ddf91d842ce..792751415c3 100644 --- a/nomad/auth/auth_test.go +++ b/nomad/auth/auth_test.go @@ -21,7 +21,6 @@ import ( "github.com/hashicorp/nomad/acl" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/testlog" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" @@ -1088,7 +1087,7 @@ func TestResolveACLToken(t *testing.T) { // Create a mock token with an expiration time long in the // past, and upsert. token := mock.ACLToken() - token.ExpirationTime = pointer.Of(time.Date( + token.ExpirationTime = new(time.Date( 1970, time.January, 1, 0, 0, 0, 0, time.UTC)) err := auth.getState().UpsertACLTokens( @@ -1400,7 +1399,7 @@ func TestResolveSecretToken(t *testing.T) { // Create a mock token with an expiration time long in the // past, and upsert. token := mock.ACLToken() - token.ExpirationTime = pointer.Of(time.Date( + token.ExpirationTime = new(time.Date( 1970, time.January, 1, 0, 0, 0, 0, time.UTC)) err := auth.getState().UpsertACLTokens( diff --git a/nomad/client_agent_endpoint.go b/nomad/client_agent_endpoint.go index 95a52885d8b..70c0eac8fb1 100644 --- a/nomad/client_agent_endpoint.go +++ b/nomad/client_agent_endpoint.go @@ -19,7 +19,6 @@ import ( "github.com/hashicorp/nomad/command/agent/host" "github.com/hashicorp/nomad/command/agent/monitor" "github.com/hashicorp/nomad/command/agent/pprof" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/peers" "github.com/hashicorp/nomad/nomad/structs" ) @@ -137,7 +136,7 @@ func (a *Agent) monitor(conn io.ReadWriteCloser) { encoder := codec.NewEncoder(conn, structs.MsgpackHandle) if err := decoder.Decode(&args); err != nil { - handleStreamResultError(err, pointer.Of(int64(500)), encoder) + handleStreamResultError(err, new(int64(500)), encoder) return } authErr := a.srv.Authenticate(nil, &args) @@ -152,7 +151,7 @@ func (a *Agent) monitor(conn io.ReadWriteCloser) { handleStreamResultError(err, nil, encoder) return } else if !aclObj.AllowAgentRead() { - handleStreamResultError(structs.ErrPermissionDenied, pointer.Of(int64(403)), encoder) + handleStreamResultError(structs.ErrPermissionDenied, new(int64(403)), encoder) return } @@ -162,7 +161,7 @@ func (a *Agent) monitor(conn io.ReadWriteCloser) { } if logLevel == log.NoLevel { - handleStreamResultError(errors.New("Unknown log level"), pointer.Of(int64(400)), encoder) + handleStreamResultError(errors.New("Unknown log level"), new(int64(400)), encoder) return } @@ -175,7 +174,7 @@ func (a *Agent) monitor(conn io.ReadWriteCloser) { region := args.RequestRegion() if region == "" { - handleStreamResultError(fmt.Errorf("missing target region"), pointer.Of(int64(400)), encoder) + handleStreamResultError(fmt.Errorf("missing target region"), new(int64(400)), encoder) return } if region != a.srv.Region() { @@ -187,7 +186,7 @@ func (a *Agent) monitor(conn io.ReadWriteCloser) { if args.ServerID != "" { serverToFwd, err := a.forwardFor(args.ServerID, region) if err != nil { - handleStreamResultError(err, pointer.Of(int64(400)), encoder) + handleStreamResultError(err, new(int64(400)), encoder) return } if serverToFwd != nil { @@ -253,7 +252,7 @@ func (a *Agent) monitor(conn io.ReadWriteCloser) { streamEncoder := monitor.NewStreamEncoder(&buf, conn, encoder, frameCodec, args.PlainText) streamErr := streamEncoder.EncodeStream(frames, errCh, ctx, framer, false) if streamErr != nil { - handleStreamResultError(streamErr, pointer.Of(int64(500)), encoder) + handleStreamResultError(streamErr, new(int64(500)), encoder) return } } @@ -266,7 +265,7 @@ func (a *Agent) monitorExport(conn io.ReadWriteCloser) { encoder := codec.NewEncoder(conn, structs.MsgpackHandle) if err := decoder.Decode(&args); err != nil { - handleStreamResultError(err, pointer.Of(int64(500)), encoder) + handleStreamResultError(err, new(int64(500)), encoder) return } authErr := a.srv.Authenticate(nil, &args) @@ -281,7 +280,7 @@ func (a *Agent) monitorExport(conn io.ReadWriteCloser) { handleStreamResultError(err, nil, encoder) return } else if !aclObj.AllowAgentRead() { - handleStreamResultError(structs.ErrPermissionDenied, pointer.Of(int64(403)), encoder) + handleStreamResultError(structs.ErrPermissionDenied, new(int64(403)), encoder) return } @@ -294,7 +293,7 @@ func (a *Agent) monitorExport(conn io.ReadWriteCloser) { region := args.RequestRegion() if region == "" { - handleStreamResultError(fmt.Errorf("missing target region"), pointer.Of(int64(400)), encoder) + handleStreamResultError(fmt.Errorf("missing target region"), new(int64(400)), encoder) return } if region != a.srv.Region() { @@ -306,7 +305,7 @@ func (a *Agent) monitorExport(conn io.ReadWriteCloser) { if args.ServerID != "" { serverToFwd, err := a.forwardFor(args.ServerID, region) if err != nil { - handleStreamResultError(err, pointer.Of(int64(400)), encoder) + handleStreamResultError(err, new(int64(400)), encoder) return } if serverToFwd != nil { @@ -319,7 +318,7 @@ func (a *Agent) monitorExport(conn io.ReadWriteCloser) { nomadLogPath := a.srv.GetConfig().LogFile if args.OnDisk && nomadLogPath == "" { - handleStreamResultError(errors.New("No nomad log file defined"), pointer.Of(int64(400)), encoder) + handleStreamResultError(errors.New("No nomad log file defined"), new(int64(400)), encoder) } // NodeID was empty, ServerID was equal to this server, monitor this server ctx, cancel := context.WithCancel(context.Background()) @@ -355,7 +354,7 @@ func (a *Agent) monitorExport(conn io.ReadWriteCloser) { }() m, err := monitor.NewExportMonitor(opts) if err != nil { - handleStreamResultError(err, pointer.Of(int64(500)), encoder) + handleStreamResultError(err, new(int64(500)), encoder) return } @@ -380,7 +379,7 @@ func (a *Agent) monitorExport(conn io.ReadWriteCloser) { streamErr := streamEncoder.EncodeStream(frames, errCh, ctx, framer, true) if streamErr != nil { - handleStreamResultError(streamErr, pointer.Of(int64(500)), encoder) + handleStreamResultError(streamErr, new(int64(500)), encoder) return } } @@ -428,7 +427,7 @@ func (a *Agent) forwardMonitorClient(conn io.ReadWriteCloser, args any, encoder // or creating direct stream state, srv, err := a.findClientConn(nodeID) if err != nil { - handleStreamResultError(err, pointer.Of(int64(500)), encoder) + handleStreamResultError(err, new(int64(500)), encoder) return } @@ -465,7 +464,7 @@ func (a *Agent) forwardMonitorClient(conn io.ReadWriteCloser, args any, encoder func (a *Agent) forwardMonitorServer(conn io.ReadWriteCloser, server *peers.Parts, args any, encoder *codec.Encoder, decoder *codec.Decoder, endpoint string) { serverConn, err := a.srv.streamingRpc(server, "Agent.Monitor") if err != nil { - handleStreamResultError(err, pointer.Of(int64(500)), encoder) + handleStreamResultError(err, new(int64(500)), encoder) return } defer serverConn.Close() @@ -473,7 +472,7 @@ func (a *Agent) forwardMonitorServer(conn io.ReadWriteCloser, server *peers.Part // Send the Request outEncoder := codec.NewEncoder(serverConn, structs.MsgpackHandle) if err := outEncoder.Encode(args); err != nil { - handleStreamResultError(err, pointer.Of(int64(500)), encoder) + handleStreamResultError(err, new(int64(500)), encoder) return } diff --git a/nomad/client_alloc_endpoint.go b/nomad/client_alloc_endpoint.go index 960840972ac..62a84a824e4 100644 --- a/nomad/client_alloc_endpoint.go +++ b/nomad/client_alloc_endpoint.go @@ -17,7 +17,6 @@ import ( "github.com/hashicorp/nomad/acl" cstructs "github.com/hashicorp/nomad/client/structs" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/structs" ) @@ -492,7 +491,7 @@ func (a *ClientAllocations) exec(conn io.ReadWriteCloser) { encoder := codec.NewEncoder(conn, structs.MsgpackHandle) if err := decoder.Decode(&args); err != nil { - handleStreamResultError(err, pointer.Of(int64(500)), encoder) + handleStreamResultError(err, new(int64(500)), encoder) return } @@ -512,7 +511,7 @@ func (a *ClientAllocations) exec(conn io.ReadWriteCloser) { // Verify the arguments. if args.AllocID == "" { - handleStreamResultError(errors.New("missing AllocID"), pointer.Of(int64(400)), encoder) + handleStreamResultError(errors.New("missing AllocID"), new(int64(400)), encoder) return } @@ -525,7 +524,7 @@ func (a *ClientAllocations) exec(conn io.ReadWriteCloser) { alloc, err := getAlloc(snap, args.AllocID) if structs.IsErrUnknownAllocation(err) { - handleStreamResultError(err, pointer.Of(int64(404)), encoder) + handleStreamResultError(err, new(int64(404)), encoder) return } if err != nil { @@ -545,7 +544,7 @@ func (a *ClientAllocations) exec(conn io.ReadWriteCloser) { if alloc.ClientTerminalStatus() { handleStreamResultError(fmt.Errorf("exec not possible, client status of allocation %s is %s", alloc.ID, alloc.ClientStatus), - pointer.Of(int64(http.StatusBadRequest)), encoder) + new(int64(http.StatusBadRequest)), encoder) return } @@ -555,13 +554,13 @@ func (a *ClientAllocations) exec(conn io.ReadWriteCloser) { job, err := snap.JobByID(nil, args.Namespace, args.JobID) if err != nil { handleStreamResultError(err, - pointer.Of(int64(http.StatusInternalServerError)), encoder) + new(int64(http.StatusInternalServerError)), encoder) return } if job == nil { handleStreamResultError( fmt.Errorf("job %s not found in namespace %s", args.JobID, args.Namespace), - pointer.Of(int64(http.StatusNotFound)), encoder) + new(int64(http.StatusNotFound)), encoder) return } @@ -569,7 +568,7 @@ func (a *ClientAllocations) exec(conn io.ReadWriteCloser) { if args.JobID != alloc.JobID { handleStreamResultError( fmt.Errorf("job %s does not have allocation %s", args.JobID, alloc.ID), - pointer.Of(int64(http.StatusBadRequest)), encoder, + new(int64(http.StatusBadRequest)), encoder, ) } } @@ -579,18 +578,18 @@ func (a *ClientAllocations) exec(conn io.ReadWriteCloser) { // Make sure Node is valid and new enough to support RPC node, err := snap.NodeByID(nil, nodeID) if err != nil { - handleStreamResultError(err, pointer.Of(int64(500)), encoder) + handleStreamResultError(err, new(int64(500)), encoder) return } if node == nil { err := fmt.Errorf("Unknown node %q", nodeID) - handleStreamResultError(err, pointer.Of(int64(400)), encoder) + handleStreamResultError(err, new(int64(400)), encoder) return } if err := nodeSupportsRpc(node); err != nil { - handleStreamResultError(err, pointer.Of(int64(400)), encoder) + handleStreamResultError(err, new(int64(400)), encoder) return } @@ -604,7 +603,7 @@ func (a *ClientAllocations) exec(conn io.ReadWriteCloser) { if err != nil { var code *int64 if structs.IsErrNoNodeConn(err) { - code = pointer.Of(int64(404)) + code = new(int64(404)) } handleStreamResultError(err, code, encoder) return diff --git a/nomad/client_fs_endpoint.go b/nomad/client_fs_endpoint.go index a01ba826aa8..b790bd810ce 100644 --- a/nomad/client_fs_endpoint.go +++ b/nomad/client_fs_endpoint.go @@ -14,7 +14,6 @@ import ( log "github.com/hashicorp/go-hclog" metrics "github.com/hashicorp/go-metrics/compat" cstructs "github.com/hashicorp/nomad/client/structs" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/go-msgpack/v2/codec" "github.com/hashicorp/nomad/acl" @@ -69,7 +68,7 @@ func forwardRegionStreamingRpc(fsrv *Server, conn io.ReadWriteCloser, } if allocResp.Alloc == nil { - handleStreamResultError(structs.NewErrUnknownAllocation(allocID), pointer.Of(int64(404)), encoder) + handleStreamResultError(structs.NewErrUnknownAllocation(allocID), new(int64(404)), encoder) return } @@ -78,7 +77,7 @@ func forwardRegionStreamingRpc(fsrv *Server, conn io.ReadWriteCloser, if err != nil { var code *int64 if structs.IsErrNoNodeConn(err) { - code = pointer.Of(int64(404)) + code = new(int64(404)) } handleStreamResultError(err, code, encoder) return @@ -232,7 +231,7 @@ func (f *FileSystem) stream(conn io.ReadWriteCloser) { encoder := codec.NewEncoder(conn, structs.MsgpackHandle) if err := decoder.Decode(&args); err != nil { - handleStreamResultError(err, pointer.Of(int64(500)), encoder) + handleStreamResultError(err, new(int64(500)), encoder) return } @@ -252,7 +251,7 @@ func (f *FileSystem) stream(conn io.ReadWriteCloser) { // Verify the arguments. if args.AllocID == "" { - handleStreamResultError(errors.New("missing AllocID"), pointer.Of(int64(400)), encoder) + handleStreamResultError(errors.New("missing AllocID"), new(int64(400)), encoder) return } @@ -265,7 +264,7 @@ func (f *FileSystem) stream(conn io.ReadWriteCloser) { alloc, err := getAlloc(snap, args.AllocID) if structs.IsErrUnknownAllocation(err) { - handleStreamResultError(structs.NewErrUnknownAllocation(args.AllocID), pointer.Of(int64(404)), encoder) + handleStreamResultError(structs.NewErrUnknownAllocation(args.AllocID), new(int64(404)), encoder) return } if err != nil { @@ -287,18 +286,18 @@ func (f *FileSystem) stream(conn io.ReadWriteCloser) { // Make sure Node is valid and new enough to support RPC node, err := snap.NodeByID(nil, nodeID) if err != nil { - handleStreamResultError(err, pointer.Of(int64(500)), encoder) + handleStreamResultError(err, new(int64(500)), encoder) return } if node == nil { err := fmt.Errorf("Unknown node %q", nodeID) - handleStreamResultError(err, pointer.Of(int64(400)), encoder) + handleStreamResultError(err, new(int64(400)), encoder) return } if err := nodeSupportsRpc(node); err != nil { - handleStreamResultError(err, pointer.Of(int64(400)), encoder) + handleStreamResultError(err, new(int64(400)), encoder) return } @@ -312,7 +311,7 @@ func (f *FileSystem) stream(conn io.ReadWriteCloser) { if err != nil { var code *int64 if structs.IsErrNoNodeConn(err) { - code = pointer.Of(int64(404)) + code = new(int64(404)) } handleStreamResultError(err, code, encoder) return @@ -357,7 +356,7 @@ func (f *FileSystem) logs(conn io.ReadWriteCloser) { encoder := codec.NewEncoder(conn, structs.MsgpackHandle) if err := decoder.Decode(&args); err != nil { - handleStreamResultError(err, pointer.Of(int64(500)), encoder) + handleStreamResultError(err, new(int64(500)), encoder) return } @@ -377,7 +376,7 @@ func (f *FileSystem) logs(conn io.ReadWriteCloser) { // Verify the arguments. if args.AllocID == "" { - handleStreamResultError(structs.ErrMissingAllocID, pointer.Of(int64(400)), encoder) + handleStreamResultError(structs.ErrMissingAllocID, new(int64(400)), encoder) return } @@ -390,7 +389,7 @@ func (f *FileSystem) logs(conn io.ReadWriteCloser) { alloc, err := getAlloc(snap, args.AllocID) if structs.IsErrUnknownAllocation(err) { - handleStreamResultError(structs.NewErrUnknownAllocation(args.AllocID), pointer.Of(int64(404)), encoder) + handleStreamResultError(structs.NewErrUnknownAllocation(args.AllocID), new(int64(404)), encoder) return } if err != nil { @@ -415,18 +414,18 @@ func (f *FileSystem) logs(conn io.ReadWriteCloser) { // Make sure Node is valid and new enough to support RPC node, err := snap.NodeByID(nil, nodeID) if err != nil { - handleStreamResultError(err, pointer.Of(int64(500)), encoder) + handleStreamResultError(err, new(int64(500)), encoder) return } if node == nil { err := fmt.Errorf("Unknown node %q", nodeID) - handleStreamResultError(err, pointer.Of(int64(400)), encoder) + handleStreamResultError(err, new(int64(400)), encoder) return } if err := nodeSupportsRpc(node); err != nil { - handleStreamResultError(err, pointer.Of(int64(400)), encoder) + handleStreamResultError(err, new(int64(400)), encoder) return } @@ -440,7 +439,7 @@ func (f *FileSystem) logs(conn io.ReadWriteCloser) { if err != nil { var code *int64 if structs.IsErrNoNodeConn(err) { - code = pointer.Of(int64(404)) + code = new(int64(404)) } handleStreamResultError(err, code, encoder) return diff --git a/nomad/client_meta_endpoint_test.go b/nomad/client_meta_endpoint_test.go index 60a72f16a8d..a0e27ee8cf2 100644 --- a/nomad/client_meta_endpoint_test.go +++ b/nomad/client_meta_endpoint_test.go @@ -9,7 +9,6 @@ import ( "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/client" "github.com/hashicorp/nomad/client/config" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/structs" "github.com/hashicorp/nomad/testutil" "github.com/shoenig/test/must" @@ -104,7 +103,7 @@ func TestNodeMeta_Forward(t *testing.T) { Region: region, }, NodeID: nodeID, - Meta: map[string]*string{"testing": pointer.Of("123")}, + Meta: map[string]*string{"testing": new("123")}, } reply := &structs.NodeMetaResponse{} must.NoError(t, rpc("NodeMeta.Apply", args, reply)) diff --git a/nomad/core_sched.go b/nomad/core_sched.go index ecac54f162d..0d17bf0e6e8 100644 --- a/nomad/core_sched.go +++ b/nomad/core_sched.go @@ -14,7 +14,6 @@ import ( log "github.com/hashicorp/go-hclog" memdb "github.com/hashicorp/go-memdb" version "github.com/hashicorp/go-version" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/state" "github.com/hashicorp/nomad/nomad/structs" @@ -94,7 +93,7 @@ func (c *CoreScheduler) Process(eval *structs.Evaluation) error { // forceGC is used to garbage collect all eligible objects. func (c *CoreScheduler) forceGC(eval *structs.Evaluation) error { // set a minimal threshold for all objects to make force GC possible - force := pointer.Of(time.Millisecond) + force := new(time.Millisecond) if err := c.jobGC(eval, force); err != nil { return err diff --git a/nomad/core_sched_test.go b/nomad/core_sched_test.go index 03340cad397..8a58b72c1e6 100644 --- a/nomad/core_sched_test.go +++ b/nomad/core_sched_test.go @@ -14,7 +14,6 @@ import ( version "github.com/hashicorp/go-version" msgpackrpc "github.com/hashicorp/net-rpc-msgpackrpc/v2" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/state" @@ -532,7 +531,7 @@ func TestCoreScheduler_EvalGC_Batch(t *testing.T) { // set a shorter GC threshold this time gc = s1.coreJobEval(structs.CoreJobEvalGC, jobModifyIdx*2) - core.(*CoreScheduler).customThresholdForObject[structs.CoreJobEvalGC] = pointer.Of(time.Minute) + core.(*CoreScheduler).customThresholdForObject[structs.CoreJobEvalGC] = new(time.Minute) must.NoError(t, core.Process(gc)) // We expect the following: @@ -3019,17 +3018,17 @@ func TestCoreScheduler_ExpiredACLTokenGC(t *testing.T) { // expired, one is not. expiredGlobal := mock.ACLToken() expiredGlobal.Global = true - expiredGlobal.ExpirationTime = pointer.Of(now.Add(-2 * time.Hour)) + expiredGlobal.ExpirationTime = new(now.Add(-2 * time.Hour)) unexpiredGlobal := mock.ACLToken() unexpiredGlobal.Global = true - unexpiredGlobal.ExpirationTime = pointer.Of(now.Add(2 * time.Hour)) + unexpiredGlobal.ExpirationTime = new(now.Add(2 * time.Hour)) expiredLocal := mock.ACLToken() - expiredLocal.ExpirationTime = pointer.Of(now.Add(-2 * time.Hour)) + expiredLocal.ExpirationTime = new(now.Add(-2 * time.Hour)) unexpiredLocal := mock.ACLToken() - unexpiredLocal.ExpirationTime = pointer.Of(now.Add(2 * time.Hour)) + unexpiredLocal.ExpirationTime = new(now.Add(2 * time.Hour)) // Set creation time in the past for all the tokens, otherwise GC won't trigger for _, token := range []*structs.ACLToken{expiredGlobal, unexpiredGlobal, expiredLocal, unexpiredLocal} { @@ -3098,10 +3097,10 @@ func TestCoreScheduler_ExpiredACLTokenGC_Force(t *testing.T) { mockedToken.CreateTime = time.Now().Add(-10 * time.Hour) if i%2 == 0 { expiredGlobalTokens = append(expiredGlobalTokens, mockedToken) - mockedToken.ExpirationTime = pointer.Of(expiryTimeThreshold.Add(-24 * time.Hour)) + mockedToken.ExpirationTime = new(expiryTimeThreshold.Add(-24 * time.Hour)) } else { nonExpiredGlobalTokens = append(nonExpiredGlobalTokens, mockedToken) - mockedToken.ExpirationTime = pointer.Of(expiryTimeThreshold.Add(24 * time.Hour)) + mockedToken.ExpirationTime = new(expiryTimeThreshold.Add(24 * time.Hour)) } } @@ -3113,10 +3112,10 @@ func TestCoreScheduler_ExpiredACLTokenGC_Force(t *testing.T) { mockedToken.CreateTime = time.Now().Add(-10 * time.Hour) if i%2 == 0 { expiredLocalTokens = append(expiredLocalTokens, mockedToken) - mockedToken.ExpirationTime = pointer.Of(expiryTimeThreshold.Add(-24 * time.Hour)) + mockedToken.ExpirationTime = new(expiryTimeThreshold.Add(-24 * time.Hour)) } else { nonExpiredLocalTokens = append(nonExpiredLocalTokens, mockedToken) - mockedToken.ExpirationTime = pointer.Of(expiryTimeThreshold.Add(24 * time.Hour)) + mockedToken.ExpirationTime = new(expiryTimeThreshold.Add(24 * time.Hour)) } } diff --git a/nomad/deployment_endpoint_test.go b/nomad/deployment_endpoint_test.go index 8fc5712b102..bfe55e12e1e 100644 --- a/nomad/deployment_endpoint_test.go +++ b/nomad/deployment_endpoint_test.go @@ -11,7 +11,6 @@ import ( msgpackrpc "github.com/hashicorp/net-rpc-msgpackrpc/v2" "github.com/hashicorp/nomad/acl" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" @@ -519,7 +518,7 @@ func TestDeploymentEndpoint_Promote(t *testing.T) { d.TaskGroups[a.TaskGroup].PlacedCanaries = []string{a.ID} a.DeploymentID = d.ID a.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), } state := s1.fsm.State() @@ -584,7 +583,7 @@ func TestDeploymentEndpoint_Promote_ACL(t *testing.T) { d.TaskGroups[a.TaskGroup].PlacedCanaries = []string{a.ID} a.DeploymentID = d.ID a.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), } state := s1.fsm.State() diff --git a/nomad/deploymentwatcher/deployment_watcher.go b/nomad/deploymentwatcher/deployment_watcher.go index d5905c6ff31..cf461224753 100644 --- a/nomad/deploymentwatcher/deployment_watcher.go +++ b/nomad/deploymentwatcher/deployment_watcher.go @@ -11,7 +11,6 @@ import ( log "github.com/hashicorp/go-hclog" memdb "github.com/hashicorp/go-memdb" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/state" "github.com/hashicorp/nomad/nomad/structs" @@ -29,7 +28,7 @@ var ( // allocations part of a deployment to be rescheduled. We create a one off // variable to avoid creating a new object for every request. allowRescheduleTransition = &structs.DesiredTransition{ - Reschedule: pointer.Of(true), + Reschedule: new(true), } ) @@ -237,7 +236,7 @@ func (w *deploymentWatcher) setAllocHealth( resp.DeploymentModifyIndex = index resp.Index = index if j != nil { - resp.RevertedJobVersion = pointer.Of(j.Version) + resp.RevertedJobVersion = new(j.Version) } return nil } @@ -398,7 +397,7 @@ func (w *deploymentWatcher) FailDeployment( resp.DeploymentModifyIndex = i resp.Index = i if rollbackJob != nil { - resp.RevertedJobVersion = pointer.Of(rollbackJob.Version) + resp.RevertedJobVersion = new(rollbackJob.Version) } return nil } diff --git a/nomad/deploymentwatcher/deployments_watcher_test.go b/nomad/deploymentwatcher/deployments_watcher_test.go index 30e2dfb5d41..f28e6fd9f26 100644 --- a/nomad/deploymentwatcher/deployments_watcher_test.go +++ b/nomad/deploymentwatcher/deployments_watcher_test.go @@ -11,7 +11,6 @@ import ( "github.com/hashicorp/go-memdb" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/testlog" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" @@ -342,7 +341,7 @@ func TestWatcher_PromoteDeployment_HealthyCanaries(t *testing.T) { d.TaskGroups[a.TaskGroup].DesiredCanaries = 1 d.TaskGroups[a.TaskGroup].PlacedCanaries = []string{a.ID} a.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), } a.DeploymentID = d.ID must.NoError(t, m.state.UpsertJob(structs.MsgTypeTestSetup, m.nextIndex(), nil, j)) @@ -908,7 +907,7 @@ func TestDeploymentWatcher_Watch_ProgressDeadline(t *testing.T) { // Update the alloc to be unhealthy and require that nothing happens. a2 := a.Copy() a2.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(false), + Healthy: new(false), Timestamp: now, } must.NoError(t, m.state.UpdateAllocsFromClient(structs.MsgTypeTestSetup, 100, []*structs.Allocation{a2})) @@ -988,7 +987,7 @@ func TestDeploymentWatcher_ProgressCutoff(t *testing.T) { // Update the first allocation to be healthy a3 := a.Copy() - a3.DeploymentStatus = &structs.AllocDeploymentStatus{Healthy: pointer.Of(true)} + a3.DeploymentStatus = &structs.AllocDeploymentStatus{Healthy: new(true)} must.NoError(t, m.state.UpsertAllocs(structs.MsgTypeTestSetup, m.nextIndex(), []*structs.Allocation{a3})) // Get the updated deployment @@ -1007,7 +1006,7 @@ func TestDeploymentWatcher_ProgressCutoff(t *testing.T) { // Update the second allocation to be healthy a4 := a2.Copy() - a4.DeploymentStatus = &structs.AllocDeploymentStatus{Healthy: pointer.Of(true)} + a4.DeploymentStatus = &structs.AllocDeploymentStatus{Healthy: new(true)} must.NoError(t, m.state.UpsertAllocs(structs.MsgTypeTestSetup, m.nextIndex(), []*structs.Allocation{a4})) // Get the updated deployment @@ -1059,7 +1058,7 @@ func TestDeploymentWatcher_Watch_ProgressDeadline_Canaries(t *testing.T) { // Update the alloc to be unhealthy and require that nothing happens. a2 := a.Copy() a2.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), Timestamp: now, } must.NoError(t, m.state.UpdateAllocsFromClient(structs.MsgTypeTestSetup, m.nextIndex(), []*structs.Allocation{a2})) @@ -1114,7 +1113,7 @@ func TestDeploymentWatcher_PromotedCanary_UpdatedAllocs(t *testing.T) { a.Job = j a.JobID = j.ID a.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), Timestamp: now, } must.NoError(t, m.state.UpsertJob(structs.MsgTypeTestSetup, m.nextIndex(), nil, j)) @@ -1133,7 +1132,7 @@ func TestDeploymentWatcher_PromotedCanary_UpdatedAllocs(t *testing.T) { a2.Job = j a2.JobID = j.ID a2.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), Timestamp: now, } d.TaskGroups["web"].RequireProgressBy = time.Now().Add(2 * time.Second) @@ -1229,7 +1228,7 @@ func TestDeploymentWatcher_ProgressDeadline_LatePromote(t *testing.T) { canary2.ModifyTime = now.UnixNano() canary2.DeploymentStatus = &structs.AllocDeploymentStatus{ Canary: true, - Healthy: pointer.Of(true), + Healthy: new(true), Timestamp: now, } @@ -1248,7 +1247,7 @@ func TestDeploymentWatcher_ProgressDeadline_LatePromote(t *testing.T) { canary1.ModifyTime = now.UnixNano() canary1.DeploymentStatus = &structs.AllocDeploymentStatus{ Canary: true, - Healthy: pointer.Of(true), + Healthy: new(true), Timestamp: now, } @@ -1306,7 +1305,7 @@ func TestDeploymentWatcher_ProgressDeadline_LatePromote(t *testing.T) { alloc1a.ModifyTime = now.UnixNano() alloc1a.DeploymentStatus = &structs.AllocDeploymentStatus{ Canary: false, - Healthy: pointer.Of(true), + Healthy: new(true), Timestamp: now, } @@ -1315,7 +1314,7 @@ func TestDeploymentWatcher_ProgressDeadline_LatePromote(t *testing.T) { alloc1b.ModifyTime = now.UnixNano() alloc1b.DeploymentStatus = &structs.AllocDeploymentStatus{ Canary: false, - Healthy: pointer.Of(true), + Healthy: new(true), Timestamp: now, } @@ -1380,7 +1379,7 @@ func TestDeploymentWatcher_Watch_StartWithoutProgressDeadline(t *testing.T) { // Update the alloc to be unhealthy a2 := a.Copy() a2.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(false), + Healthy: new(false), Timestamp: time.Now(), } must.NoError(t, m.state.UpdateAllocsFromClient(structs.MsgTypeTestSetup, m.nextIndex(), []*structs.Allocation{a2})) @@ -1438,7 +1437,7 @@ func TestDeploymentWatcher_Watch_FailEarly(t *testing.T) { // Update the alloc to be unhealthy a2 := a.Copy() a2.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(false), + Healthy: new(false), Timestamp: now, } must.Nil(t, m.state.UpdateAllocsFromClient(structs.MsgTypeTestSetup, m.nextIndex(), []*structs.Allocation{a2})) diff --git a/nomad/drainer/drainer.go b/nomad/drainer/drainer.go index 3bd26b7d508..9898da15a55 100644 --- a/nomad/drainer/drainer.go +++ b/nomad/drainer/drainer.go @@ -10,7 +10,6 @@ import ( log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/state" "github.com/hashicorp/nomad/nomad/structs" @@ -399,14 +398,14 @@ func (n *NodeDrainer) drainAllocs(future *structs.BatchFuture, allocs []*structs transitions := make(map[string]*structs.DesiredTransition, len(allocs)) for _, alloc := range allocs { transitions[alloc.ID] = &structs.DesiredTransition{ - Migrate: pointer.Of(true), + Migrate: new(true), } // When draining batch job allocations, the allocation should be // be stopped. Setting this ensures the allocation is stopped in // the migration process, but that a new allocation is not placed. if alloc.Job.Type == structs.JobTypeBatch { - transitions[alloc.ID].MigrateDisablePlacement = pointer.Of(true) + transitions[alloc.ID].MigrateDisablePlacement = new(true) } jobs[alloc.JobNamespacedID()] = alloc.Job } diff --git a/nomad/drainer/watch_jobs_test.go b/nomad/drainer/watch_jobs_test.go index ce8eddcbbbc..ff32bfc063d 100644 --- a/nomad/drainer/watch_jobs_test.go +++ b/nomad/drainer/watch_jobs_test.go @@ -14,7 +14,6 @@ import ( "golang.org/x/time/rate" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/testlog" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" @@ -142,7 +141,7 @@ func TestDrainingJobWatcher_DrainJobs(t *testing.T) { for i := 0; i < count; i++ { a := newAlloc(drainingNode, job) a.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), } allocs = append(allocs, a) } @@ -164,7 +163,7 @@ func TestDrainingJobWatcher_DrainJobs(t *testing.T) { // the old ones drainedAllocs := make([]*structs.Allocation, len(drains.Allocs)) for i, a := range drains.Allocs { - a.DesiredTransition.Migrate = pointer.Of(true) + a.DesiredTransition.Migrate = new(true) // create a copy so we can reuse this slice drainedAllocs[i] = a.Copy() @@ -221,7 +220,7 @@ func TestDrainingJobWatcher_DrainJobs(t *testing.T) { for _, a := range replacements { a.ClientStatus = structs.AllocClientStatusRunning a.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), } } must.NoError(t, store.UpsertAllocs(structs.MsgTypeTestSetup, index, replacements)) @@ -235,7 +234,7 @@ func TestDrainingJobWatcher_DrainJobs(t *testing.T) { // Fake migrations once more to finish the drain drainedAllocs = make([]*structs.Allocation, len(drains.Allocs)) for i, a := range drains.Allocs { - a.DesiredTransition.Migrate = pointer.Of(true) + a.DesiredTransition.Migrate = new(true) // create a copy so we can reuse this slice drainedAllocs[i] = a.Copy() @@ -265,7 +264,7 @@ func TestDrainingJobWatcher_DrainJobs(t *testing.T) { for _, a := range replacements { a.ClientStatus = structs.AllocClientStatusRunning a.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), } } must.NoError(t, store.UpsertAllocs(structs.MsgTypeTestSetup, index, replacements)) @@ -279,7 +278,7 @@ func TestDrainingJobWatcher_DrainJobs(t *testing.T) { // Fake migrations once more to finish the drain drainedAllocs = make([]*structs.Allocation, len(drains.Allocs)) for i, a := range drains.Allocs { - a.DesiredTransition.Migrate = pointer.Of(true) + a.DesiredTransition.Migrate = new(true) // create a copy so we can reuse this slice drainedAllocs[i] = a.Copy() @@ -309,7 +308,7 @@ func TestDrainingJobWatcher_DrainJobs(t *testing.T) { for _, a := range replacements { a.ClientStatus = structs.AllocClientStatusRunning a.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), } } must.NoError(t, store.UpsertAllocs(structs.MsgTypeTestSetup, index, replacements)) @@ -351,7 +350,7 @@ func TestDrainingJobWatcher_HandleTaskGroup(t *testing.T) { expectDone: false, addAllocFn: func(i int, a *structs.Allocation, drainingID, runningID string) { if i == 1 { - a.DesiredTransition.Migrate = pointer.Of(true) + a.DesiredTransition.Migrate = new(true) } }, }, @@ -363,7 +362,7 @@ func TestDrainingJobWatcher_HandleTaskGroup(t *testing.T) { maxParallel: 5, addAllocFn: func(i int, a *structs.Allocation, drainingID, runningID string) { if i > 0 && i%2 == 0 { - a.DesiredTransition.Migrate = pointer.Of(true) + a.DesiredTransition.Migrate = new(true) } }, }, @@ -410,7 +409,7 @@ func TestDrainingJobWatcher_HandleTaskGroup(t *testing.T) { expectDone: false, addAllocFn: func(i int, a *structs.Allocation, drainingID, runningID string) { if i == 0 { - a.DesiredTransition.Migrate = pointer.Of(true) + a.DesiredTransition.Migrate = new(true) return } a.NodeID = runningID @@ -637,7 +636,7 @@ func TestDrainingJobWatcher_HandleTaskGroup(t *testing.T) { // Default to being healthy on the draining node a.NodeID = drainingNode.ID a.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), } if tc.addAllocFn != nil { tc.addAllocFn(i, a, drainingNode.ID, runningNode.ID) @@ -684,7 +683,7 @@ func TestHandleTaskGroup_Migrations(t *testing.T) { a.TaskGroup = job.TaskGroups[0].Name a.NodeID = n.ID a.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(false), + Healthy: new(false), } if i%2 == 0 { @@ -754,7 +753,7 @@ func TestHandleTaskGroup_GarbageCollectedNode(t *testing.T) { a.TaskGroup = job.TaskGroups[0].Name a.NodeID = n.ID a.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(false), + Healthy: new(false), } if i%2 == 0 { diff --git a/nomad/drainer/watch_nodes_test.go b/nomad/drainer/watch_nodes_test.go index 73f1289a295..de8d91ec101 100644 --- a/nomad/drainer/watch_nodes_test.go +++ b/nomad/drainer/watch_nodes_test.go @@ -12,7 +12,6 @@ import ( "github.com/shoenig/test/wait" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/state" @@ -44,7 +43,7 @@ func TestNodeDrainWatcher_AddNodes(t *testing.T) { alloc1.Job = job alloc1.TaskGroup = job.TaskGroups[0].Name alloc1.NodeID = n1.ID - alloc1.DeploymentStatus = &structs.AllocDeploymentStatus{Healthy: pointer.Of(true)} + alloc1.DeploymentStatus = &structs.AllocDeploymentStatus{Healthy: new(true)} alloc2 := alloc1.Copy() alloc2.ID = uuid.Generate() alloc2.NodeID = n2.ID @@ -225,7 +224,7 @@ func testNodeDrainWatcherSetup( alloc.Job = job alloc.TaskGroup = job.TaskGroups[0].Name alloc.NodeID = node.ID - alloc.DeploymentStatus = &structs.AllocDeploymentStatus{Healthy: pointer.Of(true)} + alloc.DeploymentStatus = &structs.AllocDeploymentStatus{Healthy: new(true)} index++ must.NoError(t, store.UpsertAllocs( structs.MsgTypeTestSetup, index, []*structs.Allocation{alloc})) diff --git a/nomad/drainer_int_test.go b/nomad/drainer_int_test.go index a0a3029c7b0..8e3a78ecd8e 100644 --- a/nomad/drainer_int_test.go +++ b/nomad/drainer_int_test.go @@ -16,7 +16,6 @@ import ( "github.com/shoenig/test/wait" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/drainer" "github.com/hashicorp/nomad/nomad/mock" @@ -63,7 +62,7 @@ func allocClientStateSimulator(t *testing.T, errCh chan<- error, ctx context.Con } newAlloc := alloc.Copy() newAlloc.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), Timestamp: now, } updates = append(updates, newAlloc) diff --git a/nomad/encrypter_test.go b/nomad/encrypter_test.go index 0f3fdd27530..568f09c3ca2 100644 --- a/nomad/encrypter_test.go +++ b/nomad/encrypter_test.go @@ -26,7 +26,6 @@ import ( msgpackrpc "github.com/hashicorp/net-rpc-msgpackrpc/v2" "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/helper" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/testlog" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/auth" @@ -938,7 +937,7 @@ func TestEncrypter_TransitConfigFallback(t *testing.T) { TLSCaPath: "/etc/certs/ca", TLSCertFile: "/var/certs/vault.crt", TLSKeyFile: "/var/certs/vault.key", - TLSSkipVerify: pointer.Of(true), + TLSSkipVerify: new(true), TLSServerName: "foo", Token: "vault-token", }}, diff --git a/nomad/event_endpoint.go b/nomad/event_endpoint.go index ae0141b024c..a3768e184bd 100644 --- a/nomad/event_endpoint.go +++ b/nomad/event_endpoint.go @@ -12,7 +12,6 @@ import ( "github.com/hashicorp/go-msgpack/v2/codec" "github.com/hashicorp/nomad/acl" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/peers" "github.com/hashicorp/nomad/nomad/stream" "github.com/hashicorp/nomad/nomad/structs" @@ -38,13 +37,13 @@ func (e *Event) stream(conn io.ReadWriteCloser) { encoder := codec.NewEncoder(conn, structs.MsgpackHandle) if err := decoder.Decode(&args); err != nil { - handleJsonResultError(err, pointer.Of(int64(500)), encoder) + handleJsonResultError(err, new(int64(500)), encoder) return } authErr := e.srv.Authenticate(nil, &args) if authErr != nil { - handleJsonResultError(structs.ErrPermissionDenied, pointer.Of(int64(403)), encoder) + handleJsonResultError(structs.ErrPermissionDenied, new(int64(403)), encoder) return } @@ -52,7 +51,7 @@ func (e *Event) stream(conn io.ReadWriteCloser) { if args.Region != e.srv.config.Region { err := e.forwardStreamingRPC(args.Region, "Event.Stream", args, conn) if err != nil { - handleJsonResultError(err, pointer.Of(int64(500)), encoder) + handleJsonResultError(err, new(int64(500)), encoder) } return } @@ -61,13 +60,13 @@ func (e *Event) stream(conn io.ReadWriteCloser) { resolvedACL, err := e.srv.ResolveACL(&args) if err != nil { - handleJsonResultError(structs.ErrPermissionDenied, pointer.Of(int64(403)), encoder) + handleJsonResultError(structs.ErrPermissionDenied, new(int64(403)), encoder) return } validatedNses, err := e.validateACL(args.Namespace, args.Topics, resolvedACL) if err != nil { - handleJsonResultError(structs.ErrPermissionDenied, pointer.Of(int64(403)), encoder) + handleJsonResultError(structs.ErrPermissionDenied, new(int64(403)), encoder) return } @@ -114,7 +113,7 @@ func (e *Event) stream(conn io.ReadWriteCloser) { // Get the servers broker and subscribe publisher, err := e.srv.State().EventBroker() if err != nil { - handleJsonResultError(err, pointer.Of(int64(500)), encoder) + handleJsonResultError(err, new(int64(500)), encoder) return } @@ -124,7 +123,7 @@ func (e *Event) stream(conn io.ReadWriteCloser) { subscription, subErr = publisher.Subscribe(subReq) if subErr != nil { - handleJsonResultError(subErr, pointer.Of(int64(500)), encoder) + handleJsonResultError(subErr, new(int64(500)), encoder) return } defer subscription.Unsubscribe() @@ -217,7 +216,7 @@ OUTER: } if streamErr != nil { - handleJsonResultError(streamErr, pointer.Of(int64(500)), encoder) + handleJsonResultError(streamErr, new(int64(500)), encoder) return } diff --git a/nomad/event_endpoint_test.go b/nomad/event_endpoint_test.go index 7f5ece7d036..28d0cdb9a7b 100644 --- a/nomad/event_endpoint_test.go +++ b/nomad/event_endpoint_test.go @@ -19,7 +19,6 @@ import ( msgpackrpc "github.com/hashicorp/net-rpc-msgpackrpc/v2" "github.com/hashicorp/nomad/acl" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/stream" "github.com/hashicorp/nomad/nomad/structs" @@ -713,7 +712,7 @@ func TestEventStream_ACLTokenExpiry(t *testing.T) { // Create and upsert and ACL token which has a short expiry set. aclTokenWithExpiry := mock.ACLManagementToken() - aclTokenWithExpiry.ExpirationTime = pointer.Of(time.Now().Add(2 * time.Second)) + aclTokenWithExpiry.ExpirationTime = new(time.Now().Add(2 * time.Second)) must.NoError(t, testServer.fsm.State().UpsertACLTokens( structs.MsgTypeTestSetup, 10, []*structs.ACLToken{aclTokenWithExpiry})) diff --git a/nomad/fsm.go b/nomad/fsm.go index cdf12e24127..685836a53a3 100644 --- a/nomad/fsm.go +++ b/nomad/fsm.go @@ -16,7 +16,6 @@ import ( "github.com/hashicorp/go-memdb" metrics "github.com/hashicorp/go-metrics/compat" "github.com/hashicorp/go-msgpack/v2/codec" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/state" "github.com/hashicorp/nomad/nomad/structs" @@ -880,7 +879,7 @@ func (n *nomadFSM) handleJobDeregister(index uint64, jobID, namespace string, pu if err != nil { return err } - transition := &structs.DesiredTransition{NoShutdownDelay: pointer.Of(true)} + transition := &structs.DesiredTransition{NoShutdownDelay: new(true)} for _, alloc := range allocs { err := n.state.UpdateAllocDesiredTransitionTxn(tx, index, alloc.ID, transition) if err != nil { diff --git a/nomad/fsm_test.go b/nomad/fsm_test.go index 320ed7f7a77..7ea5bedf0a4 100644 --- a/nomad/fsm_test.go +++ b/nomad/fsm_test.go @@ -23,7 +23,6 @@ import ( "github.com/stretchr/testify/require" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/testlog" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" @@ -1569,7 +1568,7 @@ func TestFSM_UpdateAllocDesiredTransition(t *testing.T) { must.NoError(t, state.UpsertAllocs(structs.MsgTypeTestSetup, 11, []*structs.Allocation{alloc, alloc2})) t1 := &structs.DesiredTransition{ - Migrate: pointer.Of(true), + Migrate: new(true), } eval := &structs.Evaluation{ @@ -1905,7 +1904,7 @@ func TestFSM_DeploymentPromotion(t *testing.T) { c1.DeploymentID = d.ID d.TaskGroups[c1.TaskGroup].PlacedCanaries = append(d.TaskGroups[c1.TaskGroup].PlacedCanaries, c1.ID) c1.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), } c2 := mock.Alloc() c2.JobID = j.ID @@ -1913,7 +1912,7 @@ func TestFSM_DeploymentPromotion(t *testing.T) { d.TaskGroups[c2.TaskGroup].PlacedCanaries = append(d.TaskGroups[c2.TaskGroup].PlacedCanaries, c2.ID) c2.TaskGroup = tg2.Name c2.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), } if err := state.UpsertAllocs(structs.MsgTypeTestSetup, 3, []*structs.Allocation{c1, c2}); err != nil { diff --git a/nomad/job_endpoint.go b/nomad/job_endpoint.go index 94f2c523fa1..b089879baea 100644 --- a/nomad/job_endpoint.go +++ b/nomad/job_endpoint.go @@ -20,7 +20,6 @@ import ( "github.com/hashicorp/go-set/v3" "github.com/hashicorp/nomad/acl" "github.com/hashicorp/nomad/helper" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/state" "github.com/hashicorp/nomad/nomad/state/paginator" @@ -47,7 +46,7 @@ var ( // allocations to be force rescheduled. We create a one off // variable to avoid creating a new object for every request. allowForceRescheduleTransition = &structs.DesiredTransition{ - ForceReschedule: pointer.Of(true), + ForceReschedule: new(true), } ) diff --git a/nomad/job_endpoint_hook_connect.go b/nomad/job_endpoint_hook_connect.go index b753f984a7f..b20e2ca5078 100644 --- a/nomad/job_endpoint_hook_connect.go +++ b/nomad/job_endpoint_hook_connect.go @@ -14,7 +14,6 @@ import ( "github.com/hashicorp/go-set/v3" "github.com/hashicorp/nomad/client/taskenv" "github.com/hashicorp/nomad/helper/envoy" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/structs" ) @@ -442,7 +441,7 @@ func gatewayProxy(gateway *structs.ConsulGateway, mode string) *structs.ConsulGa // set default connect timeout if not set if proxy.ConnectTimeout == nil { - proxy.ConnectTimeout = pointer.Of(defaultConnectTimeout) + proxy.ConnectTimeout = new(defaultConnectTimeout) } if mode == "bridge" || strings.HasPrefix(mode, "cni/") { diff --git a/nomad/job_endpoint_hook_connect_test.go b/nomad/job_endpoint_hook_connect_test.go index cd1d96eb295..ae56e3fb882 100644 --- a/nomad/job_endpoint_hook_connect_test.go +++ b/nomad/job_endpoint_hook_connect_test.go @@ -10,7 +10,6 @@ import ( "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/helper" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" "github.com/hashicorp/nomad/testutil" @@ -934,7 +933,7 @@ func TestJobEndpointConnect_gatewayProxyIsDefault(t *testing.T) { t.Run("unrelated fields set", func(t *testing.T) { result := gatewayProxyIsDefault(&structs.ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(2 * time.Second), + ConnectTimeout: new(2 * time.Second), Config: map[string]interface{}{"foo": 1}, }) require.True(t, result) @@ -1055,7 +1054,7 @@ func TestJobEndpointConnect_gatewayProxy(t *testing.T) { }, }, "bridge") require.Equal(t, &structs.ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(defaultConnectTimeout), + ConnectTimeout: new(defaultConnectTimeout), EnvoyGatewayNoDefaultBind: true, EnvoyGatewayBindTaggedAddresses: false, EnvoyGatewayBindAddresses: map[string]*structs.ConsulGatewayBindAddress{ @@ -1069,7 +1068,7 @@ func TestJobEndpointConnect_gatewayProxy(t *testing.T) { t.Run("ingress set defaults", func(t *testing.T) { result := gatewayProxy(&structs.ConsulGateway{ Proxy: &structs.ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(2 * time.Second), + ConnectTimeout: new(2 * time.Second), Config: map[string]interface{}{"foo": 1}, }, Ingress: &structs.ConsulIngressConfigEntry{ @@ -1083,7 +1082,7 @@ func TestJobEndpointConnect_gatewayProxy(t *testing.T) { }, }, "bridge") require.Equal(t, &structs.ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(2 * time.Second), + ConnectTimeout: new(2 * time.Second), Config: map[string]interface{}{"foo": 1}, EnvoyGatewayNoDefaultBind: true, EnvoyGatewayBindTaggedAddresses: false, @@ -1123,7 +1122,7 @@ func TestJobEndpointConnect_gatewayProxy(t *testing.T) { t.Run("terminating set defaults", func(t *testing.T) { result := gatewayProxy(&structs.ConsulGateway{ Proxy: &structs.ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(2 * time.Second), + ConnectTimeout: new(2 * time.Second), EnvoyDNSDiscoveryType: "STRICT_DNS", }, Terminating: &structs.ConsulTerminatingConfigEntry{ @@ -1137,7 +1136,7 @@ func TestJobEndpointConnect_gatewayProxy(t *testing.T) { }, }, "bridge") require.Equal(t, &structs.ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(2 * time.Second), + ConnectTimeout: new(2 * time.Second), EnvoyGatewayNoDefaultBind: true, EnvoyGatewayBindTaggedAddresses: false, EnvoyDNSDiscoveryType: "STRICT_DNS", @@ -1174,14 +1173,14 @@ func TestJobEndpointConnect_gatewayProxy(t *testing.T) { t.Run("mesh set defaults in bridge", func(t *testing.T) { result := gatewayProxy(&structs.ConsulGateway{ Proxy: &structs.ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(2 * time.Second), + ConnectTimeout: new(2 * time.Second), }, Mesh: &structs.ConsulMeshConfigEntry{ // nothing }, }, "bridge") require.Equal(t, &structs.ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(2 * time.Second), + ConnectTimeout: new(2 * time.Second), EnvoyGatewayNoDefaultBind: true, EnvoyGatewayBindTaggedAddresses: false, EnvoyGatewayBindAddresses: map[string]*structs.ConsulGatewayBindAddress{ @@ -1200,14 +1199,14 @@ func TestJobEndpointConnect_gatewayProxy(t *testing.T) { t.Run("mesh set defaults in host", func(t *testing.T) { result := gatewayProxy(&structs.ConsulGateway{ Proxy: &structs.ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(2 * time.Second), + ConnectTimeout: new(2 * time.Second), }, Mesh: &structs.ConsulMeshConfigEntry{ // nothing }, }, "host") require.Equal(t, &structs.ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(2 * time.Second), + ConnectTimeout: new(2 * time.Second), }, result) }) diff --git a/nomad/job_endpoint_hook_vault_ce_test.go b/nomad/job_endpoint_hook_vault_ce_test.go index 541e8981bd7..c1e84fbcc8e 100644 --- a/nomad/job_endpoint_hook_vault_ce_test.go +++ b/nomad/job_endpoint_hook_vault_ce_test.go @@ -10,7 +10,6 @@ import ( "testing" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" "github.com/hashicorp/nomad/nomad/structs/config" @@ -23,7 +22,7 @@ func TestJobEndpointHook_VaultCE(t *testing.T) { srv, cleanup := TestServer(t, func(c *Config) { c.NumSchedulers = 0 - c.VaultConfigs[structs.VaultDefaultCluster].Enabled = pointer.Of(true) + c.VaultConfigs[structs.VaultDefaultCluster].Enabled = new(true) c.VaultConfigs[structs.VaultDefaultCluster].DefaultIdentity = &config.WorkloadIdentityConfig{ Name: "vault_default", Audience: []string{"vault.io"}, diff --git a/nomad/job_endpoint_hooks_test.go b/nomad/job_endpoint_hooks_test.go index 90abf8a7e55..61bf8070389 100644 --- a/nomad/job_endpoint_hooks_test.go +++ b/nomad/job_endpoint_hooks_test.go @@ -9,7 +9,6 @@ import ( "time" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" "github.com/hashicorp/nomad/nomad/structs/config" @@ -75,7 +74,7 @@ func Test_jobValidate_Validate_consul_service(t *testing.T) { structs.ConsulDefaultCluster: { ServiceIdentity: &config.WorkloadIdentityConfig{ Audience: []string{"consul.io"}, - TTL: pointer.Of(time.Hour), + TTL: new(time.Hour), }, }, }, @@ -178,7 +177,7 @@ func Test_jobValidate_Validate_vault(t *testing.T) { structs.VaultDefaultCluster: { DefaultIdentity: &config.WorkloadIdentityConfig{ Audience: []string{"vault.io"}, - TTL: pointer.Of(time.Hour), + TTL: new(time.Hour), }, }, }, @@ -194,7 +193,7 @@ func Test_jobValidate_Validate_vault(t *testing.T) { "other": { DefaultIdentity: &config.WorkloadIdentityConfig{ Audience: []string{"vault.io"}, - TTL: pointer.Of(time.Hour), + TTL: new(time.Hour), }, }, }, diff --git a/nomad/job_endpoint_test.go b/nomad/job_endpoint_test.go index 5b4588bddae..9998b0cec89 100644 --- a/nomad/job_endpoint_test.go +++ b/nomad/job_endpoint_test.go @@ -21,7 +21,6 @@ import ( "github.com/hashicorp/nomad/client/lib/idset" "github.com/hashicorp/nomad/client/lib/numalib" "github.com/hashicorp/nomad/client/lib/numalib/hw" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" @@ -622,7 +621,7 @@ func TestJobEndpoint_Register_ConnectIngressGateway_full(t *testing.T) { job.TaskGroups[0].Services[0].Connect = &structs.ConsulConnect{ Gateway: &structs.ConsulGateway{ Proxy: &structs.ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(1 * time.Second), + ConnectTimeout: new(1 * time.Second), EnvoyGatewayBindTaggedAddresses: true, EnvoyGatewayBindAddresses: map[string]*structs.ConsulGatewayBindAddress{ "service1": { @@ -1729,7 +1728,7 @@ func TestJobEndpoint_Register_Vault_MultiNamespaces(t *testing.T) { testutil.WaitForLeader(t, s1.RPC) // Enable vault - s1.config.GetDefaultVault().Enabled = pointer.Of(true) + s1.config.GetDefaultVault().Enabled = new(true) // Create the register request with a job asking for a vault policy but // don't send a Vault token @@ -2024,12 +2023,12 @@ func TestJobEndpoint_Register_ValidateMemoryMax_NodePool(t *testing.T) { withMemOversub := mock.NodePool() withMemOversub.SchedulerConfiguration = &structs.NodePoolSchedulerConfiguration{ - MemoryOversubscriptionEnabled: pointer.Of(true), + MemoryOversubscriptionEnabled: new(true), } noMemOversub := mock.NodePool() noMemOversub.SchedulerConfiguration = &structs.NodePoolSchedulerConfiguration{ - MemoryOversubscriptionEnabled: pointer.Of(false), + MemoryOversubscriptionEnabled: new(false), } s.State().UpsertNodePools(structs.MsgTypeTestSetup, 100, []*structs.NodePool{ @@ -2458,7 +2457,7 @@ func TestJobEndpoint_Revert(t *testing.T) { revertReq := &structs.JobRevertRequest{ JobID: job.ID, JobVersion: 0, - EnforcePriorVersion: pointer.Of(uint64(10)), + EnforcePriorVersion: new(uint64(10)), WriteRequest: structs.WriteRequest{ Region: "global", Namespace: job.Namespace, @@ -2491,7 +2490,7 @@ func TestJobEndpoint_Revert(t *testing.T) { revertReq = &structs.JobRevertRequest{ JobID: job.ID, JobVersion: 0, - EnforcePriorVersion: pointer.Of(uint64(1)), + EnforcePriorVersion: new(uint64(1)), WriteRequest: structs.WriteRequest{ Region: "global", Namespace: job.Namespace, @@ -6408,7 +6407,7 @@ func TestJobEndpoint_ImplicitConstraints_Vault(t *testing.T) { testutil.WaitForLeader(t, s1.RPC) // Enable vault - s1.config.GetDefaultVault().Enabled = pointer.Of(true) + s1.config.GetDefaultVault().Enabled = new(true) // Create the register request with a job using Vault. job := mock.Job() @@ -7384,7 +7383,7 @@ func TestJobEndpoint_Scale(t *testing.T) { Target: map[string]string{ structs.ScalingTargetGroup: groupName, }, - Count: pointer.Of(int64(originalCount + 1)), + Count: new(int64(originalCount + 1)), Message: "because of the load", Meta: map[string]interface{}{ "metrics": map[string]string{ @@ -7469,7 +7468,7 @@ func TestJobEndpoint_Scale_DeploymentBlocking(t *testing.T) { }, Meta: scalingMetadata, Message: scalingMessage, - Count: pointer.Of(newCount), + Count: new(newCount), WriteRequest: structs.WriteRequest{ Region: "global", Namespace: job.Namespace, @@ -7509,7 +7508,7 @@ func TestJobEndpoint_ScaleEnforceIndex(t *testing.T) { Target: map[string]string{ structs.ScalingTargetGroup: groupName, }, - Count: pointer.Of(int64(originalCount + 1)), + Count: new(int64(originalCount + 1)), Message: "because of the load", Meta: map[string]interface{}{ "metrics": map[string]string{ @@ -7807,7 +7806,7 @@ func TestJobEndpoint_Scale_Invalid(t *testing.T) { Target: map[string]string{ structs.ScalingTargetGroup: job.TaskGroups[0].Name, }, - Count: pointer.Of(int64(count) + 1), + Count: new(int64(count) + 1), Message: "this should fail", Meta: map[string]interface{}{ "metrics": map[string]string{ @@ -7831,7 +7830,7 @@ func TestJobEndpoint_Scale_Invalid(t *testing.T) { err = state.UpsertJob(structs.MsgTypeTestSetup, 1000, nil, job) require.Nil(err) - scale.Count = pointer.Of(int64(10)) + scale.Count = new(int64(10)) scale.Message = "error message" scale.Error = true err = msgpackrpc.CallWithCodec(codec, "Job.Scale", scale, &resp) @@ -7864,7 +7863,7 @@ func TestJobEndpoint_Scale_TaskGroupOutOfBounds(t *testing.T) { Target: map[string]string{ structs.ScalingTargetGroup: job.TaskGroups[0].Name, }, - Count: pointer.Of(pol.Max + 1), + Count: new(pol.Max + 1), Message: "out of bounds", PolicyOverride: false, WriteRequest: structs.WriteRequest{ @@ -7876,7 +7875,7 @@ func TestJobEndpoint_Scale_TaskGroupOutOfBounds(t *testing.T) { require.Error(err) require.Contains(err.Error(), "group count was greater than scaling policy maximum: 11 > 10") - scale.Count = pointer.Of(int64(2)) + scale.Count = new(int64(2)) err = msgpackrpc.CallWithCodec(codec, "Job.Scale", scale, &resp) require.Error(err) require.Contains(err.Error(), "group count was less than scaling policy minimum: 2 < 3") @@ -7907,7 +7906,7 @@ func TestJobEndpoint_Scale_JobOutOfBounds(t *testing.T) { Target: map[string]string{ structs.ScalingTargetGroup: job.TaskGroups[0].Name, }, - Count: pointer.Of(int64(requestedCount)), + Count: new(int64(requestedCount)), Message: "count too high", PolicyOverride: false, WriteRequest: structs.WriteRequest{ @@ -8008,7 +8007,7 @@ func TestJobEndpoint_Scale_Priority(t *testing.T) { Target: map[string]string{ structs.ScalingTargetGroup: groupName, }, - Count: pointer.Of(int64(originalCount + 1)), + Count: new(int64(originalCount + 1)), Message: "scotty, we need more power", PolicyOverride: false, WriteRequest: structs.WriteRequest{ @@ -8053,7 +8052,7 @@ func TestJobEndpoint_Scale_SystemJob(t *testing.T) { Target: map[string]string{ structs.ScalingTargetGroup: mockSystemJob.TaskGroups[0].Name, }, - Count: pointer.Of(int64(0)), + Count: new(int64(0)), WriteRequest: structs.WriteRequest{ Region: DefaultRegion, Namespace: mockSystemJob.Namespace, @@ -8065,21 +8064,21 @@ func TestJobEndpoint_Scale_SystemJob(t *testing.T) { must.NoError(t, err) // Scale to a negative number - scaleReq.Count = pointer.Of(int64(-5)) + scaleReq.Count = new(int64(-5)) resp = structs.JobRegisterResponse{} must.ErrorContains(t, msgpackrpc.CallWithCodec(codec, "Job.Scale", scaleReq, &resp), `400,scaling action count can't be negative`) // Scale back to 1 - scaleReq.Count = pointer.Of(int64(1)) + scaleReq.Count = new(int64(1)) resp = structs.JobRegisterResponse{} err = msgpackrpc.CallWithCodec(codec, "Job.Scale", scaleReq, &resp) must.NoError(t, err) // Scale beyond 1 - scaleReq.Count = pointer.Of(int64(13)) + scaleReq.Count = new(int64(13)) resp = structs.JobRegisterResponse{} must.ErrorContains(t, msgpackrpc.CallWithCodec(codec, "Job.Scale", scaleReq, &resp), @@ -8103,7 +8102,7 @@ func TestJobEndpoint_Scale_BatchJob(t *testing.T) { Target: map[string]string{ structs.ScalingTargetGroup: mockBatchJob.TaskGroups[0].Name, }, - Count: pointer.Of(int64(13)), + Count: new(int64(13)), WriteRequest: structs.WriteRequest{ Region: DefaultRegion, Namespace: mockBatchJob.Namespace, @@ -8143,7 +8142,7 @@ func TestJobEndpoint_InvalidCount(t *testing.T) { Target: map[string]string{ structs.ScalingTargetGroup: job.TaskGroups[0].Name, }, - Count: pointer.Of(int64(-1)), + Count: new(int64(-1)), WriteRequest: structs.WriteRequest{ Region: "global", Namespace: job.Namespace, @@ -8197,7 +8196,7 @@ func TestJobEndpoint_GetScaleStatus(t *testing.T) { a1.ClientStatus = structs.AllocClientStatusRunning // healthy a1.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), } a2 := mock.Alloc() a2.Job = jobV2 @@ -8206,7 +8205,7 @@ func TestJobEndpoint_GetScaleStatus(t *testing.T) { a2.ClientStatus = structs.AllocClientStatusPending // unhealthy a2.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(false), + Healthy: new(false), } a3 := mock.Alloc() a3.Job = jobV2 @@ -8215,7 +8214,7 @@ func TestJobEndpoint_GetScaleStatus(t *testing.T) { a3.ClientStatus = structs.AllocClientStatusRunning // canary a3.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), Canary: true, } // no health @@ -8229,7 +8228,7 @@ func TestJobEndpoint_GetScaleStatus(t *testing.T) { event := &structs.ScalingEvent{ Time: time.Now().Unix(), - Count: pointer.Of(int64(5)), + Count: new(int64(5)), Message: "message", Error: false, Meta: map[string]interface{}{ @@ -8773,12 +8772,12 @@ func TestIntegration_SystemDeploymentHealth(t *testing.T) { NodeID: alloc.NodeID, ClientStatus: structs.AllocClientStatusRunning, DeploymentStatus: &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), Canary: isCanary, }, } if healthyYet { - stripped.DeploymentStatus.Healthy = pointer.Of(true) + stripped.DeploymentStatus.Healthy = new(true) } nodeSecretID := nodes[alloc.NodeID].SecretID diff --git a/nomad/mock/connect.go b/nomad/mock/connect.go index 3ecbcdfe820..0712901a13a 100644 --- a/nomad/mock/connect.go +++ b/nomad/mock/connect.go @@ -8,7 +8,6 @@ import ( "time" "github.com/hashicorp/nomad/helper/envoy" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/structs" ) @@ -68,7 +67,7 @@ func ConnectIngressGatewayJob(mode string, inject bool) *structs.Job { Connect: &structs.ConsulConnect{ Gateway: &structs.ConsulGateway{ Proxy: &structs.ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(3 * time.Second), + ConnectTimeout: new(3 * time.Second), EnvoyGatewayBindAddresses: make(map[string]*structs.ConsulGatewayBindAddress), }, Ingress: &structs.ConsulIngressConfigEntry{ @@ -119,7 +118,7 @@ func ConnectTerminatingGatewayJob(mode string, inject bool) *structs.Job { Connect: &structs.ConsulConnect{ Gateway: &structs.ConsulGateway{ Proxy: &structs.ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(3 * time.Second), + ConnectTimeout: new(3 * time.Second), EnvoyGatewayBindAddresses: make(map[string]*structs.ConsulGatewayBindAddress), }, Terminating: &structs.ConsulTerminatingConfigEntry{ @@ -170,7 +169,7 @@ func ConnectMeshGatewayJob(mode string, inject bool) *structs.Job { Connect: &structs.ConsulConnect{ Gateway: &structs.ConsulGateway{ Proxy: &structs.ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(3 * time.Second), + ConnectTimeout: new(3 * time.Second), EnvoyGatewayBindAddresses: make(map[string]*structs.ConsulGatewayBindAddress), }, Mesh: &structs.ConsulMeshConfigEntry{ diff --git a/nomad/state/events_test.go b/nomad/state/events_test.go index 2bc3abf1f5d..23c13fca843 100644 --- a/nomad/state/events_test.go +++ b/nomad/state/events_test.go @@ -9,7 +9,6 @@ import ( memdb "github.com/hashicorp/go-memdb" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" @@ -180,7 +179,7 @@ func TestEventsFromChanges_DeploymentPromotion(t *testing.T) { c1.DeploymentID = d.ID d.TaskGroups[c1.TaskGroup].PlacedCanaries = append(d.TaskGroups[c1.TaskGroup].PlacedCanaries, c1.ID) c1.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), } c2 := mock.Alloc() c2.JobID = j.ID @@ -188,7 +187,7 @@ func TestEventsFromChanges_DeploymentPromotion(t *testing.T) { d.TaskGroups[c2.TaskGroup].PlacedCanaries = append(d.TaskGroups[c2.TaskGroup].PlacedCanaries, c2.ID) c2.TaskGroup = tg2.Name c2.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), } must.NoError(t, s.upsertAllocsImpl(10, []*structs.Allocation{c1, c2}, setupTx)) @@ -257,7 +256,7 @@ func TestEventsFromChanges_DeploymentAllocHealthRequestType(t *testing.T) { c1.DeploymentID = d.ID d.TaskGroups[c1.TaskGroup].PlacedCanaries = append(d.TaskGroups[c1.TaskGroup].PlacedCanaries, c1.ID) c1.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), } c2 := mock.Alloc() c2.JobID = j.ID @@ -265,7 +264,7 @@ func TestEventsFromChanges_DeploymentAllocHealthRequestType(t *testing.T) { d.TaskGroups[c2.TaskGroup].PlacedCanaries = append(d.TaskGroups[c2.TaskGroup].PlacedCanaries, c2.ID) c2.TaskGroup = tg2.Name c2.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), } must.NoError(t, s.upsertAllocsImpl(10, []*structs.Allocation{c1, c2}, setupTx)) @@ -661,7 +660,7 @@ func TestEventsFromChanges_AllocUpdateDesiredTransitionRequestType(t *testing.T) req := &structs.AllocUpdateDesiredTransitionRequest{ Allocs: map[string]*structs.DesiredTransition{ - alloc.ID: {Migrate: pointer.Of(true)}, + alloc.ID: {Migrate: new(true)}, }, Evals: evals, } diff --git a/nomad/state/state_store.go b/nomad/state/state_store.go index 38969c1d136..34a92430c0d 100644 --- a/nomad/state/state_store.go +++ b/nomad/state/state_store.go @@ -19,7 +19,6 @@ import ( "github.com/hashicorp/go-multierror" "github.com/hashicorp/go-set/v3" "github.com/hashicorp/nomad/helper" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/lib/lang" "github.com/hashicorp/nomad/nomad/stream" "github.com/hashicorp/nomad/nomad/structs" @@ -4084,7 +4083,7 @@ func (s *StateStore) nestedUpdateAllocFromClient(txn *txn, index uint64, alloc * // We got new health information from the client if newHasHealthy && (!oldHasHealthy || *copyAlloc.DeploymentStatus.Healthy != *alloc.DeploymentStatus.Healthy) { // Updated deployment health and timestamp - copyAlloc.DeploymentStatus.Healthy = pointer.Of(*alloc.DeploymentStatus.Healthy) + copyAlloc.DeploymentStatus.Healthy = new(*alloc.DeploymentStatus.Healthy) copyAlloc.DeploymentStatus.Timestamp = alloc.DeploymentStatus.Timestamp copyAlloc.DeploymentStatus.ModifyIndex = index } @@ -5121,7 +5120,7 @@ func (s *StateStore) UpdateDeploymentAllocHealth(msgType structs.MessageType, in if copy.DeploymentStatus == nil { copy.DeploymentStatus = &structs.AllocDeploymentStatus{} } - copy.DeploymentStatus.Healthy = pointer.Of(healthy) + copy.DeploymentStatus.Healthy = new(healthy) copy.DeploymentStatus.Timestamp = ts copy.DeploymentStatus.ModifyIndex = index copy.ModifyTime = req.Timestamp.UnixNano() diff --git a/nomad/state/state_store_acl_test.go b/nomad/state/state_store_acl_test.go index 6d4f6d162f4..ec8c2ff33b2 100644 --- a/nomad/state/state_store_acl_test.go +++ b/nomad/state/state_store_acl_test.go @@ -10,7 +10,6 @@ import ( "github.com/hashicorp/go-memdb" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" @@ -61,7 +60,7 @@ func TestStateStore_ACLTokensByExpired(t *testing.T) { // long ago and therefore before all others coming in the tests. It should // therefore always be the first out. expiredLocalToken := mock.ACLToken() - expiredLocalToken.ExpirationTime = pointer.Of(expiryTimeThreshold.Add(-48 * time.Hour)) + expiredLocalToken.ExpirationTime = new(expiryTimeThreshold.Add(-48 * time.Hour)) err = testState.UpsertACLTokens(structs.MsgTypeTestSetup, 20, []*structs.ACLToken{expiredLocalToken}) must.NoError(t, err) @@ -77,7 +76,7 @@ func TestStateStore_ACLTokensByExpired(t *testing.T) { // therefore always be the first out. expiredGlobalToken := mock.ACLToken() expiredGlobalToken.Global = true - expiredGlobalToken.ExpirationTime = pointer.Of(expiryTimeThreshold.Add(-48 * time.Hour)) + expiredGlobalToken.ExpirationTime = new(expiryTimeThreshold.Add(-48 * time.Hour)) err = testState.UpsertACLTokens(structs.MsgTypeTestSetup, 30, []*structs.ACLToken{expiredGlobalToken}) must.NoError(t, err) @@ -104,9 +103,9 @@ func TestStateStore_ACLTokensByExpired(t *testing.T) { mockedToken.Global = global if i%2 == 0 { expiredTokens = append(expiredTokens, mockedToken) - mockedToken.ExpirationTime = pointer.Of(expiryTimeThreshold.Add(-24 * time.Hour)) + mockedToken.ExpirationTime = new(expiryTimeThreshold.Add(-24 * time.Hour)) } else { - mockedToken.ExpirationTime = pointer.Of(expiryTimeThreshold.Add(24 * time.Hour)) + mockedToken.ExpirationTime = new(expiryTimeThreshold.Add(24 * time.Hour)) } mixedTokens[i] = mockedToken } diff --git a/nomad/state/state_store_test.go b/nomad/state/state_store_test.go index a04e1262119..b1faf4a0981 100644 --- a/nomad/state/state_store_test.go +++ b/nomad/state/state_store_test.go @@ -14,7 +14,6 @@ import ( "github.com/hashicorp/go-memdb" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" @@ -5564,7 +5563,7 @@ func TestStateStore_UpdateAllocsFromClient_Deployment(t *testing.T) { JobID: alloc.JobID, TaskGroup: alloc.TaskGroup, DeploymentStatus: &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), Timestamp: healthy, }, } @@ -5641,8 +5640,8 @@ func TestStateStore_UpdateAllocsFromClient_DeploymentStateMerges(t *testing.T) { update = update.Copy() update.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), // should update - Canary: false, // should not update + Healthy: new(true), // should update + Canary: false, // should not update } must.NoError(t, state.UpdateAllocsFromClient( structs.MsgTypeTestSetup, 1010, []*structs.Allocation{update})) @@ -6268,10 +6267,10 @@ func TestStateStore_UpdateAllocDesiredTransition(t *testing.T) { must.Nil(t, state.UpsertAllocs(structs.MsgTypeTestSetup, 1000, []*structs.Allocation{alloc})) t1 := &structs.DesiredTransition{ - Migrate: pointer.Of(true), + Migrate: new(true), } t2 := &structs.DesiredTransition{ - Migrate: pointer.Of(false), + Migrate: new(false), } eval := &structs.Evaluation{ ID: uuid.Generate(), @@ -7863,7 +7862,7 @@ func TestStateStore_UpsertDeploymentPromotion_Unhealthy(t *testing.T) { c3.JobID = j.ID c3.DeploymentID = d.ID c3.DesiredStatus = structs.AllocDesiredStatusStop - c3.DeploymentStatus = &structs.AllocDeploymentStatus{Healthy: pointer.Of(true)} + c3.DeploymentStatus = &structs.AllocDeploymentStatus{Healthy: new(true)} d.TaskGroups[c3.TaskGroup].PlacedCanaries = append(d.TaskGroups[c3.TaskGroup].PlacedCanaries, c3.ID) must.NoError(t, store.UpsertAllocs(structs.MsgTypeTestSetup, 3, []*structs.Allocation{c1, c2, c3})) @@ -7942,7 +7941,7 @@ func TestStateStore_UpsertDeploymentPromotion_All(t *testing.T) { c1.DeploymentID = d.ID d.TaskGroups[c1.TaskGroup].PlacedCanaries = append(d.TaskGroups[c1.TaskGroup].PlacedCanaries, c1.ID) c1.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), } c2 := mock.Alloc() c2.JobID = j.ID @@ -7950,7 +7949,7 @@ func TestStateStore_UpsertDeploymentPromotion_All(t *testing.T) { d.TaskGroups[c2.TaskGroup].PlacedCanaries = append(d.TaskGroups[c2.TaskGroup].PlacedCanaries, c2.ID) c2.TaskGroup = tg2.Name c2.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), } must.NoError(t, store.UpsertAllocs(structs.MsgTypeTestSetup, 3, []*structs.Allocation{c1, c2})) @@ -8020,7 +8019,7 @@ func TestStateStore_UpsertDeploymentPromotion_Subset(t *testing.T) { c1.DeploymentID = d.ID d.TaskGroups[c1.TaskGroup].PlacedCanaries = append(d.TaskGroups[c1.TaskGroup].PlacedCanaries, c1.ID) c1.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), Canary: true, } @@ -8031,7 +8030,7 @@ func TestStateStore_UpsertDeploymentPromotion_Subset(t *testing.T) { d.TaskGroups[c2.TaskGroup].PlacedCanaries = append(d.TaskGroups[c2.TaskGroup].PlacedCanaries, c2.ID) c2.TaskGroup = tg2.Name c2.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), Canary: true, } @@ -8040,7 +8039,7 @@ func TestStateStore_UpsertDeploymentPromotion_Subset(t *testing.T) { c3.DeploymentID = d.ID d.TaskGroups[c3.TaskGroup].PlacedCanaries = append(d.TaskGroups[c3.TaskGroup].PlacedCanaries, c3.ID) c3.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(false), + Healthy: new(false), Canary: true, } @@ -8174,7 +8173,7 @@ func TestStateStore_UpsertDeploymentAlloc_Canaries(t *testing.T) { a.JobID = job.ID a.DeploymentID = d1.ID a.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(false), + Healthy: new(false), Canary: true, } must.NoError(t, state.UpsertAllocs(structs.MsgTypeTestSetup, 4, []*structs.Allocation{a})) @@ -8192,7 +8191,7 @@ func TestStateStore_UpsertDeploymentAlloc_Canaries(t *testing.T) { b.JobID = job.ID b.DeploymentID = d1.ID b.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(false), + Healthy: new(false), Canary: false, } must.NoError(t, state.UpsertAllocs(structs.MsgTypeTestSetup, 4, []*structs.Allocation{b})) @@ -8213,7 +8212,7 @@ func TestStateStore_UpsertDeploymentAlloc_Canaries(t *testing.T) { c.JobID = job.ID c.DeploymentID = d2.ID c.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(false), + Healthy: new(false), Canary: true, } must.NoError(t, state.UpsertAllocs(structs.MsgTypeTestSetup, 6, []*structs.Allocation{c})) @@ -8244,7 +8243,7 @@ func TestStateStore_UpsertDeploymentAlloc_NoCanaries(t *testing.T) { a.JobID = job.ID a.DeploymentID = d1.ID a.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), Canary: false, } must.NoError(t, state.UpsertAllocs(structs.MsgTypeTestSetup, 4, []*structs.Allocation{a})) diff --git a/nomad/structs/acl.go b/nomad/structs/acl.go index 1b7ef9c5f7d..ea7ff9090b2 100644 --- a/nomad/structs/acl.go +++ b/nomad/structs/acl.go @@ -22,7 +22,6 @@ import ( lru "github.com/hashicorp/golang-lru/v2" "github.com/hashicorp/nomad/acl" "github.com/hashicorp/nomad/helper" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/lib/lang" "golang.org/x/crypto/blake2b" @@ -739,7 +738,7 @@ func (a *ACLToken) Canonicalize() { // If the user has not set the expiration time, but has provided a TTL, we // calculate and populate the former filed. if a.ExpirationTime == nil && a.ExpirationTTL != 0 { - a.ExpirationTime = pointer.Of(a.CreateTime.Add(a.ExpirationTTL)) + a.ExpirationTime = new(a.CreateTime.Add(a.ExpirationTTL)) } } } diff --git a/nomad/structs/acl_test.go b/nomad/structs/acl_test.go index a5b09fcb0c8..efcff93f209 100644 --- a/nomad/structs/acl_test.go +++ b/nomad/structs/acl_test.go @@ -13,7 +13,6 @@ import ( "github.com/hashicorp/go-hclog" "github.com/hashicorp/go-multierror" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/shoenig/test/must" "github.com/stretchr/testify/require" @@ -156,7 +155,7 @@ func TestACLTokenValidate(t *testing.T) { Type: ACLManagementToken, Name: "foo", CreateTime: time.Date(2022, time.July, 11, 16, 23, 0, 0, time.UTC), - ExpirationTime: pointer.Of(time.Date(2022, time.July, 11, 16, 23, 10, 0, time.UTC)), + ExpirationTime: new(time.Date(2022, time.July, 11, 16, 23, 10, 0, time.UTC)), }, inputExistingACLToken: nil, expectedErrorContains: "expiration time cannot be less than", @@ -167,7 +166,7 @@ func TestACLTokenValidate(t *testing.T) { Type: ACLManagementToken, Name: "foo", CreateTime: time.Date(2022, time.July, 11, 16, 23, 0, 0, time.UTC), - ExpirationTime: pointer.Of(time.Date(2042, time.July, 11, 16, 23, 0, 0, time.UTC)), + ExpirationTime: new(time.Date(2042, time.July, 11, 16, 23, 0, 0, time.UTC)), }, inputExistingACLToken: nil, expectedErrorContains: "expiration time cannot be more than", @@ -224,21 +223,21 @@ func TestACLToken_HasExpirationTime(t *testing.T) { { name: "expiration set to now", inputACLToken: &ACLToken{ - ExpirationTime: pointer.Of(time.Now().UTC()), + ExpirationTime: new(time.Now().UTC()), }, expectedOutput: true, }, { name: "expiration set to past", inputACLToken: &ACLToken{ - ExpirationTime: pointer.Of(time.Date(2022, time.February, 21, 19, 35, 0, 0, time.UTC)), + ExpirationTime: new(time.Date(2022, time.February, 21, 19, 35, 0, 0, time.UTC)), }, expectedOutput: true, }, { name: "expiration set to future", inputACLToken: &ACLToken{ - ExpirationTime: pointer.Of(time.Date(2087, time.April, 25, 12, 0, 0, 0, time.UTC)), + ExpirationTime: new(time.Date(2087, time.April, 25, 12, 0, 0, 0, time.UTC)), }, expectedOutput: true, }, @@ -274,7 +273,7 @@ func TestACLToken_IsExpired(t *testing.T) { { name: "token not expired", inputACLToken: &ACLToken{ - ExpirationTime: pointer.Of(time.Date(2022, time.May, 9, 10, 27, 0, 0, time.UTC)), + ExpirationTime: new(time.Date(2022, time.May, 9, 10, 27, 0, 0, time.UTC)), }, inputTime: time.Date(2022, time.May, 9, 10, 26, 0, 0, time.UTC), expectedOutput: false, @@ -282,7 +281,7 @@ func TestACLToken_IsExpired(t *testing.T) { { name: "token expired", inputACLToken: &ACLToken{ - ExpirationTime: pointer.Of(time.Date(2022, time.May, 9, 10, 27, 0, 0, time.UTC)), + ExpirationTime: new(time.Date(2022, time.May, 9, 10, 27, 0, 0, time.UTC)), }, inputTime: time.Date(2022, time.May, 9, 10, 28, 0, 0, time.UTC), expectedOutput: true, @@ -290,7 +289,7 @@ func TestACLToken_IsExpired(t *testing.T) { { name: "empty input time", inputACLToken: &ACLToken{ - ExpirationTime: pointer.Of(time.Date(2022, time.May, 9, 10, 27, 0, 0, time.UTC)), + ExpirationTime: new(time.Date(2022, time.May, 9, 10, 27, 0, 0, time.UTC)), }, inputTime: time.Time{}, expectedOutput: true, diff --git a/nomad/structs/alloc.go b/nomad/structs/alloc.go index fbc7777e776..ce3eb564f40 100644 --- a/nomad/structs/alloc.go +++ b/nomad/structs/alloc.go @@ -1402,7 +1402,7 @@ func (a *AllocDeploymentStatus) Copy() *AllocDeploymentStatus { *c = *a if a.Healthy != nil { - c.Healthy = pointer.Of(*a.Healthy) + c.Healthy = new(*a.Healthy) } return c diff --git a/nomad/structs/config/artifact.go b/nomad/structs/config/artifact.go index 1f0819afa39..03f28368e97 100644 --- a/nomad/structs/config/artifact.go +++ b/nomad/structs/config/artifact.go @@ -258,47 +258,47 @@ func DefaultArtifactConfig() *ArtifactConfig { return &ArtifactConfig{ // Read timeout for HTTP operations. Must be long enough to // accommodate large/slow downloads. - HTTPReadTimeout: pointer.Of("30m"), + HTTPReadTimeout: new("30m"), // Maximum download size. Must be large enough to accommodate // large downloads. - HTTPMaxSize: pointer.Of("100GB"), + HTTPMaxSize: new("100GB"), // Timeout for GCS operations. Must be long enough to // accommodate large/slow downloads. - GCSTimeout: pointer.Of("30m"), + GCSTimeout: new("30m"), // Timeout for Git operations. Must be long enough to // accommodate large/slow clones. - GitTimeout: pointer.Of("30m"), + GitTimeout: new("30m"), // Timeout for Hg operations. Must be long enough to // accommodate large/slow clones. - HgTimeout: pointer.Of("30m"), + HgTimeout: new("30m"), // Timeout for S3 operations. Must be long enough to // accommodate large/slow downloads. - S3Timeout: pointer.Of("30m"), + S3Timeout: new("30m"), // DecompressionFileCountLimit limits the number of files decompressed // for a single artifact. Must be large enough for payloads with lots // of files. - DecompressionFileCountLimit: pointer.Of(4096), + DecompressionFileCountLimit: new(4096), // DecompressionSizeLimit limits the amount of data decompressed for // a single artifact. Must be large enough to accommodate large payloads. - DecompressionSizeLimit: pointer.Of("100GB"), + DecompressionSizeLimit: new("100GB"), // Toggle for disabling artifact inspection - DisableArtifactInspection: pointer.Of(false), + DisableArtifactInspection: new(false), // Toggle for disabling filesystem isolation, where available. - DisableFilesystemIsolation: pointer.Of(false), + DisableFilesystemIsolation: new(false), // No Filesystem Isolation Extra Locations by default FilesystemIsolationExtraPaths: nil, // No environment variables are inherited from Client by default. - SetEnvironmentVariables: pointer.Of(""), + SetEnvironmentVariables: new(""), } } diff --git a/nomad/structs/config/artifact_test.go b/nomad/structs/config/artifact_test.go index c9ad5b6ed68..2b5fff221fb 100644 --- a/nomad/structs/config/artifact_test.go +++ b/nomad/structs/config/artifact_test.go @@ -7,7 +7,6 @@ import ( "testing" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/shoenig/test/must" ) @@ -24,12 +23,12 @@ func TestArtifactConfig_Copy(t *testing.T) { must.Equal(t, a, b) must.Equal(t, b, a) - b.HTTPReadTimeout = pointer.Of("5m") - b.HTTPMaxSize = pointer.Of("2MB") - b.GitTimeout = pointer.Of("3m") - b.HgTimeout = pointer.Of("2m") - b.DecompressionFileCountLimit = pointer.Of(7) - b.DecompressionSizeLimit = pointer.Of("2GB") + b.HTTPReadTimeout = new("5m") + b.HTTPMaxSize = new("2MB") + b.GitTimeout = new("3m") + b.HgTimeout = new("2m") + b.DecompressionFileCountLimit = new(7) + b.DecompressionSizeLimit = new("2GB") must.NotEqual(t, a, b) b = a.Copy() @@ -49,169 +48,169 @@ func TestArtifactConfig_Merge(t *testing.T) { { name: "merge all fields", source: &ArtifactConfig{ - HTTPReadTimeout: pointer.Of("30m"), - HTTPMaxSize: pointer.Of("100GB"), - GCSTimeout: pointer.Of("30m"), - GitTimeout: pointer.Of("30m"), - HgTimeout: pointer.Of("30m"), - S3Timeout: pointer.Of("30m"), - DecompressionFileCountLimit: pointer.Of(4096), - DecompressionSizeLimit: pointer.Of("100GB"), - DisableFilesystemIsolation: pointer.Of(false), + HTTPReadTimeout: new("30m"), + HTTPMaxSize: new("100GB"), + GCSTimeout: new("30m"), + GitTimeout: new("30m"), + HgTimeout: new("30m"), + S3Timeout: new("30m"), + DecompressionFileCountLimit: new(4096), + DecompressionSizeLimit: new("100GB"), + DisableFilesystemIsolation: new(false), FilesystemIsolationExtraPaths: []string{ "f:r:/dev/urandom", "d:rx:/opt/bin", "d:r:/tmp/stash", }, - SetEnvironmentVariables: pointer.Of(""), + SetEnvironmentVariables: new(""), }, other: &ArtifactConfig{ - HTTPReadTimeout: pointer.Of("5m"), - HTTPMaxSize: pointer.Of("2GB"), - GCSTimeout: pointer.Of("1m"), - GitTimeout: pointer.Of("2m"), - HgTimeout: pointer.Of("3m"), - S3Timeout: pointer.Of("4m"), - DecompressionFileCountLimit: pointer.Of(100), - DecompressionSizeLimit: pointer.Of("8GB"), - DisableFilesystemIsolation: pointer.Of(true), + HTTPReadTimeout: new("5m"), + HTTPMaxSize: new("2GB"), + GCSTimeout: new("1m"), + GitTimeout: new("2m"), + HgTimeout: new("3m"), + S3Timeout: new("4m"), + DecompressionFileCountLimit: new(100), + DecompressionSizeLimit: new("8GB"), + DisableFilesystemIsolation: new(true), FilesystemIsolationExtraPaths: []string{ "d:rw:/opt/certs", "f:rx:/opt/bin/runme", }, - SetEnvironmentVariables: pointer.Of("FOO,BAR"), + SetEnvironmentVariables: new("FOO,BAR"), }, expected: &ArtifactConfig{ - HTTPReadTimeout: pointer.Of("5m"), - HTTPMaxSize: pointer.Of("2GB"), - GCSTimeout: pointer.Of("1m"), - GitTimeout: pointer.Of("2m"), - HgTimeout: pointer.Of("3m"), - S3Timeout: pointer.Of("4m"), - DecompressionFileCountLimit: pointer.Of(100), - DecompressionSizeLimit: pointer.Of("8GB"), - DisableFilesystemIsolation: pointer.Of(true), + HTTPReadTimeout: new("5m"), + HTTPMaxSize: new("2GB"), + GCSTimeout: new("1m"), + GitTimeout: new("2m"), + HgTimeout: new("3m"), + S3Timeout: new("4m"), + DecompressionFileCountLimit: new(100), + DecompressionSizeLimit: new("8GB"), + DisableFilesystemIsolation: new(true), FilesystemIsolationExtraPaths: []string{ "d:rw:/opt/certs", "f:rx:/opt/bin/runme", }, - SetEnvironmentVariables: pointer.Of("FOO,BAR"), + SetEnvironmentVariables: new("FOO,BAR"), }, }, { name: "null source", source: nil, other: &ArtifactConfig{ - HTTPReadTimeout: pointer.Of("5m"), - HTTPMaxSize: pointer.Of("2GB"), - GCSTimeout: pointer.Of("1m"), - GitTimeout: pointer.Of("2m"), - HgTimeout: pointer.Of("3m"), - S3Timeout: pointer.Of("4m"), - DecompressionFileCountLimit: pointer.Of(100), - DecompressionSizeLimit: pointer.Of("8GB"), - DisableFilesystemIsolation: pointer.Of(true), + HTTPReadTimeout: new("5m"), + HTTPMaxSize: new("2GB"), + GCSTimeout: new("1m"), + GitTimeout: new("2m"), + HgTimeout: new("3m"), + S3Timeout: new("4m"), + DecompressionFileCountLimit: new(100), + DecompressionSizeLimit: new("8GB"), + DisableFilesystemIsolation: new(true), FilesystemIsolationExtraPaths: []string{ "d:rw:/opt/certs", "f:rx:/opt/bin/runme", }, - SetEnvironmentVariables: pointer.Of("FOO,BAR"), + SetEnvironmentVariables: new("FOO,BAR"), }, expected: &ArtifactConfig{ - HTTPReadTimeout: pointer.Of("5m"), - HTTPMaxSize: pointer.Of("2GB"), - GCSTimeout: pointer.Of("1m"), - GitTimeout: pointer.Of("2m"), - HgTimeout: pointer.Of("3m"), - S3Timeout: pointer.Of("4m"), - DecompressionFileCountLimit: pointer.Of(100), - DecompressionSizeLimit: pointer.Of("8GB"), - DisableFilesystemIsolation: pointer.Of(true), + HTTPReadTimeout: new("5m"), + HTTPMaxSize: new("2GB"), + GCSTimeout: new("1m"), + GitTimeout: new("2m"), + HgTimeout: new("3m"), + S3Timeout: new("4m"), + DecompressionFileCountLimit: new(100), + DecompressionSizeLimit: new("8GB"), + DisableFilesystemIsolation: new(true), FilesystemIsolationExtraPaths: []string{ "d:rw:/opt/certs", "f:rx:/opt/bin/runme", }, - SetEnvironmentVariables: pointer.Of("FOO,BAR"), + SetEnvironmentVariables: new("FOO,BAR"), }, }, { name: "null other", source: &ArtifactConfig{ - HTTPReadTimeout: pointer.Of("30m"), - HTTPMaxSize: pointer.Of("100GB"), - GCSTimeout: pointer.Of("30m"), - GitTimeout: pointer.Of("30m"), - HgTimeout: pointer.Of("30m"), - S3Timeout: pointer.Of("30m"), - DecompressionFileCountLimit: pointer.Of(4096), - DecompressionSizeLimit: pointer.Of("100GB"), - DisableFilesystemIsolation: pointer.Of(true), + HTTPReadTimeout: new("30m"), + HTTPMaxSize: new("100GB"), + GCSTimeout: new("30m"), + GitTimeout: new("30m"), + HgTimeout: new("30m"), + S3Timeout: new("30m"), + DecompressionFileCountLimit: new(4096), + DecompressionSizeLimit: new("100GB"), + DisableFilesystemIsolation: new(true), FilesystemIsolationExtraPaths: []string{ "f:r:/dev/urandom", "d:rx:/opt/bin", "d:r:/tmp/stash", }, - SetEnvironmentVariables: pointer.Of("FOO,BAR"), + SetEnvironmentVariables: new("FOO,BAR"), }, other: nil, expected: &ArtifactConfig{ - HTTPReadTimeout: pointer.Of("30m"), - HTTPMaxSize: pointer.Of("100GB"), - GCSTimeout: pointer.Of("30m"), - GitTimeout: pointer.Of("30m"), - HgTimeout: pointer.Of("30m"), - S3Timeout: pointer.Of("30m"), - DecompressionFileCountLimit: pointer.Of(4096), - DecompressionSizeLimit: pointer.Of("100GB"), - DisableFilesystemIsolation: pointer.Of(true), + HTTPReadTimeout: new("30m"), + HTTPMaxSize: new("100GB"), + GCSTimeout: new("30m"), + GitTimeout: new("30m"), + HgTimeout: new("30m"), + S3Timeout: new("30m"), + DecompressionFileCountLimit: new(4096), + DecompressionSizeLimit: new("100GB"), + DisableFilesystemIsolation: new(true), FilesystemIsolationExtraPaths: []string{ "f:r:/dev/urandom", "d:rx:/opt/bin", "d:r:/tmp/stash", }, - SetEnvironmentVariables: pointer.Of("FOO,BAR"), + SetEnvironmentVariables: new("FOO,BAR"), }, }, { name: "null fsIsolationLocation", source: &ArtifactConfig{ - HTTPReadTimeout: pointer.Of("30m"), - HTTPMaxSize: pointer.Of("100GB"), - GCSTimeout: pointer.Of("30m"), - GitTimeout: pointer.Of("30m"), - HgTimeout: pointer.Of("30m"), - S3Timeout: pointer.Of("30m"), - DecompressionFileCountLimit: pointer.Of(4096), - DecompressionSizeLimit: pointer.Of("100GB"), - DisableFilesystemIsolation: pointer.Of(false), + HTTPReadTimeout: new("30m"), + HTTPMaxSize: new("100GB"), + GCSTimeout: new("30m"), + GitTimeout: new("30m"), + HgTimeout: new("30m"), + S3Timeout: new("30m"), + DecompressionFileCountLimit: new(4096), + DecompressionSizeLimit: new("100GB"), + DisableFilesystemIsolation: new(false), FilesystemIsolationExtraPaths: nil, - SetEnvironmentVariables: pointer.Of(""), + SetEnvironmentVariables: new(""), }, other: &ArtifactConfig{ - HTTPReadTimeout: pointer.Of("5m"), - HTTPMaxSize: pointer.Of("2GB"), - GCSTimeout: pointer.Of("1m"), - GitTimeout: pointer.Of("2m"), - HgTimeout: pointer.Of("3m"), - S3Timeout: pointer.Of("4m"), - DecompressionFileCountLimit: pointer.Of(100), - DecompressionSizeLimit: pointer.Of("8GB"), - DisableFilesystemIsolation: pointer.Of(true), + HTTPReadTimeout: new("5m"), + HTTPMaxSize: new("2GB"), + GCSTimeout: new("1m"), + GitTimeout: new("2m"), + HgTimeout: new("3m"), + S3Timeout: new("4m"), + DecompressionFileCountLimit: new(100), + DecompressionSizeLimit: new("8GB"), + DisableFilesystemIsolation: new(true), FilesystemIsolationExtraPaths: nil, - SetEnvironmentVariables: pointer.Of("FOO,BAR"), + SetEnvironmentVariables: new("FOO,BAR"), }, expected: &ArtifactConfig{ - HTTPReadTimeout: pointer.Of("5m"), - HTTPMaxSize: pointer.Of("2GB"), - GCSTimeout: pointer.Of("1m"), - GitTimeout: pointer.Of("2m"), - HgTimeout: pointer.Of("3m"), - S3Timeout: pointer.Of("4m"), - DecompressionFileCountLimit: pointer.Of(100), - DecompressionSizeLimit: pointer.Of("8GB"), - DisableFilesystemIsolation: pointer.Of(true), + HTTPReadTimeout: new("5m"), + HTTPMaxSize: new("2GB"), + GCSTimeout: new("1m"), + GitTimeout: new("2m"), + HgTimeout: new("3m"), + S3Timeout: new("4m"), + DecompressionFileCountLimit: new(100), + DecompressionSizeLimit: new("8GB"), + DisableFilesystemIsolation: new(true), FilesystemIsolationExtraPaths: nil, - SetEnvironmentVariables: pointer.Of("FOO,BAR"), + SetEnvironmentVariables: new("FOO,BAR"), }, }, } @@ -247,28 +246,28 @@ func TestArtifactConfig_Validate(t *testing.T) { { name: "http read timeout is invalid", config: func(a *ArtifactConfig) { - a.HTTPReadTimeout = pointer.Of("invalid") + a.HTTPReadTimeout = new("invalid") }, expErr: "http_read_timeout not a valid duration", }, { name: "http read timeout is empty", config: func(a *ArtifactConfig) { - a.HTTPReadTimeout = pointer.Of("") + a.HTTPReadTimeout = new("") }, expErr: "http_read_timeout not a valid duration", }, { name: "http read timeout is zero", config: func(a *ArtifactConfig) { - a.HTTPReadTimeout = pointer.Of("0") + a.HTTPReadTimeout = new("0") }, expErr: "", }, { name: "http read timeout is negative", config: func(a *ArtifactConfig) { - a.HTTPReadTimeout = pointer.Of("-10m") + a.HTTPReadTimeout = new("-10m") }, expErr: "http_read_timeout must be > 0", }, @@ -282,28 +281,28 @@ func TestArtifactConfig_Validate(t *testing.T) { { name: "http max size is invalid", config: func(a *ArtifactConfig) { - a.HTTPMaxSize = pointer.Of("invalid") + a.HTTPMaxSize = new("invalid") }, expErr: "http_max_size not a valid size", }, { name: "http max size is empty", config: func(a *ArtifactConfig) { - a.HTTPMaxSize = pointer.Of("") + a.HTTPMaxSize = new("") }, expErr: "http_max_size not a valid size", }, { name: "http max size is zero", config: func(a *ArtifactConfig) { - a.HTTPMaxSize = pointer.Of("0") + a.HTTPMaxSize = new("0") }, expErr: "", }, { name: "http max size is negative", config: func(a *ArtifactConfig) { - a.HTTPMaxSize = pointer.Of("-l0MB") + a.HTTPMaxSize = new("-l0MB") }, expErr: "http_max_size not a valid size", }, @@ -317,28 +316,28 @@ func TestArtifactConfig_Validate(t *testing.T) { { name: "gcs timeout is invalid", config: func(a *ArtifactConfig) { - a.GCSTimeout = pointer.Of("invalid") + a.GCSTimeout = new("invalid") }, expErr: "gcs_timeout not a valid duration", }, { name: "gcs timeout is empty", config: func(a *ArtifactConfig) { - a.GCSTimeout = pointer.Of("") + a.GCSTimeout = new("") }, expErr: "gcs_timeout not a valid duration", }, { name: "gcs timeout is zero", config: func(a *ArtifactConfig) { - a.GCSTimeout = pointer.Of("0") + a.GCSTimeout = new("0") }, expErr: "", }, { name: "gcs timeout is negative", config: func(a *ArtifactConfig) { - a.GCSTimeout = pointer.Of("-l0m") + a.GCSTimeout = new("-l0m") }, expErr: "gcs_timeout not a valid duration", }, @@ -352,28 +351,28 @@ func TestArtifactConfig_Validate(t *testing.T) { { name: "git timeout is invalid", config: func(a *ArtifactConfig) { - a.GitTimeout = pointer.Of("invalid") + a.GitTimeout = new("invalid") }, expErr: "git_timeout not a valid duration", }, { name: "git timeout is empty", config: func(a *ArtifactConfig) { - a.GitTimeout = pointer.Of("") + a.GitTimeout = new("") }, expErr: "git_timeout not a valid duration", }, { name: "git timeout is zero", config: func(a *ArtifactConfig) { - a.GitTimeout = pointer.Of("0") + a.GitTimeout = new("0") }, expErr: "", }, { name: "git timeout is negative", config: func(a *ArtifactConfig) { - a.GitTimeout = pointer.Of("-l0m") + a.GitTimeout = new("-l0m") }, expErr: "git_timeout not a valid duration", }, @@ -387,28 +386,28 @@ func TestArtifactConfig_Validate(t *testing.T) { { name: "hg timeout is invalid", config: func(a *ArtifactConfig) { - a.HgTimeout = pointer.Of("invalid") + a.HgTimeout = new("invalid") }, expErr: "hg_timeout not a valid duration", }, { name: "hg timeout is empty", config: func(a *ArtifactConfig) { - a.HgTimeout = pointer.Of("") + a.HgTimeout = new("") }, expErr: "hg_timeout not a valid duration", }, { name: "hg timeout is zero", config: func(a *ArtifactConfig) { - a.HgTimeout = pointer.Of("0") + a.HgTimeout = new("0") }, expErr: "", }, { name: "hg timeout is negative", config: func(a *ArtifactConfig) { - a.HgTimeout = pointer.Of("-l0m") + a.HgTimeout = new("-l0m") }, expErr: "hg_timeout not a valid duration", }, @@ -422,28 +421,28 @@ func TestArtifactConfig_Validate(t *testing.T) { { name: "s3 timeout is invalid", config: func(a *ArtifactConfig) { - a.S3Timeout = pointer.Of("invalid") + a.S3Timeout = new("invalid") }, expErr: "s3_timeout not a valid duration", }, { name: "s3 timeout is empty", config: func(a *ArtifactConfig) { - a.S3Timeout = pointer.Of("") + a.S3Timeout = new("") }, expErr: "s3_timeout not a valid duration", }, { name: "s3 timeout is zero", config: func(a *ArtifactConfig) { - a.S3Timeout = pointer.Of("0") + a.S3Timeout = new("0") }, expErr: "", }, { name: "s3 timeout is negative", config: func(a *ArtifactConfig) { - a.S3Timeout = pointer.Of("-l0m") + a.S3Timeout = new("-l0m") }, expErr: "s3_timeout not a valid duration", }, @@ -457,7 +456,7 @@ func TestArtifactConfig_Validate(t *testing.T) { { name: "decompression file count limit is negative", config: func(a *ArtifactConfig) { - a.DecompressionFileCountLimit = pointer.Of(-1) + a.DecompressionFileCountLimit = new(-1) }, expErr: "decompression_file_count_limit must be >= 0 but found -1", }, @@ -471,7 +470,7 @@ func TestArtifactConfig_Validate(t *testing.T) { { name: "decompression size limit is negative", config: func(a *ArtifactConfig) { - a.DecompressionSizeLimit = pointer.Of("-1GB") + a.DecompressionSizeLimit = new("-1GB") }, expErr: "decompression_size_limit is not a valid size", }, diff --git a/nomad/structs/config/audit.go b/nomad/structs/config/audit.go index b2722f7cc75..23508495ffb 100644 --- a/nomad/structs/config/audit.go +++ b/nomad/structs/config/audit.go @@ -6,8 +6,6 @@ package config import ( "slices" "time" - - "github.com/hashicorp/nomad/helper/pointer" ) // AuditConfig is the configuration specific to Audit Logging @@ -87,7 +85,7 @@ func (a *AuditConfig) Copy() *AuditConfig { // Copy bool pointers if a.Enabled != nil { - nc.Enabled = pointer.Of(*a.Enabled) + nc.Enabled = new(*a.Enabled) } // Copy Sinks and Filters @@ -102,7 +100,7 @@ func (a *AuditConfig) Merge(b *AuditConfig) *AuditConfig { result := a.Copy() if b.Enabled != nil { - result.Enabled = pointer.Of(*b.Enabled) + result.Enabled = new(*b.Enabled) } // Merge Sinks diff --git a/nomad/structs/config/audit_test.go b/nomad/structs/config/audit_test.go index 5ccdc0e32e6..392d1107034 100644 --- a/nomad/structs/config/audit_test.go +++ b/nomad/structs/config/audit_test.go @@ -8,7 +8,6 @@ import ( "time" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/stretchr/testify/require" ) @@ -16,7 +15,7 @@ func TestAuditConfig_Merge(t *testing.T) { ci.Parallel(t) c1 := &AuditConfig{ - Enabled: pointer.Of(true), + Enabled: new(true), Sinks: []*AuditSink{ { DeliveryGuarantee: "enforced", @@ -74,7 +73,7 @@ func TestAuditConfig_Merge(t *testing.T) { } e := &AuditConfig{ - Enabled: pointer.Of(true), + Enabled: new(true), Sinks: []*AuditSink{ { DeliveryGuarantee: "best-effort", diff --git a/nomad/structs/config/autopilot.go b/nomad/structs/config/autopilot.go index a06869d977e..af10406f6a3 100644 --- a/nomad/structs/config/autopilot.go +++ b/nomad/structs/config/autopilot.go @@ -5,8 +5,6 @@ package config import ( "time" - - "github.com/hashicorp/nomad/helper/pointer" ) type AutopilotConfig struct { @@ -63,7 +61,7 @@ func (a *AutopilotConfig) Merge(b *AutopilotConfig) *AutopilotConfig { result := a.Copy() if b.CleanupDeadServers != nil { - result.CleanupDeadServers = pointer.Of(*b.CleanupDeadServers) + result.CleanupDeadServers = new(*b.CleanupDeadServers) } if b.ServerStabilizationTime != 0 { result.ServerStabilizationTime = b.ServerStabilizationTime @@ -87,7 +85,7 @@ func (a *AutopilotConfig) Merge(b *AutopilotConfig) *AutopilotConfig { result.EnableRedundancyZones = b.EnableRedundancyZones } if b.DisableUpgradeMigration != nil { - result.DisableUpgradeMigration = pointer.Of(*b.DisableUpgradeMigration) + result.DisableUpgradeMigration = new(*b.DisableUpgradeMigration) } if b.EnableCustomUpgrades != nil { result.EnableCustomUpgrades = b.EnableCustomUpgrades @@ -107,16 +105,16 @@ func (a *AutopilotConfig) Copy() *AutopilotConfig { // Copy the bools if a.CleanupDeadServers != nil { - nc.CleanupDeadServers = pointer.Of(*a.CleanupDeadServers) + nc.CleanupDeadServers = new(*a.CleanupDeadServers) } if a.EnableRedundancyZones != nil { - nc.EnableRedundancyZones = pointer.Of(*a.EnableRedundancyZones) + nc.EnableRedundancyZones = new(*a.EnableRedundancyZones) } if a.DisableUpgradeMigration != nil { - nc.DisableUpgradeMigration = pointer.Of(*a.DisableUpgradeMigration) + nc.DisableUpgradeMigration = new(*a.DisableUpgradeMigration) } if a.EnableCustomUpgrades != nil { - nc.EnableCustomUpgrades = pointer.Of(*a.EnableCustomUpgrades) + nc.EnableCustomUpgrades = new(*a.EnableCustomUpgrades) } return nc diff --git a/nomad/structs/config/consul.go b/nomad/structs/config/consul.go index d217779fcb8..dae6f3052ee 100644 --- a/nomad/structs/config/consul.go +++ b/nomad/structs/config/consul.go @@ -13,7 +13,6 @@ import ( consul "github.com/hashicorp/consul/api" "github.com/hashicorp/go-secure-stdlib/listenerutil" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/structs" ) @@ -199,18 +198,18 @@ func DefaultConsulConfig() *ConsulConfig { ServerRPCCheckName: "Nomad Server RPC Check", ClientServiceName: "nomad-client", ClientHTTPCheckName: "Nomad Client HTTP Check", - AutoAdvertise: pointer.Of(true), - ChecksUseAdvertise: pointer.Of(false), - ServerAutoJoin: pointer.Of(true), - ClientAutoJoin: pointer.Of(true), + AutoAdvertise: new(true), + ChecksUseAdvertise: new(false), + ServerAutoJoin: new(true), + ClientAutoJoin: new(true), Timeout: 5 * time.Second, ServiceIdentityAuthMethod: structs.ConsulWorkloadsDefaultAuthMethodName, TaskIdentityAuthMethod: structs.ConsulWorkloadsDefaultAuthMethodName, // From Consul api package defaults Addr: def.Address, - EnableSSL: pointer.Of(def.Scheme == "https"), - VerifySSL: pointer.Of(!def.TLSConfig.InsecureSkipVerify), + EnableSSL: new(def.Scheme == "https"), + VerifySSL: new(!def.TLSConfig.InsecureSkipVerify), CAFile: def.TLSConfig.CAFile, Namespace: def.Namespace, Token: def.Token, @@ -256,7 +255,7 @@ func (c *ConsulConfig) Merge(b *ConsulConfig) *ConsulConfig { } result.Tags = append(result.Tags, b.Tags...) if b.AutoAdvertise != nil { - result.AutoAdvertise = pointer.Of(*b.AutoAdvertise) + result.AutoAdvertise = new(*b.AutoAdvertise) } if b.Addr != "" { result.Addr = b.Addr @@ -277,13 +276,13 @@ func (c *ConsulConfig) Merge(b *ConsulConfig) *ConsulConfig { result.Auth = b.Auth } if b.EnableSSL != nil { - result.EnableSSL = pointer.Of(*b.EnableSSL) + result.EnableSSL = new(*b.EnableSSL) } if b.VerifySSL != nil { - result.VerifySSL = pointer.Of(*b.VerifySSL) + result.VerifySSL = new(*b.VerifySSL) } if b.ShareSSL != nil { - result.ShareSSL = pointer.Of(*b.ShareSSL) + result.ShareSSL = new(*b.ShareSSL) } if b.GRPCCAFile != "" { result.GRPCCAFile = b.GRPCCAFile @@ -298,13 +297,13 @@ func (c *ConsulConfig) Merge(b *ConsulConfig) *ConsulConfig { result.KeyFile = b.KeyFile } if b.ServerAutoJoin != nil { - result.ServerAutoJoin = pointer.Of(*b.ServerAutoJoin) + result.ServerAutoJoin = new(*b.ServerAutoJoin) } if b.ClientAutoJoin != nil { - result.ClientAutoJoin = pointer.Of(*b.ClientAutoJoin) + result.ClientAutoJoin = new(*b.ClientAutoJoin) } if b.ChecksUseAdvertise != nil { - result.ChecksUseAdvertise = pointer.Of(*b.ChecksUseAdvertise) + result.ChecksUseAdvertise = new(*b.ChecksUseAdvertise) } if b.Namespace != "" { result.Namespace = b.Namespace diff --git a/nomad/structs/config/consul_test.go b/nomad/structs/config/consul_test.go index e6bd1a8669b..955420e61cb 100644 --- a/nomad/structs/config/consul_test.go +++ b/nomad/structs/config/consul_test.go @@ -17,7 +17,6 @@ import ( "github.com/stretchr/testify/require" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" ) func TestMain(m *testing.M) { @@ -94,9 +93,9 @@ func TestConsulConfig_Merge(t *testing.T) { ServiceIdentity: &WorkloadIdentityConfig{ Name: "test", Audience: []string{"consul.io", "nomad.dev"}, - Env: pointer.Of(false), - File: pointer.Of(true), - TTL: pointer.Of(2 * time.Hour), + Env: new(false), + File: new(true), + TTL: new(2 * time.Hour), }, ExtraKeysHCL: []string{"b", "2"}, } @@ -128,9 +127,9 @@ func TestConsulConfig_Merge(t *testing.T) { ServiceIdentity: &WorkloadIdentityConfig{ Name: "test", Audience: []string{"consul.io", "nomad.dev"}, - Env: pointer.Of(false), - File: pointer.Of(true), - TTL: pointer.Of(2 * time.Hour), + Env: new(false), + File: new(true), + TTL: new(2 * time.Hour), }, ExtraKeysHCL: []string{"a", "1"}, // not merged } diff --git a/nomad/structs/config/drain.go b/nomad/structs/config/drain.go index adba89bcc5d..402390c59bb 100644 --- a/nomad/structs/config/drain.go +++ b/nomad/structs/config/drain.go @@ -42,10 +42,10 @@ func (d *DrainConfig) Merge(o *DrainConfig) *DrainConfig { nd.Deadline = pointer.Copy(o.Deadline) } if o.IgnoreSystemJobs != nil && *o.IgnoreSystemJobs { - nd.IgnoreSystemJobs = pointer.Of(true) + nd.IgnoreSystemJobs = new(true) } if o.Force != nil && *o.Force { - nd.Force = pointer.Of(true) + nd.Force = new(true) } return nd } diff --git a/nomad/structs/config/drain_test.go b/nomad/structs/config/drain_test.go index 9f52393d0bb..1d31aecc191 100644 --- a/nomad/structs/config/drain_test.go +++ b/nomad/structs/config/drain_test.go @@ -8,7 +8,6 @@ import ( "testing" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/shoenig/test/must" ) @@ -28,12 +27,12 @@ func TestDrainConfig_Copy(t *testing.T) { { name: "partial config", inputDrainConfig: &DrainConfig{ - Deadline: pointer.Of("5m"), + Deadline: new("5m"), IgnoreSystemJobs: nil, Force: nil, }, expectedOutput: &DrainConfig{ - Deadline: pointer.Of("5m"), + Deadline: new("5m"), IgnoreSystemJobs: nil, Force: nil, }, @@ -41,14 +40,14 @@ func TestDrainConfig_Copy(t *testing.T) { { name: "full config", inputDrainConfig: &DrainConfig{ - Deadline: pointer.Of("5m"), - IgnoreSystemJobs: pointer.Of(false), - Force: pointer.Of(true), + Deadline: new("5m"), + IgnoreSystemJobs: new(false), + Force: new(true), }, expectedOutput: &DrainConfig{ - Deadline: pointer.Of("5m"), - IgnoreSystemJobs: pointer.Of(false), - Force: pointer.Of(true), + Deadline: new("5m"), + IgnoreSystemJobs: new(false), + Force: new(true), }, }, } @@ -84,46 +83,46 @@ func TestDrainConfig_Merge(t *testing.T) { name: "nil input", inputDrainConfig: nil, mergeDrainConfig: &DrainConfig{ - Deadline: pointer.Of("5m"), - IgnoreSystemJobs: pointer.Of(false), - Force: pointer.Of(true), + Deadline: new("5m"), + IgnoreSystemJobs: new(false), + Force: new(true), }, expectedOutput: &DrainConfig{ - Deadline: pointer.Of("5m"), - IgnoreSystemJobs: pointer.Of(false), - Force: pointer.Of(true), + Deadline: new("5m"), + IgnoreSystemJobs: new(false), + Force: new(true), }, }, { name: "nil merge", inputDrainConfig: &DrainConfig{ - Deadline: pointer.Of("5m"), - IgnoreSystemJobs: pointer.Of(false), - Force: pointer.Of(true), + Deadline: new("5m"), + IgnoreSystemJobs: new(false), + Force: new(true), }, mergeDrainConfig: nil, expectedOutput: &DrainConfig{ - Deadline: pointer.Of("5m"), - IgnoreSystemJobs: pointer.Of(false), - Force: pointer.Of(true), + Deadline: new("5m"), + IgnoreSystemJobs: new(false), + Force: new(true), }, }, { name: "partial", inputDrainConfig: &DrainConfig{ - Deadline: pointer.Of("5m"), - IgnoreSystemJobs: pointer.Of(false), + Deadline: new("5m"), + IgnoreSystemJobs: new(false), Force: nil, }, mergeDrainConfig: &DrainConfig{ Deadline: nil, IgnoreSystemJobs: nil, - Force: pointer.Of(true), + Force: new(true), }, expectedOutput: &DrainConfig{ - Deadline: pointer.Of("5m"), - IgnoreSystemJobs: pointer.Of(false), - Force: pointer.Of(true), + Deadline: new("5m"), + IgnoreSystemJobs: new(false), + Force: new(true), }, }, } diff --git a/nomad/structs/config/limits.go b/nomad/structs/config/limits.go index c81df39c895..e9f6dfacc1a 100644 --- a/nomad/structs/config/limits.go +++ b/nomad/structs/config/limits.go @@ -3,8 +3,6 @@ package config -import "github.com/hashicorp/nomad/helper/pointer" - const ( // LimitsNonStreamingConnsPerClient is the number of connections per // peer to reserve for non-streaming RPC connections. Since streaming @@ -50,9 +48,9 @@ type Limits struct { func DefaultLimits() Limits { return Limits{ HTTPSHandshakeTimeout: "5s", - HTTPMaxConnsPerClient: pointer.Of(100), + HTTPMaxConnsPerClient: new(100), RPCHandshakeTimeout: "5s", - RPCMaxConnsPerClient: pointer.Of(100), + RPCMaxConnsPerClient: new(100), } } @@ -65,13 +63,13 @@ func (l *Limits) Merge(o Limits) Limits { m.HTTPSHandshakeTimeout = o.HTTPSHandshakeTimeout } if o.HTTPMaxConnsPerClient != nil { - m.HTTPMaxConnsPerClient = pointer.Of(*o.HTTPMaxConnsPerClient) + m.HTTPMaxConnsPerClient = new(*o.HTTPMaxConnsPerClient) } if o.RPCHandshakeTimeout != "" { m.RPCHandshakeTimeout = o.RPCHandshakeTimeout } if o.RPCMaxConnsPerClient != nil { - m.RPCMaxConnsPerClient = pointer.Of(*o.RPCMaxConnsPerClient) + m.RPCMaxConnsPerClient = new(*o.RPCMaxConnsPerClient) } return m @@ -81,10 +79,10 @@ func (l *Limits) Merge(o Limits) Limits { func (l *Limits) Copy() Limits { c := *l if l.HTTPMaxConnsPerClient != nil { - c.HTTPMaxConnsPerClient = pointer.Of(*l.HTTPMaxConnsPerClient) + c.HTTPMaxConnsPerClient = new(*l.HTTPMaxConnsPerClient) } if l.RPCMaxConnsPerClient != nil { - c.RPCMaxConnsPerClient = pointer.Of(*l.RPCMaxConnsPerClient) + c.RPCMaxConnsPerClient = new(*l.RPCMaxConnsPerClient) } return c } diff --git a/nomad/structs/config/limits_test.go b/nomad/structs/config/limits_test.go index 503d3540b27..43f70f6ee0d 100644 --- a/nomad/structs/config/limits_test.go +++ b/nomad/structs/config/limits_test.go @@ -8,7 +8,6 @@ import ( "time" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/stretchr/testify/require" ) @@ -35,9 +34,9 @@ func TestLimits_Copy(t *testing.T) { // Assert changes to copy are not propagated to the original c.HTTPSHandshakeTimeout = "1s" - c.HTTPMaxConnsPerClient = pointer.Of(50) + c.HTTPMaxConnsPerClient = new(50) c.RPCHandshakeTimeout = "1s" - c.RPCMaxConnsPerClient = pointer.Of(50) + c.RPCMaxConnsPerClient = new(50) require.NotEqual(t, c.HTTPSHandshakeTimeout, o.HTTPSHandshakeTimeout) @@ -77,7 +76,7 @@ func TestLimits_Merge(t *testing.T) { // Use short struct initialization style so it fails to compile if // fields are added - expected := Limits{"10s", pointer.Of(100), "5s", pointer.Of(100)} + expected := Limits{"10s", new(100), "5s", new(100)} require.Equal(t, expected, m2) // Mergin in 0 values should not change anything diff --git a/nomad/structs/config/reporting_test.go b/nomad/structs/config/reporting_test.go index dac445f9a6d..48c4e011314 100644 --- a/nomad/structs/config/reporting_test.go +++ b/nomad/structs/config/reporting_test.go @@ -7,7 +7,6 @@ import ( "testing" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/shoenig/test/must" ) @@ -16,13 +15,13 @@ func TestReporting_Merge(t *testing.T) { a := &ReportingConfig{ License: &LicenseReportingConfig{ - Enabled: pointer.Of(false), + Enabled: new(false), }, } b := &ReportingConfig{ License: &LicenseReportingConfig{ - Enabled: pointer.Of(true), + Enabled: new(true), }, } diff --git a/nomad/structs/config/ui.go b/nomad/structs/config/ui.go index 158d19b575c..96352aefd3a 100644 --- a/nomad/structs/config/ui.go +++ b/nomad/structs/config/ui.go @@ -7,8 +7,6 @@ import ( "fmt" "slices" "strings" - - "github.com/hashicorp/nomad/helper/pointer" ) // UIConfig contains the operator configuration of the web UI @@ -147,7 +145,7 @@ func DefaultUIConfig() *UIConfig { Vault: &VaultUIConfig{}, Label: &LabelUIConfig{}, ContentSecurityPolicy: DefaultCSPConfig(), - ShowCLIHints: pointer.Of(true), + ShowCLIHints: new(true), } } diff --git a/nomad/structs/config/users.go b/nomad/structs/config/users.go index 741cd47ae46..c6613e83ff7 100644 --- a/nomad/structs/config/users.go +++ b/nomad/structs/config/users.go @@ -94,7 +94,7 @@ func (u *UsersConfig) Validate() error { // DefaultUsersConfig returns the default users configuration. func DefaultUsersConfig() *UsersConfig { return &UsersConfig{ - MinDynamicUser: pointer.Of(80_000), - MaxDynamicUser: pointer.Of(89_999), + MinDynamicUser: new(80_000), + MaxDynamicUser: new(89_999), } } diff --git a/nomad/structs/config/users_test.go b/nomad/structs/config/users_test.go index 7960998e57f..6ad2b67a21c 100644 --- a/nomad/structs/config/users_test.go +++ b/nomad/structs/config/users_test.go @@ -7,7 +7,6 @@ import ( "testing" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/shoenig/test/must" ) @@ -19,7 +18,7 @@ func TestUsersConfig_Copy(t *testing.T) { must.Equal(t, a, b) must.Equal(t, b, a) - a.MaxDynamicUser = pointer.Of(1000) + a.MaxDynamicUser = new(1000) must.NotEqual(t, a, b) must.NotEqual(t, b, a) } @@ -36,40 +35,40 @@ func TestUsersConfig_Merge(t *testing.T) { { name: "merge all fields", source: &UsersConfig{ - MinDynamicUser: pointer.Of(100), - MaxDynamicUser: pointer.Of(200), + MinDynamicUser: new(100), + MaxDynamicUser: new(200), }, other: &UsersConfig{ - MinDynamicUser: pointer.Of(3000), - MaxDynamicUser: pointer.Of(4000), + MinDynamicUser: new(3000), + MaxDynamicUser: new(4000), }, exp: &UsersConfig{ - MinDynamicUser: pointer.Of(3000), - MaxDynamicUser: pointer.Of(4000), + MinDynamicUser: new(3000), + MaxDynamicUser: new(4000), }, }, { name: "null source", source: nil, other: &UsersConfig{ - MinDynamicUser: pointer.Of(100), - MaxDynamicUser: pointer.Of(200), + MinDynamicUser: new(100), + MaxDynamicUser: new(200), }, exp: &UsersConfig{ - MinDynamicUser: pointer.Of(100), - MaxDynamicUser: pointer.Of(200), + MinDynamicUser: new(100), + MaxDynamicUser: new(200), }, }, { name: "null other", other: nil, source: &UsersConfig{ - MinDynamicUser: pointer.Of(100), - MaxDynamicUser: pointer.Of(200), + MinDynamicUser: new(100), + MaxDynamicUser: new(200), }, exp: &UsersConfig{ - MinDynamicUser: pointer.Of(100), - MaxDynamicUser: pointer.Of(200), + MinDynamicUser: new(100), + MaxDynamicUser: new(200), }, }, } @@ -106,7 +105,7 @@ func TestUsersConfig_Validate(t *testing.T) { { name: "min dynamic user not valid", modify: func(u *UsersConfig) { - u.MinDynamicUser = pointer.Of(-2) + u.MinDynamicUser = new(-2) }, exp: errDynamicUserMinInvalid, }, @@ -120,7 +119,7 @@ func TestUsersConfig_Validate(t *testing.T) { { name: "max dynamic user not valid", modify: func(u *UsersConfig) { - u.MaxDynamicUser = pointer.Of(-2) + u.MaxDynamicUser = new(-2) }, exp: errDynamicUserMaxInvalid, }, diff --git a/nomad/structs/config/vault_test.go b/nomad/structs/config/vault_test.go index 4fa43322785..388e587d46a 100644 --- a/nomad/structs/config/vault_test.go +++ b/nomad/structs/config/vault_test.go @@ -9,7 +9,6 @@ import ( "time" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/shoenig/test/must" ) @@ -17,7 +16,7 @@ func TestVaultConfig_Merge(t *testing.T) { ci.Parallel(t) c1 := &VaultConfig{ - Enabled: pointer.Of(false), + Enabled: new(false), Role: "1", Addr: "1", JWTAuthBackendPath: "jwt", @@ -25,13 +24,13 @@ func TestVaultConfig_Merge(t *testing.T) { TLSCaPath: "1", TLSCertFile: "1", TLSKeyFile: "1", - TLSSkipVerify: pointer.Of(true), + TLSSkipVerify: new(true), TLSServerName: "1", DefaultIdentity: nil, } c2 := &VaultConfig{ - Enabled: pointer.Of(true), + Enabled: new(true), Role: "2", Addr: "2", JWTAuthBackendPath: "jwt2", @@ -43,13 +42,13 @@ func TestVaultConfig_Merge(t *testing.T) { TLSServerName: "2", DefaultIdentity: &WorkloadIdentityConfig{ Audience: []string{"vault.dev"}, - Env: pointer.Of(true), - File: pointer.Of(false), + Env: new(true), + File: new(false), }, } e := &VaultConfig{ - Enabled: pointer.Of(true), + Enabled: new(true), Role: "2", Addr: "2", JWTAuthBackendPath: "jwt2", @@ -57,12 +56,12 @@ func TestVaultConfig_Merge(t *testing.T) { TLSCaPath: "2", TLSCertFile: "2", TLSKeyFile: "2", - TLSSkipVerify: pointer.Of(true), + TLSSkipVerify: new(true), TLSServerName: "2", DefaultIdentity: &WorkloadIdentityConfig{ Audience: []string{"vault.dev"}, - Env: pointer.Of(true), - File: pointer.Of(false), + Env: new(true), + File: new(false), }, } @@ -76,7 +75,7 @@ func TestVaultConfig_Equals(t *testing.T) { ci.Parallel(t) c1 := &VaultConfig{ - Enabled: pointer.Of(false), + Enabled: new(false), Role: "1", Namespace: "1", Addr: "1", @@ -86,17 +85,17 @@ func TestVaultConfig_Equals(t *testing.T) { TLSCaPath: "1", TLSCertFile: "1", TLSKeyFile: "1", - TLSSkipVerify: pointer.Of(true), + TLSSkipVerify: new(true), TLSServerName: "1", DefaultIdentity: &WorkloadIdentityConfig{ Audience: []string{"vault.dev"}, - Env: pointer.Of(true), - File: pointer.Of(false), + Env: new(true), + File: new(false), }, } c2 := &VaultConfig{ - Enabled: pointer.Of(false), + Enabled: new(false), Role: "1", Namespace: "1", Addr: "1", @@ -106,19 +105,19 @@ func TestVaultConfig_Equals(t *testing.T) { TLSCaPath: "1", TLSCertFile: "1", TLSKeyFile: "1", - TLSSkipVerify: pointer.Of(true), + TLSSkipVerify: new(true), TLSServerName: "1", DefaultIdentity: &WorkloadIdentityConfig{ Audience: []string{"vault.dev"}, - Env: pointer.Of(true), - File: pointer.Of(false), + Env: new(true), + File: new(false), }, } must.Equal(t, c1, c2) c3 := &VaultConfig{ - Enabled: pointer.Of(true), + Enabled: new(true), Role: "1", Namespace: "1", Addr: "1", @@ -127,17 +126,17 @@ func TestVaultConfig_Equals(t *testing.T) { TLSCaPath: "1", TLSCertFile: "1", TLSKeyFile: "1", - TLSSkipVerify: pointer.Of(true), + TLSSkipVerify: new(true), TLSServerName: "1", DefaultIdentity: &WorkloadIdentityConfig{ Audience: []string{"vault.dev"}, - Env: pointer.Of(true), - File: pointer.Of(false), + Env: new(true), + File: new(false), }, } c4 := &VaultConfig{ - Enabled: pointer.Of(false), + Enabled: new(false), Role: "1", Namespace: "1", Addr: "1", @@ -146,12 +145,12 @@ func TestVaultConfig_Equals(t *testing.T) { TLSCaPath: "1", TLSCertFile: "1", TLSKeyFile: "1", - TLSSkipVerify: pointer.Of(true), + TLSSkipVerify: new(true), TLSServerName: "1", DefaultIdentity: &WorkloadIdentityConfig{ Audience: []string{"vault.io"}, - Env: pointer.Of(false), - File: pointer.Of(true), + Env: new(false), + File: new(true), }, } diff --git a/nomad/structs/config/workload_id.go b/nomad/structs/config/workload_id.go index be244e69c8a..028b4d86f06 100644 --- a/nomad/structs/config/workload_id.go +++ b/nomad/structs/config/workload_id.go @@ -57,13 +57,13 @@ func (wi *WorkloadIdentityConfig) Copy() *WorkloadIdentityConfig { nwi.Audience = slices.Clone(wi.Audience) if wi.Env != nil { - nwi.Env = pointer.Of(*wi.Env) + nwi.Env = new(*wi.Env) } if wi.File != nil { - nwi.File = pointer.Of(*wi.File) + nwi.File = new(*wi.File) } if wi.TTL != nil { - nwi.TTL = pointer.Of(*wi.TTL) + nwi.TTL = new(*wi.TTL) } nwi.ExtraClaims = maps.Clone(wi.ExtraClaims) diff --git a/nomad/structs/config/workload_id_test.go b/nomad/structs/config/workload_id_test.go index c429c7fb793..590070cf3b6 100644 --- a/nomad/structs/config/workload_id_test.go +++ b/nomad/structs/config/workload_id_test.go @@ -8,7 +8,6 @@ import ( "time" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/shoenig/test/must" ) @@ -18,10 +17,10 @@ func TestWorkloadIdentityConfig_Copy(t *testing.T) { original := &WorkloadIdentityConfig{ Name: "test", Audience: []string{"aud"}, - Env: pointer.Of(true), - File: pointer.Of(false), + Env: new(true), + File: new(false), Filepath: "foo", - TTL: pointer.Of(time.Hour), + TTL: new(time.Hour), } // Verify Copy() returns the same values but different pointer. @@ -62,18 +61,18 @@ func TestWorkloadIdentityConfig_Equal(t *testing.T) { a: &WorkloadIdentityConfig{ Name: "test", Audience: []string{"aud"}, - Env: pointer.Of(true), - File: pointer.Of(false), + Env: new(true), + File: new(false), Filepath: "foo", - TTL: pointer.Of(time.Hour), + TTL: new(time.Hour), }, b: &WorkloadIdentityConfig{ Name: "test", Audience: []string{"aud"}, - Env: pointer.Of(true), - File: pointer.Of(false), + Env: new(true), + File: new(false), Filepath: "foo", - TTL: pointer.Of(time.Hour), + TTL: new(time.Hour), }, expectEq: true, }, @@ -100,17 +99,17 @@ func TestWorkloadIdentityConfig_Equal(t *testing.T) { { name: "different env", a: &WorkloadIdentityConfig{ - Env: pointer.Of(true), + Env: new(true), }, b: &WorkloadIdentityConfig{ - Env: pointer.Of(false), + Env: new(false), }, expectEq: false, }, { name: "different env nil", a: &WorkloadIdentityConfig{ - Env: pointer.Of(true), + Env: new(true), }, b: &WorkloadIdentityConfig{ Env: nil, @@ -120,10 +119,10 @@ func TestWorkloadIdentityConfig_Equal(t *testing.T) { { name: "different file", a: &WorkloadIdentityConfig{ - File: pointer.Of(true), + File: new(true), }, b: &WorkloadIdentityConfig{ - File: pointer.Of(false), + File: new(false), }, expectEq: false, }, @@ -140,7 +139,7 @@ func TestWorkloadIdentityConfig_Equal(t *testing.T) { { name: "different file nil", a: &WorkloadIdentityConfig{ - File: pointer.Of(true), + File: new(true), }, b: &WorkloadIdentityConfig{ File: nil, @@ -150,10 +149,10 @@ func TestWorkloadIdentityConfig_Equal(t *testing.T) { { name: "different ttl", a: &WorkloadIdentityConfig{ - TTL: pointer.Of(time.Hour), + TTL: new(time.Hour), }, b: &WorkloadIdentityConfig{ - TTL: pointer.Of(time.Minute), + TTL: new(time.Minute), }, expectEq: false, }, @@ -186,10 +185,10 @@ func TestWorkloadIdentityConfig_Merge(t *testing.T) { expected: &WorkloadIdentityConfig{ Name: "other", Audience: []string{"aud"}, - Env: pointer.Of(true), - File: pointer.Of(false), + Env: new(true), + File: new(false), Filepath: "test", - TTL: pointer.Of(time.Hour), + TTL: new(time.Hour), }, }, { @@ -200,38 +199,38 @@ func TestWorkloadIdentityConfig_Merge(t *testing.T) { expected: &WorkloadIdentityConfig{ Name: "test", Audience: []string{"aud", "other"}, - Env: pointer.Of(true), - File: pointer.Of(false), + Env: new(true), + File: new(false), Filepath: "test", - TTL: pointer.Of(time.Hour), + TTL: new(time.Hour), }, }, { name: "merge env", other: &WorkloadIdentityConfig{ - Env: pointer.Of(false), + Env: new(false), }, expected: &WorkloadIdentityConfig{ Name: "test", Audience: []string{"aud"}, - Env: pointer.Of(false), - File: pointer.Of(false), + Env: new(false), + File: new(false), Filepath: "test", - TTL: pointer.Of(time.Hour), + TTL: new(time.Hour), }, }, { name: "merge file", other: &WorkloadIdentityConfig{ - File: pointer.Of(true), + File: new(true), }, expected: &WorkloadIdentityConfig{ Name: "test", Audience: []string{"aud"}, - Env: pointer.Of(true), - File: pointer.Of(true), + Env: new(true), + File: new(true), Filepath: "test", - TTL: pointer.Of(time.Hour), + TTL: new(time.Hour), }, }, { @@ -242,24 +241,24 @@ func TestWorkloadIdentityConfig_Merge(t *testing.T) { expected: &WorkloadIdentityConfig{ Name: "test", Audience: []string{"aud"}, - Env: pointer.Of(true), - File: pointer.Of(false), + Env: new(true), + File: new(false), Filepath: "other", - TTL: pointer.Of(time.Hour), + TTL: new(time.Hour), }, }, { name: "merge ttl", other: &WorkloadIdentityConfig{ - TTL: pointer.Of(time.Second), + TTL: new(time.Second), }, expected: &WorkloadIdentityConfig{ Name: "test", Audience: []string{"aud"}, - Env: pointer.Of(true), - File: pointer.Of(false), + Env: new(true), + File: new(false), Filepath: "test", - TTL: pointer.Of(time.Second), + TTL: new(time.Second), }, }, } @@ -269,10 +268,10 @@ func TestWorkloadIdentityConfig_Merge(t *testing.T) { original := &WorkloadIdentityConfig{ Name: "test", Audience: []string{"aud"}, - Env: pointer.Of(true), - File: pointer.Of(false), + Env: new(true), + File: new(false), Filepath: "test", - TTL: pointer.Of(time.Hour), + TTL: new(time.Hour), } got := original.Merge(tc.other) must.Eq(t, tc.expected, got) @@ -284,33 +283,33 @@ func TestWorkloadIdentityConfig_Merge_multiple(t *testing.T) { widConfig1 := &WorkloadIdentityConfig{ Name: "wid1", Audience: []string{"aud1"}, - Env: pointer.Of(true), + Env: new(true), } widConfig2 := &WorkloadIdentityConfig{ Name: "wid2", Audience: []string{"aud2"}, - Env: pointer.Of(false), + Env: new(false), } got12 := widConfig1.Merge(widConfig2) must.Eq(t, &WorkloadIdentityConfig{ Name: "wid2", Audience: []string{"aud1", "aud2"}, - Env: pointer.Of(false), + Env: new(false), }, got12) widConfig3 := &WorkloadIdentityConfig{ Name: "wid3", Audience: []string{"aud1", "aud2", "aud3"}, - File: pointer.Of(false), + File: new(false), } got123 := got12.Merge(widConfig3) must.Eq(t, &WorkloadIdentityConfig{ Name: "wid3", Audience: []string{"aud1", "aud2", "aud3"}, - Env: pointer.Of(false), - File: pointer.Of(false), + Env: new(false), + File: new(false), }, got123) } diff --git a/nomad/structs/diff_test.go b/nomad/structs/diff_test.go index b296b2de564..b25ac2e7f99 100644 --- a/nomad/structs/diff_test.go +++ b/nomad/structs/diff_test.go @@ -9,7 +9,6 @@ import ( "time" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/shoenig/test/must" ) @@ -2973,9 +2972,9 @@ func TestTaskGroupDiff(t *testing.T) { Old: &TaskGroup{ Disconnect: &DisconnectStrategy{ LostAfter: 1 * time.Second, - Replace: pointer.Of(true), + Replace: new(true), Reconcile: ReconcileOptionLongestRunning, - StopOnClientAfter: pointer.Of(1 * time.Second), + StopOnClientAfter: new(1 * time.Second), }, }, New: &TaskGroup{}, @@ -3021,9 +3020,9 @@ func TestTaskGroupDiff(t *testing.T) { New: &TaskGroup{ Disconnect: &DisconnectStrategy{ LostAfter: time.Second, - Replace: pointer.Of(true), + Replace: new(true), Reconcile: ReconcileOptionLongestRunning, - StopOnClientAfter: pointer.Of(1 * time.Second), + StopOnClientAfter: new(1 * time.Second), }, }, Expected: &TaskGroupDiff{ @@ -3067,17 +3066,17 @@ func TestTaskGroupDiff(t *testing.T) { Old: &TaskGroup{ Disconnect: &DisconnectStrategy{ LostAfter: time.Second, - Replace: pointer.Of(false), + Replace: new(false), Reconcile: ReconcileOptionLongestRunning, - StopOnClientAfter: pointer.Of(1 * time.Second), + StopOnClientAfter: new(1 * time.Second), }, }, New: &TaskGroup{ Disconnect: &DisconnectStrategy{ LostAfter: time.Minute, - Replace: pointer.Of(true), + Replace: new(true), Reconcile: ReconcileOptionBestScore, - StopOnClientAfter: pointer.Of(1 * time.Minute), + StopOnClientAfter: new(1 * time.Minute), }, }, Expected: &TaskGroupDiff{ @@ -3122,17 +3121,17 @@ func TestTaskGroupDiff(t *testing.T) { Old: &TaskGroup{ Disconnect: &DisconnectStrategy{ LostAfter: time.Second, - Replace: pointer.Of(false), + Replace: new(false), Reconcile: ReconcileOptionLongestRunning, - StopOnClientAfter: pointer.Of(1 * time.Second), + StopOnClientAfter: new(1 * time.Second), }, }, New: &TaskGroup{ Disconnect: &DisconnectStrategy{ LostAfter: time.Minute, - Replace: pointer.Of(true), + Replace: new(true), Reconcile: ReconcileOptionBestScore, - StopOnClientAfter: pointer.Of(1 * time.Second), + StopOnClientAfter: new(1 * time.Second), }, }, Expected: &TaskGroupDiff{ @@ -3397,7 +3396,7 @@ func TestTaskGroupDiff(t *testing.T) { }, Gateway: &ConsulGateway{ Proxy: &ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(1 * time.Second), + ConnectTimeout: new(1 * time.Second), EnvoyGatewayBindTaggedAddresses: false, EnvoyGatewayBindAddresses: map[string]*ConsulGatewayBindAddress{ "service1": { @@ -3510,7 +3509,7 @@ func TestTaskGroupDiff(t *testing.T) { }, Gateway: &ConsulGateway{ Proxy: &ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(2 * time.Second), + ConnectTimeout: new(2 * time.Second), EnvoyGatewayBindTaggedAddresses: true, EnvoyGatewayBindAddresses: map[string]*ConsulGatewayBindAddress{ "service1": { @@ -4643,10 +4642,10 @@ func TestTaskGroupDiff(t *testing.T) { { TestCase: "TaskGroup shutdown_delay edited", Old: &TaskGroup{ - ShutdownDelay: pointer.Of(30 * time.Second), + ShutdownDelay: new(30 * time.Second), }, New: &TaskGroup{ - ShutdownDelay: pointer.Of(5 * time.Second), + ShutdownDelay: new(5 * time.Second), }, Expected: &TaskGroupDiff{ Type: DiffTypeEdited, @@ -4663,7 +4662,7 @@ func TestTaskGroupDiff(t *testing.T) { { TestCase: "TaskGroup shutdown_delay removed", Old: &TaskGroup{ - ShutdownDelay: pointer.Of(30 * time.Second), + ShutdownDelay: new(30 * time.Second), }, New: &TaskGroup{}, Expected: &TaskGroupDiff{ @@ -4682,7 +4681,7 @@ func TestTaskGroupDiff(t *testing.T) { TestCase: "TaskGroup shutdown_delay added", Old: &TaskGroup{}, New: &TaskGroup{ - ShutdownDelay: pointer.Of(30 * time.Second), + ShutdownDelay: new(30 * time.Second), }, Expected: &TaskGroupDiff{ Type: DiffTypeEdited, @@ -8427,11 +8426,11 @@ func TestTaskDiff(t *testing.T) { }, Splay: 1, Perms: "0644", - Uid: pointer.Of(1001), - Gid: pointer.Of(21), + Uid: new(1001), + Gid: new(21), Wait: &WaitConfig{ - Min: pointer.Of(5 * time.Second), - Max: pointer.Of(5 * time.Second), + Min: new(5 * time.Second), + Max: new(5 * time.Second), }, ErrMissingKey: false, }, @@ -8449,8 +8448,8 @@ func TestTaskDiff(t *testing.T) { }, Splay: 2, Perms: "0666", - Uid: pointer.Of(1000), - Gid: pointer.Of(20), + Uid: new(1000), + Gid: new(20), Envvars: true, }, }, @@ -8471,11 +8470,11 @@ func TestTaskDiff(t *testing.T) { }, Splay: 1, Perms: "0644", - Uid: pointer.Of(1001), - Gid: pointer.Of(21), + Uid: new(1001), + Gid: new(21), Wait: &WaitConfig{ - Min: pointer.Of(5 * time.Second), - Max: pointer.Of(10 * time.Second), + Min: new(5 * time.Second), + Max: new(10 * time.Second), }, ErrMissingKey: true, }, @@ -8493,11 +8492,11 @@ func TestTaskDiff(t *testing.T) { }, Splay: 3, Perms: "0776", - Uid: pointer.Of(1002), - Gid: pointer.Of(22), + Uid: new(1002), + Gid: new(22), Wait: &WaitConfig{ - Min: pointer.Of(5 * time.Second), - Max: pointer.Of(10 * time.Second), + Min: new(5 * time.Second), + Max: new(10 * time.Second), }, ErrMissingKey: true, }, @@ -10737,12 +10736,12 @@ func TestDiff_SidecarIdentities(t *testing.T) { }, }, Meta: map[string]string{"meta": "val"}, - KillTimeout: pointer.Of(10 * time.Second), + KillTimeout: new(10 * time.Second), LogConfig: &LogConfig{ MaxFiles: 3, MaxFileSizeMB: 100, }, - ShutdownDelay: pointer.Of(20 * time.Second), + ShutdownDelay: new(20 * time.Second), KillSignal: "SIGUSR1", Identities: []*WorkloadIdentity{ { @@ -10766,12 +10765,12 @@ func TestDiff_SidecarIdentities(t *testing.T) { }, }, Meta: map[string]string{"meta": "val"}, - KillTimeout: pointer.Of(10 * time.Second), + KillTimeout: new(10 * time.Second), LogConfig: &LogConfig{ MaxFiles: 3, MaxFileSizeMB: 100, }, - ShutdownDelay: pointer.Of(20 * time.Second), + ShutdownDelay: new(20 * time.Second), KillSignal: "SIGUSR1", Identities: []*WorkloadIdentity{ { @@ -10968,12 +10967,12 @@ func TestDiff_SidecarVolumes(t *testing.T) { }, }, Meta: map[string]string{"meta": "val"}, - KillTimeout: pointer.Of(10 * time.Second), + KillTimeout: new(10 * time.Second), LogConfig: &LogConfig{ MaxFiles: 3, MaxFileSizeMB: 100, }, - ShutdownDelay: pointer.Of(20 * time.Second), + ShutdownDelay: new(20 * time.Second), KillSignal: "SIGUSR1", VolumeMounts: []*VolumeMount{ { @@ -10995,12 +10994,12 @@ func TestDiff_SidecarVolumes(t *testing.T) { }, }, Meta: map[string]string{"meta": "val"}, - KillTimeout: pointer.Of(10 * time.Second), + KillTimeout: new(10 * time.Second), LogConfig: &LogConfig{ MaxFiles: 3, MaxFileSizeMB: 100, }, - ShutdownDelay: pointer.Of(20 * time.Second), + ShutdownDelay: new(20 * time.Second), KillSignal: "SIGUSR1", VolumeMounts: []*VolumeMount{ { diff --git a/nomad/structs/group.go b/nomad/structs/group.go index f7b0c59ef71..735db2f5e65 100644 --- a/nomad/structs/group.go +++ b/nomad/structs/group.go @@ -9,7 +9,6 @@ import ( "time" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/nomad/helper/pointer" ) const ( @@ -33,7 +32,7 @@ var ( func NewDefaultDisconnectStrategy() *DisconnectStrategy { return &DisconnectStrategy{ - Replace: pointer.Of(true), + Replace: new(true), Reconcile: ReconcileOptionBestScore, } } @@ -108,11 +107,11 @@ func (ds *DisconnectStrategy) Copy() *DisconnectStrategy { *nds = *ds if ds.StopOnClientAfter != nil { - nds.StopOnClientAfter = pointer.Of(*ds.StopOnClientAfter) + nds.StopOnClientAfter = new(*ds.StopOnClientAfter) } if ds.Replace != nil { - nds.Replace = pointer.Of(*ds.Replace) + nds.Replace = new(*ds.Replace) } return nds @@ -120,7 +119,7 @@ func (ds *DisconnectStrategy) Copy() *DisconnectStrategy { func (ds *DisconnectStrategy) Canonicalize() { if ds.Replace == nil { - ds.Replace = pointer.Of(true) + ds.Replace = new(true) } if ds.Reconcile == "" { diff --git a/nomad/structs/group_test.go b/nomad/structs/group_test.go index ac348042f39..423afdf7457 100644 --- a/nomad/structs/group_test.go +++ b/nomad/structs/group_test.go @@ -9,7 +9,6 @@ import ( "time" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/shoenig/test/must" ) @@ -52,7 +51,7 @@ func TestDisconnectStrategy_Validate(t *testing.T) { { name: "negative-stop-after", strategy: &DisconnectStrategy{ - StopOnClientAfter: pointer.Of(-1 * time.Second), + StopOnClientAfter: new(-1 * time.Second), }, jobType: JobTypeService, err: errNegativeStopAfter, @@ -60,7 +59,7 @@ func TestDisconnectStrategy_Validate(t *testing.T) { { name: "stop-after-on-system", strategy: &DisconnectStrategy{ - StopOnClientAfter: pointer.Of(1 * time.Second), + StopOnClientAfter: new(1 * time.Second), }, jobType: JobTypeSystem, err: errStopAfterNonService, @@ -77,7 +76,7 @@ func TestDisconnectStrategy_Validate(t *testing.T) { name: "lost-after-and-stop-after-enabled", strategy: &DisconnectStrategy{ LostAfter: 1 * time.Second, - StopOnClientAfter: pointer.Of(1 * time.Second), + StopOnClientAfter: new(1 * time.Second), }, jobType: JobTypeService, err: errStopAndLost, @@ -96,7 +95,7 @@ func TestDisconnectStrategy_Validate(t *testing.T) { strategy: &DisconnectStrategy{ LostAfter: 1 * time.Second, Reconcile: ReconcileOptionKeepOriginal, - Replace: pointer.Of(true), + Replace: new(true), StopOnClientAfter: nil, }, jobType: JobTypeService, @@ -199,7 +198,7 @@ func TestJob_Validate_DisconnectRescheduleLost(t *testing.T) { Name: "cache", Disconnect: &DisconnectStrategy{ LostAfter: 1 * time.Hour, - Replace: pointer.Of(false), + Replace: new(false), }, Tasks: []*Task{ { diff --git a/nomad/structs/node_pool.go b/nomad/structs/node_pool.go index b4dfc4308d7..5f2290b2794 100644 --- a/nomad/structs/node_pool.go +++ b/nomad/structs/node_pool.go @@ -12,7 +12,6 @@ import ( "time" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/nomad/helper/pointer" "golang.org/x/crypto/blake2b" ) @@ -264,7 +263,7 @@ func (n *NodePoolSchedulerConfiguration) Copy() *NodePoolSchedulerConfiguration *nc = *n if n.MemoryOversubscriptionEnabled != nil { - nc.MemoryOversubscriptionEnabled = pointer.Of(*n.MemoryOversubscriptionEnabled) + nc.MemoryOversubscriptionEnabled = new(*n.MemoryOversubscriptionEnabled) } return nc diff --git a/nomad/structs/node_pool_test.go b/nomad/structs/node_pool_test.go index 08c0790e225..a59a2395a1e 100644 --- a/nomad/structs/node_pool_test.go +++ b/nomad/structs/node_pool_test.go @@ -9,7 +9,6 @@ import ( "time" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/shoenig/test/must" ) @@ -55,7 +54,7 @@ func TestNodePool_Copy(t *testing.T) { Meta: map[string]string{"original": "true"}, SchedulerConfiguration: &NodePoolSchedulerConfiguration{ SchedulerAlgorithm: SchedulerAlgorithmSpread, - MemoryOversubscriptionEnabled: pointer.Of(false), + MemoryOversubscriptionEnabled: new(false), }, } poolCopy := pool.Copy() @@ -64,7 +63,7 @@ func TestNodePool_Copy(t *testing.T) { poolCopy.Meta["original"] = "false" poolCopy.Meta["new_key"] = "true" poolCopy.SchedulerConfiguration.SchedulerAlgorithm = SchedulerAlgorithmBinpack - poolCopy.SchedulerConfiguration.MemoryOversubscriptionEnabled = pointer.Of(true) + poolCopy.SchedulerConfiguration.MemoryOversubscriptionEnabled = new(true) must.NotEq(t, pool, poolCopy) must.NotEq(t, pool.Meta, poolCopy.Meta) @@ -201,7 +200,7 @@ func TestNodePool_MemoryOversubscriptionEnabled(t *testing.T) { name: "pool overrides global if it defines memory oversub", pool: &NodePool{ SchedulerConfiguration: &NodePoolSchedulerConfiguration{ - MemoryOversubscriptionEnabled: pointer.Of(false), + MemoryOversubscriptionEnabled: new(false), }, }, global: &SchedulerConfiguration{ @@ -213,7 +212,7 @@ func TestNodePool_MemoryOversubscriptionEnabled(t *testing.T) { name: "pool used if global is nil", pool: &NodePool{ SchedulerConfiguration: &NodePoolSchedulerConfiguration{ - MemoryOversubscriptionEnabled: pointer.Of(true), + MemoryOversubscriptionEnabled: new(true), }, }, global: nil, diff --git a/nomad/structs/operator_test.go b/nomad/structs/operator_test.go index 113338d0cf6..142f4a03e30 100644 --- a/nomad/structs/operator_test.go +++ b/nomad/structs/operator_test.go @@ -7,7 +7,6 @@ import ( "testing" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/shoenig/test/must" ) @@ -51,7 +50,7 @@ func TestSchedulerConfiguration_WithNodePool(t *testing.T) { }, pool: &NodePool{ SchedulerConfiguration: &NodePoolSchedulerConfiguration{ - MemoryOversubscriptionEnabled: pointer.Of(true), + MemoryOversubscriptionEnabled: new(true), }, }, expected: &SchedulerConfiguration{ diff --git a/nomad/structs/services.go b/nomad/structs/services.go index f74872ea6f0..7ff83256bd0 100644 --- a/nomad/structs/services.go +++ b/nomad/structs/services.go @@ -1544,11 +1544,11 @@ func (t *SidecarTask) Copy() *SidecarTask { } if t.KillTimeout != nil { - nt.KillTimeout = pointer.Of(*t.KillTimeout) + nt.KillTimeout = new(*t.KillTimeout) } if t.ShutdownDelay != nil { - nt.ShutdownDelay = pointer.Of(*t.ShutdownDelay) + nt.ShutdownDelay = new(*t.ShutdownDelay) } nt.VolumeMounts = CopySliceVolumeMount(t.VolumeMounts) @@ -2059,7 +2059,7 @@ func (p *ConsulGatewayProxy) Copy() *ConsulGatewayProxy { } return &ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(*p.ConnectTimeout), + ConnectTimeout: new(*p.ConnectTimeout), EnvoyGatewayBindTaggedAddresses: p.EnvoyGatewayBindTaggedAddresses, EnvoyGatewayBindAddresses: p.copyBindAddresses(), EnvoyGatewayNoDefaultBind: p.EnvoyGatewayNoDefaultBind, diff --git a/nomad/structs/services_test.go b/nomad/structs/services_test.go index 1d127572523..b069a2be816 100644 --- a/nomad/structs/services_test.go +++ b/nomad/structs/services_test.go @@ -11,7 +11,6 @@ import ( "github.com/hashicorp/go-multierror" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/shoenig/test/must" "github.com/stretchr/testify/require" ) @@ -658,7 +657,7 @@ func TestConsulConnect_GatewayProxy_CopyEqual(t *testing.T) { ci.Parallel(t) c := &ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(1 * time.Second), + ConnectTimeout: new(1 * time.Second), EnvoyGatewayBindTaggedAddresses: false, EnvoyGatewayBindAddresses: make(map[string]*ConsulGatewayBindAddress), } @@ -692,11 +691,11 @@ func TestSidecarTask_MergeIntoTask(t *testing.T) { Meta: map[string]string{ "abc": "123", }, - KillTimeout: pointer.Of(15 * time.Second), + KillTimeout: new(15 * time.Second), LogConfig: &LogConfig{ MaxFiles: 3, }, - ShutdownDelay: pointer.Of(5 * time.Second), + ShutdownDelay: new(5 * time.Second), KillSignal: "SIGABRT", } @@ -749,12 +748,12 @@ func TestSidecarTask_Equal(t *testing.T) { TTL: 1337 * time.Minute, }}, Meta: map[string]string{"index": "1"}, - KillTimeout: pointer.Of(2 * time.Second), + KillTimeout: new(2 * time.Second), LogConfig: &LogConfig{ MaxFiles: 2, MaxFileSizeMB: 300, }, - ShutdownDelay: pointer.Of(10 * time.Second), + ShutdownDelay: new(10 * time.Second), KillSignal: "SIGTERM", } @@ -805,7 +804,7 @@ func TestSidecarTask_Equal(t *testing.T) { }) t.Run("mod kill timeout", func(t *testing.T) { - try(t, func(s *st) { s.KillTimeout = pointer.Of(3 * time.Second) }) + try(t, func(s *st) { s.KillTimeout = new(3 * time.Second) }) }) t.Run("mod log config", func(t *testing.T) { @@ -813,7 +812,7 @@ func TestSidecarTask_Equal(t *testing.T) { }) t.Run("mod shutdown delay", func(t *testing.T) { - try(t, func(s *st) { s.ShutdownDelay = pointer.Of(20 * time.Second) }) + try(t, func(s *st) { s.ShutdownDelay = new(20 * time.Second) }) }) t.Run("mod kill signal", func(t *testing.T) { @@ -1038,7 +1037,7 @@ func TestConsulSidecarService_Copy(t *testing.T) { var ( consulIngressGateway1 = &ConsulGateway{ Proxy: &ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(1 * time.Second), + ConnectTimeout: new(1 * time.Second), EnvoyGatewayBindTaggedAddresses: true, EnvoyGatewayBindAddresses: map[string]*ConsulGatewayBindAddress{ "listener1": {Address: "10.0.0.1", Port: 2001}, @@ -1075,7 +1074,7 @@ var ( consulTerminatingGateway1 = &ConsulGateway{ Proxy: &ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(1 * time.Second), + ConnectTimeout: new(1 * time.Second), EnvoyDNSDiscoveryType: "STRICT_DNS", EnvoyGatewayBindAddresses: nil, }, @@ -1094,7 +1093,7 @@ var ( consulMeshGateway1 = &ConsulGateway{ Proxy: &ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(1 * time.Second), + ConnectTimeout: new(1 * time.Second), }, Mesh: &ConsulMeshConfigEntry{ // nothing @@ -1199,7 +1198,7 @@ func TestConsulGateway_Equal_ingress(t *testing.T) { // proxy block equality checks t.Run("mod gateway timeout", func(t *testing.T) { - try(t, func(g *cg) { g.Proxy.ConnectTimeout = pointer.Of(9 * time.Second) }) + try(t, func(g *cg) { g.Proxy.ConnectTimeout = new(9 * time.Second) }) }) t.Run("mod gateway envoy_gateway_bind_tagged_addresses", func(t *testing.T) { @@ -1481,7 +1480,7 @@ func TestConsulGatewayProxy_Validate(t *testing.T) { t.Run("invalid bind address", func(t *testing.T) { err := (&ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(1 * time.Second), + ConnectTimeout: new(1 * time.Second), EnvoyGatewayBindAddresses: map[string]*ConsulGatewayBindAddress{ "service1": { Address: "10.0.0.1", @@ -1493,7 +1492,7 @@ func TestConsulGatewayProxy_Validate(t *testing.T) { t.Run("invalid dns discovery type", func(t *testing.T) { err := (&ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(1 * time.Second), + ConnectTimeout: new(1 * time.Second), EnvoyDNSDiscoveryType: "RANDOM_DNS", }).Validate() require.EqualError(t, err, "Consul Gateway Proxy Envoy DNS Discovery type must be STRICT_DNS or LOGICAL_DNS") @@ -1501,14 +1500,14 @@ func TestConsulGatewayProxy_Validate(t *testing.T) { t.Run("ok with nothing set", func(t *testing.T) { err := (&ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(1 * time.Second), + ConnectTimeout: new(1 * time.Second), }).Validate() require.NoError(t, err) }) t.Run("ok with everything set", func(t *testing.T) { err := (&ConsulGatewayProxy{ - ConnectTimeout: pointer.Of(1 * time.Second), + ConnectTimeout: new(1 * time.Second), EnvoyGatewayBindAddresses: map[string]*ConsulGatewayBindAddress{ "service1": { Address: "10.0.0.1", diff --git a/nomad/structs/structs_test.go b/nomad/structs/structs_test.go index 1040d74a793..15981c626ba 100644 --- a/nomad/structs/structs_test.go +++ b/nomad/structs/structs_test.go @@ -18,7 +18,6 @@ import ( "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/client/lib/idset" "github.com/hashicorp/nomad/client/lib/numalib/hw" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" psstructs "github.com/hashicorp/nomad/plugins/shared/structs" "github.com/kr/pretty" @@ -717,7 +716,7 @@ func TestJob_Warnings(t *testing.T) { { Name: "Group services with group-level shutdown delay but no task-level shutdown delay set", Expected: []string{}, - Job: groupServiceJob(pointer.Of(time.Second)), + Job: groupServiceJob(new(time.Second)), }, { Name: "Group service references task without shutdown delay warning", @@ -732,12 +731,12 @@ func TestJob_Warnings(t *testing.T) { { Name: "Connect sidecar task without 0 shutdown delay no warning", Expected: []string{}, - Job: connectSidecarServiceJob(pointer.Of(time.Duration(0))), + Job: connectSidecarServiceJob(new(time.Duration(0))), }, { Name: "Connect sidecar task with shutdown delay no warning", Expected: []string{}, - Job: connectSidecarServiceJob(pointer.Of(time.Second)), + Job: connectSidecarServiceJob(new(time.Second)), }, } @@ -3454,15 +3453,15 @@ func TestTemplate_Copy(t *testing.T) { }, Splay: 10 * time.Second, Perms: "777", - Uid: pointer.Of(1000), - Gid: pointer.Of(2000), + Uid: new(1000), + Gid: new(2000), LeftDelim: "[[", RightDelim: "]]", Envvars: true, VaultGrace: time.Minute, Wait: &WaitConfig{ - Min: pointer.Of(time.Second), - Max: pointer.Of(time.Minute), + Min: new(time.Second), + Max: new(time.Minute), }, } t2 := t1.Copy() @@ -3475,14 +3474,14 @@ func TestTemplate_Copy(t *testing.T) { t1.ChangeScript.Args = []string{"--forces", "--debugs"} t1.Splay = 5 * time.Second t1.Perms = "700" - t1.Uid = pointer.Of(5000) - t1.Gid = pointer.Of(6000) + t1.Uid = new(5000) + t1.Gid = new(6000) t1.LeftDelim = "((" t1.RightDelim = "))" t1.Envvars = false t1.VaultGrace = 2 * time.Minute - t1.Wait.Min = pointer.Of(2 * time.Second) - t1.Wait.Max = pointer.Of(2 * time.Minute) + t1.Wait.Min = new(2 * time.Second) + t1.Wait.Max = new(2 * time.Minute) require.NotEqual(t, t1.SourcePath, t2.SourcePath) require.NotEqual(t, t1.DestPath, t2.DestPath) @@ -3593,8 +3592,8 @@ func TestTemplate_Validate(t *testing.T) { DestPath: "local/foo", ChangeMode: "noop", Wait: &WaitConfig{ - Min: pointer.Of(10 * time.Second), - Max: pointer.Of(5 * time.Second), + Min: new(10 * time.Second), + Max: new(5 * time.Second), }, }, Fail: true, @@ -3608,8 +3607,8 @@ func TestTemplate_Validate(t *testing.T) { DestPath: "local/foo", ChangeMode: "noop", Wait: &WaitConfig{ - Min: pointer.Of(5 * time.Second), - Max: pointer.Of(5 * time.Second), + Min: new(5 * time.Second), + Max: new(5 * time.Second), }, }, Fail: false, @@ -3620,8 +3619,8 @@ func TestTemplate_Validate(t *testing.T) { DestPath: "local/foo", ChangeMode: "noop", Wait: &WaitConfig{ - Min: pointer.Of(5 * time.Second), - Max: pointer.Of(10 * time.Second), + Min: new(5 * time.Second), + Max: new(10 * time.Second), }, }, Fail: false, @@ -3686,12 +3685,12 @@ func TestTaskWaitConfig_Equals(t *testing.T) { { name: "all-fields", wc1: &WaitConfig{ - Min: pointer.Of(5 * time.Second), - Max: pointer.Of(10 * time.Second), + Min: new(5 * time.Second), + Max: new(10 * time.Second), }, wc2: &WaitConfig{ - Min: pointer.Of(5 * time.Second), - Max: pointer.Of(10 * time.Second), + Min: new(5 * time.Second), + Max: new(10 * time.Second), }, exp: true, }, @@ -3704,27 +3703,27 @@ func TestTaskWaitConfig_Equals(t *testing.T) { { name: "min-only", wc1: &WaitConfig{ - Min: pointer.Of(5 * time.Second), + Min: new(5 * time.Second), }, wc2: &WaitConfig{ - Min: pointer.Of(5 * time.Second), + Min: new(5 * time.Second), }, exp: true, }, { name: "max-only", wc1: &WaitConfig{ - Max: pointer.Of(10 * time.Second), + Max: new(10 * time.Second), }, wc2: &WaitConfig{ - Max: pointer.Of(10 * time.Second), + Max: new(10 * time.Second), }, exp: true, }, { name: "min-nil-vs-set", wc1: &WaitConfig{ - Min: pointer.Of(1 * time.Second), + Min: new(1 * time.Second), }, wc2: &WaitConfig{ Min: nil, @@ -3734,7 +3733,7 @@ func TestTaskWaitConfig_Equals(t *testing.T) { { name: "max-nil-vs-set", wc1: &WaitConfig{ - Max: pointer.Of(1 * time.Second), + Max: new(1 * time.Second), }, wc2: &WaitConfig{ Max: nil, @@ -6616,7 +6615,7 @@ func TestDevicesEquals(t *testing.T) { }, }}, Attributes: map[string]*psstructs.Attribute{ - "test-attr": {String: pointer.Of("test-value")}, + "test-attr": {String: new("test-value")}, }, }}, } @@ -6671,7 +6670,7 @@ func TestDevicesEquals(t *testing.T) { name: "diff attribute", change: func(r *NodeResources) { r.Devices[0].Attributes["test-attr"] = &psstructs.Attribute{ - String: pointer.Of("another-value"), + String: new("another-value"), } }, }, @@ -7276,14 +7275,14 @@ func TestWaitConfig_Equal(t *testing.T) { must.NotEqual[*WaitConfig](t, nil, new(WaitConfig)) must.StructEqual(t, &WaitConfig{ - Min: pointer.Of[time.Duration](100), - Max: pointer.Of[time.Duration](200), + Min: new(time.Duration(100)), + Max: new(time.Duration(200)), }, []must.Tweak[*WaitConfig]{{ Field: "Min", - Apply: func(c *WaitConfig) { c.Min = pointer.Of[time.Duration](111) }, + Apply: func(c *WaitConfig) { c.Min = new(time.Duration(111)) }, }, { Field: "Max", - Apply: func(c *WaitConfig) { c.Max = pointer.Of[time.Duration](222) }, + Apply: func(c *WaitConfig) { c.Max = new(time.Duration(222)) }, }}) } @@ -7371,15 +7370,15 @@ func TestTemplate_Equal(t *testing.T) { }, Splay: 1, Perms: "perms", - Uid: pointer.Of(1000), - Gid: pointer.Of(1000), + Uid: new(1000), + Gid: new(1000), LeftDelim: "{", RightDelim: "}", Envvars: true, VaultGrace: 1 * time.Second, Wait: &WaitConfig{ - Min: pointer.Of[time.Duration](1), - Max: pointer.Of[time.Duration](2), + Min: new(time.Duration(1)), + Max: new(time.Duration(2)), }, ErrMissingKey: true, }, []must.Tweak[*Template]{{ @@ -7415,10 +7414,10 @@ func TestTemplate_Equal(t *testing.T) { Apply: func(t *Template) { t.Perms = "perms2" }, }, { Field: "Uid", - Apply: func(t *Template) { t.Uid = pointer.Of(0) }, + Apply: func(t *Template) { t.Uid = new(0) }, }, { Field: "Gid", - Apply: func(t *Template) { t.Gid = pointer.Of(0) }, + Apply: func(t *Template) { t.Gid = new(0) }, }, { Field: "LeftDelim", Apply: func(t *Template) { t.LeftDelim = "[" }, @@ -7435,7 +7434,7 @@ func TestTemplate_Equal(t *testing.T) { Field: "Wait", Apply: func(t *Template) { t.Wait = &WaitConfig{ - Min: pointer.Of[time.Duration](1), + Min: new(time.Duration(1)), Max: nil, } }, diff --git a/plugins/device/cmd/example/device.go b/plugins/device/cmd/example/device.go index 5e3000c66fd..da1a2afb891 100644 --- a/plugins/device/cmd/example/device.go +++ b/plugins/device/cmd/example/device.go @@ -13,7 +13,6 @@ import ( "time" log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/plugins/base" "github.com/hashicorp/nomad/plugins/device" "github.com/hashicorp/nomad/plugins/shared/hclspec" @@ -251,7 +250,7 @@ func getDeviceGroup(devices []*device.Device) *device.DeviceGroup { Devices: devices, Attributes: map[string]*structs.Attribute{ "cool-attribute": { - String: pointer.Of("attribute-wearing-sunglasses"), + String: new("attribute-wearing-sunglasses"), }, }, } @@ -351,23 +350,23 @@ func (d *FsDevice) collectStats() (*device.DeviceGroupStats, error) { s := &device.DeviceStats{ Summary: &structs.StatValue{ - IntNumeratorVal: pointer.Of(f.Size()), + IntNumeratorVal: new(f.Size()), Unit: "bytes", Desc: "Filesize in bytes", }, Stats: &structs.StatObject{ Attributes: map[string]*structs.StatValue{ "size": { - IntNumeratorVal: pointer.Of(f.Size()), + IntNumeratorVal: new(f.Size()), Unit: "bytes", Desc: "Filesize in bytes", }, "modify_time": { - StringVal: pointer.Of(f.ModTime().String()), + StringVal: new(f.ModTime().String()), Desc: "Last modified", }, "mode": { - StringVal: pointer.Of(f.Mode().String()), + StringVal: new(f.Mode().String()), Desc: "File mode", }, }, diff --git a/plugins/device/plugin_test.go b/plugins/device/plugin_test.go index 558c4833b2b..a611ea68b6d 100644 --- a/plugins/device/plugin_test.go +++ b/plugins/device/plugin_test.go @@ -12,7 +12,6 @@ import ( pb "github.com/golang/protobuf/proto" plugin "github.com/hashicorp/go-plugin" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/structs" "github.com/hashicorp/nomad/plugins/base" "github.com/hashicorp/nomad/plugins/shared/hclspec" @@ -198,7 +197,7 @@ func TestDevicePlugin_Fingerprint(t *testing.T) { Name: "foo", Attributes: map[string]*psstructs.Attribute{ "memory": { - Int: pointer.Of(int64(4)), + Int: new(int64(4)), Unit: "GiB", }, }, @@ -479,8 +478,8 @@ func TestDevicePlugin_Stats(t *testing.T) { InstanceStats: map[string]*DeviceStats{ "1": { Summary: &psstructs.StatValue{ - IntNumeratorVal: pointer.Of(int64(10)), - IntDenominatorVal: pointer.Of(int64(20)), + IntNumeratorVal: new(int64(10)), + IntDenominatorVal: new(int64(20)), Unit: "MB", Desc: "Unit test", }, @@ -496,8 +495,8 @@ func TestDevicePlugin_Stats(t *testing.T) { InstanceStats: map[string]*DeviceStats{ "1": { Summary: &psstructs.StatValue{ - FloatNumeratorVal: pointer.Of(float64(10.0)), - FloatDenominatorVal: pointer.Of(float64(20.0)), + FloatNumeratorVal: new(float64(10.0)), + FloatDenominatorVal: new(float64(20.0)), Unit: "MB", Desc: "Unit test", }, @@ -511,7 +510,7 @@ func TestDevicePlugin_Stats(t *testing.T) { InstanceStats: map[string]*DeviceStats{ "1": { Summary: &psstructs.StatValue{ - StringVal: pointer.Of("foo"), + StringVal: new("foo"), Unit: "MB", Desc: "Unit test", }, @@ -525,7 +524,7 @@ func TestDevicePlugin_Stats(t *testing.T) { InstanceStats: map[string]*DeviceStats{ "1": { Summary: &psstructs.StatValue{ - BoolVal: pointer.Of(true), + BoolVal: new(true), Unit: "MB", Desc: "Unit test", }, diff --git a/plugins/shared/structs/attribute.go b/plugins/shared/structs/attribute.go index a13e5e7866c..215462aceac 100644 --- a/plugins/shared/structs/attribute.go +++ b/plugins/shared/structs/attribute.go @@ -9,8 +9,6 @@ import ( "strconv" "strings" "unicode" - - "github.com/hashicorp/nomad/helper/pointer" ) const ( @@ -61,7 +59,7 @@ func (u *Unit) Comparable(o *Unit) bool { func ParseAttribute(input string) *Attribute { ll := len(input) if ll == 0 { - return &Attribute{String: pointer.Of(input)} + return &Attribute{String: new(input)} } // Check if the string is a number ending with potential units @@ -85,22 +83,22 @@ func ParseAttribute(input string) *Attribute { // Try to parse as an int i, err := strconv.ParseInt(numeric, 10, 64) if err == nil { - return &Attribute{Int: pointer.Of(i), Unit: unit} + return &Attribute{Int: new(i), Unit: unit} } // Try to parse as a float f, err := strconv.ParseFloat(numeric, 64) if err == nil { - return &Attribute{Float: pointer.Of(f), Unit: unit} + return &Attribute{Float: new(f), Unit: unit} } // Try to parse as a bool b, err := strconv.ParseBool(input) if err == nil { - return &Attribute{Bool: pointer.Of(b)} + return &Attribute{Bool: new(b)} } - return &Attribute{String: pointer.Of(input)} + return &Attribute{String: new(input)} } // Attribute is used to describe the value of an attribute, optionally @@ -125,14 +123,14 @@ type Attribute struct { // NewStringAttribute returns a new string attribute. func NewStringAttribute(s string) *Attribute { return &Attribute{ - String: pointer.Of(s), + String: new(s), } } // NewBoolAttribute returns a new boolean attribute. func NewBoolAttribute(b bool) *Attribute { return &Attribute{ - Bool: pointer.Of(b), + Bool: new(b), } } @@ -140,7 +138,7 @@ func NewBoolAttribute(b bool) *Attribute { // to be valid. func NewIntAttribute(i int64, unit string) *Attribute { return &Attribute{ - Int: pointer.Of(i), + Int: new(i), Unit: unit, } } @@ -149,7 +147,7 @@ func NewIntAttribute(i int64, unit string) *Attribute { // be valid. func NewFloatAttribute(f float64, unit string) *Attribute { return &Attribute{ - Float: pointer.Of(f), + Float: new(f), Unit: unit, } } @@ -205,16 +203,16 @@ func (a *Attribute) Copy() *Attribute { } if a.Float != nil { - ca.Float = pointer.Of(*a.Float) + ca.Float = new(*a.Float) } if a.Int != nil { - ca.Int = pointer.Of(*a.Int) + ca.Int = new(*a.Int) } if a.Bool != nil { - ca.Bool = pointer.Of(*a.Bool) + ca.Bool = new(*a.Bool) } if a.String != nil { - ca.String = pointer.Of(*a.String) + ca.String = new(*a.String) } return ca diff --git a/plugins/shared/structs/attribute_test.go b/plugins/shared/structs/attribute_test.go index a023b2ce958..33805845c6e 100644 --- a/plugins/shared/structs/attribute_test.go +++ b/plugins/shared/structs/attribute_test.go @@ -7,7 +7,6 @@ import ( "fmt" "testing" - "github.com/hashicorp/nomad/helper/pointer" "github.com/shoenig/test/must" ) @@ -18,56 +17,56 @@ func TestAttribute_Validate(t *testing.T) { }{ { Input: &Attribute{ - Bool: pointer.Of(true), + Bool: new(true), }, }, { Input: &Attribute{ - String: pointer.Of("foo"), + String: new("foo"), }, }, { Input: &Attribute{ - Int: pointer.Of(int64(123)), + Int: new(int64(123)), }, }, { Input: &Attribute{ - Float: pointer.Of(float64(123.2)), + Float: new(float64(123.2)), }, }, { Input: &Attribute{ - Bool: pointer.Of(true), + Bool: new(true), Unit: "MB", }, Fail: true, }, { Input: &Attribute{ - String: pointer.Of("foo"), + String: new("foo"), Unit: "MB", }, Fail: true, }, { Input: &Attribute{ - Int: pointer.Of(int64(123)), + Int: new(int64(123)), Unit: "lolNO", }, Fail: true, }, { Input: &Attribute{ - Float: pointer.Of(float64(123.2)), + Float: new(float64(123.2)), Unit: "lolNO", }, Fail: true, }, { Input: &Attribute{ - Int: pointer.Of(int64(123)), - Float: pointer.Of(float64(123.2)), + Int: new(int64(123)), + Float: new(float64(123.2)), Unit: "mW", }, Fail: true, @@ -94,46 +93,46 @@ func TestAttribute_Compare_Bool(t *testing.T) { cases := []*compareTestCase{ { A: &Attribute{ - Bool: pointer.Of(true), + Bool: new(true), }, B: &Attribute{ - Bool: pointer.Of(true), + Bool: new(true), }, Expected: 0, }, { A: &Attribute{ - Bool: pointer.Of(true), + Bool: new(true), }, B: &Attribute{ - Bool: pointer.Of(false), + Bool: new(false), }, Expected: 1, }, { A: &Attribute{ - Bool: pointer.Of(true), + Bool: new(true), }, B: &Attribute{ - String: pointer.Of("foo"), + String: new("foo"), }, NotComparable: true, }, { A: &Attribute{ - Bool: pointer.Of(true), + Bool: new(true), }, B: &Attribute{ - Int: pointer.Of(int64(123)), + Int: new(int64(123)), }, NotComparable: true, }, { A: &Attribute{ - Bool: pointer.Of(true), + Bool: new(true), }, B: &Attribute{ - Float: pointer.Of(float64(123.2)), + Float: new(float64(123.2)), }, NotComparable: true, }, @@ -145,55 +144,55 @@ func TestAttribute_Compare_String(t *testing.T) { cases := []*compareTestCase{ { A: &Attribute{ - String: pointer.Of("a"), + String: new("a"), }, B: &Attribute{ - String: pointer.Of("b"), + String: new("b"), }, Expected: -1, }, { A: &Attribute{ - String: pointer.Of("hello"), + String: new("hello"), }, B: &Attribute{ - String: pointer.Of("hello"), + String: new("hello"), }, Expected: 0, }, { A: &Attribute{ - String: pointer.Of("b"), + String: new("b"), }, B: &Attribute{ - String: pointer.Of("a"), + String: new("a"), }, Expected: 1, }, { A: &Attribute{ - String: pointer.Of("hello"), + String: new("hello"), }, B: &Attribute{ - Bool: pointer.Of(true), + Bool: new(true), }, NotComparable: true, }, { A: &Attribute{ - String: pointer.Of("hello"), + String: new("hello"), }, B: &Attribute{ - Int: pointer.Of(int64(123)), + Int: new(int64(123)), }, NotComparable: true, }, { A: &Attribute{ - String: pointer.Of("hello"), + String: new("hello"), }, B: &Attribute{ - Float: pointer.Of(float64(123.2)), + Float: new(float64(123.2)), }, NotComparable: true, }, @@ -205,46 +204,46 @@ func TestAttribute_Compare_Float(t *testing.T) { cases := []*compareTestCase{ { A: &Attribute{ - Float: pointer.Of(float64(101.5)), + Float: new(float64(101.5)), }, B: &Attribute{ - Float: pointer.Of(float64(100001.5)), + Float: new(float64(100001.5)), }, Expected: -1, }, { A: &Attribute{ - Float: pointer.Of(float64(100001.5)), + Float: new(float64(100001.5)), }, B: &Attribute{ - Float: pointer.Of(float64(100001.5)), + Float: new(float64(100001.5)), }, Expected: 0, }, { A: &Attribute{ - Float: pointer.Of(float64(999999999.5)), + Float: new(float64(999999999.5)), }, B: &Attribute{ - Float: pointer.Of(float64(101.5)), + Float: new(float64(101.5)), }, Expected: 1, }, { A: &Attribute{ - Float: pointer.Of(float64(101.5)), + Float: new(float64(101.5)), }, B: &Attribute{ - Bool: pointer.Of(true), + Bool: new(true), }, NotComparable: true, }, { A: &Attribute{ - Float: pointer.Of(float64(101.5)), + Float: new(float64(101.5)), }, B: &Attribute{ - String: pointer.Of("hello"), + String: new("hello"), }, NotComparable: true, }, @@ -256,46 +255,46 @@ func TestAttribute_Compare_Int(t *testing.T) { cases := []*compareTestCase{ { A: &Attribute{ - Int: pointer.Of(int64(3)), + Int: new(int64(3)), }, B: &Attribute{ - Int: pointer.Of(int64(10)), + Int: new(int64(10)), }, Expected: -1, }, { A: &Attribute{ - Int: pointer.Of(int64(10)), + Int: new(int64(10)), }, B: &Attribute{ - Int: pointer.Of(int64(10)), + Int: new(int64(10)), }, Expected: 0, }, { A: &Attribute{ - Int: pointer.Of(int64(100)), + Int: new(int64(100)), }, B: &Attribute{ - Int: pointer.Of(int64(10)), + Int: new(int64(10)), }, Expected: 1, }, { A: &Attribute{ - Int: pointer.Of(int64(10)), + Int: new(int64(10)), }, B: &Attribute{ - Bool: pointer.Of(true), + Bool: new(true), }, NotComparable: true, }, { A: &Attribute{ - Int: pointer.Of(int64(10)), + Int: new(int64(10)), }, B: &Attribute{ - String: pointer.Of("hello"), + String: new("hello"), }, NotComparable: true, }, @@ -307,77 +306,77 @@ func TestAttribute_Compare_Int_With_Units(t *testing.T) { cases := []*compareTestCase{ { A: &Attribute{ - Int: pointer.Of(int64(3)), + Int: new(int64(3)), Unit: "MB", }, B: &Attribute{ - Int: pointer.Of(int64(10)), + Int: new(int64(10)), Unit: "MB", }, Expected: -1, }, { A: &Attribute{ - Int: pointer.Of(int64(10)), + Int: new(int64(10)), Unit: "MB", }, B: &Attribute{ - Int: pointer.Of(int64(10)), + Int: new(int64(10)), Unit: "MB", }, Expected: 0, }, { A: &Attribute{ - Int: pointer.Of(int64(100)), + Int: new(int64(100)), Unit: "MB", }, B: &Attribute{ - Int: pointer.Of(int64(10)), + Int: new(int64(10)), Unit: "MB", }, Expected: 1, }, { A: &Attribute{ - Int: pointer.Of(int64(3)), + Int: new(int64(3)), Unit: "GB", }, B: &Attribute{ - Int: pointer.Of(int64(3)), + Int: new(int64(3)), Unit: "MB", }, Expected: 1, }, { A: &Attribute{ - Int: pointer.Of(int64(1)), + Int: new(int64(1)), Unit: "GiB", }, B: &Attribute{ - Int: pointer.Of(int64(1024)), + Int: new(int64(1024)), Unit: "MiB", }, Expected: 0, }, { A: &Attribute{ - Int: pointer.Of(int64(1)), + Int: new(int64(1)), Unit: "GiB", }, B: &Attribute{ - Int: pointer.Of(int64(1025)), + Int: new(int64(1025)), Unit: "MiB", }, Expected: -1, }, { A: &Attribute{ - Int: pointer.Of(int64(1000)), + Int: new(int64(1000)), Unit: "mW", }, B: &Attribute{ - Int: pointer.Of(int64(1)), + Int: new(int64(1)), Unit: "W", }, Expected: 0, @@ -390,88 +389,88 @@ func TestAttribute_Compare_Float_With_Units(t *testing.T) { cases := []*compareTestCase{ { A: &Attribute{ - Float: pointer.Of(float64(3.0)), + Float: new(float64(3.0)), Unit: "MB", }, B: &Attribute{ - Float: pointer.Of(float64(10.0)), + Float: new(float64(10.0)), Unit: "MB", }, Expected: -1, }, { A: &Attribute{ - Float: pointer.Of(float64(10.0)), + Float: new(float64(10.0)), Unit: "MB", }, B: &Attribute{ - Float: pointer.Of(float64(10.0)), + Float: new(float64(10.0)), Unit: "MB", }, Expected: 0, }, { A: &Attribute{ - Float: pointer.Of(float64(100.0)), + Float: new(float64(100.0)), Unit: "MB", }, B: &Attribute{ - Float: pointer.Of(float64(10.0)), + Float: new(float64(10.0)), Unit: "MB", }, Expected: 1, }, { A: &Attribute{ - Float: pointer.Of(float64(3.0)), + Float: new(float64(3.0)), Unit: "GB", }, B: &Attribute{ - Float: pointer.Of(float64(3.0)), + Float: new(float64(3.0)), Unit: "MB", }, Expected: 1, }, { A: &Attribute{ - Float: pointer.Of(float64(1.0)), + Float: new(float64(1.0)), Unit: "GiB", }, B: &Attribute{ - Float: pointer.Of(float64(1024.0)), + Float: new(float64(1024.0)), Unit: "MiB", }, Expected: 0, }, { A: &Attribute{ - Float: pointer.Of(float64(1.0)), + Float: new(float64(1.0)), Unit: "GiB", }, B: &Attribute{ - Float: pointer.Of(float64(1025.0)), + Float: new(float64(1025.0)), Unit: "MiB", }, Expected: -1, }, { A: &Attribute{ - Float: pointer.Of(float64(1000.0)), + Float: new(float64(1000.0)), Unit: "mW", }, B: &Attribute{ - Float: pointer.Of(float64(1.0)), + Float: new(float64(1.0)), Unit: "W", }, Expected: 0, }, { A: &Attribute{ - Float: pointer.Of(float64(1.5)), + Float: new(float64(1.5)), Unit: "GiB", }, B: &Attribute{ - Float: pointer.Of(float64(1400.0)), + Float: new(float64(1400.0)), Unit: "MiB", }, Expected: 1, @@ -484,46 +483,46 @@ func TestAttribute_Compare_IntToFloat(t *testing.T) { cases := []*compareTestCase{ { A: &Attribute{ - Int: pointer.Of(int64(3)), + Int: new(int64(3)), }, B: &Attribute{ - Float: pointer.Of(float64(10.0)), + Float: new(float64(10.0)), }, Expected: -1, }, { A: &Attribute{ - Int: pointer.Of(int64(10)), + Int: new(int64(10)), }, B: &Attribute{ - Float: pointer.Of(float64(10.0)), + Float: new(float64(10.0)), }, Expected: 0, }, { A: &Attribute{ - Int: pointer.Of(int64(10)), + Int: new(int64(10)), }, B: &Attribute{ - Float: pointer.Of(float64(10.1)), + Float: new(float64(10.1)), }, Expected: -1, }, { A: &Attribute{ - Int: pointer.Of(int64(100)), + Int: new(int64(100)), }, B: &Attribute{ - Float: pointer.Of(float64(10.0)), + Float: new(float64(10.0)), }, Expected: 1, }, { A: &Attribute{ - Int: pointer.Of(int64(100)), + Int: new(int64(100)), }, B: &Attribute{ - Float: pointer.Of(float64(100.00001)), + Float: new(float64(100.00001)), }, Expected: -1, }, @@ -552,108 +551,108 @@ func TestAttribute_ParseAndValidate(t *testing.T) { { Input: "true", Expected: &Attribute{ - Bool: pointer.Of(true), + Bool: new(true), }, }, { Input: "false", Expected: &Attribute{ - Bool: pointer.Of(false), + Bool: new(false), }, }, { Input: "1", Expected: &Attribute{ - Int: pointer.Of(int64(1)), + Int: new(int64(1)), }, }, { Input: "100", Expected: &Attribute{ - Int: pointer.Of(int64(100)), + Int: new(int64(100)), }, }, { Input: "-100", Expected: &Attribute{ - Int: pointer.Of(int64(-100)), + Int: new(int64(-100)), }, }, { Input: "-1.0", Expected: &Attribute{ - Float: pointer.Of(float64(-1.0)), + Float: new(float64(-1.0)), }, }, { Input: "-100.25", Expected: &Attribute{ - Float: pointer.Of(float64(-100.25)), + Float: new(float64(-100.25)), }, }, { Input: "1.01", Expected: &Attribute{ - Float: pointer.Of(float64(1.01)), + Float: new(float64(1.01)), }, }, { Input: "100.25", Expected: &Attribute{ - Float: pointer.Of(float64(100.25)), + Float: new(float64(100.25)), }, }, { Input: "foobar", Expected: &Attribute{ - String: pointer.Of("foobar"), + String: new("foobar"), }, }, { Input: "foo123bar", Expected: &Attribute{ - String: pointer.Of("foo123bar"), + String: new("foo123bar"), }, }, { Input: "100MB", Expected: &Attribute{ - Int: pointer.Of(int64(100)), + Int: new(int64(100)), Unit: "MB", }, }, { Input: "-100MHz", Expected: &Attribute{ - Int: pointer.Of(int64(-100)), + Int: new(int64(-100)), Unit: "MHz", }, }, { Input: "-1.0MB/s", Expected: &Attribute{ - Float: pointer.Of(float64(-1.0)), + Float: new(float64(-1.0)), Unit: "MB/s", }, }, { Input: "-100.25GiB/s", Expected: &Attribute{ - Float: pointer.Of(float64(-100.25)), + Float: new(float64(-100.25)), Unit: "GiB/s", }, }, { Input: "1.01TB", Expected: &Attribute{ - Float: pointer.Of(float64(1.01)), + Float: new(float64(1.01)), Unit: "TB", }, }, { Input: "100.25mW", Expected: &Attribute{ - Float: pointer.Of(float64(100.25)), + Float: new(float64(100.25)), Unit: "mW", }, }, diff --git a/plugins/shared/structs/util.go b/plugins/shared/structs/util.go index f1f5c6476a8..d595c73c325 100644 --- a/plugins/shared/structs/util.go +++ b/plugins/shared/structs/util.go @@ -5,7 +5,6 @@ package structs import ( "github.com/golang/protobuf/ptypes/wrappers" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/plugins/shared/structs/proto" ) @@ -16,13 +15,13 @@ func ConvertProtoAttribute(in *proto.Attribute) *Attribute { switch in.Value.(type) { case *proto.Attribute_BoolVal: - out.Bool = pointer.Of(in.GetBoolVal()) + out.Bool = new(in.GetBoolVal()) case *proto.Attribute_FloatVal: - out.Float = pointer.Of(in.GetFloatVal()) + out.Float = new(in.GetFloatVal()) case *proto.Attribute_IntVal: - out.Int = pointer.Of(in.GetIntVal()) + out.Int = new(in.GetIntVal()) case *proto.Attribute_StringVal: - out.String = pointer.Of(in.GetStringVal()) + out.String = new(in.GetStringVal()) default: } diff --git a/scheduler/generic_sched_test.go b/scheduler/generic_sched_test.go index ff008e91258..6a9e404df10 100644 --- a/scheduler/generic_sched_test.go +++ b/scheduler/generic_sched_test.go @@ -14,7 +14,6 @@ import ( memdb "github.com/hashicorp/go-memdb" "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/helper" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" @@ -1051,7 +1050,7 @@ func TestServiceSched_JobRegister_Datacenter_Downgrade(t *testing.T) { alloc.JobID = job1.ID alloc.NodeID = nodes[i].ID alloc.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), Timestamp: time.Now(), Canary: false, ModifyIndex: h.NextIndex(), @@ -1190,7 +1189,7 @@ func TestServiceSched_JobRegister_NodePool_Downgrade(t *testing.T) { alloc.JobID = job1.ID alloc.NodeID = nodes[i].ID alloc.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), Timestamp: time.Now(), Canary: false, ModifyIndex: h.NextIndex(), @@ -3193,7 +3192,7 @@ func TestServiceSched_JobModify_InPlace(t *testing.T) { alloc.JobID = job.ID alloc.Name = fmt.Sprintf("my-job.web[%d]", i) alloc.DeploymentID = d.ID - alloc.DeploymentStatus = &structs.AllocDeploymentStatus{Healthy: pointer.Of(true)} + alloc.DeploymentStatus = &structs.AllocDeploymentStatus{Healthy: new(true)} alloc.AllocatedResources.Tasks[taskName].Devices = []*structs.AllocatedDeviceResource{&adr} alloc.AllocatedResources.Shared = asr allocs = append(allocs, alloc) @@ -3847,7 +3846,7 @@ func TestServiceSched_NodeDown(t *testing.T) { alloc.ClientStatus = tc.client // Mark for migration if necessary - alloc.DesiredTransition.Migrate = pointer.Of(tc.migrate) + alloc.DesiredTransition.Migrate = new(tc.migrate) allocs := []*structs.Allocation{alloc} must.NoError(t, h.State.UpsertAllocs(structs.MsgTypeTestSetup, h.NextIndex(), allocs)) @@ -3928,7 +3927,7 @@ func TestServiceSched_StopOnClientAfter(t *testing.T) { jobSpecFn: func(job *structs.Job) { job.TaskGroups[0].Count = 1 job.TaskGroups[0].Disconnect = &structs.DisconnectStrategy{ - StopOnClientAfter: pointer.Of(1 * time.Second), + StopOnClientAfter: new(1 * time.Second), } }, previousStopWhen: time.Now().UTC().Add(-10 * time.Second), @@ -3940,7 +3939,7 @@ func TestServiceSched_StopOnClientAfter(t *testing.T) { jobSpecFn: func(job *structs.Job) { job.TaskGroups[0].Count = 1 job.TaskGroups[0].Disconnect = &structs.DisconnectStrategy{ - StopOnClientAfter: pointer.Of(1 * time.Second), + StopOnClientAfter: new(1 * time.Second), } }, expectBlockedEval: false, @@ -4148,7 +4147,7 @@ func TestServiceSched_NodeDrain(t *testing.T) { alloc.JobID = job.ID alloc.NodeID = node.ID alloc.Name = fmt.Sprintf("my-job.web[%d]", i) - alloc.DesiredTransition.Migrate = pointer.Of(true) + alloc.DesiredTransition.Migrate = new(true) allocs = append(allocs, alloc) } must.NoError(t, h.State.UpsertAllocs(structs.MsgTypeTestSetup, h.NextIndex(), allocs)) @@ -4235,7 +4234,7 @@ func TestServiceSched_NodeDrain_Down(t *testing.T) { for i := 0; i < 6; i++ { newAlloc := allocs[i].Copy() newAlloc.ClientStatus = structs.AllocDesiredStatusStop - newAlloc.DesiredTransition.Migrate = pointer.Of(true) + newAlloc.DesiredTransition.Migrate = new(true) stop = append(stop, newAlloc) } must.NoError(t, h.State.UpsertAllocs(structs.MsgTypeTestSetup, h.NextIndex(), stop)) @@ -4354,11 +4353,11 @@ func TestServiceSched_NodeDrain_Canaries(t *testing.T) { alloc.NodeID = drainedNode.ID alloc.Name = fmt.Sprintf("my-job.web[%d]", i) alloc.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(false), + Healthy: new(false), Canary: true, } alloc.DesiredTransition = structs.DesiredTransition{ - Migrate: pointer.Of(true), + Migrate: new(true), } allocs = append(allocs, alloc) canaries = append(canaries, alloc.ID) @@ -4380,7 +4379,7 @@ func TestServiceSched_NodeDrain_Canaries(t *testing.T) { replacement.ClientStatus = structs.AllocClientStatusRunning replacement.PreviousAllocation = canaries[0] replacement.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(false), + Healthy: new(false), Canary: true, } allocs = append(allocs, replacement) @@ -4455,7 +4454,7 @@ func TestServiceSched_NodeDrain_Queued_Allocations(t *testing.T) { alloc.JobID = job.ID alloc.NodeID = node.ID alloc.Name = fmt.Sprintf("my-job.web[%d]", i) - alloc.DesiredTransition.Migrate = pointer.Of(true) + alloc.DesiredTransition.Migrate = new(true) allocs = append(allocs, alloc) } must.NoError(t, h.State.UpsertAllocs(structs.MsgTypeTestSetup, h.NextIndex(), allocs)) @@ -5098,7 +5097,7 @@ func TestServiceSched_BlockedDisconnectReplace(t *testing.T) { lostAfterDuration := 12 * time.Hour job.TaskGroups[0].Disconnect = &structs.DisconnectStrategy{ LostAfter: lostAfterDuration, - Replace: pointer.Of(true), + Replace: new(true), Reconcile: "best_score", } job.TaskGroups[0].ReschedulePolicy = &structs.ReschedulePolicy{ @@ -5358,7 +5357,7 @@ func TestDeployment_FailedAllocs_Reschedule(t *testing.T) { allocs[1].TaskStates = map[string]*structs.TaskState{"web": {State: "start", StartedAt: time.Now().Add(-12 * time.Hour), FinishedAt: time.Now().Add(-10 * time.Hour)}} - allocs[1].DesiredTransition.Reschedule = pointer.Of(true) + allocs[1].DesiredTransition.Reschedule = new(true) must.NoError(t, h.State.UpsertAllocs(structs.MsgTypeTestSetup, h.NextIndex(), allocs)) @@ -6382,7 +6381,7 @@ func TestServiceSched_NodeDrain_Sticky(t *testing.T) { alloc.NodeID = node.ID alloc.Job.TaskGroups[0].Count = 1 alloc.Job.TaskGroups[0].EphemeralDisk.Sticky = true - alloc.DesiredTransition.Migrate = pointer.Of(true) + alloc.DesiredTransition.Migrate = new(true) must.NoError(t, h.State.UpsertJob(structs.MsgTypeTestSetup, h.NextIndex(), nil, alloc.Job)) must.NoError(t, h.State.UpsertAllocs(structs.MsgTypeTestSetup, h.NextIndex(), []*structs.Allocation{alloc})) @@ -7007,7 +7006,7 @@ func TestServiceSched_Migrate_NonCanary(t *testing.T) { alloc.Name = "my-job.web[0]" alloc.DesiredStatus = structs.AllocDesiredStatusRun alloc.ClientStatus = structs.AllocClientStatusRunning - alloc.DesiredTransition.Migrate = pointer.Of(true) + alloc.DesiredTransition.Migrate = new(true) must.NoError(t, h.State.UpsertAllocs(structs.MsgTypeTestSetup, h.NextIndex(), []*structs.Allocation{alloc})) // Create a mock evaluation diff --git a/scheduler/integration/spread_test.go b/scheduler/integration/spread_test.go index 55e8fe98d36..2cc094eb678 100644 --- a/scheduler/integration/spread_test.go +++ b/scheduler/integration/spread_test.go @@ -11,7 +11,6 @@ import ( "time" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" @@ -316,7 +315,7 @@ func TestSpreadPanicDowngrade(t *testing.T) { alloc.JobID = job1.ID alloc.NodeID = nodes[i].ID alloc.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), Timestamp: time.Now(), Canary: false, ModifyIndex: h.NextIndex(), diff --git a/scheduler/reconciler/allocs_test.go b/scheduler/reconciler/allocs_test.go index 961008da420..e60357aab45 100644 --- a/scheduler/reconciler/allocs_test.go +++ b/scheduler/reconciler/allocs_test.go @@ -8,7 +8,6 @@ import ( "time" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" @@ -19,7 +18,7 @@ func testJob_Disconnected() *structs.Job { testJob := mock.Job() testJob.TaskGroups[0].Disconnect = &structs.DisconnectStrategy{ LostAfter: 5 * time.Second, - Replace: pointer.Of(true), + Replace: new(true), } return testJob @@ -29,7 +28,7 @@ func testJobSingle_Disconnected() *structs.Job { testJobSingle := mock.Job() testJobSingle.TaskGroups[0].Disconnect = &structs.DisconnectStrategy{ LostAfter: 5 * time.Second, - Replace: pointer.Of(true), + Replace: new(true), } return testJobSingle } @@ -45,7 +44,7 @@ func testJobNoMaxDisconnectSingle_Disconnected() *structs.Job { testJobNoMaxDisconnectSingle := mock.Job() testJobNoMaxDisconnectSingle.TaskGroups[0].Disconnect = &structs.DisconnectStrategy{ LostAfter: 0 * time.Second, - Replace: pointer.Of(false), + Replace: new(false), } return testJobNoMaxDisconnectSingle @@ -173,7 +172,7 @@ func TestAllocSet_filterByTainted(t *testing.T) { "migrating1": { ID: "migrating1", ClientStatus: structs.AllocClientStatusRunning, - DesiredTransition: structs.DesiredTransition{Migrate: pointer.Of(true)}, + DesiredTransition: structs.DesiredTransition{Migrate: new(true)}, Job: testJob, NodeID: "draining", }, @@ -181,7 +180,7 @@ func TestAllocSet_filterByTainted(t *testing.T) { "migrating2": { ID: "migrating2", ClientStatus: structs.AllocClientStatusRunning, - DesiredTransition: structs.DesiredTransition{Migrate: pointer.Of(true)}, + DesiredTransition: structs.DesiredTransition{Migrate: new(true)}, Job: testJob, NodeID: "nil", }, @@ -220,7 +219,7 @@ func TestAllocSet_filterByTainted(t *testing.T) { "migrating1": { ID: "migrating1", ClientStatus: structs.AllocClientStatusRunning, - DesiredTransition: structs.DesiredTransition{Migrate: pointer.Of(true)}, + DesiredTransition: structs.DesiredTransition{Migrate: new(true)}, Job: testJob, NodeID: "draining", }, @@ -228,7 +227,7 @@ func TestAllocSet_filterByTainted(t *testing.T) { "migrating2": { ID: "migrating2", ClientStatus: structs.AllocClientStatusRunning, - DesiredTransition: structs.DesiredTransition{Migrate: pointer.Of(true)}, + DesiredTransition: structs.DesiredTransition{Migrate: new(true)}, Job: testJob, NodeID: "nil", }, @@ -875,7 +874,7 @@ func TestAllocSet_filterByTainted(t *testing.T) { "migrating1": { ID: "migrating1", ClientStatus: structs.AllocClientStatusRunning, - DesiredTransition: structs.DesiredTransition{Migrate: pointer.Of(true)}, + DesiredTransition: structs.DesiredTransition{Migrate: new(true)}, Job: testJobSingle, NodeID: "draining", }, @@ -883,7 +882,7 @@ func TestAllocSet_filterByTainted(t *testing.T) { "migrating2": { ID: "migrating2", ClientStatus: structs.AllocClientStatusRunning, - DesiredTransition: structs.DesiredTransition{Migrate: pointer.Of(true)}, + DesiredTransition: structs.DesiredTransition{Migrate: new(true)}, Job: testJobSingle, NodeID: "nil", }, @@ -922,7 +921,7 @@ func TestAllocSet_filterByTainted(t *testing.T) { "migrating1": { ID: "migrating1", ClientStatus: structs.AllocClientStatusRunning, - DesiredTransition: structs.DesiredTransition{Migrate: pointer.Of(true)}, + DesiredTransition: structs.DesiredTransition{Migrate: new(true)}, Job: testJobSingle, NodeID: "draining", }, @@ -930,7 +929,7 @@ func TestAllocSet_filterByTainted(t *testing.T) { "migrating2": { ID: "migrating2", ClientStatus: structs.AllocClientStatusRunning, - DesiredTransition: structs.DesiredTransition{Migrate: pointer.Of(true)}, + DesiredTransition: structs.DesiredTransition{Migrate: new(true)}, Job: testJobSingle, NodeID: "nil", }, @@ -1880,7 +1879,7 @@ func TestAllocSet_filterByRescheduleable(t *testing.T) { Job: testJob, TaskGroup: "rescheduleTG", DesiredTransition: structs.DesiredTransition{ - Reschedule: pointer.Of(true), + Reschedule: new(true), }, ModifyTime: now.Unix(), TaskStates: map[string]*structs.TaskState{ @@ -1895,7 +1894,7 @@ func TestAllocSet_filterByRescheduleable(t *testing.T) { Job: testJob, TaskGroup: "rescheduleTG", DesiredTransition: structs.DesiredTransition{ - Reschedule: pointer.Of(true), + Reschedule: new(true), }, ModifyTime: now.Unix(), TaskStates: map[string]*structs.TaskState{ diff --git a/scheduler/reconciler/reconcile_cluster_prop_test.go b/scheduler/reconciler/reconcile_cluster_prop_test.go index 62ba26dc7e5..81ba8456b8b 100644 --- a/scheduler/reconciler/reconcile_cluster_prop_test.go +++ b/scheduler/reconciler/reconcile_cluster_prop_test.go @@ -12,7 +12,6 @@ import ( "time" "github.com/hashicorp/nomad/helper" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/testlog" "github.com/hashicorp/nomad/nomad/structs" "github.com/shoenig/test/must" @@ -494,7 +493,7 @@ func genTaskGroup(idg *idGenerator) *rapid.Generator[*structs.TaskGroup] { Update: genUpdateBlock(tgCount).Draw(t, "tg_update_block"), Disconnect: &structs.DisconnectStrategy{ LostAfter: maybeDuration(50, 300).Draw(t, "disconnect:lost_after"), - Replace: pointer.Of(rapid.Bool().Draw(t, "disconnect:replace")), + Replace: new(rapid.Bool().Draw(t, "disconnect:replace")), Reconcile: structs.ReconcileOptionBestScore, }, // we'll use a fairly static policy and then use the alloc diff --git a/scheduler/reconciler/reconcile_cluster_test.go b/scheduler/reconciler/reconcile_cluster_test.go index e8428fd2839..f7d25970f0d 100644 --- a/scheduler/reconciler/reconcile_cluster_test.go +++ b/scheduler/reconciler/reconcile_cluster_test.go @@ -13,7 +13,6 @@ import ( "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/helper" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/testlog" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" @@ -1225,7 +1224,7 @@ func TestReconciler_DrainNode(t *testing.T) { for i := 0; i < 2; i++ { n := mock.DrainNode() n.ID = allocs[i].NodeID - allocs[i].DesiredTransition.Migrate = pointer.Of(true) + allocs[i].DesiredTransition.Migrate = new(true) tainted[n.ID] = n } @@ -1286,7 +1285,7 @@ func TestReconciler_MigrateBatchAllocs(t *testing.T) { // Flag two allocations to migrate for i := 0; i < 2; i++ { - allocs[i].DesiredTransition.Migrate = pointer.Of(true) + allocs[i].DesiredTransition.Migrate = new(true) } reconciler := NewAllocReconciler( @@ -1345,8 +1344,8 @@ func TestReconciler_MigrateDisablePlacementBatchAllocs(t *testing.T) { // Flag two allocations to migrate for i := 0; i < 2; i++ { - allocs[i].DesiredTransition.Migrate = pointer.Of(true) - allocs[i].DesiredTransition.MigrateDisablePlacement = pointer.Of(true) + allocs[i].DesiredTransition.Migrate = new(true) + allocs[i].DesiredTransition.MigrateDisablePlacement = new(true) } reconciler := NewAllocReconciler( @@ -1409,8 +1408,8 @@ func TestReconciler_MigrateRescheduleBatchAllocs(t *testing.T) { // Flag two allocations to migrate and reschedule for i := 0; i < 2; i++ { - allocs[i].DesiredTransition.Migrate = pointer.Of(true) - allocs[i].DesiredTransition.Reschedule = pointer.Of(true) + allocs[i].DesiredTransition.Migrate = new(true) + allocs[i].DesiredTransition.Reschedule = new(true) } reconciler := NewAllocReconciler( @@ -1464,8 +1463,8 @@ func TestReconciler_MigrateRescheduleBatchAllocs(t *testing.T) { // Flag two allocations to migrate and reschedule for i := 0; i < 2; i++ { - allocs[i].DesiredTransition.Migrate = pointer.Of(true) - allocs[i].DesiredTransition.Reschedule = pointer.Of(true) + allocs[i].DesiredTransition.Migrate = new(true) + allocs[i].DesiredTransition.Reschedule = new(true) } reconciler := NewAllocReconciler( @@ -1516,8 +1515,8 @@ func TestReconciler_MigrateRescheduleBatchAllocs(t *testing.T) { // Flag two allocations to migrate and reschedule for i := 0; i < 2; i++ { - allocs[i].DesiredTransition.Migrate = pointer.Of(true) - allocs[i].DesiredTransition.Reschedule = pointer.Of(true) + allocs[i].DesiredTransition.Migrate = new(true) + allocs[i].DesiredTransition.Reschedule = new(true) } reconciler := NewAllocReconciler( @@ -1572,8 +1571,8 @@ func TestReconciler_MigrateRescheduleBatchAllocs(t *testing.T) { // Flag two allocations to migrate and reschedule for i := 0; i < 2; i++ { - allocs[i].DesiredTransition.Migrate = pointer.Of(true) - allocs[i].DesiredTransition.Reschedule = pointer.Of(true) + allocs[i].DesiredTransition.Migrate = new(true) + allocs[i].DesiredTransition.Reschedule = new(true) } reconciler := NewAllocReconciler( @@ -1635,7 +1634,7 @@ func TestReconciler_DrainNode_ScaleUp(t *testing.T) { for i := 0; i < 2; i++ { n := mock.DrainNode() n.ID = allocs[i].NodeID - allocs[i].DesiredTransition.Migrate = pointer.Of(true) + allocs[i].DesiredTransition.Migrate = new(true) tainted[n.ID] = n } @@ -1701,7 +1700,7 @@ func TestReconciler_DrainNode_ScaleDown(t *testing.T) { for i := 0; i < 3; i++ { n := mock.DrainNode() n.ID = allocs[i].NodeID - allocs[i].DesiredTransition.Migrate = pointer.Of(true) + allocs[i].DesiredTransition.Migrate = new(true) tainted[n.ID] = n } @@ -2949,7 +2948,7 @@ func TestReconciler_RescheduleNow_Service_WithCanaries(t *testing.T) { alloc.DeploymentID = d.ID alloc.DeploymentStatus = &structs.AllocDeploymentStatus{ Canary: true, - Healthy: pointer.Of(false), + Healthy: new(false), } s.PlacedCanaries = append(s.PlacedCanaries, alloc.ID) allocs = append(allocs, alloc) @@ -3048,7 +3047,7 @@ func TestReconciler_RescheduleNow_Service_Canaries(t *testing.T) { alloc.DeploymentID = d.ID alloc.DeploymentStatus = &structs.AllocDeploymentStatus{ Canary: true, - Healthy: pointer.Of(false), + Healthy: new(false), } s.PlacedCanaries = append(s.PlacedCanaries, alloc.ID) allocs = append(allocs, alloc) @@ -3056,7 +3055,7 @@ func TestReconciler_RescheduleNow_Service_Canaries(t *testing.T) { // Mark the canaries as failed allocs[5].ClientStatus = structs.AllocClientStatusFailed - allocs[5].DesiredTransition.Reschedule = pointer.Of(true) + allocs[5].DesiredTransition.Reschedule = new(true) // Mark one of them as already rescheduled once allocs[5].RescheduleTracker = &structs.RescheduleTracker{Events: []*structs.RescheduleEvent{ @@ -3070,7 +3069,7 @@ func TestReconciler_RescheduleNow_Service_Canaries(t *testing.T) { StartedAt: now.Add(-1 * time.Hour), FinishedAt: now.Add(-10 * time.Second)}} allocs[6].ClientStatus = structs.AllocClientStatusFailed - allocs[6].DesiredTransition.Reschedule = pointer.Of(true) + allocs[6].DesiredTransition.Reschedule = new(true) // Create 4 unhealthy canary allocations that have already been replaced for i := 0; i < 4; i++ { @@ -3083,7 +3082,7 @@ func TestReconciler_RescheduleNow_Service_Canaries(t *testing.T) { alloc.DeploymentID = d.ID alloc.DeploymentStatus = &structs.AllocDeploymentStatus{ Canary: true, - Healthy: pointer.Of(false), + Healthy: new(false), } s.PlacedCanaries = append(s.PlacedCanaries, alloc.ID) allocs = append(allocs, alloc) @@ -3185,7 +3184,7 @@ func TestReconciler_RescheduleNow_Service_Canaries_Limit(t *testing.T) { alloc.DeploymentID = d.ID alloc.DeploymentStatus = &structs.AllocDeploymentStatus{ Canary: true, - Healthy: pointer.Of(false), + Healthy: new(false), } s.PlacedCanaries = append(s.PlacedCanaries, alloc.ID) allocs = append(allocs, alloc) @@ -3193,7 +3192,7 @@ func TestReconciler_RescheduleNow_Service_Canaries_Limit(t *testing.T) { // Mark the canaries as failed allocs[5].ClientStatus = structs.AllocClientStatusFailed - allocs[5].DesiredTransition.Reschedule = pointer.Of(true) + allocs[5].DesiredTransition.Reschedule = new(true) // Mark one of them as already rescheduled once allocs[5].RescheduleTracker = &structs.RescheduleTracker{Events: []*structs.RescheduleEvent{ @@ -3207,7 +3206,7 @@ func TestReconciler_RescheduleNow_Service_Canaries_Limit(t *testing.T) { StartedAt: now.Add(-1 * time.Hour), FinishedAt: now.Add(-10 * time.Second)}} allocs[6].ClientStatus = structs.AllocClientStatusFailed - allocs[6].DesiredTransition.Reschedule = pointer.Of(true) + allocs[6].DesiredTransition.Reschedule = new(true) // Create 4 unhealthy canary allocations that have already been replaced for i := 0; i < 4; i++ { @@ -3220,7 +3219,7 @@ func TestReconciler_RescheduleNow_Service_Canaries_Limit(t *testing.T) { alloc.DeploymentID = d.ID alloc.DeploymentStatus = &structs.AllocDeploymentStatus{ Canary: true, - Healthy: pointer.Of(false), + Healthy: new(false), } s.PlacedCanaries = append(s.PlacedCanaries, alloc.ID) allocs = append(allocs, alloc) @@ -4067,8 +4066,8 @@ func TestReconciler_DrainNode_Canary(t *testing.T) { tainted := make(map[string]*structs.Node, 1) // This is what drainer sets for draining allocations - allocs[10].DesiredTransition.Migrate = pointer.Of(true) - allocs[11].DesiredTransition.Migrate = pointer.Of(true) + allocs[10].DesiredTransition.Migrate = new(true) + allocs[11].DesiredTransition.Migrate = new(true) tainted[n.ID] = n mockUpdateFn := allocUpdateFnMock(handled, allocUpdateFnDestructive) @@ -4731,7 +4730,7 @@ func TestReconciler_PromoteCanaries_Unblock(t *testing.T) { s.PlacedCanaries = append(s.PlacedCanaries, canary.ID) canary.DeploymentID = d.ID canary.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), } allocs = append(allocs, canary) handled[canary.ID] = allocUpdateFnIgnore @@ -4818,7 +4817,7 @@ func TestReconciler_PromoteCanaries_CanariesEqualCount(t *testing.T) { s.PlacedCanaries = append(s.PlacedCanaries, canary.ID) canary.DeploymentID = d.ID canary.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), } allocs = append(allocs, canary) handled[canary.ID] = allocUpdateFnIgnore @@ -4920,20 +4919,20 @@ func TestReconciler_DeploymentLimit_HealthAccounting(t *testing.T) { // Create the new allocs handled := make(map[string]AllocUpdateType) for i := 0; i < 4; i++ { - new := mock.Alloc() - new.Job = job - new.JobID = job.ID - new.NodeID = uuid.Generate() - new.Name = structs.AllocName(job.ID, job.TaskGroups[0].Name, uint(i)) - new.TaskGroup = job.TaskGroups[0].Name - new.DeploymentID = d.ID + newAlloc := mock.Alloc() + newAlloc.Job = job + newAlloc.JobID = job.ID + newAlloc.NodeID = uuid.Generate() + newAlloc.Name = structs.AllocName(job.ID, job.TaskGroups[0].Name, uint(i)) + newAlloc.TaskGroup = job.TaskGroups[0].Name + newAlloc.DeploymentID = d.ID if i < c.healthy { - new.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + newAlloc.DeploymentStatus = &structs.AllocDeploymentStatus{ + Healthy: new(true), } } - allocs = append(allocs, new) - handled[new.ID] = allocUpdateFnIgnore + allocs = append(allocs, newAlloc) + handled[newAlloc.ID] = allocUpdateFnIgnore } mockUpdateFn := allocUpdateFnMock(handled, allocUpdateFnDestructive) @@ -5002,18 +5001,18 @@ func TestReconciler_TaintedNode_RollingUpgrade(t *testing.T) { // Create the healthy replacements handled := make(map[string]AllocUpdateType) for i := 0; i < 8; i++ { - new := mock.Alloc() - new.Job = job - new.JobID = job.ID - new.NodeID = uuid.Generate() - new.Name = structs.AllocName(job.ID, job.TaskGroups[0].Name, uint(i)) - new.TaskGroup = job.TaskGroups[0].Name - new.DeploymentID = d.ID - new.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + newAlloc := mock.Alloc() + newAlloc.Job = job + newAlloc.JobID = job.ID + newAlloc.NodeID = uuid.Generate() + newAlloc.Name = structs.AllocName(job.ID, job.TaskGroups[0].Name, uint(i)) + newAlloc.TaskGroup = job.TaskGroups[0].Name + newAlloc.DeploymentID = d.ID + newAlloc.DeploymentStatus = &structs.AllocDeploymentStatus{ + Healthy: new(true), } - allocs = append(allocs, new) - handled[new.ID] = allocUpdateFnIgnore + allocs = append(allocs, newAlloc) + handled[newAlloc.ID] = allocUpdateFnIgnore } // Build a map of tainted nodes @@ -5025,7 +5024,7 @@ func TestReconciler_TaintedNode_RollingUpgrade(t *testing.T) { n.Status = structs.NodeStatusDown } else { n.DrainStrategy = mock.DrainNode().DrainStrategy - allocs[2+i].DesiredTransition.Migrate = pointer.Of(true) + allocs[2+i].DesiredTransition.Migrate = new(true) } tainted[n.ID] = n } @@ -5100,18 +5099,18 @@ func TestReconciler_FailedDeployment_TaintedNodes(t *testing.T) { // Create the healthy replacements handled := make(map[string]AllocUpdateType) for i := 0; i < 4; i++ { - new := mock.Alloc() - new.Job = job - new.JobID = job.ID - new.NodeID = uuid.Generate() - new.Name = structs.AllocName(job.ID, job.TaskGroups[0].Name, uint(i)) - new.TaskGroup = job.TaskGroups[0].Name - new.DeploymentID = d.ID - new.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + newAlloc := mock.Alloc() + newAlloc.Job = job + newAlloc.JobID = job.ID + newAlloc.NodeID = uuid.Generate() + newAlloc.Name = structs.AllocName(job.ID, job.TaskGroups[0].Name, uint(i)) + newAlloc.TaskGroup = job.TaskGroups[0].Name + newAlloc.DeploymentID = d.ID + newAlloc.DeploymentStatus = &structs.AllocDeploymentStatus{ + Healthy: new(true), } - allocs = append(allocs, new) - handled[new.ID] = allocUpdateFnIgnore + allocs = append(allocs, newAlloc) + handled[newAlloc.ID] = allocUpdateFnIgnore } // Build a map of tainted nodes @@ -5123,7 +5122,7 @@ func TestReconciler_FailedDeployment_TaintedNodes(t *testing.T) { n.Status = structs.NodeStatusDown } else { n.DrainStrategy = mock.DrainNode().DrainStrategy - allocs[6+i].DesiredTransition.Migrate = pointer.Of(true) + allocs[6+i].DesiredTransition.Migrate = new(true) } tainted[n.ID] = n } @@ -5193,7 +5192,7 @@ func TestReconciler_CompleteDeployment(t *testing.T) { alloc.TaskGroup = job.TaskGroups[0].Name alloc.DeploymentID = d.ID alloc.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), } allocs = append(allocs, alloc) } @@ -5256,11 +5255,11 @@ func TestReconciler_MarkDeploymentComplete_FailedAllocations(t *testing.T) { alloc.DeploymentStatus = &structs.AllocDeploymentStatus{} if i < 10 { alloc.ClientStatus = structs.AllocClientStatusRunning - alloc.DeploymentStatus.Healthy = pointer.Of(true) + alloc.DeploymentStatus.Healthy = new(true) } else { alloc.DesiredStatus = structs.AllocDesiredStatusStop alloc.ClientStatus = structs.AllocClientStatusFailed - alloc.DeploymentStatus.Healthy = pointer.Of(false) + alloc.DeploymentStatus.Healthy = new(false) } allocs = append(allocs, alloc) @@ -5344,22 +5343,22 @@ func TestReconciler_FailedDeployment_CancelCanaries(t *testing.T) { // Create the healthy replacements for i := 0; i < replacements; i++ { - new := mock.Alloc() - new.Job = job - new.JobID = job.ID - new.NodeID = uuid.Generate() - new.Name = structs.AllocName(job.ID, job.TaskGroups[group].Name, uint(i)) - new.TaskGroup = job.TaskGroups[group].Name - new.DeploymentID = d.ID - new.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + newAlloc := mock.Alloc() + newAlloc.Job = job + newAlloc.JobID = job.ID + newAlloc.NodeID = uuid.Generate() + newAlloc.Name = structs.AllocName(job.ID, job.TaskGroups[group].Name, uint(i)) + newAlloc.TaskGroup = job.TaskGroups[group].Name + newAlloc.DeploymentID = d.ID + newAlloc.DeploymentStatus = &structs.AllocDeploymentStatus{ + Healthy: new(true), } - allocs = append(allocs, new) - handled[new.ID] = allocUpdateFnIgnore + allocs = append(allocs, newAlloc) + handled[newAlloc.ID] = allocUpdateFnIgnore // Add the alloc to the canary list if i < 2 { - state.PlacedCanaries = append(state.PlacedCanaries, new.ID) + state.PlacedCanaries = append(state.PlacedCanaries, newAlloc.ID) } } for i := replacements; i < 10; i++ { @@ -5439,17 +5438,17 @@ func TestReconciler_FailedDeployment_NewJob(t *testing.T) { // Create the healthy replacements for i := 0; i < 4; i++ { - new := mock.Alloc() - new.Job = job - new.JobID = job.ID - new.NodeID = uuid.Generate() - new.Name = structs.AllocName(job.ID, job.TaskGroups[0].Name, uint(i)) - new.TaskGroup = job.TaskGroups[0].Name - new.DeploymentID = d.ID - new.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + newAlloc := mock.Alloc() + newAlloc.Job = job + newAlloc.JobID = job.ID + newAlloc.NodeID = uuid.Generate() + newAlloc.Name = structs.AllocName(job.ID, job.TaskGroups[0].Name, uint(i)) + newAlloc.TaskGroup = job.TaskGroups[0].Name + newAlloc.DeploymentID = d.ID + newAlloc.DeploymentStatus = &structs.AllocDeploymentStatus{ + Healthy: new(true), } - allocs = append(allocs, new) + allocs = append(allocs, newAlloc) } // Up the job version @@ -5519,7 +5518,7 @@ func TestReconciler_MarkDeploymentComplete(t *testing.T) { alloc.TaskGroup = job.TaskGroups[0].Name alloc.DeploymentID = d.ID alloc.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), } allocs = append(allocs, alloc) } @@ -5862,7 +5861,7 @@ func TestReconciler_DeploymentWithFailedAllocs_DontReschedule(t *testing.T) { // Mark half of them as reschedulable for i := 0; i < 5; i++ { - allocs[i].DesiredTransition.Reschedule = pointer.Of(true) + allocs[i].DesiredTransition.Reschedule = new(true) } reconciler := NewAllocReconciler( @@ -5933,34 +5932,34 @@ func TestReconciler_FailedDeployment_AutoRevert_CancelCanaries(t *testing.T) { // Create the original var allocs []*structs.Allocation for i := 0; i < 3; i++ { - new := mock.Alloc() - new.Job = jobv2 - new.JobID = job.ID - new.NodeID = uuid.Generate() - new.Name = structs.AllocName(job.ID, job.TaskGroups[0].Name, uint(i)) - new.TaskGroup = job.TaskGroups[0].Name - new.DeploymentID = d.ID - new.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + newAlloc := mock.Alloc() + newAlloc.Job = jobv2 + newAlloc.JobID = job.ID + newAlloc.NodeID = uuid.Generate() + newAlloc.Name = structs.AllocName(job.ID, job.TaskGroups[0].Name, uint(i)) + newAlloc.TaskGroup = job.TaskGroups[0].Name + newAlloc.DeploymentID = d.ID + newAlloc.DeploymentStatus = &structs.AllocDeploymentStatus{ + Healthy: new(true), } - new.ClientStatus = structs.AllocClientStatusRunning - allocs = append(allocs, new) + newAlloc.ClientStatus = structs.AllocClientStatusRunning + allocs = append(allocs, newAlloc) } for i := 0; i < 3; i++ { - new := mock.Alloc() - new.Job = jobv1 - new.JobID = jobv1.ID - new.NodeID = uuid.Generate() - new.Name = structs.AllocName(jobv1.ID, jobv1.TaskGroups[0].Name, uint(i)) - new.TaskGroup = job.TaskGroups[0].Name - new.DeploymentID = uuid.Generate() - new.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(false), + newAlloc := mock.Alloc() + newAlloc.Job = jobv1 + newAlloc.JobID = jobv1.ID + newAlloc.NodeID = uuid.Generate() + newAlloc.Name = structs.AllocName(jobv1.ID, jobv1.TaskGroups[0].Name, uint(i)) + newAlloc.TaskGroup = job.TaskGroups[0].Name + newAlloc.DeploymentID = uuid.Generate() + newAlloc.DeploymentStatus = &structs.AllocDeploymentStatus{ + Healthy: new(false), } - new.DesiredStatus = structs.AllocDesiredStatusStop - new.ClientStatus = structs.AllocClientStatusFailed - allocs = append(allocs, new) + newAlloc.DesiredStatus = structs.AllocDesiredStatusStop + newAlloc.ClientStatus = structs.AllocClientStatusFailed + allocs = append(allocs, newAlloc) } reconciler := NewAllocReconciler( @@ -6111,7 +6110,7 @@ func TestReconciler_ForceReschedule_Service(t *testing.T) { }} // Mark DesiredTransition ForceReschedule - allocs[0].DesiredTransition = structs.DesiredTransition{ForceReschedule: pointer.Of(true)} + allocs[0].DesiredTransition = structs.DesiredTransition{ForceReschedule: new(true)} reconciler := NewAllocReconciler( testlog.HCLogger(t), allocUpdateFnIgnore, ReconcilerState{ @@ -6586,7 +6585,7 @@ func TestReconciler_Disconnected_Client(t *testing.T) { alloc.NextAllocation = replacement.ID if tc.taintReplacement { - replacement.DesiredTransition.Migrate = pointer.Of(true) + replacement.DesiredTransition.Migrate = new(true) } if tc.disconnectReplacement { replacement.AllocStates = tc.disconnectedAllocStates @@ -7171,7 +7170,7 @@ func TestReconciler_Client_Disconnect_Canaries(t *testing.T) { Canary: true, } if alloc.ClientStatus == structs.AllocClientStatusRunning { - alloc.DeploymentStatus.Healthy = pointer.Of(true) + alloc.DeploymentStatus.Healthy = new(true) } if alloc.ClientStatus == structs.AllocClientStatusUnknown { diff --git a/scheduler/reconciler/reconcile_node_prop_test.go b/scheduler/reconciler/reconcile_node_prop_test.go index 2a23268e569..014d08f8562 100644 --- a/scheduler/reconciler/reconcile_node_prop_test.go +++ b/scheduler/reconciler/reconcile_node_prop_test.go @@ -7,7 +7,6 @@ import ( "testing" "time" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/nomad/structs" "github.com/shoenig/test/must" "pgregory.net/rapid" @@ -167,7 +166,7 @@ func genNodeReconciler(jobType string, idg *idGenerator) *rapid.Generator[*nodeR if structs.ShouldDrainNode(node.Status) || node.DrainStrategy != nil { taintedNodes[node.ID] = node alloc.DesiredTransition = structs.DesiredTransition{ - Migrate: pointer.Of(true), + Migrate: new(true), } } if node.Status == structs.NodeStatusDisconnected { diff --git a/scheduler/reconciler/reconcile_node_test.go b/scheduler/reconciler/reconcile_node_test.go index afde20f828a..ccaf6026d0d 100644 --- a/scheduler/reconciler/reconcile_node_test.go +++ b/scheduler/reconciler/reconcile_node_test.go @@ -12,7 +12,6 @@ import ( "github.com/shoenig/test/must" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" @@ -331,7 +330,7 @@ func TestDiffSystemAllocsForNode_DrainingNode(t *testing.T) { Name: "my-job.web[0]", Job: oldJob, DesiredTransition: structs.DesiredTransition{ - Migrate: pointer.Of(true), + Migrate: new(true), }, }, { // allocs not marked for drain should be ignored @@ -584,7 +583,7 @@ func TestDiffSystemAllocs(t *testing.T) { Name: "my-job.web[0]", Job: oldJob, DesiredTransition: structs.DesiredTransition{ - Migrate: pointer.Of(true), + Migrate: new(true), }, }, // Mark as lost on a dead node diff --git a/scheduler/scheduler_sysbatch_test.go b/scheduler/scheduler_sysbatch_test.go index beb2e38b9d5..45731dbbf80 100644 --- a/scheduler/scheduler_sysbatch_test.go +++ b/scheduler/scheduler_sysbatch_test.go @@ -11,7 +11,6 @@ import ( "github.com/hashicorp/go-memdb" "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/helper" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" @@ -564,7 +563,7 @@ func TestSysBatch_NodeDown(t *testing.T) { alloc.JobID = job.ID alloc.NodeID = node.ID alloc.Name = "my-sysbatch.pinger[0]" - alloc.DesiredTransition.Migrate = pointer.Of(true) + alloc.DesiredTransition.Migrate = new(true) must.NoError(t, h.State.UpsertAllocs(structs.MsgTypeTestSetup, h.NextIndex(), []*structs.Allocation{alloc})) // Create a mock evaluation to deal with drain @@ -678,7 +677,7 @@ func TestSysBatch_NodeDrain(t *testing.T) { alloc.JobID = job.ID alloc.NodeID = node.ID alloc.Name = "my-sysbatch.pinger[0]" - alloc.DesiredTransition.Migrate = pointer.Of(true) + alloc.DesiredTransition.Migrate = new(true) must.NoError(t, h.State.UpsertAllocs(structs.MsgTypeTestSetup, h.NextIndex(), []*structs.Allocation{alloc})) // Create a mock evaluation to deal with drain @@ -1443,7 +1442,7 @@ func TestSysBatch_PlanWithDrainedNode(t *testing.T) { alloc.JobID = job.ID alloc.NodeID = node.ID alloc.Name = "my-sysbatch.pinger[0]" - alloc.DesiredTransition.Migrate = pointer.Of(true) + alloc.DesiredTransition.Migrate = new(true) alloc.TaskGroup = "pinger" alloc2 := mock.SysBatchAlloc() diff --git a/scheduler/scheduler_system_test.go b/scheduler/scheduler_system_test.go index 494dc1c6cb0..267e9edc4d5 100644 --- a/scheduler/scheduler_system_test.go +++ b/scheduler/scheduler_system_test.go @@ -14,7 +14,6 @@ import ( memdb "github.com/hashicorp/go-memdb" "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/helper" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" @@ -1000,7 +999,7 @@ func TestSystemSched_NodeDown(t *testing.T) { alloc.JobID = job.ID alloc.NodeID = node.ID alloc.Name = "my-job.web[0]" - alloc.DesiredTransition.Migrate = pointer.Of(true) + alloc.DesiredTransition.Migrate = new(true) must.NoError(t, h.State.UpsertAllocs(structs.MsgTypeTestSetup, h.NextIndex(), []*structs.Allocation{alloc})) // Create a mock evaluation to deal with drain @@ -1114,7 +1113,7 @@ func TestSystemSched_NodeDrain(t *testing.T) { alloc.JobID = job.ID alloc.NodeID = node.ID alloc.Name = "my-job.web[0]" - alloc.DesiredTransition.Migrate = pointer.Of(true) + alloc.DesiredTransition.Migrate = new(true) must.NoError(t, h.State.UpsertAllocs(structs.MsgTypeTestSetup, h.NextIndex(), []*structs.Allocation{alloc})) // Create a mock evaluation to deal with drain @@ -1911,7 +1910,7 @@ func TestSystemSched_PlanWithDrainedNode(t *testing.T) { alloc.JobID = job.ID alloc.NodeID = node.ID alloc.Name = "my-job.web[0]" - alloc.DesiredTransition.Migrate = pointer.Of(true) + alloc.DesiredTransition.Migrate = new(true) alloc.TaskGroup = "web" alloc2 := mock.Alloc() @@ -3063,7 +3062,7 @@ func TestSystemSched_NodeDisconnected(t *testing.T) { alloc.TaskGroup = job.TaskGroups[0].Name alloc.ClientStatus = tc.clientStatus alloc.DesiredStatus = tc.desiredStatus - alloc.DesiredTransition.Migrate = pointer.Of(tc.migrate) + alloc.DesiredTransition.Migrate = new(tc.migrate) alloc.AllocStates = tc.allocState alloc.TaskStates = tc.taskState @@ -4049,7 +4048,7 @@ func TestSystemSched_UpdateBlock(t *testing.T) { for _, canaryNodeIdx := range tc.existingCanary[tg] { if nodeIdx == canaryNodeIdx { alloc.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(true), + Healthy: new(true), Timestamp: time.Time{}, Canary: true, ModifyIndex: 0, @@ -4078,7 +4077,7 @@ func TestSystemSched_UpdateBlock(t *testing.T) { for _, canaryNodeIdx := range tc.existingCanary[tg] { if nodeIdx == canaryNodeIdx { alloc.DeploymentStatus = &structs.AllocDeploymentStatus{ - Healthy: pointer.Of(false), + Healthy: new(false), Timestamp: time.Time{}, Canary: true, ModifyIndex: 0, diff --git a/scheduler/scheduler_test.go b/scheduler/scheduler_test.go index 0e5a126d347..d2d7d961678 100644 --- a/scheduler/scheduler_test.go +++ b/scheduler/scheduler_test.go @@ -9,7 +9,6 @@ import ( "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/helper/iterator" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" "github.com/hashicorp/nomad/nomad/structs" @@ -27,12 +26,12 @@ func TestScheduler_JobRegister_MemoryMaxHonored(t *testing.T) { poolWithMemOversub := mock.NodePool() poolWithMemOversub.SchedulerConfiguration = &structs.NodePoolSchedulerConfiguration{ - MemoryOversubscriptionEnabled: pointer.Of(true), + MemoryOversubscriptionEnabled: new(true), } poolNoMemOversub := mock.NodePool() poolNoMemOversub.SchedulerConfiguration = &structs.NodePoolSchedulerConfiguration{ - MemoryOversubscriptionEnabled: pointer.Of(false), + MemoryOversubscriptionEnabled: new(false), } cases := []struct { diff --git a/scheduler/util_test.go b/scheduler/util_test.go index 1fd73fcdfc0..55d0f27a730 100644 --- a/scheduler/util_test.go +++ b/scheduler/util_test.go @@ -8,7 +8,6 @@ import ( "time" "github.com/hashicorp/nomad/ci" - "github.com/hashicorp/nomad/helper/pointer" "github.com/hashicorp/nomad/helper/testlog" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad/mock" @@ -341,8 +340,8 @@ func TestTasksUpdated(t *testing.T) { j22.TaskGroups[0].Tasks[0].Templates = []*structs.Template{ { Wait: &structs.WaitConfig{ - Min: pointer.Of(5 * time.Second), - Max: pointer.Of(5 * time.Second), + Min: new(5 * time.Second), + Max: new(5 * time.Second), }, }, } @@ -350,14 +349,14 @@ func TestTasksUpdated(t *testing.T) { j23.TaskGroups[0].Tasks[0].Templates = []*structs.Template{ { Wait: &structs.WaitConfig{ - Min: pointer.Of(5 * time.Second), - Max: pointer.Of(5 * time.Second), + Min: new(5 * time.Second), + Max: new(5 * time.Second), }, }, } must.False(t, tasksUpdated(j22, j23, name).modified) // Compare changed Template wait configs - j23.TaskGroups[0].Tasks[0].Templates[0].Wait.Max = pointer.Of(10 * time.Second) + j23.TaskGroups[0].Tasks[0].Templates[0].Wait.Max = new(10 * time.Second) must.True(t, tasksUpdated(j22, j23, name).modified) // Add a volume diff --git a/testutil/server.go b/testutil/server.go index 44d1d348ef7..782d3a13cf6 100644 --- a/testutil/server.go +++ b/testutil/server.go @@ -28,7 +28,6 @@ import ( cleanhttp "github.com/hashicorp/go-cleanhttp" "github.com/hashicorp/nomad/ci" "github.com/hashicorp/nomad/helper/discover" - "github.com/hashicorp/nomad/helper/pointer" "github.com/shoenig/test/must" ) @@ -143,7 +142,7 @@ func defaultServerConfig() *TestServerConfig { }, Vaults: []*VaultConfig{{ Enabled: false, - AllowUnauthenticated: pointer.Of(true), + AllowUnauthenticated: new(true), }}, ACL: &ACLConfig{ Enabled: false,