-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
210 lines (189 loc) · 4.63 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package main
import (
"bytes"
"context"
"fmt"
"log"
"os"
"os/exec"
"strings"
"github.com/google/go-github/github"
shellwords "github.com/mattn/go-shellwords"
"github.com/nlopes/slack"
"github.com/pkg/errors"
"github.com/urfave/cli"
"golang.org/x/oauth2"
)
func main() {
l := log.New(os.Stderr, "", 0)
h, err := newHandler()
if err != nil {
log.Fatal(err)
}
if err := h.run(l); err != nil {
log.Fatal(err)
}
}
type handler struct {
SlackToken string
GithubToken string
GithubOrg string
GithubRepo string
DockerImagePrefix string
K8sNamespace string
K8sDeployment string
}
func newHandler() (*handler, error) {
h := &handler{
SlackToken: os.Getenv("SLACK_TOKEN"),
GithubToken: os.Getenv("GITHUB_TOKEN"),
GithubOrg: os.Getenv("GITHUB_ORG"),
GithubRepo: os.Getenv("GITHUB_REPO"),
DockerImagePrefix: os.Getenv("DOCKER_IMAGE_PREFIX"),
K8sNamespace: os.Getenv("K8S_NAMESPACE"),
K8sDeployment: os.Getenv("K8S_DEPLOYMENT"),
}
// TODO: validate all variables are set
return h, nil
}
func (h *handler) run(l *log.Logger) error {
cl := slack.New(h.SlackToken)
rtm := cl.NewRTM()
go rtm.ManageConnection()
rsp, err := cl.AuthTest()
if err != nil {
return err
}
l.Printf(rsp.UserID)
list, err := cl.GetChannels(true)
if err != nil {
return errors.WithStack(err)
}
chans := []string{}
for _, c := range list {
ok := func() bool {
for _, m := range c.Members {
if m == rsp.UserID {
return true
}
}
return false
}()
if ok {
chans = append(chans, c.ID)
}
}
if len(chans) != 1 {
return errors.Errorf("must only be in one channel")
}
channelID := chans[0]
l.Printf("channel=%s", channelID)
for c := range rtm.IncomingEvents {
l.Printf("%s %T", c.Type, c.Data)
switch cc := c.Data.(type) {
case *slack.HelloEvent:
msg := rtm.NewOutgoingMessage("Hi there", channelID)
rtm.SendMessage(msg)
_ = cc
case *slack.MessageEvent:
if cc.User == rsp.UserID {
continue
}
if !strings.HasPrefix(cc.Text, "!") {
continue
}
printer := printer(func(s string) {
msg := rtm.NewOutgoingMessage(s, cc.Channel)
rtm.SendMessage(msg)
})
buf := &bytes.Buffer{}
app := &cli.App{Name: "GDG Bot"}
app.Commands = []cli.Command{
{Name: "pods", Action: adapt(printer, podsCmd), Flags: []cli.Flag{
cli.StringFlag{Name: "namespace"},
}},
{
Name: "deploy", Action: adapt(printer, h.deployCmd),
},
}
app.ExitErrHandler = func(*cli.Context, error) {}
app.Writer = buf
app.ErrWriter = buf
args, err := shellwords.Parse(strings.TrimPrefix(cc.Text, "!"))
if err != nil {
printer("error: " + err.Error())
continue
}
app.Run(append([]string{"foo"}, args...))
if buf.Len() > 0 {
printer("```" + buf.String() + "```")
}
}
}
return nil
}
type printer func(string)
func adapt(p printer, f func(printer, *cli.Context) error) func(*cli.Context) error {
return func(ctx *cli.Context) error {
return f(p, ctx)
}
}
func (h *handler) deployCmd(p printer, ctx *cli.Context) error {
p("about to deploy")
cl, err := h.githubClientFromENV()
if err != nil {
return errors.WithStack(err)
}
list, _, err := cl.Repositories.ListCommits(context.Background(), h.GithubOrg, h.GithubRepo, nil)
if err != nil {
return errors.WithStack(err)
}
sha := func() string {
for _, c := range list {
if c.SHA != nil {
s := *c.SHA
return s[0:12]
}
}
return ""
}()
if sha == "" {
return errors.Errorf("no sha found")
}
p(fmt.Sprintf("%d commits", len(list)))
image := h.DockerImagePrefix + ":" + sha
p("deploying image " + image)
b, err := exec.Command("kubectl", "-n", h.K8sNamespace, "set", "image", "deployments/"+h.K8sDeployment, "*="+image).CombinedOutput()
if err != nil {
p("ERROR: " + string(b))
return nil
}
p(string(b))
b, err = exec.Command("kubectl", "-n", h.K8sNamespace, "rollout", "status", "deployments/"+h.K8sDeployment).CombinedOutput()
if err != nil {
p("ERROR: " + string(b))
return nil
}
p(string(b))
p("finished deployment")
return nil
}
func (h *handler) githubClientFromENV() (*github.Client, error) {
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: h.GithubToken})
tc := oauth2.NewClient(oauth2.NoContext, ts)
return github.NewClient(tc), nil
}
func podsCmd(p printer, ctx *cli.Context) error {
p("about to list pods")
args := []string{"get", "pods"}
if n := ctx.String("namespace"); n != "" {
args = append(args, "-n", n)
}
b, err := exec.Command("kubectl", args...).CombinedOutput()
if err != nil {
log.Printf("err=%q", string(b))
} else {
p("```" + string(b) + "```")
}
return nil
}