model

package
v0.0.0-...-1a56975 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 23, 2019 License: Apache-2.0 Imports: 43 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// SDSStatPrefix is the human readable prefix to use when emitting statistics for the SDS service.
	SDSStatPrefix = "sdsstat"

	// SDSDefaultResourceName is the default name in sdsconfig, used for fetching normal key/cert.
	SDSDefaultResourceName = "default"

	// SDSRootResourceName is the sdsconfig name for root CA, used for fetching root cert.
	SDSRootResourceName = "ROOTCA"

	// K8sSATrustworthyJwtFileName is the token volume mount file name for k8s trustworthy jwt token.
	K8sSATrustworthyJwtFileName = "/var/run/secrets/tokens/istio-token"

	// K8sSAJwtFileName is the token volume mount file name for k8s jwt token.
	K8sSAJwtFileName = "/var/run/secrets/kubernetes.io/serviceaccount/token"

	// FileBasedMetadataPlugName is File Based Metadata credentials plugin name.
	FileBasedMetadataPlugName = "envoy.grpc_credentials.file_based_metadata"

	// K8sSAJwtTokenHeaderKey is the request header key for k8s jwt token.
	// Binary header name must has suffix "-bin", according to https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md.
	K8sSAJwtTokenHeaderKey = "istio_sds_credentials_header-bin"

	// IngressGatewaySdsUdsPath is the UDS path for ingress gateway to get credentials via SDS.
	IngressGatewaySdsUdsPath = "unix:/var/run/ingress_gateway/sds"

	// IngressGatewaySdsCaSuffix is the suffix of the sds resource name for root CA.
	IngressGatewaySdsCaSuffix = "-cacert"
)
View Source
const (
	// IstioAPIGroupDomain defines API group domain of all Istio configuration resources.
	// Group domain suffix to the proto schema's group to generate the full resource group.
	IstioAPIGroupDomain = ".istio.io"

	// NamespaceAll is a designated symbol for listing across all namespaces
	NamespaceAll = ""

	// IstioMeshGateway is the built in gateway for all sidecars
	IstioMeshGateway = "mesh"

	// IstioSystemNamespace is the namespace where Istio's components are deployed
	IstioSystemNamespace = "istio-system"
)
View Source
const (

	// IngressCertsPath is the path location for ingress certificates
	IngressCertsPath = "/etc/istio/ingress-certs/"

	// AuthCertsPath is the path location for mTLS certificates
	AuthCertsPath = "/etc/certs/"

	// CertChainFilename is mTLS chain file
	CertChainFilename = "cert-chain.pem"

	// DefaultServerCertChain is the default path to the mTLS chain file
	DefaultCertChain = AuthCertsPath + CertChainFilename

	// KeyFilename is mTLS private key
	KeyFilename = "key.pem"

	// DefaultServerKey is the default path to the mTLS private key file
	DefaultKey = AuthCertsPath + KeyFilename

	// RootCertFilename is mTLS root cert
	RootCertFilename = "root-cert.pem"

	// DefaultRootCert is the default path to the mTLS root cert file
	DefaultRootCert = AuthCertsPath + RootCertFilename

	// IngressCertFilename is the ingress cert file name
	IngressCertFilename = "tls.crt"

	// IngressKeyFilename is the ingress private key file name
	IngressKeyFilename = "tls.key"

	// ConfigPathDir config directory for storing envoy json config files.
	ConfigPathDir = "/etc/istio/proxy"

	// BinaryPathFilename envoy binary location
	BinaryPathFilename = "/usr/local/bin/envoy"

	// ServiceClusterName service cluster name used in xDS calls
	ServiceClusterName = "istio-proxy"

	// DiscoveryPlainAddress discovery IP address:port with plain text
	DiscoveryPlainAddress = "istio-pilot:15010"

	// IstioIngressGatewayName is the internal gateway name assigned to ingress
	IstioIngressGatewayName = "istio-autogenerated-k8s-ingress"

	// IstioIngressNamespace is the namespace where Istio ingress controller is deployed
	IstioIngressNamespace = "istio-system"
)
View Source
const (

	// NodeMetadataIstioProxyVersion specifies the Envoy version associated with the proxy
	NodeMetadataIstioProxyVersion = "ISTIO_PROXY_VERSION"

	// NodeMetadataNetwork defines the network the node belongs to. It is an optional metadata,
	// set at injection time. When set, the Endpoints returned to a note and not on same network
	// will be replaced with the gateway defined in the settings.
	NodeMetadataNetwork = "NETWORK"

	// NodeMetadataInterceptionMode is the name of the metadata variable that carries info about
	// traffic interception mode at the proxy
	NodeMetadataInterceptionMode = "INTERCEPTION_MODE"

	// NodeMetadataHTTP10 indicates the application behind the sidecar is making outbound http requests with HTTP/1.0
	// protocol. It will enable the "AcceptHttp_10" option on the http options for outbound HTTP listeners.
	// Alpha in 1.1, based on feedback may be turned into an API or change. Set to "1" to enable.
	NodeMetadataHTTP10 = "HTTP10"

	// NodeMetadataConfigNamespace is the name of the metadata variable that carries info about
	// the config namespace associated with the proxy
	NodeMetadataConfigNamespace = "CONFIG_NAMESPACE"

	// NodeMetadataSidecarUID is the user ID running envoy. Pilot can check if envoy runs as root, and may generate
	// different configuration. If not set, the default istio-proxy UID (1337) is assumed.
	NodeMetadataSidecarUID = "SIDECAR_UID"

	// NodeMetadataRequestedNetworkView specifies the networks that the proxy wants to see
	NodeMetadataRequestedNetworkView = "REQUESTED_NETWORK_VIEW"

	// NodeMetadataRouterMode indicates whether the proxy is functioning as a SNI-DNAT router
	// processing the AUTO_PASSTHROUGH gateway servers
	NodeMetadataRouterMode = "ROUTER_MODE"

	// NodeMetadataInstanceIPs is the set of IPs attached to this proxy
	NodeMetadataInstanceIPs = "INSTANCE_IPS"

	// NodeMetadataSdsTokenPath specifies the path of the SDS token used by the Envoy proxy.
	// If not set, Pilot uses the default SDS token path.
	NodeMetadataSdsTokenPath = "SDS_TOKEN_PATH"

	// NodeMetadataTLSServerCertChain is the absolute path to server cert-chain file
	NodeMetadataTLSServerCertChain = "TLS_SERVER_CERT_CHAIN"

	// NodeMetadataTLSServerKey is the absolute path to server private key file
	NodeMetadataTLSServerKey = "TLS_SERVER_KEY"

	// NodeMetadataTLSServerRootCert is the absolute path to server root cert file
	NodeMetadataTLSServerRootCert = "TLS_SERVER_ROOT_CERT"

	// NodeMetadataTLSClientCertChain is the absolute path to client cert-chain file
	NodeMetadataTLSClientCertChain = "TLS_CLIENT_CERT_CHAIN"

	// NodeMetadataTLSClientKey is the absolute path to client private key file
	NodeMetadataTLSClientKey = "TLS_CLIENT_KEY"

	// NodeMetadataTLSClientRootCert is the absolute path to client root cert file
	NodeMetadataTLSClientRootCert = "TLS_CLIENT_ROOT_CERT"

	// NodeMetadataPolicyCheck determines the policy for behavior when unable to connect to mixer
	// If not set, FAIL_CLOSE is set, rejecting requests.
	NodeMetadataPolicyCheck = "policy.istio.io/check"

	// NodeMetadataPolicyCheckRetries is the max number of retries on transport error to mixer
	// If not set, this will be 0, indicating no retries.
	NodeMetadataPolicyCheckRetries = "policy.istio.io/checkRetries"

	// NodeMetadataPolicyCheckBaseRetryWaitTime for base time to wait between retries, will be adjusted by backoff and jitter.
	// In duration format. If not set, this will be 80ms.
	NodeMetadataPolicyCheckBaseRetryWaitTime = "policy.istio.io/checkBaseRetryWaitTime"

	// NodeMetadataPolicyCheckMaxRetryWaitTime for max time to wait between retries
	// In duration format. If not set, this will be 1000ms.
	NodeMetadataPolicyCheckMaxRetryWaitTime = "policy.istio.io/checkMaxRetryWaitTime"
)

Pile all node metadata constants here

View Source
const (

	// JwtPubKeyExpireDuration is the expire duration for JWT public key in the cache.
	// After this duration expire, refresher job will fetch key for the cached item again.
	JwtPubKeyExpireDuration = time.Hour

	// JwtPubKeyEvictionDuration is the life duration for cached item.
	// Cached item will be removed from the cache if it hasn't been used longer than JwtPubKeyEvictionDuration.
	JwtPubKeyEvictionDuration = 24 * 7 * time.Hour

	// JwtPubKeyRefreshInterval is the running interval of JWT pubKey refresh job.
	JwtPubKeyRefreshInterval = time.Minute * 20
)
View Source
const (
	// UnspecifiedIP constant for empty IP address
	UnspecifiedIP = "0.0.0.0"

	// IstioDefaultConfigNamespace constant for default namespace
	IstioDefaultConfigNamespace = "default"

	// LocalityLabel indicates the region/zone/subzone of an instance. It is used to override the native
	// registry's value.
	//
	// Note: because k8s labels does not support `/`, so we use `.` instead in k8s.
	LocalityLabel = "istio-locality"
)
View Source
const (
	// DefaultAuthenticationPolicyName is the name of the cluster-scoped authentication policy. Only
	// policy with this name in the cluster-scoped will be considered.
	DefaultAuthenticationPolicyName = "default"
)
View Source
const (
	// DefaultRbacConfigName is the name of the mesh global RbacConfig name. Only RbacConfig with this
	// name will be considered.
	DefaultRbacConfigName = "default"
)
View Source
const UnixAddressPrefix = "unix://"

UnixAddressPrefix is the prefix used to indicate an address is for a Unix Domain socket. It is used in ServiceEntry.Endpoint.Address message.

View Source
const UnnamedNetwork = ""

UnnamedNetwork is the default network that proxies in the mesh get when they don't request a specific network view.

Variables

View Source
var (
	// MockConfig is used purely for testing
	MockConfig = ProtoSchema{
		Type:        "mock-config",
		Plural:      "mock-configs",
		Group:       "test",
		Version:     "v1",
		MessageName: "test.MockConfig",
		Validate: func(name, namespace string, config proto.Message) error {
			if config.(*test.MockConfig).Key == "" {
				return errors.New("empty key")
			}
			return nil
		},
	}

	// VirtualService describes v1alpha3 route rules
	VirtualService = ProtoSchema{
		Type:        "virtual-service",
		Plural:      "virtual-services",
		Group:       "networking",
		Version:     "v1alpha3",
		MessageName: "istio.networking.v1alpha3.VirtualService",
		Validate:    ValidateVirtualService,
		Collection:  metadata.IstioNetworkingV1alpha3Virtualservices.Collection.String(),
	}

	// Gateway describes a gateway (how a proxy is exposed on the network)
	Gateway = ProtoSchema{
		Type:        "gateway",
		Plural:      "gateways",
		Group:       "networking",
		Version:     "v1alpha3",
		MessageName: "istio.networking.v1alpha3.Gateway",
		Validate:    ValidateGateway,
		Collection:  metadata.IstioNetworkingV1alpha3Gateways.Collection.String(),
	}

	// ServiceEntry describes service entries
	ServiceEntry = ProtoSchema{
		Type:        "service-entry",
		Plural:      "service-entries",
		Group:       "networking",
		Version:     "v1alpha3",
		MessageName: "istio.networking.v1alpha3.ServiceEntry",
		Validate:    ValidateServiceEntry,
		Collection:  metadata.IstioNetworkingV1alpha3Serviceentries.Collection.String(),
	}

	// DestinationRule describes destination rules
	DestinationRule = ProtoSchema{
		Type:        "destination-rule",
		Plural:      "destination-rules",
		Group:       "networking",
		Version:     "v1alpha3",
		MessageName: "istio.networking.v1alpha3.DestinationRule",
		Validate:    ValidateDestinationRule,
		Collection:  metadata.IstioNetworkingV1alpha3Destinationrules.Collection.String(),
	}

	// EnvoyFilter describes additional envoy filters to be inserted by Pilot
	EnvoyFilter = ProtoSchema{
		Type:        "envoy-filter",
		Plural:      "envoy-filters",
		Group:       "networking",
		Version:     "v1alpha3",
		MessageName: "istio.networking.v1alpha3.EnvoyFilter",
		Validate:    ValidateEnvoyFilter,
		Collection:  metadata.IstioNetworkingV1alpha3Envoyfilters.Collection.String(),
	}

	// Sidecar describes the listeners associated with sidecars in a namespace
	Sidecar = ProtoSchema{
		Type:        "sidecar",
		Plural:      "sidecars",
		Group:       "networking",
		Version:     "v1alpha3",
		MessageName: "istio.networking.v1alpha3.Sidecar",
		Validate:    ValidateSidecar,
		Collection:  metadata.IstioNetworkingV1alpha3Sidecars.Collection.String(),
	}

	// HTTPAPISpec describes an HTTP API specification.
	HTTPAPISpec = ProtoSchema{
		Type:        "http-api-spec",
		Plural:      "http-api-specs",
		Group:       "config",
		Version:     istioAPIVersion,
		MessageName: "istio.mixer.v1.config.client.HTTPAPISpec",
		Validate:    ValidateHTTPAPISpec,
		Collection:  metadata.IstioConfigV1alpha2Httpapispecs.Collection.String(),
	}

	// HTTPAPISpecBinding describes an HTTP API specification binding.
	HTTPAPISpecBinding = ProtoSchema{
		Type:        "http-api-spec-binding",
		Plural:      "http-api-spec-bindings",
		Group:       "config",
		Version:     istioAPIVersion,
		MessageName: "istio.mixer.v1.config.client.HTTPAPISpecBinding",
		Validate:    ValidateHTTPAPISpecBinding,
		Collection:  metadata.IstioConfigV1alpha2Httpapispecbindings.Collection.String(),
	}

	// QuotaSpec describes an Quota specification.
	QuotaSpec = ProtoSchema{
		Type:        "quota-spec",
		Plural:      "quota-specs",
		Group:       "config",
		Version:     istioAPIVersion,
		MessageName: "istio.mixer.v1.config.client.QuotaSpec",
		Validate:    ValidateQuotaSpec,
		Collection:  metadata.IstioMixerV1ConfigClientQuotaspecs.Collection.String(),
	}

	// QuotaSpecBinding describes an Quota specification binding.
	QuotaSpecBinding = ProtoSchema{
		Type:        "quota-spec-binding",
		Plural:      "quota-spec-bindings",
		Group:       "config",
		Version:     istioAPIVersion,
		MessageName: "istio.mixer.v1.config.client.QuotaSpecBinding",
		Validate:    ValidateQuotaSpecBinding,
		Collection:  metadata.IstioMixerV1ConfigClientQuotaspecbindings.Collection.String(),
	}

	// AuthenticationPolicy describes an authentication policy.
	AuthenticationPolicy = ProtoSchema{
		SchemaObjectName: "AuthenticationPolicy",
		Type:             "policy",
		Plural:           "policies",
		Group:            "authentication",
		Version:          "v1alpha1",
		MessageName:      "istio.authentication.v1alpha1.Policy",
		Validate:         ValidateAuthenticationPolicy,
		Collection:       metadata.IstioAuthenticationV1alpha1Policies.Collection.String(),
	}

	// AuthenticationMeshPolicy describes an authentication policy at mesh level.
	AuthenticationMeshPolicy = ProtoSchema{
		ClusterScoped:    true,
		SchemaObjectName: "AuthenticationMeshPolicy",
		Type:             "mesh-policy",
		Plural:           "mesh-policies",
		Group:            "authentication",
		Version:          "v1alpha1",
		MessageName:      "istio.authentication.v1alpha1.Policy",
		Validate:         ValidateAuthenticationPolicy,
		Collection:       metadata.IstioAuthenticationV1alpha1Meshpolicies.Collection.String(),
	}

	// ServiceRole describes an RBAC service role.
	ServiceRole = ProtoSchema{
		Type:        "service-role",
		Plural:      "service-roles",
		Group:       "rbac",
		Version:     "v1alpha1",
		MessageName: "istio.rbac.v1alpha1.ServiceRole",
		Validate:    ValidateServiceRole,
		Collection:  metadata.IstioRbacV1alpha1Serviceroles.Collection.String(),
	}

	// ServiceRoleBinding describes an RBAC service role.
	ServiceRoleBinding = ProtoSchema{
		ClusterScoped: false,
		Type:          "service-role-binding",
		Plural:        "service-role-bindings",
		Group:         "rbac",
		Version:       "v1alpha1",
		MessageName:   "istio.rbac.v1alpha1.ServiceRoleBinding",
		Validate:      ValidateServiceRoleBinding,
		Collection:    metadata.IstioRbacV1alpha1Servicerolebindings.Collection.String(),
	}

	// AuthorizationPolicy describes an authorization policy.
	AuthorizationPolicy = ProtoSchema{
		ClusterScoped: false,
		Type:          "authorization-policy",
		Plural:        "authorization-policies",
		Group:         "rbac",
		Version:       "v1alpha1",
		MessageName:   "istio.rbac.v1alpha1.AuthorizationPolicy",
		Validate:      ValidateAuthorizationPolicy,
		Collection:    metadata.IstioRbacV1alpha1Authorizationpolicies.Collection.String(),
	}

	// RbacConfig describes the mesh level RBAC config.
	// Deprecated: use ClusterRbacConfig instead.
	// See https://github.com/istio/istio/issues/8825 for more details.
	RbacConfig = ProtoSchema{
		Type:        "rbac-config",
		Plural:      "rbac-configs",
		Group:       "rbac",
		Version:     "v1alpha1",
		MessageName: "istio.rbac.v1alpha1.RbacConfig",
		Validate:    ValidateRbacConfig,
		Collection:  metadata.IstioRbacV1alpha1Rbacconfigs.Collection.String(),
	}

	// ClusterRbacConfig describes the cluster level RBAC config.
	ClusterRbacConfig = ProtoSchema{
		ClusterScoped: true,
		Type:          "cluster-rbac-config",
		Plural:        "cluster-rbac-configs",
		Group:         "rbac",
		Version:       "v1alpha1",
		MessageName:   "istio.rbac.v1alpha1.RbacConfig",
		Validate:      ValidateClusterRbacConfig,
		Collection:    metadata.IstioRbacV1alpha1Clusterrbacconfigs.Collection.String(),
	}

	// IstioConfigTypes lists all Istio config types with schemas and validation
	IstioConfigTypes = ConfigDescriptor{
		VirtualService,
		Gateway,
		ServiceEntry,
		DestinationRule,
		EnvoyFilter,
		Sidecar,
		HTTPAPISpec,
		HTTPAPISpecBinding,
		QuotaSpec,
		QuotaSpecBinding,
		AuthenticationPolicy,
		AuthenticationMeshPolicy,
		ServiceRole,
		ServiceRoleBinding,
		AuthorizationPolicy,
		RbacConfig,
		ClusterRbacConfig,
	}
)
View Source
var (

	// EndpointNoPod tracks endpoints without an associated pod. This is an error condition, since
	// we can't figure out the labels. It may be a transient problem, if endpoint is processed before
	// pod.
	EndpointNoPod = newPushMetric(
		"endpoint_no_pod",
		"Endpoints without an associated pod.",
	)

	// ProxyStatusNoService represents proxies not selected by any service
	// This can be normal - for workloads that act only as client, or are not covered by a Service.
	// It can also be an error, for example in cases the Endpoint list of a service was not updated by the time
	// the sidecar calls.
	// Updated by GetProxyServiceInstances
	ProxyStatusNoService = newPushMetric(
		"pilot_no_ip",
		"Pods not found in the endpoint table, possibly invalid.",
	)

	// ProxyStatusEndpointNotReady represents proxies found not be ready.
	// Updated by GetProxyServiceInstances. Normal condition when starting
	// an app with readiness, error if it doesn't change to 0.
	ProxyStatusEndpointNotReady = newPushMetric(
		"pilot_endpoint_not_ready",
		"Endpoint found in unready state.",
	)

	// ProxyStatusConflictOutboundListenerTCPOverHTTP metric tracks number of
	// wildcard TCP listeners that conflicted with existing wildcard HTTP listener on same port
	ProxyStatusConflictOutboundListenerTCPOverHTTP = newPushMetric(
		"pilot_conflict_outbound_listener_tcp_over_current_http",
		"Number of conflicting wildcard tcp listeners with current wildcard http listener.",
	)

	// ProxyStatusConflictOutboundListenerTCPOverTCP metric tracks number of
	// TCP listeners that conflicted with existing TCP listeners on same port
	ProxyStatusConflictOutboundListenerTCPOverTCP = newPushMetric(
		"pilot_conflict_outbound_listener_tcp_over_current_tcp",
		"Number of conflicting tcp listeners with current tcp listener.",
	)

	// ProxyStatusConflictOutboundListenerHTTPOverTCP metric tracks number of
	// wildcard HTTP listeners that conflicted with existing wildcard TCP listener on same port
	ProxyStatusConflictOutboundListenerHTTPOverTCP = newPushMetric(
		"pilot_conflict_outbound_listener_http_over_current_tcp",
		"Number of conflicting wildcard http listeners with current wildcard tcp listener.",
	)

	// ProxyStatusConflictInboundListener tracks cases of multiple inbound
	// listeners - 2 services selecting the same port of the pod.
	ProxyStatusConflictInboundListener = newPushMetric(
		"pilot_conflict_inbound_listener",
		"Number of conflicting inbound listeners.",
	)

	// DuplicatedClusters tracks duplicate clusters seen while computing CDS
	DuplicatedClusters = newPushMetric(
		"pilot_duplicate_envoy_clusters",
		"Duplicate envoy clusters caused by service entries with same hostname",
	)

	// ProxyStatusClusterNoInstances tracks clusters (services) without workloads.
	ProxyStatusClusterNoInstances = newPushMetric(
		"pilot_eds_no_instances",
		"Number of clusters without instances.",
	)

	// DuplicatedSubsets tracks duplicate subsets that we rejected while merging multiple destination rules for same host
	DuplicatedSubsets = newPushMetric(
		"pilot_destrule_subsets",
		"Duplicate subsets across destination rules for same host",
	)

	// LastPushStatus preserves the metrics and data collected during lasts global push.
	// It can be used by debugging tools to inspect the push event. It will be reset after each push with the
	// new version.
	LastPushStatus *PushContext
	// LastPushMutex will protect the LastPushStatus
	LastPushMutex sync.Mutex
)
View Source
var IstioIngressWorkloadLabels = map[string]string{"istio": "ingress"}

IstioIngressWorkloadLabels is the label assigned to Istio ingress pods

JwtKeyResolver resolves JWT public key and JwksURI.

Functions

func ApplyJSON

func ApplyJSON(js string, pb proto.Message, strict bool) error

ApplyJSON unmarshals a JSON string into a proto message. Unknown fields will produce an // error unless strict is set to false.

func ApplyMeshConfigDefaults

func ApplyMeshConfigDefaults(yaml string) (*meshconfig.MeshConfig, error)

ApplyMeshConfigDefaults returns a new MeshConfig decoded from the input YAML with defaults applied to omitted configuration values.

func ApplyYAML

func ApplyYAML(yml string, pb proto.Message, strict bool) error

ApplyYAML unmarshals a YAML string into a proto message. Unknown fields will produce an error unless strict is set to false.

