ronantakizawa/codereview-bench huggingface dataset:
Repository: hashicorp/nomad
File: drivers/rawexec/driver_test.go (Go)

Code before:
}

func TestRawExecDriver_Env(t *testing.T) {
	ci.Parallel(t)

	require := require.New(t)

	d := newEnabledRawExecDriver(t)
	allocID := uuid.Generate()
	taskName := "sleep"

	testCases := []struct {
		name         string
		driver       *Driver
		driverConfig *Config
		taskConfig   *TaskConfig
		varsExpected bool
		checkVars    []string
	}{
		{name: "no denied vars",
			driver:       d,
			driverConfig: nil,
			taskConfig: &TaskConfig{
				Command: testtask.Path(),
			},
			checkVars:    []string{"NOMAD_TOKEN", "GITHUB_TOKEN", "AWS_SECRET_KEY", "NOMAD_ADDR", "TEST_TOKEN", "TEST_AWS_VAR", "VAR_TEST_AWS", "PORT"},
			varsExpected: true,
		},
		{name: "both levels, named vars",
			driver: d,
			driverConfig: &Config{
				Enabled:       true,
				DeniedEnvvars: []string{"NOMAD_ADDR"},
			},
			taskConfig: &TaskConfig{
				Command:       testtask.Path(),
				DeniedEnvvars: []string{"NOMAD_TOKEN"},
			},
			checkVars:    []string{"NOMAD_TOKEN", "NOMAD_ADDR"},
			varsExpected: false,
		}, {name: "driver level, glob suffix vars",
			driver: d,
			driverConfig: &Config{
				Enabled:       true,
				DeniedEnvvars: []string{"NOMAD_*"},
			},
			taskConfig: &TaskConfig{
				Command: testtask.Path(),
			},
			varsExpected: false,
			checkVars:    []string{"NOMAD_TOKEN", "NOMAD_ADDR"},

Review comment (suggestion):
I suspect the way that we're using `testtask` here may be the source of why we're getting short reads from stdout. Without any `Args` in the `TaskConfig`, this is going to exit immediately. So when we try to `ExecTask` we're racing with the process exit. In other tests, it looks like we've had `Args: []string{"sleep", "1"}` to ensure the task is still running for the whole test case.

Code after:

	d := newEnabledRawExecDriver(t)
	allocID := uuid.Generate()
	taskName := "sleep"

	task :=
		&drivers.TaskConfig{
			AllocID:   allocID,
			ID:        uuid.Generate(),
			Name:      taskName,
			Env:       genEnv(),
			Resources: testResources(allocID, taskName),
		}
	testCases := []struct {
		name         string
		driver       *Driver
		driverConfig *Config
		taskConfig   *TaskConfig
		varsExpected bool
		deniedVars   []string
	}{
		{name: "no denied vars",
			driver:       d,
			driverConfig: nil,
			taskConfig: &TaskConfig{
				Command: testtask.Path(),
				Args:    []string{"sleep", "10ms"},
			},
			deniedVars:   []string{},
			varsExpected: true,
		},
		{name: "both levels, named vars",
			driver: d,
			driverConfig: &Config{
				Enabled:       true,
				DeniedEnvvars: []string{"NOMAD_ADDR"},
			},
			taskConfig: &TaskConfig{
				Command:       testtask.Path(),
				Args:          []string{"sleep", "10ms"},
				DeniedEnvvars: []string{"NOMAD_TOKEN"},
			},
			deniedVars: []string{
				"NOMAD_ADDR=klm",
				"NOMAD_TOKEN=abcd",
			},
			varsExpected: false,
		}, {name: "driver level, glob suffix vars",
			driver: d,
			driverConfig: &Config{
				Enabled:       true,
Repository: hashicorp/nomad
File: nomad/acl_endpoint.go (Go)

Code before:
				if err != nil {
					return err
				}
				if out != nil {
					reply.Tokens[out.AccessorID] = out
				}
			}

			// Use the last index that affected the token table
			index, err := state.Index("acl_token")
			if err != nil {
				return err
			}
			reply.Index = index
			return nil
		}}
	return a.srv.blockingRPC(&opts)
}

func (a *ACL) UpsertOneTimeToken(args *structs.OneTimeTokenUpsertRequest, reply *structs.OneTimeTokenUpsertResponse) error {
	if !a.srv.config.ACLEnabled {
		return aclDisabled
	}
	if done, err := a.srv.forward(
		"ACL.UpsertOneTimeToken", args, args, reply); done {
		return err
	}
	defer metrics.MeasureSince(
		[]string{"nomad", "acl", "upsert_one_time_token"}, time.Now())

	if !ServersMeetMinimumVersion(a.srv.Members(), a.srv.Region(), minOneTimeAuthenticationTokenVersion, false) {
		return fmt.Errorf("All servers should be running version %v or later to use one-time authentication tokens", minOneTimeAuthenticationTokenVersion)
	}

	// Snapshot the state
	state, err := a.srv.State().Snapshot()
	if err != nil {
		return err
	}

	// Look up the token; there's no capability check as you can only
	// request a OTT for your own ACL token
	aclToken, err := state.ACLTokenBySecretID(nil, args.AuthToken)
	if err != nil {
		return err
	}
	if aclToken == nil {
		return structs.ErrPermissionDenied
	}

	ott := &structs.OneTimeToken{

Review comment (suggestion):
Even though this has been deprecated a long time, I don't think we can safely remove it in this PR. During upgrades, you could get an RPC being forwarded from an older version of Nomad.

Code after:
				if err != nil {
					return err
				}
				if out != nil {
					reply.Tokens[out.AccessorID] = out
				}
			}

			// Use the last index that affected the token table
			index, err := state.Index("acl_token")
			if err != nil {
				return err
			}
			reply.Index = index
			return nil
		}}
	return a.srv.blockingRPC(&opts)
}

