penguin/monok8s

k8s image for Mono Gateway Dev Kit

clitools/pkg/node/agent.go

raw ยท 10036 bytes

package node

import (
	"context"
	"fmt"
	"reflect"
	"strings"

	appsv1 "k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
	rbacv1 "k8s.io/api/rbac/v1"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/klog/v2"

	monov1alpha1 "example.com/monok8s/pkg/apis/monok8s/v1alpha1"
	"example.com/monok8s/pkg/kube"
	templates "example.com/monok8s/pkg/templates"
)

const (
	controlAgentName              = "control-agent"
	controlAgentNodeSelectorValue = "true"
	controlAgentImage             = "localhost/monok8s/control-agent:dev"
	kubeconfig                    = "/etc/kubernetes/admin.conf"
)

func ApplyControlAgentDaemonSetResources(ctx context.Context, n *NodeContext) error {
	// Only the control-plane should bootstrap this DaemonSet definition.
	// And only when the feature is enabled.
	if strings.TrimSpace(n.Config.Spec.ClusterRole) != "control-plane" || !n.Config.Spec.EnableControlAgent {
		klog.InfoS("skipped for", "clusterRole", n.Config.Spec.ClusterRole, "enableControlAgent", n.Config.Spec.EnableControlAgent)
		return nil
	}

	err := ApplyCRDs(ctx, n)
	if err != nil {
		return err
	}

	namespace := strings.TrimSpace(n.Config.Namespace)
	if namespace == "" {
		namespace = templates.DefaultNamespace
	}

	clients, err := kube.NewClientsFromKubeconfig(kubeconfig)
	if err != nil {
		return fmt.Errorf("build kube clients from %s: %w", kubeconfig, err)
	}

	labels := map[string]string{
		"app.kubernetes.io/name":       controlAgentName,
		"app.kubernetes.io/component":  "agent",
		"app.kubernetes.io/part-of":    "monok8s",
		"app.kubernetes.io/managed-by": "ctl",
	}

	kubeClient := clients.Kubernetes

	if err := applyControlAgentServiceAccount(ctx, kubeClient, namespace, labels); err != nil {
		return fmt.Errorf("apply serviceaccount: %w", err)
	}
	if err := applyControlAgentClusterRole(ctx, kubeClient, labels); err != nil {
		return fmt.Errorf("apply clusterrole: %w", err)
	}
	if err := applyControlAgentClusterRoleBinding(ctx, kubeClient, namespace, labels); err != nil {
		return fmt.Errorf("apply clusterrolebinding: %w", err)
	}
	if err := applyControlAgentDaemonSet(ctx, kubeClient, namespace, labels); err != nil {
		return fmt.Errorf("apply daemonset: %w", err)
	}

	return nil
}

func applyControlAgentServiceAccount(ctx context.Context, kubeClient kubernetes.Interface, namespace string, labels map[string]string) error {
	want := &corev1.ServiceAccount{
		ObjectMeta: metav1.ObjectMeta{
			Name:      controlAgentName,
			Namespace: namespace,
			Labels:    labels,
		},
	}

	existing, err := kubeClient.CoreV1().ServiceAccounts(namespace).Get(ctx, controlAgentName, metav1.GetOptions{})
	if apierrors.IsNotFound(err) {
		_, err = kubeClient.CoreV1().ServiceAccounts(namespace).Create(ctx, want, metav1.CreateOptions{})
		return err
	}
	if err != nil {
		return err
	}

	changed := false
	if !reflect.DeepEqual(existing.Labels, want.Labels) {
		existing.Labels = want.Labels
		changed = true
	}

	if !changed {
		return nil
	}

	_, err = kubeClient.CoreV1().ServiceAccounts(namespace).Update(ctx, existing, metav1.UpdateOptions{})
	return err
}

