alibaba_cloud.go 30.9 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
/*
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.
*/

17
package alibabacloud
Li Yi's avatar
Li Yi committed
18
19

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"
36
	"sigs.k8s.io/external-dns/provider"
Li Yi's avatar
Li Yi committed
37
38
39
40
41
42
43
)

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

// 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
54
	DescribeDomains(request *alidns.DescribeDomainsRequest) (response *alidns.DescribeDomainsResponse, err error)
Li Yi's avatar
Li Yi committed
55
56
}

xianlubird's avatar
xianlubird committed
57
// 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
58
59
60
61
62
63
64
65
66
67
68
69
// 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 {
70
	provider.BaseProvider
71
	domainFilter         endpoint.DomainFilter
72
	zoneIDFilter         provider.ZoneIDFilter // Private Zone only
Li Yi's avatar
Li Yi committed
73
74
75
76
77
78
79
80
	MaxChangeCount       int
	EvaluateTargetHealth bool
	AssumeRole           string
	vpcID                string // Private Zone only
	dryRun               bool
	dnsClient            AlibabaCloudDNSAPI
	pvtzClient           AlibabaCloudPrivateZoneAPI
	privateZone          bool
xianlubird's avatar
xianlubird committed
81
82
	clientLock           sync.RWMutex
	nextExpire           time.Time
Li Yi's avatar
Li Yi committed
83
84
85
}

type alibabaCloudConfig struct {
xianlubird's avatar
xianlubird committed
86
87
88
89
90
91
92
	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
93
94
95
96
97
}

// NewAlibabaCloudProvider creates a new Alibaba Cloud provider.
//
// Returns the provider or an error if a provider could not be created.
98
func NewAlibabaCloudProvider(configFile string, domainFilter endpoint.DomainFilter, zoneIDFileter provider.ZoneIDFilter, zoneType string, dryRun bool) (*AlibabaCloudProvider, error) {
Li Yi's avatar
Li Yi committed
99
100
101
102
103
104
105
106
107
108
109
	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
110
111
112
113
		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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
		}
	}

	// 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
128
		dnsClient, err = alidns.NewClientWithStsToken(
Li Yi's avatar
Li Yi committed
129
			cfg.RegionID,
xianlubird's avatar
xianlubird committed
130
131
132
			cfg.AccessKeyID,
			cfg.AccessKeySecret,
			cfg.StsToken,
Li Yi's avatar
Li Yi committed
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
		)
	}

	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
149
150
151
152
153
		pvtzClient, err = pvtz.NewClientWithStsToken(
			cfg.RegionID,
			cfg.AccessKeyID,
			cfg.AccessKeySecret,
			cfg.StsToken,
Li Yi's avatar
Li Yi committed
154
155
156
		)
	}

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

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

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

xianlubird's avatar
xianlubird committed
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
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)
241
242
		if sleepTime < 10*time.Minute {
			sleepTime = time.Second * 1
xianlubird's avatar
xianlubird committed
243
		} else {
244
			sleepTime = 9 * time.Minute
xianlubird's avatar
xianlubird committed
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
			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
282
283
284
// Records gets the current records.
//
// Returns the current records or an error if the operation failed.
285
func (p *AlibabaCloudProvider) Records(ctx context.Context) (endpoints []*endpoint.Endpoint, err error) {
Li Yi's avatar
Li Yi committed
286
287
288
289
290
291
292
293
294
295
296
	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.
297
func (p *AlibabaCloudProvider) ApplyChanges(ctx context.Context, changes *plan.Changes) error {
Li Yi's avatar
Li Yi committed
298
299
300
301
302
303
304
305
	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
306
	return p.applyChangesForDNS(changes)
Li Yi's avatar
Li Yi committed
307
308
309
310
311
312
}

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

// 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
353
	return pageNumber + 1
Li Yi's avatar
Li Yi committed
354
355
356
357
358
359
}

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

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
384
	log.Infof("Retrieving Alibaba Cloud DNS Domain Records")
Li Yi's avatar
Li Yi committed
385
386
	var results []alidns.Record

387
	if len(p.domainFilter.Filters) == 1 && p.domainFilter.Filters[0] == "" {
xianlubird's avatar
xianlubird committed
388
389
390
391
392
393
394
		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
395
			if err != nil {
xianlubird's avatar
xianlubird committed
396
397
				log.Errorf("AlibabaCloudProvider getDomainRecords %s error %v", tmpDomainName, err)
				continue
Li Yi's avatar
Li Yi committed
398
			}
xianlubird's avatar
xianlubird committed
399
400
401
			results = append(results, tmpResults...)
		}
	} else {
402
		for _, domainName := range p.domainFilter.Filters {
xianlubird's avatar
xianlubird committed
403
404
405
406
407
408
409
410
411
412
413
			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
414

xianlubird's avatar
xianlubird committed
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
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
438

xianlubird's avatar
xianlubird committed
439
440
441
442
443
444
445
446
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
447

xianlubird's avatar
xianlubird committed
448
449
450
451
		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
452

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

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

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

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

			//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
474
475
		}
	}
xianlubird's avatar
xianlubird committed
476

Li Yi's avatar
Li Yi committed
477
478
479
480
	return results, nil
}

