github.com/projecteru2/core@v0.0.0-20240321043226-06bcc1c23f58/resource/plugins/binary/call.go (about)

     1  package binary
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"encoding/json"
     7  	"os/exec"
     8  
     9  	"github.com/projecteru2/core/log"
    10  )
    11  
    12  // calls the plugin and gets json response
    13  func (p Plugin) call(ctx context.Context, cmd string, req any, resp any) error {
    14  	ctx, cancel := context.WithTimeout(ctx, p.config.ResourcePlugin.CallTimeout)
    15  	defer cancel()
    16  	logger := log.WithFunc("resource.binary.call")
    17  
    18  	command := exec.CommandContext(ctx, p.path, cmd) // nolint
    19  	command.Dir = p.config.ResourcePlugin.Dir
    20  
    21  	out, err := p.execCommand(ctx, command, req)
    22  	if err != nil {
    23  		logger.Error(ctx, err, string(out))
    24  		return err
    25  	}
    26  
    27  	if len(out) == 0 {
    28  		return nil
    29  	}
    30  	return json.Unmarshal(out, resp)
    31  }
    32  
    33  func (p Plugin) execCommand(ctx context.Context, cmd *exec.Cmd, req any) ([]byte, error) {
    34  	logger := log.WithFunc("resource.binary.execCommand")
    35  	b, err := json.Marshal(req)
    36  	if err != nil {
    37  		return nil, err
    38  	}
    39  	if len(cmd.Args) < 2 || cmd.Args[1] != GetMetricsCommand {
    40  		logger.WithField("in", string(b)).WithField("cmd", cmd.String()).Info(ctx, "call params")
    41  	}
    42  	cmd.Stdin = bytes.NewBuffer(b)
    43  	return cmd.CombinedOutput()
    44  }