-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroutes-v0.go
1499 lines (1266 loc) · 38.4 KB
/
routes-v0.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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"encoding/csv"
"encoding/json"
"fmt"
"log"
"net/http"
"reflect"
"sort"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/go-sql-driver/mysql"
"github.com/pdxfixit/hostdb"
)
func getAPIConfig(c *gin.Context) {
sendResponse(c, http.StatusOK, config.API.V0)
}
// POST expects no id/name in query string
// PUT should require an id/name
func saveRecord(c *gin.Context) {
// record
data := hostdb.Record{
ID: c.Param("id"),
}
// get the raw request data
rawData, err := c.GetRawData()
if err != nil {
log.Println(fmt.Sprintf(err.Error()))
c.AbortWithStatusJSON(http.StatusInternalServerError, hostdb.GenericError{
Error: "could not get raw request data",
})
return
}
// marshal the []bytes into our struct
err = json.Unmarshal([]byte(rawData), &data)
if err != nil {
log.Println(fmt.Sprintf(err.Error()))
c.AbortWithStatusJSON(http.StatusInternalServerError, hostdb.GenericError{
Error: "could not unmarshal the data",
})
return
}
// ensure all the necessary data is there
if err = ensureDataIsComplete(&data); err != nil {
log.Println(fmt.Sprintf("%v", err.Error()))
c.AbortWithStatusJSON(http.StatusInternalServerError, hostdb.GenericError{
Error: "data is not complete",
})
return
}
// SAVE
if err := saveMariadbRow(data); err != nil {
if err, ok := err.(*mysql.MySQLError); ok {
log.Println(fmt.Sprintf("%v: %v", err.Number, err.Message))
c.AbortWithStatusJSON(http.StatusInternalServerError, hostdb.GenericError{
Error: "something went wrong with the database when saving the record",
})
return
}
// any other type of error
log.Println(err.Error())
c.AbortWithStatusJSON(http.StatusInternalServerError, hostdb.GenericError{
Error: "something went wrong saving the record",
})
return
}
sendResponse(c, http.StatusCreated, hostdb.PutRecordResponse{
ID: data.ID,
OK: true,
})
return
}
// get full detail of record(s)
func getDetail(c *gin.Context) {
// get the records collected into a response
response := get(c)
if c.IsAborted() {
return
}
// is it an error
if response, ok := response.(hostdb.ErrorResponse); ok {
sendResponse(c, response.Code, hostdb.GenericError{Error: response.Message})
return
}
// is it a response
if response, ok := response.(hostdb.GetRecordsResponse); ok {
sendResponse(c, http.StatusOK, response)
return
}
c.AbortWithStatusJSON(http.StatusInternalServerError, hostdb.GenericError{
Error: "unknown",
})
return
}
// get list of record(s), providing only the requested (or default) fields
func getList(c *gin.Context) {
// timer
start := time.Now()
// get the records collected into a response
response := get(c)
if c.IsAborted() {
return
}
// is it an error
if response, ok := response.(hostdb.ErrorResponse); ok {
c.AbortWithStatusJSON(response.Code, hostdb.GenericError{
Error: response.Message,
})
return
}
if response, ok := response.(error); ok {
c.AbortWithStatusJSON(http.StatusInternalServerError, hostdb.GenericError{
Error: response.Error(),
})
return
}
// is it a response
if response, ok := response.(hostdb.GetRecordsResponse); ok {
// list view is designed to return back a limited set of data, for brevity
// with a full dataset in the response, we'll now remove the unwanted data
// figure out if the user has requested specific fields,
// or if we should fallback to the defaults in the config file
var fieldSlice []string
if fieldsParam := c.Query("_fields"); fieldsParam != "" {
// if the user has specified which fields they want returned
// TODO: try to do some deep matching ...
// if vc_url is requested, try to find that
if strings.Contains(fieldsParam, ",") {
fieldSlice = strings.Split(fieldsParam, ",")
} else {
fieldSlice = []string{fieldsParam}
}
} else {
// loop through the fields in config
fieldSlice = config.API.V0.ListFields
}
// for each record, only keep requested/default fields
collection := map[string]hostdb.Record{}
for id, record := range response.Records {
newRecord := hostdb.Record{}
for _, field := range fieldSlice {
// loop over fields in the record struct
for i := 0; i < reflect.TypeOf(record).NumField(); i++ {
// if the field is to be preserved
if field == strings.ToLower(reflect.TypeOf(record).Field(i).Name) {
// lookup field by name
newRecordField := reflect.ValueOf(&newRecord).Elem().Field(i)
if !newRecordField.IsValid() {
break
}
// field must be exported
if !newRecordField.CanSet() {
log.Println(fmt.Sprintf("unable to set the field %s", field))
break
}
value := reflect.ValueOf(&record).Elem().Field(i)
newRecordField.Set(value)
break
}
}
// todo: if the requested field isn't part of the standard record struct
// attempt to find a match in the queryparams (e.g. ?_fields=stack_name,env,image)
//
// the problem with this, is that GetRecordsResponse has a map of Records
// that struct won't work in this scenario
}
collection[id] = newRecord
}
// stop the query timer
end := time.Now()
latency := end.Sub(start)
sendResponse(c, http.StatusOK, hostdb.GetRecordsResponse{
Count: response.Count,
QueryTime: fmt.Sprintf("%v", latency),
Records: collection,
})
return
}
c.AbortWithStatusJSON(http.StatusInternalServerError, hostdb.GenericError{
Error: "unknown",
})
return
}
func get(c *gin.Context) (response interface{}) {
// timer
start := time.Now()
// check if an ID has been specified
id := c.Param("id")
if id != "" {
record, err := getRecord(id)
if err != nil {
return err
}
// stop the query timer
end := time.Now()
latency := end.Sub(start)
return hostdb.GetRecordsResponse{
Count: 1,
QueryTime: fmt.Sprintf("%v", latency),
Records: map[string]hostdb.Record{id: record},
}
}
// check for any query params
query := c.Request.URL.Query()
// if none, return all records
if len(query) == 0 {
records, foundRows, err := getMariadbRows(hostdb.MariadbWhereClauses{}, hostdb.MariadbLimit{})
if err != nil {
return err
}
// stop the query timer
end := time.Now()
latency := end.Sub(start)
return hostdb.GetRecordsResponse{
Count: foundRows,
QueryTime: fmt.Sprintf("%v", latency),
Records: records,
}
}
// start processing query params
records, foundRows, err := processQueryParams(query)
if err != nil {
return err
}
// stop the query timer
end := time.Now()
latency := end.Sub(start)
// return what we've got
return hostdb.GetRecordsResponse{
Count: foundRows,
QueryTime: fmt.Sprintf("%v", latency),
Records: records,
}
}
// parse the query parameters into a Where object, return a collection of records indexed by their ID
func processQueryParams(query map[string][]string) (records map[string]hostdb.Record, foundRows int, err error) {
where := hostdb.MariadbWhereClauses{
Groups: []hostdb.MariadbWhereGrouping{},
}
limit := hostdb.MariadbLimit{}
// for each of the requested query params
i := 0
for requestedParam, requestedParamValue := range query {
switch requestedParam {
case "_limit":
i, err := strconv.Atoi(requestedParamValue[0])
if err != nil {
return nil, 0, err
}
// if i is negative, foul
if i < 0 {
return nil, 0, hostdb.ErrorResponse{
Code: http.StatusBadRequest,
Message: "_limit parameter must not be negative",
}
}
limit.Limit = i
case "_offset":
i, err := strconv.Atoi(requestedParamValue[0])
if err != nil {
return nil, 0, err
}
// if i is negative, foul
if i < 0 {
return nil, 0, hostdb.ErrorResponse{
Code: http.StatusBadRequest,
Message: "_offset parameter must not be negative",
}
}
limit.Offset = i
case "_search", "!_search":
// sloppy search
for _, val := range requestedParamValue {
if len(val) < 1 {
continue
}
likeOperator := "LIKE"
nullOperator := "IS NOT NULL"
relativity := "OR"
if requestedParam[0:1] == "!" {
// detect a negative assertion
requestedParam = requestedParam[1:]
likeOperator = "NOT LIKE"
nullOperator = "IS NULL"
relativity = "AND"
}
where.Groups = append(where.Groups, hostdb.MariadbWhereGrouping{
Clauses: []hostdb.MariadbWhereClause{
{
Relativity: relativity,
Key: []string{fmt.Sprintf("json_search(data, 'one', '%%%v%%')", val)},
Operator: nullOperator,
Value: []string{},
}, {
Relativity: relativity,
Key: []string{fmt.Sprintf("json_search(context, 'one', '%%%v%%')", val)},
Operator: nullOperator,
Value: []string{},
}, {
Relativity: relativity,
Key: []string{"hostname"},
Operator: likeOperator,
Value: []string{fmt.Sprintf("%%%s%%", val)},
}, {
Relativity: relativity,
Key: []string{"ip"},
Operator: likeOperator,
Value: []string{fmt.Sprintf("%%%s%%", val)},
}, {
Relativity: relativity,
Key: []string{"type"},
Operator: likeOperator,
Value: []string{fmt.Sprintf("%%%s%%", val)},
}, {
Relativity: relativity,
Key: []string{"committer"},
Operator: likeOperator,
Value: []string{fmt.Sprintf("%%%s%%", val)},
},
},
})
}
default:
var keys, values []string
var negativeAssertion bool
var paramMatch = false
var param map[string]hostdb.APIv0QueryParam
if requestedParam[len(requestedParam)-2:] == "[]" {
// attempt to detect an array of checkboxes (foo[] => foo)
requestedParam = requestedParam[0 : len(requestedParam)-2]
} else if requestedParam[0:1] == "!" {
// detect a negative assertion
requestedParam = requestedParam[1:]
negativeAssertion = true
}
// check if this param is supported
for paramName, queryParam := range config.API.V0.QueryParams {
if paramName == requestedParam {
paramMatch = true
param = queryParam
break
}
}
// foul if a requested param isn't supported
// params with leading underscores are special/fancy and exempt
if !paramMatch && requestedParam[0:1] != "_" {
return nil, 0, hostdb.ErrorResponse{
Code: http.StatusBadRequest,
Message: fmt.Sprintf("unsupported query param '%s'", requestedParam),
}
}
// prepare the key/field for the WHERE clause
for _, recordType := range param {
var key string
// key
if recordType.Table != "" {
// look for the key in the table itself
key = recordType.Table
} else if recordType.Context != "" {
// look for the key in the record context
key = fmt.Sprintf("json_value(context, '$%s') ", recordType.Context)
} else if recordType.Data != "" {
// look for the key in the record data
key = fmt.Sprintf("json_value(data, '$%s') ", recordType.Data)
} else {
// this param isn't supported after all; ignore it
continue
}
exist := false
for _, k := range keys {
if k == key {
exist = true
}
}
if !exist {
keys = append(keys, key)
}
}
if len(keys) < 1 {
continue
}
// prepare the value(s) for the WHERE clause
operator := "="
if negativeAssertion {
operator = "!="
}
for _, value := range requestedParamValue {
if strings.Contains(value, ",") {
split := strings.Split(value, ",")
values = append(values, split...)
} else {
if len(value) > 0 {
// regex is supported with /bounding slashes/
if value[len(value)-1:] == "/" && value[0:1] == "/" {
values = append(values, value[1:len(value)-1])
if negativeAssertion {
operator = "NOT RLIKE"
} else {
operator = "RLIKE"
}
} else {
values = append(values, value)
}
}
}
}
if len(values) < 1 {
if negativeAssertion {
operator = "IS NULL"
} else {
operator = "IS NOT NULL"
}
} else if len(values) > 1 {
if negativeAssertion {
operator = "IS NOT IN"
} else {
operator = "IN"
}
}
// put it all together
if len(keys) > 0 && operator != "" {
where.Groups = append(where.Groups, hostdb.MariadbWhereGrouping{
Clauses: []hostdb.MariadbWhereClause{
{
Relativity: "AND",
Key: keys,
Operator: operator,
Value: values,
},
},
})
}
}
i++
}
// get records from the db
records, foundRows, err = getMariadbRows(where, limit)
if err != nil {
return nil, 0, err
}
return records, foundRows, nil
}
// given an id, return a HostDB record
func getRecord(id string) (record hostdb.Record, err error) {
record, err = getMariadbRow(id)
if err != nil {
if err, ok := err.(*mysql.MySQLError); ok {
log.Println(fmt.Sprintf("%v: %v", err.Number, err.Message))
return hostdb.Record{},
hostdb.ErrorResponse{
Code: http.StatusInternalServerError,
Message: "getting the record from the database failed",
}
}
// all other errors
log.Println(err.Error())
return hostdb.Record{},
hostdb.ErrorResponse{
Code: http.StatusInternalServerError,
Message: "somewhere, something went wrong",
}
} else if record.ID == "" {
return hostdb.Record{},
hostdb.ErrorResponse{
Code: http.StatusUnprocessableEntity,
Message: "record not found",
}
}
return record, nil
}
// get a catalog of thing(s)
func getCatalog(c *gin.Context) {
// setup
var frequencyCount bool
var filter string
// timer
start := time.Now()
// check if an item has been specified
item := c.Param("item")
if item == "" {
c.AbortWithStatusJSON(http.StatusBadRequest, hostdb.GenericError{Error: "no item specified"})
return
} else if !validQueryParam(item) { // check if it's a valid item
c.AbortWithStatusJSON(http.StatusUnprocessableEntity, hostdb.GenericError{Error: "that item is not familiar"})
return
}
query := c.Request.URL.Query()
if len(query) >= 1 {
for key, values := range query {
switch key {
case "count":
if values[0] != "0" && strings.ToLower(values[0]) != "false" {
frequencyCount = true
}
case "filter":
if values[0][:1] != "/" || values[0][len(values[0])-1:] != "/" {
c.AbortWithStatusJSON(http.StatusBadRequest, hostdb.GenericError{Error: "invalid regex encapsulation"})
return
}
filter = values[0]
default:
continue // unsupported query parameter
}
}
}
catalog, err := getMariadbCatalog(item, frequencyCount, filter)
if err != nil {
if err, ok := err.(*mysql.MySQLError); ok {
log.Println(fmt.Sprintf("%v: %v", err.Number, err.Message))
c.AbortWithStatusJSON(http.StatusInternalServerError, hostdb.GenericError{Error: "getting the record from the database failed"})
return
}
// all other errors
log.Println(err.Error())
c.AbortWithStatusJSON(http.StatusInternalServerError, hostdb.GenericError{Error: "somewhere, something went wrong"})
return
} else if len(catalog) < 1 {
c.AbortWithStatusJSON(http.StatusNotFound, hostdb.GenericError{Error: "catalog not found"})
return
}
if c.IsAborted() {
return
}
// stop the query timer
end := time.Now()
latency := end.Sub(start)
// get the records collected into a response
if frequencyCount {
sendResponse(c, http.StatusOK, hostdb.GetCatalogQuantityResponse{
Count: len(catalog),
QueryTime: fmt.Sprintf("%v", latency),
Catalog: catalog,
})
} else {
items := make([]string, 0, len(catalog))
for i := range catalog {
items = append(items, i)
}
sendResponse(c, http.StatusOK, hostdb.GetCatalogResponse{
Count: len(catalog),
QueryTime: fmt.Sprintf("%v", latency),
Catalog: items,
})
}
return
}
// check if a queryParam / item is valid. Returns true/false.
func validQueryParam(item string) bool {
// check if this param is supported
for paramName := range config.API.V0.QueryParams {
if paramName == item {
return true
}
}
return false
}
// delete a single record
func deleteRecord(c *gin.Context) {
// verify id
id := c.Param("id")
if id == "" {
c.AbortWithStatusJSON(http.StatusBadRequest, hostdb.GenericError{
Error: "no id provided",
})
return
}
// check for the record
record, err := getMariadbRow(id)
if err != nil {
if err, ok := err.(*mysql.MySQLError); ok {
log.Println(fmt.Sprintf("%v: %v", err.Number, err.Message))
c.AbortWithStatusJSON(http.StatusInternalServerError, hostdb.GenericError{
Error: "could not get record from the database",
})
return
}
// all other errors
log.Println(err.Error())
c.AbortWithStatusJSON(http.StatusInternalServerError, hostdb.GenericError{
Error: "delete failed",
})
return
}
// if we didn't get a record back, return a 422
if record.ID == "" {
c.AbortWithStatus(http.StatusUnprocessableEntity)
return
}
// DELETE
if err := deleteMariadbRow(id); err != nil {
if err, ok := err.(*mysql.MySQLError); ok {
log.Println(fmt.Sprintf("%v: %v", err.Number, err.Message))
c.AbortWithStatusJSON(http.StatusInternalServerError, hostdb.GenericError{
Error: "deleting the record failed",
})
return
}
// all other errors
log.Println(err.Error())
c.AbortWithStatusJSON(http.StatusInternalServerError, hostdb.GenericError{
Error: "delete failed",
})
return
}
sendResponse(c, http.StatusOK, gin.H{
"id": id,
"deleted": true,
})
return
}
// post many records at once
func postBulk(c *gin.Context) {
var bulk hostdb.RecordSet
var replacements []hostdb.Record
// get the raw request data
rawData, err := c.GetRawData()
if err != nil {
log.Println(err.Error())
c.AbortWithStatusJSON(http.StatusInternalServerError, hostdb.PostRecordsResponse{
OK: false,
Error: "failed to get request data",
})
return
}
// marshal the []bytes into our struct
if err = json.Unmarshal([]byte(rawData), &bulk); err != nil {
log.Println(err.Error())
c.AbortWithStatusJSON(http.StatusBadRequest, hostdb.PostRecordsResponse{
OK: false,
Error: "did not conform to expected standards",
})
return
}
//
// validation
//
// ensure we have a type, and that it contains no spaces
if bulk.Type == "" {
c.AbortWithStatusJSON(http.StatusBadRequest, hostdb.PostRecordsResponse{
OK: false,
Error: "no type provided",
})
return
} else if strings.Contains(bulk.Type, " ") {
c.AbortWithStatusJSON(http.StatusBadRequest, hostdb.PostRecordsResponse{
OK: false,
Error: "type cannot contain a space character",
})
return
}
// ensure we have a timestamp
if bulk.Timestamp == "" {
c.AbortWithStatusJSON(http.StatusBadRequest, hostdb.PostRecordsResponse{
OK: false,
Error: "no timestamp provided",
})
return
}
// is the timestamp valid
timestamp, err := time.Parse("2006-01-02 15:04:05", bulk.Timestamp)
if timestamp.IsZero() {
bulk.Timestamp = time.Now().UTC().Format("2006-01-02 15:04:05")
}
// ensure we have context
if bulk.Context == nil {
c.AbortWithStatusJSON(http.StatusBadRequest, hostdb.PostRecordsResponse{
OK: false,
Error: "no context provided",
})
return
}
// ensure we have a committer
if bulk.Committer == "" {
bulk.Committer = fmt.Sprintf("%v: %v", c.Request.RemoteAddr, c.Request.UserAgent())
}
// ensure each of the required context fields are present for this type of record
for recordType := range config.API.V0.ContextFields {
if strings.Contains(bulk.Type, recordType) {
for _, k := range config.API.V0.ContextFields[bulk.Type] {
if _, ok := bulk.Context[k]; !ok {
c.AbortWithStatusJSON(http.StatusBadRequest, hostdb.PostRecordsResponse{
OK: false,
Error: fmt.Sprintf("missing context value for %s", k),
})
return
}
}
break
}
}
// ensure we have a data payload for each record
for _, record := range bulk.Records {
if record.Data == nil {
c.AbortWithStatusJSON(http.StatusBadRequest, hostdb.PostRecordsResponse{
OK: false,
Error: "data payload/element is missing from one or more records",
})
return
}
}
// prepare a collection of existing records, based on type and bulk.Context
var collection map[string]hostdb.Record
where := hostdb.MariadbWhereClauses{
Groups: []hostdb.MariadbWhereGrouping{
{
Clauses: []hostdb.MariadbWhereClause{
{
Relativity: "AND",
Key: []string{"type"},
Operator: "=",
Value: []string{bulk.Type},
},
},
},
},
}
// build the WHERE clauses for this bulk.Type
if strings.Contains(bulk.Type, "aws") {
where.Groups = append(where.Groups, hostdb.MariadbWhereGrouping{
Clauses: []hostdb.MariadbWhereClause{
{
Relativity: "AND",
Key: []string{fmt.Sprintf("json_value(context, '$%s')", config.API.V0.QueryParams["aws-region"]["aws"].Context)},
Operator: "",
Value: []string{bulk.Context["aws-region"].(string)},
}, {
Relativity: "AND",
Key: []string{fmt.Sprintf("json_value(context, '$%s')", config.API.V0.QueryParams["aws-account-id"]["aws"].Context)},
Operator: "",
Value: []string{bulk.Context["aws-account-id"].(string)},
},
},
})
} else if strings.Contains(bulk.Type, "oneview") { // filter by oneview_url
where.Groups = append(where.Groups, hostdb.MariadbWhereGrouping{
Clauses: []hostdb.MariadbWhereClause{
{
Relativity: "AND",
Key: []string{fmt.Sprintf("json_value(context, '$%s')", config.API.V0.QueryParams["oneview_url"]["oneview"].Context)},
Operator: "",
Value: []string{bulk.Context["oneview_url"].(string)},
},
},
})
} else if bulk.Type == "openstack" { // ensure we only get records for this tenant
where.Groups = append(where.Groups, hostdb.MariadbWhereGrouping{
Clauses: []hostdb.MariadbWhereClause{
{
Relativity: "AND",
Key: []string{fmt.Sprintf("json_value(context, '$%s')", config.API.V0.QueryParams["tenant"]["openstack"].Context)},
Operator: "=",
Value: []string{bulk.Context["tenant_name"].(string)},
},
},
})
} else if strings.Contains(bulk.Type, "ucs") { // filter by ucs_url
where.Groups = append(where.Groups, hostdb.MariadbWhereGrouping{
Clauses: []hostdb.MariadbWhereClause{
{
Relativity: "AND",
Key: []string{fmt.Sprintf("json_value(context, '$%s')", config.API.V0.QueryParams["ucs_url"]["ucs"].Context)},
Operator: "",
Value: []string{bulk.Context["ucs_url"].(string)},
},
},
})
} else if bulk.Type == "vrops-vmware" { // filter by vc_url
where.Groups[0].Clauses[0].Operator = "LIKE"
where.Groups[0].Clauses[0].Value = []string{fmt.Sprintf("%s%%", where.Groups[0].Clauses[0].Value[0])}
where.Groups = append(where.Groups, hostdb.MariadbWhereGrouping{
Clauses: []hostdb.MariadbWhereClause{
{
Relativity: "AND",
Key: []string{fmt.Sprintf("json_value(context, '$%s')", config.API.V0.QueryParams["vc_url"]["vrops-vmware"].Context)},
Operator: "=",
Value: []string{bulk.Context["vc_url"].(string)},
},
},
})
}
// attempt to retrieve existing records
if len(where.Groups[0].Clauses) > 0 {
collection, _, err = getMariadbRows(where, hostdb.MariadbLimit{})
if err != nil {
log.Println(err.Error())
c.AbortWithStatusJSON(http.StatusInternalServerError, hostdb.PostRecordsResponse{
OK: false,
Error: "Couldn't get existing records before applying bulk record request.",
})
return
}
}
// loop over the new records in the request
for _, record := range bulk.Records {
// get any missing data from the bulk record set
if record.Type == "" {
record.Type = bulk.Type
}
if record.Timestamp == "" {
record.Timestamp = bulk.Timestamp
}
if record.Committer == "" {
record.Committer = bulk.Committer
}
// smoosh context
for key, val := range bulk.Context {
if record.Context == nil {
record.Context = map[string]interface{}{}
}
if _, ok := record.Context[key]; ok {
if record.Context[key] == "" {
// if the context key is present, but empty
record.Context[key] = val
}
} else {
// if the context key is absent
record.Context[key] = val
}
}
// hash data payload
record.Hash, err = hashPayload(record.Data)
if err != nil {
log.Println(err.Error())
c.AbortWithStatusJSON(http.StatusInternalServerError, hostdb.PostRecordsResponse{
OK: false,
Error: "hashing the data failed",
})
return
}
// ensure data consistency before finding a match
if err = ensureDataIsComplete(&record); err != nil {
log.Println(err.Error())
c.AbortWithStatusJSON(http.StatusInternalServerError, hostdb.PostRecordsResponse{
OK: false,
Error: "attempting to enforce data consistency failed",
})
return
}
existing := hostdb.Record{}
if record.ID == "" {
// if there are no records to check against
// then this must be a new record
if len(collection) < 1 {
record.ID = getUUID("hdb")
}