net.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. package net
  2. import (
  3. "context"
  4. "encoding/json"
  5. "net"
  6. "github.com/shirou/gopsutil/v3/internal/common"
  7. )
  8. var invoke common.Invoker = common.Invoke{}
  9. type IOCountersStat struct {
  10. Name string `json:"name"` // interface name
  11. BytesSent uint64 `json:"bytesSent"` // number of bytes sent
  12. BytesRecv uint64 `json:"bytesRecv"` // number of bytes received
  13. PacketsSent uint64 `json:"packetsSent"` // number of packets sent
  14. PacketsRecv uint64 `json:"packetsRecv"` // number of packets received
  15. Errin uint64 `json:"errin"` // total number of errors while receiving
  16. Errout uint64 `json:"errout"` // total number of errors while sending
  17. Dropin uint64 `json:"dropin"` // total number of incoming packets which were dropped
  18. Dropout uint64 `json:"dropout"` // total number of outgoing packets which were dropped (always 0 on OSX and BSD)
  19. Fifoin uint64 `json:"fifoin"` // total number of FIFO buffers errors while receiving
  20. Fifoout uint64 `json:"fifoout"` // total number of FIFO buffers errors while sending
  21. }
  22. // Addr is implemented compatibility to psutil
  23. type Addr struct {
  24. IP string `json:"ip"`
  25. Port uint32 `json:"port"`
  26. }
  27. type ConnectionStat struct {
  28. Fd uint32 `json:"fd"`
  29. Family uint32 `json:"family"`
  30. Type uint32 `json:"type"`
  31. Laddr Addr `json:"localaddr"`
  32. Raddr Addr `json:"remoteaddr"`
  33. Status string `json:"status"`
  34. Uids []int32 `json:"uids"`
  35. Pid int32 `json:"pid"`
  36. }
  37. // System wide stats about different network protocols
  38. type ProtoCountersStat struct {
  39. Protocol string `json:"protocol"`
  40. Stats map[string]int64 `json:"stats"`
  41. }
  42. // NetInterfaceAddr is designed for represent interface addresses
  43. type InterfaceAddr struct {
  44. Addr string `json:"addr"`
  45. }
  46. // InterfaceAddrList is a list of InterfaceAddr
  47. type InterfaceAddrList []InterfaceAddr
  48. type InterfaceStat struct {
  49. Index int `json:"index"`
  50. MTU int `json:"mtu"` // maximum transmission unit
  51. Name string `json:"name"` // e.g., "en0", "lo0", "eth0.100"
  52. HardwareAddr string `json:"hardwareAddr"` // IEEE MAC-48, EUI-48 and EUI-64 form
  53. Flags []string `json:"flags"` // e.g., FlagUp, FlagLoopback, FlagMulticast
  54. Addrs InterfaceAddrList `json:"addrs"`
  55. }
  56. // InterfaceStatList is a list of InterfaceStat
  57. type InterfaceStatList []InterfaceStat
  58. type FilterStat struct {
  59. ConnTrackCount int64 `json:"connTrackCount"`
  60. ConnTrackMax int64 `json:"connTrackMax"`
  61. }
  62. // ConntrackStat has conntrack summary info
  63. type ConntrackStat struct {
  64. Entries uint32 `json:"entries"` // Number of entries in the conntrack table
  65. Searched uint32 `json:"searched"` // Number of conntrack table lookups performed
  66. Found uint32 `json:"found"` // Number of searched entries which were successful
  67. New uint32 `json:"new"` // Number of entries added which were not expected before
  68. Invalid uint32 `json:"invalid"` // Number of packets seen which can not be tracked
  69. Ignore uint32 `json:"ignore"` // Packets seen which are already connected to an entry
  70. Delete uint32 `json:"delete"` // Number of entries which were removed
  71. DeleteList uint32 `json:"deleteList"` // Number of entries which were put to dying list
  72. Insert uint32 `json:"insert"` // Number of entries inserted into the list
  73. InsertFailed uint32 `json:"insertFailed"` // # insertion attempted but failed (same entry exists)
  74. Drop uint32 `json:"drop"` // Number of packets dropped due to conntrack failure.
  75. EarlyDrop uint32 `json:"earlyDrop"` // Dropped entries to make room for new ones, if maxsize reached
  76. IcmpError uint32 `json:"icmpError"` // Subset of invalid. Packets that can't be tracked d/t error
  77. ExpectNew uint32 `json:"expectNew"` // Entries added after an expectation was already present
  78. ExpectCreate uint32 `json:"expectCreate"` // Expectations added
  79. ExpectDelete uint32 `json:"expectDelete"` // Expectations deleted
  80. SearchRestart uint32 `json:"searchRestart"` // Conntrack table lookups restarted due to hashtable resizes
  81. }
  82. func NewConntrackStat(e uint32, s uint32, f uint32, n uint32, inv uint32, ign uint32, del uint32, dlst uint32, ins uint32, insfail uint32, drop uint32, edrop uint32, ie uint32, en uint32, ec uint32, ed uint32, sr uint32) *ConntrackStat {
  83. return &ConntrackStat{
  84. Entries: e,
  85. Searched: s,
  86. Found: f,
  87. New: n,
  88. Invalid: inv,
  89. Ignore: ign,
  90. Delete: del,
  91. DeleteList: dlst,
  92. Insert: ins,
  93. InsertFailed: insfail,
  94. Drop: drop,
  95. EarlyDrop: edrop,
  96. IcmpError: ie,
  97. ExpectNew: en,
  98. ExpectCreate: ec,
  99. ExpectDelete: ed,
  100. SearchRestart: sr,
  101. }
  102. }
  103. type ConntrackStatList struct {
  104. items []*ConntrackStat
  105. }
  106. func NewConntrackStatList() *ConntrackStatList {
  107. return &ConntrackStatList{
  108. items: []*ConntrackStat{},
  109. }
  110. }
  111. func (l *ConntrackStatList) Append(c *ConntrackStat) {
  112. l.items = append(l.items, c)
  113. }
  114. func (l *ConntrackStatList) Items() []ConntrackStat {
  115. items := make([]ConntrackStat, len(l.items))
  116. for i, el := range l.items {
  117. items[i] = *el
  118. }
  119. return items
  120. }
  121. // Summary returns a single-element list with totals from all list items.
  122. func (l *ConntrackStatList) Summary() []ConntrackStat {
  123. summary := NewConntrackStat(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
  124. for _, cs := range l.items {
  125. summary.Entries += cs.Entries
  126. summary.Searched += cs.Searched
  127. summary.Found += cs.Found
  128. summary.New += cs.New
  129. summary.Invalid += cs.Invalid
  130. summary.Ignore += cs.Ignore
  131. summary.Delete += cs.Delete
  132. summary.DeleteList += cs.DeleteList
  133. summary.Insert += cs.Insert
  134. summary.InsertFailed += cs.InsertFailed
  135. summary.Drop += cs.Drop
  136. summary.EarlyDrop += cs.EarlyDrop
  137. summary.IcmpError += cs.IcmpError
  138. summary.ExpectNew += cs.ExpectNew
  139. summary.ExpectCreate += cs.ExpectCreate
  140. summary.ExpectDelete += cs.ExpectDelete
  141. summary.SearchRestart += cs.SearchRestart
  142. }
  143. return []ConntrackStat{*summary}
  144. }
  145. func (n IOCountersStat) String() string {
  146. s, _ := json.Marshal(n)
  147. return string(s)
  148. }
  149. func (n ConnectionStat) String() string {
  150. s, _ := json.Marshal(n)
  151. return string(s)
  152. }
  153. func (n ProtoCountersStat) String() string {
  154. s, _ := json.Marshal(n)
  155. return string(s)
  156. }
  157. func (a Addr) String() string {
  158. s, _ := json.Marshal(a)
  159. return string(s)
  160. }
  161. func (n InterfaceStat) String() string {
  162. s, _ := json.Marshal(n)
  163. return string(s)
  164. }
  165. func (l InterfaceStatList) String() string {
  166. s, _ := json.Marshal(l)
  167. return string(s)
  168. }
  169. func (n InterfaceAddr) String() string {
  170. s, _ := json.Marshal(n)
  171. return string(s)
  172. }
  173. func (n ConntrackStat) String() string {
  174. s, _ := json.Marshal(n)
  175. return string(s)
  176. }
  177. func Interfaces() (InterfaceStatList, error) {
  178. return InterfacesWithContext(context.Background())
  179. }
  180. func InterfacesWithContext(ctx context.Context) (InterfaceStatList, error) {
  181. is, err := net.Interfaces()
  182. if err != nil {
  183. return nil, err
  184. }
  185. ret := make(InterfaceStatList, 0, len(is))
  186. for _, ifi := range is {
  187. var flags []string
  188. if ifi.Flags&net.FlagUp != 0 {
  189. flags = append(flags, "up")
  190. }
  191. if ifi.Flags&net.FlagBroadcast != 0 {
  192. flags = append(flags, "broadcast")
  193. }
  194. if ifi.Flags&net.FlagLoopback != 0 {
  195. flags = append(flags, "loopback")
  196. }
  197. if ifi.Flags&net.FlagPointToPoint != 0 {
  198. flags = append(flags, "pointtopoint")
  199. }
  200. if ifi.Flags&net.FlagMulticast != 0 {
  201. flags = append(flags, "multicast")
  202. }
  203. r := InterfaceStat{
  204. Index: ifi.Index,
  205. Name: ifi.Name,
  206. MTU: ifi.MTU,
  207. HardwareAddr: ifi.HardwareAddr.String(),
  208. Flags: flags,
  209. }
  210. addrs, err := ifi.Addrs()
  211. if err == nil {
  212. r.Addrs = make(InterfaceAddrList, 0, len(addrs))
  213. for _, addr := range addrs {
  214. r.Addrs = append(r.Addrs, InterfaceAddr{
  215. Addr: addr.String(),
  216. })
  217. }
  218. }
  219. ret = append(ret, r)
  220. }
  221. return ret, nil
  222. }
  223. func getIOCountersAll(n []IOCountersStat) ([]IOCountersStat, error) {
  224. r := IOCountersStat{
  225. Name: "all",
  226. }
  227. for _, nic := range n {
  228. r.BytesRecv += nic.BytesRecv
  229. r.PacketsRecv += nic.PacketsRecv
  230. r.Errin += nic.Errin
  231. r.Dropin += nic.Dropin
  232. r.BytesSent += nic.BytesSent
  233. r.PacketsSent += nic.PacketsSent
  234. r.Errout += nic.Errout
  235. r.Dropout += nic.Dropout
  236. }
  237. return []IOCountersStat{r}, nil
  238. }