Dynamic reload first implementation

This commit is contained in:
Valeriano Manassero 2018-02-27 14:22:41 +01:00
parent 56036ddc57
commit 2f258be982
15 changed files with 860 additions and 15 deletions

View file

@ -50,7 +50,7 @@ IMAGE = $(REGISTRY)/$(IMGNAME)
MULTI_ARCH_IMG = $(IMAGE)-$(ARCH)
# Set default base image dynamically for each arch
BASEIMAGE?=quay.io/kubernetes-ingress-controller/nginx-$(ARCH):0.34
BASEIMAGE?=quay.io/kubernetes-ingress-controller/nginx-$(ARCH):0.35
ifeq ($(ARCH),arm)
QEMUARCH=arm

View file

@ -131,6 +131,8 @@ func parseFlags() (bool, *controller.Configuration, error) {
publishStatusAddress = flags.String("publish-status-address", "",
`User customized address to be set in the status of ingress resources. The controller will set the
endpoint records on the ingress using this address.`)
dynamicReload = flags.Bool("dynamic-reload", false, `Enable dynamic reloads`)
)
flag.Set("logtostderr", "true")
@ -222,6 +224,7 @@ func parseFlags() (bool, *controller.Configuration, error) {
SSLProxy: *sslProxyPort,
Status: *statusPort,
},
DynamicReload: *dynamicReload,
}
return false, config, nil

View file

@ -119,6 +119,12 @@ func main() {
glog.Fatalf("resync period (%vs) is too low", conf.ResyncPeriod.Seconds())
}
if conf.DynamicReload {
glog.Infof("Dynamic Reload ENABLED")
} else {
glog.Infof("Dynamic Reload DISABLED")
}
// create the default SSL certificate (dummy)
defCert, defKey := ssl.GetFakeSSLCert()
c, err := ssl.AddOrUpdateCertAndKey(fakeCertificate, defCert, defKey, []byte{}, fs)

View file

