istio: istio.io/istio/pilot/pkg/model Index | Files | Directories

package model

import "istio.io/istio/pilot/pkg/model"

Copyright 2019 Istio Authors

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

http://www.apache.org/licenses/LICENSE-2.0

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

Index

Package Files

authorization.go config.go context.go controller.go destination_rule.go disabled_ledger.go envoyfilter.go gateway.go jwks_resolver.go log.go push_context.go service.go sidecar.go validation.go

Constants

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

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

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

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

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

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

Pile all node metadata constants here

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

    // JwtPubKeyRefreshInterval is the running interval of JWT pubKey refresh job.
    JwtPubKeyRefreshInterval = time.Minute * 20
)
const (
    // IstioDefaultConfigNamespace constant for default namespace
    IstioDefaultConfigNamespace = "default"

    // LocalityLabel indicates the region/zone/subzone of an instance. It is used to override the native
    // registry's value.
    //
    // Note: because k8s labels does not support `/`, so we use `.` instead in k8s.
    LocalityLabel = "istio-locality"
)
const (
    // MTLSReadyLabelName name for the mtlsReady label given to service instances to toggle mTLS autopilot
    MTLSReadyLabelName = "security.istio.io/mtlsReady"
)
const (
    // NamespaceAll is a designated symbol for listing across all namespaces
    NamespaceAll = ""
)
const UnixAddressPrefix = "unix://"

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

const UnnamedNetwork = ""

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

Variables

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 GetProxyServiceInstances
    ProxyStatusNoService = monitoring.NewGauge(
        "pilot_no_ip",
        "Pods not found in the endpoint table, possibly invalid.",
    )

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

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

    // ProxyStatusConflictOutboundListenerHTTPoverHTTPS metric tracks number of
    // HTTP listeners that conflicted with well known HTTPS ports
    ProxyStatusConflictOutboundListenerHTTPoverHTTPS = monitoring.NewGauge(
        "pilot_conflict_outbound_listener_http_over_https",
        "Number of conflicting HTTP listeners with well known HTTPS ports",
    )

    // 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.",
    )

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

    // ProxyStatusConflictInboundListener tracks cases of multiple inbound
    // listeners - 2 services selecting the same port of the pod.
    ProxyStatusConflictInboundListener = 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",
    )

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

    // JwtKeyResolver resolves JWT public key and JwksURI.
    JwtKeyResolver = NewJwksResolver(JwtPubKeyEvictionDuration, JwtPubKeyRefreshInterval)
)
var (
    MaxIstioVersion = &IstioVersion{Major: 65535, Minor: 65535, Patch: 65535}
)

func BuildDNSSrvSubsetKey Uses

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 BuildSubsetKey Uses

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 GetLocalityOrDefault Uses

func GetLocalityOrDefault(label, defaultLocality string) string

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

func GetNetworkView Uses

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

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

func GetOrDefault Uses

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 Uses

func GetProxyConfigNamespace(proxy *Proxy) string

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

func IsApplicationNodeType Uses

func IsApplicationNodeType(nType NodeType) bool

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

func IsValidSubsetKey Uses

func IsValidSubsetKey(s string) bool

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

func Key Uses

func Key(typ, name, namespace string) string

Key function for the configuration objects

func MatchesDestHost Uses

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

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

func MostSpecificHostMatch Uses

func MostSpecificHostMatch(needle host.Name, stack []host.Name) (host.Name, bool)

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

func ParseGatewayRDSRouteName Uses

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

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

func ParsePort Uses

func ParsePort(addr string) int

ParsePort extracts port number from a valid proxy address

func ResolveHostname Uses

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

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

func ResolveShortnameToFQDN Uses

func ResolveShortnameToFQDN(hostname string, meta ConfigMeta) host.Name

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

func ServiceKey Uses

func ServiceKey(hostname host.Name, servicePorts PortList, labelsList labels.Collection) string

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

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

func SortQuotaSpec Uses

func SortQuotaSpec(specs []Config)

SortQuotaSpec sorts a slice in a stable manner.

func ValidateNetworkEndpointAddress Uses

func ValidateNetworkEndpointAddress(n *NetworkEndpoint) error

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

type AddressFamily Uses

type AddressFamily int

AddressFamily indicates the kind of transport used to reach a NetworkEndpoint

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

func (AddressFamily) String Uses

func (f AddressFamily) String() string

String converts addressfamily into string (tcp/unix)

type AuthorizationPolicies Uses

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

