/
kube-apiserver.go
395 lines (355 loc) · 13.6 KB
/
kube-apiserver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
/*
Copyright © 2021 MicroShift Contributors
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 controllers
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net"
"os"
"path/filepath"
"strconv"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/klog/v2"
kubeapiserver "k8s.io/kubernetes/cmd/kube-apiserver/app"
hostassignmentv1 "k8s.io/kubernetes/openshift-kube-apiserver/admission/route/apis/hostassignment/v1"
"sigs.k8s.io/yaml"
configv1 "github.com/openshift/api/config/v1"
kubecontrolplanev1 "github.com/openshift/api/kubecontrolplane/v1"
"github.com/openshift/library-go/pkg/crypto"
"github.com/openshift/library-go/pkg/operator/resource/resourcemerge"
embedded "github.com/openshift/microshift/assets"
"github.com/openshift/microshift/pkg/config"
"github.com/openshift/microshift/pkg/config/apiserver"
"github.com/openshift/microshift/pkg/util"
"github.com/openshift/microshift/pkg/util/cryptomaterial"
)
const (
kubeAPIStartupTimeout = 60
)
var (
baseKubeAPIServerConfigs = [][]byte{
// todo: a nice way to generate the baseline kas config for microshift
embedded.MustAsset("controllers/kube-apiserver/defaultconfig.yaml"),
embedded.MustAsset("controllers/kube-apiserver/config-overrides.yaml"),
}
)
var fixedTLSProfile *configv1.TLSProfileSpec
func init() {
var ok bool
fixedTLSProfile, ok = configv1.TLSProfiles[configv1.TLSProfileIntermediateType]
if !ok {
panic("lookup of intermediate tls profile failed")
}
}
type KubeAPIServer struct {
kasConfigBytes []byte
verbosity int
configureErr error // todo: report configuration errors immediately
masterURL string
servingCAPath string
advertiseAddress string
}
func NewKubeAPIServer(cfg *config.Config) *KubeAPIServer {
s := &KubeAPIServer{}
if err := s.configure(cfg); err != nil {
s.configureErr = err
}
return s
}
func (s *KubeAPIServer) Name() string { return "kube-apiserver" }
func (s *KubeAPIServer) Dependencies() []string { return []string{"etcd", "network-configuration"} }
func (s *KubeAPIServer) configure(cfg *config.Config) error {
s.verbosity = cfg.GetVerbosity()
certsDir := cryptomaterial.CertsDirectory(config.DataDir)
kubeCSRSignerDir := cryptomaterial.CSRSignerCertDir(certsDir)
kubeletClientDir := cryptomaterial.KubeAPIServerToKubeletClientCertDir(certsDir)
clientCABundlePath := cryptomaterial.TotalClientCABundlePath(certsDir)
aggregatorCAPath := cryptomaterial.CACertPath(cryptomaterial.AggregatorSignerDir(certsDir))
aggregatorClientCertDir := cryptomaterial.AggregatorClientCertDir(certsDir)
etcdClientCertDir := cryptomaterial.EtcdAPIServerClientCertDir(certsDir)
serviceNetworkServingCertDir := cryptomaterial.KubeAPIServerServiceNetworkServingCertDir(certsDir)
servingCert := cryptomaterial.ServingCertPath(serviceNetworkServingCertDir)
servingKey := cryptomaterial.ServingKeyPath(serviceNetworkServingCertDir)
if err := s.configureAuditPolicy(cfg); err != nil {
return fmt.Errorf("failed to configure kube-apiserver audit policy: %w", err)
}
s.masterURL = cfg.ApiServer.URL
s.servingCAPath = cryptomaterial.ServiceAccountTokenCABundlePath(certsDir)
s.advertiseAddress = cfg.ApiServer.AdvertiseAddress
namedCerts := []configv1.NamedCertificate{
{
CertInfo: configv1.CertInfo{
CertFile: cryptomaterial.ServingCertPath(cryptomaterial.KubeAPIServerExternalServingCertDir(certsDir)),
KeyFile: cryptomaterial.ServingKeyPath(cryptomaterial.KubeAPIServerExternalServingCertDir(certsDir)),
},
},
{
CertInfo: configv1.CertInfo{
CertFile: cryptomaterial.ServingCertPath(cryptomaterial.KubeAPIServerLocalhostServingCertDir(certsDir)),
KeyFile: cryptomaterial.ServingKeyPath(cryptomaterial.KubeAPIServerLocalhostServingCertDir(certsDir)),
},
},
{
CertInfo: configv1.CertInfo{
CertFile: servingCert,
KeyFile: servingKey,
},
},
}
if len(cfg.ApiServer.NamedCertificates) > 0 {
for _, namedCertsCfg := range cfg.ApiServer.NamedCertificates {
//Validate the cert is non-destructive
certAllowed, err := util.IsCertAllowed(cfg.ApiServer.AdvertiseAddress, cfg.Network.ClusterNetwork, cfg.Network.ServiceNetwork, namedCertsCfg.CertPath, namedCertsCfg.Names)
if err != nil {
klog.Warningf("Failed to read NamedCertificate from %s - ignoring: %v", namedCertsCfg.CertPath, err)
continue
}
if !certAllowed {
klog.Warningf("Certificate %v is not allowed - ignoring", namedCertsCfg)
continue
}
cert := []configv1.NamedCertificate{
{
Names: namedCertsCfg.Names,
CertInfo: configv1.CertInfo{
CertFile: namedCertsCfg.CertPath,
KeyFile: namedCertsCfg.KeyPath,
},
},
}
// prepend the named certs to the beginning of the slice (so it will take precedence for same SNI)
namedCerts = append(cert, namedCerts...)
}
}
overrides := &kubecontrolplanev1.KubeAPIServerConfig{
APIServerArguments: map[string]kubecontrolplanev1.Arguments{
"advertise-address": {s.advertiseAddress},
"audit-policy-file": {filepath.Join(config.DataDir, "/resources/kube-apiserver-audit-policies/default.yaml")},
"audit-log-maxage": {strconv.Itoa(cfg.ApiServer.AuditLog.MaxFileAge)},
"audit-log-maxbackup": {strconv.Itoa(cfg.ApiServer.AuditLog.MaxFiles)},
"audit-log-maxsize": {strconv.Itoa(cfg.ApiServer.AuditLog.MaxFileSize)},
"client-ca-file": {clientCABundlePath},
"etcd-cafile": {cryptomaterial.CACertPath(cryptomaterial.EtcdSignerDir(certsDir))},
"etcd-certfile": {cryptomaterial.ClientCertPath(etcdClientCertDir)},
"etcd-keyfile": {cryptomaterial.ClientKeyPath(etcdClientCertDir)},
"etcd-servers": {
"https://localhost:2379",
},
"kubelet-certificate-authority": {cryptomaterial.CABundlePath(kubeCSRSignerDir)},
"kubelet-client-certificate": {cryptomaterial.ClientCertPath(kubeletClientDir)},
"kubelet-client-key": {cryptomaterial.ClientKeyPath(kubeletClientDir)},
// MicroShift nodes expose these two types of addresses. In order to support having more than one
// node with the current approach (which is running a stand alone kubelet and share certificates
// with the master node) we need to use names only because of the way certificates are generated.
// The names are fed through the subjectAltNames configuration parameter, and using master node
// IP in the certificates when having more than one node is not possible due to apiserver SNI
// limitations. For this, we prefer using names and IPs as a fallback, supporting both single
// and multi node.
"kubelet-preferred-address-types": {"Hostname", "InternalIP"},
"proxy-client-cert-file": {cryptomaterial.ClientCertPath(aggregatorClientCertDir)},
"proxy-client-key-file": {cryptomaterial.ClientKeyPath(aggregatorClientCertDir)},
"requestheader-client-ca-file": {aggregatorCAPath},
"service-account-signing-key-file": {filepath.Join(config.DataDir, "/resources/kube-apiserver/secrets/service-account-key/service-account.key")},
"service-node-port-range": {cfg.Network.ServiceNodePortRange},
"tls-cert-file": {servingCert},
"tls-private-key-file": {servingKey},
"disable-admission-plugins": {
"authorization.openshift.io/RestrictSubjectBindings",
"authorization.openshift.io/ValidateRoleBindingRestriction",
"autoscaling.openshift.io/ManagementCPUsOverride",
"config.openshift.io/DenyDeleteClusterConfiguration",
"config.openshift.io/ValidateAPIServer",
"config.openshift.io/ValidateAuthentication",
"config.openshift.io/ValidateConsole",
"config.openshift.io/ValidateFeatureGate",
"config.openshift.io/ValidateImage",
"config.openshift.io/ValidateOAuth",
"config.openshift.io/ValidateProject",
"config.openshift.io/ValidateScheduler",
"image.openshift.io/ImagePolicy",
"quota.openshift.io/ClusterResourceQuota",
"quota.openshift.io/ValidateClusterResourceQuota",
},
"enable-admission-plugins": {},
"send-retry-after-while-not-ready-once": {"true"},
"shutdown-delay-duration": {"5s"},
},
GenericAPIServerConfig: configv1.GenericAPIServerConfig{
AdmissionConfig: configv1.AdmissionConfig{
PluginConfig: map[string]configv1.AdmissionPluginConfig{
"route.openshift.io/RouteHostAssignment": {
Configuration: runtime.RawExtension{
Object: &hostassignmentv1.HostAssignmentAdmissionConfig{
TypeMeta: metav1.TypeMeta{
APIVersion: "route.openshift.io/v1",
Kind: "HostAssignmentAdmissionConfig",
},
Domain: "apps." + cfg.DNS.BaseDomain,
},
},
},
},
},
// from cluster-kube-apiserver-operator
CORSAllowedOrigins: []string{
`//127\.0\.0\.1(:|$)`,
`//localhost(:|$)`,
},
ServingInfo: configv1.HTTPServingInfo{
ServingInfo: configv1.ServingInfo{
BindAddress: net.JoinHostPort("0.0.0.0", strconv.Itoa(cfg.ApiServer.Port)),
MinTLSVersion: string(fixedTLSProfile.MinTLSVersion),
CipherSuites: crypto.OpenSSLToIANACipherSuites(fixedTLSProfile.Ciphers),
NamedCertificates: namedCerts,
},
},
},
ServiceAccountPublicKeyFiles: []string{
filepath.Join(config.DataDir, "/resources/kube-apiserver/secrets/service-account-key/service-account.pub"),
},
ServicesSubnet: cfg.Network.ServiceNetwork[0],
ServicesNodePortRange: cfg.Network.ServiceNodePortRange,
}
overridesBytes, err := json.Marshal(overrides)
if err != nil {
return err
}
s.kasConfigBytes, err = resourcemerge.MergePrunedProcessConfig(
&kubecontrolplanev1.KubeAPIServerConfig{},
map[string]resourcemerge.MergeFunc{
".apiServerArguments.enable-admission-plugins": func(dst interface{}, src interface{}, currentPath string) (interface{}, error) {
var result []interface{}
for _, existing := range dst.([]interface{}) {
drop := false
for _, disabled := range overrides.APIServerArguments["disable-admission-plugins"] {
if existing == disabled {
drop = true
}
}
if !drop {
result = append(result, existing)
}
}
result = append(result, src.([]interface{})...)
return result, nil
},
},
append(baseKubeAPIServerConfigs, overridesBytes)...,
)
if err != nil {
return err
}
return nil
}
func (s *KubeAPIServer) configureAuditPolicy(cfg *config.Config) error {
p, err := apiserver.GetPolicy(cfg.ApiServer.AuditLog.Profile)
if err != nil {
return err
}
path := filepath.Join(config.DataDir, "resources", "kube-apiserver-audit-policies", "default.yaml")
if err := os.MkdirAll(filepath.Dir(path), os.FileMode(0700)); err != nil {
return err
}
data, err := yaml.Marshal(p)
if err != nil {
return err
}
return os.WriteFile(path, data, 0400)
}
func (s *KubeAPIServer) Run(ctx context.Context, ready chan<- struct{}, stopped chan<- struct{}) error {
if s.configureErr != nil {
return fmt.Errorf("configuration failed: %w", s.configureErr)
}
defer close(stopped)
errorChannel := make(chan error, 1)
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// run readiness check
go func() {
err := wait.PollUntilContextTimeout(ctx, time.Second, kubeAPIStartupTimeout*time.Second, true, func(ctx context.Context) (bool, error) {
restConfig, err := clientcmd.BuildConfigFromFlags(s.masterURL, "")
if err != nil {
return false, err
}
if err := rest.SetKubernetesDefaults(restConfig); err != nil {
return false, err
}
restConfig.NegotiatedSerializer = serializer.NewCodecFactory(runtime.NewScheme())
restConfig.CAFile = s.servingCAPath
restClient, err := rest.UnversionedRESTClientFor(restConfig)
if err != nil {
return false, err
}
var status int
if err := restClient.Get().AbsPath("/readyz").Do(ctx).StatusCode(&status).Error(); err != nil {
klog.Infof("%q not yet ready: %v", s.Name(), err)
return false, nil
}
if status < 200 || status >= 400 {
klog.Infof("%q not yet ready: received http status %d", s.Name(), status)
return false, nil
}
return true, nil
})
if err != nil {
errorChannel <- fmt.Errorf("readiness check failed: %w", err)
cancel()
return
}
klog.Infof("%q is ready", s.Name())
close(ready)
}()
fd, err := os.CreateTemp("", "kube-apiserver-config-*.yaml")
if err != nil {
return err
}
defer func() {
err := os.Remove(fd.Name())
if err != nil {
klog.Warningf("failed to delete temporary kube-apiserver config file: %v", err)
}
}()
err = func() error {
defer fd.Close()
_, err = io.Copy(fd, bytes.NewBuffer(s.kasConfigBytes))
return err
}()
if err != nil {
return err
}
// audit logs go here
if err := os.MkdirAll("/var/log/kube-apiserver", 0700); err != nil {
return err
}
// Carrying a patch for NewAPIServerCommand to use cmd.Context().Done() as the stop channel
// instead of the channel returned by SetupSignalHandler, which expects to be called at most
// once in a process.
cmd := kubeapiserver.NewAPIServerCommand()
cmd.SetArgs([]string{
"--openshift-config", fd.Name(),
"-v", strconv.Itoa(s.verbosity),
})
go func() {
errorChannel <- cmd.ExecuteContext(ctx)
}()
return <-errorChannel
}