github.com/hernad/nomad@v1.6.112/command/agent/host/network.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package host
     5  
     6  import (
     7  	"fmt"
     8  
     9  	sockaddr "github.com/hashicorp/go-sockaddr"
    10  )
    11  
    12  // network uses go-sockaddr to capture our view of the network
    13  // on error, return the text of the error
    14  func network() (output []map[string]string) {
    15  	ifaddrs, err := sockaddr.GetAllInterfaces()
    16  	if err != nil {
    17  		output = append(output, map[string]string{"error": err.Error()})
    18  		return output
    19  	}
    20  
    21  	for _, inf := range ifaddrs {
    22  		output = append(output, dumpSockAddr(inf.SockAddr))
    23  	}
    24  
    25  	return output
    26  }
    27  
    28  // dumpSockAddr is adapted from
    29  // https://github.com/hashicorp/go-sockaddr/blob/c7188e74f6acae5a989bdc959aa779f8b9f42faf/cmd/sockaddr/command/dump.go#L144-L244
    30  func dumpSockAddr(sa sockaddr.SockAddr) map[string]string {
    31  	output := make(map[string]string)
    32  
    33  	// Attributes for all SockAddr types
    34  	for _, attr := range sockaddr.SockAddrAttrs() {
    35  		output[string(attr)] = sockaddr.SockAddrAttr(sa, attr)
    36  	}
    37  
    38  	// Attributes for all IP types (both IPv4 and IPv6)
    39  	if sa.Type()&sockaddr.TypeIP != 0 {
    40  		ip := *sockaddr.ToIPAddr(sa)
    41  		for _, attr := range sockaddr.IPAttrs() {
    42  			output[string(attr)] = sockaddr.IPAddrAttr(ip, attr)
    43  		}
    44  	}
    45  
    46  	if sa.Type() == sockaddr.TypeIPv4 {
    47  		ipv4 := *sockaddr.ToIPv4Addr(sa)
    48  		for _, attr := range sockaddr.IPv4Attrs() {
    49  			output[string(attr)] = sockaddr.IPv4AddrAttr(ipv4, attr)
    50  		}
    51  	}
    52  
    53  	if sa.Type() == sockaddr.TypeIPv6 {
    54  		ipv6 := *sockaddr.ToIPv6Addr(sa)
    55  		for _, attr := range sockaddr.IPv6Attrs() {
    56  			output[string(attr)] = sockaddr.IPv6AddrAttr(ipv6, attr)
    57  		}
    58  	}
    59  
    60  	if sa.Type() == sockaddr.TypeUnix {
    61  		us := *sockaddr.ToUnixSock(sa)
    62  		for _, attr := range sockaddr.UnixSockAttrs() {
    63  			output[string(attr)] = sockaddr.UnixSockAttr(us, attr)
    64  		}
    65  	}
    66  
    67  	// Developer-focused arguments
    68  	{
    69  		arg1, arg2 := sa.DialPacketArgs()
    70  		output["DialPacket"] = fmt.Sprintf("%+q %+q", arg1, arg2)
    71  	}
    72  	{
    73  		arg1, arg2 := sa.DialStreamArgs()
    74  		output["DialStream"] = fmt.Sprintf("%+q %+q", arg1, arg2)
    75  	}
    76  	{
    77  		arg1, arg2 := sa.ListenPacketArgs()
    78  		output["ListenPacket"] = fmt.Sprintf("%+q %+q", arg1, arg2)
    79  	}
    80  	{
    81  		arg1, arg2 := sa.ListenStreamArgs()
    82  		output["ListenStream"] = fmt.Sprintf("%+q %+q", arg1, arg2)
    83  	}
    84  
    85  	return output
    86  }