AuthorizationPolicies organizes authorization policies by namespace.

func GetAuthorizationPolicies Uses

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

GetAuthorizationPolicies gets the authorization policies in the mesh.

func (*AuthorizationPolicies) IsGlobalPermissiveEnabled Uses

func (policy *AuthorizationPolicies) IsGlobalPermissiveEnabled() bool

IsGlobalPermissiveEnabled returns true if global permissive mode is enabled.

func (*AuthorizationPolicies) IsRBACEnabled Uses

func (policy *AuthorizationPolicies) IsRBACEnabled(service string, namespace string) bool

IsRBACEnabled returns true if RBAC is enabled for the service in the given namespace.

func (*AuthorizationPolicies) ListAuthorizationPolicies Uses

func (policy *AuthorizationPolicies) ListAuthorizationPolicies(configNamespace string,
    workloadLabels labels.Collection) []Config

ListAuthorizationPolicies returns the AuthorizationPolicy for the workload in root namespace and the config namespace.

func (*AuthorizationPolicies) ListNamespacesOfToV1alpha1Policies Uses

func (policy *AuthorizationPolicies) ListNamespacesOfToV1alpha1Policies() []string

ListNamespacesOfToV1alpha1Policies returns all namespaces that have V1alpha1 policies.

func (*AuthorizationPolicies) ListServiceRoleBindings Uses

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

ListServiceRoleBindings returns the ServiceRoleBindings in the given namespace.

func (*AuthorizationPolicies) ListServiceRoles Uses

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

ListServiceRoles returns ServiceRole in the given namespace.

type Config Uses

type Config struct {
    ConfigMeta

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

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

func (Config) DeepCopy Uses

func (config Config) DeepCopy() Config

type ConfigMeta Uses

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

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

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

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

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

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

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

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

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

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

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

func (*ConfigMeta) Key Uses

func (meta *ConfigMeta) Key() string

Key is the unique identifier for a configuration object

type ConfigStore Uses

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

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

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

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

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

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

    Version() string

    GetResourceAtVersion(version string, key string) (resourceVersion string, err error)
}

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

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

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

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

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

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

type ConfigStoreCache Uses

type ConfigStoreCache interface {
    ConfigStore

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

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

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

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

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

Handlers execute on the single worker queue in the order they are appended. Handlers receive the notification event and the associated object. Note that all handlers must be registered before starting the cache controller. go:generate counterfeiter -o ../config/aggregate/fakes/config_store_cache.gen.go --fake-name ConfigStoreCache . ConfigStoreCache

type Controller Uses

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

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

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

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

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

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

type DisabledLedger Uses

type DisabledLedger struct {
    ledger.Ledger
}

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

func (*DisabledLedger) Delete Uses

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

func (*DisabledLedger) Get Uses

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

func (*DisabledLedger) GetPreviousValue Uses

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

func (*DisabledLedger) Put Uses

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

func (*DisabledLedger) RootHash Uses

func (d *DisabledLedger) RootHash() string

type Environment Uses

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

    // Config interface for listing routing rules
    IstioConfigStore

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

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

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

Environment provides an aggregate environmental API for Pilot

type EnvoyFilterConfigPatchWrapper Uses

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
}

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

type EnvoyFilterWrapper Uses

type EnvoyFilterWrapper struct {
    Patches map[networking.EnvoyFilter_ApplyTo][]*EnvoyFilterConfigPatchWrapper
    // contains filtered or unexported fields
}

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

type Event Uses

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 Uses

func (event Event) String() string

type IstioConfigStore Uses

