1
0
mirror of https://github.com/woodpecker-ci/woodpecker.git synced 2024-11-30 08:06:52 +02:00
woodpecker/pipeline/pipeline.go

290 lines
6.6 KiB
Go
Raw Normal View History

// Copyright 2023 Woodpecker 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.
2017-03-05 09:56:08 +02:00
package pipeline
import (
"context"
"errors"
"strings"
"sync"
2017-03-05 09:56:08 +02:00
"time"
"github.com/oklog/ulid/v2"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
2017-03-05 09:56:08 +02:00
"golang.org/x/sync/errgroup"
backend "go.woodpecker-ci.org/woodpecker/v2/pipeline/backend/types"
"go.woodpecker-ci.org/woodpecker/v2/pipeline/frontend/metadata"
2017-03-05 09:56:08 +02:00
)
// TODO: move runtime into "runtime" subpackage
2017-03-05 09:56:08 +02:00
type (
// State defines the pipeline and process state.
State struct {
// Global state of the pipeline.
Pipeline struct {
// Pipeline time started
2024-07-01 11:20:55 +02:00
Started int64 `json:"time"`
2017-03-05 09:56:08 +02:00
// Current pipeline step
Step *backend.Step `json:"step"`
// Current pipeline error state
Error error `json:"error"`
}
// Current process state.
Process *backend.State
}
)
// Runtime is a configuration runtime.
type Runtime struct {
err error
spec *backend.Config
engine backend.Backend
2017-03-05 09:56:08 +02:00
started int64
ctx context.Context
tracer Tracer
logger Logger
taskUUID string
Description map[string]string // The runtime descriptors.
2017-03-05 09:56:08 +02:00
}
// New returns a new runtime using the specified runtime
// configuration and runtime engine.
func New(spec *backend.Config, opts ...Option) *Runtime {
r := new(Runtime)
r.Description = map[string]string{}
2017-03-05 09:56:08 +02:00
r.spec = spec
r.ctx = context.Background()
r.taskUUID = ulid.Make().String()
2017-03-05 09:56:08 +02:00
for _, opts := range opts {
opts(r)
}
return r
}
func (r *Runtime) MakeLogger() zerolog.Logger {
logCtx := log.With()
for key, val := range r.Description {
logCtx = logCtx.Str(key, val)
}
return logCtx.Logger()
}
// Run starts the execution of a workflow and waits for it to complete.
func (r *Runtime) Run(runnerCtx context.Context) error {
logger := r.MakeLogger()
logger.Debug().Msgf("executing %d stages, in order of:", len(r.spec.Stages))
for stagePos, stage := range r.spec.Stages {
stepNames := []string{}
for _, step := range stage.Steps {
stepNames = append(stepNames, step.Name)
}
logger.Debug().
Int("StagePos", stagePos).
Str("Steps", strings.Join(stepNames, ",")).
Msg("stage")
}
2017-03-05 09:56:08 +02:00
defer func() {
2024-07-14 01:06:20 +02:00
ctx := runnerCtx //nolint:contextcheck
if ctx.Err() != nil {
ctx = GetShutdownCtx()
}
if err := r.engine.DestroyWorkflow(ctx, r.spec, r.taskUUID); err != nil {
logger.Error().Err(err).Msg("could not destroy engine")
}
2017-03-05 09:56:08 +02:00
}()
r.started = time.Now().Unix()
if err := r.engine.SetupWorkflow(runnerCtx, r.spec, r.taskUUID); err != nil {
2017-03-05 09:56:08 +02:00
return err
}
for _, stage := range r.spec.Stages {
select {
case <-r.ctx.Done():
return ErrCancel
case err := <-r.execAll(stage.Steps):
if err != nil {
r.err = err
}
}
}
return r.err
}
// Updates the current status of a step.
func (r *Runtime) traceStep(processState *backend.State, err error, step *backend.Step) error {
if r.tracer == nil {
// no tracer nothing to trace :)
return nil
}
if processState == nil {
processState = new(backend.State)
if err != nil {
processState.Error = err
processState.Exited = true
processState.OOMKilled = false
processState.ExitCode = 126 // command invoked cannot be executed.
}
}
state := new(State)
2024-07-01 11:20:55 +02:00
state.Pipeline.Started = r.started
state.Pipeline.Step = step
state.Process = processState // empty
state.Pipeline.Error = r.err
if traceErr := r.tracer.Trace(state); traceErr != nil {
return traceErr
}
return err
}
2017-03-05 09:56:08 +02:00
// Executes a set of parallel steps.
func (r *Runtime) execAll(steps []*backend.Step) <-chan error {
2017-03-05 09:56:08 +02:00
var g errgroup.Group
done := make(chan error)
logger := r.MakeLogger()
2017-03-05 09:56:08 +02:00
for _, step := range steps {
2024-01-14 11:54:02 +02:00
// Required since otherwise the loop variable
// will be captured by the function. This will
// recreate the step "variable"
step := step
2017-03-05 09:56:08 +02:00
g.Go(func() error {
// Case the pipeline was already complete.
logger.Debug().
2024-01-14 11:54:02 +02:00
Str("step", step.Name).
Msg("prepare")
switch {
case r.err != nil && !step.OnFailure:
logger.Debug().
2024-01-14 11:54:02 +02:00
Str("step", step.Name).
Err(r.err).
2024-01-14 11:54:02 +02:00
Msgf("skipped due to OnFailure=%t", step.OnFailure)
return nil
case r.err == nil && !step.OnSuccess:
logger.Debug().
2024-01-14 11:54:02 +02:00
Str("step", step.Name).
Msgf("skipped due to OnSuccess=%t", step.OnSuccess)
return nil
}
// Trace started.
err := r.traceStep(nil, nil, step)
if err != nil {
return err
}
// add compatibility for drone-ci plugins
metadata.SetDroneEnviron(step.Environment)
logger.Debug().
2024-01-14 11:54:02 +02:00
Str("step", step.Name).
Msg("executing")
processState, err := r.exec(step)
logger.Debug().
2024-01-14 11:54:02 +02:00
Str("step", step.Name).
Msg("complete")
// Return the error after tracing it.
err = r.traceStep(processState, err, step)
if err != nil && step.Failure == metadata.FailureIgnore {
return nil
}
return err
2017-03-05 09:56:08 +02:00
})
}
go func() {
done <- g.Wait()
close(done)
}()
return done
}
// Executes the step and returns the state and error.
func (r *Runtime) exec(step *backend.Step) (*backend.State, error) {
if err := r.engine.StartStep(r.ctx, step, r.taskUUID); err != nil {
return nil, err
2017-03-05 09:56:08 +02:00
}
var wg sync.WaitGroup
2017-03-05 09:56:08 +02:00
if r.logger != nil {
rc, err := r.engine.TailStep(r.ctx, step, r.taskUUID)
2017-03-05 09:56:08 +02:00
if err != nil {
return nil, err
2017-03-05 09:56:08 +02:00
}
wg.Add(1)
2017-03-05 09:56:08 +02:00
go func() {
defer wg.Done()
logger := r.MakeLogger()
2024-01-14 11:54:02 +02:00
if err := r.logger(step, rc); err != nil {
logger.Error().Err(err).Msg("process logging failed")
}
_ = rc.Close()
2017-03-05 09:56:08 +02:00
}()
}
// nothing else to do, this is a detached process.
if step.Detached {
return nil, nil
2017-03-05 09:56:08 +02:00
}
// We wait until all data was logged. (Needed for some backends like local as WaitStep kills the log stream)
wg.Wait()
waitState, err := r.engine.WaitStep(r.ctx, step, r.taskUUID)
2017-03-05 09:56:08 +02:00
if err != nil {
if errors.Is(err, context.Canceled) {
return waitState, ErrCancel
}
return nil, err
2017-03-05 09:56:08 +02:00
}
if err := r.engine.DestroyStep(r.ctx, step, r.taskUUID); err != nil {
return nil, err
}
if waitState.OOMKilled {
return waitState, &OomError{
UUID: step.UUID,
Code: waitState.ExitCode,
2017-03-05 09:56:08 +02:00
}
} else if waitState.ExitCode != 0 {
return waitState, &ExitError{
UUID: step.UUID,
Code: waitState.ExitCode,
2017-03-05 09:56:08 +02:00
}
}
return waitState, nil
2017-03-05 09:56:08 +02:00
}