forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
actions_yaml.go
204 lines (186 loc) · 6.16 KB
/
actions_yaml.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
package cluster
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/ghodss/yaml"
"github.com/pkg/errors"
"github.com/rancher/norman/api/access"
"github.com/rancher/norman/types"
"github.com/rancher/norman/types/convert"
"github.com/rancher/rancher/pkg/controllers/user/nslabels"
"github.com/rancher/rancher/pkg/kubectl"
"github.com/rancher/rancher/pkg/ref"
"github.com/rancher/types/apis/cluster.cattle.io/v3/schema"
corev1 "github.com/rancher/types/apis/core/v1"
v3 "github.com/rancher/types/apis/management.cattle.io/v3"
clusterclient "github.com/rancher/types/client/cluster/v3"
mgmtclient "github.com/rancher/types/client/management/v3"
"github.com/rancher/types/compose"
kerrors "k8s.io/apimachinery/pkg/api/errors"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
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, v1.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(v1.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, v1.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 := yaml.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) 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) 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, v1.GetOptions{})
if kerrors.IsNotFound(err) {
apiContext.SubContext = map[string]string{
"/v3/schemas/cluster": clusterName,
}
err := access.Create(apiContext, &schema.Version, clusterclient.NamespaceType, map[string]interface{}{
clusterclient.NamespaceFieldName: ns,
clusterclient.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
}