build: move e2e dependencies into e2e/go.mod

Several packages are only used while running the e2e suite. These
packages are less important to update, as the they can not influence the
final executable that is part of the Ceph-CSI container-image.

By moving these dependencies out of the main Ceph-CSI go.mod, it is
easier to identify if a reported CVE affects Ceph-CSI, or only the
testing (like most of the Kubernetes CVEs).

Signed-off-by: Niels de Vos <ndevos@ibm.com>
This commit is contained in:
Niels de Vos
2025-03-04 08:57:28 +01:00
committed by mergify[bot]
parent 15da101b1b
commit bec6090996
8047 changed files with 1407827 additions and 3453 deletions

View File

@ -0,0 +1,54 @@
/*
Copyright 2018 The Kubernetes 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.
*/
package options
import (
"github.com/spf13/pflag"
cpconfig "k8s.io/cloud-provider/config"
)
// CloudProviderOptions holds the cloudprovider options.
type CloudProviderOptions struct {
*cpconfig.CloudProviderConfiguration
}
// Validate checks validation of cloudprovider options.
func (s *CloudProviderOptions) Validate() []error {
allErrors := []error{}
return allErrors
}
// AddFlags adds flags related to cloudprovider for controller manager to the specified FlagSet.
func (s *CloudProviderOptions) AddFlags(fs *pflag.FlagSet) {
fs.StringVar(&s.Name, "cloud-provider", s.Name,
"The provider for cloud services. Empty string for no provider.")
fs.StringVar(&s.CloudConfigFile, "cloud-config", s.CloudConfigFile,
"The path to the cloud provider configuration file. Empty string for no configuration file.")
}
// ApplyTo fills up cloudprovider config with options.
func (s *CloudProviderOptions) ApplyTo(cfg *cpconfig.CloudProviderConfiguration) error {
if s == nil {
return nil
}
cfg.Name = s.Name
cfg.CloudConfigFile = s.CloudConfigFile
return nil
}

View File

