/
crd.go
169 lines (148 loc) · 5.63 KB
/
crd.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
/*
Copyright 2018 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 crd
import (
"context"
"fmt"
"time"
"k8s.io/klog/v2"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
crdclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
)
const (
// Sleep interval to check the CRD is present.
checkCRDPresentInterval = time.Second
// Timeout to check the CRD is present.
checkCRDPresentTimeout = 60 * time.Second
// Sleep interval to check the Established condition of CRD.
checkCRDEstablishedInterval = time.Second
// Timeout for checking the Established condition of CRD.
checkCRDEstablishedTimeout = 60 * time.Second
)
// CRDHandler takes care of ensuring CRD's for a cluster.
type CRDHandler struct {
client crdclient.Interface
logger klog.Logger
}
// NewCRDHandler returns a new CRDHandler.
func NewCRDHandler(client crdclient.Interface, logger klog.Logger) *CRDHandler {
return &CRDHandler{client, logger.WithName("CRDHandler")}
}
// EnsureCRD ensures a CRD in a cluster given the CRD's metadata.
func (h *CRDHandler) EnsureCRD(meta *CRDMeta, namespacedScoped bool) (*apiextensionsv1.CustomResourceDefinition, error) {
crd, err := h.createOrUpdateCRD(meta, namespacedScoped)
if err != nil {
return nil, err
}
// After CRD creation, it might take a few seconds for the RESTful API endpoint
// to be created. Keeps watching the Established condition of BackendConfig
// CRD to be true.
if err := wait.PollImmediate(checkCRDEstablishedInterval, checkCRDEstablishedTimeout, func() (bool, error) {
crd, err = h.client.ApiextensionsV1().CustomResourceDefinitions().Get(context.TODO(), crd.Name, metav1.GetOptions{})
if err != nil {
return false, err
}
for _, c := range crd.Status.Conditions {
if c.Type == apiextensionsv1.Established && c.Status == apiextensionsv1.ConditionTrue {
return true, nil
}
}
return false, nil
}); err != nil {
return nil, fmt.Errorf("timed out waiting for %v CRD to become Established: %v", meta.kind, err)
}
h.logger.V(0).Info("CRD is Established", "kind", meta.kind)
return crd, nil
}
func (h *CRDHandler) createOrUpdateCRD(meta *CRDMeta, namespacedScoped bool) (*apiextensionsv1.CustomResourceDefinition, error) {
updateCRD := false
crd := crd(meta, namespacedScoped, h.logger)
if err := wait.PollImmediate(checkCRDPresentInterval, checkCRDPresentTimeout, func() (bool, error) {
existingCRD, err := h.client.ApiextensionsV1().CustomResourceDefinitions().Get(context.TODO(), crd.Name, metav1.GetOptions{})
// Retry until the RBAC permissions are propagated to be able to read the CRD
if apierrors.IsForbidden(err) {
return false, nil
}
// CRD doesn't exist, create it
if apierrors.IsNotFound(err) {
return true, nil
}
// Fail on any other error
if err != nil {
return false, fmt.Errorf("failed to verify the existence of %v CRD: %v", meta.kind, err)
}
// CRD exists, get current resource version and update it
updateCRD = true
crd.ResourceVersion = existingCRD.ResourceVersion
return true, nil
}); err != nil {
return nil, fmt.Errorf("timed out waiting to Get %v CRD: %v", meta.kind, err)
}
// Update CRD if already present.
if updateCRD {
h.logger.V(0).Info("Updating existing CRD...", "kind", meta.kind)
return h.client.ApiextensionsV1().CustomResourceDefinitions().Update(context.TODO(), crd, metav1.UpdateOptions{})
}
h.logger.V(0).Info("Creating CRD...", "kind", meta.kind)
return h.client.ApiextensionsV1().CustomResourceDefinitions().Create(context.TODO(), crd, metav1.CreateOptions{})
}
func crd(meta *CRDMeta, namespacedScoped bool, logger klog.Logger) *apiextensionsv1.CustomResourceDefinition {
scope := apiextensionsv1.NamespaceScoped
if !namespacedScoped {
scope = apiextensionsv1.ClusterScoped
}
crd := &apiextensionsv1.CustomResourceDefinition{
ObjectMeta: metav1.ObjectMeta{Name: meta.plural + "." + meta.groupName},
Spec: apiextensionsv1.CustomResourceDefinitionSpec{
Group: meta.groupName,
Scope: scope,
Names: apiextensionsv1.CustomResourceDefinitionNames{
Kind: meta.kind,
ListKind: meta.listKind,
Plural: meta.plural,
Singular: meta.singular,
ShortNames: meta.shortNames,
},
},
}
if len(meta.versions) == 0 {
logger.Error(nil, "No versions specified in CRD meta")
}
var versions []apiextensionsv1.CustomResourceDefinitionVersion
for i, v := range meta.versions {
validationSchema, err := v.validation()
if err != nil {
logger.Error(err, "Error adding simple validation for CRD", "kind", meta.kind, "apiVersion", v.name)
}
if validationSchema == nil {
logger.Error(nil, "No validation schema exists for CRD", "kind", meta.kind, "apiVersion", v.name)
}
version := apiextensionsv1.CustomResourceDefinitionVersion{
Name: v.name,
Served: true,
Storage: false,
Schema: validationSchema,
Deprecated: v.deprecated,
}
// Set storage to true for the latest version.
if i == 0 {
version.Storage = true
}
versions = append(versions, version)
}
crd.Spec.Versions = versions
return crd
}