forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
core_dns_client.go
302 lines (252 loc) · 7.09 KB
/
core_dns_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
package approuter
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"reflect"
"sort"
"sync"
"github.com/pkg/errors"
"github.com/rancher/rdns-server/model"
v1 "github.com/rancher/types/apis/core/v1"
"github.com/sirupsen/logrus"
k8scorev1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const (
contentType = "Content-Type"
jsonContentType = "application/json"
secretKey = "rdns-token"
)
func jsonBody(payload interface{}) (io.Reader, error) {
buf := &bytes.Buffer{}
err := json.NewEncoder(buf).Encode(payload)
if err != nil {
return nil, err
}
return buf, nil
}
type Client struct {
httpClient *http.Client
base string
lock *sync.RWMutex
managementSecretLister v1.SecretLister
secrets v1.SecretInterface
clusterName string
}
func (c *Client) request(method string, url string, body io.Reader) (*http.Request, error) {
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
req.Header.Add(contentType, jsonContentType)
return req, nil
}
func (c *Client) do(req *http.Request) (model.Response, error) {
var data model.Response
resp, err := c.httpClient.Do(req)
if err != nil {
return data, err
}
// when err is nil, resp contains a non-nil resp.Body which must be closed
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return data, errors.Wrap(err, "Read response body error")
}
err = json.Unmarshal(body, &data)
if err != nil {
return data, errors.Wrapf(err, "Decode response error: %s", string(body))
}
logrus.Debugf("Got response entry: %+v", data)
if code := resp.StatusCode; code < 200 || code > 300 {
if data.Message != "" {
return data, errors.Errorf("Got request error: %s", data.Message)
}
}
return data, nil
}
func (c *Client) ApplyDomain(hosts []string) (bool, string, error) {
c.lock.RLock()
defer c.lock.RUnlock()
d, err := c.GetDomain()
if err != nil {
return false, "", err
}
if d == nil {
logrus.Debugf("Fqdn configuration does not exist, need to create a new one")
fqdn, err := c.CreateDomain(hosts)
return true, fqdn, err
}
sort.Strings(d.Hosts)
sort.Strings(hosts)
if !reflect.DeepEqual(d.Hosts, hosts) {
logrus.Debugf("Fqdn %s has some changes, need to update", d.Fqdn)
fqdn, err := c.UpdateDomain(hosts)
return false, fqdn, err
}
logrus.Debugf("Fqdn %s has no changes, no need to update", d.Fqdn)
fqdn, _, _ := c.getSecret()
return false, fqdn, nil
}
func (c *Client) GetDomain() (d *model.Domain, err error) {
fqdn, token, err := c.getSecret()
if err != nil {
if k8serrors.IsNotFound(err) {
return nil, nil
}
return nil, errors.Wrap(err, "GetDomain: failed to get stored secret")
}
url := buildURL(c.base, "/"+fqdn, "")
req, err := c.request(http.MethodGet, url, nil)
if err != nil {
return d, errors.Wrap(err, "GetDomain: failed to build a request")
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
o, err := c.do(req)
if err != nil {
return d, errors.Wrap(err, "GetDomain: failed to execute a request")
}
return &o.Data, nil
}
func (c *Client) CreateDomain(hosts []string) (string, error) {
c.lock.RLock()
defer c.lock.RUnlock()
url := buildURL(c.base, "", "")
body, err := jsonBody(&model.DomainOptions{Hosts: hosts})
if err != nil {
return "", err
}
req, err := c.request(http.MethodPost, url, body)
if err != nil {
return "", errors.Wrap(err, "CreateDomain: failed to build a request")
}
resp, err := c.do(req)
if err != nil {
return "", errors.Wrap(err, "CreateDomain: failed to execute a request")
}
//to find token in management cluster namespace
if _, _, err = c.getSecret(); err != nil {
if !k8serrors.IsNotFound(err) {
return "", err
}
//if token not found, create a new one
if err = c.setSecret(&resp); err != nil {
return "", err
}
}
return resp.Data.Fqdn, err
}
func (c *Client) UpdateDomain(hosts []string) (string, error) {
c.lock.RLock()
defer c.lock.RUnlock()
fqdn, token, err := c.getSecret()
if err != nil {
return "", errors.Wrap(err, "UpdateDomain: failed to get stored secret")
}
url := buildURL(c.base, "/"+fqdn, "")
body, err := jsonBody(&model.DomainOptions{Hosts: hosts})
if err != nil {
return "", err
}
req, err := c.request(http.MethodPut, url, body)
if err != nil {
return "", errors.Wrap(err, "UpdateDomain: failed to build a request")
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
_, err = c.do(req)
if err != nil {
return "", errors.Wrap(err, "UpdateDomain: failed to execute a request")
}
return fqdn, nil
}
func (c *Client) DeleteDomain() (string, error) {
c.lock.RLock()
defer c.lock.RUnlock()
fqdn, token, err := c.getSecret()
if err != nil {
return "", errors.Wrap(err, "DeleteDomain: failed to get stored secret")
}
url := buildURL(c.base, "/"+fqdn, "")
req, err := c.request(http.MethodDelete, url, nil)
if err != nil {
return "", errors.Wrap(err, "DeleteDomain: failed to build a request")
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
_, err = c.do(req)
if err != nil {
return "", errors.Wrap(err, "DeleteDomain: failed to execute a request")
}
return fqdn, err
}
func (c *Client) RenewDomain() (string, error) {
c.lock.RLock()
defer c.lock.RUnlock()
fqdn, token, err := c.getSecret()
if err != nil {
return "", errors.Wrap(err, "RenewDomain: failed to get stored secret")
}
url := buildURL(c.base, "/"+fqdn, "/renew")
req, err := c.request(http.MethodPut, url, nil)
if err != nil {
return "", errors.Wrap(err, "RenewDomain: failed to build a request")
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
_, err = c.do(req)
if err != nil {
return "", errors.Wrap(err, "RenewDomain: failed to execute a request")
}
return fqdn, err
}
func (c *Client) SetBaseURL(base string) {
c.lock.RLock()
defer c.lock.RUnlock()
if base != c.base {
c.base = base
}
}
func (c *Client) setSecret(resp *model.Response) error {
_, err := c.secrets.Create(&k8scorev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: secretKey,
Namespace: c.clusterName,
},
Type: k8scorev1.SecretTypeOpaque,
StringData: map[string]string{
"token": resp.Token,
"fqdn": resp.Data.Fqdn,
},
})
if err != nil {
if k8serrors.IsAlreadyExists(err) {
return nil
}
return err
}
return nil
}
//getSecret return token and fqdn
func (c *Client) getSecret() (string, string, error) {
sec, err := c.managementSecretLister.Get(c.clusterName, secretKey)
if err != nil {
return "", "", err
}
return string(sec.Data["fqdn"]), string(sec.Data["token"]), nil
}
func NewClient(secrets v1.SecretInterface, secretLister v1.SecretLister, clusterName string) *Client {
return &Client{
httpClient: http.DefaultClient,
lock: &sync.RWMutex{},
secrets: secrets,
managementSecretLister: secretLister,
clusterName: clusterName,
}
}
//buildUrl return request url
func buildURL(base, fqdn, path string) (url string) {
return fmt.Sprintf("%s/domain%s%s", base, fqdn, path)
}