@ -0,0 +1,110 @@
/*
Copyright 2018 The Kubernetes 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.
*/
package options
import (
"fmt"
"github.com/spf13/pflag"
cpconfig "k8s.io/cloud-provider/config"
"k8s.io/cloud-provider/names"
)
// KubeCloudSharedOptions holds the options shared between kube-controller-manager
// and cloud-controller-manager.
type KubeCloudSharedOptions struct {
*cpconfig.KubeCloudSharedConfiguration
CloudProvider *CloudProviderOptions
}
// NewKubeCloudSharedOptions returns common/default configuration values for both
// the kube-controller-manager and the cloud-contoller-manager. Any common changes should
// be made here. Any individual changes should be made in that controller.
func NewKubeCloudSharedOptions(cfg *cpconfig.KubeCloudSharedConfiguration) *KubeCloudSharedOptions {
o := &KubeCloudSharedOptions{
KubeCloudSharedConfiguration: cfg,
CloudProvider: &CloudProviderOptions{
CloudProviderConfiguration: &cpconfig.CloudProviderConfiguration{},
},
}
return o
}
// AddFlags adds flags related to shared variable for controller manager to the specified FlagSet.
func (o *KubeCloudSharedOptions) AddFlags(fs *pflag.FlagSet) {
if o == nil {
return
}
o.CloudProvider.AddFlags(fs)
fs.StringVar(&o.ExternalCloudVolumePlugin, "external-cloud-volume-plugin", o.ExternalCloudVolumePlugin, "The plugin to use when cloud provider is set to external. Can be empty, should only be set when cloud-provider is external. Currently used to allow node-ipam-controller, persistentvolume-binder-controller, persistentvolume-expander-controller and attach-detach-controller to work for in tree cloud providers.")
fs.BoolVar(&o.UseServiceAccountCredentials, "use-service-account-credentials", o.UseServiceAccountCredentials, "If true, use individual service account credentials for each controller.")
fs.BoolVar(&o.AllowUntaggedCloud, "allow-untagged-cloud", false, "Allow the cluster to run without the cluster-id on cloud instances. This is a legacy mode of operation and a cluster-id will be required in the future.")
fs.MarkDeprecated("allow-untagged-cloud", "This flag is deprecated and will be removed in a future release. A cluster-id will be required on cloud instances.")
fs.DurationVar(&o.RouteReconciliationPeriod.Duration, "route-reconciliation-period", o.RouteReconciliationPeriod.Duration, "The period for reconciling routes created for Nodes by cloud provider.")
fs.DurationVar(&o.NodeMonitorPeriod.Duration, "node-monitor-period", o.NodeMonitorPeriod.Duration,
fmt.Sprintf("The period for syncing NodeStatus in %s.", names.CloudNodeLifecycleController))
fs.StringVar(&o.ClusterName, "cluster-name", o.ClusterName, "The instance prefix for the cluster.")
fs.StringVar(&o.ClusterCIDR, "cluster-cidr", o.ClusterCIDR, "CIDR Range for Pods in cluster. Only used when --allocate-node-cidrs=true; if false, this option will be ignored.")
fs.BoolVar(&o.AllocateNodeCIDRs, "allocate-node-cidrs", false, "Should CIDRs for Pods be allocated and set on the cloud provider. Requires --cluster-cidr.")
fs.StringVar(&o.CIDRAllocatorType, "cidr-allocator-type", "RangeAllocator", "Type of CIDR allocator to use")
fs.BoolVar(&o.ConfigureCloudRoutes, "configure-cloud-routes", true, "Should CIDRs allocated by allocate-node-cidrs be configured on the cloud provider.")
fs.DurationVar(&o.NodeSyncPeriod.Duration, "node-sync-period", 0, ""+
"This flag is deprecated and will be removed in future releases. See node-monitor-period for Node health checking or "+
"route-reconciliation-period for cloud provider's route configuration settings.")
fs.MarkDeprecated("node-sync-period", "This flag is currently no-op and will be deleted.")
}
// ApplyTo fills up KubeCloudShared config with options.
func (o *KubeCloudSharedOptions) ApplyTo(cfg *cpconfig.KubeCloudSharedConfiguration) error {
if o == nil {
return nil
}
if err := o.CloudProvider.ApplyTo(&cfg.CloudProvider); err != nil {
return err
}
cfg.ExternalCloudVolumePlugin = o.ExternalCloudVolumePlugin
cfg.UseServiceAccountCredentials = o.UseServiceAccountCredentials
cfg.AllowUntaggedCloud = o.AllowUntaggedCloud
cfg.RouteReconciliationPeriod = o.RouteReconciliationPeriod
cfg.NodeMonitorPeriod = o.NodeMonitorPeriod
cfg.ClusterName = o.ClusterName
cfg.ClusterCIDR = o.ClusterCIDR
cfg.AllocateNodeCIDRs = o.AllocateNodeCIDRs
cfg.CIDRAllocatorType = o.CIDRAllocatorType
cfg.ConfigureCloudRoutes = o.ConfigureCloudRoutes
cfg.NodeSyncPeriod = o.NodeSyncPeriod
return nil
}
// Validate checks validation of KubeCloudSharedOptions.
func (o *KubeCloudSharedOptions) Validate() []error {
if o == nil {
return nil
}
errs := []error{}
errs = append(errs, o.CloudProvider.Validate()...)
return errs
}

View File

@ -0,0 +1,62 @@
/*
Copyright 2022 The Kubernetes 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.
*/
package options
import (
"fmt"
"github.com/spf13/pflag"
nodeconfig "k8s.io/cloud-provider/controllers/node/config"
)
// NodeControllerOptions holds the ServiceController options.
type NodeControllerOptions struct {
*nodeconfig.NodeControllerConfiguration
}
// AddFlags adds flags related to ServiceController for controller manager to the specified FlagSet.
func (o *NodeControllerOptions) AddFlags(fs *pflag.FlagSet) {
if o == nil {
return
}
fs.Int32Var(&o.ConcurrentNodeSyncs, "concurrent-node-syncs", o.ConcurrentNodeSyncs, "Number of workers concurrently synchronizing nodes.")
}
// ApplyTo fills up ServiceController config with options.
func (o *NodeControllerOptions) ApplyTo(cfg *nodeconfig.NodeControllerConfiguration) error {
if o == nil {
return nil
}
cfg.ConcurrentNodeSyncs = o.ConcurrentNodeSyncs
return nil
}
// Validate checks validation of NodeControllerOptions.
func (o *NodeControllerOptions) Validate() []error {
if o == nil {
return nil
}
var errors []error
if o.ConcurrentNodeSyncs <= 0 {
errors = append(errors, fmt.Errorf("concurrent-node-syncs must be a positive number"))
}
return errors
}

308
e2e/vendor/k8s.io/cloud-provider/options/options.go generated vendored Normal file
View File

