forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
project_actions.go
398 lines (343 loc) · 13.2 KB
/
project_actions.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
package project
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/ghodss/yaml"
"github.com/pkg/errors"
"github.com/rancher/norman/api/handler"
"github.com/rancher/norman/httperror"
"github.com/rancher/norman/types"
"github.com/rancher/norman/types/convert"
"github.com/rancher/rancher/pkg/clustermanager"
"github.com/rancher/rancher/pkg/monitoring"
"github.com/rancher/rancher/pkg/ref"
"github.com/rancher/types/apis/management.cattle.io/v3"
managementschema "github.com/rancher/types/apis/management.cattle.io/v3/schema"
"github.com/rancher/types/client/management/v3"
"github.com/rancher/types/compose"
"github.com/rancher/types/user"
)
func Formatter(apiContext *types.APIContext, resource *types.RawResource) {
resource.AddAction(apiContext, "setpodsecuritypolicytemplate")
resource.AddAction(apiContext, "exportYaml")
if err := apiContext.AccessControl.CanDo(v3.ProjectGroupVersionKind.Group, v3.ProjectResource.Name, "update", apiContext, resource.Values, apiContext.Schema); err == nil {
if convert.ToBool(resource.Values["enableProjectMonitoring"]) {
resource.AddAction(apiContext, "disableMonitoring")
resource.AddAction(apiContext, "editMonitoring")
} else {
resource.AddAction(apiContext, "enableMonitoring")
}
}
if convert.ToBool(resource.Values["enableProjectMonitoring"]) {
resource.AddAction(apiContext, "viewMonitoring")
}
}
type Handler struct {
Projects v3.ProjectInterface
ProjectLister v3.ProjectLister
ClusterManager *clustermanager.Manager
UserMgr user.Manager
}
func (h *Handler) Actions(actionName string, action *types.Action, apiContext *types.APIContext) error {
canUpdateProject := func() bool {
project := map[string]interface{}{
"id": apiContext.ID,
}
return apiContext.AccessControl.CanDo(v3.ProjectGroupVersionKind.Group, v3.ProjectResource.Name, "update", apiContext, project, apiContext.Schema) == nil
}
switch actionName {
case "setpodsecuritypolicytemplate":
return h.setPodSecurityPolicyTemplate(actionName, action, apiContext)
case "exportYaml":
return h.ExportYamlHandler(actionName, action, apiContext)
case "viewMonitoring":
return h.viewMonitoring(actionName, action, apiContext)
case "editMonitoring":
if !canUpdateProject() {
return httperror.NewAPIError(httperror.Unauthorized, "can not access")
}
return h.editMonitoring(actionName, action, apiContext)
case "enableMonitoring":
if !canUpdateProject() {
return httperror.NewAPIError(httperror.Unauthorized, "can not access")
}
return h.enableMonitoring(actionName, action, apiContext)
case "disableMonitoring":
if !canUpdateProject() {
return httperror.NewAPIError(httperror.Unauthorized, "can not access")
}
return h.disableMonitoring(actionName, action, apiContext)
}
return errors.Errorf("unrecognized action %v", actionName)
}
func (h *Handler) ExportYamlHandler(actionName string, action *types.Action, apiContext *types.APIContext) error {
namespace, id := ref.Parse(apiContext.ID)
project, err := h.ProjectLister.Get(namespace, id)
if err != nil {
return err
}
topkey := compose.Config{}
topkey.Version = "v3"
p := client.Project{}
if err := convert.ToObj(project.Spec, &p); err != nil {
return err
}
topkey.Projects = map[string]client.Project{}
topkey.Projects[project.Spec.DisplayName] = p
m, err := convert.EncodeToMap(topkey)
if err != nil {
return err
}
delete(m["projects"].(map[string]interface{})[project.Spec.DisplayName].(map[string]interface{}), "actions")
delete(m["projects"].(map[string]interface{})[project.Spec.DisplayName].(map[string]interface{}), "links")
data, err := json.Marshal(m)
if err != nil {
return err
}
buf, err := yaml.JSONToYAML(data)
if err != nil {
return err
}
reader := bytes.NewReader(buf)
apiContext.Response.Header().Set("Content-Type", "text/yaml")
http.ServeContent(apiContext.Response, apiContext.Request, "exportYaml", time.Now(), reader)
return nil
}
func (h *Handler) viewMonitoring(actionName string, action *types.Action, apiContext *types.APIContext) error {
namespace, id := ref.Parse(apiContext.ID)
project, err := h.ProjectLister.Get(namespace, id)
if err != nil {
return httperror.WrapAPIError(err, httperror.NotFound, "none existent Project")
}
if project.DeletionTimestamp != nil {
return httperror.NewAPIError(httperror.InvalidType, "deleting Project")
}
if !project.Spec.EnableProjectMonitoring {
return httperror.NewAPIError(httperror.InvalidState, "disabling Monitoring")
}
// need to support `map[string]string` as entry value type in norman Builder.convertMap
answers, err := convert.EncodeToMap(monitoring.GetOverwroteAppAnswers(project.Annotations))
if err != nil {
return httperror.WrapAPIError(err, httperror.ServerError, "failed to parse response")
}
apiContext.WriteResponse(http.StatusOK, map[string]interface{}{
"answers": answers,
"type": "monitoringOutput",
})
return nil
}
func (h *Handler) editMonitoring(actionName string, action *types.Action, apiContext *types.APIContext) error {
namespace, id := ref.Parse(apiContext.ID)
project, err := h.ProjectLister.Get(namespace, id)
if err != nil {
return httperror.WrapAPIError(err, httperror.NotFound, "none existent Project")
}
if project.DeletionTimestamp != nil {
return httperror.NewAPIError(httperror.InvalidType, "deleting Project")
}
if !project.Spec.EnableProjectMonitoring {
return httperror.NewAPIError(httperror.InvalidState, "disabling Monitoring")
}
data, err := ioutil.ReadAll(apiContext.Request.Body)
if err != nil {
return httperror.WrapAPIError(err, httperror.InvalidBodyContent, "unable to read request content")
}
var input v3.MonitoringInput
if err = json.Unmarshal(data, &input); err != nil {
return httperror.WrapAPIError(err, httperror.InvalidBodyContent, "failed to parse request content")
}
project = project.DeepCopy()
project.Annotations = monitoring.AppendAppOverwritingAnswers(project.Annotations, string(data))
_, err = h.Projects.Update(project)
if err != nil {
return httperror.WrapAPIError(err, httperror.ServerError, "failed to upgrade Monitoring")
}
apiContext.WriteResponse(http.StatusNoContent, map[string]interface{}{})
return nil
}
func (h *Handler) enableMonitoring(actionName string, action *types.Action, apiContext *types.APIContext) error {
namespace, id := ref.Parse(apiContext.ID)
project, err := h.ProjectLister.Get(namespace, id)
if err != nil {
return httperror.WrapAPIError(err, httperror.NotFound, "none existent Project")
}
if project.DeletionTimestamp != nil {
return httperror.NewAPIError(httperror.InvalidType, "deleting Project")
}
if project.Spec.EnableProjectMonitoring {
apiContext.WriteResponse(http.StatusNoContent, map[string]interface{}{})
return nil
}
data, err := ioutil.ReadAll(apiContext.Request.Body)
if err != nil {
return httperror.WrapAPIError(err, httperror.InvalidBodyContent, "unable to read request content")
}
var input v3.MonitoringInput
if err = json.Unmarshal(data, &input); err != nil {
return httperror.WrapAPIError(err, httperror.InvalidBodyContent, "failed to parse request content")
}
project = project.DeepCopy()
project.Spec.EnableProjectMonitoring = true
project.Annotations = monitoring.AppendAppOverwritingAnswers(project.Annotations, string(data))
_, err = h.Projects.Update(project)
if err != nil {
return httperror.WrapAPIError(err, httperror.ServerError, "failed to enable monitoring")
}
apiContext.WriteResponse(http.StatusNoContent, map[string]interface{}{})
return nil
}
func (h *Handler) disableMonitoring(actionName string, action *types.Action, apiContext *types.APIContext) error {
namespace, id := ref.Parse(apiContext.ID)
project, err := h.ProjectLister.Get(namespace, id)
if err != nil {
return httperror.WrapAPIError(err, httperror.NotFound, "none existent Project")
}
if project.DeletionTimestamp != nil {
return httperror.NewAPIError(httperror.InvalidType, "deleting Project")
}
if !project.Spec.EnableProjectMonitoring {
apiContext.WriteResponse(http.StatusNoContent, map[string]interface{}{})
return nil
}
project = project.DeepCopy()
project.Spec.EnableProjectMonitoring = false
_, err = h.Projects.Update(project)
if err != nil {
return httperror.WrapAPIError(err, httperror.ServerError, "failed to disable monitoring")
}
apiContext.WriteResponse(http.StatusNoContent, map[string]interface{}{})
return nil
}
func (h *Handler) setPodSecurityPolicyTemplate(actionName string, action *types.Action,
request *types.APIContext) error {
input, err := handler.ParseAndValidateActionBody(request, request.Schemas.Schema(&managementschema.Version,
client.SetPodSecurityPolicyTemplateInputType))
if err != nil {
return fmt.Errorf("error parse/validate action body: %v", err)
}
podSecurityPolicyTemplateName, ok :=
input[client.PodSecurityPolicyTemplateProjectBindingFieldPodSecurityPolicyTemplateName].(string)
if !ok && input[client.PodSecurityPolicyTemplateProjectBindingFieldPodSecurityPolicyTemplateName] != nil {
return fmt.Errorf("could not convert: %v",
input[client.PodSecurityPolicyTemplateProjectBindingFieldPodSecurityPolicyTemplateName])
}
schema := request.Schemas.Schema(&managementschema.Version, client.PodSecurityPolicyTemplateProjectBindingType)
if schema == nil {
return fmt.Errorf("no %v store available", client.PodSecurityPolicyTemplateProjectBindingType)
}
err = h.createOrUpdateBinding(request, schema, podSecurityPolicyTemplateName)
if err != nil {
return err
}
project, err := h.updateProjectPSPTID(request, podSecurityPolicyTemplateName)
if err != nil {
return fmt.Errorf("error updating PSPT ID: %v", err)
}
request.WriteResponse(http.StatusOK, project)
return nil
}
func (h *Handler) createOrUpdateBinding(request *types.APIContext, schema *types.Schema,
podSecurityPolicyTemplateName string) error {
bindings, err := schema.Store.List(request, schema, &types.QueryOptions{
Conditions: []*types.QueryCondition{
types.NewConditionFromString(client.PodSecurityPolicyTemplateProjectBindingFieldTargetProjectName,
types.ModifierEQ, request.ID),
},
})
if err != nil {
return fmt.Errorf("error retrieving binding: %v", err)
}
if podSecurityPolicyTemplateName == "" {
for _, binding := range bindings {
namespace, okNamespace := binding[client.PodSecurityPolicyTemplateProjectBindingFieldNamespaceId].(string)
name, okName := binding[client.PodSecurityPolicyTemplateProjectBindingFieldName].(string)
if okNamespace && okName {
_, err := schema.Store.Delete(request, schema, namespace+":"+name)
if err != nil {
return fmt.Errorf("error deleting binding: %v", err)
}
} else {
return fmt.Errorf("could not convert name or namespace field: %v %v",
binding[client.PodSecurityPolicyTemplateProjectBindingFieldNamespaceId],
binding[client.PodSecurityPolicyTemplateProjectBindingFieldName])
}
}
} else {
if len(bindings) == 0 {
err = h.createNewBinding(request, schema, podSecurityPolicyTemplateName)
if err != nil {
return fmt.Errorf("error creating binding: %v", err)
}
} else {
binding := bindings[0]
id, ok := binding["id"].(string)
if ok {
split := strings.Split(id, ":")
binding, err = schema.Store.ByID(request, schema, split[0]+":"+split[len(split)-1])
if err != nil {
return fmt.Errorf("error retreiving binding: %v for %v", err, bindings[0])
}
err = h.updateBinding(binding, request, schema, podSecurityPolicyTemplateName)
if err != nil {
return err
}
} else {
return fmt.Errorf("could not convert id field: %v", binding["id"])
}
}
}
return nil
}
func (h *Handler) updateProjectPSPTID(request *types.APIContext,
podSecurityPolicyTemplateName string) (*v3.Project, error) {
split := strings.Split(request.ID, ":")
project, err := h.ProjectLister.Get(split[0], split[len(split)-1])
if err != nil {
return nil, fmt.Errorf("error getting project: %v", err)
}
project = project.DeepCopy()
project.Status.PodSecurityPolicyTemplateName = podSecurityPolicyTemplateName
return h.Projects.Update(project)
}
func (h *Handler) createNewBinding(request *types.APIContext, schema *types.Schema,
podSecurityPolicyTemplateName string) error {
binding := make(map[string]interface{})
binding["targetProjectId"] = request.ID
binding["podSecurityPolicyTemplateId"] = podSecurityPolicyTemplateName
binding["namespaceId"] = strings.Split(request.ID, ":")[0]
_, err := schema.Store.Create(request, schema, binding)
return err
}
func (h *Handler) updateBinding(binding map[string]interface{}, request *types.APIContext, schema *types.Schema,
podSecurityPolicyTemplateName string) error {
binding[client.PodSecurityPolicyTemplateProjectBindingFieldPodSecurityPolicyTemplateName] =
podSecurityPolicyTemplateName
id, err := getID(binding["id"])
if err != nil {
return err
}
binding["id"] = id
if _, ok := binding["id"].(string); ok && id != "" {
var err error
binding, err = schema.Store.Update(request, schema, binding, id)
if err != nil {
return fmt.Errorf("error updating binding: %v", err)
}
} else {
return fmt.Errorf("could not parse: %v", binding["id"])
}
return nil
}
func getID(id interface{}) (string, error) {
s, ok := id.(string)
if !ok {
return "", fmt.Errorf("could not convert %v", id)
}
split := strings.Split(s, ":")
return split[0] + ":" + split[len(split)-1], nil
}