forked from int128/slack-docker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
93 lines (87 loc) · 2.45 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main
import (
"context"
"fmt"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/int128/slack"
"github.com/int128/slack-docker/formatter"
"github.com/jessevdk/go-flags"
"io"
"log"
"regexp"
)
type options struct {
Webhook string `long:"webhook" env:"webhook" description:"Slack Incoming WebHook URL" required:"1"`
DockerImageRegexp string `long:"image-regexp" env:"image_regexp" description:"Filter events by image name (default to all)"`
}
func (o *options) Run(ctx context.Context) error {
var eventFilter formatter.EventFilter
if o.DockerImageRegexp != "" {
r, err := regexp.Compile(o.DockerImageRegexp)
if err != nil {
return fmt.Errorf("Invalid image-regexp: %s", err)
}
eventFilter.ImageRegexp = r
}
docker, err := client.NewEnvClient()
if err != nil {
return fmt.Errorf("Could not create a Docker client: %s", err)
}
if err := o.showVersion(ctx, docker); err != nil {
return err
}
if err := o.showEvents(ctx, docker, eventFilter); err != nil {
return err
}
return nil
}
func (o *options) showVersion(ctx context.Context, docker *client.Client) error {
v, err := docker.ServerVersion(ctx)
if err != nil {
return fmt.Errorf("Could not get version from the Docker server: %s", err)
}
log.Printf("Connected to Docker server: %+v", v)
if err := slack.Send(o.Webhook, formatter.Version(v)); err != nil {
return fmt.Errorf("Could not send a message to Slack: %s", err)
}
return nil
}
func (o *options) showEvents(ctx context.Context, docker *client.Client, filter formatter.EventFilter) error {
msgCh, errCh := docker.Events(ctx, types.EventsOptions{})
for {
select {
case msg := <-msgCh:
log.Printf("Event %+v", msg)
m := formatter.Event(msg, filter)
if m != nil {
if err := slack.Send(o.Webhook, m); err != nil {
log.Printf("Error while sending a message to Slack: %s", err)
}
}
case err := <-errCh:
if err == io.EOF {
break
}
log.Printf("Error while receiving events from Docker server: %s", err)
if err := slack.Send(o.Webhook, formatter.Error(err)); err != nil {
log.Printf("Error while sending a message to Slack: %s", err)
}
case <-ctx.Done():
break
}
}
}
func main() {
var o options
args, err := flags.NewParser(&o, flags.HelpFlag).Parse()
if err != nil {
log.Fatal(err)
}
if len(args) > 0 {
log.Fatalf("Too many arguments")
}
if err := o.Run(context.Background()); err != nil {
log.Fatalf("Error: %s", err)
}
}