@ -0,0 +1,308 @@
/*
Copyright 2016 The Kubernetes 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.
*/
package options
import (
"context"
"fmt"
"math/rand"
"net"
"time"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
apiserveroptions "k8s.io/apiserver/pkg/server/options"
utilfeature "k8s.io/apiserver/pkg/util/feature"
"k8s.io/client-go/informers"
clientset "k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/record"
cloudprovider "k8s.io/cloud-provider"
"k8s.io/cloud-provider/app/config"
ccmconfig "k8s.io/cloud-provider/config"
ccmconfigscheme "k8s.io/cloud-provider/config/install"
ccmconfigv1alpha1 "k8s.io/cloud-provider/config/v1alpha1"
"k8s.io/cloud-provider/names"
cliflag "k8s.io/component-base/cli/flag"
cmoptions "k8s.io/controller-manager/options"
"k8s.io/controller-manager/pkg/clientbuilder"
netutils "k8s.io/utils/net"
// add the related feature gates
_ "k8s.io/controller-manager/pkg/features/register"
)
const (
// CloudControllerManagerUserAgent is the userAgent name when starting cloud-controller managers.
CloudControllerManagerUserAgent = "cloud-controller-manager"
)
// CloudControllerManagerOptions is the main context object for the controller manager.
type CloudControllerManagerOptions struct {
Generic *cmoptions.GenericControllerManagerConfigurationOptions
KubeCloudShared *KubeCloudSharedOptions
ServiceController *ServiceControllerOptions
NodeController *NodeControllerOptions
SecureServing *apiserveroptions.SecureServingOptionsWithLoopback
Authentication *apiserveroptions.DelegatingAuthenticationOptions
Authorization *apiserveroptions.DelegatingAuthorizationOptions
Master string
WebhookServing *WebhookServingOptions
Webhook *WebhookOptions
// NodeStatusUpdateFrequency is the frequency at which the controller updates nodes' status
NodeStatusUpdateFrequency metav1.Duration
}
// ProviderDefaults are provided by the consumer when calling
// NewCloudControllerManagerOptions(), so that they can customize certain flag
// default values.
type ProviderDefaults struct {
// WebhookBindAddress is the default address. It can be overridden by "--webhook-bind-address".
WebhookBindAddress *net.IP
// WebhookBindPort is the default port. It can be overridden by "--webhook-bind-port".
WebhookBindPort *int
}
// NewCloudControllerManagerOptions creates a new ExternalCMServer with a default config.
func NewCloudControllerManagerOptions() (*CloudControllerManagerOptions, error) {
return NewCloudControllerManagerOptionsWithProviderDefaults(ProviderDefaults{})
}
// NewCloudControllerManagerOptionsWithProviderDefaults creates a new
// ExternalCMServer with a default config, but allows the cloud provider to
// override a select number of default option values.
func NewCloudControllerManagerOptionsWithProviderDefaults(defaults ProviderDefaults) (*CloudControllerManagerOptions, error) {
componentConfig, err := NewDefaultComponentConfig()
if err != nil {
return nil, err
}
s := CloudControllerManagerOptions{
Generic: cmoptions.NewGenericControllerManagerConfigurationOptions(&componentConfig.Generic),
KubeCloudShared: NewKubeCloudSharedOptions(&componentConfig.KubeCloudShared),
NodeController: &NodeControllerOptions{
NodeControllerConfiguration: &componentConfig.NodeController,
},
ServiceController: &ServiceControllerOptions{
ServiceControllerConfiguration: &componentConfig.ServiceController,
},
SecureServing: apiserveroptions.NewSecureServingOptions().WithLoopback(),
Webhook: NewWebhookOptions(),
WebhookServing: NewWebhookServingOptions(defaults),
Authentication: apiserveroptions.NewDelegatingAuthenticationOptions(),
Authorization: apiserveroptions.NewDelegatingAuthorizationOptions(),
NodeStatusUpdateFrequency: componentConfig.NodeStatusUpdateFrequency,
}
s.Authentication.RemoteKubeConfigFileOptional = true
s.Authorization.RemoteKubeConfigFileOptional = true
// Set the PairName but leave certificate directory blank to generate in-memory by default
s.SecureServing.ServerCert.CertDirectory = ""
s.SecureServing.ServerCert.PairName = "cloud-controller-manager"
s.SecureServing.BindPort = cloudprovider.CloudControllerManagerPort
s.Generic.LeaderElection.ResourceName = "cloud-controller-manager"
s.Generic.LeaderElection.ResourceNamespace = "kube-system"
return &s, nil
}
// NewDefaultComponentConfig returns cloud-controller manager configuration object.
func NewDefaultComponentConfig() (*ccmconfig.CloudControllerManagerConfiguration, error) {
versioned := &ccmconfigv1alpha1.CloudControllerManagerConfiguration{}
ccmconfigscheme.Scheme.Default(versioned)
internal := &ccmconfig.CloudControllerManagerConfiguration{}
if err := ccmconfigscheme.Scheme.Convert(versioned, internal, nil); err != nil {
return nil, err
}
return internal, nil
}
// Flags returns flags for a specific CloudController by section name
func (o *CloudControllerManagerOptions) Flags(allControllers []string, disabledByDefaultControllers []string, controllerAliases map[string]string, allWebhooks, disabledByDefaultWebhooks []string) cliflag.NamedFlagSets {
fss := cliflag.NamedFlagSets{}
o.Generic.AddFlags(&fss, allControllers, disabledByDefaultControllers, controllerAliases)
o.KubeCloudShared.AddFlags(fss.FlagSet("generic"))
o.NodeController.AddFlags(fss.FlagSet(names.CloudNodeController))
o.ServiceController.AddFlags(fss.FlagSet(names.ServiceLBController))
if o.Webhook != nil {
o.Webhook.AddFlags(fss.FlagSet("webhook"), allWebhooks, disabledByDefaultWebhooks)
}
if o.WebhookServing != nil {
o.WebhookServing.AddFlags(fss.FlagSet("webhook serving"))
}
o.SecureServing.AddFlags(fss.FlagSet("secure serving"))
o.Authentication.AddFlags(fss.FlagSet("authentication"))
o.Authorization.AddFlags(fss.FlagSet("authorization"))
fs := fss.FlagSet("misc")
fs.StringVar(&o.Master, "master", o.Master, "The address of the Kubernetes API server (overrides any value in kubeconfig).")
fs.StringVar(&o.Generic.ClientConnection.Kubeconfig, "kubeconfig", o.Generic.ClientConnection.Kubeconfig, "Path to kubeconfig file with authorization and master location information (the master location can be overridden by the master flag).")
fs.DurationVar(&o.NodeStatusUpdateFrequency.Duration, "node-status-update-frequency", o.NodeStatusUpdateFrequency.Duration, "Specifies how often the controller updates nodes' status.")
utilfeature.DefaultMutableFeatureGate.AddFlag(fss.FlagSet("generic"))
return fss
}
// ApplyTo fills up cloud controller manager config with options.
func (o *CloudControllerManagerOptions) ApplyTo(c *config.Config, allControllers []string, disabledByDefaultControllers []string, controllerAliases map[string]string, userAgent string) error {
var err error
// Build kubeconfig first to so that if it fails, it doesn't cause leaking
// goroutines (started from initializing secure serving - which underneath
// creates a queue which in its constructor starts a goroutine).
c.Kubeconfig, err = clientcmd.BuildConfigFromFlags(o.Master, o.Generic.ClientConnection.Kubeconfig)
if err != nil {
return err
}
c.Kubeconfig.DisableCompression = true
c.Kubeconfig.ContentConfig.AcceptContentTypes = o.Generic.ClientConnection.AcceptContentTypes
c.Kubeconfig.ContentConfig.ContentType = o.Generic.ClientConnection.ContentType
c.Kubeconfig.QPS = o.Generic.ClientConnection.QPS
c.Kubeconfig.Burst = int(o.Generic.ClientConnection.Burst)
if err = o.Generic.ApplyTo(&c.ComponentConfig.Generic, allControllers, disabledByDefaultControllers, controllerAliases); err != nil {
return err
}
if err = o.KubeCloudShared.ApplyTo(&c.ComponentConfig.KubeCloudShared); err != nil {
return err
}
if err = o.ServiceController.ApplyTo(&c.ComponentConfig.ServiceController); err != nil {
return err
}
if o.Webhook != nil {
if err = o.Webhook.ApplyTo(&c.ComponentConfig.Webhook); err != nil {
return err
}
}
if o.WebhookServing != nil {
if err = o.WebhookServing.ApplyTo(&c.WebhookSecureServing, c.ComponentConfig.Webhook); err != nil {
return err
}
}
if err = o.SecureServing.ApplyTo(&c.SecureServing, &c.LoopbackClientConfig); err != nil {
return err
}
if o.SecureServing.BindPort != 0 || o.SecureServing.Listener != nil {
if err = o.Authentication.ApplyTo(&c.Authentication, c.SecureServing, nil); err != nil {
return err
}
if err = o.Authorization.ApplyTo(&c.Authorization); err != nil {
return err
}
}
c.Client, err = clientset.NewForConfig(restclient.AddUserAgent(c.Kubeconfig, userAgent))
if err != nil {
return err
}
c.EventBroadcaster = record.NewBroadcaster(record.WithContext(context.TODO())) // TODO: move broadcaster construction to a place where there is a proper context.
c.EventRecorder = c.EventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: userAgent})
rootClientBuilder := clientbuilder.SimpleControllerClientBuilder{
ClientConfig: c.Kubeconfig,
}
if c.ComponentConfig.KubeCloudShared.UseServiceAccountCredentials {
c.ClientBuilder = clientbuilder.NewDynamicClientBuilder(
restclient.AnonymousClientConfig(c.Kubeconfig),
c.Client.CoreV1(),
metav1.NamespaceSystem)
} else {
c.ClientBuilder = rootClientBuilder
}
c.VersionedClient = rootClientBuilder.ClientOrDie("shared-informers")
c.SharedInformers = informers.NewSharedInformerFactory(c.VersionedClient, resyncPeriod(c)())
// sync back to component config
// TODO: find more elegant way than syncing back the values.
c.ComponentConfig.NodeStatusUpdateFrequency = o.NodeStatusUpdateFrequency
c.ComponentConfig.NodeController.ConcurrentNodeSyncs = o.NodeController.ConcurrentNodeSyncs
return nil
}
// Validate is used to validate config before launching the cloud controller manager
func (o *CloudControllerManagerOptions) Validate(allControllers []string, disabledByDefaultControllers []string, controllerAliases map[string]string, allWebhooks, disabledByDefaultWebhooks []string) error {
errors := []error{}
errors = append(errors, o.Generic.Validate(allControllers, disabledByDefaultControllers, controllerAliases)...)
errors = append(errors, o.KubeCloudShared.Validate()...)
errors = append(errors, o.ServiceController.Validate()...)
errors = append(errors, o.SecureServing.Validate()...)
errors = append(errors, o.Authentication.Validate()...)
errors = append(errors, o.Authorization.Validate()...)
if o.Webhook != nil {
errors = append(errors, o.Webhook.Validate(allWebhooks, disabledByDefaultWebhooks)...)
}
if o.WebhookServing != nil {
errors = append(errors, o.WebhookServing.Validate()...)
if o.WebhookServing.BindPort == o.SecureServing.BindPort && o.WebhookServing.BindPort != 0 {
errors = append(errors, fmt.Errorf("--webhook-secure-port cannot be the same value as --secure-port"))
}
}
if len(o.KubeCloudShared.CloudProvider.Name) == 0 {
errors = append(errors, fmt.Errorf("--cloud-provider cannot be empty"))
}
return utilerrors.NewAggregate(errors)
}
// resyncPeriod computes the time interval a shared informer waits before resyncing with the api server
func resyncPeriod(c *config.Config) func() time.Duration {
return func() time.Duration {
factor := rand.Float64() + 1
return time.Duration(float64(c.ComponentConfig.Generic.MinResyncPeriod.Nanoseconds()) * factor)
}
}
// Config return a cloud controller manager config objective
func (o *CloudControllerManagerOptions) Config(allControllers []string, disabledByDefaultControllers []string, controllerAliases map[string]string, allWebhooks, disabledByDefaultWebhooks []string) (*config.Config, error) {
if err := o.Validate(allControllers, disabledByDefaultControllers, controllerAliases, allWebhooks, disabledByDefaultWebhooks); err != nil {
return nil, err
}
if err := o.SecureServing.MaybeDefaultWithSelfSignedCerts("localhost", nil, []net.IP{netutils.ParseIPSloppy("127.0.0.1")}); err != nil {
return nil, fmt.Errorf("error creating self-signed certificates: %v", err)
}
if o.WebhookServing != nil {
if err := o.WebhookServing.MaybeDefaultWithSelfSignedCerts("localhost", nil, []net.IP{netutils.ParseIPSloppy("127.0.0.1")}); err != nil {
return nil, fmt.Errorf("error creating self-signed certificates for webhook: %v", err)
}
}
c := &config.Config{}
if err := o.ApplyTo(c, allControllers, disabledByDefaultControllers, controllerAliases, CloudControllerManagerUserAgent); err != nil {
return nil, err
}
return c, nil
}

