2022-09-05 03:06:08 -04:00
|
|
|
/*
|
|
|
|
Copyright (c) Edgeless Systems GmbH
|
|
|
|
|
|
|
|
SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
*/
|
|
|
|
|
2022-03-22 11:03:15 -04:00
|
|
|
package k8sapi
|
|
|
|
|
|
|
|
import (
|
2022-05-19 11:18:22 -04:00
|
|
|
"context"
|
2022-07-15 03:33:11 -04:00
|
|
|
"crypto/rand"
|
|
|
|
"crypto/x509"
|
2022-08-12 04:20:19 -04:00
|
|
|
"encoding/json"
|
2022-07-15 03:33:11 -04:00
|
|
|
"encoding/pem"
|
2022-03-22 11:03:15 -04:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
2022-07-18 06:28:02 -04:00
|
|
|
"io/fs"
|
2022-07-15 03:33:11 -04:00
|
|
|
"net"
|
2022-06-13 10:01:21 -04:00
|
|
|
"net/http"
|
2022-03-22 11:03:15 -04:00
|
|
|
"os"
|
|
|
|
"os/exec"
|
2022-07-15 03:33:11 -04:00
|
|
|
"path/filepath"
|
2022-08-31 09:37:07 -04:00
|
|
|
"strconv"
|
2022-06-13 10:01:21 -04:00
|
|
|
"strings"
|
2022-05-04 08:32:34 -04:00
|
|
|
"time"
|
2022-03-22 11:03:15 -04:00
|
|
|
|
2022-07-15 03:33:11 -04:00
|
|
|
"github.com/edgelesssys/constellation/bootstrapper/internal/kubelet"
|
2022-06-29 09:26:29 -04:00
|
|
|
"github.com/edgelesssys/constellation/bootstrapper/internal/kubernetes/k8sapi/resources"
|
2022-08-12 04:20:19 -04:00
|
|
|
"github.com/edgelesssys/constellation/internal/constants"
|
2022-08-29 08:30:20 -04:00
|
|
|
"github.com/edgelesssys/constellation/internal/kubernetes"
|
2022-08-31 21:40:29 -04:00
|
|
|
"github.com/edgelesssys/constellation/internal/role"
|
2022-08-12 04:20:19 -04:00
|
|
|
kubeconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants"
|
|
|
|
|
2022-07-26 04:58:39 -04:00
|
|
|
"github.com/edgelesssys/constellation/internal/crypto"
|
2022-08-12 04:20:19 -04:00
|
|
|
"github.com/edgelesssys/constellation/internal/deploy/helm"
|
2022-07-15 03:33:11 -04:00
|
|
|
"github.com/edgelesssys/constellation/internal/file"
|
2022-07-14 07:30:44 -04:00
|
|
|
"github.com/edgelesssys/constellation/internal/logger"
|
2022-07-18 06:28:02 -04:00
|
|
|
"github.com/edgelesssys/constellation/internal/versions"
|
|
|
|
"github.com/icholy/replace"
|
2022-07-15 03:33:11 -04:00
|
|
|
"github.com/spf13/afero"
|
2022-07-07 05:43:35 -04:00
|
|
|
"go.uber.org/zap"
|
2022-07-18 06:28:02 -04:00
|
|
|
"golang.org/x/text/transform"
|
2022-08-12 04:20:19 -04:00
|
|
|
"helm.sh/helm/v3/pkg/action"
|
|
|
|
"helm.sh/helm/v3/pkg/cli"
|
2022-07-18 06:28:02 -04:00
|
|
|
corev1 "k8s.io/api/core/v1"
|
2022-03-22 11:03:15 -04:00
|
|
|
)
|
|
|
|
|
2022-05-19 11:18:22 -04:00
|
|
|
const (
|
|
|
|
// kubeConfig is the path to the Kubernetes admin config (used for authentication).
|
|
|
|
kubeConfig = "/etc/kubernetes/admin.conf"
|
|
|
|
// kubeletStartTimeout is the maximum time given to the kubelet service to (re)start.
|
|
|
|
kubeletStartTimeout = 10 * time.Minute
|
2022-08-04 10:15:52 -04:00
|
|
|
// crdTimeout is the maximum time given to the CRDs to be created.
|
|
|
|
crdTimeout = 15 * time.Second
|
2022-08-19 07:28:16 -04:00
|
|
|
// helmTimeout is the maximum time given to the helm client.
|
|
|
|
helmTimeout = 5 * time.Minute
|
2022-05-19 11:18:22 -04:00
|
|
|
)
|
2022-03-22 11:03:15 -04:00
|
|
|
|
2022-07-14 15:15:31 -04:00
|
|
|
// Client provides the functions to talk to the k8s API.
|
2022-03-22 11:03:15 -04:00
|
|
|
type Client interface {
|
2022-08-29 08:30:20 -04:00
|
|
|
Apply(resources kubernetes.Marshaler, forceConflicts bool) error
|
2022-03-22 11:03:15 -04:00
|
|
|
SetKubeconfig(kubeconfig []byte)
|
2022-07-18 06:28:02 -04:00
|
|
|
CreateConfigMap(ctx context.Context, configMap corev1.ConfigMap) error
|
2022-07-28 10:07:29 -04:00
|
|
|
AddTolerationsToDeployment(ctx context.Context, tolerations []corev1.Toleration, name string, namespace string) error
|
|
|
|
AddNodeSelectorsToDeployment(ctx context.Context, selectors map[string]string, name string, namespace string) error
|
2022-08-04 10:15:52 -04:00
|
|
|
WaitForCRDs(ctx context.Context, crds []string) error
|
2022-03-22 11:03:15 -04:00
|
|
|
}
|
|
|
|
|
2022-07-18 06:28:02 -04:00
|
|
|
type installer interface {
|
|
|
|
Install(
|
|
|
|
ctx context.Context, sourceURL string, destinations []string, perm fs.FileMode,
|
|
|
|
extract bool, transforms ...transform.Transformer,
|
|
|
|
) error
|
|
|
|
}
|
|
|
|
|
2022-05-19 11:18:22 -04:00
|
|
|
// KubernetesUtil provides low level management of the kubernetes cluster.
|
|
|
|
type KubernetesUtil struct {
|
|
|
|
inst installer
|
2022-07-15 03:33:11 -04:00
|
|
|
file file.Handler
|
2022-05-19 11:18:22 -04:00
|
|
|
}
|
|
|
|
|
2022-07-08 04:59:59 -04:00
|
|
|
// NewKubernetesUtil creates a new KubernetesUtil.
|
2022-05-19 11:18:22 -04:00
|
|
|
func NewKubernetesUtil() *KubernetesUtil {
|
|
|
|
return &KubernetesUtil{
|
|
|
|
inst: newOSInstaller(),
|
2022-07-15 03:33:11 -04:00
|
|
|
file: file.NewHandler(afero.NewOsFs()),
|
2022-05-19 11:18:22 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// InstallComponents installs kubernetes components in the version specified.
|
2022-07-22 09:05:04 -04:00
|
|
|
func (k *KubernetesUtil) InstallComponents(ctx context.Context, version versions.ValidK8sVersion) error {
|
|
|
|
versionConf := versions.VersionConfigs[version]
|
2022-07-18 06:28:02 -04:00
|
|
|
|
|
|
|
if err := k.inst.Install(
|
|
|
|
ctx, versionConf.CNIPluginsURL, []string{cniPluginsDir}, executablePerm, true,
|
|
|
|
); err != nil {
|
|
|
|
return fmt.Errorf("installing cni plugins: %w", err)
|
|
|
|
}
|
|
|
|
if err := k.inst.Install(
|
|
|
|
ctx, versionConf.CrictlURL, []string{binDir}, executablePerm, true,
|
|
|
|
); err != nil {
|
|
|
|
return fmt.Errorf("installing crictl: %w", err)
|
|
|
|
}
|
|
|
|
if err := k.inst.Install(
|
|
|
|
ctx, versionConf.KubeletServiceURL, []string{kubeletServiceEtcPath, kubeletServiceStatePath}, systemdUnitPerm, false, replace.String("/usr/bin", binDir),
|
|
|
|
); err != nil {
|
|
|
|
return fmt.Errorf("installing kubelet service: %w", err)
|
|
|
|
}
|
|
|
|
if err := k.inst.Install(
|
|
|
|
ctx, versionConf.KubeadmConfURL, []string{kubeadmConfEtcPath, kubeadmConfStatePath}, systemdUnitPerm, false, replace.String("/usr/bin", binDir),
|
|
|
|
); err != nil {
|
|
|
|
return fmt.Errorf("installing kubeadm conf: %w", err)
|
|
|
|
}
|
|
|
|
if err := k.inst.Install(
|
|
|
|
ctx, versionConf.KubeletURL, []string{kubeletPath}, executablePerm, false,
|
|
|
|
); err != nil {
|
|
|
|
return fmt.Errorf("installing kubelet: %w", err)
|
|
|
|
}
|
|
|
|
if err := k.inst.Install(
|
|
|
|
ctx, versionConf.KubeadmURL, []string{kubeadmPath}, executablePerm, false,
|
|
|
|
); err != nil {
|
|
|
|
return fmt.Errorf("installing kubeadm: %w", err)
|
|
|
|
}
|
|
|
|
if err := k.inst.Install(
|
|
|
|
ctx, versionConf.KubectlURL, []string{kubectlPath}, executablePerm, false,
|
|
|
|
); err != nil {
|
|
|
|
return fmt.Errorf("installing kubectl: %w", err)
|
2022-05-19 11:18:22 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
return enableSystemdUnit(ctx, kubeletServiceEtcPath)
|
|
|
|
}
|
2022-03-22 11:03:15 -04:00
|
|
|
|
2022-07-15 03:33:11 -04:00
|
|
|
func (k *KubernetesUtil) InitCluster(
|
2022-08-31 21:40:29 -04:00
|
|
|
ctx context.Context, initConfig []byte, nodeName string, ips []net.IP, controlPlaneEndpoint string, log *logger.Logger,
|
2022-07-15 03:33:11 -04:00
|
|
|
) error {
|
2022-05-20 11:30:37 -04:00
|
|
|
// TODO: audit policy should be user input
|
|
|
|
auditPolicy, err := resources.NewDefaultAuditPolicy().Marshal()
|
|
|
|
if err != nil {
|
2022-06-09 10:04:30 -04:00
|
|
|
return fmt.Errorf("generating default audit policy: %w", err)
|
2022-05-20 11:30:37 -04:00
|
|
|
}
|
|
|
|
if err := os.WriteFile(auditPolicyPath, auditPolicy, 0o644); err != nil {
|
2022-06-09 10:04:30 -04:00
|
|
|
return fmt.Errorf("writing default audit policy: %w", err)
|
2022-05-20 11:30:37 -04:00
|
|
|
}
|
|
|
|
|
2022-03-22 11:03:15 -04:00
|
|
|
initConfigFile, err := os.CreateTemp("", "kubeadm-init.*.yaml")
|
|
|
|
if err != nil {
|
2022-06-09 10:04:30 -04:00
|
|
|
return fmt.Errorf("creating init config file %v: %w", initConfigFile.Name(), err)
|
2022-03-22 11:03:15 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
if _, err := initConfigFile.Write(initConfig); err != nil {
|
2022-06-09 10:04:30 -04:00
|
|
|
return fmt.Errorf("writing kubeadm init yaml config %v: %w", initConfigFile.Name(), err)
|
2022-03-22 11:03:15 -04:00
|
|
|
}
|
|
|
|
|
2022-07-15 03:33:11 -04:00
|
|
|
// preflight
|
|
|
|
log.Infof("Running kubeadm preflight checks")
|
|
|
|
cmd := exec.CommandContext(ctx, kubeadmPath, "init", "phase", "preflight", "-v=5", "--config", initConfigFile.Name())
|
2022-07-07 05:43:35 -04:00
|
|
|
out, err := cmd.CombinedOutput()
|
2022-07-15 03:33:11 -04:00
|
|
|
if err != nil {
|
|
|
|
var exitErr *exec.ExitError
|
|
|
|
if errors.As(err, &exitErr) {
|
|
|
|
return fmt.Errorf("kubeadm init phase preflight failed (code %v) with: %s", exitErr.ExitCode(), out)
|
|
|
|
}
|
|
|
|
return fmt.Errorf("kubeadm init: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// create CA certs
|
|
|
|
log.Infof("Creating Kubernetes control-plane certificates and keys")
|
|
|
|
cmd = exec.CommandContext(ctx, kubeadmPath, "init", "phase", "certs", "all", "-v=5", "--config", initConfigFile.Name())
|
|
|
|
out, err = cmd.CombinedOutput()
|
|
|
|
if err != nil {
|
|
|
|
var exitErr *exec.ExitError
|
|
|
|
if errors.As(err, &exitErr) {
|
|
|
|
return fmt.Errorf("kubeadm init phase certs all failed (code %v) with: %s", exitErr.ExitCode(), out)
|
|
|
|
}
|
|
|
|
return fmt.Errorf("kubeadm init: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// create kubelet key and CA signed certificate for the node
|
|
|
|
log.Infof("Creating signed kubelet certificate")
|
|
|
|
if err := k.createSignedKubeletCert(nodeName, ips); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-08-31 21:40:29 -04:00
|
|
|
log.Infof("Preparing node for Konnectivity")
|
|
|
|
if err := k.prepareControlPlaneForKonnectivity(ctx, controlPlaneEndpoint); err != nil {
|
|
|
|
return fmt.Errorf("setup konnectivity: %w", err)
|
|
|
|
}
|
|
|
|
|
2022-07-15 03:33:11 -04:00
|
|
|
// initialize the cluster
|
|
|
|
log.Infof("Initializing the cluster using kubeadm init")
|
2022-08-31 09:37:07 -04:00
|
|
|
cmd = exec.CommandContext(ctx, kubeadmPath, "init", "-v=5", "--skip-phases=preflight,certs,addon/kube-proxy", "--config", initConfigFile.Name())
|
2022-07-15 03:33:11 -04:00
|
|
|
out, err = cmd.CombinedOutput()
|
2022-03-22 11:03:15 -04:00
|
|
|
if err != nil {
|
|
|
|
var exitErr *exec.ExitError
|
|
|
|
if errors.As(err, &exitErr) {
|
2022-07-07 05:43:35 -04:00
|
|
|
return fmt.Errorf("kubeadm init failed (code %v) with: %s", exitErr.ExitCode(), out)
|
2022-03-22 11:03:15 -04:00
|
|
|
}
|
2022-06-09 10:04:30 -04:00
|
|
|
return fmt.Errorf("kubeadm init: %w", err)
|
2022-03-22 11:03:15 -04:00
|
|
|
}
|
2022-07-14 07:30:44 -04:00
|
|
|
log.With(zap.String("output", string(out))).Infof("kubeadm init succeeded")
|
2022-05-04 08:32:34 -04:00
|
|
|
return nil
|
2022-03-22 11:03:15 -04:00
|
|
|
}
|
|
|
|
|
2022-08-31 21:40:29 -04:00
|
|
|
func (k *KubernetesUtil) prepareControlPlaneForKonnectivity(ctx context.Context, loadBalancerEndpoint string) error {
|
|
|
|
if !strings.Contains(loadBalancerEndpoint, ":") {
|
|
|
|
loadBalancerEndpoint = net.JoinHostPort(loadBalancerEndpoint, strconv.Itoa(constants.KubernetesPort))
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := os.MkdirAll("/etc/kubernetes/manifests", os.ModePerm); err != nil {
|
|
|
|
return fmt.Errorf("creating static pods directory: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
konnectivityServerYaml, err := resources.NewKonnectivityServerStaticPod().Marshal()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("generating konnectivity server static pod: %w", err)
|
|
|
|
}
|
|
|
|
if err := os.WriteFile("/etc/kubernetes/manifests/konnectivity-server.yaml", konnectivityServerYaml, 0o644); err != nil {
|
|
|
|
return fmt.Errorf("writing konnectivity server pod: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
egressConfigYaml, err := resources.NewEgressSelectorConfiguration().Marshal()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("generating egress selector configuration: %w", err)
|
|
|
|
}
|
|
|
|
if err := os.WriteFile("/etc/kubernetes/egress-selector-configuration.yaml", egressConfigYaml, 0o644); err != nil {
|
|
|
|
return fmt.Errorf("writing egress selector config: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := k.createSignedKonnectivityCert(); err != nil {
|
|
|
|
return fmt.Errorf("generating konnectivity server certificate: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if out, err := exec.CommandContext(ctx, kubectlPath, "config", "set-credentials", "--kubeconfig", "/etc/kubernetes/konnectivity-server.conf", "system:konnectivity-server",
|
|
|
|
"--client-certificate", "/etc/kubernetes/konnectivity.crt", "--client-key", "/etc/kubernetes/konnectivity.key", "--embed-certs=true").CombinedOutput(); err != nil {
|
|
|
|
return fmt.Errorf("konnectivity kubeconfig set-credentials: %w, %s", err, string(out))
|
|
|
|
}
|
|
|
|
if out, err := exec.CommandContext(ctx, kubectlPath, "--kubeconfig", "/etc/kubernetes/konnectivity-server.conf", "config", "set-cluster", "kubernetes", "--server", "https://"+loadBalancerEndpoint,
|
|
|
|
"--certificate-authority", "/etc/kubernetes/pki/ca.crt", "--embed-certs=true").CombinedOutput(); err != nil {
|
|
|
|
return fmt.Errorf("konnectivity kubeconfig set-cluster: %w, %s", err, string(out))
|
|
|
|
}
|
|
|
|
if out, err := exec.CommandContext(ctx, kubectlPath, "--kubeconfig", "/etc/kubernetes/konnectivity-server.conf", "config", "set-context", "system:konnectivity-server@kubernetes",
|
|
|
|
"--cluster", "kubernetes", "--user", "system:konnectivity-server").CombinedOutput(); err != nil {
|
|
|
|
return fmt.Errorf("konnectivity kubeconfig set-context: %w, %s", err, string(out))
|
|
|
|
}
|
|
|
|
if out, err := exec.CommandContext(ctx, kubectlPath, "--kubeconfig", "/etc/kubernetes/konnectivity-server.conf", "config", "use-context", "system:konnectivity-server@kubernetes").CombinedOutput(); err != nil {
|
|
|
|
return fmt.Errorf("konnectivity kubeconfig use-context: %w, %s", err, string(out))
|
|
|
|
}
|
|
|
|
// cleanup
|
|
|
|
if err := os.Remove("/etc/kubernetes/konnectivity.crt"); err != nil {
|
|
|
|
return fmt.Errorf("removing konnectivity certificate: %w", err)
|
|
|
|
}
|
|
|
|
if err := os.Remove("/etc/kubernetes/konnectivity.key"); err != nil {
|
|
|
|
return fmt.Errorf("removing konnectivity key: %w", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (k *KubernetesUtil) SetupKonnectivity(kubectl Client, konnectivityAgentsDaemonSet kubernetes.Marshaler) error {
|
|
|
|
return kubectl.Apply(konnectivityAgentsDaemonSet, true)
|
|
|
|
}
|
|
|
|
|
2022-08-12 04:20:19 -04:00
|
|
|
func (k *KubernetesUtil) SetupHelmDeployments(ctx context.Context, kubectl Client, helmDeployments []byte, in SetupPodNetworkInput, log *logger.Logger) error {
|
|
|
|
var helmDeploy helm.Deployments
|
|
|
|
if err := json.Unmarshal(helmDeployments, &helmDeploy); err != nil {
|
|
|
|
return fmt.Errorf("unmarshalling helm deployments: %w", err)
|
|
|
|
}
|
|
|
|
settings := cli.New()
|
|
|
|
settings.KubeConfig = kubeConfig
|
|
|
|
|
|
|
|
actionConfig := new(action.Configuration)
|
|
|
|
if err := actionConfig.Init(settings.RESTClientGetter(), constants.HelmNamespace,
|
|
|
|
"secret", log.Infof); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
helmClient := action.NewInstall(actionConfig)
|
|
|
|
helmClient.Namespace = constants.HelmNamespace
|
|
|
|
helmClient.ReleaseName = "cilium"
|
|
|
|
helmClient.Wait = true
|
2022-08-19 07:28:16 -04:00
|
|
|
helmClient.Timeout = helmTimeout
|
2022-08-12 04:20:19 -04:00
|
|
|
|
|
|
|
if err := k.deployCilium(ctx, in, helmClient, helmDeploy.Cilium, kubectl); err != nil {
|
|
|
|
return fmt.Errorf("deploying cilium: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-05-24 04:04:42 -04:00
|
|
|
type SetupPodNetworkInput struct {
|
2022-08-31 09:37:07 -04:00
|
|
|
CloudProvider string
|
|
|
|
NodeName string
|
|
|
|
FirstNodePodCIDR string
|
|
|
|
SubnetworkPodCIDR string
|
|
|
|
ProviderID string
|
|
|
|
LoadBalancerEndpoint string
|
2022-05-24 04:04:42 -04:00
|
|
|
}
|
|
|
|
|
2022-08-12 04:20:19 -04:00
|
|
|
// deployCilium sets up the cilium pod network.
|
|
|
|
func (k *KubernetesUtil) deployCilium(ctx context.Context, in SetupPodNetworkInput, helmClient *action.Install, ciliumDeployment helm.Deployment, kubectl Client) error {
|
2022-05-24 04:04:42 -04:00
|
|
|
switch in.CloudProvider {
|
|
|
|
case "gcp":
|
2022-08-31 09:37:07 -04:00
|
|
|
return k.deployCiliumGCP(ctx, helmClient, kubectl, ciliumDeployment, in.NodeName, in.FirstNodePodCIDR, in.SubnetworkPodCIDR, in.LoadBalancerEndpoint)
|
2022-05-24 04:04:42 -04:00
|
|
|
case "azure":
|
2022-08-31 09:37:07 -04:00
|
|
|
return k.deployCiliumAzure(ctx, helmClient, ciliumDeployment, in.LoadBalancerEndpoint)
|
2022-05-24 04:04:42 -04:00
|
|
|
case "qemu":
|
2022-09-02 14:19:20 -04:00
|
|
|
return k.deployCiliumQEMU(ctx, helmClient, ciliumDeployment, in.SubnetworkPodCIDR, in.LoadBalancerEndpoint)
|
2022-05-24 04:04:42 -04:00
|
|
|
default:
|
|
|
|
return fmt.Errorf("unsupported cloud provider %q", in.CloudProvider)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-31 09:37:07 -04:00
|
|
|
func (k *KubernetesUtil) deployCiliumAzure(ctx context.Context, helmClient *action.Install, ciliumDeployment helm.Deployment, kubeAPIEndpoint string) error {
|
|
|
|
host := kubeAPIEndpoint
|
|
|
|
ciliumDeployment.Values["k8sServiceHost"] = host
|
|
|
|
ciliumDeployment.Values["k8sServicePort"] = strconv.Itoa(constants.KubernetesPort)
|
|
|
|
|
2022-08-12 04:20:19 -04:00
|
|
|
_, err := helmClient.RunWithContext(ctx, ciliumDeployment.Chart, ciliumDeployment.Values)
|
2022-05-24 04:04:42 -04:00
|
|
|
if err != nil {
|
2022-08-12 04:20:19 -04:00
|
|
|
return fmt.Errorf("installing cilium: %w", err)
|
2022-05-24 04:04:42 -04:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-08-31 09:37:07 -04:00
|
|
|
func (k *KubernetesUtil) deployCiliumGCP(ctx context.Context, helmClient *action.Install, kubectl Client, ciliumDeployment helm.Deployment, nodeName, nodePodCIDR, subnetworkPodCIDR, kubeAPIEndpoint string) error {
|
2022-05-24 04:04:42 -04:00
|
|
|
out, err := exec.CommandContext(ctx, kubectlPath, "--kubeconfig", kubeConfig, "patch", "node", nodeName, "-p", "{\"spec\":{\"podCIDR\": \""+nodePodCIDR+"\"}}").CombinedOutput()
|
|
|
|
if err != nil {
|
|
|
|
err = errors.New(string(out))
|
2022-03-22 11:03:15 -04:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-09-08 08:45:27 -04:00
|
|
|
timeoutS := int64(10)
|
2022-03-22 11:03:15 -04:00
|
|
|
// allow coredns to run on uninitialized nodes (required by cloud-controller-manager)
|
2022-07-14 15:15:31 -04:00
|
|
|
tolerations := []corev1.Toleration{
|
|
|
|
{
|
|
|
|
Key: "node.cloudprovider.kubernetes.io/uninitialized",
|
|
|
|
Value: "true",
|
2022-09-08 08:45:27 -04:00
|
|
|
Effect: corev1.TaintEffectNoSchedule,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
Key: "node.kubernetes.io/unreachable",
|
|
|
|
Operator: corev1.TolerationOpExists,
|
|
|
|
Effect: corev1.TaintEffectNoExecute,
|
|
|
|
TolerationSeconds: &timeoutS,
|
2022-07-14 15:15:31 -04:00
|
|
|
},
|
|
|
|
}
|
2022-07-28 10:07:29 -04:00
|
|
|
if err = kubectl.AddTolerationsToDeployment(ctx, tolerations, "coredns", "kube-system"); err != nil {
|
2022-07-14 15:15:31 -04:00
|
|
|
return err
|
|
|
|
}
|
2022-07-26 04:10:34 -04:00
|
|
|
selectors := map[string]string{
|
|
|
|
"node-role.kubernetes.io/control-plane": "",
|
|
|
|
}
|
2022-07-28 10:07:29 -04:00
|
|
|
if err = kubectl.AddNodeSelectorsToDeployment(ctx, selectors, "coredns", "kube-system"); err != nil {
|
2022-07-26 04:10:34 -04:00
|
|
|
return err
|
|
|
|
}
|
2022-05-24 04:04:42 -04:00
|
|
|
|
2022-08-31 09:37:07 -04:00
|
|
|
host, port, err := net.SplitHostPort(kubeAPIEndpoint)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-08-12 04:20:19 -04:00
|
|
|
// configure pod network CIDR
|
|
|
|
ciliumDeployment.Values["ipv4NativeRoutingCIDR"] = subnetworkPodCIDR
|
|
|
|
ciliumDeployment.Values["strictModeCIDR"] = subnetworkPodCIDR
|
2022-08-31 09:37:07 -04:00
|
|
|
ciliumDeployment.Values["k8sServiceHost"] = host
|
|
|
|
if port != "" {
|
|
|
|
ciliumDeployment.Values["k8sServicePort"] = port
|
|
|
|
}
|
2022-08-12 04:20:19 -04:00
|
|
|
|
|
|
|
_, err = helmClient.RunWithContext(ctx, ciliumDeployment.Chart, ciliumDeployment.Values)
|
2022-05-24 04:04:42 -04:00
|
|
|
if err != nil {
|
2022-08-12 04:20:19 -04:00
|
|
|
return fmt.Errorf("installing cilium: %w", err)
|
2022-05-24 04:04:42 -04:00
|
|
|
}
|
2022-06-13 10:01:21 -04:00
|
|
|
|
2022-05-24 04:04:42 -04:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-06-13 10:01:21 -04:00
|
|
|
// FixCilium fixes https://github.com/cilium/cilium/issues/19958 but instead of a rollout restart of
|
|
|
|
// the cilium daemonset, it only restarts the local cilium pod.
|
2022-09-08 08:45:27 -04:00
|
|
|
func (k *KubernetesUtil) FixCilium(log *logger.Logger) {
|
2022-06-13 10:01:21 -04:00
|
|
|
// wait for cilium pod to be healthy
|
2022-08-12 04:20:19 -04:00
|
|
|
client := http.Client{}
|
2022-06-13 10:01:21 -04:00
|
|
|
for {
|
|
|
|
time.Sleep(5 * time.Second)
|
2022-08-12 04:20:19 -04:00
|
|
|
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://127.0.0.1:9879/healthz", http.NoBody)
|
2022-06-13 10:01:21 -04:00
|
|
|
if err != nil {
|
2022-08-02 10:25:47 -04:00
|
|
|
log.With(zap.Error(err)).Errorf("Unable to create request")
|
|
|
|
continue
|
|
|
|
}
|
2022-08-12 04:20:19 -04:00
|
|
|
resp, err := client.Do(req)
|
2022-08-02 10:25:47 -04:00
|
|
|
if err != nil {
|
|
|
|
log.With(zap.Error(err)).Warnf("Waiting for local cilium daemonset pod not healthy")
|
2022-06-13 10:01:21 -04:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
resp.Body.Close()
|
|
|
|
if resp.StatusCode == 200 {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// get cilium pod name
|
|
|
|
out, err := exec.CommandContext(context.Background(), "/bin/bash", "-c", "/run/state/bin/crictl ps -o json | jq -r '.containers[] | select(.metadata.name == \"cilium-agent\") | .podSandboxId'").CombinedOutput()
|
|
|
|
if err != nil {
|
2022-08-02 10:25:47 -04:00
|
|
|
log.With(zap.Error(err)).Errorf("Getting pod id failed: %s", out)
|
2022-06-13 10:01:21 -04:00
|
|
|
return
|
|
|
|
}
|
|
|
|
outLines := strings.Split(string(out), "\n")
|
|
|
|
podID := outLines[len(outLines)-2]
|
|
|
|
|
|
|
|
// stop and delete pod
|
|
|
|
out, err = exec.CommandContext(context.Background(), "/run/state/bin/crictl", "stopp", podID).CombinedOutput()
|
|
|
|
if err != nil {
|
2022-08-02 10:25:47 -04:00
|
|
|
log.With(zap.Error(err)).Errorf("Stopping cilium agent pod failed: %s", out)
|
2022-06-13 10:01:21 -04:00
|
|
|
return
|
|
|
|
}
|
|
|
|
out, err = exec.CommandContext(context.Background(), "/run/state/bin/crictl", "rmp", podID).CombinedOutput()
|
|
|
|
if err != nil {
|
2022-08-02 10:25:47 -04:00
|
|
|
log.With(zap.Error(err)).Errorf("Removing cilium agent pod failed: %s", out)
|
2022-06-13 10:01:21 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-02 14:19:20 -04:00
|
|
|
func (k *KubernetesUtil) deployCiliumQEMU(ctx context.Context, helmClient *action.Install, ciliumDeployment helm.Deployment, subnetworkPodCIDR, kubeAPIEndpoint string) error {
|
2022-08-12 04:20:19 -04:00
|
|
|
// configure pod network CIDR
|
|
|
|
ciliumDeployment.Values["ipam"] = map[string]interface{}{
|
|
|
|
"operator": map[string]interface{}{
|
|
|
|
"clusterPoolIPv4PodCIDRList": []interface{}{
|
|
|
|
subnetworkPodCIDR,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2022-09-02 14:19:20 -04:00
|
|
|
ciliumDeployment.Values["k8sServiceHost"] = kubeAPIEndpoint
|
|
|
|
ciliumDeployment.Values["k8sServicePort"] = strconv.Itoa(constants.KubernetesPort)
|
|
|
|
|
2022-08-12 04:20:19 -04:00
|
|
|
_, err := helmClient.RunWithContext(ctx, ciliumDeployment.Chart, ciliumDeployment.Values)
|
2022-03-22 11:03:15 -04:00
|
|
|
if err != nil {
|
2022-08-12 04:20:19 -04:00
|
|
|
return fmt.Errorf("installing cilium: %w", err)
|
2022-03-22 11:03:15 -04:00
|
|
|
}
|
2022-05-24 04:04:42 -04:00
|
|
|
return nil
|
2022-03-22 11:03:15 -04:00
|
|
|
}
|
|
|
|
|
2022-03-25 05:42:27 -04:00
|
|
|
// SetupAutoscaling deploys the k8s cluster autoscaler.
|
2022-08-29 08:30:20 -04:00
|
|
|
func (k *KubernetesUtil) SetupAutoscaling(kubectl Client, clusterAutoscalerConfiguration kubernetes.Marshaler, secrets kubernetes.Marshaler) error {
|
2022-03-29 07:25:04 -04:00
|
|
|
if err := kubectl.Apply(secrets, true); err != nil {
|
2022-06-09 10:04:30 -04:00
|
|
|
return fmt.Errorf("applying cluster-autoscaler Secrets: %w", err)
|
2022-03-29 07:25:04 -04:00
|
|
|
}
|
2022-03-22 11:03:15 -04:00
|
|
|
return kubectl.Apply(clusterAutoscalerConfiguration, true)
|
|
|
|
}
|
|
|
|
|
2022-07-05 08:13:19 -04:00
|
|
|
// SetupJoinService deploys the Constellation node join service.
|
2022-08-29 08:30:20 -04:00
|
|
|
func (k *KubernetesUtil) SetupJoinService(kubectl Client, joinServiceConfiguration kubernetes.Marshaler) error {
|
2022-07-05 08:13:19 -04:00
|
|
|
return kubectl.Apply(joinServiceConfiguration, true)
|
2022-06-15 10:00:48 -04:00
|
|
|
}
|
|
|
|
|
2022-07-05 08:14:11 -04:00
|
|
|
// SetupGCPGuestAgent deploys the GCP guest agent daemon set.
|
2022-08-29 08:30:20 -04:00
|
|
|
func (k *KubernetesUtil) SetupGCPGuestAgent(kubectl Client, guestAgentDaemonset kubernetes.Marshaler) error {
|
2022-07-05 08:14:11 -04:00
|
|
|
return kubectl.Apply(guestAgentDaemonset, true)
|
|
|
|
}
|
|
|
|
|
2022-03-25 05:42:27 -04:00
|
|
|
// SetupCloudControllerManager deploys the k8s cloud-controller-manager.
|
2022-08-29 08:30:20 -04:00
|
|
|
func (k *KubernetesUtil) SetupCloudControllerManager(kubectl Client, cloudControllerManagerConfiguration kubernetes.Marshaler, configMaps kubernetes.Marshaler, secrets kubernetes.Marshaler) error {
|
2022-03-25 05:42:27 -04:00
|
|
|
if err := kubectl.Apply(configMaps, true); err != nil {
|
2022-06-09 10:04:30 -04:00
|
|
|
return fmt.Errorf("applying ccm ConfigMaps: %w", err)
|
2022-03-25 05:42:27 -04:00
|
|
|
}
|
|
|
|
if err := kubectl.Apply(secrets, true); err != nil {
|
2022-06-09 10:04:30 -04:00
|
|
|
return fmt.Errorf("applying ccm Secrets: %w", err)
|
2022-03-25 05:42:27 -04:00
|
|
|
}
|
|
|
|
if err := kubectl.Apply(cloudControllerManagerConfiguration, true); err != nil {
|
2022-06-09 10:04:30 -04:00
|
|
|
return fmt.Errorf("applying ccm: %w", err)
|
2022-03-25 05:42:27 -04:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2022-03-25 05:49:18 -04:00
|
|
|
|
|
|
|
// SetupCloudNodeManager deploys the k8s cloud-node-manager.
|
2022-08-29 08:30:20 -04:00
|
|
|
func (k *KubernetesUtil) SetupCloudNodeManager(kubectl Client, cloudNodeManagerConfiguration kubernetes.Marshaler) error {
|
2022-03-25 05:49:18 -04:00
|
|
|
return kubectl.Apply(cloudNodeManagerConfiguration, true)
|
2022-06-13 10:23:19 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// SetupAccessManager deploys the constellation-access-manager for deploying SSH keys on control-plane & worker nodes.
|
2022-08-29 08:30:20 -04:00
|
|
|
func (k *KubernetesUtil) SetupAccessManager(kubectl Client, accessManagerConfiguration kubernetes.Marshaler) error {
|
2022-06-13 10:23:19 -04:00
|
|
|
return kubectl.Apply(accessManagerConfiguration, true)
|
2022-03-22 11:03:15 -04:00
|
|
|
}
|
|
|
|
|
2022-06-28 11:03:28 -04:00
|
|
|
// SetupKMS deploys the KMS deployment.
|
2022-08-29 08:30:20 -04:00
|
|
|
func (k *KubernetesUtil) SetupKMS(kubectl Client, kmsConfiguration kubernetes.Marshaler) error {
|
2022-06-28 11:03:28 -04:00
|
|
|
if err := kubectl.Apply(kmsConfiguration, true); err != nil {
|
|
|
|
return fmt.Errorf("applying KMS configuration: %w", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetupVerificationService deploys the verification service.
|
2022-08-29 08:30:20 -04:00
|
|
|
func (k *KubernetesUtil) SetupVerificationService(kubectl Client, verificationServiceConfiguration kubernetes.Marshaler) error {
|
2022-06-28 11:03:28 -04:00
|
|
|
return kubectl.Apply(verificationServiceConfiguration, true)
|
|
|
|
}
|
|
|
|
|
2022-08-29 08:30:20 -04:00
|
|
|
func (k *KubernetesUtil) SetupOperatorLifecycleManager(ctx context.Context, kubectl Client, olmCRDs, olmConfiguration kubernetes.Marshaler, crdNames []string) error {
|
2022-08-04 10:15:52 -04:00
|
|
|
if err := kubectl.Apply(olmCRDs, true); err != nil {
|
|
|
|
return fmt.Errorf("applying OLM CRDs: %w", err)
|
|
|
|
}
|
|
|
|
crdReadyTimeout, cancel := context.WithTimeout(ctx, crdTimeout)
|
|
|
|
defer cancel()
|
|
|
|
if err := kubectl.WaitForCRDs(crdReadyTimeout, crdNames); err != nil {
|
|
|
|
return fmt.Errorf("waiting for OLM CRDs: %w", err)
|
|
|
|
}
|
|
|
|
return kubectl.Apply(olmConfiguration, true)
|
|
|
|
}
|
|
|
|
|
2022-08-29 08:30:20 -04:00
|
|
|
func (k *KubernetesUtil) SetupNodeMaintenanceOperator(kubectl Client, nodeMaintenanceOperatorConfiguration kubernetes.Marshaler) error {
|
2022-08-04 10:15:52 -04:00
|
|
|
return kubectl.Apply(nodeMaintenanceOperatorConfiguration, true)
|
|
|
|
}
|
|
|
|
|
2022-08-29 08:30:20 -04:00
|
|
|
func (k *KubernetesUtil) SetupNodeOperator(ctx context.Context, kubectl Client, nodeOperatorConfiguration kubernetes.Marshaler) error {
|
2022-08-04 10:15:52 -04:00
|
|
|
return kubectl.Apply(nodeOperatorConfiguration, true)
|
|
|
|
}
|
|
|
|
|
2022-04-26 05:22:21 -04:00
|
|
|
// JoinCluster joins existing Kubernetes cluster using kubeadm join.
|
2022-08-31 21:40:29 -04:00
|
|
|
func (k *KubernetesUtil) JoinCluster(ctx context.Context, joinConfig []byte, peerRole role.Role, controlPlaneEndpoint string, log *logger.Logger) error {
|
2022-05-20 11:30:37 -04:00
|
|
|
// TODO: audit policy should be user input
|
|
|
|
auditPolicy, err := resources.NewDefaultAuditPolicy().Marshal()
|
|
|
|
if err != nil {
|
2022-06-09 10:04:30 -04:00
|
|
|
return fmt.Errorf("generating default audit policy: %w", err)
|
2022-05-20 11:30:37 -04:00
|
|
|
}
|
|
|
|
if err := os.WriteFile(auditPolicyPath, auditPolicy, 0o644); err != nil {
|
2022-06-09 10:04:30 -04:00
|
|
|
return fmt.Errorf("writing default audit policy: %w", err)
|
2022-05-20 11:30:37 -04:00
|
|
|
}
|
|
|
|
|
2022-03-22 11:03:15 -04:00
|
|
|
joinConfigFile, err := os.CreateTemp("", "kubeadm-join.*.yaml")
|
|
|
|
if err != nil {
|
2022-06-09 10:04:30 -04:00
|
|
|
return fmt.Errorf("creating join config file %v: %w", joinConfigFile.Name(), err)
|
2022-03-22 11:03:15 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
if _, err := joinConfigFile.Write(joinConfig); err != nil {
|
2022-06-09 10:04:30 -04:00
|
|
|
return fmt.Errorf("writing kubeadm init yaml config %v: %w", joinConfigFile.Name(), err)
|
2022-03-22 11:03:15 -04:00
|
|
|
}
|
|
|
|
|
2022-08-31 21:40:29 -04:00
|
|
|
if peerRole == role.ControlPlane {
|
|
|
|
log.Infof("Prep Init Kubernetes cluster")
|
|
|
|
if err := k.prepareControlPlaneForKonnectivity(ctx, controlPlaneEndpoint); err != nil {
|
|
|
|
return fmt.Errorf("setup konnectivity: %w", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-26 05:22:21 -04:00
|
|
|
// run `kubeadm join` to join a worker node to an existing Kubernetes cluster
|
2022-07-05 08:14:11 -04:00
|
|
|
cmd := exec.CommandContext(ctx, kubeadmPath, "join", "-v=5", "--config", joinConfigFile.Name())
|
2022-07-07 05:43:35 -04:00
|
|
|
out, err := cmd.CombinedOutput()
|
|
|
|
if err != nil {
|
2022-03-22 11:03:15 -04:00
|
|
|
var exitErr *exec.ExitError
|
|
|
|
if errors.As(err, &exitErr) {
|
2022-07-07 05:43:35 -04:00
|
|
|
return fmt.Errorf("kubeadm join failed (code %v) with: %s (full err: %s)", exitErr.ExitCode(), out, err)
|
2022-03-22 11:03:15 -04:00
|
|
|
}
|
2022-06-09 10:04:30 -04:00
|
|
|
return fmt.Errorf("kubeadm join: %w", err)
|
2022-03-22 11:03:15 -04:00
|
|
|
}
|
2022-07-14 07:30:44 -04:00
|
|
|
log.With(zap.String("output", string(out))).Infof("kubeadm join succeeded")
|
2022-06-13 10:01:21 -04:00
|
|
|
|
2022-03-22 11:03:15 -04:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-05-19 11:18:22 -04:00
|
|
|
// StartKubelet enables and starts the kubelet systemd unit.
|
|
|
|
func (k *KubernetesUtil) StartKubelet() error {
|
|
|
|
ctx, cancel := context.WithTimeout(context.TODO(), kubeletStartTimeout)
|
|
|
|
defer cancel()
|
|
|
|
if err := enableSystemdUnit(ctx, kubeletServiceEtcPath); err != nil {
|
2022-06-09 10:04:30 -04:00
|
|
|
return fmt.Errorf("enabling kubelet systemd unit: %w", err)
|
2022-05-19 11:18:22 -04:00
|
|
|
}
|
|
|
|
return startSystemdUnit(ctx, "kubelet.service")
|
|
|
|
}
|
|
|
|
|
2022-07-15 03:33:11 -04:00
|
|
|
// createSignedKubeletCert manually creates a Kubernetes CA signed kubelet certificate for the bootstrapper node.
|
|
|
|
// This is necessary because this node does not request a certificate from the join service.
|
|
|
|
func (k *KubernetesUtil) createSignedKubeletCert(nodeName string, ips []net.IP) error {
|
2022-08-31 21:40:29 -04:00
|
|
|
// Create CSR
|
2022-07-15 03:33:11 -04:00
|
|
|
certRequestRaw, kubeletKey, err := kubelet.GetCertificateRequest(nodeName, ips)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err := k.file.Write(kubelet.KeyFilename, kubeletKey, file.OptMkdirAll); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-08-31 21:40:29 -04:00
|
|
|
certRequest, err := x509.ParseCertificateRequest(certRequestRaw)
|
2022-07-15 03:33:11 -04:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-08-31 21:40:29 -04:00
|
|
|
|
|
|
|
// Prepare certificate signing
|
|
|
|
serialNumber, err := crypto.GenerateCertificateSerialNumber()
|
2022-07-15 03:33:11 -04:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-08-31 21:40:29 -04:00
|
|
|
now := time.Now()
|
|
|
|
// Create the kubelet certificate
|
|
|
|
// For a reference on the certificate fields, see: https://kubernetes.io/docs/setup/best-practices/certificates/
|
|
|
|
certTmpl := &x509.Certificate{
|
|
|
|
SerialNumber: serialNumber,
|
|
|
|
NotBefore: now.Add(-2 * time.Hour),
|
|
|
|
NotAfter: now.Add(24 * 365 * time.Hour),
|
|
|
|
Subject: certRequest.Subject,
|
|
|
|
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
|
|
|
|
ExtKeyUsage: []x509.ExtKeyUsage{
|
|
|
|
x509.ExtKeyUsageClientAuth,
|
|
|
|
x509.ExtKeyUsageServerAuth,
|
|
|
|
},
|
|
|
|
IsCA: false,
|
|
|
|
BasicConstraintsValid: true,
|
|
|
|
IPAddresses: certRequest.IPAddresses,
|
|
|
|
}
|
|
|
|
|
|
|
|
parentCert, parentKey, err := k.getKubernetesCACertAndKey()
|
2022-07-15 03:33:11 -04:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-08-31 21:40:29 -04:00
|
|
|
|
|
|
|
// Sign the certificate
|
|
|
|
certRaw, err := x509.CreateCertificate(rand.Reader, certTmpl, parentCert, certRequest.PublicKey, parentKey)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2022-07-15 03:33:11 -04:00
|
|
|
}
|
2022-08-31 21:40:29 -04:00
|
|
|
|
|
|
|
// Write the certificate
|
|
|
|
kubeletCert := pem.EncodeToMemory(&pem.Block{
|
|
|
|
Type: "CERTIFICATE",
|
|
|
|
Bytes: certRaw,
|
|
|
|
})
|
|
|
|
|
|
|
|
return k.file.Write(kubelet.CertificateFilename, kubeletCert, file.OptMkdirAll)
|
|
|
|
}
|
|
|
|
|
|
|
|
// createSignedKonnectivityCert manually creates a Kubernetes CA signed certificate for the Konnectivity server.
|
|
|
|
func (k *KubernetesUtil) createSignedKonnectivityCert() error {
|
|
|
|
// Create CSR
|
|
|
|
certRequestRaw, keyPem, err := resources.GetKonnectivityCertificateRequest()
|
2022-07-15 03:33:11 -04:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-08-31 21:40:29 -04:00
|
|
|
if err := k.file.Write(resources.KonnectivityKeyFilename, keyPem, file.OptMkdirAll); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-07-15 03:33:11 -04:00
|
|
|
|
|
|
|
certRequest, err := x509.ParseCertificateRequest(certRequestRaw)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-08-31 21:40:29 -04:00
|
|
|
// Prepare certificate signing
|
2022-07-26 04:58:39 -04:00
|
|
|
serialNumber, err := crypto.GenerateCertificateSerialNumber()
|
2022-07-15 03:33:11 -04:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
now := time.Now()
|
|
|
|
// Create the kubelet certificate
|
|
|
|
// For a reference on the certificate fields, see: https://kubernetes.io/docs/setup/best-practices/certificates/
|
|
|
|
certTmpl := &x509.Certificate{
|
|
|
|
SerialNumber: serialNumber,
|
|
|
|
NotBefore: now.Add(-2 * time.Hour),
|
|
|
|
NotAfter: now.Add(24 * 365 * time.Hour),
|
|
|
|
Subject: certRequest.Subject,
|
|
|
|
}
|
|
|
|
|
2022-08-31 21:40:29 -04:00
|
|
|
parentCert, parentKey, err := k.getKubernetesCACertAndKey()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Sign the certificate
|
2022-07-15 03:33:11 -04:00
|
|
|
certRaw, err := x509.CreateCertificate(rand.Reader, certTmpl, parentCert, certRequest.PublicKey, parentKey)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-08-31 21:40:29 -04:00
|
|
|
|
|
|
|
// Write the certificate
|
|
|
|
konnectivityCert := pem.EncodeToMemory(&pem.Block{
|
2022-07-15 03:33:11 -04:00
|
|
|
Type: "CERTIFICATE",
|
|
|
|
Bytes: certRaw,
|
|
|
|
})
|
|
|
|
|
2022-08-31 21:40:29 -04:00
|
|
|
return k.file.Write(resources.KonnectivityCertificateFilename, konnectivityCert, file.OptMkdirAll)
|
|
|
|
}
|
|
|
|
|
|
|
|
// getKubernetesCACertAndKey returns the Kubernetes CA certificate and key.
|
|
|
|
// The key of type `any` can be consumed by `x509.CreateCertificate()`.
|
|
|
|
func (k *KubernetesUtil) getKubernetesCACertAndKey() (*x509.Certificate, any, error) {
|
|
|
|
parentCertRaw, err := k.file.Read(filepath.Join(
|
|
|
|
kubeconstants.KubernetesDir,
|
|
|
|
kubeconstants.DefaultCertificateDir,
|
|
|
|
kubeconstants.CACertName,
|
|
|
|
))
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
parentCert, err := crypto.PemToX509Cert(parentCertRaw)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
parentKeyRaw, err := k.file.Read(filepath.Join(
|
|
|
|
kubeconstants.KubernetesDir,
|
|
|
|
kubeconstants.DefaultCertificateDir,
|
|
|
|
kubeconstants.CAKeyName,
|
|
|
|
))
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
parentKeyPEM, _ := pem.Decode(parentKeyRaw)
|
|
|
|
var parentKey any
|
|
|
|
switch parentKeyPEM.Type {
|
|
|
|
case "EC PRIVATE KEY":
|
|
|
|
parentKey, err = x509.ParseECPrivateKey(parentKeyPEM.Bytes)
|
|
|
|
case "RSA PRIVATE KEY":
|
|
|
|
parentKey, err = x509.ParsePKCS1PrivateKey(parentKeyPEM.Bytes)
|
|
|
|
case "PRIVATE KEY":
|
|
|
|
parentKey, err = x509.ParsePKCS8PrivateKey(parentKeyPEM.Bytes)
|
|
|
|
default:
|
|
|
|
err = fmt.Errorf("unsupported key type %q", parentKeyPEM.Type)
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
return parentCert, parentKey, nil
|
2022-07-15 03:33:11 -04:00
|
|
|
}
|