This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
86 lines (73 loc) · 2.19 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
package main
import (
"fmt"
"os"
"strings"
"github.com/fsouza/go-dockerclient"
"github.com/go-martini/martini"
)
func main() {
endpoint := os.Getenv("ENDPOINT")
imageName := os.Getenv("IMAGE")
containerName := os.Getenv("CONTAINER_NAME")
username := os.Getenv("USERNAME")
password := os.Getenv("PASSWORD")
if len(username) == 0 || len(password) == 0 {
fmt.Println("missing USERNAME/PASSWORD env!")
os.Exit(1)
}
dockerURI := os.Getenv("DOCKERSOCKET")
client, _ := docker.NewClient(dockerURI)
err := client.Ping()
if err != nil {
fmt.Println("unable to connect to docker:", err)
fmt.Println("(did you use `docker run -v /var/run/docker.sock:/var/run/docker.sock ...`?)")
os.Exit(1)
}
image := docker.PullImageOptions{Repository: imageName, Tag: "latest"}
auth := docker.AuthConfiguration{Username: username, Password: password}
passes := strings.Split(os.Getenv("PASS_ENV"), " ")
envs := make([]string, len(passes))
for i, env := range passes {
envs[i] = env + "=" + os.Getenv(env)
}
config := docker.Config{Image: imageName, Env: envs}
if len(os.Getenv("CMD")) != 0 {
// TODO: Parse this CMD string as bashlike:
config.Cmd = strings.Split(os.Getenv("CMD"), " ")
}
create := docker.CreateContainerOptions{Name: containerName, Config: &config}
hostConfig := docker.HostConfig{PublishAllPorts: true}
links := os.Getenv("LINKS")
if len(links) != 0 {
hostConfig.Links = strings.Split(links, " ")
}
deploy := make(chan int, 100)
go func() {
for {
_ = <-deploy
fmt.Println("Pulling image:", imageName)
client.PullImage(image, auth)
fmt.Println("Removing old container:", containerName)
client.RemoveContainer(docker.RemoveContainerOptions{ID: containerName, Force: true})
fmt.Println("Creating new container:", containerName)
container, err := client.CreateContainer(create)
if err != nil {
fmt.Println("Unable to create new container:", err)
} else {
fmt.Println("Starting container:", container.ID)
client.StartContainer(container.ID, &hostConfig)
}
}
}()
m := martini.Classic()
m.Get(endpoint, func() string {
deploy <- 0
return "OK\n"
})
m.Post(endpoint, func() string {
deploy <- 0
return "OK\n"
})
m.RunOnAddr(":8080")
}