type IstioConfigStore interface {
    ConfigStore

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

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

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

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

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

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

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

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

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

IstioConfigStore is a specialized interface to access config store using Istio configuration types nolint go:generate counterfeiter -o ../networking/core/v1alpha3/fakes/fake_istio_config_store.gen.go --fake-name IstioConfigStore . IstioConfigStore

func MakeIstioStore Uses

func MakeIstioStore(store ConfigStore) IstioConfigStore

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

type IstioEgressListenerWrapper Uses

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

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

func (*IstioEgressListenerWrapper) Services Uses

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

Services returns the list of services imported by this egress listener

func (*IstioEgressListenerWrapper) VirtualServices Uses

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

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

type IstioEndpoint Uses

type IstioEndpoint struct {

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

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

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

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

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

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

    // ServiceAccount holds the associated service account.
    ServiceAccount string

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

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

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

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

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

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

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

type IstioVersion Uses

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 Uses

func ParseIstioVersion(ver string) *IstioVersion

ParseIstioVersion parses a version string and returns IstioVersion struct

func (*IstioVersion) Compare Uses

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

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

type JwksResolver Uses

type JwksResolver struct {
    // cache for jwksURI.
    JwksURICache cache.ExpiringCache

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

func NewJwksResolver(evictionDuration, refreshInterval time.Duration) *JwksResolver

NewJwksResolver creates new instance of JwksResolver.

func (*JwksResolver) Close Uses

func (r *JwksResolver) Close()

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 Uses

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

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

func (*JwksResolver) SetAuthenticationPolicyJwksURIs Uses

func (r *JwksResolver) SetAuthenticationPolicyJwksURIs(policy *authn.Policy) error

Set jwks_uri through openID discovery if it's not set in auth policy.

type MergedGateway Uses

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

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

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

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

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

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

func MergeGateways Uses

func MergeGateways(gateways ...Config) *MergedGateway

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

type NetworkEndpoint Uses

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

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

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

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

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

    // The network where this endpoint is present
    Network string

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

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

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

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

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

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

type NodeMetadata Uses

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

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

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

    // ConfigNamespace is the name of the metadata variable that carries info about
    // the config namespace associated with the proxy
    ConfigNamespace string `json:"CONFIG_NAMESPACE,omitempty"`

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

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

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

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

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

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

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

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

    // ExchangeKeys specifies a list of metadata keys that should be used for Node Metadata Exchange.
    ExchangeKeys StringList `json:"EXCHANGE_KEYS,omitempty"`

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

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

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

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

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

    // CanonicalTelemetryService specifies the service name to use for all node telemetry.
    CanonicalTelemetryService string `json:"CANONICAL_TELEMETRY_SERVICE,omitempty"`

    // LocalityLabel defines the locality specified for the pod
    LocalityLabel string `json:"istio-locality,omitempty"`

    IncludeInboundPorts string `json:"INCLUDE_INBOUND_PORTS,omitempty"`

    PolicyCheck                  string `json:"policy.istio.io/check,omitempty"`
    PolicyCheckRetries           string `json:"policy.istio.io/checkRetries,omitempty"`
    PolicyCheckBaseRetryWaitTime string `json:"policy.istio.io/checkBaseRetryWaitTime,omitempty"`
    PolicyCheckMaxRetryWaitTime  string `json:"policy.istio.io/checkMaxRetryWaitTime,omitempty"`

    StatsInclusionPrefixes string `json:"sidecar.istio.io/statsInclusionPrefixes,omitempty"`
    StatsInclusionRegexps  string `json:"sidecar.istio.io/statsInclusionRegexps,omitempty"`
    StatsInclusionSuffixes string `json:"sidecar.istio.io/statsInclusionSuffixes,omitempty"`

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

    // SdsTokenPath specifies the path of the SDS token used by the Envoy proxy.
    // If not set, Pilot uses the default SDS token path.
    SdsTokenPath string `json:"SDS_TOKEN_PATH,omitempty"`
    UserSds      string `json:"USER_SDS,omitempty"`
    SdsBase      string `json:"BASE,omitempty"`
    // SdsEnabled indicates if SDS is enabled or not. This is are set to "1" if true
    SdsEnabled string `json:"SDS,omitempty"`
    // SdsTrustJwt indicates if SDS trust jwt is enabled or not. This is are set to "1" if true
    SdsTrustJwt string `json:"TRUSTJWT,omitempty"`

    InsecurePath string `json:"istio.io/insecurepath,omitempty"`

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

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

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

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

func ParseMetadata Uses

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

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

func (NodeMetadata) ToStruct Uses

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

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

func (*NodeMetadata) UnmarshalJSON Uses

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

type NodeType Uses

type NodeType string

NodeType decides the responsibility of the proxy serves in the mesh

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

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

    // AllPortsLiteral is the string value indicating all ports
    AllPortsLiteral = "*"
)

type PodPort Uses

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

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

type PodPortList Uses

type PodPortList []PodPort

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

func (PodPortList) MarshalJSON Uses

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

func (*PodPortList) UnmarshalJSON Uses

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

type Port Uses

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

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

    // Protocol to be used for the port.
    Protocol protocol.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) Match Uses

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

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

type PortList Uses

type PortList []*Port

PortList is a set of ports

func ParseServiceKey Uses

func ParseServiceKey(s string) (hostname host.Name, ports PortList, lc labels.Collection)

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

func (PortList) Get Uses

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

Get retrieves a port declaration by name

func (PortList) GetByPort Uses

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

GetByPort retrieves a port declaration by port value

func (PortList) GetNames Uses

func (ports PortList) GetNames() []string

GetNames returns port names

type Probe Uses

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

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

type ProbeList Uses

type ProbeList []*Probe

ProbeList is a set of probes

type Proxy Uses

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

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

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

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

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

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

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

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

    // the sidecarScope associated with the proxy
    SidecarScope *SidecarScope

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

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

    // labels associated with the workload
    WorkloadLabels labels.Collection

    // Istio version associated with the Proxy
    IstioVersion *IstioVersion
}

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 Uses

