Skip to content

Instantly share code, notes, and snippets.

@roidelapluie
Created September 26, 2019 08:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save roidelapluie/f5b146dc1c64a4f5010a60dfe0e26ebe to your computer and use it in GitHub Desktop.
Save roidelapluie/f5b146dc1c64a4f5010a60dfe0e26ebe to your computer and use it in GitHub Desktop.
Read Alertmanager NFLOG
package main
import (
"errors"
"flag"
"fmt"
"io"
"os"
"github.com/gogo/protobuf/jsonpb"
pb "github.com/prometheus/alertmanager/nflog/nflogpb"
"github.com/matttproud/golang_protobuf_extensions/pbutil"
)
type state map[string]*pb.MeshEntry
// stateKey returns a string key for a log entry consisting of the group key
// and receiver.
func stateKey(k string, r *pb.Receiver) string {
return fmt.Sprintf("%s:%s", k, receiverKey(r))
}
func receiverKey(r *pb.Receiver) string {
return fmt.Sprintf("%s/%s/%d", r.GroupName, r.Integration, r.Idx)
}
func main() {
flag.Parse()
r, err := os.Open(flag.Arg(0))
if err != nil {
panic(err)
}
s, err := decodeState(r)
if err != nil {
panic(err)
}
for entry, mesh := range s {
m := &jsonpb.Marshaler{
Indent: " ",
}
os.Stdout.Write([]byte(fmt.Sprintf("Entry: %s\n", entry)))
m.Marshal(os.Stdout, mesh)
os.Stdout.Write([]byte("\n"))
}
}
func decodeState(r io.Reader) (state, error) {
st := state{}
for {
var e pb.MeshEntry
_, err := pbutil.ReadDelimited(r, &e)
if err == nil {
if e.Entry == nil || e.Entry.Receiver == nil {
return nil, errors.New("oops")
}
st[stateKey(string(e.Entry.GroupKey), e.Entry.Receiver)] = &e
continue
}
if err == io.EOF {
break
}
return nil, err
}
return st, nil
}
@FUSAKLA
Copy link

FUSAKLA commented Sep 20, 2023

Thanks for this piece of code!

One improvement, if you dump the result as JSON, the output will be sorted and consistent which can be handy if debugging Alertmanager cluster and comparing nflogs of multiple instances for example

enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", "  ")
enc.Encode(s)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment