Version: v0.0.0-...-ce3ba50 Latest Latest

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

Go to latest
Published: Jul 24, 2021 License: Apache-2.0 Imports: 68 Imported by: 262



Copyright Istio Authors

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.



View Source
const (

	// 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 or if pilot
	// has failed to refresh it for more than JwtPubKeyEvictionDuration.
	JwtPubKeyEvictionDuration = 24 * 7 * time.Hour

	// JwtPubKeyRefreshIntervalOnFailure is the running interval of JWT pubKey refresh job on failure.
	JwtPubKeyRefreshIntervalOnFailure = time.Minute

	// JwtPubKeyRetryInterval is the retry interval between the attempt to retry getting the remote
	// content from network.
	JwtPubKeyRetryInterval = time.Second

	// JwtPubKeyRefreshIntervalOnFailureResetThreshold is the threshold to reset the refresh interval on failure.
	JwtPubKeyRefreshIntervalOnFailureResetThreshold = 60 * time.Minute
View Source
const (
	// RDSHttpProxy is the special name for HTTP PROXY route
	RDSHttpProxy = "http_proxy"

	// VirtualOutboundListenerName is the name for traffic capture listener
	VirtualOutboundListenerName = "virtualOutbound"

	// VirtualOutboundCatchAllTCPFilterChainName is the name of the catch all tcp filter chain
	VirtualOutboundCatchAllTCPFilterChainName = "virtualOutbound-catchall-tcp"

	// VirtualOutboundCatchAllTCPFilterChainName is the name of the filter chain to blackhole undesired traffic
	VirtualOutboundBlackholeFilterChainName = "virtualOutbound-blackhole"
	// VirtualInboundCatchAllTCPFilterChainName is the name of the filter chain to blackhole undesired traffic
	VirtualInboundBlackholeFilterChainName = "virtualInbound-blackhole"

	// VirtualInboundListenerName is the name for traffic capture listener
	VirtualInboundListenerName = "virtualInbound"

	// virtualInboundCatchAllHTTPFilterChainName is the name of the catch all http filter chain
	VirtualInboundCatchAllHTTPFilterChainName = "virtualInbound-catchall-http"
View Source
const (
	// 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 (
	// TLSModeLabelShortname name used for determining endpoint level tls transport socket configuration
	TLSModeLabelShortname = "tlsMode"

	// DisabledTLSModeLabel implies that this endpoint should receive traffic as is (mostly plaintext)
	DisabledTLSModeLabel = "disabled"

	// IstioMutualTLSModeLabel implies that the endpoint is ready to receive Istio mTLS connections.
	IstioMutualTLSModeLabel = "istio"

	// IstioCanonicalServiceLabelName is the name of label for the Istio Canonical Service for a workload instance.
	IstioCanonicalServiceLabelName = ""

	// IstioCanonicalServiceRevisionLabelName is the name of label for the Istio Canonical Service revision for a workload instance.
	IstioCanonicalServiceRevisionLabelName = ""
View Source
const (
	UnixAddressPrefix      = "unix://"
	PodIPAddressPrefix     = ""
	LocalhostAddressPrefix = ""

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 DisableGatewayPortTranslationLabel = ""

DisableGatewayPortTranslationLabel is a label on Service that declares that, for that particular service, we should not translate Gateway ports to target ports. For example, if I have a Service on port 80 with target port 8080, with the label. Gateways on port 80 would *not* match. Instead, only Gateways on port 8080 would be used. This prevents ambiguities when there are multiple Services on port 80 referring to different target ports. Long term, this will be replaced by Gateways directly referencing a Service, rather than label selectors. Warning: this label is intended solely for as a workaround for Knative's Istio integration, and not intended for any other usage. It can, and will, be removed immediately after the new direct reference is ready for use.

View Source
const InternalGatewayServiceAnnotation = ""

InternalGatewayServiceAnnotation represents the hostname of the service a gateway will use. This is only used internally to transfer information from the Kubernetes Gateway API to the Istio Gateway API which does not have a field to represent this. The format is a comma separated list of hostnames. For example, "ingress.istio-system.svc.cluster.local," The Gateway will apply to all ServiceInstances of these services, *in the same namespace as the Gateway*.

View Source
const (
	// NamespaceAll is a designated symbol for listing across all namespaces
	NamespaceAll = ""
View Source
const (
	ResourceSeparator = "~"


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 = monitoring.NewGauge(
		"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 = monitoring.NewGauge(
		"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 = monitoring.NewGauge(
		"Endpoint found in unready state.",

	// ProxyStatusConflictOutboundListenerTCPOverHTTP metric tracks number of
	// wildcard TCP listeners that conflicted with existing wildcard HTTP listener on same port
	ProxyStatusConflictOutboundListenerTCPOverHTTP = monitoring.NewGauge(
		"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 = monitoring.NewGauge(
		"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 = monitoring.NewGauge(
		"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 = monitoring.NewGauge(
		"Number of conflicting inbound listeners.",

	// DuplicatedClusters tracks duplicate clusters seen while computing CDS
	DuplicatedClusters = monitoring.NewGauge(
		"Duplicate envoy clusters caused by service entries with same hostname",

	// DNSNoEndpointClusters tracks dns clusters without endpoints
	DNSNoEndpointClusters = monitoring.NewGauge(
		"DNS clusters without endpoints caused by the endpoint field in "+
			"STRICT_DNS type cluster is not set or the corresponding subset cannot select any endpoint",

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

	// DuplicatedDomains tracks rejected VirtualServices due to duplicated hostname.
	DuplicatedDomains = monitoring.NewGauge(
		"Virtual services with dup domains.",

	// DuplicatedSubsets tracks duplicate subsets that we rejected while merging multiple destination rules for same host
	DuplicatedSubsets = monitoring.NewGauge(
		"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 AlwaysDiscoverable = func(*IstioEndpoint, *Proxy) bool {
	return true

AlwaysDiscoverable is an EndpointDiscoverabilityPolicy that allows an endpoint to be discoverable throughout the mesh.

View Source
var DefaultXdsLogDetails = XdsLogDetails{}
View Source
var DiscoverableFromSameCluster = func(ep *IstioEndpoint, p *Proxy) bool {
	return p.InCluster(ep.Locality.ClusterID)

DiscoverableFromSameCluster is an EndpointDiscoverabilityPolicy that only allows an endpoint to be discoverable from proxies within the same cluster.

View Source
var (

	// JwtPubKeyRefreshInterval is the running interval of JWT pubKey refresh job.
	JwtPubKeyRefreshInterval = features.PilotJwtPubKeyRefreshInterval
View Source
var MaxIstioVersion = &IstioVersion{Major: 65535, Minor: 65535, Patch: 65535}
View Source
var NodeTypes = [...]NodeType{SidecarProxy, Router}


func BuildDNSSrvSubsetKey

func BuildDNSSrvSubsetKey(direction TrafficDirection, subsetName string, hostname host.Name, 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 BuildInboundSubsetKey

func BuildInboundSubsetKey(port int) string

BuildInboundSubsetKey generates a unique string referencing service instances with port.

func BuildSubsetKey

func BuildSubsetKey(direction TrafficDirection, subsetName string, hostname host.Name, 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 CheckDuplicates

func CheckDuplicates(hosts []string, knownHosts sets.Set) []string

CheckDuplicates returns all of the hosts provided that are already known If there were no duplicates, all hosts are added to the known hosts.

func ConfigNamesOfKind

func ConfigNamesOfKind(configs map[ConfigKey]struct{}, kind config.GroupVersionKind) map[string]struct{}

ConfigNamesOfKind extracts config names of the specified kind.

func ConfigsOfKind

func ConfigsOfKind(configs map[ConfigKey]struct{}, kind config.GroupVersionKind) map[ConfigKey]struct{}

ConfigsOfKind extracts configs of the specified kind.

func CreateFakeJwks

func CreateFakeJwks(jwksURI string) string

CreateFakeJwks is a helper function to make a fake jwks when istiod failed to fetch it.

func GetLocalityLabelOrDefault

func GetLocalityLabelOrDefault(label, defaultLabel string) string

GetLocalityLabelOrDefault returns the locality from the supplied label, or falls back to the supplied default locality if the supplied label is empty. Because Kubernetes labels don't support `/`, we replace "." with "/" in the supplied label as a workaround.

func GetOrDefault

func GetOrDefault(s string, def string) string

GetOrDefault returns either the value, or the default if the value is empty. 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 GetSNIHostsForServer

func GetSNIHostsForServer(server *networking.Server) []string

func GetServiceAccounts

func GetServiceAccounts(svc *Service, ports []int, discovery ServiceDiscovery) []string

GetServiceAccounts returns aggregated list of service accounts of Service plus its instances.

func GetTLSModeFromEndpointLabels

func GetTLSModeFromEndpointLabels(labels map[string]string) string

GetTLSModeFromEndpointLabels returns the value of the label if set. Do not return Enums or constants from this function as users could provide values other than istio/disabled and apply custom transport socket matchers here.

func IsApplicationNodeType

func IsApplicationNodeType(nType NodeType) bool

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

func IsDNSSrvSubsetKey

func IsDNSSrvSubsetKey(s string) bool

IsDNSSrvSubsetKey checks whether the given key is a DNSSrv key (built by BuildDNSSrvSubsetKey).

func IsValidSubsetKey

func IsValidSubsetKey(s string) bool

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

func MostSpecificHostMatch

func MostSpecificHostMatch(needle host.Name, m map[host.Name]struct{}, stack []host.Name) (host.Name, 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 ParseGatewayRDSRouteName

func ParseGatewayRDSRouteName(name string) (portNumber int, portName, gatewayName string)

ParseGatewayRDSRouteName is used by the EnvoyFilter patching logic to match a specific route configuration to patch.

func ParsePort

func ParsePort(addr string) int

ParsePort extracts port number from a valid proxy address

func RecordRejectedConfig

func RecordRejectedConfig(gatewayName string)

func ResolveShortnameToFQDN

func ResolveShortnameToFQDN(hostname string, meta config.Meta) host.Name

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

func ResourcesToAny

func ResourcesToAny(r Resources) []*any.Any

func SplitLocalityLabel

func SplitLocalityLabel(locality string) (region, zone, subzone string)

SplitLocalityLabel splits a locality label into region, zone and subzone strings.

func WorkloadInstancesEqual

func WorkloadInstancesEqual(first, second *WorkloadInstance) bool

a custom comparison of workload instances based on the fields that we need i.e. excluding the ports. Returns true if equal, false otherwise.


type AuthenticationPolicies

type AuthenticationPolicies struct {

	// AggregateVersion contains the versions of all peer authentications.
	AggregateVersion string
	// contains filtered or unexported fields

AuthenticationPolicies organizes authentication (mTLS + JWT) policies by namespace.

func (*AuthenticationPolicies) GetJwtPoliciesForWorkload

func (policy *AuthenticationPolicies) GetJwtPoliciesForWorkload(namespace string,
	workloadLabels labels.Collection) []*config.Config

GetJwtPoliciesForWorkload returns a list of JWT policies matching to labels.

func (*AuthenticationPolicies) GetNamespaceMutualTLSMode

func (policy *AuthenticationPolicies) GetNamespaceMutualTLSMode(namespace string) MutualTLSMode

GetNamespaceMutualTLSMode returns the MutualTLSMode as defined by a namespace or mesh level PeerAuthentication. The return value could be `MTLSUnknown` if there is no mesh nor namespace PeerAuthentication policy for the given namespace.

func (*AuthenticationPolicies) GetPeerAuthenticationsForWorkload

func (policy *AuthenticationPolicies) GetPeerAuthenticationsForWorkload(namespace string,
	workloadLabels labels.Collection) []*config.Config

GetPeerAuthenticationsForWorkload returns a list of peer authentication policies matching to labels.

func (*AuthenticationPolicies) GetRootNamespace

func (policy *AuthenticationPolicies) GetRootNamespace() string

GetRootNamespace return root namespace that is tracked by the policy object.

type AuthorizationPolicies

type AuthorizationPolicies struct {
	// Maps from namespace to the Authorization policies.
	NamespaceToPolicies map[string][]AuthorizationPolicy `json:"namespace_to_policies"`

	// The name of the root namespace. Policy in the root namespace applies to workloads in all namespaces.
	RootNamespace string `json:"root_namespace"`

AuthorizationPolicies organizes AuthorizationPolicy by namespace.

func GetAuthorizationPolicies

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

GetAuthorizationPolicies returns the AuthorizationPolicies for the given environment.

func (*AuthorizationPolicies) ListAuthorizationPolicies

func (policy *AuthorizationPolicies) ListAuthorizationPolicies(namespace string, workload labels.Collection) AuthorizationPoliciesResult

ListAuthorizationPolicies returns authorization policies applied to the workload in the given namespace.

type AuthorizationPoliciesResult

type AuthorizationPoliciesResult struct {
	Custom []AuthorizationPolicy
	Deny   []AuthorizationPolicy
	Allow  []AuthorizationPolicy
	Audit  []AuthorizationPolicy

type AuthorizationPolicy

type AuthorizationPolicy struct {
	Name        string                      `json:"name"`
	Namespace   string                      `json:"namespace"`
	Annotations map[string]string           `json:"annotations"`
	Spec        *authpb.AuthorizationPolicy `json:"spec"`

type BootstrapNodeMetadata

type BootstrapNodeMetadata struct {

	// InstanceName is the short name for the workload instance (ex: pod name)
	// replaces POD_NAME
	InstanceName string `json:"NAME,omitempty"`

	// WorkloadName specifies the name of the workload represented by this node.
	WorkloadName string `json:"WORKLOAD_NAME,omitempty"`

	// Owner specifies the workload owner (opaque string). Typically, this is the owning controller of
	// of the workload instance (ex: k8s deployment for a k8s pod).
	Owner string `json:"OWNER,omitempty"`

	// ProxyViaAgent specifies whether xDS streams are proxied through the agent.
	ProxyViaAgent bool `json:"PROXY_VIA_AGENT,omitempty"`

	// PilotSAN is the list of subject alternate names for the xDS server.
	PilotSubjectAltName []string `json:"PILOT_SAN,omitempty"`

	// OutlierLogPath is the cluster manager outlier event log path.
	OutlierLogPath string `json:"OUTLIER_LOG_PATH,omitempty"`

	// ProvCertDir is the directory containing pre-provisioned certs.
	ProvCert string `json:"PROV_CERT,omitempty"`

	// AppContainers is the list of containers in the pod.
	AppContainers string `json:"APP_CONTAINERS,omitempty"`

	// IstioProxySHA is the SHA of the proxy version.
	IstioProxySHA string `json:"ISTIO_PROXY_SHA,omitempty"`

BootstrapNodeMetadata is a superset of NodeMetadata, intended to model the entirety of the node metadata we configure in the Envoy bootstrap. This is split out from NodeMetadata to explicitly segment the parameters that are consumed by Pilot from the parameters used only as part of the bootstrap. Fields used by bootstrap only are consumed by Envoy itself, such as the telemetry filters.

func (*BootstrapNodeMetadata) UnmarshalJSON

func (m *BootstrapNodeMetadata) UnmarshalJSON(data []byte) error

type CacheToken

type CacheToken uint64

type ClusterLocalHosts

type ClusterLocalHosts host.Names

ClusterLocalHosts is a list of host names or wildcard patterns which should only be made accessible from within the same cluster.

func (ClusterLocalHosts) IsClusterLocal

func (c ClusterLocalHosts) IsClusterLocal(h host.Name) bool

IsClusterLocal indicates whether the given host should be treated as a cluster-local destination.

type ClusterLocalProvider

type ClusterLocalProvider interface {
	// GetClusterLocalHosts returns the list of cluster-local hosts, sorted in
	// ascending order. The caller must not modify the returned list.
	GetClusterLocalHosts() ClusterLocalHosts

ClusterLocalProvider provides the cluster-local hosts.

func NewClusterLocalProvider

func NewClusterLocalProvider(e *Environment) ClusterLocalProvider

NewClusterLocalProvider returns a new ClusterLocalProvider for the Environment.

type ConfigKey

type ConfigKey struct {
	Kind      config.GroupVersionKind
	Name      string
	Namespace string

ConfigKey describe a specific config item. In most cases, the name is the config's name. However, for ServiceEntry it is service's FQDN.

func (ConfigKey) HashCode

func (key ConfigKey) HashCode() uint64

type ConfigStore

type ConfigStore interface {
	// Schemas 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.
	Schemas() collection.Schemas

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

	// List returns objects by type and namespace.
	// Use "" for the namespace to list across namespaces.
	List(typ config.GroupVersionKind, namespace string) ([]config.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.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.Config) (newRevision string, err error)

	UpdateStatus(config config.Config) (newRevision string, err error)

	// Patch applies only the modifications made in the PatchFunc rather than doing a full replace. Useful to avoid
	// read-modify-write conflicts when there are many concurrent-writers to the same resource.
	Patch(orig config.Config, patchFn config.PatchFunc) (string, error)

	// Delete removes an object from the store by key
	// For k8s, resourceVersion must be fulfilled before a deletion is carried out.
	// If not possible, a 409 Conflict status will be returned.
	Delete(typ config.GroupVersionKind, name, namespace string, resourceVersion *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 {

	// RegisterEventHandler adds a handler to receive config update events for a
	// configuration type
	RegisterEventHandler(kind config.GroupVersionKind, handler func(config.Config, config.Config, Event))

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

	SetWatchErrorHandler(func(r *cache.Reflector, err error)) error

	// 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))

	// AppendWorkloadHandler notifies about changes to workloads. This differs from InstanceHandler,
	// which deals with service instances (the result of a merge of Service and Workload)
	AppendWorkloadHandler(f func(*WorkloadInstance, Event))

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

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

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 DisabledCache

type DisabledCache struct{}

DisabledCache is a cache that is always empty

func (DisabledCache) Add

func (d DisabledCache) Add(key XdsCacheEntry, pushReq *PushRequest, value *discovery.Resource)

func (DisabledCache) Clear

func (d DisabledCache) Clear(configsUpdated map[ConfigKey]struct{})

func (DisabledCache) ClearAll

func (d DisabledCache) ClearAll()

func (DisabledCache) Get

func (DisabledCache) Keys

func (d DisabledCache) Keys() []string

func (DisabledCache) Snapshot

func (d DisabledCache) Snapshot() map[string]*discovery.Resource

type DisabledLedger

type DisabledLedger struct {

DisabledLedger is an empty mock of the ledger.Ledger interface which we will substitute when distribution tracking is disabled.

func (*DisabledLedger) Delete

func (d *DisabledLedger) Delete(key string) error

func (*DisabledLedger) Get

func (d *DisabledLedger) Get(key string) (string, error)

func (*DisabledLedger) GetPreviousValue

func (d *DisabledLedger) GetPreviousValue(previousHash, key string) (result string, err error)

func (*DisabledLedger) Put

func (d *DisabledLedger) Put(key, value string) (string, error)

func (*DisabledLedger) RootHash

func (d *DisabledLedger) RootHash() string

type EndpointDiscoverabilityPolicy

type EndpointDiscoverabilityPolicy func(*IstioEndpoint, *Proxy) bool

EndpointDiscoverabilityPolicy determines the discoverability of an endpoint throughout the mesh.

type Environment

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

	// Config interface for listing routing rules

	// Watcher is the watcher for the mesh config (to be merged into the config store)

	// NetworksWatcher (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.

	// 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.
	PushContext *PushContext

	// DomainSuffix provides a default domain for the Istio server.
	DomainSuffix string

	// TrustBundle: List of Mesh TrustAnchors
	TrustBundle *trustbundle.TrustBundle

	GatewayAPIController GatewayController
	// contains filtered or unexported fields

Environment provides an aggregate environmental API for Pilot

func (*Environment) AddMeshHandler

func (e *Environment) AddMeshHandler(h func())

func (*Environment) AddMetric

func (e *Environment) AddMetric(metric monitoring.Metric, key string, proxyID, msg string)

func (*Environment) AddNetworksHandler

func (e *Environment) AddNetworksHandler(h func())

func (*Environment) ClusterLocal

func (e *Environment) ClusterLocal() ClusterLocalProvider

func (*Environment) GetDiscoveryAddress

func (e *Environment) GetDiscoveryAddress() (host.Name, string, error)

GetDiscoveryAddress parses the DiscoveryAddress specified via MeshConfig.

func (*Environment) GetLedger

func (e *Environment) GetLedger() ledger.Ledger

func (*Environment) Init

func (e *Environment) Init()

Init initializes the Environment for use.

func (*Environment) Mesh

func (e *Environment) Mesh() *meshconfig.MeshConfig

func (*Environment) Networks

func (e *Environment) Networks() *meshconfig.MeshNetworks

func (*Environment) SetLedger

func (e *Environment) SetLedger(l ledger.Ledger)

func (*Environment) Version

func (e *Environment) Version() string

type EnvoyFilterConfigPatchWrapper

type EnvoyFilterConfigPatchWrapper struct {
	Value     proto.Message
	Match     *networking.EnvoyFilter_EnvoyConfigObjectMatch
	ApplyTo   networking.EnvoyFilter_ApplyTo
	Operation networking.EnvoyFilter_Patch_Operation
	// Pre-compile the regex from proxy version match in the match
	ProxyVersionRegex *regexp.Regexp
	// ProxyPrefixMatch provides a prefix match for the proxy version. The current API only allows
	// regex match, but as an optimization we can reduce this to a prefix match for common cases.
	// If this is set, ProxyVersionRegex is ignored.
	ProxyPrefixMatch string
	Name             string
	Namespace        string

EnvoyFilterConfigPatchWrapper is a wrapper over the EnvoyFilter ConfigPatch api object fields are ordered such that this struct is aligned

func (*EnvoyFilterConfigPatchWrapper) Key

type EnvoyFilterWrapper

type EnvoyFilterWrapper struct {
	Name      string
	Namespace string

	Patches map[networking.EnvoyFilter_ApplyTo][]*EnvoyFilterConfigPatchWrapper
	// contains filtered or unexported fields

EnvoyFilterWrapper is a wrapper for the EnvoyFilter api object with pre-processed data

func (*EnvoyFilterWrapper) Key

func (efw *EnvoyFilterWrapper) Key() string

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

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

func (Event) String

func (event Event) String() string

type FakeStore

type FakeStore struct {
	// contains filtered or unexported fields

func NewFakeStore

func NewFakeStore() *FakeStore

func (*FakeStore) Create

func (s *FakeStore) Create(cfg config.Config) (revision string, err error)

func (*FakeStore) Delete

func (*FakeStore) Delete(typ config.GroupVersionKind, name, namespace string, rv *string) error

func (*FakeStore) Get

func (*FakeStore) Get(typ config.GroupVersionKind, name, namespace string) *config.Config

func (*FakeStore) List

func (s *FakeStore) List(typ config.GroupVersionKind, namespace string) ([]config.Config, error)

func (*FakeStore) Patch

func (*FakeStore) Patch(orig config.Config, patchFn config.PatchFunc) (string, error)

func (*FakeStore) Schemas

func (s *FakeStore) Schemas() collection.Schemas

func (*FakeStore) Update

func (*FakeStore) Update(config config.Config) (newRevision string, err error)

func (*FakeStore) UpdateStatus

func (*FakeStore) UpdateStatus(config config.Config) (string, error)

type GatewayContext

type GatewayContext struct {
	// contains filtered or unexported fields

GatewayContext contains a minimal subset of push context functionality to be exposed to GatewayAPIControllers

func NewGatewayContext

func NewGatewayContext(ps *PushContext) GatewayContext

func (GatewayContext) ResolveGatewayInstances

func (gc GatewayContext) ResolveGatewayInstances(namespace string, gwsvcs []string, servers []*networking.Server) (internal, external, warns []string)

ResolveGatewayInstances attempts to resolve all instances that a gateway will be exposed on. Note: this function considers *all* instances of the service; its possible those instances will not actually be properly functioning gateways, so this is not 100% accurate, but sufficient to expose intent to users. The actual configuration generation is done on a per-workload basis and will get the exact set of matched instances for that workload. Three sets are exposed: * Internal addresses (ie istio-ingressgateway.istio-system.svc.cluster.local:80). * External addresses (ie, this comes from LoadBalancer services. There may be multiple in some cases (especially multi cluster). * Warnings for references that could not be resolved. These are intended to be user facing.

type GatewayController

type GatewayController interface {
	Recompute(GatewayContext) error

type GatewayPortMap

type GatewayPortMap map[int]map[int]struct{}

type IstioConfigStore

type IstioConfigStore interface {

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

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

	// AuthorizationPolicies selects AuthorizationPolicies in the specified namespace.
	AuthorizationPolicies(namespace string) []config.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.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 labels.Instance

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

	// ServicePortName tracks the name of the port, this is used to select the IstioEndpoint by service port.
	ServicePortName 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 network.ID

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

	// 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

	// TLSMode endpoint is injected with istio sidecar and ready to configure Istio mTLS
	TLSMode string

	// Namespace that this endpoint belongs to. This is for telemetry purpose.
	Namespace string

	// Name of the workload that this endpoint belongs to. This is for telemetry purpose.
	WorkloadName string

	// Specifies the hostname of the Pod, empty for vm workload.
	HostName string

	// If specified, the fully qualified Pod hostname will be "<hostname>.<subdomain>.<pod namespace>.svc.<cluster domain>".
	SubDomain string

	// The ingress tunnel supportability of this endpoint.
	// If this endpoint sidecar proxy does not support h2 tunnel, this endpoint will not show up in the EDS clusters
	// which are generated for h2 tunnel.
	TunnelAbility networking.TunnelAbility

	// Determines the discoverability of this endpoint throughout the mesh.
	DiscoverabilityPolicy EndpointDiscoverabilityPolicy `json:"-"`

IstioEndpoint 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 is accessible through port 80 and 8080, and it maps to an instance with IP, 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 endpoint structs for the service

--> (with ServicePort pointing to 80) and
--> (with ServicePort pointing to 8080)

TODO: Investigate removing ServiceInstance entirely.

func (*IstioEndpoint) DeepCopy

func (ep *IstioEndpoint) DeepCopy() *IstioEndpoint

DeepCopy creates a clone of IstioEndpoint.

func (*IstioEndpoint) GetLoadBalancingWeight

func (ep *IstioEndpoint) GetLoadBalancingWeight() uint32

GetLoadBalancingWeight returns the weight for this endpoint, normalized to always be > 0.

func (*IstioEndpoint) IsDiscoverableFromProxy

func (ep *IstioEndpoint) IsDiscoverableFromProxy(p *Proxy) bool

IsDiscoverableFromProxy indicates whether or not this endpoint is discoverable from the given Proxy.

type IstioVersion

type IstioVersion struct {
	Major int
	Minor int
	Patch int

IstioVersion encodes the Istio version of the proxy. This is a low key way to do semver style comparisons and generate the appropriate envoy config

func ParseIstioVersion

func ParseIstioVersion(ver string) *IstioVersion

ParseIstioVersion parses a version string and returns IstioVersion struct

func (*IstioVersion) Compare

func (pversion *IstioVersion) Compare(inv *IstioVersion) int

Compare returns -1/0/1 if version is less than, equal or greater than inv To compare only on major, call this function with { X, -1, -1}. to compare only on major & minor, call this function with {X, Y, -1}.

type JwksResolver

type JwksResolver struct {
	// Callback function to invoke when detecting jwt public key change.
	PushFunc func()
	// contains filtered or unexported fields

JwksResolver is resolver for jwksURI and jwt public key.

func NewJwksResolver

func NewJwksResolver(evictionDuration, refreshDefaultInterval, refreshIntervalOnFailure, retryInterval time.Duration) *JwksResolver

NewJwksResolver creates new instance of JwksResolver.

func (*JwksResolver) BuildLocalJwks

func (r *JwksResolver) BuildLocalJwks(jwksURI, jwtIssuer, jwtPubKey string) *envoy_jwt.JwtProvider_LocalJwks

BuildLocalJwks builds local Jwks by fetching the Jwt Public Key from the URL passed if it is empty.

func (*JwksResolver) Close

func (r *JwksResolver) Close()

Close will shut down the refresher job. TODO: may need to figure out the right place to call this function. (right now calls it from initDiscoveryService in pkg/bootstrap/server.go).

func (*JwksResolver) GetPublicKey

func (r *JwksResolver) GetPublicKey(issuer string, jwksURI string) (string, error)

GetPublicKey gets JWT public key and cache the key for future use.

type Locality

type Locality struct {
	// Label for locality on the endpoint. This is a "/" separated string.
	Label string

	// ClusterID where the endpoint is located
	ClusterID cluster.ID

Locality information for an IstioEndpoint

type MergedGateway

type MergedGateway struct {
	// ServerPorts maintains a list of unique server ports, used for stable ordering.
	ServerPorts []ServerPort

	// MergedServers maps from physical port to virtual servers.
	MergedServers map[ServerPort]*MergedServers

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

	// ServersByRouteName 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

	// TLSServerInfo maps from server to a corresponding TLS information like TLS Routename and SNIHosts.
	TLSServerInfo map[*networking.Server]*TLSServerInfo

	// ContainsAutoPassthroughGateways determines if there are any type AUTO_PASSTHROUGH Gateways, requiring additional
	// clusters to be sent to the workload
	ContainsAutoPassthroughGateways bool

	// PortMap defines a mapping of targetPorts to the set of Service ports that reference them
	PortMap GatewayPortMap

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

func MergeGateways

func MergeGateways(gateways []gatewayWithInstances) *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 MergedServers

type MergedServers struct {
	Servers   []*networking.Server
	RouteName string // RouteName for http servers. For HTTPS, TLSServerInfo will hold the route name.

MergedServers describes set of servers defined in all gateways per port.

type Metrics

type Metrics interface {
	// AddMetric will add an case to the metric for the given node.
	AddMetric(metric monitoring.Metric, key string, proxyID, msg string)

Metrics is an interface for capturing metrics on a per-node basis.

type MutualTLSMode

type MutualTLSMode int

MutualTLSMode is the mutual TLS mode specified by authentication policy.

const (
	// MTLSUnknown is used to indicate the variable hasn't been initialized correctly (with the authentication policy).
	MTLSUnknown MutualTLSMode = iota

	// MTLSDisable if authentication policy disable mTLS.

	// MTLSPermissive if authentication policy enable mTLS in permissive mode.

	// MTLSStrict if authentication policy enable mTLS in strict mode.

func ConvertToMutualTLSMode

func ConvertToMutualTLSMode(mode v1beta1.PeerAuthentication_MutualTLS_Mode) MutualTLSMode

ConvertToMutualTLSMode converts from peer authn MTLS mode (`PeerAuthentication_MutualTLS_Mode`) to the MTLS mode specified by authn policy.

func (MutualTLSMode) String

func (mode MutualTLSMode) String() string

String converts MutualTLSMode to human readable string for debugging.

type NetworkGateway

type NetworkGateway struct {
	// Network is the ID of the network where this Gateway resides.
	Network network.ID
	// Cluster is the ID of the k8s cluster where this Gateway resides.
	Cluster cluster.ID
	// gateway ip address
	Addr string
	// gateway port
	Port uint32

NetworkGateway is the gateway of a network

func SortGateways

func SortGateways(gws []*NetworkGateway) []*NetworkGateway

type NetworkManager

type NetworkManager struct {
	// contains filtered or unexported fields

NetworkManager provides gateway details for accessing remote networks.

func NewNetworkManager

func NewNetworkManager(env *Environment) *NetworkManager

NewNetworkManager creates a new NetworkManager from the Environment by merging together the MeshNetworks and ServiceRegistry-specific gateways.

func (*NetworkManager) AllGateways

func (mgr *NetworkManager) AllGateways() []*NetworkGateway

func (*NetworkManager) GatewaysByNetwork

func (mgr *NetworkManager) GatewaysByNetwork() map[network.ID][]*NetworkGateway

func (*NetworkManager) GatewaysForNetwork

func (mgr *NetworkManager) GatewaysForNetwork(nw network.ID) []*NetworkGateway

func (*NetworkManager) GatewaysForNetworkAndCluster

func (mgr *NetworkManager) GatewaysForNetworkAndCluster(nw network.ID, c cluster.ID) []*NetworkGateway

func (*NetworkManager) GetMaxGatewaysPerNetwork

func (mgr *NetworkManager) GetMaxGatewaysPerNetwork() uint32

GetMaxGatewaysPerNetwork returns an upper bound on the number of gateways there could be for any one network.

func (*NetworkManager) IsMultiNetworkEnabled

func (mgr *NetworkManager) IsMultiNetworkEnabled() bool

type Node

type Node struct {
	// ID of the Envoy node
	ID string
	// Metadata is the typed node metadata
	Metadata *BootstrapNodeMetadata
	// RawMetadata is the untyped node metadata
	RawMetadata map[string]interface{}
	// Locality from Envoy bootstrap
	Locality *core.Locality

Node is a typed version of Envoy node with metadata.

type NodeMetaProxyConfig

type NodeMetaProxyConfig meshconfig.ProxyConfig

ProxyConfig can only be marshaled using (gogo) jsonpb. However, the rest of node meta is not a proto To allow marshaling, we need to define a custom type that calls out to the gogo marshaller

func (NodeMetaProxyConfig) MarshalJSON

func (s NodeMetaProxyConfig) MarshalJSON() ([]byte, error)

func (*NodeMetaProxyConfig) UnmarshalJSON

func (s *NodeMetaProxyConfig) UnmarshalJSON(data []byte) error

type NodeMetadata

type NodeMetadata struct {
	// ProxyConfig defines the proxy config specified for a proxy.
	// Note that this setting may be configured different for each proxy, due user overrides
	// or from different versions of proxies connecting. While Pilot has access to the meshConfig.defaultConfig,
	// this field should be preferred if it is present.
	ProxyConfig *NodeMetaProxyConfig `json:"PROXY_CONFIG,omitempty"`

	// IstioVersion specifies the Istio version associated with the proxy
	IstioVersion string `json:"ISTIO_VERSION,omitempty"`

	// Labels specifies the set of workload instance (ex: k8s pod) labels associated with this node.
	Labels map[string]string `json:"LABELS,omitempty"`

	// Labels specifies the set of workload instance (ex: k8s pod) annotations associated with this node.
	Annotations map[string]string `json:"ANNOTATIONS,omitempty"`

	// InstanceIPs is the set of IPs attached to this proxy
	InstanceIPs StringList `json:"INSTANCE_IPS,omitempty"`

	// Namespace is the namespace in which the workload instance is running.
	Namespace string `json:"NAMESPACE,omitempty"`

	// InterceptionMode is the name of the metadata variable that carries info about
	// traffic interception mode at the proxy
	InterceptionMode TrafficInterceptionMode `json:"INTERCEPTION_MODE,omitempty"`

	// ServiceAccount specifies the service account which is running the workload.
	ServiceAccount string `json:"SERVICE_ACCOUNT,omitempty"`

	// RouterMode indicates whether the proxy is functioning as a SNI-DNAT router
	// processing the AUTO_PASSTHROUGH gateway servers
	RouterMode string `json:"ROUTER_MODE,omitempty"`

	// MeshID specifies the mesh ID environment variable.
	MeshID string `json:"MESH_ID,omitempty"`

	// ClusterID defines the cluster the node belongs to.
	ClusterID cluster.ID `json:"CLUSTER_ID,omitempty"`

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

	// RequestedNetworkView specifies the networks that the proxy wants to see
	RequestedNetworkView StringList `json:"REQUESTED_NETWORK_VIEW,omitempty"`

	// PodPorts defines the ports on a pod. This is used to lookup named ports.
	PodPorts PodPortList `json:"POD_PORTS,omitempty"`

	// TLSServerCertChain is the absolute path to server cert-chain file
	TLSServerCertChain string `json:"TLS_SERVER_CERT_CHAIN,omitempty"`
	// TLSServerKey is the absolute path to server private key file
	TLSServerKey string `json:"TLS_SERVER_KEY,omitempty"`
	// TLSServerRootCert is the absolute path to server root cert file
	TLSServerRootCert string `json:"TLS_SERVER_ROOT_CERT,omitempty"`
	// TLSClientCertChain is the absolute path to client cert-chain file
	TLSClientCertChain string `json:"TLS_CLIENT_CERT_CHAIN,omitempty"`
	// TLSClientKey is the absolute path to client private key file
	TLSClientKey string `json:"TLS_CLIENT_KEY,omitempty"`
	// TLSClientRootCert is the absolute path to client root cert file
	TLSClientRootCert string `json:"TLS_CLIENT_ROOT_CERT,omitempty"`

	CertBaseDir string `json:"BASE,omitempty"`

	// IdleTimeout specifies the idle timeout for the proxy, in duration format (10s).
	// If not set, default timeout is 1 hour.
	IdleTimeout string `json:"IDLE_TIMEOUT,omitempty"`

	// HTTP10 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.
	HTTP10 string `json:"HTTP10,omitempty"`

	// Generator indicates the client wants to use a custom Generator plugin.
	Generator string `json:"GENERATOR,omitempty"`

	// DNSCapture indicates whether the workload has enabled dns capture
	DNSCapture StringBool `json:"DNS_CAPTURE,omitempty"`

	// DNSAutoAllocate indicates whether the workload should have auto allocated addresses for ServiceEntry
	// This allows resolving ServiceEntries, which is especially useful for distinguishing TCP traffic
	// This depends on DNSCapture.
	DNSAutoAllocate StringBool `json:"DNS_AUTO_ALLOCATE,omitempty"`

	// AutoRegister will enable auto registration of the connected endpoint to the service registry using the given WorkloadGroup name
	AutoRegisterGroup string `json:"AUTO_REGISTER_GROUP,omitempty"`

	// UnprivilegedPod is used to determine whether a Gateway Pod can open ports < 1024
	UnprivilegedPod string `json:"UNPRIVILEGED_POD,omitempty"`

	// PlatformMetadata contains any platform specific metadata
	PlatformMetadata map[string]string `json:"PLATFORM_METADATA,omitempty"`

	// StsPort specifies the port of security token exchange server (STS).
	// Used by envoy filters
	StsPort string `json:"STS_PORT,omitempty"`

	// Envoy status port redirecting to agent status port.
	EnvoyStatusPort int `json:"ENVOY_STATUS_PORT,omitempty"`

	// Envoy prometheus port redirecting to admin port prometheus endpoint.
	EnvoyPrometheusPort int `json:"ENVOY_PROMETHEUS_PORT,omitempty"`

	// Contains a copy of the raw metadata. This is needed to lookup arbitrary values.
	// If a value is known ahead of time it should be added to the struct rather than reading from here,
	Raw map[string]interface{} `json:"-"`

NodeMetadata defines the metadata associated with a proxy Fields should not be assumed to exist on the proxy, especially newly added fields which will not exist on older versions. The JSON field names should never change, as they are needed for backward compatibility with older proxies nolint: maligned

func ParseMetadata

func ParseMetadata(metadata *structpb.Struct) (*NodeMetadata, error)

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

func (NodeMetadata) ProxyConfigOrDefault

func (m NodeMetadata) ProxyConfigOrDefault(def *meshconfig.ProxyConfig) *meshconfig.ProxyConfig

ProxyConfigOrDefault is a helper function to get the ProxyConfig from metadata, or fallback to a default This is useful as the logic should check for proxy config from proxy first and then defer to mesh wide defaults if not present.

func (NodeMetadata) ToStruct

func (m NodeMetadata) ToStruct() *structpb.Struct

Converts this to a protobuf structure. This should be used only for debugging - performance is bad.

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"

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

type PodPort

type PodPort struct {
	// If specified, this must be an IANA_SVC_NAME and unique within the pod. Each
	// named port in a pod must have a unique name. Name for the port that can be
	// referred to by services.
	// +optional
	Name string `json:"name,omitempty"`
	// Number of port to expose on the pod's IP address.
	// This must be a valid port number, 0 < x < 65536.
	ContainerPort int `json:"containerPort"`
	// Name of the protocol
	Protocol string `json:"protocol"`

PodPort describes a mapping of port name to port number. Generally, this is just the definition of a port in Kubernetes, but without depending on Kubernetes api.

type PodPortList

type PodPortList []PodPort

PodPortList defines a list of PodPort's that is serialized as a string This is for legacy reasons, where proper JSON was not supported and was written as a string

func (PodPortList) MarshalJSON

func (l PodPortList) MarshalJSON() ([]byte, error)

func (*PodPortList) UnmarshalJSON

func (l *PodPortList) UnmarshalJSON(data []byte) error

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.
	Port int `json:"port"`

	// Protocol to be used for the port.
	Protocol protocol.Instance `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.

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 Proxy

type Proxy struct {

	// 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: "". In some cases, the host
	// where the proxy 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 <podName.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

	// ConfigNamespace defines the namespace where this proxy resides
	// for the purposes of network scoping.
	ConfigNamespace string

	// Metadata key-value pairs extending the Node identifier
	Metadata *NodeMetadata

	// the sidecarScope associated with the proxy
	SidecarScope *SidecarScope

	// the sidecarScope associated with the proxy previously
	PrevSidecarScope *SidecarScope

	// The merged gateways associated with the proxy if this is a Router
	MergedGateway *MergedGateway

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

	// Istio version associated with the Proxy
	IstioVersion *IstioVersion

	// VerifiedIdentity determines whether a proxy had its identity verified. This
	// generally occurs by JWT or mTLS authentication. This can be false when
	// connecting over plaintext. If this is set to true, we can verify the proxy has
	// access to ConfigNamespace namespace. However, other options such as node type
	// are not part of an Istio identity and thus are not verified.
	VerifiedIdentity *spiffe.Identity

	// GlobalUnicastIP stores the global unicast IP if available, otherwise nil
	GlobalUnicastIP string

	// XdsResourceGenerator is used to generate resources for the node, based on the PushContext.
	// If nil, the default networking/core v2 generator is used. This field can be set
	// at connect time, based on node metadata, to trigger generation of a different style
	// of configuration.
	XdsResourceGenerator XdsResourceGenerator

	// WatchedResources contains the list of watched resources for the proxy, keyed by the DiscoveryRequest TypeUrl.
	WatchedResources map[string]*WatchedResource

	// XdsNode is the xDS node identifier
	XdsNode *core.Node
	// contains filtered or unexported fields

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(nodeID string, metadata *NodeMetadata) (*Proxy, error)

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

func (*Proxy) DiscoverIPVersions

func (node *Proxy) DiscoverIPVersions()

DiscoverIPVersions discovers the IP Versions supported by Proxy based on its IP addresses.

func (*Proxy) GetInterceptionMode

func (node *Proxy) GetInterceptionMode() TrafficInterceptionMode

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

func (*Proxy) GetNetworkView

func (node *Proxy) GetNetworkView() map[network.ID]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 in any network.

func (*Proxy) InCluster

func (node *Proxy) InCluster(cluster cluster.ID) bool

InCluster returns true if the proxy is in the given cluster, or if either the proxy's cluster id or the given cluster id is unspecified ("").

func (*Proxy) InNetwork

func (node *Proxy) InNetwork(network network.ID) bool

InNetwork returns true if the proxy is on the given network, or if either the proxy's network or the given network is unspecified ("").

func (*Proxy) IsVM

func (node *Proxy) IsVM() bool

func (*Proxy) ServiceNode

func (node *Proxy) ServiceNode() string

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

func (*Proxy) SetGatewaysForProxy

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

SetGatewaysForProxy merges the Gateway objects associated with this proxy and caches the merged object in the proxy Node. This is a convenience hack so that callers can simply call push.MergedGateways(node) instead of having to fetch all the gateways and invoke the merge call in multiple places (lds/rds). Must be called after ServiceInstances are set

func (*Proxy) SetServiceInstances

func (node *Proxy) SetServiceInstances(serviceDiscovery ServiceDiscovery)

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)

SetWorkloadLabels will set the node.Metadata.Labels only when it is nil.

func (*Proxy) SupportsIPv4

func (node *Proxy) SupportsIPv4() bool

SupportsIPv4 returns true if proxy supports IPv4 addresses.

func (*Proxy) SupportsIPv6

func (node *Proxy) SupportsIPv6() bool

SupportsIPv6 returns true if proxy supports IPv6 addresses.

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

	// ServiceIndex is the index of services by various fields.
	ServiceIndex serviceIndex

	// ServiceAccounts contains a map of hostname and port to service accounts.
	ServiceAccounts map[host.Name]map[int][]string `json:"-"`

	// AuthnPolicies contains Authn policies by namespace.
	AuthnPolicies *AuthenticationPolicies `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:"-"`

	// Telemetry stores the existing Telemetry resources for the cluster.
	Telemetry *Telemetries `json:"-"`

	// Mesh configuration for the mesh.
	Mesh *meshconfig.MeshConfig `json:"-"`

	// PushVersion describes the push version this push context was computed for
	PushVersion string

	// LedgerVersion is the version of the configuration ledger
	LedgerVersion string

	// JwtKeyResolver holds a reference to the JWT key resolver instance.
	JwtKeyResolver *JwksResolver
	// 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) AddMetric

func (ps *PushContext) AddMetric(metric monitoring.Metric, key string, proxyID, msg string)

AddMetric will add an case to the metric.

func (*PushContext) AddPublicServices

func (ps *PushContext) AddPublicServices(services []*Service)

AddPublicServices adds the services to context public services - mainly used in tests.

func (*PushContext) AddServiceInstances

func (ps *PushContext) AddServiceInstances(service *Service, instances map[int][]*ServiceInstance)

AddServiceInstances adds instances to the context service instances - mainly used in tests.

func (*PushContext) BestEffortInferServiceMTLSMode

func (ps *PushContext) BestEffortInferServiceMTLSMode(tp *networking.TrafficPolicy, service *Service, port *Port) MutualTLSMode

BestEffortInferServiceMTLSMode infers the mTLS mode for the service + port from all authentication policies (both alpha and beta) in the system. The function always returns MTLSUnknown for external service. The result is a best effort. It is because the PeerAuthentication is workload-based, this function is unable to compute the correct service mTLS mode without knowing service to workload binding. For now, this function uses only mesh and namespace level PeerAuthentication and ignore workload & port level policies. This function is used to give a hint for auto-mTLS configuration on client side.

func (*PushContext) DelegateVirtualServicesConfigKey

func (ps *PushContext) DelegateVirtualServicesConfigKey(vses []config.Config) []ConfigKey

DelegateVirtualServicesConfigKey lists all the delegate virtual services configkeys associated with the provided virtual services

func (*PushContext) DestinationRule

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

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

func (*PushContext) EnvoyFilters

func (ps *PushContext) EnvoyFilters(proxy *Proxy) *EnvoyFilterWrapper

EnvoyFilters return the merged EnvoyFilterWrapper of a proxy

func (*PushContext) GatewayServices

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

GatewayServices returns the set of services which are referred from the proxy gateways.

func (*PushContext) InitContext

func (ps *PushContext) InitContext(env *Environment, oldPushContext *PushContext, pushReq *PushRequest) 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) IsClusterLocal

func (ps *PushContext) IsClusterLocal(service *Service) bool

IsClusterLocal indicates whether the endpoints for the service should only be accessible to clients within the cluster.

func (*PushContext) IsServiceVisible

func (ps *PushContext) IsServiceVisible(service *Service, namespace string) bool

IsServiceVisible returns true if the input service is visible to the given namespace.

func (*PushContext) NetworkManager

func (ps *PushContext) NetworkManager() *NetworkManager

func (*PushContext) OnConfigChange

func (ps *PushContext) OnConfigChange()

OnConfigChange is called when a config change is detected.

func (*PushContext) ServiceForHostname

func (ps *PushContext) ServiceForHostname(proxy *Proxy, hostname host.Name) *Service

ServiceForHostname returns the service associated with a given hostname following SidecarScope

func (*PushContext) ServiceInstancesByPort

func (ps *PushContext) ServiceInstancesByPort(svc *Service, port int, labels labels.Collection) []*ServiceInstance

ServiceInstancesByPort returns the cached instances by port if it exists.

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.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. This will not work properly for Sidecars, which will precompute their destination rules on init

func (*PushContext) StatusJSON

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

JSON implements json.Marshaller, with a lock.

func (*PushContext) SubsetToLabels

func (ps *PushContext) SubsetToLabels(proxy *Proxy, subsetName string, hostname host.Name) labels.Collection

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) VirtualServicesForGateway

func (ps *PushContext) VirtualServicesForGateway(proxy *Proxy, gateway string) []config.Config

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

type PushRequest

type PushRequest struct {
	// Full determines whether a full push is required or not. If false, an incremental update will be sent.
	// Incremental pushes:
	// * Do not recompute the push context
	// * Do not recompute proxy state (such as ServiceInstances)
	// * Are not reported in standard metrics such as push time
	// As a result, configuration updates should never be incremental. Generally, only EDS will set this, but
	// in the future SDS will as well.
	Full bool

	// ConfigsUpdated keeps track of configs that have changed.
	// This is used as an optimization to avoid unnecessary pushes to proxies that are scoped with a Sidecar.
	// If this is empty, then all proxies will get an update.
	// Otherwise only proxies depend on these configs will get an update.
	// The kind of resources are defined in pkg/config/schemas.
	ConfigsUpdated map[ConfigKey]struct{}

	// Push stores the push context to use for the update. This may initially be nil, as we will
	// debounce changes before a PushContext is eventually created.
	Push *PushContext

	// Start represents the time a push was started. This represents the time of adding to the PushQueue.
	// Note that this does not include time spent debouncing.
	Start time.Time

	// Reason represents the reason for requesting a push. This should only be a fixed set of values,
	// to avoid unbounded cardinality in metrics. If this is not set, it may be automatically filled in later.
	// There should only be multiple reasons if the push request is the result of two distinct triggers, rather than
	// classifying a single trigger as having multiple reasons.
	Reason []TriggerReason

PushRequest defines a request to push to proxies It is used to send updates to the config update debouncer and pass to the PushQueue.

func (*PushRequest) Merge

func (pr *PushRequest) Merge(other *PushRequest) *PushRequest

Merge two update requests together

func (*PushRequest) PushReason

func (pr *PushRequest) PushReason() string

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
	// Passthrough implies that the proxy should forward traffic to the destination IP requested by the caller

func (Resolution) String

func (resolution Resolution) String() string

String converts Resolution in to String.

type Resources

type Resources = []*discovery.Resource

Resources is an alias for array of marshaled resources.

func AnyToUnnamedResources

func AnyToUnnamedResources(r []*any.Any) Resources

type SdsCertificateConfig

type SdsCertificateConfig struct {
	CertificatePath   string
	PrivateKeyPath    string
	CaCertificatePath string

SdsCertificateConfig holds TLS certs needed to build SDS TLS context.

func SdsCertificateConfigFromResourceName

func SdsCertificateConfigFromResourceName(resource string) (SdsCertificateConfig, bool)

SdsCertificateConfigFromResourceName converts the provided resource name into a SdsCertificateConfig If the resource name is not valid, false is returned.

func (SdsCertificateConfig) GetResourceName

func (s SdsCertificateConfig) GetResourceName() string

GetResourceName converts a SdsCertificateConfig to a string to be used as an SDS resource name

func (SdsCertificateConfig) GetRootResourceName

func (s SdsCertificateConfig) GetRootResourceName() string

GetRootResourceName converts a SdsCertificateConfig to a string to be used as an SDS resource name for the root

func (SdsCertificateConfig) IsKeyCertificate

func (s SdsCertificateConfig) IsKeyCertificate() bool

IsKeyCertificate returns true if this config represents key certificate config.

func (SdsCertificateConfig) IsRootCertificate

func (s SdsCertificateConfig) IsRootCertificate() bool

IsRootCertificate returns true if this config represents a root certificate config.

type ServerPort

type ServerPort struct {
	// A valid non-negative integer port number.
	Number uint32
	// The protocol exposed on the port.
	Protocol string
	// The bind server specified on this port.
	Bind string

ServerPort defines port for the gateway server.

type Service

type Service struct {
	// Attributes contains additional attributes associated with the service
	// used mostly by RBAC for policy enforcement purposes.
	Attributes ServiceAttributes

	// 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"`

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

	// Name of the service, e.g. ""
	Hostname host.Name `json:"hostname"`

	// Address specifies the service IPv4 address of the load balancer
	// Do not access directly. Use GetServiceAddressForProxy
	Address string `json:"address,omitempty"`

	// AutoAllocatedAddress specifies the automatically allocated
	// IPv4 address out of the reserved Class E subnet
	// ( for service entries with non-wildcard
	// hostnames. The IPs assigned to services are not
	// synchronized across istiod replicas as the DNS resolution
	// for these service entries happens completely inside a pod
	// whose proxy is managed by one istiod. That said, the algorithm
	// to allocate IPs is pretty deterministic that at stable state, two
	// istiods will allocate the exact same set of IPs for a given set of
	// service entries.
	AutoAllocatedAddress string `json:"autoAllocatedAddress,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[cluster.ID]string `json:"cluster-vips,omitempty"`

	// 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

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

Service describes an Istio service (e.g., 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 and listens on ports 80, 8080

func (*Service) DeepCopy

func (s *Service) DeepCopy() *Service

DeepCopy creates a clone of Service. TODO : See if there is any efficient alternative to this function - copystructure can not be used as is because Service has sync.RWMutex that can not be copied.

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) Validate

func (s *Service) Validate() error

Validate ensures that the service object is well-defined

type ServiceAttributes

type ServiceAttributes struct {
	// ServiceRegistry indicates the backing service registry system where this service
	// was sourced from.
	// TODO: move the ServiceRegistry type from platform.go to model
	ServiceRegistry provider.ID
	// Name is "" attribute
	Name string
	// Namespace is "destination.service.namespace" attribute
	Namespace string
	// Labels applied to the service
	Labels map[string]string
	// ExportTo defines the visibility of Service in
	// a namespace when the namespace is imported.
	ExportTo map[visibility.Instance]bool

	// LabelSelectors are the labels used by the service to select workloads.
	// Applicable to both Kubernetes and ServiceEntries.
	LabelSelectors map[string]string

	// ClusterExternalAddresses is a mapping between a cluster name and the external
	// address(es) to access the service from outside the cluster.
	// Used by the aggregator to aggregate the Attributes.ClusterExternalAddresses
	// for clusters where the service resides
	ClusterExternalAddresses map[cluster.ID][]string

	// ClusterExternalPorts is a mapping between a cluster name and the service port
	// to node port mappings for a given service. When accessing the service via
	// node port IPs, we need to use the kubernetes assigned node ports of the service
	// The port that the user provides in the meshNetworks config is the service port.
	// We translate that to the appropriate node port here.
	ClusterExternalPorts map[cluster.ID]map[uint32]uint32

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
	GetService(hostname host.Name) (*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 an example of
	// Instances(, 80) ->
	//      --> IstioEndpoint(, Service(, Labels(foo=bar)
	//      --> IstioEndpoint(, Service(, Labels(foo=bar)
	//      --> IstioEndpoint(, Service(, Labels(kitty=cat)
	//      --> IstioEndpoint(, Service(, Labels(kitty=cat)
	// Calling Instances with specific labels returns a trimmed list.
	// e.g., Instances(, 80, foo=bar) ->
	//      --> IstioEndpoint(, Service(, Labels(foo=bar)
	//      --> IstioEndpoint(, Service(, 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(svc *Service, servicePort int, labels labels.Collection) []*ServiceInstance

	// 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 IstioEndpoint 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 IstioEndpoint 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

	GetProxyWorkloadLabels(*Proxy) labels.Collection

	// 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(svc *Service, ports []int) []string

	// NetworkGateways returns a list of network gateways that can be used to access endpoints
	// residing in this registry.
	NetworkGateways() []*NetworkGateway

ServiceDiscovery enumerates Istio service instances. nolint: lll

type ServiceInstance

type ServiceInstance struct {
	Service     *Service       `json:"service,omitempty"`
	ServicePort *Port          `json:"servicePort,omitempty"`
	Endpoint    *IstioEndpoint `json:"endpoint,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 IstioEndpoint, 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 are modeled like this

--> IstioEndpoint(, Service(, Labels(foo=bar)
--> IstioEndpoint(, Service(, Labels(foo=bar)
--> IstioEndpoint(, Service(, Labels(kitty=cat)
--> IstioEndpoint(, Service(, Labels(kitty=cat)

func (*ServiceInstance) DeepCopy

func (instance *ServiceInstance) DeepCopy() *ServiceInstance

DeepCopy creates a copy of ServiceInstance.

func (*ServiceInstance) Validate

func (instance *ServiceInstance) Validate() error

Validate ensures that the service instance is well-defined

type SidecarScope

type SidecarScope struct {
	Name string
	// This is the namespace where the sidecar takes effect,
	// maybe different from the ns where sidecar resides if sidecar is in root ns.
	Namespace string
	// The crd itself. Can be nil if we are constructing the default
	// sidecar scope
	Sidecar *networking.Sidecar

	// Version this sidecar was computed for
	Version string

	// 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

	// OutboundTrafficPolicy defines the outbound traffic policy for this sidecar.
	// If OutboundTrafficPolicy is ALLOW_ANY traffic to unknown destinations will
	// be forwarded.
	OutboundTrafficPolicy *networking.OutboundTrafficPolicy

	// The namespace to treat as the administrative root namespace for
	// Istio configuration.
	// Changes to Sidecar resources in this namespace will trigger a push.
	RootNamespace string
	// 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.Config, configNamespace string) *SidecarScope

ConvertToSidecarScope converts from Sidecar config to SidecarScope object

func DefaultSidecarScopeForNamespace

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

DefaultSidecarScopeForNamespace 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) AddConfigDependencies

func (sc *SidecarScope) AddConfigDependencies(dependencies ...ConfigKey)

AddConfigDependencies add extra config dependencies to this scope. This action should be done before the SidecarScope being used to avoid concurrent read/write.

func (*SidecarScope) DependsOnConfig

func (sc *SidecarScope) DependsOnConfig(config ConfigKey) bool

DependsOnConfig determines if the proxy depends on the given config. Returns whether depends on this config or this kind of config is not scoped(unknown to be depended) here.

func (*SidecarScope) DestinationRule

func (sc *SidecarScope) DestinationRule(hostname host.Name) *config.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) HasIngressListener

func (sc *SidecarScope) HasIngressListener() bool

HasIngressListener returns if the sidecar scope has ingress listener set

func (*SidecarScope) MarshalJSON

func (sc *SidecarScope) MarshalJSON() ([]byte, error)

Implement json.Marshaller

func (*SidecarScope) Services

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

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

type StringBool

type StringBool bool

StringBool defines a boolean that is serialized as a string for legacy reasons

func (StringBool) MarshalJSON

func (s StringBool) MarshalJSON() ([]byte, error)

func (*StringBool) UnmarshalJSON

func (s *StringBool) UnmarshalJSON(data []byte) error

type StringList

type StringList []string

StringList is a list that will be marshaled to a comma separate string in Json

func (StringList) MarshalJSON

func (l StringList) MarshalJSON() ([]byte, error)

func (*StringList) UnmarshalJSON

func (l *StringList) UnmarshalJSON(data []byte) error

type TLSServerInfo

type TLSServerInfo struct {
	RouteName string
	SNIHosts  []string

TLSServerInfo contains additional information for TLS Servers.

type Telemetries

type Telemetries struct {
	// Maps from namespace to the Telemetry configs.
	NamespaceToTelemetries map[string][]Telemetry `json:"namespace_to_telemetries"`

	// The name of the root namespace.
	RootNamespace string `json:"root_namespace"`

Telemetries organizes Telemetry configuration by namespace.

func GetTelemetries

func GetTelemetries(env *Environment) (*Telemetries, error)

GetTelemetries returns the Telemetry configurations for the given environment.

func (*Telemetries) EffectiveTelemetry

func (t *Telemetries) EffectiveTelemetry(proxy *Proxy) *tpb.Telemetry

type Telemetry

type Telemetry struct {
	Name      string         `json:"name"`
	Namespace string         `json:"namespace"`
	Spec      *tpb.Telemetry `json:"spec"`

Telemetry holds configuration for Telemetry API resources.

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"

func ParseSubsetKey

func ParseSubsetKey(s string) (direction TrafficDirection, subsetName string, hostname host.Name, port int)

ParseSubsetKey is the inverse of the BuildSubsetKey method

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 TriggerReason

type TriggerReason string
const (
	// Describes a push triggered by an Endpoint change
	EndpointUpdate TriggerReason = "endpoint"
	// Describes a push triggered by a config (generally and Istio CRD) change.
	ConfigUpdate TriggerReason = "config"
	// Describes a push triggered by a Service change
	ServiceUpdate TriggerReason = "service"
	// Describes a push triggered by a change to an individual proxy (such as label change)
	ProxyUpdate TriggerReason = "proxy"
	// Describes a push triggered by a change to global config, such as mesh config
	GlobalUpdate TriggerReason = "global"
	// Describes a push triggered by an unknown reason
	UnknownTrigger TriggerReason = "unknown"
	// Describes a push triggered for debugging
	DebugTrigger TriggerReason = "debug"
	// Describes a push triggered for a Secret change
	SecretTrigger TriggerReason = "secret"
	// Describes a push triggered for Networks change
	NetworksTrigger TriggerReason = "networks"
	// Desribes a push triggered based on proxy request
	ProxyRequest TriggerReason = "proxyrequest"

type WatchedResource

type WatchedResource struct {
	// TypeUrl is copied from the DiscoveryRequest.TypeUrl that initiated watching this resource.
	// nolint
	TypeUrl string

	// ResourceNames tracks the list of resources that are actively watched. If empty, all resources of the
	// TypeUrl type are watched.
	// For endpoints the resource names will have list of clusters and for clusters it is empty.
	ResourceNames []string

	// VersionSent is the version of the resource included in the last sent response.
	// It corresponds to the [Cluster/Route/Listener]VersionSent in the XDS package.
	VersionSent string

	// NonceSent is the nonce sent in the last sent response. If it is equal with NonceAcked, the
	// last message has been processed. If empty: we never sent a message of this type.
	NonceSent string

	// VersionAcked represents the version that was applied successfully. It can be different from
	// VersionSent: if NonceSent == NonceAcked and versions are different it means the client rejected
	// the last version, and VersionAcked is the last accepted and active config.
	// If empty it means the client has no accepted/valid version, and is not ready.
	VersionAcked string

	// NonceAcked is the last acked message.
	NonceAcked string

	// NonceNacked is the last nacked message. This is reset following a successful ACK
	NonceNacked string

	// LastSent tracks the time of the generated push, to determine the time it takes the client to ack.
	LastSent time.Time

	// Updates count the number of generated updates for the resource
	Updates int

	// LastSize tracks the size of the last update
	LastSize int

	// Last request contains the last DiscoveryRequest received for
	// this type. Generators are called immediately after each request,
	// and may use the information in DiscoveryRequest.
	// Note that Envoy may send multiple requests for the same type, for
	// example to update the set of watched resources or to ACK/NACK.
	LastRequest *discovery.DiscoveryRequest

WatchedResource tracks an active DiscoveryRequest subscription.

type WorkloadInstance

type WorkloadInstance struct {
	Name      string            `json:"name,omitempty"`
	Namespace string            `json:"namespace,omitempty"`
	Endpoint  *IstioEndpoint    `json:"endpoint,omitempty"`
	PortMap   map[string]uint32 `json:"portMap,omitempty"`

func (*WorkloadInstance) DeepCopy

func (instance *WorkloadInstance) DeepCopy() *WorkloadInstance

DeepCopy creates a copy of WorkloadInstance.

type XDSUpdater

type XDSUpdater interface {

	// EDSUpdate is called when the list of endpoints or labels in a Service 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, namespace string, entry []*IstioEndpoint)

	// EDSCacheUpdate is called when the list of endpoints or labels in a Service 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.
	// Note: the difference with `EDSUpdate` is that it only update the cache rather than requesting a push
	EDSCacheUpdate(shard, hostname string, namespace string, entry []*IstioEndpoint)

	// SvcUpdate is called when a service definition is updated/deleted.
	SvcUpdate(shard, hostname string, namespace string, event Event)

	// ConfigUpdate is called to notify the XDS server of config updates and request a push.
	// The requests may be collapsed and throttled.
	ConfigUpdate(req *PushRequest)

	// ProxyUpdate is called to notify the XDS server to send a push to the specified proxy.
	// The requests may be collapsed and throttled.
	ProxyUpdate(clusterID cluster.ID, ip string)

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. 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.

type XdsCache

type XdsCache interface {
	// Add adds the given XdsCacheEntry with the value for the given pushContext to the cache.
	// If the cache has been updated to a newer push context, the write will be dropped silently.
	// This ensures stale data does not overwrite fresh data when dealing with concurrent
	// writers.
	Add(entry XdsCacheEntry, pushRequest *PushRequest, value *discovery.Resource)
	// Get retrieves the cached value if it exists. The boolean indicates
	// whether the entry exists in the cache.
	Get(entry XdsCacheEntry) (*discovery.Resource, bool)
	// Clear removes the cache entries that are dependent on the configs passed.
	// ClearAll clears the entire cache.
	// Keys returns all currently configured keys. This is for testing/debug only
	Keys() []string
	// Snapshot returns a snapshot of all keys and values. This is for testing/debug only
	Snapshot() map[string]*discovery.Resource

XdsCache interface defines a store for caching XDS responses. All operations are thread safe.

func NewLenientXdsCache

func NewLenientXdsCache() XdsCache

NewLenientXdsCache returns an instance of a cache that does not validate token based get/set and enable assertions.

func NewXdsCache

func NewXdsCache() XdsCache

NewXdsCache returns an instance of a cache.

type XdsCacheEntry

type XdsCacheEntry interface {
	// Key is the key to be used in cache.
	Key() string
	// DependentTypes are config types that this cache key is dependant on.
	// Whenever any configs of this type changes, we should invalidate this cache entry.
	// Note: DependentConfigs should be preferred wherever possible.
	DependentTypes() []config.GroupVersionKind
	// DependentConfigs is config items that this cache key is dependent on.
	// Whenever these configs change, we should invalidate this cache entry.
	DependentConfigs() []ConfigKey
	// Cacheable indicates whether this entry is valid for cache. For example
	// for EDS to be cacheable, the Endpoint should have corresponding service.
	Cacheable() bool

XdsCacheEntry interface defines functions that should be implemented by resources that can be cached.

type XdsLogDetails

type XdsLogDetails struct {
	Incremental    bool
	AdditionalInfo string

XdsLogDetails contains additional metadata that is captured by Generators and used by xds processors like Ads and Delta to uniformly log.

type XdsResourceGenerator

type XdsResourceGenerator interface {
	Generate(proxy *Proxy, push *PushContext, w *WatchedResource, updates *PushRequest) (Resources, XdsLogDetails, error)

XdsResourceGenerator creates the response for a typeURL DiscoveryRequest. If no generator is associated with a Proxy, the default (a networking.core.ConfigGenerator instance) will be used. The server may associate a different generator based on client metadata. Different WatchedResources may use same or different Generator. Note: any errors returned will completely close the XDS stream. Use with caution; typically and empty or no response is preferred.

type XdsUpdates

type XdsUpdates = map[ConfigKey]struct{}

XdsUpdates include information about the subset of updated resources. See for example EDS incremental updates.


Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to