Skip to content

Commit

Permalink
Split cli package (prometheus#1314)
Browse files Browse the repository at this point in the history
* cli: move commands to cli/cmd

* cli: use StatusAPI interface for config command

* cli: use SilenceAPI interface for silence commands

* cli: use AlertAPI for alert command

* cli: move back commands to cli package

And move API client code to its own package.

* cli: remove unused structs
  • Loading branch information
simonpasquier authored and stuartnelson3 committed Apr 11, 2018
1 parent 510e67e commit c92ed69
Show file tree
Hide file tree
Showing 16 changed files with 182 additions and 405 deletions.
98 changes: 14 additions & 84 deletions cli/alert.go
Original file line number Diff line number Diff line change
@@ -1,45 +1,24 @@
package cli

import (
"encoding/json"
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"time"

"github.com/alecthomas/kingpin"
"github.com/prometheus/client_golang/api"

"github.com/prometheus/alertmanager/cli/format"
"github.com/prometheus/alertmanager/dispatch"
"github.com/prometheus/alertmanager/client"
"github.com/prometheus/alertmanager/pkg/parse"
"github.com/prometheus/alertmanager/types"
"github.com/prometheus/common/model"
)

type alertmanagerAlertResponse struct {
Status string `json:"status"`
Data []*alertGroup `json:"data,omitempty"`
ErrorType string `json:"errorType,omitempty"`
Error string `json:"error,omitempty"`
}

type alertGroup struct {
Labels model.LabelSet `json:"labels"`
GroupKey string `json:"groupKey"`
Blocks []*alertBlock `json:"blocks"`
}

type alertBlock struct {
RouteOpts interface{} `json:"routeOpts"`
Alerts []*dispatch.APIAlert `json:"alerts"`
}

var (
alertCmd = app.Command("alert", "View and search through current alerts")
alertQueryCmd = alertCmd.Command("query", "View and search through current alerts").Default()
expired = alertQueryCmd.Flag("expired", "Show expired alerts as well as active").Bool()
showSilenced = alertQueryCmd.Flag("silenced", "Show silenced alerts").Short('s').Bool()
silenced = alertQueryCmd.Flag("silenced", "Show silenced alerts").Short('s').Bool()
alertQuery = alertQueryCmd.Arg("matcher-groups", "Query filter").Strings()
)

Expand Down Expand Up @@ -70,47 +49,12 @@ amtool alert query 'alertname=~foo.*'
longHelpText["alert query"] = longHelpText["alert"]
}

func fetchAlerts(filter string) ([]*dispatch.APIAlert, error) {
alertResponse := alertmanagerAlertResponse{}

u := GetAlertmanagerURL("/api/v1/alerts/groups")
u.RawQuery = "filter=" + url.QueryEscape(filter)

res, err := http.Get(u.String())
if err != nil {
return []*dispatch.APIAlert{}, err
}

defer res.Body.Close()

err = json.NewDecoder(res.Body).Decode(&alertResponse)
if err != nil {
return []*dispatch.APIAlert{}, fmt.Errorf("unable to decode json response: %s", err)
}

if alertResponse.Status != "success" {
return []*dispatch.APIAlert{}, fmt.Errorf("[%s] %s", alertResponse.ErrorType, alertResponse.Error)
}

return flattenAlertOverview(alertResponse.Data), nil
}

func flattenAlertOverview(overview []*alertGroup) []*dispatch.APIAlert {
alerts := []*dispatch.APIAlert{}
for _, group := range overview {
for _, block := range group.Blocks {
alerts = append(alerts, block.Alerts...)
}
}
return alerts
}

