import "github.com/projectcontour/contour/internal/dag"
Package dag provides a data model, in the form of a directed acyclic graph, of the relationship between Kubernetes Ingress, Service, and Secret objects.
accessors.go builder.go cache.go conditions.go dag.go extension_processor.go httpproxy_processor.go ingress_processor.go listener_processor.go policy.go secret.go status.go
const CACertificateKey = "ca.crt"
CACertificateKey is the key name for accessing TLS CA certificate bundles in Kubernetes Secrets.
ValidateRegex returns an error if the supplied RE2 regex syntax is invalid.
type Builder struct { // Source is the source of Kubernetes objects // from which to build a DAG. Source KubernetesCache // Processors is the ordered list of Processors to // use to build the DAG. Processors []Processor }
Builder builds a DAG.
Build builds and returns a new DAG by running the configured DAG processors, in order.
type CORSPolicy struct { // Specifies whether the resource allows credentials. AllowCredentials bool // AllowOrigin specifies the origins that will be allowed to do CORS requests. AllowOrigin []string // AllowMethods specifies the content for the *access-control-allow-methods* header. AllowMethods []string // AllowHeaders specifies the content for the *access-control-allow-headers* header. AllowHeaders []string // ExposeHeaders Specifies the content for the *access-control-expose-headers* header. ExposeHeaders []string // MaxAge specifies the content for the *access-control-max-age* header. MaxAge timeout.Setting }
CORSPolicy allows setting the CORS policy
type Cluster struct { // Upstream is the backend Kubernetes service traffic arriving // at this Cluster will be forwarded too. Upstream *Service // The relative weight of this Cluster compared to its siblings. Weight uint32 // The protocol to use to speak to this cluster. Protocol string // UpstreamValidation defines how to verify the backend service's certificate UpstreamValidation *PeerValidationContext // The load balancer type to use when picking a host in the cluster. // See https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/cluster/v3/cluster.proto#enum-config-cluster-v3-cluster-lbpolicy LoadBalancerPolicy string // Cluster http health check policy *HTTPHealthCheckPolicy // Cluster tcp health check policy *TCPHealthCheckPolicy // RequestHeadersPolicy defines how headers are managed during forwarding RequestHeadersPolicy *HeadersPolicy // ResponseHeadersPolicy defines how headers are managed during forwarding ResponseHeadersPolicy *HeadersPolicy // SNI is used when a route proxies an upstream using tls. // SNI describes how the SNI is set on a Cluster and is configured via RequestHeadersPolicy.Host key. // Policies set on service are used before policies set on a route. Otherwise the value of the externalService // is used if the route is configured to proxy to an externalService type. // If the value is not set, then SNI is not changed. SNI string // DNSLookupFamily defines how external names are looked up // When configured as V4, the DNS resolver will only perform a lookup // for addresses in the IPv4 family. If V6 is configured, the DNS resolver // will only perform a lookup for addresses in the IPv6 family. // If AUTO is configured, the DNS resolver will first perform a lookup // for addresses in the IPv6 family and fallback to a lookup for addresses // in the IPv4 family. // Note: This only applies to externalName clusters. DNSLookupFamily string // ClientCertificate is the optional identifier of the TLS secret containing client certificate and // private key to be used when establishing TLS connection to upstream cluster. ClientCertificate *Secret }
Cluster holds the connection specific parameters that apply to traffic routed to an upstream service.
type DAG struct { // StatusCache holds a cache of status updates to send. StatusCache status.Cache // contains filtered or unexported fields }
A DAG represents a directed acyclic graph of objects representing the relationship between Kubernetes Ingress objects, the backend Services, and Secret objects. The DAG models these relationships as Roots and Vertices.
AddRoot appends the given root to the DAG's roots.
func (dag *DAG) EnsureSecureVirtualHost(name string) *SecureVirtualHost
EnsureSecureVirtualHost adds a secure virtual host with the provided name to the DAG if it does not already exist, and returns it.
func (dag *DAG) EnsureService(meta types.NamespacedName, port intstr.IntOrString, cache *KubernetesCache) (*Service, error)
EnsureService looks for a Kubernetes service in the cache matching the provided namespace, name and port, and returns a DAG service for it. If a matching service cannot be found in the cache, an error is returned.
func (dag *DAG) EnsureVirtualHost(name string) *VirtualHost
EnsureVirtualHost adds a virtual host with the provided name to the DAG if it does not already exist, and returns it.
func (dag *DAG) GetExtensionCluster(name string) *ExtensionCluster
GetExtensionCluster returns the extension cluster in the DAG that matches the provided name, or nil if no matching extension cluster is found.
func (dag *DAG) GetExtensionClusters() map[string]*ExtensionCluster
GetExtensionClusters returns all extension clusters in the DAG.
func (dag *DAG) GetSecureVirtualHost(name string) *SecureVirtualHost
GetSecureVirtualHost returns the secure virtual host in the DAG that matches the provided name, or nil if no matching secure virtual host is found.
func (dag *DAG) GetSecureVirtualHosts() map[string]*SecureVirtualHost
GetSecureVirtualHosts returns all secure virtual hosts in the DAG.
GetService returns the service in the DAG that matches the provided namespace, name and port, or nil if no matching service is found.
func (dag *DAG) GetServices() map[RouteServiceName]*Service
GetServices returns all services in the DAG.
func (dag *DAG) GetVirtualHost(name string) *VirtualHost
GetVirtualHost returns the virtual host in the DAG that matches the provided name, or nil if no matching virtual host is found.
func (dag *DAG) GetVirtualHosts() map[string]*VirtualHost
GetVirtualHosts returns all virtual hosts in the DAG.
RemoveRoot removes the given root from the DAG's roots if it exists.
Visit calls fn on each root of this DAG.
type ExtensionCluster struct { // Name is the (globally unique) name of the corresponding Envoy cluster resource. Name string // Upstream is the cluster that receives network traffic. Upstream ServiceCluster // The protocol to use to speak to this cluster. Protocol string // UpstreamValidation defines how to verify the backend service's certificate UpstreamValidation *PeerValidationContext // The load balancer type to use when picking a host in the cluster. // See https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/cluster/v3/cluster.proto#enum-config-cluster-v3-cluster-lbpolicy LoadBalancerPolicy string // TimeoutPolicy specifies how to handle timeouts to this extension. TimeoutPolicy TimeoutPolicy // SNI is used when a route proxies an upstream using TLS. SNI string // ClientCertificate is the optional identifier of the TLS secret containing client certificate and // private key to be used when establishing TLS connection to upstream cluster. ClientCertificate *Secret }
ExtensionCluster generates an Envoy cluster (aka ClusterLoadAssignment) for an ExtensionService resource.
func (e *ExtensionCluster) Visit(f func(Vertex))
Visit processes extension clusters.
type ExtensionServiceProcessor struct { logrus.FieldLogger // ClientCertificate is the optional identifier of the TLS // secret containing client certificate and private key to be // used when establishing TLS connection to upstream cluster. ClientCertificate *types.NamespacedName }
func (p *ExtensionServiceProcessor) Run(dag *DAG, cache *KubernetesCache)
type HTTPHealthCheckPolicy struct { Path string Host string Interval time.Duration Timeout time.Duration UnhealthyThreshold uint32 HealthyThreshold uint32 }
Cluster http health check policy
type HTTPProxyProcessor struct { // DisablePermitInsecure disables the use of the // permitInsecure field in HTTPProxy. DisablePermitInsecure bool // FallbackCertificate is the optional identifier of the // TLS secret to use by default when SNI is not set on a // request. FallbackCertificate *types.NamespacedName // DNSLookupFamily defines how external names are looked up // When configured as V4, the DNS resolver will only perform a lookup // for addresses in the IPv4 family. If V6 is configured, the DNS resolver // will only perform a lookup for addresses in the IPv6 family. // If AUTO is configured, the DNS resolver will first perform a lookup // for addresses in the IPv6 family and fallback to a lookup for addresses // in the IPv4 family. // Note: This only applies to externalName clusters. DNSLookupFamily config.ClusterDNSFamilyType // ClientCertificate is the optional identifier of the TLS secret containing client certificate and // private key to be used when establishing TLS connection to upstream cluster. ClientCertificate *types.NamespacedName // contains filtered or unexported fields }
HTTPProxyProcessor translates HTTPProxies into DAG objects and adds them to the DAG.
func (p *HTTPProxyProcessor) Run(dag *DAG, source *KubernetesCache)
Run translates HTTPProxies into DAG objects and adds them to the DAG.
HeaderMatchCondition matches request headers by MatchType
func (hc *HeaderMatchCondition) String() string
type HeaderValue struct { // Name represents a key of a header Key string // Value represents the value of a header specified by a key Value string }
type HeadersPolicy struct { // HostRewrite defines if a host should be rewritten on upstream requests HostRewrite string Set map[string]string Remove []string }
HeadersPolicy defines how headers are managed during forwarding
type IngressProcessor struct { logrus.FieldLogger // ClientCertificate is the optional identifier of the TLS secret containing client certificate and // private key to be used when establishing TLS connection to upstream cluster. ClientCertificate *types.NamespacedName // contains filtered or unexported fields }
IngressProcessor translates Ingresses into DAG objects and adds them to the DAG.
func (p *IngressProcessor) Run(dag *DAG, source *KubernetesCache)
Run translates Ingresses into DAG objects and adds them to the DAG.
type KubernetesCache struct { // RootNamespaces specifies the namespaces where root // HTTPProxies can be defined. If empty, roots can be defined in any // namespace. RootNamespaces []string // Contour's IngressClass. // If not set, defaults to DEFAULT_INGRESS_CLASS. IngressClass string // Secrets that are referred from the configuration file. ConfiguredSecretRefs []*types.NamespacedName logrus.FieldLogger // contains filtered or unexported fields }
A KubernetesCache holds Kubernetes objects and associated configuration and produces DAG values.
func (kc *KubernetesCache) DelegationPermitted(secret types.NamespacedName, targetNamespace string) bool
DelegationPermitted returns true if the referenced secret has been delegated to the namespace where the ingress object is located.
func (kc *KubernetesCache) Insert(obj interface{}) bool
Insert inserts obj into the KubernetesCache. Insert returns true if the cache accepted the object, or false if the value is not interesting to the cache. If an object with a matching type, name, and namespace exists, it will be overwritten.
func (kc *KubernetesCache) LookupDownstreamValidation(vc *contour_api_v1.DownstreamValidation, namespace string) (*PeerValidationContext, error)
func (kc *KubernetesCache) LookupSecret(name types.NamespacedName, validate func(*v1.Secret) error) (*Secret, error)
LookupSecret returns a Secret if present or nil if the underlying kubernetes secret fails validation or is missing.
func (kc *KubernetesCache) LookupService(meta types.NamespacedName, port intstr.IntOrString) (*v1.Service, v1.ServicePort, error)
LookupService returns the Kubernetes service and port matching the provided parameters, or an error if a match can't be found.
func (kc *KubernetesCache) LookupUpstreamValidation(uv *contour_api_v1.UpstreamValidation, namespace string) (*PeerValidationContext, error)
func (kc *KubernetesCache) Remove(obj interface{}) bool
Remove removes obj from the KubernetesCache. Remove returns a boolean indicating if the cache changed after the remove operation.
type Listener struct { // Address is the TCP address to listen on. // If blank 0.0.0.0, or ::/0 for IPv6, is assumed. Address string // Port is the TCP port to listen on. Port int VirtualHosts []Vertex }
A Listener represents a TCP socket that accepts incoming connections.
type ListenerProcessor struct{}
ListenerProcessor adds an HTTP and an HTTPS listener to the DAG if there are virtual hosts and secure virtual hosts already defined as roots in the DAG.
func (p *ListenerProcessor) Run(dag *DAG, _ *KubernetesCache)
Run adds HTTP and HTTPS listeners to the DAG if there are virtual hosts and secure virtual hosts already defined as roots in the DAG.
type LocalRateLimitPolicy struct { MaxTokens uint32 TokensPerFill uint32 FillInterval time.Duration ResponseStatusCode uint32 ResponseHeadersToAdd map[string]string }
LocalRateLimitPolicy holds local rate limiting parameters.
MirrorPolicy defines the mirroring policy for a route.
type ObjectStatusWriter struct {
// contains filtered or unexported fields
}
func (osw *ObjectStatusWriter) SetInvalid(format string, args ...interface{})
func (osw *ObjectStatusWriter) SetValid()
func (osw *ObjectStatusWriter) WithObject(obj k8s.Object) (_ *ObjectStatusWriter, commit func())
WithObject returns a new ObjectStatusWriter with a copy of the current ObjectStatusWriter's values, including its status if set. This is convenient if the object shares a relationship with its parent. The caller should arrange for the commit function to be called to write the final status of the object.
func (osw *ObjectStatusWriter) WithValue(key, val string) *ObjectStatusWriter
Observer is an interface for receiving notification of DAG updates.
ComposeObservers returns a new Observer that calls each of its arguments in turn.
ObserverFunc is a function that implements the Observer interface by calling itself. It can be nil.
func (f ObserverFunc) OnChange(d *DAG)
type PeerValidationContext struct { // CACertificate holds a reference to the Secret containing the CA to be used to // verify the upstream connection. CACertificate *Secret // SubjectName holds an optional subject name which Envoy will check against the // certificate presented by the upstream. SubjectName string }
PeerValidationContext defines how to validate the certificate on the upstream service.
func (pvc *PeerValidationContext) GetCACertificate() []byte
GetCACertificate returns the CA certificate from PeerValidationContext.
func (pvc *PeerValidationContext) GetSubjectName() string
GetSubjectName returns the SubjectName from PeerValidationContext.
PrefixMatchCondition matches the start of a URL.
func (pc *PrefixMatchCondition) String() string
type Processor interface { // Run executes the processor. Run(dag *DAG, source *KubernetesCache) }
Processor constructs part of a DAG.
type ProcessorFunc func(*DAG, *KubernetesCache)
ProcessorFunc adapts a function to the Processor interface.
func (pf ProcessorFunc) Run(dag *DAG, source *KubernetesCache)
type RateLimitPolicy struct { Local *LocalRateLimitPolicy }
RateLimitPolicy holds rate limiting parameters.
RegexMatchCondition matches the URL by regular expression.
func (rc *RegexMatchCondition) String() string
type RetryPolicy struct { // RetryOn specifies the conditions under which retry takes place. // If empty, retries will not be performed. RetryOn string // RetriableStatusCodes specifies the HTTP status codes under which retry takes place. RetriableStatusCodes []uint32 // NumRetries specifies the allowed number of retries. // Ignored if RetryOn is blank, or defaults to 1 if RetryOn is set. NumRetries uint32 // PerTryTimeout specifies the timeout per retry attempt. // Ignored if RetryOn is blank. PerTryTimeout timeout.Setting }
RetryPolicy defines the retry / number / timeout options
type Route struct { // PathMatchCondition specifies a MatchCondition to match on the request path. // Must not be nil. PathMatchCondition MatchCondition // HeaderMatchConditions specifies a set of additional Conditions to // match on the request headers. HeaderMatchConditions []HeaderMatchCondition Clusters []*Cluster // Should this route generate a 301 upgrade if accessed // over HTTP? HTTPSUpgrade bool // AuthDisabled is set if authorization should be disabled // for this route. If authorization is disabled, the AuthContext // field has no effect. AuthDisabled bool // AuthContext sets the authorization context (if authorization is enabled). AuthContext map[string]string // Is this a websocket route? // TODO(dfc) this should go on the service Websocket bool // TimeoutPolicy defines the timeout request/idle TimeoutPolicy TimeoutPolicy // RetryPolicy defines the retry / number / timeout options for a route RetryPolicy *RetryPolicy // Indicates that during forwarding, the matched prefix (or path) should be swapped with this value PrefixRewrite string // Mirror Policy defines the mirroring policy for this Route. MirrorPolicy *MirrorPolicy // RequestHeadersPolicy defines how headers are managed during forwarding RequestHeadersPolicy *HeadersPolicy // ResponseHeadersPolicy defines how headers are managed during forwarding ResponseHeadersPolicy *HeadersPolicy // RateLimitPolicy defines if/how requests for the route are rate limited. RateLimitPolicy *RateLimitPolicy }
Route defines the properties of a route to a Cluster.
HasPathPrefix returns whether this route has a PrefixPathCondition.
HasPathRegex returns whether this route has a RegexPathCondition.
RouteServiceName identifies a service used in a route.
Secret represents a K8s Secret for TLS usage as a DAG Vertex. A Secret is a leaf in the DAG.
Cert returns the secret's tls certificate
Data returns the contents of the backing secret's map.
PrivateKey returns the secret's tls private key
type SecureVirtualHost struct { VirtualHost // TLS minimum protocol version. Defaults to envoy_tls_v3.TlsParameters_TLS_AUTO MinTLSVersion string // The cert and key for this host. Secret *Secret // FallbackCertificate FallbackCertificate *Secret // Service to TCP proxy all incoming connections. *TCPProxy // DownstreamValidation defines how to verify the client's certificate. DownstreamValidation *PeerValidationContext // AuthorizationService points to the extension that client // requests are forwarded to for authorization. If nil, no // authorization is enabled for this host. AuthorizationService *ExtensionCluster // AuthorizationResponseTimeout sets how long the proxy should wait // for authorization server responses. AuthorizationResponseTimeout timeout.Setting // AuthorizationFailOpen sets whether authorization server // failures should cause the client request to also fail. The // only reason to set this to `true` is when you are migrating // from internal to external authorization. AuthorizationFailOpen bool }
A SecureVirtualHost represents a HTTP host protected by TLS.
func (s *SecureVirtualHost) Valid() bool
func (s *SecureVirtualHost) Visit(f func(Vertex))
type Service struct { Weighted WeightedService // Protocol is the layer 7 protocol of this service // One of "", "h2", "h2c", or "tls". Protocol string // Max connections is maximum number of connections // that Envoy will make to the upstream cluster. MaxConnections uint32 // MaxPendingRequests is maximum number of pending // requests that Envoy will allow to the upstream cluster. MaxPendingRequests uint32 // MaxRequests is the maximum number of parallel requests that // Envoy will make to the upstream cluster. MaxRequests uint32 // MaxRetries is the maximum number of parallel retries that // Envoy will allow to the upstream cluster. MaxRetries uint32 // ExternalName is an optional field referencing a dns entry for Service type "ExternalName" ExternalName string }
Service represents a single Kubernetes' Service's Port.
Visit applies the visitor function to the Service vertex.
type ServiceCluster struct { // ClusterName is a globally unique name for this ServiceCluster. // It is eventually used as the Envoy ClusterLoadAssignment // name, and must not be empty. ClusterName string // Services are the load balancing targets. This slice must not be empty. Services []WeightedService }
ServiceCluster capture the set of Kubernetes Services that will compose the endpoints for a Envoy cluster. Traffic is balanced across the Service slice based on the weight of the elements.
func (s *ServiceCluster) AddService(name types.NamespacedName, port v1.ServicePort)
AddService adds the given service with a default weight of 1.
func (s *ServiceCluster) AddWeightedService(weight uint32, name types.NamespacedName, port v1.ServicePort)
AddWeightedService adds the given service with the given weight.
func (s *ServiceCluster) DeepCopy() *ServiceCluster
TODO(jpeach): apply deepcopy-gen to DAG objects.
func (s *ServiceCluster) Rebalance()
Rebalance rewrites the weights for the service cluster so that if no weights are specifies, the traffic is evenly distributed. This matches the behavior of weighted routes. Note that this is a destructive operation.
func (s *ServiceCluster) Validate() error
Validate checks whether this ServiceCluster satisfies its semantic invariants.
func (s *ServiceCluster) Visit(func(Vertex))
Status contains the status for an HTTPProxy (valid / invalid / orphan, etc)
type StatusWriter struct {
// contains filtered or unexported fields
}
func (sw *StatusWriter) WithObject(obj k8s.Object) (_ *ObjectStatusWriter, commit func())
WithObject returns an ObjectStatusWriter that can be used to set the state of the object. The state can be set as many times as necessary. The state of the object can be made permanent by calling the commit function returned from WithObject. The caller should pass the ObjectStatusWriter to functions interested in writing status, but keep the commit function for itself. The commit function should be either called via a defer, or directly if statuses are being set in a loop (as defers will not fire until the end of the function).
type TCPHealthCheckPolicy struct { Interval time.Duration Timeout time.Duration UnhealthyThreshold uint32 HealthyThreshold uint32 }
Cluster tcp health check policy
type TCPProxy struct { // Clusters is the, possibly weighted, set // of upstream services to forward decrypted traffic. Clusters []*Cluster }
TCPProxy represents a cluster of TCP endpoints.
type TimeoutPolicy struct { // ResponseTimeout is the timeout applied to the response // from the backend server. ResponseTimeout timeout.Setting // IdleTimeout is the timeout applied to idle connections. IdleTimeout timeout.Setting }
TimeoutPolicy defines the timeout policy for a route.
Vertex is a node in the DAG that can be visited.
type VirtualHost struct { // Name is the fully qualified domain name of a network host, // as defined by RFC 3986. Name string // CORSPolicy is the cross-origin policy to apply to the VirtualHost. CORSPolicy *CORSPolicy // RateLimitPolicy defines if/how requests for the virtual host // are rate limited. RateLimitPolicy *RateLimitPolicy // contains filtered or unexported fields }
A VirtualHost represents a named L4/L7 service.
func (v *VirtualHost) Valid() bool
func (v *VirtualHost) Visit(f func(Vertex))
type WeightedService struct { // Weight is the integral load balancing weight. Weight uint32 // ServiceName is the v1.Service name. ServiceName string // ServiceNamespace is the v1.Service namespace. ServiceNamespace string // ServicePort is the port to which we forward traffic. ServicePort v1.ServicePort }
WeightedService represents the load balancing weight of a particular v1.Weighted port.
Package dag imports 31 packages (graph) and is imported by 18 packages. Updated 2021-01-22. Refresh now. Tools for package owners.