Browse Source

Move Client to package 'bot'

master
Silke 3 years ago
parent
commit
af75c0b9e8
  1. 13
      alertmanager_matrix.go
  2. 28
      bot/formatting.go
  3. 42
      bot/matrix.go
  4. 2
      bot/util.go

13
alertmanager_matrix.go

@ -8,12 +8,13 @@ import (
"os"
"git.slxh.eu/prometheus/alertmanager_matrix/alertmanager"
"git.slxh.eu/prometheus/alertmanager_matrix/bot"
"github.com/gorilla/mux"
)
func handler(w http.ResponseWriter, r *http.Request) {
// Get room from request
room := client.ma.NewRoom(mux.Vars(r)["room"])
room := client.Matrix.NewRoom(mux.Vars(r)["room"])
if room.ID[0] != '!' {
log.Print("Invalid room ID: ", room.ID)
w.WriteHeader(http.StatusBadRequest)
@ -29,7 +30,7 @@ func handler(w http.ResponseWriter, r *http.Request) {
}
// Create readable messages for Matrix
plain, html := formatAlerts(data.Alerts, false)
plain, html := bot.FormatAlerts(data.Alerts, false)
log.Printf("Sending message to %s: %s", room.ID, plain)
if _, err := room.SendHTML(plain, html); err != nil {
@ -56,7 +57,7 @@ func setMapFromJSONFile(m *map[string]string, fileName string) {
}
// Main client
var client *Client
var client *bot.Client
func main() {
var (
@ -85,10 +86,10 @@ func main() {
// Load mappings from files
if iconFile != "" {
setMapFromJSONFile(&alertIcons, iconFile)
setMapFromJSONFile(&bot.AlertIcons, iconFile)
}
if colorFile != "" {
setMapFromJSONFile(&alertColors, colorFile)
setMapFromJSONFile(&bot.AlertColors, colorFile)
}
// Check if user is set
@ -103,7 +104,7 @@ func main() {
// Create/connect client
log.Printf("Connecting to Matrix homeserver at %s as %s, and to Alertmanager at %s", homeserver, userID, alertmanagerURL)
client, err := NewClient(homeserver, userID, token, messageType, rooms, alertmanagerURL)
client, err := bot.NewClient(homeserver, userID, token, messageType, rooms, alertmanagerURL)
if err != nil {
log.Fatalf("Error connecting to Matrix: %s", err)
}

28
formatting.go → bot/formatting.go

@ -1,4 +1,4 @@
package main
package bot
import (
"fmt"
@ -9,8 +9,8 @@ import (
"github.com/prometheus/alertmanager/types"
)
// alertIcons represent the icons corresponding to the alert status
var alertIcons = map[string]string{
// AlertIcons represent the icons corresponding to the alert status
var AlertIcons = map[string]string{
"alert": "🔔️",
"information": "ℹ️",
"warning": "⚠️",
@ -19,8 +19,8 @@ var alertIcons = map[string]string{
"silenced": "🔕",
}
// alertColors represent the colors corresponding to the alert status
var alertColors = map[string]string{
// AlertColors represent the colors corresponding to the alert status
var AlertColors = map[string]string{
"alert": "black",
"information": "blue",
"warning": "orange",
@ -31,7 +31,7 @@ var alertColors = map[string]string{
// icon returns the icon for a string
func icon(t string) string {
if e, ok := alertIcons[t]; ok {
if e, ok := AlertIcons[t]; ok {
return e
}
log.Printf("Unknown status: %s", t)
@ -40,15 +40,15 @@ func icon(t string) string {
// color returns the color for string
func color(t string) string {
if c, ok := alertColors[t]; ok {
if c, ok := AlertColors[t]; ok {
return c
}
log.Printf("Unknown status: %s", t)
return "gray"
}
// createMessage formats a message using the status, name and summary
func createMessage(status, name, summary, id string) (plain, html string) {
// CreateMessage formats a message using the status, name and summary
func CreateMessage(status, name, summary, id string) (plain, html string) {
icon := icon(status)
color := color(status)
@ -63,8 +63,8 @@ func createMessage(status, name, summary, id string) (plain, html string) {
return
}
// formatAlerts formats alerts as plain text and HTML
func formatAlerts(alerts []*alertmanager.Alert, labels bool) (string, string) {
// FormatAlerts formats alerts as plain text and HTML
func FormatAlerts(alerts []*alertmanager.Alert, labels bool) (string, string) {
plain := make([]string, len(alerts))
html := make([]string, len(alerts))
@ -89,7 +89,7 @@ func formatAlerts(alerts []*alertmanager.Alert, labels bool) (string, string) {
}
// Format main message
plain[i], html[i] = createMessage(status, alertName, summary, a.Fingerprint)
plain[i], html[i] = CreateMessage(status, alertName, summary, a.Fingerprint)
// Add labels
if labels {
@ -110,8 +110,8 @@ func formatAlerts(alerts []*alertmanager.Alert, labels bool) (string, string) {
return plainBody, htmlBody
}
// formatSilences formats silences as Markdown.
func formatSilences(silences []*types.Silence, state string) string {
// FormatSilences formats silences as Markdown.
func FormatSilences(silences []*types.Silence, state string) string {
md := ""
for _, s := range silences {

42
matrix.go → bot/matrix.go

@ -1,4 +1,4 @@
package main
package bot
import (
"context"
@ -30,30 +30,30 @@ const (
// Client represents an Alertmanager/Matrix client
type Client struct {
ma *matrix.Client
am *alertmanager.Client
roomList []string
rooms map[string]struct{}
Matrix *matrix.Client
Alertmanager *alertmanager.Client
roomList []string
rooms map[string]struct{}
}
// Create and start a new Alertmanager/Matrix client
// NewClient creates and starts a new Alertmanager/Matrix client
func NewClient(homeserver, userID, token, messageType, rooms, alertmanagerURL string) (client *Client, err error) {
client = new(Client)
// Create Alertmanager client
client.am, err = alertmanager.NewClient(alertmanagerURL)
client.Alertmanager, err = alertmanager.NewClient(alertmanagerURL)
if err != nil {
return
}
// Create Matrix client
client.ma, err = matrix.NewClient(homeserver, userID, token, messageType)
client.Matrix, err = matrix.NewClient(homeserver, userID, token, messageType)
if err != nil {
return
}
// Register sync/message handler
client.ma.Syncer.OnEventType("m.room.message", client.messageHandler)
client.Matrix.Syncer.OnEventType("m.room.message", client.messageHandler)
// Create room list
if rooms != "" {
@ -63,7 +63,7 @@ func NewClient(homeserver, userID, token, messageType, rooms, alertmanagerURL st
return
}
// Start the Matrix client
// Run the client in a blocking thread
func (c *Client) Run() error {
// Join rooms
if c.roomList != nil {
@ -83,7 +83,7 @@ func (c *Client) joinRooms(roomList []string) error {
// Join all rooms
for _, r := range roomList {
j, err := c.ma.JoinRoom(r, "", nil)
j, err := c.Matrix.JoinRoom(r, "", nil)
if err != nil {
return err
}
@ -96,7 +96,7 @@ func (c *Client) joinRooms(roomList []string) error {
// sync runs a never ending Matrix sync
func (c *Client) sync() error {
for {
err := c.ma.Sync()
err := c.Matrix.Sync()
if err != nil {
return err
}
@ -117,7 +117,7 @@ func (c *Client) messageHandler(e *matrix.Event) {
// - sent by the bot itself
// - does not start with command
if !ok ||
e.Sender == c.ma.UserID ||
e.Sender == c.Matrix.UserID ||
!strings.HasPrefix(text, command) {
return
}
@ -131,7 +131,7 @@ func (c *Client) messageHandler(e *matrix.Event) {
}
// Room to send response to
room := c.ma.NewRoom(e.RoomID)
room := c.Matrix.NewRoom(e.RoomID)
// Get command
cmd := strings.Split(text, " ")
@ -172,7 +172,7 @@ func (c *Client) messageHandler(e *matrix.Event) {
// Alerts returns all or non-silenced alerts
func (c *Client) Alerts(silenced bool, labels bool) (string, string) {
alerts, err := c.am.GetAlerts(silenced)
alerts, err := c.Alertmanager.GetAlerts(silenced)
if err != nil {
return err.Error(), ""
}
@ -180,17 +180,17 @@ func (c *Client) Alerts(silenced bool, labels bool) (string, string) {
return "No alerts", ""
}
return formatAlerts(alerts, labels)
return FormatAlerts(alerts, labels)
}
// Silences returns a Markdown formatted message containing silences with the specified state
func (c *Client) Silences(state string) string {
silences, err := c.am.Silence.List(context.TODO(), "")
silences, err := c.Alertmanager.Silence.List(context.TODO(), "")
if err != nil {
return err.Error()
}
md := formatSilences(silences, state)
md := FormatSilences(silences, state)
if md == "" {
return fmt.Sprintf("No %s silences", state)
@ -221,7 +221,7 @@ func (c *Client) NewSilence(author string, args []string) string {
// Check if an ID is given instead of matchers
if len(matchers) == 1 && !strings.ContainsRune(matchers[0], '=') {
alert, err := c.am.GetAlert(matchers[0])
alert, err := c.Alertmanager.GetAlert(matchers[0])
if err != nil {
return err.Error()
}
@ -250,7 +250,7 @@ func (c *Client) NewSilence(author string, args []string) string {
}
}
id, err := c.am.Silence.Set(context.TODO(), silence)
id, err := c.Alertmanager.Silence.Set(context.TODO(), silence)
if err != nil {
return err.Error()
}
@ -267,7 +267,7 @@ func (c *Client) DelSilence(ids []string) string {
var errors []string
for _, id := range ids {
err := c.am.Silence.Expire(context.TODO(), id)
err := c.Alertmanager.Silence.Expire(context.TODO(), id)
if err != nil {
errors = append(errors,
fmt.Sprintf("Error deleting %s: %s", id, err))

2
util.go → bot/util.go

@ -1,4 +1,4 @@
package main
package bot
import (
"regexp"
Loading…
Cancel
Save