-
Notifications
You must be signed in to change notification settings - Fork 0
/
hook.go
239 lines (193 loc) · 5.64 KB
/
hook.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"os/signal"
"strings"
"time"
)
// startup up time in millis
var startTime string
// ServerConfig configuration
type ServerConfig struct {
Addr string
}
// DeploymentMessage returned to the user
type DeploymentMessage struct {
Status string `json:"status"`
Message string `json:"message"`
Duration int64 `json:"duration"`
}
// Metric info shows that total number of deployment and last stats for that deployment
type Metric struct {
Hits int `json:"hits"` // Number of hits
Commit string `json:"commit"` // Commit deployed
Ref string `json:"ref"` // Ref deployed
Time string `json:"time"` // Deployment time
Duration int64 `json:"duration"` // Duration of the deployment
}
// metrics
var metrics map[string]Metric
// StatusHandler displays status of the service
func StatusHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Request received : %v", r.URL.Path)
msg := "Webhook Service : " + startTime
w.Write([]byte(msg))
}
// MetricsHandler displays metrics information
func MetricsHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Request received : %v", r.URL.Path)
bytes, err := json.Marshal(metrics)
if err != nil {
log.Fatal(err)
}
log.Printf("Payload > %s", string(bytes))
w.Write(bytes)
}
// HookHandler handles incomming request
func HookHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Request received : %v", r.URL.Path)
if r.Method != "POST" {
http.Error(w, "Only POST method is supported", 400)
return
}
if r.Body == nil {
http.Error(w, "Please send a request body", 400)
return
}
body, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
log.Printf("Error reading body: %v", err)
http.Error(w, err.Error(), 500)
return
}
data, err := url.QueryUnescape(string(body))
if err != nil {
log.Fatal(err)
return
}
log.Printf("body: %s", data)
status := "success"
name := "" // repository name
ref := "" // The full git ref that was pushed. Example: refs/heads/master.
commit := "" // The SHA of the most recent commit on ref after the push.
// determine source
headers := r.Header
agent := headers["User-Agent"][0]
contentType := headers["Content-Type"][0]
for k, v := range headers {
fmt.Printf("Header [%s] = %s\n", k, v)
}
log.Printf("User-Agent : %s", agent)
log.Printf("Content-Type : %s", contentType)
// Data can be POSTed in two methods
// handling content-types [application/json, application/x-www-form-urlencoded]
if strings.Index(agent, "GitHub-Hookshot") > -1 || strings.Index(data, "api.github.com") > -1 {
log.Printf("Github payload received")
var payloadJSON string
if contentType == "application/json" {
payloadJSON = string(body)
} else { //x-www-form-urlencoded
val, err := url.ParseQuery(data)
if err != nil {
log.Fatal(err)
}
payloadJSON = val.Get("payload")
}
var pushEvent PushEventPayloadGithub
if err := json.Unmarshal([]byte(payloadJSON), &pushEvent); err != nil {
log.Printf("Error decoding body %v", err)
if e, ok := err.(*json.SyntaxError); ok {
log.Printf("syntax error at byte offset %d", e.Offset)
}
log.Fatal(err)
}
name = pushEvent.Repository.Name
ref = pushEvent.Ref
commit = pushEvent.After
}
log.Printf("name : %s", name)
log.Printf("ref : %s", ref)
log.Printf("commit : %s", commit)
metric := metrics[name]
metric.Hits++
metric.Commit = commit
metric.Ref = ref
tic := nowAsUnixMilliseconds()
// Execute deployment script
cmd := exec.Command("/etc/deploy-webhook/deploy.sh", name, ref, commit)
log.Printf("Running deployment and waiting for it to finish...")
payload, err := cmd.Output()
if err != nil {
log.Printf("Command finished with error: %v", err)
status = "error"
}
toc := nowAsUnixMilliseconds()
duration := toc - tic
metric.Duration = duration
metric.Time = time.Now().Format("Jan _2 15:04:05")
metric.Commit = commit
metric.Ref = ref
// https://github.com/golang/go/issues/3117
metrics[name] = metric
log.Printf("Command finished with \n------------------------------\n %s \n------------------------------", payload)
bytes, err := json.Marshal(DeploymentMessage{
Status: status,
Message: string(payload),
Duration: duration,
})
if err != nil {
log.Fatal(err)
}
log.Printf("Payload > %s", string(bytes))
w.Write(bytes)
}
func nowAsUnixMilliseconds() int64 {
return time.Now().Round(time.Millisecond).UnixNano() / 1e6
}
// StartHTTPServer starts http server and registers handlers
// Exposed endpoints
// /deploy
func StartHTTPServer(config *ServerConfig) *http.Server {
server := &http.Server{Addr: config.Addr, Handler: nil}
http.HandleFunc("/", StatusHandler)
http.HandleFunc("/deploy", HookHandler)
http.HandleFunc("/metrics", MetricsHandler)
go func() {
if err := server.ListenAndServe(); err != http.ErrServerClosed {
log.Fatal("HTTP Server Error - ", err)
panic(err)
}
}()
return server
}
func main() {
if len(os.Args) != 2 {
fmt.Println("Usage:", os.Args[0], "host:port")
return
}
startTime = time.Now().Format("Jan _2 15:04:05")
metrics = make(map[string]Metric)
port := os.Args[1]
log.Printf("main: Server starting port# %v", port)
conf := ServerConfig{Addr: port} // *":8080"
srv := StartHTTPServer(&conf)
// signal capture
done := make(chan os.Signal, 1)
signal.Notify(done, os.Interrupt)
// Waiting for SIGINT pkill -2 (user presses ctrl-c)
log.Printf("main: Server ready to accept connections")
<-done
if err := srv.Shutdown(context.TODO()); err != nil {
log.Fatal("HTTP Shutdown Error - ", err)
}
log.Printf("main: HTTP server stoped")
}