-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcommand_update_zone.go
More file actions
239 lines (213 loc) · 6.64 KB
/
Copy pathcommand_update_zone.go
File metadata and controls
239 lines (213 loc) · 6.64 KB
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
// Copyright 2018. Akamai Technologies, Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/dns"
"github.com/akamai/cli-dns/edgegrid"
"github.com/fatih/color"
"github.com/urfave/cli"
)
func cmdUpdateZone(c *cli.Context) error {
// Initialize context and Edgegrid session
ctx := context.Background()
sess, err := edgegrid.InitializeSession(c)
if err != nil {
return failStep("Preparing zone", "Session initialization failed: %v", err)
}
ctx = edgegrid.WithSession(ctx, sess)
dnsClient := dns.Client(edgegrid.GetSession(ctx))
// Validate zonename argument
if c.NArg() == 0 {
return failStep("Preparing zone", "zonename is required")
}
zonename := c.Args().First()
// Check if the zone is an ALIAS zone
zoneResp, err := dnsClient.GetZone(ctx, dns.GetZoneRequest{
Zone: zonename,
})
if err != nil {
return failStep("Preparing zone", "Failed to retrieve zone information for %s. Error: %s", zonename, err)
}
if strings.EqualFold(zoneResp.Type, "ALIAS") {
return failStep("Preparing zone", "Zone %s is an ALIAS zone and does not have recordsets", zonename)
}
fmt.Printf("Preparing zone ... %s\n", color.GreenString("[OK]"))
var (
inputPath string
outputPath string
)
var fileData []byte
if c.IsSet("file") {
inputPath = filepath.FromSlash(c.String("file"))
fileData, err = os.ReadFile(inputPath)
if err != nil {
return failStep("Preparing zone", "Failed to read input file: %v", err)
}
} else {
stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) != 0 {
return failStep("Preparing zone", "No input file or piped data provided")
}
fileData, err = io.ReadAll(os.Stdin)
if err != nil {
return failStep("Preparing zone", "Failed to read from STDIN: %v", err)
}
}
if c.IsSet("output") {
outputPath = filepath.FromSlash(c.String("output"))
}
// Handle master zone file upload if --dns flag is set
if c.Bool("dns") {
masterZoneFileData := string(fileData)
const httpMaxBody = 10 * 1024 * 1024
if len(masterZoneFileData) > httpMaxBody {
return failStep("Uploading Master Zone File", "Master Zone File size too large to process")
}
err = dnsClient.PostMasterZoneFile(ctx, dns.PostMasterZoneFileRequest{
Zone: zonename,
FileData: masterZoneFileData,
})
if err != nil {
return failStep("Uploading Master Zone File", "Master Zone File upload failed: %v", err)
}
fmt.Printf("Uploading Master Zone File ... %s\n", color.GreenString("[OK]"))
return nil
}
// Parse input JSON for recordsets
inputRecordSets := &dns.RecordSets{}
err = json.Unmarshal(fileData, inputRecordSets)
if err != nil {
return failStep("Preparing zone", "Failed to parse JSON input file: %v", err)
}
// Prepare recordset update list and handle SOA record
var recordsetWorkList []dns.RecordSet
soaInSet := false
soaIndex := -1
if c.Bool("overwrite") {
recordsetWorkList = inputRecordSets.RecordSets
for i, rs := range recordsetWorkList {
if rs.Type == "SOA" {
soaInSet = true
soaIndex = i
break
}
}
} else {
fmt.Fprintf(os.Stderr, "Retrieving Existing Recordsets ... %s\n", color.GreenString("[OK]"))
existingResp, err := dnsClient.GetRecordSets(ctx, dns.GetRecordSetsRequest{
Zone: zonename,
QueryArgs: &dns.RecordSetQueryArgs{
ShowAll: true,
},
})
if err != nil {
return failStep("Retrieving Existing Recordsets", "Recordset list retrieval failed: %v", err)
}
recordsetWorkList = existingResp.RecordSets
for i, rs := range recordsetWorkList {
if rs.Type == "SOA" {
soaIndex = i
break
}
}
for _, updatedRS := range inputRecordSets.RecordSets {
found := false
for i, existingRS := range recordsetWorkList {
if updatedRS.Name == existingRS.Name && updatedRS.Type == existingRS.Type {
recordsetWorkList[i] = updatedRS
found = true
break
}
}
if !found {
recordsetWorkList = append(recordsetWorkList, updatedRS)
}
if updatedRS.Type == "SOA" {
soaInSet = true
}
}
if !soaInSet && soaIndex >= 0 {
soaRec := &recordsetWorkList[soaIndex]
if len(soaRec.Rdata) > 0 {
soavals := strings.Fields(soaRec.Rdata[0])
if len(soavals) >= 3 {
serial, err := strconv.Atoi(soavals[2])
if err == nil {
serial++
soavals[2] = strconv.Itoa(serial)
soaRec.Rdata[0] = strings.Join(soavals, " ")
} else {
fmt.Fprintf(os.Stderr, "Warning: failed to parse SOA serial: %v\n", err)
}
}
}
}
}
err = dnsClient.UpdateRecordSets(ctx, dns.UpdateRecordSetsRequest{
Zone: zonename,
RecordSets: &dns.RecordSets{RecordSets: recordsetWorkList},
RecLock: nil,
})
if err != nil {
return failStep("Updating Recordsets", "Recordset update failed: %v", err)
}
fmt.Printf("Updating Recordsets ... %s\n", color.GreenString("[OK]"))
if c.Bool("suppress") {
return nil
}
// Retrieve and display updated recordsets
resp, err := dnsClient.GetRecordSets(ctx, dns.GetRecordSetsRequest{
Zone: zonename,
})
if err != nil {
return failStep("Retrieving updated records", "Failed to retrieve recordsets after update: %v", err)
}
fmt.Fprintf(os.Stderr, "Retrieving updated records ... %s\n", color.GreenString("[OK]"))
var results string
if c.Bool("json") {
rjson, err := json.MarshalIndent(resp, "", " ")
if err != nil {
return failStep("Assembling Recordsets List", "Unable to display recordsets list")
}
results = string(rjson)
} else {
results = renderRecordsetListTable(resp.RecordSets)
}
fmt.Fprintf(os.Stderr, "Assembling Recordsets List ... %s\n", color.GreenString("[OK]"))
// Output results to file or console
if outputPath != "" {
f, err := os.Create(outputPath)
if err != nil {
return failStep("Writing Output", "Failed to create output file: %v", err)
}
defer func() { _ = f.Close() }()
_, err = f.WriteString(results)
if err != nil {
return failStep("Writing Output", "Failed to write zone output to file")
}
_ = f.Sync()
_, _ = fmt.Fprintln(os.Stderr, color.GreenString("Output written to %s", outputPath))
} else {
_, _ = fmt.Fprintln(c.App.Writer, results)
}
return nil
}