func applyControlAgentClusterRole(ctx context.Context, kubeClient kubernetes.Interface, labels map[string]string) error {
	wantRules := []rbacv1.PolicyRule{
		{
			APIGroups: []string{monov1alpha1.Group},
			Resources: []string{"osupgrades"},
			Verbs:     []string{"get", "list", "watch"},
		},
		{
			APIGroups: []string{monov1alpha1.Group},
			Resources: []string{"osupgrades/status"},
			Verbs:     []string{"get", "patch", "update"},
		},
		{
			APIGroups: []string{""},
			Resources: []string{"nodes"},
			Verbs:     []string{"get", "list", "watch"},
		},
	}

	want := &rbacv1.ClusterRole{
		ObjectMeta: metav1.ObjectMeta{
			Name:   controlAgentName,
			Labels: labels,
		},
		Rules: wantRules,
	}

	existing, err := kubeClient.RbacV1().ClusterRoles().Get(ctx, controlAgentName, metav1.GetOptions{})
	if apierrors.IsNotFound(err) {
		_, err = kubeClient.RbacV1().ClusterRoles().Create(ctx, want, metav1.CreateOptions{})
		return err
	}
	if err != nil {
		return err
	}

	changed := false
	if !reflect.DeepEqual(existing.Labels, want.Labels) {
		existing.Labels = want.Labels
		changed = true
	}
	if !reflect.DeepEqual(existing.Rules, want.Rules) {
		existing.Rules = want.Rules
		changed = true
	}

	if !changed {
		return nil
	}

	_, err = kubeClient.RbacV1().ClusterRoles().Update(ctx, existing, metav1.UpdateOptions{})
	return err
}

func applyControlAgentClusterRoleBinding(ctx context.Context, kubeClient kubernetes.Interface, namespace string, labels map[string]string) error {
	wantRoleRef := rbacv1.RoleRef{
		APIGroup: rbacv1.GroupName,
		Kind:     "ClusterRole",
		Name:     controlAgentName,
	}
	wantSubjects := []rbacv1.Subject{
		{
			Kind:      "ServiceAccount",
			Name:      controlAgentName,
			Namespace: namespace,
		},
	}

	want := &rbacv1.ClusterRoleBinding{
		ObjectMeta: metav1.ObjectMeta{
			Name:   controlAgentName,
			Labels: labels,
		},
		RoleRef:  wantRoleRef,
		Subjects: wantSubjects,
	}

	existing, err := kubeClient.RbacV1().ClusterRoleBindings().Get(ctx, controlAgentName, metav1.GetOptions{})
	if apierrors.IsNotFound(err) {
		_, err = kubeClient.RbacV1().ClusterRoleBindings().Create(ctx, want, metav1.CreateOptions{})
		return err
	}
	if err != nil {
		return err
	}

	// roleRef is immutable. If it differs, fail loudly instead of pretending we can patch it.
	if !reflect.DeepEqual(existing.RoleRef, want.RoleRef) {
		return fmt.Errorf("existing ClusterRoleBinding %q has different roleRef and must be recreated", controlAgentName)
	}

	changed := false
	if !reflect.DeepEqual(existing.Labels, want.Labels) {
		existing.Labels = want.Labels
		changed = true
	}
	if !reflect.DeepEqual(existing.Subjects, want.Subjects) {
		existing.Subjects = want.Subjects
		changed = true
	}

	if !changed {
		return nil
	}

	_, err = kubeClient.RbacV1().ClusterRoleBindings().Update(ctx, existing, metav1.UpdateOptions{})
	return err
}