@ -60,4 +60,5 @@ Usage of :
--version Shows release information about the NGINX Ingress controller
--vmodule moduleSpec comma-separated list of pattern=N settings for file-filtered logging
--watch-namespace string Namespace to watch for Ingress. Default is to watch all namespaces
--dynamic-reload Defines if NGINX should add/remove virtualhosts without the classic reload (default false)
```

View file

@ -616,6 +616,7 @@ type TemplateConfig struct {
RedirectServers map[string]string
ListenPorts *ListenPorts
PublishService *apiv1.Service
DynamicReload bool
}
// ListenPorts describe the ports required to run the

View file

@ -95,6 +95,8 @@ type Configuration struct {
FakeCertificateSHA string
SyncRateLimit float32
DynamicReload bool
}
// GetPublishService returns the configured service used to set ingress status
@ -164,12 +166,14 @@ func (n *NGINXController) syncIngress(item interface{}) error {
PassthroughBackends: passUpstreams,
}
if !n.isForceReload() && n.runningConfig.Equal(&pcfg) {
glog.V(3).Infof("skipping backend reload (no changes detected)")
return nil
if !n.cfg.DynamicReload {
if !n.isForceReload() && n.runningConfig.Equal(&pcfg) {
glog.V(3).Infof("skipping backend reload (no changes detected)")
return nil
}
}
glog.Infof("backend reload required")
glog.Infof("backend reload/update required")
err := n.OnUpdate(pcfg)
if err != nil {
@ -178,7 +182,7 @@ func (n *NGINXController) syncIngress(item interface{}) error {
return err
}
glog.Infof("ingress backend successfully reloaded...")
glog.Infof("ingress backend successfully reloaded/updated...")
incReloadCount()
setSSLExpireTime(servers)

View file

@ -58,6 +58,9 @@ import (
"k8s.io/ingress-nginx/internal/net/ssl"
"k8s.io/ingress-nginx/internal/task"
"k8s.io/ingress-nginx/internal/watch"
"net/http"
"encoding/json"
"regexp"
)
type statusModule string
@ -73,6 +76,8 @@ var (
tmplPath = "/etc/nginx/template/nginx.tmpl"
geoipPath = "/etc/nginx/geoip"
cfgPath = "/etc/nginx/nginx.conf"
tmplvhostsPath = "/etc/nginx/template/routes.tmpl"
cfgvhostsPath = "/etc/nginx/routes.json"
nginxBinary = "/usr/sbin/nginx"
)
@ -181,6 +186,13 @@ Error loading new template : %v
n.t = ngxTpl
ngxvhostsTpl, err := ngx_template.NewTemplate(tmplvhostsPath, fs)
if err != nil {
glog.Fatalf("invalid NGINX VHOSTS template: %v", err)
}
n.tv = ngxvhostsTpl
// TODO: refactor
if _, ok := fs.(filesystem.DefaultFs); !ok {
watch.NewDummyFileWatcher(tmplPath, onTemplateChange)
@ -255,6 +267,7 @@ type NGINXController struct {
forceReload int32
t *ngx_template.Template
tv *ngx_template.Template
binary string
resolver []net.IP
@ -602,6 +615,31 @@ func (n *NGINXController) OnUpdate(ingressCfg ingress.Configuration) error {
cfg.SSLDHParam = sslDHParam
for _, server := range ingressCfg.Servers {
if server.SSLCertificate != "" {
b, err := ioutil.ReadFile(server.SSLCertificate)
if err == nil {
re := regexp.MustCompile(`\n`)
b_string := string(b)
b_string = re.ReplaceAllString(b_string, "\\n")
server.SSLCertificateReal = b_string
} else {
glog.Warningf("unexpected error reading certificate: %v (%v)", server.SSLCertificate, err)
}
}
if server.SSLFullChainCertificate != "" {
b, err := ioutil.ReadFile(server.SSLFullChainCertificate)
if err == nil {
re := regexp.MustCompile(`\n`)
b_string := string(b)
b_string = re.ReplaceAllString(b_string, "\\n")
server.SSLFullChainCertificateReal = b_string
} else {
glog.Warningf("unexpected error reading certificate: %v (%v)", server.SSLFullChainCertificate, err)
}
}
}
tc := ngx_config.TemplateConfig{
ProxySetHeaders: setHeaders,
AddHeaders: addHeaders,
@ -620,6 +658,7 @@ func (n *NGINXController) OnUpdate(ingressCfg ingress.Configuration) error {
IsSSLPassthroughEnabled: n.cfg.EnableSSLPassthrough,
ListenPorts: n.cfg.ListenPorts,
PublishService: n.GetPublishService(),
DynamicReload: n.cfg.DynamicReload,
}
content, err := n.t.Write(tc)
@ -632,7 +671,7 @@ func (n *NGINXController) OnUpdate(ingressCfg ingress.Configuration) error {
if err != nil {
return err
}
if glog.V(2) {
src, _ := ioutil.ReadFile(cfgPath)
if !bytes.Equal(src, content) {
@ -660,16 +699,78 @@ func (n *NGINXController) OnUpdate(ingressCfg ingress.Configuration) error {
}
}
err = ioutil.WriteFile(cfgPath, content, 0644)
if err != nil {
return err
}
if n.cfg.DynamicReload {
src, _ := ioutil.ReadFile(cfgPath)
if !bytes.Equal(src, content) {
err = ioutil.WriteFile(cfgPath, content, 0644)
if err != nil {
return err
}
o, err := exec.Command(n.binary, "-s", "reload", "-c", cfgPath).CombinedOutput()
if err != nil {
return fmt.Errorf("%v\n%v", err, string(o))
}
o, err := exec.Command(n.binary, "-s", "reload", "-c", cfgPath).CombinedOutput()
if err != nil {
return fmt.Errorf("%v\n%v", err, string(o))
}
} else {
glog.Infof("NGINX reload not needed, executing live update only\n")
}
content, err = n.tv.Write(tc)
err = os.Chmod(cfgvhostsPath, os.FileMode(0600))
if err != nil {
glog.Infof("Cannot chmod routes file\n")
}
if err != nil {
return err
}
err = ioutil.WriteFile(cfgvhostsPath, content, 0644)
if err != nil {
return err
}
retries := 1
updateOK := false
for retries <= 5 {
if !updateOK {
if retries > 1{
glog.Infof("NGINX dynamic update (retrying)\n")
}
srcvhosts, _ := ioutil.ReadFile(cfgvhostsPath)
b := new(bytes.Buffer)
srcvhosts_json := string(srcvhosts)
json.NewEncoder(b).Encode(srcvhosts_json)
resp, err := http.Post("http://localhost:" + strconv.Itoa(n.cfg.ListenPorts.Status) + "/nginx_update",
"application/json", b)
if err != nil {
time.Sleep(1 * time.Second)
glog.Infof("NGINX dynamic update not ready\n")
} else if resp.StatusCode != 200 {
time.Sleep(1 * time.Second)
glog.Infof("NGINX dynamic update not ready\n")
} else {
updateOK = true
glog.Infof("NGINX dynamic update OK\n")
}
}
retries += 1
}
if !updateOK {
return fmt.Errorf("%v\n%v", err, "Unexpected NGINX update error")
}
} else {
err = ioutil.WriteFile(cfgPath, content, 0644)
if err != nil {
return err
}
o, err := exec.Command(n.binary, "-s", "reload", "-c", cfgPath).CombinedOutput()
if err != nil {
return fmt.Errorf("%v\n%v", err, string(o))
}
}
return nil
}

View file

@ -138,9 +138,14 @@ type Server struct {
SSLPassthrough bool `json:"sslPassthrough"`
// SSLCertificate path to the SSL certificate on disk
SSLCertificate string `json:"sslCertificate"`
// SSLCertificateReal real value
SSLCertificateReal string `json:"sslCertificateReal"`
// SSLFullChainCertificate path to the SSL certificate on disk
// This certificate contains the full chain (ca + intermediates + cert)
SSLFullChainCertificate string `json:"sslFullChainCertificate"`
// SSLFullChainCertificateReal real value
// This certificate contains the full chain (ca + intermediates + cert)
SSLFullChainCertificateReal string `json:"sslFullChainCertificateReal"`
// SSLExpireTime has the expire date of this certificate
SSLExpireTime time.Time `json:"sslExpireTime"`
// SSLPemChecksum returns the checksum of the certificate file on disk.

View file

@ -0,0 +1,71 @@
local json = require "json"
local b = require "ngx.balancer"
local http_host = ngx.var.host
local request_uri = ngx.var.request_uri
local shared_memory = ngx.shared.shared_memory;
local vhosts_json = shared_memory:get("VHOSTS")
local vhosts = json.decode(json.decode(vhosts_json))
local server = vhosts.servers[http_host]
if (server == nil) then
server = vhosts.servers["_"]
if (server == nil) then
ngx.status = 503
ngx.exit(ngx.status)
end
end
local location
local hit_length = 0
for k, v in pairs(server.locations) do
local path_length = string.len(k)
if string.sub(request_uri,1, path_length)==k then
if path_length > hit_length then
hit_length = path_length
location = server.locations[k]
end
end
end
if (location == nil) then
ngx.status = 404
ngx.exit(ngx.status)
end
if (location.endpoints == nil) then
ngx.status = 404
ngx.exit(ngx.status)
end
if (location.endpoints[1] == nil) then
ngx.status = 404
ngx.exit(ngx.status)
end
local selected_endpoint
local endpoints_roundrobin = ngx.shared.endpoints_roundrobin;
local ep_index = endpoints_roundrobin:get(http_host)
if ep_index == nil then
selected_endpoint = location.endpoints[1]
endpoints_roundrobin:set(http_host, 1, 600)
else
local new_index = ep_index + 1
if location.endpoints[new_index] == nil then
selected_endpoint = location.endpoints[1]
endpoints_roundrobin:set(http_host, 1, 600)
else
selected_endpoint = location.endpoints[new_index]
endpoints_roundrobin:set(http_host, new_index, 600)
end
end
local max_retries = 20
if selected_endpoint.maxfails ~= 0 then
max_retries = selected_endpoint.maxfails
end
assert(b.set_current_peer(selected_endpoint.hostname, selected_endpoint.port))
if (selected_endpoint.failtimeout ~= 0) then
assert(b.set_timeouts(selected_endpoint.failtimeout, selected_endpoint.failtimeout, selected_endpoint.failtimeout))
end

View file

@ -0,0 +1,67 @@
local json = require "json"
local ssl = require "ngx.ssl"
local shared_memory = ngx.shared.shared_memory;
local http_host, err = ssl.server_name()
if http_host ~= nil then
local vhosts_json = shared_memory:get("VHOSTS")
local vhosts = json.decode(json.decode(vhosts_json))
local server = vhosts.servers[http_host]
if (server == nil) then
server = vhosts.servers["_"]
if (server == nil) then
ngx.status = 503
ngx.exit(ngx.status)
end
end
if server.sslcertificate ~= "" then
local ok, err = ssl.clear_certs()
if not ok then
ngx.log(ngx.ERR, "SSL ["..http_host.."]: failed to clear fallback certificates")
return ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
end
local cert_key_data = server.sslcertificatereal
if cert_key_data == nil then
ngx.log(ngx.ERR, "SSL certificate not found in memory")
return ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
end
local pem_cert_chain = string.match(cert_key_data, "%-*BEGIN CERTIFICATE.-END CERTIFICATE%-*")
local der_cert_chain, err = ssl.cert_pem_to_der(pem_cert_chain)
if not der_cert_chain then
ngx.log(ngx.ERR, "failed to convert certificate chain ",
"from PEM to DER: ", err)
return ngx.exit(ngx.ERROR)
end
local ok, err = ssl.set_der_cert(der_cert_chain)
if not ok then
ngx.log(ngx.ERR, "failed to set DER cert: ", err)
return ngx.exit(ngx.ERROR)
end
local pem_pkey = string.match(cert_key_data, "%-*BEGIN RSA PRIVATE KEY.-END RSA PRIVATE KEY%-*")
local der_pkey, err = ssl.priv_key_pem_to_der(pem_pkey)
if not der_pkey then
ngx.log(ngx.ERR, "failed to convert private key ",
"from PEM to DER: ", err)
return ngx.exit(ngx.ERROR)
end
local ok, err = ssl.set_der_priv_key(der_pkey)
if not ok then
ngx.log(ngx.ERR, "failed to set DER private key: ", err)
return ngx.exit(ngx.ERROR)
end
end
else
ngx.log(ngx.ERR, "No SNI not provided from client")
end

View file

@ -0,0 +1,9 @@
if ngx.var.request_method == "POST" then
ngx.req.read_body()
local vhosts_json = ngx.req.get_body_data()
local shared_memory = ngx.shared.shared_memory
shared_memory:set("VHOSTS", vhosts_json, 0)
ngx.exit(200)
elseif method == "GET" then
ngx.exit(405)
end

View file

@ -0,0 +1 @@
{}

View file

@ -32,6 +32,14 @@ events {
}
http {
{{ if $all.DynamicReload }}
lua_package_path '/usr/local/lib/lua/0.10.12rc2/?.lua;;';
lua_shared_dict shared_memory 512m;
lua_shared_dict endpoints_roundrobin 512m;
lua_shared_dict endpoints_leastconn 512m;
lua_shared_dict endpoints_iphash 512m;
{{ end}}
{{/* we use the value of the header X-Forwarded-For to be able to use the geo_ip module */}}
{{ if $cfg.UseProxyProtocol }}
real_ip_header proxy_protocol;
@ -305,6 +313,7 @@ http {
{{ end }}
{{ range $name, $upstream := $backends }}
{{ if (or (not ($all.DynamicReload)) (eq $upstream.Name "upstream-default-backend")) }}
{{ if eq $upstream.SessionAffinity.AffinityType "cookie" }}
upstream sticky-{{ $upstream.Name }} {
sticky hash={{ $upstream.SessionAffinity.CookieSessionAffinity.Hash }} name={{ $upstream.SessionAffinity.CookieSessionAffinity.Name }} httponly;
@ -336,6 +345,20 @@ http {
{{ end }}
}
{{ end }}
{{ end }}
{{ if $all.DynamicReload }}
## start server vhosts
upstream dynamic-upstream {
server 0.0.0.1;
balancer_by_lua_file /etc/nginx/lua/balancer.lua;
}
## end server vhosts
{{ end }}
{{/* build the maps that will be use to validate the Whitelist */}}
@ -409,6 +432,65 @@ http {
}
{{ end }}
{{ if $all.DynamicReload }}
## start server vhosts
server {
server_name _;
{{ range $address := $all.Cfg.BindAddressIpv4 }}
listen {{ $address }}:{{ $all.ListenPorts.HTTP }}{{ if $all.Cfg.UseProxyProtocol }} proxy_protocol{{ end }};
{{ else }}
listen {{ $all.ListenPorts.HTTP }}{{ if $all.Cfg.UseProxyProtocol }} proxy_protocol{{ end }};
{{ end }}
{{ if $all.IsIPV6Enabled }}
{{ range $address := $all.Cfg.BindAddressIpv6 }}
listen {{ $address }}:{{ $all.ListenPorts.HTTP }}{{ if $all.Cfg.UseProxyProtocol }} proxy_protocol{{ end }};
{{ else }}
listen [::]:{{ $all.ListenPorts.HTTP }}{{ if $all.Cfg.UseProxyProtocol }} proxy_protocol{{ end }};
{{ end }}
{{ end }}
set $proxy_upstream_name "-";
{{ range $address := $all.Cfg.BindAddressIpv4 }}
listen {{ $address }}:{{ if $all.IsSSLPassthroughEnabled }}{{ $all.ListenPorts.SSLProxy }} proxy_protocol {{ else }}{{ $all.ListenPorts.HTTPS }}{{ if $all.Cfg.UseProxyProtocol }} proxy_protocol{{ end }}{{ end }} ssl {{ if $all.Cfg.UseHTTP2 }}http2{{ end }};
{{ else }}
listen {{ if $all.IsSSLPassthroughEnabled }}{{ $all.ListenPorts.SSLProxy }} proxy_protocol {{ else }}{{ $all.ListenPorts.HTTPS }}{{ if $all.Cfg.UseProxyProtocol }} proxy_protocol{{ end }}{{ end }} ssl {{ if $all.Cfg.UseHTTP2 }}http2{{ end }};
{{ end }}
{{ if $all.IsIPV6Enabled }}
{{ range $address := $all.Cfg.BindAddressIpv6 }}
listen {{ $address }}:{{ if $all.IsSSLPassthroughEnabled }}{{ $all.ListenPorts.SSLProxy }} proxy_protocol{{ else }}{{ $all.ListenPorts.HTTPS }}{{ if $all.Cfg.UseProxyProtocol }} proxy_protocol{{ end }}{{ end }} ssl {{ if $all.Cfg.UseHTTP2 }}http2{{ end }};
{{ else }}
listen [::]:{{ if $all.IsSSLPassthroughEnabled }}{{ $all.ListenPorts.SSLProxy }} proxy_protocol{{ else }}{{ $all.ListenPorts.HTTPS }}{{ if $all.Cfg.UseProxyProtocol }} proxy_protocol{{ end }}{{ end }} ssl {{ if $all.Cfg.UseHTTP2 }}http2{{ end }};
{{ end }}
{{ end }}
ssl_certificate /ingress-controller/ssl/default-fake-certificate.pem;
ssl_certificate_key /ingress-controller/ssl/default-fake-certificate.pem;
ssl_certificate_by_lua_file /etc/nginx/lua/ssl.lua;
{{ if not (empty $cfg.ServerSnippet) }}
# Custom code snippet configured in the configuration configmap
{{ $cfg.ServerSnippet }}
{{ end }}
location / {
proxy_intercept_errors off;
proxy_set_header X-Format $http_accept;
proxy_set_header X-Original-URI $request_uri;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header HOST $host;
if ($scheme = https) {
add_header HTTPS on;
}
proxy_pass http://dynamic-upstream;
}
}
## end server vhosts
{{ else }}
{{ range $index, $server := $servers }}
## start server {{ $server.Hostname }}
@ -427,6 +509,8 @@ http {
{{ end }}
{{ end }}
# default server, used for NGINX healthcheck and access to nginx stats
server {
# Use the port {{ $all.ListenPorts.Status }} (random value just to avoid known ports) as default port for nginx.
@ -441,6 +525,18 @@ http {
return 200;
}
{{ if $all.DynamicReload }}
location /nginx_update {
client_max_body_size 512m;
client_body_buffer_size 512m;
access_log off;
content_by_lua_file /etc/nginx/lua/update.lua;
limit_except POST {
deny all;
}
}
{{ end }}
location /nginx_status {
set $proxy_upstream_name "internal";

View file

@ -0,0 +1,100 @@
{{ $cfg := .Cfg }}
{{ $listenports := .ListenPorts }}
{{ $backlogsize := .BacklogSize }}
{{ $isipv6enabled := .IsIPV6Enabled }}
{{ $issslpassthroughenabled := .IsSSLPassthroughEnabled }}
{{ $proxysetheaders := .ProxySetHeaders }}
{{ $servers := .Servers }}
{{ $backends := .Backends }}
{
"cfg" : {
"upstreamkeepaliveconnections" : "{{ $cfg.UpstreamKeepaliveConnections }}",
"loadbalancealgorithm" : "{{ $cfg.LoadBalanceAlgorithm }}",
"serversnippet" : "{{ $cfg.ServerSnippet }}",
"customhttperrors" : [
{{ range $index, $errCode := $cfg.CustomHTTPErrors }}
{{if $index}},{{end}}
"{{ $errCode }}"
{{ end }}
],
"bindaddressipv4" : [
{{ range $index, $address := $cfg.BindAddressIpv4 }}
{{if $index}},{{end}}
"{{ $address }}"
{{ end }}
],
"bindaddressipv6" : [
{{ range $index, $address := $cfg.BindAddressIpv6 }}
{{if $index}},{{end}}
"{{ $address }}"
{{ end }}
],
"useproxyprotocol" : "{{ $cfg.UseProxyProtocol }}",
"reuseport" : "{{ $cfg.ReusePort }}",
"usehttp2" : "{{ $cfg.UseHTTP2 }}",
"enablemodsecurity" : "{{ $cfg.EnableModsecurity }}",
"enableowaspcorerules" : "{{ $cfg.EnableOWASPCoreRules }}",
"computefullforwardedfor" : "{{ $cfg.ComputeFullForwardedFor }}",
"ForwardedForHeader" : "{{ $cfg.ForwardedForHeader }}",
"hsts" : "{{ $cfg.HSTS }}",
"hstsmaxage" : "{{ $cfg.HSTSMaxAge }}",
"hstsincludesubdomains" : "{{ $cfg.HSTSIncludeSubdomains }}",
"hstspreload" : "{{ $cfg.HSTSPreload }}",
"enablevtsstatus" : "{{ $cfg.EnableVtsStatus }}",
"httpredirectcode" : "{{ $cfg.HTTPRedirectCode }}",
"retrynonidempotent" : "{{ $cfg.RetryNonIdempotent }}",
"locationsnippet" : "{{ $cfg.LocationSnippet }}"
},
"listenports" : {
"http" : "{{ $listenports.HTTP }}",
"https" : "{{ $listenports.HTTPS }}",
"sslproxy" : "{{ $listenports.SSLProxy }}"
},
"backlogsize" : "{{ $backlogsize }}",
"isipv6enabled" : "{{ $isipv6enabled }}",
"issslpassthroughenabled" : "{{ $issslpassthroughenabled }}",
"servers" : {
{{ range $index, $server := $servers }}
{{if $index}},{{end}}
"{{ $server.Hostname }}" : {
"alias" : "{{ $server.Alias }}",
"sslcertificate" : "{{ $server.SSLCertificate }}",
"sslcertificatereal" : "{{ $server.SSLCertificateReal }}",
"sslfullchaincertificate" : "{{ $server.SSLFullChainCertificate }}",
"sslfullchaincertificatereal" : "{{ $server.SSLFullChainCertificateReal }}",
"locations" : {
{{ range $index, $location := $server.Locations }}
{{if $index}},{{end}}
"{{ $location.Path }}" : {
{{ range $name, $upstream := $backends }}
{{ if eq $upstream.Name $location.Backend }}
"name" : "{{ $upstream.Name }}",
"upstreamhashby" : "{{ $upstream.UpstreamHashBy }}",
"sessionaffinity" : {
"affinitytype" : "{{ $upstream.SessionAffinity.AffinityType }}",
"cookiesessionaffinity" : {
"name" : "{{ $upstream.SessionAffinity.CookieSessionAffinity.Name }}",
"hash" : "{{ $upstream.SessionAffinity.CookieSessionAffinity.Hash }}"
}
},
"endpoints" : [
{{ range $index, $endpoint := $upstream.Endpoints }}
{{if $index}},{{end}}
{
"hostname" : "{{ $endpoint.Address | formatIP }}",
"port" : {{ $endpoint.Port }},
"maxfails" : {{ $endpoint.MaxFails }},
"failtimeout" : {{ $endpoint.FailTimeout }}
}
{{ end }}
]
{{ end }}
{{ end }}
}
{{ end }}
}
}
{{ end }}
}
}

View file

@ -0,0 +1,380 @@
--
-- json.lua
--
-- Copyright (c) 2015 rxi
--
-- This library is free software; you can redistribute it and/or modify it
-- under the terms of the MIT license. See LICENSE for details.
--
local json = { _version = "0.1.0" }
-------------------------------------------------------------------------------
-- Encode
-------------------------------------------------------------------------------
local encode
local escape_char_map = {
[ "\\" ] = "\\\\",
[ "\"" ] = "\\\"",
[ "\b" ] = "\\b",
[ "\f" ] = "\\f",
[ "\n" ] = "\\n",
[ "\r" ] = "\\r",
[ "\t" ] = "\\t",
}
local escape_char_map_inv = { [ "\\/" ] = "/" }
for k, v in pairs(escape_char_map) do
escape_char_map_inv[v] = k
end
local function escape_char(c)
return escape_char_map[c] or string.format("\\u%04x", c:byte())
end
local function encode_nil(val)
return "null"
end
local function encode_table(val, stack)
local res = {}
stack = stack or {}
-- Circular reference?
if stack[val] then error("circular reference") end
stack[val] = true
if val[1] ~= nil or next(val) == nil then
-- Treat as array -- check keys are valid and it is not sparse
local n = 0
for k in pairs(val) do
if type(k) ~= "number" then
error("invalid table: mixed or invalid key types")
end
n = n + 1
end
if n ~= #val then
error("invalid table: sparse array")
end
-- Encode
for i, v in ipairs(val) do
table.insert(res, encode(v, stack))
end
stack[val] = nil
return "[" .. table.concat(res, ",") .. "]"
else
-- Treat as an object
for k, v in pairs(val) do
if type(k) ~= "string" then
error("invalid table: mixed or invalid key types")
end
table.insert(res, encode(k, stack) .. ":" .. encode(v, stack))
end
stack[val] = nil
return "{" .. table.concat(res, ",") .. "}"
end
end
local function encode_string(val)
return '"' .. val:gsub('[%z\1-\31\\"]', escape_char) .. '"'
end
local function encode_number(val)
-- Check for NaN, -inf and inf
if val ~= val or val <= -math.huge or val >= math.huge then
error("unexpected number value '" .. tostring(val) .. "'")
end
return string.format("%.14g", val)
end
local type_func_map = {
[ "nil" ] = encode_nil,
[ "table" ] = encode_table,
[ "string" ] = encode_string,
[ "number" ] = encode_number,
[ "boolean" ] = tostring,
}
encode = function(val, stack)
local t = type(val)
local f = type_func_map[t]
if f then
return f(val, stack)
end
error("unexpected type '" .. t .. "'")
end
function json.encode(val)
return ( encode(val) )
end
-------------------------------------------------------------------------------
-- Decode
-------------------------------------------------------------------------------
local parse
local function create_set(...)
local res = {}
for i = 1, select("#", ...) do
res[ select(i, ...) ] = true
end
return res
end
local space_chars = create_set(" ", "\t", "\r", "\n")
local delim_chars = create_set(" ", "\t", "\r", "\n", "]", "}", ",")
local escape_chars = create_set("\\", "/", '"', "b", "f", "n", "r", "t", "u")
local literals = create_set("true", "false", "null")
local literal_map = {
[ "true" ] = true,
[ "false" ] = false,
[ "null" ] = nil,
}
local function next_char(str, idx, set, negate)
for i = idx, #str do
if set[str:sub(i, i)] ~= negate then
return i
end
end
return #str + 1
end
local function decode_error(str, idx, msg)
local line_count = 1
local col_count = 1
for i = 1, idx - 1 do
col_count = col_count + 1
if str:sub(i, i) == "\n" then
line_count = line_count + 1
col_count = 1
end
end
error( string.format("%s at line %d col %d", msg, line_count, col_count) )
end
local function codepoint_to_utf8(n)
-- http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=iws-appendixa
local f = math.floor
if n <= 0x7f then
return string.char(n)
elseif n <= 0x7ff then
return string.char(f(n / 64) + 192, n % 64 + 128)
elseif n <= 0xffff then
return string.char(f(n / 4096) + 224, f(n % 4096 / 64) + 128, n % 64 + 128)
elseif n <= 0x10ffff then
return string.char(f(n / 262144) + 240, f(n % 262144 / 4096) + 128,
f(n % 4096 / 64) + 128, n % 64 + 128)
end
error( string.format("invalid unicode codepoint '%x'", n) )
end
local function parse_unicode_escape(s)
local n1 = tonumber( s:sub(3, 6), 16 )
local n2 = tonumber( s:sub(9, 12), 16 )
-- Surrogate pair?
if n2 then
return codepoint_to_utf8((n1 - 0xd800) * 0x400 + (n2 - 0xdc00) + 0x10000)
else
return codepoint_to_utf8(n1)
end
end
local function parse_string(str, i)
local has_unicode_escape = false
local has_surrogate_escape = false
local has_escape = false
local last
for j = i + 1, #str do
local x = str:byte(j)
if x < 32 then
decode_error(str, j, "control character in string")
end
if last == 92 then -- "\\" (escape char)
if x == 117 then -- "u" (unicode escape sequence)
local hex = str:sub(j + 1, j + 5)
if not hex:find("%x%x%x%x") then
decode_error(str, j, "invalid unicode escape in string")
end
if hex:find("^[dD][89aAbB]") then
has_surrogate_escape = true
else
has_unicode_escape = true
end
else
local c = string.char(x)
if not escape_chars[c] then
decode_error(str, j, "invalid escape char '" .. c .. "' in string")
end
has_escape = true
end
last = nil
elseif x == 34 then -- '"' (end of string)
local s = str:sub(i + 1, j - 1)
if has_surrogate_escape then
s = s:gsub("\\u[dD][89aAbB]..\\u....", parse_unicode_escape)
end
if has_unicode_escape then
s = s:gsub("\\u....", parse_unicode_escape)
end
if has_escape then
s = s:gsub("\\.", escape_char_map_inv)
end
return s, j + 1
else
last = x
end
end
decode_error(str, i, "expected closing quote for string")
end
local function parse_number(str, i)
local x = next_char(str, i, delim_chars)
local s = str:sub(i, x - 1)
local n = tonumber(s)
if not n then
decode_error(str, i, "invalid number '" .. s .. "'")
end
return n, x
end
local function parse_literal(str, i)
local x = next_char(str, i, delim_chars)
local word = str:sub(i, x - 1)
if not literals[word] then
decode_error(str, i, "invalid literal '" .. word .. "'")
end
return literal_map[word], x
end
local function parse_array(str, i)
local res = {}
local n = 1
i = i + 1
while 1 do
local x
i = next_char(str, i, space_chars, true)
-- Empty / end of array?
if str:sub(i, i) == "]" then
i = i + 1
break
end
-- Read token
x, i = parse(str, i)
res[n] = x
n = n + 1
-- Next token
i = next_char(str, i, space_chars, true)
local chr = str:sub(i, i)
i = i + 1
if chr == "]" then break end
if chr ~= "," then decode_error(str, i, "expected ']' or ','") end
end
return res, i
end
local function parse_object(str, i)
local res = {}
i = i + 1
while 1 do
local key, val
i = next_char(str, i, space_chars, true)
-- Empty / end of object?
if str:sub(i, i) == "}" then
i = i + 1
break
end
-- Read key
if str:sub(i, i) ~= '"' then
decode_error(str, i, "expected string for key")
end
key, i = parse(str, i)
-- Read ':' delimiter
i = next_char(str, i, space_chars, true)
if str:sub(i, i) ~= ":" then
decode_error(str, i, "expected ':' after key")
end
i = next_char(str, i + 1, space_chars, true)
-- Read value
val, i = parse(str, i)
-- Set
res[key] = val
-- Next token
i = next_char(str, i, space_chars, true)
local chr = str:sub(i, i)
i = i + 1
if chr == "}" then break end
if chr ~= "," then decode_error(str, i, "expected '}' or ','") end
end
return res, i
end
local char_func_map = {
[ '"' ] = parse_string,
[ "0" ] = parse_number,
[ "1" ] = parse_number,
[ "2" ] = parse_number,
[ "3" ] = parse_number,
[ "4" ] = parse_number,
[ "5" ] = parse_number,
[ "6" ] = parse_number,
[ "7" ] = parse_number,
[ "8" ] = parse_number,
[ "9" ] = parse_number,
[ "-" ] = parse_number,
[ "t" ] = parse_literal,
[ "f" ] = parse_literal,
[ "n" ] = parse_literal,
[ "[" ] = parse_array,
[ "{" ] = parse_object,
}
parse = function(str, idx)
local chr = str:sub(idx, idx)
local f = char_func_map[chr]
if f then
return f(str, idx)
end
decode_error(str, idx, "unexpected character '" .. chr .. "'")
end
function json.decode(str)
if type(str) ~= "string" then
error("expected argument of type string, got " .. type(str))
end
return ( parse(str, next_char(str, 1, space_chars, true)) )
end
return json