From fb33c58d188e8fb3ee21b3f5957daed2c2e24a1d Mon Sep 17 00:00:00 2001 From: Manuel de Brito Fontes Date: Tue, 7 Nov 2017 13:36:51 -0300 Subject: [PATCH 1/6] Refactor annotations --- .../annotations.go | 159 +++++++----------- .../annotations_test.go | 100 +++++++---- pkg/ingress/annotations/auth/main.go | 10 +- pkg/ingress/annotations/auth/main_test.go | 2 +- pkg/ingress/annotations/authreq/main.go | 10 +- pkg/ingress/annotations/authreq/main_test.go | 4 +- pkg/ingress/annotations/authtls/main.go | 21 +-- pkg/ingress/annotations/cors/main.go | 8 +- pkg/ingress/annotations/cors/main_test.go | 2 +- pkg/ingress/annotations/healthcheck/main.go | 8 +- .../annotations/healthcheck/main_test.go | 2 +- .../annotations/portinredirect/main_test.go | 3 +- pkg/ingress/annotations/proxy/main.go | 8 +- pkg/ingress/annotations/proxy/main_test.go | 8 +- pkg/ingress/annotations/ratelimit/main.go | 10 +- .../annotations/ratelimit/main_test.go | 2 +- pkg/ingress/annotations/redirect/redirect.go | 12 +- pkg/ingress/annotations/rewrite/main.go | 8 +- pkg/ingress/annotations/rewrite/main_test.go | 13 +- .../annotations/secureupstream/main.go | 8 +- .../annotations/secureupstream/main_test.go | 3 +- .../annotations/sessionaffinity/main.go | 31 ++-- .../annotations/sessionaffinity/main_test.go | 14 +- pkg/ingress/controller/backend_ssl.go | 16 -- pkg/ingress/controller/controller.go | 143 ++++++++++------ pkg/ingress/controller/listers.go | 12 +- pkg/ingress/controller/nginx.go | 28 +-- pkg/ingress/controller/template/template.go | 4 +- .../controller/template/template_test.go | 6 +- pkg/ingress/controller/util.go | 16 -- pkg/ingress/controller/util_test.go | 56 ------ pkg/ingress/store/main.go | 17 ++ pkg/ingress/types.go | 27 +-- 33 files changed, 370 insertions(+), 401 deletions(-) rename pkg/ingress/{controller => annotations}/annotations.go (59%) rename pkg/ingress/{controller => annotations}/annotations_test.go (81%) diff --git a/pkg/ingress/controller/annotations.go b/pkg/ingress/annotations/annotations.go similarity index 59% rename from pkg/ingress/controller/annotations.go rename to pkg/ingress/annotations/annotations.go index d251db4eb..d4aca392a 100644 --- a/pkg/ingress/controller/annotations.go +++ b/pkg/ingress/annotations/annotations.go @@ -14,12 +14,15 @@ See the License for the specific language governing permissions and limitations under the License. */ -package controller +package annotations import ( "github.com/golang/glog" + "github.com/imdario/mergo" extensions "k8s.io/api/extensions/v1beta1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/ingress-nginx/pkg/ingress/annotations/alias" "k8s.io/ingress-nginx/pkg/ingress/annotations/auth" "k8s.io/ingress-nginx/pkg/ingress/annotations/authreq" @@ -48,51 +51,89 @@ import ( "k8s.io/ingress-nginx/pkg/ingress/resolver" ) -type extractorConfig interface { +// DeniedKeyName name of the key that contains the reason to deny a location +const DeniedKeyName = "Denied" + +type config interface { resolver.AuthCertificate resolver.DefaultBackend resolver.Secret resolver.Service } -type annotationExtractor struct { +// Ingress defines the valid annotations present in one NGINX Ingress rule +type Ingress struct { + metav1.ObjectMeta + Alias string + BasicDigestAuth auth.Config + CertificateAuth authtls.Config + ClientBodyBufferSize string + ConfigurationSnippet string + CorsConfig cors.Config + DefaultBackend string + ExternalAuth authreq.Config + HealthCheck healthcheck.Config + Proxy proxy.Config + RateLimit ratelimit.Config + Redirect redirect.Config + Rewrite rewrite.Config + SecureUpstream secureupstream.Config + ServerSnippet string + ServiceUpstream bool + SessionAffinity sessionaffinity.Config + SSLPassthrough bool + UsePortInRedirects bool + UpstreamHashBy string + UpstreamVhost string + VtsFilterKey string + Whitelist ipwhitelist.SourceRange +} + +// Extractor defines the annotation parsers to be used in the extraction of annotations +type Extractor struct { secretResolver resolver.Secret annotations map[string]parser.IngressAnnotation } -func newAnnotationExtractor(cfg extractorConfig) annotationExtractor { - return annotationExtractor{ +// NewAnnotationExtractor creates a new annotations extractor +func NewAnnotationExtractor(cfg config) Extractor { + return Extractor{ cfg, map[string]parser.IngressAnnotation{ + "Alias": alias.NewParser(), "BasicDigestAuth": auth.NewParser(auth.AuthDirectory, cfg), - "ExternalAuth": authreq.NewParser(), "CertificateAuth": authtls.NewParser(cfg), + "ClientBodyBufferSize": clientbodybuffersize.NewParser(), + "ConfigurationSnippet": snippet.NewParser(), "CorsConfig": cors.NewParser(), + "DefaultBackend": defaultbackend.NewParser(cfg), + "ExternalAuth": authreq.NewParser(), "HealthCheck": healthcheck.NewParser(cfg), - "Whitelist": ipwhitelist.NewParser(cfg), - "UsePortInRedirects": portinredirect.NewParser(cfg), "Proxy": proxy.NewParser(cfg), "RateLimit": ratelimit.NewParser(cfg), "Redirect": redirect.NewParser(), "Rewrite": rewrite.NewParser(cfg), "SecureUpstream": secureupstream.NewParser(cfg), + "ServerSnippet": serversnippet.NewParser(), "ServiceUpstream": serviceupstream.NewParser(), "SessionAffinity": sessionaffinity.NewParser(), "SSLPassthrough": sslpassthrough.NewParser(), - "ConfigurationSnippet": snippet.NewParser(), - "Alias": alias.NewParser(), - "ClientBodyBufferSize": clientbodybuffersize.NewParser(), - "DefaultBackend": defaultbackend.NewParser(cfg), + "UsePortInRedirects": portinredirect.NewParser(cfg), "UpstreamHashBy": upstreamhashby.NewParser(), "UpstreamVhost": upstreamvhost.NewParser(), "VtsFilterKey": vtsfilterkey.NewParser(), - "ServerSnippet": serversnippet.NewParser(), + "Whitelist": ipwhitelist.NewParser(cfg), }, } } -func (e *annotationExtractor) Extract(ing *extensions.Ingress) map[string]interface{} { - anns := make(map[string]interface{}) +// Extract extracts the annotations from an Ingress +func (e Extractor) Extract(ing *extensions.Ingress) *Ingress { + pia := &Ingress{ + ObjectMeta: ing.ObjectMeta, + } + + data := make(map[string]interface{}) for name, annotationParser := range e.annotations { val, err := annotationParser.Parse(ing) glog.V(5).Infof("annotation %v in Ingress %v/%v: %v", name, ing.GetNamespace(), ing.GetName(), val) @@ -105,9 +146,9 @@ func (e *annotationExtractor) Extract(ing *extensions.Ingress) map[string]interf continue } - _, alreadyDenied := anns[DeniedKeyName] + _, alreadyDenied := data[DeniedKeyName] if !alreadyDenied { - anns[DeniedKeyName] = err + data[DeniedKeyName] = err glog.Errorf("error reading %v annotation in Ingress %v/%v: %v", name, ing.GetNamespace(), ing.GetName(), err) continue } @@ -116,90 +157,14 @@ func (e *annotationExtractor) Extract(ing *extensions.Ingress) map[string]interf } if val != nil { - anns[name] = val + data[name] = val } } - return anns -} - -const ( - secureUpstream = "SecureUpstream" - healthCheck = "HealthCheck" - sslPassthrough = "SSLPassthrough" - sessionAffinity = "SessionAffinity" - serviceUpstream = "ServiceUpstream" - serverAlias = "Alias" - corsConfig = "CorsConfig" - clientBodyBufferSize = "ClientBodyBufferSize" - certificateAuth = "CertificateAuth" - serverSnippet = "ServerSnippet" - upstreamHashBy = "UpstreamHashBy" -) - -func (e *annotationExtractor) ServiceUpstream(ing *extensions.Ingress) bool { - val, _ := e.annotations[serviceUpstream].Parse(ing) - return val.(bool) -} - -func (e *annotationExtractor) SecureUpstream(ing *extensions.Ingress) *secureupstream.Secure { - val, err := e.annotations[secureUpstream].Parse(ing) + err := mergo.Map(pia, data) if err != nil { - glog.Errorf("error parsing secure upstream: %v", err) - } - secure := val.(*secureupstream.Secure) - return secure -} - -func (e *annotationExtractor) HealthCheck(ing *extensions.Ingress) *healthcheck.Upstream { - val, _ := e.annotations[healthCheck].Parse(ing) - return val.(*healthcheck.Upstream) -} - -func (e *annotationExtractor) SSLPassthrough(ing *extensions.Ingress) bool { - val, _ := e.annotations[sslPassthrough].Parse(ing) - return val.(bool) -} - -func (e *annotationExtractor) Alias(ing *extensions.Ingress) string { - val, _ := e.annotations[serverAlias].Parse(ing) - return val.(string) -} - -func (e *annotationExtractor) ClientBodyBufferSize(ing *extensions.Ingress) string { - val, _ := e.annotations[clientBodyBufferSize].Parse(ing) - return val.(string) -} - -func (e *annotationExtractor) SessionAffinity(ing *extensions.Ingress) *sessionaffinity.AffinityConfig { - val, _ := e.annotations[sessionAffinity].Parse(ing) - return val.(*sessionaffinity.AffinityConfig) -} - -func (e *annotationExtractor) Cors(ing *extensions.Ingress) *cors.CorsConfig { - val, _ := e.annotations[corsConfig].Parse(ing) - return val.(*cors.CorsConfig) -} - -func (e *annotationExtractor) CertificateAuth(ing *extensions.Ingress) *authtls.AuthSSLConfig { - val, err := e.annotations[certificateAuth].Parse(ing) - if errors.IsMissingAnnotations(err) { - return nil + glog.Errorf("unexpected error merging extracted annotations: %v", err) } - if err != nil { - glog.Errorf("error parsing certificate auth: %v", err) - } - secure := val.(*authtls.AuthSSLConfig) - return secure -} - -func (e *annotationExtractor) ServerSnippet(ing *extensions.Ingress) string { - val, _ := e.annotations[serverSnippet].Parse(ing) - return val.(string) -} - -func (e *annotationExtractor) UpstreamHashBy(ing *extensions.Ingress) string { - val, _ := e.annotations[upstreamHashBy].Parse(ing) - return val.(string) + return pia } diff --git a/pkg/ingress/controller/annotations_test.go b/pkg/ingress/annotations/annotations_test.go similarity index 81% rename from pkg/ingress/controller/annotations_test.go rename to pkg/ingress/annotations/annotations_test.go index 025a526d5..55fde07ae 100644 --- a/pkg/ingress/controller/annotations_test.go +++ b/pkg/ingress/annotations/annotations_test.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package controller +package annotations import ( "testing" @@ -75,20 +75,6 @@ func (m mockCfg) GetAuthCertificate(name string) (*resolver.AuthSSLCert, error) return nil, nil } -func TestAnnotationExtractor(t *testing.T) { - ec := newAnnotationExtractor(mockCfg{}) - ing := buildIngress() - - m := ec.Extract(ing) - // the map at least should contains HealthCheck and Proxy information (defaults) - if _, ok := m["HealthCheck"]; !ok { - t.Error("expected HealthCheck annotation") - } - if _, ok := m["Proxy"]; !ok { - t.Error("expected Proxy annotation") - } -} - func buildIngress() *extensions.Ingress { defaultBackend := extensions.IngressBackend{ ServiceName: "default-backend", @@ -125,7 +111,7 @@ func buildIngress() *extensions.Ingress { } func TestSecureUpstream(t *testing.T) { - ec := newAnnotationExtractor(mockCfg{}) + ec := NewAnnotationExtractor(mockCfg{}) ing := buildIngress() fooAnns := []struct { @@ -141,7 +127,7 @@ func TestSecureUpstream(t *testing.T) { for _, foo := range fooAnns { ing.SetAnnotations(foo.annotations) - r := ec.SecureUpstream(ing) + r := ec.Extract(ing).SecureUpstream if r.Secure != foo.er { t.Errorf("Returned %v but expected %v", r, foo.er) } @@ -149,7 +135,7 @@ func TestSecureUpstream(t *testing.T) { } func TestSecureVerifyCACert(t *testing.T) { - ec := newAnnotationExtractor(mockCfg{ + ec := NewAnnotationExtractor(mockCfg{ MockSecrets: map[string]*apiv1.Secret{ "default/secure-verify-ca": { ObjectMeta: metav1.ObjectMeta{ @@ -176,15 +162,16 @@ func TestSecureVerifyCACert(t *testing.T) { for _, ann := range anns { ing := buildIngress() ing.SetAnnotations(ann.annotations) - res := ec.SecureUpstream(ing) - if (res.CACert.CAFileName != "") != ann.exists { + res := ec.Extract(ing).SecureUpstream + + if (res != nil && res.CACert.CAFileName != "") != ann.exists { t.Errorf("Expected exists was %v on iteration %v", ann.exists, ann.it) } } } func TestHealthCheck(t *testing.T) { - ec := newAnnotationExtractor(mockCfg{}) + ec := NewAnnotationExtractor(mockCfg{}) ing := buildIngress() fooAnns := []struct { @@ -201,7 +188,7 @@ func TestHealthCheck(t *testing.T) { for _, foo := range fooAnns { ing.SetAnnotations(foo.annotations) - r := ec.HealthCheck(ing) + r := ec.Extract(ing).HealthCheck if r == nil { t.Errorf("Returned nil but expected a healthcheck.Upstream") continue @@ -218,7 +205,7 @@ func TestHealthCheck(t *testing.T) { } func TestSSLPassthrough(t *testing.T) { - ec := newAnnotationExtractor(mockCfg{}) + ec := NewAnnotationExtractor(mockCfg{}) ing := buildIngress() fooAnns := []struct { @@ -234,7 +221,7 @@ func TestSSLPassthrough(t *testing.T) { for _, foo := range fooAnns { ing.SetAnnotations(foo.annotations) - r := ec.SSLPassthrough(ing) + r := ec.Extract(ing).SSLPassthrough if r != foo.er { t.Errorf("Returned %v but expected %v", r, foo.er) } @@ -242,7 +229,7 @@ func TestSSLPassthrough(t *testing.T) { } func TestUpstreamHashBy(t *testing.T) { - ec := newAnnotationExtractor(mockCfg{}) + ec := NewAnnotationExtractor(mockCfg{}) ing := buildIngress() fooAnns := []struct { @@ -258,7 +245,7 @@ func TestUpstreamHashBy(t *testing.T) { for _, foo := range fooAnns { ing.SetAnnotations(foo.annotations) - r := ec.UpstreamHashBy(ing) + r := ec.Extract(ing).UpstreamHashBy if r != foo.er { t.Errorf("Returned %v but expected %v", r, foo.er) } @@ -266,7 +253,7 @@ func TestUpstreamHashBy(t *testing.T) { } func TestAffinitySession(t *testing.T) { - ec := newAnnotationExtractor(mockCfg{}) + ec := NewAnnotationExtractor(mockCfg{}) ing := buildIngress() fooAnns := []struct { @@ -284,25 +271,25 @@ func TestAffinitySession(t *testing.T) { for _, foo := range fooAnns { ing.SetAnnotations(foo.annotations) - r := ec.SessionAffinity(ing) + r := ec.Extract(ing).SessionAffinity t.Logf("Testing pass %v %v %v", foo.affinitytype, foo.hash, foo.name) if r == nil { t.Errorf("Returned nil but expected a SessionAffinity.AffinityConfig") continue } - if r.CookieConfig.Hash != foo.hash { - t.Errorf("Returned %v but expected %v for Hash", r.CookieConfig.Hash, foo.hash) + if r.Cookie.Hash != foo.hash { + t.Errorf("Returned %v but expected %v for Hash", r.Cookie.Hash, foo.hash) } - if r.CookieConfig.Name != foo.name { - t.Errorf("Returned %v but expected %v for Name", r.CookieConfig.Name, foo.name) + if r.Cookie.Name != foo.name { + t.Errorf("Returned %v but expected %v for Name", r.Cookie.Name, foo.name) } } } func TestCors(t *testing.T) { - ec := newAnnotationExtractor(mockCfg{}) + ec := NewAnnotationExtractor(mockCfg{}) ing := buildIngress() fooAnns := []struct { @@ -322,7 +309,7 @@ func TestCors(t *testing.T) { for _, foo := range fooAnns { ing.SetAnnotations(foo.annotations) - r := ec.Cors(ing) + r := ec.Extract(ing).CorsConfig t.Logf("Testing pass %v %v %v %v %v", foo.corsenabled, foo.methods, foo.headers, foo.origin, foo.credentials) if r == nil { t.Errorf("Returned nil but expected a Cors.CorsConfig") @@ -351,3 +338,48 @@ func TestCors(t *testing.T) { } } + +/* +func TestMergeLocationAnnotations(t *testing.T) { + // initial parameters + keys := []string{"BasicDigestAuth", "CorsConfig", "ExternalAuth", "RateLimit", "Redirect", "Rewrite", "Whitelist", "Proxy", "UsePortInRedirects"} + + loc := ingress.Location{} + annotations := &Ingress{ + BasicDigestAuth: &auth.Config{}, + CorsConfig: &cors.Config{}, + ExternalAuth: &authreq.Config{}, + RateLimit: &ratelimit.Config{}, + Redirect: &redirect.Config{}, + Rewrite: &rewrite.Config{}, + Whitelist: &ipwhitelist.SourceRange{}, + Proxy: &proxy.Config{}, + UsePortInRedirects: true, + } + + // create test table + type fooMergeLocationAnnotationsStruct struct { + fName string + er interface{} + } + fooTests := []fooMergeLocationAnnotationsStruct{} + for name, value := range keys { + fva := fooMergeLocationAnnotationsStruct{name, value} + fooTests = append(fooTests, fva) + } + + // execute test + MergeWithLocation(&loc, annotations) + + // check result + for _, foo := range fooTests { + fv := reflect.ValueOf(loc).FieldByName(foo.fName).Interface() + if !reflect.DeepEqual(fv, foo.er) { + t.Errorf("Returned %v but expected %v for the field %s", fv, foo.er, foo.fName) + } + } + if _, ok := annotations[DeniedKeyName]; ok { + t.Errorf("%s should be removed after mergeLocationAnnotations", DeniedKeyName) + } +} +*/ diff --git a/pkg/ingress/annotations/auth/main.go b/pkg/ingress/annotations/auth/main.go index 5830f0f71..1b28d81d4 100644 --- a/pkg/ingress/annotations/auth/main.go +++ b/pkg/ingress/annotations/auth/main.go @@ -46,8 +46,8 @@ var ( AuthDirectory = "/etc/ingress-controller/auth" ) -// BasicDigest returns authentication configuration for an Ingress rule -type BasicDigest struct { +// Config returns authentication configuration for an Ingress rule +type Config struct { Type string `json:"type"` Realm string `json:"realm"` File string `json:"file"` @@ -55,8 +55,8 @@ type BasicDigest struct { FileSHA string `json:"fileSha"` } -// Equal tests for equality between two BasicDigest types -func (bd1 *BasicDigest) Equal(bd2 *BasicDigest) bool { +// Equal tests for equality between two Config types +func (bd1 *Config) Equal(bd2 *Config) bool { if bd1 == bd2 { return true } @@ -140,7 +140,7 @@ func (a auth) Parse(ing *extensions.Ingress) (interface{}, error) { return nil, err } - return &BasicDigest{ + return &Config{ Type: at, Realm: realm, File: passFile, diff --git a/pkg/ingress/annotations/auth/main_test.go b/pkg/ingress/annotations/auth/main_test.go index df042ad4f..ffb421719 100644 --- a/pkg/ingress/annotations/auth/main_test.go +++ b/pkg/ingress/annotations/auth/main_test.go @@ -109,7 +109,7 @@ func TestIngressAuth(t *testing.T) { if err != nil { t.Errorf("Uxpected error with ingress: %v", err) } - auth, ok := i.(*BasicDigest) + auth, ok := i.(*Config) if !ok { t.Errorf("expected a BasicDigest type") } diff --git a/pkg/ingress/annotations/authreq/main.go b/pkg/ingress/annotations/authreq/main.go index 89ec8d8c1..28e884892 100644 --- a/pkg/ingress/annotations/authreq/main.go +++ b/pkg/ingress/annotations/authreq/main.go @@ -36,7 +36,7 @@ const ( ) // External returns external authentication configuration for an Ingress rule -type External struct { +type Config struct { URL string `json:"url"` // Host contains the hostname defined in the URL Host string `json:"host"` @@ -45,8 +45,8 @@ type External struct { ResponseHeaders []string `json:"responseHeaders,omitEmpty"` } -// Equal tests for equality between two External types -func (e1 *External) Equal(e2 *External) bool { +// Equal tests for equality between two Config types +func (e1 *Config) Equal(e2 *Config) bool { if e1 == e2 { return true } @@ -116,7 +116,7 @@ func NewParser() parser.IngressAnnotation { } // ParseAnnotations parses the annotations contained in the ingress -// rule used to use an external URL as source for authentication +// rule used to use an Config URL as source for authentication func (a authReq) Parse(ing *extensions.Ingress) (interface{}, error) { str, err := parser.GetStringAnnotation(authURL, ing) if err != nil { @@ -165,7 +165,7 @@ func (a authReq) Parse(ing *extensions.Ingress) (interface{}, error) { } } - return &External{ + return &Config{ URL: str, Host: ur.Hostname(), SigninURL: signin, diff --git a/pkg/ingress/annotations/authreq/main_test.go b/pkg/ingress/annotations/authreq/main_test.go index 1fc75fcbc..8256302a7 100644 --- a/pkg/ingress/annotations/authreq/main_test.go +++ b/pkg/ingress/annotations/authreq/main_test.go @@ -97,7 +97,7 @@ func TestAnnotations(t *testing.T) { } continue } - u, ok := i.(*External) + u, ok := i.(*Config) if !ok { t.Errorf("%v: expected an External type", test.title) } @@ -149,7 +149,7 @@ func TestHeaderAnnotations(t *testing.T) { } t.Log(i) - u, ok := i.(*External) + u, ok := i.(*Config) if !ok { t.Errorf("%v: expected an External type", test.title) continue diff --git a/pkg/ingress/annotations/authtls/main.go b/pkg/ingress/annotations/authtls/main.go index 7b2746435..73556bee2 100644 --- a/pkg/ingress/annotations/authtls/main.go +++ b/pkg/ingress/annotations/authtls/main.go @@ -20,11 +20,12 @@ import ( "github.com/pkg/errors" extensions "k8s.io/api/extensions/v1beta1" + "regexp" + "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" ing_errors "k8s.io/ingress-nginx/pkg/ingress/errors" "k8s.io/ingress-nginx/pkg/ingress/resolver" "k8s.io/ingress-nginx/pkg/k8s" - "regexp" ) const ( @@ -41,17 +42,17 @@ var ( authVerifyClientRegex = regexp.MustCompile(`on|off|optional|optional_no_ca`) ) -// AuthSSLConfig contains the AuthSSLCert used for muthual autentication +// Config contains the AuthSSLCert used for muthual autentication // and the configured ValidationDepth -type AuthSSLConfig struct { +type Config struct { resolver.AuthSSLCert VerifyClient string `json:"verify_client"` ValidationDepth int `json:"validationDepth"` ErrorPage string `json:"errorPage"` } -// Equal tests for equality between two AuthSSLConfig types -func (assl1 *AuthSSLConfig) Equal(assl2 *AuthSSLConfig) bool { +// Equal tests for equality between two Config types +func (assl1 *Config) Equal(assl2 *Config) bool { if assl1 == assl2 { return true } @@ -88,16 +89,16 @@ func (a authTLS) Parse(ing *extensions.Ingress) (interface{}, error) { tlsauthsecret, err := parser.GetStringAnnotation(annotationAuthTLSSecret, ing) if err != nil { - return &AuthSSLConfig{}, err + return &Config{}, err } if tlsauthsecret == "" { - return &AuthSSLConfig{}, ing_errors.NewLocationDenied("an empty string is not a valid secret name") + return &Config{}, ing_errors.NewLocationDenied("an empty string is not a valid secret name") } _, _, err = k8s.ParseNameNS(tlsauthsecret) if err != nil { - return &AuthSSLConfig{}, ing_errors.NewLocationDenied(err.Error()) + return &Config{}, ing_errors.NewLocationDenied(err.Error()) } tlsVerifyClient, err := parser.GetStringAnnotation(annotationAuthVerifyClient, ing) @@ -112,7 +113,7 @@ func (a authTLS) Parse(ing *extensions.Ingress) (interface{}, error) { authCert, err := a.certResolver.GetAuthCertificate(tlsauthsecret) if err != nil { - return &AuthSSLConfig{}, ing_errors.LocationDenied{ + return &Config{}, ing_errors.LocationDenied{ Reason: errors.Wrap(err, "error obtaining certificate"), } } @@ -122,7 +123,7 @@ func (a authTLS) Parse(ing *extensions.Ingress) (interface{}, error) { errorpage = "" } - return &AuthSSLConfig{ + return &Config{ AuthSSLCert: *authCert, VerifyClient: tlsVerifyClient, ValidationDepth: tlsdepth, diff --git a/pkg/ingress/annotations/cors/main.go b/pkg/ingress/annotations/cors/main.go index 152174cb6..f382606fa 100644 --- a/pkg/ingress/annotations/cors/main.go +++ b/pkg/ingress/annotations/cors/main.go @@ -51,8 +51,8 @@ var ( type cors struct { } -// CorsConfig contains the Cors configuration to be used in the Ingress -type CorsConfig struct { +// Config contains the Cors configuration to be used in the Ingress +type Config struct { CorsEnabled bool `json:"corsEnabled"` CorsAllowOrigin string `json:"corsAllowOrigin"` CorsAllowMethods string `json:"corsAllowMethods"` @@ -66,7 +66,7 @@ func NewParser() parser.IngressAnnotation { } // Equal tests for equality between two External types -func (c1 *CorsConfig) Equal(c2 *CorsConfig) bool { +func (c1 *Config) Equal(c2 *Config) bool { if c1 == c2 { return true } @@ -120,7 +120,7 @@ func (a cors) Parse(ing *extensions.Ingress) (interface{}, error) { corsallowcredentials = true } - return &CorsConfig{ + return &Config{ CorsEnabled: corsenabled, CorsAllowOrigin: corsalloworigin, CorsAllowHeaders: corsallowheaders, diff --git a/pkg/ingress/annotations/cors/main_test.go b/pkg/ingress/annotations/cors/main_test.go index 11a022731..101e26cbc 100644 --- a/pkg/ingress/annotations/cors/main_test.go +++ b/pkg/ingress/annotations/cors/main_test.go @@ -72,7 +72,7 @@ func TestIngressCorsConfig(t *testing.T) { ing.SetAnnotations(data) corst, _ := NewParser().Parse(ing) - nginxCors, ok := corst.(*CorsConfig) + nginxCors, ok := corst.(*Config) if !ok { t.Errorf("expected a Config type") } diff --git a/pkg/ingress/annotations/healthcheck/main.go b/pkg/ingress/annotations/healthcheck/main.go index 5d3850d90..8b29838be 100644 --- a/pkg/ingress/annotations/healthcheck/main.go +++ b/pkg/ingress/annotations/healthcheck/main.go @@ -28,9 +28,9 @@ const ( upsFailTimeout = "ingress.kubernetes.io/upstream-fail-timeout" ) -// Upstream returns the URL and method to use check the status of +// Config returns the URL and method to use check the status of // the upstream server/s -type Upstream struct { +type Config struct { MaxFails int `json:"maxFails"` FailTimeout int `json:"failTimeout"` } @@ -49,7 +49,7 @@ func NewParser(br resolver.DefaultBackend) parser.IngressAnnotation { func (a healthCheck) Parse(ing *extensions.Ingress) (interface{}, error) { defBackend := a.backendResolver.GetDefaultBackend() if ing.GetAnnotations() == nil { - return &Upstream{defBackend.UpstreamMaxFails, defBackend.UpstreamFailTimeout}, nil + return &Config{defBackend.UpstreamMaxFails, defBackend.UpstreamFailTimeout}, nil } mf, err := parser.GetIntAnnotation(upsMaxFails, ing) @@ -62,5 +62,5 @@ func (a healthCheck) Parse(ing *extensions.Ingress) (interface{}, error) { ft = defBackend.UpstreamFailTimeout } - return &Upstream{mf, ft}, nil + return &Config{mf, ft}, nil } diff --git a/pkg/ingress/annotations/healthcheck/main_test.go b/pkg/ingress/annotations/healthcheck/main_test.go index afcc9540d..d32dc8de2 100644 --- a/pkg/ingress/annotations/healthcheck/main_test.go +++ b/pkg/ingress/annotations/healthcheck/main_test.go @@ -77,7 +77,7 @@ func TestIngressHealthCheck(t *testing.T) { ing.SetAnnotations(data) hzi, _ := NewParser(mockBackend{}).Parse(ing) - nginxHz, ok := hzi.(*Upstream) + nginxHz, ok := hzi.(*Config) if !ok { t.Errorf("expected a Upstream type") } diff --git a/pkg/ingress/annotations/portinredirect/main_test.go b/pkg/ingress/annotations/portinredirect/main_test.go index 44b0444e9..802e8b50a 100644 --- a/pkg/ingress/annotations/portinredirect/main_test.go +++ b/pkg/ingress/annotations/portinredirect/main_test.go @@ -17,6 +17,7 @@ limitations under the License. package portinredirect import ( + "fmt" "testing" api "k8s.io/api/core/v1" @@ -24,8 +25,6 @@ import ( meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" - "fmt" - "k8s.io/ingress-nginx/pkg/ingress/defaults" ) diff --git a/pkg/ingress/annotations/proxy/main.go b/pkg/ingress/annotations/proxy/main.go index b35696b97..ee8360d97 100644 --- a/pkg/ingress/annotations/proxy/main.go +++ b/pkg/ingress/annotations/proxy/main.go @@ -36,8 +36,8 @@ const ( requestBuffering = "ingress.kubernetes.io/proxy-request-buffering" ) -// Configuration returns the proxy timeout to use in the upstream server/s -type Configuration struct { +// Config returns the proxy timeout to use in the upstream server/s +type Config struct { BodySize string `json:"bodySize"` ConnectTimeout int `json:"connectTimeout"` SendTimeout int `json:"sendTimeout"` @@ -51,7 +51,7 @@ type Configuration struct { } // Equal tests for equality between two Configuration types -func (l1 *Configuration) Equal(l2 *Configuration) bool { +func (l1 *Config) Equal(l2 *Config) bool { if l1 == l2 { return true } @@ -156,5 +156,5 @@ func (a proxy) Parse(ing *extensions.Ingress) (interface{}, error) { rb = defBackend.ProxyRequestBuffering } - return &Configuration{bs, ct, st, rt, bufs, cd, cp, nu, pp, rb}, nil + return &Config{bs, ct, st, rt, bufs, cd, cp, nu, pp, rb}, nil } diff --git a/pkg/ingress/annotations/proxy/main_test.go b/pkg/ingress/annotations/proxy/main_test.go index 04ffbda53..8fa08ed34 100644 --- a/pkg/ingress/annotations/proxy/main_test.go +++ b/pkg/ingress/annotations/proxy/main_test.go @@ -97,9 +97,9 @@ func TestProxy(t *testing.T) { if err != nil { t.Fatalf("unexpected error parsing a valid") } - p, ok := i.(*Configuration) + p, ok := i.(*Config) if !ok { - t.Fatalf("expected a Configuration type") + t.Fatalf("expected a Config type") } if p.ConnectTimeout != 1 { t.Errorf("expected 1 as connect-timeout but returned %v", p.ConnectTimeout) @@ -137,9 +137,9 @@ func TestProxyWithNoAnnotation(t *testing.T) { if err != nil { t.Fatalf("unexpected error parsing a valid") } - p, ok := i.(*Configuration) + p, ok := i.(*Config) if !ok { - t.Fatalf("expected a Configuration type") + t.Fatalf("expected a Config type") } if p.ConnectTimeout != 10 { t.Errorf("expected 10 as connect-timeout but returned %v", p.ConnectTimeout) diff --git a/pkg/ingress/annotations/ratelimit/main.go b/pkg/ingress/annotations/ratelimit/main.go index 651b71859..6118e8a04 100644 --- a/pkg/ingress/annotations/ratelimit/main.go +++ b/pkg/ingress/annotations/ratelimit/main.go @@ -45,11 +45,11 @@ const ( defSharedSize = 5 ) -// RateLimit returns rate limit configuration for an Ingress rule limiting the +// Config returns rate limit configuration for an Ingress rule limiting the // number of connections per IP address and/or connections per second. // If you both annotations are specified in a single Ingress rule, RPS limits // takes precedence -type RateLimit struct { +type Config struct { // Connections indicates a limit with the number of connections per IP address Connections Zone `json:"connections"` // RPS indicates a limit with the number of connections per second @@ -69,7 +69,7 @@ type RateLimit struct { } // Equal tests for equality between two RateLimit types -func (rt1 *RateLimit) Equal(rt2 *RateLimit) bool { +func (rt1 *Config) Equal(rt2 *Config) bool { if rt1 == rt2 { return true } @@ -185,7 +185,7 @@ func (a ratelimit) Parse(ing *extensions.Ingress) (interface{}, error) { } if rpm == 0 && rps == 0 && conn == 0 { - return &RateLimit{ + return &Config{ Connections: Zone{}, RPS: Zone{}, RPM: Zone{}, @@ -196,7 +196,7 @@ func (a ratelimit) Parse(ing *extensions.Ingress) (interface{}, error) { zoneName := fmt.Sprintf("%v_%v", ing.GetNamespace(), ing.GetName()) - return &RateLimit{ + return &Config{ Connections: Zone{ Name: fmt.Sprintf("%v_conn", zoneName), Limit: conn, diff --git a/pkg/ingress/annotations/ratelimit/main_test.go b/pkg/ingress/annotations/ratelimit/main_test.go index 9b079f293..bf21e30dc 100644 --- a/pkg/ingress/annotations/ratelimit/main_test.go +++ b/pkg/ingress/annotations/ratelimit/main_test.go @@ -107,7 +107,7 @@ func TestBadRateLimiting(t *testing.T) { if err != nil { t.Errorf("unexpected error: %v", err) } - rateLimit, ok := i.(*RateLimit) + rateLimit, ok := i.(*Config) if !ok { t.Errorf("expected a RateLimit type") } diff --git a/pkg/ingress/annotations/redirect/redirect.go b/pkg/ingress/annotations/redirect/redirect.go index 41074ca7c..d5f46fd4e 100644 --- a/pkg/ingress/annotations/redirect/redirect.go +++ b/pkg/ingress/annotations/redirect/redirect.go @@ -33,8 +33,8 @@ const ( www = "ingress.kubernetes.io/from-to-www-redirect" ) -// Redirect returns the redirect configuration for an Ingress rule -type Redirect struct { +// Config returns the redirect configuration for an Ingress rule +type Config struct { URL string `json:"url"` Code int `json:"code"` FromToWWW bool `json:"fromToWWW"` @@ -64,7 +64,7 @@ func (a redirect) Parse(ing *extensions.Ingress) (interface{}, error) { return nil, err } - return &Redirect{ + return &Config{ URL: tr, Code: http.StatusFound, FromToWWW: r3w, @@ -81,7 +81,7 @@ func (a redirect) Parse(ing *extensions.Ingress) (interface{}, error) { return nil, err } - return &Redirect{ + return &Config{ URL: pr, Code: http.StatusMovedPermanently, FromToWWW: r3w, @@ -89,7 +89,7 @@ func (a redirect) Parse(ing *extensions.Ingress) (interface{}, error) { } if r3w { - return &Redirect{ + return &Config{ FromToWWW: r3w, }, nil } @@ -98,7 +98,7 @@ func (a redirect) Parse(ing *extensions.Ingress) (interface{}, error) { } // Equal tests for equality between two Redirect types -func (r1 *Redirect) Equal(r2 *Redirect) bool { +func (r1 *Config) Equal(r2 *Config) bool { if r1 == r2 { return true } diff --git a/pkg/ingress/annotations/rewrite/main.go b/pkg/ingress/annotations/rewrite/main.go index ce97f657d..d396ec8c2 100644 --- a/pkg/ingress/annotations/rewrite/main.go +++ b/pkg/ingress/annotations/rewrite/main.go @@ -32,8 +32,8 @@ const ( appRoot = "ingress.kubernetes.io/app-root" ) -// Redirect describes the per location redirect config -type Redirect struct { +// Config describes the per location redirect config +type Config struct { // Target URI where the traffic must be redirected Target string `json:"target"` // AddBaseURL indicates if is required to add a base tag in the head @@ -50,7 +50,7 @@ type Redirect struct { } // Equal tests for equality between two Redirect types -func (r1 *Redirect) Equal(r2 *Redirect) bool { +func (r1 *Config) Equal(r2 *Config) bool { if r1 == r2 { return true } @@ -103,7 +103,7 @@ func (a rewrite) Parse(ing *extensions.Ingress) (interface{}, error) { abu, _ := parser.GetBoolAnnotation(addBaseURL, ing) bus, _ := parser.GetStringAnnotation(baseURLScheme, ing) ar, _ := parser.GetStringAnnotation(appRoot, ing) - return &Redirect{ + return &Config{ Target: rt, AddBaseURL: abu, BaseURLScheme: bus, diff --git a/pkg/ingress/annotations/rewrite/main_test.go b/pkg/ingress/annotations/rewrite/main_test.go index 5da0cfeee..3ad61f6cf 100644 --- a/pkg/ingress/annotations/rewrite/main_test.go +++ b/pkg/ingress/annotations/rewrite/main_test.go @@ -93,7 +93,7 @@ func TestRedirect(t *testing.T) { if err != nil { t.Errorf("Unexpected error with ingress: %v", err) } - redirect, ok := i.(*Redirect) + redirect, ok := i.(*Config) if !ok { t.Errorf("expected a Redirect type") } @@ -110,7 +110,7 @@ func TestSSLRedirect(t *testing.T) { ing.SetAnnotations(data) i, _ := NewParser(mockBackend{true}).Parse(ing) - redirect, ok := i.(*Redirect) + redirect, ok := i.(*Config) if !ok { t.Errorf("expected a Redirect type") } @@ -122,7 +122,7 @@ func TestSSLRedirect(t *testing.T) { ing.SetAnnotations(data) i, _ = NewParser(mockBackend{false}).Parse(ing) - redirect, ok = i.(*Redirect) + redirect, ok = i.(*Config) if !ok { t.Errorf("expected a Redirect type") } @@ -139,7 +139,7 @@ func TestForceSSLRedirect(t *testing.T) { ing.SetAnnotations(data) i, _ := NewParser(mockBackend{true}).Parse(ing) - redirect, ok := i.(*Redirect) + redirect, ok := i.(*Config) if !ok { t.Errorf("expected a Redirect type") } @@ -151,7 +151,7 @@ func TestForceSSLRedirect(t *testing.T) { ing.SetAnnotations(data) i, _ = NewParser(mockBackend{false}).Parse(ing) - redirect, ok = i.(*Redirect) + redirect, ok = i.(*Config) if !ok { t.Errorf("expected a Redirect type") } @@ -167,12 +167,11 @@ func TestAppRoot(t *testing.T) { ing.SetAnnotations(data) i, _ := NewParser(mockBackend{true}).Parse(ing) - redirect, ok := i.(*Redirect) + redirect, ok := i.(*Config) if !ok { t.Errorf("expected a App Context") } if redirect.AppRoot != "/app1" { t.Errorf("Unexpected value got in AppRoot") } - } diff --git a/pkg/ingress/annotations/secureupstream/main.go b/pkg/ingress/annotations/secureupstream/main.go index 119041cac..60b24eb95 100644 --- a/pkg/ingress/annotations/secureupstream/main.go +++ b/pkg/ingress/annotations/secureupstream/main.go @@ -31,8 +31,8 @@ const ( secureVerifyCASecret = "ingress.kubernetes.io/secure-verify-ca-secret" ) -// Secure describes SSL backend configuration -type Secure struct { +// Config describes SSL backend configuration +type Config struct { Secure bool `json:"secure"` CACert resolver.AuthSSLCert `json:"caCert"` } @@ -53,7 +53,7 @@ func NewParser(resolver resolver.AuthCertificate) parser.IngressAnnotation { func (a su) Parse(ing *extensions.Ingress) (interface{}, error) { s, _ := parser.GetBoolAnnotation(secureUpstream, ing) ca, _ := parser.GetStringAnnotation(secureVerifyCASecret, ing) - secure := &Secure{ + secure := &Config{ Secure: s, CACert: resolver.AuthSSLCert{}, } @@ -71,7 +71,7 @@ func (a su) Parse(ing *extensions.Ingress) (interface{}, error) { if caCert == nil { return secure, nil } - return &Secure{ + return &Config{ Secure: s, CACert: *caCert, }, nil diff --git a/pkg/ingress/annotations/secureupstream/main_test.go b/pkg/ingress/annotations/secureupstream/main_test.go index 27e4f22d7..35225285e 100644 --- a/pkg/ingress/annotations/secureupstream/main_test.go +++ b/pkg/ingress/annotations/secureupstream/main_test.go @@ -17,14 +17,13 @@ limitations under the License. package secureupstream import ( + "fmt" "testing" api "k8s.io/api/core/v1" extensions "k8s.io/api/extensions/v1beta1" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "fmt" - "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/ingress-nginx/pkg/ingress/resolver" ) diff --git a/pkg/ingress/annotations/sessionaffinity/main.go b/pkg/ingress/annotations/sessionaffinity/main.go index c0b274b09..87a2e6f28 100644 --- a/pkg/ingress/annotations/sessionaffinity/main.go +++ b/pkg/ingress/annotations/sessionaffinity/main.go @@ -42,24 +42,24 @@ var ( affinityCookieHashRegex = regexp.MustCompile(`^(index|md5|sha1)$`) ) -// AffinityConfig describes the per ingress session affinity config -type AffinityConfig struct { +// Config describes the per ingress session affinity config +type Config struct { // The type of affinity that will be used - AffinityType string `json:"type"` - CookieConfig + Type string `json:"type"` + Cookie } -// CookieConfig describes the Config of cookie type affinity -type CookieConfig struct { +// Cookie describes the Config of cookie type affinity +type Cookie struct { // The name of the cookie that will be used in case of cookie affinity type. Name string `json:"name"` // The hash that will be used to encode the cookie in case of cookie affinity type Hash string `json:"hash"` } -// CookieAffinityParse gets the annotation values related to Cookie Affinity +// cookieAffinityParse gets the annotation values related to Cookie Affinity // It also sets default values when no value or incorrect value is found -func CookieAffinityParse(ing *extensions.Ingress) *CookieConfig { +func cookieAffinityParse(ing *extensions.Ingress) *Cookie { sn, err := parser.GetStringAnnotation(annotationAffinityCookieName, ing) @@ -75,7 +75,7 @@ func CookieAffinityParse(ing *extensions.Ingress) *CookieConfig { sh = defaultAffinityCookieHash } - return &CookieConfig{ + return &Cookie{ Name: sn, Hash: sh, } @@ -92,7 +92,7 @@ type affinity struct { // ParseAnnotations parses the annotations contained in the ingress // rule used to configure the affinity directives func (a affinity) Parse(ing *extensions.Ingress) (interface{}, error) { - cookieAffinityConfig := &CookieConfig{} + cookie := &Cookie{} // Check the type of affinity that will be used at, err := parser.GetStringAnnotation(annotationAffinityType, ing) if err != nil { @@ -101,15 +101,14 @@ func (a affinity) Parse(ing *extensions.Ingress) (interface{}, error) { switch at { case "cookie": - cookieAffinityConfig = CookieAffinityParse(ing) - + cookie = cookieAffinityParse(ing) default: glog.V(3).Infof("No default affinity was found for Ingress %v", ing.Name) } - return &AffinityConfig{ - AffinityType: at, - CookieConfig: *cookieAffinityConfig, - }, nil + return &Config{ + Type: at, + Cookie: *cookie, + }, nil } diff --git a/pkg/ingress/annotations/sessionaffinity/main_test.go b/pkg/ingress/annotations/sessionaffinity/main_test.go index 5008c6b1e..625019827 100644 --- a/pkg/ingress/annotations/sessionaffinity/main_test.go +++ b/pkg/ingress/annotations/sessionaffinity/main_test.go @@ -70,20 +70,20 @@ func TestIngressAffinityCookieConfig(t *testing.T) { ing.SetAnnotations(data) affin, _ := NewParser().Parse(ing) - nginxAffinity, ok := affin.(*AffinityConfig) + nginxAffinity, ok := affin.(*Config) if !ok { t.Errorf("expected a Config type") } - if nginxAffinity.AffinityType != "cookie" { - t.Errorf("expected cookie as sticky-type but returned %v", nginxAffinity.AffinityType) + if nginxAffinity.Type != "cookie" { + t.Errorf("expected cookie as sticky-type but returned %v", nginxAffinity.Type) } - if nginxAffinity.CookieConfig.Hash != "md5" { - t.Errorf("expected md5 as sticky-hash but returned %v", nginxAffinity.CookieConfig.Hash) + if nginxAffinity.Cookie.Hash != "md5" { + t.Errorf("expected md5 as sticky-hash but returned %v", nginxAffinity.Cookie.Hash) } - if nginxAffinity.CookieConfig.Name != "INGRESSCOOKIE" { - t.Errorf("expected route as sticky-name but returned %v", nginxAffinity.CookieConfig.Name) + if nginxAffinity.Cookie.Name != "INGRESSCOOKIE" { + t.Errorf("expected route as sticky-name but returned %v", nginxAffinity.Cookie.Name) } } diff --git a/pkg/ingress/controller/backend_ssl.go b/pkg/ingress/controller/backend_ssl.go index fd88caa23..09affd0ff 100644 --- a/pkg/ingress/controller/backend_ssl.go +++ b/pkg/ingress/controller/backend_ssl.go @@ -25,7 +25,6 @@ import ( apiv1 "k8s.io/api/core/v1" extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/client-go/tools/cache" "k8s.io/ingress-nginx/pkg/ingress" "k8s.io/ingress-nginx/pkg/ingress/annotations/class" @@ -156,18 +155,3 @@ func (ic *NGINXController) checkMissingSecrets() { } } } - -// sslCertTracker holds a store of referenced Secrets in Ingress rules -type sslCertTracker struct { - cache.ThreadSafeStore -} - -func newSSLCertTracker() *sslCertTracker { - return &sslCertTracker{ - cache.NewThreadSafeStore(cache.Indexers{}, cache.Indices{}), - } -} - -func (s *sslCertTracker) DeleteAll(key string) { - s.Delete(key) -} diff --git a/pkg/ingress/controller/controller.go b/pkg/ingress/controller/controller.go index dc1c0d1c0..0c46c85b0 100644 --- a/pkg/ingress/controller/controller.go +++ b/pkg/ingress/controller/controller.go @@ -37,6 +37,7 @@ import ( clientset "k8s.io/client-go/kubernetes" "k8s.io/ingress-nginx/pkg/ingress" + "k8s.io/ingress-nginx/pkg/ingress/annotations" "k8s.io/ingress-nginx/pkg/ingress/annotations/class" "k8s.io/ingress-nginx/pkg/ingress/annotations/healthcheck" "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" @@ -316,7 +317,7 @@ func (n *NGINXController) getStreamServices(configmapName string, proto apiv1.Pr for _, sp := range svc.Spec.Ports { if sp.Name == svcPort { if sp.Protocol == proto { - endps = n.getEndpoints(svc, &sp, proto, &healthcheck.Upstream{}) + endps = n.getEndpoints(svc, &sp, proto, &healthcheck.Config{}) break } } @@ -327,7 +328,7 @@ func (n *NGINXController) getStreamServices(configmapName string, proto apiv1.Pr for _, sp := range svc.Spec.Ports { if sp.Port == int32(targetPort) { if sp.Protocol == proto { - endps = n.getEndpoints(svc, &sp, proto, &healthcheck.Upstream{}) + endps = n.getEndpoints(svc, &sp, proto, &healthcheck.Config{}) break } } @@ -379,7 +380,7 @@ func (n *NGINXController) getDefaultUpstream() *ingress.Backend { } svc := svcObj.(*apiv1.Service) - endps := n.getEndpoints(svc, &svc.Spec.Ports[0], apiv1.ProtocolTCP, &healthcheck.Upstream{}) + endps := n.getEndpoints(svc, &svc.Spec.Ports[0], apiv1.ProtocolTCP, &healthcheck.Config{}) if len(endps) == 0 { glog.Warningf("service %v does not have any active endpoints", svcKey) endps = []ingress.Endpoint{n.DefaultEndpoint()} @@ -398,8 +399,7 @@ func (n *NGINXController) getBackendServers(ingresses []*extensions.Ingress) ([] servers := n.createServers(ingresses, upstreams, du) for _, ing := range ingresses { - affinity := n.annotations.SessionAffinity(ing) - anns := n.annotations.Extract(ing) + anns := n.getIngressAnnotations(ing) for _, rule := range ing.Spec.Rules { host := rule.Host @@ -418,13 +418,11 @@ func (n *NGINXController) getBackendServers(ingresses []*extensions.Ingress) ([] } if server.CertificateAuth.CAFileName == "" { - ca := n.annotations.CertificateAuth(ing) - if ca != nil { - server.CertificateAuth = *ca - // It is possible that no CAFileName is found in the secret - if server.CertificateAuth.CAFileName == "" { - glog.V(3).Infof("secret %v does not contain 'ca.crt', mutual authentication not enabled - ingress rule %v/%v.", server.CertificateAuth.Secret, ing.Namespace, ing.Name) - } + server.CertificateAuth = anns.CertificateAuth + // It is possible that no CAFileName is found in the secret + if server.CertificateAuth.CAFileName == "" { + glog.V(3).Infof("secret %v does not contain 'ca.crt', mutual authentication not enabled - ingress rule %v/%v.", server.CertificateAuth.Secret, ing.Namespace, ing.Name) + } } else { glog.V(3).Infof("server %v already contains a mutual authentication configuration - ingress rule %v/%v", server.Hostname, ing.Namespace, ing.Name) @@ -461,7 +459,19 @@ func (n *NGINXController) getBackendServers(ingresses []*extensions.Ingress) ([] loc.Port = ups.Port loc.Service = ups.Service loc.Ingress = ing - mergeLocationAnnotations(loc, anns) + loc.BasicDigestAuth = anns.BasicDigestAuth + loc.ClientBodyBufferSize = anns.ClientBodyBufferSize + loc.ConfigurationSnippet = anns.ConfigurationSnippet + loc.CorsConfig = anns.CorsConfig + loc.ExternalAuth = anns.ExternalAuth + loc.Proxy = anns.Proxy + loc.RateLimit = anns.RateLimit + loc.Redirect = anns.Redirect + loc.Rewrite = anns.Rewrite + loc.UpstreamVhost = anns.UpstreamVhost + loc.VtsFilterKey = anns.VtsFilterKey + loc.Whitelist = anns.Whitelist + if loc.Redirect.FromToWWW { server.RedirectFromToWWW = true } @@ -472,14 +482,26 @@ func (n *NGINXController) getBackendServers(ingresses []*extensions.Ingress) ([] if addLoc { glog.V(3).Infof("adding location %v in ingress rule %v/%v upstream %v", nginxPath, ing.Namespace, ing.Name, ups.Name) loc := &ingress.Location{ - Path: nginxPath, - Backend: ups.Name, - IsDefBackend: false, - Service: ups.Service, - Port: ups.Port, - Ingress: ing, + Path: nginxPath, + Backend: ups.Name, + IsDefBackend: false, + Service: ups.Service, + Port: ups.Port, + Ingress: ing, + BasicDigestAuth: anns.BasicDigestAuth, + ClientBodyBufferSize: anns.ClientBodyBufferSize, + ConfigurationSnippet: anns.ConfigurationSnippet, + CorsConfig: anns.CorsConfig, + ExternalAuth: anns.ExternalAuth, + Proxy: anns.Proxy, + RateLimit: anns.RateLimit, + Redirect: anns.Redirect, + Rewrite: anns.Rewrite, + UpstreamVhost: anns.UpstreamVhost, + VtsFilterKey: anns.VtsFilterKey, + Whitelist: anns.Whitelist, } - mergeLocationAnnotations(loc, anns) + if loc.Redirect.FromToWWW { server.RedirectFromToWWW = true } @@ -487,12 +509,12 @@ func (n *NGINXController) getBackendServers(ingresses []*extensions.Ingress) ([] } if ups.SessionAffinity.AffinityType == "" { - ups.SessionAffinity.AffinityType = affinity.AffinityType + ups.SessionAffinity.AffinityType = anns.SessionAffinity.Type } - if affinity.AffinityType == "cookie" { - ups.SessionAffinity.CookieSessionAffinity.Name = affinity.CookieConfig.Name - ups.SessionAffinity.CookieSessionAffinity.Hash = affinity.CookieConfig.Hash + if anns.SessionAffinity.Type == "cookie" { + ups.SessionAffinity.CookieSessionAffinity.Name = anns.SessionAffinity.Cookie.Name + ups.SessionAffinity.CookieSessionAffinity.Hash = anns.SessionAffinity.Cookie.Hash locs := ups.SessionAffinity.CookieSessionAffinity.Locations if _, ok := locs[host]; !ok { @@ -519,7 +541,7 @@ func (n *NGINXController) getBackendServers(ingresses []*extensions.Ingress) ([] // check if the location contains endpoints and a custom default backend if location.DefaultBackend != nil { sp := location.DefaultBackend.Spec.Ports[0] - endps := n.getEndpoints(location.DefaultBackend, &sp, apiv1.ProtocolTCP, &healthcheck.Upstream{}) + endps := n.getEndpoints(location.DefaultBackend, &sp, apiv1.ProtocolTCP, &healthcheck.Config{}) if len(endps) > 0 { glog.V(3).Infof("using custom default backend in server %v location %v (service %v/%v)", server.Hostname, location.Path, location.DefaultBackend.Namespace, location.DefaultBackend.Name) @@ -617,10 +639,7 @@ func (n *NGINXController) createUpstreams(data []*extensions.Ingress, du *ingres upstreams[defUpstreamName] = du for _, ing := range data { - secUpstream := n.annotations.SecureUpstream(ing) - hz := n.annotations.HealthCheck(ing) - serviceUpstream := n.annotations.ServiceUpstream(ing) - upstreamHashBy := n.annotations.UpstreamHashBy(ing) + anns := n.getIngressAnnotations(ing) var defBackend string if ing.Spec.Backend != nil { @@ -635,7 +654,7 @@ func (n *NGINXController) createUpstreams(data []*extensions.Ingress, du *ingres // Add the service cluster endpoint as the upstream instead of individual endpoints // if the serviceUpstream annotation is enabled - if serviceUpstream { + if anns.ServiceUpstream { endpoint, err := n.getServiceClusterEndpoint(svcKey, ing.Spec.Backend) if err != nil { glog.Errorf("Failed to get service cluster endpoint for service %s: %v", svcKey, err) @@ -645,7 +664,7 @@ func (n *NGINXController) createUpstreams(data []*extensions.Ingress, du *ingres } if len(upstreams[defBackend].Endpoints) == 0 { - endps, err := n.serviceEndpoints(svcKey, ing.Spec.Backend.ServicePort.String(), hz) + endps, err := n.serviceEndpoints(svcKey, ing.Spec.Backend.ServicePort.String(), &anns.HealthCheck) upstreams[defBackend].Endpoints = append(upstreams[defBackend].Endpoints, endps...) if err != nil { glog.Warningf("error creating upstream %v: %v", defBackend, err) @@ -674,22 +693,22 @@ func (n *NGINXController) createUpstreams(data []*extensions.Ingress, du *ingres upstreams[name].Port = path.Backend.ServicePort if !upstreams[name].Secure { - upstreams[name].Secure = secUpstream.Secure + upstreams[name].Secure = anns.SecureUpstream.Secure } if upstreams[name].SecureCACert.Secret == "" { - upstreams[name].SecureCACert = secUpstream.CACert + upstreams[name].SecureCACert = anns.SecureUpstream.CACert } if upstreams[name].UpstreamHashBy == "" { - upstreams[name].UpstreamHashBy = upstreamHashBy + upstreams[name].UpstreamHashBy = anns.UpstreamHashBy } svcKey := fmt.Sprintf("%v/%v", ing.GetNamespace(), path.Backend.ServiceName) // Add the service cluster endpoint as the upstream instead of individual endpoints // if the serviceUpstream annotation is enabled - if serviceUpstream { + if anns.ServiceUpstream { endpoint, err := n.getServiceClusterEndpoint(svcKey, &path.Backend) if err != nil { glog.Errorf("failed to get service cluster endpoint for service %s: %v", svcKey, err) @@ -699,7 +718,7 @@ func (n *NGINXController) createUpstreams(data []*extensions.Ingress, du *ingres } if len(upstreams[name].Endpoints) == 0 { - endp, err := n.serviceEndpoints(svcKey, path.Backend.ServicePort.String(), hz) + endp, err := n.serviceEndpoints(svcKey, path.Backend.ServicePort.String(), &anns.HealthCheck) if err != nil { glog.Warningf("error obtaining service endpoints: %v", err) continue @@ -759,7 +778,7 @@ func (n *NGINXController) getServiceClusterEndpoint(svcKey string, backend *exte // serviceEndpoints returns the upstream servers (endpoints) associated // to a service. func (n *NGINXController) serviceEndpoints(svcKey, backendPort string, - hz *healthcheck.Upstream) ([]ingress.Endpoint, error) { + hz *healthcheck.Config) ([]ingress.Endpoint, error) { svc, err := n.listers.Service.GetByName(svcKey) var upstreams []ingress.Endpoint @@ -843,7 +862,7 @@ func (n *NGINXController) createServers(data []*extensions.Ingress, aliases := make(map[string]string, len(data)) bdef := n.GetDefaultBackend() - ngxProxy := proxy.Configuration{ + ngxProxy := proxy.Config{ BodySize: bdef.ProxyBodySize, ConnectTimeout: bdef.ProxyConnectTimeout, SendTimeout: bdef.ProxySendTimeout, @@ -884,9 +903,7 @@ func (n *NGINXController) createServers(data []*extensions.Ingress, // initialize all the servers for _, ing := range data { - - // check if ssl passthrough is configured - sslpt := n.annotations.SSLPassthrough(ing) + anns := n.getIngressAnnotations(ing) // default upstream server un := du.Name @@ -930,16 +947,14 @@ func (n *NGINXController) createServers(data []*extensions.Ingress, Service: &apiv1.Service{}, }, }, - SSLPassthrough: sslpt, + SSLPassthrough: anns.SSLPassthrough, } } } // configure default location, alias, and SSL for _, ing := range data { - // setup server-alias based on annotations - aliasAnnotation := n.annotations.Alias(ing) - srvsnippet := n.annotations.ServerSnippet(ing) + anns := n.getIngressAnnotations(ing) for _, rule := range ing.Spec.Rules { host := rule.Host @@ -948,11 +963,11 @@ func (n *NGINXController) createServers(data []*extensions.Ingress, } // setup server aliases - if aliasAnnotation != "" { + if anns.Alias != "" { if servers[host].Alias == "" { - servers[host].Alias = aliasAnnotation - if _, ok := aliases[aliasAnnotation]; !ok { - aliases[aliasAnnotation] = host + servers[host].Alias = anns.Alias + if _, ok := aliases["Alias"]; !ok { + aliases["Alias"] = host } } else { glog.Warningf("ingress %v/%v for host %v contains an Alias but one has already been configured.", @@ -961,14 +976,14 @@ func (n *NGINXController) createServers(data []*extensions.Ingress, } //notifying the user that it has already been configured. - if servers[host].ServerSnippet != "" && srvsnippet != "" { + if servers[host].ServerSnippet != "" && anns.ServerSnippet != "" { glog.Warningf("ingress %v/%v for host %v contains a Server Snippet section that it has already been configured.", ing.Namespace, ing.Name, host) } // only add a server snippet if the server does not have one previously configured - if servers[host].ServerSnippet == "" && srvsnippet != "" { - servers[host].ServerSnippet = srvsnippet + if servers[host].ServerSnippet == "" && anns.ServerSnippet != "" { + servers[host].ServerSnippet = anns.ServerSnippet } // only add a certificate if the server does not have one previously configured @@ -1044,7 +1059,7 @@ func (n *NGINXController) getEndpoints( s *apiv1.Service, servicePort *apiv1.ServicePort, proto apiv1.Protocol, - hz *healthcheck.Upstream) []ingress.Endpoint { + hz *healthcheck.Config) []ingress.Endpoint { upsServers := []ingress.Endpoint{} @@ -1152,6 +1167,7 @@ func (n *NGINXController) isForceReload() bool { return atomic.LoadInt32(&n.forceReload) != 0 } +// SetForceReload sets if the ingress controller should be reloaded or not func (n *NGINXController) SetForceReload(shouldReload bool) { if shouldReload { atomic.StoreInt32(&n.forceReload, 1) @@ -1160,3 +1176,24 @@ func (n *NGINXController) SetForceReload(shouldReload bool) { atomic.StoreInt32(&n.forceReload, 0) } } + +func (n *NGINXController) extractAnnotations(ing *extensions.Ingress) { + anns := n.annotations.Extract(ing) + glog.V(3).Infof("updating annotations information for ingres %v/%v", anns.Namespace, anns.Name) + n.listers.IngressAnnotation.Update(anns) +} + +// getByIngress returns the parsed annotations from an Ingress +func (n *NGINXController) getIngressAnnotations(ing *extensions.Ingress) *annotations.Ingress { + key := fmt.Sprintf("%v/%v", ing.Namespace, ing.Name) + item, exists, err := n.listers.IngressAnnotation.GetByKey(key) + if err != nil { + glog.Errorf("unexpected error getting ingress annotation %v: %v", key, err) + return &annotations.Ingress{} + } + if !exists { + glog.Errorf("ingress annotation %v was not found", key) + return &annotations.Ingress{} + } + return item.(*annotations.Ingress) +} diff --git a/pkg/ingress/controller/listers.go b/pkg/ingress/controller/listers.go index 6ccc6d318..766a19640 100644 --- a/pkg/ingress/controller/listers.go +++ b/pkg/ingress/controller/listers.go @@ -27,6 +27,7 @@ import ( "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/client-go/tools/cache" + cache_client "k8s.io/client-go/tools/cache" "k8s.io/ingress-nginx/pkg/ingress" "k8s.io/ingress-nginx/pkg/ingress/annotations/class" @@ -60,7 +61,7 @@ func (c *cacheController) Run(stopCh chan struct{}) { } } -func (n *NGINXController) createListers(stopCh chan struct{}) *ingress.StoreLister { +func (n *NGINXController) createListers(stopCh chan struct{}) (*ingress.StoreLister, *cacheController) { // from here to the end of the method all the code is just boilerplate // required to watch Ingress, Secrets, ConfigMaps and Endoints. // This is used to detect new content, updates or removals and act accordingly @@ -73,6 +74,7 @@ func (n *NGINXController) createListers(stopCh chan struct{}) *ingress.StoreList return } + n.extractAnnotations(addIng) n.recorder.Eventf(addIng, apiv1.EventTypeNormal, "CREATE", fmt.Sprintf("Ingress %s/%s", addIng.Namespace, addIng.Name)) n.syncQueue.Enqueue(obj) }, @@ -113,6 +115,7 @@ func (n *NGINXController) createListers(stopCh chan struct{}) *ingress.StoreList n.recorder.Eventf(curIng, apiv1.EventTypeNormal, "UPDATE", fmt.Sprintf("Ingress %s/%s", curIng.Namespace, curIng.Name)) } + n.extractAnnotations(curIng) n.syncQueue.Enqueue(cur) }, } @@ -141,7 +144,7 @@ func (n *NGINXController) createListers(stopCh chan struct{}) *ingress.StoreList } } key := fmt.Sprintf("%v/%v", sec.Namespace, sec.Name) - n.sslCertTracker.DeleteAll(key) + n.sslCertTracker.Delete(key) n.syncQueue.Enqueue(key) }, } @@ -196,6 +199,7 @@ func (n *NGINXController) createListers(stopCh chan struct{}) *ingress.StoreList } lister := &ingress.StoreLister{} + lister.IngressAnnotation.Store = cache_client.NewStore(cache_client.DeletionHandlingMetaNamespaceKeyFunc) controller := &cacheController{} @@ -219,7 +223,5 @@ func (n *NGINXController) createListers(stopCh chan struct{}) *ingress.StoreList cache.NewListWatchFromClient(n.cfg.Client.CoreV1().RESTClient(), "services", n.cfg.Namespace, fields.Everything()), &apiv1.Service{}, n.cfg.ResyncPeriod, cache.ResourceEventHandlerFuncs{}) - controller.Run(n.stopCh) - - return lister + return lister, controller } diff --git a/pkg/ingress/controller/nginx.go b/pkg/ingress/controller/nginx.go index 7428c53dc..8b1af612d 100644 --- a/pkg/ingress/controller/nginx.go +++ b/pkg/ingress/controller/nginx.go @@ -43,6 +43,7 @@ import ( "k8s.io/kubernetes/pkg/util/filesystem" "k8s.io/ingress-nginx/pkg/ingress" + "k8s.io/ingress-nginx/pkg/ingress/annotations" "k8s.io/ingress-nginx/pkg/ingress/annotations/class" "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" ngx_config "k8s.io/ingress-nginx/pkg/ingress/controller/config" @@ -50,6 +51,7 @@ import ( ngx_template "k8s.io/ingress-nginx/pkg/ingress/controller/template" "k8s.io/ingress-nginx/pkg/ingress/defaults" "k8s.io/ingress-nginx/pkg/ingress/status" + "k8s.io/ingress-nginx/pkg/ingress/store" ing_net "k8s.io/ingress-nginx/pkg/net" "k8s.io/ingress-nginx/pkg/net/dns" "k8s.io/ingress-nginx/pkg/net/ssl" @@ -102,7 +104,7 @@ func NewNGINXController(config *Configuration) *NGINXController { resolver: h, cfg: config, - sslCertTracker: newSSLCertTracker(), + sslCertTracker: store.NewSSLCertTracker(), syncRateLimiter: flowcontrol.NewTokenBucketRateLimiter(0.3, 1), recorder: eventBroadcaster.NewRecorder(scheme.Scheme, apiv1.EventSource{ @@ -115,11 +117,13 @@ func NewNGINXController(config *Configuration) *NGINXController { fileSystem: filesystem.DefaultFs{}, } + n.listers, n.controllers = n.createListers(n.stopCh) + n.stats = newStatsCollector(config.Namespace, config.IngressClass, n.binary, n.cfg.ListenPorts.Status) n.syncQueue = task.NewTaskQueue(n.syncIngress) - n.listers = n.createListers(n.stopCh) + n.annotations = annotations.NewAnnotationExtractor(n) if config.UpdateStatus { n.syncStatus = status.NewStatusSyncer(status.Config{ @@ -135,7 +139,6 @@ func NewNGINXController(config *Configuration) *NGINXController { } else { glog.Warning("Update of ingress status is disabled (flag --update-status=false was specified)") } - n.annotations = newAnnotationExtractor(n) var onChange func() onChange = func() { @@ -170,9 +173,10 @@ Error loading new template : %v type NGINXController struct { cfg *Configuration - listers *ingress.StoreLister + listers *ingress.StoreLister + controllers *cacheController - annotations annotationExtractor + annotations annotations.Extractor recorder record.EventRecorder @@ -182,7 +186,7 @@ type NGINXController struct { // local store of SSL certificates // (only certificates used in ingress) - sslCertTracker *sslCertTracker + sslCertTracker *store.SSLCertTracker syncRateLimiter flowcontrol.RateLimiter @@ -234,6 +238,8 @@ type NGINXController struct { func (n *NGINXController) Start() { glog.Infof("starting Ingress controller") + n.controllers.Run(n.stopCh) + // initial sync of secrets to avoid unnecessary reloads glog.Info("running initial sync of secrets") for _, obj := range n.listers.Ingress.List() { @@ -425,12 +431,12 @@ func (n *NGINXController) SetConfig(cmap *apiv1.ConfigMap) { n.backendDefaults = c.Backend } -// OnUpdate is called by syncQueue in https://github.com/kubernetes/ingress-nginx/blob/master/pkg/ingress/controller/controller.go#L426 -// periodically to keep the configuration in sync. +// OnUpdate is called periodically by syncQueue to keep the configuration in sync. +// +// 1. converts configmap configuration to custom configuration object +// 2. write the custom template (the complexity depends on the implementation) +// 3. write the configuration file // -// convert configmap to custom configuration object (different in each implementation) -// write the custom template (the complexity depends on the implementation) -// write the configuration file // returning nill implies the backend will be reloaded. // if an error is returned means requeue the update func (n *NGINXController) OnUpdate(ingressCfg ingress.Configuration) error { diff --git a/pkg/ingress/controller/template/template.go b/pkg/ingress/controller/template/template.go index ef640242c..8a8e8463a 100644 --- a/pkg/ingress/controller/template/template.go +++ b/pkg/ingress/controller/template/template.go @@ -354,8 +354,8 @@ func buildProxyPass(host string, b interface{}, loc interface{}) string { } // TODO: Needs Unit Tests -func filterRateLimits(input interface{}) []ratelimit.RateLimit { - ratelimits := []ratelimit.RateLimit{} +func filterRateLimits(input interface{}) []ratelimit.Config { + ratelimits := []ratelimit.Config{} found := sets.String{} servers, ok := input.([]*ingress.Server) diff --git a/pkg/ingress/controller/template/template_test.go b/pkg/ingress/controller/template/template_test.go index 3d0b99991..ada3f1ec3 100644 --- a/pkg/ingress/controller/template/template_test.go +++ b/pkg/ingress/controller/template/template_test.go @@ -114,7 +114,7 @@ func TestBuildLocation(t *testing.T) { for k, tc := range tmplFuncTestcases { loc := &ingress.Location{ Path: tc.Path, - Rewrite: rewrite.Redirect{Target: tc.Target, AddBaseURL: tc.AddBaseURL}, + Rewrite: rewrite.Config{Target: tc.Target, AddBaseURL: tc.AddBaseURL}, } newLoc := buildLocation(loc) @@ -128,7 +128,7 @@ func TestBuildProxyPass(t *testing.T) { for k, tc := range tmplFuncTestcases { loc := &ingress.Location{ Path: tc.Path, - Rewrite: rewrite.Redirect{Target: tc.Target, AddBaseURL: tc.AddBaseURL, BaseURLScheme: tc.BaseURLScheme}, + Rewrite: rewrite.Config{Target: tc.Target, AddBaseURL: tc.AddBaseURL, BaseURLScheme: tc.BaseURLScheme}, Backend: "upstream-name", } @@ -141,7 +141,7 @@ func TestBuildProxyPass(t *testing.T) { func TestBuildAuthResponseHeaders(t *testing.T) { loc := &ingress.Location{ - ExternalAuth: authreq.External{ResponseHeaders: []string{"h1", "H-With-Caps-And-Dashes"}}, + ExternalAuth: authreq.Config{ResponseHeaders: []string{"h1", "H-With-Caps-And-Dashes"}}, } headers := buildAuthResponseHeaders(loc) expected := []string{ diff --git a/pkg/ingress/controller/util.go b/pkg/ingress/controller/util.go index c527ceaeb..0961c61cc 100644 --- a/pkg/ingress/controller/util.go +++ b/pkg/ingress/controller/util.go @@ -21,17 +21,12 @@ import ( "github.com/golang/glog" - "github.com/imdario/mergo" - api "k8s.io/api/core/v1" "k8s.io/kubernetes/pkg/util/sysctl" "k8s.io/ingress-nginx/pkg/ingress" ) -// DeniedKeyName name of the key that contains the reason to deny a location -const DeniedKeyName = "Denied" - // newUpstream creates an upstream without servers. func newUpstream(name string) *ingress.Backend { return &ingress.Backend{ @@ -46,17 +41,6 @@ func newUpstream(name string) *ingress.Backend { } } -func mergeLocationAnnotations(loc *ingress.Location, anns map[string]interface{}) { - if _, ok := anns[DeniedKeyName]; ok { - loc.Denied = anns[DeniedKeyName].(error) - } - delete(anns, DeniedKeyName) - err := mergo.Map(loc, anns) - if err != nil { - glog.Errorf("unexpected error merging extracted annotations in location type: %v", err) - } -} - // sysctlSomaxconn returns the value of net.core.somaxconn, i.e. // maximum number of connections that can be queued for acceptance // http://nginx.org/en/docs/http/ngx_http_core_module.html#listen diff --git a/pkg/ingress/controller/util_test.go b/pkg/ingress/controller/util_test.go index be3e382f6..dc02bf0dc 100644 --- a/pkg/ingress/controller/util_test.go +++ b/pkg/ingress/controller/util_test.go @@ -17,18 +17,7 @@ limitations under the License. package controller import ( - "reflect" "testing" - - "k8s.io/ingress-nginx/pkg/ingress" - "k8s.io/ingress-nginx/pkg/ingress/annotations/auth" - "k8s.io/ingress-nginx/pkg/ingress/annotations/authreq" - "k8s.io/ingress-nginx/pkg/ingress/annotations/cors" - "k8s.io/ingress-nginx/pkg/ingress/annotations/ipwhitelist" - "k8s.io/ingress-nginx/pkg/ingress/annotations/proxy" - "k8s.io/ingress-nginx/pkg/ingress/annotations/ratelimit" - "k8s.io/ingress-nginx/pkg/ingress/annotations/redirect" - "k8s.io/ingress-nginx/pkg/ingress/annotations/rewrite" ) type fakeError struct{} @@ -37,51 +26,6 @@ func (fe *fakeError) Error() string { return "fakeError" } -func TestMergeLocationAnnotations(t *testing.T) { - // initial parameters - loc := ingress.Location{} - annotations := map[string]interface{}{ - "Path": "/checkpath", - "IsDefBackend": true, - "Backend": "foo_backend", - "BasicDigestAuth": auth.BasicDigest{}, - DeniedKeyName: &fakeError{}, - "CorsConfig": cors.CorsConfig{}, - "ExternalAuth": authreq.External{}, - "RateLimit": ratelimit.RateLimit{}, - "Redirect": redirect.Redirect{}, - "Rewrite": rewrite.Redirect{}, - "Whitelist": ipwhitelist.SourceRange{}, - "Proxy": proxy.Configuration{}, - "UsePortInRedirects": true, - } - - // create test table - type fooMergeLocationAnnotationsStruct struct { - fName string - er interface{} - } - fooTests := []fooMergeLocationAnnotationsStruct{} - for name, value := range annotations { - fva := fooMergeLocationAnnotationsStruct{name, value} - fooTests = append(fooTests, fva) - } - - // execute test - mergeLocationAnnotations(&loc, annotations) - - // check result - for _, foo := range fooTests { - fv := reflect.ValueOf(loc).FieldByName(foo.fName).Interface() - if !reflect.DeepEqual(fv, foo.er) { - t.Errorf("Returned %v but expected %v for the field %s", fv, foo.er, foo.fName) - } - } - if _, ok := annotations[DeniedKeyName]; ok { - t.Errorf("%s should be removed after mergeLocationAnnotations", DeniedKeyName) - } -} - func TestIntInSlice(t *testing.T) { fooTests := []struct { i int diff --git a/pkg/ingress/store/main.go b/pkg/ingress/store/main.go index 166fd2ada..299f54c0b 100644 --- a/pkg/ingress/store/main.go +++ b/pkg/ingress/store/main.go @@ -28,6 +28,11 @@ type IngressLister struct { cache.Store } +// IngressAnnotationsLister makes a Store that lists annotations in Ingress rules. +type IngressAnnotationsLister struct { + cache.Store +} + // SecretLister makes a Store that lists Secrets. type SecretLister struct { cache.Store @@ -94,3 +99,15 @@ func (s *EndpointLister) GetServiceEndpoints(svc *apiv1.Service) (*apiv1.Endpoin } return nil, fmt.Errorf("could not find endpoints for service: %v", svc.Name) } + +// SSLCertTracker holds a store of referenced Secrets in Ingress rules +type SSLCertTracker struct { + cache.ThreadSafeStore +} + +// NewSSLCertTracker creates a new SSLCertTracker store +func NewSSLCertTracker() *SSLCertTracker { + return &SSLCertTracker{ + cache.NewThreadSafeStore(cache.Indexers{}, cache.Indices{}), + } +} diff --git a/pkg/ingress/types.go b/pkg/ingress/types.go index 73e53fa64..4622860a5 100644 --- a/pkg/ingress/types.go +++ b/pkg/ingress/types.go @@ -47,11 +47,12 @@ var ( // StoreLister returns the configured stores for ingresses, services, // endpoints, secrets and configmaps. type StoreLister struct { - Ingress store.IngressLister - Service store.ServiceLister - Endpoint store.EndpointLister - Secret store.SecretLister - ConfigMap store.ConfigMapLister + Ingress store.IngressLister + Service store.ServiceLister + Endpoint store.EndpointLister + Secret store.SecretLister + ConfigMap store.ConfigMapLister + IngressAnnotation store.IngressAnnotationsLister } // Configuration holds the definition of all the parts required to describe all @@ -165,7 +166,7 @@ type Server struct { RedirectFromToWWW bool `json:"redirectFromToWWW,omitempty"` // CertificateAuth indicates the this server requires mutual authentication // +optional - CertificateAuth authtls.AuthSSLConfig `json:"certificateAuth"` + CertificateAuth authtls.Config `json:"certificateAuth"` // ServerSnippet returns the snippet of server // +optional @@ -211,28 +212,28 @@ type Location struct { // BasicDigestAuth returns authentication configuration for // an Ingress rule. // +optional - BasicDigestAuth auth.BasicDigest `json:"basicDigestAuth,omitempty"` + BasicDigestAuth auth.Config `json:"basicDigestAuth,omitempty"` // Denied returns an error when this location cannot not be allowed // Requesting a denied location should return HTTP code 403. Denied error `json:"denied,omitempty"` // CorsConfig returns the Cors Configration for the ingress rule // +optional - CorsConfig cors.CorsConfig `json:"corsConfig,omitempty"` + CorsConfig cors.Config `json:"corsConfig,omitempty"` // ExternalAuth indicates the access to this location requires // authentication using an external provider // +optional - ExternalAuth authreq.External `json:"externalAuth,omitempty"` + ExternalAuth authreq.Config `json:"externalAuth,omitempty"` // RateLimit describes a limit in the number of connections per IP // address or connections per second. // The Redirect annotation precedes RateLimit // +optional - RateLimit ratelimit.RateLimit `json:"rateLimit,omitempty"` + RateLimit ratelimit.Config `json:"rateLimit,omitempty"` // Redirect describes a temporal o permanent redirection this location. // +optional - Redirect redirect.Redirect `json:"redirect,omitempty"` + Redirect redirect.Config `json:"redirect,omitempty"` // Rewrite describes the redirection this location. // +optional - Rewrite rewrite.Redirect `json:"rewrite,omitempty"` + Rewrite rewrite.Config `json:"rewrite,omitempty"` // Whitelist indicates only connections from certain client // addresses or networks are allowed. // +optional @@ -240,7 +241,7 @@ type Location struct { // Proxy contains information about timeouts and buffer sizes // to be used in connections against endpoints // +optional - Proxy proxy.Configuration `json:"proxy,omitempty"` + Proxy proxy.Config `json:"proxy,omitempty"` // UsePortInRedirects indicates if redirects must specify the port // +optional UsePortInRedirects bool `json:"usePortInRedirects"` From 73fe95722c0733694244ad2b58fd6d5dff1a8bdb Mon Sep 17 00:00:00 2001 From: Manuel de Brito Fontes Date: Tue, 7 Nov 2017 19:02:12 -0300 Subject: [PATCH 2/6] Rename package pkg to internal --- cmd/nginx/flags.go | 6 +-- cmd/nginx/main.go | 8 +-- {pkg => internal}/file/file.go | 0 {pkg => internal}/file/file_test.go | 0 .../ingress/annotations/alias/main.go | 2 +- .../ingress/annotations/alias/main_test.go | 0 .../ingress/annotations/annotations.go | 52 +++++++++---------- .../ingress/annotations/annotations_test.go | 21 ++------ .../ingress/annotations/auth/main.go | 8 +-- .../ingress/annotations/auth/main_test.go | 0 .../ingress/annotations/authreq/main.go | 4 +- .../ingress/annotations/authreq/main_test.go | 0 .../ingress/annotations/authtls/main.go | 8 +-- .../ingress/annotations/authtls/main_test.go | 0 .../ingress/annotations/class/main.go | 4 +- .../ingress/annotations/class/main_test.go | 0 .../annotations/clientbodybuffersize/main.go | 2 +- .../clientbodybuffersize/main_test.go | 0 .../ingress/annotations/cors/main.go | 2 +- .../ingress/annotations/cors/main_test.go | 0 .../annotations/defaultbackend/main.go | 4 +- .../ingress/annotations/healthcheck/main.go | 4 +- .../annotations/healthcheck/main_test.go | 2 +- .../ingress/annotations/ipwhitelist/main.go | 8 +-- .../annotations/ipwhitelist/main_test.go | 2 +- .../ingress/annotations/parser/main.go | 2 +- .../ingress/annotations/parser/main_test.go | 0 .../annotations/portinredirect/main.go | 4 +- .../annotations/portinredirect/main_test.go | 2 +- .../ingress/annotations/proxy/main.go | 4 +- .../ingress/annotations/proxy/main_test.go | 2 +- .../ingress/annotations/ratelimit/main.go | 6 +-- .../annotations/ratelimit/main_test.go | 2 +- .../ingress/annotations/redirect/redirect.go | 4 +- .../ingress/annotations/rewrite/main.go | 4 +- .../ingress/annotations/rewrite/main_test.go | 2 +- .../annotations/secureupstream/main.go | 4 +- .../annotations/secureupstream/main_test.go | 2 +- .../ingress/annotations/serversnippet/main.go | 2 +- .../annotations/serversnippet/main_test.go | 0 .../annotations/serviceupstream/main.go | 2 +- .../annotations/serviceupstream/main_test.go | 0 .../annotations/sessionaffinity/main.go | 2 +- .../annotations/sessionaffinity/main_test.go | 0 .../ingress/annotations/snippet/main.go | 2 +- .../ingress/annotations/snippet/main_test.go | 0 .../annotations/sslpassthrough/main.go | 4 +- .../annotations/sslpassthrough/main_test.go | 0 .../annotations/upstreamhashby/main.go | 2 +- .../annotations/upstreamhashby/main_test.go | 0 .../ingress/annotations/upstreamvhost/main.go | 2 +- .../ingress/annotations/vtsfilterkey/main.go | 2 +- .../ingress/controller/backend_ssl.go | 8 +-- .../ingress/controller/backend_ssl_test.go | 8 +-- .../ingress/controller/checker.go | 0 .../ingress/controller/checker_test.go | 2 +- .../ingress/controller/config/config.go | 4 +- .../ingress/controller/config/config_test.go | 0 .../ingress/controller/controller.go | 22 ++++---- .../ingress/controller/listers.go | 10 ++-- .../controller/metric/collector/nginx.go | 0 .../controller/metric/collector/process.go | 0 .../controller/metric/collector/scrape.go | 0 .../controller/metric/collector/status.go | 0 .../metric/collector/status_test.go | 0 .../controller/metric/collector/vts.go | 0 .../ingress/controller/metrics.go | 2 +- {pkg => internal}/ingress/controller/nginx.go | 28 +++++----- .../ingress/controller/nginx_test.go | 0 .../ingress/controller/process/nginx.go | 0 .../ingress/controller/process/nginx_test.go | 0 .../ingress/controller/stat_collector.go | 2 +- {pkg => internal}/ingress/controller/tcp.go | 0 .../ingress/controller/template/configmap.go | 4 +- .../controller/template/configmap_test.go | 2 +- .../ingress/controller/template/template.go | 14 ++--- .../controller/template/template_test.go | 8 +-- {pkg => internal}/ingress/controller/util.go | 2 +- .../ingress/controller/util_test.go | 0 {pkg => internal}/ingress/defaults/main.go | 0 {pkg => internal}/ingress/errors/errors.go | 0 .../ingress/errors/errors_test.go | 0 {pkg => internal}/ingress/resolver/main.go | 2 +- {pkg => internal}/ingress/sort_ingress.go | 0 .../ingress/sort_ingress_test.go | 0 {pkg => internal}/ingress/status/status.go | 8 +-- .../ingress/status/status_test.go | 8 +-- {pkg => internal}/ingress/store/main.go | 0 {pkg => internal}/ingress/type_equals_test.go | 0 {pkg => internal}/ingress/types.go | 22 ++++---- {pkg => internal}/ingress/types_equals.go | 0 .../ingress/zz_generated.deepcopy.go | 0 {pkg => internal}/k8s/main.go | 0 {pkg => internal}/k8s/main_test.go | 0 {pkg => internal}/net/dns/dns.go | 0 {pkg => internal}/net/dns/dns_test.go | 0 {pkg => internal}/net/ipnet.go | 0 {pkg => internal}/net/ipnet_test.go | 0 {pkg => internal}/net/net.go | 0 {pkg => internal}/net/net_test.go | 0 {pkg => internal}/net/ssl/ssl.go | 4 +- {pkg => internal}/net/ssl/ssl_test.go | 2 +- {pkg => internal}/task/queue.go | 0 {pkg => internal}/task/queue_test.go | 0 {pkg => internal}/watch/file_watcher.go | 0 {pkg => internal}/watch/file_watcher_test.go | 0 106 files changed, 171 insertions(+), 184 deletions(-) rename {pkg => internal}/file/file.go (100%) rename {pkg => internal}/file/file_test.go (100%) rename {pkg => internal}/ingress/annotations/alias/main.go (94%) rename {pkg => internal}/ingress/annotations/alias/main_test.go (100%) rename {pkg => internal}/ingress/annotations/annotations.go (73%) rename {pkg => internal}/ingress/annotations/annotations_test.go (95%) rename {pkg => internal}/ingress/annotations/auth/main.go (95%) rename {pkg => internal}/ingress/annotations/auth/main_test.go (100%) rename {pkg => internal}/ingress/annotations/authreq/main.go (97%) rename {pkg => internal}/ingress/annotations/authreq/main_test.go (100%) rename {pkg => internal}/ingress/annotations/authtls/main.go (94%) rename {pkg => internal}/ingress/annotations/authtls/main_test.go (100%) rename {pkg => internal}/ingress/annotations/class/main.go (94%) rename {pkg => internal}/ingress/annotations/class/main_test.go (100%) rename {pkg => internal}/ingress/annotations/clientbodybuffersize/main.go (95%) rename {pkg => internal}/ingress/annotations/clientbodybuffersize/main_test.go (100%) rename {pkg => internal}/ingress/annotations/cors/main.go (98%) rename {pkg => internal}/ingress/annotations/cors/main_test.go (100%) rename {pkg => internal}/ingress/annotations/defaultbackend/main.go (92%) rename {pkg => internal}/ingress/annotations/healthcheck/main.go (94%) rename {pkg => internal}/ingress/annotations/healthcheck/main_test.go (97%) rename {pkg => internal}/ingress/annotations/ipwhitelist/main.go (92%) rename {pkg => internal}/ingress/annotations/ipwhitelist/main_test.go (99%) rename {pkg => internal}/ingress/annotations/parser/main.go (98%) rename {pkg => internal}/ingress/annotations/parser/main_test.go (100%) rename {pkg => internal}/ingress/annotations/portinredirect/main.go (92%) rename {pkg => internal}/ingress/annotations/portinredirect/main_test.go (98%) rename {pkg => internal}/ingress/annotations/proxy/main.go (97%) rename {pkg => internal}/ingress/annotations/proxy/main_test.go (98%) rename {pkg => internal}/ingress/annotations/ratelimit/main.go (97%) rename {pkg => internal}/ingress/annotations/ratelimit/main_test.go (98%) rename {pkg => internal}/ingress/annotations/redirect/redirect.go (96%) rename {pkg => internal}/ingress/annotations/rewrite/main.go (96%) rename {pkg => internal}/ingress/annotations/rewrite/main_test.go (98%) rename {pkg => internal}/ingress/annotations/secureupstream/main.go (94%) rename {pkg => internal}/ingress/annotations/secureupstream/main_test.go (98%) rename {pkg => internal}/ingress/annotations/serversnippet/main.go (95%) rename {pkg => internal}/ingress/annotations/serversnippet/main_test.go (100%) rename {pkg => internal}/ingress/annotations/serviceupstream/main.go (94%) rename {pkg => internal}/ingress/annotations/serviceupstream/main_test.go (100%) rename {pkg => internal}/ingress/annotations/sessionaffinity/main.go (98%) rename {pkg => internal}/ingress/annotations/sessionaffinity/main_test.go (100%) rename {pkg => internal}/ingress/annotations/snippet/main.go (95%) rename {pkg => internal}/ingress/annotations/snippet/main_test.go (100%) rename {pkg => internal}/ingress/annotations/sslpassthrough/main.go (90%) rename {pkg => internal}/ingress/annotations/sslpassthrough/main_test.go (100%) rename {pkg => internal}/ingress/annotations/upstreamhashby/main.go (95%) rename {pkg => internal}/ingress/annotations/upstreamhashby/main_test.go (100%) rename {pkg => internal}/ingress/annotations/upstreamvhost/main.go (95%) rename {pkg => internal}/ingress/annotations/vtsfilterkey/main.go (95%) rename {pkg => internal}/ingress/controller/backend_ssl.go (95%) rename {pkg => internal}/ingress/controller/backend_ssl_test.go (98%) rename {pkg => internal}/ingress/controller/checker.go (100%) rename {pkg => internal}/ingress/controller/checker_test.go (97%) rename {pkg => internal}/ingress/controller/config/config.go (99%) rename {pkg => internal}/ingress/controller/config/config_test.go (100%) rename {pkg => internal}/ingress/controller/controller.go (98%) rename {pkg => internal}/ingress/controller/listers.go (95%) rename {pkg => internal}/ingress/controller/metric/collector/nginx.go (100%) rename {pkg => internal}/ingress/controller/metric/collector/process.go (100%) rename {pkg => internal}/ingress/controller/metric/collector/scrape.go (100%) rename {pkg => internal}/ingress/controller/metric/collector/status.go (100%) rename {pkg => internal}/ingress/controller/metric/collector/status_test.go (100%) rename {pkg => internal}/ingress/controller/metric/collector/vts.go (100%) rename {pkg => internal}/ingress/controller/metrics.go (98%) rename {pkg => internal}/ingress/controller/nginx.go (96%) rename {pkg => internal}/ingress/controller/nginx_test.go (100%) rename {pkg => internal}/ingress/controller/process/nginx.go (100%) rename {pkg => internal}/ingress/controller/process/nginx_test.go (100%) rename {pkg => internal}/ingress/controller/stat_collector.go (97%) rename {pkg => internal}/ingress/controller/tcp.go (100%) rename {pkg => internal}/ingress/controller/template/configmap.go (97%) rename {pkg => internal}/ingress/controller/template/configmap_test.go (98%) rename {pkg => internal}/ingress/controller/template/template.go (98%) rename {pkg => internal}/ingress/controller/template/template_test.go (98%) rename {pkg => internal}/ingress/controller/util.go (98%) rename {pkg => internal}/ingress/controller/util_test.go (100%) rename {pkg => internal}/ingress/defaults/main.go (100%) rename {pkg => internal}/ingress/errors/errors.go (100%) rename {pkg => internal}/ingress/errors/errors_test.go (100%) rename {pkg => internal}/ingress/resolver/main.go (97%) rename {pkg => internal}/ingress/sort_ingress.go (100%) rename {pkg => internal}/ingress/sort_ingress_test.go (100%) rename {pkg => internal}/ingress/status/status.go (98%) rename {pkg => internal}/ingress/status/status_test.go (98%) rename {pkg => internal}/ingress/store/main.go (100%) rename {pkg => internal}/ingress/type_equals_test.go (100%) rename {pkg => internal}/ingress/types.go (95%) rename {pkg => internal}/ingress/types_equals.go (100%) rename {pkg => internal}/ingress/zz_generated.deepcopy.go (100%) rename {pkg => internal}/k8s/main.go (100%) rename {pkg => internal}/k8s/main_test.go (100%) rename {pkg => internal}/net/dns/dns.go (100%) rename {pkg => internal}/net/dns/dns_test.go (100%) rename {pkg => internal}/net/ipnet.go (100%) rename {pkg => internal}/net/ipnet_test.go (100%) rename {pkg => internal}/net/net.go (100%) rename {pkg => internal}/net/net_test.go (100%) rename {pkg => internal}/net/ssl/ssl.go (99%) rename {pkg => internal}/net/ssl/ssl_test.go (98%) rename {pkg => internal}/task/queue.go (100%) rename {pkg => internal}/task/queue_test.go (100%) rename {pkg => internal}/watch/file_watcher.go (100%) rename {pkg => internal}/watch/file_watcher_test.go (100%) diff --git a/cmd/nginx/flags.go b/cmd/nginx/flags.go index 1430987b1..608ef5c9a 100644 --- a/cmd/nginx/flags.go +++ b/cmd/nginx/flags.go @@ -27,9 +27,9 @@ import ( apiv1 "k8s.io/api/core/v1" - "k8s.io/ingress-nginx/pkg/ingress/controller" - ngx_config "k8s.io/ingress-nginx/pkg/ingress/controller/config" - ing_net "k8s.io/ingress-nginx/pkg/net" + "k8s.io/ingress-nginx/internal/ingress/controller" + ngx_config "k8s.io/ingress-nginx/internal/ingress/controller/config" + ing_net "k8s.io/ingress-nginx/internal/net" ) const ( diff --git a/cmd/nginx/main.go b/cmd/nginx/main.go index a77418d42..245445653 100644 --- a/cmd/nginx/main.go +++ b/cmd/nginx/main.go @@ -39,10 +39,10 @@ import ( "k8s.io/client-go/tools/clientcmd" clientcmdapi "k8s.io/client-go/tools/clientcmd/api" - "k8s.io/ingress-nginx/pkg/ingress" - "k8s.io/ingress-nginx/pkg/ingress/controller" - "k8s.io/ingress-nginx/pkg/k8s" - "k8s.io/ingress-nginx/pkg/net/ssl" + "k8s.io/ingress-nginx/internal/ingress" + "k8s.io/ingress-nginx/internal/ingress/controller" + "k8s.io/ingress-nginx/internal/k8s" + "k8s.io/ingress-nginx/internal/net/ssl" "k8s.io/ingress-nginx/version" ) diff --git a/pkg/file/file.go b/internal/file/file.go similarity index 100% rename from pkg/file/file.go rename to internal/file/file.go diff --git a/pkg/file/file_test.go b/internal/file/file_test.go similarity index 100% rename from pkg/file/file_test.go rename to internal/file/file_test.go diff --git a/pkg/ingress/annotations/alias/main.go b/internal/ingress/annotations/alias/main.go similarity index 94% rename from pkg/ingress/annotations/alias/main.go rename to internal/ingress/annotations/alias/main.go index cde40e2ba..0194e72af 100644 --- a/pkg/ingress/annotations/alias/main.go +++ b/internal/ingress/annotations/alias/main.go @@ -19,7 +19,7 @@ package alias import ( extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" ) const ( diff --git a/pkg/ingress/annotations/alias/main_test.go b/internal/ingress/annotations/alias/main_test.go similarity index 100% rename from pkg/ingress/annotations/alias/main_test.go rename to internal/ingress/annotations/alias/main_test.go diff --git a/pkg/ingress/annotations/annotations.go b/internal/ingress/annotations/annotations.go similarity index 73% rename from pkg/ingress/annotations/annotations.go rename to internal/ingress/annotations/annotations.go index d4aca392a..ff888cf84 100644 --- a/pkg/ingress/annotations/annotations.go +++ b/internal/ingress/annotations/annotations.go @@ -23,32 +23,32 @@ import ( extensions "k8s.io/api/extensions/v1beta1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/ingress-nginx/pkg/ingress/annotations/alias" - "k8s.io/ingress-nginx/pkg/ingress/annotations/auth" - "k8s.io/ingress-nginx/pkg/ingress/annotations/authreq" - "k8s.io/ingress-nginx/pkg/ingress/annotations/authtls" - "k8s.io/ingress-nginx/pkg/ingress/annotations/clientbodybuffersize" - "k8s.io/ingress-nginx/pkg/ingress/annotations/cors" - "k8s.io/ingress-nginx/pkg/ingress/annotations/defaultbackend" - "k8s.io/ingress-nginx/pkg/ingress/annotations/healthcheck" - "k8s.io/ingress-nginx/pkg/ingress/annotations/ipwhitelist" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" - "k8s.io/ingress-nginx/pkg/ingress/annotations/portinredirect" - "k8s.io/ingress-nginx/pkg/ingress/annotations/proxy" - "k8s.io/ingress-nginx/pkg/ingress/annotations/ratelimit" - "k8s.io/ingress-nginx/pkg/ingress/annotations/redirect" - "k8s.io/ingress-nginx/pkg/ingress/annotations/rewrite" - "k8s.io/ingress-nginx/pkg/ingress/annotations/secureupstream" - "k8s.io/ingress-nginx/pkg/ingress/annotations/serversnippet" - "k8s.io/ingress-nginx/pkg/ingress/annotations/serviceupstream" - "k8s.io/ingress-nginx/pkg/ingress/annotations/sessionaffinity" - "k8s.io/ingress-nginx/pkg/ingress/annotations/snippet" - "k8s.io/ingress-nginx/pkg/ingress/annotations/sslpassthrough" - "k8s.io/ingress-nginx/pkg/ingress/annotations/upstreamhashby" - "k8s.io/ingress-nginx/pkg/ingress/annotations/upstreamvhost" - "k8s.io/ingress-nginx/pkg/ingress/annotations/vtsfilterkey" - "k8s.io/ingress-nginx/pkg/ingress/errors" - "k8s.io/ingress-nginx/pkg/ingress/resolver" + "k8s.io/ingress-nginx/internal/ingress/annotations/alias" + "k8s.io/ingress-nginx/internal/ingress/annotations/auth" + "k8s.io/ingress-nginx/internal/ingress/annotations/authreq" + "k8s.io/ingress-nginx/internal/ingress/annotations/authtls" + "k8s.io/ingress-nginx/internal/ingress/annotations/clientbodybuffersize" + "k8s.io/ingress-nginx/internal/ingress/annotations/cors" + "k8s.io/ingress-nginx/internal/ingress/annotations/defaultbackend" + "k8s.io/ingress-nginx/internal/ingress/annotations/healthcheck" + "k8s.io/ingress-nginx/internal/ingress/annotations/ipwhitelist" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/annotations/portinredirect" + "k8s.io/ingress-nginx/internal/ingress/annotations/proxy" + "k8s.io/ingress-nginx/internal/ingress/annotations/ratelimit" + "k8s.io/ingress-nginx/internal/ingress/annotations/redirect" + "k8s.io/ingress-nginx/internal/ingress/annotations/rewrite" + "k8s.io/ingress-nginx/internal/ingress/annotations/secureupstream" + "k8s.io/ingress-nginx/internal/ingress/annotations/serversnippet" + "k8s.io/ingress-nginx/internal/ingress/annotations/serviceupstream" + "k8s.io/ingress-nginx/internal/ingress/annotations/sessionaffinity" + "k8s.io/ingress-nginx/internal/ingress/annotations/snippet" + "k8s.io/ingress-nginx/internal/ingress/annotations/sslpassthrough" + "k8s.io/ingress-nginx/internal/ingress/annotations/upstreamhashby" + "k8s.io/ingress-nginx/internal/ingress/annotations/upstreamvhost" + "k8s.io/ingress-nginx/internal/ingress/annotations/vtsfilterkey" + "k8s.io/ingress-nginx/internal/ingress/errors" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) // DeniedKeyName name of the key that contains the reason to deny a location diff --git a/pkg/ingress/annotations/annotations_test.go b/internal/ingress/annotations/annotations_test.go similarity index 95% rename from pkg/ingress/annotations/annotations_test.go rename to internal/ingress/annotations/annotations_test.go index 55fde07ae..114be2318 100644 --- a/pkg/ingress/annotations/annotations_test.go +++ b/internal/ingress/annotations/annotations_test.go @@ -24,8 +24,8 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" - "k8s.io/ingress-nginx/pkg/ingress/defaults" - "k8s.io/ingress-nginx/pkg/ingress/resolver" + "k8s.io/ingress-nginx/internal/ingress/defaults" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) const ( @@ -162,9 +162,8 @@ func TestSecureVerifyCACert(t *testing.T) { for _, ann := range anns { ing := buildIngress() ing.SetAnnotations(ann.annotations) - res := ec.Extract(ing).SecureUpstream - - if (res != nil && res.CACert.CAFileName != "") != ann.exists { + su := ec.Extract(ing).SecureUpstream + if (su.CACert.CAFileName != "") != ann.exists { t.Errorf("Expected exists was %v on iteration %v", ann.exists, ann.it) } } @@ -189,10 +188,6 @@ func TestHealthCheck(t *testing.T) { for _, foo := range fooAnns { ing.SetAnnotations(foo.annotations) r := ec.Extract(ing).HealthCheck - if r == nil { - t.Errorf("Returned nil but expected a healthcheck.Upstream") - continue - } if r.FailTimeout != foo.euft { t.Errorf("Returned %d but expected %d for FailTimeout", r.FailTimeout, foo.euft) @@ -273,10 +268,6 @@ func TestAffinitySession(t *testing.T) { ing.SetAnnotations(foo.annotations) r := ec.Extract(ing).SessionAffinity t.Logf("Testing pass %v %v %v", foo.affinitytype, foo.hash, foo.name) - if r == nil { - t.Errorf("Returned nil but expected a SessionAffinity.AffinityConfig") - continue - } if r.Cookie.Hash != foo.hash { t.Errorf("Returned %v but expected %v for Hash", r.Cookie.Hash, foo.hash) @@ -311,10 +302,6 @@ func TestCors(t *testing.T) { ing.SetAnnotations(foo.annotations) r := ec.Extract(ing).CorsConfig t.Logf("Testing pass %v %v %v %v %v", foo.corsenabled, foo.methods, foo.headers, foo.origin, foo.credentials) - if r == nil { - t.Errorf("Returned nil but expected a Cors.CorsConfig") - continue - } if r.CorsEnabled != foo.corsenabled { t.Errorf("Returned %v but expected %v for Cors Enabled", r.CorsEnabled, foo.corsenabled) diff --git a/pkg/ingress/annotations/auth/main.go b/internal/ingress/annotations/auth/main.go similarity index 95% rename from pkg/ingress/annotations/auth/main.go rename to internal/ingress/annotations/auth/main.go index 1b28d81d4..606b225ed 100644 --- a/pkg/ingress/annotations/auth/main.go +++ b/internal/ingress/annotations/auth/main.go @@ -27,10 +27,10 @@ import ( api "k8s.io/api/core/v1" extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/pkg/file" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" - ing_errors "k8s.io/ingress-nginx/pkg/ingress/errors" - "k8s.io/ingress-nginx/pkg/ingress/resolver" + "k8s.io/ingress-nginx/internal/file" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + ing_errors "k8s.io/ingress-nginx/internal/ingress/errors" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) const ( diff --git a/pkg/ingress/annotations/auth/main_test.go b/internal/ingress/annotations/auth/main_test.go similarity index 100% rename from pkg/ingress/annotations/auth/main_test.go rename to internal/ingress/annotations/auth/main_test.go diff --git a/pkg/ingress/annotations/authreq/main.go b/internal/ingress/annotations/authreq/main.go similarity index 97% rename from pkg/ingress/annotations/authreq/main.go rename to internal/ingress/annotations/authreq/main.go index 28e884892..17a997652 100644 --- a/pkg/ingress/annotations/authreq/main.go +++ b/internal/ingress/annotations/authreq/main.go @@ -23,8 +23,8 @@ import ( extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" - ing_errors "k8s.io/ingress-nginx/pkg/ingress/errors" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + ing_errors "k8s.io/ingress-nginx/internal/ingress/errors" ) const ( diff --git a/pkg/ingress/annotations/authreq/main_test.go b/internal/ingress/annotations/authreq/main_test.go similarity index 100% rename from pkg/ingress/annotations/authreq/main_test.go rename to internal/ingress/annotations/authreq/main_test.go diff --git a/pkg/ingress/annotations/authtls/main.go b/internal/ingress/annotations/authtls/main.go similarity index 94% rename from pkg/ingress/annotations/authtls/main.go rename to internal/ingress/annotations/authtls/main.go index 73556bee2..7fb5eac71 100644 --- a/pkg/ingress/annotations/authtls/main.go +++ b/internal/ingress/annotations/authtls/main.go @@ -22,10 +22,10 @@ import ( "regexp" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" - ing_errors "k8s.io/ingress-nginx/pkg/ingress/errors" - "k8s.io/ingress-nginx/pkg/ingress/resolver" - "k8s.io/ingress-nginx/pkg/k8s" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + ing_errors "k8s.io/ingress-nginx/internal/ingress/errors" + "k8s.io/ingress-nginx/internal/ingress/resolver" + "k8s.io/ingress-nginx/internal/k8s" ) const ( diff --git a/pkg/ingress/annotations/authtls/main_test.go b/internal/ingress/annotations/authtls/main_test.go similarity index 100% rename from pkg/ingress/annotations/authtls/main_test.go rename to internal/ingress/annotations/authtls/main_test.go diff --git a/pkg/ingress/annotations/class/main.go b/internal/ingress/annotations/class/main.go similarity index 94% rename from pkg/ingress/annotations/class/main.go rename to internal/ingress/annotations/class/main.go index 1d1d6d0ba..9c0db669b 100644 --- a/pkg/ingress/annotations/class/main.go +++ b/internal/ingress/annotations/class/main.go @@ -20,8 +20,8 @@ import ( "github.com/golang/glog" extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" - "k8s.io/ingress-nginx/pkg/ingress/errors" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/errors" ) const ( diff --git a/pkg/ingress/annotations/class/main_test.go b/internal/ingress/annotations/class/main_test.go similarity index 100% rename from pkg/ingress/annotations/class/main_test.go rename to internal/ingress/annotations/class/main_test.go diff --git a/pkg/ingress/annotations/clientbodybuffersize/main.go b/internal/ingress/annotations/clientbodybuffersize/main.go similarity index 95% rename from pkg/ingress/annotations/clientbodybuffersize/main.go rename to internal/ingress/annotations/clientbodybuffersize/main.go index 08547d1e8..c8abf2701 100644 --- a/pkg/ingress/annotations/clientbodybuffersize/main.go +++ b/internal/ingress/annotations/clientbodybuffersize/main.go @@ -19,7 +19,7 @@ package clientbodybuffersize import ( extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" ) const ( diff --git a/pkg/ingress/annotations/clientbodybuffersize/main_test.go b/internal/ingress/annotations/clientbodybuffersize/main_test.go similarity index 100% rename from pkg/ingress/annotations/clientbodybuffersize/main_test.go rename to internal/ingress/annotations/clientbodybuffersize/main_test.go diff --git a/pkg/ingress/annotations/cors/main.go b/internal/ingress/annotations/cors/main.go similarity index 98% rename from pkg/ingress/annotations/cors/main.go rename to internal/ingress/annotations/cors/main.go index f382606fa..aa03ce035 100644 --- a/pkg/ingress/annotations/cors/main.go +++ b/internal/ingress/annotations/cors/main.go @@ -21,7 +21,7 @@ import ( extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" ) const ( diff --git a/pkg/ingress/annotations/cors/main_test.go b/internal/ingress/annotations/cors/main_test.go similarity index 100% rename from pkg/ingress/annotations/cors/main_test.go rename to internal/ingress/annotations/cors/main_test.go diff --git a/pkg/ingress/annotations/defaultbackend/main.go b/internal/ingress/annotations/defaultbackend/main.go similarity index 92% rename from pkg/ingress/annotations/defaultbackend/main.go rename to internal/ingress/annotations/defaultbackend/main.go index 8fc6f0d4e..fa19a583d 100644 --- a/pkg/ingress/annotations/defaultbackend/main.go +++ b/internal/ingress/annotations/defaultbackend/main.go @@ -22,8 +22,8 @@ import ( "github.com/pkg/errors" extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" - "k8s.io/ingress-nginx/pkg/ingress/resolver" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) const ( diff --git a/pkg/ingress/annotations/healthcheck/main.go b/internal/ingress/annotations/healthcheck/main.go similarity index 94% rename from pkg/ingress/annotations/healthcheck/main.go rename to internal/ingress/annotations/healthcheck/main.go index 8b29838be..ca386a296 100644 --- a/pkg/ingress/annotations/healthcheck/main.go +++ b/internal/ingress/annotations/healthcheck/main.go @@ -19,8 +19,8 @@ package healthcheck import ( extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" - "k8s.io/ingress-nginx/pkg/ingress/resolver" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) const ( diff --git a/pkg/ingress/annotations/healthcheck/main_test.go b/internal/ingress/annotations/healthcheck/main_test.go similarity index 97% rename from pkg/ingress/annotations/healthcheck/main_test.go rename to internal/ingress/annotations/healthcheck/main_test.go index d32dc8de2..31b43eb39 100644 --- a/pkg/ingress/annotations/healthcheck/main_test.go +++ b/internal/ingress/annotations/healthcheck/main_test.go @@ -24,7 +24,7 @@ import ( meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" - "k8s.io/ingress-nginx/pkg/ingress/defaults" + "k8s.io/ingress-nginx/internal/ingress/defaults" ) func buildIngress() *extensions.Ingress { diff --git a/pkg/ingress/annotations/ipwhitelist/main.go b/internal/ingress/annotations/ipwhitelist/main.go similarity index 92% rename from pkg/ingress/annotations/ipwhitelist/main.go rename to internal/ingress/annotations/ipwhitelist/main.go index df2fe522c..2b4cd72aa 100644 --- a/pkg/ingress/annotations/ipwhitelist/main.go +++ b/internal/ingress/annotations/ipwhitelist/main.go @@ -23,11 +23,11 @@ import ( "github.com/pkg/errors" extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/pkg/net" + "k8s.io/ingress-nginx/internal/net" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" - ing_errors "k8s.io/ingress-nginx/pkg/ingress/errors" - "k8s.io/ingress-nginx/pkg/ingress/resolver" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + ing_errors "k8s.io/ingress-nginx/internal/ingress/errors" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) const ( diff --git a/pkg/ingress/annotations/ipwhitelist/main_test.go b/internal/ingress/annotations/ipwhitelist/main_test.go similarity index 99% rename from pkg/ingress/annotations/ipwhitelist/main_test.go rename to internal/ingress/annotations/ipwhitelist/main_test.go index 66899a517..a4e166608 100644 --- a/pkg/ingress/annotations/ipwhitelist/main_test.go +++ b/internal/ingress/annotations/ipwhitelist/main_test.go @@ -24,7 +24,7 @@ import ( meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" - "k8s.io/ingress-nginx/pkg/ingress/defaults" + "k8s.io/ingress-nginx/internal/ingress/defaults" ) func buildIngress() *extensions.Ingress { diff --git a/pkg/ingress/annotations/parser/main.go b/internal/ingress/annotations/parser/main.go similarity index 98% rename from pkg/ingress/annotations/parser/main.go rename to internal/ingress/annotations/parser/main.go index 2ef0a81ea..cbec167a5 100644 --- a/pkg/ingress/annotations/parser/main.go +++ b/internal/ingress/annotations/parser/main.go @@ -21,7 +21,7 @@ import ( extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/pkg/ingress/errors" + "k8s.io/ingress-nginx/internal/ingress/errors" ) // IngressAnnotation has a method to parse annotations located in Ingress diff --git a/pkg/ingress/annotations/parser/main_test.go b/internal/ingress/annotations/parser/main_test.go similarity index 100% rename from pkg/ingress/annotations/parser/main_test.go rename to internal/ingress/annotations/parser/main_test.go diff --git a/pkg/ingress/annotations/portinredirect/main.go b/internal/ingress/annotations/portinredirect/main.go similarity index 92% rename from pkg/ingress/annotations/portinredirect/main.go rename to internal/ingress/annotations/portinredirect/main.go index 90386cc8f..093af7dde 100644 --- a/pkg/ingress/annotations/portinredirect/main.go +++ b/internal/ingress/annotations/portinredirect/main.go @@ -19,8 +19,8 @@ package portinredirect import ( extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" - "k8s.io/ingress-nginx/pkg/ingress/resolver" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) const ( diff --git a/pkg/ingress/annotations/portinredirect/main_test.go b/internal/ingress/annotations/portinredirect/main_test.go similarity index 98% rename from pkg/ingress/annotations/portinredirect/main_test.go rename to internal/ingress/annotations/portinredirect/main_test.go index 802e8b50a..a7454302a 100644 --- a/pkg/ingress/annotations/portinredirect/main_test.go +++ b/internal/ingress/annotations/portinredirect/main_test.go @@ -25,7 +25,7 @@ import ( meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" - "k8s.io/ingress-nginx/pkg/ingress/defaults" + "k8s.io/ingress-nginx/internal/ingress/defaults" ) func buildIngress() *extensions.Ingress { diff --git a/pkg/ingress/annotations/proxy/main.go b/internal/ingress/annotations/proxy/main.go similarity index 97% rename from pkg/ingress/annotations/proxy/main.go rename to internal/ingress/annotations/proxy/main.go index ee8360d97..8dee7ce07 100644 --- a/pkg/ingress/annotations/proxy/main.go +++ b/internal/ingress/annotations/proxy/main.go @@ -19,8 +19,8 @@ package proxy import ( extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" - "k8s.io/ingress-nginx/pkg/ingress/resolver" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) const ( diff --git a/pkg/ingress/annotations/proxy/main_test.go b/internal/ingress/annotations/proxy/main_test.go similarity index 98% rename from pkg/ingress/annotations/proxy/main_test.go rename to internal/ingress/annotations/proxy/main_test.go index 8fa08ed34..749d28206 100644 --- a/pkg/ingress/annotations/proxy/main_test.go +++ b/internal/ingress/annotations/proxy/main_test.go @@ -24,7 +24,7 @@ import ( meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" - "k8s.io/ingress-nginx/pkg/ingress/defaults" + "k8s.io/ingress-nginx/internal/ingress/defaults" ) func buildIngress() *extensions.Ingress { diff --git a/pkg/ingress/annotations/ratelimit/main.go b/internal/ingress/annotations/ratelimit/main.go similarity index 97% rename from pkg/ingress/annotations/ratelimit/main.go rename to internal/ingress/annotations/ratelimit/main.go index 6118e8a04..e2a21f240 100644 --- a/pkg/ingress/annotations/ratelimit/main.go +++ b/internal/ingress/annotations/ratelimit/main.go @@ -24,9 +24,9 @@ import ( extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" - "k8s.io/ingress-nginx/pkg/ingress/resolver" - "k8s.io/ingress-nginx/pkg/net" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/resolver" + "k8s.io/ingress-nginx/internal/net" ) const ( diff --git a/pkg/ingress/annotations/ratelimit/main_test.go b/internal/ingress/annotations/ratelimit/main_test.go similarity index 98% rename from pkg/ingress/annotations/ratelimit/main_test.go rename to internal/ingress/annotations/ratelimit/main_test.go index bf21e30dc..4437bea56 100644 --- a/pkg/ingress/annotations/ratelimit/main_test.go +++ b/internal/ingress/annotations/ratelimit/main_test.go @@ -24,7 +24,7 @@ import ( meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" - "k8s.io/ingress-nginx/pkg/ingress/defaults" + "k8s.io/ingress-nginx/internal/ingress/defaults" ) func buildIngress() *extensions.Ingress { diff --git a/pkg/ingress/annotations/redirect/redirect.go b/internal/ingress/annotations/redirect/redirect.go similarity index 96% rename from pkg/ingress/annotations/redirect/redirect.go rename to internal/ingress/annotations/redirect/redirect.go index d5f46fd4e..6cd90d960 100644 --- a/pkg/ingress/annotations/redirect/redirect.go +++ b/internal/ingress/annotations/redirect/redirect.go @@ -23,8 +23,8 @@ import ( extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" - "k8s.io/ingress-nginx/pkg/ingress/errors" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/errors" ) const ( diff --git a/pkg/ingress/annotations/rewrite/main.go b/internal/ingress/annotations/rewrite/main.go similarity index 96% rename from pkg/ingress/annotations/rewrite/main.go rename to internal/ingress/annotations/rewrite/main.go index d396ec8c2..2b08fe323 100644 --- a/pkg/ingress/annotations/rewrite/main.go +++ b/internal/ingress/annotations/rewrite/main.go @@ -19,8 +19,8 @@ package rewrite import ( extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" - "k8s.io/ingress-nginx/pkg/ingress/resolver" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) const ( diff --git a/pkg/ingress/annotations/rewrite/main_test.go b/internal/ingress/annotations/rewrite/main_test.go similarity index 98% rename from pkg/ingress/annotations/rewrite/main_test.go rename to internal/ingress/annotations/rewrite/main_test.go index 3ad61f6cf..8e62ec49e 100644 --- a/pkg/ingress/annotations/rewrite/main_test.go +++ b/internal/ingress/annotations/rewrite/main_test.go @@ -24,7 +24,7 @@ import ( meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" - "k8s.io/ingress-nginx/pkg/ingress/defaults" + "k8s.io/ingress-nginx/internal/ingress/defaults" ) const ( diff --git a/pkg/ingress/annotations/secureupstream/main.go b/internal/ingress/annotations/secureupstream/main.go similarity index 94% rename from pkg/ingress/annotations/secureupstream/main.go rename to internal/ingress/annotations/secureupstream/main.go index 60b24eb95..95439ba1a 100644 --- a/pkg/ingress/annotations/secureupstream/main.go +++ b/internal/ingress/annotations/secureupstream/main.go @@ -22,8 +22,8 @@ import ( "github.com/pkg/errors" extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" - "k8s.io/ingress-nginx/pkg/ingress/resolver" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) const ( diff --git a/pkg/ingress/annotations/secureupstream/main_test.go b/internal/ingress/annotations/secureupstream/main_test.go similarity index 98% rename from pkg/ingress/annotations/secureupstream/main_test.go rename to internal/ingress/annotations/secureupstream/main_test.go index 35225285e..390b38485 100644 --- a/pkg/ingress/annotations/secureupstream/main_test.go +++ b/internal/ingress/annotations/secureupstream/main_test.go @@ -25,7 +25,7 @@ import ( meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" - "k8s.io/ingress-nginx/pkg/ingress/resolver" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) func buildIngress() *extensions.Ingress { diff --git a/pkg/ingress/annotations/serversnippet/main.go b/internal/ingress/annotations/serversnippet/main.go similarity index 95% rename from pkg/ingress/annotations/serversnippet/main.go rename to internal/ingress/annotations/serversnippet/main.go index a67cae177..969c2eee5 100644 --- a/pkg/ingress/annotations/serversnippet/main.go +++ b/internal/ingress/annotations/serversnippet/main.go @@ -19,7 +19,7 @@ package serversnippet import ( extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" ) const ( diff --git a/pkg/ingress/annotations/serversnippet/main_test.go b/internal/ingress/annotations/serversnippet/main_test.go similarity index 100% rename from pkg/ingress/annotations/serversnippet/main_test.go rename to internal/ingress/annotations/serversnippet/main_test.go diff --git a/pkg/ingress/annotations/serviceupstream/main.go b/internal/ingress/annotations/serviceupstream/main.go similarity index 94% rename from pkg/ingress/annotations/serviceupstream/main.go rename to internal/ingress/annotations/serviceupstream/main.go index 0a21fde5f..a1d9a5a9d 100644 --- a/pkg/ingress/annotations/serviceupstream/main.go +++ b/internal/ingress/annotations/serviceupstream/main.go @@ -18,7 +18,7 @@ package serviceupstream import ( extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" ) const ( diff --git a/pkg/ingress/annotations/serviceupstream/main_test.go b/internal/ingress/annotations/serviceupstream/main_test.go similarity index 100% rename from pkg/ingress/annotations/serviceupstream/main_test.go rename to internal/ingress/annotations/serviceupstream/main_test.go diff --git a/pkg/ingress/annotations/sessionaffinity/main.go b/internal/ingress/annotations/sessionaffinity/main.go similarity index 98% rename from pkg/ingress/annotations/sessionaffinity/main.go rename to internal/ingress/annotations/sessionaffinity/main.go index 87a2e6f28..b32009f55 100644 --- a/pkg/ingress/annotations/sessionaffinity/main.go +++ b/internal/ingress/annotations/sessionaffinity/main.go @@ -23,7 +23,7 @@ import ( extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" ) const ( diff --git a/pkg/ingress/annotations/sessionaffinity/main_test.go b/internal/ingress/annotations/sessionaffinity/main_test.go similarity index 100% rename from pkg/ingress/annotations/sessionaffinity/main_test.go rename to internal/ingress/annotations/sessionaffinity/main_test.go diff --git a/pkg/ingress/annotations/snippet/main.go b/internal/ingress/annotations/snippet/main.go similarity index 95% rename from pkg/ingress/annotations/snippet/main.go rename to internal/ingress/annotations/snippet/main.go index 3e37fb5a6..954c13f6d 100644 --- a/pkg/ingress/annotations/snippet/main.go +++ b/internal/ingress/annotations/snippet/main.go @@ -19,7 +19,7 @@ package snippet import ( extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" ) const ( diff --git a/pkg/ingress/annotations/snippet/main_test.go b/internal/ingress/annotations/snippet/main_test.go similarity index 100% rename from pkg/ingress/annotations/snippet/main_test.go rename to internal/ingress/annotations/snippet/main_test.go diff --git a/pkg/ingress/annotations/sslpassthrough/main.go b/internal/ingress/annotations/sslpassthrough/main.go similarity index 90% rename from pkg/ingress/annotations/sslpassthrough/main.go rename to internal/ingress/annotations/sslpassthrough/main.go index a4fcca83e..c3752f8bd 100644 --- a/pkg/ingress/annotations/sslpassthrough/main.go +++ b/internal/ingress/annotations/sslpassthrough/main.go @@ -19,8 +19,8 @@ package sslpassthrough import ( extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" - ing_errors "k8s.io/ingress-nginx/pkg/ingress/errors" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + ing_errors "k8s.io/ingress-nginx/internal/ingress/errors" ) const ( diff --git a/pkg/ingress/annotations/sslpassthrough/main_test.go b/internal/ingress/annotations/sslpassthrough/main_test.go similarity index 100% rename from pkg/ingress/annotations/sslpassthrough/main_test.go rename to internal/ingress/annotations/sslpassthrough/main_test.go diff --git a/pkg/ingress/annotations/upstreamhashby/main.go b/internal/ingress/annotations/upstreamhashby/main.go similarity index 95% rename from pkg/ingress/annotations/upstreamhashby/main.go rename to internal/ingress/annotations/upstreamhashby/main.go index b4d898000..c29f5cbbb 100644 --- a/pkg/ingress/annotations/upstreamhashby/main.go +++ b/internal/ingress/annotations/upstreamhashby/main.go @@ -19,7 +19,7 @@ package upstreamhashby import ( extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" ) const ( diff --git a/pkg/ingress/annotations/upstreamhashby/main_test.go b/internal/ingress/annotations/upstreamhashby/main_test.go similarity index 100% rename from pkg/ingress/annotations/upstreamhashby/main_test.go rename to internal/ingress/annotations/upstreamhashby/main_test.go diff --git a/pkg/ingress/annotations/upstreamvhost/main.go b/internal/ingress/annotations/upstreamvhost/main.go similarity index 95% rename from pkg/ingress/annotations/upstreamvhost/main.go rename to internal/ingress/annotations/upstreamvhost/main.go index c7af79246..c702d621a 100644 --- a/pkg/ingress/annotations/upstreamvhost/main.go +++ b/internal/ingress/annotations/upstreamvhost/main.go @@ -19,7 +19,7 @@ package upstreamvhost import ( extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" ) const ( diff --git a/pkg/ingress/annotations/vtsfilterkey/main.go b/internal/ingress/annotations/vtsfilterkey/main.go similarity index 95% rename from pkg/ingress/annotations/vtsfilterkey/main.go rename to internal/ingress/annotations/vtsfilterkey/main.go index 04965bbf2..809187fae 100644 --- a/pkg/ingress/annotations/vtsfilterkey/main.go +++ b/internal/ingress/annotations/vtsfilterkey/main.go @@ -19,7 +19,7 @@ package vtsfilterkey import ( extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" ) const ( diff --git a/pkg/ingress/controller/backend_ssl.go b/internal/ingress/controller/backend_ssl.go similarity index 95% rename from pkg/ingress/controller/backend_ssl.go rename to internal/ingress/controller/backend_ssl.go index 09affd0ff..a1e3b4f1e 100644 --- a/pkg/ingress/controller/backend_ssl.go +++ b/internal/ingress/controller/backend_ssl.go @@ -26,10 +26,10 @@ import ( apiv1 "k8s.io/api/core/v1" extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/pkg/ingress" - "k8s.io/ingress-nginx/pkg/ingress/annotations/class" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" - "k8s.io/ingress-nginx/pkg/net/ssl" + "k8s.io/ingress-nginx/internal/ingress" + "k8s.io/ingress-nginx/internal/ingress/annotations/class" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/net/ssl" ) // syncSecret keeps in sync Secrets used by Ingress rules with the files on diff --git a/pkg/ingress/controller/backend_ssl_test.go b/internal/ingress/controller/backend_ssl_test.go similarity index 98% rename from pkg/ingress/controller/backend_ssl_test.go rename to internal/ingress/controller/backend_ssl_test.go index f59cbe8f5..16892da62 100644 --- a/pkg/ingress/controller/backend_ssl_test.go +++ b/internal/ingress/controller/backend_ssl_test.go @@ -28,9 +28,9 @@ import ( cache_client "k8s.io/client-go/tools/cache" "k8s.io/client-go/util/flowcontrol" - "k8s.io/ingress-nginx/pkg/ingress" - "k8s.io/ingress-nginx/pkg/ingress/store" - "k8s.io/ingress-nginx/pkg/task" + "k8s.io/ingress-nginx/internal/ingress" + "k8s.io/ingress-nginx/internal/ingress/store" + "k8s.io/ingress-nginx/internal/task" "k8s.io/kubernetes/pkg/api" ) @@ -110,7 +110,7 @@ func buildGenericControllerForBackendSSL() *NGINXController { Client: buildSimpleClientSetForBackendSSL(), }, listers: buildListers(), - sslCertTracker: newSSLCertTracker(), + sslCertTracker: store.NewSSLCertTracker(), } gc.syncQueue = task.NewTaskQueue(gc.syncIngress) diff --git a/pkg/ingress/controller/checker.go b/internal/ingress/controller/checker.go similarity index 100% rename from pkg/ingress/controller/checker.go rename to internal/ingress/controller/checker.go diff --git a/pkg/ingress/controller/checker_test.go b/internal/ingress/controller/checker_test.go similarity index 97% rename from pkg/ingress/controller/checker_test.go rename to internal/ingress/controller/checker_test.go index 9620547b9..51002a5ea 100644 --- a/pkg/ingress/controller/checker_test.go +++ b/internal/ingress/controller/checker_test.go @@ -27,7 +27,7 @@ import ( "k8s.io/apiserver/pkg/server/healthz" "k8s.io/kubernetes/pkg/util/filesystem" - ngx_config "k8s.io/ingress-nginx/pkg/ingress/controller/config" + ngx_config "k8s.io/ingress-nginx/internal/ingress/controller/config" ) func TestNginxCheck(t *testing.T) { diff --git a/pkg/ingress/controller/config/config.go b/internal/ingress/controller/config/config.go similarity index 99% rename from pkg/ingress/controller/config/config.go rename to internal/ingress/controller/config/config.go index 083eaf3b9..4a0586a07 100644 --- a/pkg/ingress/controller/config/config.go +++ b/internal/ingress/controller/config/config.go @@ -25,8 +25,8 @@ import ( apiv1 "k8s.io/api/core/v1" - "k8s.io/ingress-nginx/pkg/ingress" - "k8s.io/ingress-nginx/pkg/ingress/defaults" + "k8s.io/ingress-nginx/internal/ingress" + "k8s.io/ingress-nginx/internal/ingress/defaults" ) const ( diff --git a/pkg/ingress/controller/config/config_test.go b/internal/ingress/controller/config/config_test.go similarity index 100% rename from pkg/ingress/controller/config/config_test.go rename to internal/ingress/controller/config/config_test.go diff --git a/pkg/ingress/controller/controller.go b/internal/ingress/controller/controller.go similarity index 98% rename from pkg/ingress/controller/controller.go rename to internal/ingress/controller/controller.go index 0c46c85b0..2861f9f91 100644 --- a/pkg/ingress/controller/controller.go +++ b/internal/ingress/controller/controller.go @@ -36,17 +36,17 @@ import ( "k8s.io/apimachinery/pkg/util/sets" clientset "k8s.io/client-go/kubernetes" - "k8s.io/ingress-nginx/pkg/ingress" - "k8s.io/ingress-nginx/pkg/ingress/annotations" - "k8s.io/ingress-nginx/pkg/ingress/annotations/class" - "k8s.io/ingress-nginx/pkg/ingress/annotations/healthcheck" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" - "k8s.io/ingress-nginx/pkg/ingress/annotations/proxy" - ngx_config "k8s.io/ingress-nginx/pkg/ingress/controller/config" - "k8s.io/ingress-nginx/pkg/ingress/defaults" - "k8s.io/ingress-nginx/pkg/ingress/resolver" - "k8s.io/ingress-nginx/pkg/k8s" - "k8s.io/ingress-nginx/pkg/task" + "k8s.io/ingress-nginx/internal/ingress" + "k8s.io/ingress-nginx/internal/ingress/annotations" + "k8s.io/ingress-nginx/internal/ingress/annotations/class" + "k8s.io/ingress-nginx/internal/ingress/annotations/healthcheck" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/annotations/proxy" + ngx_config "k8s.io/ingress-nginx/internal/ingress/controller/config" + "k8s.io/ingress-nginx/internal/ingress/defaults" + "k8s.io/ingress-nginx/internal/ingress/resolver" + "k8s.io/ingress-nginx/internal/k8s" + "k8s.io/ingress-nginx/internal/task" ) const ( diff --git a/pkg/ingress/controller/listers.go b/internal/ingress/controller/listers.go similarity index 95% rename from pkg/ingress/controller/listers.go rename to internal/ingress/controller/listers.go index 766a19640..bdfd5931b 100644 --- a/pkg/ingress/controller/listers.go +++ b/internal/ingress/controller/listers.go @@ -29,9 +29,9 @@ import ( "k8s.io/client-go/tools/cache" cache_client "k8s.io/client-go/tools/cache" - "k8s.io/ingress-nginx/pkg/ingress" - "k8s.io/ingress-nginx/pkg/ingress/annotations/class" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress" + "k8s.io/ingress-nginx/internal/ingress/annotations/class" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" ) type cacheController struct { @@ -62,9 +62,6 @@ func (c *cacheController) Run(stopCh chan struct{}) { } func (n *NGINXController) createListers(stopCh chan struct{}) (*ingress.StoreLister, *cacheController) { - // from here to the end of the method all the code is just boilerplate - // required to watch Ingress, Secrets, ConfigMaps and Endoints. - // This is used to detect new content, updates or removals and act accordingly ingEventHandler := cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { addIng := obj.(*extensions.Ingress) @@ -98,6 +95,7 @@ func (n *NGINXController) createListers(stopCh chan struct{}) (*ingress.StoreLis return } n.recorder.Eventf(delIng, apiv1.EventTypeNormal, "DELETE", fmt.Sprintf("Ingress %s/%s", delIng.Namespace, delIng.Name)) + n.listers.IngressAnnotation.Delete(delIng) n.syncQueue.Enqueue(obj) }, UpdateFunc: func(old, cur interface{}) { diff --git a/pkg/ingress/controller/metric/collector/nginx.go b/internal/ingress/controller/metric/collector/nginx.go similarity index 100% rename from pkg/ingress/controller/metric/collector/nginx.go rename to internal/ingress/controller/metric/collector/nginx.go diff --git a/pkg/ingress/controller/metric/collector/process.go b/internal/ingress/controller/metric/collector/process.go similarity index 100% rename from pkg/ingress/controller/metric/collector/process.go rename to internal/ingress/controller/metric/collector/process.go diff --git a/pkg/ingress/controller/metric/collector/scrape.go b/internal/ingress/controller/metric/collector/scrape.go similarity index 100% rename from pkg/ingress/controller/metric/collector/scrape.go rename to internal/ingress/controller/metric/collector/scrape.go diff --git a/pkg/ingress/controller/metric/collector/status.go b/internal/ingress/controller/metric/collector/status.go similarity index 100% rename from pkg/ingress/controller/metric/collector/status.go rename to internal/ingress/controller/metric/collector/status.go diff --git a/pkg/ingress/controller/metric/collector/status_test.go b/internal/ingress/controller/metric/collector/status_test.go similarity index 100% rename from pkg/ingress/controller/metric/collector/status_test.go rename to internal/ingress/controller/metric/collector/status_test.go diff --git a/pkg/ingress/controller/metric/collector/vts.go b/internal/ingress/controller/metric/collector/vts.go similarity index 100% rename from pkg/ingress/controller/metric/collector/vts.go rename to internal/ingress/controller/metric/collector/vts.go diff --git a/pkg/ingress/controller/metrics.go b/internal/ingress/controller/metrics.go similarity index 98% rename from pkg/ingress/controller/metrics.go rename to internal/ingress/controller/metrics.go index e46223444..9a311563d 100644 --- a/pkg/ingress/controller/metrics.go +++ b/internal/ingress/controller/metrics.go @@ -19,7 +19,7 @@ package controller import ( "github.com/prometheus/client_golang/prometheus" - "k8s.io/ingress-nginx/pkg/ingress" + "k8s.io/ingress-nginx/internal/ingress" ) const ( diff --git a/pkg/ingress/controller/nginx.go b/internal/ingress/controller/nginx.go similarity index 96% rename from pkg/ingress/controller/nginx.go rename to internal/ingress/controller/nginx.go index 8b1af612d..7417e278b 100644 --- a/pkg/ingress/controller/nginx.go +++ b/internal/ingress/controller/nginx.go @@ -42,20 +42,20 @@ import ( "k8s.io/client-go/util/flowcontrol" "k8s.io/kubernetes/pkg/util/filesystem" - "k8s.io/ingress-nginx/pkg/ingress" - "k8s.io/ingress-nginx/pkg/ingress/annotations" - "k8s.io/ingress-nginx/pkg/ingress/annotations/class" - "k8s.io/ingress-nginx/pkg/ingress/annotations/parser" - ngx_config "k8s.io/ingress-nginx/pkg/ingress/controller/config" - "k8s.io/ingress-nginx/pkg/ingress/controller/process" - ngx_template "k8s.io/ingress-nginx/pkg/ingress/controller/template" - "k8s.io/ingress-nginx/pkg/ingress/defaults" - "k8s.io/ingress-nginx/pkg/ingress/status" - "k8s.io/ingress-nginx/pkg/ingress/store" - ing_net "k8s.io/ingress-nginx/pkg/net" - "k8s.io/ingress-nginx/pkg/net/dns" - "k8s.io/ingress-nginx/pkg/net/ssl" - "k8s.io/ingress-nginx/pkg/task" + "k8s.io/ingress-nginx/internal/ingress" + "k8s.io/ingress-nginx/internal/ingress/annotations" + "k8s.io/ingress-nginx/internal/ingress/annotations/class" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + ngx_config "k8s.io/ingress-nginx/internal/ingress/controller/config" + "k8s.io/ingress-nginx/internal/ingress/controller/process" + ngx_template "k8s.io/ingress-nginx/internal/ingress/controller/template" + "k8s.io/ingress-nginx/internal/ingress/defaults" + "k8s.io/ingress-nginx/internal/ingress/status" + "k8s.io/ingress-nginx/internal/ingress/store" + ing_net "k8s.io/ingress-nginx/internal/net" + "k8s.io/ingress-nginx/internal/net/dns" + "k8s.io/ingress-nginx/internal/net/ssl" + "k8s.io/ingress-nginx/internal/task" ) type statusModule string diff --git a/pkg/ingress/controller/nginx_test.go b/internal/ingress/controller/nginx_test.go similarity index 100% rename from pkg/ingress/controller/nginx_test.go rename to internal/ingress/controller/nginx_test.go diff --git a/pkg/ingress/controller/process/nginx.go b/internal/ingress/controller/process/nginx.go similarity index 100% rename from pkg/ingress/controller/process/nginx.go rename to internal/ingress/controller/process/nginx.go diff --git a/pkg/ingress/controller/process/nginx_test.go b/internal/ingress/controller/process/nginx_test.go similarity index 100% rename from pkg/ingress/controller/process/nginx_test.go rename to internal/ingress/controller/process/nginx_test.go diff --git a/pkg/ingress/controller/stat_collector.go b/internal/ingress/controller/stat_collector.go similarity index 97% rename from pkg/ingress/controller/stat_collector.go rename to internal/ingress/controller/stat_collector.go index 2ce19c1fd..ad3434d15 100644 --- a/pkg/ingress/controller/stat_collector.go +++ b/internal/ingress/controller/stat_collector.go @@ -20,7 +20,7 @@ import ( "github.com/golang/glog" "github.com/prometheus/client_golang/prometheus" - "k8s.io/ingress-nginx/pkg/ingress/controller/metric/collector" + "k8s.io/ingress-nginx/internal/ingress/controller/metric/collector" ) const ( diff --git a/pkg/ingress/controller/tcp.go b/internal/ingress/controller/tcp.go similarity index 100% rename from pkg/ingress/controller/tcp.go rename to internal/ingress/controller/tcp.go diff --git a/pkg/ingress/controller/template/configmap.go b/internal/ingress/controller/template/configmap.go similarity index 97% rename from pkg/ingress/controller/template/configmap.go rename to internal/ingress/controller/template/configmap.go index fa8ecbf6c..02d9bddf3 100644 --- a/pkg/ingress/controller/template/configmap.go +++ b/internal/ingress/controller/template/configmap.go @@ -26,8 +26,8 @@ import ( "github.com/mitchellh/mapstructure" - "k8s.io/ingress-nginx/pkg/ingress/controller/config" - ing_net "k8s.io/ingress-nginx/pkg/net" + "k8s.io/ingress-nginx/internal/ingress/controller/config" + ing_net "k8s.io/ingress-nginx/internal/net" ) const ( diff --git a/pkg/ingress/controller/template/configmap_test.go b/internal/ingress/controller/template/configmap_test.go similarity index 98% rename from pkg/ingress/controller/template/configmap_test.go rename to internal/ingress/controller/template/configmap_test.go index a25d828a7..1df9eae3f 100644 --- a/pkg/ingress/controller/template/configmap_test.go +++ b/internal/ingress/controller/template/configmap_test.go @@ -21,7 +21,7 @@ import ( "github.com/kylelemons/godebug/pretty" - "k8s.io/ingress-nginx/pkg/ingress/controller/config" + "k8s.io/ingress-nginx/internal/ingress/controller/config" ) func TestFilterErrors(t *testing.T) { diff --git a/pkg/ingress/controller/template/template.go b/internal/ingress/controller/template/template.go similarity index 98% rename from pkg/ingress/controller/template/template.go rename to internal/ingress/controller/template/template.go index 8a8e8463a..72de61cc2 100644 --- a/pkg/ingress/controller/template/template.go +++ b/internal/ingress/controller/template/template.go @@ -35,11 +35,11 @@ import ( extensions "k8s.io/api/extensions/v1beta1" "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/ingress-nginx/pkg/ingress" - "k8s.io/ingress-nginx/pkg/ingress/annotations/ratelimit" - "k8s.io/ingress-nginx/pkg/ingress/controller/config" - ing_net "k8s.io/ingress-nginx/pkg/net" - "k8s.io/ingress-nginx/pkg/watch" + "k8s.io/ingress-nginx/internal/ingress" + "k8s.io/ingress-nginx/internal/ingress/annotations/ratelimit" + "k8s.io/ingress-nginx/internal/ingress/controller/config" + ing_net "k8s.io/ingress-nginx/internal/net" + "k8s.io/ingress-nginx/internal/watch" ) const ( @@ -115,7 +115,9 @@ func (t *Template) Write(conf config.TemplateConfig) ([]byte, error) { return tmplBuf.Bytes(), nil } - return outCmdBuf.Bytes(), nil + a := make([]byte, outCmdBuf.Len()) + copy(a, outCmdBuf.Bytes()) + return a, nil } var ( diff --git a/pkg/ingress/controller/template/template_test.go b/internal/ingress/controller/template/template_test.go similarity index 98% rename from pkg/ingress/controller/template/template_test.go rename to internal/ingress/controller/template/template_test.go index ada3f1ec3..e147a2e7b 100644 --- a/pkg/ingress/controller/template/template_test.go +++ b/internal/ingress/controller/template/template_test.go @@ -26,10 +26,10 @@ import ( "strings" "testing" - "k8s.io/ingress-nginx/pkg/ingress" - "k8s.io/ingress-nginx/pkg/ingress/annotations/authreq" - "k8s.io/ingress-nginx/pkg/ingress/annotations/rewrite" - "k8s.io/ingress-nginx/pkg/ingress/controller/config" + "k8s.io/ingress-nginx/internal/ingress" + "k8s.io/ingress-nginx/internal/ingress/annotations/authreq" + "k8s.io/ingress-nginx/internal/ingress/annotations/rewrite" + "k8s.io/ingress-nginx/internal/ingress/controller/config" ) var ( diff --git a/pkg/ingress/controller/util.go b/internal/ingress/controller/util.go similarity index 98% rename from pkg/ingress/controller/util.go rename to internal/ingress/controller/util.go index 0961c61cc..a71bb7400 100644 --- a/pkg/ingress/controller/util.go +++ b/internal/ingress/controller/util.go @@ -24,7 +24,7 @@ import ( api "k8s.io/api/core/v1" "k8s.io/kubernetes/pkg/util/sysctl" - "k8s.io/ingress-nginx/pkg/ingress" + "k8s.io/ingress-nginx/internal/ingress" ) // newUpstream creates an upstream without servers. diff --git a/pkg/ingress/controller/util_test.go b/internal/ingress/controller/util_test.go similarity index 100% rename from pkg/ingress/controller/util_test.go rename to internal/ingress/controller/util_test.go diff --git a/pkg/ingress/defaults/main.go b/internal/ingress/defaults/main.go similarity index 100% rename from pkg/ingress/defaults/main.go rename to internal/ingress/defaults/main.go diff --git a/pkg/ingress/errors/errors.go b/internal/ingress/errors/errors.go similarity index 100% rename from pkg/ingress/errors/errors.go rename to internal/ingress/errors/errors.go diff --git a/pkg/ingress/errors/errors_test.go b/internal/ingress/errors/errors_test.go similarity index 100% rename from pkg/ingress/errors/errors_test.go rename to internal/ingress/errors/errors_test.go diff --git a/pkg/ingress/resolver/main.go b/internal/ingress/resolver/main.go similarity index 97% rename from pkg/ingress/resolver/main.go rename to internal/ingress/resolver/main.go index e024df933..61f91518e 100644 --- a/pkg/ingress/resolver/main.go +++ b/internal/ingress/resolver/main.go @@ -19,7 +19,7 @@ package resolver import ( apiv1 "k8s.io/api/core/v1" - "k8s.io/ingress-nginx/pkg/ingress/defaults" + "k8s.io/ingress-nginx/internal/ingress/defaults" ) // DefaultBackend has a method that returns the backend diff --git a/pkg/ingress/sort_ingress.go b/internal/ingress/sort_ingress.go similarity index 100% rename from pkg/ingress/sort_ingress.go rename to internal/ingress/sort_ingress.go diff --git a/pkg/ingress/sort_ingress_test.go b/internal/ingress/sort_ingress_test.go similarity index 100% rename from pkg/ingress/sort_ingress_test.go rename to internal/ingress/sort_ingress_test.go diff --git a/pkg/ingress/status/status.go b/internal/ingress/status/status.go similarity index 98% rename from pkg/ingress/status/status.go rename to internal/ingress/status/status.go index 3c3bb7d51..effdb9f7f 100644 --- a/pkg/ingress/status/status.go +++ b/internal/ingress/status/status.go @@ -40,10 +40,10 @@ import ( "k8s.io/client-go/tools/record" "k8s.io/kubernetes/pkg/kubelet/util/sliceutils" - "k8s.io/ingress-nginx/pkg/ingress/annotations/class" - "k8s.io/ingress-nginx/pkg/ingress/store" - "k8s.io/ingress-nginx/pkg/k8s" - "k8s.io/ingress-nginx/pkg/task" + "k8s.io/ingress-nginx/internal/ingress/annotations/class" + "k8s.io/ingress-nginx/internal/ingress/store" + "k8s.io/ingress-nginx/internal/k8s" + "k8s.io/ingress-nginx/internal/task" ) const ( diff --git a/pkg/ingress/status/status_test.go b/internal/ingress/status/status_test.go similarity index 98% rename from pkg/ingress/status/status_test.go rename to internal/ingress/status/status_test.go index f997052b1..97c0b5033 100644 --- a/pkg/ingress/status/status_test.go +++ b/internal/ingress/status/status_test.go @@ -28,10 +28,10 @@ import ( "k8s.io/client-go/tools/cache" "k8s.io/kubernetes/pkg/api" - "k8s.io/ingress-nginx/pkg/ingress/annotations/class" - "k8s.io/ingress-nginx/pkg/ingress/store" - "k8s.io/ingress-nginx/pkg/k8s" - "k8s.io/ingress-nginx/pkg/task" + "k8s.io/ingress-nginx/internal/ingress/annotations/class" + "k8s.io/ingress-nginx/internal/ingress/store" + "k8s.io/ingress-nginx/internal/k8s" + "k8s.io/ingress-nginx/internal/task" ) func buildLoadBalancerIngressByIP() []apiv1.LoadBalancerIngress { diff --git a/pkg/ingress/store/main.go b/internal/ingress/store/main.go similarity index 100% rename from pkg/ingress/store/main.go rename to internal/ingress/store/main.go diff --git a/pkg/ingress/type_equals_test.go b/internal/ingress/type_equals_test.go similarity index 100% rename from pkg/ingress/type_equals_test.go rename to internal/ingress/type_equals_test.go diff --git a/pkg/ingress/types.go b/internal/ingress/types.go similarity index 95% rename from pkg/ingress/types.go rename to internal/ingress/types.go index 4622860a5..d9da68b2f 100644 --- a/pkg/ingress/types.go +++ b/internal/ingress/types.go @@ -23,17 +23,17 @@ import ( extensions "k8s.io/api/extensions/v1beta1" "k8s.io/apimachinery/pkg/util/intstr" - "k8s.io/ingress-nginx/pkg/ingress/annotations/auth" - "k8s.io/ingress-nginx/pkg/ingress/annotations/authreq" - "k8s.io/ingress-nginx/pkg/ingress/annotations/authtls" - "k8s.io/ingress-nginx/pkg/ingress/annotations/cors" - "k8s.io/ingress-nginx/pkg/ingress/annotations/ipwhitelist" - "k8s.io/ingress-nginx/pkg/ingress/annotations/proxy" - "k8s.io/ingress-nginx/pkg/ingress/annotations/ratelimit" - "k8s.io/ingress-nginx/pkg/ingress/annotations/redirect" - "k8s.io/ingress-nginx/pkg/ingress/annotations/rewrite" - "k8s.io/ingress-nginx/pkg/ingress/resolver" - "k8s.io/ingress-nginx/pkg/ingress/store" + "k8s.io/ingress-nginx/internal/ingress/annotations/auth" + "k8s.io/ingress-nginx/internal/ingress/annotations/authreq" + "k8s.io/ingress-nginx/internal/ingress/annotations/authtls" + "k8s.io/ingress-nginx/internal/ingress/annotations/cors" + "k8s.io/ingress-nginx/internal/ingress/annotations/ipwhitelist" + "k8s.io/ingress-nginx/internal/ingress/annotations/proxy" + "k8s.io/ingress-nginx/internal/ingress/annotations/ratelimit" + "k8s.io/ingress-nginx/internal/ingress/annotations/redirect" + "k8s.io/ingress-nginx/internal/ingress/annotations/rewrite" + "k8s.io/ingress-nginx/internal/ingress/resolver" + "k8s.io/ingress-nginx/internal/ingress/store" ) var ( diff --git a/pkg/ingress/types_equals.go b/internal/ingress/types_equals.go similarity index 100% rename from pkg/ingress/types_equals.go rename to internal/ingress/types_equals.go diff --git a/pkg/ingress/zz_generated.deepcopy.go b/internal/ingress/zz_generated.deepcopy.go similarity index 100% rename from pkg/ingress/zz_generated.deepcopy.go rename to internal/ingress/zz_generated.deepcopy.go diff --git a/pkg/k8s/main.go b/internal/k8s/main.go similarity index 100% rename from pkg/k8s/main.go rename to internal/k8s/main.go diff --git a/pkg/k8s/main_test.go b/internal/k8s/main_test.go similarity index 100% rename from pkg/k8s/main_test.go rename to internal/k8s/main_test.go diff --git a/pkg/net/dns/dns.go b/internal/net/dns/dns.go similarity index 100% rename from pkg/net/dns/dns.go rename to internal/net/dns/dns.go diff --git a/pkg/net/dns/dns_test.go b/internal/net/dns/dns_test.go similarity index 100% rename from pkg/net/dns/dns_test.go rename to internal/net/dns/dns_test.go diff --git a/pkg/net/ipnet.go b/internal/net/ipnet.go similarity index 100% rename from pkg/net/ipnet.go rename to internal/net/ipnet.go diff --git a/pkg/net/ipnet_test.go b/internal/net/ipnet_test.go similarity index 100% rename from pkg/net/ipnet_test.go rename to internal/net/ipnet_test.go diff --git a/pkg/net/net.go b/internal/net/net.go similarity index 100% rename from pkg/net/net.go rename to internal/net/net.go diff --git a/pkg/net/net_test.go b/internal/net/net_test.go similarity index 100% rename from pkg/net/net_test.go rename to internal/net/net_test.go diff --git a/pkg/net/ssl/ssl.go b/internal/net/ssl/ssl.go similarity index 99% rename from pkg/net/ssl/ssl.go rename to internal/net/ssl/ssl.go index 591b4bcb6..0b9b791ca 100644 --- a/pkg/net/ssl/ssl.go +++ b/internal/net/ssl/ssl.go @@ -38,8 +38,8 @@ import ( "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/ingress-nginx/pkg/file" - "k8s.io/ingress-nginx/pkg/ingress" + "k8s.io/ingress-nginx/internal/file" + "k8s.io/ingress-nginx/internal/ingress" ) var ( diff --git a/pkg/net/ssl/ssl_test.go b/internal/net/ssl/ssl_test.go similarity index 98% rename from pkg/net/ssl/ssl_test.go rename to internal/net/ssl/ssl_test.go index 477444ec9..95767eeca 100644 --- a/pkg/net/ssl/ssl_test.go +++ b/internal/net/ssl/ssl_test.go @@ -26,7 +26,7 @@ import ( certutil "k8s.io/client-go/util/cert" "k8s.io/client-go/util/cert/triple" - "k8s.io/ingress-nginx/pkg/ingress" + "k8s.io/ingress-nginx/internal/ingress" ) // generateRSACerts generates a self signed certificate using a self generated ca diff --git a/pkg/task/queue.go b/internal/task/queue.go similarity index 100% rename from pkg/task/queue.go rename to internal/task/queue.go diff --git a/pkg/task/queue_test.go b/internal/task/queue_test.go similarity index 100% rename from pkg/task/queue_test.go rename to internal/task/queue_test.go diff --git a/pkg/watch/file_watcher.go b/internal/watch/file_watcher.go similarity index 100% rename from pkg/watch/file_watcher.go rename to internal/watch/file_watcher.go diff --git a/pkg/watch/file_watcher_test.go b/internal/watch/file_watcher_test.go similarity index 100% rename from pkg/watch/file_watcher_test.go rename to internal/watch/file_watcher_test.go From 97577c07a57b2c9160d927825fbb01cb2912a46b Mon Sep 17 00:00:00 2001 From: Manuel de Brito Fontes Date: Tue, 7 Nov 2017 21:37:35 -0300 Subject: [PATCH 3/6] Include a buffer pool to improve memory usage --- .../controller/template/buffer_pool.go | 51 +++++++++++++++++++ .../ingress/controller/template/template.go | 21 +++----- 2 files changed, 58 insertions(+), 14 deletions(-) create mode 100644 internal/ingress/controller/template/buffer_pool.go diff --git a/internal/ingress/controller/template/buffer_pool.go b/internal/ingress/controller/template/buffer_pool.go new file mode 100644 index 000000000..e0a1f287c --- /dev/null +++ b/internal/ingress/controller/template/buffer_pool.go @@ -0,0 +1,51 @@ +/* +Copyright 2017 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package template + +import ( + "bytes" + "sync" +) + +// BufferPool defines a Pool of Buffers +type BufferPool struct { + sync.Pool +} + +// NewBufferPool creates a new BufferPool with a custom buffer size +func NewBufferPool(s int) *BufferPool { + return &BufferPool{ + Pool: sync.Pool{ + New: func() interface{} { + b := bytes.NewBuffer(make([]byte, s)) + b.Reset() + return b + }, + }, + } +} + +// Get returns a Buffer from the pool +func (bp *BufferPool) Get() *bytes.Buffer { + return bp.Pool.Get().(*bytes.Buffer) +} + +// Put resets ans returns a Buffer to the pool +func (bp *BufferPool) Put(b *bytes.Buffer) { + b.Reset() + bp.Pool.Put(b) +} diff --git a/internal/ingress/controller/template/template.go b/internal/ingress/controller/template/template.go index 72de61cc2..078a05a0e 100644 --- a/internal/ingress/controller/template/template.go +++ b/internal/ingress/controller/template/template.go @@ -17,7 +17,6 @@ limitations under the License. package template import ( - "bytes" "encoding/base64" "encoding/json" "fmt" @@ -52,7 +51,7 @@ const ( type Template struct { tmpl *text_template.Template fw watch.FileWatcher - s int + bp *BufferPool } //NewTemplate returns a new Template instance or an @@ -70,7 +69,7 @@ func NewTemplate(file string, onChange func()) (*Template, error) { return &Template{ tmpl: tmpl, fw: fw, - s: defBufferSize, + bp: NewBufferPool(defBufferSize), }, nil } @@ -82,15 +81,11 @@ func (t *Template) Close() { // 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) { - tmplBuf := bytes.NewBuffer(make([]byte, 0, t.s)) - outCmdBuf := bytes.NewBuffer(make([]byte, 0, t.s)) + tmplBuf := t.bp.Get() + defer t.bp.Put(tmplBuf) - defer func() { - if t.s < tmplBuf.Cap() { - glog.V(2).Infof("adjusting template buffer size from %v to %v", t.s, tmplBuf.Cap()) - t.s = tmplBuf.Cap() - } - }() + outCmdBuf := t.bp.Get() + defer t.bp.Put(outCmdBuf) if glog.V(3) { b, err := json.Marshal(conf) @@ -115,9 +110,7 @@ func (t *Template) Write(conf config.TemplateConfig) ([]byte, error) { return tmplBuf.Bytes(), nil } - a := make([]byte, outCmdBuf.Len()) - copy(a, outCmdBuf.Bytes()) - return a, nil + return outCmdBuf.Bytes(), nil } var ( From 8f1ff15a6e2c3ec855a3a60a285bd3ddeef9890c Mon Sep 17 00:00:00 2001 From: Manuel de Brito Fontes Date: Wed, 8 Nov 2017 17:58:57 -0300 Subject: [PATCH 4/6] Add prefix nginx to annotations --- cmd/nginx/flags.go | 3 + internal/ingress/annotations/alias/main.go | 12 ++-- .../ingress/annotations/alias/main_test.go | 5 +- internal/ingress/annotations/annotations.go | 39 +++++-------- .../ingress/annotations/annotations_test.go | 29 +++++----- internal/ingress/annotations/auth/main.go | 22 +++----- .../ingress/annotations/auth/main_test.go | 18 +++--- internal/ingress/annotations/authreq/main.go | 24 +++----- .../ingress/annotations/authreq/main_test.go | 17 +++--- internal/ingress/annotations/authtls/main.go | 23 +++----- internal/ingress/annotations/class/main.go | 9 +-- .../annotations/clientbodybuffersize/main.go | 14 ++--- .../clientbodybuffersize/main_test.go | 4 +- internal/ingress/annotations/cors/main.go | 23 ++++---- .../ingress/annotations/cors/main_test.go | 13 +++-- .../annotations/defaultbackend/main.go | 14 ++--- .../ingress/annotations/healthcheck/main.go | 19 +++---- .../annotations/healthcheck/main_test.go | 4 +- .../ingress/annotations/ipwhitelist/main.go | 14 ++--- .../annotations/ipwhitelist/main_test.go | 30 +++++----- internal/ingress/annotations/parser/main.go | 22 +++++--- .../ingress/annotations/parser/main_test.go | 32 ++++++----- .../annotations/portinredirect/main.go | 14 ++--- .../annotations/portinredirect/main_test.go | 6 +- internal/ingress/annotations/proxy/main.go | 41 +++++--------- .../ingress/annotations/proxy/main_test.go | 18 +++--- .../ingress/annotations/ratelimit/main.go | 27 ++++----- .../annotations/ratelimit/main_test.go | 18 +++--- .../ingress/annotations/redirect/redirect.go | 21 +++---- internal/ingress/annotations/rewrite/main.go | 32 ++++------- .../ingress/annotations/rewrite/main_test.go | 24 ++++---- .../annotations/secureupstream/main.go | 19 ++----- .../annotations/secureupstream/main_test.go | 13 +++-- .../ingress/annotations/serversnippet/main.go | 12 ++-- .../annotations/serversnippet/main_test.go | 5 +- .../annotations/serviceupstream/main.go | 13 ++--- .../annotations/serviceupstream/main_test.go | 11 ++-- .../annotations/sessionaffinity/main.go | 27 +++++---- .../annotations/sessionaffinity/main_test.go | 10 ++-- internal/ingress/annotations/snippet/main.go | 12 ++-- .../ingress/annotations/snippet/main_test.go | 5 +- .../annotations/sslpassthrough/main.go | 12 ++-- .../annotations/sslpassthrough/main_test.go | 9 +-- .../annotations/upstreamhashby/main.go | 12 ++-- .../annotations/upstreamhashby/main_test.go | 5 +- .../ingress/annotations/upstreamvhost/main.go | 12 ++-- .../ingress/annotations/vtsfilterkey/main.go | 12 ++-- internal/ingress/controller/backend_ssl.go | 4 +- internal/ingress/controller/controller.go | 9 ++- internal/ingress/controller/listers.go | 2 +- internal/ingress/controller/nginx.go | 2 +- .../ingress/controller/template/template.go | 6 +- internal/ingress/resolver/main.go | 27 ++++----- internal/ingress/resolver/mock.go | 56 +++++++++++++++++++ 54 files changed, 445 insertions(+), 441 deletions(-) create mode 100644 internal/ingress/resolver/mock.go diff --git a/cmd/nginx/flags.go b/cmd/nginx/flags.go index 608ef5c9a..2029f4d78 100644 --- a/cmd/nginx/flags.go +++ b/cmd/nginx/flags.go @@ -122,6 +122,8 @@ func parseFlags() (bool, *controller.Configuration, error) { sslProxyPort = flags.Int("ssl-passtrough-proxy-port", 442, `Default port to use internally for SSL when SSL Passthgough is enabled`) defServerPort = flags.Int("default-server-port", 8181, `Default port to use for exposing the default server (catch all)`) healthzPort = flags.Int("healthz-port", 10254, "port for healthz endpoint.") + + annotationsPrefix = flags.String("annotations-prefix", "nginx.ingress.kubernetes.io", `Prefix of the ingress annotations.`) ) flag.Set("logtostderr", "true") @@ -177,6 +179,7 @@ func parseFlags() (bool, *controller.Configuration, error) { } config := &controller.Configuration{ + AnnotationsPrefix: *annotationsPrefix, APIServerHost: *apiserverHost, KubeConfigFile: *kubeConfigFile, UpdateStatus: *updateStatus, diff --git a/internal/ingress/annotations/alias/main.go b/internal/ingress/annotations/alias/main.go index 0194e72af..2fb81b2a4 100644 --- a/internal/ingress/annotations/alias/main.go +++ b/internal/ingress/annotations/alias/main.go @@ -20,22 +20,20 @@ import ( extensions "k8s.io/api/extensions/v1beta1" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" -) - -const ( - annotation = "ingress.kubernetes.io/server-alias" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) type alias struct { + r resolver.Resolver } // NewParser creates a new Alias annotation parser -func NewParser() parser.IngressAnnotation { - return alias{} +func NewParser(r resolver.Resolver) parser.IngressAnnotation { + return alias{r} } // Parse parses the annotations contained in the ingress rule // used to add an alias to the provided hosts func (a alias) Parse(ing *extensions.Ingress) (interface{}, error) { - return parser.GetStringAnnotation(annotation, ing) + return parser.GetStringAnnotation("server-alias", ing, a.r) } diff --git a/internal/ingress/annotations/alias/main_test.go b/internal/ingress/annotations/alias/main_test.go index de4fe17f5..579ed83f4 100644 --- a/internal/ingress/annotations/alias/main_test.go +++ b/internal/ingress/annotations/alias/main_test.go @@ -22,10 +22,13 @@ import ( api "k8s.io/api/core/v1" extensions "k8s.io/api/extensions/v1beta1" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const annotation = "nginx/server-alias" + func TestParse(t *testing.T) { - ap := NewParser() + ap := NewParser(&resolver.Mock{}) if ap == nil { t.Fatalf("expected a parser.IngressAnnotation but returned nil") } diff --git a/internal/ingress/annotations/annotations.go b/internal/ingress/annotations/annotations.go index ff888cf84..a12c2cc44 100644 --- a/internal/ingress/annotations/annotations.go +++ b/internal/ingress/annotations/annotations.go @@ -54,13 +54,6 @@ import ( // DeniedKeyName name of the key that contains the reason to deny a location const DeniedKeyName = "Denied" -type config interface { - resolver.AuthCertificate - resolver.DefaultBackend - resolver.Secret - resolver.Service -} - // Ingress defines the valid annotations present in one NGINX Ingress rule type Ingress struct { metav1.ObjectMeta @@ -91,37 +84,35 @@ type Ingress struct { // Extractor defines the annotation parsers to be used in the extraction of annotations type Extractor struct { - secretResolver resolver.Secret - annotations map[string]parser.IngressAnnotation + annotations map[string]parser.IngressAnnotation } // NewAnnotationExtractor creates a new annotations extractor -func NewAnnotationExtractor(cfg config) Extractor { +func NewAnnotationExtractor(cfg resolver.Resolver) Extractor { return Extractor{ - cfg, map[string]parser.IngressAnnotation{ - "Alias": alias.NewParser(), + "Alias": alias.NewParser(cfg), "BasicDigestAuth": auth.NewParser(auth.AuthDirectory, cfg), "CertificateAuth": authtls.NewParser(cfg), - "ClientBodyBufferSize": clientbodybuffersize.NewParser(), - "ConfigurationSnippet": snippet.NewParser(), - "CorsConfig": cors.NewParser(), + "ClientBodyBufferSize": clientbodybuffersize.NewParser(cfg), + "ConfigurationSnippet": snippet.NewParser(cfg), + "CorsConfig": cors.NewParser(cfg), "DefaultBackend": defaultbackend.NewParser(cfg), - "ExternalAuth": authreq.NewParser(), + "ExternalAuth": authreq.NewParser(cfg), "HealthCheck": healthcheck.NewParser(cfg), "Proxy": proxy.NewParser(cfg), "RateLimit": ratelimit.NewParser(cfg), - "Redirect": redirect.NewParser(), + "Redirect": redirect.NewParser(cfg), "Rewrite": rewrite.NewParser(cfg), "SecureUpstream": secureupstream.NewParser(cfg), - "ServerSnippet": serversnippet.NewParser(), - "ServiceUpstream": serviceupstream.NewParser(), - "SessionAffinity": sessionaffinity.NewParser(), - "SSLPassthrough": sslpassthrough.NewParser(), + "ServerSnippet": serversnippet.NewParser(cfg), + "ServiceUpstream": serviceupstream.NewParser(cfg), + "SessionAffinity": sessionaffinity.NewParser(cfg), + "SSLPassthrough": sslpassthrough.NewParser(cfg), "UsePortInRedirects": portinredirect.NewParser(cfg), - "UpstreamHashBy": upstreamhashby.NewParser(), - "UpstreamVhost": upstreamvhost.NewParser(), - "VtsFilterKey": vtsfilterkey.NewParser(), + "UpstreamHashBy": upstreamhashby.NewParser(cfg), + "UpstreamVhost": upstreamvhost.NewParser(cfg), + "VtsFilterKey": vtsfilterkey.NewParser(cfg), "Whitelist": ipwhitelist.NewParser(cfg), }, } diff --git a/internal/ingress/annotations/annotations_test.go b/internal/ingress/annotations/annotations_test.go index 114be2318..fd086d43d 100644 --- a/internal/ingress/annotations/annotations_test.go +++ b/internal/ingress/annotations/annotations_test.go @@ -29,25 +29,26 @@ import ( ) const ( - annotationSecureUpstream = "ingress.kubernetes.io/secure-backends" - annotationSecureVerifyCACert = "ingress.kubernetes.io/secure-verify-ca-secret" - annotationUpsMaxFails = "ingress.kubernetes.io/upstream-max-fails" - annotationUpsFailTimeout = "ingress.kubernetes.io/upstream-fail-timeout" - annotationPassthrough = "ingress.kubernetes.io/ssl-passthrough" - annotationAffinityType = "ingress.kubernetes.io/affinity" - annotationCorsEnabled = "ingress.kubernetes.io/enable-cors" - annotationCorsAllowOrigin = "ingress.kubernetes.io/cors-allow-origin" - annotationCorsAllowMethods = "ingress.kubernetes.io/cors-allow-methods" - annotationCorsAllowHeaders = "ingress.kubernetes.io/cors-allow-headers" - annotationCorsAllowCredentials = "ingress.kubernetes.io/cors-allow-credentials" + annotationSecureUpstream = "nginx/secure-backends" + annotationSecureVerifyCACert = "nginx/secure-verify-ca-secret" + annotationUpsMaxFails = "nginx/upstream-max-fails" + annotationUpsFailTimeout = "nginx/upstream-fail-timeout" + annotationPassthrough = "nginx/ssl-passthrough" + annotationAffinityType = "nginx/affinity" + annotationCorsEnabled = "nginx/enable-cors" + annotationCorsAllowOrigin = "nginx/cors-allow-origin" + annotationCorsAllowMethods = "nginx/cors-allow-methods" + annotationCorsAllowHeaders = "nginx/cors-allow-headers" + annotationCorsAllowCredentials = "nginx/cors-allow-credentials" defaultCorsMethods = "GET, PUT, POST, DELETE, PATCH, OPTIONS" defaultCorsHeaders = "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization" - annotationAffinityCookieName = "ingress.kubernetes.io/session-cookie-name" - annotationAffinityCookieHash = "ingress.kubernetes.io/session-cookie-hash" - annotationUpstreamHashBy = "ingress.kubernetes.io/upstream-hash-by" + annotationAffinityCookieName = "nginx/session-cookie-name" + annotationAffinityCookieHash = "nginx/session-cookie-hash" + annotationUpstreamHashBy = "nginx/upstream-hash-by" ) type mockCfg struct { + resolver.Mock MockSecrets map[string]*apiv1.Secret MockServices map[string]*apiv1.Service } diff --git a/internal/ingress/annotations/auth/main.go b/internal/ingress/annotations/auth/main.go index 606b225ed..0b2187368 100644 --- a/internal/ingress/annotations/auth/main.go +++ b/internal/ingress/annotations/auth/main.go @@ -33,12 +33,6 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) -const ( - authType = "ingress.kubernetes.io/auth-type" - authSecret = "ingress.kubernetes.io/auth-secret" - authRealm = "ingress.kubernetes.io/auth-realm" -) - var ( authTypeRegex = regexp.MustCompile(`basic|digest`) // AuthDirectory default directory used to store files @@ -83,12 +77,12 @@ func (bd1 *Config) Equal(bd2 *Config) bool { } type auth struct { - secretResolver resolver.Secret - authDirectory string + r resolver.Resolver + authDirectory string } // NewParser creates a new authentication annotation parser -func NewParser(authDirectory string, sr resolver.Secret) parser.IngressAnnotation { +func NewParser(authDirectory string, r resolver.Resolver) parser.IngressAnnotation { os.MkdirAll(authDirectory, 0755) currPath := authDirectory @@ -100,7 +94,7 @@ func NewParser(authDirectory string, sr resolver.Secret) parser.IngressAnnotatio } } - return auth{sr, authDirectory} + return auth{r, authDirectory} } // Parse parses the annotations contained in the ingress @@ -108,7 +102,7 @@ func NewParser(authDirectory string, sr resolver.Secret) parser.IngressAnnotatio // and generated an htpasswd compatible file to be used as source // during the authentication process func (a auth) Parse(ing *extensions.Ingress) (interface{}, error) { - at, err := parser.GetStringAnnotation(authType, ing) + at, err := parser.GetStringAnnotation("auth-type", ing, a.r) if err != nil { return nil, err } @@ -117,7 +111,7 @@ func (a auth) Parse(ing *extensions.Ingress) (interface{}, error) { return nil, ing_errors.NewLocationDenied("invalid authentication type") } - s, err := parser.GetStringAnnotation(authSecret, ing) + s, err := parser.GetStringAnnotation("auth-secret", ing, a.r) if err != nil { return nil, ing_errors.LocationDenied{ Reason: errors.Wrap(err, "error reading secret name from annotation"), @@ -125,14 +119,14 @@ func (a auth) Parse(ing *extensions.Ingress) (interface{}, error) { } name := fmt.Sprintf("%v/%v", ing.Namespace, s) - secret, err := a.secretResolver.GetSecret(name) + secret, err := a.r.GetSecret(name) if err != nil { return nil, ing_errors.LocationDenied{ Reason: errors.Wrapf(err, "unexpected error reading secret %v", name), } } - realm, _ := parser.GetStringAnnotation(authRealm, ing) + realm, _ := parser.GetStringAnnotation("auth-realm", ing, a.r) passFile := fmt.Sprintf("%v/%v-%v.passwd", a.authDirectory, ing.GetNamespace(), ing.GetName()) err = dumpSecret(passFile, secret) diff --git a/internal/ingress/annotations/auth/main_test.go b/internal/ingress/annotations/auth/main_test.go index ffb421719..c93dddb67 100644 --- a/internal/ingress/annotations/auth/main_test.go +++ b/internal/ingress/annotations/auth/main_test.go @@ -29,6 +29,7 @@ import ( extensions "k8s.io/api/extensions/v1beta1" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) func buildIngress() *extensions.Ingress { @@ -67,6 +68,7 @@ func buildIngress() *extensions.Ingress { } type mockSecret struct { + resolver.Mock } func (m mockSecret) GetSecret(name string) (*api.Secret, error) { @@ -87,7 +89,7 @@ func TestIngressWithoutAuth(t *testing.T) { ing := buildIngress() _, dir, _ := dummySecretContent(t) defer os.RemoveAll(dir) - _, err := NewParser(dir, mockSecret{}).Parse(ing) + _, err := NewParser(dir, &mockSecret{}).Parse(ing) if err == nil { t.Error("Expected error with ingress without annotations") } @@ -97,15 +99,15 @@ func TestIngressAuth(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[authType] = "basic" - data[authSecret] = "demo-secret" - data[authRealm] = "-realm-" + data["nginx/auth-type"] = "basic" + data["nginx/auth-secret"] = "demo-secret" + data["nginx/auth-realm"] = "-realm-" ing.SetAnnotations(data) _, dir, _ := dummySecretContent(t) defer os.RemoveAll(dir) - i, err := NewParser(dir, mockSecret{}).Parse(ing) + i, err := NewParser(dir, &mockSecret{}).Parse(ing) if err != nil { t.Errorf("Uxpected error with ingress: %v", err) } @@ -128,9 +130,9 @@ func TestIngressAuthWithoutSecret(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[authType] = "basic" - data[authSecret] = "invalid-secret" - data[authRealm] = "-realm-" + data["nginx/auth-type"] = "basic" + data["nginx/auth-secret"] = "invalid-secret" + data["nginx/auth-realm"] = "-realm-" ing.SetAnnotations(data) _, dir, _ := dummySecretContent(t) diff --git a/internal/ingress/annotations/authreq/main.go b/internal/ingress/annotations/authreq/main.go index 17a997652..dbc9f51a2 100644 --- a/internal/ingress/annotations/authreq/main.go +++ b/internal/ingress/annotations/authreq/main.go @@ -25,17 +25,10 @@ import ( "k8s.io/ingress-nginx/internal/ingress/annotations/parser" ing_errors "k8s.io/ingress-nginx/internal/ingress/errors" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) -const ( - // external URL that provides the authentication - authURL = "ingress.kubernetes.io/auth-url" - authSigninURL = "ingress.kubernetes.io/auth-signin" - authMethod = "ingress.kubernetes.io/auth-method" - authHeaders = "ingress.kubernetes.io/auth-response-headers" -) - -// External returns external authentication configuration for an Ingress rule +// Config returns external authentication configuration for an Ingress rule type Config struct { URL string `json:"url"` // Host contains the hostname defined in the URL @@ -108,17 +101,18 @@ func validHeader(header string) bool { } type authReq struct { + r resolver.Resolver } // NewParser creates a new authentication request annotation parser -func NewParser() parser.IngressAnnotation { - return authReq{} +func NewParser(r resolver.Resolver) parser.IngressAnnotation { + return authReq{r} } // ParseAnnotations parses the annotations contained in the ingress // rule used to use an Config URL as source for authentication func (a authReq) Parse(ing *extensions.Ingress) (interface{}, error) { - str, err := parser.GetStringAnnotation(authURL, ing) + str, err := parser.GetStringAnnotation("auth-url", ing, a.r) if err != nil { return nil, err } @@ -127,7 +121,7 @@ func (a authReq) Parse(ing *extensions.Ingress) (interface{}, error) { return nil, ing_errors.NewLocationDenied("an empty string is not a valid URL") } - signin, _ := parser.GetStringAnnotation(authSigninURL, ing) + signin, _ := parser.GetStringAnnotation("auth-signin", ing, a.r) ur, err := url.Parse(str) if err != nil { @@ -144,13 +138,13 @@ func (a authReq) Parse(ing *extensions.Ingress) (interface{}, error) { return nil, ing_errors.NewLocationDenied("invalid url host") } - m, _ := parser.GetStringAnnotation(authMethod, ing) + m, _ := parser.GetStringAnnotation("auth-method", ing, a.r) if len(m) != 0 && !validMethod(m) { return nil, ing_errors.NewLocationDenied("invalid HTTP method") } h := []string{} - hstr, _ := parser.GetStringAnnotation(authHeaders, ing) + hstr, _ := parser.GetStringAnnotation("auth-response-headers", ing, a.r) if len(hstr) != 0 { harr := strings.Split(hstr, ",") diff --git a/internal/ingress/annotations/authreq/main_test.go b/internal/ingress/annotations/authreq/main_test.go index 8256302a7..2208cc24e 100644 --- a/internal/ingress/annotations/authreq/main_test.go +++ b/internal/ingress/annotations/authreq/main_test.go @@ -24,6 +24,7 @@ import ( api "k8s.io/api/core/v1" extensions "k8s.io/api/extensions/v1beta1" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/ingress-nginx/internal/ingress/resolver" "k8s.io/apimachinery/pkg/util/intstr" ) @@ -86,11 +87,11 @@ func TestAnnotations(t *testing.T) { } for _, test := range tests { - data[authURL] = test.url - data[authSigninURL] = test.signinURL - data[authMethod] = fmt.Sprintf("%v", test.method) + data["nginx/auth-url"] = test.url + data["nginx/auth-signin"] = test.signinURL + data["nginx/auth-method"] = fmt.Sprintf("%v", test.method) - i, err := NewParser().Parse(ing) + i, err := NewParser(&resolver.Mock{}).Parse(ing) if test.expErr { if err == nil { t.Errorf("%v: expected error but retuned nil", test.title) @@ -136,11 +137,11 @@ func TestHeaderAnnotations(t *testing.T) { } for _, test := range tests { - data[authURL] = test.url - data[authHeaders] = test.headers - data[authMethod] = "GET" + data["nginx/auth-url"] = test.url + data["nginx/auth-response-headers"] = test.headers + data["nginx/auth-method"] = "GET" - i, err := NewParser().Parse(ing) + i, err := NewParser(&resolver.Mock{}).Parse(ing) if test.expErr { if err == nil { t.Errorf("%v: expected error but retuned nil", err.Error()) diff --git a/internal/ingress/annotations/authtls/main.go b/internal/ingress/annotations/authtls/main.go index 7fb5eac71..7fa511873 100644 --- a/internal/ingress/annotations/authtls/main.go +++ b/internal/ingress/annotations/authtls/main.go @@ -29,13 +29,8 @@ import ( ) const ( - // name of the secret - annotationAuthTLSSecret = "ingress.kubernetes.io/auth-tls-secret" - annotationAuthVerifyClient = "ingress.kubernetes.io/auth-tls-verify-client" - annotationAuthTLSDepth = "ingress.kubernetes.io/auth-tls-verify-depth" - annotationAuthTLSErrorPage = "ingress.kubernetes.io/auth-tls-error-page" - defaultAuthTLSDepth = 1 - defaultAuthVerifyClient = "on" + defaultAuthTLSDepth = 1 + defaultAuthVerifyClient = "on" ) var ( @@ -75,19 +70,19 @@ func (assl1 *Config) Equal(assl2 *Config) bool { } // NewParser creates a new TLS authentication annotation parser -func NewParser(resolver resolver.AuthCertificate) parser.IngressAnnotation { +func NewParser(resolver resolver.Resolver) parser.IngressAnnotation { return authTLS{resolver} } type authTLS struct { - certResolver resolver.AuthCertificate + r resolver.Resolver } // Parse parses the annotations contained in the ingress // rule used to use a Certificate as authentication method func (a authTLS) Parse(ing *extensions.Ingress) (interface{}, error) { - tlsauthsecret, err := parser.GetStringAnnotation(annotationAuthTLSSecret, ing) + tlsauthsecret, err := parser.GetStringAnnotation(a.r.GetAnnotationWithPrefix("auth-tls-secret"), ing, a.r) if err != nil { return &Config{}, err } @@ -101,24 +96,24 @@ func (a authTLS) Parse(ing *extensions.Ingress) (interface{}, error) { return &Config{}, ing_errors.NewLocationDenied(err.Error()) } - tlsVerifyClient, err := parser.GetStringAnnotation(annotationAuthVerifyClient, ing) + tlsVerifyClient, err := parser.GetStringAnnotation("auth-tls-verify-client", ing, a.r) if err != nil || !authVerifyClientRegex.MatchString(tlsVerifyClient) { tlsVerifyClient = defaultAuthVerifyClient } - tlsdepth, err := parser.GetIntAnnotation(annotationAuthTLSDepth, ing) + tlsdepth, err := parser.GetIntAnnotation("auth-tls-verify-depth", ing, a.r) if err != nil || tlsdepth == 0 { tlsdepth = defaultAuthTLSDepth } - authCert, err := a.certResolver.GetAuthCertificate(tlsauthsecret) + authCert, err := a.r.GetAuthCertificate(tlsauthsecret) if err != nil { return &Config{}, ing_errors.LocationDenied{ Reason: errors.Wrap(err, "error obtaining certificate"), } } - errorpage, err := parser.GetStringAnnotation(annotationAuthTLSErrorPage, ing) + errorpage, err := parser.GetStringAnnotation("auth-tls-error-page", ing, a.r) if err != nil || errorpage == "" { errorpage = "" } diff --git a/internal/ingress/annotations/class/main.go b/internal/ingress/annotations/class/main.go index 9c0db669b..33c7c7629 100644 --- a/internal/ingress/annotations/class/main.go +++ b/internal/ingress/annotations/class/main.go @@ -19,9 +19,6 @@ package class import ( "github.com/golang/glog" extensions "k8s.io/api/extensions/v1beta1" - - "k8s.io/ingress-nginx/internal/ingress/annotations/parser" - "k8s.io/ingress-nginx/internal/ingress/errors" ) const ( @@ -35,9 +32,9 @@ const ( // the ingress.class annotation, or it's set to the configured in the // ingress controller. func IsValid(ing *extensions.Ingress, controller, defClass string) bool { - ingress, err := parser.GetStringAnnotation(IngressKey, ing) - if err != nil && !errors.IsMissingAnnotations(err) { - glog.Warningf("unexpected error reading ingress annotation: %v", err) + ingress, ok := ing.GetAnnotations()[IngressKey] + if !ok { + glog.V(3).Infof("annotation %v is not present in ingress %v/%v", IngressKey, ing.Namespace, ing.Name) } // we have 2 valid combinations diff --git a/internal/ingress/annotations/clientbodybuffersize/main.go b/internal/ingress/annotations/clientbodybuffersize/main.go index c8abf2701..6ff3e070a 100644 --- a/internal/ingress/annotations/clientbodybuffersize/main.go +++ b/internal/ingress/annotations/clientbodybuffersize/main.go @@ -20,22 +20,20 @@ import ( extensions "k8s.io/api/extensions/v1beta1" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" -) - -const ( - annotation = "ingress.kubernetes.io/client-body-buffer-size" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) type clientBodyBufferSize struct { + r resolver.Resolver } // NewParser creates a new clientBodyBufferSize annotation parser -func NewParser() parser.IngressAnnotation { - return clientBodyBufferSize{} +func NewParser(r resolver.Resolver) parser.IngressAnnotation { + return clientBodyBufferSize{r} } // Parse parses the annotations contained in the ingress rule // used to add an client-body-buffer-size to the provided locations -func (a clientBodyBufferSize) Parse(ing *extensions.Ingress) (interface{}, error) { - return parser.GetStringAnnotation(annotation, ing) +func (cbbs clientBodyBufferSize) Parse(ing *extensions.Ingress) (interface{}, error) { + return parser.GetStringAnnotation("client-body-buffer-size", ing, cbbs.r) } diff --git a/internal/ingress/annotations/clientbodybuffersize/main_test.go b/internal/ingress/annotations/clientbodybuffersize/main_test.go index 8ed6e0c38..b47231498 100644 --- a/internal/ingress/annotations/clientbodybuffersize/main_test.go +++ b/internal/ingress/annotations/clientbodybuffersize/main_test.go @@ -22,10 +22,12 @@ import ( api "k8s.io/api/core/v1" extensions "k8s.io/api/extensions/v1beta1" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) func TestParse(t *testing.T) { - ap := NewParser() + annotation := "nginx/client-body-buffer-size" + ap := NewParser(&resolver.Mock{}) if ap == nil { t.Fatalf("expected a parser.IngressAnnotation but returned nil") } diff --git a/internal/ingress/annotations/cors/main.go b/internal/ingress/annotations/cors/main.go index aa03ce035..ac77c250a 100644 --- a/internal/ingress/annotations/cors/main.go +++ b/internal/ingress/annotations/cors/main.go @@ -22,14 +22,10 @@ import ( extensions "k8s.io/api/extensions/v1beta1" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) const ( - annotationCorsEnabled = "ingress.kubernetes.io/enable-cors" - annotationCorsAllowOrigin = "ingress.kubernetes.io/cors-allow-origin" - annotationCorsAllowMethods = "ingress.kubernetes.io/cors-allow-methods" - annotationCorsAllowHeaders = "ingress.kubernetes.io/cors-allow-headers" - annotationCorsAllowCredentials = "ingress.kubernetes.io/cors-allow-credentials" // Default values defaultCorsMethods = "GET, PUT, POST, DELETE, PATCH, OPTIONS" defaultCorsHeaders = "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization" @@ -49,6 +45,7 @@ var ( ) type cors struct { + r resolver.Resolver } // Config contains the Cors configuration to be used in the Ingress @@ -61,8 +58,8 @@ type Config struct { } // NewParser creates a new CORS annotation parser -func NewParser() parser.IngressAnnotation { - return cors{} +func NewParser(r resolver.Resolver) parser.IngressAnnotation { + return cors{r} } // Equal tests for equality between two External types @@ -94,28 +91,28 @@ func (c1 *Config) Equal(c2 *Config) bool { // Parse parses the annotations contained in the ingress // rule used to indicate if the location/s should allows CORS -func (a cors) Parse(ing *extensions.Ingress) (interface{}, error) { - corsenabled, err := parser.GetBoolAnnotation(annotationCorsEnabled, ing) +func (c cors) Parse(ing *extensions.Ingress) (interface{}, error) { + corsenabled, err := parser.GetBoolAnnotation("enable-cors", ing, c.r) if err != nil { corsenabled = false } - corsalloworigin, err := parser.GetStringAnnotation(annotationCorsAllowOrigin, ing) + corsalloworigin, err := parser.GetStringAnnotation("cors-allow-origin", ing, c.r) if err != nil || corsalloworigin == "" || !corsOriginRegex.MatchString(corsalloworigin) { corsalloworigin = "*" } - corsallowheaders, err := parser.GetStringAnnotation(annotationCorsAllowHeaders, ing) + corsallowheaders, err := parser.GetStringAnnotation("cors-allow-headers", ing, c.r) if err != nil || corsallowheaders == "" || !corsHeadersRegex.MatchString(corsallowheaders) { corsallowheaders = defaultCorsHeaders } - corsallowmethods, err := parser.GetStringAnnotation(annotationCorsAllowMethods, ing) + corsallowmethods, err := parser.GetStringAnnotation("cors-allow-methods", ing, c.r) if err != nil || corsallowmethods == "" || !corsMethodsRegex.MatchString(corsallowmethods) { corsallowmethods = defaultCorsMethods } - corsallowcredentials, err := parser.GetBoolAnnotation(annotationCorsAllowCredentials, ing) + corsallowcredentials, err := parser.GetBoolAnnotation("cors-allow-credentials", ing, c.r) if err != nil { corsallowcredentials = true } diff --git a/internal/ingress/annotations/cors/main_test.go b/internal/ingress/annotations/cors/main_test.go index 101e26cbc..2eda3a0fa 100644 --- a/internal/ingress/annotations/cors/main_test.go +++ b/internal/ingress/annotations/cors/main_test.go @@ -23,6 +23,7 @@ import ( extensions "k8s.io/api/extensions/v1beta1" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) func buildIngress() *extensions.Ingress { @@ -64,14 +65,14 @@ func TestIngressCorsConfig(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[annotationCorsEnabled] = "true" - data[annotationCorsAllowHeaders] = "DNT,X-CustomHeader, Keep-Alive,User-Agent" - data[annotationCorsAllowCredentials] = "false" - data[annotationCorsAllowMethods] = "PUT, GET,OPTIONS, PATCH, $nginx_version" - data[annotationCorsAllowOrigin] = "https://origin123.test.com:4443" + data["nginx/enable-cors"] = "true" + data["nginx/cors-allow-headers"] = "DNT,X-CustomHeader, Keep-Alive,User-Agent" + data["nginx/cors-allow-credentials"] = "false" + data["nginx/cors-allow-methods"] = "PUT, GET,OPTIONS, PATCH, $nginx_version" + data["nginx/cors-allow-origin"] = "https://origin123.test.com:4443" ing.SetAnnotations(data) - corst, _ := NewParser().Parse(ing) + corst, _ := NewParser(&resolver.Mock{}).Parse(ing) nginxCors, ok := corst.(*Config) if !ok { t.Errorf("expected a Config type") diff --git a/internal/ingress/annotations/defaultbackend/main.go b/internal/ingress/annotations/defaultbackend/main.go index fa19a583d..1d4be720f 100644 --- a/internal/ingress/annotations/defaultbackend/main.go +++ b/internal/ingress/annotations/defaultbackend/main.go @@ -26,29 +26,25 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) -const ( - defaultBackend = "ingress.kubernetes.io/default-backend" -) - type backend struct { - serviceResolver resolver.Service + r resolver.Resolver } // NewParser creates a new default backend annotation parser -func NewParser(sr resolver.Service) parser.IngressAnnotation { - return backend{sr} +func NewParser(r resolver.Resolver) parser.IngressAnnotation { + return backend{r} } // Parse parses the annotations contained in the ingress to use // a custom default backend func (db backend) Parse(ing *extensions.Ingress) (interface{}, error) { - s, err := parser.GetStringAnnotation(defaultBackend, ing) + s, err := parser.GetStringAnnotation("default-backend", ing, db.r) if err != nil { return nil, err } name := fmt.Sprintf("%v/%v", ing.Namespace, s) - svc, err := db.serviceResolver.GetService(name) + svc, err := db.r.GetService(name) if err != nil { return nil, errors.Wrapf(err, "unexpected error reading service %v", name) } diff --git a/internal/ingress/annotations/healthcheck/main.go b/internal/ingress/annotations/healthcheck/main.go index ca386a296..44c5b3602 100644 --- a/internal/ingress/annotations/healthcheck/main.go +++ b/internal/ingress/annotations/healthcheck/main.go @@ -23,11 +23,6 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) -const ( - upsMaxFails = "ingress.kubernetes.io/upstream-max-fails" - upsFailTimeout = "ingress.kubernetes.io/upstream-fail-timeout" -) - // Config returns the URL and method to use check the status of // the upstream server/s type Config struct { @@ -36,28 +31,28 @@ type Config struct { } type healthCheck struct { - backendResolver resolver.DefaultBackend + r resolver.Resolver } // NewParser creates a new health check annotation parser -func NewParser(br resolver.DefaultBackend) parser.IngressAnnotation { - return healthCheck{br} +func NewParser(r resolver.Resolver) parser.IngressAnnotation { + return healthCheck{r} } // ParseAnnotations parses the annotations contained in the ingress // rule used to configure upstream check parameters -func (a healthCheck) Parse(ing *extensions.Ingress) (interface{}, error) { - defBackend := a.backendResolver.GetDefaultBackend() +func (hc healthCheck) Parse(ing *extensions.Ingress) (interface{}, error) { + defBackend := hc.r.GetDefaultBackend() if ing.GetAnnotations() == nil { return &Config{defBackend.UpstreamMaxFails, defBackend.UpstreamFailTimeout}, nil } - mf, err := parser.GetIntAnnotation(upsMaxFails, ing) + mf, err := parser.GetIntAnnotation("upstream-max-fails", ing, hc.r) if err != nil { mf = defBackend.UpstreamMaxFails } - ft, err := parser.GetIntAnnotation(upsFailTimeout, ing) + ft, err := parser.GetIntAnnotation("upstream-fail-timeout", ing, hc.r) if err != nil { ft = defBackend.UpstreamFailTimeout } diff --git a/internal/ingress/annotations/healthcheck/main_test.go b/internal/ingress/annotations/healthcheck/main_test.go index 31b43eb39..1654aa0c2 100644 --- a/internal/ingress/annotations/healthcheck/main_test.go +++ b/internal/ingress/annotations/healthcheck/main_test.go @@ -25,6 +25,7 @@ import ( "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/ingress-nginx/internal/ingress/defaults" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) func buildIngress() *extensions.Ingress { @@ -63,6 +64,7 @@ func buildIngress() *extensions.Ingress { } type mockBackend struct { + resolver.Mock } func (m mockBackend) GetDefaultBackend() defaults.Backend { @@ -73,7 +75,7 @@ func TestIngressHealthCheck(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[upsMaxFails] = "2" + data["nginx/upstream-max-fails"] = "2" ing.SetAnnotations(data) hzi, _ := NewParser(mockBackend{}).Parse(ing) diff --git a/internal/ingress/annotations/ipwhitelist/main.go b/internal/ingress/annotations/ipwhitelist/main.go index 2b4cd72aa..2681f7136 100644 --- a/internal/ingress/annotations/ipwhitelist/main.go +++ b/internal/ingress/annotations/ipwhitelist/main.go @@ -30,10 +30,6 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) -const ( - whitelist = "ingress.kubernetes.io/whitelist-source-range" -) - // SourceRange returns the CIDR type SourceRange struct { CIDR []string `json:"cidr,omitEmpty"` @@ -69,12 +65,12 @@ func (sr1 *SourceRange) Equal(sr2 *SourceRange) bool { } type ipwhitelist struct { - backendResolver resolver.DefaultBackend + r resolver.Resolver } // NewParser creates a new whitelist annotation parser -func NewParser(br resolver.DefaultBackend) parser.IngressAnnotation { - return ipwhitelist{br} +func NewParser(r resolver.Resolver) parser.IngressAnnotation { + return ipwhitelist{r} } // ParseAnnotations parses the annotations contained in the ingress @@ -82,10 +78,10 @@ func NewParser(br resolver.DefaultBackend) parser.IngressAnnotation { // Multiple ranges can specified using commas as separator // e.g. `18.0.0.0/8,56.0.0.0/8` func (a ipwhitelist) Parse(ing *extensions.Ingress) (interface{}, error) { - defBackend := a.backendResolver.GetDefaultBackend() + defBackend := a.r.GetDefaultBackend() sort.Strings(defBackend.WhitelistSourceRange) - val, err := parser.GetStringAnnotation(whitelist, ing) + val, err := parser.GetStringAnnotation("whitelist-source-range", ing, a.r) // A missing annotation is not a problem, just use the default if err == ing_errors.ErrMissingAnnotations { return &SourceRange{CIDR: defBackend.WhitelistSourceRange}, nil diff --git a/internal/ingress/annotations/ipwhitelist/main_test.go b/internal/ingress/annotations/ipwhitelist/main_test.go index a4e166608..2e7d54f5c 100644 --- a/internal/ingress/annotations/ipwhitelist/main_test.go +++ b/internal/ingress/annotations/ipwhitelist/main_test.go @@ -23,8 +23,8 @@ import ( extensions "k8s.io/api/extensions/v1beta1" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" - "k8s.io/ingress-nginx/internal/ingress/defaults" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) func buildIngress() *extensions.Ingress { @@ -62,14 +62,6 @@ func buildIngress() *extensions.Ingress { } } -type mockBackend struct { - defaults.Backend -} - -func (m mockBackend) GetDefaultBackend() defaults.Backend { - return m.Backend -} - func TestParseAnnotations(t *testing.T) { ing := buildIngress() tests := map[string]struct { @@ -102,9 +94,9 @@ func TestParseAnnotations(t *testing.T) { for testName, test := range tests { data := map[string]string{} - data[whitelist] = test.net + data["nginx/whitelist-source-range"] = test.net ing.SetAnnotations(data) - p := NewParser(mockBackend{}) + p := NewParser(&resolver.Mock{}) i, err := p.Parse(ing) if err != nil && !test.expectErr { t.Errorf("%v:unexpected error: %v", testName, err) @@ -126,12 +118,24 @@ func TestParseAnnotations(t *testing.T) { } } +type mockBackend struct { + resolver.Mock +} + +// GetDefaultBackend returns the backend that must be used as default +func (m mockBackend) GetDefaultBackend() defaults.Backend { + return defaults.Backend{ + WhitelistSourceRange: []string{"4.4.4.0/24", "1.2.3.4/32"}, + } +} + // Test that when we have a whitelist set on the Backend that is used when we // don't have the annotation func TestParseAnnotationsWithDefaultConfig(t *testing.T) { ing := buildIngress() + mockBackend := mockBackend{} - mockBackend.Backend.WhitelistSourceRange = []string{"4.4.4.0/24", "1.2.3.4/32"} + tests := map[string]struct { net string expectCidr []string @@ -162,7 +166,7 @@ func TestParseAnnotationsWithDefaultConfig(t *testing.T) { for testName, test := range tests { data := map[string]string{} - data[whitelist] = test.net + data["nginx/whitelist-source-range"] = test.net ing.SetAnnotations(data) p := NewParser(mockBackend) i, err := p.Parse(ing) diff --git a/internal/ingress/annotations/parser/main.go b/internal/ingress/annotations/parser/main.go index cbec167a5..d0e8dca71 100644 --- a/internal/ingress/annotations/parser/main.go +++ b/internal/ingress/annotations/parser/main.go @@ -22,6 +22,7 @@ import ( extensions "k8s.io/api/extensions/v1beta1" "k8s.io/ingress-nginx/internal/ingress/errors" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) // IngressAnnotation has a method to parse annotations located in Ingress @@ -75,28 +76,31 @@ func checkAnnotation(name string, ing *extensions.Ingress) error { } // GetBoolAnnotation extracts a boolean from an Ingress annotation -func GetBoolAnnotation(name string, ing *extensions.Ingress) (bool, error) { - err := checkAnnotation(name, ing) +func GetBoolAnnotation(name string, ing *extensions.Ingress, r resolver.Resolver) (bool, error) { + v := r.GetAnnotationWithPrefix(name) + err := checkAnnotation(v, ing) if err != nil { return false, err } - return ingAnnotations(ing.GetAnnotations()).parseBool(name) + return ingAnnotations(ing.GetAnnotations()).parseBool(v) } // GetStringAnnotation extracts a string from an Ingress annotation -func GetStringAnnotation(name string, ing *extensions.Ingress) (string, error) { - err := checkAnnotation(name, ing) +func GetStringAnnotation(name string, ing *extensions.Ingress, r resolver.Resolver) (string, error) { + v := r.GetAnnotationWithPrefix(name) + err := checkAnnotation(v, ing) if err != nil { return "", err } - return ingAnnotations(ing.GetAnnotations()).parseString(name) + return ingAnnotations(ing.GetAnnotations()).parseString(v) } // GetIntAnnotation extracts an int from an Ingress annotation -func GetIntAnnotation(name string, ing *extensions.Ingress) (int, error) { - err := checkAnnotation(name, ing) +func GetIntAnnotation(name string, ing *extensions.Ingress, r resolver.Resolver) (int, error) { + v := r.GetAnnotationWithPrefix(name) + err := checkAnnotation(v, ing) if err != nil { return 0, err } - return ingAnnotations(ing.GetAnnotations()).parseInt(name) + return ingAnnotations(ing.GetAnnotations()).parseInt(v) } diff --git a/internal/ingress/annotations/parser/main_test.go b/internal/ingress/annotations/parser/main_test.go index 4bcc3188e..b04f0d722 100644 --- a/internal/ingress/annotations/parser/main_test.go +++ b/internal/ingress/annotations/parser/main_test.go @@ -17,11 +17,13 @@ limitations under the License. package parser import ( + "fmt" "testing" api "k8s.io/api/core/v1" extensions "k8s.io/api/extensions/v1beta1" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) func buildIngress() *extensions.Ingress { @@ -35,9 +37,11 @@ func buildIngress() *extensions.Ingress { } func TestGetBoolAnnotation(t *testing.T) { + r := &resolver.Mock{} + ing := buildIngress() - _, err := GetBoolAnnotation("", nil) + _, err := GetBoolAnnotation("", nil, r) if err == nil { t.Errorf("expected error but retuned nil") } @@ -49,8 +53,6 @@ func TestGetBoolAnnotation(t *testing.T) { exp bool expErr bool }{ - {"empty - false", "", "false", false, true}, - {"empty - true", "", "true", false, true}, {"valid - false", "bool", "false", false, false}, {"valid - true", "bool", "true", true, false}, } @@ -59,9 +61,9 @@ func TestGetBoolAnnotation(t *testing.T) { ing.SetAnnotations(data) for _, test := range tests { - data[test.field] = test.value + data[fmt.Sprintf("nginx/%v", test.field)] = test.value - u, err := GetBoolAnnotation(test.field, ing) + u, err := GetBoolAnnotation(test.field, ing, r) if test.expErr { if err == nil { t.Errorf("%v: expected error but retuned nil", test.name) @@ -77,9 +79,11 @@ func TestGetBoolAnnotation(t *testing.T) { } func TestGetStringAnnotation(t *testing.T) { + r := &resolver.Mock{} + ing := buildIngress() - _, err := GetStringAnnotation("", nil) + _, err := GetStringAnnotation("", nil, r) if err == nil { t.Errorf("expected error but retuned nil") } @@ -91,8 +95,6 @@ func TestGetStringAnnotation(t *testing.T) { exp string expErr bool }{ - {"empty - A", "", "A", "", true}, - {"empty - B", "", "B", "", true}, {"valid - A", "string", "A", "A", false}, {"valid - B", "string", "B", "B", false}, } @@ -101,9 +103,9 @@ func TestGetStringAnnotation(t *testing.T) { ing.SetAnnotations(data) for _, test := range tests { - data[test.field] = test.value + data[fmt.Sprintf("nginx/%v", test.field)] = test.value - s, err := GetStringAnnotation(test.field, ing) + s, err := GetStringAnnotation(test.field, ing, r) if test.expErr { if err == nil { t.Errorf("%v: expected error but retuned nil", test.name) @@ -119,9 +121,11 @@ func TestGetStringAnnotation(t *testing.T) { } func TestGetIntAnnotation(t *testing.T) { + r := &resolver.Mock{} + ing := buildIngress() - _, err := GetIntAnnotation("", nil) + _, err := GetIntAnnotation("", nil, r) if err == nil { t.Errorf("expected error but retuned nil") } @@ -133,8 +137,6 @@ func TestGetIntAnnotation(t *testing.T) { exp int expErr bool }{ - {"empty - A", "", "1", 0, true}, - {"empty - B", "", "2", 0, true}, {"valid - A", "string", "1", 1, false}, {"valid - B", "string", "2", 2, false}, } @@ -143,9 +145,9 @@ func TestGetIntAnnotation(t *testing.T) { ing.SetAnnotations(data) for _, test := range tests { - data[test.field] = test.value + data[fmt.Sprintf("nginx/%v", test.field)] = test.value - s, err := GetIntAnnotation(test.field, ing) + s, err := GetIntAnnotation(test.field, ing, r) if test.expErr { if err == nil { t.Errorf("%v: expected error but retuned nil", test.name) diff --git a/internal/ingress/annotations/portinredirect/main.go b/internal/ingress/annotations/portinredirect/main.go index 093af7dde..459878069 100644 --- a/internal/ingress/annotations/portinredirect/main.go +++ b/internal/ingress/annotations/portinredirect/main.go @@ -23,25 +23,21 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) -const ( - annotation = "ingress.kubernetes.io/use-port-in-redirects" -) - type portInRedirect struct { - backendResolver resolver.DefaultBackend + r resolver.Resolver } // NewParser creates a new port in redirect annotation parser -func NewParser(db resolver.DefaultBackend) parser.IngressAnnotation { - return portInRedirect{db} +func NewParser(r resolver.Resolver) parser.IngressAnnotation { + return portInRedirect{r} } // Parse parses the annotations contained in the ingress // rule used to indicate if the redirects must func (a portInRedirect) Parse(ing *extensions.Ingress) (interface{}, error) { - up, err := parser.GetBoolAnnotation(annotation, ing) + up, err := parser.GetBoolAnnotation("use-port-in-redirects", ing, a.r) if err != nil { - return a.backendResolver.GetDefaultBackend().UsePortInRedirects, nil + return a.r.GetDefaultBackend().UsePortInRedirects, nil } return up, nil diff --git a/internal/ingress/annotations/portinredirect/main_test.go b/internal/ingress/annotations/portinredirect/main_test.go index a7454302a..9bd0e4f31 100644 --- a/internal/ingress/annotations/portinredirect/main_test.go +++ b/internal/ingress/annotations/portinredirect/main_test.go @@ -26,6 +26,7 @@ import ( "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/ingress-nginx/internal/ingress/defaults" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) func buildIngress() *extensions.Ingress { @@ -64,6 +65,7 @@ func buildIngress() *extensions.Ingress { } type mockBackend struct { + resolver.Mock usePortInRedirects bool } @@ -90,11 +92,11 @@ func TestPortInRedirect(t *testing.T) { data := map[string]string{} if test.usePort != nil { - data[annotation] = fmt.Sprintf("%v", *test.usePort) + data["nginx/use-port-in-redirects"] = fmt.Sprintf("%v", *test.usePort) } ing.SetAnnotations(data) - i, err := NewParser(mockBackend{test.def}).Parse(ing) + i, err := NewParser(mockBackend{usePortInRedirects: test.def}).Parse(ing) if err != nil { t.Errorf("unexpected error parsing a valid") } diff --git a/internal/ingress/annotations/proxy/main.go b/internal/ingress/annotations/proxy/main.go index 8dee7ce07..e193312de 100644 --- a/internal/ingress/annotations/proxy/main.go +++ b/internal/ingress/annotations/proxy/main.go @@ -23,19 +23,6 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) -const ( - bodySize = "ingress.kubernetes.io/proxy-body-size" - connect = "ingress.kubernetes.io/proxy-connect-timeout" - send = "ingress.kubernetes.io/proxy-send-timeout" - read = "ingress.kubernetes.io/proxy-read-timeout" - bufferSize = "ingress.kubernetes.io/proxy-buffer-size" - cookiePath = "ingress.kubernetes.io/proxy-cookie-path" - cookieDomain = "ingress.kubernetes.io/proxy-cookie-domain" - nextUpstream = "ingress.kubernetes.io/proxy-next-upstream" - passParams = "ingress.kubernetes.io/proxy-pass-params" - requestBuffering = "ingress.kubernetes.io/proxy-request-buffering" -) - // Config returns the proxy timeout to use in the upstream server/s type Config struct { BodySize string `json:"bodySize"` @@ -94,64 +81,64 @@ func (l1 *Config) Equal(l2 *Config) bool { } type proxy struct { - backendResolver resolver.DefaultBackend + r resolver.Resolver } // NewParser creates a new reverse proxy configuration annotation parser -func NewParser(br resolver.DefaultBackend) parser.IngressAnnotation { - return proxy{br} +func NewParser(r resolver.Resolver) parser.IngressAnnotation { + return proxy{r} } // ParseAnnotations parses the annotations contained in the ingress // rule used to configure upstream check parameters func (a proxy) Parse(ing *extensions.Ingress) (interface{}, error) { - defBackend := a.backendResolver.GetDefaultBackend() - ct, err := parser.GetIntAnnotation(connect, ing) + defBackend := a.r.GetDefaultBackend() + ct, err := parser.GetIntAnnotation("proxy-connect-timeout", ing, a.r) if err != nil { ct = defBackend.ProxyConnectTimeout } - st, err := parser.GetIntAnnotation(send, ing) + st, err := parser.GetIntAnnotation("proxy-send-timeout", ing, a.r) if err != nil { st = defBackend.ProxySendTimeout } - rt, err := parser.GetIntAnnotation(read, ing) + rt, err := parser.GetIntAnnotation("proxy-read-timeout", ing, a.r) if err != nil { rt = defBackend.ProxyReadTimeout } - bufs, err := parser.GetStringAnnotation(bufferSize, ing) + bufs, err := parser.GetStringAnnotation("proxy-buffer-size", ing, a.r) if err != nil || bufs == "" { bufs = defBackend.ProxyBufferSize } - cp, err := parser.GetStringAnnotation(cookiePath, ing) + cp, err := parser.GetStringAnnotation("proxy-cookie-path", ing, a.r) if err != nil || cp == "" { cp = defBackend.ProxyCookiePath } - cd, err := parser.GetStringAnnotation(cookieDomain, ing) + cd, err := parser.GetStringAnnotation("proxy-cookie-domain", ing, a.r) if err != nil || cd == "" { cd = defBackend.ProxyCookieDomain } - bs, err := parser.GetStringAnnotation(bodySize, ing) + bs, err := parser.GetStringAnnotation("proxy-body-size", ing, a.r) if err != nil || bs == "" { bs = defBackend.ProxyBodySize } - nu, err := parser.GetStringAnnotation(nextUpstream, ing) + nu, err := parser.GetStringAnnotation("proxy-next-upstream", ing, a.r) if err != nil || nu == "" { nu = defBackend.ProxyNextUpstream } - pp, err := parser.GetStringAnnotation(passParams, ing) + pp, err := parser.GetStringAnnotation("proxy-pass-params", ing, a.r) if err != nil || pp == "" { pp = defBackend.ProxyPassParams } - rb, err := parser.GetStringAnnotation(requestBuffering, ing) + rb, err := parser.GetStringAnnotation("proxy-request-buffering", ing, a.r) if err != nil || rb == "" { rb = defBackend.ProxyRequestBuffering } diff --git a/internal/ingress/annotations/proxy/main_test.go b/internal/ingress/annotations/proxy/main_test.go index 749d28206..c83dc9ef1 100644 --- a/internal/ingress/annotations/proxy/main_test.go +++ b/internal/ingress/annotations/proxy/main_test.go @@ -25,6 +25,7 @@ import ( "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/ingress-nginx/internal/ingress/defaults" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) func buildIngress() *extensions.Ingress { @@ -63,6 +64,7 @@ func buildIngress() *extensions.Ingress { } type mockBackend struct { + resolver.Mock } func (m mockBackend) GetDefaultBackend() defaults.Backend { @@ -83,14 +85,14 @@ func TestProxy(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[connect] = "1" - data[send] = "2" - data[read] = "3" - data[bufferSize] = "1k" - data[bodySize] = "2k" - data[nextUpstream] = "off" - data[passParams] = "smax=5 max=10" - data[requestBuffering] = "off" + data["nginx/proxy-connect-timeout"] = "1" + data["nginx/proxy-send-timeout"] = "2" + data["nginx/proxy-read-timeout"] = "3" + data["nginx/proxy-buffer-size"] = "1k" + data["nginx/proxy-body-size"] = "2k" + data["nginx/proxy-next-upstream"] = "off" + data["nginx/proxy-pass-params"] = "smax=5 max=10" + data["nginx/proxy-request-buffering"] = "off" ing.SetAnnotations(data) i, err := NewParser(mockBackend{}).Parse(ing) diff --git a/internal/ingress/annotations/ratelimit/main.go b/internal/ingress/annotations/ratelimit/main.go index e2a21f240..624d4aefd 100644 --- a/internal/ingress/annotations/ratelimit/main.go +++ b/internal/ingress/annotations/ratelimit/main.go @@ -30,13 +30,6 @@ import ( ) const ( - limitIP = "ingress.kubernetes.io/limit-connections" - limitRPS = "ingress.kubernetes.io/limit-rps" - limitRPM = "ingress.kubernetes.io/limit-rpm" - limitRATE = "ingress.kubernetes.io/limit-rate" - limitRATEAFTER = "ingress.kubernetes.io/limit-rate-after" - limitWhitelist = "ingress.kubernetes.io/limit-whitelist" - // allow 5 times the specified limit as burst defBurst = 5 @@ -152,32 +145,32 @@ func (z1 *Zone) Equal(z2 *Zone) bool { } type ratelimit struct { - backendResolver resolver.DefaultBackend + r resolver.Resolver } // NewParser creates a new ratelimit annotation parser -func NewParser(br resolver.DefaultBackend) parser.IngressAnnotation { - return ratelimit{br} +func NewParser(r resolver.Resolver) parser.IngressAnnotation { + return ratelimit{r} } // ParseAnnotations parses the annotations contained in the ingress // rule used to rewrite the defined paths func (a ratelimit) Parse(ing *extensions.Ingress) (interface{}, error) { - defBackend := a.backendResolver.GetDefaultBackend() - lr, err := parser.GetIntAnnotation(limitRATE, ing) + defBackend := a.r.GetDefaultBackend() + lr, err := parser.GetIntAnnotation("limit-rate", ing, a.r) if err != nil { lr = defBackend.LimitRate } - lra, err := parser.GetIntAnnotation(limitRATEAFTER, ing) + lra, err := parser.GetIntAnnotation("limit-rate-after", ing, a.r) if err != nil { lra = defBackend.LimitRateAfter } - rpm, _ := parser.GetIntAnnotation(limitRPM, ing) - rps, _ := parser.GetIntAnnotation(limitRPS, ing) - conn, _ := parser.GetIntAnnotation(limitIP, ing) + rpm, _ := parser.GetIntAnnotation("limit-rpm", ing, a.r) + rps, _ := parser.GetIntAnnotation("limit-rps", ing, a.r) + conn, _ := parser.GetIntAnnotation("limit-connections", ing, a.r) - val, _ := parser.GetStringAnnotation(limitWhitelist, ing) + val, _ := parser.GetStringAnnotation("limit-whitelist", ing, a.r) cidrs, err := parseCIDRs(val) if err != nil { diff --git a/internal/ingress/annotations/ratelimit/main_test.go b/internal/ingress/annotations/ratelimit/main_test.go index 4437bea56..a470bbb47 100644 --- a/internal/ingress/annotations/ratelimit/main_test.go +++ b/internal/ingress/annotations/ratelimit/main_test.go @@ -25,6 +25,7 @@ import ( "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/ingress-nginx/internal/ingress/defaults" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) func buildIngress() *extensions.Ingress { @@ -63,6 +64,7 @@ func buildIngress() *extensions.Ingress { } type mockBackend struct { + resolver.Mock } func (m mockBackend) GetDefaultBackend() defaults.Backend { @@ -84,9 +86,9 @@ func TestBadRateLimiting(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[limitIP] = "0" - data[limitRPS] = "0" - data[limitRPM] = "0" + data["nginx/limit-connections"] = "0" + data["nginx/limit-rps"] = "0" + data["nginx/limit-rpm"] = "0" ing.SetAnnotations(data) _, err := NewParser(mockBackend{}).Parse(ing) @@ -95,11 +97,11 @@ func TestBadRateLimiting(t *testing.T) { } data = map[string]string{} - data[limitIP] = "5" - data[limitRPS] = "100" - data[limitRPM] = "10" - data[limitRATEAFTER] = "100" - data[limitRATE] = "10" + data["nginx/limit-connections"] = "5" + data["nginx/limit-rps"] = "100" + data["nginx/limit-rpm"] = "10" + data["nginx/limit-rate-after"] = "100" + data["nginx/limit-rate"] = "10" ing.SetAnnotations(data) diff --git a/internal/ingress/annotations/redirect/redirect.go b/internal/ingress/annotations/redirect/redirect.go index 6cd90d960..255763ef6 100644 --- a/internal/ingress/annotations/redirect/redirect.go +++ b/internal/ingress/annotations/redirect/redirect.go @@ -25,12 +25,7 @@ import ( "k8s.io/ingress-nginx/internal/ingress/annotations/parser" "k8s.io/ingress-nginx/internal/ingress/errors" -) - -const ( - permanent = "ingress.kubernetes.io/permanent-redirect" - temporal = "ingress.kubernetes.io/temporal-redirect" - www = "ingress.kubernetes.io/from-to-www-redirect" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) // Config returns the redirect configuration for an Ingress rule @@ -40,11 +35,13 @@ type Config struct { FromToWWW bool `json:"fromToWWW"` } -type redirect struct{} +type redirect struct { + r resolver.Resolver +} // NewParser creates a new redirect annotation parser -func NewParser() parser.IngressAnnotation { - return redirect{} +func NewParser(r resolver.Resolver) parser.IngressAnnotation { + return redirect{r} } // Parse parses the annotations contained in the ingress @@ -52,9 +49,9 @@ func NewParser() parser.IngressAnnotation { // If the Ingress contains both annotations the execution order is // temporal and then permanent func (a redirect) Parse(ing *extensions.Ingress) (interface{}, error) { - r3w, _ := parser.GetBoolAnnotation(www, ing) + r3w, _ := parser.GetBoolAnnotation("from-to-www-redirect", ing, a.r) - tr, err := parser.GetStringAnnotation(temporal, ing) + tr, err := parser.GetStringAnnotation("temporal-redirect", ing, a.r) if err != nil && !errors.IsMissingAnnotations(err) { return nil, err } @@ -71,7 +68,7 @@ func (a redirect) Parse(ing *extensions.Ingress) (interface{}, error) { }, nil } - pr, err := parser.GetStringAnnotation(permanent, ing) + pr, err := parser.GetStringAnnotation("permanent-redirect", ing, a.r) if err != nil && !errors.IsMissingAnnotations(err) { return nil, err } diff --git a/internal/ingress/annotations/rewrite/main.go b/internal/ingress/annotations/rewrite/main.go index 2b08fe323..227cba446 100644 --- a/internal/ingress/annotations/rewrite/main.go +++ b/internal/ingress/annotations/rewrite/main.go @@ -23,15 +23,6 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) -const ( - rewriteTo = "ingress.kubernetes.io/rewrite-target" - addBaseURL = "ingress.kubernetes.io/add-base-url" - baseURLScheme = "ingress.kubernetes.io/base-url-scheme" - sslRedirect = "ingress.kubernetes.io/ssl-redirect" - forceSSLRedirect = "ingress.kubernetes.io/force-ssl-redirect" - appRoot = "ingress.kubernetes.io/app-root" -) - // Config describes the per location redirect config type Config struct { // Target URI where the traffic must be redirected @@ -80,29 +71,30 @@ func (r1 *Config) Equal(r2 *Config) bool { } type rewrite struct { - backendResolver resolver.DefaultBackend + r resolver.Resolver } // NewParser creates a new reqrite annotation parser -func NewParser(br resolver.DefaultBackend) parser.IngressAnnotation { - return rewrite{br} +func NewParser(r resolver.Resolver) parser.IngressAnnotation { + return rewrite{r} } // ParseAnnotations parses the annotations contained in the ingress // rule used to rewrite the defined paths func (a rewrite) Parse(ing *extensions.Ingress) (interface{}, error) { - rt, _ := parser.GetStringAnnotation(rewriteTo, ing) - sslRe, err := parser.GetBoolAnnotation(sslRedirect, ing) + rt, _ := parser.GetStringAnnotation("rewrite-target", ing, a.r) + sslRe, err := parser.GetBoolAnnotation("ssl-redirect", ing, a.r) if err != nil { - sslRe = a.backendResolver.GetDefaultBackend().SSLRedirect + sslRe = a.r.GetDefaultBackend().SSLRedirect } - fSslRe, err := parser.GetBoolAnnotation(forceSSLRedirect, ing) + fSslRe, err := parser.GetBoolAnnotation("force-ssl-redirect", ing, a.r) if err != nil { - fSslRe = a.backendResolver.GetDefaultBackend().ForceSSLRedirect + fSslRe = a.r.GetDefaultBackend().ForceSSLRedirect } - abu, _ := parser.GetBoolAnnotation(addBaseURL, ing) - bus, _ := parser.GetStringAnnotation(baseURLScheme, ing) - ar, _ := parser.GetStringAnnotation(appRoot, ing) + abu, _ := parser.GetBoolAnnotation("add-base-url", ing, a.r) + bus, _ := parser.GetStringAnnotation("base-url-scheme", ing, a.r) + ar, _ := parser.GetStringAnnotation("app-root", ing, a.r) + return &Config{ Target: rt, AddBaseURL: abu, diff --git a/internal/ingress/annotations/rewrite/main_test.go b/internal/ingress/annotations/rewrite/main_test.go index 8e62ec49e..7b0f9c7c1 100644 --- a/internal/ingress/annotations/rewrite/main_test.go +++ b/internal/ingress/annotations/rewrite/main_test.go @@ -25,6 +25,7 @@ import ( "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/ingress-nginx/internal/ingress/defaults" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) const ( @@ -67,6 +68,7 @@ func buildIngress() *extensions.Ingress { } type mockBackend struct { + resolver.Mock redirect bool } @@ -86,7 +88,7 @@ func TestRedirect(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[rewriteTo] = defRoute + data["nginx/rewrite-target"] = defRoute ing.SetAnnotations(data) i, err := NewParser(mockBackend{}).Parse(ing) @@ -106,10 +108,10 @@ func TestSSLRedirect(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[rewriteTo] = defRoute + data["nginx/rewrite-target"] = defRoute ing.SetAnnotations(data) - i, _ := NewParser(mockBackend{true}).Parse(ing) + i, _ := NewParser(mockBackend{redirect: true}).Parse(ing) redirect, ok := i.(*Config) if !ok { t.Errorf("expected a Redirect type") @@ -118,10 +120,10 @@ func TestSSLRedirect(t *testing.T) { t.Errorf("Expected true but returned false") } - data[sslRedirect] = "false" + data["nginx/ssl-redirect"] = "false" ing.SetAnnotations(data) - i, _ = NewParser(mockBackend{false}).Parse(ing) + i, _ = NewParser(mockBackend{redirect: false}).Parse(ing) redirect, ok = i.(*Config) if !ok { t.Errorf("expected a Redirect type") @@ -135,10 +137,10 @@ func TestForceSSLRedirect(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[rewriteTo] = defRoute + data["nginx/rewrite-target"] = defRoute ing.SetAnnotations(data) - i, _ := NewParser(mockBackend{true}).Parse(ing) + i, _ := NewParser(mockBackend{redirect: true}).Parse(ing) redirect, ok := i.(*Config) if !ok { t.Errorf("expected a Redirect type") @@ -147,10 +149,10 @@ func TestForceSSLRedirect(t *testing.T) { t.Errorf("Expected false but returned true") } - data[forceSSLRedirect] = "true" + data["nginx/force-ssl-redirect"] = "true" ing.SetAnnotations(data) - i, _ = NewParser(mockBackend{false}).Parse(ing) + i, _ = NewParser(mockBackend{redirect: false}).Parse(ing) redirect, ok = i.(*Config) if !ok { t.Errorf("expected a Redirect type") @@ -163,10 +165,10 @@ func TestAppRoot(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[appRoot] = "/app1" + data["nginx/app-root"] = "/app1" ing.SetAnnotations(data) - i, _ := NewParser(mockBackend{true}).Parse(ing) + i, _ := NewParser(mockBackend{redirect: true}).Parse(ing) redirect, ok := i.(*Config) if !ok { t.Errorf("expected a App Context") diff --git a/internal/ingress/annotations/secureupstream/main.go b/internal/ingress/annotations/secureupstream/main.go index 95439ba1a..c2d5082e7 100644 --- a/internal/ingress/annotations/secureupstream/main.go +++ b/internal/ingress/annotations/secureupstream/main.go @@ -26,11 +26,6 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) -const ( - secureUpstream = "ingress.kubernetes.io/secure-backends" - secureVerifyCASecret = "ingress.kubernetes.io/secure-verify-ca-secret" -) - // Config describes SSL backend configuration type Config struct { Secure bool `json:"secure"` @@ -38,21 +33,19 @@ type Config struct { } type su struct { - certResolver resolver.AuthCertificate + r resolver.Resolver } // NewParser creates a new secure upstream annotation parser -func NewParser(resolver resolver.AuthCertificate) parser.IngressAnnotation { - return su{ - certResolver: resolver, - } +func NewParser(r resolver.Resolver) parser.IngressAnnotation { + return su{r} } // Parse parses the annotations contained in the ingress // rule used to indicate if the upstream servers should use SSL func (a su) Parse(ing *extensions.Ingress) (interface{}, error) { - s, _ := parser.GetBoolAnnotation(secureUpstream, ing) - ca, _ := parser.GetStringAnnotation(secureVerifyCASecret, ing) + s, _ := parser.GetBoolAnnotation("secure-backends", ing, a.r) + ca, _ := parser.GetStringAnnotation("secure-verify-ca-secret", ing, a.r) secure := &Config{ Secure: s, CACert: resolver.AuthSSLCert{}, @@ -64,7 +57,7 @@ func (a su) Parse(ing *extensions.Ingress) (interface{}, error) { if ca == "" { return secure, nil } - caCert, err := a.certResolver.GetAuthCertificate(fmt.Sprintf("%v/%v", ing.Namespace, ca)) + caCert, err := a.r.GetAuthCertificate(fmt.Sprintf("%v/%v", ing.Namespace, ca)) if err != nil { return secure, errors.Wrap(err, "error obtaining certificate") } diff --git a/internal/ingress/annotations/secureupstream/main_test.go b/internal/ingress/annotations/secureupstream/main_test.go index 390b38485..6563c8c6e 100644 --- a/internal/ingress/annotations/secureupstream/main_test.go +++ b/internal/ingress/annotations/secureupstream/main_test.go @@ -64,6 +64,7 @@ func buildIngress() *extensions.Ingress { } type mockCfg struct { + resolver.Mock certs map[string]resolver.AuthSSLCert } @@ -77,8 +78,8 @@ func (cfg mockCfg) GetAuthCertificate(secret string) (*resolver.AuthSSLCert, err func TestAnnotations(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[secureUpstream] = "true" - data[secureVerifyCASecret] = "secure-verify-ca" + data["nginx/secure-backends"] = "true" + data["nginx/secure-verify-ca-secret"] = "secure-verify-ca" ing.SetAnnotations(data) _, err := NewParser(mockCfg{ @@ -94,8 +95,8 @@ func TestAnnotations(t *testing.T) { func TestSecretNotFound(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[secureUpstream] = "true" - data[secureVerifyCASecret] = "secure-verify-ca" + data["nginx/secure-backends"] = "true" + data["nginx/secure-verify-ca-secret"] = "secure-verify-ca" ing.SetAnnotations(data) _, err := NewParser(mockCfg{}).Parse(ing) if err == nil { @@ -106,8 +107,8 @@ func TestSecretNotFound(t *testing.T) { func TestSecretOnNonSecure(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[secureUpstream] = "false" - data[secureVerifyCASecret] = "secure-verify-ca" + data["nginx/secure-backends"] = "false" + data["nginx/secure-verify-ca-secret"] = "secure-verify-ca" ing.SetAnnotations(data) _, err := NewParser(mockCfg{ certs: map[string]resolver.AuthSSLCert{ diff --git a/internal/ingress/annotations/serversnippet/main.go b/internal/ingress/annotations/serversnippet/main.go index 969c2eee5..d6830d8fe 100644 --- a/internal/ingress/annotations/serversnippet/main.go +++ b/internal/ingress/annotations/serversnippet/main.go @@ -20,23 +20,21 @@ import ( extensions "k8s.io/api/extensions/v1beta1" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" -) - -const ( - annotation = "ingress.kubernetes.io/server-snippet" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) type serverSnippet struct { + r resolver.Resolver } // NewParser creates a new server snippet annotation parser -func NewParser() parser.IngressAnnotation { - return serverSnippet{} +func NewParser(r resolver.Resolver) parser.IngressAnnotation { + return serverSnippet{r} } // Parse parses the annotations contained in the ingress rule // used to indicate if the location/s contains a fragment of // configuration to be included inside the paths of the rules func (a serverSnippet) Parse(ing *extensions.Ingress) (interface{}, error) { - return parser.GetStringAnnotation(annotation, ing) + return parser.GetStringAnnotation("server-snippet", ing, a.r) } diff --git a/internal/ingress/annotations/serversnippet/main_test.go b/internal/ingress/annotations/serversnippet/main_test.go index 1a4d51bed..4d17e5e49 100644 --- a/internal/ingress/annotations/serversnippet/main_test.go +++ b/internal/ingress/annotations/serversnippet/main_test.go @@ -22,10 +22,13 @@ import ( api "k8s.io/api/core/v1" extensions "k8s.io/api/extensions/v1beta1" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) func TestParse(t *testing.T) { - ap := NewParser() + annotation := "nginx/server-snippet" + + ap := NewParser(&resolver.Mock{}) if ap == nil { t.Fatalf("expected a parser.IngressAnnotation but returned nil") } diff --git a/internal/ingress/annotations/serviceupstream/main.go b/internal/ingress/annotations/serviceupstream/main.go index a1d9a5a9d..a8386edb6 100644 --- a/internal/ingress/annotations/serviceupstream/main.go +++ b/internal/ingress/annotations/serviceupstream/main.go @@ -18,21 +18,20 @@ package serviceupstream import ( extensions "k8s.io/api/extensions/v1beta1" - "k8s.io/ingress-nginx/internal/ingress/annotations/parser" -) -const ( - annotationServiceUpstream = "ingress.kubernetes.io/service-upstream" + "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) type serviceUpstream struct { + r resolver.Resolver } // NewParser creates a new serviceUpstream annotation parser -func NewParser() parser.IngressAnnotation { - return serviceUpstream{} +func NewParser(r resolver.Resolver) parser.IngressAnnotation { + return serviceUpstream{r} } func (s serviceUpstream) Parse(ing *extensions.Ingress) (interface{}, error) { - return parser.GetBoolAnnotation(annotationServiceUpstream, ing) + return parser.GetBoolAnnotation("service-upstream", ing, s.r) } diff --git a/internal/ingress/annotations/serviceupstream/main_test.go b/internal/ingress/annotations/serviceupstream/main_test.go index 9dcfdece6..0b196ca0f 100644 --- a/internal/ingress/annotations/serviceupstream/main_test.go +++ b/internal/ingress/annotations/serviceupstream/main_test.go @@ -23,6 +23,7 @@ import ( extensions "k8s.io/api/extensions/v1beta1" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) func buildIngress() *extensions.Ingress { @@ -64,10 +65,10 @@ func TestIngressAnnotationServiceUpstreamEnabled(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[annotationServiceUpstream] = "true" + data["nginx/service-upstream"] = "true" ing.SetAnnotations(data) - val, _ := NewParser().Parse(ing) + val, _ := NewParser(&resolver.Mock{}).Parse(ing) enabled, ok := val.(bool) if !ok { t.Errorf("expected a bool type") @@ -83,10 +84,10 @@ func TestIngressAnnotationServiceUpstreamSetFalse(t *testing.T) { // Test with explicitly set to false data := map[string]string{} - data[annotationServiceUpstream] = "false" + data["nginx/service-upstream"] = "false" ing.SetAnnotations(data) - val, _ := NewParser().Parse(ing) + val, _ := NewParser(&resolver.Mock{}).Parse(ing) enabled, ok := val.(bool) if !ok { t.Errorf("expected a bool type") @@ -100,7 +101,7 @@ func TestIngressAnnotationServiceUpstreamSetFalse(t *testing.T) { data = map[string]string{} ing.SetAnnotations(data) - val, _ = NewParser().Parse(ing) + val, _ = NewParser(&resolver.Mock{}).Parse(ing) enabled, ok = val.(bool) if !ok { t.Errorf("expected a bool type") diff --git a/internal/ingress/annotations/sessionaffinity/main.go b/internal/ingress/annotations/sessionaffinity/main.go index b32009f55..fd4bceeb4 100644 --- a/internal/ingress/annotations/sessionaffinity/main.go +++ b/internal/ingress/annotations/sessionaffinity/main.go @@ -24,17 +24,20 @@ import ( extensions "k8s.io/api/extensions/v1beta1" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) const ( - annotationAffinityType = "ingress.kubernetes.io/affinity" + annotationAffinityType = "affinity" // If a cookie with this name exists, // its value is used as an index into the list of available backends. - annotationAffinityCookieName = "ingress.kubernetes.io/session-cookie-name" - defaultAffinityCookieName = "INGRESSCOOKIE" + annotationAffinityCookieName = "session-cookie-name" + + defaultAffinityCookieName = "INGRESSCOOKIE" + // This is the algorithm used by nginx to generate a value for the session cookie, if // one isn't supplied and affinity is set to "cookie". - annotationAffinityCookieHash = "ingress.kubernetes.io/session-cookie-hash" + annotationAffinityCookieHash = "session-cookie-hash" defaultAffinityCookieHash = "md5" ) @@ -59,16 +62,15 @@ type Cookie struct { // cookieAffinityParse gets the annotation values related to Cookie Affinity // It also sets default values when no value or incorrect value is found -func cookieAffinityParse(ing *extensions.Ingress) *Cookie { - - sn, err := parser.GetStringAnnotation(annotationAffinityCookieName, ing) +func (a affinity) cookieAffinityParse(ing *extensions.Ingress) *Cookie { + sn, err := parser.GetStringAnnotation(annotationAffinityCookieName, ing, a.r) if err != nil || sn == "" { glog.V(3).Infof("Ingress %v: No value found in annotation %v. Using the default %v", ing.Name, annotationAffinityCookieName, defaultAffinityCookieName) sn = defaultAffinityCookieName } - sh, err := parser.GetStringAnnotation(annotationAffinityCookieHash, ing) + sh, err := parser.GetStringAnnotation(annotationAffinityCookieHash, ing, a.r) if err != nil || !affinityCookieHashRegex.MatchString(sh) { glog.V(3).Infof("Invalid or no annotation value found in Ingress %v: %v. Setting it to default %v", ing.Name, annotationAffinityCookieHash, defaultAffinityCookieHash) @@ -82,11 +84,12 @@ func cookieAffinityParse(ing *extensions.Ingress) *Cookie { } // NewParser creates a new Affinity annotation parser -func NewParser() parser.IngressAnnotation { - return affinity{} +func NewParser(r resolver.Resolver) parser.IngressAnnotation { + return affinity{r} } type affinity struct { + r resolver.Resolver } // ParseAnnotations parses the annotations contained in the ingress @@ -94,14 +97,14 @@ type affinity struct { func (a affinity) Parse(ing *extensions.Ingress) (interface{}, error) { cookie := &Cookie{} // Check the type of affinity that will be used - at, err := parser.GetStringAnnotation(annotationAffinityType, ing) + at, err := parser.GetStringAnnotation(annotationAffinityType, ing, a.r) if err != nil { at = "" } switch at { case "cookie": - cookie = cookieAffinityParse(ing) + cookie = a.cookieAffinityParse(ing) default: glog.V(3).Infof("No default affinity was found for Ingress %v", ing.Name) diff --git a/internal/ingress/annotations/sessionaffinity/main_test.go b/internal/ingress/annotations/sessionaffinity/main_test.go index 625019827..464435117 100644 --- a/internal/ingress/annotations/sessionaffinity/main_test.go +++ b/internal/ingress/annotations/sessionaffinity/main_test.go @@ -17,12 +17,14 @@ limitations under the License. package sessionaffinity import ( + "fmt" "testing" api "k8s.io/api/core/v1" extensions "k8s.io/api/extensions/v1beta1" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) func buildIngress() *extensions.Ingress { @@ -64,12 +66,12 @@ func TestIngressAffinityCookieConfig(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[annotationAffinityType] = "cookie" - data[annotationAffinityCookieHash] = "sha123" - data[annotationAffinityCookieName] = "INGRESSCOOKIE" + data[fmt.Sprintf("nginx/%v", annotationAffinityType)] = "cookie" + data[fmt.Sprintf("nginx/%v", annotationAffinityCookieHash)] = "sha123" + data[fmt.Sprintf("nginx/%v", annotationAffinityCookieName)] = "INGRESSCOOKIE" ing.SetAnnotations(data) - affin, _ := NewParser().Parse(ing) + affin, _ := NewParser(&resolver.Mock{}).Parse(ing) nginxAffinity, ok := affin.(*Config) if !ok { t.Errorf("expected a Config type") diff --git a/internal/ingress/annotations/snippet/main.go b/internal/ingress/annotations/snippet/main.go index 954c13f6d..b93dbf63b 100644 --- a/internal/ingress/annotations/snippet/main.go +++ b/internal/ingress/annotations/snippet/main.go @@ -20,23 +20,21 @@ import ( extensions "k8s.io/api/extensions/v1beta1" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" -) - -const ( - annotation = "ingress.kubernetes.io/configuration-snippet" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) type snippet struct { + r resolver.Resolver } // NewParser creates a new CORS annotation parser -func NewParser() parser.IngressAnnotation { - return snippet{} +func NewParser(r resolver.Resolver) parser.IngressAnnotation { + return snippet{r} } // Parse parses the annotations contained in the ingress rule // used to indicate if the location/s contains a fragment of // configuration to be included inside the paths of the rules func (a snippet) Parse(ing *extensions.Ingress) (interface{}, error) { - return parser.GetStringAnnotation(annotation, ing) + return parser.GetStringAnnotation("configuration-snippet", ing, a.r) } diff --git a/internal/ingress/annotations/snippet/main_test.go b/internal/ingress/annotations/snippet/main_test.go index b92abfc45..30943379f 100644 --- a/internal/ingress/annotations/snippet/main_test.go +++ b/internal/ingress/annotations/snippet/main_test.go @@ -22,10 +22,13 @@ import ( api "k8s.io/api/core/v1" extensions "k8s.io/api/extensions/v1beta1" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) func TestParse(t *testing.T) { - ap := NewParser() + annotation := "nginx/configuration-snippet" + + ap := NewParser(&resolver.Mock{}) if ap == nil { t.Fatalf("expected a parser.IngressAnnotation but returned nil") } diff --git a/internal/ingress/annotations/sslpassthrough/main.go b/internal/ingress/annotations/sslpassthrough/main.go index c3752f8bd..82b69a170 100644 --- a/internal/ingress/annotations/sslpassthrough/main.go +++ b/internal/ingress/annotations/sslpassthrough/main.go @@ -21,18 +21,16 @@ import ( "k8s.io/ingress-nginx/internal/ingress/annotations/parser" ing_errors "k8s.io/ingress-nginx/internal/ingress/errors" -) - -const ( - passthrough = "ingress.kubernetes.io/ssl-passthrough" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) type sslpt struct { + r resolver.Resolver } // NewParser creates a new SSL passthrough annotation parser -func NewParser() parser.IngressAnnotation { - return sslpt{} +func NewParser(r resolver.Resolver) parser.IngressAnnotation { + return sslpt{r} } // ParseAnnotations parses the annotations contained in the ingress @@ -42,5 +40,5 @@ func (a sslpt) Parse(ing *extensions.Ingress) (interface{}, error) { return false, ing_errors.ErrMissingAnnotations } - return parser.GetBoolAnnotation(passthrough, ing) + return parser.GetBoolAnnotation("ssl-passthrough", ing, a.r) } diff --git a/internal/ingress/annotations/sslpassthrough/main_test.go b/internal/ingress/annotations/sslpassthrough/main_test.go index bf3e083d8..0320c007e 100644 --- a/internal/ingress/annotations/sslpassthrough/main_test.go +++ b/internal/ingress/annotations/sslpassthrough/main_test.go @@ -22,6 +22,7 @@ import ( api "k8s.io/api/core/v1" extensions "k8s.io/api/extensions/v1beta1" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/ingress-nginx/internal/ingress/resolver" "k8s.io/apimachinery/pkg/util/intstr" ) @@ -44,16 +45,16 @@ func buildIngress() *extensions.Ingress { func TestParseAnnotations(t *testing.T) { ing := buildIngress() - _, err := NewParser().Parse(ing) + _, err := NewParser(&resolver.Mock{}).Parse(ing) if err == nil { t.Errorf("unexpected error: %v", err) } data := map[string]string{} - data[passthrough] = "true" + data["nginx/ssl-passthrough"] = "true" ing.SetAnnotations(data) // test ingress using the annotation without a TLS section - _, err = NewParser().Parse(ing) + _, err = NewParser(&resolver.Mock{}).Parse(ing) if err != nil { t.Errorf("unexpected error parsing ingress with sslpassthrough") } @@ -64,7 +65,7 @@ func TestParseAnnotations(t *testing.T) { Hosts: []string{"foo.bar.com"}, }, } - i, err := NewParser().Parse(ing) + i, err := NewParser(&resolver.Mock{}).Parse(ing) if err != nil { t.Errorf("expected error parsing ingress with sslpassthrough") } diff --git a/internal/ingress/annotations/upstreamhashby/main.go b/internal/ingress/annotations/upstreamhashby/main.go index c29f5cbbb..b543070a0 100644 --- a/internal/ingress/annotations/upstreamhashby/main.go +++ b/internal/ingress/annotations/upstreamhashby/main.go @@ -20,23 +20,21 @@ import ( extensions "k8s.io/api/extensions/v1beta1" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" -) - -const ( - annotation = "ingress.kubernetes.io/upstream-hash-by" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) type upstreamhashby struct { + r resolver.Resolver } // NewParser creates a new CORS annotation parser -func NewParser() parser.IngressAnnotation { - return upstreamhashby{} +func NewParser(r resolver.Resolver) parser.IngressAnnotation { + return upstreamhashby{r} } // Parse parses the annotations contained in the ingress rule // used to indicate if the location/s contains a fragment of // configuration to be included inside the paths of the rules func (a upstreamhashby) Parse(ing *extensions.Ingress) (interface{}, error) { - return parser.GetStringAnnotation(annotation, ing) + return parser.GetStringAnnotation("upstream-hash-by", ing, a.r) } diff --git a/internal/ingress/annotations/upstreamhashby/main_test.go b/internal/ingress/annotations/upstreamhashby/main_test.go index ad5afafc8..5507a8c7f 100644 --- a/internal/ingress/annotations/upstreamhashby/main_test.go +++ b/internal/ingress/annotations/upstreamhashby/main_test.go @@ -22,10 +22,13 @@ import ( api "k8s.io/api/core/v1" extensions "k8s.io/api/extensions/v1beta1" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) func TestParse(t *testing.T) { - ap := NewParser() + annotation := "nginx/upstream-hash-by" + + ap := NewParser(&resolver.Mock{}) if ap == nil { t.Fatalf("expected a parser.IngressAnnotation but returned nil") } diff --git a/internal/ingress/annotations/upstreamvhost/main.go b/internal/ingress/annotations/upstreamvhost/main.go index c702d621a..02c1e96cf 100644 --- a/internal/ingress/annotations/upstreamvhost/main.go +++ b/internal/ingress/annotations/upstreamvhost/main.go @@ -20,23 +20,21 @@ import ( extensions "k8s.io/api/extensions/v1beta1" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" -) - -const ( - annotation = "ingress.kubernetes.io/upstream-vhost" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) type upstreamVhost struct { + r resolver.Resolver } // NewParser creates a new upstream VHost annotation parser -func NewParser() parser.IngressAnnotation { - return upstreamVhost{} +func NewParser(r resolver.Resolver) parser.IngressAnnotation { + return upstreamVhost{r} } // Parse parses the annotations contained in the ingress rule // used to indicate if the location/s contains a fragment of // configuration to be included inside the paths of the rules func (a upstreamVhost) Parse(ing *extensions.Ingress) (interface{}, error) { - return parser.GetStringAnnotation(annotation, ing) + return parser.GetStringAnnotation("upstream-vhost", ing, a.r) } diff --git a/internal/ingress/annotations/vtsfilterkey/main.go b/internal/ingress/annotations/vtsfilterkey/main.go index 809187fae..41288e291 100644 --- a/internal/ingress/annotations/vtsfilterkey/main.go +++ b/internal/ingress/annotations/vtsfilterkey/main.go @@ -20,23 +20,21 @@ import ( extensions "k8s.io/api/extensions/v1beta1" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" -) - -const ( - annotation = "ingress.kubernetes.io/vts-filter-key" + "k8s.io/ingress-nginx/internal/ingress/resolver" ) type vtsFilterKey struct { + r resolver.Resolver } // NewParser creates a new vts filter key annotation parser -func NewParser() parser.IngressAnnotation { - return vtsFilterKey{} +func NewParser(r resolver.Resolver) parser.IngressAnnotation { + return vtsFilterKey{r} } // Parse parses the annotations contained in the ingress rule // used to indicate if the location/s contains a fragment of // configuration to be included inside the paths of the rules func (a vtsFilterKey) Parse(ing *extensions.Ingress) (interface{}, error) { - return parser.GetStringAnnotation(annotation, ing) + return parser.GetStringAnnotation("vts-filter-key", ing, a.r) } diff --git a/internal/ingress/controller/backend_ssl.go b/internal/ingress/controller/backend_ssl.go index a1e3b4f1e..272b24c37 100644 --- a/internal/ingress/controller/backend_ssl.go +++ b/internal/ingress/controller/backend_ssl.go @@ -92,7 +92,7 @@ func (ic *NGINXController) getPemCertificate(secretName string) (*ingress.SSLCer } // If 'ca.crt' is also present, it will allow this secret to be used in the - // 'ingress.kubernetes.io/auth-tls-secret' annotation + // 'nginx.ingress.kubernetes.io/auth-tls-secret' annotation s, err = ssl.AddOrUpdateCertAndKey(nsSecName, cert, key, ca) if err != nil { return nil, fmt.Errorf("unexpected error creating pem file: %v", err) @@ -145,7 +145,7 @@ func (ic *NGINXController) checkMissingSecrets() { } } - key, _ := parser.GetStringAnnotation("ingress.kubernetes.io/auth-tls-secret", ing) + key, _ := parser.GetStringAnnotation("auth-tls-secret", ing, ic) if key == "" { continue } diff --git a/internal/ingress/controller/controller.go b/internal/ingress/controller/controller.go index 2861f9f91..b22007f56 100644 --- a/internal/ingress/controller/controller.go +++ b/internal/ingress/controller/controller.go @@ -66,6 +66,8 @@ func init() { // Configuration contains all the settings required by an Ingress controller type Configuration struct { + AnnotationsPrefix string + APIServerHost string KubeConfigFile string Client clientset.Interface @@ -133,6 +135,11 @@ func (n NGINXController) GetService(name string) (*apiv1.Service, error) { return n.listers.Service.GetByName(name) } +// GetAnnotationWithPrefix returns the prefix of ingress annotations +func (n NGINXController) GetAnnotationWithPrefix(suffix string) string { + return fmt.Sprintf("%v/%v", n.cfg.AnnotationsPrefix, suffix) +} + // sync collects all the pieces required to assemble the configuration file and // then sends the content to the backend (OnUpdate) receiving the populated // template as response reloading the backend if is required. @@ -1156,7 +1163,7 @@ func (n *NGINXController) readSecrets(ing *extensions.Ingress) { n.syncSecret(key) } - key, _ := parser.GetStringAnnotation("ingress.kubernetes.io/auth-tls-secret", ing) + key, _ := parser.GetStringAnnotation("auth-tls-secret", ing, n) if key == "" { return } diff --git a/internal/ingress/controller/listers.go b/internal/ingress/controller/listers.go index bdfd5931b..8149891b4 100644 --- a/internal/ingress/controller/listers.go +++ b/internal/ingress/controller/listers.go @@ -66,7 +66,7 @@ func (n *NGINXController) createListers(stopCh chan struct{}) (*ingress.StoreLis AddFunc: func(obj interface{}) { addIng := obj.(*extensions.Ingress) if !class.IsValid(addIng, n.cfg.IngressClass, defIngressClass) { - a, _ := parser.GetStringAnnotation(class.IngressKey, addIng) + a, _ := parser.GetStringAnnotation(class.IngressKey, addIng, n) glog.Infof("ignoring add for ingress %v based on annotation %v with value %v", addIng.Name, class.IngressKey, a) return } diff --git a/internal/ingress/controller/nginx.go b/internal/ingress/controller/nginx.go index 7417e278b..b88002fec 100644 --- a/internal/ingress/controller/nginx.go +++ b/internal/ingress/controller/nginx.go @@ -246,7 +246,7 @@ func (n *NGINXController) Start() { ing := obj.(*extensions.Ingress) if !class.IsValid(ing, n.cfg.IngressClass, n.cfg.DefaultIngressClass) { - a, _ := parser.GetStringAnnotation(class.IngressKey, ing) + a, _ := parser.GetStringAnnotation(class.IngressKey, ing, n) glog.Infof("ignoring add for ingress %v based on annotation %v with value %v", ing.Name, class.IngressKey, a) continue } diff --git a/internal/ingress/controller/template/template.go b/internal/ingress/controller/template/template.go index 078a05a0e..b5cea55e6 100644 --- a/internal/ingress/controller/template/template.go +++ b/internal/ingress/controller/template/template.go @@ -193,7 +193,7 @@ func buildResolvers(input interface{}) string { } // buildLocation produces the location string, if the ingress has redirects -// (specified through the ingress.kubernetes.io/rewrite-to annotation) +// (specified through the nginx.ingress.kubernetes.io/rewrite-to annotation) func buildLocation(input interface{}) string { location, ok := input.(*ingress.Location) if !ok { @@ -268,8 +268,8 @@ func buildLogFormatUpstream(input interface{}) string { } // buildProxyPass produces the proxy pass string, if the ingress has redirects -// (specified through the ingress.kubernetes.io/rewrite-to annotation) -// If the annotation ingress.kubernetes.io/add-base-url:"true" is specified it will +// (specified through the nginx.ingress.kubernetes.io/rewrite-to 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 { backends, ok := b.([]*ingress.Backend) diff --git a/internal/ingress/resolver/main.go b/internal/ingress/resolver/main.go index 61f91518e..9fd43828f 100644 --- a/internal/ingress/resolver/main.go +++ b/internal/ingress/resolver/main.go @@ -22,29 +22,24 @@ import ( "k8s.io/ingress-nginx/internal/ingress/defaults" ) -// DefaultBackend has a method that returns the backend -// that must be used as default -type DefaultBackend interface { +// Resolver is an interface that knows how to extract information from a controller +type Resolver interface { + // GetDefaultBackend returns the backend that must be used as default GetDefaultBackend() defaults.Backend -} -// Secret has a method that searches for secrets contenating -// the namespace and name using a the character / -type Secret interface { + // GetSecret searches for secrets contenating the namespace and name using a the character / GetSecret(string) (*apiv1.Secret, error) -} -// AuthCertificate resolves a given secret name into an SSL certificate. -// The secret must contain 3 keys named: -// ca.crt: contains the certificate chain used for authentication -type AuthCertificate interface { + // GetAuthCertificate resolves a given secret name into an SSL certificate. + // The secret must contain 3 keys named: + // ca.crt: contains the certificate chain used for authentication GetAuthCertificate(string) (*AuthSSLCert, error) -} -// Service has a method that searches for services contenating -// the namespace and name using a the character / -type Service interface { + // GetService searches for services contenating the namespace and name using a the character / GetService(string) (*apiv1.Service, error) + + // GetAnnotationWithPrefix returns the prefix of the Ingress annotations + GetAnnotationWithPrefix(suffix string) string } // AuthSSLCert contains the necessary information to do certificate based diff --git a/internal/ingress/resolver/mock.go b/internal/ingress/resolver/mock.go new file mode 100644 index 000000000..7a11972b9 --- /dev/null +++ b/internal/ingress/resolver/mock.go @@ -0,0 +1,56 @@ +/* +Copyright 2017 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package resolver + +import ( + "fmt" + + apiv1 "k8s.io/api/core/v1" + + "k8s.io/ingress-nginx/internal/ingress/defaults" +) + +// Mock implements the Resolver interface +type Mock struct { +} + +// GetDefaultBackend returns the backend that must be used as default +func (m Mock) GetDefaultBackend() defaults.Backend { + return defaults.Backend{} +} + +// GetSecret searches for secrets contenating the namespace and name using a the character / +func (m Mock) GetSecret(string) (*apiv1.Secret, error) { + return nil, nil +} + +// GetAuthCertificate resolves a given secret name into an SSL certificate. +// The secret must contain 3 keys named: +// ca.crt: contains the certificate chain used for authentication +func (m Mock) GetAuthCertificate(string) (*AuthSSLCert, error) { + return nil, nil +} + +// GetService searches for services contenating the namespace and name using a the character / +func (m Mock) GetService(string) (*apiv1.Service, error) { + return nil, nil +} + +// GetAnnotationWithPrefix returns the prefix of the Ingress annotations +func (m Mock) GetAnnotationWithPrefix(name string) string { + return fmt.Sprintf("nginx/%v", name) +} From d4fd127a1f0fa8572d47e87791e6935bffce9a81 Mon Sep 17 00:00:00 2001 From: Manuel de Brito Fontes Date: Wed, 8 Nov 2017 18:36:03 -0300 Subject: [PATCH 5/6] Add missing field --- internal/ingress/annotations/annotations.go | 1 + internal/ingress/controller/controller.go | 2 ++ 2 files changed, 3 insertions(+) diff --git a/internal/ingress/annotations/annotations.go b/internal/ingress/annotations/annotations.go index a12c2cc44..0ec0db8f4 100644 --- a/internal/ingress/annotations/annotations.go +++ b/internal/ingress/annotations/annotations.go @@ -64,6 +64,7 @@ type Ingress struct { ConfigurationSnippet string CorsConfig cors.Config DefaultBackend string + Denied error ExternalAuth authreq.Config HealthCheck healthcheck.Config Proxy proxy.Config diff --git a/internal/ingress/controller/controller.go b/internal/ingress/controller/controller.go index b22007f56..d71d4bfbd 100644 --- a/internal/ingress/controller/controller.go +++ b/internal/ingress/controller/controller.go @@ -478,6 +478,7 @@ func (n *NGINXController) getBackendServers(ingresses []*extensions.Ingress) ([] loc.UpstreamVhost = anns.UpstreamVhost loc.VtsFilterKey = anns.VtsFilterKey loc.Whitelist = anns.Whitelist + loc.Denied = anns.Denied if loc.Redirect.FromToWWW { server.RedirectFromToWWW = true @@ -507,6 +508,7 @@ func (n *NGINXController) getBackendServers(ingresses []*extensions.Ingress) ([] UpstreamVhost: anns.UpstreamVhost, VtsFilterKey: anns.VtsFilterKey, Whitelist: anns.Whitelist, + Denied: anns.Denied, } if loc.Redirect.FromToWWW { From 4c1c707e9c802703939ed05a40b205b42c202b20 Mon Sep 17 00:00:00 2001 From: Manuel de Brito Fontes Date: Thu, 9 Nov 2017 23:00:38 -0300 Subject: [PATCH 6/6] Add tests for alias annotation --- internal/ingress/controller/controller.go | 3 +- test/e2e/annotations/alias.go | 150 +++++++++++++++++++++ test/e2e/annotations/auth.go | 15 +++ test/e2e/defaultbackend/default_backend.go | 47 +++---- test/e2e/defaultbackend/ssl.go | 34 ++--- test/e2e/e2e.go | 1 + test/e2e/framework/echo.go | 118 ++++++++++++++++ test/e2e/framework/framework.go | 30 ++++- test/e2e/framework/k8s.go | 95 +++++++++++++ test/e2e/framework/util.go | 43 +++++- 10 files changed, 479 insertions(+), 57 deletions(-) create mode 100644 test/e2e/annotations/alias.go create mode 100644 test/e2e/annotations/auth.go create mode 100644 test/e2e/framework/echo.go create mode 100644 test/e2e/framework/k8s.go diff --git a/internal/ingress/controller/controller.go b/internal/ingress/controller/controller.go index d71d4bfbd..0aece8cf5 100644 --- a/internal/ingress/controller/controller.go +++ b/internal/ingress/controller/controller.go @@ -1016,8 +1016,7 @@ func (n *NGINXController) createServers(data []*extensions.Ingress, } if !found { - glog.Warningf("ingress %v/%v for host %v contains a TLS section but none of the host match", - ing.Namespace, ing.Name, host) + // does not contains a TLS section but none of the host match continue } diff --git a/test/e2e/annotations/alias.go b/test/e2e/annotations/alias.go new file mode 100644 index 000000000..c0fb4b5d0 --- /dev/null +++ b/test/e2e/annotations/alias.go @@ -0,0 +1,150 @@ +/* +Copyright 2017 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package annotations + +import ( + "fmt" + "net/http" + + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" + "github.com/parnurzeal/gorequest" + + v1beta1 "k8s.io/api/extensions/v1beta1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/intstr" + + "k8s.io/ingress-nginx/test/e2e/framework" +) + +var _ = framework.IngressNginxDescribe("Annotations - Alias", func() { + f := framework.NewDefaultFramework("alias") + + BeforeEach(func() { + err := f.NewEchoDeployment() + Expect(err).NotTo(HaveOccurred()) + }) + + AfterEach(func() { + }) + + It("should return status code 200 for host 'foo' and 404 for 'bar'", func() { + host := "foo" + + ing, err := f.EnsureIngress(&v1beta1.Ingress{ + ObjectMeta: metav1.ObjectMeta{ + Name: host, + Namespace: f.Namespace.Name, + }, + Spec: v1beta1.IngressSpec{ + Rules: []v1beta1.IngressRule{ + { + Host: host, + IngressRuleValue: v1beta1.IngressRuleValue{ + HTTP: &v1beta1.HTTPIngressRuleValue{ + Paths: []v1beta1.HTTPIngressPath{ + { + Path: "/", + Backend: v1beta1.IngressBackend{ + ServiceName: "http-svc", + ServicePort: intstr.FromInt(80), + }, + }, + }, + }, + }, + }, + }, + }, + }) + + Expect(err).NotTo(HaveOccurred()) + Expect(ing).NotTo(BeNil()) + + err = f.WaitForNginxServer(host) + Expect(err).NotTo(HaveOccurred()) + + resp, body, errs := gorequest.New(). + Get(f.NginxHTTPURL). + Set("Host", host). + End() + + Expect(len(errs)).Should(BeNumerically("==", 0)) + Expect(resp.StatusCode).Should(Equal(http.StatusOK)) + Expect(body).Should(ContainSubstring(fmt.Sprintf("host=%v", host))) + + resp, body, errs = gorequest.New(). + Get(f.NginxHTTPURL). + Set("Host", "bar"). + End() + + Expect(len(errs)).Should(BeNumerically("==", 0)) + Expect(resp.StatusCode).Should(Equal(http.StatusNotFound)) + Expect(body).Should(ContainSubstring("default backend - 404")) + }) + + It("should return status code 200 for host 'foo' and 'bar'", func() { + host := "bar" + ing, err := f.EnsureIngress(&v1beta1.Ingress{ + ObjectMeta: metav1.ObjectMeta{ + Name: host, + Namespace: f.Namespace.Name, + Annotations: map[string]string{ + "nginx.ingress.kubernetes.io/server-alias": host, + }, + }, + Spec: v1beta1.IngressSpec{ + Rules: []v1beta1.IngressRule{ + { + Host: "foo", + IngressRuleValue: v1beta1.IngressRuleValue{ + HTTP: &v1beta1.HTTPIngressRuleValue{ + Paths: []v1beta1.HTTPIngressPath{ + { + Path: "/", + Backend: v1beta1.IngressBackend{ + ServiceName: "http-svc", + ServicePort: intstr.FromInt(80), + }, + }, + }, + }, + }, + }, + }, + }, + }) + + Expect(err).NotTo(HaveOccurred()) + Expect(ing).NotTo(BeNil()) + + err = f.WaitForNginxServer(host) + Expect(err).NotTo(HaveOccurred()) + + hosts := []string{"foo", "bar"} + for _, host := range hosts { + resp, body, errs := gorequest.New(). + Get(f.NginxHTTPURL). + Set("Host", host). + End() + + Expect(len(errs)).Should(BeNumerically("==", 0)) + Expect(resp.StatusCode).Should(Equal(http.StatusOK)) + Expect(body).Should(ContainSubstring(fmt.Sprintf("host=%v", host))) + } + }) +}) diff --git a/test/e2e/annotations/auth.go b/test/e2e/annotations/auth.go new file mode 100644 index 000000000..1ee7e1546 --- /dev/null +++ b/test/e2e/annotations/auth.go @@ -0,0 +1,15 @@ +package annotations + +// Tests: +// No auth +// Basic +// 401 +// Realm name +// Auth ok +// Auth error +// Digest +// 401 +// Realm name +// Auth ok +// Auth error +// Check return 403 if there's an error retrieving the secret diff --git a/test/e2e/defaultbackend/default_backend.go b/test/e2e/defaultbackend/default_backend.go index dc07f3841..824a70609 100644 --- a/test/e2e/defaultbackend/default_backend.go +++ b/test/e2e/defaultbackend/default_backend.go @@ -39,14 +39,6 @@ var _ = framework.IngressNginxDescribe("Default backend", func() { }) It("should return 404 sending requests when only a default backend is running", func() { - httpURL, err := f.GetNginxURL(framework.HTTP) - Expect(err).NotTo(HaveOccurred()) - - httpsURL, err := f.GetNginxURL(framework.HTTPS) - Expect(err).NotTo(HaveOccurred()) - - request := gorequest.New() - testCases := []struct { Name string Host string @@ -55,38 +47,39 @@ var _ = framework.IngressNginxDescribe("Default backend", func() { Path string Status int }{ - {"basic HTTP GET request without host to path / should return 404", "", framework.HTTP, "GET", "/", 404}, - {"basic HTTP GET request without host to path /demo should return 404", "", framework.HTTP, "GET", "/demo", 404}, - {"basic HTTPS GET request without host to path / should return 404", "", framework.HTTPS, "GET", "/", 404}, - {"basic HTTPS GET request without host to path /demo should return 404", "", framework.HTTPS, "GET", "/demo", 404}, + {"basic HTTP GET request without host to path / should return 404", "", framework.HTTP, "GET", "/", http.StatusNotFound}, + {"basic HTTP GET request without host to path /demo should return 404", "", framework.HTTP, "GET", "/demo", http.StatusNotFound}, + {"basic HTTPS GET request without host to path / should return 404", "", framework.HTTPS, "GET", "/", http.StatusNotFound}, + {"basic HTTPS GET request without host to path /demo should return 404", "", framework.HTTPS, "GET", "/demo", http.StatusNotFound}, - {"basic HTTP POST request without host to path / should return 404", "", framework.HTTP, "POST", "/", 404}, - {"basic HTTP POST request without host to path /demo should return 404", "", framework.HTTP, "POST", "/demo", 404}, - {"basic HTTPS POST request without host to path / should return 404", "", framework.HTTPS, "POST", "/", 404}, - {"basic HTTPS POST request without host to path /demo should return 404", "", framework.HTTPS, "POST", "/demo", 404}, + {"basic HTTP POST request without host to path / should return 404", "", framework.HTTP, "POST", "/", http.StatusNotFound}, + {"basic HTTP POST request without host to path /demo should return 404", "", framework.HTTP, "POST", "/demo", http.StatusNotFound}, + {"basic HTTPS POST request without host to path / should return 404", "", framework.HTTPS, "POST", "/", http.StatusNotFound}, + {"basic HTTPS POST request without host to path /demo should return 404", "", framework.HTTPS, "POST", "/demo", http.StatusNotFound}, - {"basic HTTP GET request to host foo.bar.com and path / should return 404", " foo.bar.com", framework.HTTP, "GET", "/", 404}, - {"basic HTTP GET request to host foo.bar.com and path /demo should return 404", " foo.bar.com", framework.HTTP, "GET", "/demo", 404}, - {"basic HTTPS GET request to host foo.bar.com and path / should return 404", " foo.bar.com", framework.HTTPS, "GET", "/", 404}, - {"basic HTTPS GET request to host foo.bar.com and path /demo should return 404", " foo.bar.com", framework.HTTPS, "GET", "/demo", 404}, + {"basic HTTP GET request to host foo.bar.com and path / should return 404", " foo.bar.com", framework.HTTP, "GET", "/", http.StatusNotFound}, + {"basic HTTP GET request to host foo.bar.com and path /demo should return 404", " foo.bar.com", framework.HTTP, "GET", "/demo", http.StatusNotFound}, + {"basic HTTPS GET request to host foo.bar.com and path / should return 404", " foo.bar.com", framework.HTTPS, "GET", "/", http.StatusNotFound}, + {"basic HTTPS GET request to host foo.bar.com and path /demo should return 404", " foo.bar.com", framework.HTTPS, "GET", "/demo", http.StatusNotFound}, - {"basic HTTP POST request to host foo.bar.com and path / should return 404", " foo.bar.com", framework.HTTP, "POST", "/", 404}, - {"basic HTTP POST request to host foo.bar.com and path /demo should return 404", " foo.bar.com", framework.HTTP, "POST", "/demo", 404}, - {"basic HTTPS POST request to host foo.bar.com and path / should return 404", " foo.bar.com", framework.HTTPS, "POST", "/", 404}, - {"basic HTTPS POST request to host foo.bar.com and path /demo should return 404", " foo.bar.com", framework.HTTPS, "POST", "/demo", 404}, + {"basic HTTP POST request to host foo.bar.com and path / should return 404", " foo.bar.com", framework.HTTP, "POST", "/", http.StatusNotFound}, + {"basic HTTP POST request to host foo.bar.com and path /demo should return 404", " foo.bar.com", framework.HTTP, "POST", "/demo", http.StatusNotFound}, + {"basic HTTPS POST request to host foo.bar.com and path / should return 404", " foo.bar.com", framework.HTTPS, "POST", "/", http.StatusNotFound}, + {"basic HTTPS POST request to host foo.bar.com and path /demo should return 404", " foo.bar.com", framework.HTTPS, "POST", "/demo", http.StatusNotFound}, } for _, test := range testCases { By(test.Name) - var errs []error + + request := gorequest.New() var cm *gorequest.SuperAgent switch test.Scheme { case framework.HTTP: - cm = request.CustomMethod(test.Method, httpURL) + cm = request.CustomMethod(test.Method, f.NginxHTTPURL) break case framework.HTTPS: - cm = request.CustomMethod(test.Method, httpsURL) + cm = request.CustomMethod(test.Method, f.NginxHTTPSURL) // the default backend uses a self generated certificate cm.Transport = &http.Transport{ TLSClientConfig: &tls.Config{ diff --git a/test/e2e/defaultbackend/ssl.go b/test/e2e/defaultbackend/ssl.go index 8773600cb..49511d491 100644 --- a/test/e2e/defaultbackend/ssl.go +++ b/test/e2e/defaultbackend/ssl.go @@ -18,7 +18,6 @@ package defaultbackend import ( "crypto/tls" - "net/http" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" @@ -37,36 +36,29 @@ var _ = framework.IngressNginxDescribe("Default backend - SSL", func() { }) It("should return a self generated SSL certificate", func() { - httpsURL, err := f.GetNginxURL(framework.HTTPS) - Expect(err).NotTo(HaveOccurred()) - - request := gorequest.New() - By("checking SSL Certificate using the NGINX IP address") - cm := request.Post(httpsURL) - // the default backend uses a self generated certificate - cm.Transport = &http.Transport{ - TLSClientConfig: &tls.Config{ + resp, _, errs := gorequest.New(). + Post(f.NginxHTTPSURL). + TLSClientConfig(&tls.Config{ + // the default backend uses a self generated certificate InsecureSkipVerify: true, - }, - } - resp, _, errs := cm.End() + }).End() + Expect(len(errs)).Should(BeNumerically("==", 0)) Expect(len(resp.TLS.PeerCertificates)).Should(BeNumerically("==", 1)) + for _, pc := range resp.TLS.PeerCertificates { Expect(pc.Issuer.CommonName).Should(Equal("Kubernetes Ingress Controller Fake Certificate")) } By("checking SSL Certificate using the NGINX catch all server") - cm = request.Post(httpsURL) - // the default backend uses a self generated certificate - cm.Transport = &http.Transport{ - TLSClientConfig: &tls.Config{ + resp, _, errs = gorequest.New(). + Post(f.NginxHTTPSURL). + TLSClientConfig(&tls.Config{ + // the default backend uses a self generated certificate InsecureSkipVerify: true, - }, - } - cm.Set("Host", "foo.bar.com") - resp, _, errs = cm.End() + }). + Set("Host", "foo.bar.com").End() Expect(len(errs)).Should(BeNumerically("==", 0)) Expect(len(resp.TLS.PeerCertificates)).Should(BeNumerically("==", 1)) for _, pc := range resp.TLS.PeerCertificates { diff --git a/test/e2e/e2e.go b/test/e2e/e2e.go index b98766c60..4f0601687 100644 --- a/test/e2e/e2e.go +++ b/test/e2e/e2e.go @@ -26,6 +26,7 @@ import ( "k8s.io/apiserver/pkg/util/logs" _ "k8s.io/client-go/plugin/pkg/client/auth" + _ "k8s.io/ingress-nginx/test/e2e/annotations" _ "k8s.io/ingress-nginx/test/e2e/defaultbackend" "k8s.io/ingress-nginx/test/e2e/framework" ) diff --git a/test/e2e/framework/echo.go b/test/e2e/framework/echo.go new file mode 100644 index 000000000..7d9cdc966 --- /dev/null +++ b/test/e2e/framework/echo.go @@ -0,0 +1,118 @@ +/* +Copyright 2017 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package framework + +import ( + "fmt" + "time" + + "github.com/pkg/errors" + + corev1 "k8s.io/api/core/v1" + extensions "k8s.io/api/extensions/v1beta1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/fields" + "k8s.io/apimachinery/pkg/util/intstr" +) + +// NewEchoDeployment creates a new deployment of the echoserver image in a particular namespace +func (f *Framework) NewEchoDeployment() error { + deployment := &extensions.Deployment{ + ObjectMeta: metav1.ObjectMeta{ + Name: "http-svc", + Namespace: f.Namespace.Name, + DeletionGracePeriodSeconds: NewInt64(5), + }, + Spec: extensions.DeploymentSpec{ + Replicas: NewInt32(1), + Selector: &metav1.LabelSelector{ + MatchLabels: map[string]string{ + "app": "http-svc", + }, + }, + Template: corev1.PodTemplateSpec{ + ObjectMeta: metav1.ObjectMeta{ + Labels: map[string]string{ + "app": "http-svc", + }, + }, + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ + { + Name: "http-svc", + Image: "gcr.io/google_containers/echoserver:1.8", + Env: []corev1.EnvVar{}, + Ports: []corev1.ContainerPort{ + { + Name: "http", + ContainerPort: 8080, + }, + }, + }, + }, + }, + }, + }, + } + + d, err := f.EnsureDeployment(deployment) + if err != nil { + return err + } + + if d == nil { + return fmt.Errorf("unexpected error creating deployement for echoserver") + } + + err = f.WaitForPodsReady(10*time.Second, 1, metav1.ListOptions{ + LabelSelector: fields.SelectorFromSet(fields.Set(d.Spec.Template.ObjectMeta.Labels)).String(), + }) + if err != nil { + return errors.Wrap(err, "failed to wait for to become ready") + } + + service := &corev1.Service{ + ObjectMeta: metav1.ObjectMeta{ + Name: "http-svc", + Namespace: f.Namespace.Name, + }, + Spec: corev1.ServiceSpec{ + Ports: []corev1.ServicePort{ + { + Name: "http", + Port: 80, + TargetPort: intstr.FromInt(8080), + Protocol: "TCP", + }, + }, + Selector: map[string]string{ + "app": "http-svc", + }, + }, + } + + s, err := f.EnsureService(service) + if err != nil { + return err + } + + if s == nil { + return fmt.Errorf("unexpected error creating service for echoserver deployment") + } + + return nil +} diff --git a/test/e2e/framework/framework.go b/test/e2e/framework/framework.go index b697b3945..d26c7b07d 100644 --- a/test/e2e/framework/framework.go +++ b/test/e2e/framework/framework.go @@ -17,10 +17,11 @@ import ( "fmt" "os/exec" "strings" + "time" "k8s.io/api/core/v1" apiextcs "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" - meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" . "github.com/onsi/ginkgo" @@ -31,6 +32,11 @@ const ( podName = "test-ingress-controller" ) +const ( + MaxRetry = 200 + NoRetry = 1 +) + type RequestScheme string // These are valid test request schemes. @@ -54,9 +60,12 @@ type Framework struct { // we install a Cleanup action before each test and clear it after. If we // should abort, the AfterSuite hook should run all Cleanup actions. cleanupHandle CleanupActionHandle + + NginxHTTPURL string + NginxHTTPSURL string } -// NewFramework makes a new framework and sets up a BeforeEach/AfterEach for +// NewDefaultFramework makes a new framework and sets up a BeforeEach/AfterEach for // you (you can write additional before/after each functions). func NewDefaultFramework(baseName string) *Framework { f := &Framework{ @@ -83,6 +92,14 @@ func (f *Framework) BeforeEach() { By("Building a namespace api object") f.Namespace, err = CreateKubeNamespace(f.BaseName, f.KubeClientSet) Expect(err).NotTo(HaveOccurred()) + + By("Building NGINX HTTP URL") + f.NginxHTTPURL, err = f.GetNginxURL(HTTP) + Expect(err).NotTo(HaveOccurred()) + + By("Building NGINX HTTPS URL") + f.NginxHTTPSURL, err = f.GetNginxURL(HTTPS) + Expect(err).NotTo(HaveOccurred()) } // AfterEach deletes the namespace, after reading its events. @@ -94,7 +111,7 @@ func (f *Framework) AfterEach() { Expect(err).NotTo(HaveOccurred()) By("Waiting for test namespace to no longer exist") - err = WaitForKubeNamespaceNotExist(f.KubeClientSet, f.Namespace.Name) + err = WaitForNoPodsInNamespace(f.KubeClientSet, f.Namespace.Name) Expect(err).NotTo(HaveOccurred()) } @@ -115,7 +132,7 @@ func (f *Framework) GetNginxIP() (string, error) { // GetNginxPort returns the number of TCP port where NGINX is running func (f *Framework) GetNginxPort(name string) (int, error) { - s, err := f.KubeClientSet.CoreV1().Services("ingress-nginx").Get("ingress-nginx", meta_v1.GetOptions{}) + s, err := f.KubeClientSet.CoreV1().Services("ingress-nginx").Get("ingress-nginx", metav1.GetOptions{}) if err != nil { return -1, err } @@ -143,3 +160,8 @@ func (f *Framework) GetNginxURL(scheme RequestScheme) (string, error) { return fmt.Sprintf("%v://%v:%v", scheme, ip, port), nil } + +func (f *Framework) WaitForNginxServer(name string) error { + time.Sleep(5 * time.Second) + return nil +} diff --git a/test/e2e/framework/k8s.go b/test/e2e/framework/k8s.go new file mode 100644 index 000000000..8ce459fb4 --- /dev/null +++ b/test/e2e/framework/k8s.go @@ -0,0 +1,95 @@ +/* +Copyright 2017 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package framework + +import ( + "time" + + api "k8s.io/api/core/v1" + core "k8s.io/api/core/v1" + extensions "k8s.io/api/extensions/v1beta1" + k8sErrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/wait" +) + +func (f *Framework) EnsureSecret(secret *api.Secret) (*api.Secret, error) { + s, err := f.KubeClientSet.CoreV1().Secrets(secret.Namespace).Create(secret) + if err != nil { + if k8sErrors.IsAlreadyExists(err) { + return f.KubeClientSet.CoreV1().Secrets(secret.Namespace).Update(secret) + } + return nil, err + } + return s, nil +} + +func (f *Framework) EnsureIngress(ingress *extensions.Ingress) (*extensions.Ingress, error) { + s, err := f.KubeClientSet.ExtensionsV1beta1().Ingresses(ingress.Namespace).Update(ingress) + if err != nil { + if k8sErrors.IsNotFound(err) { + return f.KubeClientSet.ExtensionsV1beta1().Ingresses(ingress.Namespace).Create(ingress) + } + return nil, err + } + return s, nil +} + +func (f *Framework) EnsureService(service *core.Service) (*core.Service, error) { + s, err := f.KubeClientSet.CoreV1().Services(service.Namespace).Update(service) + if err != nil { + if k8sErrors.IsNotFound(err) { + return f.KubeClientSet.CoreV1().Services(service.Namespace).Create(service) + } + return nil, err + } + return s, nil +} + +func (f *Framework) EnsureDeployment(deployment *extensions.Deployment) (*extensions.Deployment, error) { + d, err := f.KubeClientSet.Extensions().Deployments(deployment.Namespace).Update(deployment) + if err != nil { + if k8sErrors.IsNotFound(err) { + return f.KubeClientSet.Extensions().Deployments(deployment.Namespace).Create(deployment) + } + return nil, err + } + return d, nil +} + +func (f *Framework) WaitForPodsReady(timeout time.Duration, expectedReplicas int, opts metav1.ListOptions) error { + return wait.Poll(time.Second, timeout, func() (bool, error) { + pl, err := f.KubeClientSet.Core().Pods(f.Namespace.Name).List(opts) + if err != nil { + return false, err + } + + r := 0 + for _, p := range pl.Items { + if p.Status.Phase != core.PodRunning { + continue + } + r++ + } + + if r == expectedReplicas { + return true, nil + } + + return false, nil + }) +} diff --git a/test/e2e/framework/util.go b/test/e2e/framework/util.go index 907539e32..bad785de1 100644 --- a/test/e2e/framework/util.go +++ b/test/e2e/framework/util.go @@ -120,7 +120,11 @@ func CreateKubeNamespace(baseName string, c kubernetes.Interface) (*v1.Namespace } func DeleteKubeNamespace(c kubernetes.Interface, namespace string) error { - return c.Core().Namespaces().Delete(namespace, nil) + deletePolicy := metav1.DeletePropagationForeground + return c.Core().Namespaces().Delete(namespace, &metav1.DeleteOptions{ + GracePeriodSeconds: NewInt64(0), + PropagationPolicy: &deletePolicy, + }) } func ExpectNoError(err error, explain ...interface{}) { @@ -131,7 +135,7 @@ func ExpectNoError(err error, explain ...interface{}) { } func WaitForKubeNamespaceNotExist(c kubernetes.Interface, namespace string) error { - return wait.PollImmediate(Poll, time.Minute*2, namespaceNotExist(c, namespace)) + return wait.PollImmediate(Poll, time.Minute*1, namespaceNotExist(c, namespace)) } func namespaceNotExist(c kubernetes.Interface, namespace string) wait.ConditionFunc { @@ -147,7 +151,28 @@ func namespaceNotExist(c kubernetes.Interface, namespace string) wait.ConditionF } } -// Waits default amount of time (PodStartTimeout) for the specified pod to become running. +func WaitForNoPodsInNamespace(c kubernetes.Interface, namespace string) error { + return wait.PollImmediate(Poll, time.Minute*2, noPodsInNamespace(c, namespace)) +} + +func noPodsInNamespace(c kubernetes.Interface, namespace string) wait.ConditionFunc { + return func() (bool, error) { + items, err := c.CoreV1().Pods(namespace).List(metav1.ListOptions{}) + if apierrors.IsNotFound(err) { + return true, nil + } + if err != nil { + return false, err + } + + if len(items.Items) == 0 { + return true, nil + } + return false, nil + } +} + +// WaitForPodRunningInNamespace waits default amount of time (PodStartTimeout) for the specified pod to become running. // Returns an error if timeout occurs first, or pod goes in to failed state. func WaitForPodRunningInNamespace(c kubernetes.Interface, pod *v1.Pod) error { if pod.Status.Phase == v1.PodRunning { @@ -175,3 +200,15 @@ func podRunning(c kubernetes.Interface, podName, namespace string) wait.Conditio return false, nil } } + +func NewInt32(val int32) *int32 { + p := new(int32) + *p = val + return p +} + +func NewInt64(val int64) *int64 { + p := new(int64) + *p = val + return p +}