-
Notifications
You must be signed in to change notification settings - Fork 84
/
selfreg_manager.go
258 lines (208 loc) · 9.19 KB
/
selfreg_manager.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
package selfregmanager
import (
"context"
"fmt"
"io"
"net/http"
urlpkg "net/url"
"path"
"strings"
"github.com/kyma-incubator/compass/components/director/internal/domain/tenant"
"github.com/kyma-incubator/compass/components/director/pkg/resource"
"github.com/kyma-incubator/compass/components/director/pkg/config"
"github.com/kyma-incubator/compass/components/director/pkg/apperrors"
"github.com/kyma-incubator/compass/components/director/pkg/consumer"
"github.com/kyma-incubator/compass/components/director/pkg/httputils"
"github.com/kyma-incubator/compass/components/director/pkg/log"
"github.com/kyma-incubator/compass/components/director/pkg/str"
"github.com/pkg/errors"
"github.com/tidwall/gjson"
)
// ExternalSvcCaller is used to call external services with given authentication
//
//go:generate mockery --name=ExternalSvcCaller --output=automock --outpkg=automock --case=underscore --disable-version-string
type ExternalSvcCaller interface {
Call(*http.Request) (*http.Response, error)
}
// ExternalSvcCallerProvider provides ExternalSvcCaller based on the provided SelfRegConfig and region
//
//go:generate mockery --name=ExternalSvcCallerProvider --output=automock --outpkg=automock --case=underscore --disable-version-string
type ExternalSvcCallerProvider interface {
GetCaller(config.SelfRegConfig, string) (ExternalSvcCaller, error)
}
// RegionLabel label for the label repository indicating region
const RegionLabel = "region"
type selfRegisterManager struct {
cfg config.SelfRegConfig
appTemplateProductLabel string
callerProvider ExternalSvcCallerProvider
}
// NewSelfRegisterManager creates a new SelfRegisterManager which is responsible for doing preparation/clean-up during
// self-registration of runtimes configured with values from cfg.
func NewSelfRegisterManager(cfg config.SelfRegConfig, provider ExternalSvcCallerProvider, appTemplateProductLabel string) (*selfRegisterManager, error) {
if err := cfg.PrepareConfiguration(); err != nil {
return nil, errors.Wrap(err, "while preparing self register manager configuration")
}
return &selfRegisterManager{cfg: cfg, appTemplateProductLabel: appTemplateProductLabel, callerProvider: provider}, nil
}
// IsSelfRegistrationFlow check if self registration flow is triggered
func (s *selfRegisterManager) IsSelfRegistrationFlow(ctx context.Context, labels map[string]interface{}) (bool, error) {
consumerInfo, err := consumer.LoadFromContext(ctx)
if err != nil {
return false, errors.Wrapf(err, "while loading consumer")
}
if _, err := tenant.LoadFromContext(ctx); err == nil && consumerInfo.Flow.IsCertFlow() {
_, distinguishLabelExists := labels[s.cfg.SelfRegisterDistinguishLabelKey]
_, productLabelExists := labels[s.appTemplateProductLabel]
if !distinguishLabelExists && !productLabelExists {
return false, errors.Errorf("missing %q or %q label", s.cfg.SelfRegisterDistinguishLabelKey, s.appTemplateProductLabel)
}
if distinguishLabelExists && productLabelExists {
return false, errors.Errorf("should provide either %q or %q label - providing both at the same time is not allowed", s.cfg.SelfRegisterDistinguishLabelKey, s.appTemplateProductLabel)
}
if distinguishLabelExists {
return true, nil
}
return false, nil
}
return false, nil
}
// PrepareForSelfRegistration executes the prerequisite calls for self-registration in case the runtime
// is being self-registered
func (s *selfRegisterManager) PrepareForSelfRegistration(ctx context.Context, resourceType resource.Type, labels map[string]interface{}, id string, validate func() error) (map[string]interface{}, error) {
consumerInfo, err := consumer.LoadFromContext(ctx)
if err != nil {
return nil, errors.Wrapf(err, "while loading consumer")
}
if _, err := tenant.LoadFromContext(ctx); err == nil && consumerInfo.Flow.IsCertFlow() {
distinguishLabel, exists := labels[s.cfg.SelfRegisterDistinguishLabelKey]
if !exists {
if resourceType == resource.Runtime {
return labels, nil
}
return nil, errors.Errorf("missing %q label", s.cfg.SelfRegisterDistinguishLabelKey)
}
if err := validate(); err != nil {
return nil, err
}
if labels[RegionLabel] != nil {
return nil, errors.Errorf("providing %q label and value is forbidden", RegionLabel)
}
region := consumerInfo.Region
if region == "" {
return nil, errors.Errorf("missing %s value in consumer context", RegionLabel)
}
labels[RegionLabel] = region
instanceConfig, exists := s.cfg.RegionToInstanceConfig[region]
if !exists {
return nil, errors.Errorf("missing configuration for region: %s", region)
}
request, err := s.createSelfRegPrepRequest(id, consumerInfo.ConsumerID, instanceConfig.URL)
if err != nil {
return nil, err
}
caller, err := s.callerProvider.GetCaller(s.cfg, region)
if err != nil {
return nil, errors.Wrapf(err, "while getting caller")
}
response, err := caller.Call(request)
if err != nil {
return nil, errors.Wrapf(err, "while executing preparation of self registered resource")
}
defer httputils.Close(ctx, response.Body)
respBytes, err := io.ReadAll(response.Body)
if err != nil {
return nil, errors.Wrapf(err, "while reading response body")
}
if response.StatusCode != http.StatusCreated {
return nil, apperrors.NewCustomErrorWithCode(response.StatusCode, fmt.Sprintf("received unexpected status %d while preparing self-registered resource: %s", response.StatusCode, string(respBytes)))
}
selfRegLabelVal := gjson.GetBytes(respBytes, s.cfg.SelfRegisterResponseKey)
labels[s.cfg.SelfRegisterLabelKey] = selfRegLabelVal.Str
if resourceType == resource.Runtime {
saasAppName, exists := s.cfg.RegionToSaaSAppName[region]
if !exists {
return nil, errors.Errorf("missing SaaS application name for region: %q", region)
}
if saasAppName == "" {
return nil, errors.Errorf("SaaS application name for region: %q could not be empty", region)
}
labels[s.cfg.SaaSAppNameLabelKey] = saasAppName
}
log.C(ctx).Infof("Successfully executed prep for self-registration with distinguishing label value %s", str.CastOrEmpty(distinguishLabel))
}
return labels, nil
}
// CleanupSelfRegistration executes cleanup calls for self-registered runtimes
func (s *selfRegisterManager) CleanupSelfRegistration(ctx context.Context, resourceID, region string) error {
consumerInfo, err := consumer.LoadFromContext(ctx)
if err != nil {
return errors.Wrapf(err, "while loading consumer")
}
if !consumerInfo.Flow.IsCertFlow() {
log.C(ctx).Infof("Not certificate flow, skipping clone deletion for resource %q", resourceID)
return nil
}
if resourceID == "" {
return nil
}
instanceConfig, exists := s.cfg.RegionToInstanceConfig[region]
if !exists {
return errors.Errorf("missing configuration for region: %s", region)
}
request, err := s.createSelfRegDelRequest(resourceID, instanceConfig.URL)
if err != nil {
return err
}
caller, err := s.callerProvider.GetCaller(s.cfg, region)
if err != nil {
return errors.Wrapf(err, "while getting caller")
}
resp, err := caller.Call(request)
if err != nil {
return errors.Wrapf(err, "while executing cleanup of self-registered resource with id %q", resourceID)
}
if resp.StatusCode != http.StatusOK {
return errors.Errorf("received unexpected status code %d while cleaning up self-registered resource with id %q", resp.StatusCode, resourceID)
}
log.C(ctx).Infof("Successfully executed clean-up self-registered resource with id %q", resourceID)
return nil
}
// GetSelfRegDistinguishingLabelKey returns the label key to be used in order to determine whether a resource
// is being self-registered.
func (s *selfRegisterManager) GetSelfRegDistinguishingLabelKey() string {
return s.cfg.SelfRegisterDistinguishLabelKey
}
func (s *selfRegisterManager) createSelfRegPrepRequest(id, tenant, targetURL string) (*http.Request, error) {
selfRegLabelVal := s.cfg.SelfRegisterLabelValuePrefix + id
url, err := urlpkg.Parse(targetURL)
if err != nil {
return nil, errors.Wrapf(err, "while creating url for preparation of self-registered resource")
}
url.Path = path.Join(url.Path, s.cfg.SelfRegisterPath)
q := url.Query()
q.Add(s.cfg.SelfRegisterNameQueryParam, selfRegLabelVal)
q.Add(s.cfg.SelfRegisterTenantQueryParam, tenant)
url.RawQuery = q.Encode()
request, err := http.NewRequest(http.MethodPost, url.String(), strings.NewReader(fmt.Sprintf(s.cfg.SelfRegisterRequestBodyPattern, selfRegLabelVal)))
if err != nil {
return nil, errors.Wrapf(err, "while preparing request for self-registered resource")
}
request.Header.Set("Content-Type", "application/json")
return request, nil
}
func (s *selfRegisterManager) createSelfRegDelRequest(resourceID, targetURL string) (*http.Request, error) {
selfRegLabelVal := s.cfg.SelfRegisterLabelValuePrefix + resourceID
url, err := urlpkg.Parse(targetURL)
if err != nil {
return nil, errors.Wrapf(err, "while creating url for cleanup of self-registered resource")
}
url.Path = path.Join(url.Path, s.cfg.SelfRegisterPath)
url.Path = path.Join(url.Path, selfRegLabelVal)
request, err := http.NewRequest(http.MethodDelete, url.String(), nil)
if err != nil {
return nil, errors.Wrapf(err, "while preparing request for cleanup of self-registered resource")
}
request.Header.Set("Content-Type", "application/json")
return request, nil
}