[Agent] [Status] network info accomplish

This commit is contained in:
zeaslity
2023-12-21 09:58:37 +08:00
parent 14516c93fa
commit 4272296809
3 changed files with 114 additions and 30 deletions

View File

@@ -7,6 +7,7 @@ import (
"github.com/shirou/gopsutil/v3/net" "github.com/shirou/gopsutil/v3/net"
net2 "net" net2 "net"
"regexp" "regexp"
"strconv"
"strings" "strings"
"time" "time"
) )
@@ -19,6 +20,14 @@ type NetworkMetric struct {
} }
type NetworkInfo struct { type NetworkInfo struct {
Name string `json:"name"` // e.g., "en0", "lo0", "eth0.100"
MTU int `json:"mtu"` // maximum transmission unit
HardwareAddr string `json:"hardwareAddr"` // IEEE MAC-48, EUI-48 and EUI-64 form
Flags []string `json:"flags"` // e.g., FlagUp, FlagLoopback, FlagMulticast
InternalIPv4 []string `json:"internal_ip_v4,omitempty"`
InternalIPv6 []string `json:"internal_ip_v6,omitempty"`
ExternalIPv4 []string `json:"external_ip_v4,omitempty"`
ExternalIPv6 []string `json:"external_ip_v6,omitempty"`
} }
type NetworkStatus struct { type NetworkStatus struct {
@@ -89,9 +98,11 @@ func GetNetworkMetric() ([]NetworkMetric, error) {
RecvSpeed: 0, RecvSpeed: 0,
} }
// calculate speed
networkMetric.SendSpeed = (float64(after.BytesSent - before.BytesSent)) / duration.Seconds() networkMetric.SendSpeed = (float64(after.BytesSent - before.BytesSent)) / duration.Seconds()
networkMetric.RecvSpeed = (float64(after.BytesRecv - before.BytesRecv)) / duration.Seconds() networkMetric.RecvSpeed = (float64(after.BytesRecv - before.BytesRecv)) / duration.Seconds()
// append result
result = append(result, networkMetric) result = append(result, networkMetric)
} }
} }
@@ -104,49 +115,91 @@ func GetNetworkMetric() ([]NetworkMetric, error) {
return result, nil return result, nil
} }
func GetNetworkInfo() { func GetNetworkInfo() ([]NetworkInfo, error) {
interfaceStatList, err := net.Interfaces() interfaceStatList, err := net.Interfaces()
if err != nil { if err != nil {
log.ErrorF("[GetNetworkInfo] - get net interface list error %s", err.Error()) log.ErrorF("[GetNetworkInfo] - get net interface list error %s", err.Error())
} }
var result []NetworkInfo
for _, interfaceStat := range interfaceStatList { for _, interfaceStat := range interfaceStatList {
fmt.Println() if MatchNetInterfaceRight(interfaceStat.Name) {
marshal, _ := json.Marshal(interfaceStat) // just collect useful net interface
fmt.Println(string(marshal))
fmt.Println() // new result
networkInfo := NetworkInfo{
Name: interfaceStat.Name,
MTU: interfaceStat.MTU,
HardwareAddr: interfaceStat.HardwareAddr,
Flags: interfaceStat.Flags,
InternalIPv4: []string{},
InternalIPv6: []string{},
ExternalIPv4: nil,
ExternalIPv6: nil,
}
// calculate real ip addr
for _, interfaceAddr := range interfaceStat.Addrs {
ip, cidr, err := net2.ParseCIDR(interfaceAddr.Addr)
if err != nil {
log.ErrorF("[GetNetworkInfo] - parse interface addr error %v", err)
continue
}
// get the mask size
maskLength, _ := cidr.Mask.Size()
if ip.To4() != nil {
networkInfo.InternalIPv4 = append(networkInfo.InternalIPv4, ip.String()+"/"+strconv.Itoa(maskLength))
} else if ip.To16() != nil {
networkInfo.InternalIPv6 = append(networkInfo.InternalIPv6, ip.String()+"/"+strconv.Itoa(maskLength))
}
}
// assign
result = append(result, networkInfo)
}
} }
connections, _ := net.Connections("tcp4") return result, nil
}
func GetNetworkConnectionALl() []net.ConnectionStat {
connections, err := net.Connections("all")
if err != nil {
log.ErrorF("[GetNetworkConnectionALl] - get network connections error ! %v", err)
return nil
}
for _, con := range connections { for _, con := range connections {
fmt.Println() fmt.Println()
marshal, _ := json.Marshal(con) marshal, _ := json.Marshal(con)
fmt.Println(string(marshal)) fmt.Println(string(marshal))
fmt.Println() fmt.Println()
} }
return connections
}
protoCounters, err := net.ProtoCounters([]string{}) func GetNetworkConnectionTCP4() {
if err != nil {
log.ErrorF("[GetNetworkInfo] - get proto counter list error %s", err.Error()) }
}
for _, proto := range protoCounters { func GetNetworkConnectionTCP6() {
connections, _ := net.Connections("tcp6")
for _, con := range connections {
fmt.Println() fmt.Println()
marshal, _ := json.Marshal(proto) marshal, _ := json.Marshal(con)
fmt.Println(string(marshal)) fmt.Println(string(marshal))
fmt.Println() fmt.Println()
} }
}
filterCounters, err := net.FilterCounters() func GetNetworkConnectionUDP4() {
if err != nil {
log.ErrorF("[GetNetworkInfo] - get filter counter list error %s", err.Error()) }
}
for _, filter := range filterCounters { func GetNetworkConnectionUDP6() {
fmt.Println()
marshal, _ := json.Marshal(filter)
fmt.Println(string(marshal))
fmt.Println()
}
} }
@@ -167,7 +220,7 @@ func GetNetworkStatus() (*NetworkStatus, error) {
for _, addr := range mainInterface.Addrs { for _, addr := range mainInterface.Addrs {
allAddrs = append(allAddrs, addr.Addr) allAddrs = append(allAddrs, addr.Addr)
} }
ipv4List, ipv6List := GetInternelIpAddrs(allAddrs) ipv4List, ipv6List := GetInternalIpAdders(allAddrs)
log.DebugF("ipv4 list are => %v, ipv6 list are => %v", ipv4List, ipv6List) log.DebugF("ipv4 list are => %v, ipv6 list are => %v", ipv4List, ipv6List)
counters, err := net.IOCounters(true) counters, err := net.IOCounters(true)
@@ -231,9 +284,8 @@ func formatBytes(bytes uint64) string {
return fmt.Sprintf("%.1f %cB", float64(bytes)/float64(div), "KMGTPE"[exp]) return fmt.Sprintf("%.1f %cB", float64(bytes)/float64(div), "KMGTPE"[exp])
} }
func GetInternelIpAddrs(addresses []string) ([]string, []string) { func GetInternalIpAdders(addresses []string) (ipv4List []string, ipv6List []string) {
var ipv4 []string
var ipv6 []string
for _, addr := range addresses { for _, addr := range addresses {
// it parse (0.0.0.0) not cidr // it parse (0.0.0.0) not cidr
ip, _, err := net2.ParseCIDR(addr) ip, _, err := net2.ParseCIDR(addr)
@@ -241,12 +293,12 @@ func GetInternelIpAddrs(addresses []string) ([]string, []string) {
continue continue
} }
if ip.To4() != nil { if ip.To4() != nil {
ipv4 = append(ipv4, addr) ipv4List = append(ipv4List, addr)
} else if ip.To16() != nil { } else if ip.To16() != nil {
ipv6 = append(ipv6, addr) ipv6List = append(ipv6List, addr)
} }
} }
return ipv4, ipv6 return ipv4List, ipv6List
} }
func MatchNetInterfaceRight(interfaceName string) bool { func MatchNetInterfaceRight(interfaceName string) bool {

View File

@@ -31,6 +31,16 @@ func TestGetNetworkMetric(t *testing.T) {
} }
func TestGetNetworkInfo(t *testing.T) { func TestGetNetworkInfo(t *testing.T) {
GetNetworkInfo() networkInfos, err := GetNetworkInfo()
if err != nil {
t.Errorf("GetNetworkInfo error of %s", err)
}
for _, networkInfo := range networkInfos {
fmt.Println()
marshal, _ := json.MarshalIndent(networkInfo, "", " ")
fmt.Println(string(marshal))
fmt.Println()
}
} }

View File

@@ -0,0 +1,22 @@
package utils
import (
"agent-go/logger"
"encoding/json"
"fmt"
)
var log = logger.Log
func BeautifulPrint(object interface{}) {
bytes, err := json.MarshalIndent(object, "", " ")
if err != nil {
log.ErrorF("[BeautifulPrint] - json marshal error ! => %v", object)
}
fmt.Println()
fmt.Println(string(bytes))
fmt.Println()
}