func ParseServiceNodeWithMetadata(s string, metadata *NodeMetadata) (*Proxy, error)

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

func (*Proxy) GetInterceptionMode Uses

func (node *Proxy) GetInterceptionMode() TrafficInterceptionMode

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

func (*Proxy) GetRouterMode Uses

func (node *Proxy) GetRouterMode() RouterMode

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

func (*Proxy) ServiceNode Uses

func (node *Proxy) ServiceNode() string

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

func (*Proxy) SetGatewaysForProxy Uses

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

func (*Proxy) SetServiceInstances Uses

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

func (*Proxy) SetSidecarScope Uses

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

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

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

func (*Proxy) SetWorkloadLabels Uses

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

SetWorkloadLabels will reset the proxy.WorkloadLabels if `force` = true, otherwise only set it when it is nil.

type ProxyPushStatus Uses

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

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

type PushContext Uses

type PushContext struct {

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

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

    // ServiceByHostnameAndNamespace has all services, indexed by hostname then namespace.
    ServiceByHostnameAndNamespace map[host.Name]map[string]*Service `json:"-"`
    // ServiceAccounts contains a map of hostname and port to service accounts.
    ServiceAccounts map[host.Name]map[int][]string `json:"-"`

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

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

    // AuthNPolicies contains a map of hostname and port to authentication policy
    AuthnPolicies processedAuthnPolicies `json:"-"`

    Version string
    // 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 Uses

func NewPushContext() *PushContext

NewPushContext creates a new PushContext structure to track push status.

func (*PushContext) Add Uses

func (ps *PushContext) Add(metric monitoring.Metric, key string, proxy *Proxy, msg string)

Add will add an case to the metric.

func (*PushContext) AuthenticationPolicyForWorkload Uses

func (ps *PushContext) AuthenticationPolicyForWorkload(service *Service, port *Port) (*authn.Policy, *ConfigMeta)

AuthenticationPolicyForWorkload returns the matching auth policy for a given service This replaces store.AuthenticationPolicyForWorkload

func (*PushContext) DestinationRule Uses

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

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

func (*PushContext) EnvoyFilters Uses

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

func (*PushContext) GetAllSidecarScopes Uses

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

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

func (*PushContext) InitContext Uses

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) JSON Uses

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

JSON implements json.Marshaller, with a lock.

func (*PushContext) OnConfigChange Uses

func (ps *PushContext) OnConfigChange()

OnConfigChange is called when a config change is detected.

func (*PushContext) Services Uses

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

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

func (*PushContext) SetDestinationRules Uses

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

SetDestinationRules is updates internal structures using a set of configs. Split out of DestinationRule expensive conversions, computed once per push. This also allows tests to inject a config without having the mock. This will not work properly for Sidecars, which will precompute their destination rules on init

func (*PushContext) SubsetToLabels Uses

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

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

func (*PushContext) UpdateMetrics Uses

func (ps *PushContext) UpdateMetrics()

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

func (*PushContext) VirtualServices Uses

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

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

type PushRequest Uses

type PushRequest struct {
    // Full determines whether a full push is required or not. If set to false, only endpoints will be sent.
    Full bool

    // NamespacesUpdated contains a list of namespaces whose services/endpoints were changed in the update.
    // This is used as an optimization to avoid unnecessary pushes to proxies that are scoped with a Sidecar.
    // Currently, this will only scope EDS updates, as config updates are more complicated.
    // If this is empty, then all proxies will get an update.
    // If this is present, then only proxies that import this namespace will get an update
    NamespacesUpdated map[string]struct{}

    // ConfigTypesUpdated contains the types of configs that have changed.
    // The config types are those defined in pkg/config/schemas
    // Applicable only when Full is set to true.
    ConfigTypesUpdated map[string]struct{}

    // EdsUpdates keeps track of all service updated since last full push.
    // Key is the hostname (serviceName).
    // This is used by incremental eds.
    EdsUpdates map[string]struct{}

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

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

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

func (*PushRequest) Merge Uses

func (first *PushRequest) Merge(other *PushRequest) *PushRequest

Merge two update requests together

type Resolution Uses

type Resolution int

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

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

type RolesAndBindings Uses

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

    // ServiceRoleBindings indexed by its associated ServiceRole's name.
    Bindings map[string][]*rbacproto.ServiceRoleBinding
}

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

