-
Notifications
You must be signed in to change notification settings - Fork 24
/
controller.go
305 lines (264 loc) · 7.74 KB
/
controller.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package utils
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"github.com/spf13/cobra"
flag "github.com/spf13/pflag"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/kubernetes"
_ "k8s.io/client-go/plugin/pkg/client/auth"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/portforward"
"k8s.io/client-go/transport/spdy"
cmdv1 "github.com/fluxninja/aperture/api/v2/gen/proto/go/aperture/cmd/v1"
"github.com/fluxninja/aperture/v2/pkg/log"
)
var controllerNs string
// ControllerConn manages flags for connecting to controller – either via
// address or kubeconfig.
type ControllerConn struct {
// kube is true if controller should be found in Kubernetes cluster.
kube bool
controllerAddr string
allowInsecure bool
skipVerify bool
kubeConfigPath string
kubeConfig *rest.Config
forwarderStopChan chan struct{}
conn *grpc.ClientConn
}
// InitFlags sets up flags for kubeRestConfig.
func (c *ControllerConn) InitFlags(flags *flag.FlagSet) {
flags.StringVar(
&c.controllerAddr,
"controller",
"",
"Address of Aperture Controller",
)
flags.BoolVar(
&c.allowInsecure,
"insecure",
false,
"Allow connection to controller running without TLS",
)
flags.BoolVar(
&c.skipVerify,
"skip-verify",
false,
"Skip TLS certificate verification while connecting to controller",
)
flags.BoolVar(
&c.kube,
"kube",
false,
"Find controller in Kubernetes cluster, instead of connecting directly",
)
flags.StringVar(
&c.kubeConfigPath,
"kube-config",
"",
"Path to the Kubernetes cluster config. Defaults to '~/.kube/config' or $KUBECONFIG",
)
flags.StringVar(
&controllerNs,
"controller-ns",
"",
"Namespace in which the Aperture Controller is running",
)
}
// PreRunE verifies flags (optionally loading kubeconfig) and should be run at PreRunE stage.
func (c *ControllerConn) PreRunE(_ *cobra.Command, _ []string) error {
if c.controllerAddr == "" && !c.kube {
log.Info().Msg("Neither --controller nor --kube flag is set. Assuming --kube=true.")
c.kube = true
}
if c.controllerAddr != "" && c.kube {
return errors.New("--controller cannot be used with --kube")
}
if c.kubeConfigPath != "" && !c.kube {
return errors.New("--kube-config can only be used with --kube")
}
if c.kube {
var err error
c.kubeConfig, err = GetKubeConfig(c.kubeConfigPath)
if err != nil {
return err
}
}
return nil
}
// client returns Controller IntrospectionClient, connecting to controller if not yet connected.
func (c *ControllerConn) IntrospectionClient() (IntrospectionClient, error) {
return c.client()
}
// client returns Controller PolicyClient, connecting to controller if not yet connected.
func (c *ControllerConn) PolicyClient() (SelfHostedPolicyClient, error) {
return c.client()
}
// client returns Controller StatusClient, connecting to controller if not yet connected.
func (c *ControllerConn) StatusClient() (StatusClient, error) {
return c.client()
}
// client returns Controller Client, connecting to controller if not yet connected.
//
// This functions is not exposed to force callers to go through the check above.
func (c *ControllerConn) client() (cmdv1.ControllerClient, error) {
if c.conn != nil {
return cmdv1.NewControllerClient(c.conn), nil
}
var addr string
var cred credentials.TransportCredentials
if c.allowInsecure {
cred = insecure.NewCredentials()
} else if c.skipVerify {
cred = credentials.NewTLS(&tls.Config{
InsecureSkipVerify: true, //nolint:gosec // Requires enabling CLI option
})
}
if !c.kube {
addr = c.controllerAddr
if cred == nil {
certPool, err := x509.SystemCertPool()
if err != nil {
return nil, err
}
cred = credentials.NewClientTLSFromCert(certPool, "")
}
} else {
deployment, err := GetControllerDeployment(c.kubeConfig, controllerNs)
if err != nil {
return nil, err
}
controllerNs = deployment.GetNamespace()
port, cert, err := c.startPortForward()
if err != nil {
return nil, fmt.Errorf("failed to start port forward for Aperture Controller: %w", err)
}
addr = fmt.Sprintf("localhost:%d", port)
if cred == nil {
if cert == nil {
return nil, errors.New("cannot find controller cert and --insecure is off")
}
certPool := x509.NewCertPool()
ok := certPool.AppendCertsFromPEM(cert)
if !ok {
return nil, fmt.Errorf("cannot apply controller cert")
}
cred = credentials.NewClientTLSFromCert(certPool, fmt.Sprintf("%s.%s", deployment.GetName(), deployment.GetNamespace()))
}
}
var err error
c.conn, err = grpc.Dial(addr, grpc.WithTransportCredentials(cred))
if err != nil {
return nil, err
}
return cmdv1.NewControllerClient(c.conn), nil
}
// PostRun cleans up ControllerConn's resources, and should be run at PostRun stage.
func (c *ControllerConn) PostRun(_ *cobra.Command, _ []string) {
if c.conn != nil {
if err := c.conn.Close(); err != nil {
log.Warn().Err(err).Msg("Failed to close controller connection")
}
}
if c.forwarderStopChan != nil {
close(c.forwarderStopChan)
}
}
func (c *ControllerConn) startPortForward() (localPort uint16, cert []byte, err error) {
clientset, err := kubernetes.NewForConfig(c.kubeConfig)
if err != nil {
return 0, nil, fmt.Errorf("failed to create Kubernetes client: %w", err)
}
// FIXME Forwarding to a service would be nicer solution, but could not make
// it work for some reason, thus forwarding to pod directly.
pods, err := clientset.CoreV1().Pods(controllerNs).List(context.Background(), metav1.ListOptions{
LabelSelector: labels.Set{"app.kubernetes.io/component": "aperture-controller"}.String(),
FieldSelector: labels.Set{"status.phase": "Running"}.String(),
})
if err != nil {
return 0, nil, fmt.Errorf("failed to list pods: %w", err)
}
if len(pods.Items) == 0 {
return 0, nil, fmt.Errorf("no pods found")
}
pod := &pods.Items[0]
path := fmt.Sprintf("/api/v1/namespaces/%s/pods/%s/portforward", pod.Namespace, pod.Name)
transport, upgrader, err := spdy.RoundTripperFor(c.kubeConfig)
if err != nil {
return 0, nil, err
}
hostIP := strings.TrimPrefix(c.kubeConfig.Host, "https://")
targetURL := url.URL{Scheme: "https", Path: path, Host: hostIP}
dialer := spdy.NewDialer(
upgrader,
&http.Client{Transport: transport},
http.MethodPost,
&targetURL,
)
c.forwarderStopChan = make(chan struct{})
readyChan := make(chan struct{})
fw, err := portforward.New(
dialer,
[]string{":8080"},
c.forwarderStopChan,
readyChan,
io.Discard,
io.Discard,
)
if err != nil {
return 0, nil, err
}
fwErrChan := make(chan error, 1)
go func() {
fwErrChan <- fw.ForwardPorts()
}()
secrets, err := clientset.CoreV1().Secrets(controllerNs).List(
context.Background(),
metav1.ListOptions{
LabelSelector: labels.Set{"app.kubernetes.io/name": "aperture"}.String(),
},
)
if err != nil || len(secrets.Items) == 0 {
return 0, nil, fmt.Errorf("no secrets found for Aperture Controller certificate")
}
for _, secret := range secrets.Items {
if !strings.HasSuffix(secret.Name, "controller-cert") {
continue
}
cert = secret.Data["crt.pem"]
}
select {
case err = <-fwErrChan:
return 0, nil, err
case <-readyChan:
}
ports, err := fw.GetPorts()
if err != nil {
return 0, nil, err
}
return ports[0].Local, cert, nil
}
// IsKube returns true if controller should be found in Kubernetes cluster.
func (c *ControllerConn) IsKube() bool {
return c.kube
}
// GetKubeRestConfig returns kubeRestConfig.
func (c *ControllerConn) GetKubeRestConfig() *rest.Config {
return c.kubeConfig
}
// GetControllerNs returns namespace in which the Aperture Controller is running.
func GetControllerNs() string {
return controllerNs
}