/
cron.go
228 lines (204 loc) · 7.19 KB
/
cron.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
// Copyright (c) 2021 Terminus, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package pipelinesvc
import (
"context"
"encoding/json"
"fmt"
"strconv"
"time"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/erda-project/erda/apistructs"
"github.com/erda-project/erda/modules/pipeline/commonutil/thirdparty/gittarutil"
"github.com/erda-project/erda/modules/pipeline/conf"
"github.com/erda-project/erda/modules/pipeline/services/apierrors"
"github.com/erda-project/erda/modules/pipeline/services/appsvc"
"github.com/erda-project/erda/modules/pipeline/spec"
"github.com/erda-project/erda/pkg/discover"
"github.com/erda-project/erda/pkg/loop"
)
// RunCronPipelineFunc 定时触发时会先创建 pipeline 记录,然后尝试执行;
// 如果因为某些因素(比如并行数量限制)不能立即执行,用户后续仍然可以再次手动执行这条 pipeline。
func (s *PipelineSvc) RunCronPipelineFunc(id uint64) {
var err error
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%v", r)
}
if err != nil {
logrus.Errorf("crond: pipelineCronID: %d, err: %v", id, err)
}
}()
// 立即获取触发时间
cronTriggerTime := time.Now()
// 查询 cron 详情
pc, err := s.dbClient.GetPipelineCron(id)
if err != nil {
return
}
// if trigger time less than cronStartFrom, return directly
if s.isCronShouldBeIgnored(pc) {
logrus.Warnf("crond: pipelineCronID: %d, triggered but ignored, triggerTime: %s, cronStartFrom: %s",
pc.ID, cronTriggerTime, *pc.Extra.CronStartFrom)
return
}
if err = s.UpgradePipelineCron(&pc); err != nil {
err = errors.Errorf("failed to upgrade pipeline cron, err: %v", err)
return
}
if pc.Extra.NormalLabels == nil {
pc.Extra.NormalLabels = make(map[string]string)
}
if pc.Extra.FilterLabels == nil {
pc.Extra.FilterLabels = make(map[string]string)
}
// userID
if pc.Extra.NormalLabels[apistructs.LabelUserID] == "" {
pc.Extra.NormalLabels[apistructs.LabelUserID] = conf.InternalUserID()
if err = s.dbClient.UpdatePipelineCron(pc.ID, &pc); err != nil {
return
}
}
// cron
if _, ok := pc.Extra.FilterLabels[apistructs.LabelPipelineTriggerMode]; ok {
pc.Extra.FilterLabels[apistructs.LabelPipelineTriggerMode] = apistructs.PipelineTriggerModeCron.String()
}
pc.Extra.NormalLabels[apistructs.LabelPipelineTriggerMode] = apistructs.PipelineTriggerModeCron.String()
pc.Extra.NormalLabels[apistructs.LabelPipelineType] = apistructs.PipelineTypeNormal.String()
pc.Extra.NormalLabels[apistructs.LabelPipelineYmlSource] = apistructs.PipelineYmlSourceContent.String()
pc.Extra.NormalLabels[apistructs.LabelPipelineCronTriggerTime] = strconv.FormatInt(cronTriggerTime.UnixNano(), 10)
pc.Extra.NormalLabels[apistructs.LabelPipelineCronID] = strconv.FormatUint(pc.ID, 10)
// 使用 v2 方式创建定时流水线
_, err = s.CreateV2(&apistructs.PipelineCreateRequestV2{
PipelineYml: pc.Extra.PipelineYml,
ClusterName: pc.Extra.ClusterName,
PipelineYmlName: pc.PipelineYmlName,
PipelineSource: pc.PipelineSource,
Labels: pc.Extra.FilterLabels,
NormalLabels: pc.Extra.NormalLabels,
Envs: pc.Extra.Envs,
ConfigManageNamespaces: pc.Extra.ConfigManageNamespaces,
AutoRunAtOnce: true,
AutoStartCron: false,
IdentityInfo: apistructs.IdentityInfo{
UserID: pc.Extra.NormalLabels[apistructs.LabelUserID],
InternalClient: "system-cron",
},
})
}
// 更新老数据
// 1) 根据 application 和 branch 获取元数据
// 2) 根据 basePipelineID 获取元数据
func (s *PipelineSvc) UpgradePipelineCron(pc *spec.PipelineCron) error {
// 升级后,extra 里 version 为 v2
if pc.Extra.Version == "v2" {
return nil
}
pc.Extra.Version = "v2"
if pc.ApplicationID > 0 && pc.Branch != "" {
var app *appsvc.WorkspaceApp
app, err := s.appSvc.GetWorkspaceApp(pc.ApplicationID, pc.Branch)
if err != nil {
return err
}
repo := gittarutil.NewRepo(discover.Gittar(), app.GitRepoAbbrev)
var f []byte
f, err = repo.FetchFile(pc.Branch, pc.PipelineYmlName, pc.GetUserID())
if err != nil {
return err
}
pc.PipelineSource = apistructs.PipelineSourceDice
if pc.Branch == "master" && pc.PipelineYmlName != apistructs.DefaultPipelineYmlName {
pc.PipelineSource = apistructs.PipelineSourceBigData
}
pc.PipelineYmlName = app.GenerateV1UniquePipelineYmlName(pc.PipelineYmlName)
pc.Extra.PipelineYml = string(f)
pc.Extra.ClusterName = app.ClusterName
pc.Extra.NormalLabels = app.GenerateLabels()
// commit
commit, err := repo.GetCommit(app.Branch, pc.GetUserID())
if err != nil {
return apierrors.ErrGetGittarRepo.InternalError(err)
}
pc.Extra.NormalLabels[apistructs.LabelCommit] = commit.ID
commitDetail := apistructs.CommitDetail{
Repo: app.GitRepo,
RepoAbbr: app.GitRepoAbbrev,
Author: commit.Committer.Name,
Email: commit.Committer.Email,
Time: func() *time.Time {
commitTime, err := time.Parse("2006-01-02T15:04:05-07:00", commit.Committer.When)
if err != nil {
return nil
}
return &commitTime
}(),
Comment: commit.CommitMessage,
}
commitDetailStr, _ := json.Marshal(commitDetail)
pc.Extra.NormalLabels[apistructs.LabelCommitDetail] = string(commitDetailStr)
} else if pc.BasePipelineID > 0 {
var basePipeline spec.Pipeline
basePipeline, err := s.dbClient.GetPipeline(pc.BasePipelineID)
if err != nil {
return err
}
pc.PipelineSource = basePipeline.PipelineSource
pc.PipelineYmlName = basePipeline.GenerateV1UniquePipelineYmlName(pc.PipelineYmlName)
pc.Extra.PipelineYml = basePipeline.PipelineYml
pc.Extra.ClusterName = basePipeline.ClusterName
pc.Extra.NormalLabels = basePipeline.GenerateNormalLabelsForCreateV2()
pc.Extra.FilterLabels = basePipeline.Labels
} else {
return errors.Errorf("both invalid (application_id + branch) and (base_pipeline_id)")
}
// 更新 cron 配置至最新
if err := s.dbClient.UpdatePipelineCron(pc.ID, pc); err != nil {
return err
}
return nil
}
func (s *PipelineSvc) DoCrondAbout(ctx context.Context) {
// 加载定时配置
logs, err := s.crondSvc.ReloadCrond(ctx, s.RunCronPipelineFunc)
for _, log := range logs {
logrus.Info(log)
}
if err != nil {
logrus.Errorf("failed to reload crond from db (%v)", err)
return
}
// watch crond
go s.crondSvc.ListenCrond(ctx, s.RunCronPipelineFunc)
// Print a snapshot of a scheduled task regularly
go func() {
for {
select {
case <-ctx.Done():
return
default:
_ = loop.New(loop.WithInterval(time.Minute)).Do(
func() (bool, error) {
for _, log := range s.crondSvc.CrondSnapshot() {
logrus.Debug(log)
}
return false, nil
})
}
}
}()
// 定时补偿
go s.ContinueCompensate(ctx)
}