-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
235 lines (213 loc) · 5.78 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
package main
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"time"
)
type container struct {
ID string `json:"container_id"`
}
type createOptions struct {
// Provider tests do not require an UI,
// so we can speed up the container creation.
SkipUI bool `json:"skip_ui"`
FatmouseBranch string `json:"fatmouse_branch,omitempty"`
ScalrBranch string `json:"scalr_branch,omitempty"`
Notes string `json:"notes"`
Python bool `json:"update_python"`
}
const (
teBaseURL = "test-env.scalr.com"
// Such a large timeout due to the fact that sometimes
// the result of creating a container cannot be obtained
// for a long time on the server side.
createTimeout = 800 * time.Second
healthCheckMaxRetries = 30
healthCheckRetryDelay = 3 * time.Second
)
var (
revizorBaseURL = getEnv("REVIZOR_URL")
revizorToken = getEnv("REVIZOR_TOKEN")
scalrToken = getEnv("SCALR_TOKEN")
upstreamID = getEnv("UPSTREAM_ID")
)
func getEnv(key string) string {
value, present := os.LookupEnv(key)
if !present || len(value) == 0 {
log.Fatalf("No required environment variable: %s", key)
return ""
}
return value
}
func newRequest(method, path string, payload *createOptions) *http.Request {
reqBody := bytes.NewBuffer(nil)
reqHeaders := make(http.Header)
reqHeaders.Set("Authorization", fmt.Sprintf("Token %s", revizorToken))
if payload != nil {
reqHeaders.Set("Content-Type", "application/json")
jsonEncoded, err := json.Marshal(payload)
if err != nil {
log.Fatal(err)
}
reqBody.Write(jsonEncoded)
}
req, err := http.NewRequest(method, revizorBaseURL+path, reqBody)
if err != nil {
log.Fatal(err)
}
for k, v := range reqHeaders {
req.Header[k] = v
}
return req
}
type HealthCheckError struct {
StatusCode int
Err error
}
func (r *HealthCheckError) Error() string {
return fmt.Sprintf("Health check errror. Status %d: %v", r.StatusCode, r.Err)
}
func doHealthCheck(containerID *string) error {
url := fmt.Sprintf("https://%s.%s/api/iacp/v3/ping", *containerID, teBaseURL)
req, err := http.NewRequest("GET", url, nil)
statuses := [2]int{200, 204}
var ok bool = false
if err != nil {
log.Fatal(err)
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", scalrToken))
client := &http.Client{}
resp, err := client.Do(req)
if err != nil || resp == nil {
return &HealthCheckError{
Err: fmt.Errorf("ping %s %v", url, err),
}
}
for _, x := range statuses {
if resp.StatusCode == x {
ok = true
break
}
}
if !ok {
return &HealthCheckError{
Err: fmt.Errorf("ping %s not successful", url),
StatusCode: resp.StatusCode,
}
}
log.Printf("The container %s is ready for use", *containerID)
return nil
}
func newCreateOptions() *createOptions {
options := &createOptions{
SkipUI: true,
Notes: fmt.Sprintf("Provider upstream #%s", upstreamID),
}
// Setup revizor container branches
apiBranch := os.Getenv("API_BRANCH")
dbBranch := os.Getenv("DB_BRANCH")
python := os.Getenv("PY_REQ")
if len(apiBranch) != 0 {
options.FatmouseBranch = apiBranch
}
if len(dbBranch) != 0 {
options.ScalrBranch = dbBranch
}
options.Python = python == "yes"
return options
}
func setOutputsfromCreate(cont *container) {
// set-output: GitHub Action mechanism that sets the output parameter.
fmt.Printf("::set-output name=container_id::%s\n", cont.ID)
fmt.Printf("::set-output name=hostname::%s.%s\n", cont.ID, teBaseURL)
}
func doCreate(options *createOptions, retry bool) error {
optionsJSON, _ := json.Marshal(options)
log.Printf("Creating the container with options %s", string(optionsJSON))
req := newRequest("POST", "/api/containers/", options)
client := &http.Client{Timeout: createTimeout}
resp, err := client.Do(req)
if err != nil || resp == nil {
log.Fatalf("Cannot create the container due to %v", err)
}
if resp.StatusCode != 201 {
log.Fatalf("Cannot create the container. Error status code: %d", resp.StatusCode)
}
if resp.Body == nil {
log.Fatal("Invalid response. The response body is empty")
}
defer resp.Body.Close()
respBody, _ := ioutil.ReadAll(resp.Body)
var cont container
err = json.Unmarshal(respBody, &cont)
if err != nil {
log.Fatal(err)
}
log.Printf("The container %s has been created", cont.ID)
setOutputsfromCreate(&cont)
var healthCheckErr *HealthCheckError
for i := 1; i <= healthCheckMaxRetries; i++ {
err := doHealthCheck(&cont.ID)
if err != nil {
healthCheckErr = err.(*HealthCheckError)
log.Println(err)
time.Sleep(healthCheckRetryDelay)
} else {
return nil
}
}
err = doDelete(cont.ID)
if err != nil {
log.Fatal(err)
}
// For unknown reasons, sometimes we can't find the container we created,
// so we try again to create a container.
if retry && healthCheckErr.StatusCode == 404 {
return doCreate(options, false)
} else {
return errors.New("Cannot create container")
}
}
func doDelete(containerID string) error {
log.Printf("Deleting the container %s...", containerID)
req := newRequest("DELETE", fmt.Sprintf("/api/containers/%s/", containerID), nil)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil || resp == nil {
return fmt.Errorf("Failed to delete the container due to %v", err)
}
if resp.StatusCode != 202 {
return fmt.Errorf("Failed to delete the container, status code %d", resp.StatusCode)
}
log.Printf("The container %s was successfully deleted", containerID)
return nil
}
func main() {
flag.Parse()
cmd := flag.Arg(0)
switch cmd {
case "create":
err := doCreate(newCreateOptions(), true)
if err != nil {
log.Fatal(err)
}
case "delete":
containerID := flag.Arg(1)
if len(containerID) == 0 {
log.Fatal("The container ID not specified")
}
err := doDelete(containerID)
if err != nil {
log.Fatal(err)
}
default:
log.Fatalf("No such command: %s", cmd)
}
}