Skip to content
Snippets Groups Projects
kubernetes.go 2.26 KiB
package wrappers

import (
	"context"

	"github.com/spf13/pflag"
	"k8s.io/component-base/cli/flag"
	apiserver "k8s.io/kubernetes/cmd/kube-apiserver/app"
	apiserveropts "k8s.io/kubernetes/cmd/kube-apiserver/app/options"
	cm "k8s.io/kubernetes/cmd/kube-controller-manager/app"
	scheduler "k8s.io/kubernetes/cmd/kube-scheduler/app"
	scheduleropts "k8s.io/kubernetes/cmd/kube-scheduler/app/options"
	kubelet "k8s.io/kubernetes/cmd/kubelet/app"
)

func ControllerManager(ctx context.Context, args []string) (context.Context, error) {
	command := cm.NewControllerManagerCommand()
	command.SetArgs(args)
	newCtx, cancel := context.WithCancel(ctx)

	go func() {
		command.ExecuteContext(ctx)
		cancel()
	}()

	return newCtx, nil
}

func Scheduler(ctx context.Context, args []string) (context.Context, error) {
	config := scheduleropts.NewOptions()
	flags := flagsFromNamedFlagSet("scheduler", config.Flags)
	if err := flags.Parse(args); err != nil {
		return nil, err
	}
	cc, sched, err := scheduler.Setup(ctx, config)
	if err != nil {
		return nil, err
	}

	newCtx, cancel := context.WithCancel(ctx)

	go func() {
		scheduler.Run(ctx, cc, sched)
		cancel()
	}()

	return newCtx, nil
}

func Kubelet(ctx context.Context, args []string) (context.Context, error) {
	command := kubelet.NewKubeletCommand()
	command.SetArgs(args)
	newCtx, cancel := context.WithCancel(ctx)

	go func() {
		command.ExecuteContext(ctx)
		cancel()
	}()

	return newCtx, nil
}

func APIServer(ctx context.Context, args []string) (context.Context, error) {
	config := apiserveropts.NewServerRunOptions()
	nfs := config.Flags()
	flags := flagsFromNamedFlagSet("apiserver", &nfs)
	if err := flags.Parse(args); err != nil {
		return nil, err
	}
	completedOptions, err := apiserver.Complete(config)
	if err != nil {
		return nil, err
	}
	server, err := apiserver.CreateServerChain(completedOptions)
	if err != nil {
		return nil, err
	}
	prepared, err := server.PrepareRun()
	if err != nil {
		return nil, err
	}

	newCtx, cancel := context.WithCancel(ctx)

	go func() {
		prepared.Run(ctx.Done())
		cancel()
	}()

	return newCtx, nil
}

func flagsFromNamedFlagSet(name string, nfs *flag.NamedFlagSets) *pflag.FlagSet {
	flags := pflag.NewFlagSet(name, pflag.ContinueOnError)
	for _, f := range nfs.FlagSets {
		flags.AddFlagSet(f)
	}
	return flags
}