forked from nathanleclaire/tarzan
/
main.go
242 lines (220 loc) · 6.44 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
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
240
241
242
package main
import (
"bufio"
"encoding/json"
"fmt"
"net/http"
"os"
"os/exec"
"strings"
"github.com/codegangsta/cli"
"github.com/codegangsta/negroni"
"github.com/davecgh/go-spew/spew"
"github.com/gorilla/mux"
logging "github.com/op/go-logging"
"github.com/unrolled/render"
)
type GithubPushEventPayload struct {
Hook struct {
Config struct {
Secret string `json:"secret"`
} `json:"config"`
} `json:"hook"`
Repository struct {
FullName string `json:"full_name"`
HtmlUrl string `json:"html_url"`
} `json:"repository"`
}
type Layer struct {
Id string
Command string
Size int64
}
type AutomatedBuild struct {
FromImage string
RepoName string
DockerfileUrl string
Status string
Branches []string
Layers []Layer
}
var (
log = logging.MustGetLogger("streamLog")
format = "%{color}%{time:15:04:05} => %{color:reset} %{message}"
buildStatuses = map[string]string{}
)
func loadBuildStatus() error {
return nil
}
func streamCommand(name string, args ...string) error {
cmd := exec.Command(name, args...)
cmdReader, err := cmd.StdoutPipe()
if err != nil {
return err
}
scanner := bufio.NewScanner(cmdReader)
go func() {
for scanner.Scan() {
log.Notice(scanner.Text())
}
}()
err = cmd.Start()
if err != nil {
return err
}
err = cmd.Wait()
if err != nil {
return err
}
return nil
}
func BuildHookReceiver(c *cli.Context, r *render.Render, dockerBinary string) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
var (
payload GithubPushEventPayload
)
decoder := json.NewDecoder(req.Body)
err := decoder.Decode(&payload)
if err != nil {
fmt.Fprintln(os.Stderr, "Error decoding Github push payload:", err)
}
spew.Dump(payload)
// TODO: Add job to queue instead of running immediately?
if c.String("secret") == "" || payload.Hook.Config.Secret == c.String("secret") {
githubFullName := payload.Repository.FullName
repoPath := fmt.Sprintf("./repos/%s", githubFullName)
repoUrl := payload.Repository.HtmlUrl
if _, err := os.Stat(repoPath); err != nil {
if os.IsNotExist(err) {
fmt.Println("Executing command", "git clone --recursive", repoUrl, repoPath)
if err := exec.Command("git", "clone", "--recursive", repoUrl, repoPath).Run(); err != nil {
fmt.Fprintln(os.Stderr, "Error cloning git repository:", err)
}
} else {
fmt.Fprintln(os.Stderr, "Error stat-ing directory", repoPath, ":", err)
}
os.Chdir(repoPath)
} else {
os.Chdir(repoPath)
fmt.Println("Pulling existing repository")
if err := exec.Command("git", "pull").Run(); err != nil {
fmt.Fprintln(os.Stderr, "Error pulling git repository:", err)
r.JSON(w, http.StatusInternalServerError, "")
}
}
namespacedImage := ""
splitImage := strings.Split(githubFullName, "/")
imageBase := splitImage[len(splitImage)-1]
if c.String("hub-name") == "" {
if c.String("alt-registry") == "" {
namespacedImage = githubFullName
} else {
namespacedImage = fmt.Sprintf("%s/%s", c.String("alt-registry"), imageBase)
}
} else {
namespacedImage = fmt.Sprintf("%s/%s", c.String("hub-name"), imageBase)
}
fmt.Println("Building docker image")
err := streamCommand(dockerBinary, "build", "-t", namespacedImage, ".")
if err != nil {
fmt.Fprintln(os.Stderr, "Error building docker image for", namespacedImage, ":", err)
r.JSON(w, http.StatusInternalServerError, map[string]interface{}{
"Error": err,
})
}
registryName := ""
if c.String("alt-registry") != "" {
registryName = c.String("alt-registry")
} else {
registryName = "Docker Hub"
}
fmt.Println(fmt.Sprintf("Pushing image back to specified registry (%s)...", registryName))
err = streamCommand(dockerBinary, "push", namespacedImage)
if err != nil {
fmt.Fprintln(os.Stderr, "Error pushing docker image for", namespacedImage, ":", err)
r.JSON(w, http.StatusInternalServerError, map[string]interface{}{
"Error": err,
})
}
} else {
r.JSON(w, http.StatusInternalServerError, map[string]interface{}{
"Error": "Secret from payload was invalid",
})
}
r.JSON(w, http.StatusOK, "")
}
}
func MakeBuildListHandler(r *render.Render) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
var (
buildList = []AutomatedBuild{}
)
r.JSON(w, http.StatusOK, buildList)
}
}
func main() {
logBackend := logging.NewLogBackend(os.Stderr, "", 0)
logging.SetBackend(logBackend)
logging.SetFormatter(logging.MustStringFormatter(format))
logging.SetLevel(logging.NOTICE, "streamLog")
homeDir := os.Getenv("HOME")
app := cli.NewApp()
app.Name = "tarzan"
app.Usage = "naive cached automated build implementation"
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "p,port",
Value: "3000",
Usage: "port to serve tarzan on",
},
cli.StringFlag{
Name: "alt-registry",
Value: "",
Usage: "alternative registry to push images to instead of Docker Hub",
},
cli.StringFlag{
Name: "secret",
Value: "",
Usage: "secret to use when receiving webhook payload",
},
cli.StringFlag{
Name: "hub-name",
Value: "",
Usage: "specify a username on Docker Hub which is different than your Github handle",
},
cli.StringFlag{
Name: "docker-binary-name",
Value: "docker",
Usage: "specify the docker binary name (if it is not docker in $PATH)",
},
}
app.Action = func(c *cli.Context) {
dockerBinary := c.String("docker-binary-name")
if err := loadBuildStatus(); err != nil {
fmt.Fprintln(os.Stderr, "Error loading build status (did your repos/ dir get corrupted?):", err)
os.Exit(1)
}
if _, err := os.Stat(fmt.Sprintf("%s/.dockercfg", homeDir)); err != nil {
if os.IsNotExist(err) {
log.Warning("Detected no Docker Hub login. Please log in now.")
cmd := exec.Command(dockerBinary, "login")
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
fmt.Fprintln(os.Stderr, "Error running docker login")
os.Exit(1)
}
}
}
r := render.New(render.Options{})
router := mux.NewRouter()
router.HandleFunc("/build", BuildHookReceiver(c, r, dockerBinary)).Methods("POST")
router.HandleFunc("/buildList", MakeBuildListHandler(r)).Methods("GET")
n := negroni.Classic()
n.Use(negroni.NewStatic(http.Dir("frontend/")))
n.UseHandler(router)
n.Run(fmt.Sprintf(":%s", c.String("port")))
}
app.Run(os.Args)
}