-
Notifications
You must be signed in to change notification settings - Fork 142
/
handler.go
298 lines (247 loc) · 7.45 KB
/
handler.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
// Copyright 2023 The PipeCD Authors.
//
// 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 planpreview
import (
"context"
"encoding/json"
"fmt"
"time"
"go.uber.org/zap"
"google.golang.org/grpc"
metrics "github.com/pipe-cd/pipecd/pkg/app/piped/planpreview/planpreviewmetrics"
"github.com/pipe-cd/pipecd/pkg/app/server/service/pipedservice"
"github.com/pipe-cd/pipecd/pkg/cache"
"github.com/pipe-cd/pipecd/pkg/config"
"github.com/pipe-cd/pipecd/pkg/git"
"github.com/pipe-cd/pipecd/pkg/model"
"github.com/pipe-cd/pipecd/pkg/regexpool"
)
const (
defaultWorkerNum = 3
defaultCommandQueueBufferSize = 10
defaultCommandCheckInterval = 5 * time.Second
defaultCommandHandleTimeout = 5 * time.Minute
)
type options struct {
workerNum int
commandQueueBufferSize int
commandCheckInterval time.Duration
commandHandleTimeout time.Duration
logger *zap.Logger
}
type Option func(*options)
func WithWorkerNum(n int) Option {
return func(opts *options) {
opts.workerNum = n
}
}
func WithCommandQueueBufferSize(s int) Option {
return func(opts *options) {
opts.commandQueueBufferSize = s
}
}
func WithCommandCheckInterval(i time.Duration) Option {
return func(opts *options) {
opts.commandCheckInterval = i
}
}
func WithCommandHandleTimeout(t time.Duration) Option {
return func(opts *options) {
opts.commandHandleTimeout = t
}
}
func WithLogger(l *zap.Logger) Option {
return func(opts *options) {
opts.logger = l
}
}
type gitClient interface {
Clone(ctx context.Context, repoID, remote, branch, destination string) (git.Repo, error)
}
type apiClient interface {
GetApplicationMostRecentDeployment(ctx context.Context, req *pipedservice.GetApplicationMostRecentDeploymentRequest, opts ...grpc.CallOption) (*pipedservice.GetApplicationMostRecentDeploymentResponse, error)
}
type applicationLister interface {
List() []*model.Application
}
type commandLister interface {
ListBuildPlanPreviewCommands() []model.ReportableCommand
}
type secretDecrypter interface {
Decrypt(string) (string, error)
}
type Handler struct {
gitClient gitClient
commandLister commandLister
commandCh chan model.ReportableCommand
prevCommands map[string]struct{}
options *options
builderFactory func() Builder
logger *zap.Logger
}
func NewHandler(
gc gitClient,
ac apiClient,
cl commandLister,
al applicationLister,
cg lastTriggeredCommitGetter,
sd secretDecrypter,
appManifestsCache cache.Cache,
cfg *config.PipedSpec,
opts ...Option,
) *Handler {
opt := &options{
workerNum: defaultWorkerNum,
commandQueueBufferSize: defaultCommandQueueBufferSize,
commandCheckInterval: defaultCommandCheckInterval,
commandHandleTimeout: defaultCommandHandleTimeout,
logger: zap.NewNop(),
}
for _, o := range opts {
o(opt)
}
h := &Handler{
gitClient: gc,
commandLister: cl,
commandCh: make(chan model.ReportableCommand, opt.commandQueueBufferSize),
prevCommands: map[string]struct{}{},
options: opt,
logger: opt.logger.Named("plan-preview-handler"),
}
regexPool := regexpool.DefaultPool()
h.builderFactory = func() Builder {
return newBuilder(gc, ac, al, cg, sd, appManifestsCache, regexPool, cfg, h.logger)
}
return h
}
// Run starts running Handler until the given context has done.
func (h *Handler) Run(ctx context.Context) error {
h.logger.Info("start running planpreview handler")
startWorker := func(ctx context.Context, cmdCh <-chan model.ReportableCommand) {
h.logger.Info("started a worker for handling plan-preview command")
for {
select {
case cmd := <-cmdCh:
h.handleCommand(ctx, cmd)
case <-ctx.Done():
h.logger.Info("a worker has been stopped")
return
}
}
}
h.logger.Info(fmt.Sprintf("spawn %d worker to handle commands", h.options.workerNum))
for i := 0; i < h.options.workerNum; i++ {
go startWorker(ctx, h.commandCh)
}
commandTicker := time.NewTicker(h.options.commandCheckInterval)
defer commandTicker.Stop()
for {
select {
case <-ctx.Done():
h.logger.Info("planpreview handler has been stopped")
return nil
case <-commandTicker.C:
h.enqueueNewCommands(ctx)
}
}
}
func (h *Handler) enqueueNewCommands(ctx context.Context) {
h.logger.Debug("fetching unhandled commands to enqueue")
commands := h.commandLister.ListBuildPlanPreviewCommands()
if len(commands) == 0 {
h.logger.Debug("there is no command to enqueue")
return
}
news := make([]model.ReportableCommand, 0, len(commands))
cmds := make(map[string]struct{}, len(commands))
for _, cmd := range commands {
cmds[cmd.Id] = struct{}{}
if _, ok := h.prevCommands[cmd.Id]; !ok {
news = append(news, cmd)
}
}
h.logger.Info("fetched unhandled commands to enqueue",
zap.Any("pre-commands", h.prevCommands),
zap.Any("commands", cmds),
zap.Int("news", len(news)),
)
if len(news) == 0 {
h.logger.Info("there is no new command to enqueue")
return
}
h.prevCommands = cmds
metrics.ReceivedCommands(len(news))
h.logger.Info(fmt.Sprintf("will enqueue %d new commands", len(news)))
for _, cmd := range news {
select {
case h.commandCh <- cmd:
h.logger.Info("queued a new new command", zap.String("command", cmd.Id))
case <-ctx.Done():
return
}
}
}
func (h *Handler) handleCommand(ctx context.Context, cmd model.ReportableCommand) {
start := time.Now()
logger := h.logger.With(
zap.String("command", cmd.Id),
)
logger.Info("received a plan-preview command to handle")
result := &model.PlanPreviewCommandResult{
CommandId: cmd.Id,
PipedId: cmd.PipedId,
}
reportError := func(err error) {
metrics.HandledCommand(metrics.StatusFailure, time.Since(start))
result.Error = err.Error()
output, err := json.Marshal(result)
if err != nil {
logger.Error("failed to marshal command result", zap.Error(err))
}
if err := cmd.Report(ctx, model.CommandStatus_COMMAND_FAILED, nil, output); err != nil {
logger.Error("failed to report command status", zap.Error(err))
return
}
logger.Info("successfully reported a failure command")
}
if cmd.BuildPlanPreview == nil {
reportError(fmt.Errorf("malformed command"))
return
}
timeout := time.Duration(cmd.BuildPlanPreview.Timeout) * time.Second
if timeout == 0 {
timeout = h.options.commandHandleTimeout
}
buildCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
b := h.builderFactory()
appResults, err := b.Build(buildCtx, cmd.Id, *cmd.BuildPlanPreview)
if err != nil {
reportError(err)
return
}
result.Results = appResults
output, err := json.Marshal(result)
if err != nil {
reportError(fmt.Errorf("failed to marshal command result (%w)", err))
return
}
if err := cmd.Report(ctx, model.CommandStatus_COMMAND_SUCCEEDED, nil, output); err != nil {
metrics.HandledCommand(metrics.StatusFailure, time.Since(start))
logger.Error("failed to report command status", zap.Error(err))
return
}
metrics.HandledCommand(metrics.StatusSuccess, time.Since(start))
logger.Info("successfully reported a success command")
}