// ResolveToken is used to lookup a specific token by a secret ID.
//
// Deprecated: This RPC has been deprecated since Nomad 1.5 and is only kept for
// compatibility purposes.
func (a *ACL) ResolveToken(args *structs.ResolveACLTokenRequest, reply *structs.ResolveACLTokenResponse) error {
	if !a.srv.config.ACLEnabled {
		return aclDisabled
	}
	if done, err := a.srv.forward("ACL.ResolveToken", args, args, reply); done {
		return err
	}
	a.srv.MeasureRPCRate("acl", structs.RateMetricRead, args)
	defer metrics.MeasureSince([]string{"nomad", "acl", "resolve_token"}, time.Now())

	// Setup the query meta
	a.srv.setQueryMeta(&reply.QueryMeta)

	// Snapshot the state
	state, err := a.srv.State().Snapshot()
	if err != nil {
		return err
	}

	// Look for the token
	out, err := state.ACLTokenBySecretID(nil, args.SecretID)
	if err != nil {
		return err
	}

	// Setup the output
	reply.Token = out
	if out != nil {
Repository: hashicorp/nomad
File: command/agent/acl_endpoint.go (Go)

Code before:
		return nil, err
	}

	setMeta(resp, &out.QueryMeta)
	if out.Token == nil {
		return nil, CodedError(404, "ACL token not found")
	}
	return out.Token, nil
}

func (s *HTTPServer) aclTokenSelf(resp http.ResponseWriter, req *http.Request) (any, error) {
	if req.Method != http.MethodGet {
		return nil, CodedError(405, ErrInvalidMethod)
	}
	args := structs.GenericRequest{}
	if s.parse(resp, req, &args.Region, &args.QueryOptions) {
		return nil, nil
	}

	var out structs.ACLWhoAmIResponse
	if err := s.agent.RPC("ACL.WhoAmI", &args, &out); err != nil {
		return nil, err
	}

	setMeta(resp, &out.QueryMeta)
	if out.Identity.ACLToken == nil {
		return nil, CodedError(404, "ACL token not found")
	}
	return out.Identity.ACLToken, nil
}

