forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
367 lines (314 loc) · 8.88 KB
/
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
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
package powerdns
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/hashicorp/go-cleanhttp"
)
type Client struct {
ServerUrl string // Location of PowerDNS server to use
ApiKey string // REST API Static authentication key
ApiVersion int // API version to use
Http *http.Client
}
// NewClient returns a new PowerDNS client
func NewClient(serverUrl string, apiKey string) (*Client, error) {
client := Client{
ServerUrl: serverUrl,
ApiKey: apiKey,
Http: cleanhttp.DefaultClient(),
}
var err error
client.ApiVersion, err = client.detectApiVersion()
if err != nil {
return nil, err
}
return &client, nil
}
// Creates a new request with necessary headers
func (c *Client) newRequest(method string, endpoint string, body []byte) (*http.Request, error) {
var urlStr string
if c.ApiVersion > 0 {
urlStr = c.ServerUrl + "/api/v" + strconv.Itoa(c.ApiVersion) + endpoint
} else {
urlStr = c.ServerUrl + endpoint
}
url, err := url.Parse(urlStr)
if err != nil {
return nil, fmt.Errorf("Error during parsing request URL: %s", err)
}
var bodyReader io.Reader
if body != nil {
bodyReader = bytes.NewReader(body)
}
req, err := http.NewRequest(method, url.String(), bodyReader)
if err != nil {
return nil, fmt.Errorf("Error during creation of request: %s", err)
}
req.Header.Add("X-API-Key", c.ApiKey)
req.Header.Add("Accept", "application/json")
if method != "GET" {
req.Header.Add("Content-Type", "application/json")
}
return req, nil
}
type ZoneInfo struct {
Id string `json:"id"`
Name string `json:"name"`
URL string `json:"url"`
Kind string `json:"kind"`
DnsSec bool `json:"dnsssec"`
Serial int64 `json:"serial"`
Records []Record `json:"records,omitempty"`
ResourceRecordSets []ResourceRecordSet `json:"rrsets,omitempty"`
}
type Record struct {
Name string `json:"name"`
Type string `json:"type"`
Content string `json:"content"`
TTL int `json:"ttl"` // For API v0
Disabled bool `json:"disabled"`
}
type ResourceRecordSet struct {
Name string `json:"name"`
Type string `json:"type"`
ChangeType string `json:"changetype"`
TTL int `json:"ttl"` // For API v1
Records []Record `json:"records,omitempty"`
}
type zonePatchRequest struct {
RecordSets []ResourceRecordSet `json:"rrsets"`
}
type errorResponse struct {
ErrorMsg string `json:"error"`
}
const idSeparator string = ":::"
func (record *Record) Id() string {
return record.Name + idSeparator + record.Type
}
func (rrSet *ResourceRecordSet) Id() string {
return rrSet.Name + idSeparator + rrSet.Type
}
// Returns name and type of record or record set based on it's ID
func parseId(recId string) (string, string, error) {
s := strings.Split(recId, idSeparator)
if len(s) == 2 {
return s[0], s[1], nil
} else {
return "", "", fmt.Errorf("Unknown record ID format")
}
}
// Detects the API version in use on the server
// Uses int to represent the API version: 0 is the legacy AKA version 3.4 API
// Any other integer correlates with the same API version
func (client *Client) detectApiVersion() (int, error) {
req, err := client.newRequest("GET", "/api/v1/servers", nil)
if err != nil {
return -1, err
}
resp, err := client.Http.Do(req)
if err != nil {
return -1, err
}
defer resp.Body.Close()
if resp.StatusCode == 200 {
return 1, nil
} else {
return 0, nil
}
}
// Returns all Zones of server, without records
func (client *Client) ListZones() ([]ZoneInfo, error) {
req, err := client.newRequest("GET", "/servers/localhost/zones", nil)
if err != nil {
return nil, err
}
resp, err := client.Http.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var zoneInfos []ZoneInfo
err = json.NewDecoder(resp.Body).Decode(&zoneInfos)
if err != nil {
return nil, err
}
return zoneInfos, nil
}
// Returns all records in Zone
func (client *Client) ListRecords(zone string) ([]Record, error) {
req, err := client.newRequest("GET", fmt.Sprintf("/servers/localhost/zones/%s", zone), nil)
if err != nil {
return nil, err
}
resp, err := client.Http.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
zoneInfo := new(ZoneInfo)
err = json.NewDecoder(resp.Body).Decode(zoneInfo)
if err != nil {
return nil, err
}
records := zoneInfo.Records
// Convert the API v1 response to v0 record structure
for _, rrs := range zoneInfo.ResourceRecordSets {
for _, record := range rrs.Records {
records = append(records, Record{
Name: rrs.Name,
Type: rrs.Type,
Content: record.Content,
TTL: rrs.TTL,
})
}
}
return records, nil
}
// Returns only records of specified name and type
func (client *Client) ListRecordsInRRSet(zone string, name string, tpe string) ([]Record, error) {
allRecords, err := client.ListRecords(zone)
if err != nil {
return nil, err
}
records := make([]Record, 0, 10)
for _, r := range allRecords {
if r.Name == name && r.Type == tpe {
records = append(records, r)
}
}
return records, nil
}
func (client *Client) ListRecordsByID(zone string, recId string) ([]Record, error) {
name, tpe, err := parseId(recId)
if err != nil {
return nil, err
} else {
return client.ListRecordsInRRSet(zone, name, tpe)
}
}
// Checks if requested record exists in Zone
func (client *Client) RecordExists(zone string, name string, tpe string) (bool, error) {
allRecords, err := client.ListRecords(zone)
if err != nil {
return false, err
}
for _, record := range allRecords {
if record.Name == name && record.Type == tpe {
return true, nil
}
}
return false, nil
}
// Checks if requested record exists in Zone by it's ID
func (client *Client) RecordExistsByID(zone string, recId string) (bool, error) {
name, tpe, err := parseId(recId)
if err != nil {
return false, err
} else {
return client.RecordExists(zone, name, tpe)
}
}
// Creates new record with single content entry
func (client *Client) CreateRecord(zone string, record Record) (string, error) {
reqBody, _ := json.Marshal(zonePatchRequest{
RecordSets: []ResourceRecordSet{
{
Name: record.Name,
Type: record.Type,
ChangeType: "REPLACE",
Records: []Record{record},
},
},
})
req, err := client.newRequest("PATCH", fmt.Sprintf("/servers/localhost/zones/%s", zone), reqBody)
if err != nil {
return "", err
}
resp, err := client.Http.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != 200 && resp.StatusCode != 204 {
errorResp := new(errorResponse)
if err = json.NewDecoder(resp.Body).Decode(errorResp); err != nil {
return "", fmt.Errorf("Error creating record: %s", record.Id())
} else {
return "", fmt.Errorf("Error creating record: %s, reason: %q", record.Id(), errorResp.ErrorMsg)
}
} else {
return record.Id(), nil
}
}
// Creates new record set in Zone
func (client *Client) ReplaceRecordSet(zone string, rrSet ResourceRecordSet) (string, error) {
rrSet.ChangeType = "REPLACE"
reqBody, _ := json.Marshal(zonePatchRequest{
RecordSets: []ResourceRecordSet{rrSet},
})
req, err := client.newRequest("PATCH", fmt.Sprintf("/servers/localhost/zones/%s", zone), reqBody)
if err != nil {
return "", err
}
resp, err := client.Http.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != 200 && resp.StatusCode != 204 {
errorResp := new(errorResponse)
if err = json.NewDecoder(resp.Body).Decode(errorResp); err != nil {
return "", fmt.Errorf("Error creating record set: %s", rrSet.Id())
} else {
return "", fmt.Errorf("Error creating record set: %s, reason: %q", rrSet.Id(), errorResp.ErrorMsg)
}
} else {
return rrSet.Id(), nil
}
}
// Deletes record set from Zone
func (client *Client) DeleteRecordSet(zone string, name string, tpe string) error {
reqBody, _ := json.Marshal(zonePatchRequest{
RecordSets: []ResourceRecordSet{
{
Name: name,
Type: tpe,
ChangeType: "DELETE",
},
},
})
req, err := client.newRequest("PATCH", fmt.Sprintf("/servers/localhost/zones/%s", zone), reqBody)
if err != nil {
return err
}
resp, err := client.Http.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 && resp.StatusCode != 204 {
errorResp := new(errorResponse)
if err = json.NewDecoder(resp.Body).Decode(errorResp); err != nil {
return fmt.Errorf("Error deleting record: %s %s", name, tpe)
} else {
return fmt.Errorf("Error deleting record: %s %s, reason: %q", name, tpe, errorResp.ErrorMsg)
}
} else {
return nil
}
}
// Deletes record from Zone by it's ID
func (client *Client) DeleteRecordSetByID(zone string, recId string) error {
name, tpe, err := parseId(recId)
if err != nil {
return err
} else {
return client.DeleteRecordSet(zone, name, tpe)
}
}