Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to analyze the function of Pilot-agent and its source code

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

This article shows you how to analyze the role of Pilot-agent and its source code, the content is concise and easy to understand, absolutely can make your eyes bright, through the detailed introduction of this article, I hope you can get something.

The Istio source code used by the editor is release 1.5.

Introduction

When Sidecar is injected, two containers, istio-init and istio-proxy, are injected. Pilot-agent is the entry point to launch istio-proxy. We can see the startup command through the kubectl command:

[root@localhost] # kubectl exec-it details-v1-6c9f8bcbcb-shltm-c istio-proxy-- ps-efwwUID PID PPID C STIME TTY TIME CMDistio-p+ 1 00 08:52? 00:00:13 / usr/local/bin/pilot-agent proxy sidecar-domain default.svc.cluster.local-configPath / etc/istio/proxy-binaryPath / usr/local/bin/envoy-serviceCluster details.default-drainDuration 45s-- ParentShutdownDuration 1m0s-- discoveryAddress istiod.istio-system.svc:15012-- zipkinAddress zipkin.istio-system:9411-- proxyLogLevel=warning-- proxyComponentLogLevel=misc:error-- connectTimeout 10s-- proxyAdminPort 15000-concurrency 2-- controlPlaneAuthPolicy NONE-- dnsRefreshRate 300s-- statusPort 15020-- trust-domain=cluster.local-- controlPlaneBootstrap=falseistio-p+ 18 10 08:52? 00:01:11 / usr/local/bin/envoy-c / etc/istio/proxy/envoy-rev0.json-- restart-epoch 0-- drain- Time-s 45-- parent-shutdown-time-s 60-- service-cluster details.default-- service-node sidecar~172.20.0.14~details-v1-6c9f8bcbcb-shltm.default~default.svc.cluster.local-- max-obj-name-len 189-- local-address-ip-version v4-- log-format [Envoy (Epoch 0)] [% Y-%m-%d% T.% e] [% t] [% l] [% n]% v-l warning-- component-log-level misc:error-- concurrency 2

In addition to launching istio-proxy, Pilot-agent has the following capabilities:

Generate the Bootstrap configuration file for Envoy

Health examination

Monitor the change of the certificate, notify the Envoy process to hot restart, and realize the hot loading of the certificate

Provides Envoy daemon function to restart Envoy when Envoy exits abnormally.

Notify Envoy to quit gracefully

Code execution flow analysis proxyCmd = & cobra.Command {Use: "proxy", Short: "Envoy proxy agent", FParseErrWhitelist: cobra.FParseErrWhitelist {UnknownFlags: true,}, RunE: func (c * cobra.Command Args [] string) error {. / / is used to set the default configuration-related parameters of the default profile proxyConfig: = mesh.DefaultProxyConfig () / / set all flags proxyConfig.CustomConfigFile = customConfigFile ProxyConfig.ProxyBootstrapTemplatePath = templateFile proxyConfig.ConfigPath = configPath proxyConfig.BinaryPath = binaryPath proxyConfig.ServiceCluster = serviceCluster proxyConfig.DrainDuration = types.DurationProto (drainDuration) proxyConfig.ParentShutdownDuration = types.DurationProto (parentShutdownDuration) proxyConfig.DiscoveryAddress = discoveryAddress ProxyConfig.ConnectTimeout = types.DurationProto (connectTimeout) proxyConfig.StatsdUdpAddress = statsdUDPAddress. Ctx Cancel: = context.WithCancel (context.Background ()) / / launch status server if statusPort > 0 {localHostAddr: = localHostIPv4 if proxyIPv6 {localHostAddr = localHostIPv6 } prober: = kubeAppProberNameVar.Get () / / Health probe statusServer Err: = status.NewServer (status.Config {LocalHostAddr: localHostAddr, AdminPort: proxyAdminPort, / / set StatusPort: statusPort by parameter-- statusPort 15020) KubeAppProbers: prober, NodeType: role.Type }) if err! = nil {cancel () return err} go waitForCompletion (ctx StatusServer.Run)}. / / construct a Proxy instance, including configuration Startup parameters such as envoyProxy: = envoy.NewProxy (envoy.ProxyConfig {Config: proxyConfig, Node: role.ServiceNode (), LogLevel: proxyLogLevel ComponentLogLevel: proxyComponentLogLevel, PilotSubjectAltName: pilotSAN, MixerSubjectAltName: mixerSAN, NodeIPs: role.IPAddresses, DNSRefreshRate: dnsRefreshRate PodName: podName, PodNamespace: podNamespace, PodIP: podIP, SDSUDSPath: sdsUDSPath, SDSTokenPath: sdsTokenPath STSPort: stsPort, ControlPlaneAuth: controlPlaneAuthEnabled, DisableReportCalls: disableInternalTelemetry, OutlierLogPath: outlierLogPath, PilotCertProvider: pilotCertProvider }) / / construct an agent instance Implement Agent interface agent: = envoy.NewAgent (envoyProxy, features.TerminationDrainDuration ()) if nodeAgentSDSEnabled {tlsCertsToWatch = [] string {}} / / construct watcher instance watcher: = envoy.NewWatcher (tlsCertsToWatch) Agent.Restart) / / start watcher go watcher.Run (ctx) / / gracefully exit go cmd.WaitSignalFunc (cancel) / / start agent return agent.Run (ctx)},}

