diff --git a/changelog/unreleased/kong/fix-loggly-hostname-notfound.yml b/changelog/unreleased/kong/fix-loggly-hostname-notfound.yml new file mode 100644 index 000000000000..5e2cadb73bdd --- /dev/null +++ b/changelog/unreleased/kong/fix-loggly-hostname-notfound.yml @@ -0,0 +1,2 @@ +message: "**loggly**: fixed the error caused by the missing `/bin/hostname`." +type: bugfix diff --git a/kong/pdk/node.lua b/kong/pdk/node.lua index 9302c17cde1a..23f83ca449d1 100644 --- a/kong/pdk/node.lua +++ b/kong/pdk/node.lua @@ -252,15 +252,15 @@ local function new(self) local buf = ffi_new("unsigned char[?]", SIZE) local res = C.gethostname(buf, SIZE) - if res == 0 then - local hostname = ffi_str(buf, SIZE) - return gsub(hostname, "%z+$", "") + if res ~= 0 then + -- Return an empty string "" instead of nil and error message, + -- because strerror is not thread-safe and the behavior of strerror_r + -- is inconsistent across different systems. + return "" end - local f = io.popen("/bin/hostname") - local hostname = f:read("*a") or "" - f:close() - return gsub(hostname, "\n$", "") + local hostname = ffi_str(buf, SIZE) + return gsub(hostname, "%z+$", "") end diff --git a/kong/plugins/loggly/handler.lua b/kong/plugins/loggly/handler.lua index 9288adb37b7c..1e3eb4eab8b0 100644 --- a/kong/plugins/loggly/handler.lua +++ b/kong/plugins/loggly/handler.lua @@ -1,6 +1,7 @@ local cjson = require "cjson" local sandbox = require "kong.tools.sandbox".sandbox local kong_meta = require "kong.meta" +local get_host_name = require "kong.pdk.node".new().get_hostname local kong = kong @@ -16,15 +17,6 @@ local insert = table.insert local sandbox_opts = { env = { kong = kong, ngx = ngx } } -local function get_host_name() - local f = io.popen("/bin/hostname") - local hostname = f:read("*a") or "" - f:close() - hostname = string.gsub(hostname, "\n$", "") - return hostname -end - - local HOSTNAME = get_host_name() local SENDER_NAME = "kong" local LOG_LEVELS = {