-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
context.go
300 lines (258 loc) · 8.41 KB
/
context.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
/*
Copyright 2019 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 fi
import (
"bytes"
"context"
"fmt"
"os"
"reflect"
"strings"
"k8s.io/klog/v2"
"k8s.io/kops/pkg/apis/kops"
"k8s.io/kops/pkg/apis/nodeup"
"k8s.io/kops/util/pkg/vfs"
)
type Context[T SubContext] struct {
ctx context.Context
Target Target[T]
tasks map[string]Task[T]
warnings []*Warning[T]
T T
}
type CloudupContext = Context[CloudupSubContext]
type InstallContext = Context[InstallSubContext]
type NodeupContext = Context[NodeupSubContext]
type SubContext interface {
CloudupSubContext | InstallSubContext | NodeupSubContext
}
type CloudupSubContext struct {
Cloud Cloud
Cluster *kops.Cluster
// TODO: Few places use this. They could instead get it from the cluster spec.
ClusterConfigBase vfs.Path
Keystore Keystore
SecretStore SecretStore
}
type InstallSubContext struct{}
type NodeupSubContext struct {
BootConfig *nodeup.BootConfig
NodeupConfig *nodeup.Config
Keystore KeystoreReader
}
func (c *Context[T]) Context() context.Context {
return c.ctx
}
// Warning holds the details of a warning encountered during validation/creation
type Warning[T SubContext] struct {
Task Task[T]
Message string
}
func newContext[T SubContext](ctx context.Context, target Target[T], sub T, tasks map[string]Task[T]) (*Context[T], error) {
c := &Context[T]{
ctx: ctx,
Target: target,
tasks: tasks,
T: sub,
}
return c, nil
}
func NewInstallContext(ctx context.Context, target InstallTarget, tasks map[string]InstallTask) (*InstallContext, error) {
sub := InstallSubContext{}
return newContext[InstallSubContext](ctx, target, sub, tasks)
}
func NewNodeupContext(ctx context.Context, target NodeupTarget, keystore KeystoreReader, bootConfig *nodeup.BootConfig, nodeupConfig *nodeup.Config, tasks map[string]NodeupTask) (*NodeupContext, error) {
sub := NodeupSubContext{
BootConfig: bootConfig,
NodeupConfig: nodeupConfig,
Keystore: keystore,
}
return newContext[NodeupSubContext](ctx, target, sub, tasks)
}
func NewCloudupContext(ctx context.Context, target CloudupTarget, cluster *kops.Cluster, cloud Cloud, keystore Keystore, secretStore SecretStore, clusterConfigBase vfs.Path, tasks map[string]CloudupTask) (*CloudupContext, error) {
sub := CloudupSubContext{
Cloud: cloud,
Cluster: cluster,
ClusterConfigBase: clusterConfigBase,
Keystore: keystore,
SecretStore: secretStore,
}
return newContext[CloudupSubContext](ctx, target, sub, tasks)
}
func (c *Context[T]) AllTasks() map[string]Task[T] {
return c.tasks
}
func (c *Context[T]) RunTasks(options RunTasksOptions) error {
e := &executor[T]{
context: c,
options: options,
}
return e.RunTasks(c.tasks)
}
// Render dispatches the creation of an object to the appropriate handler defined on the Task,
// it is typically called after we have checked the existing state of the Task and determined that is different
// from the desired state.
func (c *Context[T]) Render(a, e, changes Task[T]) error {
typeContextPtr := reflect.TypeOf((*Context[T])(nil))
var lifecycle Lifecycle
if hl, ok := e.(HasLifecycle); ok {
lifecycle = hl.GetLifecycle()
}
if lifecycle != "" {
if reflect.ValueOf(a).IsNil() {
switch lifecycle {
case LifecycleExistsAndValidates:
return fmt.Errorf("lifecycle set to ExistsAndValidates, but object was not found")
case LifecycleExistsAndWarnIfChanges:
return NewExistsAndWarnIfChangesError("Lifecycle set to ExistsAndWarnIfChanges and object was not found.")
}
} else {
switch lifecycle {
case LifecycleExistsAndValidates, LifecycleExistsAndWarnIfChanges:
out := os.Stderr
changeList, err := buildChangeList(a, e, changes)
if err != nil {
return err
}
b := &bytes.Buffer{}
taskName := getTaskName(e)
fmt.Fprintf(b, "Object from different phase did not match, problems possible:\n")
fmt.Fprintf(b, " %s/%s\n", taskName, "?")
for _, change := range changeList {
lines := strings.Split(change.Description, "\n")
if len(lines) == 1 {
fmt.Fprintf(b, " \t%-20s\t%s\n", change.FieldName, change.Description)
} else {
fmt.Fprintf(b, " \t%-20s\n", change.FieldName)
for _, line := range lines {
fmt.Fprintf(b, " \t%-20s\t%s\n", "", line)
}
}
}
fmt.Fprintf(b, "\n")
b.WriteTo(out)
if lifecycle == LifecycleExistsAndValidates {
return fmt.Errorf("lifecycle set to ExistsAndValidates, but object did not match")
}
// Warn, but then we continue
return nil
}
}
}
if _, ok := c.Target.(*DryRunTarget[T]); ok {
return c.Target.(*DryRunTarget[T]).Render(a, e, changes)
}
v := reflect.ValueOf(e)
vType := v.Type()
targetType := reflect.ValueOf(c.Target).Type()
var renderer *reflect.Method
var rendererArgs []reflect.Value
for i := 0; i < vType.NumMethod(); i++ {
method := vType.Method(i)
if !strings.HasPrefix(method.Name, "Render") {
continue
}
match := true
var args []reflect.Value
for j := 0; j < method.Type.NumIn(); j++ {
arg := method.Type.In(j)
if arg.ConvertibleTo(vType) {
continue
}
if arg.ConvertibleTo(typeContextPtr) {
args = append(args, reflect.ValueOf(c))
continue
}
if arg.ConvertibleTo(targetType) {
args = append(args, reflect.ValueOf(c.Target))
continue
}
match = false
break
}
if match {
if renderer != nil {
if method.Name == "Render" {
continue
}
if renderer.Name != "Render" {
return fmt.Errorf("found multiple Render methods that could be involved on %T", e)
}
}
renderer = &method
rendererArgs = args
}
}
if renderer == nil {
return fmt.Errorf("could not find Render method on type %T (target %T)", e, c.Target)
}
rendererArgs = append(rendererArgs, reflect.ValueOf(a))
rendererArgs = append(rendererArgs, reflect.ValueOf(e))
rendererArgs = append(rendererArgs, reflect.ValueOf(changes))
klog.V(11).Infof("Calling method %s on %T", renderer.Name, e)
m := v.MethodByName(renderer.Name)
rv := m.Call(rendererArgs)
var rvErr error
if !rv[0].IsNil() {
rvErr = rv[0].Interface().(error)
}
return rvErr
}
// AddWarning records a warning encountered during validation / creation.
// Typically this will be an error that we choose to ignore because of Lifecycle.
func (c *Context[T]) AddWarning(task Task[T], message string) {
warning := &Warning[T]{
Task: task,
Message: message,
}
// We don't actually do anything with these warnings yet, other than log them to glog below.
// In future we might produce a structured warning report.
c.warnings = append(c.warnings, warning)
klog.Warningf("warning during task %s: %s", task, message)
}
// ExistsAndWarnIfChangesError is the custom error return for fi.LifecycleExistsAndWarnIfChanges.
// This error is used when an object needs to fail validation, but let the user proceed with a warning.
type ExistsAndWarnIfChangesError struct {
msg string
}
// NewExistsAndWarnIfChangesError is a builder for ExistsAndWarnIfChangesError.
func NewExistsAndWarnIfChangesError(message string) *ExistsAndWarnIfChangesError {
return &ExistsAndWarnIfChangesError{
msg: message,
}
}
// ExistsAndWarnIfChangesError implementation of the error interface.
func (e *ExistsAndWarnIfChangesError) Error() string { return e.msg }
// TryAgainLaterError is the custom used when a task needs to fail validation with a message and try again later
type TryAgainLaterError struct {
msg string
inner error
}
// NewTryAgainLaterError is a builder for TryAgainLaterError.
func NewTryAgainLaterError(message string) *TryAgainLaterError {
return &TryAgainLaterError{
msg: message,
}
}
func (e *TryAgainLaterError) WithError(err error) *TryAgainLaterError {
e.inner = err
return e
}
// TryAgainLaterError implementation of the error interface.
func (e *TryAgainLaterError) Error() string {
if e.inner != nil {
return fmt.Sprintf("%v: %v", e.msg, e.inner)
}
return e.msg
}
func (e *TryAgainLaterError) Unwrap() error { return e.inner }