The execution process is roughly divided into several steps:

Used to set default configuration-related parameters for the default profile

Start status server for health check

Construct Proxy instance, including configuration, startup parameters, and construct agent instance

Construct the watcher instance and start

Turn on the thread listening signal to exit gracefully

Start agent

Default configuration related parameters kubectl exec-it details-v1-6c9f8bcbcb-shltm-c istio-proxy-/ usr/local/bin/pilot-agent proxy-- helpEnvoy proxy agentUsage: pilot-agent proxy [flags] Flags:-- binaryPath string Path to the proxy binary (default "/ usr/local/bin/envoy")-concurrency int number of worker threads To run-configPath string Path to the generated configuration file directory (default "/ etc/istio/proxy")-connectTimeout duration Connection timeout used by Envoy for supporting services (default 1s)-controlPlaneAuthPolicy string Control Plane Authentication Policy (default "NONE")-controlPlaneBootstrap Process bootstrap provided via templateFile to be used by control plane components. (default true)-customConfigFile string Path to the custom configuration file-datadogAgentAddress string Address of the Datadog Agent-disableInternalTelemetry Disable internal telemetry-discoveryAddress string Address of the discovery service exposing xDS (e.g. Istio-pilot:8080) (default "istio-pilot:15010")- -dnsRefreshRate string The dns_refresh_rate for bootstrap STRICT_DNS clusters (default "300s")-- domain string DNS domain suffix. If not provided uses ${POD_NAMESPACE} .svc.cluster.local-- drainDuration duration The time in seconds that Envoy will drain connections during a hot restart (default 45s)-- envoyAccessLogService string Settings of an Envoy gRPC AccessLogService API implementation-- envoyMetricsService string Settings of an Envoy gRPC MetricsService API implementation-h -- help help for proxy-- id string Proxy unique ID. If not provided uses ${POD_NAME}. ${POD_NAMESPACE} from environment variables-- ip string Proxy IP address. If not provided uses ${INSTANCE_IP} environment variable. -lightstepAccessToken string AccessToken for LightStep Satellite pool-- lightstepAddress string Address of the LightStep Satellite pool-- lightstepCacertPath string Path to the trusted cacert used to authenticate the pool-- lightstepSecure Should connection to the LightStep Satellite pool be secure-- mixerIdentity string The identity used as the suffix for mixer's spiffe SAN. This would only be used by pilot all other proxy would get this value from pilot-outlierLogPath string The log path for outlier detection-parentShutdownDuration duration The time in seconds that Envoy will wait before shutting down the parent process during a hot restart (default 1m0s)-pilotIdentity string The identity used as the suffix for pilot's spiffe SAN-proxyAdminPort uint16 Port on which Envoy should listen for administrative commands (default 15000)-proxyComponentLogLevel string The component log level used to start the Envoy proxy (default "misc:error")-proxyLogLevel string The log level used to start the Envoy proxy (choose from {trace) Debug, info, warning, error, critical, off}) (default "warning")-serviceCluster string Service cluster (default "istio-proxy")-serviceregistry string Select the platform for serviceregistry, options are {Kubernetes, Consul Mock} (default "Kubernetes")-- statsdUdpAddress string IP Address and Port of a statsd UDP listener (e.g. 10.75.241.127)-- statusPort uint16 HTTP Port on which to serve pilot agent status. If zero, agent status will not be provided. -stsPort int HTTP Port on which to serve Security Token Service (STS). If zero, STS service will not be provided. -templateFile string Go template bootstrap config-tokenManagerPlugin string Token provider specific plugin name. (default "GoogleTokenExchange")-- trust-domain string The domain to use for identities-- zipkinAddress string Address of the Zipkin service (e.g. Zipkin:9411)

From the output above, we can also see the meaning of the proxy parameter and the corresponding default values.

Func DefaultProxyConfig () meshconfig.ProxyConfig {return meshconfig.ProxyConfig {ConfigPath: constants.ConfigPathDir, BinaryPath: constants.BinaryPathFilename, ServiceCluster: constants.ServiceClusterName, DrainDuration: types.DurationProto (45 * time.Second), ParentShutdownDuration: types.DurationProto (60 * time.Second) DiscoveryAddress: constants.DiscoveryPlainAddress, ConnectTimeout: types.DurationProto (1 * time.Second), StatsdUdpAddress: ", EnvoyMetricsService: & meshconfig.RemoteService {Address:"}, EnvoyAccessLogService: & meshconfig.RemoteService {Address: ""}, ProxyAdminPort: 15000 ControlPlaneAuthPolicy: meshconfig.AuthenticationPolicy_NONE, CustomConfigFile: "", Concurrency: 0, StatNameLength: 189, Tracing: nil,}}

The default startup parameters are set in the DefaultProxyConfig method, and the default startup configuration is as follows:

ConfigPath:/etc/istio/proxy

BinaryPath:/usr/local/bin/envoy

ServiceCluster:istio-proxy

DrainDuration:45s

ParentShutdownDuration:60s

DiscoveryAddress:istio-pilot:15010

ConnectTimeout:1s

StatsdUdpAddress: ""

EnvoyMetricsService:meshconfig.RemoteService

EnvoyAccessLogService:meshconfig.RemoteService

ProxyAdminPort:15000

ControlPlaneAuthPolicy:0

CustomConfigFile: ""

Concurrency:0

StatNameLength:189

Tracing:nil

Status server health check

Initialize status server:

Func NewServer (config Config) (* Server, error) {s: = & Server {statusPort: config.StatusPort, ready: & ready.Probe {LocalHostAddr: config.LocalHostAddr, AdminPort: config.AdminPort, NodeType: config.NodeType,} }... Return s, nil}

After initialization, a thread is started to call the Run method of statusServer:

Go waitForCompletion (ctx, statusServer.Run) func (s * Server) Run (ctx context.Context) {log.Infof ("Opening status port% d\ n", s.statusPort) mux: = http.NewServeMux () / / Add the handler for ready probes. / / initialize the callback processor of the probe / / healthz/ready mux.HandleFunc (readyPath, s.handleReadyProbe) mux.HandleFunc (quitPath, s.handleQuit) / / Application Port check mux.HandleFunc ("/ app-health/", s.handleAppProbe) / / Port sets l, err: = net.Listen ("tcp", fmt.Sprintf (":% d") through the parameter-- statusPort 15020 S.statusPort) if err! = nil {log.Errorf ("Error listening on status port:% v", err.Error ()) return}. Defer l.Close () / / enable listening go func () {if err: = http.Serve (l, mux); err! = nil {log.Errora (err) notifyExit ()} ()

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report