-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathclient.go
251 lines (205 loc) · 6.92 KB
/
client.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
package client
import (
"context"
"encoding/json"
"reflect"
"github.com/go-kit/kit/log"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
var (
DefaultUpdatePreparations = []UpdatePreparation{
UpdatePreparationFunc(PrepareServiceForUpdate),
UpdatePreparationFunc(PrepareDeploymentForUpdate),
}
DefaultUpdateChecks = []UpdateCheck{
UpdateCheckFunc(CheckServiceAccountForUpdate),
}
)
type UpdatePreparation interface {
Prepare(current, updated *unstructured.Unstructured) error
}
type UpdatePreparationFunc func(current, updated *unstructured.Unstructured) error
func (f UpdatePreparationFunc) Prepare(current, updated *unstructured.Unstructured) error {
return f(current, updated)
}
type UpdateCheck interface {
Check(current, updated *unstructured.Unstructured) (bool, error)
}
type UpdateCheckFunc func(current, updated *unstructured.Unstructured) (bool, error)
func (f UpdateCheckFunc) Check(current, updated *unstructured.Unstructured) (bool, error) {
return f(current, updated)
}
type Client struct {
kclient kubernetes.Interface
cfg *rest.Config
updatePreparations []UpdatePreparation
updateChecks []UpdateCheck
logger log.Logger
}
func NewClient(cfg *rest.Config, kclient kubernetes.Interface) *Client {
c := &Client{
logger: log.NewNopLogger(),
kclient: kclient,
cfg: cfg,
}
return c
}
func (c *Client) WithLogger(logger log.Logger) {
c.logger = logger
}
func (c *Client) SetUpdatePreparations(preparations []UpdatePreparation) {
c.updatePreparations = preparations
}
func (c *Client) SetUpdateChecks(checks []UpdateCheck) {
c.updateChecks = checks
}
func (c *Client) ClientForUnstructured(u *unstructured.Unstructured) (*ResourceClient, error) {
return c.ClientFor(u.GetAPIVersion(), u.GetKind(), u.GetNamespace())
}
func (c *Client) ClientFor(apiVersion, kind, namespace string) (*ResourceClient, error) {
apiResourceList, err := c.kclient.Discovery().ServerResourcesForGroupVersion(apiVersion)
if err != nil {
return nil, errors.Wrapf(err, "discovering resource information failed for %s in %s", kind, apiVersion)
}
dc, err := newForConfig(apiResourceList.GroupVersion, c.cfg)
if err != nil {
return nil, errors.Wrapf(err, "creating dynamic client failed for %s", apiResourceList.GroupVersion)
}
gv, err := schema.ParseGroupVersion(apiResourceList.GroupVersion)
if err != nil {
return nil, errors.Wrapf(err, "parsing GroupVersion failed %s", apiResourceList.GroupVersion)
}
resourceName := ""
for _, r := range apiResourceList.APIResources {
if r.Kind == kind {
resourceName = r.Name
break
}
}
gvr := schema.GroupVersionResource{
Group: gv.Group,
Version: gv.Version,
Resource: resourceName,
}
return &ResourceClient{ResourceInterface: dc.Resource(gvr).Namespace(namespace), updatePreparations: c.updatePreparations, updateChecks: c.updateChecks}, nil
}
func newForConfig(groupVersion string, c *rest.Config) (dynamic.Interface, error) {
config := *c
err := setConfigDefaults(groupVersion, &config)
if err != nil {
return nil, err
}
return dynamic.NewForConfig(&config)
}
func setConfigDefaults(groupVersion string, config *rest.Config) error {
gv, err := schema.ParseGroupVersion(groupVersion)
if err != nil {
return err
}
config.GroupVersion = &gv
config.APIPath = "/apis"
if config.GroupVersion.Group == "" && config.GroupVersion.Version == "v1" {
config.APIPath = "/api"
}
return nil
}
type ResourceClient struct {
dynamic.ResourceInterface
updatePreparations []UpdatePreparation
updateChecks []UpdateCheck
}
func (rc *ResourceClient) UpdateWithCurrent(ctx context.Context, current, updated *unstructured.Unstructured, subresources ...string) (*unstructured.Unstructured, error) {
if err := rc.prepareUnstructuredForUpdate(current, updated); err != nil {
return nil, err
}
needUpdate, err := rc.checkUnstructuredForUpdate(current, updated)
if err != nil {
return nil, err
}
if !needUpdate {
return nil, nil
}
return rc.ResourceInterface.Update(ctx, updated, v1.UpdateOptions{}, subresources...)
}
func (rc *ResourceClient) prepareUnstructuredForUpdate(current, updated *unstructured.Unstructured) error {
updated.SetResourceVersion(current.GetResourceVersion())
for _, p := range rc.updatePreparations {
if err := p.Prepare(current, updated); err != nil {
return err
}
}
return nil
}
func (rc *ResourceClient) checkUnstructuredForUpdate(current, updated *unstructured.Unstructured) (bool, error) {
for _, p := range rc.updateChecks {
needUpdate, err := p.Check(current, updated)
if err != nil {
return needUpdate, err
}
if !needUpdate {
return needUpdate, nil
}
}
return true, nil
}
// For ServiceAccount, check if name/namespace/labels/annotations change, then do update.
// or else, it creates secrets per time when do update.
func CheckServiceAccountForUpdate(current, updated *unstructured.Unstructured) (bool, error) {
if updated.GetAPIVersion() == "v1" && updated.GetKind() == "ServiceAccount" {
currentJSON, _ := current.MarshalJSON()
currentSA := &corev1.ServiceAccount{}
err := json.Unmarshal(currentJSON, currentSA)
if err != nil {
return true, err
}
updatedJSON, _ := updated.MarshalJSON()
updatedSA := &corev1.ServiceAccount{}
err = json.Unmarshal(updatedJSON, updatedSA)
if err != nil {
return true, err
}
if currentSA.ObjectMeta.GetName() == updatedSA.ObjectMeta.GetName() &&
currentSA.ObjectMeta.GetNamespace() == updatedSA.ObjectMeta.GetNamespace() &&
reflect.DeepEqual(currentSA.ObjectMeta.GetLabels(), updatedSA.ObjectMeta.GetLabels()) &&
reflect.DeepEqual(currentSA.ObjectMeta.GetAnnotations(), updatedSA.ObjectMeta.GetAnnotations()) {
return false, nil
}
}
return true, nil
}
func PrepareServiceForUpdate(current, updated *unstructured.Unstructured) error {
if updated.GetAPIVersion() == "v1" && updated.GetKind() == "Service" {
clusterIP, found, err := unstructured.NestedString(current.Object, "spec", "clusterIP")
if err != nil {
return err
}
if found {
return unstructured.SetNestedField(updated.Object, clusterIP, "spec", "clusterIP")
}
}
return nil
}
const (
deploymentRevisionAnnotation = "deployment.kubernetes.io/revision"
)
func PrepareDeploymentForUpdate(current, updated *unstructured.Unstructured) error {
if (updated.GetAPIVersion() == "apps/v1" || updated.GetAPIVersion() == "v1beta2") && updated.GetKind() == "Deployment" {
updatedAnnotations := updated.GetAnnotations()
if updatedAnnotations == nil {
updatedAnnotations = map[string]string{}
}
curAnnotations := current.GetAnnotations()
if curAnnotations != nil {
updatedAnnotations[deploymentRevisionAnnotation] = curAnnotations[deploymentRevisionAnnotation]
updated.SetAnnotations(updatedAnnotations)
}
}
return nil
}