model

package
v0.0.0-...-fd5c82b Latest Latest
Warning

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

Go to latest
Published: Dec 24, 2024 License: Apache-2.0 Imports: 107 Imported by: 623

Documentation

Index

Constants

View Source
const (
	SidecarProxy = pm.SidecarProxy
	Router       = pm.Router
	Waypoint     = pm.Waypoint
	Ztunnel      = pm.Ztunnel

	IPv4 = pm.IPv4
	IPv6 = pm.IPv6
	Dual = pm.Dual
)
View Source
const (
	WasmSecretEnv          = pm.WasmSecretEnv
	WasmPolicyEnv          = pm.WasmPolicyEnv
	WasmResourceVersionEnv = pm.WasmResourceVersionEnv

	// WasmPluginResourceNamePrefix is the prefix of the resource name of WasmPlugin,
	// preventing the name collision with other resources.
	WasmPluginResourceNamePrefix = "extenstions.istio.io/wasmplugin/"
)
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"

	// VirtualOutboundBlackholeFilterChainName is the name of the filter chain to blackhole undesired traffic
	VirtualOutboundBlackholeFilterChainName = "virtualOutbound-blackhole"
	// VirtualInboundBlackholeFilterChainName 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 (
	// TunnelLabel defines the label workloads describe to indicate that they support tunneling.
	// Values are expected to be a CSV list, sorted by preference, of protocols supported.
	// Currently supported values:
	// * "http": indicates tunneling over HTTP over TCP. HTTP/2 vs HTTP/1.1 may be supported by ALPN negotiation.
	// Planned future values:
	// * "http3": indicates tunneling over HTTP over QUIC. This is distinct from "http", since we cannot do ALPN
	//   negotiation for QUIC vs TCP.
	// Users should appropriately parse the full list rather than doing a string literal check to
	// ensure future-proofing against new protocols being added.
	TunnelLabel = "networking.istio.io/tunnel"
	// TunnelLabelShortName is a short name for TunnelLabel to be used in optimized scenarios.
	TunnelLabelShortName = "tunnel"
	// TunnelHTTP indicates tunneling over HTTP over TCP. HTTP/2 vs HTTP/1.1 may be supported by ALPN
	// negotiation. Note: ALPN negotiation is not currently implemented; HTTP/2 will always be used.
	// This is future-proofed, however, because only the `h2` ALPN is exposed.
	TunnelHTTP = "http"
)
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 = pm.IstioCanonicalServiceLabelName

	// IstioCanonicalServiceRevisionLabelName is the name of label for the Istio Canonical Service revision for a workload instance.
	IstioCanonicalServiceRevisionLabelName = pm.IstioCanonicalServiceRevisionLabelName
)
View Source
const (
	// PodKind indicates the workload is from pod
	PodKind workloadKind = iota
	// WorkloadEntryKind indicates the workload is from workloadentry
	WorkloadEntryKind
)
View Source
const (
	WaypointPolicyReasonAccepted         = "Accepted"
	WaypointPolicyReasonInvalid          = "Invalid"
	WaypointPolicyReasonPartiallyInvalid = "PartiallyInvalid"
	WaypointPolicyReasonAncestorNotBound = "AncestorNotBound"
	WaypointPolicyReasonTargetNotFound   = "TargetNotFound"
)
View Source
const (
	// EnvoyTextLogFormat format for envoy text based access logs for Istio 1.9 onwards.
	// This includes the additional new operator RESPONSE_CODE_DETAILS and CONNECTION_TERMINATION_DETAILS that tells
	// the reason why Envoy rejects a request.
	EnvoyTextLogFormat = "[%START_TIME%] \"%REQ(:METHOD)% %REQ(X-ENVOY-ORIGINAL-PATH?:PATH)% " +
		"%PROTOCOL%\" %RESPONSE_CODE% %RESPONSE_FLAGS% " +
		"%RESPONSE_CODE_DETAILS% %CONNECTION_TERMINATION_DETAILS% " +
		"\"%UPSTREAM_TRANSPORT_FAILURE_REASON%\" %BYTES_RECEIVED% %BYTES_SENT% " +
		"%DURATION% %RESP(X-ENVOY-UPSTREAM-SERVICE-TIME)% \"%REQ(X-FORWARDED-FOR)%\" " +
		"\"%REQ(USER-AGENT)%\" \"%REQ(X-REQUEST-ID)%\" \"%REQ(:AUTHORITY)%\" \"%UPSTREAM_HOST%\" " +
		"%UPSTREAM_CLUSTER_RAW% %UPSTREAM_LOCAL_ADDRESS% %DOWNSTREAM_LOCAL_ADDRESS% " +
		"%DOWNSTREAM_REMOTE_ADDRESS% %REQUESTED_SERVER_NAME% %ROUTE_NAME%\n"

	HTTPEnvoyAccessLogFriendlyName = "http_envoy_accesslog"
	TCPEnvoyAccessLogFriendlyName  = "tcp_envoy_accesslog"
	OtelEnvoyAccessLogFriendlyName = "otel_envoy_accesslog"

	TCPEnvoyALSName  = "envoy.tcp_grpc_access_log"
	OtelEnvoyALSName = "envoy.access_loggers.open_telemetry"

	DevStdout = "/dev/stdout"
)
View Source
const (
	UnixAddressPrefix          = "unix://"
	PodIPAddressPrefix         = "0.0.0.0"
	LocalhostAddressPrefix     = "127.0.0.1"
	PodIPv6AddressPrefix       = "::"
	LocalhostIPv6AddressPrefix = "::1"
)

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 (
	CDSType = "cds"
	EDSType = "eds"
	RDSType = "rds"
	SDSType = "sds"
)
View Source
const DisableGatewayPortTranslationLabel = "experimental.istio.io/disable-gateway-port-translation"

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 FakeJwks = `` /* 1716-byte string literal not displayed */

FakeJwks is a fake jwks, generated by following code

fakeJwksRSAKey, _ := rsa.GenerateKey(rand.Reader, 2048)
key, _ := jwk.FromRaw(fakeJwksRSAKey)
rsaKey, _ := key.(jwk.RSAPrivateKey)
res, _ := json.Marshal(rsaKey)
fmt.Printf("{\"keys\":[ %s]}\n", string(res))

it should be static across different instances and versions. more details can be found: https://github.com/istio/istio/pull/47661. nolint: lll

View Source
const (

	// HBoneInboundListenPort is the port on which incoming HBone traffic will be captured.
	HBoneInboundListenPort = 15008
)
View Source
const InternalGatewayServiceAnnotation = "internal.istio.io/gateway-service"

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,ingress.example.com" The Gateway will apply to all ServiceInstances of these services, *in the same namespace as the Gateway*.

View Source
const (
	// 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 = pm.LocalityLabel
)
View Source
const (
	// NamespaceAll is a designated symbol for listing across all namespaces
	NamespaceAll = ""
)

Variables

View Source
var (
	// MinGatewayTTL is exported for testing
	MinGatewayTTL = 30 * time.Second

	// https://github.com/coredns/coredns/blob/v1.10.1/plugin/pkg/dnsutil/ttl.go#L51
	MaxGatewayTTL = 1 * time.Hour
)
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(
		"endpoint_no_pod",
		"Endpoints without an associated pod.",
	)

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

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

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

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

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

	// DNSNoEndpointClusters tracks dns clusters without endpoints
	DNSNoEndpointClusters = monitoring.NewGauge(
		"pilot_dns_cluster_without_endpoints",
		"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(
		"pilot_eds_no_instances",
		"Number of clusters without instances.",
	)

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

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

	// LastPushStatus preserves the metrics and data collected during lasts global push.
	// It can be used by debugging tools to inspect the push event. It will be reset after each push with the
	// new version.
	LastPushStatus *PushContext
	// LastPushMutex will protect the LastPushStatus
	LastPushMutex sync.Mutex
)
View Source
var DefaultXdsLogDetails = XdsLogDetails{}
View Source
var (

	// EnvoyJSONLogFormatIstio map of values for envoy json based access logs for Istio 1.9 onwards.
	// This includes the additional log operator RESPONSE_CODE_DETAILS and CONNECTION_TERMINATION_DETAILS that tells
	// the reason why Envoy rejects a request.
	EnvoyJSONLogFormatIstio = &structpb.Struct{
		Fields: map[string]*structpb.Value{
			"start_time":                        {Kind: &structpb.Value_StringValue{StringValue: "%START_TIME%"}},
			"route_name":                        {Kind: &structpb.Value_StringValue{StringValue: "%ROUTE_NAME%"}},
			"method":                            {Kind: &structpb.Value_StringValue{StringValue: "%REQ(:METHOD)%"}},
			"path":                              {Kind: &structpb.Value_StringValue{StringValue: "%REQ(X-ENVOY-ORIGINAL-PATH?:PATH)%"}},
			"protocol":                          {Kind: &structpb.Value_StringValue{StringValue: "%PROTOCOL%"}},
			"response_code":                     {Kind: &structpb.Value_StringValue{StringValue: "%RESPONSE_CODE%"}},
			"response_flags":                    {Kind: &structpb.Value_StringValue{StringValue: "%RESPONSE_FLAGS%"}},
			"response_code_details":             {Kind: &structpb.Value_StringValue{StringValue: "%RESPONSE_CODE_DETAILS%"}},
			"connection_termination_details":    {Kind: &structpb.Value_StringValue{StringValue: "%CONNECTION_TERMINATION_DETAILS%"}},
			"bytes_received":                    {Kind: &structpb.Value_StringValue{StringValue: "%BYTES_RECEIVED%"}},
			"bytes_sent":                        {Kind: &structpb.Value_StringValue{StringValue: "%BYTES_SENT%"}},
			"duration":                          {Kind: &structpb.Value_StringValue{StringValue: "%DURATION%"}},
			"upstream_service_time":             {Kind: &structpb.Value_StringValue{StringValue: "%RESP(X-ENVOY-UPSTREAM-SERVICE-TIME)%"}},
			"x_forwarded_for":                   {Kind: &structpb.Value_StringValue{StringValue: "%REQ(X-FORWARDED-FOR)%"}},
			"user_agent":                        {Kind: &structpb.Value_StringValue{StringValue: "%REQ(USER-AGENT)%"}},
			"request_id":                        {Kind: &structpb.Value_StringValue{StringValue: "%REQ(X-REQUEST-ID)%"}},
			"authority":                         {Kind: &structpb.Value_StringValue{StringValue: "%REQ(:AUTHORITY)%"}},
			"upstream_host":                     {Kind: &structpb.Value_StringValue{StringValue: "%UPSTREAM_HOST%"}},
			"upstream_cluster":                  {Kind: &structpb.Value_StringValue{StringValue: "%UPSTREAM_CLUSTER_RAW%"}},
			"upstream_local_address":            {Kind: &structpb.Value_StringValue{StringValue: "%UPSTREAM_LOCAL_ADDRESS%"}},
			"downstream_local_address":          {Kind: &structpb.Value_StringValue{StringValue: "%DOWNSTREAM_LOCAL_ADDRESS%"}},
			"downstream_remote_address":         {Kind: &structpb.Value_StringValue{StringValue: "%DOWNSTREAM_REMOTE_ADDRESS%"}},
			"requested_server_name":             {Kind: &structpb.Value_StringValue{StringValue: "%REQUESTED_SERVER_NAME%"}},
			"upstream_transport_failure_reason": {Kind: &structpb.Value_StringValue{StringValue: "%UPSTREAM_TRANSPORT_FAILURE_REASON%"}},
		},
	}
)
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 NetworkGatewayTestDNSServers []string

