Example #1
0
func post(in <-chan []LM) {
	for metrics := range in {
		if len(metrics) < 1 {
			fmt.Printf("at=%q\n", "post.empty.metrics")
			continue
		}
		token := store.Token{Id: metrics[0].Token}
		token.Get()
		payload := LP{metrics}
		j, err := json.Marshal(payload)
		postBody := bytes.NewBuffer(j)
		if err != nil {
			utils.MeasureE("librato.json", err)
			continue
		}
		req, err := http.NewRequest("POST", libratoUrl, postBody)
		if err != nil {
			continue
		}
		req.Header.Add("Content-Type", "application/json")
		req.SetBasicAuth(token.User, token.Pass)
		resp, err := http.DefaultClient.Do(req)
		if err != nil {
			utils.MeasureE("librato-post", err)
			continue
		}
		if resp.StatusCode/100 != 2 {
			b, _ := ioutil.ReadAll(resp.Body)
			fmt.Printf("status=%d post-body=%s resp-body=%s\n",
				resp.StatusCode, postBody, b)
		}
		utils.MeasureI("librato.post", 1)
		resp.Body.Close()
	}
}
Example #2
0
func post(outbox <-chan []*LM) {
	for metrics := range outbox {
		if len(metrics) < 1 {
			fmt.Printf("at=%q\n", "empty-metrics-error")
			continue
		}

		sampleMetric := metrics[0]
		token := store.Token{Id: sampleMetric.Token}

		// If a global user/token is provided, use the token for all metrics.
		// This enable a databaseless librato_outlet.
		if len(globalTokenUser) == 0 || len(globalTokenPass) == 0 {
			token.Get()
		} else {
			token.User = globalTokenUser
			token.Pass = globalTokenPass
		}

		payload := new(LP)
		payload.Gauges = metrics

		j, err := json.Marshal(payload)
		if err != nil {
			fmt.Printf("at=json-marshal-error error=%s\n", err)
			continue
		}

		if len(j) == 0 {
			fmt.Printf("at=empty-body-error body=%s\n", j)
			continue
		}
		fmt.Printf("at=%q name=%s source=%s len=%d\n",
			"post-metric", sampleMetric.Name, sampleMetric.Source,
			len(metrics))
		maxRetry := 5
		for i := 0; i <= maxRetry; i++ {
			b := bytes.NewBuffer(j)
			req, err := http.NewRequest("POST", libratoUrl, b)
			if err != nil {
				fmt.Printf("at=%q error=%s body=%s\n", "request-error", err, b)
				continue
			}
			req.Header.Add("Content-Type", "application/json")
			req.SetBasicAuth(token.User, token.Pass)

			resp, err := http.DefaultClient.Do(req)
			if err != nil {
				fmt.Printf("at=%q error=%s body=%s\n", "do-error", err, b)
				continue
			}
			if resp.StatusCode/100 == 2 {
				resp.Body.Close()
				utils.MeasureI("librato-http-post", 1)
				break
			} else {
				resp.Body.Close()
				if i == maxRetry {
					fmt.Printf("at=%q status=%d\n",
						"librato-status-error", resp.StatusCode)
				}
			}
		}
	}
}