forked from helm/helm
/
registryprovider.go
421 lines (349 loc) · 12.6 KB
/
registryprovider.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
/*
Copyright 2015 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package registry
import (
"github.com/google/go-github/github"
"github.com/kubernetes/deployment-manager/common"
"github.com/kubernetes/deployment-manager/util"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
storage "google.golang.org/api/storage/v1"
"fmt"
"log"
"net/http"
"net/url"
"regexp"
"strings"
"sync"
)
// RegistryProvider is a factory for Registry instances.
type RegistryProvider interface {
GetRegistryByShortURL(URL string) (Registry, error)
GetRegistryByName(registryName string) (Registry, error)
}
type registryProvider struct {
sync.RWMutex
rs common.RegistryService
grp GithubRegistryProvider
gcsrp GCSRegistryProvider
cp common.CredentialProvider
registries map[string]Registry
}
// NewDefaultRegistryProvider creates a default registry provider with the supplied credential.
func NewDefaultRegistryProvider(cp common.CredentialProvider, rs common.RegistryService) RegistryProvider {
return NewRegistryProvider(rs, NewGithubRegistryProvider(cp), NewGCSRegistryProvider(cp), cp)
}
// NewRegistryProvider creates a new registry provider using the supplied arguments.
func NewRegistryProvider(rs common.RegistryService, grp GithubRegistryProvider, gcsrp GCSRegistryProvider, cp common.CredentialProvider) RegistryProvider {
if rs == nil {
rs = NewInmemRegistryService()
}
if cp == nil {
cp = NewInmemCredentialProvider()
}
if grp == nil {
grp = NewGithubRegistryProvider(cp)
}
if gcsrp == nil {
gcsrp = NewGCSRegistryProvider(cp)
}
registries := make(map[string]Registry)
rp := ®istryProvider{rs: rs, grp: grp, gcsrp: gcsrp, cp: cp, registries: registries}
return rp
}
func (rp *registryProvider) getRegistry(cr common.Registry) (Registry, error) {
switch cr.Type {
case common.GithubRegistryType:
return rp.grp.GetGithubRegistry(cr)
case common.GCSRegistryType:
log.Printf("Creating a bigstore client using %#v", rp.gcsrp)
return rp.gcsrp.GetGCSRegistry(cr)
default:
return nil, fmt.Errorf("unknown registry type: %s", cr.Type)
}
}
// GetRegistryByShortURL returns the registry identified by a short URL.
func (rp *registryProvider) GetRegistryByShortURL(URL string) (Registry, error) {
rp.RLock()
defer rp.RUnlock()
result := rp.findRegistryByShortURL(URL)
if result == nil {
cr, err := rp.rs.GetByURL(URL)
if err != nil {
return nil, err
}
r, err := rp.getRegistry(*cr)
if err != nil {
return nil, err
}
rp.registries[r.GetRegistryName()] = r
result = r
}
return result, nil
}
// findRegistryByShortURL trims the scheme from both the supplied URL
// and the short URL returned by GetRegistryShortURL.
func (rp *registryProvider) findRegistryByShortURL(URL string) Registry {
trimmed := util.TrimURLScheme(URL)
for _, r := range rp.registries {
if strings.HasPrefix(trimmed, util.TrimURLScheme(r.GetRegistryShortURL())) {
return r
}
}
return nil
}
// GetRegistryByName returns a registry by name.
func (rp *registryProvider) GetRegistryByName(registryName string) (Registry, error) {
rp.RLock()
defer rp.RUnlock()
cr, err := rp.rs.Get(registryName)
if err != nil {
return nil, err
}
r, err := rp.getRegistry(*cr)
if err != nil {
return nil, err
}
rp.registries[r.GetRegistryName()] = r
return r, nil
}
// ParseRegistryFormat creates a map from a registry format string.
func ParseRegistryFormat(rf common.RegistryFormat) map[common.RegistryFormat]bool {
split := strings.Split(string(rf), ";")
var result = map[common.RegistryFormat]bool{}
for _, format := range split {
result[common.RegistryFormat(format)] = true
}
return result
}
// GithubRegistryProvider is a factory for GithubRegistry instances.
type GithubRegistryProvider interface {
GetGithubRegistry(cr common.Registry) (GithubRegistry, error)
}
type githubRegistryProvider struct {
cp common.CredentialProvider
}
// NewGithubRegistryProvider creates a GithubRegistryProvider.
func NewGithubRegistryProvider(cp common.CredentialProvider) GithubRegistryProvider {
if cp == nil {
// TODO: replace this panic with an error return.
panic(fmt.Errorf("no credential provider"))
}
return &githubRegistryProvider{cp: cp}
}
func (grp githubRegistryProvider) createGithubClient(credentialName string) (*http.Client, *github.Client, error) {
if credentialName == "" {
return http.DefaultClient, github.NewClient(nil), nil
}
c, err := grp.cp.GetCredential(credentialName)
if err != nil {
log.Printf("Failed to fetch credential %s: %v", credentialName, err)
log.Print("Trying to use unauthenticated client")
return http.DefaultClient, github.NewClient(nil), nil
}
if c != nil {
if c.APIToken != "" {
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: string(c.APIToken)},
)
tc := oauth2.NewClient(oauth2.NoContext, ts)
return tc, github.NewClient(tc), nil
}
if c.BasicAuth.Username != "" && c.BasicAuth.Password != "" {
tp := github.BasicAuthTransport{
Username: c.BasicAuth.Username,
Password: c.BasicAuth.Password,
}
return tp.Client(), github.NewClient(tp.Client()), nil
}
}
return nil, nil, fmt.Errorf("No suitable credential found for %s", credentialName)
}
// GetGithubRegistry returns a new GithubRegistry. If there's a credential that is specified, will try
// to fetch it and use it, and if there's no credential found, will fall back to unauthenticated client.
func (grp githubRegistryProvider) GetGithubRegistry(cr common.Registry) (GithubRegistry, error) {
// If there's a credential that we need to use, fetch it and create a client for it.
httpClient, client, err := grp.createGithubClient(cr.CredentialName)
if err != nil {
return nil, err
}
fMap := ParseRegistryFormat(cr.Format)
if fMap[common.UnversionedRegistry] && fMap[common.OneLevelRegistry] {
return NewGithubPackageRegistry(cr.Name, cr.URL, nil, httpClient, client)
}
if fMap[common.VersionedRegistry] && fMap[common.CollectionRegistry] {
return NewGithubTemplateRegistry(cr.Name, cr.URL, nil, httpClient, client)
}
return nil, fmt.Errorf("unknown registry format: %s", cr.Format)
}
// GCSRegistryProvider is a factory for GCS Registry instances.
type GCSRegistryProvider interface {
GetGCSRegistry(cr common.Registry) (ObjectStorageRegistry, error)
}
type gcsRegistryProvider struct {
cp common.CredentialProvider
}
// NewGCSRegistryProvider creates a GCSRegistryProvider.
func NewGCSRegistryProvider(cp common.CredentialProvider) GCSRegistryProvider {
if cp == nil {
// TODO: replace this panic with an error return.
panic(fmt.Errorf("no credential provider"))
}
return &gcsRegistryProvider{cp: cp}
}
// GetGCSRegistry returns a new Google Cloud Storage . If there's a credential that is specified, will try
// to fetch it and use it, and if there's no credential found, will fall back to unauthenticated client.
func (gcsrp gcsRegistryProvider) GetGCSRegistry(cr common.Registry) (ObjectStorageRegistry, error) {
client, err := gcsrp.createGCSClient(cr.CredentialName)
if err != nil {
return nil, err
}
service, err := storage.New(client)
if err != nil {
log.Fatalf("Unable to create storage service: %v", err)
}
return NewGCSRegistry(cr.Name, cr.URL, client, service)
}
func (gcsrp gcsRegistryProvider) createGCSClient(credentialName string) (*http.Client, error) {
if credentialName == "" {
return http.DefaultClient, nil
}
c, err := gcsrp.cp.GetCredential(credentialName)
if err != nil {
log.Printf("Failed to fetch credential %s: %v", credentialName, err)
log.Print("Trying to use unauthenticated client")
return http.DefaultClient, nil
}
config, err := google.JWTConfigFromJSON([]byte(c.ServiceAccount), storage.DevstorageReadOnlyScope)
if err != nil {
log.Fatalf("Unable to parse client secret file to config: %v", err)
}
return config.Client(oauth2.NoContext), nil
}
// RE for a registry type that does support versions and has collections.
var TemplateRegistryMatcher = regexp.MustCompile("github.com/(.*)/(.*)/(.*)/(.*):(.*)")
// RE for a registry type that does not support versions and does not have collections.
var PackageRegistryMatcher = regexp.MustCompile("github.com/(.*)/(.*)/(.*)")
// RE for GCS storage
var GCSRegistryMatcher = regexp.MustCompile("gs://(.*)/(.*)")
// IsGithubShortType returns whether a given type is a type description in a short format to a github repository type.
// For now, this means using github types:
// github.com/owner/repo/qualifier/type:version
// for example:
// github.com/kubernetes/application-dm-templates/storage/redis:v1
func IsGithubShortType(t string) bool {
return TemplateRegistryMatcher.MatchString(t)
}
// IsGithubShortPackageType returns whether a given type is a type description in a short format to a github
// package repository type.
// For now, this means using github types:
// github.com/owner/repo/type
// for example:
// github.com/helm/charts/cassandra
func IsGithubShortPackageType(t string) bool {
return PackageRegistryMatcher.MatchString(t)
}
// IsGCSShortType returns whether a given type is a type description in a short format to GCS
func IsGCSShortType(t string) bool {
return strings.HasPrefix(t, "gs://")
}
// GetDownloadURLs checks a type to see if it is either a short git hub url or a fully specified URL
// and returns the URLs that should be used to fetch it. If the url is not fetchable (primitive type
// for example), it returns an empty slice.
func GetDownloadURLs(rp RegistryProvider, t string) ([]string, Registry, error) {
if IsGithubShortType(t) {
return ShortTypeToDownloadURLs(rp, t)
} else if IsGithubShortPackageType(t) {
return ShortTypeToPackageDownloadURLs(rp, t)
} else if IsGCSShortType(t) {
return ShortTypeToGCSDownloadUrls(rp, t)
} else if util.IsHTTPURL(t) {
result, err := url.Parse(t)
if err != nil {
return nil, nil, fmt.Errorf("cannot parse download URL %s: %s", t, err)
}
return []string{result.String()}, nil, nil
}
return []string{}, nil, nil
}
// ShortTypeToDownloadURLs converts a github URL into downloadable URL from github.
// Input must be of the type and is assumed to have been validated before this call:
// github.com/owner/repo/qualifier/type:version
// for example:
// github.com/kubernetes/application-dm-templates/storage/redis:v1
func ShortTypeToDownloadURLs(rp RegistryProvider, t string) ([]string, Registry, error) {
m := TemplateRegistryMatcher.FindStringSubmatch(t)
if len(m) != 6 {
return nil, nil, fmt.Errorf("cannot parse short github url: %s", t)
}
r, err := rp.GetRegistryByShortURL(t)
if err != nil {
return nil, nil, err
}
if r == nil {
return nil, nil, fmt.Errorf("cannot get github registry for %s", t)
}
tt, err := NewType(m[3], m[4], m[5])
if err != nil {
return nil, r, err
}
urls, err := r.GetDownloadURLs(tt)
if err != nil {
return nil, r, err
}
return util.ConvertURLsToStrings(urls), r, err
}
// ShortTypeToPackageDownloadURLs converts a github URL into downloadable URLs from github.
// Input must be of the type and is assumed to have been validated before this call:
// github.com/owner/repo/type
// for example:
// github.com/helm/charts/cassandra
func ShortTypeToPackageDownloadURLs(rp RegistryProvider, t string) ([]string, Registry, error) {
m := PackageRegistryMatcher.FindStringSubmatch(t)
if len(m) != 4 {
return nil, nil, fmt.Errorf("Failed to parse short github url: %s", t)
}
r, err := rp.GetRegistryByShortURL(t)
if err != nil {
return nil, nil, err
}
tt, err := NewType("", m[3], "")
if err != nil {
return nil, r, err
}
urls, err := r.GetDownloadURLs(tt)
if err != nil {
return nil, r, err
}
return util.ConvertURLsToStrings(urls), r, err
}
// ShortTypeToGCSDownloadUrls returns the download URLs for a short type name.
func ShortTypeToGCSDownloadUrls(rp RegistryProvider, t string) ([]string, Registry, error) {
m := GCSRegistryMatcher.FindStringSubmatch(t)
if len(m) != 3 {
return nil, nil, fmt.Errorf("Failed to parse short gs url: %s", t)
}
r, err := rp.GetRegistryByShortURL(t)
if err != nil {
return nil, nil, err
}
tt, err := NewType(m[1], m[2], "")
if err != nil {
return nil, r, err
}
urls, err := r.GetDownloadURLs(tt)
if err != nil {
return nil, r, err
}
return util.ConvertURLsToStrings(urls), r, err
}