alibaba_cloud.go 30.8 KB
Newer Older
Li Yi's avatar
Li Yi committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*
Copyright 2017 The Kubernetes Authors.

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 provider

import (
20
	"context"
Li Yi's avatar
Li Yi committed
21
22
	"fmt"
	"io/ioutil"
njuettner's avatar
njuettner committed
23
24
25
	"strings"
	"sync"
	"time"
Li Yi's avatar
Li Yi committed
26
27

	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
njuettner's avatar
njuettner committed
28
	"github.com/aliyun/alibaba-cloud-sdk-go/services/alidns"
Li Yi's avatar
Li Yi committed
29
30
	"github.com/aliyun/alibaba-cloud-sdk-go/services/pvtz"
	"github.com/denverdino/aliyungo/metadata"
njuettner's avatar
njuettner committed
31
32
	log "github.com/sirupsen/logrus"
	yaml "gopkg.in/yaml.v2"
33
34
35

	"sigs.k8s.io/external-dns/endpoint"
	"sigs.k8s.io/external-dns/plan"
Li Yi's avatar
Li Yi committed
36
37
38
39
40
41
42
)

const (
	defaultAlibabaCloudRecordTTL            = 600
	defaultAlibabaCloudPrivateZoneRecordTTL = 60
	defaultAlibabaCloudPageSize             = 50
	nullHostAlibabaCloud                    = "@"
43
	pVTZDoamin                              = "pvtz.aliyuncs.com"
Li Yi's avatar
Li Yi committed
44
45
46
47
48
49
50
51
52
)

// AlibabaCloudDNSAPI is a minimal implementation of DNS API that we actually use, used primarily for unit testing.
// See https://help.aliyun.com/document_detail/29739.html for descriptions of all of its methods.
type AlibabaCloudDNSAPI interface {
	AddDomainRecord(request *alidns.AddDomainRecordRequest) (response *alidns.AddDomainRecordResponse, err error)
	DeleteDomainRecord(request *alidns.DeleteDomainRecordRequest) (response *alidns.DeleteDomainRecordResponse, err error)
	UpdateDomainRecord(request *alidns.UpdateDomainRecordRequest) (response *alidns.UpdateDomainRecordResponse, err error)
	DescribeDomainRecords(request *alidns.DescribeDomainRecordsRequest) (response *alidns.DescribeDomainRecordsResponse, err error)
xianlubird's avatar
xianlubird committed
53
	DescribeDomains(request *alidns.DescribeDomainsRequest) (response *alidns.DescribeDomainsResponse, err error)
Li Yi's avatar
Li Yi committed
54
55
}

xianlubird's avatar
xianlubird committed
56
// AlibabaCloudPrivateZoneAPI is a minimal implementation of Private Zone API that we actually use, used primarily for unit testing.
Li Yi's avatar
Li Yi committed
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// See https://help.aliyun.com/document_detail/66234.html for descriptions of all of its methods.
type AlibabaCloudPrivateZoneAPI interface {
	AddZoneRecord(request *pvtz.AddZoneRecordRequest) (response *pvtz.AddZoneRecordResponse, err error)
	DeleteZoneRecord(request *pvtz.DeleteZoneRecordRequest) (response *pvtz.DeleteZoneRecordResponse, err error)
	UpdateZoneRecord(request *pvtz.UpdateZoneRecordRequest) (response *pvtz.UpdateZoneRecordResponse, err error)
	DescribeZoneRecords(request *pvtz.DescribeZoneRecordsRequest) (response *pvtz.DescribeZoneRecordsResponse, err error)
	DescribeZones(request *pvtz.DescribeZonesRequest) (response *pvtz.DescribeZonesResponse, err error)
	DescribeZoneInfo(request *pvtz.DescribeZoneInfoRequest) (response *pvtz.DescribeZoneInfoResponse, err error)
}

// AlibabaCloudProvider implements the DNS provider for Alibaba Cloud.
type AlibabaCloudProvider struct {
	domainFilter         DomainFilter
	zoneIDFilter         ZoneIDFilter // Private Zone only
	MaxChangeCount       int
	EvaluateTargetHealth bool
	AssumeRole           string
	vpcID                string // Private Zone only
	dryRun               bool
	dnsClient            AlibabaCloudDNSAPI
	pvtzClient           AlibabaCloudPrivateZoneAPI
	privateZone          bool
xianlubird's avatar
xianlubird committed
79
80
	clientLock           sync.RWMutex
	nextExpire           time.Time
Li Yi's avatar
Li Yi committed
81
82
83
}

type alibabaCloudConfig struct {
xianlubird's avatar
xianlubird committed
84
85
86
87
88
89
90
	RegionID        string    `json:"regionId" yaml:"regionId"`
	AccessKeyID     string    `json:"accessKeyId" yaml:"accessKeyId"`
	AccessKeySecret string    `json:"accessKeySecret" yaml:"accessKeySecret"`
	VPCID           string    `json:"vpcId" yaml:"vpcId"`
	RoleName        string    `json:"-" yaml:"-"` // For ECS RAM role only
	StsToken        string    `json:"-" yaml:"-"`
	ExpireTime      time.Time `json:"-" yaml:"-"`
Li Yi's avatar
Li Yi committed
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
}