type RouterMode Uses

type RouterMode string

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

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

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

type Service Uses

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

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

    // Protect concurrent ClusterVIPs read/write
    Mutex sync.RWMutex
    // ClusterVIPs specifies the service address of the load balancer
    // in each of the clusters where the service resides
    ClusterVIPs map[string]string `json:"cluster-vips,omitempty"`
    // Ports is the set of network ports where the service is listening for
    // connections
    Ports PortList `json:"ports,omitempty"`

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

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

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

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

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

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

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

func (*Service) External Uses

func (s *Service) External() bool

External predicate checks whether the service is external

func (*Service) GetServiceAddressForProxy Uses

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

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

func (*Service) Key Uses

func (s *Service) Key(port *Port, l labels.Instance) string

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

func (*Service) Validate Uses

func (s *Service) Validate() error

Validate ensures that the service object is well-defined

type ServiceAttributes Uses

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 string
    // Name is "destination.service.name" attribute
    Name string
    // Namespace is "destination.service.namespace" attribute
    Namespace string
    // UID is "destination.service.uid" attribute
    UID string
    // ExportTo defines the visibility of Service in
    // a namespace when the namespace is imported.
    ExportTo map[visibility.Instance]bool

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

ServiceAttributes represents a group of custom attributes of the service.

type ServiceDiscovery Uses

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

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

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

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

    GetProxyWorkloadLabels(*Proxy) (labels.Collection, error)

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

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

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

ServiceDiscovery enumerates Istio service instances. nolint: lll go:generate counterfeiter -o ../networking/core/v1alpha3/fakes/fake_service_discovery.gen.go --fake-name ServiceDiscovery . ServiceDiscovery

type ServiceInstance Uses

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

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

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

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

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

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

func (*ServiceInstance) GetLocality Uses

func (si *ServiceInstance) GetLocality() string

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

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

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

func (*ServiceInstance) Validate Uses

func (instance *ServiceInstance) Validate() error

Validate ensures that the service instance is well-defined

type SidecarScope Uses

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

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

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

    // A given hostname should only be considered in a single namespace. This mapping determines which
    // namespace a hostname exists in
    NamespaceForHostname map[host.Name]string

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

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

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

ConvertToSidecarScope converts from Sidecar config to SidecarScope object

func DefaultSidecarScopeForNamespace Uses

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

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

func (*SidecarScope) DependsOnNamespace Uses

func (sc *SidecarScope) DependsOnNamespace(namespace string) bool

DependsOnNamespace determines if the Sidecar includes the given namespace.

func (*SidecarScope) DestinationRule Uses

func (sc *SidecarScope) DestinationRule(hostname host.Name) *Config

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

func (*SidecarScope) GetEgressListenerForRDS Uses

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) ServiceForHostname Uses

func (sc *SidecarScope) ServiceForHostname(hostname host.Name, serviceByHostname map[host.Name]map[string]*Service) *Service

ServiceForHostname returns the service associated with a given hostname following SidecarScope

func (*SidecarScope) Services Uses

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

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

type StringList Uses

type StringList []string

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

func (StringList) MarshalJSON Uses

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

func (*StringList) UnmarshalJSON Uses

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

type TrafficDirection Uses

type TrafficDirection string

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

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

func ParseSubsetKey Uses

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

ParseSubsetKey is the inverse of the BuildSubsetKey method

type TrafficInterceptionMode Uses

type TrafficInterceptionMode string

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

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

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

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

type XDSUpdater Uses

type XDSUpdater interface {

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

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

    // ConfigUpdate is called to notify the XDS server of config updates and request a push.
    // The requests may be collapsed and throttled.
    // This replaces the 'cache invalidation' model.
    ConfigUpdate(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, ip string)
}

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

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

Directories

PathSynopsis
test

Package model imports 46 packages (graph) and is imported by 104 packages. Updated 2019-10-16. Refresh now. Tools for package owners.