forked from neuvector/neuvector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rest.go
1765 lines (1597 loc) · 62.2 KB
/
rest.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 rest
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"os/signal"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/hashicorp/go-version"
"github.com/julienschmidt/httprouter"
log "github.com/sirupsen/logrus"
// admissionv1beta1 "k8s.io/api/admission/v1beta1"
"github.com/neuvector/neuvector/controller/access"
"github.com/neuvector/neuvector/controller/api"
"github.com/neuvector/neuvector/controller/cache"
"github.com/neuvector/neuvector/controller/common"
"github.com/neuvector/neuvector/controller/kv"
"github.com/neuvector/neuvector/controller/scan"
"github.com/neuvector/neuvector/share"
"github.com/neuvector/neuvector/share/auth"
"github.com/neuvector/neuvector/share/cluster"
"github.com/neuvector/neuvector/share/global"
"github.com/neuvector/neuvector/share/utils"
)
const retryClusterMax int = 3
const clusterLockWait = time.Duration(time.Second * 20)
var evqueue cluster.ObjectQueueInterface
var auditQueue cluster.ObjectQueueInterface
var messenger cluster.MessengerInterface
var clusHelper kv.ClusterHelper
var cfgHelper kv.ConfigHelper
var cacher cache.CacheInterface
var scanner scan.ScanInterface
var localDev *common.LocalDevice
var remoteAuther auth.RemoteAuthInterface
var k8sPlatform bool
var fedRestServerMutex sync.Mutex
var fedRestServerState uint64
var crdEventProcTicker *time.Ticker
var dockerRegistries utils.Set
var defaultRegistries utils.Set
const (
_fedRestServerStopped_ = iota
_fedRestServerRunning_
)
const _maxTransacKeys = 64
var _restPort uint
var _fedPort uint
var _fedServerChan chan bool
var _licSigKeyEnv int
const defaultSSLCertFile = "/etc/neuvector/certs/ssl-cert.pem"
const defaultSSLKeyFile = "/etc/neuvector/certs/ssl-cert.key"
const restErrMessageDefault string = "Unknown error"
const crdEventProcPeriod = time.Duration(time.Second * 10)
var restErrNeedAgentWorkloadFilter = errors.New("Enforcer or workload filter must be provided")
var restErrNeedAgentFilter = errors.New("Enforcer filter must be provided")
var restErrWorkloadNotFound error = errors.New("Container is not found")
var restErrAgentNotFound error = errors.New("Enforcer is not found")
var restErrAgentDisconnected error = errors.New("Enforcer is disconnected")
var restErrMessage = []string{
api.RESTErrNotFound: "URL not found",
api.RESTErrMethodNotAllowed: "Method not allowed",
api.RESTErrUnauthorized: "Authentication failed",
api.RESTErrOpNotAllowed: "Operation not allowed",
api.RESTErrTooManyLoginUser: "Too many login users",
api.RESTErrInvalidRequest: "Request in wrong format",
api.RESTErrObjectNotFound: "Object not found",
api.RESTErrFailWriteCluster: "Write to cluster failed",
api.RESTErrFailReadCluster: "Read from cluster failed",
api.RESTErrClusterWrongData: "Data read from cluster in wrong format",
api.RESTErrClusterTimeout: "Request to cluster timeout",
api.RESTErrNotEnoughFilter: "More search criteria required",
api.RESTErrDuplicateName: "Duplicate name",
api.RESTErrWeakPassword: "Password is weak",
api.RESTErrInvalidName: "Name in wrong format",
api.RESTErrObjectInuse: "Object in use",
api.RESTErrFailExport: "Failed to export",
api.RESTErrFailImport: "Failed to import",
api.RESTErrFailLockCluster: "Acquire cluster lock failed",
api.RESTErrLicenseFail: "Request not supported by license",
api.RESTErrAgentError: "Enforcer error",
api.RESTErrWorkloadNotRunning: "Container not running",
api.RESTErrCISBenchError: "CIS benchmark error",
api.RESTErrClusterRPCError: "Cluster RPC error",
api.RESTErrObjectAccessDenied: "Object access denied",
api.RESTErrFailRepoScan: "Fail to scan repository",
api.RESTErrFailRegistryScan: "Fail to scan registry",
api.RESTErrFailKubernetesApi: "Kubernetes API error",
api.RESTErrAdmCtrlUnSupported: "Admission control is not supported on non-Kubernetes environment",
api.RESTErrClusterRoleForAdmCtrl: "Kubernetes clusterrole/clusterrolebinding required for NeuVector is not configured correctly",
api.RESTErrWebhookSvcForAdmCtrl: "The neuvector-svc-admission-webhook service required for NeuVector Admission Control is not configured correctly",
api.RESTErrNoUpdatePermission: "NeuVector controller doesn't have UPDATE permission for service resource",
api.RESTErrK8sApiSrvToWebhook: "Failed to receive a request from Kube-apiserver. Please try different client mode",
api.RESTErrNvPermission: "NeuVector controller is forbidden to get service details. Please check the clusterrole/clusterrolebinding required for NeuVector default service account",
api.RESTErrWebhookIsDisabled: "Configuring NeuVector Admission Control global settings is not allowed when admission control is disabled",
api.RESTErrRemoteUnauthorized: "Authentication to the remote cluster failed",
api.RESTErrRemoterRequestFail: "Request to the remote cluster failed",
api.RESTErrFedOperationFailed: "Federation operation failed",
api.RESTErrFedJointUnreachable: "Managed cluster is unreachable from primary cluster",
api.RESTErrFedDuplicateName: "Another cluster with the same name already exists in the federation",
api.RESTErrMasterUpgradeRequired: "Version of primary cluster is too old",
api.RESTErrJointUpgradeRequired: "Version of managed cluster is too old",
api.RESTErrIBMSATestFailed: "Failed to call IBM Security Advisor Findings endpoint",
api.RESTErrIBMSABadDashboardURL: "Invalid dashboard URL",
api.RESTErrReadOnlyRules: "Read-only rule(s) cannot be updated by current login user",
api.RESTErrUserLoginBlocked: "Temporarily blocked because of too many login failures",
api.RESTErrPasswordExpired: "Password expired",
api.RESTErrPromoteFail: "Failed to promote rules",
}
func restRespForward(w http.ResponseWriter, r *http.Request, statusCode int, headers map[string]string, data []byte, remoteExport, remoteRegScanTest bool) {
hNames := []string{"Content-Encoding", "Cache-Control", "Content-Type"}
if remoteExport {
hNames = append(hNames, "Content-Disposition")
}
if remoteRegScanTest {
hNames = append(hNames, "X-Transaction-ID")
}
for _, hName := range hNames {
if v, _ := headers[hName]; v != "" {
w.Header().Set(hName, v)
}
}
w.WriteHeader(statusCode)
if data != nil {
w.Write(data)
}
}
func restRespPartial(w http.ResponseWriter, r *http.Request, resp interface{}) {
var data []byte
if resp != nil {
var e common.EmptyMarshaller
data, _ = e.Marshal(resp)
if hdrs, ok := r.Header["Accept-Encoding"]; ok {
loop:
for _, hdr := range hdrs {
// Accept-Encoding: gzip, deflate
for _, enc := range strings.Split(hdr, ",") {
if enc == "gzip" {
w.Header().Set("Content-Encoding", "gzip")
data = utils.GzipBytes(data)
break loop
}
}
}
}
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-cache")
w.WriteHeader(http.StatusPartialContent)
if data != nil {
w.Write(data)
}
}
func restRespSuccess(w http.ResponseWriter, r *http.Request, resp interface{},
acc *access.AccessControl, login *loginSession, req interface{}, msg string) {
var data []byte
if resp != nil {
if restIsSupportReq(r) {
var m common.MaskMarshaller
data, _ = m.Marshal(resp)
} else {
var e common.EmptyMarshaller
data, _ = e.Marshal(resp)
}
if hdrs, ok := r.Header["Accept-Encoding"]; ok {
loop:
for _, hdr := range hdrs {
// Accept-Encoding: gzip, deflate
for _, enc := range strings.Split(hdr, ",") {
if enc == "gzip" {
w.Header().Set("Content-Encoding", "gzip")
data = utils.GzipBytes(data)
break loop
}
}
}
}
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-cache")
w.WriteHeader(http.StatusOK)
if data != nil {
w.Write(data)
}
if msg != "" {
switch r.Method {
case http.MethodGet:
// no log
case http.MethodPost, http.MethodPatch, http.MethodDelete:
var masked []byte
if req != nil {
var m common.MaskMarshaller
masked, _ = m.Marshal(req)
}
restEventLog(r, masked, login, restLogFields{restLogFieldMsg: msg})
}
}
}
func restRespErrorMessage(w http.ResponseWriter, status int, code int, msg string) {
if w == nil {
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
var e string
if code >= len(restErrMessage) || restErrMessage[code] == "" {
e = restErrMessageDefault
} else {
e = restErrMessage[code]
}
if msg == "" {
msg = e
}
resp := api.RESTError{Code: code, Error: e, Message: msg}
value, _ := json.Marshal(resp)
w.Write(value)
}
func restRespErrorMessageEx(w http.ResponseWriter, status int, code int, msg string, i interface{}) {
if w == nil {
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
var e string
if code >= len(restErrMessage) || restErrMessage[code] == "" {
e = restErrMessageDefault
} else {
e = restErrMessage[code]
}
if msg == "" {
msg = e
}
resp := api.RESTError{Code: code, Error: e, Message: msg}
switch v := i.(type) {
case api.RESTPwdProfileBasic:
// v has type api.RESTPwdProfileBasic
if v.MinLen > 0 {
resp.PwdProfileBasic = &v
}
case api.RESTImportTaskData:
// v has type api.RESTImportTaskData
resp.ImportTaskData = &v
}
value, _ := json.Marshal(resp)
w.Write(value)
}
func restRespError(w http.ResponseWriter, status int, code int) {
restRespErrorMessage(w, status, code, "")
}
func restRespErrorReadOnlyRules(w http.ResponseWriter, status int, code int, msg string, readOnlyRuleIDs []uint32) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
var e string
if code >= len(restErrMessage) || restErrMessage[code] == "" {
e = restErrMessageDefault
} else {
e = restErrMessage[code]
}
if msg == "" {
msg = e
}
resp := api.RESTErrorReadOnlyRules{
RESTError: api.RESTError{
Code: code,
Error: e,
Message: msg,
},
ReadOnlyRuleIDs: readOnlyRuleIDs,
}
value, _ := json.Marshal(resp)
w.Write(value)
}
func restRespAccessDenied(w http.ResponseWriter, login *loginSession) {
if w == nil {
return
}
restRespError(w, http.StatusForbidden, api.RESTErrObjectAccessDenied)
log.WithFields(log.Fields{"roles": login.domainRoles, "nvPage": login.nvPage}).Error("Object access denied")
if login.nvPage != api.RESTNvPageDashboard {
authLog(share.CLUSEvAuthAccessDenied, login.fullname, login.remote, login.id, login.domainRoles, "")
}
}
func restRespNotFoundLogAccessDenied(w http.ResponseWriter, login *loginSession, err error) {
if w == nil {
return
}
if err == common.ErrObjectAccessDenied {
restRespAccessDenied(w, login)
} else if err == common.ErrObjectNotFound {
restRespErrorMessage(w, http.StatusNotFound, api.RESTErrObjectNotFound, "Object not found")
log.WithFields(log.Fields{"roles": login.domainRoles}).Error(err.Error())
authLog(share.CLUSEvAuthAccessDenied, login.fullname, login.remote, login.id, login.domainRoles, "")
} else if err == restErrNeedAgentWorkloadFilter || err == restErrNeedAgentFilter {
restRespErrorMessage(w, http.StatusBadRequest, api.RESTErrNotEnoughFilter, err.Error())
} else {
restRespErrorMessage(w, http.StatusNotFound, api.RESTErrObjectNotFound, err.Error())
}
}
func handlerNotFound(w http.ResponseWriter, r *http.Request) {
restRespError(w, http.StatusNotFound, api.RESTErrNotFound)
r.Body.Close()
}
func handlerMethodNotAllowed(w http.ResponseWriter, r *http.Request) {
restRespError(w, http.StatusMethodNotAllowed, api.RESTErrMethodNotAllowed)
r.Body.Close()
}
// ---
const MaxFilelds int = 8
type restFieldFilter struct {
tag string
field string
op string
value string
valueInt int64
valueFloat float64
valueBool bool
}
type restFieldSort struct {
tag string
field string
asc bool
}
type restQuery struct {
start int
limit int
backward bool
brief bool
raw bool
verbose bool
withCap bool
filters []restFieldFilter
sorts []restFieldSort
pairs map[string]string
}
func restIsSupportReq(r *http.Request) bool {
query := r.URL.Query()
if values, ok := query[api.SupportFlag]; ok {
if sup, err := strconv.ParseBool(values[0]); err == nil {
return sup
}
}
return false
}
func restParseQuery(r *http.Request) *restQuery {
var rq restQuery
rq.pairs = make(map[string]string)
query := r.URL.Query()
for key, values := range query {
value := values[0]
if key == api.PageStart {
if start, err := strconv.Atoi(value); err == nil {
if start >= 0 {
rq.start = start
} else {
rq.start = -start
rq.backward = true
}
}
} else if key == api.PageLimit {
if limit, err := strconv.Atoi(value); err == nil {
if limit >= 0 {
rq.limit = limit
}
}
} else if key == api.RawFlag {
if raw, err := strconv.ParseBool(value); err == nil {
rq.raw = raw
}
} else if key == api.WithCapFlag {
if withCap, err := strconv.ParseBool(value); err == nil {
rq.withCap = withCap
}
} else if key == api.BriefFlag {
if brief, err := strconv.ParseBool(value); err == nil {
rq.brief = brief
}
} else if key == api.VerboseFlag {
if verbose, err := strconv.ParseBool(value); err == nil {
rq.verbose = verbose
}
} else if strings.HasPrefix(key, api.FilterPrefix) && len(key) > 2 {
if len(rq.filters) >= MaxFilelds {
continue
}
tag := key[2:]
v := strings.Split(value, ",")
if len(v) == 1 && len(v[0]) > 0 {
rq.filters = append(rq.filters,
restFieldFilter{
tag: tag,
op: api.OPeq,
value: v[0],
})
} else if len(v) > 1 && len(v[1]) > 0 {
var op string
switch v[0] {
case api.OPeq, api.OPneq, api.OPin,
api.OPgt, api.OPgte, api.OPlt, api.OPlte, api.OPprefix:
op = v[0]
default:
op = api.OPeq
}
rq.filters = append(rq.filters,
restFieldFilter{
tag: tag,
op: op,
value: v[1],
})
}
} else if strings.HasPrefix(key, api.SortPrefix) {
if len(rq.sorts) >= MaxFilelds {
continue
}
tag := key[2:]
switch value {
case api.SortDesc:
rq.sorts = append(rq.sorts, restFieldSort{tag: tag, asc: false})
case api.SortAsc:
rq.sorts = append(rq.sorts, restFieldSort{tag: tag, asc: true})
}
} else {
rq.pairs[key] = value
}
}
log.WithFields(log.Fields{"req": rq}).Debug("")
return &rq
}
// -- Filter
type restFilter struct {
filters []*restFieldFilter
tags map[string]string
}
func filterString(value string, filter *restFieldFilter) bool {
switch filter.op {
case api.OPeq:
return value == filter.value
case api.OPneq:
return value != filter.value
case api.OPin:
ss := strings.Split(filter.value, "|")
for _, s := range ss {
if strings.Contains(value, s) {
return true
}
}
return false
case api.OPgt:
return value > filter.value
case api.OPgte:
return value >= filter.value
case api.OPlt:
return value < filter.value
case api.OPlte:
return value <= filter.value
case api.OPprefix:
return strings.HasPrefix(value, filter.value)
}
return false
}
func filterInt(value int64, filter *restFieldFilter) bool {
switch filter.op {
case api.OPeq:
return value == filter.valueInt
case api.OPneq:
return value != filter.valueInt
case api.OPgt:
return value > filter.valueInt
case api.OPgte:
return value >= filter.valueInt
case api.OPlt:
return value < filter.valueInt
case api.OPlte:
return value <= filter.valueInt
}
return false
}
func filterFloat(value float64, filter *restFieldFilter) bool {
switch filter.op {
case api.OPeq:
return value == filter.valueFloat
case api.OPneq:
return value != filter.valueFloat
case api.OPgt:
return value > filter.valueFloat
case api.OPgte:
return value >= filter.valueFloat
case api.OPlt:
return value < filter.valueFloat
case api.OPlte:
return value <= filter.valueFloat
}
return false
}
func filterBool(value bool, filter *restFieldFilter) bool {
switch filter.op {
case api.OPeq:
return value == filter.valueBool
case api.OPneq:
return value != filter.valueBool
case api.OPgt:
return value && !filter.valueBool
case api.OPgte:
return value || !filter.valueBool
case api.OPlt:
return !value && filter.valueBool
case api.OPlte:
return !value || filter.valueBool
}
return false
}
func filter(d interface{}, filter *restFieldFilter) bool {
v := reflect.ValueOf(d).Elem()
f := v.FieldByName(filter.field)
switch f.Kind() {
case reflect.String:
return filterString(f.String(), filter)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return filterInt(f.Int(), filter)
case reflect.Float32, reflect.Float64:
return filterFloat(f.Float(), filter)
case reflect.Bool:
return filterBool(f.Bool(), filter)
}
return false
}
func restNewFilter(data interface{}, filters []restFieldFilter) *restFilter {
rf := restFilter{
filters: make([]*restFieldFilter, 0),
tags: make(map[string]string),
}
// Build tag to field name map.
// Embedded fields first so non-embedded fields can overwrite fields with the same names.
t := reflect.TypeOf(data).Elem()
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if f.Anonymous {
ft := f.Type
if ft.Kind() == reflect.Struct {
for i := 0; i < ft.NumField(); i++ {
f = ft.Field(i)
if tag := f.Tag.Get("json"); tag != "" {
if comma := strings.Index(tag, ","); comma > 0 { // comma cannot be the first char
tag = tag[:comma]
}
rf.tags[tag] = f.Name
}
}
/* Embedded pointer to struct is not supported, see TestFilterEmbedded()
} else if ft.Kind() == reflect.Ptr {
ft = ft.Elem()
if ft.Kind() == reflect.Struct {
for i := 0; i < ft.NumField(); i++ {
f = ft.Field(i)
tag := f.Tag.Get("json")
if tag != "" {
rf.tags[tag] = f.Name
}
}
}
*/
}
}
}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if !f.Anonymous {
if tag := f.Tag.Get("json"); tag != "" {
if comma := strings.Index(tag, ","); comma > 0 { // comma cannot be the first char
tag = tag[:comma]
}
rf.tags[tag] = f.Name
}
}
}
for i, _ := range filters {
rf.FilteredBy(data, &filters[i])
}
return &rf
}
func (rf *restFilter) FilteredBy(data interface{}, ff *restFieldFilter) *restFilter {
v := reflect.ValueOf(data).Elem()
// Get field name from tag
if ff.field, _ = rf.tags[ff.tag]; ff.field == "" {
log.WithFields(log.Fields{"tag": ff.tag}).Debug("Field with tag not exist")
return rf
}
// Check if field exists
f := v.FieldByName(ff.field)
if !f.IsValid() {
log.WithFields(log.Fields{"field": ff.field}).Debug("Field not exist")
return rf
}
// Check if type is supported
switch f.Kind() {
case reflect.String:
rf.filters = append(rf.filters, ff)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if valueInt, err := strconv.ParseInt(ff.value, 10, 64); err == nil {
ff.valueInt = valueInt
rf.filters = append(rf.filters, ff)
}
case reflect.Float32, reflect.Float64:
if valueFloat, err := strconv.ParseFloat(ff.value, 64); err == nil {
ff.valueFloat = valueFloat
rf.filters = append(rf.filters, ff)
}
case reflect.Bool:
if valueBool, err := strconv.ParseBool(ff.value); err == nil {
ff.valueBool = valueBool
rf.filters = append(rf.filters, ff)
}
default:
log.WithFields(log.Fields{
"field": ff.field, "kind": f.Kind(),
}).Error("Field type not supported")
}
return rf
}
func (rf *restFilter) Filter(data interface{}) bool {
for _, ff := range rf.filters {
if !filter(data, ff) {
return false
}
}
return true
}
// -- Sort
type restSorter struct {
data []interface{}
sort []*restFieldSort
tags map[string]string
}
func compareInt(i, j int64) int {
if i < j {
return -1
} else if i > j {
return 1
} else {
return 0
}
}
func compareFloat(i, j float64) int {
if i < j {
return -1
} else if i > j {
return 1
} else {
return 0
}
}
func compareBool(i, j bool) int {
if !i && j {
return -1
} else if i && !j {
return 1
} else {
return 0
}
}
func compare(di, dj interface{}, field string) int {
vi := reflect.ValueOf(di).Elem()
fi := vi.FieldByName(field)
vj := reflect.ValueOf(dj).Elem()
fj := vj.FieldByName(field)
switch fi.Kind() {
case reflect.String:
return strings.Compare(fi.String(), fj.String())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return compareInt(fi.Int(), fj.Int())
case reflect.Float32, reflect.Float64:
return compareFloat(fi.Float(), fj.Float())
case reflect.Bool:
return compareBool(fi.Bool(), fj.Bool())
}
return 0
}
func restNewSorter(data []interface{}, sorts []restFieldSort) *restSorter {
if len(data) == 0 {
return nil
}
rs := restSorter{
data: data,
sort: make([]*restFieldSort, 0),
tags: make(map[string]string),
}
// Build tag to field name map
// Embedded fields first so non-embedded fields can overwrite fields with the same names.
d := rs.data[0]
t := reflect.TypeOf(d).Elem()
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if f.Anonymous {
ft := f.Type
if ft.Kind() == reflect.Struct {
for i := 0; i < ft.NumField(); i++ {
f = ft.Field(i)
if tag := f.Tag.Get("json"); tag != "" {
if comma := strings.Index(tag, ","); comma > 0 { // comma cannot be the first char
tag = tag[:comma]
}
rs.tags[tag] = f.Name
}
}
}
}
}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if !f.Anonymous {
if tag := f.Tag.Get("json"); tag != "" {
if comma := strings.Index(tag, ","); comma > 0 { // comma cannot be the first char
tag = tag[:comma]
}
rs.tags[tag] = f.Name
}
}
}
for i, _ := range sorts {
rs.SortedBy(&sorts[i])
}
return &rs
}
func (rs *restSorter) SortedBy(s *restFieldSort) *restSorter {
d := rs.data[0]
v := reflect.ValueOf(d).Elem()
// Get field name from tag
if s.field, _ = rs.tags[s.tag]; s.field == "" {
log.WithFields(log.Fields{"tag": s.tag}).Error("Field with tag not exist")
return rs
}
// Check if field exists
f := v.FieldByName(s.field)
if !f.IsValid() {
log.WithFields(log.Fields{"field": s.field}).Error("Field not exist")
return rs
}
// Check if type is supported
switch f.Kind() {
case reflect.String:
rs.sort = append(rs.sort, s)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
rs.sort = append(rs.sort, s)
case reflect.Float32, reflect.Float64:
rs.sort = append(rs.sort, s)
case reflect.Bool:
rs.sort = append(rs.sort, s)
default:
log.WithFields(log.Fields{
"field": s.field, "kind": f.Kind(),
}).Error("Field type not supported")
}
return rs
}
func (rs *restSorter) Sort() {
if len(rs.data) <= 1 || len(rs.sort) == 0 {
return
}
sort.Sort(rs)
}
// Len is part of sort.Interface.
func (rs *restSorter) Len() int {
return len(rs.data)
}
// Swap is part of sort.Interface.
func (rs *restSorter) Swap(i, j int) {
rs.data[i], rs.data[j] = rs.data[j], rs.data[i]
}
func (rs *restSorter) Less(i, j int) bool {
di, dj := rs.data[i], rs.data[j]
var k, r int
var s *restFieldSort
// Try all but the last comparison.
for k = 0; k < len(rs.sort)-1; k++ {
s = rs.sort[k]
r = compare(di, dj, s.field)
if r > 0 {
return !s.asc
} else if r < 0 {
return s.asc
}
}
// All previous comparison are equal, return the last one.
s = rs.sort[k]
r = compare(di, dj, s.field)
if r > 0 {
return !s.asc
} else {
return s.asc
}
}
// --
const restEventLogBodyMax int = 1024
const (
restLogFieldMsg = "msg"
)
type restLogFields map[string]string
func restEventLog(r *http.Request, body []byte, login *loginSession, fields restLogFields) {
clog := share.CLUSEventLog{
Event: share.CLUSEvRESTRead,
HostID: localDev.Host.ID,
HostName: localDev.Host.Name,
ControllerID: localDev.Ctrler.ID,
ControllerName: localDev.Ctrler.Name,
ReportedAt: time.Now().UTC(),
}
if r.Method != http.MethodGet {
clog.Event = share.CLUSEvRESTWrite
}
if login != nil {
if login.mainSessionID == _interactiveSessionID {
clog.User = login.fullname
clog.UserRoles = login.domainRoles
} else {
userRole := api.UserRoleFedAdmin
if r, ok := login.domainRoles[access.AccessDomainGlobal]; ok && r == api.UserRoleReader {
userRole = api.UserRoleFedReader
}
clog.User = fmt.Sprintf("%s (primary cluster)", login.mainSessionUser)
clog.UserRoles = map[string]string{access.AccessDomainGlobal: userRole}
}
clog.UserAddr = login.remote
clog.UserSession = login.id
}
clog.RESTMethod = r.Method
clog.RESTRequest = r.URL.String()
if body != nil {
size := len(body)
if size > restEventLogBodyMax {
size = restEventLogBodyMax
}
clog.RESTBody = string(body[:size])
}
if fields != nil {
for key, value := range fields {
switch key {
case restLogFieldMsg:
clog.Msg = value
}
}
}
evqueue.Append(&clog)
}
// --
func getNewestVersion(vers utils.Set) string {
var newest string
for ver := range vers.Iter() {
if v, err := version.NewVersion(ver.(string)); err == nil {
if newest == "" || v.Compare(version.Must(version.NewVersion(newest))) > 0 {
newest = ver.(string)
}
}
}
return newest
}
func isIDStringValid(name string) bool {
valid, _ := regexp.MatchString("^[.a-zA-Z0-9_-]*$", name)
return valid
}
func isObjectNameValid(name string) bool {
// Object name must starts with letters or digits
valid, _ := regexp.MatchString("^[a-zA-Z0-9]+[.:a-zA-Z0-9_-]*$", name)
return valid
}
func isObjectNameWithSpaceValid(name string) bool {
// Object name must starts with letters or digits
valid, _ := regexp.MatchString("(^[a-zA-Z0-9]$)|(^[a-zA-Z0-9]+[ .:a-zA-Z0-9_-]*[.:a-zA-Z0-9_-]+$)", name)
return valid
}
func isNamePathValid(name string) bool {
// Accept name or path, such as "https://mydomain.com/groups" or "/groups"
valid, _ := regexp.MatchString("^[/a-zA-Z0-9]+[/.:a-zA-Z0-9_-]*$", name)
return valid
}
func isDomainNameValid(name string) bool {
// k8s namesapce naming rule: a DNS-1123 label must consist of lower case alphanumeric characters or '-', and must start and end with an alphanumeric character (e.g. 'my-name', or '123-abc')
// plus, we support * at the end of namespace configuration for regex matching
valid, _ := regexp.MatchString(`^[a-z0-9]+[-a-z0-9\*]*[\*a-z0-9]$`, name)
return valid