-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
186 lines (151 loc) · 4.06 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
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/client"
"golang.org/x/net/context"
)
var authKey string
func main() {
authKey = getAuthKey()
http.HandleFunc("/services", handleListServices)
http.HandleFunc("/services/update", handleUpdateService)
port := os.Getenv("PORT")
if port == "" {
port = "80"
}
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}
func handleListServices(w http.ResponseWriter, r *http.Request) {
if checkAuth(r) == false {
http.Error(w, "Not Authorized", http.StatusUnauthorized)
return
}
cli, err := client.NewEnvClient()
if err != nil {
panic(err)
}
services, err := cli.ServiceList(context.Background(), types.ServiceListOptions{})
if err != nil {
fmt.Fprintf(w, err.Error())
log.Print(err.Error())
return
}
for _, service := range services {
fmt.Fprintf(w, "id: %q, name: %q, image: %q, version: %d\n",
service.ID, service.Spec.Name, service.Spec.TaskTemplate.ContainerSpec.Image,
service.Version.Index)
}
}
func handleUpdateService(w http.ResponseWriter, r *http.Request) {
if checkAuth(r) == false {
http.Error(w, "Not Authorized", http.StatusUnauthorized)
return
}
// get params
name := r.FormValue("name")
image := r.FormValue("image")
commit := r.FormValue("commit")
if r.Method != "POST" || name == "" || image == "" {
http.Error(w, "POST attributes 'name' and 'image' are requried", http.StatusUnprocessableEntity)
return
}
if checkWhitelist(name) == false {
http.Error(w, "Service Not Whitelisted", http.StatusForbidden)
return
}
// create docker client
cli, err := client.NewEnvClient()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
services := fetchServiceInfo(cli, name)
if len(services) != 1 {
http.Error(w, fmt.Sprintf("Service %q not found.", name), http.StatusNotFound)
return
}
// update service spec
services[0].Spec.TaskTemplate.ContainerSpec.Image = image
services[0].Spec.TaskTemplate.ContainerSpec.Labels["last_deploy"] = time.Now().Format(time.RFC3339)
services[0].Spec.TaskTemplate.ContainerSpec.Labels["commit_hash"] = commit
services[0].Spec.Labels["commit_hash"] = commit
services[0].Spec.Labels["last_deploy"] = time.Now().Format(time.RFC3339)
response, err := cli.ServiceUpdate(context.Background(),
services[0].ID,
services[0].Version,
services[0].Spec,
types.ServiceUpdateOptions{
QueryRegistry: true,
})
if err != nil {
panic(err)
}
for _, warn := range response.Warnings {
fmt.Fprintf(w, "Warning: %s\n", warn)
}
fmt.Fprintf(w, "Updating service %s image to %s", name, image)
}
func fetchServiceInfo(cli *client.Client, name string) []swarm.Service {
filters := filters.NewArgs()
filters.Add("name", name)
services, err := cli.ServiceList(context.Background(), types.ServiceListOptions{
Filters: filters,
})
if err != nil {
panic(err)
}
return services
}
// Gets the auth key value from file or env var
func getAuthKey() string {
fileEnv := os.Getenv("AUTH_KEY_FILE")
if fileEnv != "" {
data, err := ioutil.ReadFile(fileEnv)
if err != nil {
panic(err)
}
log.Println("AUTH: ", string(data))
return strings.TrimRight(string(data), "\r\n")
}
keyEnv := os.Getenv("AUTH_KEY")
if keyEnv == "" {
log.Println("Warning: AUTH_KEY is not set. Public access is allowed.")
}
return keyEnv
}
func checkAuth(r *http.Request) bool {
if authKey == "" {
return true
}
reqToken := r.Header.Get("Authorization")
if reqToken == "" {
return false
}
splitToken := strings.Split(reqToken, "Bearer ")
if len(splitToken) != 2 {
return false
}
return authKey == splitToken[1]
}
func checkWhitelist(name string) bool {
whitelist := os.Getenv("WHITELIST")
if whitelist == "" {
log.Println("Warning: Whitelist is disabled. Any service can be updated.")
return true
}
for _, service := range strings.Split(whitelist, ",") {
if service == name {
return true
}
}
return false
}