-
Notifications
You must be signed in to change notification settings - Fork 0
/
cluster_pipeline.go
340 lines (295 loc) · 10.3 KB
/
cluster_pipeline.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
package pipeline
import (
"encoding/json"
"fmt"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
"github.com/rancher/norman/api/access"
"github.com/rancher/norman/httperror"
"github.com/rancher/norman/types"
"github.com/rancher/rancher/pkg/controllers/user/pipeline/remote"
"github.com/rancher/rancher/pkg/controllers/user/pipeline/utils"
"github.com/rancher/rancher/pkg/ref"
"github.com/rancher/types/apis/core/v1"
"github.com/rancher/types/apis/management.cattle.io/v3"
"github.com/rancher/types/client/management/v3"
"github.com/sirupsen/logrus"
"io/ioutil"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"net/http"
"strings"
)
type ClusterPipelineHandler struct {
ClusterPipelines v3.ClusterPipelineInterface
ClusterPipelineLister v3.ClusterPipelineLister
SourceCodeCredentials v3.SourceCodeCredentialInterface
SourceCodeCredentialLister v3.SourceCodeCredentialLister
SourceCodeRepositories v3.SourceCodeRepositoryInterface
SourceCodeRepositoryLister v3.SourceCodeRepositoryLister
SecretLister v1.SecretLister
Secrets v1.SecretInterface
AuthConfigs v3.AuthConfigInterface
}
func ClusterPipelineFormatter(apiContext *types.APIContext, resource *types.RawResource) {
resource.AddAction(apiContext, "deploy")
resource.AddAction(apiContext, "destroy")
resource.AddAction(apiContext, "revokeapp")
resource.AddAction(apiContext, "authapp")
resource.AddAction(apiContext, "authuser")
resource.Links["envvars"] = apiContext.URLBuilder.Link("envvars", resource)
}
func (h *ClusterPipelineHandler) LinkHandler(apiContext *types.APIContext, next types.RequestHandler) error {
if apiContext.Link == "envvars" {
bytes, err := json.Marshal(utils.PreservedEnvVars)
if err != nil {
return err
}
apiContext.Response.Write(bytes)
return nil
}
return httperror.NewAPIError(httperror.NotFound, "Link not found")
}
func (h *ClusterPipelineHandler) ActionHandler(actionName string, action *types.Action, apiContext *types.APIContext) error {
switch actionName {
case "deploy":
return h.deploy(apiContext)
case "destroy":
return h.destroy(apiContext)
case "revokeapp":
return h.revokeapp(apiContext)
case "authapp":
return h.authapp(apiContext)
case "authuser":
return h.authuser(apiContext)
}
return httperror.NewAPIError(httperror.InvalidAction, "unsupported action")
}
func (h *ClusterPipelineHandler) deploy(apiContext *types.APIContext) error {
ns, name := ref.Parse(apiContext.ID)
clusterPipeline, err := h.ClusterPipelineLister.Get(ns, name)
if err != nil {
return err
}
if !clusterPipeline.Spec.Deploy {
clusterPipeline.Spec.Deploy = true
if _, err = h.ClusterPipelines.Update(clusterPipeline); err != nil {
return err
}
}
data := map[string]interface{}{}
if err := access.ByID(apiContext, apiContext.Version, apiContext.Type, apiContext.ID, &data); err != nil {
return err
}
apiContext.WriteResponse(http.StatusOK, data)
return nil
}
func (h *ClusterPipelineHandler) destroy(apiContext *types.APIContext) error {
ns, name := ref.Parse(apiContext.ID)
clusterPipeline, err := h.ClusterPipelineLister.Get(ns, name)
if err != nil {
return err
}
if clusterPipeline.Spec.Deploy {
clusterPipeline.Spec.Deploy = false
if _, err = h.ClusterPipelines.Update(clusterPipeline); err != nil {
return err
}
}
data := map[string]interface{}{}
if err := access.ByID(apiContext, apiContext.Version, apiContext.Type, apiContext.ID, &data); err != nil {
return err
}
apiContext.WriteResponse(http.StatusOK, data)
return nil
}
func (h *ClusterPipelineHandler) authapp(apiContext *types.APIContext) error {
ns, name := ref.Parse(apiContext.ID)
authAppInput := v3.AuthAppInput{}
requestBytes, err := ioutil.ReadAll(apiContext.Request.Body)
if err != nil {
return err
}
if err := json.Unmarshal(requestBytes, &authAppInput); err != nil {
return err
}
clusterPipeline, err := h.ClusterPipelineLister.Get(ns, name)
if err != nil {
return err
}
clientSecret := ""
if authAppInput.SourceCodeType == "github" {
clusterPipeline.Spec.GithubConfig = &v3.GithubClusterConfig{
TLS: authAppInput.TLS,
Host: authAppInput.Host,
ClientID: authAppInput.ClientID,
RedirectURL: authAppInput.RedirectURL,
}
clientSecret = authAppInput.ClientSecret
if authAppInput.InheritGlobal {
globalConfig, err := h.getGithubConfigCR()
if err != nil {
return err
}
clusterPipeline.Spec.GithubConfig.TLS = globalConfig.TLS
clusterPipeline.Spec.GithubConfig.Host = globalConfig.Hostname
clusterPipeline.Spec.GithubConfig.ClientID = globalConfig.ClientID
clientSecret = globalConfig.ClientSecret
}
} else {
return fmt.Errorf("Error unsupported source code type %s", authAppInput.SourceCodeType)
}
//oauth and add user
clusterPipelineCopy := clusterPipeline.DeepCopy()
clusterPipelineCopy.Spec.GithubConfig.ClientSecret = clientSecret
userName := apiContext.Request.Header.Get("Impersonate-User")
sourceCodeCredential, err := h.authAddAccount(clusterPipelineCopy, authAppInput.SourceCodeType, userName, authAppInput.RedirectURL, authAppInput.Code)
if err != nil {
return err
}
//update cluster pipeline config
if _, err := h.ClusterPipelines.Update(clusterPipeline); err != nil {
return err
}
//store credential in secrets
if err := h.saveClientSecret(ns, authAppInput.SourceCodeType, clientSecret); err != nil {
return err
}
data := map[string]interface{}{}
if err := access.ByID(apiContext, apiContext.Version, apiContext.Type, apiContext.ID, &data); err != nil {
return err
}
go refreshReposByCredential(h.SourceCodeRepositories, h.SourceCodeRepositoryLister, sourceCodeCredential, clusterPipeline)
apiContext.WriteResponse(http.StatusOK, data)
return nil
}
func (h *ClusterPipelineHandler) authuser(apiContext *types.APIContext) error {
ns, name := ref.Parse(apiContext.ID)
authUserInput := v3.AuthUserInput{}
requestBytes, err := ioutil.ReadAll(apiContext.Request.Body)
if err != nil {
return err
}
if err := json.Unmarshal(requestBytes, &authUserInput); err != nil {
return err
}
clusterPipeline, err := h.ClusterPipelineLister.Get(ns, name)
if err != nil {
return err
}
if authUserInput.SourceCodeType == "github" && clusterPipeline.Spec.GithubConfig == nil {
return errors.New("github oauth app is not configured")
}
clientSecret, err := h.getClientSecret(ns, authUserInput.SourceCodeType)
if err != nil {
return err
}
clusterPipelineCopy := clusterPipeline.DeepCopy()
clusterPipelineCopy.Spec.GithubConfig.ClientSecret = clientSecret
//oauth and add user
userName := apiContext.Request.Header.Get("Impersonate-User")
logrus.Debugf("try auth with %v,%v,%v,%v,%v", clusterPipeline, authUserInput.SourceCodeType, userName, authUserInput.RedirectURL, authUserInput.Code)
account, err := h.authAddAccount(clusterPipelineCopy, authUserInput.SourceCodeType, userName, authUserInput.RedirectURL, authUserInput.Code)
if err != nil {
return err
}
if _, err := refreshReposByCredential(h.SourceCodeRepositories, h.SourceCodeRepositoryLister, account, clusterPipeline); err != nil {
return err
}
data := map[string]interface{}{}
if err := access.ByID(apiContext, apiContext.Version, client.SourceCodeCredentialType, account.Name, &data); err != nil {
return err
}
apiContext.WriteResponse(http.StatusOK, data)
return nil
}
func (h *ClusterPipelineHandler) revokeapp(apiContext *types.APIContext) error {
ns, name := ref.Parse(apiContext.ID)
clusterPipeline, err := h.ClusterPipelineLister.Get(ns, name)
if err != nil {
return err
}
clusterPipeline.Spec.GithubConfig = nil
_, err = h.ClusterPipelines.Update(clusterPipeline)
if err != nil {
return err
}
data := map[string]interface{}{}
if err := access.ByID(apiContext, apiContext.Version, apiContext.Type, apiContext.ID, &data); err != nil {
return err
}
apiContext.WriteResponse(http.StatusOK, data)
return nil
}
func (h *ClusterPipelineHandler) authAddAccount(clusterPipeline *v3.ClusterPipeline, remoteType string, userID string, redirectURL string, code string) (*v3.SourceCodeCredential, error) {
if userID == "" {
return nil, errors.New("unauth")
}
remote, err := remote.New(*clusterPipeline, remoteType)
if err != nil {
return nil, err
}
account, err := remote.Login(redirectURL, code)
if err != nil {
return nil, err
}
account.Name = strings.ToLower(fmt.Sprintf("%s-%s-%s", clusterPipeline.Spec.ClusterName, remoteType, account.Spec.LoginName))
account.Namespace = userID
account.Spec.UserName = userID
account.Spec.ClusterName = clusterPipeline.Spec.ClusterName
account, err = h.SourceCodeCredentials.Create(account)
if err != nil && !apierrors.IsAlreadyExists(err) {
return nil, err
}
return account, nil
}
func (h *ClusterPipelineHandler) getGithubConfigCR() (*v3.GithubConfig, error) {
authConfigObj, err := h.AuthConfigs.ObjectClient().UnstructuredClient().Get("github", metav1.GetOptions{})
if err != nil {
return nil, fmt.Errorf("failed to retrieve GithubConfig, error: %v", err)
}
u, ok := authConfigObj.(runtime.Unstructured)
if !ok {
return nil, fmt.Errorf("failed to retrieve GithubConfig, cannot read k8s Unstructured data")
}
storedGithubConfigMap := u.UnstructuredContent()
storedGithubConfig := &v3.GithubConfig{}
mapstructure.Decode(storedGithubConfigMap, storedGithubConfig)
metadataMap, ok := storedGithubConfigMap["metadata"].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("failed to retrieve GithubConfig metadata, cannot read k8s Unstructured data")
}
typemeta := &metav1.ObjectMeta{}
mapstructure.Decode(metadataMap, typemeta)
storedGithubConfig.ObjectMeta = *typemeta
return storedGithubConfig, nil
}
func (h *ClusterPipelineHandler) saveClientSecret(namespace, name, token string) error {
secret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Namespace: namespace,
Name: name,
},
Data: map[string][]byte{
"clientSecret": []byte(token),
},
}
_, err := h.Secrets.Create(secret)
if apierrors.IsAlreadyExists(err) {
if _, err := h.Secrets.Update(secret); err != nil {
return err
}
return nil
}
return err
}
func (h *ClusterPipelineHandler) getClientSecret(namespace, name string) (string, error) {
secret, err := h.SecretLister.Get(namespace, name)
if err != nil {
return "", err
}
clientSecret := string(secret.Data["clientSecret"])
return clientSecret, nil
}