NetworkGatewayTestDNSServers if set will ignore resolv.conf and use the given DNS servers for tests.

Functions

func AssertProvidersHandled

func AssertProvidersHandled(expected int)

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, bind string, knownHosts map[string]string) []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 sets.Set[ConfigKey], kind kind.Kind) sets.String

ConfigNamesOfKind extracts config names of the specified kind.

func ConfigsOfKind

func ConfigsOfKind(configs sets.Set[ConfigKey], kind kind.Kind) sets.Set[ConfigKey]

ConfigsOfKind extracts configs of the specified kind.

func ConvertStructToAttributeKeyValues

func ConvertStructToAttributeKeyValues(labels map[string]*structpb.Value) []*otlpcommon.KeyValue

func FileAccessLogFromMeshConfig

func FileAccessLogFromMeshConfig(path string, mesh *meshconfig.MeshConfig) *accesslog.AccessLog

func GetAmbientPolicyConfigName

func GetAmbientPolicyConfigName(key ConfigKey) string

func GetLocalityLabel

func GetLocalityLabel(label string) string

GetLocalityLabel returns the locality from the supplied label. 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 GetTLSModeFromEndpointLabels

func GetTLSModeFromEndpointLabels(labels map[string]string) string

GetTLSModeFromEndpointLabels returns the value of the label security.istio.io/tlsMode 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 GetTargetRefs

GetTargetRefs returns the list of targetRefs, taking into account the legacy targetRef

func HasConfigsOfKind

func HasConfigsOfKind(configs sets.Set[ConfigKey], kind kind.Kind) bool

HasConfigsOfKind returns true if configs has changes of type kind

func IncLookupClusterFailures

func IncLookupClusterFailures(provider string)

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 LookupCluster

func LookupCluster(push *PushContext, service string, port int) (hostname string, cluster string, err error)

func MostSpecificHostMatch

func MostSpecificHostMatch[V any](needle host.Name, specific map[host.Name]V, wildcard map[host.Name]V) (host.Name, V, bool)

MostSpecificHostMatch compares the maps of specific and wildcard hosts to the needle, and returns the longest element matching the needle and it's value, or false if no element in the maps matches the needle.

func OutboundListenerClass

func OutboundListenerClass(t NodeType) istionetworking.ListenerClass

OutboundListenerClass is a helper to turn a NodeType for outbound to a ListenerClass.

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 ParseSubsetKeyHostname

func ParseSubsetKeyHostname(s string) (hostname string)

ParseSubsetKeyHostname is an optimized specialization of ParseSubsetKey that only returns the hostname. This is created as this is used in some hot paths and is about 2x faster than ParseSubsetKey; for typical use ParseSubsetKey is sufficient (and zero-alloc).

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 SelectVirtualServices

func SelectVirtualServices(vsidx virtualServiceIndex, configNamespace string, hostsByNamespace map[string]hostClassification) []config.Config

SelectVirtualServices selects the virtual services by matching given services' host names. This function is used by sidecar converter.

func SupportsTunnel

func SupportsTunnel(labels map[string]string, tunnelType string) bool

func UseGatewaySemantics

func UseGatewaySemantics(cfg config.Config) bool

UseGatewaySemantics determines which logic we should use for VirtualService This allows gateway-api and VS to both be represented by VirtualService, but have different semantics.

func UseIngressSemantics

func UseIngressSemantics(cfg config.Config) bool

UseIngressSemantics determines which logic we should use for VirtualService This allows ingress and VS to both be represented by VirtualService, but have different semantics.

func WarmingDependencies

func WarmingDependencies(typeURL string) []string

WarmingDependencies returns the dependent typeURLs that need to be responded with for warming of this typeURL.

func WorkloadInstancesEqual

func WorkloadInstancesEqual(first, second *WorkloadInstance) bool

WorkloadInstancesEqual is a custom comparison of workload instances based on the fields that we need. Returns true if equal, false otherwise.

Types

type AddressInfo

type AddressInfo struct {
	*workloadapi.Address
}

func (AddressInfo) Aliases

func (i AddressInfo) Aliases() []string

func (AddressInfo) ResourceName

func (i AddressInfo) ResourceName() string

type AddressMap

type AddressMap struct {
	// Addresses hold the underlying map. Most code should only access this through the available methods.
	// Should only be used by tests and construction/initialization logic, where there is no concern
	// for race conditions.
	Addresses map[cluster.ID][]string
	// contains filtered or unexported fields
}

AddressMap provides a thread-safe mapping of addresses for each Kubernetes cluster.

func (*AddressMap) AddAddressesFor

func (m *AddressMap) AddAddressesFor(c cluster.ID, addresses []string) *AddressMap

func (*AddressMap) DeepCopy

func (m *AddressMap) DeepCopy() *AddressMap

func (*AddressMap) ForEach

func (m *AddressMap) ForEach(fn func(c cluster.ID, addresses []string))

func (*AddressMap) GetAddresses

func (m *AddressMap) GetAddresses() map[cluster.ID][]string

GetAddresses returns the mapping of clusters to addresses.

func (*AddressMap) GetAddressesFor

func (m *AddressMap) GetAddressesFor(c cluster.ID) []string

func (*AddressMap) Len

func (m *AddressMap) Len() int

func (*AddressMap) SetAddresses

func (m *AddressMap) SetAddresses(addrs map[cluster.ID][]string)

SetAddresses sets the addresses per cluster.

func (*AddressMap) SetAddressesFor

func (m *AddressMap) SetAddressesFor(c cluster.ID, addresses []string) *AddressMap

type AggregateController

type AggregateController interface {
	Controller
	// AppendServiceHandlerForCluster is similar to Controller.AppendServiceHandler,
	// but it is used to store the handler from a specific cluster.
	AppendServiceHandlerForCluster(clusterID cluster.ID, f ServiceHandler)
	UnRegisterHandlersForCluster(clusterID cluster.ID)
}

AggregateController is a wrapper of Controller, it supports registering handlers of a specific cluster。

type AmbientIndexes

type AmbientIndexes interface {
	ServicesWithWaypoint(key string) []ServiceWaypointInfo
	AddressInformation(addresses sets.String) ([]AddressInfo, sets.String)
	AdditionalPodSubscriptions(
		proxy *Proxy,
		allAddresses sets.String,
		currentSubs sets.String,
	) sets.String
	Policies(requested sets.Set[ConfigKey]) []WorkloadAuthorization
	ServicesForWaypoint(WaypointKey) []ServiceInfo
	WorkloadsForWaypoint(WaypointKey) []WorkloadInfo
}

type AuthenticationPolicies

type AuthenticationPolicies struct {
	// contains filtered or unexported fields
}

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

func (*AuthenticationPolicies) GetJwtPoliciesForWorkload

func (policy *AuthenticationPolicies) GetJwtPoliciesForWorkload(policyMatcher WorkloadPolicyMatcher) []*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(policyMatcher WorkloadPolicyMatcher) []*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.

func (*AuthenticationPolicies) GetVersion

func (policy *AuthenticationPolicies) GetVersion() string

GetVersion return versions of all peer authentications..

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

GetAuthorizationPolicies returns the AuthorizationPolicies for the given environment.

func (*AuthorizationPolicies) ListAuthorizationPolicies

func (policy *AuthorizationPolicies) ListAuthorizationPolicies(selectionOpts WorkloadPolicyMatcher) 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"`
}

func (*AuthorizationPolicy) NamespacedName

func (ap *AuthorizationPolicy) NamespacedName() types.NamespacedName

type BootstrapNodeMetadata

type BootstrapNodeMetadata = pm.BootstrapNodeMetadata

func ParseBootstrapNodeMetadata

func ParseBootstrapNodeMetadata(metadata *structpb.Struct) (*BootstrapNodeMetadata, error)

ParseBootstrapNodeMetadata parses the opaque Metadata from an Envoy Node into string key-value pairs.

type CacheToken

type CacheToken uint64

type ClusterLocalHosts

type ClusterLocalHosts struct {
	// contains filtered or unexported fields
}

ClusterLocalHosts is a map of host names or wildcard patterns which indicate whether a host be made accessible from within the same cluster or not.

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 Condition

type Condition struct {
	ObservedGeneration int64
	Reason             string
	Message            string
	Status             bool
}

func (*Condition) Equals

func (c *Condition) Equals(v *Condition) bool

type ConditionSet

type ConditionSet = map[ConditionType]*Condition

type ConditionType

type ConditionType string
const (
	WaypointBound    ConditionType = "istio.io/WaypointBound"
	ZtunnelAccepted  ConditionType = "ZtunnelAccepted"
	WaypointAccepted ConditionType = "WaypointAccepted"
)

type ConfigHash

type ConfigHash uint64

type ConfigKey

