penguin/monok8s

k8s image for Mono Gateway Dev Kit

clitools/pkg/cmd/agent/agent.go

raw ยท 2051 bytes

package agent

import (
	"context"
	"fmt"
	"time"

	"github.com/spf13/cobra"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/cli-runtime/pkg/genericclioptions"
	"k8s.io/klog/v2"

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

func NewCmdAgent(flags *genericclioptions.ConfigFlags) *cobra.Command {
	var namespace string
	var envFile string

	cmd := &cobra.Command{
		Use:   "agent --env-file path",
		Short: "Watch OSUpgrade resources and do nothing for now",
		RunE: func(cmd *cobra.Command, _ []string) error {

			var cfg *monov1alpha1.MonoKSConfig // or value, depending on your API

			if err := mkscmd.LoadEnvFile(envFile); err != nil {
				return fmt.Errorf("load env file %q: %w", envFile, err)
			}
			vals := templates.LoadTemplateValuesFromEnv()
			rendered := templates.DefaultMonoKSConfig(vals)
			cfg = &rendered

			klog.InfoS("starting agent", "node", cfg.Spec.NodeName, "envFile", envFile)

			clients, err := kube.NewClients(flags)
			if err != nil {
				return err
			}
			gvr := schema.GroupVersionResource{Group: monov1alpha1.Group, Version: monov1alpha1.Version, Resource: "osupgrades"}
			ctx := cmd.Context()
			for {
				list, err := clients.Dynamic.Resource(gvr).Namespace(namespace).List(ctx, metav1.ListOptions{})
				if err != nil {
					return err
				}
				klog.InfoS("agent tick", "namespace", namespace, "items", len(list.Items))
				for _, item := range list.Items {
					klog.InfoS("observed osupgrade", "name", item.GetName(), "resourceVersion", item.GetResourceVersion())
				}
				select {
				case <-ctx.Done():
					return ctx.Err()
				case <-time.After(15 * time.Second):
				}
			}
		},
	}
	cmd.Flags().StringVar(&namespace, "namespace", "kube-system", "namespace to watch")
	cmd.Flags().StringVar(&envFile, "env-file", "", "path to env file containing MKS_* variables")
	return cmd
}

var _ = context.Background
var _ = fmt.Sprintf