forked from cert-manager/webhook-example
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvariomediaclient_api2019.go
387 lines (327 loc) · 12.4 KB
/
variomediaclient_api2019.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
// client implementation for Variomedia API, 2019+ version (https://api.variomedia.de/docs/)
//
// Written by Jens-Uwe Mozdzen <[email protected]>
//
// Licensed under LGPL v3
//
// Entry points:
// client = NewvariomediaClient( apikey)
// - create new instance of API client
// in:
// apikey - customer-specific API key issued by Variomedia
// returns:
// client object
//
//
// client.UpdateTxtRecord(&domain, &entry, Key, ttl)
// - update TXT record
// in:
// domain - DNS domain
// entry - host label
// key - valus of TXT record
// ttl - TTL of record
// returns:
// variomediaDNSEntryURL - the URL of the resulting DNS entry
//
// client.DeleteTxtRecord(&domain, &entry)
// - delete TXT record for entry/domain
// in:
// url - DNS entry's URL
// ttl - TTL of record
// returns:
// -
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"k8s.io/klog/v2"
)
const (
variomediaLiveDnsBaseUrl = "https://api.variomedia.de/dns-records"
statusLookupDelay = 2 * time.Second
)
type variomediaClient struct {
apiKey string
}
type variomediaDnsAttributes struct {
RecordType string `json:"record_type"`
Name string `json:"name"`
Domain string `json:"domain"`
Data string `json:"data"`
Ttl int `json:"ttl"`
} // variomediaDnsAttributes
type variomediaData struct {
RequestType string `json:"type"`
RequestAttr variomediaDnsAttributes `json:"attributes"`
} // variomediaData
type variomediaRequest struct {
variomediaData `json:"data"`
} // variomediaRequest
type variomediaJobData struct {
Type string `json:"type"`
Id string `json:"id"`
Attributes map[string]string `json:"attributes"`
Links map[string]string `json:"links"`
} // variomediaJobData
type variomediaResponse struct {
Data variomediaJobData `json:"data"`
Links map[string]string `json:"links"`
} // variomediaRequest
// NewvariomediaClient()
// create new instance of Variomedia client
func NewvariomediaClient(apiKey string) *variomediaClient {
klog.V(4).InfoS("NewvariomediaClient() called")
klog.V(5).InfoS("parameters", "API key", apiKey)
klog.V(4).InfoS("NewvariomediaClient() finished")
return &variomediaClient{
apiKey: apiKey,
}
}
// client.UpdateTxtRecord(&domain, &entry, Key, ttl)
// - create or update TXT record
// in:
// domain - DNS domain
// entry - host label
// key - valus of TXT record
// ttl - TTL of record
// returns:
// variomediaDNSEntryURL - the URL of the resulting DNS entry
func (c *variomediaClient) UpdateTxtRecord(domain *string, name *string, value *string, ttl int) (string, error) {
klog.V(4).InfoS("UpdateTxtRecord() called")
klog.V(5).InfoS("parameters", "domain", *domain, "name", *name, "value", *value, "TTL", ttl)
var reqData variomediaRequest
reqData = variomediaRequest{ variomediaData{
RequestType: "dns-record",
RequestAttr: variomediaDnsAttributes{
RecordType: "TXT",
Name: *name,
Domain: *domain,
Data: *value,
Ttl: ttl,
},
},
}
// the actual request is encoded in JSON
body, err := json.Marshal( reqData)
if err != nil {
klog.ErrorS(err, "UpdateTxtRecord() finished with error")
return "", fmt.Errorf("cannot marshall to json: %v", err)
}
req, err := http.NewRequest("POST", variomediaLiveDnsBaseUrl, bytes.NewReader(body))
if err != nil {
klog.ErrorS(err, "UpdateTxtRecord() finished with error")
return "", err
}
// contact Variomedia and check the results
status, respData, err := c.doRequest(req, true)
if err != nil {
klog.ErrorS(err, "UpdateTxtRecord() finished with error")
return "", err
}
// have we hit the rate limit?
if status == http.StatusTooManyRequests {
klog.ErrorS( nil, "UpdateTxtRecord() finished with errori 'too many requests' reported by Variomedia")
return "", fmt.Errorf("Variomedia rate limit reached (HTTP code %d)", http.StatusTooManyRequests)
}
if status != http.StatusCreated && status != http.StatusOK && status != http.StatusAccepted {
klog.ErrorS(nil, "UpdateTxtRecord() finished with error reported by server", "status code", status)
return "", fmt.Errorf("failed creating TXT record: server reported status code %d", status)
}
// the request has succeeded - but is the job already finished?
// check the response for an according '' element
var reply variomediaResponse
err = json.Unmarshal( respData, &reply)
if err != nil {
klog.ErrorS(err, "UpdateTxtRecord() finished with error")
return "", fmt.Errorf("cannot unmarshall response to json: %v", err)
}
klog.V(5).InfoS( "HTTP finished", "JSON reply", reply)
// we give it 5 iterations to finish
loopcount := 5
for {
if reply.Data.Attributes[ "status"] == "pending" {
klog.V(2).InfoS( "DNS job still pending")
// inter-loop delay
time.Sleep( statusLookupDelay)
// re-fetch the job status
req, err := http.NewRequest("GET", reply.Data.Links[ "queue-job"], nil)
if err != nil {
klog.ErrorS(err, "UpdateTxtRecord() finished with error")
return "", err
}
// contact Variomedia and check the results
status, respData, err := c.doRequest(req, true)
if err != nil {
klog.ErrorS(err, "UpdateTxtRecord() finished with error")
return "", err
}
// have we hit the rate limit?
if status == http.StatusTooManyRequests {
klog.ErrorS( nil, "UpdateTxtRecord() finished with errori 'too many requests' reported by Variomedia")
return "", fmt.Errorf("Variomedia rate limit reached (HTTP code %d)", http.StatusTooManyRequests)
}
if status != http.StatusCreated && status != http.StatusOK && status != http.StatusAccepted {
klog.ErrorS(nil, "UpdateTxtRecord() finished with error reported by server", "status code", status)
return "", fmt.Errorf("failed creating TXT record: server reported status code %d", status)
}
// the request has succeeded - but is the job already finished?
// check the response for an according '' element
err = json.Unmarshal( respData, &reply)
if err != nil {
klog.ErrorS(err, "UpdateTxtRecord() finished with error")
return "", fmt.Errorf("cannot unmarshall response to json: %v", err)
}
klog.V(5).InfoS( "HTTP finished", "JSON reply", reply)
}
loopcount -= 1
if (reply.Data.Attributes[ "status"] == "done") {
klog.V(2).InfoS( "DNS job finished", "retries left", loopcount)
break;
}
if (loopcount == 0) {
klog.ErrorS(nil, "UpdateTxtRecord() finished with error: job timed out", "most recent status", reply.Data.Attributes[ "status"])
return "", fmt.Errorf("DNS update job timed out with most recent status '%s'", reply.Data.Attributes[ "status"])
}
} // emulated do until
klog.V(4).InfoS("UpdateTxtRecord() finished")
klog.V(5).InfoS("return values", "url", reply.Data.Links[ "dns-record"])
return reply.Data.Links[ "dns-record"], nil
} //func UpdateTxtRecord()
// client.DeleteTxtRecord(&domain, &entry, Key, ttl)
// - create or update TXT record
// in:
// url - DNS entry's URL
// ttl - TTL of record
// returns:
// -
func (c *variomediaClient) DeleteTxtRecord(url string, ttl int) error {
klog.V(4).InfoS("DeleteTxtRecord() called")
klog.V(5).InfoS("parameters", "url", url, "TTL", ttl)
// deleting a record happens by sending a HTTP "DELETE" request to the DNS entry's URL
req, err := http.NewRequest("DELETE", url, nil)
if err != nil {
klog.ErrorS(err, "DeleteTxtRecord() finished with error")
return err
}
// contact Variomedia and check the results
status, respData, err := c.doRequest(req, true)
if err != nil {
klog.ErrorS(err, "DeleteTxtRecord() finished with error")
return err
}
// have we hit the rate limit?
if status == http.StatusTooManyRequests {
klog.ErrorS( nil, "DeleteTxtRecord() finished with errori 'too many requests' reported by Variomedia")
return fmt.Errorf("Variomedia rate limit reached (HTTP code %d)", http.StatusTooManyRequests)
}
if status != http.StatusCreated && status != http.StatusOK && status != http.StatusAccepted {
klog.ErrorS(nil, "DeleteTxtRecord() finished with error reported by server", "status code", status)
return fmt.Errorf("failed deleting TXT record: %v", err)
}
// the request has succeeded - but is the job already finished?
// check the response for an according '' element
var reply variomediaResponse
err = json.Unmarshal( respData, &reply)
if err != nil {
klog.ErrorS(err, "DeleteTxtRecord() finished with error")
return fmt.Errorf("cannot unmarshall response to json: %v", err)
}
klog.V(5).InfoS( "HTTP finished", "JSON reply", reply)
// we give it 5 iterations to finish
loopcount := 5
for {
if reply.Data.Attributes[ "status"] == "pending" && status != http.StatusNotFound {
klog.V(2).InfoS( "DNS job still pending")
// inter-loop delay: two seconds
time.Sleep( statusLookupDelay)
// re-fetch the job status
req, err := http.NewRequest("GET", reply.Data.Links[ "queue-job"], nil)
if err != nil {
klog.ErrorS(err, "DeleteTxtRecord() finished with error")
return err
}
// contact Variomedia and check the results
status, respData, err := c.doRequest(req, true)
if err != nil {
klog.ErrorS(err, "DeleteTxtRecord() finished with error")
return err
}
// have we hit the rate limit?
if status == http.StatusTooManyRequests {
klog.ErrorS( nil, "DeleteTxtRecord() finished with errori 'too many requests' reported by Variomedia")
return fmt.Errorf("Variomedia rate limit reached (HTTP code %d)", http.StatusTooManyRequests)
}
if status != http.StatusCreated && status != http.StatusOK && status != http.StatusAccepted && status != http.StatusNotFound {
klog.ErrorS(nil, "DeleteTxtRecord() finished with error reported by server", "status code", status)
return fmt.Errorf("failed creating TXT record: %v", err)
}
// the request has succeeded - but is the job already finished?
// check the response for an according '' element
err = json.Unmarshal( respData, &reply)
if err != nil {
klog.ErrorS(err, "DeleteTxtRecord() finished with error")
return fmt.Errorf("cannot unmarshall response to json: %v", err)
}
klog.V(5).InfoS( "HTTP finished", "JSON reply", reply)
}
// 404 means "DNS record not found" (anymore) - we're fine with that, the record is gone
if status == http.StatusNotFound {
klog.V(4).InfoS("DeleteTxtRecord() finished because DNS record is gone", "retries left", loopcount)
return nil
}
loopcount -= 1
if (reply.Data.Attributes[ "status"] == "done") {
klog.V(2).InfoS( "DNS job finished", "retries left", loopcount)
break;
}
if (loopcount == 0) {
klog.ErrorS(nil, "DeleteTxtRecord() finished with error: job timed out", "most recent status", reply.Data.Attributes[ "status"])
return fmt.Errorf("DNS update job timed out with most recent status '%s'", reply.Data.Attributes[ "status"])
}
} // emulated do until
klog.V(4).InfoS("DeleteTxtRecord() finished")
return nil
} // func DeleteTxtRecord()
func (c *variomediaClient) variomediaRecordsUrl(domain string) string {
klog.V(4).InfoS("variomediaRecordsUrl() called")
klog.V(5).InfoS("parameters", "domain", domain)
urlpart := fmt.Sprintf("%s/dns-records", domain)
klog.V(4).InfoS("variomediaRecordsUrl() finished")
klog.V(5).InfoS("return values", "url part", urlpart)
return urlpart
}
func (c *variomediaClient) doRequest(req *http.Request, readResponseBody bool) (int, []byte, error) {
klog.V(4).InfoS("doRequest() called")
klog.V(5).InfoS("parameters", "request", req, "readResponseBody", readResponseBody)
// Variomedia uses headers for auth, request content type and to signal accepted API versions
req.Header.Set("Authorization", fmt.Sprintf("token %s", c.apiKey))
req.Header.Set("Content-Type", "application/vnd.api+json")
req.Header.Set("Accept", "application/vnd.variomedia.v1+json")
client := http.Client{
Timeout: 30 * time.Second,
}
res, err := client.Do(req)
if err != nil {
klog.ErrorS(err, "doRequest() finished with error")
return 0, nil, err
}
klog.V(5).InfoS( "HTTP request", "response", res)
// check for proper returns
if (res.StatusCode == http.StatusOK || res.StatusCode == http.StatusAccepted) && readResponseBody {
data, err := ioutil.ReadAll(res.Body)
if err != nil {
klog.ErrorS(err, "HTTP request finished with error")
return 0, nil, err
}
klog.V(4).InfoS( "HTTP request succeeded", "status code", res.StatusCode)
klog.V(5).InfoS( "HTTP request result", "data", data)
return res.StatusCode, data, nil
}
klog.V(4).InfoS("doRequest() finished")
klog.V(5).InfoS("return values", "status code", res.StatusCode)
return res.StatusCode, nil, nil
}