Browse Source

Enhance network.port_is_up function with a timeout loop for basic port checks. Implement logging for connection attempts and results, improving feedback on port availability status. This change optimizes performance by creating the TCP socket once and logging progress every 10 attempts.

main
Bastian (BaM) 3 months ago
parent
commit
a6164c6333
  1. 58
      scripts/network.lua

58
scripts/network.lua

@ -55,21 +55,63 @@ function network.port_is_up(host, port, timeout_sec)
-- Fallback to basic check if socket is not available
if not network.is_socket_available() then
utils.log("Socket module not available, using basic port check with " .. timeout .. "s timeout")
local cmd = string.format("nc -z -w%d %s %d 2>/dev/null", timeout, host, port)
local result = os.execute(cmd)
return result == 0
-- Implement timeout loop with short intervals
local start_time = os.time()
local check_interval = 1 -- Check every 1 second
while (os.time() - start_time) < timeout do
local cmd = string.format("nc -z -w1 %s %d 2>/dev/null", host, port)
local result = os.execute(cmd)
if result == 0 then
utils.log("Port " .. port .. " is now available on " .. host)
return true
end
-- Wait before next check
if (os.time() - start_time) < timeout then
utils.log("Port " .. port .. " not yet available on " .. host .. ", retrying in " .. check_interval .. "s...")
os.execute("sleep " .. check_interval)
end
end
utils.log("Port " .. port .. " not available on " .. host .. " after " .. timeout .. "s timeout")
return false
end
local deadline = socket.gettime() + timeout
local check_count = 0
-- Create TCP socket once outside the loop for better performance
local tcp = socket.tcp()
if not tcp then
utils.log("Failed to create TCP socket")
return false
end
tcp:settimeout(1)
while socket.gettime() < deadline do
local tcp = socket.tcp()
if not tcp then return false end
tcp:settimeout(1)
check_count = check_count + 1
local ok = tcp:connect(host, port)
tcp:close()
if ok then return true end
tcp:close() -- Close connection after each attempt
if ok then
utils.log("Port " .. port .. " is now available on " .. host .. " (attempt " .. check_count .. ")")
return true
end
-- Log progress every 10 attempts
if check_count % 10 == 0 then
local elapsed = socket.gettime() - (deadline - timeout)
utils.log("Port " ..
port ..
" not yet available on " .. host .. " (attempt " .. check_count .. ", " .. math.floor(elapsed) .. "s elapsed)")
end
socket.sleep(0.5)
end
utils.log("Port " ..
port .. " not available on " .. host .. " after " .. timeout .. "s timeout (" .. check_count .. " attempts)")
return false
end

Loading…
Cancel
Save