From 9a1440d469997afcb742cf732d89501409b67131 Mon Sep 17 00:00:00 2001 From: beorn7 Date: Fri, 28 Jun 2019 15:12:09 +0200 Subject: [PATCH] Add Delete method Fixes #611. Signed-off-by: beorn7 --- prometheus/push/push.go | 36 ++++++++++++++++++++++++++++++++++++ prometheus/push/push_test.go | 18 ++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/prometheus/push/push.go b/prometheus/push/push.go index 3de115d..61f5697 100644 --- a/prometheus/push/push.go +++ b/prometheus/push/push.go @@ -204,6 +204,42 @@ func (p *Pusher) Format(format expfmt.Format) *Pusher { return p } +// Delete sends a “DELETE” request to the Pushgateway configured while creating +// this Pusher, using the configured job name and any added grouping labels as +// grouping key. Any added Gatherers and Collectors added to this Pusher are +// ignored by this method. +// +// Delete returns the first error encountered by any method call (including this +// one) in the lifetime of the Pusher. +func (p *Pusher) Delete() error { + if p.error != nil { + return p.error + } + urlComponents := []string{url.QueryEscape(p.job)} + for ln, lv := range p.grouping { + urlComponents = append(urlComponents, ln, lv) + } + deleteURL := fmt.Sprintf("%s/metrics/job/%s", p.url, strings.Join(urlComponents, "/")) + + req, err := http.NewRequest(http.MethodDelete, deleteURL, nil) + if err != nil { + return err + } + if p.useBasicAuth { + req.SetBasicAuth(p.username, p.password) + } + resp, err := p.client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode != 202 { + body, _ := ioutil.ReadAll(resp.Body) // Ignore any further error as this is for an error message only. + return fmt.Errorf("unexpected status code %d while deleting %s: %s", resp.StatusCode, deleteURL, body) + } + return nil +} + func (p *Pusher) push(method string) error { if p.error != nil { return p.error diff --git a/prometheus/push/push_test.go b/prometheus/push/push_test.go index 5e19f39..c34f948 100644 --- a/prometheus/push/push_test.go +++ b/prometheus/push/push_test.go @@ -191,4 +191,22 @@ func TestPush(t *testing.T) { if lastPath != "/metrics/job/testjob/a/x/b/y" && lastPath != "/metrics/job/testjob/b/y/a/x" { t.Error("unexpected path:", lastPath) } + + // Delete, all good. + if err := New(pgwOK.URL, "testjob"). + Grouping("a", "x"). + Grouping("b", "y"). + Delete(); err != nil { + t.Fatal(err) + } + if lastMethod != "DELETE" { + t.Error("want method DELETE for delete, got", lastMethod) + } + if len(lastBody) != 0 { + t.Errorf("got body of length %d, want empty body", len(lastBody)) + } + if lastPath != "/metrics/job/testjob/a/x/b/y" && lastPath != "/metrics/job/testjob/b/y/a/x" { + t.Error("unexpected path:", lastPath) + } + }