Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[CWS] make sure we do not fetch the hostname multiple times (especially in tests) #26899

Merged
merged 1 commit into from
Jun 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 25 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,35 @@ 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
}
hostnameLock.RUnlock()

hostname, err := getHostnameFromAgent(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 +86,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
Loading