Fix golangci-lint errors (#10196)

* Fix golangci-lint errors

Signed-off-by: z1cheng <imchench@gmail.com>

* Fix dupl errors

Signed-off-by: z1cheng <imchench@gmail.com>

* Fix comments

Signed-off-by: z1cheng <imchench@gmail.com>

* Fix errcheck lint errors

Signed-off-by: z1cheng <imchench@gmail.com>

* Fix assert in e2e test

Signed-off-by: z1cheng <imchench@gmail.com>

* Not interrupt the waitForPodsReady

Signed-off-by: z1cheng <imchench@gmail.com>

* Replace string with constant

Signed-off-by: z1cheng <imchench@gmail.com>

* Fix comments

Signed-off-by: z1cheng <imchench@gmail.com>

* Revert write file permision

Signed-off-by: z1cheng <imchench@gmail.com>

---------

Signed-off-by: z1cheng <imchench@gmail.com>
This commit is contained in:
Chen Chen 2023-08-31 15:36:48 +08:00 committed by GitHub
parent 46d87d3462
commit b3060bfbd0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
253 changed files with 2434 additions and 2113 deletions

View file

@ -91,6 +91,8 @@ const (
)
// ReadConfig obtains the configuration defined by the user merged with the defaults.
//
//nolint:gocyclo // Ignore function complexity error
func ReadConfig(src map[string]string) config.Configuration {
conf := map[string]string{}
// we need to copy the configmap data because the content is altered
@ -116,12 +118,12 @@ func ReadConfig(src map[string]string) config.Configuration {
luaSharedDicts := make(map[string]int)
debugConnectionsList := make([]string, 0)
//parse lua shared dict values
// parse lua shared dict values
if val, ok := conf[luaSharedDictsKey]; ok {
delete(conf, luaSharedDictsKey)
lsd := splitAndTrimSpace(val, ",")
for _, v := range lsd {
v = strings.Replace(v, " ", "", -1)
v = strings.ReplaceAll(v, " ", "")
results := strings.SplitN(v, ":", 2)
dictName := results[0]
size := dictStrToKb(results[1])
@ -196,7 +198,7 @@ func ReadConfig(src map[string]string) config.Configuration {
if ing_net.IsIPV6(ns) {
bindAddressIpv6List = append(bindAddressIpv6List, fmt.Sprintf("[%v]", ns))
} else {
bindAddressIpv4List = append(bindAddressIpv4List, fmt.Sprintf("%v", ns))
bindAddressIpv4List = append(bindAddressIpv4List, ns.String())
}
} else {
klog.Warningf("%v is not a valid textual representation of an IP address", i)
@ -250,7 +252,7 @@ func ReadConfig(src map[string]string) config.Configuration {
if val, ok := conf[globalAuthMethod]; ok {
delete(conf, globalAuthMethod)
if len(val) != 0 && !authreq.ValidMethod(val) {
if val != "" && !authreq.ValidMethod(val) {
klog.Warningf("Global auth location denied - %v.", "invalid HTTP method")
} else {
to.GlobalExternalAuth.Method = val
@ -261,7 +263,10 @@ func ReadConfig(src map[string]string) config.Configuration {
if val, ok := conf[globalAuthSignin]; ok {
delete(conf, globalAuthSignin)
signinURL, _ := parser.StringToURL(val)
signinURL, err := parser.StringToURL(val)
if err != nil {
klog.Errorf("string to URL conversion failed: %v", err)
}
if signinURL == nil {
klog.Warningf("Global auth location denied - %v.", "global-auth-signin setting is undefined and will not be set")
} else {
@ -274,7 +279,10 @@ func ReadConfig(src map[string]string) config.Configuration {
delete(conf, globalAuthSigninRedirectParam)
redirectParam := strings.TrimSpace(val)
dummySigninURL, _ := parser.StringToURL(fmt.Sprintf("%s?%s=dummy", to.GlobalExternalAuth.SigninURL, redirectParam))
dummySigninURL, err := parser.StringToURL(fmt.Sprintf("%s?%s=dummy", to.GlobalExternalAuth.SigninURL, redirectParam))
if err != nil {
klog.Errorf("string to URL conversion failed: %v", err)
}
if dummySigninURL == nil {
klog.Warningf("Global auth redirect parameter denied - %v.", "global-auth-signin-redirect-param setting is invalid and will not be set")
} else {
@ -286,7 +294,7 @@ func ReadConfig(src map[string]string) config.Configuration {
if val, ok := conf[globalAuthResponseHeaders]; ok {
delete(conf, globalAuthResponseHeaders)
if len(val) != 0 {
if val != "" {
harr := splitAndTrimSpace(val, ",")
for _, header := range harr {
if !authreq.ValidHeader(header) {
@ -385,8 +393,8 @@ func ReadConfig(src map[string]string) config.Configuration {
if val, ok := conf[debugConnections]; ok {
delete(conf, debugConnections)
for _, i := range splitAndTrimSpace(val, ",") {
validIp := net.ParseIP(i)
if validIp != nil {
validIP := net.ParseIP(i)
if validIP != nil {
debugConnectionsList = append(debugConnectionsList, i)
} else {
_, _, err := net.ParseCIDR(i)
@ -415,14 +423,14 @@ func ReadConfig(src map[string]string) config.Configuration {
to.DisableIpv6DNS = !ing_net.IsIPv6Enabled()
to.LuaSharedDicts = luaSharedDicts
config := &mapstructure.DecoderConfig{
decoderConfig := &mapstructure.DecoderConfig{
Metadata: nil,
WeaklyTypedInput: true,
Result: &to,
TagName: "json",
}
decoder, err := mapstructure.NewDecoder(config)
decoder, err := mapstructure.NewDecoder(decoderConfig)
if err != nil {
klog.Warningf("unexpected error merging defaults: %v", err)
}
@ -456,6 +464,7 @@ func filterErrors(codes []int) []int {
return fa
}
//nolint:unparam // Ignore `sep` always receives `,` error
func splitAndTrimSpace(s, sep string) []string {
f := func(c rune) bool {
return strings.EqualFold(string(c), sep)
@ -474,8 +483,11 @@ func dictStrToKb(sizeStr string) int {
if sizeMatch == nil {
return -1
}
size, _ := strconv.Atoi(sizeMatch[1]) // validated already with regex
if sizeMatch[2] == "" || strings.ToLower(sizeMatch[2]) == "m" {
size, err := strconv.Atoi(sizeMatch[1]) // validated already with regex
if err != nil {
klog.Errorf("unexpected error converting size string %s to int: %v", sizeStr, err)
}
if sizeMatch[2] == "" || strings.EqualFold(sizeMatch[2], "m") {
size *= 1024
}
return size

View file

@ -52,6 +52,12 @@ const (
nonIdempotent = "non_idempotent"
defBufferSize = 65535
writeIndentOnEmptyLines = true // backward-compatibility
httpProtocol = "HTTP"
autoHTTPProtocol = "AUTO_HTTP"
httpsProtocol = "HTTPS"
grpcProtocol = "GRPC"
grpcsProtocol = "GRPCS"
fcgiProtocol = "FCGI"
)
const (
@ -64,13 +70,13 @@ type Writer interface {
// Write renders the template.
// NOTE: Implementors must ensure that the content of the returned slice is not modified by the implementation
// after the return of this function.
Write(conf config.TemplateConfig) ([]byte, error)
Write(conf *config.TemplateConfig) ([]byte, error)
}
// Template ...
// Template ingress template
type Template struct {
tmpl *text_template.Template
//fw watch.FileWatcher
bp *BufferPool
}
@ -97,7 +103,7 @@ func NewTemplate(file string) (*Template, error) {
// 2. Collapses multiple empty lines to single one
// 3. Re-indent
// (ATW: always returns nil)
func cleanConf(in *bytes.Buffer, out *bytes.Buffer) error {
func cleanConf(in, out *bytes.Buffer) error {
depth := 0
lineStarted := false
emptyLineWritten := false
@ -176,7 +182,7 @@ func cleanConf(in *bytes.Buffer, out *bytes.Buffer) error {
// Write populates a buffer using a template with NGINX configuration
// and the servers and upstreams created by Ingress rules
func (t *Template) Write(conf config.TemplateConfig) ([]byte, error) {
func (t *Template) Write(conf *config.TemplateConfig) ([]byte, error) {
tmplBuf := t.bp.Get()
defer t.bp.Put(tmplBuf)
@ -184,14 +190,14 @@ func (t *Template) Write(conf config.TemplateConfig) ([]byte, error) {
defer t.bp.Put(outCmdBuf)
if klog.V(3).Enabled() {
b, err := json.Marshal(conf)
b, err := json.Marshal(*conf)
if err != nil {
klog.Errorf("unexpected error: %v", err)
}
klog.InfoS("NGINX", "configuration", string(b))
}
err := t.tmpl.Execute(tmplBuf, conf)
err := t.tmpl.Execute(tmplBuf, *conf)
if err != nil {
return nil, err
}
@ -211,78 +217,76 @@ func (t *Template) Write(conf config.TemplateConfig) ([]byte, error) {
return res, nil
}
var (
funcMap = text_template.FuncMap{
"empty": func(input interface{}) bool {
check, ok := input.(string)
if ok {
return len(check) == 0
}
return true
},
"escapeLiteralDollar": escapeLiteralDollar,
"buildLuaSharedDictionaries": buildLuaSharedDictionaries,
"luaConfigurationRequestBodySize": luaConfigurationRequestBodySize,
"buildLocation": buildLocation,
"buildAuthLocation": buildAuthLocation,
"shouldApplyGlobalAuth": shouldApplyGlobalAuth,
"buildAuthResponseHeaders": buildAuthResponseHeaders,
"buildAuthUpstreamLuaHeaders": buildAuthUpstreamLuaHeaders,
"buildAuthProxySetHeaders": buildAuthProxySetHeaders,
"buildAuthUpstreamName": buildAuthUpstreamName,
"shouldApplyAuthUpstream": shouldApplyAuthUpstream,
"extractHostPort": extractHostPort,
"changeHostPort": changeHostPort,
"buildProxyPass": buildProxyPass,
"filterRateLimits": filterRateLimits,
"buildRateLimitZones": buildRateLimitZones,
"buildRateLimit": buildRateLimit,
"configForLua": configForLua,
"locationConfigForLua": locationConfigForLua,
"buildResolvers": buildResolvers,
"buildUpstreamName": buildUpstreamName,
"isLocationInLocationList": isLocationInLocationList,
"isLocationAllowed": isLocationAllowed,
"buildDenyVariable": buildDenyVariable,
"getenv": os.Getenv,
"contains": strings.Contains,
"split": strings.Split,
"hasPrefix": strings.HasPrefix,
"hasSuffix": strings.HasSuffix,
"trimSpace": strings.TrimSpace,
"toUpper": strings.ToUpper,
"toLower": strings.ToLower,
"formatIP": formatIP,
"quote": quote,
"buildNextUpstream": buildNextUpstream,
"getIngressInformation": getIngressInformation,
"serverConfig": func(all config.TemplateConfig, server *ingress.Server) interface{} {
return struct{ First, Second interface{} }{all, server}
},
"isValidByteSize": isValidByteSize,
"buildForwardedFor": buildForwardedFor,
"buildAuthSignURL": buildAuthSignURL,
"buildAuthSignURLLocation": buildAuthSignURLLocation,
"buildOpentracing": buildOpentracing,
"buildOpentelemetry": buildOpentelemetry,
"proxySetHeader": proxySetHeader,
"enforceRegexModifier": enforceRegexModifier,
"buildCustomErrorDeps": buildCustomErrorDeps,
"buildCustomErrorLocationsPerServer": buildCustomErrorLocationsPerServer,
"shouldLoadModSecurityModule": shouldLoadModSecurityModule,
"buildHTTPListener": buildHTTPListener,
"buildHTTPSListener": buildHTTPSListener,
"buildOpentracingForLocation": buildOpentracingForLocation,
"buildOpentelemetryForLocation": buildOpentelemetryForLocation,
"shouldLoadOpentracingModule": shouldLoadOpentracingModule,
"shouldLoadOpentelemetryModule": shouldLoadOpentelemetryModule,
"buildModSecurityForLocation": buildModSecurityForLocation,
"buildMirrorLocations": buildMirrorLocations,
"shouldLoadAuthDigestModule": shouldLoadAuthDigestModule,
"buildServerName": buildServerName,
"buildCorsOriginRegex": buildCorsOriginRegex,
}
)
var funcMap = text_template.FuncMap{
"empty": func(input interface{}) bool {
check, ok := input.(string)
if ok {
return check == ""
}
return true
},
"escapeLiteralDollar": escapeLiteralDollar,
"buildLuaSharedDictionaries": buildLuaSharedDictionaries,
"luaConfigurationRequestBodySize": luaConfigurationRequestBodySize,
"buildLocation": buildLocation,
"buildAuthLocation": buildAuthLocation,
"shouldApplyGlobalAuth": shouldApplyGlobalAuth,
"buildAuthResponseHeaders": buildAuthResponseHeaders,
"buildAuthUpstreamLuaHeaders": buildAuthUpstreamLuaHeaders,
"buildAuthProxySetHeaders": buildAuthProxySetHeaders,
"buildAuthUpstreamName": buildAuthUpstreamName,
"shouldApplyAuthUpstream": shouldApplyAuthUpstream,
"extractHostPort": extractHostPort,
"changeHostPort": changeHostPort,
"buildProxyPass": buildProxyPass,
"filterRateLimits": filterRateLimits,
"buildRateLimitZones": buildRateLimitZones,
"buildRateLimit": buildRateLimit,
"configForLua": configForLua,
"locationConfigForLua": locationConfigForLua,
"buildResolvers": buildResolvers,
"buildUpstreamName": buildUpstreamName,
"isLocationInLocationList": isLocationInLocationList,
"isLocationAllowed": isLocationAllowed,
"buildDenyVariable": buildDenyVariable,
"getenv": os.Getenv,
"contains": strings.Contains,
"split": strings.Split,
"hasPrefix": strings.HasPrefix,
"hasSuffix": strings.HasSuffix,
"trimSpace": strings.TrimSpace,
"toUpper": strings.ToUpper,
"toLower": strings.ToLower,
"formatIP": formatIP,
"quote": quote,
"buildNextUpstream": buildNextUpstream,
"getIngressInformation": getIngressInformation,
"serverConfig": func(all config.TemplateConfig, server *ingress.Server) interface{} {
return struct{ First, Second interface{} }{all, server}
},
"isValidByteSize": isValidByteSize,
"buildForwardedFor": buildForwardedFor,
"buildAuthSignURL": buildAuthSignURL,
"buildAuthSignURLLocation": buildAuthSignURLLocation,
"buildOpentracing": buildOpentracing,
"buildOpentelemetry": buildOpentelemetry,
"proxySetHeader": proxySetHeader,
"enforceRegexModifier": enforceRegexModifier,
"buildCustomErrorDeps": buildCustomErrorDeps,
"buildCustomErrorLocationsPerServer": buildCustomErrorLocationsPerServer,
"shouldLoadModSecurityModule": shouldLoadModSecurityModule,
"buildHTTPListener": buildHTTPListener,
"buildHTTPSListener": buildHTTPSListener,
"buildOpentracingForLocation": buildOpentracingForLocation,
"buildOpentelemetryForLocation": buildOpentelemetryForLocation,
"shouldLoadOpentracingModule": shouldLoadOpentracingModule,
"shouldLoadOpentelemetryModule": shouldLoadOpentelemetryModule,
"buildModSecurityForLocation": buildModSecurityForLocation,
"buildMirrorLocations": buildMirrorLocations,
"shouldLoadAuthDigestModule": shouldLoadAuthDigestModule,
"buildServerName": buildServerName,
"buildCorsOriginRegex": buildCorsOriginRegex,
}
// escapeLiteralDollar will replace the $ character with ${literal_dollar}
// which is made to work via the following configuration in the http section of
@ -296,7 +300,7 @@ func escapeLiteralDollar(input interface{}) string {
if !ok {
return ""
}
return strings.Replace(inputStr, `$`, `${literal_dollar}`, -1)
return strings.ReplaceAll(inputStr, `$`, `${literal_dollar}`)
}
// formatIP will wrap IPv6 addresses in [] and return IPv4 addresses
@ -328,9 +332,7 @@ func quote(input interface{}) string {
return fmt.Sprintf("%q", inputStr)
}
func buildLuaSharedDictionaries(c interface{}, s interface{}) string {
var out []string
func buildLuaSharedDictionaries(c, s interface{}) string {
cfg, ok := c.(config.Configuration)
if !ok {
klog.Errorf("expected a 'config.Configuration' type but %T was returned", c)
@ -343,6 +345,7 @@ func buildLuaSharedDictionaries(c interface{}, s interface{}) string {
return ""
}
out := make([]string, 0, len(cfg.LuaSharedDicts))
for name, size := range cfg.LuaSharedDicts {
sizeStr := dictKbToStr(size)
out = append(out, fmt.Sprintf("lua_shared_dict %s %s", name, sizeStr))
@ -364,7 +367,7 @@ func luaConfigurationRequestBodySize(c interface{}) string {
if size < cfg.LuaSharedDicts["certificate_data"] {
size = cfg.LuaSharedDicts["certificate_data"]
}
size = size + 1024
size += 1024
return dictKbToStr(size)
}
@ -418,7 +421,7 @@ func configForLua(input interface{}) string {
}
// locationConfigForLua formats some location specific configuration into Lua table represented as string
func locationConfigForLua(l interface{}, a interface{}) string {
func locationConfigForLua(l, a interface{}) string {
location, ok := l.(*ingress.Location)
if !ok {
klog.Errorf("expected an '*ingress.Location' type but %T was given", l)
@ -459,7 +462,7 @@ func locationConfigForLua(l interface{}, a interface{}) string {
}
// buildResolvers returns the resolvers reading the /etc/resolv.conf file
func buildResolvers(res interface{}, disableIpv6 interface{}) string {
func buildResolvers(res, disableIpv6 interface{}) string {
// NGINX need IPV6 addresses to be surrounded by brackets
nss, ok := res.([]net.IP)
if !ok {
@ -484,7 +487,7 @@ func buildResolvers(res interface{}, disableIpv6 interface{}) string {
}
r = append(r, fmt.Sprintf("[%v]", ns))
} else {
r = append(r, fmt.Sprintf("%v", ns))
r = append(r, ns.String())
}
}
r = append(r, "valid=30s")
@ -554,7 +557,7 @@ func buildAuthLocation(input interface{}, globalExternalAuthURL string) string {
str := base64.URLEncoding.EncodeToString([]byte(location.Path))
// removes "=" after encoding
str = strings.Replace(str, "=", "", -1)
str = strings.ReplaceAll(str, "=", "")
pathType := "default"
if location.PathType != nil {
@ -644,7 +647,7 @@ func buildAuthUpstreamName(input interface{}, host string) string {
// shouldApplyAuthUpstream returns true only in case when ExternalAuth.URL and
// ExternalAuth.KeepaliveConnections are all set
func shouldApplyAuthUpstream(l interface{}, c interface{}) bool {
func shouldApplyAuthUpstream(l, c interface{}) bool {
location, ok := l.(*ingress.Location)
if !ok {
klog.Errorf("expected an '*ingress.Location' type but %T was returned", l)
@ -672,14 +675,14 @@ func shouldApplyAuthUpstream(l interface{}, c interface{}) bool {
}
// extractHostPort will extract the host:port part from the URL specified by url
func extractHostPort(url string) string {
if url == "" {
func extractHostPort(newURL string) string {
if newURL == "" {
return ""
}
authURL, err := parser.StringToURL(url)
authURL, err := parser.StringToURL(newURL)
if err != nil {
klog.Errorf("expected a valid URL but %s was returned", url)
klog.Errorf("expected a valid URL but %s was returned", newURL)
return ""
}
@ -687,14 +690,14 @@ func extractHostPort(url string) string {
}
// changeHostPort will change the host:port part of the url to value
func changeHostPort(url string, value string) string {
if url == "" {
func changeHostPort(newURL, value string) string {
if newURL == "" {
return ""
}
authURL, err := parser.StringToURL(url)
authURL, err := parser.StringToURL(newURL)
if err != nil {
klog.Errorf("expected a valid URL but %s was returned", url)
klog.Errorf("expected a valid URL but %s was returned", newURL)
return ""
}
@ -707,7 +710,7 @@ func changeHostPort(url string, value string) string {
// (specified through the nginx.ingress.kubernetes.io/rewrite-target annotation)
// If the annotation nginx.ingress.kubernetes.io/add-base-url:"true" is specified it will
// add a base tag in the head of the response from the service
func buildProxyPass(host string, b interface{}, loc interface{}) string {
func buildProxyPass(_ string, b, loc interface{}) string {
backends, ok := b.([]*ingress.Backend)
if !ok {
klog.Errorf("expected an '[]*ingress.Backend' type but %T was returned", b)
@ -726,17 +729,17 @@ func buildProxyPass(host string, b interface{}, loc interface{}) string {
proxyPass := "proxy_pass"
switch location.BackendProtocol {
case "AUTO_HTTP":
case autoHTTPProtocol:
proto = "$scheme://"
case "HTTPS":
case httpsProtocol:
proto = "https://"
case "GRPC":
case grpcProtocol:
proto = "grpc://"
proxyPass = "grpc_pass"
case "GRPCS":
case grpcsProtocol:
proto = "grpcs://"
proxyPass = "grpc_pass"
case "FCGI":
case fcgiProtocol:
proto = ""
proxyPass = "fastcgi_pass"
}
@ -748,7 +751,7 @@ func buildProxyPass(host string, b interface{}, loc interface{}) string {
if backend.SSLPassthrough {
proto = "https://"
if location.BackendProtocol == "GRPCS" {
if location.BackendProtocol == grpcsProtocol {
proto = "grpcs://"
}
}
@ -775,7 +778,7 @@ func buildProxyPass(host string, b interface{}, loc interface{}) string {
var xForwardedPrefix string
if len(location.XForwardedPrefix) > 0 {
xForwardedPrefix = fmt.Sprintf("%s X-Forwarded-Prefix \"%s\";\n", proxySetHeader(location), location.XForwardedPrefix)
xForwardedPrefix = fmt.Sprintf("%s X-Forwarded-Prefix %q;\n", proxySetHeader(location), location.XForwardedPrefix)
}
return fmt.Sprintf(`
@ -935,9 +938,7 @@ func isLocationAllowed(input interface{}) bool {
return loc.Denied == nil
}
var (
denyPathSlugMap = map[string]string{}
)
var denyPathSlugMap = map[string]string{}
// buildDenyVariable returns a nginx variable for a location in a
// server to be used in the whitelist check
@ -977,7 +978,11 @@ func buildNextUpstream(i, r interface{}) string {
return ""
}
retryNonIdempotent := r.(bool)
retryNonIdempotent, ok := r.(bool)
if !ok {
klog.Errorf("expected a 'bool' type but %T was returned", i)
return ""
}
parts := strings.Split(nextUpstream, " ")
@ -1002,8 +1007,10 @@ func buildNextUpstream(i, r interface{}) string {
// refer to http://nginx.org/en/docs/syntax.html
// Nginx differentiates between size and offset
// offset directives support gigabytes in addition
var nginxSizeRegex = regexp.MustCompile("^[0-9]+[kKmM]{0,1}$")
var nginxOffsetRegex = regexp.MustCompile("^[0-9]+[kKmMgG]{0,1}$")
var (
nginxSizeRegex = regexp.MustCompile(`^\d+[kKmM]?$`)
nginxOffsetRegex = regexp.MustCompile(`^\d+[kKmMgG]?$`)
)
// isValidByteSize validates size units valid in nginx
// http://nginx.org/en/docs/syntax.html
@ -1153,13 +1160,17 @@ func buildForwardedFor(input interface{}) string {
return ""
}
ffh := strings.Replace(s, "-", "_", -1)
ffh := strings.ReplaceAll(s, "-", "_")
ffh = strings.ToLower(ffh)
return fmt.Sprintf("$http_%v", ffh)
}
func buildAuthSignURL(authSignURL, authRedirectParam string) string {
u, _ := url.Parse(authSignURL)
u, err := url.Parse(authSignURL)
if err != nil {
klog.Errorf("error parsing authSignURL: %v", err)
return ""
}
q := u.Query()
if authRedirectParam == "" {
authRedirectParam = defaultGlobalAuthRedirectParam
@ -1198,7 +1209,7 @@ func randomString() string {
return string(b)
}
func buildOpentracing(c interface{}, s interface{}) string {
func buildOpentracing(c, s interface{}) string {
cfg, ok := c.(config.Configuration)
if !ok {
klog.Errorf("expected a 'config.Configuration' type but %T was returned", c)
@ -1217,6 +1228,7 @@ func buildOpentracing(c interface{}, s interface{}) string {
buf := bytes.NewBufferString("")
//nolint:gocritic // rewriting if-else to switch statement is not more readable
if cfg.DatadogCollectorHost != "" {
buf.WriteString("opentracing_load_tracer /usr/local/lib/libdd_opentracing.so /etc/nginx/opentracing.json;")
} else if cfg.ZipkinCollectorHost != "" {
@ -1228,16 +1240,16 @@ func buildOpentracing(c interface{}, s interface{}) string {
buf.WriteString("\r\n")
if cfg.OpentracingOperationName != "" {
buf.WriteString(fmt.Sprintf("opentracing_operation_name \"%s\";\n", cfg.OpentracingOperationName))
fmt.Fprintf(buf, "opentracing_operation_name \"%s\";\n", cfg.OpentracingOperationName)
}
if cfg.OpentracingLocationOperationName != "" {
buf.WriteString(fmt.Sprintf("opentracing_location_operation_name \"%s\";\n", cfg.OpentracingLocationOperationName))
fmt.Fprintf(buf, "opentracing_location_operation_name \"%s\";\n", cfg.OpentracingLocationOperationName)
}
return buf.String()
}
func buildOpentelemetry(c interface{}, s interface{}) string {
func buildOpentelemetry(c, s interface{}) string {
cfg, ok := c.(config.Configuration)
if !ok {
klog.Errorf("expected a 'config.Configuration' type but %T was returned", c)
@ -1259,7 +1271,7 @@ func buildOpentelemetry(c interface{}, s interface{}) string {
buf.WriteString("\r\n")
if cfg.OpentelemetryOperationName != "" {
buf.WriteString(fmt.Sprintf("opentelemetry_operation_name \"%s\";\n", cfg.OpentelemetryOperationName))
fmt.Fprintf(buf, "opentelemetry_operation_name \"%s\";\n", cfg.OpentelemetryOperationName)
}
return buf.String()
}
@ -1271,7 +1283,7 @@ func proxySetHeader(loc interface{}) string {
return "proxy_set_header"
}
if location.BackendProtocol == "GRPC" || location.BackendProtocol == "GRPCS" {
if location.BackendProtocol == grpcProtocol || location.BackendProtocol == grpcsProtocol {
return "grpc_set_header"
}
@ -1280,7 +1292,7 @@ func proxySetHeader(loc interface{}) string {
// buildCustomErrorDeps is a utility function returning a struct wrapper with
// the data required to build the 'CUSTOM_ERRORS' template
func buildCustomErrorDeps(upstreamName string, errorCodes []int, enableMetrics bool, modsecurityEnabled bool) interface{} {
func buildCustomErrorDeps(upstreamName string, errorCodes []int, enableMetrics, modsecurityEnabled bool) interface{} {
return struct {
UpstreamName string
ErrorCodes []int
@ -1355,7 +1367,7 @@ func opentracingPropagateContext(location *ingress.Location) string {
return ""
}
if location.BackendProtocol == "GRPC" || location.BackendProtocol == "GRPCS" {
if location.BackendProtocol == grpcProtocol || location.BackendProtocol == grpcsProtocol {
return "opentracing_grpc_propagate_context;"
}
@ -1372,7 +1384,7 @@ func opentelemetryPropagateContext(location *ingress.Location) string {
// shouldLoadModSecurityModule determines whether or not the ModSecurity module needs to be loaded.
// First, it checks if `enable-modsecurity` is set in the ConfigMap. If it is not, it iterates over all locations to
// check if ModSecurity is enabled by the annotation `nginx.ingress.kubernetes.io/enable-modsecurity`.
func shouldLoadModSecurityModule(c interface{}, s interface{}) bool {
func shouldLoadModSecurityModule(c, s interface{}) bool {
cfg, ok := c.(config.Configuration)
if !ok {
klog.Errorf("expected a 'config.Configuration' type but %T was returned", c)
@ -1403,7 +1415,7 @@ func shouldLoadModSecurityModule(c interface{}, s interface{}) bool {
return false
}
func buildHTTPListener(t interface{}, s interface{}) string {
func buildHTTPListener(t, s interface{}) string {
var out []string
tc, ok := t.(config.TemplateConfig)
@ -1423,9 +1435,9 @@ func buildHTTPListener(t interface{}, s interface{}) string {
addrV4 = tc.Cfg.BindAddressIpv4
}
co := commonListenOptions(tc, hostname)
co := commonListenOptions(&tc, hostname)
out = append(out, httpListener(addrV4, co, tc)...)
out = append(out, httpListener(addrV4, co, &tc)...)
if !tc.IsIPV6Enabled {
return strings.Join(out, "\n")
@ -1436,12 +1448,12 @@ func buildHTTPListener(t interface{}, s interface{}) string {
addrV6 = tc.Cfg.BindAddressIpv6
}
out = append(out, httpListener(addrV6, co, tc)...)
out = append(out, httpListener(addrV6, co, &tc)...)
return strings.Join(out, "\n")
}
func buildHTTPSListener(t interface{}, s interface{}) string {
func buildHTTPSListener(t, s interface{}) string {
var out []string
tc, ok := t.(config.TemplateConfig)
@ -1456,14 +1468,14 @@ func buildHTTPSListener(t interface{}, s interface{}) string {
return ""
}
co := commonListenOptions(tc, hostname)
co := commonListenOptions(&tc, hostname)
addrV4 := []string{""}
if len(tc.Cfg.BindAddressIpv4) > 0 {
addrV4 = tc.Cfg.BindAddressIpv4
}
out = append(out, httpsListener(addrV4, co, tc)...)
out = append(out, httpsListener(addrV4, co, &tc)...)
if !tc.IsIPV6Enabled {
return strings.Join(out, "\n")
@ -1474,12 +1486,12 @@ func buildHTTPSListener(t interface{}, s interface{}) string {
addrV6 = tc.Cfg.BindAddressIpv6
}
out = append(out, httpsListener(addrV6, co, tc)...)
out = append(out, httpsListener(addrV6, co, &tc)...)
return strings.Join(out, "\n")
}
func commonListenOptions(template config.TemplateConfig, hostname string) string {
func commonListenOptions(template *config.TemplateConfig, hostname string) string {
var out []string
if template.Cfg.UseProxyProtocol {
@ -1503,7 +1515,7 @@ func commonListenOptions(template config.TemplateConfig, hostname string) string
return strings.Join(out, " ")
}
func httpListener(addresses []string, co string, tc config.TemplateConfig) []string {
func httpListener(addresses []string, co string, tc *config.TemplateConfig) []string {
out := make([]string, 0)
for _, address := range addresses {
lo := []string{"listen"}
@ -1514,15 +1526,14 @@ func httpListener(addresses []string, co string, tc config.TemplateConfig) []str
lo = append(lo, fmt.Sprintf("%v:%v", address, tc.ListenPorts.HTTP))
}
lo = append(lo, co)
lo = append(lo, ";")
lo = append(lo, co, ";")
out = append(out, strings.Join(lo, " "))
}
return out
}
func httpsListener(addresses []string, co string, tc config.TemplateConfig) []string {
func httpsListener(addresses []string, co string, tc *config.TemplateConfig) []string {
out := make([]string, 0)
for _, address := range addresses {
lo := []string{"listen"}
@ -1545,8 +1556,7 @@ func httpsListener(addresses []string, co string, tc config.TemplateConfig) []st
}
}
lo = append(lo, co)
lo = append(lo, "ssl")
lo = append(lo, co, "ssl")
if tc.Cfg.UseHTTP2 {
lo = append(lo, "http2")
@ -1559,7 +1569,7 @@ func httpsListener(addresses []string, co string, tc config.TemplateConfig) []st
return out
}
func buildOpentracingForLocation(isOTEnabled bool, isOTTrustSet bool, location *ingress.Location) string {
func buildOpentracingForLocation(isOTEnabled, isOTTrustSet bool, location *ingress.Location) string {
isOTEnabledInLoc := location.Opentracing.Enabled
isOTSetInLoc := location.Opentracing.Set
@ -1578,13 +1588,13 @@ func buildOpentracingForLocation(isOTEnabled bool, isOTTrustSet bool, location *
if (!isOTTrustSet && !location.Opentracing.TrustSet) ||
(location.Opentracing.TrustSet && !location.Opentracing.TrustEnabled) {
opc = opc + "\nopentracing_trust_incoming_span off;"
opc += "\nopentracing_trust_incoming_span off;"
}
return opc
}
func buildOpentelemetryForLocation(isOTEnabled bool, isOTTrustSet bool, location *ingress.Location) string {
func buildOpentelemetryForLocation(isOTEnabled, isOTTrustSet bool, location *ingress.Location) string {
isOTEnabledInLoc := location.Opentelemetry.Enabled
isOTSetInLoc := location.Opentelemetry.Set
@ -1602,14 +1612,14 @@ func buildOpentelemetryForLocation(isOTEnabled bool, isOTTrustSet bool, location
}
if location.Opentelemetry.OperationName != "" {
opc = opc + "\nopentelemetry_operation_name " + location.Opentelemetry.OperationName + ";"
opc += "\nopentelemetry_operation_name " + location.Opentelemetry.OperationName + ";"
}
if (!isOTTrustSet && !location.Opentelemetry.TrustSet) ||
(location.Opentelemetry.TrustSet && !location.Opentelemetry.TrustEnabled) {
opc = opc + "\nopentelemetry_trust_incoming_spans off;"
opc += "\nopentelemetry_trust_incoming_spans off;"
} else {
opc = opc + "\nopentelemetry_trust_incoming_spans on;"
opc += "\nopentelemetry_trust_incoming_spans on;"
}
return opc
}
@ -1617,7 +1627,7 @@ func buildOpentelemetryForLocation(isOTEnabled bool, isOTTrustSet bool, location
// shouldLoadOpentracingModule determines whether or not the Opentracing module needs to be loaded.
// First, it checks if `enable-opentracing` is set in the ConfigMap. If it is not, it iterates over all locations to
// check if Opentracing is enabled by the annotation `nginx.ingress.kubernetes.io/enable-opentracing`.
func shouldLoadOpentracingModule(c interface{}, s interface{}) bool {
func shouldLoadOpentracingModule(c, s interface{}) bool {
cfg, ok := c.(config.Configuration)
if !ok {
klog.Errorf("expected a 'config.Configuration' type but %T was returned", c)
@ -1647,7 +1657,7 @@ func shouldLoadOpentracingModule(c interface{}, s interface{}) bool {
// shouldLoadOpentelemetryModule determines whether or not the Opentelemetry module needs to be loaded.
// It checks if `enable-opentelemetry` is set in the ConfigMap.
func shouldLoadOpentelemetryModule(c interface{}, s interface{}) bool {
func shouldLoadOpentelemetryModule(c, s interface{}) bool {
cfg, ok := c.(config.Configuration)
if !ok {
klog.Errorf("expected a 'config.Configuration' type but %T was returned", c)
@ -1674,6 +1684,7 @@ func shouldLoadOpentelemetryModule(c interface{}, s interface{}) bool {
return false
}
//nolint:gocritic // Ignore passing cfg by pointer error
func buildModSecurityForLocation(cfg config.Configuration, location *ingress.Location) string {
isMSEnabledInLoc := location.ModSecurity.Enable
isMSEnableSetInLoc := location.ModSecurity.EnableSet
@ -1807,7 +1818,7 @@ func convertGoSliceIntoLuaTable(goSliceInterface interface{}, emptyStringAsNil b
switch kind {
case reflect.String:
if emptyStringAsNil && len(goSlice.Interface().(string)) == 0 {
if emptyStringAsNil && goSlice.Interface().(string) == "" {
return "nil", nil
}
return fmt.Sprintf(`"%v"`, goSlice.Interface()), nil
@ -1840,17 +1851,17 @@ func buildCorsOriginRegex(corsOrigins []string) string {
return "set $http_origin *;\nset $cors 'true';"
}
var originsRegex string = "if ($http_origin ~* ("
originsRegex := "if ($http_origin ~* ("
for i, origin := range corsOrigins {
originTrimmed := strings.TrimSpace(origin)
if len(originTrimmed) > 0 {
builtOrigin := buildOriginRegex(originTrimmed)
originsRegex += builtOrigin
if i != len(corsOrigins)-1 {
originsRegex = originsRegex + "|"
originsRegex += "|"
}
}
}
originsRegex = originsRegex + ")$ ) { set $cors 'true'; }"
originsRegex += ")$ ) { set $cors 'true'; }"
return originsRegex
}

View file

@ -48,9 +48,9 @@ import (
func init() {
// the default value of nginx.TemplatePath assumes the template exists in
// the root filesystem and not in the rootfs directory
path, err := filepath.Abs(filepath.Join("../../../../rootfs/", nginx.TemplatePath))
absPath, err := filepath.Abs(filepath.Join("..", "..", "..", "..", "rootfs", nginx.TemplatePath))
if err == nil {
nginx.TemplatePath = path
nginx.TemplatePath = absPath
}
}
@ -63,7 +63,7 @@ var (
Target string
Location string
ProxyPass string
AutoHttpProxyPass string
AutoHTTPProxyPass string
Sticky bool
XForwardedPrefix string
SecureBackend bool
@ -200,6 +200,12 @@ proxy_pass $scheme://upstream_balancer;`,
}
)
const (
defaultBackend = "upstream-name"
defaultHost = "example.com"
fooAuthHost = "foo.com/auth"
)
func getTestDataDir() (string, error) {
pwd, err := os.Getwd()
if err != nil {
@ -326,9 +332,6 @@ func TestBuildLocation(t *testing.T) {
}
func TestBuildProxyPass(t *testing.T) {
defaultBackend := "upstream-name"
defaultHost := "example.com"
for k, tc := range tmplFuncTestcases {
loc := &ingress.Location{
Path: tc.Path,
@ -339,7 +342,7 @@ func TestBuildProxyPass(t *testing.T) {
}
if tc.SecureBackend {
loc.BackendProtocol = "HTTPS"
loc.BackendProtocol = httpsProtocol
}
backend := &ingress.Backend{
@ -367,9 +370,6 @@ func TestBuildProxyPass(t *testing.T) {
}
func TestBuildProxyPassAutoHttp(t *testing.T) {
defaultBackend := "upstream-name"
defaultHost := "example.com"
for k, tc := range tmplFuncTestcases {
loc := &ingress.Location{
Path: tc.Path,
@ -379,9 +379,9 @@ func TestBuildProxyPassAutoHttp(t *testing.T) {
}
if tc.SecureBackend {
loc.BackendProtocol = "HTTPS"
loc.BackendProtocol = httpsProtocol
} else {
loc.BackendProtocol = "AUTO_HTTP"
loc.BackendProtocol = autoHTTPProtocol
}
backend := &ingress.Backend{
@ -402,7 +402,7 @@ func TestBuildProxyPassAutoHttp(t *testing.T) {
backends := []*ingress.Backend{backend}
pp := buildProxyPass(defaultHost, backends, loc)
if !strings.EqualFold(tc.AutoHttpProxyPass, pp) {
if !strings.EqualFold(tc.AutoHTTPProxyPass, pp) {
t.Errorf("%s: expected \n'%v'\nbut returned \n'%v'", k, tc.ProxyPass, pp)
}
}
@ -417,7 +417,7 @@ func TestBuildAuthLocation(t *testing.T) {
t.Errorf("Expected '%v' but returned '%v'", expected, actual)
}
authURL := "foo.com/auth"
authURL := fooAuthHost
globalAuthURL := "foo.com/global-auth"
loc := &ingress.Location{
@ -428,7 +428,7 @@ func TestBuildAuthLocation(t *testing.T) {
EnableGlobalAuth: true,
}
encodedAuthURL := strings.Replace(base64.URLEncoding.EncodeToString([]byte(loc.Path)), "=", "", -1)
encodedAuthURL := strings.ReplaceAll(base64.URLEncoding.EncodeToString([]byte(loc.Path)), "=", "")
externalAuthPath := fmt.Sprintf("/_external-auth-%v-default", encodedAuthURL)
testCases := []struct {
@ -460,8 +460,7 @@ func TestBuildAuthLocation(t *testing.T) {
}
func TestShouldApplyGlobalAuth(t *testing.T) {
authURL := "foo.com/auth"
authURL := fooAuthHost
globalAuthURL := "foo.com/global-auth"
loc := &ingress.Location{
@ -579,12 +578,12 @@ func TestBuildAuthUpstreamName(t *testing.T) {
loc := &ingress.Location{
ExternalAuth: authreq.Config{
URL: "foo.com/auth",
URL: fooAuthHost,
},
Path: "/cat",
}
encodedAuthURL := strings.Replace(base64.URLEncoding.EncodeToString([]byte(loc.Path)), "=", "", -1)
encodedAuthURL := strings.ReplaceAll(base64.URLEncoding.EncodeToString([]byte(loc.Path)), "=", "")
externalAuthPath := fmt.Sprintf("external-auth-%v-default", encodedAuthURL)
testCases := []struct {
@ -606,7 +605,7 @@ func TestBuildAuthUpstreamName(t *testing.T) {
}
func TestShouldApplyAuthUpstream(t *testing.T) {
authURL := "foo.com/auth"
authURL := fooAuthHost
loc := &ingress.Location{
ExternalAuth: authreq.Config{
@ -702,7 +701,10 @@ func TestChangeHostPort(t *testing.T) {
}
func TestTemplateWithData(t *testing.T) {
pwd, _ := os.Getwd()
pwd, err := os.Getwd()
if err != nil {
t.Errorf("unexpected error: %v", err)
}
f, err := os.Open(path.Join(pwd, "../../../../test/data/config.json"))
if err != nil {
t.Errorf("unexpected error reading json file: %v", err)
@ -727,7 +729,7 @@ func TestTemplateWithData(t *testing.T) {
dat.Cfg.DefaultSSLCertificate = &ingress.SSLCert{}
rt, err := ngxTpl.Write(dat)
rt, err := ngxTpl.Write(&dat)
if err != nil {
t.Errorf("invalid NGINX template: %v", err)
}
@ -746,7 +748,10 @@ func TestTemplateWithData(t *testing.T) {
}
func BenchmarkTemplateWithData(b *testing.B) {
pwd, _ := os.Getwd()
pwd, err := os.Getwd()
if err != nil {
b.Errorf("unexpected error: %v", err)
}
f, err := os.Open(path.Join(pwd, "../../../../test/data/config.json"))
if err != nil {
b.Errorf("unexpected error reading json file: %v", err)
@ -767,7 +772,7 @@ func BenchmarkTemplateWithData(b *testing.B) {
}
for i := 0; i < b.N; i++ {
if _, err := ngxTpl.Write(dat); err != nil {
if _, err := ngxTpl.Write(&dat); err != nil {
b.Errorf("unexpected error writing template: %v", err)
}
}
@ -1066,9 +1071,6 @@ func TestBuildUpstreamName(t *testing.T) {
t.Errorf("Expected '%v' but returned '%v'", expected, actual)
}
defaultBackend := "upstream-name"
defaultHost := "example.com"
for k, tc := range tmplFuncTestcases {
loc := &ingress.Location{
Path: tc.Path,
@ -1079,7 +1081,7 @@ func TestBuildUpstreamName(t *testing.T) {
}
if tc.SecureBackend {
loc.BackendProtocol = "HTTPS"
loc.BackendProtocol = httpsProtocol
}
backend := &ingress.Backend{
@ -1134,13 +1136,13 @@ func TestEscapeLiteralDollar(t *testing.T) {
func TestOpentracingPropagateContext(t *testing.T) {
tests := map[*ingress.Location]string{
{BackendProtocol: "HTTP"}: "opentracing_propagate_context;",
{BackendProtocol: "HTTPS"}: "opentracing_propagate_context;",
{BackendProtocol: "AUTO_HTTP"}: "opentracing_propagate_context;",
{BackendProtocol: "GRPC"}: "opentracing_grpc_propagate_context;",
{BackendProtocol: "GRPCS"}: "opentracing_grpc_propagate_context;",
{BackendProtocol: "FCGI"}: "opentracing_propagate_context;",
nil: "",
{BackendProtocol: httpProtocol}: "opentracing_propagate_context;",
{BackendProtocol: httpsProtocol}: "opentracing_propagate_context;",
{BackendProtocol: autoHTTPProtocol}: "opentracing_propagate_context;",
{BackendProtocol: grpcProtocol}: "opentracing_grpc_propagate_context;",
{BackendProtocol: grpcsProtocol}: "opentracing_grpc_propagate_context;",
{BackendProtocol: fcgiProtocol}: "opentracing_propagate_context;",
nil: "",
}
for loc, expectedDirective := range tests {
@ -1153,13 +1155,13 @@ func TestOpentracingPropagateContext(t *testing.T) {
func TestOpentelemetryPropagateContext(t *testing.T) {
tests := map[*ingress.Location]string{
{BackendProtocol: "HTTP"}: "opentelemetry_propagate;",
{BackendProtocol: "HTTPS"}: "opentelemetry_propagate;",
{BackendProtocol: "AUTO_HTTP"}: "opentelemetry_propagate;",
{BackendProtocol: "GRPC"}: "opentelemetry_propagate;",
{BackendProtocol: "GRPCS"}: "opentelemetry_propagate;",
{BackendProtocol: "FCGI"}: "opentelemetry_propagate;",
nil: "",
{BackendProtocol: httpProtocol}: "opentelemetry_propagate;",
{BackendProtocol: httpsProtocol}: "opentelemetry_propagate;",
{BackendProtocol: autoHTTPProtocol}: "opentelemetry_propagate;",
{BackendProtocol: grpcProtocol}: "opentelemetry_propagate;",
{BackendProtocol: grpcsProtocol}: "opentelemetry_propagate;",
{BackendProtocol: fcgiProtocol}: "opentelemetry_propagate;",
nil: "",
}
for loc, expectedDirective := range tests {
@ -1171,7 +1173,6 @@ func TestOpentelemetryPropagateContext(t *testing.T) {
}
func TestGetIngressInformation(t *testing.T) {
testcases := map[string]struct {
Ingress interface{}
Host string
@ -1625,7 +1626,7 @@ func TestProxySetHeader(t *testing.T) {
{
name: "gRPC backend",
loc: &ingress.Location{
BackendProtocol: "GRPC",
BackendProtocol: grpcProtocol,
},
expected: "grpc_set_header",
},
@ -1716,7 +1717,6 @@ func TestBuildOpenTracing(t *testing.T) {
if expected != actual {
t.Errorf("Expected '%v' but returned '%v'", expected, actual)
}
}
func TestBuildOpenTelemetry(t *testing.T) {
@ -1777,6 +1777,7 @@ func TestEnforceRegexModifier(t *testing.T) {
}
}
//nolint:dupl // Ignore dupl errors for similar test case
func TestShouldLoadModSecurityModule(t *testing.T) {
// ### Invalid argument type tests ###
// The first tests should return false.
@ -1877,6 +1878,7 @@ opentracing_trust_incoming_span off;`
}
}
//nolint:dupl // Ignore dupl errors for similar test case
func TestShouldLoadOpentracingModule(t *testing.T) {
// ### Invalid argument type tests ###
// The first tests should return false.
@ -1978,6 +1980,7 @@ opentelemetry_trust_incoming_spans off;`
}
}
//nolint:dupl // Ignore dupl errors for similar test case
func TestShouldLoadOpentelemetryModule(t *testing.T) {
// ### Invalid argument type tests ###
// The first tests should return false.
@ -2104,7 +2107,6 @@ func TestModSecurityForLocation(t *testing.T) {
}
func TestBuildServerName(t *testing.T) {
testCases := []struct {
title string
hostname string