Skip to content

Commit

Permalink
refactor: split kubernetes/etcd resource generation into subresources
Browse files Browse the repository at this point in the history
Fixes #3062

There's no user-visible change in this PR.

It carefully separates generated secrets (e.g. certs) from source
secrets from the config (e.g. CAs), so that certs are generated on
config changes which actually affect cert input.

And same way separates etcd and Kubernetes PKI, so if etcd CA got
changed, only etcd certs will be regenerated.

This should have noticeable impact with RSA-based PKI as it reduces
number of times PKI gets generated.

Signed-off-by: Andrey Smirnov <smirnov.andrey@gmail.com>
  • Loading branch information
smira authored and talos-bot committed Feb 19, 2021
1 parent c2d1096 commit b914398
Show file tree
Hide file tree
Showing 14 changed files with 662 additions and 139 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ func (ctrl *KubeletStaticPodController) Run(ctx context.Context, r controller.Ru
return err
}

secrets := secretsResources.(*secrets.Kubernetes).Secrets()
secrets := secretsResources.(*secrets.Kubernetes).Certs()

bootstrapStatus, err := r.Get(ctx, v1alpha1.NewBootstrapStatus().Metadata())
if err != nil {
Expand Down
14 changes: 7 additions & 7 deletions internal/app/machined/pkg/controllers/k8s/manifest.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ func (ctrl *ManifestController) Run(ctx context.Context, r controller.Runtime, l
},
{
Namespace: secrets.NamespaceName,
Type: secrets.KubernetesType,
ID: pointer.ToString(secrets.KubernetesID),
Type: secrets.RootType,
ID: pointer.ToString(secrets.RootKubernetesID),
Kind: controller.DependencyWeak,
},
}); err != nil {
Expand Down Expand Up @@ -77,7 +77,7 @@ func (ctrl *ManifestController) Run(ctx context.Context, r controller.Runtime, l

config := configResource.(*config.K8sControlPlane).Manifests()

secretsResources, err := r.Get(ctx, resource.NewMetadata(secrets.NamespaceName, secrets.KubernetesType, secrets.KubernetesID, resource.VersionUndefined))
secretsResources, err := r.Get(ctx, resource.NewMetadata(secrets.NamespaceName, secrets.RootType, secrets.RootKubernetesID, resource.VersionUndefined))
if err != nil {
if state.IsNotFoundError(err) {
if err = ctrl.teardownAll(ctx, r); err != nil {
Expand All @@ -90,9 +90,9 @@ func (ctrl *ManifestController) Run(ctx context.Context, r controller.Runtime, l
return err
}

secrets := secretsResources.(*secrets.Kubernetes).Secrets()
secrets := secretsResources.(*secrets.Root).KubernetesSpec()

renderedManifests, err := ctrl.render(config, *secrets)
renderedManifests, err := ctrl.render(config, secrets)
if err != nil {
return err
}
Expand Down Expand Up @@ -137,11 +137,11 @@ type renderedManifest struct {
data []byte
}

func (ctrl *ManifestController) render(cfg config.K8sManifestsSpec, scrt secrets.KubernetesSpec) ([]renderedManifest, error) {
func (ctrl *ManifestController) render(cfg config.K8sManifestsSpec, scrt *secrets.RootKubernetesSpec) ([]renderedManifest, error) {
templateConfig := struct {
config.K8sManifestsSpec

Secrets secrets.KubernetesSpec
Secrets *secrets.RootKubernetesSpec
}{
K8sManifestsSpec: cfg,
Secrets: scrt,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ func (ctrl *ManifestApplyController) Run(ctx context.Context, r controller.Runti
return err
}

secrets := secretsResources.(*secrets.Kubernetes).Secrets()
secrets := secretsResources.(*secrets.Kubernetes).Certs()

bootstrapStatus, err := r.Get(ctx, v1alpha1.NewBootstrapStatus().Metadata())
if err != nil {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"path/filepath"
stdlibtemplate "text/template"

"github.com/AlekSi/pointer"
"github.com/talos-systems/crypto/x509"
"github.com/talos-systems/os-runtime/pkg/controller"
"github.com/talos-systems/os-runtime/pkg/resource"
Expand Down Expand Up @@ -42,9 +43,21 @@ func (ctrl *RenderSecretsStaticPodController) ManagedResources() (resource.Names
//nolint: gocyclo
func (ctrl *RenderSecretsStaticPodController) Run(ctx context.Context, r controller.Runtime, logger *log.Logger) error {
if err := r.UpdateDependencies([]controller.Dependency{
{
Namespace: secrets.NamespaceName,
Type: secrets.RootType,
Kind: controller.DependencyWeak,
},
{
Namespace: secrets.NamespaceName,
Type: secrets.KubernetesType,
ID: pointer.ToString(secrets.KubernetesID),
Kind: controller.DependencyWeak,
},
{
Namespace: secrets.NamespaceName,
Type: secrets.EtcdType,
ID: pointer.ToString(secrets.EtcdID),
Kind: controller.DependencyWeak,
},
}); err != nil {
Expand All @@ -67,9 +80,39 @@ func (ctrl *RenderSecretsStaticPodController) Run(ctx context.Context, r control
return fmt.Errorf("error getting secrets resource: %w", err)
}

secrets := secretsRes.(*secrets.Kubernetes).Secrets()
etcdRes, err := r.Get(ctx, resource.NewMetadata(secrets.NamespaceName, secrets.EtcdType, secrets.EtcdID, resource.VersionUndefined))
if err != nil {
if state.IsNotFoundError(err) {
continue
}

return fmt.Errorf("error getting secrets resource: %w", err)
}

rootEtcdRes, err := r.Get(ctx, resource.NewMetadata(secrets.NamespaceName, secrets.RootType, secrets.RootEtcdID, resource.VersionUndefined))
if err != nil {
if state.IsNotFoundError(err) {
continue
}

return fmt.Errorf("error getting secrets resource: %w", err)
}

rootK8sRes, err := r.Get(ctx, resource.NewMetadata(secrets.NamespaceName, secrets.RootType, secrets.RootKubernetesID, resource.VersionUndefined))
if err != nil {
if state.IsNotFoundError(err) {
continue
}

return fmt.Errorf("error getting secrets resource: %w", err)
}

rootEtcdSecrets := rootEtcdRes.(*secrets.Root).EtcdSpec()
rootK8sSecrets := rootK8sRes.(*secrets.Root).KubernetesSpec()
etcdSecrets := etcdRes.(*secrets.Etcd).Certs()
k8sSecrets := secretsRes.(*secrets.Kubernetes).Certs()

serviceAccountKey, err := secrets.ServiceAccount.GetKey()
serviceAccountKey, err := rootK8sSecrets.ServiceAccount.GetKey()
if err != nil {
return fmt.Errorf("error parsing service account key: %w", err)
}
Expand All @@ -96,25 +139,25 @@ func (ctrl *RenderSecretsStaticPodController) Run(ctx context.Context, r control
directory: constants.KubernetesAPIServerSecretsDir,
secrets: []secret{
{
getter: func() *x509.PEMEncodedCertificateAndKey { return secrets.EtcdCA },
getter: func() *x509.PEMEncodedCertificateAndKey { return rootEtcdSecrets.EtcdCA },
certFilename: "etcd-client-ca.crt",
},
{
getter: func() *x509.PEMEncodedCertificateAndKey { return secrets.EtcdPeer },
getter: func() *x509.PEMEncodedCertificateAndKey { return etcdSecrets.EtcdPeer },
certFilename: "etcd-client.crt",
keyFilename: "etcd-client.key",
},
{
getter: func() *x509.PEMEncodedCertificateAndKey { return secrets.CA },
getter: func() *x509.PEMEncodedCertificateAndKey { return rootK8sSecrets.CA },
certFilename: "ca.crt",
},
{
getter: func() *x509.PEMEncodedCertificateAndKey { return secrets.APIServer },
getter: func() *x509.PEMEncodedCertificateAndKey { return k8sSecrets.APIServer },
certFilename: "apiserver.crt",
keyFilename: "apiserver.key",
},
{
getter: func() *x509.PEMEncodedCertificateAndKey { return secrets.APIServerKubeletClient },
getter: func() *x509.PEMEncodedCertificateAndKey { return k8sSecrets.APIServerKubeletClient },
certFilename: "apiserver-kubelet-client.crt",
keyFilename: "apiserver-kubelet-client.key",
},
Expand All @@ -129,11 +172,11 @@ func (ctrl *RenderSecretsStaticPodController) Run(ctx context.Context, r control
keyFilename: "service-account.key",
},
{
getter: func() *x509.PEMEncodedCertificateAndKey { return secrets.AggregatorCA },
getter: func() *x509.PEMEncodedCertificateAndKey { return rootK8sSecrets.AggregatorCA },
certFilename: "aggregator-ca.crt",
},
{
getter: func() *x509.PEMEncodedCertificateAndKey { return secrets.FrontProxy },
getter: func() *x509.PEMEncodedCertificateAndKey { return k8sSecrets.FrontProxy },
certFilename: "front-proxy-client.crt",
keyFilename: "front-proxy-client.key",
},
Expand All @@ -154,7 +197,7 @@ func (ctrl *RenderSecretsStaticPodController) Run(ctx context.Context, r control
directory: constants.KubernetesControllerManagerSecretsDir,
secrets: []secret{
{
getter: func() *x509.PEMEncodedCertificateAndKey { return secrets.CA },
getter: func() *x509.PEMEncodedCertificateAndKey { return rootK8sSecrets.CA },
certFilename: "ca.crt",
keyFilename: "ca.key",
},
Expand All @@ -171,7 +214,7 @@ func (ctrl *RenderSecretsStaticPodController) Run(ctx context.Context, r control
templates: []template{
{
filename: "kubeconfig",
template: []byte("{{ .AdminKubeconfig }}"),
template: []byte("{{ .Secrets.AdminKubeconfig }}"),
},
},
},
Expand All @@ -181,7 +224,7 @@ func (ctrl *RenderSecretsStaticPodController) Run(ctx context.Context, r control
templates: []template{
{
filename: "kubeconfig",
template: []byte("{{ .AdminKubeconfig }}"),
template: []byte("{{ .Secrets.AdminKubeconfig }}"),
},
},
},
Expand Down Expand Up @@ -214,6 +257,16 @@ func (ctrl *RenderSecretsStaticPodController) Run(ctx context.Context, r control
}
}

type templateParams struct {
Root *secrets.RootKubernetesSpec
Secrets *secrets.KubernetesCertsSpec
}

params := templateParams{
Root: rootK8sSecrets,
Secrets: k8sSecrets,
}

for _, templ := range pod.templates {
var t *stdlibtemplate.Template

Expand All @@ -224,7 +277,7 @@ func (ctrl *RenderSecretsStaticPodController) Run(ctx context.Context, r control

var buf bytes.Buffer

if err = t.Execute(&buf, secrets); err != nil {
if err = t.Execute(&buf, &params); err != nil {
return fmt.Errorf("error executing template %q: %w", templ.filename, err)
}

Expand Down
2 changes: 1 addition & 1 deletion internal/app/machined/pkg/controllers/k8s/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ resources:
- aescbc:
keys:
- name: key1
secret: {{ .AESCBCEncryptionSecret }}
secret: {{ .Root.AESCBCEncryptionSecret }}
- identity: {}
`)

Expand Down
146 changes: 146 additions & 0 deletions internal/app/machined/pkg/controllers/secrets/etcd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

package secrets

import (
"context"
"fmt"
"log"

"github.com/AlekSi/pointer"
"github.com/talos-systems/os-runtime/pkg/controller"
"github.com/talos-systems/os-runtime/pkg/resource"
"github.com/talos-systems/os-runtime/pkg/state"

"github.com/talos-systems/talos/internal/pkg/etcd"
"github.com/talos-systems/talos/pkg/resources/secrets"
"github.com/talos-systems/talos/pkg/resources/v1alpha1"
)

// EtcdController manages secrets.Etcd based on configuration.
type EtcdController struct{}

// Name implements controller.Controller interface.
func (ctrl *EtcdController) Name() string {
return "secrets.EtcdController"
}

// ManagedResources implements controller.Controller interface.
func (ctrl *EtcdController) ManagedResources() (resource.Namespace, resource.Type) {
return secrets.NamespaceName, secrets.EtcdType
}

// Run implements controller.Controller interface.
//
//nolint: gocyclo, dupl
func (ctrl *EtcdController) Run(ctx context.Context, r controller.Runtime, logger *log.Logger) error {
if err := r.UpdateDependencies([]controller.Dependency{
{
Namespace: secrets.NamespaceName,
Type: secrets.RootType,
ID: pointer.ToString(secrets.RootEtcdID),
Kind: controller.DependencyWeak,
},
{
Namespace: v1alpha1.NamespaceName,
Type: v1alpha1.ServiceType,
ID: pointer.ToString("networkd"),
Kind: controller.DependencyWeak,
},
{
Namespace: v1alpha1.NamespaceName,
Type: v1alpha1.TimeSyncType,
ID: pointer.ToString(v1alpha1.TimeSyncID),
Kind: controller.DependencyWeak,
},
}); err != nil {
return fmt.Errorf("error setting up dependencies: %w", err)
}

for {
select {
case <-ctx.Done():
return nil
case <-r.EventCh():
}

etcdRootRes, err := r.Get(ctx, resource.NewMetadata(secrets.NamespaceName, secrets.RootType, secrets.RootEtcdID, resource.VersionUndefined))
if err != nil {
if state.IsNotFoundError(err) {
if err = ctrl.teardownAll(ctx, r); err != nil {
return fmt.Errorf("error destroying resources: %w", err)
}

continue
}

return fmt.Errorf("error getting etcd root secrets: %w", err)
}

etcdRoot := etcdRootRes.(*secrets.Root).EtcdSpec()

// wait for networkd to be healthy as it might change IPs/hostname
networkdResource, err := r.Get(ctx, resource.NewMetadata(v1alpha1.NamespaceName, v1alpha1.ServiceType, "networkd", resource.VersionUndefined))
if err != nil {
if state.IsNotFoundError(err) {
continue
}

return err
}

if !networkdResource.(*v1alpha1.Service).Healthy() {
continue
}

// wait for time sync as certs depend on current time
timeSyncResource, err := r.Get(ctx, resource.NewMetadata(v1alpha1.NamespaceName, v1alpha1.TimeSyncType, v1alpha1.TimeSyncID, resource.VersionUndefined))
if err != nil {
if state.IsNotFoundError(err) {
continue
}

return err
}

if !timeSyncResource.(*v1alpha1.TimeSync).Sync() {
continue
}

if err = r.Update(ctx, secrets.NewEtcd(), func(r resource.Resource) error {
return ctrl.updateSecrets(etcdRoot, r.(*secrets.Etcd).Certs())
}); err != nil {
return err
}
}
}

func (ctrl *EtcdController) updateSecrets(etcdRoot *secrets.RootEtcdSpec, etcdCerts *secrets.EtcdCertsSpec) error {
var err error

etcdCerts.EtcdPeer, err = etcd.GeneratePeerCert(etcdRoot.EtcdCA)
if err != nil {
return fmt.Errorf("error generating etcd certs: %w", err)
}

return nil
}

func (ctrl *EtcdController) teardownAll(ctx context.Context, r controller.Runtime) error {
list, err := r.List(ctx, resource.NewMetadata(secrets.NamespaceName, secrets.EtcdType, "", resource.VersionUndefined))
if err != nil {
return err
}

// TODO: change this to proper teardown sequence

for _, res := range list.Items {
if err = r.Destroy(ctx, res.Metadata()); err != nil {
return err
}
}

return nil
}
Loading

0 comments on commit b914398

Please sign in to comment.