mirror of
https://github.com/caiwx86/small-packages.git
synced 2026-09-14 04:14:40 +08:00
update 2026-05-27 19:55:46
This commit is contained in:
@@ -1 +0,0 @@
|
||||
return require("internet-detector.main")
|
||||
@@ -1,806 +0,0 @@
|
||||
|
||||
local dirent = require("posix.dirent")
|
||||
local fcntl = require("posix.fcntl")
|
||||
local signal = require("posix.signal")
|
||||
local socket = require("posix.sys.socket")
|
||||
local stat = require("posix.sys.stat")
|
||||
local syslog = require("posix.syslog")
|
||||
local time = require("posix.time")
|
||||
local unistd = require("posix.unistd")
|
||||
local uci = require("uci")
|
||||
|
||||
-- Default settings
|
||||
|
||||
local InternetDetector = {
|
||||
appName = "internet-detector",
|
||||
libDir = "/usr/lib/lua",
|
||||
logLevels = {
|
||||
emerg = { level = syslog.LOG_EMERG, num = 0 },
|
||||
alert = { level = syslog.LOG_ALERT, num = 1 },
|
||||
crit = { level = syslog.LOG_CRIT, num = 2 },
|
||||
err = { level = syslog.LOG_ERR, num = 3 },
|
||||
warning = { level = syslog.LOG_WARNING, num = 4 },
|
||||
notice = { level = syslog.LOG_NOTICE, num = 5 },
|
||||
info = { level = syslog.LOG_INFO, num = 6 },
|
||||
debug = { level = syslog.LOG_DEBUG, num = 7 },
|
||||
},
|
||||
pingCmd = "/bin/ping",
|
||||
pingParams = "-c 1",
|
||||
curlExec = "/usr/bin/curl",
|
||||
curlParams = '-s -g --no-keepalive --head --user-agent "Mozilla/5.0 (X11; Linux x86_64; rv:142.0) Gecko/20100101 Firefox/142.0"',
|
||||
mode = 0, -- 0: disabled, 1: Service, 2: UI detector
|
||||
loggingLevel = 6,
|
||||
hostname = "OpenWrt",
|
||||
uiRunTime = 30,
|
||||
noModules = false,
|
||||
uiAvailModules = { mod_public_ip = true },
|
||||
debug = false,
|
||||
serviceConfig = {
|
||||
hosts = {
|
||||
[1] = "8.8.8.8",
|
||||
[2] = "1.1.1.1",
|
||||
},
|
||||
urls = {
|
||||
[1] = "https://www.google.com",
|
||||
},
|
||||
check_type = 0, -- 0: TCP, 1: ICMP
|
||||
tcp_port = 53,
|
||||
icmp_packet_size = 56,
|
||||
interval_up = 30,
|
||||
interval_down = 5,
|
||||
connection_attempts = 2,
|
||||
connection_timeout = 2,
|
||||
proxy_type = nil,
|
||||
proxy_host = nil,
|
||||
proxy_port = nil,
|
||||
proxy_user = nil,
|
||||
proxy_passwd = nil,
|
||||
iface = nil,
|
||||
instance = nil,
|
||||
},
|
||||
modules = {},
|
||||
parsedHosts = {},
|
||||
proxyAuthString = "",
|
||||
proxyString = "",
|
||||
uiCounter = 0,
|
||||
pidFile = nil,
|
||||
statusFile = nil,
|
||||
}
|
||||
InternetDetector.configDir = string.format("/etc/%s", InternetDetector.appName)
|
||||
InternetDetector.modulesDir = string.format(
|
||||
"%s/%s/modules", InternetDetector.libDir, InternetDetector.appName)
|
||||
InternetDetector.commonDir = string.format("/tmp/run/%s", InternetDetector.appName)
|
||||
InternetDetector.appNamePattern = InternetDetector.appName:gsub("-", "%%-")
|
||||
InternetDetector.pidFilePattern = "^" .. InternetDetector.appNamePattern .. ".-%.pid$"
|
||||
|
||||
-- Loading settings from UCI
|
||||
|
||||
local uciCursor = uci.cursor()
|
||||
local mode, err = uciCursor:get(InternetDetector.appName, "config", "mode")
|
||||
if mode ~= nil then
|
||||
InternetDetector.mode = tonumber(mode)
|
||||
elseif err then
|
||||
io.stderr:write(string.format("Error: %s\n", err))
|
||||
end
|
||||
local loggingLevel, err = uciCursor:get(InternetDetector.appName, "config", "logging_level")
|
||||
if loggingLevel ~= nil then
|
||||
InternetDetector.loggingLevel = tonumber(loggingLevel)
|
||||
elseif err then
|
||||
io.stderr:write(string.format("Error: %s\n", err))
|
||||
end
|
||||
local hostname, err = uciCursor:get("system", "@[0]", "hostname")
|
||||
if hostname ~= nil then
|
||||
InternetDetector.hostname = hostname
|
||||
elseif err then
|
||||
io.stderr:write(string.format("Error: %s\n", err))
|
||||
end
|
||||
|
||||
function InternetDetector:prequire(package)
|
||||
local ok, pkg = pcall(require, package)
|
||||
return ok and pkg
|
||||
end
|
||||
|
||||
function InternetDetector:loadInstanceConfig(instance)
|
||||
local sections = uciCursor:get_all(self.appName)
|
||||
local t = sections[instance]
|
||||
if t then
|
||||
for k, v in pairs(t) do
|
||||
if type(v) == "string" and v:match("^[%d]+$") then
|
||||
v = tonumber(v)
|
||||
end
|
||||
self.serviceConfig[k] = v
|
||||
end
|
||||
self.serviceConfig.instance = instance
|
||||
self.serviceConfig.instanceNum = t[".index"]
|
||||
return true
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
function InternetDetector:writeValueToFile(filePath, str)
|
||||
local retValue = false
|
||||
local fh = io.open(filePath, "w")
|
||||
if fh then
|
||||
fh:setvbuf("no")
|
||||
fh:write(string.format("%s\n", str))
|
||||
fh:close()
|
||||
retValue = true
|
||||
end
|
||||
return retValue
|
||||
end
|
||||
|
||||
function InternetDetector:readValueFromFile(filePath)
|
||||
local retValue
|
||||
local fh = io.open(filePath, "r")
|
||||
if fh then
|
||||
retValue = fh:read("*l")
|
||||
fh:close()
|
||||
end
|
||||
return retValue
|
||||
end
|
||||
|
||||
function InternetDetector:statusJson(inet, instance, t)
|
||||
local lines = { [1] = string.format(
|
||||
'{"instance":"%s","num":"%d","inet":%d',
|
||||
instance,
|
||||
self.serviceConfig.instanceNum,
|
||||
inet)}
|
||||
if t then
|
||||
for k, v in pairs(t) do
|
||||
lines[#lines + 1] = string.format('"%s":"%s"', k, v)
|
||||
end
|
||||
end
|
||||
return table.concat(lines, ",") .. "}"
|
||||
end
|
||||
|
||||
function InternetDetector:writeLogMessage(level, msg)
|
||||
local levelItem = self.logLevels[level]
|
||||
local levelValue = (levelItem and levelItem.level) or self.logLevels["info"].level
|
||||
local num = (levelItem and levelItem.num) or self.logLevels["info"].num
|
||||
if num <= self.loggingLevel then
|
||||
syslog.syslog(levelValue, string.format(
|
||||
"%s: %s", self.serviceConfig.instance or "", msg))
|
||||
end
|
||||
end
|
||||
|
||||
function InternetDetector:debugOutput(msg)
|
||||
if self.debug then
|
||||
io.stdout:write(string.format("[%s] %s\n", os.date("%Y.%m.%d-%H:%M:%S"), msg))
|
||||
io.stdout:flush()
|
||||
end
|
||||
end
|
||||
|
||||
function InternetDetector:loadModules()
|
||||
self.modules = {}
|
||||
local ok, modulesDir = pcall(dirent.files, self.modulesDir)
|
||||
if ok then
|
||||
for item in modulesDir do
|
||||
if item:match("^mod_") then
|
||||
local modName = item:gsub("%.lua$", "")
|
||||
if self.noModules and not self.uiAvailModules[modName] then
|
||||
else
|
||||
local modConfig = {}
|
||||
for k, v in pairs(self.serviceConfig) do
|
||||
if k:match("^" .. modName) then
|
||||
modConfig[k:gsub("^" .. modName .. "_", "")] = v
|
||||
end
|
||||
end
|
||||
if modConfig.enabled == 1 then
|
||||
local m
|
||||
if self.debug then
|
||||
m = require(string.format("%s.modules.%s", self.appName, modName))
|
||||
else
|
||||
m = self:prequire(string.format("%s.modules.%s", self.appName, modName))
|
||||
end
|
||||
if m then
|
||||
m.config = self
|
||||
m.syslog = function(level, msg) self:writeLogMessage(level, msg) end
|
||||
m.debugOutput = function(msg) self:debugOutput(msg) end
|
||||
m.writeValue = function(filePath, str) return self:writeValueToFile(filePath, str) end
|
||||
m.readValue = function(filePath) return self:readValueFromFile(filePath) end
|
||||
m:init(modConfig)
|
||||
self.modules[#self.modules + 1] = m
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
table.sort(self.modules, function(a, b) return a.runPrio < b.runPrio end)
|
||||
end
|
||||
end
|
||||
|
||||
function InternetDetector:parseHost(host)
|
||||
local addr, port = host:match("^([^%[%]:]+):?(%d?%d?%d?%d?%d?)$")
|
||||
if not addr then
|
||||
addr, port = host:match("^%[?([^%[%]]+)%]?:?(%d?%d?%d?%d?%d?)$")
|
||||
end
|
||||
return addr, tonumber(port)
|
||||
end
|
||||
|
||||
function InternetDetector:parseHosts()
|
||||
self.parsedHosts = {}
|
||||
for k, v in ipairs(self.serviceConfig.hosts) do
|
||||
local addr, port = self:parseHost(v)
|
||||
self.parsedHosts[k] = { addr = addr, port = port }
|
||||
end
|
||||
end
|
||||
|
||||
function InternetDetector:parseUrls()
|
||||
self.parsedHosts = {}
|
||||
for k, v in ipairs(self.serviceConfig.urls) do
|
||||
self.parsedHosts[k] = { addr = v }
|
||||
end
|
||||
end
|
||||
|
||||
function InternetDetector:pingHost(host)
|
||||
local ping = string.format(
|
||||
"%s %s -W %d -s %d%s %s > /dev/null 2>&1",
|
||||
self.pingCmd,
|
||||
self.pingParams,
|
||||
self.serviceConfig.connection_timeout,
|
||||
self.serviceConfig.icmp_packet_size,
|
||||
self.serviceConfig.iface and (" -I " .. self.serviceConfig.iface) or "",
|
||||
host
|
||||
)
|
||||
local retCode = os.execute(ping)
|
||||
|
||||
self:debugOutput(string.format(
|
||||
"--- Ping ---\ntime = %s\n%s\nretCode = %s", os.time(), ping, retCode))
|
||||
|
||||
return retCode
|
||||
end
|
||||
|
||||
function InternetDetector:TCPConnectionToHost(host, port)
|
||||
local retCode = 1
|
||||
local saTable, errMsg, errNum = socket.getaddrinfo(host, port or self.serviceConfig.tcp_port)
|
||||
|
||||
if not saTable then
|
||||
self:debugOutput(string.format(
|
||||
"GETADDRINFO ERROR: %s, %s", errMsg, errNum))
|
||||
else
|
||||
local family = saTable[1].family
|
||||
|
||||
if family then
|
||||
local sock, errMsg, errNum = socket.socket(family, socket.SOCK_STREAM, 0)
|
||||
|
||||
if not sock then
|
||||
self:debugOutput(string.format(
|
||||
"SOCKET ERROR: %s, %s", errMsg, errNum))
|
||||
return retCode
|
||||
end
|
||||
|
||||
socket.setsockopt(sock, socket.SOL_SOCKET,
|
||||
socket.SO_SNDTIMEO, self.serviceConfig.connection_timeout, 0)
|
||||
socket.setsockopt(sock, socket.SOL_SOCKET,
|
||||
socket.SO_RCVTIMEO, self.serviceConfig.connection_timeout, 0)
|
||||
|
||||
if self.serviceConfig.iface then
|
||||
local ok, errMsg, errNum = socket.setsockopt(sock, socket.SOL_SOCKET,
|
||||
socket.SO_BINDTODEVICE, self.serviceConfig.iface)
|
||||
if not ok then
|
||||
self:debugOutput(string.format(
|
||||
"SOCKET ERROR: %s, %s", errMsg, errNum))
|
||||
|
||||
unistd.close(sock)
|
||||
return retCode
|
||||
end
|
||||
end
|
||||
|
||||
local success = socket.connect(sock, saTable[1])
|
||||
|
||||
if self.debug then
|
||||
if not success then
|
||||
self:debugOutput(string.format(
|
||||
"SOCKET CONNECT ERROR: %s", tostring(success)))
|
||||
end
|
||||
local sockTable, err_s, e_s = socket.getsockname(sock)
|
||||
local peerTable, err_p, e_p = socket.getpeername(sock)
|
||||
if not sockTable then
|
||||
sockTable = {}
|
||||
self:debugOutput(
|
||||
string.format("SOCKET ERROR: %s, %s", err_s, e_s))
|
||||
end
|
||||
if not peerTable then
|
||||
peerTable = {}
|
||||
self:debugOutput(
|
||||
string.format("SOCKET ERROR: %s, %s", err_p, e_p))
|
||||
end
|
||||
self:debugOutput(string.format(
|
||||
"--- TCP ---\ntime = %s\nconnection_timeout = %s\niface = %s\nhost:port = [%s]:%s\nsockname = [%s]:%s\npeername = [%s]:%s\nsuccess = %s",
|
||||
os.time(),
|
||||
self.serviceConfig.connection_timeout,
|
||||
tostring(self.serviceConfig.iface),
|
||||
host,
|
||||
port or self.serviceConfig.tcp_port,
|
||||
tostring(sockTable.addr),
|
||||
tostring(sockTable.port),
|
||||
tostring(peerTable.addr),
|
||||
tostring(peerTable.port),
|
||||
tostring(success))
|
||||
)
|
||||
end
|
||||
|
||||
socket.shutdown(sock, socket.SHUT_RDWR)
|
||||
unistd.close(sock)
|
||||
retCode = success and 0 or 1
|
||||
end
|
||||
end
|
||||
return retCode
|
||||
end
|
||||
|
||||
function InternetDetector:httpRequest(url)
|
||||
local retCode = 1, data
|
||||
local curl = string.format(
|
||||
'%s%s%s --connect-timeout %s %s "%s"; printf "\n$?";',
|
||||
self.curlExec,
|
||||
self.serviceConfig.iface and (" --interface " .. self.serviceConfig.iface) or "",
|
||||
self.proxyString,
|
||||
self.serviceConfig.connection_timeout,
|
||||
self.curlParams,
|
||||
url
|
||||
)
|
||||
local fh = io.popen(curl, "r")
|
||||
if fh then
|
||||
data = fh:read("*a")
|
||||
fh:close()
|
||||
if data ~= nil then
|
||||
local s, e = data:find("[0-9]+\n?$")
|
||||
retCode = tonumber(data:sub(s))
|
||||
data = data:sub(0, s - 2)
|
||||
if not data or data == "" then
|
||||
data = nil
|
||||
end
|
||||
end
|
||||
else
|
||||
retCode = 1
|
||||
end
|
||||
|
||||
self:debugOutput(string.format(
|
||||
"--- Curl ---\ntime = %s\n%s\nretCode = %s\ndata = [\n%s]\n",
|
||||
os.time(),
|
||||
curl,
|
||||
retCode,
|
||||
tostring(data)))
|
||||
|
||||
return retCode, data
|
||||
end
|
||||
|
||||
function InternetDetector:getHTTPCode(data)
|
||||
local httpCode
|
||||
local respHeader = data:match("^HTTP/[^%c]+")
|
||||
if respHeader then
|
||||
httpCode = respHeader:match("%d%d%d")
|
||||
end
|
||||
return tonumber(httpCode)
|
||||
end
|
||||
|
||||
function InternetDetector:checkURL(url)
|
||||
local httpCode
|
||||
local retCode, data = self:httpRequest(url)
|
||||
if retCode == 0 and data then
|
||||
httpCode = self:getHTTPCode(data)
|
||||
end
|
||||
return (httpCode ~= 200) and 1 or 0
|
||||
end
|
||||
|
||||
function InternetDetector:exit()
|
||||
for _, e in ipairs(self.modules) do
|
||||
e:onExit()
|
||||
end
|
||||
self:removeProcessFiles()
|
||||
if self.loggingLevel > 0 then
|
||||
self:writeLogMessage("info", "stoped")
|
||||
syslog.closelog()
|
||||
end
|
||||
os.exit(0)
|
||||
end
|
||||
|
||||
function InternetDetector:resetUiCounter(signo)
|
||||
self.uiCounter = 0
|
||||
end
|
||||
|
||||
function InternetDetector:mainLoop()
|
||||
signal.signal(signal.SIGTERM, function(signo) self:exit(signo) end)
|
||||
signal.signal(signal.SIGINT, function(signo) self:exit(signo) end)
|
||||
signal.signal(signal.SIGQUIT, function(signo) self:exit(signo) end)
|
||||
signal.signal(signal.SIGUSR1, function(signo) self:resetUiCounter(signo) end)
|
||||
|
||||
local mTimeNow, mTimeDiff, mLastTime, uiTimeNow, uiLastTime
|
||||
local lastStatus = -1
|
||||
local currentStatus = -1
|
||||
local interval = self.serviceConfig.interval_up
|
||||
local modulesStatus = {}
|
||||
local counter = 0
|
||||
local inetChecked = false
|
||||
local checking = false
|
||||
local hostNum = 1
|
||||
local attempt = 1
|
||||
|
||||
local checkFunc = self.TCPConnectionToHost
|
||||
if self.serviceConfig.check_type == 1 then
|
||||
checkFunc = self.pingHost
|
||||
self:parseHosts()
|
||||
elseif self.serviceConfig.check_type == 2 then
|
||||
checkFunc = self.checkURL
|
||||
self:parseUrls()
|
||||
if (self.serviceConfig.proxy_type and self.serviceConfig.proxy_host and
|
||||
self.serviceConfig.proxy_port) then
|
||||
if self.serviceConfig.proxy_user and self.serviceConfig.proxy_passwd then
|
||||
self.proxyAuthString = string.format(
|
||||
' --proxy-user "%s:%s"',
|
||||
self.serviceConfig.proxy_user,
|
||||
self.serviceConfig.proxy_passwd)
|
||||
end
|
||||
self.proxyString = string.format(
|
||||
" --proxy %s://%s:%d%s",
|
||||
self.serviceConfig.proxy_type,
|
||||
self.serviceConfig.proxy_host,
|
||||
self.serviceConfig.proxy_port,
|
||||
self.proxyAuthString)
|
||||
end
|
||||
else
|
||||
self:parseHosts()
|
||||
end
|
||||
|
||||
self:writeValueToFile(
|
||||
self.statusFile, self:statusJson(currentStatus, self.serviceConfig.instance))
|
||||
|
||||
while true do
|
||||
if counter == 0 or counter >= interval then
|
||||
checking = true
|
||||
end
|
||||
|
||||
inetChecked = false
|
||||
|
||||
if checking then
|
||||
local newStatus = 1
|
||||
if hostNum <= #self.parsedHosts then
|
||||
if attempt <= self.serviceConfig.connection_attempts then
|
||||
local addr = self.parsedHosts[hostNum].addr
|
||||
local port = self.parsedHosts[hostNum].port
|
||||
local retCode = 1
|
||||
if self.debug then
|
||||
retCode = checkFunc(self, addr, port)
|
||||
else
|
||||
local ok, status = pcall(checkFunc, self, addr, port)
|
||||
if ok then
|
||||
retCode = status
|
||||
else
|
||||
self:writeLogMessage("err", string.format(
|
||||
"An error occurred while checking the host %s: %s",
|
||||
tostring(addr),
|
||||
tostring(status))
|
||||
)
|
||||
end
|
||||
end
|
||||
if retCode == 0 then
|
||||
attempt = 1
|
||||
hostNum = 1
|
||||
checking = false
|
||||
newStatus = 0
|
||||
counter = 0
|
||||
inetChecked = true
|
||||
else
|
||||
attempt = attempt + 1
|
||||
if attempt > self.serviceConfig.connection_attempts then
|
||||
attempt = 1
|
||||
hostNum = hostNum + 1
|
||||
end
|
||||
end
|
||||
else
|
||||
attempt = 1
|
||||
hostNum = hostNum + 1
|
||||
end
|
||||
if hostNum > #self.parsedHosts then
|
||||
hostNum = 1
|
||||
checking = false
|
||||
counter = 0
|
||||
inetChecked = true
|
||||
end
|
||||
else
|
||||
hostNum = 1
|
||||
checking = false
|
||||
counter = 0
|
||||
inetChecked = true
|
||||
end
|
||||
|
||||
if inetChecked then
|
||||
currentStatus = newStatus
|
||||
if not stat.stat(self.statusFile) then
|
||||
self:writeValueToFile(self.statusFile, self:statusJson(
|
||||
currentStatus, self.serviceConfig.instance))
|
||||
end
|
||||
if currentStatus == 0 then
|
||||
interval = self.serviceConfig.interval_up
|
||||
if currentStatus ~= lastStatus then
|
||||
self:writeValueToFile(self.statusFile, self:statusJson(
|
||||
currentStatus, self.serviceConfig.instance))
|
||||
self:writeLogMessage("notice", "Connected")
|
||||
end
|
||||
elseif currentStatus == 1 then
|
||||
interval = self.serviceConfig.interval_down
|
||||
if currentStatus ~= lastStatus then
|
||||
self:writeValueToFile(self.statusFile, self:statusJson(
|
||||
currentStatus, self.serviceConfig.instance))
|
||||
self:writeLogMessage("notice", "Disconnected")
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
mTimeDiff = 0
|
||||
for _, e in ipairs(self.modules) do
|
||||
mTimeNow = time.clock_gettime(time.CLOCK_MONOTONIC).tv_sec
|
||||
if mLastTime then
|
||||
mTimeDiff = mTimeDiff + mTimeNow - mLastTime
|
||||
else
|
||||
mTimeDiff = 1
|
||||
end
|
||||
mLastTime = mTimeNow
|
||||
|
||||
if self.debug then
|
||||
e:run(currentStatus, lastStatus, mTimeDiff, mTimeNow, inetChecked)
|
||||
else
|
||||
local ok, err = pcall(e.run, e, currentStatus, lastStatus, mTimeDiff, mTimeNow, inetChecked)
|
||||
if not ok then
|
||||
self:writeLogMessage("err", string.format(
|
||||
"%s: Module error: %s", e.name, tostring(err)))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local modStatusChanged = false
|
||||
for k, v in ipairs(self.modules) do
|
||||
if modulesStatus[v.name] ~= v.status then
|
||||
modulesStatus[v.name] = v.status
|
||||
modStatusChanged = true
|
||||
end
|
||||
end
|
||||
if modStatusChanged and next(modulesStatus) then
|
||||
self:writeValueToFile(self.statusFile, self:statusJson(
|
||||
currentStatus, self.serviceConfig.instance, modulesStatus))
|
||||
end
|
||||
|
||||
unistd.sleep(1)
|
||||
|
||||
if not checking then
|
||||
lastStatus = currentStatus
|
||||
counter = counter + 1
|
||||
end
|
||||
|
||||
if self.mode == 2 then
|
||||
uiTimeNow = time.clock_gettime(time.CLOCK_MONOTONIC).tv_sec
|
||||
if uiLastTime then
|
||||
self.uiCounter = self.uiCounter + uiTimeNow - uiLastTime
|
||||
else
|
||||
self.uiCounter = self.uiCounter + 1
|
||||
end
|
||||
uiLastTime = uiTimeNow
|
||||
if self.uiCounter >= self.uiRunTime then
|
||||
self:exit(signal.SIGTERM)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function InternetDetector:removeProcessFiles()
|
||||
os.remove(self.statusFile)
|
||||
os.remove(self.pidFile)
|
||||
end
|
||||
|
||||
function InternetDetector:status()
|
||||
local ok, commonDir = pcall(dirent.files, self.commonDir)
|
||||
if ok then
|
||||
for item in commonDir do
|
||||
if item:match(self.pidFilePattern) then
|
||||
return "running"
|
||||
end
|
||||
end
|
||||
end
|
||||
return "stoped"
|
||||
end
|
||||
|
||||
function InternetDetector:inetStatus()
|
||||
local inetStat = '{"instances":[]}'
|
||||
local ok, commonDir = pcall(dirent.files, self.commonDir)
|
||||
if ok then
|
||||
local statusFilePattern = "^" .. self.appNamePattern .. ".-%.status$"
|
||||
local lines = {}
|
||||
for item in commonDir do
|
||||
if item:match(statusFilePattern) then
|
||||
lines[#lines + 1] = self:readValueFromFile(
|
||||
string.format("%s/%s", self.commonDir, item))
|
||||
end
|
||||
end
|
||||
inetStat = '{"instances":[' .. table.concat(lines, ",") .. "]}"
|
||||
end
|
||||
return inetStat
|
||||
end
|
||||
|
||||
function InternetDetector:stopInstance(pidFile)
|
||||
local retVal = false, pidValue
|
||||
if stat.stat(pidFile) then
|
||||
pidValue = self:readValueFromFile(pidFile)
|
||||
if pidValue then
|
||||
local ok, errMsg, errNum
|
||||
for i = 0, 10 do
|
||||
ok, errMsg, errNum = signal.kill(tonumber(pidValue), signal.SIGTERM)
|
||||
if ok then
|
||||
break
|
||||
end
|
||||
end
|
||||
if not ok then
|
||||
io.stderr:write(string.format(
|
||||
'Process stopping error: %s (%s). PID: "%s"\n', errMsg, errNum, pidValue))
|
||||
end
|
||||
if errNum == 3 then
|
||||
os.remove(pidFile)
|
||||
end
|
||||
retVal = true
|
||||
else
|
||||
os.remove(pidFile)
|
||||
end
|
||||
end
|
||||
if not pidValue then
|
||||
io.stderr:write(
|
||||
string.format('PID file "%s" does not exists. Is the %s not running?\n',
|
||||
pidFile, self.appName))
|
||||
end
|
||||
return retVal
|
||||
end
|
||||
|
||||
function InternetDetector:stop()
|
||||
local nopids = false
|
||||
for i = 0, 100 do
|
||||
nopids = true
|
||||
local ok, commonDir = pcall(dirent.files, self.commonDir)
|
||||
if ok then
|
||||
for item in commonDir do
|
||||
if item:match(self.pidFilePattern) then
|
||||
if self:stopInstance(string.format("%s/%s", self.commonDir, item)) then
|
||||
nopids = false
|
||||
end
|
||||
end
|
||||
end
|
||||
if nopids then
|
||||
break
|
||||
end
|
||||
time.nanosleep({ tv_sec = 0, tv_nsec = 10000000 })
|
||||
else
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function InternetDetector:setSIGUSR()
|
||||
local ok, commonDir = pcall(dirent.files, self.commonDir)
|
||||
if ok then
|
||||
for item in commonDir do
|
||||
if item:match(self.pidFilePattern) then
|
||||
pidValue = self:readValueFromFile(string.format("%s/%s", self.commonDir, item))
|
||||
if pidValue then
|
||||
signal.kill(tonumber(pidValue), signal.SIGUSR1)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function InternetDetector:preRun()
|
||||
-- Exit if internet-detector mode != (1 or 2)
|
||||
if self.mode ~= 1 and self.mode ~= 2 then
|
||||
io.stderr:write(string.format('Start failed, mode != (1 or 2)\n', self.appName))
|
||||
os.exit(0)
|
||||
end
|
||||
local s = stat.stat(self.commonDir)
|
||||
if not s or not (stat.S_ISDIR(s.st_mode) ~= 0) then
|
||||
if not stat.mkdir(self.commonDir) then
|
||||
io.stderr:write(
|
||||
string.format('Error occurred while creating %s. Exit.\n', self.commonDir))
|
||||
os.exit(1)
|
||||
end
|
||||
end
|
||||
if self.serviceConfig.check_type == 2 and not unistd.access(self.curlExec, "x") then
|
||||
io.stderr:write(string.format(
|
||||
"Error, %s is not available. You need to install curl.\n", self.curlExec))
|
||||
os.exit(1)
|
||||
end
|
||||
local ok, commonDir = pcall(dirent.files, self.commonDir)
|
||||
if ok then
|
||||
local instancePattern = "^" .. self.appNamePattern .. "%." .. self.serviceConfig.instance .. "%.[%d]+%.pid$"
|
||||
for item in commonDir do
|
||||
if item:match(instancePattern) then
|
||||
self:stopInstance(string.format("%s/%s", self.commonDir, item))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function InternetDetector:run()
|
||||
local pidValue = unistd.getpid()
|
||||
self.pidFile = string.format(
|
||||
"%s/%s.%s.%s.pid", self.commonDir, self.appName, self.serviceConfig.instance, pidValue)
|
||||
self.statusFile = string.format(
|
||||
"%s/%s.%s.status", self.commonDir, self.appName, self.serviceConfig.instance)
|
||||
self:writeValueToFile(self.pidFile, pidValue)
|
||||
|
||||
if self.loggingLevel > 0 then
|
||||
syslog.openlog(self.appName, syslog.LOG_PID, syslog.LOG_DAEMON)
|
||||
end
|
||||
self:writeLogMessage("info", "started")
|
||||
self:loadModules()
|
||||
|
||||
-- Loaded modules
|
||||
local modules = {}
|
||||
for _, v in ipairs(self.modules) do
|
||||
modules[#modules + 1] = string.format("%s", v.name)
|
||||
end
|
||||
if #modules > 0 then
|
||||
self:writeLogMessage(
|
||||
"info", string.format("Loaded modules: %s", table.concat(modules, ", "))
|
||||
)
|
||||
end
|
||||
|
||||
if self.debug then
|
||||
local function inspectTable()
|
||||
local tables = {}, f
|
||||
f = function(t, prefix)
|
||||
tables[t] = true
|
||||
for k, v in pairs(t) do
|
||||
self:debugOutput(string.format(
|
||||
"%s%s = %s", prefix, k, tostring(v))
|
||||
)
|
||||
if type(v) == "table" and not tables[v] then
|
||||
f(v, string.format("%s%s.", prefix, k))
|
||||
end
|
||||
end
|
||||
end
|
||||
return f
|
||||
end
|
||||
|
||||
self:debugOutput("--- Config ---")
|
||||
inspectTable()(self, "self.")
|
||||
end
|
||||
|
||||
self:mainLoop()
|
||||
self:exit()
|
||||
end
|
||||
|
||||
function InternetDetector:noDaemon()
|
||||
self:preRun()
|
||||
self:run()
|
||||
end
|
||||
|
||||
function InternetDetector:daemon()
|
||||
self:preRun()
|
||||
-- UNIX double fork
|
||||
if unistd.fork() == 0 then
|
||||
unistd.setpid("s")
|
||||
if unistd.fork() == 0 then
|
||||
unistd.chdir("/")
|
||||
stat.umask(0)
|
||||
local devnull = fcntl.open("/dev/null", fcntl.O_RDWR)
|
||||
io.stdout:flush()
|
||||
io.stderr:flush()
|
||||
unistd.dup2(devnull, 0) -- io.stdin
|
||||
unistd.dup2(devnull, 1) -- io.stdout
|
||||
unistd.dup2(devnull, 2) -- io.stderr
|
||||
self:run()
|
||||
unistd.close(devnull)
|
||||
end
|
||||
os.exit(0)
|
||||
end
|
||||
os.exit(0)
|
||||
end
|
||||
|
||||
function InternetDetector:setServiceConfig(instance)
|
||||
if self:loadInstanceConfig(instance) then
|
||||
if self.mode == 2 then
|
||||
self.loggingLevel = 0
|
||||
self.noModules = true
|
||||
end
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
return InternetDetector
|
||||
@@ -1,334 +0,0 @@
|
||||
|
||||
local dirent = require("posix.dirent")
|
||||
local time = require("posix.time")
|
||||
local unistd = require("posix.unistd")
|
||||
|
||||
local Module = {
|
||||
name = "mod_led_control",
|
||||
runPrio = 10,
|
||||
config = {},
|
||||
syslog = function(level, msg) return true end,
|
||||
debugOutput = function(msg) return true end,
|
||||
writeValue = function(filePath, str) return false end,
|
||||
readValue = function(filePath) return nil end,
|
||||
runInterval = 5,
|
||||
sysLedsDir = "/sys/class/leds",
|
||||
ledsPerInstance = 3,
|
||||
ledAction1Default = 1, -- 1: off, 2: on, 3: blinking, 4: netdev
|
||||
ledAction2Default = 1,
|
||||
ledBlinkDelayDefault = 500,
|
||||
ledNetlinkDeviceDefault = nil,
|
||||
ledNetdevModeLinkDefault = "1",
|
||||
ledNetdevModeRxDefault = "0",
|
||||
ledNetdevModeTxDefault = "0",
|
||||
status = nil,
|
||||
_enabled = false,
|
||||
_leds = {},
|
||||
_counter = 0,
|
||||
_exit = false,
|
||||
}
|
||||
|
||||
function Module:setLedAttrs(t)
|
||||
t.ledDir = string.format("%s/%s", self.sysLedsDir, t.ledName)
|
||||
t.ledMaxBrightnessFile = string.format("%s/max_brightness", t.ledDir)
|
||||
t.ledBrightnessFile = string.format("%s/brightness", t.ledDir)
|
||||
t.ledMaxBrightness = self.readValue(t.ledMaxBrightnessFile) or "1"
|
||||
t.ledTriggerFile = string.format("%s/trigger", t.ledDir)
|
||||
t.ledDelayOnFile = string.format("%s/delay_on", t.ledDir)
|
||||
t.ledDelayOffFile = string.format("%s/delay_off", t.ledDir)
|
||||
t.ledDeviceNameFile = string.format("%s/device_name", t.ledDir)
|
||||
t.ledLinkFile = string.format("%s/link", t.ledDir)
|
||||
t.ledRxFile = string.format("%s/rx", t.ledDir)
|
||||
t.ledTxFile = string.format("%s/tx", t.ledDir)
|
||||
t.ledPrevState = {
|
||||
brightness = self.readValue(t.ledBrightnessFile),
|
||||
trigger = self.readValue(t.ledTriggerFile),
|
||||
}
|
||||
if t.ledPrevState.trigger then
|
||||
local val = t.ledPrevState.trigger:match("%[[%w%-_]+%]")
|
||||
if val then
|
||||
t.ledPrevState.trigger = val:gsub("[%]%[]", "")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function Module:checkLed(t)
|
||||
return (unistd.access(t.ledDir, "r") and
|
||||
unistd.access(t.ledBrightnessFile, "rw") and
|
||||
unistd.access(t.ledTriggerFile, "rw"))
|
||||
end
|
||||
|
||||
function Module:init(t)
|
||||
for i = 1, self.ledsPerInstance do
|
||||
self._leds[i] = {}
|
||||
end
|
||||
if t.led1_name then
|
||||
self._enabled = true
|
||||
else
|
||||
return
|
||||
end
|
||||
for i, l in ipairs(self._leds) do
|
||||
local led = "led" .. i
|
||||
if t[led .. "_name"] ~= nil then
|
||||
l.ledName = t[led .. "_name"]
|
||||
l.ledAction1 = tonumber(t[led .. "_action_1"]) or self.ledAction1Default
|
||||
l.ledAction2 = tonumber(t[led .. "_action_2"]) or self.ledAction2Default
|
||||
l.ledBlinkOnDelay1 = tonumber(t[led .. "_blink_on_delay_1"]) or self.ledBlinkDelayDefault
|
||||
l.ledBlinkOffDelay1 = tonumber(t[led .. "_blink_off_delay_1"]) or self.ledBlinkDelayDefault
|
||||
l.ledBlinkOnDelay2 = tonumber(t[led .. "_blink_on_delay_2"]) or self.ledBlinkDelayDefault
|
||||
l.ledBlinkOffDelay2 = tonumber(t[led .. "_blink_off_delay_2"]) or self.ledBlinkDelayDefault
|
||||
l.ledNetlinkDevice1 = t[led .. "_netdev_device_1"] or self.ledNetlinkDeviceDefault
|
||||
l.ledNetlinkDevice2 = t[led .. "_netdev_device_2"] or self.ledNetlinkDeviceDefault
|
||||
l.ledNetdevModeLink1 = self.ledNetdevModeLinkDefault
|
||||
l.ledNetdevModeTx1 = self.ledNetdevModeTxDefault
|
||||
l.ledNetdevModeRx1 = self.ledNetdevModeRxDefault
|
||||
l.ledNetdevModeLink2 = self.ledNetdevModeLinkDefault
|
||||
l.ledNetdevModeTx2 = self.ledNetdevModeTxDefault
|
||||
l.ledNetdevModeRx2 = self.ledNetdevModeRxDefault
|
||||
local ndm1 = t[led .. "_netdev_mode_1"]
|
||||
if ndm1 ~= nil and type(ndm1) == "table" then
|
||||
local enabledFlags = {}
|
||||
for _, v in ipairs(ndm1) do
|
||||
enabledFlags[v] = "1"
|
||||
end
|
||||
l.ledNetdevModeLink1 = enabledFlags.link or "0"
|
||||
l.ledNetdevModeTx1 = enabledFlags.tx or "0"
|
||||
l.ledNetdevModeRx1 = enabledFlags.rx or "0"
|
||||
end
|
||||
local ndm2 = t[led .. "_netdev_mode_2"]
|
||||
if ndm2 ~= nil and type(ndm2) == "table" then
|
||||
local enabledFlags = {}
|
||||
for _, v in ipairs(ndm2) do
|
||||
enabledFlags[v] = "1"
|
||||
end
|
||||
l.ledNetdevModeLink2 = enabledFlags.link or "0"
|
||||
l.ledNetdevModeTx2 = enabledFlags.tx or "0"
|
||||
l.ledNetdevModeRx2 = enabledFlags.rx or "0"
|
||||
end
|
||||
self:setLedAttrs(l)
|
||||
l.enabled = true
|
||||
else
|
||||
l.enabled = false
|
||||
end
|
||||
if l.enabled and not self:checkLed(l) then
|
||||
self._enabled = false
|
||||
self.syslog("err", string.format(
|
||||
"%s: module disabled. LED '%s' is not available", self.name, l.ledName))
|
||||
end
|
||||
self._exit = false
|
||||
end
|
||||
end
|
||||
|
||||
function Module:checkLedTimer(t)
|
||||
return (unistd.access(t.ledDelayOnFile, "rw") and unistd.access(t.ledDelayOffFile, "rw"))
|
||||
end
|
||||
|
||||
function Module:checkLedNetdev(t)
|
||||
return (unistd.access(t.ledDeviceNameFile, "rw") and
|
||||
unistd.access(t.ledLinkFile, "rw") and
|
||||
unistd.access(t.ledRxFile, "rw") and
|
||||
unistd.access(t.ledTxFile, "rw"))
|
||||
end
|
||||
|
||||
function Module:setTriggerNone(t)
|
||||
self.writeValue(t.ledTriggerFile, "none")
|
||||
self.debugOutput(string.format(
|
||||
"%s: LED TRIGGER SET: none, %s", self.name, t.ledTriggerFile))
|
||||
end
|
||||
|
||||
function Module:setTriggerTimer(t, delayOn, delayOff)
|
||||
if not delayOn then
|
||||
delayOn = self.ledBlinkDelayDefault
|
||||
end
|
||||
if not delayOff then
|
||||
delayOff = self.ledBlinkDelayDefault
|
||||
end
|
||||
|
||||
self.writeValue(t.ledTriggerFile, "timer")
|
||||
|
||||
for i = 0, 10 do
|
||||
if self:checkLedTimer(t) then
|
||||
self.writeValue(t.ledDelayOnFile, delayOn)
|
||||
self.writeValue(t.ledDelayOffFile, delayOff)
|
||||
break
|
||||
else
|
||||
time.nanosleep({ tv_sec = 0, tv_nsec = 500000 })
|
||||
end
|
||||
end
|
||||
|
||||
self.debugOutput(string.format(
|
||||
"%s: LED TRIGGER SET: timer, %s; delayOn = %s, delayOff = %s",
|
||||
self.name, t.ledTriggerFile, tostring(delayOn), tostring(delayOff))
|
||||
)
|
||||
end
|
||||
|
||||
function Module:setTriggerNetdev(t, device, link, tx, rx)
|
||||
if not device then
|
||||
return
|
||||
end
|
||||
|
||||
self.writeValue(t.ledTriggerFile, "netdev")
|
||||
|
||||
for i = 0, 10 do
|
||||
if self:checkLedNetdev(t) then
|
||||
self.writeValue(t.ledDeviceNameFile, device)
|
||||
self.writeValue(t.ledLinkFile, link)
|
||||
self.writeValue(t.ledTxFile, tx)
|
||||
self.writeValue(t.ledRxFile, rx)
|
||||
break
|
||||
else
|
||||
time.nanosleep({ tv_sec = 0, tv_nsec = 500000 })
|
||||
end
|
||||
end
|
||||
|
||||
self.debugOutput(string.format(
|
||||
"%s: LED TRIGGER SET: netdev, %s; device = %s, link = %s, rx = %s, tx = %s",
|
||||
self.name, t.ledTriggerFile, tostring(device), tostring(link), tostring(rx), tostring(tx))
|
||||
)
|
||||
end
|
||||
|
||||
function Module:getCurrentTrigger(t)
|
||||
local trigger = self.readValue(t.ledTriggerFile)
|
||||
if trigger then
|
||||
if trigger:match("%[timer%]") then
|
||||
return "timer"
|
||||
elseif trigger:match("%[netdev%]") then
|
||||
return "netdev"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function Module:getTriggerValues(t, trigger)
|
||||
local currentTrigger = self:getCurrentTrigger(t)
|
||||
if trigger == currentTrigger then
|
||||
if trigger == "timer" then
|
||||
return {
|
||||
trigger = currentTrigger,
|
||||
delayOn = tonumber(self.readValue(t.ledDelayOnFile)),
|
||||
delayOff = tonumber(self.readValue(t.ledDelayOffFile)),
|
||||
}
|
||||
elseif trigger == "netdev" then
|
||||
return {
|
||||
trigger = currentTrigger,
|
||||
device = self.readValue(t.ledDeviceNameFile),
|
||||
link = self.readValue(t.ledLinkFile),
|
||||
tx = self.readValue(t.ledTxFile),
|
||||
rx = self.readValue(t.ledRxFile),
|
||||
}
|
||||
end
|
||||
end
|
||||
return {}
|
||||
end
|
||||
|
||||
function Module:on(t)
|
||||
self:setTriggerNone(t)
|
||||
self.writeValue(t.ledBrightnessFile, t.ledMaxBrightness)
|
||||
|
||||
self.debugOutput(string.format("%s: LED ON: %s", self.name, t.ledBrightnessFile))
|
||||
end
|
||||
|
||||
function Module:off(t)
|
||||
self:setTriggerNone(t)
|
||||
self.writeValue(t.ledBrightnessFile, "0")
|
||||
|
||||
self.debugOutput(string.format("%s: LED OFF: %s", self.name, t.ledBrightnessFile))
|
||||
end
|
||||
|
||||
function Module:getCurrentState(t)
|
||||
local state = self.readValue(t.ledBrightnessFile)
|
||||
if state and tonumber(state) > 0 then
|
||||
return tonumber(state)
|
||||
end
|
||||
end
|
||||
|
||||
function Module:ledRunFunc(t, currentStatus)
|
||||
if currentStatus == 0 then
|
||||
if t.ledAction1 == 1 then
|
||||
if self:getCurrentState(t) or self:getCurrentTrigger(t) then
|
||||
self:off(t)
|
||||
end
|
||||
elseif t.ledAction1 == 2 then
|
||||
if not self:getCurrentState(t) or self:getCurrentTrigger(t) then
|
||||
self:on(t)
|
||||
end
|
||||
elseif t.ledAction1 == 3 then
|
||||
local triggerValues = self:getTriggerValues(t, "timer")
|
||||
if (not next(triggerValues)) or (triggerValues.delayOn ~= t.ledBlinkOnDelay1 or
|
||||
triggerValues.delayOff ~= t.ledBlinkOffDelay1) then
|
||||
self:setTriggerTimer(t, t.ledBlinkOnDelay1, t.ledBlinkOffDelay1)
|
||||
end
|
||||
elseif t.ledAction1 == 4 then
|
||||
local triggerValues = self:getTriggerValues(t, "netdev")
|
||||
if (not next(triggerValues)) or (triggerValues.device ~= t.ledNetlinkDevice1 or
|
||||
triggerValues.link ~= t.ledNetdevModeLink1 or
|
||||
triggerValues.tx ~= t.ledNetdevModeTx1 or
|
||||
triggerValues.rx ~= t.ledNetdevModeRx1) then
|
||||
self:setTriggerNetdev(t,
|
||||
t.ledNetlinkDevice1, t.ledNetdevModeLink1,
|
||||
t.ledNetdevModeTx1, t.ledNetdevModeRx1
|
||||
)
|
||||
end
|
||||
end
|
||||
elseif currentStatus == 1 then
|
||||
if t.ledAction2 == 1 then
|
||||
if self:getCurrentState(t) or self:getCurrentTrigger(t) then
|
||||
self:off(t)
|
||||
end
|
||||
elseif t.ledAction2 == 2 then
|
||||
if not self:getCurrentState(t) or self:getCurrentTrigger(t) then
|
||||
self:on(t)
|
||||
end
|
||||
elseif t.ledAction2 == 3 then
|
||||
local triggerValues = self:getTriggerValues(t, "timer")
|
||||
if (not next(triggerValues)) or (triggerValues.delayOn ~= t.ledBlinkOnDelay2 or
|
||||
triggerValues.delayOff ~= t.ledBlinkOffDelay2) then
|
||||
self:setTriggerTimer(t, t.ledBlinkOnDelay2, t.ledBlinkOffDelay2)
|
||||
end
|
||||
elseif t.ledAction2 == 4 then
|
||||
local triggerValues = self:getTriggerValues(t, "netdev")
|
||||
if (not next(triggerValues)) or (triggerValues.device ~= t.ledNetlinkDevice2 or
|
||||
triggerValues.link ~= t.ledNetdevModeLink2 or
|
||||
triggerValues.tx ~= t.ledNetdevModeTx2 or
|
||||
triggerValues.rx ~= t.ledNetdevModeRx2) then
|
||||
self:setTriggerNetdev(t,
|
||||
t.ledNetlinkDevice2, t.ledNetdevModeLink2,
|
||||
t.ledNetdevModeTx2, t.ledNetdevModeRx2
|
||||
)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function Module:run(currentStatus, lastStatus, timeDiff, timeNow, inetChecked)
|
||||
if not self._enabled then
|
||||
return
|
||||
end
|
||||
if self._counter == 0 or self._counter >= self.runInterval or currentStatus ~= lastStatus then
|
||||
for _, t in ipairs(self._leds) do
|
||||
if self._exit then
|
||||
break
|
||||
end
|
||||
if t.enabled then
|
||||
self:ledRunFunc(t, currentStatus)
|
||||
end
|
||||
end
|
||||
self._counter = 0
|
||||
end
|
||||
self._counter = self._counter + timeDiff
|
||||
end
|
||||
|
||||
function Module:onExit()
|
||||
self._exit = true
|
||||
for _, l in ipairs(self._leds) do
|
||||
if l.ledPrevState then
|
||||
if l.ledPrevState.brightness then
|
||||
self.writeValue(l.ledBrightnessFile, l.ledPrevState.brightness)
|
||||
end
|
||||
if l.ledPrevState.trigger then
|
||||
self.writeValue(l.ledTriggerFile, l.ledPrevState.trigger)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return Module
|
||||
-160
@@ -1,160 +0,0 @@
|
||||
|
||||
local unistd = require("posix.unistd")
|
||||
|
||||
local Module = {
|
||||
name = "mod_network_restart",
|
||||
runPrio = 30,
|
||||
config = {},
|
||||
syslog = function(level, msg) return true end,
|
||||
debugOutput = function(msg) return true end,
|
||||
writeValue = function(filePath, str) return false end,
|
||||
readValue = function(filePath) return nil end,
|
||||
deadPeriod = 900,
|
||||
attempts = 1,
|
||||
attemptInterval = 15,
|
||||
deviceTimeout = 0,
|
||||
status = nil,
|
||||
_attemptsCounter = 0,
|
||||
_attemptIntervalCounter = 0,
|
||||
_deadCounter = 0,
|
||||
_firstAttempt = true,
|
||||
_ifaceRestarting = false,
|
||||
_ifaceRestartCounter = 0,
|
||||
_netIfaces = {},
|
||||
_netDevices = {},
|
||||
_netItemsNum = 0,
|
||||
_disconnectedAtStartup = false,
|
||||
}
|
||||
|
||||
function Module:toggleDevices(flag)
|
||||
if #self._netDevices == 0 then
|
||||
return
|
||||
end
|
||||
local ip = "/sbin/ip"
|
||||
if unistd.access(ip, "x") then
|
||||
for _, v in ipairs(self._netDevices) do
|
||||
os.execute(string.format("%s link set dev %s %s", ip, v, (flag and "up" or "down")))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function Module:toggleIfaces(flag)
|
||||
if #self._netIfaces == 0 then
|
||||
return
|
||||
end
|
||||
for _, v in ipairs(self._netIfaces) do
|
||||
os.execute(string.format("%s %s", (flag and "/sbin/ifup" or "/sbin/ifdown"), v))
|
||||
end
|
||||
end
|
||||
|
||||
function Module:netItemsUp()
|
||||
self:toggleDevices(true)
|
||||
self:toggleIfaces(true)
|
||||
end
|
||||
|
||||
function Module:netItemsDown()
|
||||
self:toggleIfaces(false)
|
||||
self:toggleDevices(false)
|
||||
end
|
||||
|
||||
function Module:restartNetworkService()
|
||||
return os.execute("/etc/init.d/network restart")
|
||||
end
|
||||
|
||||
function Module:init(t)
|
||||
if t.ifaces ~= nil and type(t.ifaces) == "table" then
|
||||
self._netIfaces = {}
|
||||
self._netDevices = {}
|
||||
self._netItemsNum = 0
|
||||
for k, v in ipairs(t.ifaces) do
|
||||
if v:match("^@") then
|
||||
self._netIfaces[#self._netIfaces + 1] = v:gsub("^@", "")
|
||||
else
|
||||
self._netDevices[#self._netDevices + 1] = v
|
||||
end
|
||||
self._netItemsNum = self._netItemsNum + 1
|
||||
end
|
||||
end
|
||||
if t.dead_period ~= nil then
|
||||
self.deadPeriod = tonumber(t.dead_period)
|
||||
end
|
||||
if t.attempts ~= nil then
|
||||
self.attempts = tonumber(t.attempts)
|
||||
end
|
||||
if t.attempt_interval ~= nil then
|
||||
self.attemptInterval = tonumber(t.attempt_interval)
|
||||
end
|
||||
if t.device_timeout ~= nil then
|
||||
self.deviceTimeout = tonumber(t.device_timeout)
|
||||
end
|
||||
if tonumber(t.disconnected_at_startup) == 1 then
|
||||
self._disconnectedAtStartup = true
|
||||
end
|
||||
end
|
||||
|
||||
function Module:networkRestartFunc()
|
||||
if self._netItemsNum > 0 then
|
||||
if #self._netIfaces > 0 then
|
||||
self.syslog("info", string.format("%s: restarting interfaces: %s",
|
||||
self.name, table.concat(self._netIfaces, ", ")))
|
||||
end
|
||||
if #self._netDevices > 0 then
|
||||
self.syslog("info", string.format("%s: restarting devices: %s",
|
||||
self.name, table.concat(self._netDevices, ", ")))
|
||||
end
|
||||
self:netItemsDown()
|
||||
if self.deviceTimeout < 1 then
|
||||
self:netItemsUp()
|
||||
else
|
||||
self._ifaceRestarting = true
|
||||
end
|
||||
else
|
||||
self.syslog("info", string.format(
|
||||
"%s: restarting network", self.name))
|
||||
self:restartNetworkService()
|
||||
end
|
||||
if self.attempts > 0 then
|
||||
self._attemptsCounter = self._attemptsCounter + 1
|
||||
end
|
||||
end
|
||||
|
||||
function Module:run(currentStatus, lastStatus, timeDiff, timeNow, inetChecked)
|
||||
if self._ifaceRestarting then
|
||||
if self._ifaceRestartCounter >= self.deviceTimeout then
|
||||
self:netItemsUp()
|
||||
self._ifaceRestarting = false
|
||||
self._ifaceRestartCounter = 0
|
||||
else
|
||||
self._ifaceRestartCounter = self._ifaceRestartCounter + timeDiff
|
||||
end
|
||||
else
|
||||
if currentStatus == 1 then
|
||||
if self._disconnectedAtStartup and self._deadCounter >= self.deadPeriod then
|
||||
if self.attempts == 0 or self._attemptsCounter < self.attempts then
|
||||
if self._firstAttempt or self._attemptIntervalCounter >= self.attemptInterval then
|
||||
self:networkRestartFunc()
|
||||
self._attemptIntervalCounter = 0
|
||||
self._firstAttempt = false
|
||||
else
|
||||
self._attemptIntervalCounter = self._attemptIntervalCounter + timeDiff
|
||||
end
|
||||
end
|
||||
else
|
||||
self._deadCounter = self._deadCounter + timeDiff
|
||||
end
|
||||
else
|
||||
self._attemptsCounter = 0
|
||||
self._attemptIntervalCounter = 0
|
||||
self._deadCounter = 0
|
||||
self._disconnectedAtStartup = true
|
||||
self._firstAttempt = true
|
||||
end
|
||||
self._ifaceRestartCounter = 0
|
||||
end
|
||||
end
|
||||
|
||||
function Module:onExit()
|
||||
return true
|
||||
end
|
||||
|
||||
return Module
|
||||
@@ -1,533 +0,0 @@
|
||||
|
||||
local socket = require("posix.sys.socket")
|
||||
local stdlib = require("posix.stdlib")
|
||||
local unistd = require("posix.unistd")
|
||||
|
||||
local Module = {
|
||||
name = "mod_public_ip",
|
||||
runPrio = 50,
|
||||
config = {
|
||||
noModules = false,
|
||||
debug = false,
|
||||
serviceConfig = {
|
||||
iface = nil,
|
||||
proxy_type = nil,
|
||||
proxy_host = nil,
|
||||
proxy_port = nil,
|
||||
},
|
||||
},
|
||||
syslog = function(level, msg) return true end,
|
||||
debugOutput = function(msg) return true end,
|
||||
writeValue = function(filePath, str) return false end,
|
||||
readValue = function(filePath) return nil end,
|
||||
port = 53,
|
||||
runInterval = 600,
|
||||
runIntervalFailed = 60,
|
||||
runIntervalIPFailed = 1,
|
||||
requestAttempts = 2,
|
||||
timeout = 3,
|
||||
curlExec = "/usr/bin/curl",
|
||||
curlParams = '-s -g --no-keepalive --user-agent "Mozilla/5.0 (X11; Linux x86_64; rv:142.0) Gecko/20100101 Firefox/142.0"',
|
||||
providers = {
|
||||
opendns1 = {
|
||||
name = "opendns1", type = "dns", host = "myip.opendns.com",
|
||||
server = "208.67.222.222", server6 = "2620:119:35::35",
|
||||
port = 53, queryType = "A", queryType6 = "AAAA",
|
||||
},
|
||||
opendns2 = {
|
||||
name = "opendns2", type = "dns", host = "myip.opendns.com",
|
||||
server = "208.67.220.220", server6 = "2620:119:35::35",
|
||||
port = 53, queryType = "A", queryType6 = "AAAA",
|
||||
},
|
||||
opendns3 = {
|
||||
name = "opendns3", type = "dns", host = "myip.opendns.com",
|
||||
server = "208.67.222.220", server6 = "2620:119:35::35",
|
||||
port = 53, queryType = "A", queryType6 = "AAAA",
|
||||
},
|
||||
opendns4 = {
|
||||
name = "opendns4", type = "dns", host = "myip.opendns.com",
|
||||
server = "208.67.220.222", server6 = "2620:119:35::35",
|
||||
port = 53, queryType = "A", queryType6 = "AAAA",
|
||||
},
|
||||
google = {
|
||||
name = "google", type = "dns", host = "o-o.myaddr.l.google.com",
|
||||
server = "ns1.google.com", server6 = "ns1.google.com",
|
||||
port = 53, queryType = "TXT", queryType6 = "TXT",
|
||||
},
|
||||
akamai = {
|
||||
name = "akamai", type = "dns", host = "whoami.akamai.net",
|
||||
server = "ns1-1.akamaitech.net", server6 = "ns1-1.akamaitech.net",
|
||||
port = 53, queryType = "A", queryType6 = "AAAA",
|
||||
},
|
||||
akamai_http = {
|
||||
name = "akamai_http", type = "http", url = "http://whatismyip.akamai.com/",
|
||||
parseResponseFunc = nil,
|
||||
},
|
||||
amazonaws= {
|
||||
name = "amazonaws", type = "http", url = "http://checkip.amazonaws.com/",
|
||||
parseResponseFunc = nil,
|
||||
},
|
||||
wgetip= {
|
||||
name = "wgetip", type = "http", url = "http://wgetip.com/",
|
||||
parseResponseFunc = nil,
|
||||
},
|
||||
ifconfig= {
|
||||
name = "ifconfig", type = "http", url = "http://ifconfig.me/",
|
||||
parseResponseFunc = nil,
|
||||
},
|
||||
ipecho= {
|
||||
name = "ipecho", type = "http", url = "http://ipecho.net/plain",
|
||||
parseResponseFunc = nil,
|
||||
},
|
||||
canhazip= {
|
||||
name = "canhazip", type = "http", url = "http://canhazip.com/",
|
||||
parseResponseFunc = nil,
|
||||
},
|
||||
icanhazip = {
|
||||
name = "icanhazip", type = "http", url = "http://icanhazip.com/",
|
||||
parseResponseFunc = nil,
|
||||
},
|
||||
},
|
||||
ipScript = "",
|
||||
enableIpScript = false,
|
||||
status = nil,
|
||||
_proxyString = "",
|
||||
_provider = nil,
|
||||
_qtype = false,
|
||||
_currentIp = nil,
|
||||
_lastResolvedIp = nil,
|
||||
_enabled = false,
|
||||
_counter = 0,
|
||||
_IPFalseCounter = 0,
|
||||
_interval = 600,
|
||||
_DNSPacket = nil,
|
||||
_requestIP = nil,
|
||||
}
|
||||
|
||||
function Module:runIpScript()
|
||||
if not self.config.noModules and self.enableIpScript and unistd.access(self.ipScript, "r") then
|
||||
stdlib.setenv("PUBLIC_IP", self.status)
|
||||
os.execute(string.format('/bin/sh "%s" &', self.ipScript))
|
||||
end
|
||||
end
|
||||
|
||||
function Module:getQueryType(type)
|
||||
local types = {
|
||||
A = 1,
|
||||
NS = 2,
|
||||
MD = 3,
|
||||
MF = 4,
|
||||
CNAME = 5,
|
||||
SOA = 6,
|
||||
MB = 7,
|
||||
MG = 8,
|
||||
MR = 9,
|
||||
NULL = 10,
|
||||
WKS = 11,
|
||||
PTS = 12,
|
||||
HINFO = 13,
|
||||
MINFO = 14,
|
||||
MX = 15,
|
||||
TXT = 16,
|
||||
AAAA = 28,
|
||||
}
|
||||
return types[type]
|
||||
end
|
||||
|
||||
function Module:buildMessage(address, queryType)
|
||||
if not queryType then
|
||||
queryType = "A"
|
||||
end
|
||||
queryType = self:getQueryType(queryType)
|
||||
|
||||
local addressString = ""
|
||||
for part in address:gmatch("[^.]+") do
|
||||
local t = {}
|
||||
for i in part:gmatch(".") do
|
||||
t[#t + 1] = i
|
||||
end
|
||||
addrLen = #part
|
||||
addrPart = table.concat(t)
|
||||
addressString = addressString .. string.char(addrLen) .. addrPart
|
||||
end
|
||||
|
||||
local data = (
|
||||
string.char(
|
||||
0xaa, 0xaa,
|
||||
0x01, 0x00,
|
||||
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
|
||||
) ..
|
||||
addressString ..
|
||||
string.char(
|
||||
0x00,
|
||||
0x00, queryType,
|
||||
0x00, 0x01
|
||||
)
|
||||
)
|
||||
return data
|
||||
end
|
||||
|
||||
function Module:sendUDPMessage(message, server, port)
|
||||
local success
|
||||
local retCode = 1
|
||||
local data
|
||||
|
||||
self.debugOutput(string.format("--- %s ---", self.name))
|
||||
|
||||
local saTable, errMsg, errNum = socket.getaddrinfo(server, port)
|
||||
|
||||
if not saTable then
|
||||
self.debugOutput(string.format(
|
||||
"GETADDRINFO ERROR: %s, %s", errMsg, errNum))
|
||||
else
|
||||
local family = saTable[1].family
|
||||
|
||||
if family then
|
||||
local sock, errMsg, errNum = socket.socket(family, socket.SOCK_DGRAM, 0)
|
||||
|
||||
if not sock then
|
||||
self.debugOutput(string.format(
|
||||
"SOCKET ERROR: %s, %s", errMsg, errNum))
|
||||
return retCode
|
||||
end
|
||||
|
||||
socket.setsockopt(sock, socket.SOL_SOCKET,
|
||||
socket.SO_SNDTIMEO, self.timeout, 0)
|
||||
socket.setsockopt(sock, socket.SOL_SOCKET,
|
||||
socket.SO_RCVTIMEO, self.timeout, 0)
|
||||
|
||||
if self.config.serviceConfig.iface then
|
||||
local ok, errMsg, errNum = socket.setsockopt(sock, socket.SOL_SOCKET,
|
||||
socket.SO_BINDTODEVICE, self.config.serviceConfig.iface)
|
||||
if not ok then
|
||||
self.debugOutput(string.format(
|
||||
"SOCKET ERROR: %s, %s", errMsg, errNum))
|
||||
unistd.close(sock)
|
||||
return retCode
|
||||
end
|
||||
end
|
||||
|
||||
local ok, errMsg, errNum = socket.sendto(sock, message, saTable[1])
|
||||
|
||||
local response = {}
|
||||
if ok then
|
||||
local ret, resp, errNum = socket.recvfrom(sock, 1024)
|
||||
data = ret
|
||||
if data then
|
||||
success = true
|
||||
response = resp
|
||||
else
|
||||
self.debugOutput(string.format(
|
||||
"SOCKET RECV ERROR: %s, %s", tostring(resp), tostring(errNum)))
|
||||
end
|
||||
else
|
||||
self.debugOutput(string.format(
|
||||
"SOCKET SEND ERROR: %s, %s", tostring(errMsg), tostring(errNum)))
|
||||
end
|
||||
|
||||
self.debugOutput(string.format(
|
||||
"--- UDP ---\ntime = %s\nconnection_timeout = %s\niface = %s\nserver = %s:%s\nsockname = %s:%s\nsuccess = %s",
|
||||
os.time(),
|
||||
self.timeout,
|
||||
tostring(self.config.serviceConfig.iface),
|
||||
server,
|
||||
tostring(port),
|
||||
tostring(response.addr),
|
||||
tostring(response.port),
|
||||
tostring(success))
|
||||
)
|
||||
|
||||
unistd.close(sock)
|
||||
retCode = success and 0 or 1
|
||||
end
|
||||
end
|
||||
return retCode, tostring(data)
|
||||
end
|
||||
|
||||
function Module:parseParts(message, start, parts)
|
||||
local partStart = start + 2
|
||||
local partLen = message:sub(start, start + 1)
|
||||
if #partLen == 0 then
|
||||
return parts
|
||||
end
|
||||
local partEnd = partStart + (tonumber(partLen, 16) * 2)
|
||||
parts[#parts + 1] = message:sub(partStart, partEnd - 1)
|
||||
if message:sub(partEnd, partEnd + 1) == "00" or partEnd > #message then
|
||||
return parts
|
||||
else
|
||||
return self:parseParts(message, partEnd, parts)
|
||||
end
|
||||
end
|
||||
|
||||
function Module:decodeMessage(message)
|
||||
local retTable = {}
|
||||
local t = {}
|
||||
for i = 1, #message do
|
||||
t[#t + 1] = string.format("%.2x", string.byte(message, i))
|
||||
end
|
||||
message = table.concat(t)
|
||||
|
||||
local ANCOUNT = message:sub(13, 16)
|
||||
local NSCOUNT = message:sub(17, 20)
|
||||
local ARCOUNT = message:sub(21, 24)
|
||||
|
||||
-- Question section
|
||||
local questionSectionStarts = 25
|
||||
local questionParts = self:parseParts(message, questionSectionStarts, {})
|
||||
local qtypeStarts = questionSectionStarts + (#table.concat(questionParts)) + (#questionParts * 2) + 1
|
||||
local qclassStarts = qtypeStarts + 4
|
||||
|
||||
-- Answer section
|
||||
local answerSectionStarts = qclassStarts + 4
|
||||
local numAnswers = math.max(
|
||||
tonumber(ANCOUNT, 16), tonumber(NSCOUNT, 16), tonumber(ARCOUNT, 16))
|
||||
|
||||
if numAnswers > 0 then
|
||||
for answerCount = 1, numAnswers do
|
||||
if answerSectionStarts < #message then
|
||||
local ATYPE = tonumber(
|
||||
message:sub(answerSectionStarts + 5, answerSectionStarts + 8), 16)
|
||||
local RDLENGTH = tonumber(
|
||||
message:sub(answerSectionStarts + 21, answerSectionStarts + 24), 16)
|
||||
local RDDATA = message:sub(
|
||||
answerSectionStarts + 25, answerSectionStarts + 24 + (RDLENGTH * 2))
|
||||
local RDDATA_decoded = ""
|
||||
|
||||
if #RDDATA > 0 then
|
||||
if ATYPE == self:getQueryType("A") or ATYPE == self:getQueryType("AAAA") then
|
||||
local octets = {}
|
||||
local sep = "."
|
||||
if #RDDATA > 8 then
|
||||
sep = ":"
|
||||
for i = 1, #RDDATA, 4 do
|
||||
local string = RDDATA:sub(i, i + 3)
|
||||
string = string:gsub("^00?0?", "")
|
||||
octets[#octets + 1] = string
|
||||
end
|
||||
else
|
||||
for i = 1, #RDDATA, 2 do
|
||||
octets[#octets + 1] = tonumber(RDDATA:sub(i, i + 1), 16)
|
||||
end
|
||||
end
|
||||
RDDATA_decoded = table.concat(octets, sep):gsub("0:[0:]+", "::", 1):gsub("::+", "::")
|
||||
else
|
||||
local rdata_t = {}
|
||||
for _, v in ipairs(self:parseParts(RDDATA, 1, {})) do
|
||||
local t = {}
|
||||
for i = 1, #v, 2 do
|
||||
t[#t + 1] = string.char(tonumber(v:sub(i, i + 1), 16))
|
||||
end
|
||||
rdata_t[#rdata_t + 1] = table.concat(t)
|
||||
end
|
||||
RDDATA_decoded = table.concat(rdata_t)
|
||||
end
|
||||
end
|
||||
answerSectionStarts = answerSectionStarts + 24 + (RDLENGTH * 2)
|
||||
|
||||
if RDDATA_decoded:match("^[a-fA-F0-9.:]+$") then
|
||||
retTable[#retTable + 1] = RDDATA_decoded
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return retTable
|
||||
end
|
||||
|
||||
function Module:requestIPDNS()
|
||||
local res
|
||||
local qtype = self._qtype and self._provider.queryType6 or self._provider.queryType
|
||||
local server = self._qtype and self._provider.server6 or self._provider.server
|
||||
local port = self._provider.port or self.port
|
||||
if not self._DNSPacket then
|
||||
self._DNSPacket = self:buildMessage(self._provider.host, qtype)
|
||||
end
|
||||
local retCode, response = self:sendUDPMessage(self._DNSPacket, server, port)
|
||||
if retCode == 0 and response then
|
||||
local retTable = self:decodeMessage(response)
|
||||
if #retTable > 0 then
|
||||
res = table.concat(retTable, ", ")
|
||||
end
|
||||
else
|
||||
self.syslog("warning", string.format(
|
||||
"%s: UDP error when requesting an IP address", self.name))
|
||||
end
|
||||
return res
|
||||
end
|
||||
|
||||
function Module:httpRequest(url)
|
||||
local retCode = 1, data
|
||||
local curl = string.format(
|
||||
'%s%s%s --connect-timeout %s %s "%s"; printf "\n$?";',
|
||||
self.curlExec,
|
||||
self.config.serviceConfig.iface and (" --interface " .. self.config.serviceConfig.iface) or "",
|
||||
self._proxyString,
|
||||
self.timeout,
|
||||
self.curlParams,
|
||||
url
|
||||
)
|
||||
local fh = io.popen(curl, "r")
|
||||
if fh then
|
||||
data = fh:read("*a")
|
||||
fh:close()
|
||||
if data ~= nil then
|
||||
local s, e = data:find("[0-9]+\n?$")
|
||||
retCode = tonumber(data:sub(s))
|
||||
data = data:sub(0, s - 2)
|
||||
if not data or data == "" then
|
||||
data = nil
|
||||
end
|
||||
end
|
||||
else
|
||||
retCode = 1
|
||||
end
|
||||
|
||||
self.debugOutput(string.format(
|
||||
"--- Curl ---\ntime = %s\n%s\nretCode = %s\ndata = [\n%s]\n",
|
||||
os.time(),
|
||||
curl,
|
||||
retCode,
|
||||
tostring(data))
|
||||
)
|
||||
return retCode, data
|
||||
end
|
||||
|
||||
function Module:parseHTTPResponse(data)
|
||||
data = data:gsub("^[%s%c]+", ""):gsub("[%s%c]+$", "")
|
||||
if data:match("^[a-fA-F0-9.:]+$") then
|
||||
return data
|
||||
end
|
||||
return
|
||||
end
|
||||
|
||||
function Module:requestIPHTTP()
|
||||
local res
|
||||
local url = self._provider.url
|
||||
local parseResponseFunc = self._provider.parseResponseFunc
|
||||
if url then
|
||||
local retCode, data = self:httpRequest(url)
|
||||
if retCode == 0 and data then
|
||||
if type(parseResponseFunc) == "function" then
|
||||
res = parseResponseFunc(data)
|
||||
else
|
||||
res = self:parseHTTPResponse(data)
|
||||
end
|
||||
else
|
||||
self.syslog("warning", string.format(
|
||||
"%s: HTTP error when requesting an IP address", self.name))
|
||||
end
|
||||
end
|
||||
return res
|
||||
end
|
||||
|
||||
function Module:init(t)
|
||||
if t.interval ~= nil then
|
||||
self.runInterval = tonumber(t.interval)
|
||||
end
|
||||
if t.interval_failed ~= nil then
|
||||
self.runIntervalFailed = tonumber(t.interval_failed)
|
||||
end
|
||||
if t.request_attempts ~= nil then
|
||||
self.requestAttempts = tonumber(t.request_attempts)
|
||||
end
|
||||
if t.timeout ~= nil then
|
||||
self.timeout = tonumber(t.timeout)
|
||||
end
|
||||
if t.provider ~= nil then
|
||||
self._provider = self.providers[t.provider]
|
||||
else
|
||||
self._provider = self.providers.opendns1
|
||||
end
|
||||
if self.config.configDir then
|
||||
self.ipScript = string.format(
|
||||
"%s/public-ip-script.%s", self.config.configDir, self.config.serviceConfig.instance)
|
||||
if t.enable_ip_script ~= nil then
|
||||
self.enableIpScript = (tonumber(t.enable_ip_script) ~= 0)
|
||||
end
|
||||
end
|
||||
if t.qtype ~= nil then
|
||||
self._qtype = (tonumber(t.qtype) ~= 0)
|
||||
end
|
||||
self._currentIp = nil
|
||||
self._lastResolvedIp = nil
|
||||
self._DNSPacket = nil
|
||||
self._interval = self.runInterval
|
||||
self._IPFalseCounter = 0
|
||||
self._enabled = true
|
||||
if not self._provider then
|
||||
self._enabled = false
|
||||
else
|
||||
if self._provider.url and not unistd.access(self.curlExec, "x") then
|
||||
self._enabled = false
|
||||
self.syslog("err", string.format(
|
||||
"%s: %s is not available. You need to install curl.", self.name, self.curlExec))
|
||||
end
|
||||
if self._provider.type == "dns" then
|
||||
self._requestIP = self.requestIPDNS
|
||||
elseif self._provider.type == "http" then
|
||||
self._requestIP = self.requestIPHTTP
|
||||
else
|
||||
self._enabled = false
|
||||
end
|
||||
end
|
||||
if (self.config.serviceConfig.proxy_type and
|
||||
self.config.serviceConfig.proxy_host and
|
||||
self.config.serviceConfig.proxy_port) then
|
||||
self._proxyString = string.format(
|
||||
" --proxy %s://%s:%d",
|
||||
self.config.serviceConfig.proxy_type,
|
||||
self.config.serviceConfig.proxy_host,
|
||||
self.config.serviceConfig.proxy_port)
|
||||
end
|
||||
end
|
||||
|
||||
function Module:run(currentStatus, lastStatus, timeDiff, timeNow, inetChecked)
|
||||
if not self._enabled then
|
||||
return
|
||||
end
|
||||
if currentStatus == 0 then
|
||||
if self._counter == 0 or self._counter >= self._interval or currentStatus ~= lastStatus then
|
||||
local ip = self:_requestIP()
|
||||
if not ip then
|
||||
ip = ""
|
||||
self._IPFalseCounter = self._IPFalseCounter + 1
|
||||
if self._IPFalseCounter >= self.requestAttempts then
|
||||
self._interval = self.runIntervalFailed
|
||||
self._IPFalseCounter = 0
|
||||
else
|
||||
self._interval = self.runIntervalIPFailed
|
||||
end
|
||||
else
|
||||
self._interval = self.runInterval
|
||||
self._IPFalseCounter = 0
|
||||
end
|
||||
if ip ~= self._currentIp then
|
||||
self.status = ip
|
||||
if ip ~= "" then
|
||||
if self._counter > 0 and ip ~= self._lastResolvedIp then
|
||||
self.syslog(
|
||||
"notice",
|
||||
string.format("%s: public IP address changed to %s", self.name, ip)
|
||||
)
|
||||
self:runIpScript()
|
||||
end
|
||||
self._lastResolvedIp = ip
|
||||
end
|
||||
end
|
||||
self._currentIp = ip
|
||||
self._counter = 0
|
||||
end
|
||||
else
|
||||
self._currentIp = nil
|
||||
self.status = self._currentIp
|
||||
self._IPFalseCounter = 0
|
||||
self._counter = 0
|
||||
self._interval = self.runInterval
|
||||
end
|
||||
self._counter = self._counter + timeDiff
|
||||
end
|
||||
|
||||
function Module:onExit()
|
||||
return true
|
||||
end
|
||||
|
||||
return Module
|
||||
@@ -1,63 +0,0 @@
|
||||
|
||||
local unistd = require("posix.unistd")
|
||||
|
||||
local Module = {
|
||||
name = "mod_reboot",
|
||||
runPrio = 20,
|
||||
config = {},
|
||||
syslog = function(level, msg) return true end,
|
||||
debugOutput = function(msg) return true end,
|
||||
writeValue = function(filePath, str) return false end,
|
||||
readValue = function(filePath) return nil end,
|
||||
deadPeriod = 3600,
|
||||
forceRebootDelay = 300,
|
||||
antiBootloopDelay = 300,
|
||||
status = nil,
|
||||
_deadCounter = 0,
|
||||
_rebooted = true,
|
||||
}
|
||||
|
||||
function Module:rebootDevice()
|
||||
self.syslog("warning", string.format("%s: reboot", self.name))
|
||||
os.execute("/sbin/reboot &")
|
||||
if self.forceRebootDelay > 0 then
|
||||
unistd.sleep(self.forceRebootDelay)
|
||||
self.syslog("warning", string.format("%s: force reboot", self.name))
|
||||
self.writeValue("/proc/sys/kernel/sysrq", "1")
|
||||
self.writeValue("/proc/sysrq-trigger", "b")
|
||||
end
|
||||
end
|
||||
|
||||
function Module:init(t)
|
||||
if t.dead_period ~= nil then
|
||||
self.deadPeriod = tonumber(t.dead_period)
|
||||
end
|
||||
if t.force_reboot_delay ~= nil then
|
||||
self.forceRebootDelay = tonumber(t.force_reboot_delay)
|
||||
end
|
||||
if tonumber(t.disconnected_at_startup) == 1 then
|
||||
self._rebooted = false
|
||||
end
|
||||
end
|
||||
|
||||
function Module:run(currentStatus, lastStatus, timeDiff, timeNow, inetChecked)
|
||||
if currentStatus == 1 then
|
||||
if not self._rebooted then
|
||||
if timeNow >= self.antiBootloopDelay and self._deadCounter >= self.deadPeriod then
|
||||
self:rebootDevice()
|
||||
self._rebooted = true
|
||||
else
|
||||
self._deadCounter = self._deadCounter + timeDiff
|
||||
end
|
||||
end
|
||||
else
|
||||
self._deadCounter = 0
|
||||
self._rebooted = false
|
||||
end
|
||||
end
|
||||
|
||||
function Module:onExit()
|
||||
return true
|
||||
end
|
||||
|
||||
return Module
|
||||
@@ -1,67 +0,0 @@
|
||||
|
||||
local stdlib = require("posix.stdlib")
|
||||
local time = require("posix.time")
|
||||
local unistd = require("posix.unistd")
|
||||
|
||||
local Module = {
|
||||
name = "mod_regular_script",
|
||||
runPrio = 90,
|
||||
config = {},
|
||||
syslog = function(level, msg) return true end,
|
||||
debugOutput = function(msg) return true end,
|
||||
writeValue = function(filePath, str) return false end,
|
||||
readValue = function(filePath) return nil end,
|
||||
inetState = 2, -- 0: connected, 1: disconnected, 2: both
|
||||
runInterval = 3600,
|
||||
script = "",
|
||||
status = nil,
|
||||
_nextTime = nil,
|
||||
_firstRun = true,
|
||||
}
|
||||
|
||||
function Module:runExternalScript(scriptPath, currentStatus)
|
||||
if unistd.access(scriptPath, "r") then
|
||||
stdlib.setenv("INET_STATE", currentStatus)
|
||||
os.execute(string.format('/bin/sh "%s" &', scriptPath))
|
||||
end
|
||||
end
|
||||
|
||||
function Module:init(t)
|
||||
if t.inet_state ~= nil then
|
||||
self.inetState = tonumber(t.inet_state)
|
||||
end
|
||||
if t.interval ~= nil then
|
||||
self.runInterval = tonumber(t.interval)
|
||||
end
|
||||
if self.config.configDir then
|
||||
self.script = string.format(
|
||||
"%s/regular-script.%s", self.config.configDir, self.config.serviceConfig.instance)
|
||||
end
|
||||
end
|
||||
|
||||
function Module:run(currentStatus, lastStatus, timeDiff, timeNow, inetChecked)
|
||||
if not self._nextTime then
|
||||
if timeNow < self.runInterval then
|
||||
self._nextTime = self.runInterval
|
||||
else
|
||||
self._nextTime = timeNow - (timeNow % self.runInterval) + self.runInterval
|
||||
end
|
||||
end
|
||||
if self._firstRun then
|
||||
self.status = time.strftime ("%Y-%m-%d %H:%M:%S %z", time.localtime(time.time() + self._nextTime - timeNow))
|
||||
self._firstRun = false
|
||||
end
|
||||
if timeNow >= self._nextTime then
|
||||
self._nextTime = self._nextTime + self.runInterval
|
||||
if self.inetState == 2 or (self.inetState == 0 and currentStatus == 0) or (self.inetState == 1 and currentStatus == 1) then
|
||||
self.status = time.strftime ("%Y-%m-%d %H:%M:%S %z", time.localtime(time.time() + self._nextTime - timeNow))
|
||||
self:runExternalScript(self.script, currentStatus)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function Module:onExit()
|
||||
return true
|
||||
end
|
||||
|
||||
return Module
|
||||
@@ -1,134 +0,0 @@
|
||||
|
||||
local unistd = require("posix.unistd")
|
||||
|
||||
local Module = {
|
||||
name = "mod_user_scripts",
|
||||
runPrio = 80,
|
||||
config = {},
|
||||
syslog = function(level, msg) return true end,
|
||||
debugOutput = function(msg) return true end,
|
||||
writeValue = function(filePath, str) return false end,
|
||||
readValue = function(filePath) return nil end,
|
||||
deadPeriod = 0,
|
||||
alivePeriod = 0,
|
||||
upScript = "",
|
||||
downScript = "",
|
||||
upScriptAttempts = 1,
|
||||
upScriptAttemptInterval = 15,
|
||||
downScriptAttempts = 1,
|
||||
downScriptAttemptInterval = 15,
|
||||
status = nil,
|
||||
_deadCounter = 0,
|
||||
_aliveCounter = 0,
|
||||
_upScriptAttemptsCounter = 0,
|
||||
_upScriptAttemptIntervalCounter = 0,
|
||||
_downScriptAttemptsCounter = 0,
|
||||
_downScriptAttemptIntervalCounter = 0,
|
||||
_upScriptFirstAttempt = true,
|
||||
_downScriptFirstAttempt = true,
|
||||
_disconnectedAtStartup = false,
|
||||
_connectedAtStartup = false,
|
||||
}
|
||||
|
||||
function Module:runExternalScript(scriptPath)
|
||||
if unistd.access(scriptPath, "r") then
|
||||
os.execute(string.format('/bin/sh "%s" &', scriptPath))
|
||||
end
|
||||
end
|
||||
|
||||
function Module:init(t)
|
||||
if t.dead_period ~= nil then
|
||||
self.deadPeriod = tonumber(t.dead_period)
|
||||
end
|
||||
if t.alive_period ~= nil then
|
||||
self.alivePeriod = tonumber(t.alive_period)
|
||||
end
|
||||
if t.up_script_attempts ~= nil then
|
||||
self.upScriptAttempts = tonumber(t.up_script_attempts)
|
||||
end
|
||||
if t.up_script_attempt_interval ~= nil then
|
||||
self.upScriptAttemptInterval = tonumber(t.up_script_attempt_interval)
|
||||
end
|
||||
if t.down_script_attempts ~= nil then
|
||||
self.downScriptAttempts = tonumber(t.down_script_attempts)
|
||||
end
|
||||
if t.down_script_attempt_interval ~= nil then
|
||||
self.downScriptAttemptInterval = tonumber(t.down_script_attempt_interval)
|
||||
end
|
||||
if self.config.configDir then
|
||||
self.upScript = string.format(
|
||||
"%s/up-script.%s", self.config.configDir, self.config.serviceConfig.instance)
|
||||
self.downScript = string.format(
|
||||
"%s/down-script.%s", self.config.configDir, self.config.serviceConfig.instance)
|
||||
end
|
||||
if tonumber(t.connected_at_startup) == 1 then
|
||||
self._connectedAtStartup = true
|
||||
end
|
||||
if tonumber(t.disconnected_at_startup) == 1 then
|
||||
self._disconnectedAtStartup = true
|
||||
end
|
||||
end
|
||||
|
||||
function Module:runUpScriptFunc()
|
||||
self:runExternalScript(self.upScript)
|
||||
if self.upScriptAttempts > 0 then
|
||||
self._upScriptAttemptsCounter = self._upScriptAttemptsCounter + 1
|
||||
end
|
||||
end
|
||||
|
||||
function Module:runDownScriptFunc()
|
||||
self:runExternalScript(self.downScript)
|
||||
if self.downScriptAttempts > 0 then
|
||||
self._downScriptAttemptsCounter = self._downScriptAttemptsCounter + 1
|
||||
end
|
||||
end
|
||||
|
||||
function Module:run(currentStatus, lastStatus, timeDiff, timeNow, inetChecked)
|
||||
if currentStatus == 1 then
|
||||
self._upScriptAttemptsCounter = 0
|
||||
self._upScriptAttemptIntervalCounter = 0
|
||||
self._aliveCounter = 0
|
||||
self._connectedAtStartup = true
|
||||
self._upScriptFirstAttempt = true
|
||||
|
||||
if self._disconnectedAtStartup and self._deadCounter >= self.deadPeriod then
|
||||
if self.downScriptAttempts == 0 or self._downScriptAttemptsCounter < self.downScriptAttempts then
|
||||
if self._downScriptFirstAttempt or self._downScriptAttemptIntervalCounter >= self.downScriptAttemptInterval then
|
||||
self:runDownScriptFunc()
|
||||
self._downScriptAttemptIntervalCounter = 0
|
||||
self._downScriptFirstAttempt = false
|
||||
else
|
||||
self._downScriptAttemptIntervalCounter = self._downScriptAttemptIntervalCounter + timeDiff
|
||||
end
|
||||
end
|
||||
else
|
||||
self._deadCounter = self._deadCounter + timeDiff
|
||||
end
|
||||
elseif currentStatus == 0 then
|
||||
self._downScriptAttemptsCounter = 0
|
||||
self._downScriptAttemptIntervalCounter = 0
|
||||
self._deadCounter = 0
|
||||
self._disconnectedAtStartup = true
|
||||
self._downScriptFirstAttempt = true
|
||||
|
||||
if self._connectedAtStartup and self._aliveCounter >= self.alivePeriod then
|
||||
if self.upScriptAttempts == 0 or self._upScriptAttemptsCounter < self.upScriptAttempts then
|
||||
if self._upScriptFirstAttempt or self._upScriptAttemptIntervalCounter >= self.upScriptAttemptInterval then
|
||||
self:runUpScriptFunc()
|
||||
self._upScriptAttemptIntervalCounter = 0
|
||||
self._upScriptFirstAttempt = false
|
||||
else
|
||||
self._upScriptAttemptIntervalCounter = self._upScriptAttemptIntervalCounter + timeDiff
|
||||
end
|
||||
end
|
||||
else
|
||||
self._aliveCounter = self._aliveCounter + timeDiff
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function Module:onExit()
|
||||
return true
|
||||
end
|
||||
|
||||
return Module
|
||||
Reference in New Issue
Block a user