浏览代码

增加网络状态的 lua

zjcqoo 6 年之前
父节点
当前提交
043597c7c4
共有 3 个文件被更改,包括 113 次插入0 次删除
  1. 37 0
      lua/g.lua
  2. 6 0
      lua/init.lua
  3. 70 0
      lua/worker.lua

+ 37 - 0
lua/g.lua

@@ -0,0 +1,37 @@
+local _M = {}
+local traff = ngx.shared.traff
+
+local nReq = 0
+
+
+function _M.inc()
+  nReq = nReq + 1
+end
+
+function _M.syn()
+  traff:incr('nReq', nReq)
+  nReq = 0
+end
+
+function _M.update()
+  local nReq = traff:get('nReq')
+  traff:set('nReq', 0)
+  return nReq
+end
+
+function _M.getStat()
+  return traff:get('stat')
+end
+
+function _M.setStat(stat)
+  return traff:set('stat', stat)
+end
+
+function _M.reset()
+  if traff:get('nReq') == nil then
+    traff:add('nReq', 0)
+    traff:add('stat', '')
+  end
+end
+
+return _M

+ 6 - 0
lua/init.lua

@@ -0,0 +1,6 @@
+local traff = ngx.shared.traff
+
+if traff:get('nReq') == nil then
+  traff:add('nReq', 0)
+  traff:add('stat', '')
+end

+ 70 - 0
lua/worker.lua

@@ -0,0 +1,70 @@
+local g = require('g')
+
+-- run in master worker
+if ngx.worker.id() ~= 0 then
+  return
+end
+
+local function getDevTraffic(dev)
+  --       0     1       2    3    4    5     6          7
+  -- eth0: bytes packets errs drop fifo frame compressed multicast
+  --       bytes packets errs drop fifo colls carrier    compressed
+  local regex = dev .. ':%s+(%d+)%s+' .. ('%d+%s+'):rep(7) .. '(%d+)'
+
+  local lastRxBytes = 0
+  local lastTxBytes = 0
+
+  return function(str)
+    local
+      sRxBytes,
+      sTxBytes
+    = str:match(regex)
+
+    if sTxBytes == nil then
+      return '0,0'
+    end
+
+    local nRxBytes = tonumber(sRxBytes)
+    local nTxBytes = tonumber(sTxBytes)
+
+    local rxBPS = nRxBytes - lastRxBytes
+    local txBPS = nTxBytes - lastTxBytes
+
+    lastRxBytes = nRxBytes
+    lastTxBytes = nTxBytes
+
+    return rxBPS .. ',' .. txBPS
+  end
+end
+
+
+local fileStat = io.open('/proc/net/dev')
+if fileStat == nil then
+  ngx.log(ngx.ERR, 'open `/proc/net/dev` fail')
+  return
+end
+
+local firstRun = true
+local getDevTraffic = getDevTraffic('eth0')
+
+
+local function updateTraffic()
+  local r, err = fileStat:seek('set')
+  local out = fileStat:read('*all')
+
+  local traffDev = getDevTraffic(out)
+
+  if firstRun then
+    firstRun = false
+    return
+  end
+
+  g.syn()
+
+  local traffHttp = g.update()
+  local stat = traffDev .. ',' .. traffHttp
+
+  g.setStat(stat)
+end
+
+ngx.timer.every(1, updateTraffic)