This repository has been archived by the owner on Aug 3, 2022. It is now read-only.
/
api.go
278 lines (235 loc) · 7.13 KB
/
api.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
package apiGatewayDeploy
import (
"database/sql"
"encoding/json"
"github.com/30x/apid"
"io/ioutil"
"net/http"
"strconv"
"time"
"fmt"
)
const (
RESPONSE_STATUS_SUCCESS = "SUCCESS"
RESPONSE_STATUS_FAIL = "FAIL"
ERROR_CODE_TODO = 0 // todo: add error codes where this is used
)
var (
incoming = make(chan string)
addSubscriber = make(chan chan string)
)
type errorResponse struct {
ErrorCode int `json:"errorCode"`
Reason string `json:"reason"`
}
func initAPI(services apid.Services) {
services.API().HandleFunc("/deployments/current", handleCurrentDeployment).Methods("GET")
services.API().HandleFunc("/deployments/{deploymentID}", handleDeploymentResult).Methods("POST")
}
func writeError(w http.ResponseWriter, status int, code int, reason string) {
w.WriteHeader(status)
e := errorResponse{
ErrorCode: code,
Reason: reason,
}
bytes, err := json.Marshal(e)
if err != nil {
log.Errorf("unable to marshal errorResponse: %v", err)
} else {
w.Write(bytes)
}
log.Debugf("sending %d error to client: %s", status, reason)
}
func writeDatabaseError(w http.ResponseWriter) {
writeError(w, http.StatusInternalServerError, ERROR_CODE_TODO, "database error")
}
func distributeEvents() {
subscribers := make(map[chan string]struct{})
for {
select {
case msg := <-incoming:
log.Debugf("Delivering new deployment %s to %d subscribers", msg, len(subscribers))
for subscriber := range subscribers {
select {
case subscriber <- msg:
log.Debugf("Handling deploy response for: %s", msg)
default:
log.Error("listener too far behind, message dropped")
}
}
case subscriber := <-addSubscriber:
log.Debugf("Add subscriber: %s", subscriber)
subscribers[subscriber] = struct{}{}
}
}
}
func handleCurrentDeployment(w http.ResponseWriter, r *http.Request) {
// If returning without a bundle (immediately or after timeout), status = 404
// If returning If-None-Match value is equal to current deployment, status = 304
// If returning a new value, status = 200
// If timeout > 0 AND there is no deployment (or new deployment) available (per If-None-Match), then
// block for up to the specified number of seconds until a new deployment becomes available.
b := r.URL.Query().Get("block")
var timeout int
if b != "" {
var err error
timeout, err = strconv.Atoi(b)
if err != nil {
writeError(w, http.StatusBadRequest, ERROR_CODE_TODO, "bad block value, must be number of seconds")
return
}
}
log.Debugf("api timeout: %d", timeout)
// If If-None-Match header matches the ETag of current bundle list AND if the request does NOT have a 'block'
// query param > 0, the server returns a 304 Not Modified response indicating that the client already has the
// most recent bundle list.
priorDepID := r.Header.Get("If-None-Match")
log.Debugf("if-none-match: %s", priorDepID)
depID, err := getCurrentDeploymentID()
if err != nil && err != sql.ErrNoRows{
writeDatabaseError(w)
return
}
// not found, no timeout, send immediately
if depID == "" && timeout == 0 {
w.WriteHeader(http.StatusNotFound)
return
}
// found, send immediately - if doesn't match prior ID
if depID != "" {
if depID == priorDepID {
if timeout == 0 {
w.WriteHeader(http.StatusNotModified)
return
} else {
// continue
}
} else {
sendDeployment(w, depID)
return
}
}
// can't send immediately, we need to block...
// todo: can we kill the timer & channel if client connection is lost?
// todo: resolve race condition - may miss a notification
log.Debug("Blocking request... Waiting for new Deployments.")
newReq := make(chan string)
// subscribe to new deployments
addSubscriber <- newReq
// block until new deployment or timeout
select {
case depID := <-newReq:
sendDeployment(w, depID)
case <-time.After(time.Duration(timeout) * time.Second):
log.Debug("Blocking deployment request timed out.")
if priorDepID != "" {
w.WriteHeader(http.StatusNotModified)
} else {
w.WriteHeader(http.StatusNotFound)
}
return
}
}
func sendDeployment(w http.ResponseWriter, depID string) {
deployment, err := getDeployment(depID)
if err != nil {
log.Errorf("unable to retrieve deployment [%s]: %s", depID, err)
w.WriteHeader(http.StatusInternalServerError)
}
b, err := json.Marshal(deployment)
if err != nil {
log.Errorf("unable to marshal deployment: %s", err)
w.WriteHeader(http.StatusInternalServerError)
} else {
log.Debugf("sending deployment %s: %s", depID, b)
w.Header().Set("ETag", depID)
w.Write(b)
}
}
// todo: we'll need to transmit results back to Edge somehow...
func handleDeploymentResult(w http.ResponseWriter, r *http.Request) {
depID := apid.API().Vars(r)["deploymentID"]
if depID == "" {
log.Error("No deployment ID")
writeError(w, http.StatusBadRequest, ERROR_CODE_TODO, "Missing deployment ID")
return
}
var rsp deploymentResponse
buf, _ := ioutil.ReadAll(r.Body)
err := json.Unmarshal(buf, &rsp)
if err != nil {
log.Error("Resp Handler Json Unmarshal err: ", err)
writeError(w, http.StatusBadRequest, ERROR_CODE_TODO, "Malformed JSON")
return
}
if rsp.Status != RESPONSE_STATUS_SUCCESS && rsp.Status != RESPONSE_STATUS_FAIL {
writeError(w, http.StatusBadRequest, ERROR_CODE_TODO,
fmt.Sprintf("status must be '%s' or '%s'", RESPONSE_STATUS_SUCCESS, RESPONSE_STATUS_FAIL))
return
}
if rsp.Status == RESPONSE_STATUS_FAIL && (rsp.GWbunRsp.ErrorCode == 0 || rsp.GWbunRsp.Reason == "") {
writeError(w, http.StatusBadRequest, ERROR_CODE_TODO, "errorCode and reason are required")
return
}
/*
* If the state of deployment was success, update state of bundles and
* its deployments as success as well
*/
txn, err := db.Begin()
if err != nil {
log.Errorf("Unable to begin transaction: %s", err)
writeDatabaseError(w)
return
}
var updateErr error
if rsp.Status == RESPONSE_STATUS_SUCCESS {
updateErr = updateDeploymentSuccess(depID, txn)
} else {
updateErr = updateDeploymentFailure(depID, rsp.GWbunRsp, txn)
}
if updateErr != nil {
if updateErr == sql.ErrNoRows {
writeError(w, http.StatusNotFound, ERROR_CODE_TODO, "not found")
} else {
writeDatabaseError(w)
}
err = txn.Rollback()
if err != nil {
log.Errorf("Unable to rollback transaction: %s", err)
}
return
}
err = txn.Commit()
if err != nil {
log.Errorf("Unable to commit transaction: %s", err)
writeDatabaseError(w)
}
return
}
func updateDeploymentSuccess(depID string, txn *sql.Tx) error {
log.Debugf("Marking deployment %s as succeeded", depID)
err := updateDeploymentStatus(txn, depID, DEPLOYMENT_STATE_SUCCESS, 0)
if err != nil {
return err
}
err = updateAllBundleStatus(txn, depID, DEPLOYMENT_STATE_SUCCESS)
if err != nil {
return err
}
return nil
}
func updateDeploymentFailure(depID string, rsp deploymentErrorResponse, txn *sql.Tx) error {
log.Infof("marking deployment %s as FAILED", depID)
err := updateDeploymentStatus(txn, depID, DEPLOYMENT_STATE_ERR_GWY, rsp.ErrorCode)
if err != nil {
return err
}
// Iterate over Bundles, and update the errors
for _, a := range rsp.ErrorDetails {
updateBundleStatus(txn, depID, a.BundleId, DEPLOYMENT_STATE_ERR_GWY, a.ErrorCode, a.Reason)
if err != nil {
return err
}
}
return err
}