// NewAlibabaCloudProvider creates a new Alibaba Cloud provider.
//
// Returns the provider or an error if a provider could not be created.
func NewAlibabaCloudProvider(configFile string, domainFilter DomainFilter, zoneIDFileter ZoneIDFilter, zoneType string, dryRun bool) (*AlibabaCloudProvider, error) {
	cfg := alibabaCloudConfig{}
	if configFile != "" {
		contents, err := ioutil.ReadFile(configFile)
		if err != nil {
			return nil, fmt.Errorf("Failed to read Alibaba Cloud config file '%s': %v", configFile, err)
		}
		err = yaml.Unmarshal(contents, &cfg)
		if err != nil {
			return nil, fmt.Errorf("Failed to parse Alibaba Cloud config file '%s': %v", configFile, err)
		}
	} else {
xianlubird's avatar
xianlubird committed
108
109
110
111
		var tmpError error
		cfg, tmpError = getCloudConfigFromStsToken()
		if tmpError != nil {
			return nil, fmt.Errorf("Failed to getCloudConfigFromStsToken: %v", tmpError)
Li Yi's avatar
Li Yi committed
112
113
114
115
116
117
118
119
120
121
122
123
124
125
		}
	}

	// Public DNS service
	var dnsClient AlibabaCloudDNSAPI
	var err error

	if cfg.RoleName == "" {
		dnsClient, err = alidns.NewClientWithAccessKey(
			cfg.RegionID,
			cfg.AccessKeyID,
			cfg.AccessKeySecret,
		)
	} else {
xianlubird's avatar
xianlubird committed
126
		dnsClient, err = alidns.NewClientWithStsToken(
Li Yi's avatar
Li Yi committed
127
			cfg.RegionID,
xianlubird's avatar
xianlubird committed
128
129
130
			cfg.AccessKeyID,
			cfg.AccessKeySecret,
			cfg.StsToken,
Li Yi's avatar
Li Yi committed
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
		)
	}

	if err != nil {
		return nil, fmt.Errorf("failed to create Alibaba Cloud DNS client: %v", err)
	}

	// Private DNS service
	var pvtzClient AlibabaCloudPrivateZoneAPI
	if cfg.RoleName == "" {
		pvtzClient, err = pvtz.NewClientWithAccessKey(
			"cn-hangzhou", // The Private Zone location is fixed
			cfg.AccessKeyID,
			cfg.AccessKeySecret,
		)
	} else {
xianlubird's avatar
xianlubird committed
147
148
149
150
151
		pvtzClient, err = pvtz.NewClientWithStsToken(
			cfg.RegionID,
			cfg.AccessKeyID,
			cfg.AccessKeySecret,
			cfg.StsToken,
Li Yi's avatar
Li Yi committed
152
153
154
		)
	}

njuettner's avatar
njuettner committed
155
156
157
158
	if err != nil {
		return nil, err
	}

Li Yi's avatar
Li Yi committed
159
160
161
162
163
164
165
	provider := &AlibabaCloudProvider{
		domainFilter: domainFilter,
		zoneIDFilter: zoneIDFileter,
		vpcID:        cfg.VPCID,
		dryRun:       dryRun,
		dnsClient:    dnsClient,
		pvtzClient:   pvtzClient,
xianlubird's avatar
xianlubird committed
166
167
168
169
170
171
		privateZone:  zoneType == "private",
	}

	if cfg.RoleName != "" {
		provider.setNextExpire(cfg.ExpireTime)
		go provider.refreshStsToken(1 * time.Second)
Li Yi's avatar
Li Yi committed
172
173
174
175
	}
	return provider, nil
}

xianlubird's avatar
xianlubird committed
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
func getCloudConfigFromStsToken() (alibabaCloudConfig, error) {
	cfg := alibabaCloudConfig{}
	// Load config from Metadata Service
	m := metadata.NewMetaData(nil)
	roleName := ""
	var err error
	if roleName, err = m.RoleName(); err != nil {
		return cfg, fmt.Errorf("Failed to get role name from Metadata Service: %v", err)
	}
	vpcID, err := m.VpcID()
	if err != nil {
		return cfg, fmt.Errorf("Failed to get VPC ID from Metadata Service: %v", err)
	}
	regionID, err := m.Region()
	if err != nil {
		return cfg, fmt.Errorf("Failed to get Region ID from Metadata Service: %v", err)
	}
	role, err := m.RamRoleToken(roleName)
	if err != nil {
		return cfg, fmt.Errorf("Failed to get STS Token from Metadata Service: %v", err)
	}
	cfg.RegionID = regionID
	cfg.RoleName = roleName
	cfg.VPCID = vpcID
	cfg.AccessKeyID = role.AccessKeyId
	cfg.AccessKeySecret = role.AccessKeySecret
	cfg.StsToken = role.SecurityToken
	cfg.ExpireTime = role.Expiration
	return cfg, nil
}

func (p *AlibabaCloudProvider) getDNSClient() AlibabaCloudDNSAPI {
	p.clientLock.RLock()
	defer p.clientLock.RUnlock()
	return p.dnsClient
}

func (p *AlibabaCloudProvider) getPvtzClient() AlibabaCloudPrivateZoneAPI {
	p.clientLock.RLock()
	defer p.clientLock.RUnlock()
	return p.pvtzClient
}

func (p *AlibabaCloudProvider) setNextExpire(expireTime time.Time) {
	p.clientLock.Lock()
	defer p.clientLock.Unlock()
	p.nextExpire = expireTime
}

