-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
299 lines (264 loc) · 8.08 KB
/
utils.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
package utils
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
"github.com/rancher/rancher/pkg/pipeline/remote/model"
"github.com/rancher/rancher/pkg/ref"
v3 "github.com/rancher/types/apis/project.cattle.io/v3"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/bcrypt"
"gopkg.in/yaml.v2"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func initExecution(p *v3.Pipeline, config *v3.PipelineConfig) *v3.PipelineExecution {
//add Clone stage/step at the start
toRunConfig := configWithCloneStage(config)
execution := &v3.PipelineExecution{
ObjectMeta: metav1.ObjectMeta{
Name: GetNextExecutionName(p),
Namespace: p.Namespace,
Labels: map[string]string{PipelineFinishLabel: ""},
},
Spec: v3.PipelineExecutionSpec{
ProjectName: p.Spec.ProjectName,
PipelineName: p.Namespace + ":" + p.Name,
RepositoryURL: p.Spec.RepositoryURL,
Run: p.Status.NextRun,
PipelineConfig: *toRunConfig,
},
}
execution.Status.ExecutionState = StateWaiting
execution.Status.Started = time.Now().Format(time.RFC3339)
execution.Status.Stages = make([]v3.StageStatus, len(toRunConfig.Stages))
for i := 0; i < len(execution.Status.Stages); i++ {
stage := &execution.Status.Stages[i]
stage.State = StateWaiting
stepsize := len(toRunConfig.Stages[i].Steps)
stage.Steps = make([]v3.StepStatus, stepsize)
for j := 0; j < stepsize; j++ {
step := &stage.Steps[j]
step.State = StateWaiting
}
}
return execution
}
func configWithCloneStage(config *v3.PipelineConfig) *v3.PipelineConfig {
result := config.DeepCopy()
if len(config.Stages) > 0 && len(config.Stages[0].Steps) > 0 &&
config.Stages[0].Steps[0].SourceCodeConfig != nil {
return result
}
cloneStage := v3.Stage{
Name: "Clone",
Steps: []v3.Step{{SourceCodeConfig: &v3.SourceCodeConfig{}}},
}
result.Stages = append([]v3.Stage{cloneStage}, result.Stages...)
return result
}
func GetNextExecutionName(p *v3.Pipeline) string {
if p == nil {
return ""
}
return fmt.Sprintf("%s-%d", p.Name, p.Status.NextRun)
}
func IsStageSuccess(stage v3.StageStatus) bool {
if stage.State == StateSuccess {
return true
} else if stage.State == StateFailed || stage.State == StateDenied {
return false
}
successSteps := 0
for _, step := range stage.Steps {
if step.State == StateSuccess || step.State == StateSkipped {
successSteps++
}
}
return successSteps == len(stage.Steps)
}
func IsFinishState(state string) bool {
if state == StateBuilding ||
state == StateWaiting ||
state == StateQueueing ||
state == StatePending {
return false
}
return true
}
func GenerateExecution(executions v3.PipelineExecutionInterface, pipeline *v3.Pipeline, pipelineConfig *v3.PipelineConfig, info *model.BuildInfo) (*v3.PipelineExecution, error) {
//Generate a new pipeline execution
execution := initExecution(pipeline, pipelineConfig)
execution.Spec.TriggeredBy = info.TriggerType
execution.Spec.TriggerUserName = info.TriggerUserName
execution.Spec.Branch = info.Branch
execution.Spec.Author = info.Author
execution.Spec.AvatarURL = info.AvatarURL
execution.Spec.Email = info.Email
execution.Spec.Message = info.Message
execution.Spec.HTMLLink = info.HTMLLink
execution.Spec.Title = info.Title
execution.Spec.Ref = info.Ref
execution.Spec.Commit = info.Commit
execution.Spec.Event = info.Event
if info.RepositoryURL != "" {
execution.Spec.RepositoryURL = info.RepositoryURL
}
if !Match(execution.Spec.PipelineConfig.Branch, info.Branch) {
logrus.Debug("conditions do not match")
return nil, nil
}
execution, err := executions.Create(execution)
if err != nil {
return nil, err
}
return execution, nil
}
func SplitImageTag(image string) (string, string, string) {
registry, repo, tag := "", "", ""
i := strings.Index(image, "/")
if i == -1 || (!strings.ContainsAny(image[:i], ".:") && image[:i] != "localhost") {
registry = DefaultRegistry
} else {
registry = image[:i]
image = image[i+1:]
}
i = strings.Index(image, ":")
if i == -1 {
repo = image
tag = DefaultTag
} else {
repo = image[:i]
tag = image[i+1:]
}
return registry, repo, tag
}
func ValidPipelineConfig(config v3.PipelineConfig) error {
if len(config.Stages) < 1 ||
len(config.Stages[0].Steps) < 1 ||
config.Stages[0].Steps[0].SourceCodeConfig == nil {
return fmt.Errorf("invalid definition for pipeline: expect souce code step at the start")
}
return nil
}
func GetPipelineCommonName(projectName string) string {
_, p := ref.Parse(projectName)
return p + PipelineNamespaceSuffix
}
func GetEnvVarMap(execution *v3.PipelineExecution) map[string]string {
m := map[string]string{}
repoURL := execution.Spec.RepositoryURL
repoName := ""
if strings.Contains(repoURL, "/") {
trimmedURL := strings.TrimRight(repoURL, "/")
idx := strings.LastIndex(trimmedURL, "/")
repoName = strings.TrimSuffix(trimmedURL[idx+1:], ".git")
}
commit := execution.Spec.Commit
if commit != "" && len(commit) > 7 {
//use abbreviated SHA
commit = commit[:7]
}
_, pipelineID := ref.Parse(execution.Spec.PipelineName)
clusterID, projectID := ref.Parse(execution.Spec.ProjectName)
localRegistry := ""
if execution.Annotations != nil && execution.Annotations[LocalRegistryPortLabel] != "" {
localRegistry = "127.0.0.1:" + execution.Annotations[LocalRegistryPortLabel]
}
m[EnvGitCommit] = commit
m[EnvGitRepoName] = repoName
m[EnvGitRef] = execution.Spec.Ref
m[EnvGitBranch] = execution.Spec.Branch
m[EnvGitURL] = execution.Spec.RepositoryURL
m[EnvPipelineID] = pipelineID
m[EnvTriggerType] = execution.Spec.TriggeredBy
m[EnvEvent] = execution.Spec.Event
m[EnvExecutionID] = execution.Name
m[EnvExecutionSequence] = strconv.Itoa(execution.Spec.Run)
m[EnvProjectID] = projectID
m[EnvClusterID] = clusterID
m[EnvLocalRegistry] = localRegistry
if execution.Spec.Event == WebhookEventTag {
m[EnvGitTag] = strings.TrimPrefix(execution.Spec.Ref, "refs/tags/")
}
return m
}
func PipelineConfigToYaml(pipelineConfig *v3.PipelineConfig) ([]byte, error) {
content, err := yaml.Marshal(pipelineConfig)
if err != nil {
return nil, err
}
return content, nil
}
func PipelineConfigFromYaml(content []byte) (*v3.PipelineConfig, error) {
out := &v3.PipelineConfig{}
err := yaml.Unmarshal(content, out)
if err != nil {
return nil, errors.Wrapf(err, "Failed to parse the pipeline file")
}
return out, nil
}
func BCryptHash(password string) (string, error) {
passwordBytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return "", err
}
return string(passwordBytes), nil
}
func GetRegistryPortMapping(cm *corev1.ConfigMap) (map[string]string, error) {
portMap := map[string]string{}
yamlMap := map[string]string{}
curYaml := cm.Data[RegistryPortMappingFile]
if err := yaml.Unmarshal([]byte(curYaml), &yamlMap); err != nil {
return nil, err
}
if err := json.Unmarshal([]byte(yamlMap[RegistryPortMappingKey]), &portMap); err != nil {
return nil, err
}
return portMap, nil
}
func SetRegistryPortMapping(configmap *corev1.ConfigMap, portMap map[string]string) error {
yamlMap := map[string]string{}
b, err := json.Marshal(portMap)
if err != nil {
return err
}
yamlMap[RegistryPortMappingKey] = string(b)
b, err = yaml.Marshal(yamlMap)
if err != nil {
return err
}
configmap.Data[RegistryPortMappingFile] = string(b)
return nil
}
// EnsureAccessToken Checks expiry and do token refresh when needed
func EnsureAccessToken(credentialInterface v3.SourceCodeCredentialInterface, remote model.Remote, credential *v3.SourceCodeCredential) (string, error) {
if credential == nil {
return "", nil
}
refresher, ok := remote.(model.Refresher)
if !ok {
return credential.Spec.AccessToken, nil
}
t, err := time.Parse(time.RFC3339, credential.Spec.Expiry)
if err != nil {
return "", err
}
if t.Before(time.Now().Add(time.Minute)) {
torefresh := credential.DeepCopy()
ok, err := refresher.Refresh(torefresh)
if err != nil {
return "", err
}
if ok {
if _, err := credentialInterface.Update(torefresh); err != nil {
return "", err
}
}
return torefresh.Spec.AccessToken, nil
}
return credential.Spec.AccessToken, nil
}