Skip to content

Commit bee5840

Browse files
authored
Merge pull request #2256 from josephschorr/nodeid-default
Move nodeid default calculation to init to avoid race
2 parents ee35ee1 + 208e81e commit bee5840

File tree

1 file changed

+18
-15
lines changed

1 file changed

+18
-15
lines changed

pkg/middleware/nodeid/nodeid.go

+18-15
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77

88
"github.com/cespare/xxhash/v2"
99
middleware "github.com/grpc-ecosystem/go-grpc-middleware/v2"
10+
"github.com/rs/zerolog/log"
1011
"google.golang.org/grpc"
1112
)
1213

@@ -22,6 +23,23 @@ type nodeIDHandle struct {
2223

2324
var defaultNodeID string
2425

26+
func init() {
27+
hostname, err := os.Hostname()
28+
if err != nil {
29+
log.Warn().Err(err).Msg("failed to get hostname, using an empty node ID")
30+
return
31+
}
32+
33+
// Hash the hostname to get the final default node ID.
34+
hasher := xxhash.New()
35+
if _, err := hasher.WriteString(hostname); err != nil {
36+
log.Warn().Err(err).Msg("failed to hash hostname, using an empty node ID")
37+
return
38+
}
39+
40+
defaultNodeID = spiceDBPrefix + fmt.Sprintf("%x", hasher.Sum(nil))
41+
}
42+
2543
// ContextWithHandle adds a placeholder to a context that will later be
2644
// filled by the Node ID.
2745
func ContextWithHandle(ctx context.Context) context.Context {
@@ -37,21 +55,6 @@ func FromContext(ctx context.Context) (string, error) {
3755
}
3856
}
3957

40-
if defaultNodeID == "" {
41-
hostname, err := os.Hostname()
42-
if err != nil {
43-
return "", err
44-
}
45-
46-
// Hash the hostname to get the final default node ID.
47-
hasher := xxhash.New()
48-
if _, err := hasher.WriteString(hostname); err != nil {
49-
return "", fmt.Errorf("failed to hash hostname: %w", err)
50-
}
51-
52-
defaultNodeID = spiceDBPrefix + fmt.Sprintf("%x", hasher.Sum(nil))
53-
}
54-
5558
if err := setInContext(ctx, defaultNodeID); err != nil {
5659
return "", err
5760
}

0 commit comments

Comments
 (0)