ping.go 16 KB

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