package policies
import (
"context"
"fmt"
acmapi "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/apis/anthoscertmanager/v1"
acmlisters "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/client/listers/anthoscertmanager/v1"
"gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/controller/certificates"
logf "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/logs"
"gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/util/predicate"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
corelisters "k8s.io/client-go/listers/core/v1"
)
// Gatherer is used to gather data about a Certificate in order to evaluate
// its current readiness/state by applying policy functions to it.
type Gatherer struct {
CertificateRequestLister acmlisters.CertificateRequestLister
SecretLister corelisters.SecretLister
}
// DataForCertificate returns the secret as well as the
// certificate request associated with the given certificate.
func (g *Gatherer) DataForCertificate(ctx context.Context, crt *acmapi.Certificate) (Input, error) {
log := logf.FromContext(ctx)
// attempts to fetch the secret being managed.
secret, err := g.SecretLister.Secrets(crt.Namespace).Get(crt.Spec.SecretName)
if err != nil && apierrors.IsNotFound(err) {
return Input{}, err
}
// For the first time creation, the Status.Revision is nil, so we can skip the check.
var curCr *acmapi.CertificateRequest
if crt.Status.Revision != nil {
reqs, err := certificates.ListCertificateRequestsMatchingPredicates(g.CertificateRequestLister.CertificateRequests(crt.Namespace),
labels.Everything(),
predicate.ResourceOwnedBy(crt),
predicate.CertificateRequestRevision(*crt.Status.Revision))
if err != nil {
return Input{}, err
}
switch {
case len(reqs) > 1:
return Input{}, fmt.Errorf("multiple CertificateRequests were found for the 'current' revision %v, issuance is skipped until there are no more duplicates", *crt.Status.Revision)
case len(reqs) == 1:
curCr = reqs[0]
case len(reqs) == 0:
log.V(logf.DebugLevel).Info("Found no CertificateRequest resources owned by this Certificate for the current revision", "revision", *crt.Status.Revision)
}
}
return Input{
Certificate: crt,
Secret: secret,
CurrentRevisionRequest: curCr,
}, nil
}