func BuildDNSSrvSubsetKey

func BuildDNSSrvSubsetKey(direction TrafficDirection, subsetName string, hostname Hostname, port int) string

BuildDNSSrvSubsetKey generates a unique string referencing service instances for a given service name, a subset and a port. The proxy queries Pilot with this key to obtain the list of instances in a subset. This is used only for the SNI-DNAT router. Do not use for other purposes. The DNS Srv format of the cluster is also used as the default SNI string for Istio mTLS connections

func BuildSubsetKey

func BuildSubsetKey(direction TrafficDirection, subsetName string, hostname Hostname, port int) string

BuildSubsetKey generates a unique string referencing service instances for a given service name, a subset and a port. The proxy queries Pilot with this key to obtain the list of instances in a subset.

func ConstructSdsSecretConfig

func ConstructSdsSecretConfig(name, sdsUdsPath string, useK8sSATrustworthyJwt, useK8sSANormalJwt bool, metadata map[string]string) *auth.SdsSecretConfig

ConstructSdsSecretConfig constructs SDS Sececret Configuration for workload proxy.

func ConstructSdsSecretConfigForGatewayListener

func ConstructSdsSecretConfigForGatewayListener(name, sdsUdsPath string) *auth.SdsSecretConfig

ConstructSdsSecretConfig constructs SDS secret configuration for ingress gateway.

func ConstructValidationContext

func ConstructValidationContext(rootCAFilePath string, subjectAltNames []string) *auth.CommonTlsContext_ValidationContext

ConstructValidationContext constructs ValidationContext in CommonTlsContext.

func ConstructgRPCCallCredentials

func ConstructgRPCCallCredentials(tokenFileName, headerKey string) []*core.GrpcService_GoogleGrpc_CallCredentials

this function is used to construct SDS config which is only available from 1.1

func DefaultMeshConfig

func DefaultMeshConfig() meshconfig.MeshConfig

DefaultMeshConfig configuration

func DefaultProxyConfig

func DefaultProxyConfig() meshconfig.ProxyConfig

DefaultProxyConfig for individual proxies

func EmptyMeshNetworks

func EmptyMeshNetworks() meshconfig.MeshNetworks

EmptyMeshNetworks configuration with no networks

func GetConsolidateAuthenticationPolicy

func GetConsolidateAuthenticationPolicy(store IstioConfigStore, serviceInstance *ServiceInstance) *authn.Policy

GetConsolidateAuthenticationPolicy returns the authentication policy for workload specified by hostname (or label selector if specified) and port, if defined. It also tries to resolve JWKS URI if necessary.

func GetNetworkView

func GetNetworkView(node *Proxy) map[string]bool

GetNetworkView returns the networks that the proxy requested. When sending EDS/CDS-with-dns-endpoints, Pilot will only send endpoints corresponding to the networks that the proxy wants to see. If not set, we assume that the proxy wants to see endpoints from the default unnamed network.

func GetOrDefaultFromMap

func GetOrDefaultFromMap(stringMap map[string]string, key, defaultVal string) string

GetOrDefaultFromMap returns either the value found for key or the default value if the map is nil or does not contain the key. Useful when retrieving node metadata fields.

func GetProxyConfigNamespace

func GetProxyConfigNamespace(proxy *Proxy) string

GetProxyConfigNamespace extracts the namespace associated with the proxy from the proxy metadata or the proxy ID

func IsApplicationNodeType

func IsApplicationNodeType(nType NodeType) bool

IsApplicationNodeType verifies that the NodeType is one of the declared constants in the model

func IsDNS1123Label

func IsDNS1123Label(value string) bool

IsDNS1123Label tests for a string that conforms to the definition of a label in DNS (RFC 1123).

func IsHTTPServer

func IsHTTPServer(server *networking.Server) bool

IsHTTPServer returns true if this server is using HTTP or HTTPS with termination

func IsPassThroughServer

func IsPassThroughServer(server *networking.Server) bool

IsPassThroughServer returns true if this server does TLS passthrough (auto or manual)

func IsTLSServer

func IsTLSServer(server *networking.Server) bool

IsTLSServer returns true if this server is non HTTP, with some TLS settings for termination/passthrough

func IsValidSubsetKey

func IsValidSubsetKey(s string) bool

IsValidSubsetKey checks if a string is valid for subset key parsing.

func IsWildcardDNS1123Label

func IsWildcardDNS1123Label(value string) bool

IsWildcardDNS1123Label tests for a string that conforms to the definition of a label in DNS (RFC 1123), but allows the wildcard label (`*`), and typical labels with a leading astrisk instead of alphabetic character (e.g. "*-foo")

func Key

func Key(typ, name, namespace string) string

Key function for the configuration objects

func LoadMeshNetworksConfig

func LoadMeshNetworksConfig(yaml string) (*meshconfig.MeshNetworks, error)

LoadMeshNetworksConfig returns a new MeshNetworks decoded from the input YAML.

func MatchesDestHost

func MatchesDestHost(destinationHost string, meta ConfigMeta, svc *mccpb.IstioService) bool

MatchesDestHost returns true if the service instance matches the given IstioService ex: binding host(details.istio-system.svc.cluster.local) ?= instance(reviews.default.svc.cluster.local)

func ParseMetadata

func ParseMetadata(metadata *types.Struct) map[string]string

ParseMetadata parses the opaque Metadata from an Envoy Node into string key-value pairs. Any non-string values are ignored.

func ParsePort

func ParsePort(addr string) int

ParsePort extracts port number from a valid proxy address

func ParseServiceKey

func ParseServiceKey(s string) (hostname Hostname, ports PortList, labels LabelsCollection)

ParseServiceKey is the inverse of the Service.String() method Deprecated

func ParseSubsetKey

func ParseSubsetKey(s string) (direction TrafficDirection, subsetName string, hostname Hostname, port int)

ParseSubsetKey is the inverse of the BuildSubsetKey method

func ServiceKey

func ServiceKey(hostname Hostname, servicePorts PortList, labelsList LabelsCollection) string

ServiceKey generates a service key for a collection of ports and labels Deprecated

Interface wants to turn `Hostname` into `fmt.Stringer`, completely defeating the purpose of the type alias. nolint: interfacer

func SortHTTPAPISpec

func SortHTTPAPISpec(specs []Config)

SortHTTPAPISpec sorts a slice in a stable manner.

func SortQuotaSpec

func SortQuotaSpec(specs []Config)

SortQuotaSpec sorts a slice in a stable manner.

func ToJSON

func ToJSON(msg proto.Message) (string, error)

ToJSON marshals a proto to canonical JSON

func ToJSONMap

func ToJSONMap(msg proto.Message) (map[string]interface{}, error)

ToJSONMap converts a proto message to a generic map using canonical JSON encoding JSON encoding is specified here: https://developers.google.com/protocol-buffers/docs/proto3#json

func ToJSONWithIndent

func ToJSONWithIndent(msg proto.Message, indent string) (string, error)

ToJSONWithIndent marshals a proto to canonical JSON with pretty printed string

func ToYAML

func ToYAML(msg proto.Message) (string, error)

ToYAML marshals a proto to canonical YAML

func ValidateAuthenticationPolicy

func ValidateAuthenticationPolicy(name, namespace string, msg proto.Message) error

ValidateAuthenticationPolicy checks that AuthenticationPolicy is well-formed.

func ValidateAuthorizationPolicy

func ValidateAuthorizationPolicy(_, _ string, msg proto.Message) error

ValidateAuthorizationPolicy checks that AuthorizationPolicy is well-formed.

func ValidateClusterRbacConfig

func ValidateClusterRbacConfig(name, _ string, msg proto.Message) error

ValidateClusterRbacConfig checks that ClusterRbacConfig is well-formed.

func ValidateConnectTimeout

func ValidateConnectTimeout(timeout *types.Duration) error

ValidateConnectTimeout validates the envoy conncection timeout

func ValidateDatadogCollector

func ValidateDatadogCollector(d *meshconfig.Tracing_Datadog) error

ValidateDatadogCollector validates the configuration for sending envoy spans to Datadog

func ValidateDestinationRule

func ValidateDestinationRule(_, _ string, msg proto.Message) (errs error)

ValidateDestinationRule checks proxy policies

func ValidateDuration

func ValidateDuration(pd *types.Duration) error

ValidateDuration checks that a proto duration is well-formed

func ValidateDurationGogo

func ValidateDurationGogo(pd *types.Duration) error

ValidateDurationGogo checks that a gogo proto duration is well-formed

func ValidateDurationRange

func ValidateDurationRange(dur, min, max time.Duration) error

ValidateDurationRange verifies range is in specified duration

func ValidateEnvoyFilter

func ValidateEnvoyFilter(_, _ string, msg proto.Message) (errs error)

ValidateEnvoyFilter checks envoy filter config supplied by user

func ValidateFQDN

func ValidateFQDN(fqdn string) error

ValidateFQDN checks a fully-qualified domain name

func ValidateGateway

func ValidateGateway(name, _ string, msg proto.Message) (errs error)

ValidateGateway checks gateway specifications

func ValidateGogoDuration

func ValidateGogoDuration(in *types.Duration) error

ValidateGogoDuration validates the variant of duration.

func ValidateHTTPAPISpec

func ValidateHTTPAPISpec(_, _ string, msg proto.Message) error

ValidateHTTPAPISpec checks that HTTPAPISpec is well-formed.

func ValidateHTTPAPISpecBinding

func ValidateHTTPAPISpecBinding(_, _ string, msg proto.Message) error

ValidateHTTPAPISpecBinding checks that HTTPAPISpecBinding is well-formed.

func ValidateHTTPHeaderName

func ValidateHTTPHeaderName(name string) error

ValidateHTTPHeaderName validates a header name

func ValidateIPv4Address

func ValidateIPv4Address(addr string) error

ValidateIPv4Address validates that a string in "CIDR notation" or "Dot-decimal notation"

func ValidateIPv4Subnet

func ValidateIPv4Subnet(subnet string) error

ValidateIPv4Subnet checks that a string is in "CIDR notation" or "Dot-decimal notation"

func ValidateLightstepCollector

func ValidateLightstepCollector(ls *meshconfig.Tracing_Lightstep) error

ValidateLightstepCollector validates the configuration for sending envoy spans to LightStep

func ValidateMeshConfig

func ValidateMeshConfig(mesh *meshconfig.MeshConfig) (errs error)

ValidateMeshConfig checks that the mesh config is well-formed

func ValidateMixerAttributes

func ValidateMixerAttributes(msg proto.Message) error

ValidateMixerAttributes checks that Mixer attributes is well-formed.

func ValidateMixerService

func ValidateMixerService(svc *mccpb.IstioService) (errs error)

ValidateMixerService checks for validity of a service reference

func ValidateNetworkEndpointAddress

func ValidateNetworkEndpointAddress(n *NetworkEndpoint) error

ValidateNetworkEndpointAddress checks the Address field of a NetworkEndpoint. If the family is TCP, it checks the address is a valid IP address. If the family is Unix, it checks the address is a valid socket file path.

func ValidateParentAndDrain

func ValidateParentAndDrain(drainTime, parentShutdown *types.Duration) (errs error)

ValidateParentAndDrain checks that parent and drain durations are valid

func ValidatePercent

func ValidatePercent(val int32) error

ValidatePercent checks that percent is in range

func ValidatePort

func ValidatePort(port int) error

ValidatePort checks that the network port is in range

func ValidatePorts

func ValidatePorts(ports []int32) bool

ValidatePort checks if all ports are in range [0, 65535]

func ValidateProxyAddress

func ValidateProxyAddress(hostAddr string) error

ValidateProxyAddress checks that a network address is well-formed

func ValidateProxyConfig

func ValidateProxyConfig(config *meshconfig.ProxyConfig) (errs error)

ValidateProxyConfig checks that the mesh config is well-formed