type ConfigKey struct {
	Kind      kind.Kind
	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 VirtualServiceDependencies

func VirtualServiceDependencies(vs config.Config) []ConfigKey

VirtualServiceDependencies returns dependent configs of the vs, for internal vs generated from gateway-api routes, it returns the parent routes, otherwise it just returns the vs as is.

func (ConfigKey) HashCode

func (key ConfigKey) HashCode() ConfigHash

func (ConfigKey) String

func (key ConfigKey) String() string

type ConfigStore

type ConfigStore interface {
	// Schemas exposes the configuration type schema known by the config store.
	// The type schema defines the bidirectional 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

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

type ConfigStoreController interface {
	ConfigStore

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

	// Run until a signal is received.
	// Run *should* block, so callers should typically call `go controller.Run(stop)`
	Run(stop <-chan struct{})

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

ConfigStoreController is a local fully-replicated cache of the config store with additional handlers. The controller 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 ConsolidatedDestRule

type ConsolidatedDestRule struct {
	// contains filtered or unexported fields
}

ConsolidatedDestRule represents a dr and from which it is consolidated.

func ConvertConsolidatedDestRule

func ConvertConsolidatedDestRule(cfg *config.Config, exportToSet sets.Set[visibility.Instance]) *ConsolidatedDestRule

func (*ConsolidatedDestRule) Equals

Equals compare l equals r consolidatedDestRule or not.

func (*ConsolidatedDestRule) GetFrom

func (l *ConsolidatedDestRule) GetFrom() []types.NamespacedName

func (*ConsolidatedDestRule) GetRule

func (l *ConsolidatedDestRule) GetRule() *config.Config

func (*ConsolidatedDestRule) MarshalJSON

func (l *ConsolidatedDestRule) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaller

type Controller

type Controller interface {

	// AppendServiceHandler notifies about changes to the service catalog.
	AppendServiceHandler(f ServiceHandler)

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

type ControllerHandlers struct {
	// contains filtered or unexported fields
}

ControllerHandlers is a utility to help Controller implementations manage their lists of handlers.

func (*ControllerHandlers) AppendServiceHandler

func (c *ControllerHandlers) AppendServiceHandler(f ServiceHandler)

func (*ControllerHandlers) AppendWorkloadHandler

func (c *ControllerHandlers) AppendWorkloadHandler(f func(*WorkloadInstance, Event))

func (*ControllerHandlers) GetServiceHandlers

func (c *ControllerHandlers) GetServiceHandlers() []ServiceHandler

func (*ControllerHandlers) GetWorkloadHandlers

func (c *ControllerHandlers) GetWorkloadHandlers() []func(*WorkloadInstance, Event)

func (*ControllerHandlers) NotifyServiceHandlers

func (c *ControllerHandlers) NotifyServiceHandlers(prev, curr *Service, event Event)

func (*ControllerHandlers) NotifyWorkloadHandlers

func (c *ControllerHandlers) NotifyWorkloadHandlers(w *WorkloadInstance, event Event)

type DeletedResources

type DeletedResources = []string

DeletedResources is an alias for array of strings that represent removed resources in delta.

type DisabledCache

type DisabledCache struct{}

DisabledCache is a cache that is always empty

func (DisabledCache) Add

func (d DisabledCache) Add(entry XdsCacheEntry, pushRequest *PushRequest, value *discovery.Resource)

func (DisabledCache) Clear

func (d DisabledCache) Clear(s sets.Set[ConfigKey])

func (DisabledCache) ClearAll

func (d DisabledCache) ClearAll()

func (DisabledCache) Get

func (DisabledCache) Keys

func (d DisabledCache) Keys(t string) []any

func (DisabledCache) Run

func (d DisabledCache) Run(stop <-chan struct{})

func (DisabledCache) Snapshot

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

type EdsUpdateFn

type EdsUpdateFn func(shard ShardKey, hostname string, namespace string, entry []*IstioEndpoint)

type EndpointDiscoverabilityPolicy

type EndpointDiscoverabilityPolicy interface {
	// IsDiscoverableFromProxy indicates whether an endpoint is discoverable from the given Proxy.
	IsDiscoverableFromProxy(*IstioEndpoint, *Proxy) bool

	// String returns name of this policy.
	String() string
}

EndpointDiscoverabilityPolicy determines the discoverability of an endpoint throughout the mesh.

var AlwaysDiscoverable EndpointDiscoverabilityPolicy = &endpointDiscoverabilityPolicyImpl{
	name: "AlwaysDiscoverable",
	f: func(*IstioEndpoint, *Proxy) bool {
		return true
	},
}

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

var DiscoverableFromSameCluster EndpointDiscoverabilityPolicy = &endpointDiscoverabilityPolicyImpl{
	name: "DiscoverableFromSameCluster",
	f: 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.

type EndpointIndex

type EndpointIndex struct {
	// contains filtered or unexported fields
}

EndpointIndex is a mutex protected index of endpoint shards

func NewEndpointIndex

func NewEndpointIndex(cache XdsCache) *EndpointIndex

func (*EndpointIndex) DeleteServiceShard

func (e *EndpointIndex) DeleteServiceShard(shard ShardKey, serviceName, namespace string, preserveKeys bool)

func (*EndpointIndex) DeleteShard

func (e *EndpointIndex) DeleteShard(shardKey ShardKey)

func (*EndpointIndex) GetOrCreateEndpointShard

func (e *EndpointIndex) GetOrCreateEndpointShard(serviceName, namespace string) (*EndpointShards, bool)

GetOrCreateEndpointShard returns the shards. The second return parameter will be true if this service was seen for the first time.

func (*EndpointIndex) ShardsForService

func (e *EndpointIndex) ShardsForService(serviceName, namespace string) (*EndpointShards, bool)

ShardsForService returns the shards and true if they are found, or returns nil, false.

func (*EndpointIndex) Shardz

func (e *EndpointIndex) Shardz() map[string]map[string]*EndpointShards

Shardz returns a full deep copy of the global map of shards. This should be used only for testing and debugging, as the cloning is expensive.

func (*EndpointIndex) UpdateServiceEndpoints

func (e *EndpointIndex) UpdateServiceEndpoints(
	shard ShardKey,
	hostname string,
	namespace string,
	istioEndpoints []*IstioEndpoint,
	logPushType bool,
) PushType

UpdateServiceEndpoints updates EndpointShards data by clusterID, hostname, IstioEndpoints. It also tracks the changes to ServiceAccounts. It returns whether endpoints need to be pushed and it also returns if they need to be pushed whether a full push is needed or incremental push is sufficient.

type EndpointMetadata

type EndpointMetadata struct {
	// Network holds the network where this endpoint is present
	Network network.ID

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

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

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

	// Labels points to the workload or deployment labels.
	Labels labels.Instance

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

EndpointMetadata represents metadata set on Envoy LbEndpoint used for telemetry purposes.

type EndpointShards

type EndpointShards struct {
	// mutex protecting below map.
	sync.RWMutex

	// Shards is used to track the shards. EDS updates are grouped by shard.
	// Current implementation uses the registry name as key - in multicluster this is the
	// name of the k8s cluster, derived from the config (secret).
	Shards map[ShardKey][]*IstioEndpoint

	// ServiceAccounts has the concatenation of all service accounts seen so far in endpoints.
	// This is updated on push, based on shards. If the previous list is different than
	// current list, a full push will be forced, to trigger a secure naming update.
	// Due to the larger time, it is still possible that connection errors will occur while
	// CDS is updated.
	ServiceAccounts sets.String
}

EndpointShards holds the set of endpoint shards of a service. Registries update individual shards incrementally. The shards are aggregated and split into clusters when a push for the specific cluster is needed.

func (*EndpointShards) CopyEndpoints

func (es *EndpointShards) CopyEndpoints(portMap map[string]int, ports sets.Set[int]) map[int][]*IstioEndpoint

CopyEndpoints takes a snapshot of all endpoints. As input, it takes a map of port name to number, to allow it to group the results by service port number. This is a bit weird, but lets us efficiently construct the format the caller needs.

func (*EndpointShards) DeepCopy

func (es *EndpointShards) DeepCopy() *EndpointShards

func (*EndpointShards) Keys

func (es *EndpointShards) Keys() []ShardKey

Keys gives a sorted list of keys for EndpointShards.Shards. Calls to Keys should be guarded with a lock on the EndpointShards.

type Environment

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

	// Config interface for listing routing rules
	ConfigStore

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

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

	NetworkManager *NetworkManager

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

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

	CredentialsController credentials.MulticlusterController

	GatewayAPIController GatewayController

	// EndpointShards for a service. This is a global (per-server) list, built from
	// incremental updates. This is keyed by service and namespace
	EndpointIndex *EndpointIndex

	// Cache for XDS resources.
	Cache XdsCache
	// contains filtered or unexported fields
}

Environment provides an aggregate environmental API for Pilot

func NewEnvironment

func NewEnvironment() *Environment

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

func (e *Environment) GetProxyConfigOrDefault(ns string, labels, annotations map[string]string, meshConfig *meshconfig.MeshConfig) *meshconfig.ProxyConfig

func (*Environment) Init

func (e *Environment) Init()

Init initializes the Environment for use.

func (*Environment) InitNetworksManager

func (e *Environment) InitNetworksManager(updater XDSUpdater) (err error)

func (*Environment) Mesh

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

func (*Environment) MeshNetworks

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

func (*Environment) PushContext

func (e *Environment) PushContext() *PushContext

PushContext returns the push context with lock protected

func (*Environment) SetPushContext

func (e *Environment) SetPushContext(pc *PushContext)

SetPushContext sets the push context with lock protected

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
	FullName         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
	Priority int32
	// contains filtered or unexported fields
}

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

func (*EnvoyFilterWrapper) Keys

func (efw *EnvoyFilterWrapper) Keys() []string

Returns the keys of all the wrapped envoyfilters.

func (*EnvoyFilterWrapper) KeysApplyingTo

func (efw *EnvoyFilterWrapper) KeysApplyingTo(applyTo ...networking.EnvoyFilter_ApplyTo) []string

Returns the keys of all the wrapped envoyfilters.

type Event

type Event int

Event represents a registry update event

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

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

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

func (Event) String

func (event Event) String() string

type EventHandler

type EventHandler = func(config.Config, config.Config, Event)

type FakeEndpointIndexUpdater

type FakeEndpointIndexUpdater struct {
	Index *EndpointIndex
	// Optional; if set, we will trigger ConfigUpdates in response to EDS updates as appropriate
	ConfigUpdateFunc func(req *PushRequest)
}

FakeEndpointIndexUpdater is an updater that will keep an EndpointIndex in sync. This is intended for tests only.

func NewEndpointIndexUpdater

func NewEndpointIndexUpdater(ei *EndpointIndex) *FakeEndpointIndexUpdater

func (*FakeEndpointIndexUpdater) ConfigUpdate

func (f *FakeEndpointIndexUpdater) ConfigUpdate(*PushRequest)

func (*FakeEndpointIndexUpdater) EDSCacheUpdate

func (f *FakeEndpointIndexUpdater) EDSCacheUpdate(shard ShardKey, serviceName string, namespace string, eps []*IstioEndpoint)

func (*FakeEndpointIndexUpdater) EDSUpdate

func (f *FakeEndpointIndexUpdater) EDSUpdate(shard ShardKey, serviceName string, namespace string, eps []*IstioEndpoint)

func (*FakeEndpointIndexUpdater) ProxyUpdate

func (f *FakeEndpointIndexUpdater) ProxyUpdate(_ cluster.ID, _ string)

func (*FakeEndpointIndexUpdater) RemoveShard

func (f *FakeEndpointIndexUpdater) RemoveShard(shardKey ShardKey)

func (*FakeEndpointIndexUpdater) SvcUpdate

func (f *FakeEndpointIndexUpdater) SvcUpdate(shard ShardKey, hostname string, namespace string, event Event)

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 (s *FakeStore) Delete(typ config.GroupVersionKind, name, namespace string, rv *string) error

func (*FakeStore) Get

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

func (*FakeStore) List

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

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 (s *FakeStore) Update(cfg config.Config) (newRevision string, err error)

func (*FakeStore) UpdateStatus

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

type GatewayController

type GatewayController interface {
	ConfigStoreController
	// Reconcile updates the internal state of the gateway controller for a given input. This should be
	// called before any List/Get calls if the state has changed
	Reconcile(ctx *PushContext) error
	// SecretAllowed determines if a SDS credential is accessible to a given namespace.
	// For example, for resourceName of `kubernetes-gateway://ns-name/secret-name` and namespace of `ingress-ns`,
	// this would return true only if there was a policy allowing `ingress-ns` to access Secrets in the `ns-name` namespace.
	SecretAllowed(resourceName string, namespace string) bool
}

type GatewayPortMap

type GatewayPortMap map[int]sets.Set[int]

type HealthStatus

type HealthStatus int32

Endpoint health status.

const (
	// Healthy.
	Healthy HealthStatus = 1
	// Unhealthy.
	UnHealthy HealthStatus = 2
	// Draining - the constant matches envoy
	Draining HealthStatus = 3
)

type IPMode

type IPMode = pm.IPMode

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

func (ilw *IstioEgressListenerWrapper) MostSpecificWildcardVirtualServiceIndex() map[host.Name]types.NamespacedName

MostSpecificWildcardVirtualServiceIndex returns the mostSpecificWildcardVsIndex for this egress 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

	// Addresses are the addresses of the endpoint, using envoy proto:
	// https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/endpoint/v3/endpoint_components.proto#config-endpoint-v3-endpoint-additionaladdress
	// This field can support multiple addresses for an Dual Stack endpoint, especially for an endpoint which contains both ipv4 or ipv6 addresses.
	// There should be some constraints below:
	// 1. Each address of the endpoint must have the same metadata.
	// 2. The function Key() of IstioEndpoint returns the first IP address of this field in string format.
	// 3. The IP address of field `address` in Envoy Endpoint is equal to the first address of this field.
	// When the additional_addresses field is populated for EDS in Envoy configuration, Envoy will use an Happy Eyeballs algorithm.
	// Therefore Envoy will first attempt connecting to the IP address in the `address` field of Envoy Endpoint.
	// If the first attempt fails, then it will interleave IP addresses in the `additional_addresses` field based on IP version, as described in rfc8305,
	// and attempt connections with them with a delay of 300ms each. The first connection to succeed will be used.
	// Note: it uses Hash Based Load Balancing Policies for multiple addresses support Endpoint, and only the first address of the
	// endpoint will be used as the hash key for the ring or maglev list, however, the upstream address that load balancer ends up
	// connecting to will depend on the one that ends up "winning" using the Happy Eyeballs algorithm.
	// Please refer to https://docs.google.com/document/d/1AjmTcMWwb7nia4rAgqE-iqIbSbfiXCI4h1vk-FONFdM/ for more details.
	Addresses []string

	// ServicePortName tracks the name of the port, this is used to select the IstioEndpoint by service port.
	ServicePortName string
	// LegacyClusterPortKey provides an alternative key from ServicePortName to support legacy quirks in the API.
	// Basically, EDS merges by port name, but CDS historically ignored port name and matched on number.
	// Note that for Kubernetes Service, this is identical - its only ServiceEntry where these checks can differ
	LegacyClusterPortKey int

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

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

	// Indicates the endpoint health status.
	HealthStatus HealthStatus

	// If in k8s, the node where the pod resides
	NodeName string
}

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 catalog.mystore.com is accessible through port 80 and 8080, and it maps to an instance with IP 172.16.0.1, such that connections to port 80 are forwarded to port 55446, and connections to port 8080 are forwarded to port 33333,

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

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

func (*IstioEndpoint) CmpOpts

func (ep *IstioEndpoint) CmpOpts() []cmp.Option

func (*IstioEndpoint) DeepCopy

func (ep *IstioEndpoint) DeepCopy() *IstioEndpoint

DeepCopy creates a clone of IstioEndpoint.

func (*IstioEndpoint) Equals

func (ep *IstioEndpoint) Equals(other *IstioEndpoint) bool

Equals checks whether the attributes are equal from the passed in service.

func (*IstioEndpoint) FirstAddressOrNil

func (ep *IstioEndpoint) FirstAddressOrNil() string

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 this endpoint is discoverable from the given Proxy.

func (*IstioEndpoint) Key

func (ep *IstioEndpoint) Key() string

Key returns a function suitable for usage to distinguish this IstioEndpoint from another

func (*IstioEndpoint) Metadata

func (ep *IstioEndpoint) Metadata() *EndpointMetadata

Metadata returns the endpoint metadata used for telemetry purposes.

func (*IstioEndpoint) MetadataClone

func (ep *IstioEndpoint) MetadataClone() *EndpointMetadata

MetadataClone returns the cloned endpoint metadata used for telemetry purposes. This should be used when the endpoint labels should be updated.

func (*IstioEndpoint) ShallowCopy

func (ep *IstioEndpoint) ShallowCopy() *IstioEndpoint

ShallowCopy creates a shallow clone of IstioEndpoint.

func (*IstioEndpoint) SupportsTunnel

func (ep *IstioEndpoint) SupportsTunnel(tunnelType string) bool

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

func (*IstioVersion) String

func (pversion *IstioVersion) String() string

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

func (*JwksResolver) BuildLocalJwks

func (r *JwksResolver) BuildLocalJwks(jwksURI, jwtIssuer, jwtPubKey string, timeout time.Duration) *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, timeout time.Duration) (string, error)

GetPublicKey returns the JWT public key if it is available in the cache or fetch with from jwksuri if there is a error while fetching then it adds the jwksURI in the cache to fetch the public key in the background process

type K8sAttributes

type K8sAttributes struct {
	// Type holds the value of the corev1.Type of the Kubernetes service
	// spec.Type
	Type string

	// spec.ExternalName
	ExternalName string

	// NodeLocal means the proxy will only forward traffic to node local endpoints
	// spec.InternalTrafficPolicy == Local
	NodeLocal bool

	// ObjectName is the object name of the underlying object. This may differ from the Service.Attributes.Name for legacy semantics.
	ObjectName string

	// spec.PublishNotReadyAddresses
	PublishNotReadyAddresses bool
}

type LabelSelector

type LabelSelector struct {
	Labels map[string]string
}

func NewSelector

func NewSelector(l map[string]string) LabelSelector

func (LabelSelector) GetLabelSelector

func (l LabelSelector) GetLabelSelector() map[string]string

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 LoggingConfig

type LoggingConfig struct {
	Disabled  bool
	AccessLog *accesslog.AccessLog
	Provider  *meshconfig.MeshConfig_ExtensionProvider
	Filter    *tpb.AccessLogging_Filter
}

type MCSServiceInfo

type MCSServiceInfo struct {
	Cluster         cluster.ID
	Name            string
	Namespace       string
	Exported        bool
	Imported        bool
	ClusterSetVIP   string
	Discoverability map[host.Name]string
}

MCSServiceInfo combines the name of a service with a particular Kubernetes cluster. This is used for debug information regarding the state of Kubernetes Multi-Cluster Services (MCS).

type MergedGateway

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

	// MergedServers map from physical port to virtual servers
	// using TCP protocols (like HTTP1.1, H2, mysql, redis etc)
	MergedServers map[ServerPort]*MergedServers

	// MergedQUICTransportServers map from physical port to servers listening
	// on QUIC (like HTTP3). Currently the support is experimental and
	// is limited to HTTP3 only
	MergedQUICTransportServers map[ServerPort]*MergedServers

	// HTTP3AdvertisingRoutes represents the set of HTTP routes which advertise HTTP/3.
	// This mapping is used to generate alt-svc header that is needed for HTTP/3 server discovery.
	HTTP3AdvertisingRoutes sets.String

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

	// AutoPassthroughSNIHosts
	AutoPassthroughSNIHosts sets.Set[string]

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

	// VerifiedCertificateReferences contains a set of all credentialNames referenced by gateways *in the same namespace as the proxy*.
	// These are considered "verified", since there is mutually agreement from the pod, Secret, and Gateway, as all
	// reside in the same namespace and trust boundary.
	// Note: Secrets that are not referenced by any Gateway, but are in the same namespace as the pod, are explicitly *not*
	// included. This ensures we don't give permission to unexpected secrets, such as the citadel root key/cert.
	VerifiedCertificateReferences sets.String
}

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

func (*MergedGateway) GetAutoPassthroughGatewaySNIHosts

func (g *MergedGateway) GetAutoPassthroughGatewaySNIHosts() sets.Set[string]

func (*MergedGateway) HasAutoPassthroughGateways

func (g *MergedGateway) HasAutoPassthroughGateways() bool

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

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

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

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 NamespacedHostname

type NamespacedHostname struct {
	Hostname  host.Name
	Namespace string
}

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
	// HBONEPort if non-zero indicates that the gateway supports HBONE
	HBONEPort uint32
	// ServiceAccount the gateway runs as
	ServiceAccount types.NamespacedName
}

