ping.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "math"
  6. "math/rand"
  7. "os"
  8. "runtime"
  9. "sort"
  10. "strings"
  11. "sync"
  12. "sync/atomic"
  13. "time"
  14. "trial/ping/probing"
  15. "trial/ping/probing/icmp"
  16. "trial/ping/utils"
  17. "git.wecise.com/wecise/common/matrix/cfg"
  18. "git.wecise.com/wecise/common/matrix/logger"
  19. "git.wecise.com/wecise/common/matrix/util"
  20. "github.com/scylladb/go-set/strset"
  21. )
  22. type task struct {
  23. Server string `json:"server"`
  24. Timeout int `json:"timeout"`
  25. NumberOfPings int `json:"numberofpings"`
  26. PacketInterval int `json:"packetinterval"`
  27. PacketSize int `json:"packetsize"`
  28. TypeOfService int `json:"typeofservice"` // Not used
  29. Retries int `json:"retries"` // Not used
  30. Poll int `json:"poll"`
  31. FailureRetests int `json:"failureretests"` // Not used
  32. RetestInterval int `json:"retestinterval"` // Not used
  33. HostNameLookupPreference string `json:"hostnamelookuppreference"` // Not used
  34. Description string `json:"description"` // Not used
  35. Rule string `json:"rule"`
  36. PerfRule string `json:"perfrule"`
  37. TaskTime int64 `json:"tasktime"`
  38. Indicator string `json:"indicator"`
  39. }
  40. type InputConfig struct {
  41. Poolsize int `toml:"poolsize"`
  42. Domain string `toml:"domain"`
  43. StatInterval int `toml:"stat_interval"`
  44. }
  45. type StatInfo struct {
  46. MinRtt time.Duration
  47. MaxRtt time.Duration
  48. AvgRtt time.Duration
  49. LossCount int
  50. Count int
  51. }
  52. type Input struct {
  53. *InputConfig
  54. ips []string
  55. statinfomutex sync.Mutex
  56. statinfo map[string]*StatInfo
  57. ipaddrs map[string]string
  58. subSize int
  59. workChan chan *task
  60. stopChan chan bool
  61. ds *utils.DataStat
  62. }
  63. var mcfg = cfg.MConfig()
  64. var protocol = mcfg.GetString("protocol", "udp")
  65. var allipsmutex sync.Mutex
  66. var allips = strset.New()
  67. var keepipset = strset.New()
  68. /*
  69. poolsize=1000 同时ping的不同目标地址个数
  70. count=5 每轮ping的次数,每轮次产生一次统计结果,并切换目标地址
  71. interval=1000 两次ping之间的间隔,单位毫秒
  72. size=64 每次ping发送字节数,48~8192
  73. timeout=2 ping超时,单位秒
  74. detect=1ms 自动发现可ping通地址,并追加到 hosts.txt 文件,设置发现间隔时间需指定单位,如 ms,毫秒,us,微妙等,默认 0,不进行发现处理
  75. */
  76. func main() {
  77. input := &Input{}
  78. input.statinfo = map[string]*StatInfo{}
  79. input.ipaddrs = map[string]string{}
  80. inputcfg := &InputConfig{
  81. Poolsize: 1000,
  82. StatInterval: 600,
  83. }
  84. for _, aips := range mcfg.GetStrings("keep") {
  85. keepipset.Add(strings.Split(aips, ",")...)
  86. }
  87. keepips := keepipset.List()
  88. inputcfg.Poolsize = mcfg.GetInt("poolsize", inputcfg.Poolsize)
  89. if detect_interval := mcfg.GetDuration("detect", 0); detect_interval != 0 {
  90. go detect(detect_interval)
  91. }
  92. fips := func() []string {
  93. xips := mcfg.GetStrings("ip|ping.ip", "")
  94. allipsmutex.Lock()
  95. for _, aips := range xips {
  96. allips.Add(strings.Split(aips, ",")...)
  97. }
  98. bs, _ := util.ReadFile("./hosts.txt")
  99. if len(bs) > 0 {
  100. xips := strings.Split(string(bs), "\n")
  101. for _, aips := range xips {
  102. allips.Add(strings.Split(aips, ",")...)
  103. }
  104. }
  105. if len(detectips) > 0 {
  106. for _, aips := range detectips {
  107. allips.Add(strings.Split(aips, ",")...)
  108. }
  109. util.WriteFile("./hosts.txt", []byte(string(bs)+"\n"+strings.Join(detectips, ",")), true)
  110. detectips = detectips[:0]
  111. }
  112. allips.Remove(keepips...)
  113. sips := allips.List()
  114. // sort.Sort(sort.Reverse(sort.StringSlice(sips)))
  115. rand.Shuffle(len(sips), func(i, j int) { sips[i], sips[j] = sips[j], sips[i] })
  116. allipsmutex.Unlock()
  117. return sips
  118. }
  119. input.ips = append(keepips, fips()...)
  120. if protocol != "udp" && protocol != "icmp" {
  121. protocol = "udp"
  122. }
  123. input.Init(inputcfg)
  124. go input.Run()
  125. go func() {
  126. last_count := 0
  127. t := time.NewTicker(1 * time.Second)
  128. for {
  129. select {
  130. case <-t.C:
  131. s := ""
  132. input.statinfomutex.Lock()
  133. ks := []string{}
  134. for k := range input.statinfo {
  135. ks = append(ks, k)
  136. }
  137. sort.Strings(ks)
  138. for i, k := range ks {
  139. v := input.statinfo[k]
  140. ip := input.ipaddrs[k]
  141. s += fmt.Sprintf("%-3d %-20s %15s : %-12s [%12s ~ %-12s] loss %d/%d\n", i, k, ip, v.AvgRtt, v.MinRtt, v.MaxRtt, v.LossCount, v.Count)
  142. }
  143. input.statinfomutex.Unlock()
  144. logger.Info("统计信息更新:", fmt.Sprint("\n", s))
  145. logger.Info(util.FormatDuration(time.Since(starttime)), "已经完成", pingcount, "次Ping操作,",
  146. "平均每秒", (int64(pingcount+1) * int64(time.Second) / int64(time.Since(starttime))), "次",
  147. "最近一秒", (pingcount - int32(last_count)), "次",
  148. "最大缓冲", icmp.MaxReceiveBufferUsed(),
  149. )
  150. last_count = int(pingcount)
  151. }
  152. }
  153. }()
  154. n := 0
  155. for {
  156. if n >= len(input.ips) {
  157. n = 0
  158. input.ips = fips()
  159. }
  160. ip := input.ips[n]
  161. n++
  162. //
  163. ip = strings.TrimSpace(ip)
  164. if ip != "" {
  165. atask := &task{
  166. Server: ip,
  167. Timeout: mcfg.GetInt("timeout", 2),
  168. NumberOfPings: mcfg.GetInt("count", 5), // 至少为2,小于2会导致不能正常结束
  169. PacketInterval: mcfg.GetInt("interval", 1000),
  170. PacketSize: mcfg.GetInt("size", 64),
  171. }
  172. input.workChan <- atask
  173. }
  174. // time.Sleep(1 * time.Millisecond)
  175. }
  176. }
  177. func (input *Input) Init(config interface{}) error {
  178. input.InputConfig = config.(*InputConfig)
  179. input.workChan = make(chan *task, input.Poolsize)
  180. input.stopChan = make(chan bool)
  181. input.subSize = runtime.GOMAXPROCS(0)
  182. return nil
  183. }
  184. func (input *Input) Run() (err error) {
  185. input.ds = utils.NewDataStat("service", "", input.StatInterval, input.Poolsize*2)
  186. defer input.ds.Close()
  187. go input.ds.Start()
  188. defer close(input.workChan)
  189. var wg sync.WaitGroup
  190. // Start worker
  191. // count := int32(0)
  192. // lpcmutex := sync.Mutex{}
  193. // lastprintcount := time.Now()
  194. for i := 0; i < input.Poolsize; i++ {
  195. go func(n int) {
  196. for t := range input.workChan {
  197. wg.Add(1)
  198. // Run task
  199. n := 1
  200. if keepipset.Has(t.Server) {
  201. n = math.MaxInt
  202. }
  203. var e error
  204. for ; e == nil && n > 0; n-- {
  205. e = input.send(t, n)
  206. }
  207. if e != nil {
  208. logger.Error("Send error:", e)
  209. input.ds.Send(1)
  210. } else {
  211. input.ds.Send(0)
  212. }
  213. wg.Done()
  214. // x := atomic.AddInt32(&count, 1)
  215. // lpcmutex.Lock()
  216. // printmsg := time.Since(lastprintcount) >= 1*time.Second
  217. // if printmsg {
  218. // lastprintcount = time.Now()
  219. // }
  220. // lpcmutex.Unlock()
  221. // if printmsg {
  222. // logger.Info("已经完成", x, "个目标的Ping操作")
  223. // }
  224. }
  225. }(i)
  226. }
  227. <-input.stopChan
  228. wg.Wait()
  229. return nil
  230. }
  231. var pingcount int32
  232. var starttime = time.Now()
  233. var printpingcountmutex sync.Mutex
  234. var printpingcounttime = time.Now()
  235. func (input *Input) send(t *task, workerNum int) error {
  236. hostname, _ := os.Hostname()
  237. var (
  238. status = "success"
  239. message = "Pings Complete"
  240. m = map[string]interface{}{
  241. "service": "icmp",
  242. "monitorHost": hostname,
  243. "host": t.Server,
  244. "pollInterval": t.Poll,
  245. "taskTime": t.TaskTime,
  246. "indicator": t.Indicator,
  247. }
  248. )
  249. pinger, err := probing.NewPinger(t.Server)
  250. if err != nil {
  251. status = "failure"
  252. message = err.Error()
  253. sips := strset.New(input.ips...)
  254. sips.Remove(t.Server)
  255. input.ips = sips.List()
  256. logger.Error(err)
  257. } else {
  258. /*
  259. https://stackoverflow.com/questions/41423637/go-ping-library-for-unprivileged-icmp-ping-in-golang/41425527#41425527
  260. This library attempts to send an "unprivileged" ping via UDP. On linux, this must be enabled by setting
  261. sudo sysctl -w net.ipv4.ping_group_range="0 2147483647"
  262. If you do not wish to do this, you can set pinger.SetPrivileged(true) and use setcap to allow your binary using go-ping to bind to raw sockets (or just run as super-user):
  263. setcap cap_net_raw=+ep /bin/goping-binary
  264. getcap /bin/goping-binary to validate
  265. */
  266. pinger.SetPrivileged(protocol == "icmp")
  267. if t.NumberOfPings > 0 {
  268. pinger.Count = t.NumberOfPings
  269. } else {
  270. pinger.Count = 1
  271. }
  272. if t.PacketInterval > 0 {
  273. pinger.Interval = time.Millisecond * time.Duration(t.PacketInterval)
  274. }
  275. if t.PacketSize > 0 {
  276. pinger.Size = t.PacketSize
  277. }
  278. if t.Timeout > 0 {
  279. pinger.Timeout = time.Second * time.Duration(t.Timeout)
  280. } else {
  281. pinger.Timeout = time.Second * time.Duration(pinger.Count)
  282. }
  283. var (
  284. consecutiveFailures int
  285. )
  286. var recvMutex sync.Mutex
  287. var recvList = map[int]int{}
  288. pinger.OnSend = func(pkt *probing.Packet) {
  289. recvMutex.Lock()
  290. if recvList[pkt.Seq] != 0 {
  291. println("并发控制有问题")
  292. }
  293. recvList[pkt.Seq]++
  294. recvMutex.Unlock()
  295. input.statinfomutex.Lock()
  296. si := input.statinfo[t.Server]
  297. if si == nil {
  298. si = &StatInfo{}
  299. input.statinfo[t.Server] = si
  300. }
  301. input.ipaddrs[t.Server] = pkt.IPAddr.String()
  302. si.Count++
  303. input.statinfomutex.Unlock()
  304. }
  305. pingMsg := fmt.Sprintf("\nWoker %d PING %s (%s):\n", workerNum, pinger.Addr(), pinger.IPAddr())
  306. pinger.OnRecv = func(pkt *probing.Packet) {
  307. recvMutex.Lock()
  308. recvList[pkt.Seq]++
  309. recvMutex.Unlock()
  310. s := fmt.Sprintf("%s %d bytes from %s: icmp_seq=%d time=%v\n",
  311. time.Now().Format("15:04:05.000"), pkt.Nbytes, pkt.IPAddr, pkt.Seq, pkt.Rtt)
  312. pingMsg += s
  313. // fmt.Print(s)
  314. // printpingcount
  315. atomic.AddInt32(&pingcount, 1)
  316. }
  317. pinger.OnDuplicateRecv = func(pkt *probing.Packet) {
  318. recvMutex.Lock()
  319. recvList[pkt.Seq]++
  320. recvMutex.Unlock()
  321. s := fmt.Sprintf("%s %d bytes from %s: icmp_seq=%d time=%v (DUP!)\n",
  322. time.Now().Format("15:04:05.000"), pkt.Nbytes, pkt.IPAddr, pkt.Seq, pkt.Rtt)
  323. pingMsg += s
  324. // fmt.Print(s)
  325. }
  326. pinger.OnFinish = func(stats *probing.Statistics) {
  327. m["numberPackets"] = stats.PacketsSent
  328. m["averageRTT"] = stats.AvgRtt.Milliseconds()
  329. if stats.PacketsSent == 0 {
  330. m["respondPercent"] = 1
  331. } else {
  332. m["respondPercent"] = stats.PacketsRecv / stats.PacketsSent * 100
  333. }
  334. //m["failureRetests"] = ?
  335. s := fmt.Sprintf("--- %s ping statistics ---\n", stats.Addr)
  336. s += fmt.Sprintf("%d packets transmitted, %d packets received, %v%% packet loss\n",
  337. stats.PacketsSent, stats.PacketsRecv, stats.PacketLoss)
  338. s += fmt.Sprintf("round-trip min/avg/max/stddev = %v/%v/%v/%v\n",
  339. stats.MinRtt, stats.AvgRtt, stats.MaxRtt, stats.StdDevRtt)
  340. pingMsg += s
  341. // fmt.Print(s)
  342. input.statinfomutex.Lock()
  343. si := input.statinfo[t.Server]
  344. if si == nil {
  345. si = &StatInfo{
  346. MinRtt: stats.MinRtt,
  347. MaxRtt: stats.MaxRtt,
  348. AvgRtt: stats.AvgRtt,
  349. LossCount: 0,
  350. Count: 0,
  351. }
  352. input.statinfo[t.Server] = si
  353. input.ipaddrs[t.Server] = stats.IPAddr.String()
  354. }
  355. if stats.MinRtt > 0 && (si.MinRtt == 0 || stats.MinRtt < si.MinRtt) {
  356. si.MinRtt = stats.MinRtt
  357. }
  358. if stats.MaxRtt > si.MaxRtt {
  359. si.MaxRtt = stats.MaxRtt
  360. }
  361. si.AvgRtt = stats.AvgRtt
  362. si.LossCount += stats.PacketsSent - stats.PacketsRecv
  363. input.statinfomutex.Unlock()
  364. }
  365. m["requestTime"] = time.Now().UnixNano() / int64(time.Millisecond)
  366. if err = pinger.Run(); err != nil {
  367. status = "failure"
  368. message = err.Error()
  369. logger.Errorf("Ping error: %v", err)
  370. } else {
  371. }
  372. m["responseTime"] = time.Now().UnixNano() / int64(time.Millisecond)
  373. var failCount, totalFailCount int
  374. recvMutex.Lock()
  375. for i := range recvList {
  376. if recvList[i] < 2 {
  377. failCount++
  378. message = "Packet loss"
  379. totalFailCount++
  380. } else {
  381. failCount = 0
  382. }
  383. if failCount > consecutiveFailures {
  384. consecutiveFailures = failCount
  385. }
  386. pingMsg += fmt.Sprintf("icmp_seq:%d %t\n", i, (recvList[i] >= 2))
  387. }
  388. // logger.Debug(pingMsg)
  389. m["consecutiveFailures"] = consecutiveFailures
  390. if totalFailCount == len(recvList) {
  391. message = "ICMP echo failed"
  392. }
  393. recvMutex.Unlock()
  394. }
  395. // Special
  396. m["returnStatus"] = status
  397. m["message"] = message
  398. b, err := json.Marshal(m)
  399. if err != nil {
  400. logger.Fatal(err)
  401. }
  402. protocolMsg := map[string]interface{}{
  403. "protocol": true,
  404. "output": b,
  405. "attr": map[string]string{"previous_key": input.Domain + "_" + t.Server},
  406. }
  407. b, err = json.Marshal(protocolMsg)
  408. if err != nil {
  409. logger.Fatal(err)
  410. }
  411. return nil
  412. }
  413. var detectips = []string{}
  414. func detect(detect_interval time.Duration) {
  415. t := time.NewTicker(detect_interval)
  416. for {
  417. <-t.C
  418. randip := fmt.Sprintf("%d.%d.%d.%d", 1+rand.Intn(254), 1+rand.Intn(254), 1+rand.Intn(254), 1+rand.Intn(254))
  419. allipsmutex.Lock()
  420. has := allips.Has(randip)
  421. allipsmutex.Unlock()
  422. if !has {
  423. if detectip(randip) {
  424. allipsmutex.Lock()
  425. detectips = append(detectips, randip)
  426. allipsmutex.Unlock()
  427. }
  428. }
  429. }
  430. }
  431. func detectip(addr string) (ok bool) {
  432. pinger, err := probing.NewPinger(addr)
  433. if err != nil {
  434. return false
  435. }
  436. pinger.SetPrivileged(protocol == "icmp")
  437. pinger.Count = 1
  438. pinger.Interval = 1 * time.Nanosecond
  439. pinger.Size = 32
  440. pinger.Timeout = 1 * time.Second
  441. pinger.OnRecv = func(pkt *probing.Packet) {
  442. ok = true
  443. }
  444. pinger.Run()
  445. return
  446. }