98 lines
2.4 KiB
Go
98 lines
2.4 KiB
Go
package controller
|
|
|
|
import (
|
|
"context"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/spf13/cobra"
|
|
"k8s.io/cli-runtime/pkg/genericclioptions"
|
|
"k8s.io/klog/v2"
|
|
|
|
mksadmission "example.com/monok8s/pkg/controller/admission"
|
|
"example.com/monok8s/pkg/kube"
|
|
"example.com/monok8s/pkg/templates"
|
|
)
|
|
|
|
type ServerConfig struct {
|
|
TLSCertFile string `json:"tlsCertFile,omitempty"`
|
|
TLSPrivateKeyFile string `json:"tlsPrivateKeyFile,omitempty"`
|
|
}
|
|
|
|
func NewCmdController(flags *genericclioptions.ConfigFlags) *cobra.Command {
|
|
var namespace string = templates.DefaultNamespace
|
|
var conf ServerConfig
|
|
|
|
cmd := &cobra.Command{
|
|
Use: "controller",
|
|
Short: "Admission controller that handles OSUpgrade resources",
|
|
RunE: func(cmd *cobra.Command, _ []string) error {
|
|
|
|
ctx := cmd.Context()
|
|
|
|
klog.InfoS("starting controller",
|
|
"namespace", namespace,
|
|
)
|
|
|
|
clients, err := kube.NewClients(flags)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return httpListen(ctx, clients, conf)
|
|
},
|
|
}
|
|
|
|
cmd.Flags().StringVar(&namespace, "namespace", templates.DefaultNamespace, "namespace to watch")
|
|
cmd.Flags().StringVar(&conf.TLSCertFile, "tls-cert-file", conf.TLSCertFile,
|
|
"File containing x509 Certificate used for serving HTTPS (with intermediate certs, if any, concatenated after server cert).")
|
|
cmd.Flags().StringVar(&conf.TLSPrivateKeyFile, "tls-private-key-file", conf.TLSPrivateKeyFile, "File containing x509 private key matching --tls-cert-file.")
|
|
|
|
return cmd
|
|
}
|
|
|
|
func httpListen(ctx context.Context, clients *kube.Clients, conf ServerConfig) error {
|
|
address, port := "", "8443"
|
|
addr := net.JoinHostPort(address, port)
|
|
|
|
ns := os.Getenv("POD_NAMESPACE")
|
|
nodeName := os.Getenv("NODE_NAME")
|
|
|
|
server := mksadmission.NewServer(ctx, clients, ns, nodeName)
|
|
|
|
s := &http.Server{
|
|
Addr: addr,
|
|
Handler: server,
|
|
IdleTimeout: 90 * time.Second,
|
|
ReadTimeout: 4 * 60 * time.Minute,
|
|
WriteTimeout: 4 * 60 * time.Minute,
|
|
MaxHeaderBytes: 1 << 20,
|
|
}
|
|
|
|
if conf.TLSCertFile != "" {
|
|
klog.InfoS("starting HTTPS server",
|
|
"addr", addr,
|
|
"certFile", conf.TLSCertFile,
|
|
"keyFile", conf.TLSPrivateKeyFile,
|
|
)
|
|
|
|
if err := s.ListenAndServeTLS(conf.TLSCertFile, conf.TLSPrivateKeyFile); err != nil {
|
|
klog.ErrorS(err, "HTTPS server failed")
|
|
os.Exit(1)
|
|
}
|
|
} else {
|
|
klog.InfoS("starting HTTP server",
|
|
"addr", addr,
|
|
)
|
|
|
|
if err := s.ListenAndServe(); err != nil {
|
|
klog.ErrorS(err, "HTTP server failed")
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|