func (p *AlibabaCloudProvider) applyChangesForDNS(changes *plan.Changes) error {
xianlubird's avatar
xianlubird committed
481
	log.Infof("ApplyChanges to Alibaba Cloud DNS: %++v", *changes)
Li Yi's avatar
Li Yi committed
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
529
530

	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
531
	response, err := p.getDNSClient().AddDomainRecord(request)
Li Yi's avatar
Li Yi committed
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
	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
557
	response, err := p.getDNSClient().DeleteDomainRecord(request)
Li Yi's avatar
Li Yi committed
558
	if err == nil {
xianlubird's avatar
xianlubird committed
559
		log.Infof("Delete record id %s in Alibaba Cloud DNS", response.RecordId)
Li Yi's avatar
Li Yi committed
560
	} else {
xianlubird's avatar
xianlubird committed
561
		log.Errorf("Failed to delete record '%s' in Alibaba Cloud DNS: %v", response.RecordId, err)
Li Yi's avatar
Li Yi committed
562
563
564
565
566
567
568
569
570
571
572
573
574
575
	}
	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
576
	response, err := p.getDNSClient().UpdateDomainRecord(request)
Li Yi's avatar
Li Yi committed
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
	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

677
	for _, filter := range p.domainFilter.Filters {
Li Yi's avatar
Li Yi committed
678
679
680
681
682
683
684
685
686
687
688
689
690
		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
691
692
		parts := strings.Split(name, ".")
		if len(parts) < 2 {
Li Yi's avatar
Li Yi committed
693
694
			rr = name
			domain = ""
xianlubird's avatar
xianlubird committed
695
696
697
698
699
700
701
		} 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
702
703
		}
	}
xianlubird's avatar
xianlubird committed
704

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

Li Yi's avatar
Li Yi committed
709
710
711
712
713
714
	return rr, domain
}

func (p *AlibabaCloudProvider) matchVPC(zoneID string) bool {
	request := pvtz.CreateDescribeZoneInfoRequest()
	request.ZoneId = zoneID
715
	request.Domain = pVTZDoamin
xianlubird's avatar
xianlubird committed
716
	response, err := p.getPvtzClient().DescribeZoneInfo(request)
Li Yi's avatar
Li Yi committed
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
	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"
738
	request.Domain = pVTZDoamin
Li Yi's avatar
Li Yi committed
739
	for {
xianlubird's avatar
xianlubird committed
740
		response, err := p.getPvtzClient().DescribeZones(request)
Li Yi's avatar
Li Yi committed
741
742
743
744
745
		if err != nil {
			log.Errorf("Failed to describe zones in Alibaba Cloud DNS: %v", err)
			return nil, err
		}
		for _, zone := range response.Zones.Zone {
746
			log.Infof("PrivateZones zone: %++v", zone)
Li Yi's avatar
Li Yi committed
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
773
774

			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
775
	log.Infof("Retrieving Alibaba Cloud Private Zone records")
Li Yi's avatar
Li Yi committed
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791

	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"
792
		request.Domain = pVTZDoamin
Li Yi's avatar
Li Yi committed
793
794
795
		var records []pvtz.Record

		for {
xianlubird's avatar
xianlubird committed
796
			response, err := p.getPvtzClient().DescribeZoneRecords(request)
Li Yi's avatar
Li Yi committed
797
798
799
800
801
802
803
804
805
806

			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

807
				if !provider.SupportedRecordType(recordType) {
Li Yi's avatar
Li Yi committed
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
					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
829
	log.Infof("Found %d Alibaba Cloud Private Zone record(s).", recordsCount)
Li Yi's avatar
Li Yi committed
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
891
892
	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
893
	request.Domain = pVTZDoamin
Li Yi's avatar
Li Yi committed
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910

	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
911
	response, err := p.getPvtzClient().AddZoneRecord(request)
Li Yi's avatar
Li Yi committed
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
	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)
937
	request.Domain = pVTZDoamin
Li Yi's avatar
Li Yi committed
938

xianlubird's avatar
xianlubird committed
939
	response, err := p.getPvtzClient().DeleteZoneRecord(request)
Li Yi's avatar
Li Yi committed
940
941
942
	if err == nil {
		log.Infof("Delete record id '%d' in Alibaba Cloud Private Zone", response.RecordId)
	} else {
xianlubird's avatar
xianlubird committed
943
		log.Errorf("Failed to delete record %d in Alibaba Cloud Private Zone: %v", response.RecordId, err)
Li Yi's avatar
Li Yi committed
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
984
985
	}
	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
986
	log.Infof("ApplyChanges to Alibaba Cloud Private Zone: %++v", *changes)
Li Yi's avatar
Li Yi committed
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008

	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
1009
	request.Domain = pVTZDoamin
Li Yi's avatar
Li Yi committed
1010
1011
1012
1013
	ttl := int(endpoint.RecordTTL)
	if ttl != 0 {
		request.Ttl = requests.NewInteger(ttl)
	}
xianlubird's avatar
xianlubird committed
1014
	response, err := p.getPvtzClient().UpdateZoneRecord(request)
Li Yi's avatar
Li Yi committed
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
1093
1094
	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
}