Skip to content
Merged
30 changes: 28 additions & 2 deletions apisix/discovery/kubernetes/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -372,13 +372,37 @@ local _M = {
}


local function refresh_token(handle, token_file)
local file, err = read_env(token_file)
if err then
core.log.error("failed to read token file path: ", err)
return
end

local token, err = util.read_file(file)
if err then
core.log.error("failed to refresh token from file: ", err)
return
end

token = token:gsub("%s+", "")
if token ~= handle.apiserver.token then
core.log.info("kubernetes token updated")
handle.apiserver.token = token
end
end

local function start_fetch(handle)
local timer_runner
timer_runner = function(premature)
if premature then
return
end

if handle.token_file then
refresh_token(handle, handle.token_file)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bad name

cache -> refresh: this is a good name
no cache -> refresh: it is weird

it should be name to read token or fetch token

end

local ok, status = pcall(handle.list_watch, handle, handle.apiserver)

local retry_interval = 0
Expand Down Expand Up @@ -459,7 +483,8 @@ local function single_mode_init(conf)
ctx = setmetatable({
endpoint_dict = endpoint_dict,
apiserver = apiserver,
default_weight = default_weight
default_weight = default_weight,
token_file = conf.client.token_file,
}, { __index = endpoints_informer })

start_fetch(ctx)
Expand Down Expand Up @@ -565,7 +590,8 @@ local function multiple_mode_init(confs)
ctx[id] = setmetatable({
endpoint_dict = endpoint_dict,
apiserver = apiserver,
default_weight = default_weight
default_weight = default_weight,
token_file = conf.client.token_file,
}, { __index = endpoints_informer })
end

Expand Down
36 changes: 36 additions & 0 deletions t/kubernetes/discovery/kubernetes.t
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,20 @@ _EOC_
}
}

location /update_token {
content_by_lua_block {
local token_file = "$::token_file"
local file = io.open(token_file, "w")
file:write("invalid_token_value")
file:close()
ngx.sleep(2)
file = io.open(token_file, "w")
local token_value = [[$::token_value]]
file:write(token_value)
file:close()
}
}

_EOC_

$block->set_value("config", $config);
Expand Down Expand Up @@ -346,3 +360,25 @@ GET /compare
Content-type: application/json
--- response_body
true



=== TEST 7: auto refresh token when token expired
--- yaml_config
apisix:
node_listen: 1984
config_center: yaml
deployment:
role: data_plane
role_data_plane:
config_provider: yaml
discovery:
kubernetes:
client:
token_file: /tmp/var/run/secrets/kubernetes.io/serviceaccount/token
--- request
GET /update_token
--- grep_error_log eval
qr/list failed, kind: Endpoints, reason: Unauthorized/
--- grep_error_log_out
list failed, kind: Endpoints, reason: Unauthorized
Loading