2020-07-08 17:06:44 +00:00
|
|
|
/*
|
|
|
|
Copyright 2020 VMware, Inc.
|
|
|
|
SPDX-License-Identifier: Apache-2.0
|
|
|
|
*/
|
|
|
|
|
|
|
|
// Package app is the command line entry point for placeholder-name.
|
|
|
|
package app
|
|
|
|
|
|
|
|
import (
|
2020-07-13 19:30:16 +00:00
|
|
|
"context"
|
|
|
|
"crypto/tls"
|
|
|
|
"crypto/x509/pkix"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
2020-07-08 17:06:44 +00:00
|
|
|
"io"
|
|
|
|
"log"
|
2020-07-13 19:30:16 +00:00
|
|
|
"net"
|
2020-07-08 17:06:44 +00:00
|
|
|
"net/http"
|
2020-07-13 19:30:16 +00:00
|
|
|
"time"
|
2020-07-08 17:06:44 +00:00
|
|
|
|
|
|
|
"github.com/spf13/cobra"
|
2020-07-13 19:30:16 +00:00
|
|
|
"golang.org/x/sync/errgroup"
|
2020-07-16 19:24:30 +00:00
|
|
|
corev1 "k8s.io/api/core/v1"
|
|
|
|
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
2020-07-19 03:52:18 +00:00
|
|
|
"k8s.io/apimachinery/pkg/runtime"
|
2020-07-16 19:24:30 +00:00
|
|
|
"k8s.io/apimachinery/pkg/util/intstr"
|
2020-07-14 15:50:14 +00:00
|
|
|
"k8s.io/apiserver/pkg/authentication/authenticator"
|
2020-07-16 19:24:30 +00:00
|
|
|
"k8s.io/client-go/kubernetes"
|
|
|
|
corev1client "k8s.io/client-go/kubernetes/typed/core/v1"
|
|
|
|
restclient "k8s.io/client-go/rest"
|
|
|
|
apiregistrationv1 "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1"
|
|
|
|
aggregationv1client "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset"
|
|
|
|
|
2020-07-19 03:57:00 +00:00
|
|
|
placeholderv1alpha1 "github.com/suzerain-io/placeholder-name-api/pkg/apis/placeholder/v1alpha1"
|
2020-07-16 19:24:30 +00:00
|
|
|
"github.com/suzerain-io/placeholder-name/internal/autoregistration"
|
2020-07-13 19:30:16 +00:00
|
|
|
"github.com/suzerain-io/placeholder-name/internal/certauthority"
|
2020-07-16 19:24:30 +00:00
|
|
|
"github.com/suzerain-io/placeholder-name/internal/downward"
|
2020-07-14 15:50:14 +00:00
|
|
|
"github.com/suzerain-io/placeholder-name/pkg/config"
|
2020-07-08 17:06:44 +00:00
|
|
|
"github.com/suzerain-io/placeholder-name/pkg/handlers"
|
|
|
|
)
|
|
|
|
|
2020-07-13 19:30:16 +00:00
|
|
|
// shutdownGracePeriod controls how long active connections are allowed to continue at shutdown.
|
|
|
|
const shutdownGracePeriod = 5 * time.Second
|
|
|
|
|
2020-07-08 17:06:44 +00:00
|
|
|
// App is an object that represents the placeholder-name application.
|
|
|
|
type App struct {
|
|
|
|
cmd *cobra.Command
|
|
|
|
|
2020-07-16 19:24:30 +00:00
|
|
|
// CLI flags
|
|
|
|
configPath string
|
|
|
|
downwardAPIPath string
|
|
|
|
|
2020-07-13 19:30:16 +00:00
|
|
|
// listen address for healthz serve
|
|
|
|
healthAddr string
|
|
|
|
|
|
|
|
// listen address for main serve
|
|
|
|
mainAddr string
|
|
|
|
|
2020-07-14 15:50:14 +00:00
|
|
|
// webhook authenticates tokens
|
|
|
|
webhook authenticator.Token
|
2020-07-08 17:06:44 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// New constructs a new App with command line args, stdout and stderr.
|
|
|
|
func New(args []string, stdout, stderr io.Writer) *App {
|
|
|
|
a := &App{
|
2020-07-13 19:30:16 +00:00
|
|
|
healthAddr: ":8080",
|
2020-07-16 19:24:30 +00:00
|
|
|
mainAddr: ":443",
|
2020-07-08 17:06:44 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
cmd := &cobra.Command{
|
|
|
|
Use: `placeholder-name`,
|
|
|
|
Long: `placeholder-name provides a generic API for mapping an external
|
|
|
|
credential from somewhere to an internal credential to be used for
|
|
|
|
authenticating to the Kubernetes API.`,
|
2020-07-13 19:30:16 +00:00
|
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
2020-07-16 19:24:30 +00:00
|
|
|
// Load the Kubernetes client configuration (kubeconfig),
|
2020-07-19 03:52:18 +00:00
|
|
|
kubeConfig, err := restclient.InClusterConfig()
|
2020-07-16 19:24:30 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("could not load in-cluster configuration: %w", err)
|
|
|
|
}
|
|
|
|
|
2020-07-19 03:52:18 +00:00
|
|
|
// explicitly use protobuf when talking to built-in kube APIs
|
|
|
|
protoKubeConfig := createProtoKubeConfig(kubeConfig)
|
|
|
|
|
2020-07-16 19:24:30 +00:00
|
|
|
// Connect to the core Kubernetes API.
|
2020-07-19 03:52:18 +00:00
|
|
|
k8s, err := kubernetes.NewForConfig(protoKubeConfig)
|
2020-07-16 19:24:30 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("could not initialize Kubernetes client: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Connect to the Kubernetes aggregation API.
|
2020-07-19 03:52:18 +00:00
|
|
|
aggregation, err := aggregationv1client.NewForConfig(protoKubeConfig)
|
2020-07-16 19:24:30 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("could not initialize Kubernetes client: %w", err)
|
|
|
|
}
|
|
|
|
return a.serve(context.Background(), k8s.CoreV1(), aggregation)
|
2020-07-08 17:06:44 +00:00
|
|
|
},
|
|
|
|
Args: cobra.NoArgs,
|
|
|
|
}
|
|
|
|
|
|
|
|
cmd.SetArgs(args)
|
|
|
|
cmd.SetOut(stdout)
|
|
|
|
cmd.SetErr(stderr)
|
|
|
|
|
|
|
|
cmd.Flags().StringVarP(
|
2020-07-16 19:24:30 +00:00
|
|
|
&a.configPath,
|
2020-07-08 17:06:44 +00:00
|
|
|
"config",
|
|
|
|
"c",
|
|
|
|
"placeholder-name.yaml",
|
|
|
|
"path to configuration file",
|
|
|
|
)
|
|
|
|
|
2020-07-16 19:24:30 +00:00
|
|
|
cmd.Flags().StringVar(
|
|
|
|
&a.downwardAPIPath,
|
|
|
|
"downward-api-path",
|
|
|
|
"/etc/podinfo",
|
|
|
|
"path to Downward API volume mount",
|
|
|
|
)
|
|
|
|
|
2020-07-08 17:06:44 +00:00
|
|
|
a.cmd = cmd
|
|
|
|
|
|
|
|
return a
|
|
|
|
}
|
|
|
|
|
|
|
|
func (a *App) Run() error {
|
|
|
|
return a.cmd.Execute()
|
|
|
|
}
|
2020-07-13 19:30:16 +00:00
|
|
|
|
2020-07-16 19:24:30 +00:00
|
|
|
func (a *App) serve(ctx context.Context, k8s corev1client.CoreV1Interface, aggregation aggregationv1client.Interface) error {
|
|
|
|
cfg, err := config.FromPath(a.configPath)
|
2020-07-14 15:50:14 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("could not load config: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
webhook, err := config.NewWebhook(cfg.WebhookConfig)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("could create webhook client: %w", err)
|
|
|
|
}
|
|
|
|
a.webhook = webhook
|
|
|
|
|
2020-07-16 19:24:30 +00:00
|
|
|
podinfo, err := downward.Load(a.downwardAPIPath)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("could not read pod metadata: %w", err)
|
|
|
|
}
|
|
|
|
|
2020-07-13 19:30:16 +00:00
|
|
|
ca, err := certauthority.New(pkix.Name{CommonName: "Placeholder CA"})
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("could not initialize CA: %w", err)
|
|
|
|
}
|
|
|
|
caBundle, err := ca.Bundle()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("could not read CA bundle: %w", err)
|
|
|
|
}
|
|
|
|
log.Printf("initialized CA bundle:\n%s", string(caBundle))
|
|
|
|
|
|
|
|
cert, err := ca.Issue(
|
|
|
|
pkix.Name{CommonName: "Placeholder Server"},
|
|
|
|
[]string{"placeholder-serve"},
|
|
|
|
24*365*time.Hour,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("could not issue serving certificate: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start an errgroup to manage the lifetimes of the various listener goroutines.
|
|
|
|
eg, ctx := errgroup.WithContext(ctx)
|
|
|
|
|
2020-07-16 19:24:30 +00:00
|
|
|
// Dynamically register our v1alpha1 API service.
|
|
|
|
service := corev1.Service{
|
|
|
|
ObjectMeta: metav1.ObjectMeta{Name: "placeholder-name-api"},
|
|
|
|
Spec: corev1.ServiceSpec{
|
|
|
|
Ports: []corev1.ServicePort{
|
|
|
|
{
|
|
|
|
Protocol: corev1.ProtocolTCP,
|
|
|
|
Port: 443,
|
|
|
|
TargetPort: intstr.IntOrString{IntVal: 443}, //TODO: parse this out of mainAddr
|
|
|
|
},
|
|
|
|
},
|
|
|
|
Selector: podinfo.Labels,
|
|
|
|
Type: corev1.ServiceTypeClusterIP,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
apiService := apiregistrationv1.APIService{
|
|
|
|
ObjectMeta: metav1.ObjectMeta{
|
2020-07-19 03:57:00 +00:00
|
|
|
Name: placeholderv1alpha1.SchemeGroupVersion.Version + "." + placeholderv1alpha1.GroupName,
|
2020-07-16 19:24:30 +00:00
|
|
|
},
|
|
|
|
Spec: apiregistrationv1.APIServiceSpec{
|
2020-07-19 03:57:00 +00:00
|
|
|
Group: placeholderv1alpha1.GroupName,
|
|
|
|
Version: placeholderv1alpha1.SchemeGroupVersion.Version,
|
2020-07-16 19:24:30 +00:00
|
|
|
CABundle: caBundle,
|
|
|
|
GroupPriorityMinimum: 2500,
|
|
|
|
VersionPriority: 10,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
if err := autoregistration.Setup(ctx, autoregistration.SetupOptions{
|
|
|
|
CoreV1: k8s,
|
|
|
|
AggregationV1: aggregation,
|
|
|
|
Namespace: podinfo.Namespace,
|
|
|
|
ServiceTemplate: service,
|
|
|
|
APIServiceTemplate: apiService,
|
|
|
|
}); err != nil {
|
|
|
|
return fmt.Errorf("could not register API service: %w", err)
|
|
|
|
}
|
|
|
|
|
2020-07-13 19:30:16 +00:00
|
|
|
// Start healthz listener
|
|
|
|
eg.Go(func() error {
|
|
|
|
log.Printf("Starting healthz serve on %v", a.healthAddr)
|
|
|
|
server := http.Server{
|
|
|
|
BaseContext: func(_ net.Listener) context.Context { return ctx },
|
|
|
|
Addr: a.healthAddr,
|
|
|
|
Handler: handlers.New(),
|
|
|
|
}
|
2020-07-14 15:50:14 +00:00
|
|
|
return runGracefully(ctx, &server, eg, server.ListenAndServe)
|
2020-07-13 19:30:16 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
// Start main service listener
|
|
|
|
eg.Go(func() error {
|
|
|
|
log.Printf("Starting main serve on %v", a.mainAddr)
|
|
|
|
server := http.Server{
|
|
|
|
BaseContext: func(_ net.Listener) context.Context { return ctx },
|
|
|
|
Addr: a.mainAddr,
|
|
|
|
TLSConfig: &tls.Config{
|
|
|
|
MinVersion: tls.VersionTLS12,
|
|
|
|
Certificates: []tls.Certificate{*cert},
|
|
|
|
},
|
2020-07-14 15:50:14 +00:00
|
|
|
Handler: http.HandlerFunc(a.exampleHandler),
|
2020-07-13 19:30:16 +00:00
|
|
|
}
|
2020-07-14 15:50:14 +00:00
|
|
|
return runGracefully(ctx, &server, eg, func() error {
|
|
|
|
// Doc for ListenAndServeTLS says we can pass empty strings if we configured
|
|
|
|
// keypair for TLS in http.Server.TLSConfig.
|
|
|
|
return server.ListenAndServeTLS("", "")
|
|
|
|
})
|
2020-07-13 19:30:16 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
if err := eg.Wait(); !errors.Is(err, http.ErrServerClosed) {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// exampleHandler is a stub to be replaced with our real server logic.
|
2020-07-14 15:50:14 +00:00
|
|
|
func (a *App) exampleHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
|
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
rsp, authenticated, err := a.webhook.AuthenticateToken(ctx, "")
|
|
|
|
log.Printf("token response: %+v", rsp)
|
|
|
|
log.Printf("token authenticated: %+v", authenticated)
|
|
|
|
log.Printf("token err: %+v", err)
|
|
|
|
|
|
|
|
_, _ = w.Write([]byte("hello world"))
|
2020-07-13 19:30:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// runGracefully runs an http.Server with graceful shutdown.
|
2020-07-14 15:50:14 +00:00
|
|
|
func runGracefully(ctx context.Context, srv *http.Server, eg *errgroup.Group, f func() error) error {
|
2020-07-13 19:30:16 +00:00
|
|
|
// Start the listener in a child goroutine.
|
2020-07-14 15:50:14 +00:00
|
|
|
eg.Go(f)
|
2020-07-13 19:30:16 +00:00
|
|
|
|
|
|
|
// If/when the context is canceled or times out, initiate shutting down the serve.
|
|
|
|
<-ctx.Done()
|
|
|
|
|
|
|
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownGracePeriod)
|
|
|
|
defer cancel()
|
|
|
|
return srv.Shutdown(shutdownCtx)
|
|
|
|
}
|
2020-07-19 03:52:18 +00:00
|
|
|
|
|
|
|
// createProtoKubeConfig returns a copy of the input config with the ContentConfig set to use protobuf.
|
|
|
|
// do not use this config to communicate with any CRD based APIs.
|
|
|
|
func createProtoKubeConfig(kubeConfig *restclient.Config) *restclient.Config {
|
|
|
|
protoKubeConfig := restclient.CopyConfig(kubeConfig)
|
|
|
|
const protoThenJSON = runtime.ContentTypeProtobuf + "," + runtime.ContentTypeJSON
|
|
|
|
protoKubeConfig.AcceptContentTypes = protoThenJSON
|
|
|
|
protoKubeConfig.ContentType = runtime.ContentTypeProtobuf
|
|
|
|
return protoKubeConfig
|
|
|
|
}
|