View File

@ -0,0 +1,57 @@
/*
Copyright 2018 The Kubernetes 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.
*/
package options
import (
"github.com/spf13/pflag"
serviceconfig "k8s.io/cloud-provider/controllers/service/config"
)
// ServiceControllerOptions holds the ServiceController options.
type ServiceControllerOptions struct {
*serviceconfig.ServiceControllerConfiguration
}
// AddFlags adds flags related to ServiceController for controller manager to the specified FlagSet.
func (o *ServiceControllerOptions) AddFlags(fs *pflag.FlagSet) {
if o == nil {
return
}
fs.Int32Var(&o.ConcurrentServiceSyncs, "concurrent-service-syncs", o.ConcurrentServiceSyncs, "The number of services that are allowed to sync concurrently. Larger number = more responsive service management, but more CPU (and network) load")
}
// ApplyTo fills up ServiceController config with options.
func (o *ServiceControllerOptions) ApplyTo(cfg *serviceconfig.ServiceControllerConfiguration) error {
if o == nil {
return nil
}
cfg.ConcurrentServiceSyncs = o.ConcurrentServiceSyncs
return nil
}
// Validate checks validation of ServiceControllerOptions.
func (o *ServiceControllerOptions) Validate() []error {
if o == nil {
return nil
}
errs := []error{}
return errs
}

