Skip to content

Commit

Permalink
Add helper function getHostnameAndSourceIP() (#97)
Browse files Browse the repository at this point in the history
  • Loading branch information
rockdaboot authored Jul 30, 2024
1 parent 7b17fe3 commit a0b8ba4
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 17 deletions.
26 changes: 26 additions & 0 deletions helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"net"
"os"
"runtime"
"sync"
"syscall"
Expand Down Expand Up @@ -124,6 +125,31 @@ func getSourceIPAddress(domain string) (net.IP, error) {
return srcIP, nil
}

// getHostnameAndSourceIP returns the hostname and source IP address for the traffic destined to
// the specified domain.
func getHostnameAndSourceIP(domain string) (hostname, sourceIP string, err error) {
err = runInRootNS(func() error {
var joinedErr error

if name, hostnameErr := os.Hostname(); hostnameErr == nil {
hostname = name
} else {
joinedErr = fmt.Errorf("failed to get hostname: %v", hostnameErr)
}

if srcIP, ipErr := getSourceIPAddress(domain); ipErr == nil {
sourceIP = srcIP.String()
} else {
joinedErr = errors.Join(joinedErr,
fmt.Errorf("failed to get source IP: %v", ipErr))
}

return joinedErr
})

return hostname, sourceIP, err
}

// runInRootNS executes fetcher in the root namespace.
func runInRootNS(fetcher func() error) error {
// We need to call the `setns` syscall to extract information (network route, hostname) from
Expand Down
19 changes: 2 additions & 17 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,25 +164,10 @@ func mainWithExitCode() exitCode {
metadataCollector.AddCustomData("os.kernel.release", kernelVersion)

// hostname and sourceIP will be populated from the root namespace.
var hostname, sourceIP string

if err = runInRootNS(func() error {
var hostnameErr error
hostname, hostnameErr = os.Hostname()
if hostnameErr != nil {
return fmt.Errorf("failed to get hostname: %v", hostnameErr)
}

srcIP, ipErr := getSourceIPAddress(args.collAgentAddr)
if ipErr != nil {
return fmt.Errorf("failed to get source IP: %v", ipErr)
}
sourceIP = srcIP.String()
return nil
}); err != nil {
hostname, sourceIP, err := getHostnameAndSourceIP(args.collAgentAddr)
if err != nil {
log.Warnf("Failed to fetch metadata information in the root namespace: %v", err)
}

metadataCollector.AddCustomData("host.name", hostname)
metadataCollector.AddCustomData("host.ip", sourceIP)

Expand Down

0 comments on commit a0b8ba4

Please sign in to comment.