NetworkGateway is the gateway of a network

func SortGateways

func SortGateways(gws []NetworkGateway) []NetworkGateway

SortGateways sorts the array so that it's stable.

type NetworkGatewaySet

type NetworkGatewaySet = sets.Set[NetworkGateway]

NetworkGatewaySet is a helper to manage a set of NetworkGateway instances.

type NetworkGateways

type NetworkGateways struct {
	// contains filtered or unexported fields
}

func (*NetworkGateways) AllGateways

func (gws *NetworkGateways) AllGateways() []NetworkGateway

func (*NetworkGateways) GatewaysForNetwork

func (gws *NetworkGateways) GatewaysForNetwork(nw network.ID) []NetworkGateway

func (*NetworkGateways) GatewaysForNetworkAndCluster

func (gws *NetworkGateways) GatewaysForNetworkAndCluster(nw network.ID, c cluster.ID) []NetworkGateway

func (*NetworkGateways) GetLBWeightScaleFactor

func (gws *NetworkGateways) GetLBWeightScaleFactor() uint32

GetLBWeightScaleFactor returns the least common multiple of the number of gateways per network.

func (*NetworkGateways) IsMultiNetworkEnabled

func (gws *NetworkGateways) IsMultiNetworkEnabled() bool

type NetworkGatewaysHandler

type NetworkGatewaysHandler struct {
	// contains filtered or unexported fields
}

NetworkGatewaysHandler can be embedded to easily implement NetworkGatewaysWatcher.

func (*NetworkGatewaysHandler) AppendNetworkGatewayHandler

func (ngh *NetworkGatewaysHandler) AppendNetworkGatewayHandler(h func())

func (*NetworkGatewaysHandler) NotifyGatewayHandlers

func (ngh *NetworkGatewaysHandler) NotifyGatewayHandlers()

type NetworkGatewaysWatcher

type NetworkGatewaysWatcher interface {
	NetworkGateways() []NetworkGateway
	AppendNetworkGatewayHandler(h func())
}