func (s *HTTPServer) aclTokenUpdate(resp http.ResponseWriter, req *http.Request,
	tokenAccessor string) (interface{}, error) {
	// Parse the token
	var token structs.ACLToken
	if err := decodeBody(req, &token); err != nil {
		return nil, CodedError(http.StatusBadRequest, err.Error())
	}

	// Ensure the token accessor matches
	if tokenAccessor != "" && (token.AccessorID != tokenAccessor) {
		return nil, CodedError(400, "ACL token accessor does not match request path")
	}

	// Format the request
	args := structs.ACLTokenUpsertRequest{
		Tokens: []*structs.ACLToken{&token},
	}
	s.parseWriteRequest(req, &args.WriteRequest)

	var out structs.ACLTokenUpsertResponse

Review comment (suggestion):
I don't think you can actually hit this case, but just for robustness:

```suggestion
	if out.Identity == nil || out.Identity.ACLToken == nil {
```

Code after:
		return nil, err
	}

	setMeta(resp, &out.QueryMeta)
	if out.Token == nil {
		return nil, CodedError(404, "ACL token not found")
	}
	return out.Token, nil
}

func (s *HTTPServer) aclTokenSelf(resp http.ResponseWriter, req *http.Request) (any, error) {
	if req.Method != http.MethodGet {
		return nil, CodedError(405, ErrInvalidMethod)
	}
	args := structs.GenericRequest{}
	if s.parse(resp, req, &args.Region, &args.QueryOptions) {
		return nil, nil
	}

	var out structs.ACLWhoAmIResponse
	if err := s.agent.RPC("ACL.WhoAmI", &args, &out); err != nil {
		return nil, err
	}

	setMeta(resp, &out.QueryMeta)
	if out.Identity == nil || out.Identity.ACLToken == nil {
		return nil, CodedError(404, "ACL token not found")
	}
	return out.Identity.ACLToken, nil
}

func (s *HTTPServer) aclTokenUpdate(resp http.ResponseWriter, req *http.Request,
	tokenAccessor string) (interface{}, error) {
	// Parse the token
	var token structs.ACLToken
	if err := decodeBody(req, &token); err != nil {
		return nil, CodedError(http.StatusBadRequest, err.Error())
	}

	// Ensure the token accessor matches
	if tokenAccessor != "" && (token.AccessorID != tokenAccessor) {
		return nil, CodedError(400, "ACL token accessor does not match request path")
	}

	// Format the request
	args := structs.ACLTokenUpsertRequest{
		Tokens: []*structs.ACLToken{&token},
	}
	s.parseWriteRequest(req, &args.WriteRequest)

	var out structs.ACLTokenUpsertResponse
Repository: hashicorp/nomad
File: lib/auth/oidc/client_assertion.go (Go)

Code before:
	case structs.OIDCClientAssertionHeaderX5t:
		hasher = sha1.New()
	case structs.OIDCClientAssertionHeaderX5tS256:
		hasher = sha256.New()
	default:
		// this should be validated long before here, at upsert
		return "", fmt.Errorf(`%w; must be one of: "x5t", "x5t#S256"`, structs.ErrInvalidKeyIDHeader)
	}
	hasher.Write(cert.Raw)
	hashed := hasher.Sum(nil)
	return base64.RawURLEncoding.EncodeToString(hashed), nil
}

var (
	// for user convenience, they may exclude key/cert pem header/footer
	beginPrivateKey  = []byte("-----BEGIN PRIVATE KEY-----")
	endPrivateKey    = []byte("-----END PRIVATE KEY-----")
	beginCertificate = []byte("-----BEGIN CERTIFICATE-----")
	endCertificate   = []byte("-----END CERTIFICATE-----")
)

// wrapBeginEnd wraps the provided bts in "{begin}\n{bts}\n{end}".
// if begin and end are already there, it ensures "\n" is between them and bts.
func wrapBeginEnd(bts, begin, end []byte) []byte {
	cp := bytes.Clone(bts)
	cp = bytes.TrimPrefix(cp, begin)
	cp = bytes.TrimSuffix(cp, end)
	cp = bytes.TrimSpace(cp)
	cp = bytes.Join([][]byte{begin, cp, end}, []byte("\n"))
	return cp
}


