github.com/filecoin-project/bacalhau@v0.3.23-0.20230228154132-45c989550ace/pkg/compute/bidstrategy/external_exec_strategy.go (about)

     1  package bidstrategy
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"fmt"
     7  	"os"
     8  	"os/exec"
     9  	"strings"
    10  
    11  	"github.com/filecoin-project/bacalhau/pkg/logger"
    12  	"github.com/filecoin-project/bacalhau/pkg/model"
    13  	"github.com/rs/zerolog/log"
    14  )
    15  
    16  type ExternalCommandStrategyParams struct {
    17  	Command string
    18  }
    19  
    20  type ExternalCommandStrategy struct {
    21  	command string
    22  }
    23  
    24  func NewExternalCommandStrategy(params ExternalCommandStrategyParams) *ExternalCommandStrategy {
    25  	return &ExternalCommandStrategy{
    26  		command: params.Command,
    27  	}
    28  }
    29  
    30  func (s *ExternalCommandStrategy) ShouldBid(ctx context.Context, request BidStrategyRequest) (BidStrategyResponse, error) {
    31  	if s.command == "" {
    32  		return newShouldBidResponse(), nil
    33  	}
    34  
    35  	// TODO: Use context to trace exec call
    36  
    37  	data := getJobSelectionPolicyProbeData(request)
    38  	jsonData, err := model.JSONMarshalWithMax(data)
    39  
    40  	if err != nil {
    41  		return BidStrategyResponse{},
    42  			fmt.Errorf("ExternalCommandStrategy: error marshaling job selection policy probe data: %w", err)
    43  	}
    44  
    45  	cmd := exec.Command("bash", "-c", s.command) //nolint:gosec
    46  	cmd.Env = []string{
    47  		"BACALHAU_JOB_SELECTION_PROBE_DATA=" + string(jsonData),
    48  		"PATH=" + os.Getenv("PATH"),
    49  	}
    50  	cmd.Stdin = strings.NewReader(string(jsonData))
    51  	buf := bytes.Buffer{}
    52  	cmd.Stderr = &buf
    53  	err = cmd.Run()
    54  	if err != nil {
    55  		// we ignore this error because it might be the script exiting 1 on purpose
    56  		logger.LogStream(ctx, &buf)
    57  		log.Ctx(ctx).Debug().Err(err).Str("Command", s.command).Msg("We got an error back from a job selection probe exec")
    58  	}
    59  
    60  	exitCode := cmd.ProcessState.ExitCode()
    61  	if exitCode == 0 {
    62  		return newShouldBidResponse(), nil
    63  	}
    64  	return BidStrategyResponse{
    65  		ShouldBid: false,
    66  		Reason:    fmt.Sprintf("command `%s` returned non-zero exit code %d", s.command, exitCode),
    67  	}, nil
    68  }
    69  
    70  func (s *ExternalCommandStrategy) ShouldBidBasedOnUsage(
    71  	_ context.Context, _ BidStrategyRequest, _ model.ResourceUsageData) (BidStrategyResponse, error) {
    72  	return newShouldBidResponse(), nil
    73  }