func (p *AlibabaCloudProvider) refreshStsToken(sleepTime time.Duration) {
	for {
		time.Sleep(sleepTime)
		now := time.Now()
		utcLocation, err := time.LoadLocation("")
		if err != nil {
			log.Errorf("Get utc time error %v", err)
			continue
		}
		nowTime := now.In(utcLocation)
		p.clientLock.RLock()
		sleepTime = p.nextExpire.Sub(nowTime)
		p.clientLock.RUnlock()
		log.Infof("Distance expiration time %v", sleepTime)
239
240
		if sleepTime < 10*time.Minute {
			sleepTime = time.Second * 1
xianlubird's avatar
xianlubird committed
241
		} else {
242
			sleepTime = 9 * time.Minute
xianlubird's avatar
xianlubird committed
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
			log.Info("Next fetch sts sleep interval : ", sleepTime.String())
			continue
		}
		cfg, err := getCloudConfigFromStsToken()
		if err != nil {
			log.Errorf("Failed to getCloudConfigFromStsToken: %v", err)
			continue
		}
		dnsClient, err := alidns.NewClientWithStsToken(
			cfg.RegionID,
			cfg.AccessKeyID,
			cfg.AccessKeySecret,
			cfg.StsToken,
		)
		if err != nil {
			log.Errorf("Failed to new client with sts token %v", err)
			continue
		}
		pvtzClient, err := pvtz.NewClientWithStsToken(
			cfg.RegionID,
			cfg.AccessKeyID,
			cfg.AccessKeySecret,
			cfg.StsToken,
		)
		if err != nil {
			log.Errorf("Failed to new client with sts token %v", err)
			continue
		}
		log.Infof("Refresh client from sts token, next expire time %v", cfg.ExpireTime)
		p.clientLock.Lock()
		p.dnsClient = dnsClient
		p.pvtzClient = pvtzClient
		p.nextExpire = cfg.ExpireTime
		p.clientLock.Unlock()
	}
}

Li Yi's avatar
Li Yi committed
280
281
282
// Records gets the current records.
//
// Returns the current records or an error if the operation failed.
283
func (p *AlibabaCloudProvider) Records(ctx context.Context) (endpoints []*endpoint.Endpoint, err error) {
Li Yi's avatar
Li Yi committed
284
285
286
287
288
289
290
291
292
293
294
	if p.privateZone {
		endpoints, err = p.privateZoneRecords()
	} else {
		endpoints, err = p.recordsForDNS()
	}
	return endpoints, err
}

// ApplyChanges applies the given changes.
//
// Returns nil if the operation was successful or an error if the operation failed.
295
func (p *AlibabaCloudProvider) ApplyChanges(ctx context.Context, changes *plan.Changes) error {
Li Yi's avatar
Li Yi committed
296
297
298
299
300
301
302
303
	if changes == nil || len(changes.Create)+len(changes.Delete)+len(changes.UpdateNew) == 0 {
		// No op
		return nil
	}

	if p.privateZone {
		return p.applyChangesForPrivateZone(changes)
	}
xianlubird's avatar
xianlubird committed
304
	return p.applyChangesForDNS(changes)
Li Yi's avatar
Li Yi committed
305
306
307
308
309
310
}

func (p *AlibabaCloudProvider) getDNSName(rr, domain string) string {
	if rr == nullHostAlibabaCloud {
		return domain
	}
xianlubird's avatar
xianlubird committed
311
	return rr + "." + domain
Li Yi's avatar
Li Yi committed
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
}

// recordsForDNS gets the current records.
//
// Returns the current records or an error if the operation failed.
func (p *AlibabaCloudProvider) recordsForDNS() (endpoints []*endpoint.Endpoint, _ error) {

	records, err := p.records()
	if err != nil {
		return nil, err
	}
	for _, recordList := range p.groupRecords(records) {
		name := p.getDNSName(recordList[0].RR, recordList[0].DomainName)
		recordType := recordList[0].Type
		ttl := recordList[0].TTL

		if ttl == defaultAlibabaCloudRecordTTL {
			ttl = 0
		}

		var targets []string
		for _, record := range recordList {
			target := record.Value
			if recordType == "TXT" {
				target = p.unescapeTXTRecordValue(target)
			}
			targets = append(targets, target)
		}
		ep := endpoint.NewEndpointWithTTL(name, recordType, endpoint.TTL(ttl), targets...)
		endpoints = append(endpoints, ep)
	}
	return endpoints, nil
}

func getNextPageNumber(pageNumber, pageSize, totalCount int) int {

	if pageNumber*pageSize >= totalCount {
		return 0
	}
xianlubird's avatar
xianlubird committed
351
	return pageNumber + 1
Li Yi's avatar
Li Yi committed
352
353
354
355
356
357
}

func (p *AlibabaCloudProvider) getRecordKey(record alidns.Record) string {
	if record.RR == nullHostAlibabaCloud {
		return record.Type + ":" + record.DomainName
	}
xianlubird's avatar
xianlubird committed
358
	return record.Type + ":" + record.RR + "." + record.DomainName
Li Yi's avatar
Li Yi committed
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
}

func (p *AlibabaCloudProvider) getRecordKeyByEndpoint(endpoint *endpoint.Endpoint) string {
	return endpoint.RecordType + ":" + endpoint.DNSName
}

func (p *AlibabaCloudProvider) groupRecords(records []alidns.Record) (endpointMap map[string][]alidns.Record) {

	endpointMap = make(map[string][]alidns.Record)

	for _, record := range records {

		key := p.getRecordKey(record)

		recordList := endpointMap[key]
		endpointMap[key] = append(recordList, record)

	}

	return endpointMap
}