Review comment (suggestion):
We might want to trim spaces here too, so that we can handle leading/trailing newlines nicely:

```suggestion
	cp = bytes.TrimSpace(cp)
	cp = bytes.TrimPrefix(cp, begin)
```

Code after:
		hasher = sha1.New()
	case structs.OIDCClientAssertionHeaderX5tS256:
		hasher = sha256.New()
	default:
		// this should be validated long before here, at upsert
		return "", fmt.Errorf(`%w; must be one of: "x5t", "x5t#S256"`, structs.ErrInvalidKeyIDHeader)
	}
	hasher.Write(cert.Raw)
	hashed := hasher.Sum(nil)
	return base64.RawURLEncoding.EncodeToString(hashed), nil
}

// newlineHeaders allows flexible copy-paste of a one-line key/cert PEM
// by adding newlines around "----BEGIN.*-----" and
// "-----END.*(KEY|CERTIFICATE)-----"
// it's okay to have extra whitespace, but it's imperative that there be
// at least one newline between the header/footer and the content.
func newlineHeaders(bts []byte) []byte {
	cp := bytes.Clone(bts)
	cp = bytes.TrimSpace(cp)
	cp = bytes.ReplaceAll(cp, []byte("-----BEGIN"), []byte("\n-----BEGIN"))
	cp = bytes.ReplaceAll(cp, []byte("-----END"), []byte("\n-----END"))
	// key may be "PRIVATE KEY" or "RSA PRIVATE KEY", so just look for "KEY"
	cp = bytes.ReplaceAll(cp, []byte("KEY-----"), []byte("KEY-----\n"))
	cp = bytes.ReplaceAll(cp, []byte("CERTIFICATE-----"), []byte("CERTIFICATE-----\n"))
	cp = bytes.TrimSpace(cp)
	return cp
}
Repository: hashicorp/nomad
File: client/servers/manager_test.go (Go)

Code before:

	// Try notifying for a server that is not managed by Manager
	m.NotifyFailedServer(s1)
	must.Zero(t, m.NumServers())
	m.SetServers([]*servers.Server{s1})

	// Test again w/ a server not in the list
	m.NotifyFailedServer(s2)
	must.Eq(t, 1, m.NumServers())

	m.SetServers([]*servers.Server{s1, s2})
	must.Eq(t, 2, m.NumServers())

	// Grab a server
	first := m.FindServer()

	// Find the other server
	second := s1
	if first.Equal(s1) {
		second = s2
	}

	// Fail the other server
	m.NotifyFailedServer(second)
	next := m.FindServer()
	must.True(t, next.Equal(first))

	// Fail the first
	m.NotifyFailedServer(first)
	next = m.FindServer()
	must.True(t, next.Equal(second))

	// Fail the second
	m.NotifyFailedServer(second)
	next = m.FindServer()
	must.True(t, next.Equal(first))
}

func TestServers_NumServers(t *testing.T) {
	ci.Parallel(t)

	m := testManager(t)
	must.Zero(t, m.NumServers())

	s := &servers.Server{Addr: &fauxAddr{"server1"}}
	m.SetServers([]*servers.Server{s})
	must.Eq(t, 1, m.NumServers())
}

func TestServers_RebalanceServers(t *testing.T) {
	ci.Parallel(t)

Review comment (suggestion):
I think you can use `must.Equal` here, as that calls the `Equal` method (as opposed to `must.Eq` which uses `cmp.Equal`).

Code after:

	// Try notifying for a server that is not managed by Manager
	m.NotifyFailedServer(s1)
	must.Zero(t, m.NumServers())
	m.SetServers([]*servers.Server{s1})

	// Test again w/ a server not in the list
	m.NotifyFailedServer(s2)
	must.Eq(t, 1, m.NumServers())

	m.SetServers([]*servers.Server{s1, s2})
	must.Eq(t, 2, m.NumServers())

	// Grab a server
	first := m.FindServer()

	// Find the other server
	second := s1
	if first.Equal(s1) {
		second = s2
	}

	// Fail the other server
	m.NotifyFailedServer(second)
	next := m.FindServer()
	must.Equal(t, first, next)

	// Fail the first
	m.NotifyFailedServer(first)
	next = m.FindServer()
	must.True(t, next.Equal(second))

	// Fail the second
	m.NotifyFailedServer(second)
	next = m.FindServer()
	must.True(t, next.Equal(first))
}

