-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathupgrade.go
More file actions
293 lines (267 loc) · 10.8 KB
/
upgrade.go
File metadata and controls
293 lines (267 loc) · 10.8 KB
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
/*
Copyright (C) 2022-2025 ApeCloud Co., Ltd
This file is part of KubeBlocks project
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package addon
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/Masterminds/semver/v3"
kbappsv1 "github.com/apecloud/kubeblocks/apis/apps/v1"
extensionsv1alpha1 "github.com/apecloud/kubeblocks/apis/extensions/v1alpha1"
"github.com/apecloud/kubeblocks/pkg/constant"
"github.com/spf13/cobra"
helmaction "helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/chart/loader"
"helm.sh/helm/v3/pkg/releaseutil"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
ktypes "k8s.io/apimachinery/pkg/types"
"k8s.io/cli-runtime/pkg/genericiooptions"
cmdutil "k8s.io/kubectl/pkg/cmd/util"
"k8s.io/kubectl/pkg/util/templates"
"sigs.k8s.io/yaml"
"github.com/apecloud/kbcli/pkg/cluster"
"github.com/apecloud/kbcli/pkg/printer"
"github.com/apecloud/kbcli/pkg/util/helm"
"github.com/apecloud/kbcli/pkg/types"
"github.com/apecloud/kbcli/pkg/util"
)
var addonUpgradeExample = templates.Examples(`
# upgrade an addon from default index to latest version
kbcli addon upgrade apecloud-mysql
# upgrade an addon from default index to latest version and skip KubeBlocks version compatibility check
kbcli addon upgrade apecloud-mysql --force
# upgrade an addon to latest version from a specified index
kbcli addon upgrade apecloud-mysql --index my-index
# upgrade an addon with a specified version default index
kbcli addon upgrade apecloud-mysql --version 0.7.0
# upgrade an addon with a specified version, default index and a different version of cluster chart
kbcli addon upgrade apecloud-mysql --version 0.7.0 --cluster-chart-version 0.7.1
# non-inplace upgrade an addon with a specified version
kbcli addon upgrade apecloud-mysql --inplace=false --version 0.7.0
# non-inplace upgrade an addon with a specified addon name
kbcli addon upgrade apecloud-mysql --inplace=false --name apecloud-mysql-0.7.0
`)
// upgradeOption storage the info to upgrade an addon
type upgradeOption struct {
*installOption
// currentVersion is the addon current version in KubeBlocks
currentVersion string
// if inplace is false will retain the existing addon and reinstall the new version of the addon.
// otherwise the upgrade will be in-place. It's true in default
inplace bool
// rename is the new version addon name need to set by user when inplace is false, it also will be used as resourceNamePrefix of an addon with multiple version.
// If it's not be specified by user, use `addon-version` by default
rename string
}
func newUpgradeOption(f cmdutil.Factory, streams genericiooptions.IOStreams) *upgradeOption {
return &upgradeOption{
installOption: newInstallOption(f, streams),
currentVersion: "",
inplace: true,
rename: "",
}
}
func newUpgradeCmd(f cmdutil.Factory, streams genericiooptions.IOStreams) *cobra.Command {
o := newUpgradeOption(f, streams)
cmd := &cobra.Command{
Use: "upgrade",
Short: "Upgrade an existed addon to latest version or a specified version",
Args: cobra.ExactArgs(1),
Example: addonUpgradeExample,
ValidArgsFunction: util.ResourceNameCompletionFunc(f, o.GVR),
Run: func(cmd *cobra.Command, args []string) {
o.name = args[0]
util.CheckErr(o.Complete())
util.CheckErr(o.Validate())
util.CheckErr(o.process09ClusterDefAndComponentVersions())
util.CheckErr(o.Run(f, streams))
},
}
cmd.Flags().BoolVar(&o.force, "force", false, "force upgrade the addon and ignore the version check")
cmd.Flags().StringVar(&o.version, "version", "", "specify the addon version")
cmd.Flags().StringVar(&o.index, "index", types.DefaultIndexName, "specify the addon index index, use 'kubeblocks' by default")
cmd.Flags().BoolVar(&o.inplace, "inplace", true, "when inplace is false, it will retain the existing addon and reinstall the new version of the addon, otherwise the upgrade will be in-place. The default is true.")
cmd.Flags().StringVar(&o.rename, "name", "", "name is the new version addon name need to set by user when inplace is false, it also will be used as resourceNamePrefix of an addon with multiple version.")
cmd.Flags().StringVar(&o.clusterChartVersion, "cluster-chart-version", "", "specify the cluster chart version, use the same version as the addon by default")
cmd.Flags().StringVar(&o.clusterChartRepo, "cluster-chart-repo", types.ClusterChartsRepoURL, "specify the repo of cluster chart, use the url of 'kubeblocks-addons' by default")
cmd.Flags().StringVar(&o.path, "path", "", "specify the local path contains addon CRs and needs to be specified when operating offline")
return cmd
}
func (o *upgradeOption) Complete() error {
if err := o.installOption.Complete(); err != nil {
return err
}
addon := extensionsv1alpha1.Addon{}
err := util.GetK8SClientObject(o.Dynamic, &addon, o.GVR, "", o.name)
if err != nil {
return fmt.Errorf("addon %s not found. please use 'kbcli addon install %s' first", o.name, o.name)
}
o.currentVersion = getAddonVersion(&addon)
return nil
}
// Validate will check if the current version is already the latest version compared to installOption.Validate()
func (o *upgradeOption) Validate() error {
if o.version == "" {
o.version = getAddonVersion(o.addon)
}
if !o.inplace && o.rename == "" {
o.rename = fmt.Sprintf("%s-%s", o.name, o.version)
fmt.Printf("--name is not specified by user when upgrade is non-inplace, use \"%s\" by default\n", o.rename)
}
target, err := semver.NewVersion(o.version)
if err != nil {
return err
}
current, err := semver.NewVersion(o.currentVersion)
if err != nil {
return err
}
if !target.GreaterThan(current) {
fmt.Printf("%s addon %s current version %s is either the latest or newer than the expected version %s.\n", printer.BoldYellow("Warn:"), o.name, o.currentVersion, o.version)
}
return o.installOption.Validate()
}
func (o *upgradeOption) Run(f cmdutil.Factory, streams genericiooptions.IOStreams) error {
if !o.inplace {
if o.addon.Spec.Helm.InstallValues.SetValues != nil {
o.addon.Spec.Helm.InstallValues.SetValues = append(o.addon.Spec.Helm.InstallValues.SetValues, fmt.Sprintf("%s=%s", types.AddonResourceNamePrefix, o.rename))
}
o.addon.Spec.Helm.InstallValues.SetValues = []string{fmt.Sprintf("%s=%s", types.AddonResourceNamePrefix, o.rename)}
o.addon.Name = o.rename
err := o.installOption.Run(f, streams)
if err == nil {
fmt.Printf("Addon %s-%s upgrade successed.\n", o.rename, o.version)
}
return err
}
// in-place upgrade
newData, err := json.Marshal(o.addon)
if err != nil {
return err
}
_, err = o.Dynamic.Resource(o.GVR).Patch(context.Background(), o.name, ktypes.MergePatchType, newData, metav1.PatchOptions{})
if err == nil {
fmt.Printf("Addon %s-%s upgrade successed.\n", o.name, o.version)
}
return err
}
func (o *upgradeOption) process09ClusterDefAndComponentVersions() error {
kbDeploys, err := util.GetKBDeploys(o.Client, util.KubeblocksAppComponent, metav1.NamespaceAll)
if err != nil || len(kbDeploys) < 2 {
return err
}
if !strings.HasPrefix(o.currentVersion, "0.9") {
return nil
}
var newKBNamespace string
for _, v := range kbDeploys {
if strings.HasPrefix(v.Labels[constant.AppVersionLabelKey], "1.0") {
newKBNamespace = v.Namespace
break
}
}
// 1. get manifests from the helm repo
chartsDownloader, err := helm.NewDownloader(helm.NewConfig(newKBNamespace, "", "", false))
if err != nil {
return err
}
// DownloadTo can't specify the saved name, so download it to TempDir and rename it when copy
chartPath, _, err := chartsDownloader.DownloadTo(o.addon.Spec.Helm.ChartLocationURL, "", cluster.CliChartsCacheDir)
if err != nil {
return err
}
// 2. overwrite the spec of ClusterDefinition and ComponentVersion with the new version
actionCfg, err := helm.NewActionConfig(helm.NewConfig(newKBNamespace, "", "", false))
if err != nil {
return err
}
chart, err := loader.Load(chartPath)
if err != nil {
return err
}
renderer := helmaction.NewInstall(actionCfg)
renderer.ReleaseName = o.addon.Name + "for-upgrade"
renderer.Namespace = newKBNamespace
renderer.DryRun = true
renderer.Replace = true
renderer.ClientOnly = true
valuesMap := map[string]interface{}{}
if o.addon.Spec.Helm != nil {
for _, v := range o.addon.Spec.Helm.InstallValues.SetValues {
keyValues := strings.Split(v, "=")
if len(keyValues) != 2 {
return fmt.Errorf("invalid install value: %s", v)
}
valuesMap[keyValues[0]] = keyValues[1]
}
}
release, err := renderer.Run(chart, valuesMap)
if err != nil {
return err
}
updateObject := func(obj runtime.Object, gvr schema.GroupVersionResource) error {
unstructuredObj := obj.(*unstructured.Unstructured)
targetObj, err := o.Dynamic.Resource(gvr).Namespace("").Get(context.TODO(), unstructuredObj.GetName(), metav1.GetOptions{})
if err != nil {
if apierrors.IsNotFound(err) {
return nil
}
return err
}
annotations := targetObj.GetAnnotations()
annotations[constant.CRDAPIVersionAnnotationKey] = kbappsv1.GroupVersion.String()
annotations["meta.helm.sh/release-name"] = "kb-addon-" + o.addon.Name
annotations["meta.helm.sh/release-namespace"] = newKBNamespace
targetObj.SetAnnotations(annotations)
targetObj.Object["spec"] = unstructuredObj.Object["spec"]
if _, err = o.Dynamic.Resource(gvr).Namespace("").Update(context.TODO(), targetObj, metav1.UpdateOptions{}); err != nil {
return err
}
return nil
}
manifests := releaseutil.SplitManifests(release.Manifest)
for _, manifest := range manifests {
// convert yaml to json
jsonData, err := yaml.YAMLToJSON([]byte(manifest))
if err != nil {
return err
}
// check if jsonData is empty or null
if len(jsonData) == 0 || string(jsonData) == "null" {
continue
}
// get resource gvk
obj, gvk, err := unstructured.UnstructuredJSONScheme.Decode(jsonData, nil, nil)
if err != nil {
return err
}
switch gvk.Kind {
case types.KindClusterDef:
if err = updateObject(obj, types.ClusterDefGVR()); err != nil {
return err
}
case types.KindComponentVersion:
if err = updateObject(obj, types.ComponentVersionsGVR()); err != nil {
return err
}
}
}
return nil
}