-
Notifications
You must be signed in to change notification settings - Fork 9
/
handler.go
186 lines (164 loc) · 5.04 KB
/
handler.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
package main
import (
"errors"
"fmt"
"github.com/orrc/git-webhook-proxy/hooks"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/exec"
"reflect"
"strings"
"sync"
)
type Handler struct {
gitPath string
mirrorRootDir string
remoteUrl string
proxy http.Handler
requests map[string]*sync.Mutex
}
func NewHandler(gitPath, mirrorRootDir, remoteUrl string) (h *Handler, err error) {
backendUrl, err := url.Parse(remoteUrl)
proxy := httputil.NewSingleHostReverseProxy(backendUrl)
// Ensure we send the correct Host header to the backend
defaultDirector := proxy.Director
proxy.Director = func(req *http.Request) {
defaultDirector(req)
req.Host = backendUrl.Host
}
h = &Handler{
gitPath: gitPath,
mirrorRootDir: mirrorRootDir,
remoteUrl: remoteUrl,
proxy: proxy,
requests: make(map[string]*sync.Mutex),
}
return
}
func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// Log request
log.Printf("Incoming webhook from %s %s %s", req.RemoteAddr, req.Method, req.URL)
// Determine which handler to use
// TODO: This won't work well for e.g. "/jenkins/git/notifyCommit"
var hookType hooks.Webhook
switch req.URL.Path {
case "/git/notifyCommit":
hookType = hooks.JenkinsHook{}
case "/github-webhook/":
hookType = hooks.GitHubFormHook{}
default:
log.Println("No hook handler found!")
http.NotFound(w, req)
return
}
// Parse the Git repo URI from the webhook request
repoUri, err := hookType.GetGitRepoUri(req)
if err != nil {
msg := fmt.Sprintf("%s returned error: %s", reflect.TypeOf(hookType), err)
log.Println(msg)
http.Error(w, msg, http.StatusInternalServerError)
return
}
if repoUri == "" {
msg := fmt.Sprintf("%s could not determine the repository URL from this request", reflect.TypeOf(hookType))
log.Println(msg)
http.Error(w, msg, http.StatusInternalServerError)
return
}
// Check whether we're already working on updating this repo
// TODO: Coalesce multiple blocked requests
if _, exists := h.requests[repoUri]; !exists {
h.requests[repoUri] = &sync.Mutex{}
}
lock := h.requests[repoUri]
lock.Lock()
defer lock.Unlock()
// Clone or mirror the repo
// TODO: Test what happens if the HTTP client disappears in the middle of a long clone
err = h.updateOrCloneRepoMirror(repoUri)
if err != nil {
log.Println(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if h.remoteUrl != "" {
// Proxy the original webhook request to the backend
log.Printf("Proxying webhook request to %s/%s\n", h.remoteUrl, req.URL)
h.proxy.ServeHTTP(w, req)
}
}
func (h *Handler) updateOrCloneRepoMirror(repoUri string) error {
// Check whether we have cloned this repo already
repoPath := h.getMirrorPathForRepo(repoUri)
if _, err := os.Stat(repoPath); os.IsNotExist(err) {
// TODO: Also need to somehow detect whether a directory has a full clone, or failed...
err = h.cloneRepo(repoUri)
if err != nil {
err = errors.New(fmt.Sprintf("Failed to clone %s: %s", repoUri, err.Error()))
}
return err
}
// If we already have clone the repo, ensure that it is up-to-date
log.Printf("Updating mirror at %s", repoPath)
cmd := exec.Command(h.gitPath, "remote", "update", "-p")
cmd.Dir = repoPath
err := cmd.Run()
if err == nil {
log.Printf("Successfully updated %s", repoPath)
// Also run "git gc", if required, to clean up afterwards
cmd := exec.Command(h.gitPath, "gc", "--prune=now", "--aggressive", "--auto")
cmd.Dir = repoPath
// But we don't really care about the outcome
cmd.Run()
} else {
err = fmt.Errorf("Failed to update %s: %s", repoPath, err.Error())
}
return err
}
func (h *Handler) cloneRepo(repoUri string) error {
// Ensure the mirror root directory exists
err := os.MkdirAll(h.mirrorRootDir, 0700)
if err != nil {
return err
}
// Delete the directory if cloning fails
defer func() {
if err != nil {
os.Remove(h.getMirrorPathForRepo(repoUri))
}
}()
// TODO: We may need to transform incoming repo URIs to add user credentials so they can be cloned
log.Printf("Cloning %s to %s", repoUri, h.mirrorRootDir)
cmd := exec.Command(h.gitPath, "clone", "--mirror", repoUri, getDirNameForRepo(repoUri))
cmd.Dir = h.mirrorRootDir
err = cmd.Run()
if err == nil {
log.Printf("Successfully cloned %s", repoUri)
}
return err
}
func (h *Handler) getMirrorPathForRepo(repoUri string) string {
return fmt.Sprintf("%s/%s", h.mirrorRootDir, getDirNameForRepo(repoUri))
}
func getDirNameForRepo(repoUri string) string {
repoUri = strings.TrimSpace(repoUri)
repoUri = strings.TrimSuffix(repoUri, "/")
repoUri = strings.TrimSuffix(repoUri, ".git")
repoUri = strings.ToLower(repoUri)
if strings.Contains(repoUri, "://") {
uri, _ := url.Parse(repoUri)
if i := strings.Index(uri.Host, ":"); i != -1 {
uri.Host = uri.Host[:i]
}
return fmt.Sprintf("%s/%s.git", uri.Host, uri.Path[1:])
}
if i := strings.Index(repoUri, "@"); i != -1 {
repoUri = repoUri[i+1:]
}
repoUri = strings.Replace(repoUri, ":", "/", 1)
repoUri = strings.Replace(repoUri, "//", "/", -1)
return repoUri + ".git"
}