func applyControlAgentDaemonSet(ctx context.Context, kubeClient kubernetes.Interface, namespace string, labels map[string]string) error {
	privileged := true

	dsLabels := map[string]string{
		"app.kubernetes.io/name":       controlAgentName,
		"app.kubernetes.io/component":  "agent",
		"app.kubernetes.io/part-of":    "monok8s",
		"app.kubernetes.io/managed-by": "ctl",
	}

	want := &appsv1.DaemonSet{
		ObjectMeta: metav1.ObjectMeta{
			Name:      controlAgentName,
			Namespace: namespace,
			Labels:    labels,
		},
		Spec: appsv1.DaemonSetSpec{
			Selector: &metav1.LabelSelector{
				MatchLabels: map[string]string{
					"app.kubernetes.io/name": controlAgentName,
				},
			},
			Template: corev1.PodTemplateSpec{
				ObjectMeta: metav1.ObjectMeta{
					Labels: dsLabels,
				},
				Spec: corev1.PodSpec{
					ServiceAccountName: controlAgentName,
					HostNetwork:        true,
					HostPID:            true,
					DNSPolicy:          corev1.DNSClusterFirstWithHostNet,
					NodeSelector: map[string]string{
						monov1alpha1.ControlAgentKey: controlAgentNodeSelectorValue,
					},
					Tolerations: []corev1.Toleration{
						{Operator: corev1.TolerationOpExists},
					},
					Containers: []corev1.Container{
						{
							Name:            "agent",
							Image:           controlAgentImage,
							ImagePullPolicy: corev1.PullNever,
							Args:            []string{"agent", "--env-file", "$(CLUSTER_ENV_FILE)"},
							Env: []corev1.EnvVar{
								{
									Name: "NODE_NAME",
									ValueFrom: &corev1.EnvVarSource{
										FieldRef: &corev1.ObjectFieldSelector{
											APIVersion: "v1",
											FieldPath:  "spec.nodeName",
										},
									},
								},
								{
									Name:  "CLUSTER_ENV_FILE",
									Value: "/host/opt/monok8s/config/cluster.env",
								},
								{
									Name:  "FW_ENV_CONFIG_FILE",
									Value: "/host/etc/fw_env.config",
								},
							},
							SecurityContext: &corev1.SecurityContext{
								Privileged: &privileged,
							},
							VolumeMounts: []corev1.VolumeMount{
								{
									Name:      "host-dev",
									MountPath: "/dev",
								},
								{
									Name:      "host-etc",
									MountPath: "/host/etc",
									ReadOnly:  true,
								},
								{
									Name:      "host-config",
									MountPath: "/host/opt/monok8s/config",
									ReadOnly:  true,
								},
							},
						},
					},
					Volumes: []corev1.Volume{
						{
							Name: "host-dev",
							VolumeSource: corev1.VolumeSource{
								HostPath: &corev1.HostPathVolumeSource{
									Path: "/dev",
									Type: hostPathType(corev1.HostPathDirectory),
								},
							},
						},
						{
							Name: "host-etc",
							VolumeSource: corev1.VolumeSource{
								HostPath: &corev1.HostPathVolumeSource{
									Path: "/etc",
									Type: hostPathType(corev1.HostPathDirectory),
								},
							},
						},
						{
							Name: "host-config",
							VolumeSource: corev1.VolumeSource{
								HostPath: &corev1.HostPathVolumeSource{
									Path: "/opt/monok8s/config",
									Type: hostPathType(corev1.HostPathDirectory),
								},
							},
						},
					},
				},
			},
		},
	}

	existing, err := kubeClient.AppsV1().DaemonSets(namespace).Get(ctx, controlAgentName, metav1.GetOptions{})
	if apierrors.IsNotFound(err) {
		_, err = kubeClient.AppsV1().DaemonSets(namespace).Create(ctx, want, metav1.CreateOptions{})
		return err
	}
	if err != nil {
		return err
	}

	changed := false
	if !reflect.DeepEqual(existing.Labels, want.Labels) {
		existing.Labels = want.Labels
		changed = true
	}
	if !reflect.DeepEqual(existing.Spec, want.Spec) {
		existing.Spec = want.Spec
		changed = true
	}

	if !changed {
		return nil
	}

	_, err = kubeClient.AppsV1().DaemonSets(namespace).Update(ctx, existing, metav1.UpdateOptions{})
	return err
}

func hostPathType(t corev1.HostPathType) *corev1.HostPathType {
	return &t
}

func mountPropagationMode(m corev1.MountPropagationMode) *corev1.MountPropagationMode {
	return &m
}