forked from nutcr4cker/terraform-kea-dhcp4
-
Notifications
You must be signed in to change notification settings - Fork 4
/
config.go
484 lines (444 loc) · 16.8 KB
/
config.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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"sync"
)
//SERVICE define which IP version we are use (currently only dhcp4 supported)
var SERVICE []string = []string{"dhcp4"}
// REST API response codes
const (
KEA_SUCCESS int = iota
KEA_ERROR
KEA_UNSUPPORTED
KEA_EMPTY
)
type configReq struct {
Command string `json:"command"`
Service []string `json:"service"`
}
type configSet struct {
Command string `json:"command"`
Service []string `json:"service"`
Arguments Arguments `json:"arguments"`
}
//NestedElem elements in root
type NestedElem struct {
Arguments Arguments `json:"arguments"`
Result int `json:"result"`
}
//Arguments structure
type Arguments struct {
Dhcp4 Dhcp4 `json:"Dhcp4"`
}
//Response structure
type Response struct {
Result int `json:"result"`
Text string `json:"text"`
}
//Dhcp4 structure
type Dhcp4 struct {
Authoritative bool `json:"authoritative"`
BootFileName string `json:"boot-file-name"`
CalculateTeeTimes bool `json:"calculate-tee-times"`
ClientClasses []ClientClasses `json:"client-classes,omitempty"`
ControlSocket ControlSocket `json:"control-socket"`
DDNSGeneratedPrefix string `json:"ddns-generated-prefix,omitempty"`
DDNSOverrideClientUpdates bool `json:"ddns-override-client-update,omitempty"`
DDNSOverrideNoUpdate bool `json:"ddns-override-no-update,omitempty"`
DDNSQualifyingSuffix string `json:"ddns-qualifying-suffix,omitempty"`
DDNSReplaceClientName string `json:"ddns-replace-client-name,omitempty"`
DDNSSendUpdates bool `json:"ddns-send-updates,omitempty"`
DeclineProbationPeriod int `json:"decline-probation-period"`
DHCPDDNS DHCPDDNS `json:"dhcp-ddns"`
DHCPQueueControl DHCPQueueControl `json:"dhcp-queue-control"`
DHCP4o6Port int `json:"dhcp4o6-port"`
EchoClientId bool `json:"echo-client-id"`
ExpiredLeasesProcessing ExpiredLeasesProcessing `json:"expired-leases-processing"`
HooksLibraries []HooksLibraries `json:"hooks-libraries"`
HostReservationIdentifiers []string `json:"host-reservation-identifiers"`
InterfacesConfig InterfacesConfig `json:"interfaces-config"`
LeaseDatabase LeaseDatabase `json:"lease-database"`
Loggers []Loggers `json:"loggers"`
MatchClientId bool `json:"match-client-id"`
NextServer string `json:"next-server"`
OptionData []OptionData `json:"option-data"`
OptionDef interface{} `json:"option-def,omitempty"` // Not implemented
RebindTimer int `json:"rebind-timer"`
RenewTimer int `json:"renew-timer"`
ReservationMode string `json:"reservation-mode,omitempty"`
SanityChecks SanityChecks `json:"sanity-checks"`
ServerHostname string `json:"server-hostname"`
ServerTag string `json:"server-tag"`
SharedNetworks interface{} `json:"shared-networks,omitempty"` // Not implemented
Subnet4 []Subnet4 `json:"subnet4"`
T1Percent float64 `json:"t1-percent"`
T2Percent float64 `json:"t2-percent"`
ValidLifetime int `json:"valid-lifetime"`
}
//ClientClasses structure
type ClientClasses struct {
Name string `json:"name"`
OptionData []OptionData `json:"option-data"`
Test string `json:"test"`
}
//ControlSocket structure
type ControlSocket struct {
SocketName string `json:"socket-name"`
SocketType string `json:"socket-type"`
}
//DHCPDDNS structure
type DHCPDDNS struct {
EnableUpdates bool `json:"enable-updates"`
GeneratedPrefix string `json:"generated-prefix"`
MaxQueueSize int `json:"max-queue-size"`
NCRFormat string `json:"ncr-format"`
NCRProtocol string `json:"ncr-protocol"`
OverrideClientUpdate bool `json:"override-client-update"`
OverrideNoUpdate bool `json:"override-no-update"`
QualifyingSuffix string `json:"qualifying-suffix"`
ReplaceClientName string `json:"replace-client-name"`
SenderIP string `json:"sender-ip"`
SenderPort int `json:"sender-port"`
ServerIP string `json:"server-ip"`
ServerPort int `json:"server-port"`
}
//DHCPQueueControl structure
type DHCPQueueControl struct {
Capacity int `json:"capacity"`
EnableQueue bool `json:"enable-queue"`
QueueType string `json:"queue-type"`
}
//ExpiredLeasesProcessing structure
type ExpiredLeasesProcessing struct {
FlushReclaimedTimerWaitTime int `json:"flush-reclaimed-timer-wait-time"`
HoldReclaimedTime int `json:"hold-reclaimed-time"`
MaxReclaimLeases int `json:"max-reclaim-leases"`
MaxReclaimTime int `json:"max-reclaim-time"`
ReclaimTimerWaitTime int `json:"reclaim-timer-wait-time"`
UnwarnedReclaimCycles int `json:"unwarned-reclaim-cycles"`
}
//HooksLibraries structure
type HooksLibraries struct {
Library string `json:"library"`
}
//InterfacesConfig structure
type InterfacesConfig struct {
Interfaces []string `json:"interfaces"`
ReDetect bool `json:"re-detect"`
}
//LeaseDatabase structure
type LeaseDatabase struct {
LFCInterval int `json:"lfc-interval"`
Name string `json:"name"`
Persist bool `json:"persist"`
Type string `json:"type"`
}
//Loggers structure
type Loggers struct {
DebugLevel int `json:"debuglevel"`
Name string `json:"name"`
OutputOptions []OutputOptions `json:"output_options"`
Severity string `json:"severity"`
}
//OptionData structure
type OptionData struct {
AlwaysSend bool `json:"always-send"`
Code int `json:"code,omitempty"`
CSVFormat bool `json:"csv-format"`
Data string `json:"data"`
Name string `json:"name,omitempty"`
Space string `json:"space"`
}
//OutputOptions structure
type OutputOptions struct {
Output string `json:"output"`
}
//Pools structure
type Pools struct {
OptionData []OptionData `json:"option-data"`
Pool string `json:"pool"`
}
//SanityChecks structure
type SanityChecks struct {
LeaseChecks string `json:"lease-checks"`
}
//Subnet4 structure
type Subnet4 struct {
FourOverSixInterface string `json:"4o6-interface"`
FourOverSixInterfaceId string `json:"4o6-interface-id"`
FourOverSixSubnet string `json:"4o6-subnet"`
Authoritative bool `json:"authoritative"`
CalculateTeeTimes bool `json:"calculate-tee-times"`
Id int `json:"id"`
MatchClientId bool `json:"match-client-id"`
NextServer string `json:"next-server"`
OptionData []OptionData `json:"option-data"`
Pools []Pools `json:"pools"`
RebindTimer int `json:"rebind-timer"`
Relay interface{} `json:"relay"`
RenewTimer int `json:"renew-timer"`
ReservationMode string `json:"reservation-mode,omitempty"`
Reservations []Reservations `json:"reservations"`
Subnet string `json:"subnet"`
T1Percent float64 `json:"t1-percent"`
T2Percent float64 `json:"t2-percent"`
ValidLifetime int `json:"valid-lifetime"`
}
// Relay structure
type Relay struct {
IPAddresses interface{} `json:"ip-addresses"` // Not implemented
}
//Reservations structure
type Reservations struct {
BootFileName string `json:"boot-file-name"`
ClientClasses []string `json:"client-classes"`
Hostname string `json:"hostname"`
HWAddress string `json:"hw-address"`
IPAddress string `json:"ip-address"`
NextServer string `json:"next-server"`
OptionData []OptionData `json:"option-data"`
ServerHostname string `json:"server-hostname"`
}
// Config struct for provider
type Config struct {
Server string
Username string
Password string
Configfile string
}
// Client for connections
type Client struct {
Config *Config
currentConfig []NestedElem
httpClient *http.Client
lock sync.Mutex
}
func check(e error) {
if e != nil {
log.Fatal(e)
panic(e)
}
}
//Client In go (c *Config) means this is method assosieted to struct Config
func (c *Config) Client() (*Client, error) {
log.Println("[INFO] Configuring kea-api client")
htclient := &http.Client{}
var data []byte
services := []string{"dhcp4"}
jsonStr := configReq{Command: "config-get", Service: services}
b, err := json.Marshal(jsonStr)
check(err)
req, err := http.NewRequest("POST", c.Server, bytes.NewBuffer(b))
check(err)
req.SetBasicAuth(c.Username, c.Password)
req.Header.Set("Content-Type", "application/json")
resp, err := htclient.Do(req)
if err != nil {
log.Fatalf("The HTTP request failed with error %s\n", err)
return nil, err
} else if resp.StatusCode >= 400 {
data, _ = ioutil.ReadAll(resp.Body)
errtext := fmt.Sprintf("The HTTP request failed with code %d, response was %s\n", resp.StatusCode, data)
log.Print(errtext)
return nil, fmt.Errorf(errtext)
} else {
data, _ = ioutil.ReadAll(resp.Body)
var resp []Response
err := json.Unmarshal(data, &resp)
if err != nil {
log.Printf("[Error] Could not unmarshal API response: %s\n", err)
return nil, err
}
if resp[0].Result != KEA_SUCCESS && resp[0].Result != KEA_EMPTY {
log.Printf("[Error] The HTTP request failed with error %s\n", resp[0].Text)
return nil, fmt.Errorf(resp[0].Text)
}
log.Printf("[INFO] %s\n", string(data))
}
log.Println("[INFO] Terminating GET_CONF application...")
var m []NestedElem
err = json.Unmarshal(data, &m)
check(err)
client := &Client{
Config: c,
currentConfig: m,
httpClient: htclient,
}
return client, nil
}
//ReadLease method to check if lease exists in kea-dhcpd4
func (c *Client) ReadLease(r Reservations) bool {
for _, reservation := range c.currentConfig[0].Arguments.Dhcp4.Subnet4[0].Reservations {
if reservation.Hostname == r.Hostname {
log.Printf("[DEBUG] read function found the host\n")
return true
}
}
log.Printf("[DEBUG] read function cannot find the host\n")
return false
}
//NewLease method to create new lease fot kea-dhcpd4 works!
func (c *Client) NewLease(r Reservations) error {
var data []byte
c.currentConfig[0].Arguments.Dhcp4.Subnet4[0].Reservations = append(c.currentConfig[0].Arguments.Dhcp4.Subnet4[0].Reservations, r)
jsonSet := configSet{Command: "config-set", Service: SERVICE, Arguments: c.currentConfig[0].Arguments}
enc, err := json.Marshal(jsonSet)
check(err)
log.Printf("[DEBUG] Generated JSON: %s\n", enc)
req, err := http.NewRequest("POST", c.Config.Server, bytes.NewBuffer(enc))
check(err)
req.SetBasicAuth(c.Config.Username, c.Config.Password)
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
log.Printf("[Error] The HTTP request failed with error %s\n", err)
return err
} else if resp.StatusCode >= 400 {
data, _ = ioutil.ReadAll(resp.Body)
errtext := fmt.Sprintf("The HTTP request failed with code %d, response was %s\n", resp.StatusCode, data)
log.Print(errtext)
return fmt.Errorf(errtext)
} else {
data, _ = ioutil.ReadAll(resp.Body)
var resp []Response
err := json.Unmarshal(data, &resp)
if err != nil {
log.Printf("[Error] Could not unmarshal API response: %s\n", err)
return err
}
if resp[0].Result != KEA_SUCCESS && resp[0].Result != KEA_EMPTY {
log.Printf("[Error] The HTTP request failed with error %s\n", resp[0].Text)
return fmt.Errorf(resp[0].Text)
}
c.SaveConfig()
log.Printf("[INFO] New lease shoud be added.. %s\n", string(data))
}
return nil
}
// UpdateLease resource works!
func (c *Client) UpdateLease(r Reservations) error {
var data []byte
for index, reservation := range c.currentConfig[0].Arguments.Dhcp4.Subnet4[0].Reservations {
if reservation.Hostname == r.Hostname {
c.currentConfig[0].Arguments.Dhcp4.Subnet4[0].Reservations[index] = r
}
}
jsonSet := configSet{Command: "config-set", Service: SERVICE, Arguments: c.currentConfig[0].Arguments}
enc, err := json.Marshal(jsonSet)
check(err)
log.Printf("[DEBUG] Generated JSON: %s\n", enc)
req, err := http.NewRequest("POST", c.Config.Server, bytes.NewBuffer(enc))
check(err)
req.SetBasicAuth(c.Config.Username, c.Config.Password)
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
log.Printf("[Error] The HTTP request failed with error %s\n", err)
return err
} else if resp.StatusCode >= 400 {
data, _ = ioutil.ReadAll(resp.Body)
errtext := fmt.Sprintf("The HTTP request failed with code %d, response was %s\n", resp.StatusCode, data)
log.Print(errtext)
return fmt.Errorf(errtext)
} else {
data, _ = ioutil.ReadAll(resp.Body)
var resp []Response
err := json.Unmarshal(data, &resp)
if err != nil {
log.Printf("[Error] Could not unmarshal API response: %s\n", err)
return err
}
if resp[0].Result != KEA_SUCCESS && resp[0].Result != KEA_EMPTY {
log.Printf("[Error] The HTTP request failed with error %s\n", resp[0].Text)
return fmt.Errorf(resp[0].Text)
}
c.SaveConfig()
log.Printf("[INFO] The lease shoud be updated.. %s\n", string(data))
}
return nil
}
// DeleteLease resource
func (c *Client) DeleteLease(r Reservations) error {
var data []byte
filteredReservations := make([]Reservations, 0)
for _, reservation := range c.currentConfig[0].Arguments.Dhcp4.Subnet4[0].Reservations {
if reservation.Hostname != r.Hostname {
filteredReservations = append(filteredReservations, reservation)
}
}
c.currentConfig[0].Arguments.Dhcp4.Subnet4[0].Reservations = filteredReservations
jsonSet := configSet{Command: "config-set", Service: SERVICE, Arguments: c.currentConfig[0].Arguments}
enc, err := json.Marshal(jsonSet)
check(err)
log.Printf("[DEBUG] Generated JSON: %s\n", enc)
req, err := http.NewRequest("POST", c.Config.Server, bytes.NewBuffer(enc))
check(err)
req.SetBasicAuth(c.Config.Username, c.Config.Password)
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
log.Printf("[Error] The HTTP request failed with error %s\n", err)
return err
} else if resp.StatusCode >= 400 {
data, _ = ioutil.ReadAll(resp.Body)
errtext := fmt.Sprintf("The HTTP request failed with code %d, response was %s\n", resp.StatusCode, data)
log.Print(errtext)
return fmt.Errorf(errtext)
} else {
data, _ = ioutil.ReadAll(resp.Body)
var resp []Response
err := json.Unmarshal(data, &resp)
if err != nil {
log.Printf("[Error] Could not unmarshal API response: %s\n", err)
return err
}
if resp[0].Result != KEA_SUCCESS && resp[0].Result != KEA_EMPTY {
log.Printf("[Error] The HTTP request failed with error %s\n", resp[0].Text)
return fmt.Errorf(resp[0].Text)
}
c.SaveConfig()
log.Printf("[INFO] The lease should be deleted if existed.. %s\n", string(data))
}
return nil
}
//SaveConfig method to save a config file for kea-dhcpd4
func (c *Client) SaveConfig() error {
var data []byte
jsonWrite := "{ \"command\": \"config-write\", \"service\": [ \"dhcp4\" ], \"arguments\":{\"filename\":\"" + c.Config.Configfile + "\"} }"
buff := new(bytes.Buffer)
json.NewEncoder(buff).Encode(jsonWrite)
req, err := http.NewRequest("POST", c.Config.Server, strings.NewReader(jsonWrite))
check(err)
req.SetBasicAuth(c.Config.Username, c.Config.Password)
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
log.Printf("[Error] The HTTP request failed with error %s\n", err)
return err
} else if resp.StatusCode >= 400 {
data, _ = ioutil.ReadAll(resp.Body)
errtext := fmt.Sprintf("The HTTP request failed with code %d, response was %s\n", resp.StatusCode, data)
log.Print(errtext)
return fmt.Errorf(errtext)
} else {
data, _ = ioutil.ReadAll(resp.Body)
var resp []Response
err := json.Unmarshal(data, &resp)
if err != nil {
log.Printf("[Error] Could not unmarshal API response: %s\n", err)
return err
}
if resp[0].Result != KEA_SUCCESS && resp[0].Result != KEA_EMPTY {
log.Printf("[Error] The HTTP request failed with error %s\n", resp[0].Text)
return fmt.Errorf(resp[0].Text)
}
log.Printf("[INFO] Configuration file should be saved.. %s\n", string(data))
}
return nil
}