Пример #1
0
func (p *promH) graphCmd(ctx context.Context, w hugot.ResponseWriter, m *hugot.Message) error {
	defText, defGraph := false, false
	if !hugot.IsTextOnly(w) {
		defText = true
		defGraph = false
	} else {
		defText = false
		defGraph = true
	}

	_ = m.Bool("t", defText, "Render the graphs as text sparkline.")
	webGraph := m.Bool("g", defGraph, "Render the graphs as a png.")
	dur := m.Duration("d", 15*time.Minute, "how far back to render")

	if err := m.Parse(); err != nil {
		return err
	}

	if len(m.Args()) == 0 {
		return fmt.Errorf("you need to give a query")
	}
	q := strings.Join(m.Args(), " ")
	s := time.Now().Add(-1 * *dur)
	e := time.Now()

	if *webGraph {
		nu := *p.URL()
		nu.Path = nu.Path + "graph/thing.png"
		qs := nu.Query()
		qs.Set("q", q)
		qs.Set("s", fmt.Sprintf("%d", s.UnixNano()))
		qs.Set("e", fmt.Sprintf("%d", e.UnixNano()))
		nu.RawQuery = qs.Encode()

		m := hugot.Message{
			Channel: m.Channel,
			Attachments: []hugot.Attachment{
				{
					Fallback: "fallback",
					Pretext:  "image",
					ImageURL: nu.String(),
				},
			},
		}
		w.Send(ctx, &m)
		return nil
	}

	qapi := prom.NewQueryAPI(*p.client)
	d, err := qapi.QueryRange(ctx, q, prom.Range{s, e, 15 * time.Second})
	if err != nil {
		return err
	}

	switch d.Type() {
	case model.ValScalar:
		m := d.(*model.Scalar)
		glog.Infof("scalar %v", m)
	case model.ValVector:
		m := d.(model.Vector)
		glog.Infof("vector %v", m)
	case model.ValMatrix:
		mx := d.(model.Matrix)
		sort.Sort(mx)
		for _, ss := range mx {
			l := line(ss.Values)
			fmt.Fprintf(w, "%v\n%s", ss.Metric, l)
		}
	case model.ValString:
		m := d.(*model.String)
		glog.Infof("matrix %v", m)
	case model.ValNone:
	}

	return nil
}