/
apply.go
378 lines (316 loc) · 11.6 KB
/
apply.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
/*
Copyright 2023 Stefan Prodan
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 (
"context"
"errors"
"fmt"
"os"
"strings"
"time"
"cuelang.org/go/cue/cuecontext"
"github.com/fluxcd/pkg/ssa"
"github.com/go-logr/logr"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
apiv1 "github.com/stefanprodan/timoni/api/v1alpha1"
"github.com/stefanprodan/timoni/internal/engine"
"github.com/stefanprodan/timoni/internal/engine/fetcher"
"github.com/stefanprodan/timoni/internal/flags"
"github.com/stefanprodan/timoni/internal/runtime"
)
var applyCmd = &cobra.Command{
Use: "apply [INSTANCE NAME] [MODULE URL]",
Aliases: []string{"install", "upgrade"},
Short: "Install or upgrade a module instance",
Long: `The apply command installs or upgrades a module instance on the Kubernetes cluster.
The apply command performs the following steps:
- Pulls the module version from the specified container registry.
- If the registry is private, uses the credentials found in '~/.docker/config.json'.
- If the registry credentials are specified with '--creds', these take priority over the docker ones.
- Creates the specified '--namespace' if it doesn't exist.
- Merges all the values supplied with '--values' on top of the default values found in the module.
- Builds the module by passing the instance name, namespace and values.
- Labels the resulting Kubernetes resources with the instance name and namespace.
- Applies the Kubernetes resources on the cluster.
- Creates or updates the instance inventory with the last applied resources IDs (stored in a secret named timoni.<instance_name>).
- Recreates the resources annotated with 'action.timoni.sh/force: "enabled"' if they contain changes to immutable fields.
- Waits for the applied resources to become ready.
- Deletes the resources which were previously applied but are missing from the current instance.
- Skips the resources annotated with 'action.timoni.sh/prune: "disabled"' from deletion.
- Waits for the deleted resources to be finalised.
`,
Example: ` # Install a module instance and create the namespace if it doesn't exists
timoni apply -n apps app oci://docker.io/org/module -v 1.0.0
# Do a dry-run upgrade and print the diff
timoni apply -n apps app oci://docker.io/org/module -v 1.0.0 \
--values ./values-1.cue \
--dry-run --diff
# Install or upgrade an instance with custom values by merging them in the specified order
timoni apply -n apps app oci://docker.io/org/module -v 1.0.0 \
--values ./values-1.cue \
--values ./values-2.cue
# Upgrade an instance and recreate immutable Kubernetes resources such as Jobs
timoni apply -n apps app oci://docker.io/org/module -v 2.0.0 \
--values ./values-1.cue \
--force
# Install or upgrade an instance with custom values from stdin
echo "values: replicas: 2" | timoni apply -n apps app oci://docker.io/org/module --values -
# Install or upgrade an instance with values in YAML and JSON format
timoni apply -n apps app oci://docker.io/org/module \
--values ./values-1.yaml \
--values ./values-2.json
`,
RunE: runApplyCmd,
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
switch len(args) {
case 0:
return completeInstanceList(cmd, args, toComplete)
case 1:
return nil, cobra.ShellCompDirectiveFilterDirs
default:
return nil, cobra.ShellCompDirectiveNoFileComp
}
},
}
type applyFlags struct {
name string
module string
version flags.Version
pkg flags.Package
valuesFiles []string
dryrun bool
diff bool
wait bool
force bool
overwriteOwnership bool
creds flags.Credentials
}
var applyArgs applyFlags
func init() {
applyCmd.Flags().VarP(&applyArgs.version, applyArgs.version.Type(), applyArgs.version.Shorthand(), applyArgs.version.Description())
applyCmd.Flags().VarP(&applyArgs.pkg, applyArgs.pkg.Type(), applyArgs.pkg.Shorthand(), applyArgs.pkg.Description())
applyCmd.Flags().StringSliceVarP(&applyArgs.valuesFiles, "values", "f", nil,
"The local path to values files (cue, yaml or json format).")
applyCmd.Flags().BoolVar(&applyArgs.force, "force", false,
"Recreate immutable Kubernetes resources.")
applyCmd.Flags().BoolVar(&applyArgs.overwriteOwnership, "overwrite-ownership", false,
"Overwrite instance ownership, if the instance is owned by a Bundle.")
applyCmd.Flags().BoolVar(&applyArgs.dryrun, "dry-run", false,
"Perform a server-side apply dry run.")
applyCmd.Flags().BoolVar(&applyArgs.diff, "diff", false,
"Perform a server-side apply dry run and prints the diff.")
applyCmd.Flags().BoolVar(&applyArgs.wait, "wait", true,
"Wait for the applied Kubernetes objects to become ready.")
applyCmd.Flags().Var(&applyArgs.creds, applyArgs.creds.Type(), applyArgs.creds.Description())
rootCmd.AddCommand(applyCmd)
}
func runApplyCmd(cmd *cobra.Command, args []string) error {
if len(args) < 2 {
return errors.New("name and module are required")
}
applyArgs.name = args[0]
applyArgs.module = args[1]
log := LoggerInstance(cmd.Context(), applyArgs.name)
version := applyArgs.version.String()
if version == "" {
version = apiv1.LatestVersion
}
if strings.HasPrefix(applyArgs.module, apiv1.ArtifactPrefix) {
log.Info(fmt.Sprintf("pulling %s:%s", applyArgs.module, version))
} else {
log.Info(fmt.Sprintf("building %s", applyArgs.module))
}
tmpDir, err := os.MkdirTemp("", apiv1.FieldManager)
if err != nil {
return err
}
defer os.RemoveAll(tmpDir)
ctxPull, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
defer cancel()
f, err := fetcher.New(ctxPull, fetcher.Options{
Source: applyArgs.module,
Version: version,
Destination: tmpDir,
CacheDir: rootArgs.cacheDir,
Creds: applyArgs.creds.String(),
Insecure: rootArgs.registryInsecure,
DefaultLocal: true,
})
if err != nil {
return err
}
mod, err := f.Fetch()
if err != nil {
return err
}
cuectx := cuecontext.New()
builder := engine.NewModuleBuilder(
cuectx,
applyArgs.name,
*kubeconfigArgs.Namespace,
f.GetModuleRoot(),
applyArgs.pkg.String(),
)
if err := builder.WriteSchemaFile(); err != nil {
return err
}
mod.Name, err = builder.GetModuleName()
if err != nil {
return err
}
log.Info(fmt.Sprintf("using module %s version %s", mod.Name, mod.Version))
if len(applyArgs.valuesFiles) > 0 {
valuesCue, err := convertToCue(cmd, applyArgs.valuesFiles)
if err != nil {
return err
}
err = builder.MergeValuesFile(valuesCue)
if err != nil {
return err
}
}
kubeVersion, err := runtime.ServerVersion(kubeconfigArgs)
if err != nil {
return err
}
builder.SetVersionInfo(mod.Version, kubeVersion)
buildResult, err := builder.Build()
if err != nil {
return describeErr(f.GetModuleRoot(), "build failed", err)
}
finalValues, err := builder.GetDefaultValues()
if err != nil {
return fmt.Errorf("failed to extract values: %w", err)
}
applySets, err := builder.GetApplySets(buildResult)
if err != nil {
return fmt.Errorf("failed to extract objects: %w", err)
}
var objects []*unstructured.Unstructured
for _, set := range applySets {
objects = append(objects, set.Objects...)
}
rm, err := runtime.NewResourceManager(kubeconfigArgs)
if err != nil {
return err
}
rm.SetOwnerLabels(objects, applyArgs.name, *kubeconfigArgs.Namespace)
ctx, cancel := context.WithTimeout(cmd.Context(), rootArgs.timeout)
defer cancel()
exists := false
sm := runtime.NewStorageManager(rm)
instance, err := sm.Get(ctx, applyArgs.name, *kubeconfigArgs.Namespace)
if err == nil {
exists = true
}
nsExists, err := sm.NamespaceExists(ctx, *kubeconfigArgs.Namespace)
if err != nil {
return fmt.Errorf("instance init failed: %w", err)
}
if !applyArgs.overwriteOwnership && exists {
err = instanceOwnershipConflicts(*instance)
if err != nil {
return err
}
}
im := runtime.NewInstanceManager(applyArgs.name, *kubeconfigArgs.Namespace, finalValues, *mod)
if err := im.AddObjects(objects); err != nil {
return fmt.Errorf("adding objects to instance failed: %w", err)
}
staleObjects, err := sm.GetStaleObjects(ctx, &im.Instance)
if err != nil {
return fmt.Errorf("getting stale objects failed: %w", err)
}
if applyArgs.dryrun || applyArgs.diff {
if !nsExists {
log.Info(colorizeJoin(colorizeNamespaceFromArgs(), ssa.CreatedAction, dryRunServer))
}
return instanceDryRunDiff(logr.NewContext(ctx, log), rm, objects, staleObjects, nsExists, tmpDir, applyArgs.diff)
}
if !exists {
log.Info(fmt.Sprintf("installing %s in namespace %s", applyArgs.name, *kubeconfigArgs.Namespace))
if err := sm.Apply(ctx, &im.Instance, true); err != nil {
return fmt.Errorf("instance init failed: %w", err)
}
if !nsExists {
log.Info(colorizeJoin(colorizeNamespaceFromArgs(), ssa.CreatedAction))
}
} else {
log.Info(fmt.Sprintf("upgrading %s in namespace %s", applyArgs.name, *kubeconfigArgs.Namespace))
}
applyOpts := runtime.ApplyOptions(applyArgs.force, rootArgs.timeout)
applyOpts.WaitInterval = 5 * time.Second
waitOptions := ssa.WaitOptions{
Interval: applyOpts.WaitInterval,
Timeout: rootArgs.timeout,
FailFast: true,
}
for _, set := range applySets {
if len(applySets) > 1 {
log.Info(fmt.Sprintf("applying %s", set.Name))
}
cs, err := rm.ApplyAllStaged(ctx, set.Objects, applyOpts)
if err != nil {
return err
}
for _, change := range cs.Entries {
log.Info(colorizeJoin(change))
}
if applyArgs.wait {
spin := StartSpinner(fmt.Sprintf("waiting for %v resource(s) to become ready...", len(set.Objects)))
err = rm.Wait(set.Objects, waitOptions)
spin.Stop()
if err != nil {
return err
}
log.Info("resources are ready")
}
}
if images, err := builder.GetContainerImages(buildResult); err == nil {
im.Instance.Images = images
}
if err := sm.Apply(ctx, &im.Instance, true); err != nil {
return fmt.Errorf("storing instance failed: %w", err)
}
var deletedObjects []*unstructured.Unstructured
if len(staleObjects) > 0 {
deleteOpts := runtime.DeleteOptions(applyArgs.name, *kubeconfigArgs.Namespace)
changeSet, err := rm.DeleteAll(ctx, staleObjects, deleteOpts)
if err != nil {
return fmt.Errorf("pruning objects failed: %w", err)
}
deletedObjects = runtime.SelectObjectsFromSet(changeSet, ssa.DeletedAction)
for _, change := range changeSet.Entries {
log.Info(colorizeJoin(change))
}
}
if applyArgs.wait {
if len(deletedObjects) > 0 {
spin := StartSpinner(fmt.Sprintf("waiting for %v resource(s) to be finalized...", len(deletedObjects)))
err = rm.WaitForTermination(deletedObjects, waitOptions)
spin.Stop()
if err != nil {
return fmt.Errorf("waiting for termination failed: %w", err)
}
log.Info("all resources are ready")
}
}
return nil
}
func instanceOwnershipConflicts(instance apiv1.Instance) error {
if currentOwnerBundle := instance.Labels[apiv1.BundleNameLabelKey]; currentOwnerBundle != "" {
return fmt.Errorf("instance ownership conflict encountered. Apply with \"--overwrite-ownership\" to gain instance ownership. Conflict: instance \"%s\" exists and is managed by bundle \"%s\"", instance.Name, currentOwnerBundle)
}
return nil
}