/
client.go
1034 lines (876 loc) · 30.1 KB
/
client.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 apic
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"sync"
defs "github.com/Axway/agent-sdk/pkg/apic/definitions"
"github.com/Axway/agent-sdk/pkg/util"
cache2 "github.com/Axway/agent-sdk/pkg/agent/cache"
coreapi "github.com/Axway/agent-sdk/pkg/api"
apiv1 "github.com/Axway/agent-sdk/pkg/apic/apiserver/models/api/v1"
catalog "github.com/Axway/agent-sdk/pkg/apic/apiserver/models/catalog/v1alpha1"
management "github.com/Axway/agent-sdk/pkg/apic/apiserver/models/management/v1alpha1"
"github.com/Axway/agent-sdk/pkg/apic/auth"
"github.com/Axway/agent-sdk/pkg/cache"
corecfg "github.com/Axway/agent-sdk/pkg/config"
"github.com/Axway/agent-sdk/pkg/util/errors"
hc "github.com/Axway/agent-sdk/pkg/util/healthcheck"
"github.com/Axway/agent-sdk/pkg/util/log"
)
// constants for auth policy types
const (
Apikey = "verify-api-key"
Passthrough = "pass-through"
Oauth = "verify-oauth-token"
Basic = "http-basic"
)
// other consts
const (
TeamMapKey = "TeamMap"
)
// constants for patch request
const (
PatchOpAdd = "add"
PatchOpReplace = "replace"
PatchOpDelete = "delete"
PatchOpBuildObjectTree = "x-build-object-tree"
PatchOperation = "op"
PatchPath = "path"
PatchValue = "value"
ContentTypeJsonPatch = "application/json-patch+json"
ContentTypeJson = "application/json"
)
// constants for patch request
const (
BearerTokenPrefix = "Bearer "
HdrContentType = "Content-Type"
HdrAuthorization = "Authorization"
HdrAxwayTenantID = "X-Axway-Tenant-Id"
)
// ValidPolicies - list of valid auth policies supported by Central. Add to this list as more policies are supported.
var ValidPolicies = []string{Apikey, Passthrough, Oauth, Basic}
// SubscriptionProcessor - callback method type to process subscriptions
type SubscriptionProcessor func(subscription Subscription)
// SubscriptionValidator - callback method type to validate subscription for processing
type SubscriptionValidator func(subscription Subscription) bool
// Client - interface
type Client interface {
SetTokenGetter(tokenRequester auth.PlatformTokenGetter)
SetConfig(cfg corecfg.CentralConfig)
PublishService(serviceBody *ServiceBody) (*management.APIService, error)
RegisterSubscriptionWebhook() error
RegisterSubscriptionSchema(schema SubscriptionSchema, update bool) error
UpdateSubscriptionSchema(schema SubscriptionSchema) error
GetSubscriptionManager() SubscriptionManager
GetCatalogItemIDForConsumerInstance(instanceID string) (string, error)
DeleteAPIServiceInstance(name string) error
DeleteConsumerInstance(name string) error
DeleteServiceByName(name string) error
GetConsumerInstanceByID(id string) (*management.ConsumerInstance, error)
GetConsumerInstancesByExternalAPIID(externalAPIID string) ([]*management.ConsumerInstance, error)
UpdateConsumerInstanceSubscriptionDefinition(externalAPIID, subscriptionDefinitionName string) error
GetUserEmailAddress(ID string) (string, error)
GetUserName(ID string) (string, error)
GetSubscriptionsForCatalogItem(states []string, catalogItemID string) ([]CentralSubscription, error)
GetSubscriptionDefinitionPropertiesForCatalogItem(catalogItemID, propertyKey string) (SubscriptionSchema, error)
UpdateSubscriptionDefinitionPropertiesForCatalogItem(catalogItemID, propertyKey string, schema SubscriptionSchema) error
GetCatalogItemName(ID string) (string, error)
ExecuteAPI(method, url string, queryParam map[string]string, buffer []byte) ([]byte, error)
Healthcheck(name string) *hc.Status
GetAPIRevisions(query map[string]string, stage string) ([]*management.APIServiceRevision, error)
GetAPIServiceRevisions(query map[string]string, URL, stage string) ([]*management.APIServiceRevision, error)
GetAPIServiceInstances(query map[string]string, URL string) ([]*management.APIServiceInstance, error)
GetAPIV1ResourceInstances(query map[string]string, URL string) ([]*apiv1.ResourceInstance, error)
GetAPIV1ResourceInstancesWithPageSize(query map[string]string, URL string, pageSize int) ([]*apiv1.ResourceInstance, error)
GetAPIServiceByName(name string) (*management.APIService, error)
GetAPIServiceInstanceByName(name string) (*management.APIServiceInstance, error)
GetAPIRevisionByName(name string) (*management.APIServiceRevision, error)
CreateCategory(name string) (*catalog.Category, error)
GetOrCreateCategory(category string) string
GetEnvironment() (*management.Environment, error)
GetCentralTeamByName(name string) (*defs.PlatformTeam, error)
GetTeam(query map[string]string) ([]defs.PlatformTeam, error)
GetAccessControlList(aclName string) (*management.AccessControlList, error)
UpdateAccessControlList(acl *management.AccessControlList) (*management.AccessControlList, error)
CreateAccessControlList(acl *management.AccessControlList) (*management.AccessControlList, error)
CreateSubResource(rm apiv1.ResourceMeta, subs map[string]interface{}) error
GetResource(url string) (*apiv1.ResourceInstance, error)
UpdateResourceFinalizer(ri *apiv1.ResourceInstance, finalizer, description string, addAction bool) (*apiv1.ResourceInstance, error)
IsMarketplaceSubsEnabled() bool
UpdateResourceInstance(ri apiv1.Interface) (*apiv1.ResourceInstance, error)
CreateOrUpdateResource(ri apiv1.Interface) (*apiv1.ResourceInstance, error)
CreateResourceInstance(ri apiv1.Interface) (*apiv1.ResourceInstance, error)
PatchSubResource(ri apiv1.Interface, subResourceName string, patches []map[string]interface{}) (*apiv1.ResourceInstance, error)
DeleteResourceInstance(ri apiv1.Interface) error
GetResources(ri apiv1.Interface) ([]apiv1.Interface, error)
CreateResource(url string, bts []byte) (*apiv1.ResourceInstance, error)
UpdateResource(url string, bts []byte) (*apiv1.ResourceInstance, error)
}
// New creates a new Client
func New(cfg corecfg.CentralConfig, tokenRequester auth.PlatformTokenGetter, caches cache2.Manager) Client {
serviceClient := &ServiceClient{
caches: caches,
}
serviceClient.logger = log.NewFieldLogger().
WithComponent("serviceClient").
WithPackage("sdk.apic")
serviceClient.SetTokenGetter(tokenRequester)
serviceClient.subscriptionSchemaCache = cache.New()
serviceClient.initClient(cfg)
return serviceClient
}
func (c *ServiceClient) createAPIServerURL(link string) string {
return fmt.Sprintf("%s/apis%s", c.cfg.GetURL(), link)
}
// IsMarketplaceSubsEnabled -
func (c *ServiceClient) IsMarketplaceSubsEnabled() bool {
return c.cfg.IsMarketplaceSubsEnabled()
}
// getTeamFromCache -
func (c *ServiceClient) getTeamFromCache(name string) (string, bool) {
var team *defs.PlatformTeam
if name == "" {
team = c.caches.GetDefaultTeam()
if team == nil {
return "", false
}
return team.ID, true
}
team = c.caches.GetTeamByName(name)
if team == nil {
return "", false
}
return team.ID, true
}
// GetOrCreateCategory - Returns the value on published proxy
func (c *ServiceClient) GetOrCreateCategory(title string) string {
category := c.caches.GetCategoryWithTitle(title)
if category == nil {
if !corecfg.IsCategoryAutocreationEnabled() {
c.logger.Warnf("Category auto creation is disabled: agent is not allowed to create %s category", title)
return ""
}
// create the category and add it to the cache
newCategory, err := c.CreateCategory(title)
if err != nil {
c.logger.Errorf(errors.Wrap(ErrCategoryCreate, err.Error()).FormatError(title).Error())
return ""
}
category, err = newCategory.AsInstance()
if err == nil {
c.caches.AddCategory(category)
}
}
return category.Name
}
// initClient - config change handler
func (c *ServiceClient) initClient(cfg corecfg.CentralConfig) {
c.cfg = cfg
c.apiClient = coreapi.NewClient(cfg.GetTLSConfig(), cfg.GetProxyURL(),
coreapi.WithTimeout(cfg.GetClientTimeout()), coreapi.WithSingleURL())
c.DefaultSubscriptionSchema = NewSubscriptionSchema(cfg.GetEnvironmentName() + SubscriptionSchemaNameSuffix)
err := c.setTeamCache()
if err != nil {
c.logger.Error(err)
}
// set the default webhook if one has been configured
if cfg.GetSubscriptionConfig() != nil {
webCfg := cfg.GetSubscriptionConfig().GetSubscriptionApprovalWebhookConfig()
if webCfg != nil && webCfg.IsConfigured() {
c.DefaultSubscriptionApprovalWebhook = webCfg
}
if c.subscriptionMgr == nil {
c.subscriptionMgr = newSubscriptionManager(c)
} else {
c.subscriptionMgr.OnConfigChange(c)
}
}
}
// SetTokenGetter - sets the token getter
func (c *ServiceClient) SetTokenGetter(tokenRequester auth.PlatformTokenGetter) {
c.tokenRequester = tokenRequester
}
// SetConfig - sets the config and apiClient
func (c *ServiceClient) SetConfig(cfg corecfg.CentralConfig) {
c.cfg = cfg
c.apiClient = coreapi.NewClient(cfg.GetTLSConfig(), cfg.GetProxyURL(),
coreapi.WithTimeout(cfg.GetClientTimeout()), coreapi.WithSingleURL())
}
// mapToTagsArray -
func mapToTagsArray(m map[string]interface{}, additionalTags string) []string {
strArr := []string{}
for key, val := range m {
value := key
if v, ok := val.(*string); ok && *v != "" {
value += "_" + *v
} else if v, ok := val.(string); ok && v != "" {
value += "_" + v
}
if len(value) > 80 {
value = value[:77] + "..."
}
strArr = append(strArr, value)
}
// Add any tags from config
if additionalTags != "" {
additionalTagsArray := strings.Split(additionalTags, ",")
for _, tag := range additionalTagsArray {
strArr = append(strArr, strings.TrimSpace(tag))
}
}
return strArr
}
func readResponseErrors(status int, body []byte) string {
// Return error string only for error status code
if status < http.StatusBadRequest {
return ""
}
responseErr := &ResponseError{}
err := json.Unmarshal(body, &responseErr)
if err != nil || len(responseErr.Errors) == 0 {
errStr := getHTTPResponseErrorString(status, body)
log.Tracef("HTTP response error: %v", string(errStr))
return errStr
}
// Get the first error from the API response errors
errStr := getAPIResponseErrorString(responseErr.Errors[0])
log.Tracef("HTTP response error: %s", errStr)
return errStr
}
func getHTTPResponseErrorString(status int, body []byte) string {
detail := make(map[string]*json.RawMessage)
json.Unmarshal(body, &detail)
errorMsg := ""
for _, v := range detail {
buffer, _ := v.MarshalJSON()
errorMsg = string(buffer)
}
errStr := "status - " + strconv.Itoa(status)
if errorMsg != "" {
errStr += ", detail - " + errorMsg
}
return errStr
}
func getAPIResponseErrorString(apiError APIError) string {
errStr := "status - " + strconv.Itoa(apiError.Status)
if apiError.Title != "" {
errStr += ", title - " + apiError.Title
}
if apiError.Detail != "" {
errStr += ", detail - " + apiError.Detail
}
return errStr
}
func (c *ServiceClient) createHeader() (map[string]string, error) {
token, err := c.tokenRequester.GetToken()
if err != nil {
return nil, err
}
headers := make(map[string]string)
headers[HdrAxwayTenantID] = c.cfg.GetTenantID()
headers[HdrAuthorization] = BearerTokenPrefix + token
headers[HdrContentType] = ContentTypeJson
return headers, nil
}
// GetSubscriptionManager -
func (c *ServiceClient) GetSubscriptionManager() SubscriptionManager {
return c.subscriptionMgr
}
// SetSubscriptionManager -
func (c *ServiceClient) SetSubscriptionManager(mgr SubscriptionManager) {
c.subscriptionMgr = mgr
}
// Healthcheck - verify connection to the platform
func (c *ServiceClient) Healthcheck(_ string) *hc.Status {
// Set a default response
s := hc.Status{
Result: hc.OK,
}
// Check that we can reach the platform
err := c.checkPlatformHealth()
if err != nil {
s = hc.Status{
Result: hc.FAIL,
Details: err.Error(),
}
}
_, err = c.GetEnvironment()
if err != nil {
s = hc.Status{
Result: hc.FAIL,
Details: err.Error(),
}
}
// Return our response
return &s
}
func (c *ServiceClient) checkPlatformHealth() error {
// this doesn't make a call to platform every time. Only when the token is close to expiring.
_, err := c.tokenRequester.GetToken()
if err != nil {
return errors.Wrap(ErrAuthenticationCall, err.Error())
}
return nil
}
func (c *ServiceClient) setTeamCache() error {
// passing nil to getTeam will return the full list of teams
platformTeams, err := c.GetTeam(make(map[string]string))
if err != nil {
return err
}
teamMap := make(map[string]string)
for _, team := range platformTeams {
teamMap[team.Name] = team.ID
}
return cache.GetCache().Set(TeamMapKey, teamMap)
}
// GetEnvironment get an environment
func (c *ServiceClient) GetEnvironment() (*management.Environment, error) {
headers, err := c.createHeader()
if err != nil {
return nil, errors.Wrap(ErrAuthenticationCall, err.Error())
}
queryParams := map[string]string{}
// do a request for the environment
bytes, err := c.sendServerRequest(c.cfg.GetEnvironmentURL(), headers, queryParams)
if err != nil {
return nil, err
}
// Get env id from apiServerEnvByte
env := &management.Environment{}
err = json.Unmarshal(bytes, env)
if err != nil {
return nil, errors.Wrap(ErrEnvironmentQuery, err.Error())
}
// Validate that we actually get an environment ID back within the Metadata
if env.Metadata.ID == "" {
return nil, ErrEnvironmentQuery
}
return env, nil
}
func (c *ServiceClient) sendServerRequest(url string, headers, query map[string]string) ([]byte, error) {
request := coreapi.Request{
Method: coreapi.GET,
URL: url,
QueryParams: query,
Headers: headers,
}
response, err := c.apiClient.Send(request)
if err != nil {
return nil, errors.Wrap(ErrNetwork, err.Error())
}
switch response.Code {
case http.StatusOK:
return response.Body, nil
case http.StatusUnauthorized:
return nil, ErrAuthentication
default:
responseErr := readResponseErrors(response.Code, response.Body)
return nil, errors.Wrap(ErrRequestQuery, responseErr)
}
}
// GetPlatformUserInfo - request the platform user info
func (c *ServiceClient) getPlatformUserInfo(id string) (*defs.PlatformUserInfo, error) {
headers, err := c.createHeader()
if err != nil {
return nil, err
}
platformURL := fmt.Sprintf("%s/api/v1/user/%s", c.cfg.GetPlatformURL(), id)
c.logger.Tracef("Platform URL being used to get user information %s", platformURL)
platformUserBytes, reqErr := c.sendServerRequest(platformURL, headers, make(map[string]string, 0))
if reqErr != nil {
if reqErr.(*errors.AgentError).GetErrorCode() == ErrRequestQuery.GetErrorCode() {
return nil, ErrNoAddressFound.FormatError(id)
}
return nil, reqErr
}
var platformUserInfo defs.PlatformUserInfo
err = json.Unmarshal(platformUserBytes, &platformUserInfo)
if err != nil {
return nil, err
}
return &platformUserInfo, nil
}
// GetUserEmailAddress - request the user email
func (c *ServiceClient) GetUserEmailAddress(id string) (string, error) {
platformUserInfo, err := c.getPlatformUserInfo(id)
if err != nil {
return "", err
}
email := platformUserInfo.Result.Email
c.logger.Tracef("Platform user email %s", email)
return email, nil
}
// GetUserName - request the user name
func (c *ServiceClient) GetUserName(id string) (string, error) {
platformUserInfo, err := c.getPlatformUserInfo(id)
if err != nil {
return "", err
}
userName := fmt.Sprintf("%s %s", platformUserInfo.Result.Firstname, platformUserInfo.Result.Lastname)
c.logger.Tracef("Platform user %s", userName)
return userName, nil
}
// GetCentralTeamByName - returns the team based on team name
func (c *ServiceClient) GetCentralTeamByName(name string) (*defs.PlatformTeam, error) {
// Query for the default, if no teamName is given
queryParams := map[string]string{}
if name != "" {
queryParams = map[string]string{
"query": fmt.Sprintf("name==\"%s\"", name),
}
}
platformTeams, err := c.GetTeam(queryParams)
if err != nil {
return nil, err
}
if len(platformTeams) == 0 {
return nil, ErrTeamNotFound.FormatError(name)
}
team := platformTeams[0]
if name == "" {
// Loop through to find the default team
for i, platformTeam := range platformTeams {
if platformTeam.Default {
// Found the default, set as the team var and break
team = platformTeams[i]
break
}
}
}
return &team, nil
}
// GetTeam - returns the team ID based on filter
func (c *ServiceClient) GetTeam(query map[string]string) ([]defs.PlatformTeam, error) {
headers, err := c.createHeader()
if err != nil {
return nil, err
}
// Get the teams using Client registry service instead of from platform.
// Platform teams API require access and DOSA account will not have the access
platformURL := fmt.Sprintf("%s/api/v1/platformTeams", c.cfg.GetURL())
response, reqErr := c.sendServerRequest(platformURL, headers, query)
if reqErr != nil {
return nil, reqErr
}
var platformTeams []defs.PlatformTeam
err = json.Unmarshal(response, &platformTeams)
if err != nil {
return nil, err
}
return platformTeams, nil
}
// GetAccessControlList -
func (c *ServiceClient) GetAccessControlList(name string) (*management.AccessControlList, error) {
headers, err := c.createHeader()
if err != nil {
return nil, err
}
request := coreapi.Request{
Method: http.MethodGet,
URL: fmt.Sprintf("%s/%s", c.cfg.GetEnvironmentACLsURL(), name),
Headers: headers,
}
response, err := c.apiClient.Send(request)
if err != nil {
return nil, err
}
if response.Code != http.StatusOK {
responseErr := readResponseErrors(response.Code, response.Body)
return nil, errors.Wrap(ErrRequestQuery, responseErr)
}
var acl *management.AccessControlList
err = json.Unmarshal(response.Body, &acl)
if err != nil {
return nil, err
}
return acl, err
}
// UpdateAccessControlList - removes existing then creates new AccessControlList
func (c *ServiceClient) UpdateAccessControlList(acl *management.AccessControlList) (*management.AccessControlList, error) {
return c.deployAccessControl(acl, http.MethodPut)
}
// CreateAccessControlList -
func (c *ServiceClient) CreateAccessControlList(acl *management.AccessControlList) (*management.AccessControlList, error) {
return c.deployAccessControl(acl, http.MethodPost)
}
func (c *ServiceClient) deployAccessControl(acl *management.AccessControlList, method string) (*management.AccessControlList, error) {
headers, err := c.createHeader()
if err != nil {
return nil, err
}
url := c.cfg.GetEnvironmentACLsURL()
if method == http.MethodPut || method == http.MethodDelete {
url = fmt.Sprintf("%s/%s", url, acl.Name)
}
request := coreapi.Request{
Method: method,
URL: url,
Headers: headers,
}
if method == http.MethodPut || method == http.MethodPost {
data, err := json.Marshal(*acl)
if err != nil {
return nil, err
}
request.Body = data
}
response, err := c.apiClient.Send(request)
if err != nil {
return nil, err
}
if method == http.MethodDelete && (response.Code == http.StatusNotFound || response.Code == http.StatusNoContent) {
return nil, nil
}
if response.Code == http.StatusConflict {
curACL, _ := c.GetResource(acl.GetSelfLink())
c.caches.SetAccessControlList(curACL)
}
if response.Code != http.StatusCreated && response.Code != http.StatusOK {
responseErr := readResponseErrors(response.Code, response.Body)
return nil, errors.Wrap(ErrRequestQuery, responseErr)
}
var updatedACL *management.AccessControlList
if method == http.MethodPut || method == http.MethodPost {
updatedACL = &management.AccessControlList{}
err = json.Unmarshal(response.Body, updatedACL)
if err != nil {
return nil, err
}
}
return updatedACL, err
}
// executeAPI - execute the api
func (c *ServiceClient) executeAPI(method, url string, query map[string]string, buffer []byte, overrideHeaders map[string]string) (*coreapi.Response, error) {
headers, err := c.createHeader()
if err != nil {
return nil, err
}
for key, value := range overrideHeaders {
headers[key] = value
}
request := coreapi.Request{
Method: method,
URL: url,
QueryParams: query,
Headers: headers,
Body: buffer,
}
return c.apiClient.Send(request)
}
// ExecuteAPI - execute the api
func (c *ServiceClient) ExecuteAPI(method, url string, query map[string]string, buffer []byte) ([]byte, error) {
return c.ExecuteAPIWithHeader(method, url, query, buffer, nil)
}
// ExecuteAPI - execute the api
func (c *ServiceClient) ExecuteAPIWithHeader(method, url string, query map[string]string, buffer []byte, headers map[string]string) ([]byte, error) {
response, err := c.executeAPI(method, url, query, buffer, headers)
if err != nil {
return nil, errors.Wrap(ErrNetwork, err.Error())
}
switch {
case response.Code == http.StatusNoContent && method == http.MethodDelete:
return nil, nil
case response.Code == http.StatusOK:
fallthrough
case response.Code == http.StatusCreated:
return response.Body, nil
case response.Code == http.StatusUnauthorized:
return nil, ErrAuthentication
default:
responseErr := readResponseErrors(response.Code, response.Body)
return nil, errors.Wrap(ErrRequestQuery, responseErr)
}
}
// CreateSubResource creates a sub resource on the provided resource.
func (c *ServiceClient) CreateSubResource(rm apiv1.ResourceMeta, subs map[string]interface{}) error {
_, err := c.createSubResource(rm, subs)
return err
}
func (c *ServiceClient) createSubResource(rm apiv1.ResourceMeta, subs map[string]interface{}) (*apiv1.ResourceInstance, error) {
var execErr error
var instanceBytes []byte
wg := &sync.WaitGroup{}
bytesMutex := &sync.Mutex{}
for subName, sub := range subs {
wg.Add(1)
url := c.createAPIServerURL(fmt.Sprintf("%s/%s", rm.GetSelfLink(), subName))
r := map[string]interface{}{
subName: sub,
}
bts, err := json.Marshal(r)
if err != nil {
return nil, err
}
go func(sn string) {
defer wg.Done()
var err error
bytesMutex.Lock()
instanceBytes, err = c.ExecuteAPI(http.MethodPut, url, nil, bts)
if err != nil {
execErr = err
c.logger.Errorf("failed to link sub resource %s to resource %s: %v", sn, rm.Name, err)
}
bytesMutex.Unlock()
}(subName)
}
wg.Wait()
if execErr != nil {
return nil, execErr
}
ri := &apiv1.ResourceInstance{}
err := json.Unmarshal(instanceBytes, ri)
if err != nil {
return nil, err
}
return ri, nil
}
// GetResource gets a single resource
func (c *ServiceClient) GetResource(url string) (*apiv1.ResourceInstance, error) {
response, err := c.ExecuteAPI(http.MethodGet, c.createAPIServerURL(url), nil, nil)
if err != nil {
return nil, err
}
ri := &apiv1.ResourceInstance{}
err = json.Unmarshal(response, ri)
return ri, err
}
// GetResource gets a single resource
func (c *ServiceClient) GetResources(iface apiv1.Interface) ([]apiv1.Interface, error) {
inst, err := iface.AsInstance()
if err != nil {
return nil, err
}
response, err := c.ExecuteAPI(http.MethodGet, c.createAPIServerURL(inst.GetKindLink()), nil, nil)
if err != nil {
return nil, err
}
instances := []*apiv1.ResourceInstance{}
err = json.Unmarshal(response, &instances)
if err != nil {
return nil, err
}
ifaces := []apiv1.Interface{}
for i := range instances {
ifaces = append(ifaces, instances[i])
}
return ifaces, nil
}
// UpdateResourceFinalizer - Add or remove a finalizer from a resource
func (c *ServiceClient) UpdateResourceFinalizer(res *apiv1.ResourceInstance, finalizer, description string, addAction bool) (*apiv1.ResourceInstance, error) {
if addAction {
res.Finalizers = append(res.Finalizers, apiv1.Finalizer{Name: finalizer, Description: description})
} else {
cleanedFinalizer := make([]apiv1.Finalizer, 0)
for _, f := range res.Finalizers {
if f.Name != finalizer {
cleanedFinalizer = append(cleanedFinalizer, f)
}
}
res.Finalizers = cleanedFinalizer
}
return c.UpdateResourceInstance(res)
}
// UpdateResource updates a resource
func (c *ServiceClient) UpdateResource(url string, bts []byte) (*apiv1.ResourceInstance, error) {
log.DeprecationWarningReplace("UpdateResource", "UpdateResourceInstance")
response, err := c.ExecuteAPI(http.MethodPut, c.createAPIServerURL(url), nil, bts)
if err != nil {
return nil, err
}
ri := &apiv1.ResourceInstance{}
err = json.Unmarshal(response, ri)
return ri, err
}
// CreateResource deletes a resource
func (c *ServiceClient) CreateResource(url string, bts []byte) (*apiv1.ResourceInstance, error) {
log.DeprecationWarningReplace("CreateResource", "CreateResourceInstance")
response, err := c.ExecuteAPI(http.MethodPost, c.createAPIServerURL(url), nil, bts)
if err != nil {
return nil, err
}
ri := &apiv1.ResourceInstance{}
err = json.Unmarshal(response, ri)
return ri, err
}
// updateORCreateResourceInstance
func (c *ServiceClient) updateSpecORCreateResourceInstance(data *apiv1.ResourceInstance) (*apiv1.ResourceInstance, error) {
// default to post
url := c.createAPIServerURL(data.GetKindLink())
method := coreapi.POST
// check if the KIND and ID combo have an item in the cache
var existingRI *apiv1.ResourceInstance
var err error
switch data.Kind {
case management.AccessRequestDefinitionGVK().Kind:
existingRI, err = c.caches.GetAccessRequestDefinitionByName(data.Name)
case management.CredentialRequestDefinitionGVK().Kind:
existingRI, err = c.caches.GetCredentialRequestDefinitionByName(data.Name)
case management.APIServiceInstanceGVK().Kind:
existingRI, err = c.caches.GetAPIServiceInstanceByName(data.Name)
}
updateRI := true
updateAgentDetails := true
if err == nil && existingRI != nil {
url = c.createAPIServerURL(data.GetSelfLink())
method = coreapi.PUT
// check if either hash or title has changed and mark for update
oldHash, _ := util.GetAgentDetailsValue(existingRI, defs.AttrSpecHash)
newHash, _ := util.GetAgentDetailsValue(data, defs.AttrSpecHash)
if oldHash == newHash && existingRI.Title == data.Title {
log.Debug("no updates to the hash or to the title")
updateRI = false
}
// check if x-agent-details have changed and mark for update
oldAgentDetails := util.GetAgentDetails(existingRI)
newAgentDetails := util.GetAgentDetails(data)
if util.MapsEqual(oldAgentDetails, newAgentDetails) {
log.Debug("no updates to the x-agent-details")
updateAgentDetails = false
}
// if no changes altogether, return without update
if !updateRI && !updateAgentDetails {
log.Trace("no updates made to the resource instance or to the x-agent-details.")
return existingRI, nil
}
// Update the spec and agent details subresource, if they exist in incoming data
existingRI.Spec = data.Spec
existingRI.SubResources = data.SubResources
existingRI.Title = data.Title
existingRI.Metadata.ResourceVersion = ""
// set the data and subresources to be pushed
data = existingRI
}
newRI := &apiv1.ResourceInstance{}
if updateRI {
reqBytes, err := json.Marshal(data)
if err != nil {
return nil, err
}
response, err := c.ExecuteAPI(method, url, nil, reqBytes)
if err != nil {
return nil, err
}
err = json.Unmarshal(response, newRI)
if err != nil {
return nil, err
}
} else {
newRI = existingRI
}
if data := util.GetAgentDetails(data); data != nil && updateAgentDetails {
// only send in the agent details here, that is all the agent needs to update for anything here
newRI, err = c.createSubResource(newRI.ResourceMeta, map[string]interface{}{defs.XAgentDetails: data})
if err != nil {
return nil, err
}
}
return newRI, err
}
// CreateOrUpdateResource deletes a resource
func (c *ServiceClient) CreateOrUpdateResource(data apiv1.Interface) (*apiv1.ResourceInstance, error) {
data.SetScopeName(c.cfg.GetEnvironmentName())
ri, err := data.AsInstance()
if err != nil {
return nil, err
}
ri, err = c.updateSpecORCreateResourceInstance(ri)
return ri, err
}
// UpdateResourceInstance - updates a ResourceInstance
func (c *ServiceClient) UpdateResourceInstance(ri apiv1.Interface) (*apiv1.ResourceInstance, error) {
inst, err := ri.AsInstance()
if err != nil {
return nil, err
}
if inst.GetSelfLink() == "" {
return nil, fmt.Errorf("could not remove resource instance, could not get self link")
}
inst.Metadata.ResourceVersion = ""
bts, err := json.Marshal(ri)
if err != nil {
return nil, err
}
bts, err = c.ExecuteAPI(coreapi.PUT, c.createAPIServerURL(inst.GetSelfLink()), nil, bts)
if err != nil {
return nil, err
}
r := &apiv1.ResourceInstance{}
err = json.Unmarshal(bts, r)
return r, err
}
// DeleteResourceInstance - deletes a ResourceInstance
func (c *ServiceClient) DeleteResourceInstance(ri apiv1.Interface) error {
inst, err := ri.AsInstance()
if err != nil {
return err
}
if inst.GetSelfLink() == "" {
return fmt.Errorf("could not remove resource instance, could not get self link")
}
bts, err := json.Marshal(ri)
if err != nil {
return err
}
_, err = c.ExecuteAPI(coreapi.DELETE, c.createAPIServerURL(inst.GetSelfLink()), nil, bts)
return err
}
// CreateResourceInstance - creates a ResourceInstance
func (c *ServiceClient) CreateResourceInstance(ri apiv1.Interface) (*apiv1.ResourceInstance, error) {
inst, err := ri.AsInstance()
if err != nil {
return nil, err
}
if inst.GetKindLink() == "" {
return nil, fmt.Errorf("could not create resource instance, could not get self link")
}
inst.Metadata.ResourceVersion = ""
bts, err := json.Marshal(ri)
if err != nil {
return nil, err
}
bts, err = c.ExecuteAPI(coreapi.POST, c.createAPIServerURL(inst.GetKindLink()), nil, bts)
if err != nil {
return nil, err
}
r := &apiv1.ResourceInstance{}
err = json.Unmarshal(bts, r)
return r, err
}
// PatchSubResource - applies the patches to the sub-resource
func (c *ServiceClient) PatchSubResource(ri apiv1.Interface, subResourceName string, patches []map[string]interface{}) (*apiv1.ResourceInstance, error) {
inst, err := ri.AsInstance()
if err != nil {
return nil, err
}