-
Notifications
You must be signed in to change notification settings - Fork 84
/
client.go
233 lines (196 loc) · 6.88 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
package systemfetcher
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"sync/atomic"
"time"
"github.com/kyma-incubator/compass/components/director/internal/model"
tenantEntity "github.com/kyma-incubator/compass/components/director/pkg/tenant"
"github.com/avast/retry-go/v4"
"github.com/kyma-incubator/compass/components/director/pkg/log"
"github.com/kyma-incubator/compass/components/director/pkg/paging"
"github.com/pkg/errors"
)
// APIClient missing godoc
//
//go:generate mockery --name=APIClient --output=automock --outpkg=automock --case=underscore --disable-version-string
type APIClient interface {
Do(*http.Request, string) (*http.Response, error)
}
// APIConfig missing godoc
type APIConfig struct {
Endpoint string `envconfig:"APP_SYSTEM_INFORMATION_ENDPOINT"`
FilterCriteria string `envconfig:"APP_SYSTEM_INFORMATION_FILTER_CRITERIA"`
Timeout time.Duration `envconfig:"APP_SYSTEM_INFORMATION_FETCH_TIMEOUT"`
PageSize uint64 `envconfig:"APP_SYSTEM_INFORMATION_PAGE_SIZE"`
PagingSkipParam string `envconfig:"APP_SYSTEM_INFORMATION_PAGE_SKIP_PARAM"`
PagingSizeParam string `envconfig:"APP_SYSTEM_INFORMATION_PAGE_SIZE_PARAM"`
SystemSourceKey string `envconfig:"APP_SYSTEM_INFORMATION_SOURCE_KEY"`
SystemRPSLimit uint64 `envconfig:"default=15,APP_SYSTEM_INFORMATION_RPS_LIMIT"`
}
// Client missing godoc
type Client struct {
apiConfig APIConfig
httpClient APIClient
jwtTokenClient APIClient
}
// NewClient missing godoc
func NewClient(apiConfig APIConfig, client APIClient, tokenClient APIClient) *Client {
return &Client{
apiConfig: apiConfig,
httpClient: client,
jwtTokenClient: tokenClient,
}
}
var currentRPS uint64
// FetchSystemsForTenant fetches systems from the service
func (c *Client) FetchSystemsForTenant(ctx context.Context, tenant *model.BusinessTenantMapping, systemSynchronizationTimestamps map[string]SystemSynchronizationTimestamp) ([]System, error) {
qp := c.buildFilter(systemSynchronizationTimestamps)
log.C(ctx).Infof("Fetching systems for tenant %s of type %s with query: %s", tenant.ExternalTenant, tenant.Type, qp)
var systems []System
systemsFunc := c.getSystemsPagingFunc(ctx, &systems, tenant)
pi := paging.NewPageIterator(c.apiConfig.Endpoint, c.apiConfig.PagingSkipParam, c.apiConfig.PagingSizeParam, qp, c.apiConfig.PageSize, systemsFunc)
if err := pi.FetchAll(); err != nil {
return nil, errors.Wrapf(err, "failed to fetch systems for tenant %s", tenant.ExternalTenant)
}
log.C(ctx).Infof("Fetched systems for tenant %s", tenant.ExternalTenant)
return systems, nil
}
func (c *Client) fetchSystemsForTenant(ctx context.Context, url string, tenant *model.BusinessTenantMapping) ([]System, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, errors.Wrap(err, "failed to create new HTTP request")
}
var (
resp *http.Response
)
if tenant.Type == tenantEntity.Customer {
resp, err = c.jwtTokenClient.Do(req, tenant.ExternalTenant)
} else {
resp, err = c.httpClient.Do(req, tenant.ExternalTenant)
}
if err != nil {
return nil, errors.Wrap(err, "failed to execute HTTP request")
}
defer func() {
err := resp.Body.Close()
if err != nil {
log.C(ctx).Println("Failed to close HTTP response body")
}
}()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status code: expected: %d, but got: %d", http.StatusOK, resp.StatusCode)
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrap(err, "failed to parse HTTP response body")
}
var systems []System
if err = json.Unmarshal(respBody, &systems); err != nil {
return nil, errors.Wrap(err, "failed to unmarshal systems response")
}
systemsWithTemplateID := make([]System, 0)
for _, system := range systems {
templatedSystem, err := system.EnhanceWithTemplateID()
if err != nil {
return nil, errors.Wrap(err, "failed to map systems with Application Template ID")
}
if templatedSystem.TemplateID != "" {
systemsWithTemplateID = append(systemsWithTemplateID, templatedSystem)
}
}
return systemsWithTemplateID, nil
}
func (c *Client) getSystemsPagingFunc(ctx context.Context, systems *[]System, tenant *model.BusinessTenantMapping) func(string) (uint64, error) {
return func(url string) (uint64, error) {
err := retry.Do(
func() error {
if atomic.LoadUint64(¤tRPS) >= c.apiConfig.SystemRPSLimit {
return errors.New("RPS limit reached")
} else {
atomic.AddUint64(¤tRPS, 1)
return nil
}
},
retry.Attempts(0),
retry.Delay(time.Millisecond*100),
)
if err != nil {
return 0, err
}
var currentSystems []System
err = retry.Do(
func() error {
currentSystems, err = c.fetchSystemsForTenant(ctx, url, tenant)
if err != nil && err.Error() == "unexpected status code: expected: 200, but got: 401" {
return retry.Unrecoverable(err)
}
return err
},
retry.Attempts(3),
retry.Delay(time.Second),
retry.OnRetry(func(n uint, err error) {
log.C(ctx).Infof("Retrying request attempt (%d) after error %v", n, err)
}),
)
atomic.AddUint64(¤tRPS, ^uint64(0))
if err != nil {
return 0, err
}
log.C(ctx).Infof("Fetched page of systems for URL %s", url)
*systems = append(*systems, currentSystems...)
return uint64(len(currentSystems)), nil
}
}
func (c *Client) buildFilter(systemSynchronizationTimestamps map[string]SystemSynchronizationTimestamp) map[string]string {
var filterBuilder FilterBuilder
usedSystemRoles := make(map[string]bool)
for _, templateMapping := range ApplicationTemplates {
appTemplateLblFilter, ok := templateMapping.Labels[ApplicationTemplateLabelFilter]
if !ok {
continue
}
appTemplateLblFilterArr, ok := appTemplateLblFilter.Value.([]interface{})
if !ok {
continue
}
for _, lbl := range appTemplateLblFilterArr {
appTemplateLblStr, ok := lbl.(string)
if !ok {
continue
}
if _, exists := usedSystemRoles[appTemplateLblStr]; exists {
continue
}
usedSystemRoles[appTemplateLblStr] = true
expr1 := filterBuilder.NewExpression(SystemSourceKey, "eq", appTemplateLblStr)
lblExists := false
minTime := time.Now()
if timestamp, ok := systemSynchronizationTimestamps[appTemplateLblStr]; ok {
lblExists = true
if timestamp.LastSyncTimestamp.Before(minTime) {
minTime = timestamp.LastSyncTimestamp
}
}
if lblExists {
expr2 := filterBuilder.NewExpression("lastChangeDateTime", "gt", minTime.String())
filterBuilder.addFilter(expr1, expr2)
} else {
filterBuilder.addFilter(expr1)
}
}
}
result := map[string]string{"fetchAcrossZones": "true"}
if len(c.apiConfig.FilterCriteria) > 0 {
result["$filter"] = fmt.Sprintf(c.apiConfig.FilterCriteria, filterBuilder.buildFilterQuery())
}
selectFilter := strings.Join(SelectFilter, ",")
if len(selectFilter) > 0 {
result["$select"] = selectFilter
}
return result
}