forked from rancher/external-dns
/
utils.go
101 lines (87 loc) · 2.59 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package utils
import (
"fmt"
"io"
"regexp"
"strings"
"github.com/Sirupsen/logrus"
"github.com/valyala/fasttemplate"
)
const (
stateRecordFqdnTemplate = "external-dns-%s.%s"
)
type DnsRecord struct {
Fqdn string
Records []string
Type string
TTL int
}
type ServiceDnsRecord struct {
Fqdn string
ServiceName string
StackName string
}
func ConvertToServiceDnsRecord(dnsRecord DnsRecord) ServiceDnsRecord {
splitted := strings.Split(dnsRecord.Fqdn, ".")
serviceRecord := ServiceDnsRecord{dnsRecord.Fqdn, splitted[0], splitted[1]}
return serviceRecord
}
// Fqdn ensures that the name is a fqdn adding a trailing dot if necessary.
func Fqdn(name string) string {
n := len(name)
if n == 0 || name[n-1] == '.' {
return name
}
return name + "."
}
// UnFqdn converts the fqdn into a name removing the trailing dot.
func UnFqdn(name string) string {
n := len(name)
if n != 0 && name[n-1] == '.' {
return name[:n-1]
}
return name
}
func FqdnFromTemplate(template, serviceName, stackName, environmentName, rootDomainName string) string {
t, err := fasttemplate.NewTemplate(template, "%{{", "}}")
if err != nil {
logrus.Fatalf("error while parsing fqdn template: %s", err)
}
fqdn := t.ExecuteFuncString(func(w io.Writer, tag string) (int, error) {
switch tag {
case "service_name":
return w.Write([]byte(sanitizeLabel(serviceName)))
case "stack_name":
return w.Write([]byte(sanitizeLabel(stackName)))
case "environment_name":
return w.Write([]byte(sanitizeLabel(environmentName)))
default:
return 0, fmt.Errorf("invalid placeholder '%q' in fqdn template", tag)
}
})
labels := []string{fqdn, rootDomainName}
return strings.ToLower(strings.Join(labels, "."))
}
func StateFqdn(environmentUUID, rootDomainName string) string {
fqdn := fmt.Sprintf(stateRecordFqdnTemplate, environmentUUID, rootDomainName)
return strings.ToLower(fqdn)
}
func StateRecord(fqdn string, ttl int, entries map[string]struct{}) DnsRecord {
records := make([]string, len(entries))
idx := 0
for entry, _ := range entries {
records[idx] = entry
idx++
}
return DnsRecord{fqdn, records, "TXT", ttl}
}
// sanitizeLabel replaces characters that are not allowed in DNS labels with dashes.
// According to RFC 1123 the only characters allowed in DNS labels are A-Z, a-z, 0-9
// and dashes ("-"). The latter must not appear at the start or end of a label.
func sanitizeLabel(label string) string {
re := regexp.MustCompile("[^a-zA-Z0-9-]")
dashes := regexp.MustCompile("[-]+")
label = re.ReplaceAllString(label, "-")
label = dashes.ReplaceAllString(label, "-")
return strings.Trim(label, "-")
}