| 1 |
/* |
| 2 |
Copyright 2017 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package options |
| 18 |
|
| 19 |
import ( |
| 20 |
"fmt" |
| 21 |
"strings" |
| 22 |
"time" |
| 23 |
|
| 24 |
"github.com/spf13/pflag" |
| 25 |
|
| 26 |
"k8s.io/apimachinery/pkg/runtime" |
| 27 |
utilruntime "k8s.io/apimachinery/pkg/util/runtime" |
| 28 |
"k8s.io/apimachinery/pkg/util/sets" |
| 29 |
utilwait "k8s.io/apimachinery/pkg/util/wait" |
| 30 |
"k8s.io/apiserver/pkg/admission" |
| 31 |
"k8s.io/apiserver/pkg/admission/initializer" |
| 32 |
admissionmetrics "k8s.io/apiserver/pkg/admission/metrics" |
| 33 |
"k8s.io/apiserver/pkg/admission/plugin/namespace/lifecycle" |
| 34 |
mutatingadmissionpolicy "k8s.io/apiserver/pkg/admission/plugin/policy/mutating" |
| 35 |
validatingadmissionpolicy "k8s.io/apiserver/pkg/admission/plugin/policy/validating" |
| 36 |
mutatingwebhook "k8s.io/apiserver/pkg/admission/plugin/webhook/mutating" |
| 37 |
validatingwebhook "k8s.io/apiserver/pkg/admission/plugin/webhook/validating" |
| 38 |
apiserverapi "k8s.io/apiserver/pkg/apis/apiserver" |
| 39 |
apiserverapiv1 "k8s.io/apiserver/pkg/apis/apiserver/v1" |
| 40 |
apiserverapiv1alpha1 "k8s.io/apiserver/pkg/apis/apiserver/v1alpha1" |
| 41 |
"k8s.io/apiserver/pkg/server" |
| 42 |
cacheddiscovery "k8s.io/client-go/discovery/cached/memory" |
| 43 |
"k8s.io/client-go/dynamic" |
| 44 |
"k8s.io/client-go/informers" |
| 45 |
"k8s.io/client-go/kubernetes" |
| 46 |
"k8s.io/client-go/restmapper" |
| 47 |
"k8s.io/component-base/featuregate" |
| 48 |
) |
| 49 |
|
| 50 |
var configScheme = runtime.NewScheme() |
| 51 |
|
| 52 |
func init() { |
| 53 |
utilruntime.Must(apiserverapi.AddToScheme(configScheme)) |
| 54 |
utilruntime.Must(apiserverapiv1alpha1.AddToScheme(configScheme)) |
| 55 |
utilruntime.Must(apiserverapiv1.AddToScheme(configScheme)) |
| 56 |
} |
| 57 |
|
| 58 |
// AdmissionOptions holds the admission options |
| 59 |
type AdmissionOptions struct { |
| 60 |
// RecommendedPluginOrder holds an ordered list of plugin names we recommend to use by default |
| 61 |
RecommendedPluginOrder []string |
| 62 |
// DefaultOffPlugins is a set of plugin names that is disabled by default |
| 63 |
DefaultOffPlugins sets.Set[string] |
| 64 |
|
| 65 |
// EnablePlugins indicates plugins to be enabled passed through `--enable-admission-plugins`. |
| 66 |
EnablePlugins []string |
| 67 |
// DisablePlugins indicates plugins to be disabled passed through `--disable-admission-plugins`. |
| 68 |
DisablePlugins []string |
| 69 |
// ConfigFile is the file path with admission control configuration. |
| 70 |
ConfigFile string |
| 71 |
// Plugins contains all registered plugins. |
| 72 |
Plugins *admission.Plugins |
| 73 |
// Decorators is a list of admission decorator to wrap around the admission plugins |
| 74 |
Decorators admission.Decorators |
| 75 |
} |
| 76 |
|
| 77 |
// NewAdmissionOptions creates a new instance of AdmissionOptions |
| 78 |
// Note: |
| 79 |
// |
| 80 |
// In addition it calls RegisterAllAdmissionPlugins to register |
| 81 |
// all generic admission plugins. |
| 82 |
// |
| 83 |
// Provides the list of RecommendedPluginOrder that holds sane values |
| 84 |
// that can be used by servers that don't care about admission chain. |
| 85 |
// Servers that do care can overwrite/append that field after creation. |
| 86 |
func NewAdmissionOptions() *AdmissionOptions { |
| 87 |
options := &AdmissionOptions{ |
| 88 |
Plugins: admission.NewPlugins(), |
| 89 |
Decorators: admission.Decorators{admission.DecoratorFunc(admissionmetrics.WithControllerMetrics)}, |
| 90 |
// This list is mix of mutating admission plugins and validating |
| 91 |
// admission plugins. The apiserver always runs the validating ones |
| 92 |
// after all the mutating ones, so their relative order in this list |
| 93 |
// doesn't matter. |
| 94 |
RecommendedPluginOrder: []string{lifecycle.PluginName, mutatingadmissionpolicy.PluginName, mutatingwebhook.PluginName, validatingadmissionpolicy.PluginName, validatingwebhook.PluginName}, |
| 95 |
DefaultOffPlugins: sets.Set[string]{}, |
| 96 |
} |
| 97 |
server.RegisterAllAdmissionPlugins(options.Plugins) |
| 98 |
return options |
| 99 |
} |
| 100 |
|
| 101 |
// AddFlags adds flags related to admission for a specific APIServer to the specified FlagSet |
| 102 |
func (a *AdmissionOptions) AddFlags(fs *pflag.FlagSet) { |
| 103 |
if a == nil { |
| 104 |
return |
| 105 |
} |
| 106 |
|
| 107 |
fs.StringSliceVar(&a.EnablePlugins, "enable-admission-plugins", a.EnablePlugins, ""+ |
| 108 |
"admission plugins that should be enabled in addition to default enabled ones ("+ |
| 109 |
strings.Join(a.defaultEnabledPluginNames(), ", ")+"). "+ |
| 110 |
"Comma-delimited list of admission plugins: "+strings.Join(a.Plugins.Registered(), ", ")+". "+ |
| 111 |
"The order of plugins in this flag does not matter.") |
| 112 |
fs.StringSliceVar(&a.DisablePlugins, "disable-admission-plugins", a.DisablePlugins, ""+ |
| 113 |
"admission plugins that should be disabled although they are in the default enabled plugins list ("+ |
| 114 |
strings.Join(a.defaultEnabledPluginNames(), ", ")+"). "+ |
| 115 |
"Comma-delimited list of admission plugins: "+strings.Join(a.Plugins.Registered(), ", ")+". "+ |
| 116 |
"The order of plugins in this flag does not matter.") |
| 117 |
fs.StringVar(&a.ConfigFile, "admission-control-config-file", a.ConfigFile, |
| 118 |
"File with admission control configuration.") |
| 119 |
} |
| 120 |
|
| 121 |
// ApplyTo adds the admission chain to the server configuration. |
| 122 |
// In case admission plugin names were not provided by a cluster-admin they will be prepared from the recommended/default values. |
| 123 |
// In addition the method lazily initializes a generic plugin that is appended to the list of pluginInitializers |
| 124 |
// note this method uses: |
| 125 |
// |
| 126 |
// genericconfig.Authorizer |
| 127 |
func (a *AdmissionOptions) ApplyTo( |
| 128 |
c *server.Config, |
| 129 |
informers informers.SharedInformerFactory, |
| 130 |
kubeClient kubernetes.Interface, |
| 131 |
dynamicClient dynamic.Interface, |
| 132 |
features featuregate.FeatureGate, |
| 133 |
pluginInitializers ...admission.PluginInitializer, |
| 134 |
) error { |
| 135 |
if a == nil { |
| 136 |
return nil |
| 137 |
} |
| 138 |
|
| 139 |
// Admission depends on CoreAPI to set SharedInformerFactory and ClientConfig. |
| 140 |
if informers == nil { |
| 141 |
return fmt.Errorf("admission depends on a Kubernetes core API shared informer, it cannot be nil") |
| 142 |
} |
| 143 |
if kubeClient == nil || dynamicClient == nil { |
| 144 |
return fmt.Errorf("admission depends on a Kubernetes core API client, it cannot be nil") |
| 145 |
} |
| 146 |
|
| 147 |
pluginNames := a.enabledPluginNames() |
| 148 |
|
| 149 |
pluginsConfigProvider, err := admission.ReadAdmissionConfiguration(pluginNames, a.ConfigFile, configScheme) |
| 150 |
if err != nil { |
| 151 |
return fmt.Errorf("failed to read plugin config: %v", err) |
| 152 |
} |
| 153 |
|
| 154 |
discoveryClient := cacheddiscovery.NewMemCacheClient(kubeClient.Discovery()) |
| 155 |
discoveryRESTMapper := restmapper.NewDeferredDiscoveryRESTMapper(discoveryClient) |
| 156 |
genericInitializer := initializer.New(kubeClient, dynamicClient, informers, c.Authorization.Authorizer, features, |
| 157 |
c.DrainedNotify(), discoveryRESTMapper) |
| 158 |
initializersChain := admission.PluginInitializers{genericInitializer} |
| 159 |
initializersChain = append(initializersChain, pluginInitializers...) |
| 160 |
|
| 161 |
admissionPostStartHook := func(hookContext server.PostStartHookContext) error { |
| 162 |
discoveryRESTMapper.Reset() |
| 163 |
go utilwait.Until(discoveryRESTMapper.Reset, 30*time.Second, hookContext.Done()) |
| 164 |
return nil |
| 165 |
} |
| 166 |
|
| 167 |
err = c.AddPostStartHook("start-apiserver-admission-initializer", admissionPostStartHook) |
| 168 |
if err != nil { |
| 169 |
return fmt.Errorf("failed to add post start hook for policy admission: %w", err) |
| 170 |
} |
| 171 |
|
| 172 |
admissionChain, err := a.Plugins.NewFromPlugins(pluginNames, pluginsConfigProvider, initializersChain, a.Decorators) |
| 173 |
if err != nil { |
| 174 |
return err |
| 175 |
} |
| 176 |
|
| 177 |
c.AdmissionControl = admissionmetrics.WithStepMetrics(admissionChain) |
| 178 |
return nil |
| 179 |
} |
| 180 |
|
| 181 |
// Validate verifies flags passed to AdmissionOptions. |
| 182 |
func (a *AdmissionOptions) Validate() []error { |
| 183 |
if a == nil { |
| 184 |
return nil |
| 185 |
} |
| 186 |
|
| 187 |
errs := []error{} |
| 188 |
|
| 189 |
registeredPlugins := sets.NewString(a.Plugins.Registered()...) |
| 190 |
for _, name := range a.EnablePlugins { |
| 191 |
if !registeredPlugins.Has(name) { |
| 192 |
errs = append(errs, fmt.Errorf("enable-admission-plugins plugin %q is unknown", name)) |
| 193 |
} |
| 194 |
} |
| 195 |
|
| 196 |
for _, name := range a.DisablePlugins { |
| 197 |
if !registeredPlugins.Has(name) { |
| 198 |
errs = append(errs, fmt.Errorf("disable-admission-plugins plugin %q is unknown", name)) |
| 199 |
} |
| 200 |
} |
| 201 |
|
| 202 |
enablePlugins := sets.NewString(a.EnablePlugins...) |
| 203 |
disablePlugins := sets.NewString(a.DisablePlugins...) |
| 204 |
if len(enablePlugins.Intersection(disablePlugins).List()) > 0 { |
| 205 |
errs = append(errs, fmt.Errorf("%v in enable-admission-plugins and disable-admission-plugins "+ |
| 206 |
"overlapped", enablePlugins.Intersection(disablePlugins).List())) |
| 207 |
} |
| 208 |
|
| 209 |
// Verify RecommendedPluginOrder. |
| 210 |
recommendPlugins := sets.NewString(a.RecommendedPluginOrder...) |
| 211 |
intersections := registeredPlugins.Intersection(recommendPlugins) |
| 212 |
if !intersections.Equal(recommendPlugins) { |
| 213 |
// Developer error, this should never run in. |
| 214 |
errs = append(errs, fmt.Errorf("plugins %v in RecommendedPluginOrder are not registered", |
| 215 |
recommendPlugins.Difference(intersections).List())) |
| 216 |
} |
| 217 |
if !intersections.Equal(registeredPlugins) { |
| 218 |
// Developer error, this should never run in. |
| 219 |
errs = append(errs, fmt.Errorf("plugins %v registered are not in RecommendedPluginOrder", |
| 220 |
registeredPlugins.Difference(intersections).List())) |
| 221 |
} |
| 222 |
|
| 223 |
return errs |
| 224 |
} |
| 225 |
|
| 226 |
// enabledPluginNames makes use of RecommendedPluginOrder, DefaultOffPlugins, |
| 227 |
// EnablePlugins, DisablePlugins fields |
| 228 |
// to prepare a list of ordered plugin names that are enabled. |
| 229 |
func (a *AdmissionOptions) enabledPluginNames() []string { |
| 230 |
allOffPlugins := append(sets.List[string](a.DefaultOffPlugins), a.DisablePlugins...) |
| 231 |
disabledPlugins := sets.NewString(allOffPlugins...) |
| 232 |
enabledPlugins := sets.NewString(a.EnablePlugins...) |
| 233 |
disabledPlugins = disabledPlugins.Difference(enabledPlugins) |
| 234 |
|
| 235 |
orderedPlugins := []string{} |
| 236 |
for _, plugin := range a.RecommendedPluginOrder { |
| 237 |
if !disabledPlugins.Has(plugin) { |
| 238 |
orderedPlugins = append(orderedPlugins, plugin) |
| 239 |
} |
| 240 |
} |
| 241 |
|
| 242 |
return orderedPlugins |
| 243 |
} |
| 244 |
|
| 245 |
// Return names of plugins which are enabled by default |
| 246 |
func (a *AdmissionOptions) defaultEnabledPluginNames() []string { |
| 247 |
defaultOnPluginNames := []string{} |
| 248 |
for _, pluginName := range a.RecommendedPluginOrder { |
| 249 |
if !a.DefaultOffPlugins.Has(pluginName) { |
| 250 |
defaultOnPluginNames = append(defaultOnPluginNames, pluginName) |
| 251 |
} |
| 252 |
} |
| 253 |
|
| 254 |
return defaultOnPluginNames |
| 255 |
} |