-
-
Notifications
You must be signed in to change notification settings - Fork 371
/
agent.go
282 lines (244 loc) · 7.11 KB
/
agent.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
// Copyright 2023 Woodpecker Authors
// Copyright 2018 Drone.IO 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 main
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net/http"
"os"
"runtime"
"strings"
"sync"
"time"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/tevino/abool"
"github.com/urfave/cli/v2"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
grpccredentials "google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/keepalive"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"github.com/woodpecker-ci/woodpecker/agent"
agentRpc "github.com/woodpecker-ci/woodpecker/agent/rpc"
"github.com/woodpecker-ci/woodpecker/pipeline/backend"
"github.com/woodpecker-ci/woodpecker/pipeline/backend/types"
"github.com/woodpecker-ci/woodpecker/pipeline/rpc"
"github.com/woodpecker-ci/woodpecker/shared/utils"
"github.com/woodpecker-ci/woodpecker/version"
)
func run(c *cli.Context) error {
hostname := c.String("hostname")
if len(hostname) == 0 {
hostname, _ = os.Hostname()
}
platform := runtime.GOOS + "/" + runtime.GOARCH
if c.Bool("pretty") {
log.Logger = log.Output(
zerolog.ConsoleWriter{
Out: os.Stderr,
NoColor: c.Bool("nocolor"),
},
)
}
zerolog.SetGlobalLevel(zerolog.InfoLevel)
if c.IsSet("log-level") {
logLevelFlag := c.String("log-level")
lvl, err := zerolog.ParseLevel(logLevelFlag)
if err != nil {
log.Fatal().Msgf("unknown logging level: %s", logLevelFlag)
}
zerolog.SetGlobalLevel(lvl)
}
if zerolog.GlobalLevel() <= zerolog.DebugLevel {
log.Logger = log.With().Caller().Logger()
}
counter.Polling = c.Int("max-workflows")
counter.Running = 0
if c.Bool("healthcheck") {
go func() {
if err := http.ListenAndServe(c.String("healthcheck-addr"), nil); err != nil {
log.Error().Msgf("cannot listen on address %s: %v", c.String("healthcheck-addr"), err)
}
}()
}
var transport grpc.DialOption
if c.Bool("grpc-secure") {
transport = grpc.WithTransportCredentials(grpccredentials.NewTLS(&tls.Config{InsecureSkipVerify: c.Bool("skip-insecure-grpc")}))
} else {
transport = grpc.WithTransportCredentials(insecure.NewCredentials())
}
authConn, err := grpc.Dial(
c.String("server"),
transport,
grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: c.Duration("grpc-keepalive-time"),
Timeout: c.Duration("grpc-keepalive-timeout"),
}),
)
if err != nil {
return err
}
defer authConn.Close()
agentID := int64(-1) // TODO: store agent id in a file
agentToken := c.String("grpc-token")
authClient := agentRpc.NewAuthGrpcClient(authConn, agentToken, agentID)
authInterceptor, err := agentRpc.NewAuthInterceptor(authClient, 30*time.Minute)
if err != nil {
return err
}
conn, err := grpc.Dial(
c.String("server"),
transport,
grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: c.Duration("grpc-keepalive-time"),
Timeout: c.Duration("grpc-keepalive-timeout"),
}),
grpc.WithUnaryInterceptor(authInterceptor.Unary()),
grpc.WithStreamInterceptor(authInterceptor.Stream()),
)
if err != nil {
return err
}
defer conn.Close()
client := agentRpc.NewGrpcClient(conn)
sigterm := abool.New()
ctx := metadata.NewOutgoingContext(
context.Background(),
metadata.Pairs("hostname", hostname),
)
ctx = utils.WithContextSigtermCallback(ctx, func() {
println("ctrl+c received, terminating process")
sigterm.Set()
})
// check if grpc server version is compatible with agent
grpcServerVersion, err := client.Version(ctx)
if err != nil {
log.Error().Err(err).Msg("could not get grpc server version")
return err
}
if grpcServerVersion.GrpcVersion != agentRpc.ClientGrpcVersion {
err := errors.New("GRPC version mismatch")
log.Error().Err(err).Msgf("Server version %s does report grpc version %d but we only understand %d",
grpcServerVersion.ServerVersion,
grpcServerVersion.GrpcVersion,
agentRpc.ClientGrpcVersion)
return err
}
backendCtx := context.WithValue(ctx, types.CliContext, c)
backend.Init(backendCtx)
var wg sync.WaitGroup
parallel := c.Int("max-workflows")
wg.Add(parallel)
// new engine
engine, err := backend.FindEngine(backendCtx, c.String("backend-engine"))
if err != nil {
log.Error().Err(err).Msgf("cannot find backend engine '%s'", c.String("backend-engine"))
return err
}
agentID, err = client.RegisterAgent(ctx, platform, engine.Name(), version.String(), parallel)
if err != nil {
return err
}
labels := map[string]string{
"hostname": hostname,
"platform": platform,
"backend": engine.Name(),
"repo": "*", // allow all repos by default
}
if err := stringSliceAddToMap(c.StringSlice("filter"), labels); err != nil {
return err
}
filter := rpc.Filter{
Labels: labels,
}
log.Debug().Msgf("Agent registered with ID %d", agentID)
go func() {
for {
if sigterm.IsSet() {
return
}
err := client.ReportHealth(ctx)
if err != nil {
log.Err(err).Msgf("Failed to report health")
return
}
<-time.After(time.Second * 10)
}
}()
for i := 0; i < parallel; i++ {
go func() {
defer wg.Done()
// load engine (e.g. init api client)
err = engine.Load(backendCtx)
if err != nil {
log.Error().Err(err).Msg("cannot load backend engine")
return
}
r := agent.NewRunner(client, filter, hostname, counter, &engine)
log.Debug().Msgf("loaded %s backend engine", engine.Name())
for {
if sigterm.IsSet() {
return
}
log.Debug().Msg("polling new steps")
if err := r.Run(ctx); err != nil {
log.Error().Err(err).Msg("pipeline done with error")
return
}
}
}()
}
log.Info().Msgf(
"Starting Woodpecker agent with version '%s' and backend '%s' using platform '%s' running up to %d pipelines in parallel",
version.String(), engine.Name(), platform, parallel)
wg.Wait()
return nil
}
func runWithRetry(context *cli.Context) error {
retryCount := context.Int("connect-retry-count")
retryDelay := context.Duration("connect-retry-delay")
var err error
for i := 0; i < retryCount; i++ {
if err = run(context); status.Code(err) == codes.Unavailable {
log.Warn().Err(err).Msg(fmt.Sprintf("cannot connect to server, retrying in %v", retryDelay))
time.Sleep(retryDelay)
} else {
break
}
}
return err
}
func stringSliceAddToMap(sl []string, m map[string]string) error {
if m == nil {
m = make(map[string]string)
}
for _, v := range sl {
parts := strings.SplitN(v, "=", 2)
switch len(parts) {
case 2:
m[parts[0]] = parts[1]
case 1:
return fmt.Errorf("key '%s' does not have a value assigned", parts[0])
default:
return fmt.Errorf("empty string in slice")
}
}
return nil
}