func queryAlerts(element *kingpin.ParseElement, ctx *kingpin.ParseContext) error {
var filterString = ""
if len(*alertQuery) == 1 {
// If we only have one argument then it's possible that the user wants me to assume alertname=<arg>
// Attempt to use the parser to pare the argument
// If the parser fails then we likely don't have a (=|=~|!=|!~) so lets prepend `alertname=` to the front
// If the parser fails then we likely don't have a (=|=~|!=|!~) so lets
// assume that the user wants alertname=<arg> and prepend `alertname=`
// to the front.
_, err := parse.Matcher((*alertQuery)[0])
if err != nil {
filterString = fmt.Sprintf("{alertname=%s}", (*alertQuery)[0])
Expand All @@ -121,33 +65,19 @@ func queryAlerts(element *kingpin.ParseElement, ctx *kingpin.ParseContext) error
filterString = fmt.Sprintf("{%s}", strings.Join(*alertQuery, ","))
}

fetchedAlerts, err := fetchAlerts(filterString)
c, err := api.NewClient(api.Config{Address: (*alertmanagerUrl).String()})
if err != nil {
return err
}

displayAlerts := []*dispatch.APIAlert{}
for _, alert := range fetchedAlerts {
// If we are only returning current alerts and this one has already expired skip it
if !*expired {
if !alert.EndsAt.IsZero() && alert.EndsAt.Before(time.Now()) {
continue
}
}

if !*showSilenced {
// If any silence mutes this alert don't show it
if alert.Status.State == types.AlertStateSuppressed && len(alert.Status.SilencedBy) > 0 {
continue
}
}

displayAlerts = append(displayAlerts, alert)
alertAPI := client.NewAlertAPI(c)
fetchedAlerts, err := alertAPI.List(context.Background(), filterString, *expired, *silenced)
if err != nil {
return err
}

formatter, found := format.Formatters[*output]
if !found {
return errors.New("unknown output formatter")
}
return formatter.FormatAlerts(displayAlerts)
return formatter.FormatAlerts(fetchedAlerts)
}
58 changes: 10 additions & 48 deletions cli/config.go
Original file line number Diff line number Diff line change
@@ -1,34 +1,16 @@
package cli

import (
"encoding/json"
"context"
"errors"
"fmt"
"net/http"
"time"

"github.com/alecthomas/kingpin"
"github.com/prometheus/client_golang/api"

"github.com/prometheus/alertmanager/cli/format"
"github.com/prometheus/alertmanager/config"
"github.com/prometheus/alertmanager/client"
)

// Config is the response type of alertmanager config endpoint
// Duped in cli/format needs to be moved to common/model
type Config struct {
ConfigYAML string `json:"configYAML"`
ConfigJSON config.Config `json:"configJSON"`
MeshStatus map[string]interface{} `json:"meshStatus"`
VersionInfo map[string]string `json:"versionInfo"`
Uptime time.Time `json:"uptime"`
}

type alertmanagerStatusResponse struct {
Status string `json:"status"`
Data Config `json:"data,omitempty"`
ErrorType string `json:"errorType,omitempty"`
Error string `json:"error,omitempty"`
}

// configCmd represents the config command
var configCmd = app.Command("config", "View the running config").Action(queryConfig)

Expand All @@ -40,31 +22,13 @@ The amount of output is controlled by the output selection flag:
- Json: Print entire config object as json`
}

func fetchConfig() (Config, error) {
configResponse := alertmanagerStatusResponse{}

u := GetAlertmanagerURL("/api/v1/status")
res, err := http.Get(u.String())
if err != nil {
return Config{}, err
}

defer res.Body.Close()

err = json.NewDecoder(res.Body).Decode(&configResponse)
func queryConfig(element *kingpin.ParseElement, ctx *kingpin.ParseContext) error {
c, err := api.NewClient(api.Config{Address: (*alertmanagerUrl).String()})
if err != nil {
return configResponse.Data, err
}

if configResponse.Status != "success" {
return Config{}, fmt.Errorf("[%s] %s", configResponse.ErrorType, configResponse.Error)
return err
}

return configResponse.Data, nil
}

func queryConfig(element *kingpin.ParseElement, ctx *kingpin.ParseContext) error {
config, err := fetchConfig()
statusAPI := client.NewStatusAPI(c)
status, err := statusAPI.Get(context.Background())
if err != nil {
return err
}
Expand All @@ -74,7 +38,5 @@ func queryConfig(element *kingpin.ParseElement, ctx *kingpin.ParseContext) error
return errors.New("unknown output formatter")
}

c := format.Config(config)

return formatter.FormatConfig(c)
return formatter.FormatConfig(status)
}
34 changes: 6 additions & 28 deletions cli/format/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import (
"time"

"github.com/alecthomas/kingpin"
"github.com/prometheus/alertmanager/config"
"github.com/prometheus/alertmanager/dispatch"

"github.com/prometheus/alertmanager/client"
"github.com/prometheus/alertmanager/types"
)

Expand All @@ -20,37 +20,15 @@ func InitFormatFlags(app *kingpin.Application) {
dateFormat = app.Flag("date.format", "Format of date output").Default(DefaultDateFormat).String()
}

// Config representation
// Need to get this moved to the prometheus/common/model repo having is duplicated here is smelly
type Config struct {
ConfigYAML string `json:"configYAML"`
ConfigJSON config.Config `json:"configJSON"`
MeshStatus map[string]interface{} `json:"meshStatus"`
VersionInfo map[string]string `json:"versionInfo"`
Uptime time.Time `json:"uptime"`
}

type MeshStatus struct {
Name string `json:"name"`
NickName string `json:"nickName"`
Peers []PeerStatus `json:"peerStatus"`
}

type PeerStatus struct {
Name string `json:"name"`
NickName string `json:"nickName"`
UID uint64 `uid`
}

// Formatter needs to be implemented for each new output formatter
// Formatter needs to be implemented for each new output formatter.
type Formatter interface {
SetOutput(io.Writer)
FormatSilences([]types.Silence) error
FormatAlerts([]*dispatch.APIAlert) error
FormatConfig(Config) error
FormatAlerts([]*client.ExtendedAlert) error
FormatConfig(*client.ServerStatus) error
}

// Formatters is a map of cli argument name to formatter inferface object
// Formatters is a map of cli argument names to formatter interface object.
var Formatters = map[string]Formatter{}

func FormatDate(input time.Time) string {
Expand Down
27 changes: 13 additions & 14 deletions cli/format/format_extended.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,8 @@ import (
"strings"
"text/tabwriter"

"github.com/prometheus/alertmanager/dispatch"
"github.com/prometheus/alertmanager/client"
"github.com/prometheus/alertmanager/types"
"github.com/prometheus/common/model"
)

type ExtendedFormatter struct {
Expand Down Expand Up @@ -46,7 +45,7 @@ func (formatter *ExtendedFormatter) FormatSilences(silences []types.Silence) err
return nil
}

func (formatter *ExtendedFormatter) FormatAlerts(alerts []*dispatch.APIAlert) error {
func (formatter *ExtendedFormatter) FormatAlerts(alerts []*client.ExtendedAlert) error {
w := tabwriter.NewWriter(formatter.writer, 0, 0, 2, ' ', 0)
sort.Sort(ByStartsAt(alerts))
fmt.Fprintln(w, "Labels\tAnnotations\tStarts At\tEnds At\tGenerator URL\t")
Expand All @@ -65,19 +64,19 @@ func (formatter *ExtendedFormatter) FormatAlerts(alerts []*dispatch.APIAlert) er
return nil
}

func (formatter *ExtendedFormatter) FormatConfig(config Config) error {
fmt.Fprintln(formatter.writer, config.ConfigYAML)
fmt.Fprintln(formatter.writer, "buildUser", config.VersionInfo["buildUser"])
fmt.Fprintln(formatter.writer, "goVersion", config.VersionInfo["goVersion"])
fmt.Fprintln(formatter.writer, "revision", config.VersionInfo["revision"])
fmt.Fprintln(formatter.writer, "version", config.VersionInfo["version"])
fmt.Fprintln(formatter.writer, "branch", config.VersionInfo["branch"])
fmt.Fprintln(formatter.writer, "buildDate", config.VersionInfo["buildDate"])
fmt.Fprintln(formatter.writer, "uptime", config.Uptime)
func (formatter *ExtendedFormatter) FormatConfig(status *client.ServerStatus) error {
fmt.Fprintln(formatter.writer, status.ConfigYAML)
fmt.Fprintln(formatter.writer, "buildUser", status.VersionInfo["buildUser"])
fmt.Fprintln(formatter.writer, "goVersion", status.VersionInfo["goVersion"])
fmt.Fprintln(formatter.writer, "revision", status.VersionInfo["revision"])
fmt.Fprintln(formatter.writer, "version", status.VersionInfo["version"])
fmt.Fprintln(formatter.writer, "branch", status.VersionInfo["branch"])
fmt.Fprintln(formatter.writer, "buildDate", status.VersionInfo["buildDate"])
fmt.Fprintln(formatter.writer, "uptime", status.Uptime)
return nil
}

func extendedFormatLabels(labels model.LabelSet) string {
func extendedFormatLabels(labels client.LabelSet) string {
output := []string{}
for name, value := range labels {
output = append(output, fmt.Sprintf("%s=\"%s\"", name, value))
Expand All @@ -86,7 +85,7 @@ func extendedFormatLabels(labels model.LabelSet) string {
return strings.Join(output, " ")
}

func extendedFormatAnnotations(labels model.LabelSet) string {
func extendedFormatAnnotations(labels client.LabelSet) string {
output := []string{}
for name, value := range labels {
output = append(output, fmt.Sprintf("%s=\"%s\"", name, value))
Expand Down
8 changes: 4 additions & 4 deletions cli/format/format_json.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"io"
"os"

"github.com/prometheus/alertmanager/dispatch"
"github.com/prometheus/alertmanager/client"
"github.com/prometheus/alertmanager/types"
)

Expand All @@ -26,12 +26,12 @@ func (formatter *JSONFormatter) FormatSilences(silences []types.Silence) error {
return enc.Encode(silences)
}

func (formatter *JSONFormatter) FormatAlerts(alerts []*dispatch.APIAlert) error {
func (formatter *JSONFormatter) FormatAlerts(alerts []*client.ExtendedAlert) error {
enc := json.NewEncoder(formatter.writer)
return enc.Encode(alerts)
}

func (formatter *JSONFormatter) FormatConfig(config Config) error {
func (formatter *JSONFormatter) FormatConfig(status *client.ServerStatus) error {
enc := json.NewEncoder(formatter.writer)
return enc.Encode(config)
return enc.Encode(status)
}
8 changes: 4 additions & 4 deletions cli/format/format_simple.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"strings"
"text/tabwriter"

"github.com/prometheus/alertmanager/dispatch"
"github.com/prometheus/alertmanager/client"
"github.com/prometheus/alertmanager/types"
)

Expand Down Expand Up @@ -43,7 +43,7 @@ func (formatter *SimpleFormatter) FormatSilences(silences []types.Silence) error
return nil
}

func (formatter *SimpleFormatter) FormatAlerts(alerts []*dispatch.APIAlert) error {
func (formatter *SimpleFormatter) FormatAlerts(alerts []*client.ExtendedAlert) error {
w := tabwriter.NewWriter(formatter.writer, 0, 0, 2, ' ', 0)
sort.Sort(ByStartsAt(alerts))
fmt.Fprintln(w, "Alertname\tStarts At\tSummary\t")
Expand All @@ -60,8 +60,8 @@ func (formatter *SimpleFormatter) FormatAlerts(alerts []*dispatch.APIAlert) erro
return nil
}

func (formatter *SimpleFormatter) FormatConfig(config Config) error {
fmt.Fprintln(formatter.writer, config.ConfigYAML)
func (formatter *SimpleFormatter) FormatConfig(status *client.ServerStatus) error {
fmt.Fprintln(formatter.writer, status.ConfigYAML)
return nil
}

Expand Down
Loading

0 comments on commit c92ed69

Please sign in to comment.