github.com/criteo/command-launcher@v0.0.0-20230407142452-fb616f546e98/cmd/metrics/extensible.go (about)

     1  package metrics
     2  
     3  import (
     4  	"fmt"
     5  	"strconv"
     6  	"time"
     7  
     8  	"github.com/criteo/command-launcher/internal/command"
     9  )
    10  
    11  type extensibleMetrics struct {
    12  	hook command.Command
    13  
    14  	RepoName       string
    15  	PackageName    string
    16  	GroupName      string
    17  	CmdName        string
    18  	StartTimestamp time.Time
    19  	UserPartition  uint8
    20  }
    21  
    22  func NewExtensibleMetricsCollector(hook command.Command) Metrics {
    23  	return &extensibleMetrics{
    24  		hook: hook,
    25  	}
    26  }
    27  
    28  func (metrics *extensibleMetrics) Collect(uid uint8, repo string, pkg, group string, name string) error {
    29  	if group == "" {
    30  		return fmt.Errorf("unknown command")
    31  	}
    32  
    33  	metrics.RepoName = repo
    34  	metrics.PackageName = pkg
    35  	metrics.GroupName = group
    36  	metrics.CmdName = name
    37  	metrics.StartTimestamp = time.Now()
    38  	metrics.UserPartition = uid
    39  
    40  	return nil
    41  }
    42  
    43  func (metrics *extensibleMetrics) Send(cmdExitCode int, cmdError error) error {
    44  	// call the external hook
    45  	if metrics.hook != nil {
    46  		errMsg := "nil"
    47  		if cmdError != nil {
    48  			errMsg = cmdError.Error()
    49  		}
    50  		duration := time.Now().UnixNano() - metrics.StartTimestamp.UnixNano()
    51  		exitCode, _, err := metrics.hook.ExecuteWithOutput([]string{},
    52  			metrics.RepoName,
    53  			metrics.PackageName,
    54  			metrics.GroupName,
    55  			metrics.CmdName,
    56  			strconv.Itoa(int(metrics.UserPartition)),
    57  			strconv.Itoa(cmdExitCode),
    58  			strconv.FormatInt(duration, 10),
    59  			errMsg,
    60  			strconv.FormatInt(metrics.StartTimestamp.Unix(), 10),
    61  		)
    62  		if err != nil || exitCode != 0 {
    63  			return fmt.Errorf("failed to send metrics, exit code: %d, err: %v", exitCode, err)
    64  		}
    65  	}
    66  
    67  	return nil
    68  }