-
Notifications
You must be signed in to change notification settings - Fork 22
/
dnscontrollerprovider.go
284 lines (250 loc) · 8.97 KB
/
dnscontrollerprovider.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
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
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
241
242
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
280
281
282
283
284
/*
* Copyright 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
*
* 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
*
*/
package legobridge
import (
"fmt"
"github.com/gardener/cert-management/pkg/cert/metrics"
"github.com/gardener/cert-management/pkg/cert/source"
"github.com/gardener/cert-management/pkg/cert/utils"
"k8s.io/apimachinery/pkg/util/wait"
"sync/atomic"
"time"
"github.com/go-acme/lego/v3/challenge"
"github.com/go-acme/lego/v3/challenge/dns01"
"github.com/gardener/controller-manager-library/pkg/logger"
"github.com/gardener/controller-manager-library/pkg/resources"
dnsapi "github.com/gardener/external-dns-management/pkg/apis/dns/v1alpha1"
"github.com/gardener/external-dns-management/pkg/dns"
)
// ProviderWithCount is an extended Provider interface.
type ProviderWithCount interface {
challenge.Provider
GetChallengesCount() int
}
var index uint32
func newDNSControllerProvider(cluster resources.Cluster, settings DNSControllerSettings,
certificateName resources.ObjectName, targetClass, issuerName string) (ProviderWithCount, error) {
itf, err := cluster.Resources().GetByExample(&dnsapi.DNSEntry{})
if err != nil {
return nil, fmt.Errorf("cannot get DNSEntry resources: %s", err.Error())
}
n := atomic.AddUint32(&index, 1)
return &dnsControllerProvider{
logger: logger.NewContext("DNSChallengeProvider", fmt.Sprintf("dns-challenge-provider: %s-%d", certificateName, n)),
settings: settings,
entryResources: itf,
certificateName: certificateName,
targetClass: targetClass,
issuerName: issuerName,
ttl: int64(0.501 * dns01.DefaultPropagationTimeout.Seconds()),
initialWait: true,
presenting: map[string][]string{}}, nil
}
type dnsControllerProvider struct {
logger logger.LogContext
settings DNSControllerSettings
entryResources resources.Interface
certificateName resources.ObjectName
targetClass string
issuerName string
count int32
ttl int64
presenting map[string][]string
multiValues bool
initialWait bool
}
var _ challenge.Provider = &dnsControllerProvider{}
var _ challenge.ProviderTimeout = &dnsControllerProvider{}
var backoff = wait.Backoff{
Steps: 4,
Duration: 500 * time.Millisecond,
Factor: 2.0,
Jitter: 0.1,
Cap: 2500 * time.Millisecond,
}
type updateError struct {
msg string
}
func (e *updateError) Error() string {
return e.msg
}
func retryOnUpdateError(fn func() error) error {
var lastUpdateErr error
err := wait.ExponentialBackoff(backoff, func() (bool, error) {
err := fn()
_, isUpdateErr := err.(*updateError)
switch {
case err == nil:
return true, nil
case isUpdateErr:
lastUpdateErr = err
return false, nil
default:
return false, err
}
})
if err == wait.ErrWaitTimeout {
err = lastUpdateErr
}
return err
}
func (p *dnsControllerProvider) Present(domain, token, keyAuth string) error {
metrics.AddActiveACMEDNSChallenge(p.issuerName)
atomic.AddInt32(&p.count, 1)
fqdn, value := dns01.GetRecord(domain, keyAuth)
values := p.addPresentingDomainValue(domain, value)
setSpec := func(e *dnsapi.DNSEntry) {
e.Spec.DNSName = dns.NormalizeHostname(fqdn)
e.Spec.OwnerId = p.settings.OwnerID
e.Spec.TTL = &p.ttl
e.Spec.Text = values
if p.targetClass != "" {
resources.SetAnnotation(e, source.AnnotDNSClass, p.targetClass)
}
}
entry := p.prepareEntry(domain)
if len(values) == 1 {
setSpec(entry)
p.logger.Infof("presenting DNSEntry %s/%s for certificate resource %s", entry.Namespace, entry.Name, p.certificateName)
if p.existsBlockingEntry(entry) {
p.removePresentingDomain(domain)
return fmt.Errorf("already existing DNSEntry %s/%s for certificate resource %s", entry.Namespace, entry.Name, p.certificateName)
}
_, err := p.entryResources.Create(entry)
if err != nil {
return fmt.Errorf("creating DNSEntry %s/%s failed with %s", entry.Namespace, entry.Name, err.Error())
}
return nil
}
p.multiValues = true
err := retryOnUpdateError(func() error {
obj, err := p.entryResources.Get_(entry)
if err != nil {
return fmt.Errorf("getting DNSEntry %s/%s failed with %s", entry.Namespace, entry.Name, err.Error())
}
entry = obj.Data().(*dnsapi.DNSEntry)
setSpec(entry)
p.logger.Infof("presenting DNSEntry %s/%s for certificate resource %s with %d values", entry.Namespace, entry.Name, p.certificateName, len(values))
_, err = p.entryResources.Update(entry)
if err != nil {
return &updateError{msg: fmt.Sprintf("updating DNSEntry %s/%s failed with %s", entry.Namespace, entry.Name, err.Error())}
}
return nil
})
return err
}
func (p *dnsControllerProvider) existsBlockingEntry(entry *dnsapi.DNSEntry) bool {
objectName := resources.NewObjectName(entry.Namespace, entry.Name)
obj, err := p.entryResources.Get_(objectName)
if err != nil {
return false
}
keep := obj.GetCreationTimestamp().Add(3 * time.Minute).After(time.Now())
if !keep {
// delete outdated or foreign DNSEntry
_ = p.entryResources.DeleteByName(objectName)
}
return keep
}
func (p *dnsControllerProvider) addPresentingDomainValue(domain, value string) []string {
values := append(p.presenting[domain], value)
p.presenting[domain] = values
return values
}
func (p *dnsControllerProvider) removePresentingDomain(domain string) bool {
if _, found := p.presenting[domain]; !found {
return false
}
delete(p.presenting, domain)
return true
}
func (p *dnsControllerProvider) CleanUp(domain, token, keyAuth string) error {
metrics.RemoveActiveACMEDNSChallenge(p.issuerName)
if !p.removePresentingDomain(domain) {
return nil
}
entry := p.prepareEntry(domain)
p.logger.Infof("cleanup DNSEntry %s/%s for request %s", entry.Namespace, entry.Name, p.certificateName)
err := p.entryResources.Delete(entry)
if err != nil {
return fmt.Errorf("deleting DNSEntry %s/%s failed with %s", entry.Namespace, entry.Name, err.Error())
}
return nil
}
func (p *dnsControllerProvider) GetChallengesCount() int {
return int(atomic.LoadInt32(&p.count))
}
func (p *dnsControllerProvider) prepareEntry(domain string) *dnsapi.DNSEntry {
entry := &dnsapi.DNSEntry{}
entry.Name = "cert--" + domain
entry.Namespace = p.settings.Namespace
return entry
}
func (p *dnsControllerProvider) checkDNSEntryNotPending(domain string, values []string) bool {
entry := p.prepareEntry(domain)
obj, err := p.entryResources.Get_(entry)
if err != nil {
return true // no more waiting
}
entry = obj.Data().(*dnsapi.DNSEntry)
return !(entry.Status.State == "Pending" || entry.Status.State == "Ready" && len(entry.Status.Targets) != len(values))
}
func (p *dnsControllerProvider) Timeout() (timeout, interval time.Duration) {
waitTimeout := dns01.DefaultPropagationTimeout
if p.initialWait {
p.initialWait = false
// The Timeout function is called several times after all domains are "presented".
// On the first call it is checked that no DNS entries are pending anymore.
// Depending on number of domain names and possible parallel other work,
// the dns-controller-manager may need several change batches
// until all entries are ready
prepareWaitTimeout := waitTimeout + 5*time.Second*time.Duration(len(p.presenting))
p.waitFor("DNS entry getting ready", p.checkDNSEntryNotPending, prepareWaitTimeout)
if p.waitFor("DNS record propagation", p.isDNSTxtRecordReady, waitTimeout) {
// wait some additional seconds to enlarge probability of record propagation to DNS server use by ACME server
additionalWaitTime := p.settings.AdditionalWait
p.logger.Infof("Waiting additional %d seconds...", int(additionalWaitTime.Seconds()))
time.Sleep(additionalWaitTime)
}
}
return waitTimeout / 2, dns01.DefaultPollingInterval
}
func (p *dnsControllerProvider) waitFor(msg string, isReady func(domain string, values []string) bool, timeout time.Duration) bool {
waitTime := 5 * time.Second
endTime := time.Now().Add(timeout)
pendingDomain := ""
for time.Now().Before(endTime) {
ready := true
for domain, values := range p.presenting {
if !isReady(domain, values) {
pendingDomain = domain
ready = false
break
}
}
if ready {
return true
}
p.logger.Infof("Waiting %d seconds for %s [%s]...", int(waitTime.Seconds()), msg, pendingDomain)
time.Sleep(waitTime)
}
return false
}
func (p *dnsControllerProvider) isDNSTxtRecordReady(domain string, values []string) bool {
fqdn := fmt.Sprintf("_acme-challenge.%s.", domain)
found, _ := utils.CheckDNSPropagation(p.settings.PrecheckNameservers, fqdn, values...)
return found
}