ping.go 16 KB

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