github.com/caos/orbos@v1.5.14-0.20221103111702-e6cd0cea7ad4/cmd/chore/e2e/run/graphite.go (about)

     1  package main
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"encoding/json"
     7  	"fmt"
     8  	"net/http"
     9  	"time"
    10  
    11  	"gopkg.in/raintank/schema.v1"
    12  )
    13  
    14  type runFunc func(context.Context, programSettings) error
    15  
    16  func graphite(cloudURL, cloudKey string, test runFunc) runFunc {
    17  
    18  	return func(ctx context.Context, settings programSettings) error {
    19  		send := func(value float64, ts time.Time) {
    20  			if err := sendGraphiteStatus(settings.orbID, cloudURL, cloudKey, settings.branch, value, ts); err != nil {
    21  				panic(err)
    22  			}
    23  		}
    24  
    25  		start := time.Now()
    26  		send(0.5, start)
    27  		err := test(ctx, settings)
    28  		var value float64 = 0
    29  		if err == nil {
    30  			value = 1
    31  		}
    32  		stop := time.Now()
    33  		minStop := start.Add(2 * time.Minute)
    34  		if minStop.After(stop) {
    35  			stop = minStop
    36  		}
    37  		send(value, stop)
    38  		return err
    39  	}
    40  }
    41  
    42  func sendGraphiteStatus(orbID, cloudURL, cloudKey, branch string, value float64, ts time.Time) error {
    43  
    44  	name := fmt.Sprintf("e2e.%s.%s", orbID, branch)
    45  
    46  	metrics := schema.MetricDataArray{&schema.MetricData{
    47  		Name:     name,
    48  		Interval: 10,
    49  		Value:    value,
    50  		Time:     ts.Unix(),
    51  		Mtype:    "gauge",
    52  	}}
    53  
    54  	// encode as json
    55  	data, err := json.Marshal(metrics)
    56  	if err != nil {
    57  		return err
    58  	}
    59  
    60  	client := &http.Client{}
    61  
    62  	req, err := http.NewRequest("POST", cloudURL, bytes.NewBuffer(data))
    63  	if err != nil {
    64  		return err
    65  	}
    66  
    67  	req.Header.Add("Authorization", "Bearer "+cloudKey)
    68  	req.Header.Add("Content-Type", "application/json")
    69  	resp, err := client.Do(req)
    70  	if err != nil {
    71  		return err
    72  	}
    73  	buf := make([]byte, 4096)
    74  	n, err := resp.Body.Read(buf)
    75  	if resp.StatusCode >= 400 {
    76  		return fmt.Errorf("sending metric to graphana cloud graphite api at %s failed with status %s and response %s", cloudURL, resp.Status, string(buf[:n]))
    77  	}
    78  	fmt.Println("Metric", name, "with value", value, "sent to grafana cloud graphite api")
    79  	return nil
    80  }