func (p *AlibabaCloudProvider) records() ([]alidns.Record, error) {
xianlubird's avatar
xianlubird committed
382
	log.Infof("Retrieving Alibaba Cloud DNS Domain Records")
Li Yi's avatar
Li Yi committed
383
384
	var results []alidns.Record

xianlubird's avatar
xianlubird committed
385
386
387
388
389
390
391
392
	if len(p.domainFilter.filters) == 1 && p.domainFilter.filters[0] == "" {
		domainNames, tmpErr := p.getDomainList()
		if tmpErr != nil {
			log.Errorf("AlibabaCloudProvider getDomainList error %v", tmpErr)
			return results, tmpErr
		}
		for _, tmpDomainName := range domainNames {
			tmpResults, err := p.getDomainRecords(tmpDomainName)
Li Yi's avatar
Li Yi committed
393
			if err != nil {
xianlubird's avatar
xianlubird committed
394
395
				log.Errorf("AlibabaCloudProvider getDomainRecords %s error %v", tmpDomainName, err)
				continue
Li Yi's avatar
Li Yi committed
396
			}
xianlubird's avatar
xianlubird committed
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
			results = append(results, tmpResults...)
		}
	} else {
		for _, domainName := range p.domainFilter.filters {
			tmpResults, err := p.getDomainRecords(domainName)
			if err != nil {
				log.Errorf("getDomainRecords %s error %v", domainName, err)
				continue
			}
			results = append(results, tmpResults...)
		}
	}
	log.Infof("Found %d Alibaba Cloud DNS record(s).", len(results))
	return results, nil
}
Li Yi's avatar
Li Yi committed
412

xianlubird's avatar
xianlubird committed
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
func (p *AlibabaCloudProvider) getDomainList() ([]string, error) {
	var domainNames []string
	request := alidns.CreateDescribeDomainsRequest()
	request.PageSize = requests.NewInteger(defaultAlibabaCloudPageSize)
	request.PageNumber = "1"
	for {
		resp, err := p.dnsClient.DescribeDomains(request)
		if err != nil {
			log.Errorf("Failed to describe domains for Alibaba Cloud DNS: %v", err)
			return nil, err
		}
		for _, tmpDomain := range resp.Domains.Domain {
			domainNames = append(domainNames, tmpDomain.DomainName)
		}
		nextPage := getNextPageNumber(resp.PageNumber, defaultAlibabaCloudPageSize, resp.TotalCount)
		if nextPage == 0 {
			break
		} else {
			request.PageNumber = requests.NewInteger(nextPage)
		}
	}
	return domainNames, nil
}
Li Yi's avatar
Li Yi committed
436

xianlubird's avatar
xianlubird committed
437
438
439
440
441
442
443
444
func (p *AlibabaCloudProvider) getDomainRecords(domainName string) ([]alidns.Record, error) {
	var results []alidns.Record
	request := alidns.CreateDescribeDomainRecordsRequest()
	request.DomainName = domainName
	request.PageSize = requests.NewInteger(defaultAlibabaCloudPageSize)
	request.PageNumber = "1"
	for {
		response, err := p.getDNSClient().DescribeDomainRecords(request)
Li Yi's avatar
Li Yi committed
445

xianlubird's avatar
xianlubird committed
446
447
448
449
		if err != nil {
			log.Errorf("Failed to describe domain records for Alibaba Cloud DNS: %v", err)
			return nil, err
		}
Li Yi's avatar
Li Yi committed
450

xianlubird's avatar
xianlubird committed
451
452
453
454
		for _, record := range response.DomainRecords.Record {

			domainName := record.DomainName
			recordType := record.Type
Li Yi's avatar
Li Yi committed
455

xianlubird's avatar
xianlubird committed
456
457
			if !p.domainFilter.Match(domainName) {
				continue
Li Yi's avatar
Li Yi committed
458
			}
xianlubird's avatar
xianlubird committed
459
460
461

			if !supportedRecordType(recordType) {
				continue
Li Yi's avatar
Li Yi committed
462
			}
xianlubird's avatar
xianlubird committed
463
464
465
466
467
468
469
470
471

			//TODO filter Locked record
			results = append(results, record)
		}
		nextPage := getNextPageNumber(response.PageNumber, defaultAlibabaCloudPageSize, response.TotalCount)
		if nextPage == 0 {
			break
		} else {
			request.PageNumber = requests.NewInteger(nextPage)
Li Yi's avatar
Li Yi committed
472
473
		}
	}
xianlubird's avatar
xianlubird committed
474

Li Yi's avatar
Li Yi committed
475
476
477
478
	return results, nil
}

func (p *AlibabaCloudProvider) applyChangesForDNS(changes *plan.Changes) error {
xianlubird's avatar
xianlubird committed
479
	log.Infof("ApplyChanges to Alibaba Cloud DNS: %++v", *changes)
Li Yi's avatar
Li Yi committed
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528

	records, err := p.records()
	if err != nil {
		return err
	}

	recordMap := p.groupRecords(records)

	p.createRecords(changes.Create)
	p.deleteRecords(recordMap, changes.Delete)
	p.updateRecords(recordMap, changes.UpdateNew)
	return nil
}

func (p *AlibabaCloudProvider) escapeTXTRecordValue(value string) string {
	// For unsupported chars
	return value
}

func (p *AlibabaCloudProvider) unescapeTXTRecordValue(value string) string {
	if strings.HasPrefix(value, "heritage=") {
		return fmt.Sprintf("\"%s\"", strings.Replace(value, ";", ",", -1))
	}
	return value
}

