Skip to content

Commit

Permalink
[CWS] make sure we do not fetch the hostname multiple times (especial…
Browse files Browse the repository at this point in the history
…ly in tests)
  • Loading branch information
paulcacheux committed Jun 19, 2024
1 parent 0637b28 commit fc192bd
Showing 1 changed file with 24 additions and 4 deletions.
28 changes: 24 additions & 4 deletions pkg/security/utils/hostname.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ package utils

import (
"context"
"sync"
"time"

"github.com/avast/retry-go/v4"
Expand All @@ -25,15 +26,34 @@ const (
maxAttempts = 6
)

var (
hostnameLock sync.RWMutex
cachedHostname string
)

// GetHostname attempts to acquire a hostname by connecting to the core
// agent's gRPC endpoints.
func GetHostname() (string, error) {
return GetHostnameWithContext(context.Background())
hostnameLock.RLock()
if cachedHostname != "" {
hostnameLock.RUnlock()
return cachedHostname, nil
}

hostname, err := GetHostnameWithContextAndFallback(context.Background())

if hostname != "" {
hostnameLock.Lock()
cachedHostname = hostname
hostnameLock.Unlock()
}

return hostname, err
}

// GetHostnameWithContext attempts to acquire a hostname by connecting to the
// getHostnameFromAgent attempts to acquire a hostname by connecting to the
// core agent's gRPC endpoints extending the given context.
func GetHostnameWithContext(ctx context.Context) (string, error) {
func getHostnameFromAgent(ctx context.Context) (string, error) {
var hostname string
err := retry.Do(func() error {
ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
Expand Down Expand Up @@ -65,7 +85,7 @@ func GetHostnameWithContext(ctx context.Context) (string, error) {
// GetHostnameWithContextAndFallback attempts to acquire a hostname by connecting to the
// core agent's gRPC endpoints extending the given context, or falls back to local resolution
func GetHostnameWithContextAndFallback(ctx context.Context) (string, error) {
hostnameDetected, err := GetHostnameWithContext(ctx)
hostnameDetected, err := getHostnameFromAgent(ctx)
if err != nil {
log.Warnf("Could not resolve hostname from core-agent: %v", err)
hostnameDetected, err = hostname.Get(ctx)
Expand Down

0 comments on commit fc192bd

Please sign in to comment.