func ValidateQuotaSpec

func ValidateQuotaSpec(_, _ string, msg proto.Message) error

ValidateQuotaSpec checks that Quota is well-formed.

func ValidateQuotaSpecBinding

func ValidateQuotaSpecBinding(_, _ string, msg proto.Message) error

ValidateQuotaSpecBinding checks that QuotaSpecBinding is well-formed.

func ValidateRbacConfig

func ValidateRbacConfig(name, _ string, msg proto.Message) error

ValidateRbacConfig checks that RbacConfig is well-formed.

func ValidateServiceEntry

func ValidateServiceEntry(_, _ string, config proto.Message) (errs error)

ValidateServiceEntry validates a service entry.

func ValidateServiceRole

func ValidateServiceRole(_, _ string, msg proto.Message) error

ValidateServiceRole checks that ServiceRole is well-formed.

func ValidateServiceRoleBinding

func ValidateServiceRoleBinding(_, _ string, msg proto.Message) error

ValidateServiceRoleBinding checks that ServiceRoleBinding is well-formed.

func ValidateSidecar

func ValidateSidecar(_, _ string, msg proto.Message) (errs error)

ValidateSidecar checks sidecar config supplied by user

func ValidateUnixAddress

func ValidateUnixAddress(addr string) error

ValidateUnixAddress validates that the string is a valid unix domain socket path.

func ValidateVirtualService

func ValidateVirtualService(_, _ string, msg proto.Message) (errs error)

ValidateVirtualService checks that a v1alpha3 route rule is well-formed.

func ValidateWildcardDomain

func ValidateWildcardDomain(domain string) error

ValidateWildcardDomain checks that a domain is a valid FQDN, but also allows wildcard prefixes.

func ValidateZipkinCollector

func ValidateZipkinCollector(z *meshconfig.Tracing_Zipkin) error

ValidateZipkinCollector validates the configuration for sending envoy spans to Zipkin

Types

type AddressFamily

type AddressFamily int

AddressFamily indicates the kind of transport used to reach a NetworkEndpoint

const (
	// AddressFamilyTCP represents an address that connects to a TCP endpoint. It consists of an IP address or host and
	// a port number.
	AddressFamilyTCP AddressFamily = iota
	// AddressFamilyUnix represents an address that connects to a Unix Domain Socket. It consists of a socket file path.
	AddressFamilyUnix
)

func (AddressFamily) String

func (f AddressFamily) String() string

String converts addressfamily into string (tcp/unix)

type AuthorizationConfigV2

type AuthorizationConfigV2 struct {
	// A list of AuthorizationPolicyConfig.
	AuthzPolicies []*AuthorizationPolicyConfig

	// Maps from name to ServiceRole.
	NameToServiceRoles map[string]*rbacproto.ServiceRole
}

AuthorizationConfigV2 stores a list of AuthorizationPolicyConfig and ServiceRole in a given namespace.

type AuthorizationPolicies

type AuthorizationPolicies struct {
	// Maps from namespace to ServiceRole and ServiceRoleBindings.
	NamespaceToPolicies map[string]*RolesAndBindings

	// Maps from namespace to AuthorizationConfigV2.
	NamespaceToAuthorizationConfigV2 map[string]*AuthorizationConfigV2

	// The mesh global RbacConfig.
	RbacConfig *rbacproto.RbacConfig

	// True if using RBAC v2 (i.e. AuthorizationPolicy and no ServiceRoleBinding).
	IsRbacV2 bool
}

AuthorizationPolicies stores all authorization policies (i.e. ServiceRole, ServiceRoleBinding and RbacConfig) according to its namespace.

func NewAuthzPolicies

func NewAuthzPolicies(env *Environment) (*AuthorizationPolicies, error)

NewAuthzPolicies returns the AuthorizationPolicies constructed from raw authorization policies by storing policies into different namespaces.

func (*AuthorizationPolicies) AddConfig

func (policy *AuthorizationPolicies) AddConfig(cfgs ...*Config)

AddConfig adds a config of type ServiceRole, ServiceRoleBinding or AuthorizationPolicy to AuthorizationPolicies.

func (*AuthorizationPolicies) RoleForNameAndNamespace

func (policy *AuthorizationPolicies) RoleForNameAndNamespace(roleName, ns string) *rbacproto.ServiceRole

RoleForNameAndNamespace returns a ServiceRole from this namespace, given the ServiceRole name and namespace. This function always return a non nil struct instance.

func (*AuthorizationPolicies) RoleToBindingsForNamespace

func (policy *AuthorizationPolicies) RoleToBindingsForNamespace(ns string) map[string][]*rbacproto.ServiceRoleBinding

RoleToBindingsForNamespace returns the mapping from ServiceRole name to its associated ServiceRoleBindings. This function always return a non nil map.

func (*AuthorizationPolicies) RolesForNamespace

func (policy *AuthorizationPolicies) RolesForNamespace(ns string) []Config

RolesForNamespace returns the ServiceRole configs in the given namespace. This function always return a non nil slice.

type AuthorizationPolicyConfig

type AuthorizationPolicyConfig struct {
	Name   string
	Policy *rbacproto.AuthorizationPolicy
}

AuthorizationPolicyConfig stores the AuthorizationPolicy and its name.

type Config

type Config struct {
	ConfigMeta

	// Spec holds the configuration object as a protobuf message
	Spec proto.Message
}

Config is a configuration unit consisting of the type of configuration, the key identifier that is unique per type, and the content represented as a protobuf message.

type ConfigDescriptor

type ConfigDescriptor []ProtoSchema

ConfigDescriptor defines the bijection between the short type name and its fully qualified protobuf message name

func (ConfigDescriptor) GetByType

func (descriptor ConfigDescriptor) GetByType(name string) (ProtoSchema, bool)

GetByType finds a schema by type if it is available

func (ConfigDescriptor) Types

func (descriptor ConfigDescriptor) Types() []string

Types lists all known types in the config schema

func (ConfigDescriptor) Validate

func (descriptor ConfigDescriptor) Validate() error

Validate checks that each name conforms to the spec and has a ProtoMessage

type ConfigMeta

type ConfigMeta struct {
	// Type is a short configuration name that matches the content message type
	// (e.g. "route-rule")
	Type string `json:"type,omitempty"`

	// Group is the API group of the config.
	Group string `json:"group,omitempty"`

	// Version is the API version of the Config.
	Version string `json:"version,omitempty"`

	// Name is a unique immutable identifier in a namespace
	Name string `json:"name,omitempty"`

	// Namespace defines the space for names (optional for some types),
	// applications may choose to use namespaces for a variety of purposes
	// (security domains, fault domains, organizational domains)
	Namespace string `json:"namespace,omitempty"`

	// Domain defines the suffix of the fully qualified name past the namespace.
	// Domain is not a part of the unique key unlike name and namespace.
	Domain string `json:"domain,omitempty"`

	// Map of string keys and values that can be used to organize and categorize
	// (scope and select) objects.
	Labels map[string]string `json:"labels,omitempty"`

	// Annotations is an unstructured key value map stored with a resource that may be
	// set by external tools to store and retrieve arbitrary metadata. They are not
	// queryable and should be preserved when modifying objects.
	Annotations map[string]string `json:"annotations,omitempty"`

	// ResourceVersion is an opaque identifier for tracking updates to the config registry.
	// The implementation may use a change index or a commit log for the revision.
	// The config client should not make any assumptions about revisions and rely only on
	// exact equality to implement optimistic concurrency of read-write operations.
	//
	// The lifetime of an object of a particular revision depends on the underlying data store.
	// The data store may compactify old revisions in the interest of storage optimization.
	//
	// An empty revision carries a special meaning that the associated object has
	// not been stored and assigned a revision.
	ResourceVersion string `json:"resourceVersion,omitempty"`

	// CreationTimestamp records the creation time
	CreationTimestamp time.Time `json:"creationTimestamp,omitempty"`
}

ConfigMeta is metadata attached to each configuration unit. The revision is optional, and if provided, identifies the last update operation on the object.

func (*ConfigMeta) Key

func (meta *ConfigMeta) Key() string

Key is the unique identifier for a configuration object

type ConfigStore

type ConfigStore interface {
	// ConfigDescriptor exposes the configuration type schema known by the config store.
	// The type schema defines the bidrectional mapping between configuration
	// types and the protobuf encoding schema.
	ConfigDescriptor() ConfigDescriptor

	// Get retrieves a configuration element by a type and a key
	Get(typ, name, namespace string) *Config

	// List returns objects by type and namespace.
	// Use "" for the namespace to list across namespaces.
	List(typ, namespace string) ([]Config, error)

	// Create adds a new configuration object to the store. If an object with the
	// same name and namespace for the type already exists, the operation fails
	// with no side effects.
	Create(config Config) (revision string, err error)

	// Update modifies an existing configuration object in the store.  Update
	// requires that the object has been created.  Resource version prevents
	// overriding a value that has been changed between prior _Get_ and _Put_
	// operation to achieve optimistic concurrency. This method returns a new
	// revision if the operation succeeds.
	Update(config Config) (newRevision string, err error)

	// Delete removes an object from the store by key
	Delete(typ, name, namespace string) error
}

ConfigStore describes a set of platform agnostic APIs that must be supported by the underlying platform to store and retrieve Istio configuration.

Configuration key is defined to be a combination of the type, name, and namespace of the configuration object. The configuration key is guaranteed to be unique in the store.

The storage interface presented here assumes that the underlying storage layer supports _Get_ (list), _Update_ (update), _Create_ (create) and _Delete_ semantics but does not guarantee any transactional semantics.

_Update_, _Create_, and _Delete_ are mutator operations. These operations are asynchronous, and you might not see the effect immediately (e.g. _Get_ might not return the object by key immediately after you mutate the store.) Intermittent errors might occur even though the operation succeeds, so you should always check if the object store has been modified even if the mutating operation returns an error. Objects should be created with _Create_ operation and updated with _Update_ operation.

Resource versions record the last mutation operation on each object. If a mutation is applied to a different revision of an object than what the underlying storage expects as defined by pure equality, the operation is blocked. The client of this interface should not make assumptions about the structure or ordering of the revision identifier.

Object references supplied and returned from this interface should be treated as read-only. Modifying them violates thread-safety.

type ConfigStoreCache

type ConfigStoreCache interface {
	ConfigStore

	// RegisterEventHandler adds a handler to receive config update events for a
	// configuration type
	RegisterEventHandler(typ string, handler func(Config, Event))

	// Run until a signal is received
	Run(stop <-chan struct{})

	// HasSynced returns true after initial cache synchronization is complete
	HasSynced() bool
}

ConfigStoreCache is a local fully-replicated cache of the config store. The cache actively synchronizes its local state with the remote store and provides a notification mechanism to receive update events. As such, the notification handlers must be registered prior to calling _Run_, and the cache requires initial synchronization grace period after calling _Run_.

Update notifications require the following consistency guarantee: the view in the cache must be AT LEAST as fresh as the moment notification arrives, but MAY BE more fresh (e.g. if _Delete_ cancels an _Add_ event).

Handlers execute on the single worker queue in the order they are appended. Handlers receive the notification event and the associated object. Note that all handlers must be registered before starting the cache controller.

type Controller

type Controller interface {
	// AppendServiceHandler notifies about changes to the service catalog.
	AppendServiceHandler(f func(*Service, Event)) error

	// AppendInstanceHandler notifies about changes to the service instances
	// for a service.
	AppendInstanceHandler(f func(*ServiceInstance, Event)) error

	// Run until a signal is received
	Run(stop <-chan struct{})
}

Controller defines an event controller loop. Proxy agent registers itself with the controller loop and receives notifications on changes to the service topology or changes to the configuration artifacts.