func TestServers_NumServers(t *testing.T) {
	ci.Parallel(t)

	m := testManager(t)
	must.Zero(t, m.NumServers())

	s := &servers.Server{Addr: &fauxAddr{"server1"}}
	m.SetServers([]*servers.Server{s})
	must.Eq(t, 1, m.NumServers())
}

func TestServers_RebalanceServers(t *testing.T) {
	ci.Parallel(t)
Repository: hashicorp/nomad
File: command/agent/command.go (Go)

Code before:

	// Wait for a signal
WAIT:
	var sig os.Signal
	select {
	case s := <-signalCh:
		sig = s
	case <-winsvc.ShutdownChannel():
		sig = os.Interrupt
	case <-c.ShutdownCh:
		sig = os.Interrupt
	case <-c.retryJoinErrCh:
		return 1
	}

	// Skip any SIGPIPE signal and don't try to log it (See issues #1798, #3554)
	if sig == syscall.SIGPIPE {
		goto WAIT
	}

	c.Ui.Output(fmt.Sprintf("Caught signal: %v", sig))

	// Check if this is a SIGHUP
	if sig == syscall.SIGHUP {
		var ts unix.Timespec
		if err := unix.ClockGettime(unix.CLOCK_MONOTONIC, &ts); err != nil {
			c.agent.logger.Error("failed to get clock time", "error", err)
			return 1
		}
		micro := ts.Nano() / 1000
		sdNotify(sdSock, fmt.Sprintf(sdReloading, micro))
		c.handleReload()
		sdNotify(sdSock, sdReady)
		goto WAIT
	}

	// Check if we should do a graceful leave
	graceful := false
	if sig == os.Interrupt && c.agent.GetConfig().LeaveOnInt {
		graceful = true
	} else if sig == syscall.SIGTERM && c.agent.GetConfig().LeaveOnTerm {
		graceful = true
	}

	// Bail fast if not doing a graceful leave
	if !graceful {
		return 1
	}

	// Attempt a graceful leave
	sdNotify(sdSock, sdStopping)

Review comment (suggestion):
This mimics the python equivalent of:

```python
  microsecs = time.clock_gettime_ns(time.CLOCK_MONOTONIC) // 1000
```

Code after:
		sig = os.Interrupt
	case <-c.retryJoinErrCh:
		return 1
	}

	// Skip any SIGPIPE signal and don't try to log it (See issues #1798, #3554)
	if sig == syscall.SIGPIPE {
		goto WAIT
	}

	c.Ui.Output(fmt.Sprintf("Caught signal: %v", sig))

	// Check if this is a SIGHUP
	if sig == syscall.SIGHUP {
		sdNotifyReloading(sdSock)
		c.handleReload()
		sdNotify(sdSock, sdReady)
		goto WAIT
	}

	// Check if we should do a graceful leave
	graceful := false
	if sig == os.Interrupt && c.agent.GetConfig().LeaveOnInt {
		graceful = true
	} else if sig == syscall.SIGTERM && c.agent.GetConfig().LeaveOnTerm {
		graceful = true
	}

	// Bail fast if not doing a graceful leave
	if !graceful {
		return 1
	}

	// Attempt a graceful leave
	sdNotify(sdSock, sdStopping)
	gracefulCh := make(chan struct{})
	c.Ui.Output("Gracefully shutting down agent...")
	go func() {
		if err := c.agent.Leave(); err != nil {
			c.Ui.Error(fmt.Sprintf("Error: %s", err))
			return
		}
		close(gracefulCh)
	}()

	// Wait for leave or another signal
	select {
	case <-signalCh:
		return 1
	case <-time.After(gracefulTimeout):
		return 1
Repository: hashicorp/nomad
File: command/agent/command.go (Go)

Code before:
WAIT:
	var sig os.Signal
	select {
	case s := <-signalCh:
		sig = s
	case <-winsvc.ShutdownChannel():
		sig = os.Interrupt
	case <-c.ShutdownCh:
		sig = os.Interrupt
	case <-c.retryJoinErrCh:
		return 1
	}

	// Skip any SIGPIPE signal and don't try to log it (See issues #1798, #3554)
	if sig == syscall.SIGPIPE {
		goto WAIT
	}

	c.Ui.Output(fmt.Sprintf("Caught signal: %v", sig))

	// Check if this is a SIGHUP
	if sig == syscall.SIGHUP {
		var ts unix.Timespec
		if err := unix.ClockGettime(unix.CLOCK_MONOTONIC, &ts); err != nil {
			c.agent.logger.Error("failed to get clock time", "error", err)
			return 1
		}
		micro := ts.Nano() / 1000
		sdNotify(sdSock, fmt.Sprintf(sdReloading, micro))
		c.handleReload()
		sdNotify(sdSock, sdReady)
		goto WAIT
	}

	// Check if we should do a graceful leave
	graceful := false
	if sig == os.Interrupt && c.agent.GetConfig().LeaveOnInt {
		graceful = true
	} else if sig == syscall.SIGTERM && c.agent.GetConfig().LeaveOnTerm {
		graceful = true
	}

	// Bail fast if not doing a graceful leave
	if !graceful {
		return 1
	}

	// Attempt a graceful leave
	sdNotify(sdSock, sdStopping)
	gracefulCh := make(chan struct{})
	c.Ui.Output("Gracefully shutting down agent...")

Review comment (bug):
Not sure if `return 1` is the correct thing to do here. I feel like it's very unlikely for this to fail on normal systems. They'll always have a monotonic clock. maybe debug and ignore?

Code after:
		return 1
	}

	// Skip any SIGPIPE signal and don't try to log it (See issues #1798, #3554)
	if sig == syscall.SIGPIPE {
		goto WAIT
	}

	c.Ui.Output(fmt.Sprintf("Caught signal: %v", sig))

	// Check if this is a SIGHUP
	if sig == syscall.SIGHUP {
		sdNotifyReloading(sdSock)
		c.handleReload()
		sdNotify(sdSock, sdReady)
		goto WAIT
	}

	// Check if we should do a graceful leave
	graceful := false
	if sig == os.Interrupt && c.agent.GetConfig().LeaveOnInt {
		graceful = true
	} else if sig == syscall.SIGTERM && c.agent.GetConfig().LeaveOnTerm {
		graceful = true
	}

	// Bail fast if not doing a graceful leave
	if !graceful {
		return 1
	}

	// Attempt a graceful leave
	sdNotify(sdSock, sdStopping)
	gracefulCh := make(chan struct{})
	c.Ui.Output("Gracefully shutting down agent...")
	go func() {
		if err := c.agent.Leave(); err != nil {
			c.Ui.Error(fmt.Sprintf("Error: %s", err))
			return
		}
		close(gracefulCh)
	}()

	// Wait for leave or another signal
	select {
	case <-signalCh:
		return 1
	case <-time.After(gracefulTimeout):
		return 1
	case <-gracefulCh:
		return 0
Repository: hashicorp/nomad
File: client/fingerprint/cpu_default_test.go (Go)

Code before:
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1

//go:build !darwin && !arm64 && !cgo

package fingerprint

import (
	"strconv"
	"testing"

	"github.com/hashicorp/nomad/ci"
	"github.com/hashicorp/nomad/client/config"
	"github.com/hashicorp/nomad/client/lib/numalib/hw"
	"github.com/hashicorp/nomad/client/testutil"
	"github.com/hashicorp/nomad/helper/testlog"
	"github.com/hashicorp/nomad/nomad/structs"
	"github.com/shoenig/test/must"
)

func TestCPUFingerprint_Classic(t *testing.T) {
	ci.Parallel(t)

	logger := testlog.HCLogger(t)

	// create the fingerprinter
	f := NewCPUFingerprint(logger)
	node := &structs.Node{Attributes: make(map[string]string)}


Review comment (suggestion):
The only other CPU test is for Darwin ARM64. If we make this `&&`, doesn't this prevent us from running this test on Linux ARM64 or Linux amd64 with CGO? I think we want `!(darwin && arm64 && cgo)` but I'll admit I'm not sure the `go:build` syntax supports this.

Code after:
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1

//go:build !darwin

package fingerprint

import (
	"runtime"
	"strconv"
	"testing"

	"github.com/hashicorp/nomad/ci"
	"github.com/hashicorp/nomad/client/config"
	"github.com/hashicorp/nomad/client/lib/numalib/hw"
	"github.com/hashicorp/nomad/client/testutil"
	"github.com/hashicorp/nomad/helper/testlog"
	"github.com/hashicorp/nomad/nomad/structs"
	"github.com/shoenig/test/must"
)

func TestCPUFingerprint_Classic(t *testing.T) {
	ci.Parallel(t)

	logger := testlog.HCLogger(t)

	// create the fingerprinter
	f := NewCPUFingerprint(logger)
	node := &structs.Node{Attributes: make(map[string]string)}
Repository: hashicorp/nomad
File: command/operator_debug.go (Go)

Code before:
			return 2
		}
	} else {
		// Generate temp directory
		tmp, err = os.MkdirTemp(os.TempDir(), stamped)
		if err != nil {
			c.Ui.Error(fmt.Sprintf("Error creating tmp directory: %s", err.Error()))
			return 2
		}
		defer os.RemoveAll(tmp)
	}

	c.collectDir = tmp

	// Write CLI flags to JSON file
	c.writeFlags(flags)

	// Create an instance of the API client
	client, err := c.Meta.Client()
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error initializing client: %s", err.Error()))
		return 1
	}

	c.opts = &api.QueryOptions{
		Region:     c.Meta.Region(),
		AllowStale: allowStale,
		AuthToken:  c.Meta.token,
	}

	// Get complete list of client nodes
	c.nodes, _, err = client.Nodes().List(c.queryOpts())
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error querying node info: %v", err))
		return 1
	}

	// Write nodes to file
	c.reportErr(writeResponseToFile(c.nodes, c.newFile(clusterDir, "nodes.json")))

	// Search all nodes If a node class is specified without a list of node id prefixes
	if c.nodeClass != "" && nodeIDs == "" {
		nodeIDs = "all"
	}

	// Resolve client node id prefixes
	nodesFound := 0
	nodeLookupFailCount := 0
	nodeCaptureCount := 0

	for _, id := range stringToSlice(nodeIDs) {

Review comment (bug):
This PR fixes the reported bug, but why are we passing the region like this at all in an API request? I think `operator debug` is the only command to do so. This should already go to the right region by virtue of how the API client gets constructed.

```suggestion
```

Code after:
			return 2
		}
	} else {
		// Generate temp directory
		tmp, err = os.MkdirTemp(os.TempDir(), stamped)
		if err != nil {
			c.Ui.Error(fmt.Sprintf("Error creating tmp directory: %s", err.Error()))
			return 2
		}
		defer os.RemoveAll(tmp)
	}

	c.collectDir = tmp

	// Write CLI flags to JSON file
	c.writeFlags(flags)

	// Create an instance of the API client
	client, err := c.Meta.Client()
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error initializing client: %s", err.Error()))
		return 1
	}

	c.opts = &api.QueryOptions{
		AllowStale: allowStale,
		AuthToken:  c.Meta.token,
	}

	// Get complete list of client nodes
	c.nodes, _, err = client.Nodes().List(c.queryOpts())
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error querying node info: %v", err))
		return 1
	}

	// Write nodes to file
	c.reportErr(writeResponseToFile(c.nodes, c.newFile(clusterDir, "nodes.json")))

	// Search all nodes If a node class is specified without a list of node id prefixes
	if c.nodeClass != "" && nodeIDs == "" {
		nodeIDs = "all"
	}

	// Resolve client node id prefixes
	nodesFound := 0
	nodeLookupFailCount := 0
	nodeCaptureCount := 0

	for _, id := range stringToSlice(nodeIDs) {
		if id == "all" {