func (p *AlibabaCloudProvider) createRecord(endpoint *endpoint.Endpoint, target string) error {
	rr, domain := p.splitDNSName(endpoint)
	request := alidns.CreateAddDomainRecordRequest()
	request.DomainName = domain
	request.Type = endpoint.RecordType
	request.RR = rr

	ttl := int(endpoint.RecordTTL)
	if ttl != 0 {
		request.TTL = requests.NewInteger(ttl)
	}

	if endpoint.RecordType == "TXT" {
		target = p.escapeTXTRecordValue(target)
	}

	request.Value = target

	if p.dryRun {
		log.Infof("Dry run: Create %s record named '%s' to '%s' with ttl %d for Alibaba Cloud DNS", endpoint.RecordType, endpoint.DNSName, target, ttl)
		return nil
	}

xianlubird's avatar
xianlubird committed
529
	response, err := p.getDNSClient().AddDomainRecord(request)
Li Yi's avatar
Li Yi committed
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
	if err == nil {
		log.Infof("Create %s record named '%s' to '%s' with ttl %d for Alibaba Cloud DNS: Record ID=%s", endpoint.RecordType, endpoint.DNSName, target, ttl, response.RecordId)
	} else {
		log.Errorf("Failed to create %s record named '%s' to '%s' with ttl %d for Alibaba Cloud DNS: %v", endpoint.RecordType, endpoint.DNSName, target, ttl, err)
	}
	return err
}

func (p *AlibabaCloudProvider) createRecords(endpoints []*endpoint.Endpoint) error {
	for _, endpoint := range endpoints {
		for _, target := range endpoint.Targets {
			p.createRecord(endpoint, target)
		}
	}
	return nil
}

func (p *AlibabaCloudProvider) deleteRecord(recordID string) error {
	if p.dryRun {
		log.Infof("Dry run: Delete record id '%s' in Alibaba Cloud DNS", recordID)
		return nil
	}

	request := alidns.CreateDeleteDomainRecordRequest()
	request.RecordId = recordID
xianlubird's avatar
xianlubird committed
555
	response, err := p.getDNSClient().DeleteDomainRecord(request)
Li Yi's avatar
Li Yi committed
556
	if err == nil {
xianlubird's avatar
xianlubird committed
557
		log.Infof("Delete record id %s in Alibaba Cloud DNS", response.RecordId)
Li Yi's avatar
Li Yi committed
558
	} else {
xianlubird's avatar
xianlubird committed
559
		log.Errorf("Failed to delete record '%s' in Alibaba Cloud DNS: %v", response.RecordId, err)
Li Yi's avatar
Li Yi committed
560
561
562
563
564
565
566
567
568
569
570
571
572
573
	}
	return err
}

func (p *AlibabaCloudProvider) updateRecord(record alidns.Record, endpoint *endpoint.Endpoint) error {
	request := alidns.CreateUpdateDomainRecordRequest()
	request.RecordId = record.RecordId
	request.RR = record.RR
	request.Type = record.Type
	request.Value = record.Value
	ttl := int(endpoint.RecordTTL)
	if ttl != 0 {
		request.TTL = requests.NewInteger(ttl)
	}
xianlubird's avatar
xianlubird committed
574
	response, err := p.getDNSClient().UpdateDomainRecord(request)
Li Yi's avatar
Li Yi committed
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
	if err == nil {
		log.Infof("Update record id '%s' in Alibaba Cloud DNS", response.RecordId)
	} else {
		log.Errorf("Failed to update record '%s' in Alibaba Cloud DNS: %v", response.RecordId, err)
	}
	return err
}

func (p *AlibabaCloudProvider) deleteRecords(recordMap map[string][]alidns.Record, endpoints []*endpoint.Endpoint) error {
	for _, endpoint := range endpoints {
		key := p.getRecordKeyByEndpoint(endpoint)
		records := recordMap[key]
		found := false
		for _, record := range records {
			value := record.Value
			if record.Type == "TXT" {
				value = p.unescapeTXTRecordValue(value)
			}

			for _, target := range endpoint.Targets {
				// Find matched record to delete
				if value == target {
					p.deleteRecord(record.RecordId)
					found = true
					break
				}
			}
		}
		if !found {
			log.Errorf("Failed to find %s record named '%s' to delete for Alibaba Cloud DNS", endpoint.RecordType, endpoint.DNSName)
		}
	}
	return nil
}

func (p *AlibabaCloudProvider) equals(record alidns.Record, endpoint *endpoint.Endpoint) bool {
	ttl1 := record.TTL
	if ttl1 == defaultAlibabaCloudRecordTTL {
		ttl1 = 0
	}

	ttl2 := int(endpoint.RecordTTL)
	if ttl2 == defaultAlibabaCloudRecordTTL {
		ttl2 = 0
	}

	return ttl1 == ttl2
}

func (p *AlibabaCloudProvider) updateRecords(recordMap map[string][]alidns.Record, endpoints []*endpoint.Endpoint) error {

	for _, endpoint := range endpoints {
		key := p.getRecordKeyByEndpoint(endpoint)
		records := recordMap[key]
		for _, record := range records {
			value := record.Value
			if record.Type == "TXT" {
				value = p.unescapeTXTRecordValue(value)
			}
			found := false
			for _, target := range endpoint.Targets {
				// Find matched record to delete
				if value == target {
					found = true
				}
			}
			if found {
				if !p.equals(record, endpoint) {
					// Update record
					p.updateRecord(record, endpoint)
				}
			} else {
				p.deleteRecord(record.RecordId)
			}
		}
		for _, target := range endpoint.Targets {
			if endpoint.RecordType == "TXT" {
				target = p.escapeTXTRecordValue(target)
			}
			found := false
			for _, record := range records {
				// Find matched record to delete
				if record.Value == target {
					found = true
				}
			}
			if !found {
				p.createRecord(endpoint, target)
			}
		}
	}
	return nil
}

func (p *AlibabaCloudProvider) splitDNSName(endpoint *endpoint.Endpoint) (rr string, domain string) {

	name := strings.TrimSuffix(endpoint.DNSName, ".")

	found := false

	for _, filter := range p.domainFilter.filters {
		if strings.HasSuffix(name, "."+filter) {
			rr = name[0 : len(name)-len(filter)-1]
			domain = filter
			found = true
			break
		} else if name == filter {
			domain = filter
			rr = ""
			found = true
		}
	}

	if !found {
xianlubird's avatar
xianlubird committed
689
690
		parts := strings.Split(name, ".")
		if len(parts) < 2 {
Li Yi's avatar
Li Yi committed
691
692
			rr = name
			domain = ""
xianlubird's avatar
xianlubird committed
693
694
695
696
697
698
699
		} else {
			domain = parts[len(parts)-2] + "." + parts[len(parts)-1]
			rrIndex := strings.Index(name, domain)
			if rrIndex < 1 {
				rrIndex = 1
			}
			rr = name[0 : rrIndex-1]
Li Yi's avatar
Li Yi committed
700
701
		}
	}
xianlubird's avatar
xianlubird committed
702

Li Yi's avatar
Li Yi committed
703
704
705
	if rr == "" {
		rr = nullHostAlibabaCloud
	}
xianlubird's avatar
xianlubird committed
706

Li Yi's avatar
Li Yi committed
707
708
709
710
711
712
	return rr, domain
}

func (p *AlibabaCloudProvider) matchVPC(zoneID string) bool {
	request := pvtz.CreateDescribeZoneInfoRequest()
	request.ZoneId = zoneID
713
	request.Domain = pVTZDoamin
xianlubird's avatar
xianlubird committed
714
	response, err := p.getPvtzClient().DescribeZoneInfo(request)
Li Yi's avatar
Li Yi committed
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
	if err != nil {
		log.Errorf("Failed to describe zone info %s in Alibaba Cloud DNS: %v", zoneID, err)
		return false
	}
	foundVPC := false
	for _, vpc := range response.BindVpcs.Vpc {
		if vpc.VpcId == p.vpcID {
			foundVPC = true
			break
		}
	}
	return foundVPC
}

func (p *AlibabaCloudProvider) privateZones() ([]pvtz.Zone, error) {

	var zones []pvtz.Zone

	request := pvtz.CreateDescribeZonesRequest()
	request.PageSize = requests.NewInteger(defaultAlibabaCloudPageSize)
	request.PageNumber = "1"
736
	request.Domain = pVTZDoamin
Li Yi's avatar
Li Yi committed
737
	for {
xianlubird's avatar
xianlubird committed
738
		response, err := p.getPvtzClient().DescribeZones(request)
Li Yi's avatar
Li Yi committed
739
740
741
742
743
		if err != nil {
			log.Errorf("Failed to describe zones in Alibaba Cloud DNS: %v", err)
			return nil, err
		}
		for _, zone := range response.Zones.Zone {
744
			log.Infof("PrivateZones zone: %++v", zone)
Li Yi's avatar
Li Yi committed
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772

			if !p.zoneIDFilter.Match(zone.ZoneId) {
				continue
			}
			if !p.domainFilter.Match(zone.ZoneName) {
				continue
			}
			if !p.matchVPC(zone.ZoneId) {
				continue
			}
			zones = append(zones, zone)
		}
		nextPage := getNextPageNumber(response.PageNumber, defaultAlibabaCloudPageSize, response.TotalItems)
		if nextPage == 0 {
			break
		} else {
			request.PageNumber = requests.NewInteger(nextPage)
		}
	}
	return zones, nil
}

type alibabaPrivateZone struct {
	pvtz.Zone
	records []pvtz.Record
}

func (p *AlibabaCloudProvider) getPrivateZones() (map[string]*alibabaPrivateZone, error) {
xianlubird's avatar
xianlubird committed
773
	log.Infof("Retrieving Alibaba Cloud Private Zone records")
Li Yi's avatar
Li Yi committed
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789

	result := make(map[string]*alibabaPrivateZone)
	recordsCount := 0

	zones, err := p.privateZones()

	if err != nil {
		return nil, err
	}

	for _, zone := range zones {

		request := pvtz.CreateDescribeZoneRecordsRequest()
		request.ZoneId = zone.ZoneId
		request.PageSize = requests.NewInteger(defaultAlibabaCloudPageSize)
		request.PageNumber = "1"
790
		request.Domain = pVTZDoamin
Li Yi's avatar
Li Yi committed
791
792
793
		var records []pvtz.Record

		for {
xianlubird's avatar
xianlubird committed
794
			response, err := p.getPvtzClient().DescribeZoneRecords(request)
Li Yi's avatar
Li Yi committed
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826

			if err != nil {
				log.Errorf("Failed to describe zone record '%s' in Alibaba Cloud DNS: %v", zone.ZoneId, err)
				return nil, err
			}

			for _, record := range response.Records.Record {

				recordType := record.Type

				if !supportedRecordType(recordType) {
					continue
				}

				//TODO filter Locked
				records = append(records, record)
			}
			nextPage := getNextPageNumber(response.PageNumber, defaultAlibabaCloudPageSize, response.TotalItems)
			if nextPage == 0 {
				break
			} else {
				request.PageNumber = requests.NewInteger(nextPage)
			}
		}

		privateZone := alibabaPrivateZone{
			Zone:    zone,
			records: records,
		}
		recordsCount += len(records)
		result[zone.ZoneName] = &privateZone
	}
xianlubird's avatar
xianlubird committed
827
	log.Infof("Found %d Alibaba Cloud Private Zone record(s).", recordsCount)
Li Yi's avatar
Li Yi committed
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
	return result, nil
}