The controller guarantees the following consistency requirement: registry view in the controller is as AT LEAST as fresh as the moment notification arrives, but MAY BE more fresh (e.g. "delete" cancels an "add" event). For example, an event for a service creation will see a service registry without the service if the event is immediately followed by the service deletion event.

Handlers execute on the single worker queue in the order they are appended. Handlers receive the notification event and the associated object. Note that all handlers must be appended before starting the controller.

type Environment

type Environment struct {
	// Discovery interface for listing services and instances.
	ServiceDiscovery

	// Config interface for listing routing rules
	IstioConfigStore

	// Mesh is the mesh config (to be merged into the config store)
	Mesh *meshconfig.MeshConfig

	// Mixer subject alternate name for mutual TLS
	MixerSAN []string

	// PushContext holds informations during push generation. It is reset on config change, at the beginning
	// of the pushAll. It will hold all errors and stats and possibly caches needed during the entire cache computation.
	// DO NOT USE EXCEPT FOR TESTS AND HANDLING OF NEW CONNECTIONS.
	// ALL USE DURING A PUSH SHOULD USE THE ONE CREATED AT THE
	// START OF THE PUSH, THE GLOBAL ONE MAY CHANGE AND REFLECT A DIFFERENT
	// CONFIG AND PUSH
	// Deprecated - a local config for ads will be used instead
	PushContext *PushContext

	// MeshNetworks (loaded from a config map) provides information about the
	// set of networks inside a mesh and how to route to endpoints in each
	// network. Each network provides information about the endpoints in a
	// routable L3 network. A single routable L3 network can have one or more
	// service registries.
	MeshNetworks *meshconfig.MeshNetworks
}

Environment provides an aggregate environmental API for Pilot

type Event

type Event int

Event represents a registry update event

const (
	// EventAdd is sent when an object is added
	EventAdd Event = iota

	// EventUpdate is sent when an object is modified
	// Captures the modified object
	EventUpdate

	// EventDelete is sent when an object is deleted
	// Captures the object at the last known state
	EventDelete
)

func (Event) String

func (event Event) String() string

type Hostname

type Hostname string

Hostname describes a (possibly wildcarded) hostname

func MostSpecificHostMatch

func MostSpecificHostMatch(needle Hostname, stack []Hostname) (Hostname, bool)

MostSpecificHostMatch compares the elements of the stack to the needle, and returns the longest stack element matching the needle, or false if no element in the stack matches the needle.

func ResolveHostname

func ResolveHostname(meta ConfigMeta, svc *mccpb.IstioService) Hostname

ResolveHostname produces a FQDN based on either the service or a concat of the namespace + domain Deprecated. Do not use

func ResolveShortnameToFQDN

func ResolveShortnameToFQDN(host string, meta ConfigMeta) Hostname

ResolveShortnameToFQDN uses metadata information to resolve a reference to shortname of the service to FQDN

func (Hostname) Matches

func (h Hostname) Matches(o Hostname) bool

Matches returns true if this hostname overlaps with the other hostname. Hostnames overlap if: - they're fully resolved (i.e. not wildcarded) and match exactly (i.e. an exact string match) - one or both are wildcarded (e.g. "*.foo.com"), in which case we use wildcard resolution rules to determine if h is covered by o or o is covered by h. e.g.:

Hostname("foo.com").Matches("foo.com")   = true
Hostname("foo.com").Matches("bar.com")   = false
Hostname("*.com").Matches("foo.com")     = true
Hostname("bar.com").Matches("*.com")     = true
Hostname("*.foo.com").Matches("foo.com") = false
Hostname("*").Matches("foo.com")         = true
Hostname("*").Matches("*.com")           = true

func (Hostname) SubsetOf

func (h Hostname) SubsetOf(o Hostname) bool

SubsetOf returns true if this hostname is a valid subset of the other hostname. The semantics are the same as "Matches", but only in one direction (i.e., h is covered by o).

type Hostnames

type Hostnames []Hostname

Hostnames is a collection of Hostname; it exists so it's easy to sort hostnames consistently across Pilot. In a few locations we care about the order hostnames appear in Envoy config: primarily HTTP routes, but also in gateways, and for SNI. In those locations, we sort hostnames longest to shortest with wildcards last.

func HostnamesForNamespace

func HostnamesForNamespace(hosts []string, namespace string) Hostnames

HostnamesForNamespace returns the subset of hosts that are in the specified namespace. The list of hosts contains host names optionally qualified with namespace/ or */. If not qualified or qualified with *, the host name is considered to be in every namespace. e.g.: HostnamesForNamespace(["ns1/foo.com","ns2/bar.com"], "ns1") = Hostnames(["foo.com"]) HostnamesForNamespace(["ns1/foo.com","ns2/bar.com"], "ns3") = Hostnames([]) HostnamesForNamespace(["ns1/foo.com","*/bar.com"], "ns1") = Hostnames(["foo.com","bar.com"]) HostnamesForNamespace(["ns1/foo.com","*/bar.com"], "ns3") = Hostnames(["bar.com"]) HostnamesForNamespace(["foo.com","ns2/bar.com"], "ns2") = Hostnames(["foo.com","bar.com"]) HostnamesForNamespace(["foo.com","ns2/bar.com"], "ns3") = Hostnames(["foo.com"])

func StringsToHostnames

func StringsToHostnames(hosts []string) Hostnames

StringsToHostnames converts a slice of host name strings to type Hostnames.

func (Hostnames) Contains

func (h Hostnames) Contains(host Hostname) bool

func (Hostnames) Intersection

func (h Hostnames) Intersection(other Hostnames) Hostnames

Intersection returns the subset of host names that are covered by both h and other. e.g.:

Hostnames(["foo.com","bar.com"]).Intersection(Hostnames(["*.com"]))         = Hostnames(["foo.com","bar.com"])
Hostnames(["foo.com","*.net"]).Intersection(Hostnames(["*.com","bar.net"])) = Hostnames(["foo.com","bar.net"])
Hostnames(["foo.com","*.net"]).Intersection(Hostnames(["*.bar.net"]))       = Hostnames(["*.bar.net"])
Hostnames(["foo.com"]).Intersection(Hostnames(["bar.com"]))                 = Hostnames([])
Hostnames([]).Intersection(Hostnames(["bar.com"])                           = Hostnames([])

func (Hostnames) Len

func (h Hostnames) Len() int

func (Hostnames) Less

func (h Hostnames) Less(i, j int) bool

func (Hostnames) Swap

func (h Hostnames) Swap(i, j int)

type IstioConfigStore

type IstioConfigStore interface {
	ConfigStore

	// ServiceEntries lists all service entries
	ServiceEntries() []Config

	// Gateways lists all gateways bound to the specified workload labels
	Gateways(workloadLabels LabelsCollection) []Config

	// EnvoyFilter lists the envoy filter configuration bound to the specified workload labels
	EnvoyFilter(workloadLabels LabelsCollection) *Config

	// HTTPAPISpecByDestination selects Mixerclient HTTP API Specs
	// associated with destination service instances.
	HTTPAPISpecByDestination(instance *ServiceInstance) []Config

	// QuotaSpecByDestination selects Mixerclient quota specifications
	// associated with destination service instances.
	QuotaSpecByDestination(instance *ServiceInstance) []Config

	// AuthenticationPolicyForWorkload selects authentication policy associated
	// with a workload (or labels if specified) + port.
	// If there are more than one policies at different scopes (global, namespace, service)
	// the one with the most specific scope will be selected. If there are more than
	// one with the same scope, the first one seen will be used (later, we should
	// have validation at submitting time to prevent this scenario from happening)
	AuthenticationPolicyForWorkload(service *Service, labels Labels, port *Port) *Config

	// ServiceRoles selects ServiceRoles in the specified namespace.
	ServiceRoles(namespace string) []Config

	// ServiceRoleBindings selects ServiceRoleBindings in the specified namespace.
	ServiceRoleBindings(namespace string) []Config

	// AuthorizationPolicies selects AuthorizationPolicies in the specified namespace.
	AuthorizationPolicies(namespace string) []Config

	// RbacConfig selects the RbacConfig of name DefaultRbacConfigName.
	RbacConfig() *Config

	// ClusterRbacConfig selects the ClusterRbacConfig of name DefaultRbacConfigName.
	ClusterRbacConfig() *Config
}

IstioConfigStore is a specialized interface to access config store using Istio configuration types nolint

func MakeIstioStore

func MakeIstioStore(store ConfigStore) IstioConfigStore

MakeIstioStore creates a wrapper around a store. In pilot it is initialized with a ConfigStoreCache, tests only use a regular ConfigStore.

type IstioEgressListenerWrapper

type IstioEgressListenerWrapper struct {
	// The actual IstioEgressListener api object from the Config. It can be
	// nil if this is for the default sidecar scope.
	IstioListener *networking.IstioEgressListener
	// contains filtered or unexported fields
}

IstioEgressListenerWrapper is a wrapper for networking.IstioEgressListener object. The wrapper provides performance optimizations as it allows us to precompute and store the list of services/virtualServices that apply to this listener.

func (*IstioEgressListenerWrapper) Services

func (ilw *IstioEgressListenerWrapper) Services() []*Service

Services returns the list of services imported by this egress listener

func (*IstioEgressListenerWrapper) VirtualServices

func (ilw *IstioEgressListenerWrapper) VirtualServices() []Config

VirtualServices returns the list of virtual services imported by this egress listener

type IstioEndpoint

type IstioEndpoint struct {

	// Labels points to the workload or deployment labels.
	Labels map[string]string

	// Family indicates what type of endpoint, such as TCP or Unix Domain Socket.
	// Default is TCP.
	Family AddressFamily

	// Address is the address of the endpoint, using envoy proto.
	Address string

	// ServicePortName tracks the name of the port, to avoid 'eventual consistency' issues.
	// Sometimes the Endpoint is visible before Service - so looking up the port number would
	// fail. Instead the mapping to number is made when the clusters are computed. The lazy
	// computation will also help with 'on-demand' and 'split horizon' - where it will be skipped
	// for not used clusters or endpoints behind a gate.
	ServicePortName string

	// UID identifies the workload, for telemetry purpose.
	UID string

	// EnvoyEndpoint is a cached LbEndpoint, converted from the data, to
	// avoid recomputation
	EnvoyEndpoint *endpoint.LbEndpoint

	// ServiceAccount holds the associated service account.
	ServiceAccount string

	// Network holds the network where this endpoint is present
	Network string

	// The locality where the endpoint is present. / separated string
	Locality string

	// EndpointPort is the port where the workload is listening, can be different
	// from the service port.
	EndpointPort uint32

	// The load balancing weight associated with this endpoint.
	LbWeight uint32
}

IstioEndpoint has the information about a single address+port for a specific service and shard.

TODO: Replace NetworkEndpoint and ServiceInstance with Istio endpoints - ServicePortName replaces ServicePort, since port number and protocol may not be available when endpoint callbacks are made. - It no longer splits into one ServiceInstance and one NetworkEndpoint - both are in a single struct - doesn't have a pointer to Service - the full Service object may not be available at the time the endpoint is received. The service name is used as a key and used to reconcile. - it has a cached EnvoyEndpoint object - to avoid re-allocating it for each request and client.

type Labels

type Labels map[string]string

Labels is a non empty set of arbitrary strings. Each version of a service can be differentiated by a unique set of labels associated with the version. These labels are assigned to all instances of a particular service version. For example, lets say catalog.mystore.com has 2 versions v1 and v2. v1 instances could have labels gitCommit=aeiou234, region=us-east, while v2 instances could have labels name=kittyCat,region=us-east.

func ParseLabelsString

func ParseLabelsString(s string) Labels

ParseLabelsString extracts labels from a string

func (Labels) Equals

func (l Labels) Equals(that Labels) bool

Equals returns true if the labels are identical

func (Labels) String

func (l Labels) String() string

func (Labels) SubsetOf

func (l Labels) SubsetOf(that Labels) bool

SubsetOf is true if the label has identical values for the keys

func (Labels) Validate

func (l Labels) Validate() error

Validate ensures tag is well-formed

type LabelsCollection

type LabelsCollection []Labels

LabelsCollection is a collection of labels used for comparing labels against a collection of labels

func (LabelsCollection) HasSubsetOf

func (labels LabelsCollection) HasSubsetOf(that Labels) bool

HasSubsetOf returns true if the input labels are a super set of one labels in a collection or if the tag collection is empty

func (LabelsCollection) IsSupersetOf

func (labels LabelsCollection) IsSupersetOf(that Labels) bool

IsSupersetOf returns true if the input labels are a subset set of any set of labels in a collection

type MergedGateway

type MergedGateway struct {
	// maps from physical port to virtual servers
	Servers map[uint32][]*networking.Server

	// maps from server to the owning gateway name
	// Needed to select the set of virtual services that apply to a port
	GatewayNameForServer map[*networking.Server]string

	// maps from port names to virtual hosts
	// Used for RDS. No two port names share same port except for HTTPS
	// The typical length of the value is always 1, except for HTTP (not HTTPS),
	ServersByRouteName map[string][]*networking.Server

	// maps from server to a corresponding RDS route name
	// Inverse of ServersByRouteName. Returning this as part of merge result allows to keep route name generation logic
	// encapsulated within the model and, as a side effect, to avoid generating route names twice.
	RouteNamesByServer map[*networking.Server]string
}

MergedGateway describes a set of gateways for a workload merged into a single logical gateway.

TODO: do we need a `func (m *MergedGateway) MergeInto(gateway *networking.Gateway)`?

func MergeGateways

func MergeGateways(gateways ...Config) *MergedGateway

MergeGateways combines multiple gateways targeting the same workload into a single logical Gateway. Note that today any Servers in the combined gateways listening on the same port must have the same protocol. If servers with different protocols attempt to listen on the same port, one of the protocols will be chosen at random.

type NetworkEndpoint

type NetworkEndpoint struct {
	// Family indicates what type of endpoint, such as TCP or Unix Domain Socket.
	Family AddressFamily

	// Address of the network endpoint. If Family is `AddressFamilyTCP`, it is
	// typically an IPv4 address. If Family is `AddressFamilyUnix`, it is the
	// path to the domain socket.
	Address string

	// Port number where this instance is listening for connections This
	// need not be the same as the port where the service is accessed.
	// e.g., catalog.mystore.com:8080 -> 172.16.0.1:55446
	// Ignored for `AddressFamilyUnix`.
	Port int

	// Port declaration from the service declaration This is the port for
	// the service associated with this instance (e.g.,
	// catalog.mystore.com)
	ServicePort *Port

	// Defines a platform-specific workload instance identifier (optional).
	UID string

	// The network where this endpoint is present
	Network string

	// The locality where the endpoint is present. / separated string
	Locality string

	// The load balancing weight associated with this endpoint.
	LbWeight uint32
}

NetworkEndpoint defines a network address (IP:port) associated with an instance of the service. A service has one or more instances each running in a container/VM/pod. If a service has multiple ports, then the same instance IP is expected to be listening on multiple ports (one per each service port). Note that the port associated with an instance does not have to be the same as the port associated with the service. Depending on the network setup (NAT, overlays), this could vary.

For e.g., if catalog.mystore.com is accessible through port 80 and 8080, and it maps to an instance with IP 172.16.0.1, such that connections to port 80 are forwarded to port 55446, and connections to port 8080 are forwarded to port 33333,

then internally, we have two two endpoint structs for the service catalog.mystore.com

--> 172.16.0.1:54546 (with ServicePort pointing to 80) and
--> 172.16.0.1:33333 (with ServicePort pointing to 8080)

type NodeType

type NodeType string

NodeType decides the responsibility of the proxy serves in the mesh

const (
	// SidecarProxy type is used for sidecar proxies in the application containers
	SidecarProxy NodeType = "sidecar"

	// Ingress type is used for cluster ingress proxies
	Ingress NodeType = "ingress"

	// Router type is used for standalone proxies acting as L7/L4 routers
	Router NodeType = "router"
)

type Port

type Port struct {
	// Name ascribes a human readable name for the port object. When a
	// service has multiple ports, the name field is mandatory
	Name string `json:"name,omitempty"`

	// Port number where the service can be reached. Does not necessarily
	// map to the corresponding port numbers for the instances behind the
	// service. See NetworkEndpoint definition below.
	Port int `json:"port"`

	// Protocol to be used for the port.
	Protocol Protocol `json:"protocol,omitempty"`
}

Port represents a network port where a service is listening for connections. The port should be annotated with the type of protocol used by the port.

func ParseJwksURI

func ParseJwksURI(jwksURI string) (string, *Port, bool, error)

ParseJwksURI parses the input URI and returns the corresponding hostname, port, and whether SSL is used. URI must start with "http://" or "https://", which corresponding to "http" or "https" scheme. Port number is extracted from URI if available (i.e from postfix :<port>, eg. ":80"), or assigned to a default value based on URI scheme (80 for http and 443 for https). Port name is set to URI scheme value. Note: this is to replace [buildJWKSURIClusterNameAndAddress] (https://github.com/istio/istio/blob/master/pilot/pkg/proxy/envoy/v1/mixer.go#L401), which is used for the old EUC policy.

func (Port) Match

func (port Port) Match(portSelector *authn.PortSelector) bool

Match returns true if port matches with authentication port selector criteria.

type PortList

type PortList []*Port

PortList is a set of ports

func (PortList) Get

func (ports PortList) Get(name string) (*Port, bool)

Get retrieves a port declaration by name

func (PortList) GetByPort

func (ports PortList) GetByPort(num int) (*Port, bool)

GetByPort retrieves a port declaration by port value

func (PortList) GetNames

func (ports PortList) GetNames() []string

GetNames returns port names

type Probe

type Probe struct {
	Port *Port  `json:"port,omitempty"`
	Path string `json:"path,omitempty"`
}

Probe represents a health probe associated with an instance of service.

type ProbeList

type ProbeList []*Probe

ProbeList is a set of probes

type ProtoSchema

type ProtoSchema struct {
	// ClusterScoped is true for resource in cluster-level.
	ClusterScoped bool

	// Name of the (go) object define the schema. Leave blank to infer from the 'Type' below.
	// This field is used to generate Kube CRD types map (pilot/pkg/config/kube/crd/types.go).
	SchemaObjectName string

	// Type is the config proto type.
	Type string

	// Plural is the type in plural.
	Plural string

	// Group is the config proto group.
	Group string

	// Version is the config proto version.
	Version string

	// MessageName refers to the protobuf message type name corresponding to the type
	MessageName string

	// Validate configuration as a protobuf message assuming the object is an
	// instance of the expected message type
	Validate func(name, namespace string, config proto.Message) error

	// MCP collection for this configuration resource schema
	Collection string
}

ProtoSchema provides description of the configuration schema and its key function nolint: maligned

func (*ProtoSchema) FromJSON

func (ps *ProtoSchema) FromJSON(js string) (proto.Message, error)

FromJSON converts a canonical JSON to a proto message

func (*ProtoSchema) FromJSONMap

func (ps *ProtoSchema) FromJSONMap(data interface{}) (proto.Message, error)

FromJSONMap converts from a generic map to a proto message using canonical JSON encoding JSON encoding is specified here: https://developers.google.com/protocol-buffers/docs/proto3#json

func (*ProtoSchema) FromYAML

func (ps *ProtoSchema) FromYAML(yml string) (proto.Message, error)

FromYAML converts a canonical YAML to a proto message

func (*ProtoSchema) Make

func (ps *ProtoSchema) Make() (proto.Message, error)

Make creates a new instance of the proto message

type Protocol

type Protocol string

Protocol defines network protocols for ports

const (
	// ProtocolGRPC declares that the port carries gRPC traffic.
	ProtocolGRPC Protocol = "GRPC"
	// ProtocolGRPCWeb declares that the port carries gRPC traffic.
	ProtocolGRPCWeb Protocol = "GRPC-Web"
	// ProtocolHTTP declares that the port carries HTTP/1.1 traffic.
	// Note that HTTP/1.0 or earlier may not be supported by the proxy.
	ProtocolHTTP Protocol = "HTTP"
	// ProtocolHTTP2 declares that the port carries HTTP/2 traffic.
	ProtocolHTTP2 Protocol = "HTTP2"
	// ProtocolHTTPS declares that the port carries HTTPS traffic.
	ProtocolHTTPS Protocol = "HTTPS"
	// ProtocolTCP declares the the port uses TCP.
	// This is the default protocol for a service port.
	ProtocolTCP Protocol = "TCP"
	// ProtocolTLS declares that the port carries TLS traffic.
	// TLS traffic is assumed to contain SNI as part of the handshake.
	ProtocolTLS Protocol = "TLS"
	// ProtocolUDP declares that the port uses UDP.
	// Note that UDP protocol is not currently supported by the proxy.
	ProtocolUDP Protocol = "UDP"
	// ProtocolMongo declares that the port carries MongoDB traffic.
	ProtocolMongo Protocol = "Mongo"
	// ProtocolRedis declares that the port carries Redis traffic.
	ProtocolRedis Protocol = "Redis"
	// ProtocolMySQL declares that the port carries MySQL traffic.
	ProtocolMySQL Protocol = "MySQL"
	// ProtocolUnsupported - value to signify that the protocol is unsupported.
	ProtocolUnsupported Protocol = "UnsupportedProtocol"
)

func ParseProtocol

func ParseProtocol(s string) Protocol

ParseProtocol from string ignoring case

func (Protocol) IsHTTP

func (p Protocol) IsHTTP() bool

IsHTTP is true for protocols that use HTTP as transport protocol

func (Protocol) IsHTTP2

func (p Protocol) IsHTTP2() bool

IsHTTP2 is true for protocols that use HTTP/2 as transport protocol

func (Protocol) IsTCP

func (p Protocol) IsTCP() bool

IsTCP is true for protocols that use TCP as transport protocol

func (Protocol) IsTLS

func (p Protocol) IsTLS() bool

IsTLS is true for protocols on top of TLS (e.g. HTTPS)

type Proxy

type Proxy struct {
	// ClusterID specifies the cluster where the proxy resides.
	// TODO: clarify if this is needed in the new 'network' model, likely needs to
	// be renamed to 'network'
	ClusterID string

	// Type specifies the node type. First part of the ID.
	Type NodeType

	// IPAddresses is the IP addresses of the proxy used to identify it and its
	// co-located service instances. Example: "10.60.1.6". In some cases, the host
	// where the poxy and service instances reside may have more than one IP address
	IPAddresses []string

	// ID is the unique platform-specific sidecar proxy ID. For k8s it is the pod ID and
	// namespace.
	ID string

	// Locality is the location of where Envoy proxy runs. This is extracted from
	// the registry where possible. If the registry doesn't provide a locality for the
	// proxy it will use the one sent via ADS that can be configured in the Envoy bootstrap
	Locality *core.Locality

	// DNSDomain defines the DNS domain suffix for short hostnames (e.g.
	// "default.svc.cluster.local")
	DNSDomain string

	// TrustDomain defines the trust domain of the certificate
	TrustDomain string

	//identity that will be the suffix of the spiffe id for SAN verification when connecting to pilot
	//spiffe://{TrustDomain}/{PilotIdentity}
	PilotIdentity string

	//identity that will be the suffix of the spiffe id for SAN verification when connecting to mixer
	//spiffe://{TrustDomain}/{MixerIdentity}
	//this value would only be used by pilot's proxy to connect to mixer.  All proxies would get mixer SAN pushed through pilot
	MixerIdentity string

	// ConfigNamespace defines the namespace where this proxy resides
	// for the purposes of network scoping.
	// NOTE: DO NOT USE THIS FIELD TO CONSTRUCT DNS NAMES
	ConfigNamespace string

	// Metadata key-value pairs extending the Node identifier
	Metadata map[string]string

	// the sidecarScope associated with the proxy
	SidecarScope *SidecarScope

	// service instances associated with the proxy
	ServiceInstances []*ServiceInstance

	// labels associated with the workload
	WorkloadLabels LabelsCollection
}

Proxy contains information about an specific instance of a proxy (envoy sidecar, gateway, etc). The Proxy is initialized when a sidecar connects to Pilot, and populated from 'node' info in the protocol as well as data extracted from registries.

In current Istio implementation nodes use a 4-parts '~' delimited ID. Type~IPAddress~ID~Domain

func ParseServiceNodeWithMetadata

func ParseServiceNodeWithMetadata(s string, metadata map[string]string) (*Proxy, error)

ParseServiceNodeWithMetadata parse the Envoy Node from the string generated by ServiceNode fuction and the metadata.

func (*Proxy) GetInterceptionMode

func (node *Proxy) GetInterceptionMode() TrafficInterceptionMode

GetInterceptionMode extracts the interception mode associated with the proxy from the proxy metadata

func (*Proxy) GetProxyVersion

func (node *Proxy) GetProxyVersion() (string, bool)

GetProxyVersion returns the proxy version string identifier, and whether it is present.

func (*Proxy) GetRouterMode

func (node *Proxy) GetRouterMode() RouterMode

GetRouterMode returns the operating mode associated with the router. Assumes that the proxy is of type Router

func (*Proxy) ServiceNode

func (node *Proxy) ServiceNode() string

ServiceNode encodes the proxy node attributes into a URI-acceptable string

func (*Proxy) SetServiceInstances

func (node *Proxy) SetServiceInstances(env *Environment) error

func (*Proxy) SetSidecarScope

func (node *Proxy) SetSidecarScope(ps *PushContext)

SetSidecarScope identifies the sidecar scope object associated with this proxy and updates the proxy Node. This is a convenience hack so that callers can simply call push.Services(node) while the implementation of push.Services can return the set of services from the proxyNode's sidecar scope or from the push context's set of global services. Similar logic applies to push.VirtualServices and push.DestinationRule. The short cut here is useful only for CDS and parts of RDS generation code.

Listener generation code will still use the SidecarScope object directly as it needs the set of services for each listener port.

func (*Proxy) SetWorkloadLabels

func (node *Proxy) SetWorkloadLabels(env *Environment) error

type ProxyPushStatus

type ProxyPushStatus struct {
	Proxy   string `json:"proxy,omitempty"`
	Message string `json:"message,omitempty"`
}

ProxyPushStatus represents an event captured during config push to proxies. It may contain additional message and the affected proxy.

type PushContext

type PushContext struct {

	// ProxyStatus is keyed by the error code, and holds a map keyed
	// by the ID.
	ProxyStatus map[string]map[string]ProxyPushStatus

	// Start represents the time of last config change that reset the
	// push status.
	Start time.Time
	End   time.Time

	// Mutex is used to protect the below store.
	// All data is set when the PushContext object is populated in `InitContext`,
	// data should not be changed by plugins.
	Mutex sync.Mutex `json:"-"`

	// ServiceByHostname has all services, indexed by hostname.
	ServiceByHostname map[Hostname]*Service `json:"-"`

	// AuthzPolicies stores the existing authorization policies in the cluster. Could be nil if there
	// are no authorization policies in the cluster.
	AuthzPolicies *AuthorizationPolicies `json:"-"`

	// Env has a pointer to the shared environment used to create the snapshot.
	Env *Environment `json:"-"`

	// ServicePort2Name is used to keep track of service name and port mapping.
	// This is needed because ADS names use port numbers, while endpoints use
	// port names. The key is the service name. If a service or port are not found,
	// the endpoint needs to be re-evaluated later (eventual consistency)
	ServicePort2Name map[string]PortList `json:"-"`

	// ServiceAccounts contains a map of hostname and port to service accounts.
	ServiceAccounts map[Hostname]map[int][]string `json:"-"`
	// contains filtered or unexported fields
}

PushContext tracks the status of a push - metrics and errors. Metrics are reset after a push - at the beginning all values are zero, and when push completes the status is reset. The struct is exposed in a debug endpoint - fields public to allow easy serialization as json.

func NewPushContext

func NewPushContext() *PushContext

NewPushContext creates a new PushContext structure to track push status.

func (*PushContext) Add

func (ps *PushContext) Add(metric *PushMetric, key string, proxy *Proxy, msg string)

Add will add an case to the metric.

func (*PushContext) AddVirtualServiceForTesting

func (ps *PushContext) AddVirtualServiceForTesting(config *Config)

AddVirtualServiceForTesting adds a virtual service to the push context. It is to be used for TESTING ONLY.

func (*PushContext) DestinationRule

func (ps *PushContext) DestinationRule(proxy *Proxy, service *Service) *Config

DestinationRule returns a destination rule for a service name in a given domain.

func (*PushContext) GetAllSidecarScopes

func (ps *PushContext) GetAllSidecarScopes() map[string][]*SidecarScope

GetAllSidecarScopes returns a map of namespace and the set of SidecarScope object associated with the namespace. This will be used by the CDS code to precompute CDS output for each sidecar scope. Since we have a default sidecarscope for namespaces that dont explicitly have one, we are guaranteed to have the CDS output cached for every namespace/sidecar scope combo.

func (*PushContext) InitContext

func (ps *PushContext) InitContext(env *Environment) error

InitContext will initialize the data structures used for code generation. This should be called before starting the push, from the thread creating the push context.

func (*PushContext) JSON

func (ps *PushContext) JSON() ([]byte, error)

JSON implements json.Marshaller, with a lock.

func (*PushContext) OnConfigChange

func (ps *PushContext) OnConfigChange()

OnConfigChange is called when a config change is detected.

func (*PushContext) Services

func (ps *PushContext) Services(proxy *Proxy) []*Service

Services returns the list of services that are visible to a Proxy in a given config namespace

func (*PushContext) SetDestinationRules

func (ps *PushContext) SetDestinationRules(configs []Config)

SetDestinationRules is updates internal structures using a set of configs. Split out of DestinationRule expensive conversions, computed once per push. This also allows tests to inject a config without having the mock.

func (*PushContext) SubsetToLabels

func (ps *PushContext) SubsetToLabels(proxy *Proxy, subsetName string, hostname Hostname) LabelsCollection

SubsetToLabels returns the labels associated with a subset of a given service.

func (*PushContext) UpdateMetrics

func (ps *PushContext) UpdateMetrics()

UpdateMetrics will update the prometheus metrics based on the current status of the push.

func (*PushContext) VirtualServices

func (ps *PushContext) VirtualServices(proxy *Proxy, gateways map[string]bool) []Config

VirtualServices lists all virtual services bound to the specified gateways This replaces store.VirtualServices. Used only by the gateways Sidecars use the egressListener.VirtualServices().

type PushMetric

type PushMetric struct {
	Name string
	// contains filtered or unexported fields
}

PushMetric wraps a prometheus metric.

type Resolution

type Resolution int

Resolution indicates how the service instances need to be resolved before routing traffic.

const (
	// ClientSideLB implies that the proxy will decide the endpoint from its local lb pool
	ClientSideLB Resolution = iota
	// DNSLB implies that the proxy will resolve a DNS address and forward to the resolved address
	DNSLB
	// Passthrough implies that the proxy should forward traffic to the destination IP requested by the caller
	Passthrough
)

type RolesAndBindings

type RolesAndBindings struct {
	// ServiceRoles in the same namespace.
	Roles []Config

	// Maps from ServiceRole name to its associated ServiceRoleBindings.
	RoleNameToBindings map[string][]*rbacproto.ServiceRoleBinding
}

RolesAndBindings stores the the ServiceRole and ServiceRoleBinding in the same namespace.

type RouterMode

type RouterMode string

RouterMode decides the behavior of Istio Gateway (normal or sni-dnat)

const (
	// StandardRouter is the normal gateway mode
	StandardRouter RouterMode = "standard"

	// SniDnatRouter is used for bridging two networks
	SniDnatRouter RouterMode = "sni-dnat"
)

type Service

type Service struct {
	// Hostname of the service, e.g. "catalog.mystore.com"
	Hostname Hostname `json:"hostname"`

	// Address specifies the service IPv4 address of the load balancer
	Address string `json:"address,omitempty"`

	// Protect concurrent ClusterVIPs read/write
	Mutex sync.RWMutex
	// ClusterVIPs specifies the service address of the load balancer
	// in each of the clusters where the service resides
	ClusterVIPs map[string]string `json:"cluster-vips,omitempty"`

	// Ports is the set of network ports where the service is listening for
	// connections
	Ports PortList `json:"ports,omitempty"`

	// ServiceAccounts specifies the service accounts that run the service.
	ServiceAccounts []string `json:"serviceaccounts,omitempty"`

	// MeshExternal (if true) indicates that the service is external to the mesh.
	// These services are defined using Istio's ServiceEntry spec.
	MeshExternal bool

	// Resolution indicates how the service instances need to be resolved before routing
	// traffic. Most services in the service registry will use static load balancing wherein
	// the proxy will decide the service instance that will receive the traffic. Service entries
	// could either use DNS load balancing (i.e. proxy will query DNS server for the IP of the service)
	// or use the passthrough model (i.e. proxy will forward the traffic to the network endpoint requested
	// by the caller)
	Resolution Resolution

	// CreationTime records the time this service was created, if available.
	CreationTime time.Time `json:"creationTime,omitempty"`

	// Attributes contains additional attributes associated with the service
	// used mostly by mixer and RBAC for policy enforcement purposes.
	Attributes ServiceAttributes
}

Service describes an Istio service (e.g., catalog.mystore.com:8080) Each service has a fully qualified domain name (FQDN) and one or more ports where the service is listening for connections. *Optionally*, a service can have a single load balancer/virtual IP address associated with it, such that the DNS queries for the FQDN resolves to the virtual IP address (a load balancer IP).

E.g., in kubernetes, a service foo is associated with foo.default.svc.cluster.local hostname, has a virtual IP of 10.0.1.1 and listens on ports 80, 8080

func (*Service) External

func (s *Service) External() bool

External predicate checks whether the service is external

func (*Service) GetServiceAddressForProxy

func (s *Service) GetServiceAddressForProxy(node *Proxy) string

GetServiceAddressForProxy returns a Service's IP address specific to the cluster where the node resides

func (*Service) Key

func (s *Service) Key(port *Port, labels Labels) string

Key generates a unique string referencing service instances for a given port and labels. The separator character must be exclusive to the regular expressions allowed in the service declaration. Deprecated

func (*Service) Validate

func (s *Service) Validate() error

Validate ensures that the service object is well-defined

type ServiceAttributes

type ServiceAttributes struct {
	// Name is "destination.service.name" attribute
	Name string
	// Namespace is "destination.service.namespace" attribute
	Namespace string
	// UID is "destination.service.uid" attribute
	UID string
	// ExportTo defines the visibility of Service in
	// a namespace when the namespace is imported.
	ExportTo map[Visibility]bool
}

ServiceAttributes represents a group of custom attributes of the service.

type ServiceDiscovery

type ServiceDiscovery interface {
	// Services list declarations of all services in the system
	Services() ([]*Service, error)

	// GetService retrieves a service by host name if it exists
	// Deprecated - do not use for anything other than tests
	GetService(hostname Hostname) (*Service, error)

	// InstancesByPort retrieves instances for a service on the given ports with labels that match
	// any of the supplied labels. All instances match an empty tag list.
	//
	// For example, consider the example of catalog.mystore.com as described in NetworkEndpoints
	// Instances(catalog.myservice.com, 80) ->
	//      --> NetworkEndpoint(172.16.0.1:8888), Service(catalog.myservice.com), Labels(foo=bar)
	//      --> NetworkEndpoint(172.16.0.2:8888), Service(catalog.myservice.com), Labels(foo=bar)
	//      --> NetworkEndpoint(172.16.0.3:8888), Service(catalog.myservice.com), Labels(kitty=cat)
	//      --> NetworkEndpoint(172.16.0.4:8888), Service(catalog.myservice.com), Labels(kitty=cat)
	//
	// Calling Instances with specific labels returns a trimmed list.
	// e.g., Instances(catalog.myservice.com, 80, foo=bar) ->
	//      --> NetworkEndpoint(172.16.0.1:8888), Service(catalog.myservice.com), Labels(foo=bar)
	//      --> NetworkEndpoint(172.16.0.2:8888), Service(catalog.myservice.com), Labels(foo=bar)
	//
	// Similar concepts apply for calling this function with a specific
	// port, hostname and labels.
	//
	// Introduced in Istio 0.8. It is only called with 1 port.
	// CDS (clusters.go) calls it for building 'dnslb' type clusters.
	// EDS calls it for building the endpoints result.
	// Consult istio-dev before using this for anything else (except debugging/tools)
	InstancesByPort(hostname Hostname, servicePort int, labels LabelsCollection) ([]*ServiceInstance, error)

	// GetProxyServiceInstances returns the service instances that co-located with a given Proxy
	//
	// Co-located generally means running in the same network namespace and security context.
	//
	// A Proxy operating as a Sidecar will return a non-empty slice.  A stand-alone Proxy
	// will return an empty slice.
	//
	// There are two reasons why this returns multiple ServiceInstances instead of one:
	// - A ServiceInstance has a single NetworkEndpoint which has a single Port.  But a Service
	//   may have many ports.  So a workload implementing such a Service would need
	//   multiple ServiceInstances, one for each port.
	// - A single workload may implement multiple logical Services.
	//
	// In the second case, multiple services may be implemented by the same physical port number,
	// though with a different ServicePort and NetworkEndpoint for each.  If any of these overlapping
	// services are not HTTP or H2-based, behavior is undefined, since the listener may not be able to
	// determine the intended destination of a connection without a Host header on the request.
	GetProxyServiceInstances(*Proxy) ([]*ServiceInstance, error)

	GetProxyWorkloadLabels(*Proxy) (LabelsCollection, error)

	// ManagementPorts lists set of management ports associated with an IPv4 address.
	// These management ports are typically used by the platform for out of band management
	// tasks such as health checks, etc. In a scenario where the proxy functions in the
	// transparent mode (traps all traffic to and from the service instance IP address),
	// the configuration generated for the proxy will not manipulate traffic destined for
	// the management ports
	ManagementPorts(addr string) PortList

	// WorkloadHealthCheckInfo lists set of probes associated with an IPv4 address.
	// These probes are used by the platform to identify requests that are performing
	// health checks.
	WorkloadHealthCheckInfo(addr string) ProbeList

	// GetIstioServiceAccounts returns a list of service accounts looked up from
	// the specified service hostname and ports.
	// Deprecated - service account tracking moved to XdsServer, incremental.
	GetIstioServiceAccounts(hostname Hostname, ports []int) []string
}

ServiceDiscovery enumerates Istio service instances. nolint: lll

type ServiceInstance

type ServiceInstance struct {
	Endpoint       NetworkEndpoint `json:"endpoint,omitempty"`
	Service        *Service        `json:"service,omitempty"`
	Labels         Labels          `json:"labels,omitempty"`
	ServiceAccount string          `json:"serviceaccount,omitempty"`
}

ServiceInstance represents an individual instance of a specific version of a service. It binds a network endpoint (ip:port), the service description (which is oblivious to various versions) and a set of labels that describe the service version associated with this instance.

Since a ServiceInstance has a single NetworkEndpoint, which has a single port, multiple ServiceInstances are required to represent a workload that listens on multiple ports.

The labels associated with a service instance are unique per a network endpoint. There is one well defined set of labels for each service instance network endpoint.

For example, the set of service instances associated with catalog.mystore.com are modeled like this

--> NetworkEndpoint(172.16.0.1:8888), Service(catalog.myservice.com), Labels(foo=bar)
--> NetworkEndpoint(172.16.0.2:8888), Service(catalog.myservice.com), Labels(foo=bar)
--> NetworkEndpoint(172.16.0.3:8888), Service(catalog.myservice.com), Labels(kitty=cat)
--> NetworkEndpoint(172.16.0.4:8888), Service(catalog.myservice.com), Labels(kitty=cat)

func (*ServiceInstance) GetLocality

func (si *ServiceInstance) GetLocality() string

GetLocality returns the availability zone from an instance. If service instance label for locality is set we use this. Otherwise, we use the one set by the registry:

  • k8s: region/zone, extracted from node's failure-domain.beta.kubernetes.io/{region,zone}
  • consul: defaults to 'instance.Datacenter'

This is used by CDS/EDS to group the endpoints by locality.

func (*ServiceInstance) Validate

func (instance *ServiceInstance) Validate() error

Validate ensures that the service instance is well-defined

type SidecarScope

type SidecarScope struct {
	// The crd itself. Can be nil if we are constructing the default
	// sidecar scope
	Config *Config

	// Set of egress listeners, and their associated services.  A sidecar
	// scope should have either ingress/egress listeners or both.  For
	// every proxy workload that maps to a sidecar API object (or the
	// default object), we will go through every egress listener in the
	// object and process the Envoy listener or RDS based on the imported
	// services/virtual services in that listener.
	EgressListeners []*IstioEgressListenerWrapper

	// HasCustomIngressListeners is a convenience variable that if set to
	// true indicates that the config object has one or more listeners.
	// If set to false, networking code should derive the inbound
	// listeners from the proxy service instances
	HasCustomIngressListeners bool

	// CDSOutboundClusters is the CDS output for sidecars that map to this
	// sidecarScope object. Contains the outbound clusters only, indexed
	// by localities
	CDSOutboundClusters map[string][]*xdsapi.Cluster
	// contains filtered or unexported fields
}

SidecarScope is a wrapper over the Sidecar resource with some preprocessed data to determine the list of services, virtualServices, and destinationRules that are accessible to a given sidecar. Precomputing the list of services, virtual services, dest rules for a sidecar improves performance as we no longer need to compute this list for every sidecar. We simply have to match a sidecar to a SidecarScope. Note that this is not the same as public/private scoped services. The list of services seen by every sidecar scope (namespace wide or per workload) depends on the imports, the listeners, and other settings.

Every proxy workload of SidecarProxy type will always map to a SidecarScope object. If the proxy's namespace does not have a user specified Sidecar CRD, we will construct one that has a catch all egress listener that imports every public service/virtualService in the mesh.

func ConvertToSidecarScope

func ConvertToSidecarScope(ps *PushContext, sidecarConfig *Config, configNamespace string) *SidecarScope

ConvertToSidecarScope converts from Sidecar config to SidecarScope object

func DefaultSidecarScopeForNamespace

func DefaultSidecarScopeForNamespace(ps *PushContext, configNamespace string) *SidecarScope

DefaultSidecarScope is a sidecar scope object with a default catch all egress listener that matches the default Istio behavior: a sidecar has listeners for all services in the mesh We use this scope when the user has not set any sidecar Config for a given config namespace.

func (*SidecarScope) DestinationRule

func (sc *SidecarScope) DestinationRule(hostname Hostname) *Config

DestinationRule returns the destination rule applicable for a given hostname used by CDS code

func (*SidecarScope) GetEgressListenerForRDS

func (sc *SidecarScope) GetEgressListenerForRDS(port int, bind string) *IstioEgressListenerWrapper

GetEgressListenerForRDS returns the egress listener corresponding to the listener port or the bind address or the catch all listener

func (*SidecarScope) Services

func (sc *SidecarScope) Services() []*Service

Services returns the list of services imported across all egress listeners by this Sidecar config

type TraceConfig

type TraceConfig struct {
	ClientSampling  float64
	RandomSampling  float64
	OverallSampling float64
}

TraceConfig values are percentages 0.0 - 100.0

func GetTraceConfig

func GetTraceConfig() TraceConfig

GetTraceConfig returns configured TraceConfig

type TrafficDirection

type TrafficDirection string

TrafficDirection defines whether traffic exists a service instance or enters a service instance

const (
	// TrafficDirectionInbound indicates inbound traffic
	TrafficDirectionInbound TrafficDirection = "inbound"
	// TrafficDirectionOutbound indicates outbound traffic
	TrafficDirectionOutbound TrafficDirection = "outbound"
)

type TrafficInterceptionMode

type TrafficInterceptionMode string

TrafficInterceptionMode indicates how traffic to/from the workload is captured and sent to Envoy. This should not be confused with the CaptureMode in the API that indicates how the user wants traffic to be intercepted for the listener. TrafficInterceptionMode is always derived from the Proxy metadata

const (
	// InterceptionNone indicates that the workload is not using IPtables for traffic interception
	InterceptionNone TrafficInterceptionMode = "NONE"

	// InterceptionTproxy implies traffic intercepted by IPtables with TPROXY mode
	InterceptionTproxy TrafficInterceptionMode = "TPROXY"

	// InterceptionRedirect implies traffic intercepted by IPtables with REDIRECT mode
	// This is our default mode
	InterceptionRedirect TrafficInterceptionMode = "REDIRECT"
)

type Visibility

type Visibility string

Visibility defines whether a given config or service is exported to local namespace, all namespaces or none

const (
	// VisibilityPrivate implies namespace local config
	VisibilityPrivate Visibility = "."
	// VisibilityPublic implies config is visible to all
	VisibilityPublic Visibility = "*"
)

type XDSUpdater

type XDSUpdater interface {

	// EDSUpdate is called when the list of endpoints or labels in a ServiceEntry is
	// changed. For each cluster and hostname, the full list of active endpoints (including empty list)
	// must be sent. The shard name is used as a key - current implementation is using the registry
	// name.
	EDSUpdate(shard, hostname string, entry []*IstioEndpoint) error

	// SvcUpdate is called when a service port mapping definition is updated.
	// This interface is WIP - labels, annotations and other changes to service may be
	// updated to force a EDS and CDS recomputation and incremental push, as it doesn't affect
	// LDS/RDS.
	SvcUpdate(shard, hostname string, ports map[string]uint32, rports map[uint32]string)

	// WorkloadUpdate is called by a registry when the labels or annotations on a workload have changed.
	// The 'id' is the IP address of the pod for k8s if the pod is in the main/default network.
	// In future it will include the 'network id' for pods in a different network, behind a zvpn gate.
	// The IP is used because K8S Endpoints object associated with a Service only include the IP.
	// We use Endpoints to track the membership to a service and readiness.
	WorkloadUpdate(id string, labels map[string]string, annotations map[string]string)

	// ConfigUpdate is called to notify the XDS server of config updates and request a push.
	// The requests may be collapsed and throttled.
	// This replaces the 'cache invalidation' model.
	ConfigUpdate(full bool)
}

XDSUpdater is used for direct updates of the xDS model and incremental push. Pilot uses multiple registries - for example each K8S cluster is a registry instance, as well as consul and future EDS or MCP sources. Each registry is responsible for tracking a set of endpoints associated with mesh services, and calling the EDSUpdate on changes. A registry may group endpoints for a service in smaller subsets - for example by deployment, or to deal with very large number of endpoints for a service. We want to avoid passing around large objects - like full list of endpoints for a registry, or the full list of endpoints for a service across registries, since it limits scalability.

Future optimizations will include grouping the endpoints by labels, gateway or region to reduce the time when subsetting or split-horizon is used. This design assumes pilot tracks all endpoints in the mesh and they fit in RAM - so limit is few M endpoints. It is possible to split the endpoint tracking in future.

Directories

Path Synopsis
Package test is a generated protocol buffer package.
Package test is a generated protocol buffer package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL