istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pilot/cmd/pilot-discovery/app/cmd.go (about)

     1  // Copyright Istio Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package app
    16  
    17  import (
    18  	"fmt"
    19  	"strings"
    20  	"time"
    21  
    22  	"github.com/spf13/cobra"
    23  
    24  	"istio.io/istio/pilot/pkg/bootstrap"
    25  	"istio.io/istio/pilot/pkg/features"
    26  	"istio.io/istio/pilot/pkg/serviceregistry/provider"
    27  	"istio.io/istio/pkg/cmd"
    28  	"istio.io/istio/pkg/collateral"
    29  	"istio.io/istio/pkg/config/constants"
    30  	"istio.io/istio/pkg/ctrlz"
    31  	"istio.io/istio/pkg/log"
    32  	"istio.io/istio/pkg/version"
    33  )
    34  
    35  var (
    36  	serverArgs     *bootstrap.PilotArgs
    37  	loggingOptions = log.DefaultOptions()
    38  )
    39  
    40  // NewRootCommand returns the root cobra command of pilot-discovery.
    41  func NewRootCommand() *cobra.Command {
    42  	rootCmd := &cobra.Command{
    43  		Use:          "pilot-discovery",
    44  		Short:        "Istio Pilot.",
    45  		Long:         "Istio Pilot provides mesh-wide traffic management, security and policy capabilities in the Istio Service Mesh.",
    46  		SilenceUsage: true,
    47  		FParseErrWhitelist: cobra.FParseErrWhitelist{
    48  			// Allow unknown flags for backward-compatibility.
    49  			UnknownFlags: true,
    50  		},
    51  		PreRunE: func(c *cobra.Command, args []string) error {
    52  			cmd.AddFlags(c)
    53  			return nil
    54  		},
    55  	}
    56  
    57  	discoveryCmd := newDiscoveryCommand()
    58  	addFlags(discoveryCmd)
    59  	rootCmd.AddCommand(discoveryCmd)
    60  	rootCmd.AddCommand(version.CobraCommand())
    61  	rootCmd.AddCommand(collateral.CobraCommand(rootCmd, collateral.Metadata{
    62  		Title:   "Istio Pilot Discovery",
    63  		Section: "pilot-discovery CLI",
    64  		Manual:  "Istio Pilot Discovery",
    65  	}))
    66  	rootCmd.AddCommand(requestCmd)
    67  
    68  	return rootCmd
    69  }
    70  
    71  func newDiscoveryCommand() *cobra.Command {
    72  	return &cobra.Command{
    73  		Use:   "discovery",
    74  		Short: "Start Istio proxy discovery service.",
    75  		Args:  cobra.ExactArgs(0),
    76  		FParseErrWhitelist: cobra.FParseErrWhitelist{
    77  			// Allow unknown flags for backward-compatibility.
    78  			UnknownFlags: true,
    79  		},
    80  		PreRunE: func(c *cobra.Command, args []string) error {
    81  			if err := log.Configure(loggingOptions); err != nil {
    82  				return err
    83  			}
    84  			if err := validateFlags(serverArgs); err != nil {
    85  				return err
    86  			}
    87  			if err := serverArgs.Complete(); err != nil {
    88  				return err
    89  			}
    90  			return nil
    91  		},
    92  		RunE: func(c *cobra.Command, args []string) error {
    93  			cmd.PrintFlags(c.Flags())
    94  
    95  			// Create the stop channel for all the servers.
    96  			stop := make(chan struct{})
    97  
    98  			// Create the server for the discovery service.
    99  			discoveryServer, err := bootstrap.NewServer(serverArgs)
   100  			if err != nil {
   101  				return fmt.Errorf("failed to create discovery service: %v", err)
   102  			}
   103  
   104  			// Start the server
   105  			if err := discoveryServer.Start(stop); err != nil {
   106  				return fmt.Errorf("failed to start discovery service: %v", err)
   107  			}
   108  
   109  			cmd.WaitSignal(stop)
   110  			// Wait until we shut down. In theory this could block forever; in practice we will get
   111  			// forcibly shut down after 30s in Kubernetes.
   112  			discoveryServer.WaitUntilCompletion()
   113  			return nil
   114  		},
   115  	}
   116  }
   117  
   118  func addFlags(c *cobra.Command) {
   119  	serverArgs = bootstrap.NewPilotArgs(func(p *bootstrap.PilotArgs) {
   120  		// Set Defaults
   121  		p.CtrlZOptions = ctrlz.DefaultOptions()
   122  		// TODO replace with mesh config?
   123  		p.InjectionOptions = bootstrap.InjectionOptions{
   124  			InjectionDirectory: "./var/lib/istio/inject",
   125  		}
   126  	})
   127  
   128  	// Process commandline args.
   129  	c.PersistentFlags().StringSliceVar(&serverArgs.RegistryOptions.Registries, "registries",
   130  		[]string{string(provider.Kubernetes)},
   131  		fmt.Sprintf("Comma separated list of platform service registries to read from (choose one or more from {%s, %s})",
   132  			provider.Kubernetes, provider.Mock))
   133  	c.PersistentFlags().StringVar(&serverArgs.RegistryOptions.ClusterRegistriesNamespace, "clusterRegistriesNamespace",
   134  		serverArgs.RegistryOptions.ClusterRegistriesNamespace, "Namespace for ConfigMap which stores clusters configs")
   135  	c.PersistentFlags().StringVar(&serverArgs.RegistryOptions.KubeConfig, "kubeconfig", "",
   136  		"Use a Kubernetes configuration file instead of in-cluster configuration")
   137  	c.PersistentFlags().StringVar(&serverArgs.MeshConfigFile, "meshConfig", "./etc/istio/config/mesh",
   138  		"File name for Istio mesh configuration. If not specified, a default mesh will be used.")
   139  	c.PersistentFlags().StringVar(&serverArgs.NetworksConfigFile, "networksConfig", "./etc/istio/config/meshNetworks",
   140  		"File name for Istio mesh networks configuration. If not specified, a default mesh networks will be used.")
   141  	c.PersistentFlags().StringVarP(&serverArgs.Namespace, "namespace", "n", bootstrap.PodNamespace,
   142  		"Select a namespace where the controller resides. If not set, uses ${POD_NAMESPACE} environment variable")
   143  	c.PersistentFlags().StringVar(&serverArgs.CniNamespace, "cniNamespace", bootstrap.PodNamespace,
   144  		"Select a namespace where the istio-cni resides. If not set, uses ${POD_NAMESPACE} environment variable")
   145  	c.PersistentFlags().DurationVar(&serverArgs.ShutdownDuration, "shutdownDuration", 10*time.Second,
   146  		"Duration the discovery server needs to terminate gracefully")
   147  
   148  	// RegistryOptions Controller options
   149  	c.PersistentFlags().StringVar(&serverArgs.RegistryOptions.FileDir, "configDir", "",
   150  		"Directory to watch for updates to config yaml files. If specified, the files will be used as the source of config, rather than a CRD client.")
   151  	c.PersistentFlags().StringVar(&serverArgs.RegistryOptions.KubeOptions.DomainSuffix, "domain", constants.DefaultClusterLocalDomain,
   152  		"DNS domain suffix")
   153  	c.PersistentFlags().StringVar((*string)(&serverArgs.RegistryOptions.KubeOptions.ClusterID), "clusterID", features.ClusterName,
   154  		"The ID of the cluster that this Istiod instance resides")
   155  	c.PersistentFlags().StringToStringVar(&serverArgs.RegistryOptions.KubeOptions.ClusterAliases, "clusterAliases", map[string]string{},
   156  		"Alias names for clusters")
   157  
   158  	// using address, so it can be configured as localhost:.. (possibly UDS in future)
   159  	c.PersistentFlags().StringVar(&serverArgs.ServerOptions.HTTPAddr, "httpAddr", ":8080",
   160  		"Discovery service HTTP address")
   161  	c.PersistentFlags().StringVar(&serverArgs.ServerOptions.HTTPSAddr, "httpsAddr", ":15017",
   162  		"Injection and validation service HTTPS address")
   163  	c.PersistentFlags().StringVar(&serverArgs.ServerOptions.GRPCAddr, "grpcAddr", ":15010",
   164  		"Discovery service gRPC address")
   165  	c.PersistentFlags().StringVar(&serverArgs.ServerOptions.SecureGRPCAddr, "secureGRPCAddr", ":15012",
   166  		"Discovery service secured gRPC address")
   167  	c.PersistentFlags().StringVar(&serverArgs.ServerOptions.MonitoringAddr, "monitoringAddr", ":15014",
   168  		"HTTP address to use for pilot's self-monitoring information")
   169  	c.PersistentFlags().BoolVar(&serverArgs.ServerOptions.EnableProfiling, "profile", true,
   170  		"Enable profiling via web interface host:port/debug/pprof")
   171  
   172  	// Use TLS certificates if provided.
   173  	c.PersistentFlags().StringVar(&serverArgs.ServerOptions.TLSOptions.CaCertFile, "caCertFile", "",
   174  		"File containing the x509 Server CA Certificate")
   175  	c.PersistentFlags().StringVar(&serverArgs.ServerOptions.TLSOptions.CertFile, "tlsCertFile", "",
   176  		"File containing the x509 Server Certificate")
   177  	c.PersistentFlags().StringVar(&serverArgs.ServerOptions.TLSOptions.KeyFile, "tlsKeyFile", "",
   178  		"File containing the x509 private key matching --tlsCertFile")
   179  	c.PersistentFlags().StringSliceVar(&serverArgs.ServerOptions.TLSOptions.TLSCipherSuites, "tls-cipher-suites", nil,
   180  		"Comma-separated list of cipher suites for istiod TLS server. "+
   181  			"If omitted, the default Go cipher suites will be used. \n"+
   182  			"Preferred values: "+strings.Join(secureTLSCipherNames(), ", ")+". \n"+
   183  			"Insecure values: "+strings.Join(insecureTLSCipherNames(), ", ")+".")
   184  
   185  	c.PersistentFlags().Float32Var(&serverArgs.RegistryOptions.KubeOptions.KubernetesAPIQPS, "kubernetesApiQPS", 80.0,
   186  		"Maximum QPS when communicating with the kubernetes API")
   187  
   188  	c.PersistentFlags().IntVar(&serverArgs.RegistryOptions.KubeOptions.KubernetesAPIBurst, "kubernetesApiBurst", 160,
   189  		"Maximum burst for throttle when communicating with the kubernetes API")
   190  
   191  	// Attach the Istio logging options to the command.
   192  	loggingOptions.AttachCobraFlags(c)
   193  
   194  	// Attach the Istio Ctrlz options to the command.
   195  	serverArgs.CtrlZOptions.AttachCobraFlags(c)
   196  
   197  	// Attach the Istio Keepalive options to the command.
   198  	serverArgs.KeepaliveOptions.AttachCobraFlags(c)
   199  }