/
cloudflaretunnel_controller.go
522 lines (468 loc) · 18.4 KB
/
cloudflaretunnel_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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
/*
Copyright 2022 Beez Innovation Labs.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package controllers
import (
"context"
"crypto/rand"
"encoding/base64"
"fmt"
"strconv"
"time"
"github.com/cloudflare/cloudflare-go"
"github.com/go-logr/logr"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
cfv1 "github.com/beezlabs-org/cloudflare-tunnel-operator/api/v1alpha1"
"github.com/beezlabs-org/cloudflare-tunnel-operator/controllers/constants"
"github.com/beezlabs-org/cloudflare-tunnel-operator/controllers/models"
)
// CloudflareTunnelReconciler reconciles a CloudflareTunnel object
type CloudflareTunnelReconciler struct {
Client client.Client
TunEx *TunnelExpanded
Scheme *runtime.Scheme
logger *logr.Logger
}
type TunnelExpanded struct {
TunSpec cfv1.CloudflareTunnelSpec
CloudflareAPI *cloudflare.API
AccountToken string // contains the token for the cloudflare account
AccountTag string // contains the user id/tag for the cloudflare account
Name string // name of the CRD as well as the tunnel
Namespace string // namespace of the CRD
TunnelID string // tunnel ID as generated by the remote
TunnelSecret string // the secret that is generated by us to create and then connect to the tunnel
}
//+kubebuilder:rbac:groups=cloudflare-tunnel-operator.beezlabs.app,resources=cloudflaretunnels,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=cloudflare-tunnel-operator.beezlabs.app,resources=cloudflaretunnels/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=cloudflare-tunnel-operator.beezlabs.app,resources=cloudflaretunnels/finalizers,verbs=update
func (r *CloudflareTunnelReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
lfc := log.FromContext(ctx)
r.logger = &lfc
lfc.Info("Reconciling...")
namespacedName := req.NamespacedName
var cloudflareTunnel cfv1.CloudflareTunnel
if err := r.Client.Get(ctx, namespacedName, &cloudflareTunnel); err != nil {
lfc.Error(err, "could not fetch CloudflareTunnel")
return ctrl.Result{}, err
}
lfc.V(1).Info("Resource fetched")
r.TunEx = &TunnelExpanded{
TunSpec: cloudflareTunnel.Spec,
Name: cloudflareTunnel.Name,
Namespace: cloudflareTunnel.Namespace,
TunnelID: cloudflareTunnel.Status.TunnelID,
}
if err := r.fetchDecodeSecret(ctx); err != nil {
return ctrl.Result{}, err
}
if err := r.createTunnelRemote(ctx); err != nil {
return ctrl.Result{}, err
}
// this concludes checking the remote tunnel config
secretCreate, err := r.createSecret(ctx, cloudflareTunnel)
if err != nil {
return ctrl.Result{}, err
}
// now we have to check the deployment status and reconcile
url, err := r.getTargetURL(ctx)
if err != nil {
lfc.Error(err, "could not generate URL")
return ctrl.Result{}, err
}
configMapCreate, err := r.createConfigMap(ctx, cloudflareTunnel, url)
if err != nil {
return ctrl.Result{}, err
}
if _, err = r.createDeployment(ctx, cloudflareTunnel, secretCreate, configMapCreate); err != nil {
return ctrl.Result{}, err
}
// finally we need to check if a CNAME exists for the given domain and create if not
if err = r.createDNSCNAME(ctx); err != nil {
return ctrl.Result{}, err
}
// update the status of the custom resource
if err := r.updateStatus(ctx, &cloudflareTunnel); err != nil {
return ctrl.Result{}, err
}
if err := r.Client.Status().Update(ctx, &cloudflareTunnel); err != nil {
return ctrl.Result{}, err
}
return ctrl.Result{RequeueAfter: time.Minute * 5}, nil
}
// SetupWithManager sets up the controller with the Manager.
func (r *CloudflareTunnelReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&cfv1.CloudflareTunnel{}).
//Owns(&appsv1.Deployment{}).
Complete(r)
}
func (r *CloudflareTunnelReconciler) fetchDecodeSecret(ctx context.Context) error {
// check if a secret name is mentioned in the resource or not
// TokenSecretName is the name of the secret resource that contains the account id and account token
if len(r.TunEx.TunSpec.TokenSecretName) == 0 {
err := fmt.Errorf("CredentialSecretName key does not exist")
r.logger.Error(err, "CredentialSecretName not found")
return err
}
var secret corev1.Secret
// try to get a secret with the given name
if err := r.Client.Get(ctx, types.NamespacedName{
Name: r.TunEx.TunSpec.TokenSecretName,
Namespace: r.TunEx.Namespace,
}, &secret); err != nil {
if errors.IsNotFound(err) {
// write a log only if the secret was not found and not for other errors
r.logger.Error(err, "could not find secret with name "+r.TunEx.TunSpec.TokenSecretName)
}
return err
}
r.logger.V(1).Info("Secret fetched")
// secret found, decode the token
encodedToken, okCred := secret.Data["token"]
encodedAccountID, okAccount := secret.Data["accountID"]
if !okCred {
err := fmt.Errorf("invalid key")
r.logger.Error(err, "key credentials not found")
return err
}
if !okAccount {
err := fmt.Errorf("invalid key")
r.logger.Error(err, "key accountID not found")
return err
}
r.logger.V(1).Info("Secret decoded")
r.TunEx.AccountTag = string(encodedAccountID)
r.TunEx.AccountToken = string(encodedToken)
return nil // everything good
}
func (r *CloudflareTunnelReconciler) createTunnelRemote(ctx context.Context) error {
cf, err := cloudflare.NewWithAPIToken(r.TunEx.AccountToken) // create new instance of cloudflare sdk
r.TunEx.CloudflareAPI = cf
if err != nil {
r.logger.Error(err, "could not create cloudflare instance")
return err
}
r.logger.V(1).Info("Cloudflare instance successfully created")
cf.AccountID = r.TunEx.AccountTag
falsePointer := false // needed as the function below only accepts a *bool
// first, we are checking if tunnels with the given name exists in the remote or not
// if they exist, we will be getting one or more of them, since cloudflare allows duplicate named tunnels
// if 2 or more exists, we check if the current CRD status already has the TunnelID or not
// if it has, we check if the returned tunnels has one with the same connector id and use it
// else, we cannot accurately figure out which one of them to use and error out
tunnelListParams := cloudflare.TunnelListParams{
Name: r.TunEx.Name,
IsDeleted: &falsePointer,
}
accountResourceContainer := cloudflare.AccountIdentifier(cf.AccountID)
// check if tunnelID already existed as part of the resource Status
if r.TunEx.TunnelID != "" {
tunnelListParams.UUID = r.TunEx.TunnelID
}
tunnels, err := cf.Tunnels(ctx, accountResourceContainer, tunnelListParams)
if err != nil {
r.logger.Error(err, "could not fetch tunnel list")
return err
}
r.logger.V(1).Info("Existing tunnels fetched")
var tunnel cloudflare.Tunnel
if len(tunnels) >= 2 {
err := fmt.Errorf("multiple tunnels exist")
r.logger.Error(err, "2 or more tunnels already exists with the given name. Unable to choose between one of them")
return err
} else if len(tunnels) == 1 {
// a single tunnel found with the same name, so we use that
r.logger.Info("Tunnel already exists. Reconciling...")
tunnel = tunnels[0]
} else {
r.logger.Info("Tunnel doesn't exist. Creating...")
tunnelSecret, err := generateTunnelSecret() // generate a random secret to be used as the tunnel secret
if err != nil {
r.logger.Error(err, "could not generate tunnel secret")
return err
}
r.logger.V(1).Info("Cloudflare Tunnel secret generated")
tunnelParams := cloudflare.TunnelCreateParams{
Name: r.TunEx.Name, // name of the tunnel is the same as the name of the CRD
Secret: tunnelSecret, // use the randomly generated secret
}
tunnel, err = cf.CreateTunnel(ctx, accountResourceContainer, tunnelParams)
if err != nil {
r.logger.Error(err, "could not create the tunnel")
return err
}
}
r.TunEx.TunnelID = tunnel.ID // assign the tunnelID from the created tunnel
tunnelToken, err := cf.TunnelToken(ctx, accountResourceContainer, tunnel.ID)
if err != nil {
r.logger.Error(err, "could not fetch tunnel token")
return err
}
tunnelTokenDecodedBytes, err := base64.StdEncoding.DecodeString(tunnelToken)
if err != nil {
r.logger.Error(err, "could not decode tunnel token")
return err
}
r.TunEx.TunnelSecret = string(tunnelTokenDecodedBytes)
return nil
}
func (r *CloudflareTunnelReconciler) createDNSCNAME(ctx context.Context) error {
zoneID, err := r.TunEx.CloudflareAPI.ZoneIDByName(r.TunEx.TunSpec.Zone)
if err != nil {
r.logger.Error(err, "could not fetch zone id")
return err
}
dnsRecords, err := r.TunEx.CloudflareAPI.DNSRecords(ctx, zoneID, cloudflare.DNSRecord{
Type: "CNAME",
Name: r.TunEx.TunSpec.Domain,
})
if err != nil {
r.logger.Error(err, "could not fetch dns list")
return err
}
truePointer := true // needed as the struct below only accepts a *bool
dnsRecord := cloudflare.DNSRecord{
Type: "CNAME",
Name: r.TunEx.TunSpec.Domain,
Content: r.TunEx.TunnelID + constants.CNAMESuffix,
TTL: 0,
Proxied: &truePointer,
}
if len(dnsRecords) >= 2 {
err := fmt.Errorf("multiple DNS records exist")
r.logger.Error(err, "2 or more DNS CNAME records already exists for the given name. Unable to choose between one of them")
return err
}
if len(dnsRecords) == 1 {
r.logger.V(1).Info("DNS record exists, updating")
if err := r.TunEx.CloudflareAPI.UpdateDNSRecord(ctx, zoneID, dnsRecords[0].ID, dnsRecord); err != nil {
r.logger.Error(err, "could not update DNS record")
return err
}
} else {
r.logger.V(1).Info("DNS record doesn't exist, creating")
_, err = r.TunEx.CloudflareAPI.CreateDNSRecord(ctx, zoneID, dnsRecord)
if err != nil {
r.logger.Error(err, "could not create DNS record")
return err
}
}
return nil
}
func (r *CloudflareTunnelReconciler) createSecret(ctx context.Context, cloudflareTunnel cfv1.CloudflareTunnel) (*corev1.Secret, error) {
// now first we create the secret containing the creds to the tunnel
// this is fully contained in the fetched tunnel secret including the tunnel id and account tag
var secretFetch corev1.Secret
secretCreate, err := models.Secret(models.SecretModel{
Name: r.TunEx.Name,
Namespace: r.TunEx.Namespace,
TunnelToken: r.TunEx.TunnelSecret,
TunnelID: r.TunEx.TunnelID,
}).GetSecret()
if err != nil {
return nil, err
}
// the secret needs to have an owner reference back to the controller
if err := ctrl.SetControllerReference(&cloudflareTunnel, secretCreate, r.Scheme); err != nil {
r.logger.Error(err, "could not create controller reference in secret")
return nil, err
}
r.logger.V(1).Info("Owner Reference for Secret created")
// try to get an existing secret with the given name
if err := r.Client.Get(ctx, types.NamespacedName{Name: secretCreate.Name, Namespace: r.TunEx.Namespace}, &secretFetch); err != nil {
if errors.IsNotFound(err) {
// error due to secret not being present, so, create one
r.logger.Info("creating secret...")
if err := r.Client.Create(ctx, secretCreate); err != nil {
r.logger.Error(err, "could not create secret in cluster")
return nil, err
}
} else {
return nil, err
}
} else {
// secret exists, so update it to ensure it is consistent
if err := r.Client.Update(ctx, secretCreate); err != nil {
r.logger.Error(err, "could not update secret")
return nil, err
}
}
return secretCreate, nil
}
func (r *CloudflareTunnelReconciler) createConfigMap(ctx context.Context, cloudflareTunnel cfv1.CloudflareTunnel, url string) (*corev1.ConfigMap, error) {
// now first we create the configMap containing the configuration to the tunnel
var configMapFetch corev1.ConfigMap
configMapCreate, err := models.ConfigMap(models.ConfigMapModel{
Name: r.TunEx.Name,
Namespace: r.TunEx.Namespace,
Service: url,
TunnelID: r.TunEx.TunnelID,
Domain: r.TunEx.TunSpec.Domain,
}).GetConfigMap()
if err != nil {
return nil, err
}
// the secret needs to have an owner reference back to the controller
if err := ctrl.SetControllerReference(&cloudflareTunnel, configMapCreate, r.Scheme); err != nil {
r.logger.Error(err, "could not create controller reference in configMap")
return nil, err
}
r.logger.V(1).Info("Owner Reference for ConfigMap created")
// try to get an existing secret with the given name
if err := r.Client.Get(ctx, types.NamespacedName{Name: configMapCreate.Name, Namespace: r.TunEx.Namespace}, &configMapFetch); err != nil {
if errors.IsNotFound(err) {
// error due to secret not being present, so, create one
r.logger.Info("creating ConfigMap...")
if err := r.Client.Create(ctx, configMapCreate); err != nil {
r.logger.Error(err, "could not create ConfigMap in cluster")
return nil, err
}
} else {
return nil, err
}
} else {
// secret exists, so update it to ensure it is consistent
if err := r.Client.Update(ctx, configMapCreate); err != nil {
r.logger.Error(err, "could not update ConfigMap")
return nil, err
}
}
return configMapCreate, nil
}
func (r *CloudflareTunnelReconciler) createDeployment(ctx context.Context, cloudflareTunnel cfv1.CloudflareTunnel, secret *corev1.Secret, configMap *corev1.ConfigMap) (*appsv1.Deployment, error) {
// now first we create the configMap containing the configuration to the tunnel
var deploymentFetch appsv1.Deployment
tunnelDeploymentModel := models.DeploymentModel{
Name: r.TunEx.Name,
Namespace: r.TunEx.Namespace,
Replicas: r.TunEx.TunSpec.Replicas,
TunnelID: r.TunEx.TunnelID,
Secret: secret,
ConfigMap: configMap,
}
if r.TunEx.TunSpec.Container != nil {
if r.TunEx.TunSpec.Container.Image != "" {
tunnelDeploymentModel.Image = r.TunEx.TunSpec.Container.Image
}
if r.TunEx.TunSpec.Container.ImagePullPolicy != "" {
tunnelDeploymentModel.ImagePullPolicy = r.TunEx.TunSpec.Container.ImagePullPolicy
}
if len(r.TunEx.TunSpec.Container.Command) != 0 {
tunnelDeploymentModel.Command = r.TunEx.TunSpec.Container.Command
}
if len(r.TunEx.TunSpec.Container.Args) != 0 {
tunnelDeploymentModel.Args = r.TunEx.TunSpec.Container.Args
}
}
deploymentCreate := models.Deployment(tunnelDeploymentModel).GetDeployment()
// the secret needs to have an owner reference back to the controller
if err := ctrl.SetControllerReference(&cloudflareTunnel, deploymentCreate, r.Scheme); err != nil {
r.logger.Error(err, "could not create controller reference in deployment")
return nil, err
}
r.logger.V(1).Info("Owner Reference for deployment created")
// try to get an existing deployment with the given name
if err := r.Client.Get(ctx, types.NamespacedName{Name: deploymentCreate.Name, Namespace: r.TunEx.Namespace}, &deploymentFetch); err != nil {
if errors.IsNotFound(err) {
// error due to secret not being present, so, create one
r.logger.Info("creating deployment...")
if err := r.Client.Create(ctx, deploymentCreate); err != nil {
r.logger.Error(err, "could not create deployment in cluster")
return nil, err
}
} else {
return nil, err
}
} else {
// deployment exists, so update it to ensure it is consistent
if err := r.Client.Update(ctx, deploymentCreate); err != nil {
r.logger.Error(err, "could not update deployment")
return nil, err
}
}
return deploymentCreate, nil
}
func (r *CloudflareTunnelReconciler) getTargetURL(ctx context.Context) (string, error) {
// first get the url for the targeted service
var targetService corev1.Service
if err := r.Client.Get(ctx, types.NamespacedName{
Name: r.TunEx.TunSpec.Service.Name,
Namespace: r.TunEx.TunSpec.Service.Namespace,
}, &targetService); err != nil {
if errors.IsNotFound(err) {
// error due to service not being present
r.logger.Error(err, "target service not present")
}
return "", err
} else {
// service exists, check if port is open
var port corev1.ServicePort
for _, servicePort := range targetService.Spec.Ports {
if servicePort.Port == r.TunEx.TunSpec.Service.Port {
r.logger.V(1).Info("Ports matched")
port = servicePort
break
}
}
if &port == nil {
r.logger.Error(err, "port doesn't exist in service")
return "", err
}
}
// if the service is a LoadBalancer then use the ingress IP as the host
if targetService.Spec.Type == corev1.ServiceTypeLoadBalancer {
return r.TunEx.TunSpec.Service.Protocol + "://" + targetService.Status.LoadBalancer.Ingress[0].IP + ":" + strconv.Itoa(int(r.TunEx.TunSpec.Service.Port)), nil
}
// else generate the URL of the form `service-name.namespace:port`
// see https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/#a-aaaa-records
return r.TunEx.TunSpec.Service.Protocol + "://" + r.TunEx.TunSpec.Service.Name + "." + r.TunEx.TunSpec.Service.Namespace + ":" + strconv.Itoa(int(r.TunEx.TunSpec.Service.Port)), nil
}
func (r *CloudflareTunnelReconciler) updateStatus(ctx context.Context, cloudflareTunnel *cfv1.CloudflareTunnel) error {
accountResourceContainer := cloudflare.AccountIdentifier(r.TunEx.CloudflareAPI.AccountID)
tunnelConnections, err := r.TunEx.CloudflareAPI.TunnelConnections(ctx, accountResourceContainer, r.TunEx.TunnelID)
if err != nil {
r.logger.Error(err, "could not fetch tunnel connections")
return err
}
var connections []cfv1.CloudflareTunnelConnections
for _, connectionMeta := range tunnelConnections { // 0 index since it will always return a single tunnel
for _, connection := range connectionMeta.Connections {
connections = append(connections, cfv1.CloudflareTunnelConnections{
ConnectorID: connectionMeta.ID,
Created: metav1.Time{Time: *connectionMeta.RunAt},
Architecture: connectionMeta.Arch,
Version: connectionMeta.Version,
OriginIP: connection.OriginIP,
Edge: connection.ColoName,
})
}
}
cloudflareTunnel.Status = cfv1.CloudflareTunnelStatus{
TunnelID: r.TunEx.TunnelID,
Connections: connections,
}
return nil
}
func generateTunnelSecret() (string, error) {
randomBytes := make([]byte, 32)
_, err := rand.Read(randomBytes)
return base64.StdEncoding.EncodeToString(randomBytes), err
}