func (p *AlibabaCloudProvider) groupPrivateZoneRecords(zone *alibabaPrivateZone) (endpointMap map[string][]pvtz.Record) {

	endpointMap = make(map[string][]pvtz.Record)

	for _, record := range zone.records {
		key := record.Type + ":" + record.Rr
		recordList := endpointMap[key]
		endpointMap[key] = append(recordList, record)
	}

	return endpointMap
}

// recordsForPrivateZone gets the current records.
//
// Returns the current records or an error if the operation failed.
func (p *AlibabaCloudProvider) privateZoneRecords() (endpoints []*endpoint.Endpoint, _ error) {

	zones, err := p.getPrivateZones()
	if err != nil {
		return nil, err
	}

	for _, zone := range zones {
		recordMap := p.groupPrivateZoneRecords(zone)
		for _, recordList := range recordMap {
			name := p.getDNSName(recordList[0].Rr, zone.ZoneName)
			recordType := recordList[0].Type
			ttl := recordList[0].Ttl
			if ttl == defaultAlibabaCloudPrivateZoneRecordTTL {
				ttl = 0
			}
			var targets []string
			for _, record := range recordList {
				target := record.Value
				if recordType == "TXT" {
					target = p.unescapeTXTRecordValue(target)
				}
				targets = append(targets, target)
			}
			ep := endpoint.NewEndpointWithTTL(name, recordType, endpoint.TTL(ttl), targets...)
			endpoints = append(endpoints, ep)
		}
	}
	return endpoints, nil
}

func (p *AlibabaCloudProvider) createPrivateZoneRecord(zones map[string]*alibabaPrivateZone, endpoint *endpoint.Endpoint, target string) error {
	rr, domain := p.splitDNSName(endpoint)
	zone := zones[domain]
	if zone == nil {
		err := fmt.Errorf("Failed to find private zone '%s'", domain)
		log.Errorf("Failed to create %s record named '%s' to '%s' for Alibaba Cloud Private Zone: %v", endpoint.RecordType, endpoint.DNSName, target, err)
		return err
	}

	request := pvtz.CreateAddZoneRecordRequest()
	request.ZoneId = zone.ZoneId
	request.Type = endpoint.RecordType
	request.Rr = rr
891
	request.Domain = pVTZDoamin
Li Yi's avatar
Li Yi committed
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908

	ttl := int(endpoint.RecordTTL)
	if ttl != 0 {
		request.Ttl = requests.NewInteger(ttl)
	}

	if endpoint.RecordType == "TXT" {
		target = p.escapeTXTRecordValue(target)
	}

	request.Value = target

	if p.dryRun {
		log.Infof("Dry run: Create %s record named '%s' to '%s' with ttl %d for Alibaba Cloud Private Zone", endpoint.RecordType, endpoint.DNSName, target, ttl)
		return nil
	}

xianlubird's avatar
xianlubird committed
909
	response, err := p.getPvtzClient().AddZoneRecord(request)
Li Yi's avatar
Li Yi committed
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
	if err == nil {
		log.Infof("Create %s record named '%s' to '%s' with ttl %d for Alibaba Cloud Private Zone: Record ID=%d", endpoint.RecordType, endpoint.DNSName, target, ttl, response.RecordId)
	} else {
		log.Errorf("Failed to create %s record named '%s' to '%s' with ttl %d for Alibaba Cloud Private Zone: %v", endpoint.RecordType, endpoint.DNSName, target, ttl, err)
	}
	return err
}

func (p *AlibabaCloudProvider) createPrivateZoneRecords(zones map[string]*alibabaPrivateZone, endpoints []*endpoint.Endpoint) error {
	for _, endpoint := range endpoints {
		for _, target := range endpoint.Targets {
			p.createPrivateZoneRecord(zones, endpoint, target)
		}
	}
	return nil
}

func (p *AlibabaCloudProvider) deletePrivateZoneRecord(recordID int) error {

	if p.dryRun {
		log.Infof("Dry run: Delete record id '%d' in Alibaba Cloud Private Zone", recordID)
	}

	request := pvtz.CreateDeleteZoneRecordRequest()
	request.RecordId = requests.NewInteger(recordID)
935
	request.Domain = pVTZDoamin
Li Yi's avatar
Li Yi committed
936

xianlubird's avatar
xianlubird committed
937
	response, err := p.getPvtzClient().DeleteZoneRecord(request)
Li Yi's avatar
Li Yi committed
938
939
940
	if err == nil {
		log.Infof("Delete record id '%d' in Alibaba Cloud Private Zone", response.RecordId)
	} else {
xianlubird's avatar
xianlubird committed
941
		log.Errorf("Failed to delete record %d in Alibaba Cloud Private Zone: %v", response.RecordId, err)
Li Yi's avatar
Li Yi committed
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
	}
	return err
}

