@@ -19,6 +19,7 @@ package main
1919import (
2020 "errors"
2121 "fmt"
22+ "sort"
2223 "strconv"
2324 "strings"
2425
@@ -31,6 +32,10 @@ import (
3132 "gopkg.in/urfave/cli.v1"
3233)
3334
35+ // The Route53 limits change sets to this size. DNS changes need to be split
36+ // up into multiple batches to work around the limit.
37+ const route53ChangeLimit = 30000
38+
3439var (
3540 route53AccessKeyFlag = cli.StringFlag {
3641 Name : "access-key-id" ,
@@ -53,6 +58,11 @@ type route53Client struct {
5358 zoneID string
5459}
5560
61+ type recordSet struct {
62+ values []string
63+ ttl int64
64+ }
65+
5666// newRoute53Client sets up a Route53 API client from command line flags.
5767func newRoute53Client (ctx * cli.Context ) * route53Client {
5868 akey := ctx .String (route53AccessKeyFlag .Name )
@@ -78,31 +88,39 @@ func (c *route53Client) deploy(name string, t *dnsdisc.Tree) error {
7888 }
7989
8090 // Compute DNS changes.
81- records := t .ToTXT (name )
82- changes , err := c .computeChanges (name , records )
91+ existing , err := c .collectRecords (name )
8392 if err != nil {
8493 return err
8594 }
95+ log .Info (fmt .Sprintf ("Found %d TXT records" , len (existing )))
96+
97+ records := t .ToTXT (name )
98+ changes := c .computeChanges (name , records , existing )
8699 if len (changes ) == 0 {
87100 log .Info ("No DNS changes needed" )
88101 return nil
89102 }
90103
91- // Submit change request.
92- log .Info (fmt .Sprintf ("Submitting %d changes to Route53" , len (changes )))
93- batch := new (route53.ChangeBatch )
94- batch .SetChanges (changes )
95- batch .SetComment (fmt .Sprintf ("enrtree update of %s at seq %d" , name , t .Seq ()))
96- req := & route53.ChangeResourceRecordSetsInput {HostedZoneId : & c .zoneID , ChangeBatch : batch }
97- resp , err := c .api .ChangeResourceRecordSets (req )
98- if err != nil {
99- return err
100- }
104+ // Submit change batches.
105+ batches := splitChanges (changes , route53ChangeLimit )
106+ for i , changes := range batches {
107+ log .Info (fmt .Sprintf ("Submitting %d changes to Route53" , len (changes )))
108+ batch := new (route53.ChangeBatch )
109+ batch .SetChanges (changes )
110+ batch .SetComment (fmt .Sprintf ("enrtree update %d/%d of %s at seq %d" , i + 1 , len (batches ), name , t .Seq ()))
111+ req := & route53.ChangeResourceRecordSetsInput {HostedZoneId : & c .zoneID , ChangeBatch : batch }
112+ resp , err := c .api .ChangeResourceRecordSets (req )
113+ if err != nil {
114+ return err
115+ }
101116
102- // Wait for the change to be applied.
103- log .Info (fmt .Sprintf ("Waiting for change request %s" , * resp .ChangeInfo .Id ))
104- wreq := & route53.GetChangeInput {Id : resp .ChangeInfo .Id }
105- return c .api .WaitUntilResourceRecordSetsChanged (wreq )
117+ log .Info (fmt .Sprintf ("Waiting for change request %s" , * resp .ChangeInfo .Id ))
118+ wreq := & route53.GetChangeInput {Id : resp .ChangeInfo .Id }
119+ if err := c .api .WaitUntilResourceRecordSetsChanged (wreq ); err != nil {
120+ return err
121+ }
122+ }
123+ return nil
106124}
107125
108126// checkZone verifies zone information for the given domain.
@@ -137,30 +155,23 @@ func (c *route53Client) findZoneID(name string) (string, error) {
137155}
138156
139157// computeChanges creates DNS changes for the given record.
140- func (c * route53Client ) computeChanges (name string , records map [string ]string ) ( []* route53.Change , error ) {
158+ func (c * route53Client ) computeChanges (name string , records map [string ]string , existing map [ string ] recordSet ) []* route53.Change {
141159 // Convert all names to lowercase.
142160 lrecords := make (map [string ]string , len (records ))
143161 for name , r := range records {
144162 lrecords [strings .ToLower (name )] = r
145163 }
146164 records = lrecords
147165
148- // Get existing records.
149- existing , err := c .collectRecords (name )
150- if err != nil {
151- return nil , err
152- }
153- log .Info (fmt .Sprintf ("Found %d TXT records" , len (existing )))
154-
155166 var changes []* route53.Change
156167 for path , val := range records {
157- ttl := 1
168+ ttl := int64 ( rootTTL )
158169 if path != name {
159- ttl = 2147483647
170+ ttl = int64 ( treeNodeTTL )
160171 }
161172
162173 prevRecords , exists := existing [path ]
163- prevValue := combineTXT (prevRecords )
174+ prevValue := combineTXT (prevRecords . values )
164175 if ! exists {
165176 // Entry is unknown, push a new one
166177 log .Info (fmt .Sprintf ("Creating %s = %q" , path , val ))
@@ -175,40 +186,84 @@ func (c *route53Client) computeChanges(name string, records map[string]string) (
175186 }
176187
177188 // Iterate over the old records and delete anything stale.
178- for path , values := range existing {
189+ for path , set := range existing {
179190 if _ , ok := records [path ]; ok {
180191 continue
181192 }
182193 // Stale entry, nuke it.
183- log .Info (fmt .Sprintf ("Deleting %s = %q" , path , combineTXT (values )))
184- changes = append (changes , newTXTChange ("DELETE" , path , 1 , values ))
194+ log .Info (fmt .Sprintf ("Deleting %s = %q" , path , combineTXT (set . values )))
195+ changes = append (changes , newTXTChange ("DELETE" , path , set . ttl , set . values ))
185196 }
186- return changes , nil
197+
198+ sortChanges (changes )
199+ return changes
200+ }
201+
202+ // sortChanges ensures DNS changes are in leaf-added -> root-changed -> leaf-deleted order.
203+ func sortChanges (changes []* route53.Change ) {
204+ score := map [string ]int {"CREATE" : 1 , "UPSERT" : 2 , "DELETE" : 3 }
205+ sort .Slice (changes , func (i , j int ) bool {
206+ if * changes [i ].Action == * changes [j ].Action {
207+ return * changes [i ].ResourceRecordSet .Name < * changes [j ].ResourceRecordSet .Name
208+ }
209+ return score [* changes [i ].Action ] < score [* changes [j ].Action ]
210+ })
211+ }
212+
213+ // splitChanges splits up DNS changes such that each change batch
214+ // is smaller than the given RDATA limit.
215+ func splitChanges (changes []* route53.Change , limit int ) [][]* route53.Change {
216+ var batches [][]* route53.Change
217+ var batchSize int
218+ for _ , ch := range changes {
219+ // Start new batch if this change pushes the current one over the limit.
220+ size := changeSize (ch )
221+ if len (batches ) == 0 || batchSize + size > limit {
222+ batches = append (batches , nil )
223+ batchSize = 0
224+ }
225+ batches [len (batches )- 1 ] = append (batches [len (batches )- 1 ], ch )
226+ batchSize += size
227+ }
228+ return batches
229+ }
230+
231+ // changeSize returns the RDATA size of a DNS change.
232+ func changeSize (ch * route53.Change ) int {
233+ size := 0
234+ for _ , rr := range ch .ResourceRecordSet .ResourceRecords {
235+ if rr .Value != nil {
236+ size += len (* rr .Value )
237+ }
238+ }
239+ return size
187240}
188241
189242// collectRecords collects all TXT records below the given name.
190- func (c * route53Client ) collectRecords (name string ) (map [string ][] string , error ) {
243+ func (c * route53Client ) collectRecords (name string ) (map [string ]recordSet , error ) {
191244 log .Info (fmt .Sprintf ("Retrieving existing TXT records on %s (%s)" , name , c .zoneID ))
192245 var req route53.ListResourceRecordSetsInput
193246 req .SetHostedZoneId (c .zoneID )
194- existing := make (map [string ][] string )
247+ existing := make (map [string ]recordSet )
195248 err := c .api .ListResourceRecordSetsPages (& req , func (resp * route53.ListResourceRecordSetsOutput , last bool ) bool {
196249 for _ , set := range resp .ResourceRecordSets {
197250 if ! isSubdomain (* set .Name , name ) || * set .Type != "TXT" {
198251 continue
199252 }
200- name := strings . TrimSuffix ( * set .Name , "." )
253+ s := recordSet { ttl : * set .TTL }
201254 for _ , rec := range set .ResourceRecords {
202- existing [ name ] = append (existing [ name ] , * rec .Value )
255+ s . values = append (s . values , * rec .Value )
203256 }
257+ name := strings .TrimSuffix (* set .Name , "." )
258+ existing [name ] = s
204259 }
205260 return true
206261 })
207262 return existing , err
208263}
209264
210265// newTXTChange creates a change to a TXT record.
211- func newTXTChange (action , name string , ttl int , values []string ) * route53.Change {
266+ func newTXTChange (action , name string , ttl int64 , values []string ) * route53.Change {
212267 var c route53.Change
213268 var r route53.ResourceRecordSet
214269 var rrs []* route53.ResourceRecord
@@ -219,7 +274,7 @@ func newTXTChange(action, name string, ttl int, values []string) *route53.Change
219274 }
220275 r .SetType ("TXT" )
221276 r .SetName (name )
222- r .SetTTL (int64 ( ttl ) )
277+ r .SetTTL (ttl )
223278 r .SetResourceRecords (rrs )
224279 c .SetAction (action )
225280 c .SetResourceRecordSet (& r )
0 commit comments