ping.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. // Package probing is a simple but powerful ICMP echo (ping) library.
  2. //
  3. // Here is a very simple example that sends and receives three packets:
  4. //
  5. // pinger, err := probing.NewPinger("www.google.com")
  6. // if err != nil {
  7. // panic(err)
  8. // }
  9. // pinger.Count = 3
  10. // err = pinger.Run() // blocks until finished
  11. // if err != nil {
  12. // panic(err)
  13. // }
  14. // stats := pinger.Statistics() // get send/receive/rtt stats
  15. //
  16. // Here is an example that emulates the traditional UNIX ping command:
  17. //
  18. // pinger, err := probing.NewPinger("www.google.com")
  19. // if err != nil {
  20. // panic(err)
  21. // }
  22. // // Listen for Ctrl-C.
  23. // c := make(chan os.Signal, 1)
  24. // signal.Notify(c, os.Interrupt)
  25. // go func() {
  26. // for _ = range c {
  27. // pinger.Stop()
  28. // }
  29. // }()
  30. // pinger.OnRecv = func(pkt *probing.Packet) {
  31. // fmt.Printf("%d bytes from %s: icmp_seq=%d time=%v\n",
  32. // pkt.Nbytes, pkt.IPAddr, pkt.Seq, pkt.Rtt)
  33. // }
  34. // pinger.OnFinish = func(stats *probing.Statistics) {
  35. // fmt.Printf("\n--- %s ping statistics ---\n", stats.Addr)
  36. // fmt.Printf("%d packets transmitted, %d packets received, %v%% packet loss\n",
  37. // stats.PacketsSent, stats.PacketsRecv, stats.PacketLoss)
  38. // fmt.Printf("round-trip min/avg/max/stddev = %v/%v/%v/%v\n",
  39. // stats.MinRtt, stats.AvgRtt, stats.MaxRtt, stats.StdDevRtt)
  40. // }
  41. // fmt.Printf("PING %s (%s):\n", pinger.Addr(), pinger.IPAddr())
  42. // err = pinger.Run()
  43. // if err != nil {
  44. // panic(err)
  45. // }
  46. //
  47. // It sends ICMP Echo Request packet(s) and waits for an Echo Reply in response.
  48. // If it receives a response, it calls the OnRecv callback. When it's finished,
  49. // it calls the OnFinish callback.
  50. //
  51. // For a full ping example, see "cmd/ping/ping.go".
  52. package probing
  53. import (
  54. "errors"
  55. "log"
  56. "math"
  57. "math/rand"
  58. "net"
  59. "sync"
  60. "sync/atomic"
  61. "time"
  62. "git.wecise.com/wecise/common/matrix/cfg"
  63. "github.com/google/uuid"
  64. "golang.org/x/sync/errgroup"
  65. )
  66. var mcfg = cfg.MConfig()
  67. var receive_buffer_count = mcfg.GetInt("ping.recv.buf.count", 100)
  68. var ttl = mcfg.GetInt("ping.ttl", 64)
  69. var ping_interval_one_host = mcfg.GetDuration("ping.interval.one.host", 200*time.Millisecond)
  70. var ping_interval_one_conn = mcfg.GetDuration("ping.interval.one.conn", 200*time.Millisecond)
  71. var concurlimit_ping = mcfg.GetInt("concurlimit.ping", 100)
  72. var concurlimit_send = mcfg.GetInt("concurlimit.send", 10)
  73. var concurchan_ping = make(chan struct{}, concurlimit_ping)
  74. var concurchan_send = make(chan struct{}, concurlimit_send)
  75. var lastpingtimemutex sync.Mutex
  76. var lastpingtime = map[string]time.Time{}
  77. var lastsendtimemutex sync.Mutex
  78. var lastsendtime = map[string]time.Time{}
  79. const (
  80. timeSliceLength = 8
  81. trackerLength = len(uuid.UUID{})
  82. protocolICMP = 1
  83. protocolIPv6ICMP = 58
  84. )
  85. // New returns a new Pinger struct pointer.
  86. func New(addr string) *Pinger {
  87. r := rand.New(rand.NewSource(getSeed()))
  88. firstUUID := uuid.New()
  89. var firstSequence = map[uuid.UUID]map[int]struct{}{}
  90. firstSequence[firstUUID] = make(map[int]struct{})
  91. return &Pinger{
  92. Count: -1,
  93. Interval: time.Second,
  94. RecordRtts: true,
  95. Size: timeSliceLength + trackerLength,
  96. Timeout: time.Duration(math.MaxInt64),
  97. addr: addr,
  98. done: make(chan interface{}),
  99. id: r.Intn(math.MaxUint16),
  100. trackerUUIDs: []uuid.UUID{firstUUID},
  101. ipaddr: nil,
  102. ipv4: false,
  103. network: "ip",
  104. protocol: "udp",
  105. awaitingSequences: firstSequence,
  106. TTL: 64,
  107. logger: StdLogger{Logger: log.New(log.Writer(), log.Prefix(), log.Flags())},
  108. }
  109. }
  110. // NewPinger returns a new Pinger and resolves the address.
  111. func NewPinger(addr string) (*Pinger, error) {
  112. p := New(addr)
  113. return p, p.Resolve()
  114. }
  115. // Pinger represents a packet sender/receiver.
  116. type Pinger struct {
  117. // Interval is the wait time between each packet send. Default is 1s.
  118. Interval time.Duration
  119. // Timeout specifies a timeout before ping exits, regardless of how many
  120. // packets have been received.
  121. Timeout time.Duration
  122. // Count tells pinger to stop after sending (and receiving) Count echo
  123. // packets. If this option is not specified, pinger will operate until
  124. // interrupted.
  125. Count int
  126. // Debug runs in debug mode
  127. Debug bool
  128. // Number of packets sent
  129. PacketsSent int
  130. // Number of packets received
  131. PacketsRecv int
  132. // Number of duplicate packets received
  133. PacketsRecvDuplicates int
  134. // Round trip time statistics
  135. minRtt time.Duration
  136. maxRtt time.Duration
  137. avgRtt time.Duration
  138. stdDevRtt time.Duration
  139. stddevm2 time.Duration
  140. statsMu sync.RWMutex
  141. // If true, keep a record of rtts of all received packets.
  142. // Set to false to avoid memory bloat for long running pings.
  143. RecordRtts bool
  144. // rtts is all of the Rtts
  145. rtts []time.Duration
  146. // OnSetup is called when Pinger has finished setting up the listening socket
  147. OnSetup func()
  148. // OnSend is called when Pinger sends a packet
  149. OnSend func(*Packet)
  150. // OnRecv is called when Pinger receives and processes a packet
  151. OnRecv func(*Packet)
  152. // OnRecv is called when Pinger receives and processes a packet
  153. OnTimeout func(*Packet)
  154. // OnFinish is called when Pinger exits
  155. OnFinish func(*Statistics)
  156. // OnDuplicateRecv is called when a packet is received that has already been received.
  157. OnDuplicateRecv func(*Packet)
  158. // Size of packet being sent
  159. Size int
  160. // Tracker: Used to uniquely identify packets - Deprecated
  161. Tracker uint64
  162. // Source is the source IP address
  163. Source string
  164. // Channel and mutex used to communicate when the Pinger should stop between goroutines.
  165. done chan interface{}
  166. lock sync.Mutex
  167. ipaddr *net.IPAddr
  168. addr string
  169. // trackerUUIDs is the list of UUIDs being used for sending packets.
  170. trackerUUIDs []uuid.UUID
  171. ipv4 bool
  172. id int
  173. sequence_base int
  174. sequence int
  175. // awaitingSequences are in-flight sequence numbers we keep track of to help remove duplicate receipts
  176. awaitingSequences map[uuid.UUID]map[int]struct{}
  177. // network is one of "ip", "ip4", or "ip6".
  178. network string
  179. // protocol is "icmp" or "udp".
  180. protocol string
  181. logger Logger
  182. TTL int
  183. }
  184. // Packet represents a received and processed ICMP echo packet.
  185. type Packet struct {
  186. // Rtt is the round-trip time it took to ping.
  187. Rtt time.Duration
  188. // IPAddr is the address of the host being pinged.
  189. IPAddr *net.IPAddr
  190. // Host is the string address of the host being pinged.
  191. Host string
  192. // NBytes is the number of bytes in the message.
  193. Nbytes int
  194. // Seq is the ICMP sequence number.
  195. Seq int
  196. // TTL is the Time To Live on the packet.
  197. TTL int
  198. // ID is the ICMP identifier.
  199. ID int
  200. }
  201. // Statistics represent the stats of a currently running or finished
  202. // pinger operation.
  203. type Statistics struct {
  204. // PacketsRecv is the number of packets received.
  205. PacketsRecv int
  206. // PacketsSent is the number of packets sent.
  207. PacketsSent int
  208. // PacketsRecvDuplicates is the number of duplicate responses there were to a sent packet.
  209. PacketsRecvDuplicates int
  210. // PacketLoss is the percentage of packets lost.
  211. PacketLoss float64
  212. // IPAddr is the address of the host being pinged.
  213. IPAddr *net.IPAddr
  214. // Addr is the string address of the host being pinged.
  215. Addr string
  216. // Rtts is all of the round-trip times sent via this pinger.
  217. Rtts []time.Duration
  218. // MinRtt is the minimum round-trip time sent via this pinger.
  219. MinRtt time.Duration
  220. // MaxRtt is the maximum round-trip time sent via this pinger.
  221. MaxRtt time.Duration
  222. // AvgRtt is the average round-trip time sent via this pinger.
  223. AvgRtt time.Duration
  224. // StdDevRtt is the standard deviation of the round-trip times sent via
  225. // this pinger.
  226. StdDevRtt time.Duration
  227. }
  228. func (p *Pinger) updateStatistics(pkt *Packet) {
  229. p.statsMu.Lock()
  230. defer p.statsMu.Unlock()
  231. p.PacketsRecv++
  232. if p.RecordRtts {
  233. p.rtts = append(p.rtts, pkt.Rtt)
  234. }
  235. if p.PacketsRecv == 1 || pkt.Rtt < p.minRtt {
  236. p.minRtt = pkt.Rtt
  237. }
  238. if pkt.Rtt > p.maxRtt {
  239. p.maxRtt = pkt.Rtt
  240. }
  241. pktCount := time.Duration(p.PacketsRecv)
  242. // welford's online method for stddev
  243. // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm
  244. delta := pkt.Rtt - p.avgRtt
  245. p.avgRtt += delta / pktCount
  246. delta2 := pkt.Rtt - p.avgRtt
  247. p.stddevm2 += delta * delta2
  248. p.stdDevRtt = time.Duration(math.Sqrt(float64(p.stddevm2 / pktCount)))
  249. }
  250. // SetIPAddr sets the ip address of the target host.
  251. func (p *Pinger) SetIPAddr(ipaddr *net.IPAddr) {
  252. p.ipv4 = isIPv4(ipaddr.IP)
  253. p.ipaddr = ipaddr
  254. p.addr = ipaddr.String()
  255. }
  256. // IPAddr returns the ip address of the target host.
  257. func (p *Pinger) IPAddr() *net.IPAddr {
  258. return p.ipaddr
  259. }
  260. // Resolve does the DNS lookup for the Pinger address and sets IP protocol.
  261. func (p *Pinger) Resolve() error {
  262. if len(p.addr) == 0 {
  263. return errors.New("addr cannot be empty")
  264. }
  265. ipaddr, err := net.ResolveIPAddr(p.network, p.addr)
  266. if err != nil {
  267. return err
  268. }
  269. p.ipv4 = isIPv4(ipaddr.IP)
  270. p.ipaddr = ipaddr
  271. return nil
  272. }
  273. // SetAddr resolves and sets the ip address of the target host, addr can be a
  274. // DNS name like "www.google.com" or IP like "127.0.0.1".
  275. func (p *Pinger) SetAddr(addr string) error {
  276. oldAddr := p.addr
  277. p.addr = addr
  278. err := p.Resolve()
  279. if err != nil {
  280. p.addr = oldAddr
  281. return err
  282. }
  283. return nil
  284. }
  285. // Addr returns the string ip address of the target host.
  286. func (p *Pinger) Addr() string {
  287. return p.addr
  288. }
  289. // SetNetwork allows configuration of DNS resolution.
  290. // * "ip" will automatically select IPv4 or IPv6.
  291. // * "ip4" will select IPv4.
  292. // * "ip6" will select IPv6.
  293. func (p *Pinger) SetNetwork(n string) {
  294. switch n {
  295. case "ip4":
  296. p.network = "ip4"
  297. case "ip6":
  298. p.network = "ip6"
  299. default:
  300. p.network = "ip"
  301. }
  302. }
  303. // SetPrivileged sets the type of ping pinger will send.
  304. // false means pinger will send an "unprivileged" UDP ping.
  305. // true means pinger will send a "privileged" raw ICMP ping.
  306. // NOTE: setting to true requires that it be run with super-user privileges.
  307. func (p *Pinger) SetPrivileged(privileged bool) {
  308. if privileged {
  309. p.protocol = "icmp"
  310. } else {
  311. p.protocol = "udp"
  312. }
  313. }
  314. // Privileged returns whether pinger is running in privileged mode.
  315. func (p *Pinger) Privileged() bool {
  316. return p.protocol == "icmp"
  317. }
  318. // SetLogger sets the logger to be used to log events from the pinger.
  319. func (p *Pinger) SetLogger(logger Logger) {
  320. p.logger = logger
  321. }
  322. // SetID sets the ICMP identifier.
  323. func (p *Pinger) SetID(id int) {
  324. p.id = id
  325. }
  326. // ID returns the ICMP identifier.
  327. func (p *Pinger) ID() int {
  328. return p.id
  329. }
  330. // Run runs the pinger. This is a blocking function that will exit when it's
  331. // done. If Count or Interval are not specified, it will run continuously until
  332. // it is interrupted.
  333. func (p *Pinger) Run() error {
  334. // sleeptime := time.Duration(0)
  335. // for sleeptime >= 0 {
  336. // time.Sleep(sleeptime)
  337. // lastpingtimemutex.Lock()
  338. // alastpingtime := lastpingtime[p.ipaddr.String()]
  339. // sleeptime = ping_interval_one_host - time.Since(alastpingtime)
  340. // if sleeptime <= 0 {
  341. // lastpingtime[p.ipaddr.String()] = time.Now()
  342. // } else {
  343. // // logger.Error(fmt.Sprint("ping", p.addr, "[", p.ipaddr.String(), "]", "同一地址至少间隔一秒"))
  344. // }
  345. // lastpingtimemutex.Unlock()
  346. // }
  347. // defer func() {
  348. // lastpingtimemutex.Lock()
  349. // lastpingtime[p.ipaddr.String()] = time.Now()
  350. // lastpingtimemutex.Unlock()
  351. // }()
  352. // concurchan_ping <- struct{}{}
  353. // defer func() {
  354. // <-concurchan_ping
  355. // }()
  356. return p.run()
  357. }
  358. func (p *Pinger) run() error {
  359. defer p.finish()
  360. _, err := mpconn.listen()
  361. if err != nil {
  362. return err
  363. }
  364. if handler := p.OnSetup; handler != nil {
  365. handler()
  366. }
  367. var g errgroup.Group
  368. g.Go(func() error {
  369. defer p.Stop()
  370. return p.runLoop()
  371. })
  372. return g.Wait()
  373. }
  374. func (p *Pinger) runLoop() error {
  375. logger := p.logger
  376. if logger == nil {
  377. logger = NoopLogger{}
  378. }
  379. timeout := time.NewTimer(p.Timeout)
  380. interval := time.NewTimer(0)
  381. timeout.Stop()
  382. defer func() {
  383. interval.Stop()
  384. timeout.Stop()
  385. }()
  386. received := make(chan interface{}, 1)
  387. for {
  388. select {
  389. case <-p.done:
  390. return nil
  391. case <-timeout.C:
  392. return nil
  393. case <-interval.C:
  394. if err := p.ping(received); err != nil {
  395. logger.Errorf("sending packet: %s", err)
  396. }
  397. if p.Count > 0 && p.PacketsSent >= p.Count {
  398. timeout.Reset(p.Timeout)
  399. } else {
  400. interval.Reset(p.Interval)
  401. }
  402. case <-received:
  403. if p.Count > 0 && p.PacketsRecv >= p.Count {
  404. return nil
  405. }
  406. }
  407. }
  408. }
  409. func (p *Pinger) ping(received chan interface{}) error {
  410. sleeptime := time.Duration(0)
  411. for sleeptime >= 0 {
  412. time.Sleep(sleeptime)
  413. lastpingtimemutex.Lock()
  414. alastpingtime := lastpingtime[p.ipaddr.String()]
  415. sleeptime = ping_interval_one_host - time.Since(alastpingtime)
  416. if sleeptime <= 0 {
  417. lastpingtime[p.ipaddr.String()] = time.Now()
  418. } else {
  419. // logger.Error(fmt.Sprint("ping", p.addr, "[", p.ipaddr.String(), "]", "同一地址至少间隔一秒"))
  420. }
  421. lastpingtimemutex.Unlock()
  422. }
  423. defer func() {
  424. lastpingtimemutex.Lock()
  425. lastpingtime[p.ipaddr.String()] = time.Now()
  426. lastpingtimemutex.Unlock()
  427. }()
  428. return mpconn.ping(p.addr, p.ipaddr, p.Size, p.Timeout, func(pkt *Packet) {
  429. if p.PacketsSent == 0 {
  430. p.sequence_base = pkt.Seq
  431. }
  432. p.PacketsSent++
  433. pkt.Seq -= p.sequence_base
  434. if p.OnSend != nil {
  435. p.OnSend(pkt)
  436. }
  437. }, func(pkt *Packet) {
  438. pkt.Seq -= p.sequence_base
  439. if p.OnRecv != nil {
  440. p.OnRecv(pkt)
  441. }
  442. p.updateStatistics(pkt)
  443. received <- nil
  444. })
  445. }
  446. func (p *Pinger) Stop() {
  447. p.lock.Lock()
  448. defer p.lock.Unlock()
  449. open := true
  450. select {
  451. case _, open = <-p.done:
  452. default:
  453. }
  454. if open {
  455. close(p.done)
  456. }
  457. }
  458. func (p *Pinger) finish() {
  459. handler := p.OnFinish
  460. if handler != nil {
  461. s := p.Statistics()
  462. handler(s)
  463. }
  464. }
  465. // Statistics returns the statistics of the pinger. This can be run while the
  466. // pinger is running or after it is finished. OnFinish calls this function to
  467. // get it's finished statistics.
  468. func (p *Pinger) Statistics() *Statistics {
  469. p.statsMu.RLock()
  470. defer p.statsMu.RUnlock()
  471. sent := p.PacketsSent
  472. loss := float64(sent-p.PacketsRecv) / float64(sent) * 100
  473. s := Statistics{
  474. PacketsSent: sent,
  475. PacketsRecv: p.PacketsRecv,
  476. PacketsRecvDuplicates: p.PacketsRecvDuplicates,
  477. PacketLoss: loss,
  478. Rtts: p.rtts,
  479. Addr: p.addr,
  480. IPAddr: p.ipaddr,
  481. MaxRtt: p.maxRtt,
  482. MinRtt: p.minRtt,
  483. AvgRtt: p.avgRtt,
  484. StdDevRtt: p.stdDevRtt,
  485. }
  486. return &s
  487. }
  488. func bytesToTime(b []byte) time.Time {
  489. var nsec int64
  490. for i := uint8(0); i < 8; i++ {
  491. nsec += int64(b[i]) << ((7 - i) * 8)
  492. }
  493. return time.Unix(nsec/1000000000, nsec%1000000000)
  494. }
  495. func isIPv4(ip net.IP) bool {
  496. return len(ip.To4()) == net.IPv4len
  497. }
  498. func timeToBytes(t time.Time) []byte {
  499. nsec := t.UnixNano()
  500. b := make([]byte, 8)
  501. for i := uint8(0); i < 8; i++ {
  502. b[i] = byte((nsec >> ((7 - i) * 8)) & 0xff)
  503. }
  504. return b
  505. }
  506. var seed = time.Now().UnixNano()
  507. // getSeed returns a goroutine-safe unique seed
  508. func getSeed() int64 {
  509. return atomic.AddInt64(&seed, 1)
  510. }
  511. func BufferUsedCount() int {
  512. return len(mpconn.recvchan)
  513. }