forked from jenkins-x/jx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
registry.go
184 lines (157 loc) · 4.64 KB
/
registry.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
package iks
import (
b64 "encoding/base64"
"encoding/json"
"fmt"
gohttp "net/http"
"net/url"
"strconv"
ibmcloud "github.com/IBM-Cloud/bluemix-go"
"github.com/IBM-Cloud/bluemix-go/authentication"
"github.com/IBM-Cloud/bluemix-go/bmxerror"
"github.com/IBM-Cloud/bluemix-go/client"
"github.com/IBM-Cloud/bluemix-go/http"
"github.com/IBM-Cloud/bluemix-go/rest"
"github.com/IBM-Cloud/bluemix-go/session"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
type Config struct {
Auths map[string]*Auth `json:"auths,omitempty"`
}
type Auth struct {
Auth string `json:"auth,omitempty"`
}
type RegistryServiceAPI interface {
Registry() Registry
}
//MccpService holds the client
type registry struct {
*client.Client
}
type AddTokenResponse struct {
Token string `json:"token"`
}
type Registry interface {
AddToken(account string, description string, permanent bool, write bool) (string, error)
}
var regionToEndpoint = map[string]string{
"us-south": "https://registry.ng.bluemix.net",
"us-east": "https://registry.ng.bluemix.net",
"global": "https://registry.bluemix.net",
"eu-gb": "https://registry.eu-gb.bluemix.net",
"au-syd": "https://registry.au-syd.bluemix.net",
"eu-de": "https://registry.eu-de.bluemix.net",
}
const (
ErrCodeNotAuthorized = "NotAuthorized"
ErrCodeUnableToAuthenticate = "UnableToAuthenticate"
)
func (a *registry) Registry() Registry {
return newRegistryAPI(a.Client)
}
func newRegistryAPI(c *client.Client) Registry {
return ®istry{
Client: c,
}
}
// Try to use the regional registry used by the cluster
// We will also set the corresponding secret for jenkins-x right away
func GetClusterRegistry(kubeClient kubernetes.Interface) string {
registry := "registry.bluemix.net" // default to global
secretFromConfig, err := kubeClient.CoreV1().Secrets("default").Get("bluemix-default-secret-regional", metav1.GetOptions{})
if err != nil {
return ""
}
dockerConfig := &Config{}
err = json.Unmarshal(secretFromConfig.Data[".dockerconfigjson"], dockerConfig)
if err == nil {
for k, _ := range dockerConfig.Auths {
registry = k
}
}
return registry
}
func GetRegistryConfigJSON(registry string) (string, error) {
//token :=
c := new(ibmcloud.Config)
accountID, err := ConfigFromJSON(c)
if err != nil {
return "",err
}
s, err := session.New(c)
if err != nil {
return "",err
}
registryAPI, err := NewRegistryServiceAPI(s)
registryIF := registryAPI.Registry()
clusterName, _ := GetClusterName()
token, err := registryIF.AddToken(accountID, fmt.Sprintf("%s Jenkins-X Token", clusterName), true, true)
if err != nil {
return "",err
}
newSecret := &Auth{}
dockerConfig := &Config{}
newSecret.Auth = b64.StdEncoding.EncodeToString([]byte("token:" + token))
if dockerConfig.Auths == nil {
dockerConfig.Auths = map[string]*Auth{}
}
dockerConfig.Auths[registry] = newSecret
configBytes, err := json.Marshal(dockerConfig)
if err != nil {
return "",err
}
return string(configBytes), nil
}
//New ...
func NewRegistryServiceAPI(sess *session.Session) (RegistryServiceAPI, error) {
config := sess.Config.Copy()
if config.HTTPClient == nil {
config.HTTPClient = http.NewHTTPClient(config)
}
tokenRefreher, err := authentication.NewIAMAuthRepository(config, &rest.Client{
DefaultHeader: gohttp.Header{
"User-Agent": []string{http.UserAgent()},
},
HTTPClient: config.HTTPClient,
})
if err != nil {
return nil, err
}
if config.IAMAccessToken == "" {
err := authentication.PopulateTokens(tokenRefreher, config)
if err != nil {
return nil, err
}
}
if config.Endpoint == nil {
endpoint := regionToEndpoint[config.Region]
config.Endpoint = &endpoint
}
return ®istry{
Client: client.New(config, ibmcloud.IAMService, tokenRefreher),
}, nil
}
func (a *registry) AddToken(accountID string, description string, permanent bool, write bool) (string, error) {
queryResp := AddTokenResponse{}
v := url.Values{}
v.Set("description", description)
v.Set("permanent", strconv.FormatBool(permanent))
v.Set("write", strconv.FormatBool(write))
m := make(map[string]string, 1)
m["Account"] = accountID
response, err := a.Client.Post(fmt.Sprintf("/api/v1/tokens?%s", v.Encode()), nil, &queryResp, m)
if err != nil {
fmt.Println(err)
if response.StatusCode == 401 {
return "", bmxerror.New(ErrCodeNotAuthorized,
"You are not authorized to view the requested resource, or your IBM Cloud bearer token is invalid. Correct the request and try again.")
}
if response.StatusCode == 503 {
return "", bmxerror.New(ErrCodeUnableToAuthenticate,
"Unable to authenticate with IBM Cloud. Try again later.")
}
return "", err
}
return queryResp.Token, nil
}