forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
actionhandler.go
708 lines (621 loc) · 22.7 KB
/
actionhandler.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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
package cluster
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"time"
yaml2 "github.com/ghodss/yaml"
"github.com/pkg/errors"
"github.com/rancher/norman/api/access"
"github.com/rancher/norman/httperror"
"github.com/rancher/norman/types"
"github.com/rancher/norman/types/convert"
"github.com/rancher/norman/types/values"
"github.com/rancher/rancher/pkg/clustermanager"
"github.com/rancher/rancher/pkg/controllers/management/etcdbackup"
"github.com/rancher/rancher/pkg/controllers/user/nslabels"
"github.com/rancher/rancher/pkg/kubeconfig"
"github.com/rancher/rancher/pkg/kubectl"
"github.com/rancher/rancher/pkg/monitoring"
"github.com/rancher/rancher/pkg/ref"
"github.com/rancher/types/apis/cluster.cattle.io/v3/schema"
corev1 "github.com/rancher/types/apis/core/v1"
"github.com/rancher/types/apis/management.cattle.io/v3"
"github.com/rancher/types/client/cluster/v3"
mgmtclient "github.com/rancher/types/client/management/v3"
"github.com/rancher/types/compose"
"github.com/rancher/types/user"
errors2 "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
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/util/yaml"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)
type ActionHandler struct {
NodepoolGetter v3.NodePoolsGetter
ClusterClient v3.ClusterInterface
NodeTemplateGetter v3.NodeTemplatesGetter
UserMgr user.Manager
ClusterManager *clustermanager.Manager
BackupClient v3.EtcdBackupInterface
}
func (a ActionHandler) ClusterActionHandler(actionName string, action *types.Action, apiContext *types.APIContext) error {
canUpdateCluster := func() bool {
cluster := map[string]interface{}{
"id": apiContext.ID,
}
return apiContext.AccessControl.CanDo(v3.ClusterGroupVersionKind.Group, v3.ClusterResource.Name, "update", apiContext, cluster, apiContext.Schema) == nil
}
switch actionName {
case "generateKubeconfig":
return a.GenerateKubeconfigActionHandler(actionName, action, apiContext)
case "importYaml":
return a.ImportYamlHandler(actionName, action, apiContext)
case "exportYaml":
return a.ExportYamlHandler(actionName, action, apiContext)
case "viewMonitoring":
return a.viewMonitoring(actionName, action, apiContext)
case "editMonitoring":
if !canUpdateCluster() {
return httperror.NewAPIError(httperror.Unauthorized, "can not access")
}
return a.editMonitoring(actionName, action, apiContext)
case "enableMonitoring":
if !canUpdateCluster() {
return httperror.NewAPIError(httperror.Unauthorized, "can not access")
}
return a.enableMonitoring(actionName, action, apiContext)
case "disableMonitoring":
if !canUpdateCluster() {
return httperror.NewAPIError(httperror.Unauthorized, "can not access")
}
return a.disableMonitoring(actionName, action, apiContext)
case "backupEtcd":
if !canUpdateCluster() {
return httperror.NewAPIError(httperror.Unauthorized, "can not backup etcd")
}
return a.BackupEtcdHandler(actionName, action, apiContext)
case "restoreFromEtcdBackup":
if !canUpdateCluster() {
return httperror.NewAPIError(httperror.Unauthorized, "can not restore etcd backup")
}
return a.RestoreFromEtcdBackupHandler(actionName, action, apiContext)
case "rotateCertificates":
if !canUpdateCluster() {
return httperror.NewAPIError(httperror.Unauthorized, "can not rotate certificates")
}
return a.RotateCertificates(actionName, action, apiContext)
}
return httperror.NewAPIError(httperror.NotFound, "not found")
}
func (a ActionHandler) getClusterToken(clusterID string, apiContext *types.APIContext) (string, error) {
userName := a.UserMgr.GetUser(apiContext)
return a.UserMgr.EnsureClusterToken(clusterID, fmt.Sprintf("kubeconfig-%s.%s", userName, clusterID), "Kubeconfig token", userName)
}
func (a ActionHandler) getToken(apiContext *types.APIContext) (string, error) {
userName := a.UserMgr.GetUser(apiContext)
return a.UserMgr.EnsureToken("kubeconfig-"+userName, "Kubeconfig token", userName)
}
func (a ActionHandler) GenerateKubeconfigActionHandler(actionName string, action *types.Action, apiContext *types.APIContext) error {
var cluster mgmtclient.Cluster
if err := access.ByID(apiContext, apiContext.Version, apiContext.Type, apiContext.ID, &cluster); err != nil {
return err
}
var (
cfg string
token string
err error
)
if cluster.LocalClusterAuthEndpoint.Enabled {
token, err = a.getClusterToken(cluster.ID, apiContext)
} else {
token, err = a.getToken(apiContext)
}
if err != nil {
return err
}
userName := a.UserMgr.GetUser(apiContext)
if cluster.LocalClusterAuthEndpoint.Enabled {
cfg, err = kubeconfig.ForClusterTokenBased(&cluster, apiContext.ID, apiContext.Request.Host, userName, token)
} else {
cfg, err = kubeconfig.ForTokenBased(cluster.Name, apiContext.ID, apiContext.Request.Host, userName, token)
}
if err != nil {
return err
}
data := map[string]interface{}{
"config": cfg,
"type": "generateKubeconfigOutput",
}
apiContext.WriteResponse(http.StatusOK, data)
return nil
}
func (a ActionHandler) ImportYamlHandler(actionName string, action *types.Action, apiContext *types.APIContext) error {
data, err := ioutil.ReadAll(apiContext.Request.Body)
if err != nil {
return errors.Wrap(err, "reading request body error")
}
input := mgmtclient.ImportClusterYamlInput{}
if err = json.Unmarshal(data, &input); err != nil {
return errors.Wrap(err, "unmarshaling input error")
}
var cluster mgmtclient.Cluster
if err := access.ByID(apiContext, apiContext.Version, apiContext.Type, apiContext.ID, &cluster); err != nil {
return err
}
cfg, err := a.getKubeConfig(apiContext, &cluster)
if err != nil {
return err
}
for _, context := range cfg.Contexts {
if input.DefaultNamespace == "" {
context.Namespace = input.Namespace
} else {
context.Namespace = input.DefaultNamespace
}
}
var msg []byte
if input.ProjectID != "" {
err = a.processYAML(apiContext, cluster.ID, input.ProjectID, input.YAML)
if err == nil {
msg, err = kubectl.Apply([]byte(input.YAML), cfg)
}
} else if input.Namespace == "" {
msg, err = kubectl.Apply([]byte(input.YAML), cfg)
} else {
msg, err = kubectl.ApplyWithNamespace([]byte(input.YAML), input.Namespace, cfg)
}
rtn := map[string]interface{}{
"message": string(msg),
"type": "importYamlOutput",
}
if err == nil {
apiContext.WriteResponse(http.StatusOK, rtn)
} else {
if rtn["message"] == "" {
rtn["message"] = err.Error()
}
apiContext.WriteResponse(http.StatusBadRequest, rtn)
}
return nil
}
func (a ActionHandler) ExportYamlHandler(actionName string, action *types.Action, apiContext *types.APIContext) error {
cluster, err := a.ClusterClient.Get(apiContext.ID, metav1.GetOptions{})
if err != nil {
return err
}
topkey := compose.Config{}
topkey.Version = "v3"
c := mgmtclient.Cluster{}
if err := convert.ToObj(cluster.Spec, &c); err != nil {
return err
}
topkey.Clusters = map[string]mgmtclient.Cluster{}
topkey.Clusters[cluster.Spec.DisplayName] = c
// if driver is rancherKubernetesEngine, add any nodePool if found
if cluster.Status.Driver == v3.ClusterDriverRKE {
nodepools, err := a.NodepoolGetter.NodePools(cluster.Name).List(metav1.ListOptions{})
if err != nil {
return err
}
topkey.NodePools = map[string]mgmtclient.NodePool{}
for _, nodepool := range nodepools.Items {
n := mgmtclient.NodePool{}
if err := convert.ToObj(nodepool.Spec, &n); err != nil {
return err
}
n.ClusterID = cluster.Spec.DisplayName
namespace, id := ref.Parse(nodepool.Spec.NodeTemplateName)
nodeTemplate, err := a.NodeTemplateGetter.NodeTemplates(namespace).Get(id, metav1.GetOptions{})
if err != nil {
return err
}
n.NodeTemplateID = nodeTemplate.Spec.DisplayName
topkey.NodePools[nodepool.Name] = n
}
}
m, err := convert.EncodeToMap(topkey)
if err != nil {
return err
}
delete(m["clusters"].(map[string]interface{})[cluster.Spec.DisplayName].(map[string]interface{}), "actions")
delete(m["clusters"].(map[string]interface{})[cluster.Spec.DisplayName].(map[string]interface{}), "links")
for name := range topkey.NodePools {
delete(m["nodePools"].(map[string]interface{})[name].(map[string]interface{}), "actions")
delete(m["nodePools"].(map[string]interface{})[name].(map[string]interface{}), "links")
}
data, err := json.Marshal(m)
if err != nil {
return err
}
buf, err := yaml2.JSONToYAML(data)
if err != nil {
return err
}
if apiContext.ResponseFormat == "yaml" {
reader := bytes.NewReader(buf)
apiContext.Response.Header().Set("Content-Type", "application/yaml")
http.ServeContent(apiContext.Response, apiContext.Request, "exportYaml", time.Now(), reader)
return nil
}
r := v3.ExportOutput{
YAMLOutput: string(buf),
}
jsonOutput, err := json.Marshal(r)
if err != nil {
return err
}
reader := bytes.NewReader(jsonOutput)
apiContext.Response.Header().Set("Content-Type", "application/json")
http.ServeContent(apiContext.Response, apiContext.Request, "exportYaml", time.Now(), reader)
return nil
}
func (a ActionHandler) viewMonitoring(actionName string, action *types.Action, apiContext *types.APIContext) error {
cluster, err := a.ClusterClient.Get(apiContext.ID, metav1.GetOptions{})
if err != nil {
return httperror.WrapAPIError(err, httperror.NotFound, "none existent Cluster")
}
if cluster.DeletionTimestamp != nil {
return httperror.NewAPIError(httperror.InvalidType, "deleting Cluster")
}
if !cluster.Spec.EnableClusterMonitoring {
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(cluster.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 (a ActionHandler) editMonitoring(actionName string, action *types.Action, apiContext *types.APIContext) error {
cluster, err := a.ClusterClient.Get(apiContext.ID, metav1.GetOptions{})
if err != nil {
return httperror.WrapAPIError(err, httperror.NotFound, "none existent Cluster")
}
if cluster.DeletionTimestamp != nil {
return httperror.NewAPIError(httperror.InvalidType, "deleting Cluster")
}
if !cluster.Spec.EnableClusterMonitoring {
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")
}
cluster = cluster.DeepCopy()
cluster.Annotations = monitoring.AppendAppOverwritingAnswers(cluster.Annotations, string(data))
_, err = a.ClusterClient.Update(cluster)
if err != nil {
return httperror.WrapAPIError(err, httperror.ServerError, "failed to upgrade monitoring")
}
apiContext.WriteResponse(http.StatusNoContent, map[string]interface{}{})
return nil
}
func (a ActionHandler) enableMonitoring(actionName string, action *types.Action, apiContext *types.APIContext) error {
cluster, err := a.ClusterClient.Get(apiContext.ID, metav1.GetOptions{})
if err != nil {
return httperror.WrapAPIError(err, httperror.NotFound, "none existent Cluster")
}
if cluster.DeletionTimestamp != nil {
return httperror.NewAPIError(httperror.InvalidType, "deleting Cluster")
}
if cluster.Spec.EnableClusterMonitoring {
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")
}
cluster = cluster.DeepCopy()
cluster.Spec.EnableClusterMonitoring = true
cluster.Annotations = monitoring.AppendAppOverwritingAnswers(cluster.Annotations, string(data))
_, err = a.ClusterClient.Update(cluster)
if err != nil {
return httperror.WrapAPIError(err, httperror.ServerError, "failed to enable monitoring")
}
apiContext.WriteResponse(http.StatusNoContent, map[string]interface{}{})
return nil
}
func (a ActionHandler) disableMonitoring(actionName string, action *types.Action, apiContext *types.APIContext) error {
cluster, err := a.ClusterClient.Get(apiContext.ID, metav1.GetOptions{})
if err != nil {
return httperror.WrapAPIError(err, httperror.NotFound, "none existent Cluster")
}
if cluster.DeletionTimestamp != nil {
return httperror.NewAPIError(httperror.InvalidType, "deleting Cluster")
}
if !cluster.Spec.EnableClusterMonitoring {
apiContext.WriteResponse(http.StatusNoContent, map[string]interface{}{})
return nil
}
cluster = cluster.DeepCopy()
cluster.Spec.EnableClusterMonitoring = false
_, err = a.ClusterClient.Update(cluster)
if err != nil {
return httperror.WrapAPIError(err, httperror.ServerError, "failed to disable monitoring")
}
apiContext.WriteResponse(http.StatusNoContent, map[string]interface{}{})
return nil
}
type noopCloser struct {
io.Reader
}
func (noopCloser) Close() error {
return nil
}
func findNamespaceCreates(inputYAML string) ([]string, error) {
var namespaces []string
reader := yaml.NewDocumentDecoder(noopCloser{Reader: bytes.NewBufferString(inputYAML)})
for {
next, readErr := ioutil.ReadAll(reader)
if readErr != nil && readErr != io.ErrShortBuffer {
return nil, readErr
}
obj := &unstructured.Unstructured{}
next, err := yaml2.YAMLToJSON(next)
if err != nil {
return nil, err
}
err = json.Unmarshal(next, &obj.Object)
if err != nil {
return nil, err
}
if obj.IsList() {
obj.EachListItem(func(obj runtime.Object) error {
metadata, err := meta.Accessor(obj)
if err != nil {
return err
}
if obj.GetObjectKind().GroupVersionKind().Kind == "Namespace" && obj.GetObjectKind().GroupVersionKind().Version == "v1" {
namespaces = append(namespaces, metadata.GetName())
}
if metadata.GetNamespace() != "" {
namespaces = append(namespaces, metadata.GetNamespace())
}
return nil
})
} else if obj.GetKind() == "Namespace" && obj.GetAPIVersion() == "v1" {
namespaces = append(namespaces, obj.GetName())
if obj.GetNamespace() != "" {
namespaces = append(namespaces, obj.GetNamespace())
}
}
if readErr == nil {
break
}
}
uniq := map[string]bool{}
var newNamespaces []string
for _, ns := range namespaces {
if !uniq[ns] {
uniq[ns] = true
newNamespaces = append(newNamespaces, ns)
}
}
return newNamespaces, nil
}
func (a ActionHandler) findOrCreateProjectNamespaces(apiContext *types.APIContext, namespaces []string, clusterName, projectName string) (corev1.NamespaceInterface, error) {
userCtx, err := a.ClusterManager.UserContext(clusterName)
if err != nil {
return nil, err
}
nsClient := userCtx.Core.Namespaces("")
for _, ns := range namespaces {
nsObj, err := nsClient.Get(ns, metav1.GetOptions{})
if errors2.IsNotFound(err) {
apiContext.SubContext = map[string]string{
"/v3/schemas/cluster": clusterName,
}
err := access.Create(apiContext, &schema.Version, client.NamespaceType, map[string]interface{}{
client.NamespaceFieldName: ns,
client.NamespaceFieldProjectID: projectName,
}, nil)
if err != nil {
return nil, err
}
} else if err != nil {
return nil, err
} else if nsObj.Annotations[nslabels.ProjectIDFieldLabel] == projectName {
// nothing
} else {
return nil, fmt.Errorf("Namespace [%s] already exists in project [%s]", ns, nsObj.Annotations[nslabels.ProjectIDFieldLabel])
}
}
return nsClient, nil
}
func waitForNS(nsClient corev1.NamespaceInterface, namespaces []string) {
for i := 0; i < 3; i++ {
allGood := true
for _, ns := range namespaces {
ns, err := nsClient.Get(ns, metav1.GetOptions{})
if err != nil {
allGood = false
break
}
status := ns.Annotations["cattle.io/status"]
if status == "" {
allGood = false
break
}
nsMap := map[string]interface{}{}
err = json.Unmarshal([]byte(status), &nsMap)
if err != nil {
allGood = false
break
}
foundCond := false
conds := convert.ToMapSlice(values.GetValueN(nsMap, "Conditions"))
for _, cond := range conds {
if cond["Type"] == "InitialRolesPopulated" && cond["Status"] == "True" {
foundCond = true
}
}
if !foundCond {
allGood = false
}
}
if allGood {
break
} else {
time.Sleep(2 * time.Second)
}
}
}
func (a ActionHandler) processYAML(apiContext *types.APIContext, clusterName, projectName, inputYAML string) error {
namespaces, err := findNamespaceCreates(inputYAML)
if err != nil {
return err
}
nsClient, err := a.findOrCreateProjectNamespaces(apiContext, namespaces, clusterName, projectName)
if err != nil {
return err
}
waitForNS(nsClient, namespaces)
return nil
}
func (a ActionHandler) getKubeConfig(apiContext *types.APIContext, cluster *mgmtclient.Cluster) (*clientcmdapi.Config, error) {
token, err := a.getToken(apiContext)
if err != nil {
return nil, err
}
return a.ClusterManager.KubeConfig(cluster.ID, token), nil
}
func (a ActionHandler) RotateCertificates(actionName string, action *types.Action, apiContext *types.APIContext) error {
rtn := map[string]interface{}{
"type": "rotateCertificateOutput",
"message": "rotating certificates for all components",
}
var mgmtCluster mgmtclient.Cluster
if err := access.ByID(apiContext, apiContext.Version, apiContext.Type, apiContext.ID, &mgmtCluster); err != nil {
rtn["message"] = "none existent Cluster"
apiContext.WriteResponse(http.StatusBadRequest, rtn)
return errors.Wrapf(err, "failed to get Cluster by ID %s", apiContext.ID)
}
cluster, err := a.ClusterClient.Get(apiContext.ID, metav1.GetOptions{})
if err != nil {
rtn["message"] = "none existent Cluster"
apiContext.WriteResponse(http.StatusBadRequest, rtn)
return errors.Wrapf(err, "failed to get Cluster by ID %s", apiContext.ID)
}
data, err := ioutil.ReadAll(apiContext.Request.Body)
if err != nil {
rtn["message"] = "reading request body error"
apiContext.WriteResponse(http.StatusBadRequest, rtn)
return errors.Wrapf(err, "failed to read request body")
}
input := mgmtclient.RotateCertificateInput{}
if err = json.Unmarshal(data, &input); err != nil {
rtn["message"] = "failed to parse request content"
apiContext.WriteResponse(http.StatusBadRequest, rtn)
return errors.Wrap(err, "unmarshaling input error")
}
rotateCerts := &v3.RotateCertificates{
CACertificates: input.CACertificates,
Services: []string{input.Services},
}
cluster.Spec.RancherKubernetesEngineConfig.RotateCertificates = rotateCerts
if _, err := a.ClusterClient.Update(cluster); err != nil {
rtn["message"] = "failed to update cluster object"
apiContext.WriteResponse(http.StatusInternalServerError, rtn)
return errors.Wrapf(err, "unable to update Cluster %s", cluster.Name)
}
if input.CACertificates {
rtn["message"] = "rotating CA certificates and all components"
} else if len(input.Services) > 0 {
rtn["message"] = fmt.Sprintf("rotating %s certificates", input.Services)
} else {
rtn["message"] = "rotating certificates for all components"
}
apiContext.WriteResponse(http.StatusOK, rtn)
return nil
}
func (a ActionHandler) BackupEtcdHandler(actionName string, action *types.Action, apiContext *types.APIContext) error {
response := map[string]interface{}{
"message": "starting ETCD backup",
}
// checking access
var mgmtCluster mgmtclient.Cluster
if err := access.ByID(apiContext, apiContext.Version, apiContext.Type, apiContext.ID, &mgmtCluster); err != nil {
response["message"] = "none existent Cluster"
apiContext.WriteResponse(http.StatusBadRequest, response)
return errors.Wrapf(err, "failed to get Cluster by ID %s", apiContext.ID)
}
cluster, err := a.ClusterClient.Get(apiContext.ID, metav1.GetOptions{})
if err != nil {
response["message"] = "none existent Cluster"
apiContext.WriteResponse(http.StatusBadRequest, response)
return errors.Wrapf(err, "failed to get Cluster by ID %s", apiContext.ID)
}
newBackup := etcdbackup.NewBackupObject(cluster)
backup, err := a.BackupClient.Create(newBackup)
if err != nil {
response["message"] = "failed to create etcdbackup object"
apiContext.WriteResponse(http.StatusInternalServerError, response)
return errors.Wrapf(err, "failed to cteate etcdbackup object")
}
backupJSON, err := json.Marshal(backup)
if err != nil {
return err
}
apiContext.Response.Header().Set("Content-Type", "application/json")
http.ServeContent(apiContext.Response, apiContext.Request, "backupEtcd", time.Now(), bytes.NewReader(backupJSON))
return nil
}
func (a ActionHandler) RestoreFromEtcdBackupHandler(actionName string, action *types.Action, apiContext *types.APIContext) error {
response := map[string]interface{}{
"message": "restoring etcdbackup for the cluster",
}
data, err := ioutil.ReadAll(apiContext.Request.Body)
if err != nil {
response["message"] = "reading request body error"
apiContext.WriteResponse(http.StatusInternalServerError, response)
return errors.Wrap(err, "failed to read request body")
}
input := mgmtclient.RestoreFromEtcdBackupInput{}
if err = json.Unmarshal(data, &input); err != nil {
response["message"] = "failed to parse request content"
apiContext.WriteResponse(http.StatusBadRequest, response)
return errors.Wrap(err, "unmarshaling input error")
}
// checking access
var mgmtCluster mgmtclient.Cluster
if err := access.ByID(apiContext, apiContext.Version, apiContext.Type, apiContext.ID, &mgmtCluster); err != nil {
response["message"] = "none existent Cluster"
apiContext.WriteResponse(http.StatusBadRequest, response)
return errors.Wrapf(err, "failed to get Cluster by ID %s", apiContext.ID)
}
cluster, err := a.ClusterClient.Get(apiContext.ID, metav1.GetOptions{})
if err != nil {
response["message"] = "none existent Cluster"
apiContext.WriteResponse(http.StatusBadRequest, response)
return errors.Wrapf(err, "failed to get Cluster by ID %s", apiContext.ID)
}
cluster.Spec.RancherKubernetesEngineConfig.Restore.SnapshotName = input.EtcdBackupID
cluster.Spec.RancherKubernetesEngineConfig.Restore.Restore = true
if _, err = a.ClusterClient.Update(cluster); err != nil {
response["message"] = "failed to update cluster object"
apiContext.WriteResponse(http.StatusInternalServerError, response)
return errors.Wrapf(err, "unable to update Cluster %s", cluster.Name)
}
apiContext.WriteResponse(http.StatusCreated, response)
return nil
}