type NetworkManager

type NetworkManager struct {

	// exported for test
	NameCache *networkGatewayNameCache

	// embedded NetworkGateways only includes gateways with IPs
	// hostnames are resolved in control plane (or filtered out if feature is disabled)
	*NetworkGateways
	// includes all gateways with no DNS resolution or filtering, regardless of feature flags
	Unresolved *NetworkGateways
	// contains filtered or unexported fields
}

NetworkManager provides gateway details for accessing remote networks.

func NewNetworkManager

func NewNetworkManager(env *Environment, xdsUpdater XDSUpdater) (*NetworkManager, error)

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

type Node

type Node = pm.Node

type NodeMetaProxyConfig

type NodeMetaProxyConfig = pm.NodeMetaProxyConfig

type NodeMetadata

type NodeMetadata = pm.NodeMetadata

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.

type NodeType

type NodeType = pm.NodeType

type NoopAmbientIndexes

type NoopAmbientIndexes struct{}

NoopAmbientIndexes provides an implementation of AmbientIndexes that always returns nil, to easily "skip" it.

func (NoopAmbientIndexes) AdditionalPodSubscriptions

func (u NoopAmbientIndexes) AdditionalPodSubscriptions(
	*Proxy,
	sets.String,
	sets.String,
) sets.String

func (NoopAmbientIndexes) AddressInformation

func (u NoopAmbientIndexes) AddressInformation(sets.String) ([]AddressInfo, sets.String)

func (NoopAmbientIndexes) Policies

func (NoopAmbientIndexes) ServicesForWaypoint

func (u NoopAmbientIndexes) ServicesForWaypoint(WaypointKey) []ServiceInfo

func (NoopAmbientIndexes) ServicesWithWaypoint

func (u NoopAmbientIndexes) ServicesWithWaypoint(string) []ServiceWaypointInfo

func (NoopAmbientIndexes) Waypoint

func (u NoopAmbientIndexes) Waypoint(string, string) []netip.Addr

func (NoopAmbientIndexes) WorkloadsForWaypoint

func (u NoopAmbientIndexes) WorkloadsForWaypoint(WaypointKey) []WorkloadInfo

type PodPort

type PodPort = pm.PodPort

type PolicyBindingStatus

type PolicyBindingStatus struct {
	ObservedGeneration int64
	Ancestor           string
	Status             *StatusMessage
	Bound              bool
}

func (PolicyBindingStatus) Equals

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.

func (*Port) Equals

func (p *Port) Equals(other *Port) bool

func (Port) String

func (p Port) String() string

type PortList

type PortList []*Port

PortList is a set of ports

func (PortList) Equals

func (ports PortList) Equals(other PortList) bool

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

func (PortList) String

func (ports PortList) String() string

type PrevMergedGateway

type PrevMergedGateway struct {
	ContainsAutoPassthroughGateways bool
	AutoPassthroughSNIHosts         sets.Set[string]
}

PrevMergedGateway describes previous state of the gateway. Currently, it only contains information relevant for auto passthrough gateways used by CDS.

func (*PrevMergedGateway) GetAutoPassthroughSNIHosts

func (g *PrevMergedGateway) GetAutoPassthroughSNIHosts() sets.Set[string]

func (*PrevMergedGateway) HasAutoPassthroughGateway

func (g *PrevMergedGateway) HasAutoPassthroughGateway() bool

type Proxy

