forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
225 lines (211 loc) · 7.56 KB
/
app.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
package app
import (
"fmt"
"net/http"
"reflect"
"github.com/rancher/norman/api/access"
"github.com/rancher/norman/httperror"
"github.com/rancher/norman/parse"
"github.com/rancher/norman/types"
"github.com/rancher/norman/types/convert"
"github.com/rancher/norman/types/values"
"github.com/rancher/rancher/pkg/controllers/management/compose/common"
hcommon "github.com/rancher/rancher/pkg/controllers/user/helm/common"
"github.com/rancher/rancher/pkg/ref"
clusterschema "github.com/rancher/types/apis/cluster.cattle.io/v3/schema"
"github.com/rancher/types/apis/management.cattle.io/v3"
pv3 "github.com/rancher/types/apis/project.cattle.io/v3"
projectschema "github.com/rancher/types/apis/project.cattle.io/v3/schema"
clusterv3 "github.com/rancher/types/client/cluster/v3"
projectv3 "github.com/rancher/types/client/project/v3"
"github.com/rancher/types/user"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
type Wrapper struct {
Clusters v3.ClusterInterface
TemplateVersionClient v3.CatalogTemplateVersionInterface
KubeConfigGetter common.KubeConfigGetter
AppGetter pv3.AppsGetter
UserLister v3.UserLister
UserManager user.Manager
}
const (
appLabel = "io.cattle.field/appId"
MCappLabel = "mcapp"
creatorIDAnno = "field.cattle.io/creatorId"
)
func Formatter(apiContext *types.APIContext, resource *types.RawResource) {
mcappLabel := convert.ToString(values.GetValueN(resource.Values, "labels", MCappLabel))
if mcappLabel == "" {
resource.AddAction(apiContext, "upgrade")
resource.AddAction(apiContext, "rollback")
} else {
delete(resource.Links, "remove")
}
resource.Links["revision"] = apiContext.URLBuilder.Link("revision", resource)
if _, ok := resource.Values["status"]; ok {
if status, ok := resource.Values["status"].(map[string]interface{}); ok {
delete(status, "lastAppliedTemplate")
}
}
delete(resource.Values, "appliedFiles")
delete(resource.Values, "files")
}
func (w Wrapper) Validator(request *types.APIContext, schema *types.Schema, data map[string]interface{}) error {
externalID := convert.ToString(data["externalId"])
if externalID == "" {
return nil
}
templateVersionID, templateVersionNamespace, err := hcommon.ParseExternalID(externalID)
if err != nil {
return err
}
templateVersion, err := w.TemplateVersionClient.GetNamespaced(templateVersionNamespace, templateVersionID, metav1.GetOptions{})
if err != nil {
return err
}
targetNamespace := convert.ToString(data["targetNamespace"])
if templateVersion.Spec.RequiredNamespace != "" && templateVersion.Spec.RequiredNamespace != targetNamespace {
return httperror.NewAPIError(httperror.InvalidType, "template's requiredNamespace doesn't match catalog app's target namespace")
}
// in here access.ByID will only find namespace that is assigned to the current project
var ns clusterv3.Namespace
if err := access.ByID(request, &clusterschema.Version, clusterv3.NamespaceType, targetNamespace, &ns); err != nil {
return err
}
if ns.Name == "" {
return httperror.NewAPIError(httperror.InvalidReference, fmt.Sprintf("target namespace %v is not assigned to the current project %v", targetNamespace, data["projectId"]))
}
return nil
}
func (w Wrapper) ActionHandler(actionName string, action *types.Action, apiContext *types.APIContext) error {
var app projectv3.App
if err := access.ByID(apiContext, &projectschema.Version, projectv3.AppType, apiContext.ID, &app); err != nil {
return err
}
creatorNotFound := false
if _, err := w.UserLister.Get("", app.CreatorID); err != nil && apierrors.IsNotFound(err) {
creatorNotFound = true
}
userCanCreateApp := apiContext.AccessControl.CanCreate(apiContext, apiContext.Schema) == nil
if creatorNotFound && !userCanCreateApp {
return httperror.NewAPIError(httperror.PermissionDenied, "can not upgrade/rollback app")
}
actionInput, err := parse.ReadBody(apiContext.Request)
if err != nil {
return err
}
switch actionName {
case "upgrade":
externalID := actionInput["externalId"]
answers := actionInput["answers"]
forceUpgrade := actionInput["forceUpgrade"]
files := actionInput["files"]
valuesYaml := actionInput["valuesYaml"]
_, namespace := ref.Parse(app.ProjectID)
obj, err := w.AppGetter.Apps(namespace).Get(app.Name, metav1.GetOptions{})
if err != nil {
return err
}
if answers != nil {
m, ok := answers.(map[string]interface{})
if ok {
obj.Spec.Answers = make(map[string]string)
for k, v := range m {
obj.Spec.Answers[k] = convert.ToString(v)
}
}
} else {
obj.Spec.Answers = make(map[string]string)
}
obj.Spec.ExternalID = convert.ToString(externalID)
if convert.ToBool(forceUpgrade) {
pv3.AppConditionForceUpgrade.Unknown(obj)
}
if creatorNotFound {
obj.Annotations[creatorIDAnno] = w.UserManager.GetUser(apiContext)
}
if files != nil {
inputFiles := convert.ToMapInterface(files)
if len(inputFiles) != 0 {
targetFiles := make(map[string]string)
for k, v := range inputFiles {
targetFiles[k] = convert.ToString(v)
}
obj.Spec.Files = targetFiles
obj.Spec.ExternalID = "" // ignore externalID
}
}
if valuesYaml != nil {
obj.Spec.ValuesYaml = convert.ToString(valuesYaml)
} else {
obj.Spec.ValuesYaml = ""
}
// indicate this a user driven action
pv3.AppConditionUserTriggeredAction.True(obj)
if _, err := w.AppGetter.Apps(namespace).Update(obj); err != nil {
return err
}
apiContext.WriteResponse(http.StatusNoContent, map[string]interface{}{})
return nil
case "rollback":
forceUpgrade := actionInput["forceUpgrade"]
revisionName := convert.ToString(actionInput["revisionId"])
if revisionName == "" {
return fmt.Errorf("revision is empty")
}
_, projectID := ref.Parse(app.ProjectID)
revisionID := fmt.Sprintf("%s:%s", projectID, revisionName)
var appRevision projectv3.AppRevision
if err := access.ByID(apiContext, &projectschema.Version, projectv3.AppRevisionType, revisionID, &appRevision); err != nil {
return err
}
_, namespace := ref.Parse(app.ProjectID)
obj, err := w.AppGetter.Apps(namespace).Get(app.Name, metav1.GetOptions{})
if err != nil {
return err
}
obj.Spec.Answers = appRevision.Status.Answers
obj.Spec.ExternalID = appRevision.Status.ExternalID
obj.Spec.ValuesYaml = appRevision.Status.ValuesYaml
if convert.ToBool(forceUpgrade) {
pv3.AppConditionForceUpgrade.Unknown(obj)
}
if creatorNotFound {
obj.Annotations[creatorIDAnno] = w.UserManager.GetUser(apiContext)
}
obj.Spec.Files = appRevision.Status.Files
// indicate this a user driven action
pv3.AppConditionUserTriggeredAction.True(obj)
if _, err := w.AppGetter.Apps(namespace).Update(obj); err != nil {
return err
}
apiContext.WriteResponse(http.StatusNoContent, map[string]interface{}{})
return nil
}
return nil
}
func (w Wrapper) LinkHandler(apiContext *types.APIContext, next types.RequestHandler) error {
switch apiContext.Link {
case "revision":
var app projectv3.App
if err := access.ByID(apiContext, &projectschema.Version, projectv3.AppType, apiContext.ID, &app); err != nil {
return err
}
var appRevisions, filtered []map[string]interface{}
if err := access.List(apiContext, &projectschema.Version, projectv3.AppRevisionType, &types.QueryOptions{}, &appRevisions); err != nil {
return err
}
for _, re := range appRevisions {
labels := convert.ToMapInterface(re["labels"])
if reflect.DeepEqual(labels[appLabel], app.Name) {
filtered = append(filtered, re)
}
}
apiContext.Type = projectv3.AppRevisionType
apiContext.WriteResponse(http.StatusOK, filtered)
return nil
}
return nil
}