ping.go 12 KB

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