aboutsummaryrefslogtreecommitdiff
path: root/middleware/kubernetes/nametemplate/nametemplate.go
blob: 5a34ae4ad906a7d35eef171fe1ebc511986be2de (plain) (blame)
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
package nametemplate

import (
	"errors"
	"log"
	"strings"

	"github.com/miekg/coredns/middleware/kubernetes/util"
)

// Likely symbols that require support:
// {id}
// {ip}
// {portname}
// {protocolname}
// {servicename}
// {namespace}
// {type}              "svc" or "pod"
// {zone}

// SkyDNS normal services have an A-record of the form "{servicename}.{namespace}.{type}.{zone}"
// This resolves to the cluster IP of the service.

// SkyDNS headless services have an A-record of the form "{servicename}.{namespace}.{type}.{zone}"
// This resolves to the set of IPs of the pods selected by the Service. Clients are expected to
// consume the set or else use round-robin selection from the set.

var symbols = map[string]string{
	"service":   "{service}",
	"namespace": "{namespace}",
	"type":      "{type}",
	"zone":      "{zone}",
}

var types = []string{
	"svc",
	"pod",
}

var requiredSymbols = []string{
	"namespace",
	"service",
}

// TODO: Validate that provided NameTemplate string only contains:
//			* valid, known symbols, or
//			* static strings

// TODO: Support collapsing multiple segments into a symbol. Either:
//			* all left-over segments are used as the "service" name, or
//			* some scheme like "{namespace}.{namespace}" means use
//			  segments concatenated with a "." for the namespace, or
//			* {namespace2:4} means use segements 2->4 for the namespace.

// TODO: possibly need to store length of segmented format to handle cases
//       where query string segments to a shorter or longer list than the template.
//		 When query string segments to shorter than template:
//			* either wildcards are being used, or
//			* we are not looking up an A, AAAA, or SRV record (eg NS), or
//			* we can just short-circuit failure before hitting the k8s API.
//		 Where the query string is longer than the template, need to define which
//		 symbol consumes the other segments. Most likely this would be the servicename.
//		 Also consider how to handle static strings in the format template.
type NameTemplate struct {
	formatString string
	splitFormat  []string
	// Element is a map of element name :: index in the segmented record name for the named element
	Element map[string]int
}

func (t *NameTemplate) SetTemplate(s string) error {
	var err error

	t.Element = map[string]int{}

	t.formatString = s
	t.splitFormat = strings.Split(t.formatString, ".")
	for templateIndex, v := range t.splitFormat {
		elementPositionSet := false
		for name, symbol := range symbols {
			if v == symbol {
				t.Element[name] = templateIndex
				elementPositionSet = true
				break
			}
		}
		if !elementPositionSet {
			if strings.Contains(v, "{") {
				err = errors.New("Record name template contains the unknown symbol '" + v + "'")
				log.Printf("[debug] %v\n", err)
				return err
			} else {
				log.Printf("[debug] Template string has static element '%v'\n", v)
			}
		}
	}

	if err == nil && !t.IsValid() {
		err = errors.New("Record name template does not pass NameTemplate validation")
		log.Printf("[debug] %v\n", err)
		return err
	}

	return err
}

// TODO: Find a better way to pull the data segments out of the
//       query string based on the template. Perhaps it is better
//		 to treat the query string segments as a reverse stack and
//       step down the stack to find the right element.

func (t *NameTemplate) GetZoneFromSegmentArray(segments []string) string {
	if index, ok := t.Element["zone"]; !ok {
		return ""
	} else {
		return strings.Join(segments[index:len(segments)], ".")
	}
}

func (t *NameTemplate) GetNamespaceFromSegmentArray(segments []string) string {
	return t.GetSymbolFromSegmentArray("namespace", segments)
}

func (t *NameTemplate) GetServiceFromSegmentArray(segments []string) string {
	return t.GetSymbolFromSegmentArray("service", segments)
}

func (t *NameTemplate) GetTypeFromSegmentArray(segments []string) string {
	typeSegment := t.GetSymbolFromSegmentArray("type", segments)

	// Limit type to known types symbols
	if util.StringInSlice(typeSegment, types) {
		return ""
	}

	return typeSegment
}

func (t *NameTemplate) GetSymbolFromSegmentArray(symbol string, segments []string) string {
	if index, ok := t.Element[symbol]; !ok {
		return ""
	} else {
		return segments[index]
	}
}

// GetRecordNameFromNameValues returns the string produced by applying the
// values to the NameTemplate format string.
func (t *NameTemplate) GetRecordNameFromNameValues(values NameValues) string {
	recordName := make([]string, len(t.splitFormat))
	copy(recordName[:], t.splitFormat)

	for name, index := range t.Element {
		if index == -1 {
			continue
		}
		switch name {
		case "type":
			recordName[index] = values.TypeName
		case "service":
			recordName[index] = values.ServiceName
		case "namespace":
			recordName[index] = values.Namespace
		case "zone":
			recordName[index] = values.Zone
		}
	}
	return strings.Join(recordName, ".")
}

func (t *NameTemplate) IsValid() bool {
	result := true

	// Ensure that all requiredSymbols are found in NameTemplate
	for _, symbol := range requiredSymbols {
		if _, ok := t.Element[symbol]; !ok {
			result = false
			break
		}
	}

	return result
}

type NameValues struct {
	ServiceName string
	Namespace   string
	TypeName    string
	Zone        string
}