-
Notifications
You must be signed in to change notification settings - Fork 706
/
server_utils.go
305 lines (274 loc) · 10.5 KB
/
server_utils.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
// Copyright 2021-2022 the Kubeapps contributors.
// SPDX-License-Identifier: Apache-2.0
package main
import (
"fmt"
"sort"
"strings"
"time"
"github.com/Masterminds/semver/v3"
kappcmdcore "github.com/k14s/kapp/pkg/kapp/cmd/core"
corev1 "github.com/kubeapps/kubeapps/cmd/kubeapps-apis/gen/core/packages/v1alpha1"
"github.com/kubeapps/kubeapps/cmd/kubeapps-apis/plugins/pkg/pkgutils"
kappctrlv1alpha1 "github.com/vmware-tanzu/carvel-kapp-controller/pkg/apis/kappctrl/v1alpha1"
datapackagingv1alpha1 "github.com/vmware-tanzu/carvel-kapp-controller/pkg/apiserver/apis/datapackaging/v1alpha1"
vendirversions "github.com/vmware-tanzu/carvel-vendir/pkg/vendir/versions/v1alpha1"
"k8s.io/client-go/rest"
)
type pkgSemver struct {
pkg *datapackagingv1alpha1.Package
version *semver.Version
}
// pkgVersionsMap recturns a map of packages keyed by the packagemetadataName.
//
// A Package CR in carvel is really a particular version of a package, so we need
// to sort them by the package metadata name, since this is what they share in common.
// The packages are then sorted by version.
func getPkgVersionsMap(packages []*datapackagingv1alpha1.Package) (map[string][]pkgSemver, error) {
pkgVersionsMap := map[string][]pkgSemver{}
for _, pkg := range packages {
semverVersion, err := semver.NewVersion(pkg.Spec.Version)
if err != nil {
return nil, fmt.Errorf("required field spec.version was not semver compatible on kapp-controller Package: %v\n%v", err, pkg)
}
pkgVersionsMap[pkg.Spec.RefName] = append(pkgVersionsMap[pkg.Spec.RefName], pkgSemver{pkg, semverVersion})
}
for _, pkgVersions := range pkgVersionsMap {
sort.Slice(pkgVersions, func(i, j int) bool {
return pkgVersions[i].version.GreaterThan(pkgVersions[j].version)
})
}
return pkgVersionsMap, nil
}
// latestMatchingVersion returns the latest version of a package that matches the given version constraint.
func latestMatchingVersion(versions []pkgSemver, constraints string) (*semver.Version, error) {
// constraints can be a single one (e.g., ">1.2.3") or a range (e.g., ">1.0.0 <2.0.0 || 3.0.0")
constraint, err := semver.NewConstraint(constraints)
if err != nil {
return nil, fmt.Errorf("the version in the constraint ('%s') is not semver-compatible: %v", constraints, err)
}
// assuming 'versions' is sorted,
// get the first version that satisfies the constraint
for _, v := range versions {
if constraint.Check(v.version) {
return v.version, nil
}
}
return nil, nil
}
// statusReasonForKappStatus returns the reason for a given status
func statusReasonForKappStatus(status kappctrlv1alpha1.AppConditionType) corev1.InstalledPackageStatus_StatusReason {
switch status {
case kappctrlv1alpha1.ReconcileSucceeded:
return corev1.InstalledPackageStatus_STATUS_REASON_INSTALLED
case "ValuesSchemaCheckFailed", kappctrlv1alpha1.ReconcileFailed:
return corev1.InstalledPackageStatus_STATUS_REASON_FAILED
case kappctrlv1alpha1.Reconciling:
return corev1.InstalledPackageStatus_STATUS_REASON_PENDING
}
// Fall back to unknown/unspecified.
return corev1.InstalledPackageStatus_STATUS_REASON_UNSPECIFIED
}
// simpleUserReasonForKappStatus returns the simplified reason for a given status
func simpleUserReasonForKappStatus(status kappctrlv1alpha1.AppConditionType) string {
switch status {
case kappctrlv1alpha1.ReconcileSucceeded:
return "Deployed"
case "ValuesSchemaCheckFailed", kappctrlv1alpha1.ReconcileFailed:
return "Reconcile failed"
case kappctrlv1alpha1.Reconciling:
return "Reconciling"
case "":
return "No status information yet"
}
// Fall back to unknown/unspecified.
return "Unknown"
}
// buildReadme generates a readme based on the information there is available
func buildReadme(pkgMetadata *datapackagingv1alpha1.PackageMetadata, foundPkgSemver *pkgSemver) string {
var readmeSB strings.Builder
if txt := pkgMetadata.Spec.LongDescription; txt != "" {
readmeSB.WriteString(fmt.Sprintf("## Description\n\n%s\n\n", txt))
}
if txt := foundPkgSemver.pkg.Spec.CapactiyRequirementsDescription; txt != "" {
readmeSB.WriteString(fmt.Sprintf("## Capactiy requirements\n\n%s\n\n", txt))
}
if txt := foundPkgSemver.pkg.Spec.ReleaseNotes; txt != "" {
readmeSB.WriteString(fmt.Sprintf("## Release notes\n\n%s\n\n", txt))
if date := foundPkgSemver.pkg.Spec.ReleasedAt.Time; date != (time.Time{}) {
txt := date.UTC().Format("January, 1 2006")
readmeSB.WriteString(fmt.Sprintf("Released at: %s\n\n", txt))
}
}
if txt := pkgMetadata.Spec.SupportDescription; txt != "" {
readmeSB.WriteString(fmt.Sprintf("## Support\n\n%s\n\n", txt))
}
if len(foundPkgSemver.pkg.Spec.Licenses) > 0 {
readmeSB.WriteString("## Licenses\n\n")
for _, license := range foundPkgSemver.pkg.Spec.Licenses {
if license != "" {
readmeSB.WriteString(fmt.Sprintf("- %s\n", license))
}
}
readmeSB.WriteString("\n")
}
return readmeSB.String()
}
// buildPostInstallationNotes generates the installation notes based on the application status
func buildPostInstallationNotes(app *kappctrlv1alpha1.App) string {
var postInstallNotesSB strings.Builder
deployStdout := ""
deployStderr := ""
fetchStdout := ""
fetchStderr := ""
if app.Status.Deploy != nil {
deployStdout = app.Status.Deploy.Stdout
deployStderr = app.Status.Deploy.Stderr
}
if app.Status.Fetch != nil {
fetchStdout = app.Status.Fetch.Stdout
fetchStderr = app.Status.Fetch.Stderr
}
if deployStdout != "" || fetchStdout != "" {
if deployStdout != "" {
postInstallNotesSB.WriteString(fmt.Sprintf("#### Deploy\n\n```\n%s\n```\n\n", deployStdout))
}
if fetchStdout != "" {
postInstallNotesSB.WriteString(fmt.Sprintf("#### Fetch\n\n```\n%s\n```\n\n", fetchStdout))
}
}
if deployStderr != "" || fetchStderr != "" {
postInstallNotesSB.WriteString("### Errors\n\n")
if deployStderr != "" {
postInstallNotesSB.WriteString(fmt.Sprintf("#### Deploy\n\n```\n%s\n```\n\n", deployStderr))
}
if fetchStderr != "" {
postInstallNotesSB.WriteString(fmt.Sprintf("#### Fetch\n\n```\n%s\n```\n\n", fetchStderr))
}
}
return postInstallNotesSB.String()
}
type (
kappControllerPluginConfig struct {
Core struct {
Packages struct {
V1alpha1 struct {
VersionsInSummary pkgutils.VersionsInSummary
TimeoutSeconds int32 `json:"timeoutSeconds"`
} `json:"v1alpha1"`
} `json:"packages"`
} `json:"core"`
KappController struct {
Packages struct {
V1alpha1 struct {
DefaultUpgradePolicy string `json:"defaultUpgradePolicy"`
DefaultPrereleasesVersionSelection []string `json:"defaultPrereleasesVersionSelection"`
DefaultAllowDowngrades bool `json:"defaultAllowDowngrades"`
} `json:"v1alpha1"`
} `json:"packages"`
} `json:"kappController"`
}
kappControllerPluginParsedConfig struct {
versionsInSummary pkgutils.VersionsInSummary
timeoutSeconds int32
defaultUpgradePolicy upgradePolicy
defaultPrereleasesVersionSelection []string
defaultAllowDowngrades bool
}
)
var defaultPluginConfig = &kappControllerPluginParsedConfig{
versionsInSummary: pkgutils.GetDefaultVersionsInSummary(),
timeoutSeconds: fallbackTimeoutSeconds,
defaultUpgradePolicy: fallbackDefaultUpgradePolicy,
defaultPrereleasesVersionSelection: fallbackDefaultPrereleasesVersionSelection(),
defaultAllowDowngrades: fallbackDefaultAllowDowngrades,
}
// Create a upgradePolicy enum-alike
type upgradePolicy int
const (
none upgradePolicy = iota
patch
minor
major
)
var upgradePolicyMapping = map[string]upgradePolicy{
"": none,
"none": none,
"major": major,
"minor": minor,
"patch": patch,
}
func (s upgradePolicy) string() string {
switch s {
case major:
return "major"
case minor:
return "minor"
case patch:
return "patch"
case none:
return "none"
}
return "none"
}
func versionConstraintWithUpgradePolicy(pkgVersion string, policy upgradePolicy) (string, error) {
version, err := semver.NewVersion(pkgVersion)
if err != nil {
return "", err
}
// Example: 1.2.3
switch policy {
case major:
// >= 1.2.3 (1.2.4 and 1.3.0 and 2.0.0 are valid)
return fmt.Sprintf(">=%s", version.String()), nil
case minor:
// >= 1.2.3 <2.0.0 (1.2.4 and 1.3.0 are valid, but 2.0.0 is not)
return fmt.Sprintf(">=%s <%s", version.String(), version.IncMajor().String()), nil
case patch:
// >= 1.2.3 <2.0.0 (1.2.4 is valid, but 1.3.0 and 2.0.0 are not)
return fmt.Sprintf(">=%s <%s", version.String(), version.IncMinor().String()), nil
case none:
// 1.2.3 (only 1.2.3 is valid)
return version.String(), nil
}
// Default: 1.2.3 (only 1.2.3 is valid)
return version.String(), nil
}
// prereleasesVersionSelection returns the proper value to the prereleases used in kappctrl from the selection
func prereleasesVersionSelection(prereleasesVersionSelection []string) *vendirversions.VersionSelectionSemverPrereleases {
// More info on the semantics of prereleases
// https://kubernetes.slack.com/archives/CH8KCCKA5/p1643376802571959
if prereleasesVersionSelection == nil {
// Exception: if the version constraint is a prerelease itself:
// Current behavior (as of v0.32.0): error, it won't install a prerelease if `prereleases: nil`:
// Future behavior: install it, it won't be required to set `prereleases: {}` if the version constraint is a prerelease
return nil
}
// `prereleases: {}`: allow any prerelease if the version constraint allows it
if len(prereleasesVersionSelection) == 0 {
return &vendirversions.VersionSelectionSemverPrereleases{}
} else {
// `prereleases: {Identifiers: []string{"foo"}}`: allow only prerelease with "foo" as part of the name if the version constraint allows it
prereleases := &vendirversions.VersionSelectionSemverPrereleases{Identifiers: []string{}}
for _, prereleaseVersionSelectionId := range prereleasesVersionSelection {
prereleases.Identifiers = append(prereleases.Identifiers, prereleaseVersionSelectionId)
}
return prereleases
}
}
// implementing a custom ConfigFactory to allow for customizing the *rest.Config
// https://kubernetes.slack.com/archives/CH8KCCKA5/p1642015047046200
type ConfigurableConfigFactoryImpl struct {
kappcmdcore.ConfigFactoryImpl
config *rest.Config
}
var _ kappcmdcore.ConfigFactory = &ConfigurableConfigFactoryImpl{}
func NewConfigurableConfigFactoryImpl() *ConfigurableConfigFactoryImpl {
return &ConfigurableConfigFactoryImpl{}
}
func (f *ConfigurableConfigFactoryImpl) ConfigureRESTConfig(config *rest.Config) {
f.config = config
}
func (f *ConfigurableConfigFactoryImpl) RESTConfig() (*rest.Config, error) {
return f.config, nil
}