1package integration
2
3import (
4	"fmt"
5	"net/url"
6
7	"k8s.io/apimachinery/pkg/runtime/serializer"
8	"k8s.io/client-go/kubernetes/scheme"
9	"k8s.io/client-go/rest"
10
11	"sigs.k8s.io/controller-runtime/pkg/internal/testing/integration/internal"
12)
13
14// NewTinyCA creates a new a tiny CA utility for provisioning serving certs and client certs FOR TESTING ONLY.
15// Don't use this for anything else!
16var NewTinyCA = internal.NewTinyCA
17
18// ControlPlane is a struct that knows how to start your test control plane.
19//
20// Right now, that means Etcd and your APIServer. This is likely to increase in
21// future.
22type ControlPlane struct {
23	APIServer *APIServer
24	Etcd      *Etcd
25}
26
27// Start will start your control plane processes. To stop them, call Stop().
28func (f *ControlPlane) Start() error {
29	if f.Etcd == nil {
30		f.Etcd = &Etcd{}
31	}
32	if err := f.Etcd.Start(); err != nil {
33		return err
34	}
35
36	if f.APIServer == nil {
37		f.APIServer = &APIServer{}
38	}
39	f.APIServer.EtcdURL = f.Etcd.URL
40	return f.APIServer.Start()
41}
42
43// Stop will stop your control plane processes, and clean up their data.
44func (f *ControlPlane) Stop() error {
45	if f.APIServer != nil {
46		if err := f.APIServer.Stop(); err != nil {
47			return err
48		}
49	}
50	if f.Etcd != nil {
51		if err := f.Etcd.Stop(); err != nil {
52			return err
53		}
54	}
55	return nil
56}
57
58// APIURL returns the URL you should connect to to talk to your API.
59func (f *ControlPlane) APIURL() *url.URL {
60	return f.APIServer.URL
61}
62
63// KubeCtl returns a pre-configured KubeCtl, ready to connect to this
64// ControlPlane.
65func (f *ControlPlane) KubeCtl() *KubeCtl {
66	k := &KubeCtl{}
67	k.Opts = append(k.Opts, fmt.Sprintf("--server=%s", f.APIURL()))
68	return k
69}
70
71// RESTClientConfig returns a pre-configured restconfig, ready to connect to
72// this ControlPlane.
73func (f *ControlPlane) RESTClientConfig() (*rest.Config, error) {
74	c := &rest.Config{
75		Host: f.APIURL().String(),
76		ContentConfig: rest.ContentConfig{
77			NegotiatedSerializer: serializer.WithoutConversionCodecFactory{CodecFactory: scheme.Codecs},
78		},
79	}
80	err := rest.SetKubernetesDefaults(c)
81	return c, err
82}
83