/
api.go
380 lines (342 loc) · 10.9 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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
package api
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"github.com/camptocamp/terraboard/auth"
"github.com/camptocamp/terraboard/compare"
"github.com/camptocamp/terraboard/db"
"github.com/camptocamp/terraboard/state"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
// JSONError is a wrapper function for errors
// which prints them to the http.ResponseWriter as a JSON response
func JSONError(w http.ResponseWriter, message string, err error) {
errObj := make(map[string]string)
errObj["error"] = message
errObj["details"] = fmt.Sprintf("%v", err)
j, _ := json.Marshal(errObj)
if _, err := io.WriteString(w, string(j)); err != nil {
log.Error(err.Error())
}
}
// ListTerraformVersionsWithCount lists Terraform versions with their associated
// counts, sorted by the 'orderBy' parameter (version by default)
func ListTerraformVersionsWithCount(w http.ResponseWriter, r *http.Request, d *db.Database) {
query := r.URL.Query()
versions, _ := d.ListTerraformVersionsWithCount(query)
j, err := json.Marshal(versions)
if err != nil {
JSONError(w, "Failed to marshal states", err)
return
}
if _, err := io.WriteString(w, string(j)); err != nil {
log.Error(err.Error())
}
}
// ListStateStats returns State information for a given path as parameter
func ListStateStats(w http.ResponseWriter, r *http.Request, d *db.Database) {
query := r.URL.Query()
states, page, total := d.ListStateStats(query)
// Build response object
response := make(map[string]interface{})
response["states"] = states
response["page"] = page
response["total"] = total
j, err := json.Marshal(response)
if err != nil {
JSONError(w, "Failed to marshal states", err)
return
}
if _, err := io.WriteString(w, string(j)); err != nil {
log.Error(err.Error())
}
}
// GetState provides information on a State
func GetState(w http.ResponseWriter, r *http.Request, d *db.Database) {
params := mux.Vars(r)
versionID := r.URL.Query().Get("versionid")
var err error
if versionID == "" {
versionID, err = d.DefaultVersion(params["lineage"])
if err != nil {
JSONError(w, "Failed to retrieve default version", err)
return
}
}
state := d.GetState(params["lineage"], versionID)
j, err := json.Marshal(state)
if err != nil {
JSONError(w, "Failed to marshal state", err)
return
}
if _, err := io.WriteString(w, string(j)); err != nil {
log.Error(err.Error())
}
}
// GetLineageActivity returns the activity (version history) of a Lineage
func GetLineageActivity(w http.ResponseWriter, r *http.Request, d *db.Database) {
params := mux.Vars(r)
activity := d.GetLineageActivity(params["lineage"])
j, err := json.Marshal(activity)
if err != nil {
JSONError(w, "Failed to marshal state activity", err)
return
}
if _, err := io.WriteString(w, string(j)); err != nil {
log.Error(err.Error())
}
}
// StateCompare compares two versions ('from' and 'to') of a State
func StateCompare(w http.ResponseWriter, r *http.Request, d *db.Database) {
params := mux.Vars(r)
query := r.URL.Query()
fromVersion := query.Get("from")
toVersion := query.Get("to")
from := d.GetState(params["lineage"], fromVersion)
to := d.GetState(params["lineage"], toVersion)
compare, err := compare.Compare(from, to)
if err != nil {
JSONError(w, "Failed to compare state versions", err)
return
}
j, err := json.Marshal(compare)
if err != nil {
JSONError(w, "Failed to marshal state compare", err)
return
}
if _, err := io.WriteString(w, string(j)); err != nil {
log.Error(err.Error())
}
}
// GetLocks returns information on locked States
func GetLocks(w http.ResponseWriter, _ *http.Request, sps []state.Provider) {
allLocks := make(map[string]state.LockInfo)
for _, sp := range sps {
locks, err := sp.GetLocks()
if err != nil {
JSONError(w, "Failed to get locks on a provider", err)
return
}
for k, v := range locks {
allLocks[k] = v
}
}
j, err := json.Marshal(allLocks)
if err != nil {
JSONError(w, "Failed to marshal locks", err)
return
}
if _, err := io.WriteString(w, string(j)); err != nil {
log.Error(err.Error())
}
}
// SearchAttribute performs a search on Resource Attributes
// by various parameters
func SearchAttribute(w http.ResponseWriter, r *http.Request, d *db.Database) {
query := r.URL.Query()
result, page, total := d.SearchAttribute(query)
// Build response object
response := make(map[string]interface{})
response["results"] = result
response["page"] = page
response["total"] = total
j, err := json.Marshal(response)
if err != nil {
JSONError(w, "Failed to marshal json", err)
return
}
if _, err := io.WriteString(w, string(j)); err != nil {
log.Error(err.Error())
}
}
// ListResourceTypes lists all Resource types
func ListResourceTypes(w http.ResponseWriter, _ *http.Request, d *db.Database) {
result, _ := d.ListResourceTypes()
j, err := json.Marshal(result)
if err != nil {
JSONError(w, "Failed to marshal json", err)
return
}
if _, err := io.WriteString(w, string(j)); err != nil {
log.Error(err.Error())
}
}
// ListResourceTypesWithCount lists all Resource types with their associated count
func ListResourceTypesWithCount(w http.ResponseWriter, _ *http.Request, d *db.Database) {
result, _ := d.ListResourceTypesWithCount()
j, err := json.Marshal(result)
if err != nil {
JSONError(w, "Failed to marshal json", err)
return
}
if _, err := io.WriteString(w, string(j)); err != nil {
log.Error(err.Error())
}
}
// ListResourceNames lists all Resource names
func ListResourceNames(w http.ResponseWriter, _ *http.Request, d *db.Database) {
result, _ := d.ListResourceNames()
j, err := json.Marshal(result)
if err != nil {
JSONError(w, "Failed to marshal json", err)
return
}
if _, err := io.WriteString(w, string(j)); err != nil {
log.Error(err.Error())
}
}
// ListAttributeKeys lists all Resource Attribute Keys,
// optionally filtered by resource_type
func ListAttributeKeys(w http.ResponseWriter, r *http.Request, d *db.Database) {
resourceType := r.URL.Query().Get("resource_type")
result, _ := d.ListAttributeKeys(resourceType)
j, err := json.Marshal(result)
if err != nil {
JSONError(w, "Failed to marshal json", err)
return
}
if _, err := io.WriteString(w, string(j)); err != nil {
log.Error(err.Error())
}
}
// ListTfVersions lists all Terraform versions
func ListTfVersions(w http.ResponseWriter, _ *http.Request, d *db.Database) {
result, _ := d.ListTfVersions()
j, err := json.Marshal(result)
if err != nil {
JSONError(w, "Failed to marshal json", err)
return
}
if _, err := io.WriteString(w, string(j)); err != nil {
log.Error(err.Error())
}
}
// GetUser returns information about the logged user
func GetUser(w http.ResponseWriter, r *http.Request) {
name := r.Header.Get("X-Forwarded-User")
email := r.Header.Get("X-Forwarded-Email")
user := auth.UserInfo(name, email)
j, err := json.Marshal(user)
if err != nil {
JSONError(w, "Failed to marshal user information", err)
return
}
if _, err := io.WriteString(w, string(j)); err != nil {
log.Error(err.Error())
}
}
// SubmitPlan inserts a new Terraform plan in the database.
// /api/plans POST endpoint callback
func SubmitPlan(w http.ResponseWriter, r *http.Request, db *db.Database) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Errorf("Failed to read body: %v", err)
JSONError(w, "Failed to read body during plan submit", err)
return
}
if err = db.InsertPlan(body); err != nil {
log.Errorf("Failed to insert plan to db: %v", err)
JSONError(w, "Failed to insert plan to db", err)
return
}
}
// GetPlansSummary provides summary of all Plan by lineage (only metadata added by the wrapper).
// Optional "&limit=X" parameter to limit requested quantity of plans.
// Optional "&page=X" parameter to add an offset to the query and enable pagination.
// Sorted by most recent to oldest.
// /api/plans/summary GET endpoint callback
// Also return pagination informations (current page ans total items count in database)
func GetPlansSummary(w http.ResponseWriter, r *http.Request, db *db.Database) {
lineage := r.URL.Query().Get("lineage")
limit := r.URL.Query().Get("limit")
page := r.URL.Query().Get("page")
plans, currentPage, total := db.GetPlansSummary(lineage, limit, page)
response := make(map[string]interface{})
response["plans"] = plans
response["page"] = currentPage
response["total"] = total
j, err := json.Marshal(response)
if err != nil {
log.Errorf("Failed to marshal plans: %v", err)
JSONError(w, "Failed to marshal plans", err)
return
}
if _, err := io.WriteString(w, string(j)); err != nil {
log.Error(err.Error())
}
}
// GetPlan provides a specific Plan of a lineage using ID.
// /api/plans GET endpoint callback on request with ?plan_id=X parameter
func GetPlan(w http.ResponseWriter, r *http.Request, db *db.Database) {
id := r.URL.Query().Get("planid")
plan := db.GetPlan(id)
j, err := json.Marshal(plan)
if err != nil {
log.Errorf("Failed to marshal plan: %v", err)
JSONError(w, "Failed to marshal plan", err)
return
}
if _, err := io.WriteString(w, string(j)); err != nil {
log.Error(err.Error())
}
}
// GetPlans provides all Plan by lineage.
// Optional "&limit=X" parameter to limit requested quantity of plans.
// Optional "&page=X" parameter to add an offset to the query and enable pagination.
// Sorted by most recent to oldest.
// /api/plans GET endpoint callback
// Also return pagination informations (current page ans total items count in database)
func GetPlans(w http.ResponseWriter, r *http.Request, db *db.Database) {
lineage := r.URL.Query().Get("lineage")
limit := r.URL.Query().Get("limit")
page := r.URL.Query().Get("page")
plans, currentPage, total := db.GetPlans(lineage, limit, page)
response := make(map[string]interface{})
response["plans"] = plans
response["page"] = currentPage
response["total"] = total
j, err := json.Marshal(response)
if err != nil {
log.Errorf("Failed to marshal plans: %v", err)
JSONError(w, "Failed to marshal plans", err)
return
}
if _, err := io.WriteString(w, string(j)); err != nil {
log.Error(err.Error())
}
}
// ManagePlans is used to route the request to the appropriated handler function
// on /api/plans request
func ManagePlans(w http.ResponseWriter, r *http.Request, db *db.Database) {
if r.Method == "GET" {
if r.URL.Query().Get("planid") != "" {
GetPlan(w, r, db)
} else {
GetPlans(w, r, db)
}
} else if r.Method == "POST" {
SubmitPlan(w, r, db)
} else {
http.Error(w, "Invalid request method.", 405)
}
}
// GetLineages recover all Lineage from db.
// Optional "&limit=X" parameter to limit requested quantity of them.
// Sorted by most recent to oldest.
func GetLineages(w http.ResponseWriter, r *http.Request, db *db.Database) {
limit := r.URL.Query().Get("limit")
lineages := db.GetLineages(limit)
j, err := json.Marshal(lineages)
if err != nil {
log.Errorf("Failed to marshal lineages: %v", err)
JSONError(w, "Failed to marshal lineages", err)
return
}
if _, err := io.WriteString(w, string(j)); err != nil {
log.Error(err.Error())
}
}