type Proxy struct {
	sync.RWMutex

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

	// IPAddresses is the IP addresses of the proxy used to identify it and its
	// co-located service instances. Example: "10.60.1.6". In some cases, the host
	// where the 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.
	// NOTE: DO NOT USE THIS FIELD TO CONSTRUCT DNS NAMES
	ConfigNamespace string

	// Labels specifies the set of workload instance (ex: k8s pod) labels associated with this node.
	// Labels can be different from that in Metadata because of pod labels update after startup,
	// while NodeMetadata.Labels are set during bootstrap.
	Labels map[string]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

	// PrevMergedGateway contains information about merged gateway associated with the proxy previously
	PrevMergedGateway *PrevMergedGateway

	// ServiceTargets contains a list of all Services associated with the proxy, contextualized for this particular proxy.
	// These are unique to this proxy, as the port information is specific to it - while a ServicePort is shared with the
	// service, the target port may be distinct per-endpoint. So this maintains a view specific to this proxy.
	// ServiceTargets will maintain a list entry for each Service-port, so if we have 2 services each with 3 ports, we
	// would have 6 entries.
	ServiceTargets []ServiceTarget

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

	// LastPushContext stores the most recent push context for this proxy. This will be monotonically
	// increasing in version. Requests should send config based on this context; not the global latest.
	// Historically, the latest was used which can cause problems when computing whether a push is
	// required, as the computed sidecar scope version would not monotonically increase.
	LastPushContext *PushContext
	// LastPushTime records the time of the last push. This is used in conjunction with
	// LastPushContext; the XDS cache depends on knowing the time of the PushContext to determine if a
	// key is stale or not.
	LastPushTime time.Time
	// 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) AddOrUpdateWatchedResource

func (node *Proxy) AddOrUpdateWatchedResource(r *WatchedResource)

func (*Proxy) CanBindToPort

func (node *Proxy) CanBindToPort(bindTo bool, proxy *Proxy, push *PushContext,
	bind string, port int, protocol protocol.Instance, wildcard string,
) (canbind bool, knownlistener bool)

CanBindToPort returns true if the proxy can bind to a given port. canbind indicates whether the proxy can bind to the port. knownlistener indicates whether the check failed if the proxy is trying to bind to a port that is reserved for a static listener or virtual listener.

func (*Proxy) Clusters

func (node *Proxy) Clusters() []string

func (*Proxy) DeepCloneWatchedResources

func (node *Proxy) DeepCloneWatchedResources() map[string]WatchedResource

DeepCloneWatchedResources clones the watched resources

func (*Proxy) DeleteWatchedResource

func (node *Proxy) DeleteWatchedResource(typeURL string)

func (*Proxy) DiscoverIPMode

func (node *Proxy) DiscoverIPMode()

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

func (*Proxy) EnableHBONEListen

func (node *Proxy) EnableHBONEListen() bool

func (*Proxy) FuzzValidate

func (node *Proxy) FuzzValidate() bool

func (*Proxy) GetClusterID

func (node *Proxy) GetClusterID() cluster.ID

func (*Proxy) GetID

func (node *Proxy) GetID() string

func (*Proxy) GetIPMode

func (node *Proxy) GetIPMode() IPMode

GetIPMode returns proxy's ipMode

func (*Proxy) GetInterceptionMode

func (node *Proxy) GetInterceptionMode() TrafficInterceptionMode

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

func (*Proxy) GetIstioVersion

func (node *Proxy) GetIstioVersion() string

func (*Proxy) GetNamespace

func (node *Proxy) GetNamespace() string

func (*Proxy) GetNodeName

func (node *Proxy) GetNodeName() string

func (*Proxy) GetView

func (node *Proxy) GetView() ProxyView

GetView returns a restricted view of the mesh for this proxy. The view can be restricted by network (via ISTIO_META_REQUESTED_NETWORK_VIEW). If not set, we assume that the proxy wants to see endpoints in any network.

func (*Proxy) GetWatchedResource

func (node *Proxy) GetWatchedResource(typeURL string) *WatchedResource

func (*Proxy) GetWatchedResourceTypes

func (node *Proxy) GetWatchedResourceTypes() sets.String

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

func (node *Proxy) IsAmbient() bool

IsAmbient returns true if the proxy is acting as either a ztunnel or a waypoint proxy in an ambient mesh.

func (*Proxy) IsDualStack

func (node *Proxy) IsDualStack() bool

func (*Proxy) IsIPv6

func (node *Proxy) IsIPv6() bool

IsIPv6 returns true if proxy only supports IPv6 addresses.

func (*Proxy) IsProxylessGrpc

func (node *Proxy) IsProxylessGrpc() bool

func (*Proxy) IsUnprivileged

func (node *Proxy) IsUnprivileged() bool

IsUnprivileged returns true if the proxy has explicitly indicated that it is unprivileged, i.e. it cannot bind to the privileged ports 1-1023.

func (*Proxy) IsVM

func (node *Proxy) IsVM() bool

func (*Proxy) IsWaypointProxy

func (node *Proxy) IsWaypointProxy() bool

IsWaypointProxy returns true if the proxy is acting as a waypoint proxy in an ambient mesh.

func (*Proxy) IsZTunnel

func (node *Proxy) IsZTunnel() bool

IsZTunnel returns true if the proxy is acting as a ztunnel in an ambient mesh.

func (*Proxy) NewWatchedResource

func (node *Proxy) NewWatchedResource(typeURL string, names []string)

func (*Proxy) NonceAcked

func (node *Proxy) NonceAcked(typeURL string) string

func (*Proxy) NonceSent

func (node *Proxy) NonceSent(typeURL string) 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 ServiceTargets are set

func (*Proxy) SetIPMode

func (node *Proxy) SetIPMode(mode IPMode)

SetIPMode set node's ip mode Note: Donot use this function directly in most cases, use DiscoverIPMode instead.

func (*Proxy) SetServiceTargets

func (node *Proxy) SetServiceTargets(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) SetWorkloadEntry

func (node *Proxy) SetWorkloadEntry(name string, create bool)

func (*Proxy) SetWorkloadLabels

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

SetWorkloadLabels will set the node.Labels. It merges both node meta labels and workload labels and give preference to workload labels.

func (*Proxy) ShallowCloneWatchedResources

func (node *Proxy) ShallowCloneWatchedResources() map[string]*WatchedResource

ShallowCloneWatchedResources clones the watched resources, both the keys and values are shallow copy.

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.

func (*Proxy) UpdateWatchedResource

func (node *Proxy) UpdateWatchedResource(typeURL string, updateFn func(*WatchedResource) *WatchedResource)

func (*Proxy) VersionGreaterOrEqual

func (node *Proxy) VersionGreaterOrEqual(inv *IstioVersion) bool

func (*Proxy) WorkloadEntry

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

type ProxyConfigs

type ProxyConfigs struct {
	// contains filtered or unexported fields
}

ProxyConfigs organizes ProxyConfig configuration by namespace.

func GetProxyConfigs

func GetProxyConfigs(store ConfigStore, mc *meshconfig.MeshConfig) *ProxyConfigs

func (*ProxyConfigs) EffectiveProxyConfig

func (p *ProxyConfigs) EffectiveProxyConfig(meta *NodeMetadata, mc *meshconfig.MeshConfig) *meshconfig.ProxyConfig

EffectiveProxyConfig generates the correct merged ProxyConfig for a given ProxyConfigTarget.

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 ProxyView

type ProxyView interface {
	fmt.Stringer
	IsVisible(ep *IstioEndpoint) bool
}

ProxyView provides a restricted view of mesh endpoints for a Proxy.

var ProxyViewAll ProxyView = proxyViewAll{}

ProxyViewAll is a ProxyView where all endpoints are visible.

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

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

	// ProxyConfig stores the existing ProxyConfig resources for the cluster.
	ProxyConfigs *ProxyConfigs `json:"-"`

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

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

	// JwtKeyResolver holds a reference to the JWT key resolver instance.
	JwtKeyResolver *JwksResolver

	// GatewayAPIController holds a reference to the gateway API controller.
	GatewayAPIController GatewayController

	Networks *meshconfig.MeshNetworks

	InitDone atomic.Bool
	// 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][]*IstioEndpoint)

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

func (ps *PushContext) DelegateVirtualServices(vses []config.Config) []ConfigHash

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

func (*PushContext) EnvoyFilters

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

EnvoyFilters return the merged EnvoyFilterWrapper of a proxy

func (*PushContext) ExtraWaypointServices

func (ps *PushContext) ExtraWaypointServices(proxy *Proxy) sets.String

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

func (ps *PushContext) GetAllServices() []*Service

GetAllServices returns the total services within the mesh. Note: per proxy services should use SidecarScope.Services.

func (*PushContext) GetMetric

func (ps *PushContext) GetMetric(metric string) map[string]ProxyPushStatus

func (*PushContext) HasEnvoyFilters

func (ps *PushContext) HasEnvoyFilters(name, namespace string) bool

HasEnvoyFilters checks if an EnvoyFilter exists with the given name at the given namespace.

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

func (ps *PushContext) ReferenceAllowed(kind config.GroupVersionKind, resourceName string, namespace string) bool

ReferenceAllowed determines if a given resource (of type `kind` and name `resourceName`) can be accessed by `namespace`, based of specific reference policies. Note: this function only determines if a reference is *explicitly* allowed; the reference may not require explicit authorization to be made at all in most cases. Today, this only is for allowing cross-namespace secret access.

func (*PushContext) ServiceAccounts

func (ps *PushContext) ServiceAccounts(hostname host.Name, namespace string) []string

func (*PushContext) ServiceAttachedToGateway

func (ps *PushContext) ServiceAttachedToGateway(hostname string, proxy *Proxy) bool

func (*PushContext) ServiceEndpoints

func (ps *PushContext) ServiceEndpoints(svcKey string) map[int][]*IstioEndpoint

ServiceEndpoints returns the cached instances by svc if exists.

func (*PushContext) ServiceEndpointsByPort

func (ps *PushContext) ServiceEndpointsByPort(svc *Service, port int, labels labels.Instance) []*IstioEndpoint

ServiceEndpointsByPort returns the cached instances by port if it exists.

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

func (ps *PushContext) ServicesAttachedToMesh() map[string]sets.String

func (*PushContext) ServicesForWaypoint

func (ps *PushContext) ServicesForWaypoint(key WaypointKey) []ServiceInfo

ServicesForWaypoint returns all services associated with a given waypoint identified by it's WaypointKey Used when calculating the services which should be configured for a specific waypoint proxy

func (*PushContext) ServicesWithWaypoint

func (ps *PushContext) ServicesWithWaypoint(key string) []ServiceWaypointInfo

ServicesWithWaypoint returns all services associated with any waypoint. Key can optionally be provided in the form 'namespace/hostname'. If unset, all are returned

func (*PushContext) SetDestinationRulesForTesting

func (ps *PushContext) SetDestinationRulesForTesting(configs []config.Config)

Testing Only. This allows tests to inject a config without having the mock.

func (*PushContext) StatusJSON

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

StatusJSON implements json.Marshaller, with a lock.

func (*PushContext) SupportsTunnel

func (ps *PushContext) SupportsTunnel(n network.ID, ip string) bool

SupportsTunnel checks if a given IP address supports tunneling. This currently only accepts workload IPs as arguments; services will always return "false".

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(proxyNamespace, 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().

Note that for generating the imported virtual services of sidecar egress listener, we don't call this function to copy configs for performance issues. Instead, we pass the virtualServiceIndex directly into SelectVirtualServices function.

func (*PushContext) WasmPlugins

func (ps *PushContext) WasmPlugins(proxy *Proxy) map[extensions.PluginPhase][]*WasmPluginWrapper

WasmPlugins return the WasmPluginWrappers of a proxy. For most proxy types, we include only the root namespace and same-namespace objects. However, waypoints allow cross-namespace access based on attached Service objects. In this case, include all referenced services in the selection criteria

func (*PushContext) WasmPluginsByListenerInfo

func (ps *PushContext) WasmPluginsByListenerInfo(proxy *Proxy, info WasmPluginListenerInfo,
	pluginType WasmPluginType,
) map[extensions.PluginPhase][]*WasmPluginWrapper

WasmPluginsByListenerInfo return the WasmPluginWrappers which are matched with TrafficSelector in the given proxy.

func (*PushContext) WasmPluginsByName

func (ps *PushContext) WasmPluginsByName(proxy *Proxy, names []types.NamespacedName) []*WasmPluginWrapper

func (*PushContext) WorkloadsForWaypoint

func (ps *PushContext) WorkloadsForWaypoint(key WaypointKey) []WorkloadInfo

WorkloadsForWaypoint returns all workloads associated with a given waypoint identified by it's WaypointKey Used when calculating the workloads which should be configured for a specific waypoint proxy

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 sets.Set[ConfigKey]

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

	// Delta defines the resources that were added or removed as part of this push request.
	// This is set only on requests from the client which change the set of resources they (un)subscribe from.
	Delta ResourceDelta
}

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

func (pr *PushRequest) CopyMerge(other *PushRequest) *PushRequest

CopyMerge two update requests together. Unlike Merge, this will not mutate either input. This should be used when we are modifying a shared PushRequest (typically any time it's in the context of a single proxy)

func (*PushRequest) IsProxyUpdate

func (pr *PushRequest) IsProxyUpdate() bool

func (*PushRequest) IsRequest

func (pr *PushRequest) IsRequest() bool

func (*PushRequest) Merge

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

Merge two update requests together Merge behaves similarly to a list append; usage should in the form `a = a.merge(b)`. Importantly, Merge may decide to allocate a new PushRequest object or reuse the existing one - both inputs should not be used after completion.

func (*PushRequest) PushReason

func (pr *PushRequest) PushReason() string

type PushType

type PushType int

PushType is an enumeration that decides what type push we should do when we get EDS update.

const (
	// NoPush does not push any thing.
	NoPush PushType = iota
	// IncrementalPush just pushes endpoints.
	IncrementalPush
	// FullPush triggers full push - typically used for new services.
	FullPush
)

type ReasonStats

type ReasonStats map[TriggerReason]int

func NewReasonStats

func NewReasonStats(reasons ...TriggerReason) ReasonStats

func (ReasonStats) Add

func (r ReasonStats) Add(reason TriggerReason)

func (ReasonStats) CopyMerge

func (r ReasonStats) CopyMerge(other ReasonStats) ReasonStats

func (ReasonStats) Count

func (r ReasonStats) Count() int

func (ReasonStats) Has

func (r ReasonStats) Has(reason TriggerReason) bool

func (ReasonStats) Merge

func (r ReasonStats) Merge(other ReasonStats)

type Resolution

type Resolution int

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

const (
	// ClientSideLB implies that the proxy will decide the endpoint from its local lb pool
	ClientSideLB Resolution = iota
	// DNSLB implies that the proxy will resolve a DNS address and forward to the resolved address
	DNSLB
	// Passthrough implies that the proxy should forward traffic to the destination IP requested by the caller
	Passthrough
	// DNSRoundRobinLB implies that the proxy will resolve a DNS address and forward to the resolved address
	DNSRoundRobinLB
	// Alias defines a Service that is an alias for another.
	Alias
)

func (Resolution) String

func (resolution Resolution) String() string

String converts Resolution in to String.

type ResourceDelta

type ResourceDelta = xds.ResourceDelta

type Resources

type Resources = []*discovery.Resource

Resources is an alias for array of marshaled resources.

func AnyToUnnamedResources

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

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. "catalog.mystore.com"
	Hostname host.Name `json:"hostname"`

	// ClusterVIPs specifies the service address of the load balancer
	// in each of the clusters where the service resides
	ClusterVIPs AddressMap `json:"clusterVIPs,omitempty"`

	// DefaultAddress specifies the default service IP of the load balancer.
	// Do not access directly. Use GetAddressForProxy
	DefaultAddress string `json:"defaultAddress,omitempty"`

	// AutoAllocatedIPv4Address and AutoAllocatedIPv6Address specifies
	// the automatically allocated IPv4/IPv6 address out of the reserved
	// Class E subnet (240.240.0.0/16) or reserved Benchmarking IP range
	// (2001:2::/48) in RFC5180.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.
	AutoAllocatedIPv4Address string `json:"autoAllocatedIPv4Address,omitempty"`
	AutoAllocatedIPv6Address string `json:"autoAllocatedIPv6Address,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

	// ResourceVersion represents the internal version of this object.
	ResourceVersion string
}

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

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

func SortServicesByCreationTime

func SortServicesByCreationTime(services []*Service) []*Service

SortServicesByCreationTime sorts the list of services in ascending order by their creation time (if available).

func (*Service) CmpOpts

func (s *Service) CmpOpts() []cmp.Option

func (*Service) DeepCopy

func (s *Service) DeepCopy() *Service

DeepCopy creates a clone of Service.

func (*Service) Equals

func (s *Service) Equals(other *Service) bool

Equals compares two service objects.

func (*Service) External

func (s *Service) External() bool

External predicate checks whether the service is external

func (*Service) GetAddressForProxy

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

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

func (*Service) GetAllAddressesForProxy

func (s *Service) GetAllAddressesForProxy(node *Proxy) []string

GetAllAddressesForProxy returns a k8s service's all addresses to the cluster where the node resides. Especially for dual stack k8s service to get other IP family addresses.

func (*Service) GetExtraAddressesForProxy

func (s *Service) GetExtraAddressesForProxy(node *Proxy) []string

GetExtraAddressesForProxy returns a k8s service's extra addresses to the cluster where the node resides. Especially for dual stack k8s service to get other IP family addresses.

func (*Service) Key

func (s *Service) Key() string

func (*Service) NamespacedName

func (s *Service) NamespacedName() types.NamespacedName

func (*Service) SupportsDrainingEndpoints

func (s *Service) SupportsDrainingEndpoints() bool

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 "destination.service.name" 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 sets.Set[visibility.Instance]

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

	// Aliases is the resolved set of aliases for this service. This is computed based on a global view of all Service's `AliasFor`
	// fields.
	// For example, if I had two Services with `externalName: foo`, "a" and "b", then the "foo" service would have Aliases=[a,b].
	Aliases []NamespacedHostname

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

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

	PassthroughTargetPorts map[uint32]uint32

	K8sAttributes
}

ServiceAttributes represents a group of custom attributes of the service.

func (*ServiceAttributes) DeepCopy

func (s *ServiceAttributes) DeepCopy() ServiceAttributes

DeepCopy creates a deep copy of ServiceAttributes, but skips internal mutexes.

func (*ServiceAttributes) Equals

func (s *ServiceAttributes) Equals(other *ServiceAttributes) bool

Equals checks whether the attributes are equal from the passed in service.

type ServiceDiscovery

type ServiceDiscovery interface {
	NetworkGatewaysWatcher

	// Services list declarations of all services in the system
	Services() []*Service

	// GetService retrieves a service by host name if it exists
	GetService(hostname host.Name) *Service

	// GetProxyServiceTargets returns the service targets 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 ServiceTargets instead of one:
	// - A ServiceTargets has a single Port.  But a Service
	//   may have many ports.  So a workload implementing such a Service would need
	//   multiple ServiceTargets, 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.
	GetProxyServiceTargets(*Proxy) []ServiceTarget
	GetProxyWorkloadLabels(*Proxy) labels.Instance

	// MCSServices returns information about the services that have been exported/imported via the
	// Kubernetes Multi-Cluster Services (MCS) ServiceExport API. Only applies to services in
	// Kubernetes clusters.
	MCSServices() []MCSServiceInfo
	AmbientIndexes
}

ServiceDiscovery enumerates Istio service instances. nolint: lll

type ServiceHandler

type ServiceHandler func(*Service, *Service, Event)

type ServiceInfo

type ServiceInfo struct {
	*workloadapi.Service
	// LabelSelectors for the Service. Note these are only used internally, not sent over XDS
	LabelSelector
	// PortNames provides a mapping of ServicePort -> port names. Note these are only used internally, not sent over XDS
	PortNames map[int32]ServicePortName
	// Source is the type that introduced this service.
	Source   TypedObject
	Waypoint WaypointBindingStatus
}

func (ServiceInfo) Equals

func (i ServiceInfo) Equals(other ServiceInfo) bool

func (ServiceInfo) GetConditions

func (i ServiceInfo) GetConditions() ConditionSet

func (ServiceInfo) GetStatusTarget

func (i ServiceInfo) GetStatusTarget() TypedObject

func (ServiceInfo) NamespacedName

func (i ServiceInfo) NamespacedName() types.NamespacedName

func (ServiceInfo) ResourceName

func (i ServiceInfo) ResourceName() string

type ServiceInfoForPolicyMatcher

type ServiceInfoForPolicyMatcher struct {
	Name      string
	Namespace string
	Registry  provider.ID
}

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 catalog.mystore.com are modeled like this

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

func (*ServiceInstance) CmpOpts

func (instance *ServiceInstance) CmpOpts() []cmp.Option

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 ServiceInstancePort

type ServiceInstancePort struct {
	ServicePort
	TargetPort uint32
}

ServiceInstancePort defines a port that has both a port and targetPort (which distinguishes it from model.Port) Note: ServiceInstancePort only makes sense in the context of a specific ServiceInstance, because TargetPort depends on a specific instance.

type ServicePort

type ServicePort = *Port

type ServicePortName

type ServicePortName struct {
	PortName       string
	TargetPortName string
}

type ServiceTarget

type ServiceTarget struct {
	Service *Service
	Port    ServiceInstancePort
}

ServiceTarget includes a Service object, along with a specific service port and target port. This is basically a smaller version of ServiceInstance, intended to avoid the need to have the full object when only port information is needed.

func ServiceInstanceToTarget

func ServiceInstanceToTarget(e *ServiceInstance) ServiceTarget

type ServiceWaypointInfo

type ServiceWaypointInfo struct {
	Service          *workloadapi.Service
	WaypointHostname string
}

type ShardKey

type ShardKey struct {
	Cluster  cluster.ID
	Provider provider.ID
}

ShardKey is the key for EndpointShards made of a key with the format "provider/cluster"

func ShardKeyFromRegistry

func ShardKeyFromRegistry(instance shardRegistry) ShardKey

ShardKeyFromRegistry computes the shard key based on provider type and cluster id.

func (ShardKey) MarshalText

func (sk ShardKey) MarshalText() (text []byte, err error)

MarshalText implements the TextMarshaler interface (for json key usage)

func (ShardKey) String

func (sk ShardKey) String() string

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

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

DefaultSidecarScopeForGateway builds a SidecarScope contains services and destinationRules for a given gateway/waypoint.

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

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, rootNs string) bool

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

func (*SidecarScope) DestinationRule

func (sc *SidecarScope) DestinationRule(direction TrafficDirection, proxy *Proxy, svc host.Name) *ConsolidatedDestRule

DestinationRule returns a destinationrule for a svc.

func (*SidecarScope) DestinationRuleByName

func (sc *SidecarScope) DestinationRuleByName(name, namespace string) *config.Config

func (*SidecarScope) DestinationRuleConfig

func (sc *SidecarScope) DestinationRuleConfig(direction TrafficDirection, proxy *Proxy, svc host.Name) *config.Config

DestinationRuleConfig returns merged destination rules for a svc.

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

func (sc *SidecarScope) GetService(hostname host.Name) *Service

func (*SidecarScope) HasIngressListener

func (sc *SidecarScope) HasIngressListener() bool

HasIngressListener returns if the sidecar scope has ingress listener set

func (*SidecarScope) InboundConnectionPoolForPort

func (sc *SidecarScope) InboundConnectionPoolForPort(port int) *networking.ConnectionPoolSettings

InboundConnectionPoolForPort returns the connection pool settings for a specific inbound port. If there's not a setting for that specific port, then the settings at the Sidecar resource are returned. If neither exist, then nil is returned so the caller can decide what values to fall back on.

func (*SidecarScope) MarshalJSON

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

MarshalJSON implements json.Marshaller

func (*SidecarScope) Services

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

Services returns the list of services that are visible to a sidecar.

func (*SidecarScope) ServicesForHostname

func (sc *SidecarScope) ServicesForHostname(hostname host.Name) []*Service

ServicesForHostname returns a list of services that fall under the hostname provided. This hostname can be a wildcard.

func (*SidecarScope) SetDestinationRulesForTesting

func (sc *SidecarScope) SetDestinationRulesForTesting(configs []config.Config)

Testing Only. This allows tests to inject a config without having the mock.

type StatusMessage

type StatusMessage struct {
	Reason  string
	Message string
}

type StringBool

type StringBool = pm.StringBool

type TLSServerInfo

type TLSServerInfo struct {
	RouteName string
	SNIHosts  []string
}

TLSServerInfo contains additional information for TLS Servers.

type TargetablePolicy

type TargetablePolicy interface {
	GetTargetRef() *v1beta1.PolicyTargetReference
	GetTargetRefs() []*v1beta1.PolicyTargetReference
	GetSelector() *v1beta1.WorkloadSelector
}

this can be any type from istio/api that uses these types of selectors

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"`
	// contains filtered or unexported fields
}

Telemetries organizes Telemetry configuration by namespace.

func (*Telemetries) AccessLogging

func (t *Telemetries) AccessLogging(push *PushContext, proxy *Proxy, class networking.ListenerClass, svc *Service) []LoggingConfig

AccessLogging returns the logging configuration for a given proxy and listener class. If nil or empty configuration is returned, access logs are not configured via Telemetry and should use fallback mechanisms. If access logging is explicitly disabled, a configuration with disabled set to true is returned.

func (*Telemetries) Debug

func (t *Telemetries) Debug(proxy *Proxy) any

func (*Telemetries) HTTPFilters

func (t *Telemetries) HTTPFilters(proxy *Proxy, class networking.ListenerClass, svc *Service) []*hcm.HttpFilter

HTTPFilters computes the HttpFilter for a given proxy/class

func (*Telemetries) TCPFilters

func (t *Telemetries) TCPFilters(proxy *Proxy, class networking.ListenerClass, svc *Service) []*listener.Filter

TCPFilters computes the TCPFilters for a given proxy/class

func (*Telemetries) Tracing

func (t *Telemetries) Tracing(proxy *Proxy, svc *Service) *TracingConfig

Tracing returns the logging tracing for a given proxy. If nil is returned, tracing are not configured via Telemetry and should use fallback mechanisms. If a non-nil but disabled is set, then tracing is explicitly disabled. A service can optionally be provided to include service-attached Telemetry config.

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.

func (*Telemetry) NamespacedName

func (t *Telemetry) NamespacedName() types.NamespacedName

type TracingConfig

type TracingConfig struct {
	ServerSpec TracingSpec
	ClientSpec TracingSpec
}

type TracingSpec

type TracingSpec struct {
	Provider                     *meshconfig.MeshConfig_ExtensionProvider
	Disabled                     bool
	RandomSamplingPercentage     *float64
	CustomTags                   map[string]*tpb.Tracing_CustomTag
	UseRequestIDForTraceSampling bool
	EnableIstioTags              bool
}

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"
	// TrafficDirectionInboundVIP indicates inbound traffic for vip
	TrafficDirectionInboundVIP TrafficDirection = "inbound-vip"
	// 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 = pm.TrafficInterceptionMode
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 (
	// EndpointUpdate describes a push triggered by an Endpoint change
	EndpointUpdate TriggerReason = "endpoint"
	// HeadlessEndpointUpdate describes a push triggered by an Endpoint change for headless service
	HeadlessEndpointUpdate TriggerReason = "headlessendpoint"
	// ConfigUpdate describes a push triggered by a config (generally and Istio CRD) change.
	ConfigUpdate TriggerReason = "config"
	// ServiceUpdate describes a push triggered by a Service change
	ServiceUpdate TriggerReason = "service"
	// ProxyUpdate describes a push triggered by a change to an individual proxy (such as label change)
	ProxyUpdate TriggerReason = "proxy"
	// GlobalUpdate describes a push triggered by a change to global config, such as mesh config
	GlobalUpdate TriggerReason = "global"
	// AmbientUpdate describes a push triggered by a change to ambient mesh config
	AmbientUpdate TriggerReason = "ambient"
	// UnknownTrigger describes a push triggered by an unknown reason
	UnknownTrigger TriggerReason = "unknown"
	// DebugTrigger describes a push triggered for debugging
	DebugTrigger TriggerReason = "debug"
	// SecretTrigger describes a push triggered for a Secret change
	SecretTrigger TriggerReason = "secret"
	// NetworksTrigger describes a push triggered for Networks change
	NetworksTrigger TriggerReason = "networks"
	// ProxyRequest describes a push triggered based on proxy request
	ProxyRequest TriggerReason = "proxyrequest"
	// DependentResource describes a push triggered based on a proxy request for a
	// resource that depends on this resource (e.g. a CDS request triggers an EDS response as well)
	// This is mainly used in Delta for now.
	DependentResource TriggerReason = "depdendentresource"
	// NamespaceUpdate describes a push triggered by a Namespace change
	NamespaceUpdate TriggerReason = "namespace"
	// ClusterUpdate describes a push triggered by a Cluster change
	ClusterUpdate TriggerReason = "cluster"
)

If adding a new reason, update xds/monitoring.go:triggerMetric

type TypedObject

type TypedObject struct {
	types.NamespacedName
	Kind kind.Kind
}

type WasmPluginListenerInfo

type WasmPluginListenerInfo struct {
	Port  int
	Class istionetworking.ListenerClass

	// Service that WasmPlugins can attach to via targetRefs (optional)
	Services []*Service
}

func (WasmPluginListenerInfo) WithService

func (listenerInfo WasmPluginListenerInfo) WithService(service *Service) WasmPluginListenerInfo

type WasmPluginType

type WasmPluginType int

WasmPluginType defines the type of wasm plugin

const (
	WasmPluginTypeHTTP WasmPluginType = iota
	WasmPluginTypeNetwork
	WasmPluginTypeAny
)

type WasmPluginWrapper

type WasmPluginWrapper struct {
	*extensions.WasmPlugin

	Name            string
	Namespace       string
	ResourceName    string
	ResourceVersion string
}

func (*WasmPluginWrapper) BuildHTTPWasmFilter

func (p *WasmPluginWrapper) BuildHTTPWasmFilter() *httpwasm.Wasm

func (*WasmPluginWrapper) BuildNetworkWasmFilter

func (p *WasmPluginWrapper) BuildNetworkWasmFilter() *networkwasm.Wasm

func (*WasmPluginWrapper) MatchListener

func (*WasmPluginWrapper) MatchType

func (p *WasmPluginWrapper) MatchType(pluginType WasmPluginType) bool

func (*WasmPluginWrapper) NamespacedName

func (p *WasmPluginWrapper) NamespacedName() types.NamespacedName

type WatchedResource

type WatchedResource = xds.WatchedResource

type WaypointBindingStatus

type WaypointBindingStatus struct {
	// ResourceName that clients should use when addressing traffic to this Service.
	ResourceName string
	// IngressUseWaypoint specifies whether ingress gateways should use the waypoint for this service.
	IngressUseWaypoint bool
	// IngressLabelPresent specifies whether the istio.io/ingress-use-waypoint label is set on the service.
	IngressLabelPresent bool
	// Error represents some error
	Error *StatusMessage
}

func (WaypointBindingStatus) Equals

type WaypointKey

type WaypointKey struct {
	Namespace string
	Hostnames []string

	Network   string
	Addresses []string
}

WaypointKey is a multi-address extension of NetworkAddress which is commonly used for lookups in AmbientIndex We likely need to consider alternative keying options internally such as hostname as we look to expand beyond istio-waypoint This extension can ideally support that type of lookup in the interface without introducing scope creep into things like NetworkAddress

func WaypointKeyForProxy

func WaypointKeyForProxy(node *Proxy) WaypointKey

WaypointKeyForProxy builds a key from a proxy to lookup

type WaypointPolicyStatus

type WaypointPolicyStatus struct {
	Source     TypedObject
	Conditions []PolicyBindingStatus
}

func (WaypointPolicyStatus) GetConditions

func (i WaypointPolicyStatus) GetConditions() ConditionSet

func (WaypointPolicyStatus) GetStatusTarget

func (i WaypointPolicyStatus) GetStatusTarget() TypedObject

impl pilot/pkg/serviceregistry/kube/controller/ambient/statusqueue/StatusWriter

func (WaypointPolicyStatus) ResourceName

func (i WaypointPolicyStatus) ResourceName() string

impl pkg/kube/krt/ResourceNamer

type WorkloadAuthorization

type WorkloadAuthorization struct {
	// LabelSelectors for the workload. Note these are only used internally, not sent over XDS
	LabelSelector
	Authorization *security.Authorization

	Source  TypedObject
	Binding PolicyBindingStatus
}

func (WorkloadAuthorization) Equals

func (WorkloadAuthorization) GetConditions

func (i WorkloadAuthorization) GetConditions() ConditionSet

func (WorkloadAuthorization) GetStatusTarget

func (i WorkloadAuthorization) GetStatusTarget() TypedObject

impl pilot/pkg/serviceregistry/kube/controller/ambient/statusqueue/StatusWriter

func (WorkloadAuthorization) ResourceName

func (i WorkloadAuthorization) ResourceName() string

type WorkloadInfo

type WorkloadInfo struct {
	*workloadapi.Workload
	// Labels for the workload. Note these are only used internally, not sent over XDS
	Labels map[string]string
	// Source is the type that introduced this workload.
	Source kind.Kind
	// CreationTime is the time when the workload was created. Note this is used internally only.
	CreationTime time.Time
}

func ExtractWorkloadsFromAddresses

func ExtractWorkloadsFromAddresses(addrs []AddressInfo) []WorkloadInfo

func SortWorkloadsByCreationTime

func SortWorkloadsByCreationTime(workloads []WorkloadInfo) []WorkloadInfo

func (*WorkloadInfo) Clone

func (i *WorkloadInfo) Clone() *WorkloadInfo

func (WorkloadInfo) Equals

func (i WorkloadInfo) Equals(other WorkloadInfo) bool

func (WorkloadInfo) ResourceName

func (i WorkloadInfo) ResourceName() string

type WorkloadInstance

type WorkloadInstance struct {
	Name      string `json:"name,omitempty"`
	Namespace string `json:"namespace,omitempty"`
	// Where the workloadInstance come from, valid values are`Pod` or `WorkloadEntry`
	Kind     workloadKind      `json:"kind"`
	Endpoint *IstioEndpoint    `json:"endpoint,omitempty"`
	PortMap  map[string]uint32 `json:"portMap,omitempty"`
	// Can only be selected by service entry of DNS type.
	DNSServiceEntryOnly bool `json:"dnsServiceEntryOnly,omitempty"`
}

func (*WorkloadInstance) CmpOpts

func (instance *WorkloadInstance) CmpOpts() []cmp.Option

func (*WorkloadInstance) DeepCopy

func (instance *WorkloadInstance) DeepCopy() *WorkloadInstance

DeepCopy creates a copy of WorkloadInstance.

type WorkloadPolicyMatcher

type WorkloadPolicyMatcher struct {
	WorkloadNamespace string
	WorkloadLabels    labels.Instance
	IsWaypoint        bool
	Services          []ServiceInfoForPolicyMatcher
}

WorkloadPolicyMatcher performs policy selection either using targetRef or label selectors. Label selection uses the workload labels. TargetRef selection uses either the workload's namespace + the gateway name based on labels, or the Services the workload is a part of.

func PolicyMatcherFor

func PolicyMatcherFor(workloadNamespace string, labels labels.Instance, isWaypoint bool) WorkloadPolicyMatcher

func PolicyMatcherForProxy

func PolicyMatcherForProxy(proxy *Proxy) WorkloadPolicyMatcher

func (WorkloadPolicyMatcher) ShouldAttachPolicy

func (p WorkloadPolicyMatcher) ShouldAttachPolicy(kind config.GroupVersionKind, policyName types.NamespacedName, policy TargetablePolicy) bool

func (WorkloadPolicyMatcher) WithService

func (p WorkloadPolicyMatcher) WithService(service *Service) WorkloadPolicyMatcher

func (WorkloadPolicyMatcher) WithServices

func (p WorkloadPolicyMatcher) WithServices(services []*Service) WorkloadPolicyMatcher

WithServices marks multiple services as part of the selection criteria. This is used when we want to find **all** policies attached to a specific proxy instance, rather than scoped to a specific service. This is useful when using ECDS, for example, where we might have: * Each unique service creates a listener, and applies a policy selected by `WithService` pointing to ECDS * All policies are found, by `WithServices`, and returned in ECDS.

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 ShardKey, 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 ShardKey, hostname string, namespace string, entry []*IstioEndpoint)

	// SvcUpdate is called when a service definition is updated/deleted.
	SvcUpdate(shard ShardKey, 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)

	// RemoveShard removes all endpoints for the given shard key
	RemoveShard(shardKey ShardKey)
}

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 {
	// Run starts a background thread to flush evicted indexes periodically.
	Run(stop <-chan struct{})
	// 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.
	Get(entry XdsCacheEntry) *discovery.Resource
	// Clear removes the cache entries that are dependent on the configs passed.
	Clear(sets.Set[ConfigKey])
	// ClearAll clears the entire cache.
	ClearAll()
	// Keys returns all currently configured keys for the type. This is for testing/debug only
	Keys(t string) []any
	// Snapshot returns a snapshot of all values. This is for testing/debug only
	Snapshot() []*discovery.Resource
}

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