func (p *AlibabaCloudProvider) deletePrivateZoneRecords(zones map[string]*alibabaPrivateZone, endpoints []*endpoint.Endpoint) error {
	for _, endpoint := range endpoints {
		rr, domain := p.splitDNSName(endpoint)

		zone := zones[domain]
		if zone == nil {
			err := fmt.Errorf("Failed to find private zone '%s'", domain)
			log.Errorf("Failed to delete %s record named '%s' for Alibaba Cloud Private Zone: %v", endpoint.RecordType, endpoint.DNSName, err)
			continue
		}
		found := false
		for _, record := range zone.records {
			if rr == record.Rr && endpoint.RecordType == record.Type {
				value := record.Value
				if record.Type == "TXT" {
					value = p.unescapeTXTRecordValue(value)
				}
				for _, target := range endpoint.Targets {
					// Find matched record to delete
					if value == target {
						p.deletePrivateZoneRecord(record.RecordId)
						found = true
						break
					}
				}
			}
		}
		if !found {
			log.Errorf("Failed to find %s record named '%s' to delete for Alibaba Cloud Private Zone", endpoint.RecordType, endpoint.DNSName)
		}
	}
	return nil
}

// ApplyChanges applies the given changes.
//
// Returns nil if the operation was successful or an error if the operation failed.
func (p *AlibabaCloudProvider) applyChangesForPrivateZone(changes *plan.Changes) error {
xianlubird's avatar
xianlubird committed
984
	log.Infof("ApplyChanges to Alibaba Cloud Private Zone: %++v", *changes)
Li Yi's avatar
Li Yi committed
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006

	zones, err := p.getPrivateZones()
	if err != nil {
		return err
	}

	for zoneName, zone := range zones {
		log.Debugf("%s: %++v", zoneName, zone)
	}

	p.createPrivateZoneRecords(zones, changes.Create)
	p.deletePrivateZoneRecords(zones, changes.Delete)
	p.updatePrivateZoneRecords(zones, changes.UpdateNew)
	return nil
}

func (p *AlibabaCloudProvider) updatePrivateZoneRecord(record pvtz.Record, endpoint *endpoint.Endpoint) error {
	request := pvtz.CreateUpdateZoneRecordRequest()
	request.RecordId = requests.NewInteger(record.RecordId)
	request.Rr = record.Rr
	request.Type = record.Type
	request.Value = record.Value
1007
	request.Domain = pVTZDoamin
Li Yi's avatar
Li Yi committed
1008
1009
1010
1011
	ttl := int(endpoint.RecordTTL)
	if ttl != 0 {
		request.Ttl = requests.NewInteger(ttl)
	}
xianlubird's avatar
xianlubird committed
1012
	response, err := p.getPvtzClient().UpdateZoneRecord(request)
Li Yi's avatar
Li Yi committed
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
	if err == nil {
		log.Infof("Update record id '%d' in Alibaba Cloud Private Zone", response.RecordId)
	} else {
		log.Errorf("Failed to update record '%d' in Alibaba Cloud Private Zone: %v", response.RecordId, err)
	}
	return err
}

func (p *AlibabaCloudProvider) equalsPrivateZone(record pvtz.Record, endpoint *endpoint.Endpoint) bool {
	ttl1 := record.Ttl
	if ttl1 == defaultAlibabaCloudPrivateZoneRecordTTL {
		ttl1 = 0
	}

	ttl2 := int(endpoint.RecordTTL)
	if ttl2 == defaultAlibabaCloudPrivateZoneRecordTTL {
		ttl2 = 0
	}

	return ttl1 == ttl2
}

func (p *AlibabaCloudProvider) updatePrivateZoneRecords(zones map[string]*alibabaPrivateZone, endpoints []*endpoint.Endpoint) error {

	for _, endpoint := range endpoints {
		rr, domain := p.splitDNSName(endpoint)
		zone := zones[domain]
		if zone == nil {
			err := fmt.Errorf("Failed to find private zone '%s'", domain)
			log.Errorf("Failed to update %s record named '%s' for Alibaba Cloud Private Zone: %v", endpoint.RecordType, endpoint.DNSName, err)
			continue
		}

		for _, record := range zone.records {
			if record.Rr != rr || record.Type != endpoint.RecordType {
				continue
			}
			value := record.Value
			if record.Type == "TXT" {
				value = p.unescapeTXTRecordValue(value)
			}
			found := false
			for _, target := range endpoint.Targets {
				// Find matched record to delete
				if value == target {
					found = true
					break
				}
			}
			if found {
				if !p.equalsPrivateZone(record, endpoint) {
					// Update record
					p.updatePrivateZoneRecord(record, endpoint)
				}
			} else {
				p.deletePrivateZoneRecord(record.RecordId)
			}
		}
		for _, target := range endpoint.Targets {
			if endpoint.RecordType == "TXT" {
				target = p.escapeTXTRecordValue(target)
			}
			found := false
			for _, record := range zone.records {
				if record.Rr != rr || record.Type != endpoint.RecordType {
					continue
				}
				// Find matched record to delete
				if record.Value == target {
					found = true
					break
				}
			}
			if !found {
				p.createPrivateZoneRecord(zones, endpoint, target)
			}
		}
	}
	return nil
}