-
Notifications
You must be signed in to change notification settings - Fork 68
/
main.go
274 lines (222 loc) · 8.5 KB
/
main.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
/*
Copyright 2017 The Kubernetes Authors.
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 main
import (
"crypto/x509"
"encoding/pem"
"flag"
"fmt"
"time"
certificatesv1beta1 "k8s.io/api/certificates/v1beta1"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
certificatesv1beta1client "k8s.io/client-go/kubernetes/typed/certificates/v1beta1"
corev1client "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/workqueue"
"k8s.io/klog"
mapiclient "github.com/openshift/cluster-api/pkg/client/clientset_generated/clientset"
machinev1beta1client "github.com/openshift/cluster-api/pkg/client/clientset_generated/clientset/typed/machine/v1beta1"
)
const machineAPINamespace = "openshift-machine-api"
type Controller struct {
config ClusterMachineApproverConfig
csrs certificatesv1beta1client.CertificateSigningRequestInterface
nodes corev1client.NodeInterface
machines machinev1beta1client.MachineInterface
indexer cache.Indexer
queue workqueue.RateLimitingInterface
informer cache.Controller
}
func NewController(config ClusterMachineApproverConfig, clientset *kubernetes.Clientset, machineClientset *mapiclient.Clientset, queue workqueue.RateLimitingInterface, indexer cache.Indexer, informer cache.Controller) *Controller {
return &Controller{
config: config,
csrs: clientset.CertificatesV1beta1().CertificateSigningRequests(),
nodes: clientset.CoreV1().Nodes(),
machines: machineClientset.MachineV1beta1().Machines(machineAPINamespace),
indexer: indexer,
queue: queue,
informer: informer,
}
}
func (c *Controller) processNextItem() bool {
// Wait until there is a new item in the working queue
key, quit := c.queue.Get()
if quit {
return false
}
// Tell the queue that we are done with processing this key. This unblocks the key for other workers
// This allows safe parallel processing because two csrs with the same key are never processed in
// parallel.
defer c.queue.Done(key)
// handle new CSR
err := c.handleNewCSR(key.(string))
// Handle the error if something went wrong during the execution of the business logic
c.handleErr(err, key)
return true
}
func (c *Controller) handleNewCSR(key string) error {
obj, exists, err := c.indexer.GetByKey(key)
if err != nil {
klog.Errorf("Fetching object with key %s from store failed with %v", key, err)
return err
}
if !exists {
// Below we will warm up our cache with a CSR, so that we will see a delete for one csr
klog.Infof("CSR %s does not exist anymore", key)
return nil
}
// do not mutate informer cache
csr := obj.(*certificatesv1beta1.CertificateSigningRequest).DeepCopy()
// Note that you also have to check the uid if you have a local controlled resource, which
// is dependent on the actual instance, to detect that a CSR was recreated with the same name
klog.Infof("CSR %s added", csr.Name)
if isApproved(csr) {
klog.Infof("CSR %s is already approved", csr.Name)
return nil
}
if pending := recentlyPendingCSRs(c.indexer); pending > maxPendingCSRs {
klog.Infof("ignoring all CSRs as too many recent pending CSRs seen: %d", pending)
return nil
}
parsedCSR, err := parseCSR(csr)
if err != nil {
klog.Infof("error parsing request CSR: %v", err)
return nil
}
machines, err := c.machines.List(metav1.ListOptions{})
if err != nil {
return fmt.Errorf("failed to list machines: %v", err)
}
if err := authorizeCSR(c.config, machines.Items, c.nodes, csr, parsedCSR); err != nil {
// Don't deny since it might be someone else's CSR
klog.Infof("CSR %s not authorized: %v", csr.Name, err)
return err
}
csr.Status.Conditions = append(csr.Status.Conditions, certificatesv1beta1.CertificateSigningRequestCondition{
Type: certificatesv1beta1.CertificateApproved,
Reason: "NodeCSRApprove",
Message: "This CSR was approved by the Node CSR Approver",
LastUpdateTime: metav1.Now(),
})
if _, err := c.csrs.UpdateApproval(csr); err != nil {
return err
}
klog.Infof("CSR %s approved", csr.Name)
return nil
}
// handleErr checks if an error happened and makes sure we will retry later.
func (c *Controller) handleErr(err error, key interface{}) {
if err == nil {
// Forget about the #AddRateLimited history of the key on every successful synchronization.
// This ensures that future processing of updates for this key is not delayed because of
// an outdated error history.
c.queue.Forget(key)
return
}
// This controller retries 5 times if something goes wrong. After that, it stops trying.
if c.queue.NumRequeues(key) < 5 {
klog.Infof("Error syncing csr %v: %v", key, err)
// Re-enqueue the key rate limited. Based on the rate limiter on the
// queue and the re-enqueue history, the key will be processed later again.
c.queue.AddRateLimited(key)
return
}
c.queue.Forget(key)
// Report to an external entity that, even after several retries, we could not successfully process this key
utilruntime.HandleError(err)
klog.Infof("Dropping CSR %q out of the queue: %v", key, err)
}
func (c *Controller) Run(threadiness int, stopCh chan struct{}) {
defer utilruntime.HandleCrash()
// Let the workers stop when we are done
defer c.queue.ShutDown()
klog.Info("Starting Machine Approver")
go c.informer.Run(stopCh)
// Wait for all involved caches to be synced, before processing items from the queue is started
if !cache.WaitForCacheSync(stopCh, c.informer.HasSynced) {
utilruntime.HandleError(fmt.Errorf("Timed out waiting for caches to sync"))
return
}
for i := 0; i < threadiness; i++ {
go wait.Until(c.runWorker, time.Second, stopCh)
}
<-stopCh
}
func (c *Controller) runWorker() {
for c.processNextItem() {
}
}
func main() {
var (
kubeconfig string
master string
cliConfig string
)
klog.InitFlags(nil)
flag.StringVar(&kubeconfig, "kubeconfig", "", "absolute path to the kubeconfig file")
flag.StringVar(&master, "master", "", "master url")
flag.StringVar(&cliConfig, "config", "", "CLI config")
flag.Parse()
// creates the connection
config, err := clientcmd.BuildConfigFromFlags(master, kubeconfig)
if err != nil {
klog.Fatal(err)
}
// creates the clientset
client, err := kubernetes.NewForConfig(config)
if err != nil {
klog.Fatal(err)
}
machineClient, err := mapiclient.NewForConfig(config)
if err != nil {
klog.Fatal(err)
}
// create the csr watcher
csrListWatcher := cache.NewListWatchFromClient(client.CertificatesV1beta1().RESTClient(), "certificatesigningrequests", v1.NamespaceAll, fields.Everything())
// create the workqueue
queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())
// Bind the workqueue to a cache with the help of an informer. This way we make sure that
// whenever the cache is updated, the csr key is added to the workqueue.
// Note that when we finally process the item from the workqueue, we might see a newer version
// of the CSR than the version which was responsible for triggering the update.
indexer, informer := cache.NewIndexerInformer(csrListWatcher, &certificatesv1beta1.CertificateSigningRequest{}, 0, cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
key, err := cache.MetaNamespaceKeyFunc(obj)
if err == nil {
queue.Add(key)
}
},
}, cache.Indexers{})
controller := NewController(loadConfig(cliConfig), client, machineClient, queue, indexer, informer)
// Now let's start the controller
stop := make(chan struct{})
defer close(stop)
go controller.Run(1, stop)
// Wait forever
select {}
}
// parseCSR extracts the CSR from the API object and decodes it.
func parseCSR(obj *certificatesv1beta1.CertificateSigningRequest) (*x509.CertificateRequest, error) {
// extract PEM from request object
block, _ := pem.Decode(obj.Spec.Request)
if block == nil || block.Type != "CERTIFICATE REQUEST" {
return nil, fmt.Errorf("PEM block type must be CERTIFICATE REQUEST")
}
return x509.ParseCertificateRequest(block.Bytes)
}