github.com/cilium/cilium@v1.16.2/pkg/hubble/peer/types/peer.go (about) 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright Authors of Cilium 3 4 package types 5 6 import ( 7 "net" 8 "strconv" 9 "strings" 10 11 peerpb "github.com/cilium/cilium/api/v1/peer" 12 "github.com/cilium/cilium/pkg/hubble/defaults" 13 ) 14 15 // Peer represents a hubble peer. 16 type Peer struct { 17 // Name is the name of the peer, typically the hostname. The name includes 18 // the cluster name if a value other than default has been specified. 19 // This value can be used to uniquely identify the host. 20 // When the cluster name is not the default, the cluster name is prepended 21 // to the peer name and a forward slash is added. 22 // 23 // Examples: 24 // - runtime1 25 // - testcluster/runtime1 26 Name string 27 28 // Address is the address of the peer's gRPC service. 29 Address net.Addr 30 31 // TLSEnabled indicates whether the service offered by the peer has TLS 32 // enabled. 33 TLSEnabled bool 34 35 // TLSServerName is the name the TLS certificate should be matched to. 36 TLSServerName string 37 } 38 39 // FromChangeNotification creates a new Peer from a ChangeNotification. 40 func FromChangeNotification(cn *peerpb.ChangeNotification) *Peer { 41 if cn == nil { 42 return (*Peer)(nil) 43 } 44 var err error 45 var addr net.Addr 46 switch a := cn.GetAddress(); { 47 case strings.HasPrefix(a, "unix://"), strings.HasPrefix(a, "/") && strings.HasSuffix(a, ".sock"): 48 addr, err = net.ResolveUnixAddr("unix", a) 49 case a == "": 50 // no address specified, leave it nil 51 default: 52 var host, port string 53 if host, port, err = net.SplitHostPort(a); err == nil { 54 if ip := net.ParseIP(host); ip != nil { 55 var p int 56 if p, err = strconv.Atoi(port); err == nil { 57 addr = &net.TCPAddr{ 58 IP: ip, 59 Port: p, 60 } 61 } else { 62 err = nil 63 addr = &net.TCPAddr{ 64 IP: ip, 65 Port: defaults.ServerPort, 66 } 67 } 68 } else { 69 // resolve then 70 addr, err = net.ResolveTCPAddr("tcp", a) 71 } 72 } else if ip := net.ParseIP(a); ip != nil { 73 err = nil 74 addr = &net.TCPAddr{ 75 IP: ip, 76 Port: defaults.ServerPort, 77 } 78 } 79 } 80 if err != nil { 81 addr = (net.Addr)(nil) 82 } 83 var tlsEnabled bool 84 var tlsServerName string 85 if tls := cn.GetTls(); tls != nil { 86 tlsEnabled = true 87 tlsServerName = tls.GetServerName() 88 } 89 return &Peer{ 90 Name: cn.GetName(), 91 Address: addr, 92 TLSEnabled: tlsEnabled, 93 TLSServerName: tlsServerName, 94 } 95 } 96 97 // String implements fmt's Stringer interface. 98 func (p Peer) String() string { 99 return p.Name 100 } 101 102 // Equal reports whether the Peer is equal to the provided Peer 103 func (p Peer) Equal(o Peer) bool { 104 addrEq := (p.Address == nil && o.Address == nil) || 105 (p.Address.String() == o.Address.String() && p.Address.Network() == o.Address.Network()) 106 return p.Name == o.Name && 107 p.TLSEnabled == o.TLSEnabled && 108 p.TLSServerName == o.TLSServerName && 109 addrEq 110 }