worker.lua 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. local g = require('g')
  2. -- run in master worker
  3. if ngx.worker.id() ~= 0 then
  4. return
  5. end
  6. local function buildDevTrafficFn(dev)
  7. local regex = dev ..
  8. [[:\s+(\d+)\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+(\d+)]]
  9. -- 0 1 2 3 4 5 6 7 | 8
  10. -- eth0: bytes packets errs drop fifo frame compress multi| bytes
  11. local lastRxBytes = 0
  12. local lastTxBytes = 0
  13. return function(str)
  14. local m = ngx.re.match(str, regex, 'oi')
  15. if m == nil then
  16. return '0,0'
  17. end
  18. local sRxBytes = m[1]
  19. local sTxBytes = m[2]
  20. if sTxBytes == nil then
  21. return '0,0'
  22. end
  23. local nRxBytes = tonumber(sRxBytes)
  24. local nTxBytes = tonumber(sTxBytes)
  25. local rxBPS = nRxBytes - lastRxBytes
  26. local txBPS = nTxBytes - lastTxBytes
  27. lastRxBytes = nRxBytes
  28. lastTxBytes = nTxBytes
  29. return rxBPS .. ',' .. txBPS
  30. end
  31. end
  32. local fileStat = io.open('/proc/net/dev')
  33. if fileStat == nil then
  34. ngx.log(ngx.ERR, 'open `/proc/net/dev` fail')
  35. return
  36. end
  37. local firstRun = true
  38. local getDevTraffic = buildDevTrafficFn('eth0')
  39. local function updateTraffic()
  40. local r, err = fileStat:seek('set')
  41. local out = fileStat:read('*all')
  42. local traffDev = getDevTraffic(out)
  43. if firstRun then
  44. firstRun = false
  45. return
  46. end
  47. g.syn()
  48. local traffHttp = g.update()
  49. local stat = traffDev .. ',' .. traffHttp
  50. g.setStat(stat)
  51. end
  52. ngx.timer.every(1, updateTraffic)