210
e2e/vendor/k8s.io/cloud-provider/options/webhook.go generated vendored Normal file
View File

@ -0,0 +1,210 @@
/*
Copyright 2022 The Kubernetes 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.
*/
package options
import (
"context"
"fmt"
"net"
"strconv"
"strings"
"github.com/spf13/pflag"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apiserver/pkg/server"
"k8s.io/apiserver/pkg/server/dynamiccertificates"
apiserveroptions "k8s.io/apiserver/pkg/server/options"
"k8s.io/cloud-provider/config"
netutils "k8s.io/utils/net"
)
const (
CloudControllerManagerWebhookPort = 10260
)
type WebhookOptions struct {
// Webhooks is the list of webhook names that should be enabled or disabled
Webhooks []string
}
func NewWebhookOptions() *WebhookOptions {
o := &WebhookOptions{}
return o
}
func (o *WebhookOptions) AddFlags(fs *pflag.FlagSet, allWebhooks, disabledByDefaultWebhooks []string) {
fs.StringSliceVar(&o.Webhooks, "webhooks", o.Webhooks, fmt.Sprintf(""+
"A list of webhooks to enable. '*' enables all on-by-default webhooks, 'foo' enables the webhook "+
"named 'foo', '-foo' disables the webhook named 'foo'.\nAll webhooks: %s\nDisabled-by-default webhooks: %s",
strings.Join(allWebhooks, ", "), strings.Join(disabledByDefaultWebhooks, ", ")))
}
func (o *WebhookOptions) Validate(allWebhooks, disabledByDefaultWebhooks []string) []error {
allErrors := []error{}
allWebhooksSet := sets.NewString(allWebhooks...)
toValidate := sets.NewString(o.Webhooks...)
toValidate.Insert(disabledByDefaultWebhooks...)
for _, webhook := range toValidate.List() {
if webhook == "*" {
continue
}
webhook = strings.TrimPrefix(webhook, "-")
if !allWebhooksSet.Has(webhook) {
allErrors = append(allErrors, fmt.Errorf("%q is not in the list of known webhooks", webhook))
}
}
return allErrors
}
func (o *WebhookOptions) ApplyTo(cfg *config.WebhookConfiguration) error {
if o == nil {
return nil
}
cfg.Webhooks = o.Webhooks
return nil
}
type WebhookServingOptions struct {
*apiserveroptions.SecureServingOptions
}
func NewWebhookServingOptions(defaults ProviderDefaults) *WebhookServingOptions {
var (
bindAddress net.IP
bindPort int
)
if defaults.WebhookBindAddress != nil {
bindAddress = *defaults.WebhookBindAddress
} else {
bindAddress = netutils.ParseIPSloppy("0.0.0.0")
}
if defaults.WebhookBindPort != nil {
bindPort = *defaults.WebhookBindPort
} else {
bindPort = CloudControllerManagerWebhookPort
}
return &WebhookServingOptions{
SecureServingOptions: &apiserveroptions.SecureServingOptions{
BindAddress: bindAddress,
BindPort: bindPort,
ServerCert: apiserveroptions.GeneratableKeyCert{
CertDirectory: "",
PairName: "cloud-controller-manager-webhook",
},
},
}
}
func (o *WebhookServingOptions) AddFlags(fs *pflag.FlagSet) {
fs.IPVar(&o.BindAddress, "webhook-bind-address", o.BindAddress, ""+
"The IP address on which to listen for the --webhook-secure-port port. The "+
"associated interface(s) must be reachable by the rest of the cluster, and by CLI/web "+
fmt.Sprintf("clients. If set to an unspecified address (0.0.0.0 or ::), all interfaces will be used. If unset, defaults to %v.", o.BindAddress))
fs.IntVar(&o.BindPort, "webhook-secure-port", o.BindPort, "Secure port to serve cloud provider webhooks. If 0, don't serve webhooks at all.")
fs.StringVar(&o.ServerCert.CertDirectory, "webhook-cert-dir", o.ServerCert.CertDirectory, ""+
"The directory where the TLS certs are located. "+
"If --tls-cert-file and --tls-private-key-file are provided, this flag will be ignored.")
fs.StringVar(&o.ServerCert.CertKey.CertFile, "webhook-tls-cert-file", o.ServerCert.CertKey.CertFile, ""+
"File containing the default x509 Certificate for HTTPS. (CA cert, if any, concatenated "+
"after server cert). If HTTPS serving is enabled, and --tls-cert-file and "+
"--tls-private-key-file are not provided, a self-signed certificate and key "+
"are generated for the public address and saved to the directory specified by --cert-dir.")
fs.StringVar(&o.ServerCert.CertKey.KeyFile, "webhook-tls-private-key-file", o.ServerCert.CertKey.KeyFile,
"File containing the default x509 private key matching --tls-cert-file.")
}
func (o *WebhookServingOptions) Validate() []error {
allErrors := []error{}
if o.BindPort < 0 || o.BindPort > 65535 {
allErrors = append(allErrors, fmt.Errorf("--webhook-secure-port %v must be between 0 and 65535, inclusive. A value of 0 disables the webhook endpoint entirely.", o.BindPort))
}
if (len(o.ServerCert.CertKey.CertFile) != 0 || len(o.ServerCert.CertKey.KeyFile) != 0) && o.ServerCert.GeneratedCert != nil {
allErrors = append(allErrors, fmt.Errorf("cert/key file and in-memory certificate cannot both be set"))
}
return allErrors
}
func (o *WebhookServingOptions) ApplyTo(cfg **server.SecureServingInfo, webhookCfg config.WebhookConfiguration) error {
if o == nil {
return nil
}
if o.BindPort <= 0 {
return nil
}
// no need to bind to the address if there are no webhook enabled.
if len(webhookCfg.Webhooks) == 0 {
return nil
}
var err error
var listener net.Listener
addr := net.JoinHostPort(o.BindAddress.String(), strconv.Itoa(o.BindPort))
l := net.ListenConfig{}
listener, o.BindPort, err = createListener(addr, l)
if err != nil {
return fmt.Errorf("failed to create listener: %v", err)
}
*cfg = &server.SecureServingInfo{
Listener: listener,
}
serverCertFile, serverKeyFile := o.ServerCert.CertKey.CertFile, o.ServerCert.CertKey.KeyFile
if len(serverCertFile) != 0 || len(serverKeyFile) != 0 {
var err error
(*cfg).Cert, err = dynamiccertificates.NewDynamicServingContentFromFiles("serving-cert", serverCertFile, serverKeyFile)
if err != nil {
return err
}
} else if o.ServerCert.GeneratedCert != nil {
(*cfg).Cert = o.ServerCert.GeneratedCert
}
return nil
}
func createListener(addr string, config net.ListenConfig) (net.Listener, int, error) {
ln, err := config.Listen(context.TODO(), "tcp", addr)
if err != nil {
return nil, 0, fmt.Errorf("failed to listen on %v: %v", addr, err)
}
// get port
tcpAddr, ok := ln.Addr().(*net.TCPAddr)
if !ok {
ln.Close()
return nil, 0, fmt.Errorf("invalid listen address: %q", ln.Addr().String())
}
return ln, tcpAddr.Port, nil
}