1
0
mirror of https://github.com/woodpecker-ci/woodpecker.git synced 2024-12-12 08:23:48 +02:00
woodpecker/cmd/agent/agent.go

247 lines
6.2 KiB
Go
Raw Normal View History

// Copyright 2023 Woodpecker Authors
2018-02-20 00:24:10 +02:00
// Copyright 2018 Drone.IO Inc.
2018-03-21 15:02:17 +02:00
//
2018-02-20 00:24:10 +02:00
// 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
2018-03-21 15:02:17 +02:00
//
2018-02-20 00:24:10 +02:00
// http://www.apache.org/licenses/LICENSE-2.0
2018-03-21 15:02:17 +02:00
//
2018-02-20 00:24:10 +02:00
// 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.
2017-06-30 00:51:22 +02:00
package main
2016-04-20 03:37:53 +02:00
import (
2017-03-16 12:14:02 +02:00
"context"
"crypto/tls"
"errors"
2017-09-12 20:25:55 +02:00
"net/http"
"os"
"runtime"
"strings"
2016-04-20 03:37:53 +02:00
"sync"
"time"
2016-04-20 03:37:53 +02:00
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/tevino/abool"
"github.com/urfave/cli/v2"
2017-06-28 19:21:22 +02:00
"google.golang.org/grpc"
grpccredentials "google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
2018-01-08 17:28:38 +02:00
"google.golang.org/grpc/keepalive"
"google.golang.org/grpc/metadata"
2017-06-28 19:21:22 +02:00
"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"
2016-04-20 03:37:53 +02:00
)
2017-03-16 12:14:02 +02:00
func loop(c *cli.Context) error {
hostname := c.String("hostname")
if len(hostname) == 0 {
hostname, _ = os.Hostname()
}
platform := runtime.GOOS + "/" + runtime.GOARCH
labels := map[string]string{
"hostname": hostname,
"platform": platform,
"repo": "*", // allow all repos by default
}
for _, v := range c.StringSlice("filter") {
parts := strings.SplitN(v, "=", 2)
labels[parts[0]] = parts[1]
}
filter := rpc.Filter{
Labels: labels,
}
2017-09-12 20:25:55 +02:00
if c.Bool("pretty") {
log.Logger = log.Output(
zerolog.ConsoleWriter{
Out: os.Stderr,
NoColor: c.Bool("nocolor"),
2017-09-12 20:25:55 +02:00
},
)
}
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")
2017-09-12 22:40:24 +02:00
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)
}
}()
2017-09-12 20:25:55 +02:00
}
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(
2017-06-28 19:21:22 +02:00
c.String("server"),
transport,
grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: c.Duration("grpc-keepalive-time"),
Timeout: c.Duration("grpc-keepalive-timeout"),
2017-06-30 01:35:38 +02:00
}),
)
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()),
2017-03-16 12:14:02 +02:00
)
if err != nil {
return err
2017-03-05 09:56:08 +02:00
}
2017-06-28 19:21:22 +02:00
defer conn.Close()
client := agentRpc.NewGrpcClient(conn)
2017-03-05 09:56:08 +02:00
2017-03-16 12:14:02 +02:00
sigterm := abool.New()
ctx := metadata.NewOutgoingContext(
context.Background(),
metadata.Pairs("hostname", hostname),
)
ctx = utils.WithContextSigtermCallback(ctx, func() {
2017-03-16 12:14:02 +02:00
println("ctrl+c received, terminating process")
sigterm.Set()
})
2016-09-29 23:45:13 +02:00
// 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)
2017-03-16 12:14:02 +02:00
var wg sync.WaitGroup
parallel := c.Int("max-workflows")
2017-03-16 12:14:02 +02:00
wg.Add(parallel)
2016-09-29 23:45:13 +02:00
// 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
}
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)
}
}()
2017-03-16 12:14:02 +02:00
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 {
2017-08-03 21:36:22 +02:00
log.Error().Err(err).Msg("pipeline done with error")
2017-03-16 12:14:02 +02:00
return
}
}
}()
2016-04-20 03:37:53 +02:00
}
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)
2017-03-16 12:14:02 +02:00
wg.Wait()
return nil
}