-
Notifications
You must be signed in to change notification settings - Fork 2
/
dnsclient.go
364 lines (284 loc) · 9.64 KB
/
dnsclient.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
package dnsclient
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"strconv"
extensionscontroller "github.com/gardener/gardener/extensions/pkg/controller"
ibclient "github.com/infobloxopen/infoblox-go-client/v2"
corev1 "k8s.io/api/core/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/gardener/gardener/pkg/logger"
runtimelog "sigs.k8s.io/controller-runtime/pkg/log"
raw "github.com/ujwaliyer/gardener-extension-provider-dns-infoblox/pkg/infoblox"
)
var (
errLog error
)
type DNSClient interface {
GetManagedZones(ctx context.Context) (map[string]string, error)
CreateOrUpdateRecordSet(ctx context.Context, view, zone, name, record_type string, values []string, ttl int64) error
DeleteRecordSet(ctx context.Context, zone, name, recordType string) error
}
type dnsClient struct {
client ibclient.IBConnector
}
type RecordSet []raw.Base_Record
type InfobloxConfig struct {
Host *string `json:"HOST,omitempty"`
Port *int `json:"port,omitempty"`
SSLVerify *bool `json:"sslVerify,omitempty"`
Version *string `json:"version,omitempty"`
View *string `json:"view,omitempty"`
PoolConnections *int `json:"httpPoolConnections,omitempty"`
RequestTimeout *int `json:"httpRequestTimeout,omitempty"`
CaCert *string `json:"caCert,omitempty"`
MaxResults int `json:"maxResults,omitempty"`
ProxyURL *string `json:"proxyUrl,omitempty"`
}
func assignDefaultValues(host string) (InfobloxConfig, error) {
port := 443
view := "default"
poolConnections := 10
requestTimeout := 60
version := "2.10"
return InfobloxConfig{
Host: &host,
Port: &port,
View: &view,
PoolConnections: &poolConnections,
RequestTimeout: &requestTimeout,
Version: &version,
}, nil
}
// NewDNSClient creates a new dns client based on the Infoblox config provided
func NewDNSClient(ctx context.Context, username string, password string, host string) (DNSClient, error) {
infobloxConfig, err := assignDefaultValues(host)
if err != nil {
fmt.Println(err)
}
// define hostConfig
hostConfig := ibclient.HostConfig{
Host: *infobloxConfig.Host,
Port: strconv.Itoa(*infobloxConfig.Port),
Version: *infobloxConfig.Version,
Username: username,
Password: password,
}
// debug logger
raw.LogDetails(fmt.Sprintf("%+v", hostConfig))
verify := "true"
// verify := "false"
if infobloxConfig.SSLVerify != nil {
verify = strconv.FormatBool(*infobloxConfig.SSLVerify)
}
if infobloxConfig.CaCert != nil && verify == "true" {
tmpfile, err := ioutil.TempFile("", "cacert")
if err != nil {
return nil, fmt.Errorf("cannot create temporary file for cacert: %w", err)
}
defer os.Remove(tmpfile.Name())
if _, err := tmpfile.Write([]byte(*infobloxConfig.CaCert)); err != nil {
return nil, fmt.Errorf("cannot write temporary file for cacert: %w", err)
}
if err := tmpfile.Close(); err != nil {
return nil, fmt.Errorf("cannot close temporary file for cacert: %w", err)
}
verify = tmpfile.Name()
}
// define transportConfig
transportConfig := ibclient.NewTransportConfig(verify, *infobloxConfig.RequestTimeout, *infobloxConfig.PoolConnections)
var requestBuilder ibclient.HttpRequestBuilder = &ibclient.WapiRequestBuilder{}
dns_client, err := ibclient.NewConnector(hostConfig, transportConfig, requestBuilder, &ibclient.WapiHttpRequestor{})
if err != nil {
fmt.Println(err)
}
// todo: set correct type for dns_client to create dns_object
// dns_object := ibclient.CreateObject(dns_client.(ibclient.IBObject))
return &dnsClient{
client: dns_client,
}, nil
}
// get DNS client from secret reference
// func (c *dnsClient) NewDNSClientFromSecretRef(ctx context.Context, cl client.Client, secretRef corev1.SecretReference) (DNSClient, error) {
func NewDNSClientFromSecretRef(ctx context.Context, c client.Client, secretRef corev1.SecretReference) (DNSClient, error) {
secret, err := extensionscontroller.GetSecretByReference(ctx, c, &secretRef)
if err != nil {
return nil, err
}
// debug statements
runtimelog.SetLogger(logger.ZapLogger(false))
username, ok := secret.Data["USERNAME"]
if !ok {
return nil, fmt.Errorf("no username found")
}
password, ok := secret.Data["PASSWORD"]
if !ok {
return nil, fmt.Errorf("no password found")
}
// placeholder for host details
host, ok := secret.Data["HOST"]
if !ok {
return nil, fmt.Errorf("no host details found")
}
// debug string
debug_str := "dnsclient_secretref " + string(username) + " " + string(password) + " " + string(host)
runtimelog.Log.Error(errLog, debug_str)
return NewDNSClient(ctx, string(username), string(password), string(host))
}
// GetManagedZones returns a map of all managed zone DNS names mapped to their IDs, composed of the project ID and
// their user assigned resource names.
func (c *dnsClient) GetManagedZones(ctx context.Context) (map[string]string, error) {
conn := c.client.(*ibclient.Connector)
rt := ibclient.NewZoneAuth(ibclient.ZoneAuth{})
urlStr := conn.RequestBuilder.BuildUrl(ibclient.GET, rt.ObjectType(), "", rt.ReturnFields(), &ibclient.QueryParams{})
req, err := http.NewRequest("GET", urlStr, new(bytes.Buffer))
if err != nil {
fmt.Println(err)
}
// debug: print urlstring
runtimelog.SetLogger(logger.ZapLogger(false))
runtimelog.Log.Error(errLog, "get_managed_zones "+urlStr+" "+conn.HostConfig.Username+" "+conn.HostConfig.Password)
// logger debug: using functions
// raw.LogDetails("Get Managed Zones: func: " + urlStr + " "+ conn.HostConfig.Username, conn.HostConfig.Password)
req.Header.Set("Content-Type", "application/json")
req.SetBasicAuth(conn.HostConfig.Username, conn.HostConfig.Password)
resp, err := conn.Requestor.SendRequest(req)
if err != nil {
fmt.Println(err)
}
rs := []ibclient.ZoneAuth{}
err = json.Unmarshal(resp, &rs)
if err != nil {
fmt.Println(err)
}
ZoneList := make(map[string]string)
for _, zone := range rs {
// zone_list = append(zone_list, zone.Fqdn)
ZoneList[zone.Ref] = zone.Fqdn
}
return ZoneList, nil
}
// CreateOrUpdateRecordSet creates or updates the resource recordset with the given name, record type, rrdatas, and ttl
// in the managed zone with the given name or ID.
func (c *dnsClient) CreateOrUpdateRecordSet(ctx context.Context, view, zone, name, record_type string, values []string, ttl int64) error {
records, err := c.GetRecordSet(zone, record_type)
if err != nil {
return err
}
for _, r := range records {
if r.GetDNSName() == name {
err_del := c.DeleteRecord(r.(raw.Record), zone)
if err_del != nil {
return err_del
}
}
}
for _, value := range values {
_, err := c.createRecord(name, view, value, ttl, record_type)
if err != nil {
return err
}
}
return err
}
// DeleteRecordSet deletes the resource recordset with the given name and record type
// in the managed zone with the given name or ID.
func (c *dnsClient) DeleteRecordSet(ctx context.Context, zone, name, record_type string) error {
records, err := c.GetRecordSet(zone, record_type)
if err != nil {
return err
}
for _, rec := range records {
if rec.GetId() != "" && rec.GetDNSName() == name {
err := c.DeleteRecord(rec.(raw.Record), zone)
if err != nil {
return err
}
}
}
return nil
}
// create DNS record for the Infoblox DDI setup
func (c *dnsClient) createRecord(name string, view string, value string, ttl int64, record_type string) (string, error) {
var record string
var err error
var rec ibclient.IBObject
switch record_type {
case raw.Type_A:
rec = ibclient.NewRecordA(view, "", name, value, uint32(ttl), false, "", nil, "")
case raw.Type_AAAA:
rec = ibclient.NewRecordAAAA(view, name, value, false, uint32(ttl), "", nil, "")
case raw.Type_CNAME:
rec = ibclient.NewRecordCNAME(view, value, name, true, uint32(ttl), "", nil, "")
case raw.Type_TXT:
rec = ibclient.NewRecordTXT(ibclient.RecordTXT{
Name: name,
View: view,
Text: value,
})
}
record, err = c.client.CreateObject(rec)
if err != nil {
return "", err
}
return record, nil
}
func (c *dnsClient) DeleteRecord(record raw.Record, zone string) error {
_, err := c.client.DeleteObject(record.GetId())
if err != nil {
return err
}
return nil
}
func (c *dnsClient) GetRecordSet(zone string, recordType string) (RecordSet, error) {
results := c.client.(*ibclient.Connector)
if recordType != raw.Type_TXT && recordType != raw.Type_A {
return nil, fmt.Errorf("record type %s not supported for GetRecord", recordType)
}
execRequest := func(forceProxy bool, zone string, recordType string) ([]byte, error) {
record_map := make(map[string]string)
record_map["zone"] = zone
query_params := ibclient.NewQueryParams(false, record_map)
var rec ibclient.IBObject
switch recordType {
case "A":
rec = ibclient.NewEmptyRecordA()
case "TXT":
rec = ibclient.NewRecordTXT(ibclient.RecordTXT{})
}
urlStr := results.RequestBuilder.BuildUrl(ibclient.GET, rec.ObjectType(), "", nil, query_params)
if forceProxy {
urlStr += "&_proxy_search=GM"
}
req, err := http.NewRequest("GET", urlStr, new(bytes.Buffer))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.SetBasicAuth(results.HostConfig.Username, results.HostConfig.Password)
return results.Requestor.SendRequest(req)
}
resp, err := execRequest(false, zone, recordType)
if err != nil {
// Forcing the request to redirect to Grid Master by making forcedProxy=true
resp, err = execRequest(true, zone, recordType)
}
if err != nil {
return nil, err
}
rs := []raw.RecordTXT{}
err = json.Unmarshal(resp, &rs)
if err != nil {
return nil, err
}
rs2 := RecordSet{}
for _, r := range rs {
rs2 = append(rs2, r.Copy())
}
return rs2, nil
}