func NewXdsCache

func NewXdsCache() XdsCache

NewXdsCache returns an instance of a cache.

type XdsCacheEntry

type XdsCacheEntry interface {
	// Type indicates the type of Xds resource being cached like CDS.
	Type() string
	// Key is the key to be used in cache.
	Key() any
	// DependentConfigs is config items that this cache key is dependent on.
	// Whenever these configs change, we should invalidate this cache entry.
	DependentConfigs() []ConfigHash
	// 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 XdsCacheImpl

type XdsCacheImpl struct {
	// contains filtered or unexported fields
}

func (XdsCacheImpl) Add

func (x XdsCacheImpl) Add(entry XdsCacheEntry, pushRequest *PushRequest, value *discovery.Resource)

func (XdsCacheImpl) Clear

func (x XdsCacheImpl) Clear(s sets.Set[ConfigKey])

func (XdsCacheImpl) ClearAll

func (x XdsCacheImpl) ClearAll()

func (XdsCacheImpl) Get

func (XdsCacheImpl) Keys

func (x XdsCacheImpl) Keys(t string) []any

func (XdsCacheImpl) Run

func (x XdsCacheImpl) Run(stop <-chan struct{})

func (XdsCacheImpl) Snapshot

func (x XdsCacheImpl) Snapshot() []*discovery.Resource

type XdsDeltaResourceGenerator

type XdsDeltaResourceGenerator interface {
	XdsResourceGenerator
	// GenerateDeltas returns the changed and removed resources, along with whether or not delta was actually used.
	GenerateDeltas(proxy *Proxy, req *PushRequest, w *WatchedResource) (Resources, DeletedResources, XdsLogDetails, bool, error)
}

XdsDeltaResourceGenerator generates Sotw and delta resources.

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 generates the Sotw resources for Xds.
	Generate(proxy *Proxy, w *WatchedResource, req *PushRequest) (Resources, XdsLogDetails, error)
}

XdsResourceGenerator creates the response for a typeURL DiscoveryRequest or DeltaDiscoveryRequest. 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 = sets.Set[ConfigKey]

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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