github.com/leg100/ots@v0.0.7-0.20210919080622-034055ced4bd/agent/worker.go (about)

     1  package agent
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/leg100/ots"
     7  )
     8  
     9  // Worker sequentially executes jobs on behalf of a supervisor.
    10  type Worker struct {
    11  	*Supervisor
    12  }
    13  
    14  // Start starts the worker which waits for jobs to execute.
    15  func (w *Worker) Start(ctx context.Context) {
    16  	for {
    17  		select {
    18  		case job := <-w.GetJob():
    19  			w.handleJob(ctx, job)
    20  		case <-ctx.Done():
    21  			return
    22  		}
    23  	}
    24  }
    25  
    26  func (w *Worker) handleJob(ctx context.Context, job ots.Job) {
    27  	log := w.Logger.WithValues("job", job.GetID())
    28  
    29  	env, err := ots.NewExecutor(
    30  		log,
    31  		w.RunService,
    32  		w.ConfigurationVersionService,
    33  		w.StateVersionService,
    34  		DefaultID,
    35  	)
    36  	if err != nil {
    37  		log.Error(err, "unable to create execution environment")
    38  		return
    39  	}
    40  
    41  	// Check job in with the supervisor for duration of job.
    42  	w.CheckIn(job.GetID(), env)
    43  	defer w.CheckOut(job.GetID())
    44  
    45  	if err := env.Execute(job); err != nil {
    46  		log.Error(err, "job execution failed")
    47  	}
    48  }