Download cert-manager_1/solution/solution.patch from lolbench26/LoLBench: direct link, hf CLI and curl.
- Browser
- Download file 92.5 kB
-
https://huggingface.co/datasets/lolbench26/LoLBench/resolve/main/cert-manager_1/solution/solution.patch
- Command line
-
hf download hf://datasets/lolbench26/LoLBench/cert-manager_1/solution/solution.patch
-
curl -L -o solution.patch https://huggingface.co/datasets/lolbench26/LoLBench/resolve/main/cert-manager_1/solution/solution.patch
92.5 kB
| diff --git a/internal/apis/certmanager/types_certificate.go b/internal/apis/certmanager/types_certificate.go | |
| index 5c7aed2e2..8336ee437 100644 | |
| --- a/internal/apis/certmanager/types_certificate.go | |
| +++ b/internal/apis/certmanager/types_certificate.go | |
| type CertificateSpec struct { | |
| // +optional | |
| RenewBeforePercentage *int32 | |
| + // `renewal` allows configuration of how your certificate is renewed. If the policy mentioned is | |
| + // `RenewBefore` then the controller respects `renewBefore` and `renewBeforePercentage`. | |
| + // +optional | |
| + Renewal *CertificateRenewal | |
| + | |
| // Requested DNS subject alternative names. | |
| DNSNames []string | |
| const ( | |
| Modern2023PKCS12Profile PKCS12Profile = "Modern2023" | |
| ) | |
| +type CertificateRenewal struct { | |
| + // `policy` must be one of `Disabled`, `RenewBefore`. | |
| + Policy CertificateRenewalPolicy | |
| + | |
| + // `windows` mentions the behavior of when the renewal must happen. | |
| + Windows []CertificateRenewalWindows | |
| +} | |
| + | |
| +type CertificateRenewalPolicy string | |
| + | |
| +const ( | |
| + RenewBefore CertificateRenewalPolicy = "RenewBefore" | |
| + Disabled CertificateRenewalPolicy = "Disabled" | |
| +) | |
| + | |
| +// CertificateRenewalWindows is the definition for renewal windows | |
| +type CertificateRenewalWindows struct { | |
| + // `timezone` is IANA compliant timezone. | |
| + Timezone string | |
| + | |
| + // `windowDuration` is how long the cron definition is active for. | |
| + // Value must be in units accepted by Go time.ParseDuration https://golang.org/pkg/time/#ParseDuration. | |
| + WindowDuration *metav1.Duration | |
| + | |
| + // `cron` is a cron compliant string to allow when the renewal should be allowed. | |
| + Cron string | |
| +} | |
| + | |
| // CertificateStatus defines the observed state of Certificate | |
| type CertificateStatus struct { | |
| // List of status conditions to indicate the status of certificates. | |
| diff --git a/internal/apis/certmanager/v1/zz_generated.conversion.go b/internal/apis/certmanager/v1/zz_generated.conversion.go | |
| index 8e7938ea3..0406b318e 100644 | |
| --- a/internal/apis/certmanager/v1/zz_generated.conversion.go | |
| +++ b/internal/apis/certmanager/v1/zz_generated.conversion.go | |
| func RegisterConversions(s *runtime.Scheme) error { | |
| }); err != nil { | |
| return err | |
| } | |
| + if err := s.AddGeneratedConversionFunc((*certmanagerv1.CertificateRenewal)(nil), (*certmanager.CertificateRenewal)(nil), func(a, b interface{}, scope conversion.Scope) error { | |
| + return Convert_v1_CertificateRenewal_To_certmanager_CertificateRenewal(a.(*certmanagerv1.CertificateRenewal), b.(*certmanager.CertificateRenewal), scope) | |
| + }); err != nil { | |
| + return err | |
| + } | |
| + if err := s.AddGeneratedConversionFunc((*certmanager.CertificateRenewal)(nil), (*certmanagerv1.CertificateRenewal)(nil), func(a, b interface{}, scope conversion.Scope) error { | |
| + return Convert_certmanager_CertificateRenewal_To_v1_CertificateRenewal(a.(*certmanager.CertificateRenewal), b.(*certmanagerv1.CertificateRenewal), scope) | |
| + }); err != nil { | |
| + return err | |
| + } | |
| + if err := s.AddGeneratedConversionFunc((*certmanagerv1.CertificateRenewalWindows)(nil), (*certmanager.CertificateRenewalWindows)(nil), func(a, b interface{}, scope conversion.Scope) error { | |
| + return Convert_v1_CertificateRenewalWindows_To_certmanager_CertificateRenewalWindows(a.(*certmanagerv1.CertificateRenewalWindows), b.(*certmanager.CertificateRenewalWindows), scope) | |
| + }); err != nil { | |
| + return err | |
| + } | |
| + if err := s.AddGeneratedConversionFunc((*certmanager.CertificateRenewalWindows)(nil), (*certmanagerv1.CertificateRenewalWindows)(nil), func(a, b interface{}, scope conversion.Scope) error { | |
| + return Convert_certmanager_CertificateRenewalWindows_To_v1_CertificateRenewalWindows(a.(*certmanager.CertificateRenewalWindows), b.(*certmanagerv1.CertificateRenewalWindows), scope) | |
| + }); err != nil { | |
| + return err | |
| + } | |
| if err := s.AddGeneratedConversionFunc((*certmanagerv1.CertificateRequest)(nil), (*certmanager.CertificateRequest)(nil), func(a, b interface{}, scope conversion.Scope) error { | |
| return Convert_v1_CertificateRequest_To_certmanager_CertificateRequest(a.(*certmanagerv1.CertificateRequest), b.(*certmanager.CertificateRequest), scope) | |
| }); err != nil { | |
| func Convert_certmanager_CertificatePrivateKey_To_v1_CertificatePrivateKey(in *c | |
| return autoConvert_certmanager_CertificatePrivateKey_To_v1_CertificatePrivateKey(in, out, s) | |
| } | |
| +func autoConvert_v1_CertificateRenewal_To_certmanager_CertificateRenewal(in *certmanagerv1.CertificateRenewal, out *certmanager.CertificateRenewal, s conversion.Scope) error { | |
| + out.Policy = certmanager.CertificateRenewalPolicy(in.Policy) | |
| + out.Windows = *(*[]certmanager.CertificateRenewalWindows)(unsafe.Pointer(&in.Windows)) | |
| + return nil | |
| +} | |
| + | |
| +// Convert_v1_CertificateRenewal_To_certmanager_CertificateRenewal is an autogenerated conversion function. | |
| +func Convert_v1_CertificateRenewal_To_certmanager_CertificateRenewal(in *certmanagerv1.CertificateRenewal, out *certmanager.CertificateRenewal, s conversion.Scope) error { | |
| + return autoConvert_v1_CertificateRenewal_To_certmanager_CertificateRenewal(in, out, s) | |
| +} | |
| + | |
| +func autoConvert_certmanager_CertificateRenewal_To_v1_CertificateRenewal(in *certmanager.CertificateRenewal, out *certmanagerv1.CertificateRenewal, s conversion.Scope) error { | |
| + out.Policy = certmanagerv1.CertificateRenewalPolicy(in.Policy) | |
| + out.Windows = *(*[]certmanagerv1.CertificateRenewalWindows)(unsafe.Pointer(&in.Windows)) | |
| + return nil | |
| +} | |
| + | |
| +// Convert_certmanager_CertificateRenewal_To_v1_CertificateRenewal is an autogenerated conversion function. | |
| +func Convert_certmanager_CertificateRenewal_To_v1_CertificateRenewal(in *certmanager.CertificateRenewal, out *certmanagerv1.CertificateRenewal, s conversion.Scope) error { | |
| + return autoConvert_certmanager_CertificateRenewal_To_v1_CertificateRenewal(in, out, s) | |
| +} | |
| + | |
| +func autoConvert_v1_CertificateRenewalWindows_To_certmanager_CertificateRenewalWindows(in *certmanagerv1.CertificateRenewalWindows, out *certmanager.CertificateRenewalWindows, s conversion.Scope) error { | |
| + out.Timezone = in.Timezone | |
| + out.WindowDuration = (*metav1.Duration)(unsafe.Pointer(in.WindowDuration)) | |
| + out.Cron = in.Cron | |
| + return nil | |
| +} | |
| + | |
| +// Convert_v1_CertificateRenewalWindows_To_certmanager_CertificateRenewalWindows is an autogenerated conversion function. | |
| +func Convert_v1_CertificateRenewalWindows_To_certmanager_CertificateRenewalWindows(in *certmanagerv1.CertificateRenewalWindows, out *certmanager.CertificateRenewalWindows, s conversion.Scope) error { | |
| + return autoConvert_v1_CertificateRenewalWindows_To_certmanager_CertificateRenewalWindows(in, out, s) | |
| +} | |
| + | |
| +func autoConvert_certmanager_CertificateRenewalWindows_To_v1_CertificateRenewalWindows(in *certmanager.CertificateRenewalWindows, out *certmanagerv1.CertificateRenewalWindows, s conversion.Scope) error { | |
| + out.Timezone = in.Timezone | |
| + out.WindowDuration = (*metav1.Duration)(unsafe.Pointer(in.WindowDuration)) | |
| + out.Cron = in.Cron | |
| + return nil | |
| +} | |
| + | |
| +// Convert_certmanager_CertificateRenewalWindows_To_v1_CertificateRenewalWindows is an autogenerated conversion function. | |
| +func Convert_certmanager_CertificateRenewalWindows_To_v1_CertificateRenewalWindows(in *certmanager.CertificateRenewalWindows, out *certmanagerv1.CertificateRenewalWindows, s conversion.Scope) error { | |
| + return autoConvert_certmanager_CertificateRenewalWindows_To_v1_CertificateRenewalWindows(in, out, s) | |
| +} | |
| + | |
| func autoConvert_v1_CertificateRequest_To_certmanager_CertificateRequest(in *certmanagerv1.CertificateRequest, out *certmanager.CertificateRequest, s conversion.Scope) error { | |
| out.ObjectMeta = in.ObjectMeta | |
| if err := Convert_v1_CertificateRequestSpec_To_certmanager_CertificateRequestSpec(&in.Spec, &out.Spec, s); err != nil { | |
| func autoConvert_v1_CertificateSpec_To_certmanager_CertificateSpec(in *certmanag | |
| out.Duration = (*metav1.Duration)(unsafe.Pointer(in.Duration)) | |
| out.RenewBefore = (*metav1.Duration)(unsafe.Pointer(in.RenewBefore)) | |
| out.RenewBeforePercentage = (*int32)(unsafe.Pointer(in.RenewBeforePercentage)) | |
| + out.Renewal = (*certmanager.CertificateRenewal)(unsafe.Pointer(in.Renewal)) | |
| out.DNSNames = *(*[]string)(unsafe.Pointer(&in.DNSNames)) | |
| out.IPAddresses = *(*[]string)(unsafe.Pointer(&in.IPAddresses)) | |
| out.URIs = *(*[]string)(unsafe.Pointer(&in.URIs)) | |
| func autoConvert_certmanager_CertificateSpec_To_v1_CertificateSpec(in *certmanag | |
| out.Duration = (*metav1.Duration)(unsafe.Pointer(in.Duration)) | |
| out.RenewBefore = (*metav1.Duration)(unsafe.Pointer(in.RenewBefore)) | |
| out.RenewBeforePercentage = (*int32)(unsafe.Pointer(in.RenewBeforePercentage)) | |
| + out.Renewal = (*certmanagerv1.CertificateRenewal)(unsafe.Pointer(in.Renewal)) | |
| out.DNSNames = *(*[]string)(unsafe.Pointer(&in.DNSNames)) | |
| out.IPAddresses = *(*[]string)(unsafe.Pointer(&in.IPAddresses)) | |
| out.URIs = *(*[]string)(unsafe.Pointer(&in.URIs)) | |
| diff --git a/internal/apis/certmanager/validation/certificate.go b/internal/apis/certmanager/validation/certificate.go | |
| index de109d223..8a0b9f4f6 100644 | |
| --- a/internal/apis/certmanager/validation/certificate.go | |
| +++ b/internal/apis/certmanager/validation/certificate.go | |
| import ( | |
| "github.com/cert-manager/cert-manager/internal/webhook/feature" | |
| "github.com/cert-manager/cert-manager/pkg/api/util" | |
| cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" | |
| + utilpkg "github.com/cert-manager/cert-manager/pkg/util" | |
| utilfeature "github.com/cert-manager/cert-manager/pkg/util/feature" | |
| "github.com/cert-manager/cert-manager/pkg/util/pki" | |
| ) | |
| func ValidateCertificateSpec(crt *internalcmapi.CertificateSpec, fldPath *field. | |
| el = append(el, validateIssuerRef(crt.IssuerRef, fldPath)...) | |
| - var commonName = crt.CommonName | |
| + commonName := crt.CommonName | |
| if crt.LiteralSubject != "" { | |
| if !utilfeature.DefaultFeatureGate.Enabled(feature.LiteralCertificateSubject) { | |
| el = append(el, field.Forbidden(fldPath.Child("literalSubject"), "Feature gate LiteralCertificateSubject must be enabled on both webhook and controller to use the alpha `literalSubject` field")) | |
| func ValidateCertificateSpec(crt *internalcmapi.CertificateSpec, fldPath *field. | |
| el = append(el, validateKeystores(crt, fldPath)...) | |
| } | |
| + if crt.Renewal != nil { | |
| + el = append(el, validateCertificateRenewal(crt, fldPath)...) | |
| + } | |
| + | |
| return el | |
| } | |
| func validateKeystores(crt *internalcmapi.CertificateSpec, fldPath *field.Path) | |
| return el | |
| } | |
| + | |
| +func validateCertificateRenewal(crt *internalcmapi.CertificateSpec, fldPath *field.Path) field.ErrorList { | |
| + var el field.ErrorList | |
| + switch crt.Renewal.Policy { | |
| + case internalcmapi.RenewBefore: | |
| + case internalcmapi.Disabled: | |
| + if len(crt.Renewal.Windows) > 0 { | |
| + el = append(el, field.Forbidden(fldPath.Child("renewal", "windows"), "windows cannot be set when `renewal.policy` is set to Disabled")) | |
| + } | |
| + return el | |
| + default: | |
| + el = append(el, field.NotSupported(fldPath.Child("renewal", "policy"), crt.Renewal.Policy, []string{string(internalcmapi.Disabled), string(internalcmapi.RenewBefore)})) | |
| + } | |
| + | |
| + if crt.Renewal.Windows != nil { | |
| + for i, window := range crt.Renewal.Windows { | |
| + el = append(el, validateCertificateRenewalWindows(window, fldPath.Child("renewal", "windows").Index(i))...) | |
| + } | |
| + } | |
| + | |
| + return el | |
| +} | |
| + | |
| +func validateCertificateRenewalWindows(window internalcmapi.CertificateRenewalWindows, fldPath *field.Path) field.ErrorList { | |
| + var el field.ErrorList | |
| + | |
| + if window.WindowDuration == nil { | |
| + el = append(el, field.Required(fldPath.Child("windowDuration"), "windowDuration must be specified and should be greater than 0")) | |
| + } | |
| + | |
| + if _, err := time.LoadLocation(window.Timezone); err != nil && window.Timezone != "" { | |
| + el = append(el, field.Invalid(fldPath.Child("timezone"), window.Timezone, "invalid value for timezone. timezone must be IANA compliant")) | |
| + } | |
| + | |
| + if _, err := utilpkg.CronParse(window.Cron, window.Timezone); err != nil { | |
| + el = append(el, field.Invalid(fldPath.Child("cron"), window.Cron, fmt.Sprintf("invalid cron syntax: %s. cron needs to follow: cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow", err.Error()))) | |
| + } | |
| + | |
| + return el | |
| +} | |
| diff --git a/internal/apis/certmanager/zz_generated.deepcopy.go b/internal/apis/certmanager/zz_generated.deepcopy.go | |
| index d64f9cd5e..87ac6cbeb 100644 | |
| --- a/internal/apis/certmanager/zz_generated.deepcopy.go | |
| +++ b/internal/apis/certmanager/zz_generated.deepcopy.go | |
| func (in *CertificatePrivateKey) DeepCopy() *CertificatePrivateKey { | |
| return out | |
| } | |
| +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. | |
| +func (in *CertificateRenewal) DeepCopyInto(out *CertificateRenewal) { | |
| + *out = *in | |
| + if in.Windows != nil { | |
| + in, out := &in.Windows, &out.Windows | |
| + *out = make([]CertificateRenewalWindows, len(*in)) | |
| + for i := range *in { | |
| + (*in)[i].DeepCopyInto(&(*out)[i]) | |
| + } | |
| + } | |
| + return | |
| +} | |
| + | |
| +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertificateRenewal. | |
| +func (in *CertificateRenewal) DeepCopy() *CertificateRenewal { | |
| + if in == nil { | |
| + return nil | |
| + } | |
| + out := new(CertificateRenewal) | |
| + in.DeepCopyInto(out) | |
| + return out | |
| +} | |
| + | |
| +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. | |
| +func (in *CertificateRenewalWindows) DeepCopyInto(out *CertificateRenewalWindows) { | |
| + *out = *in | |
| + if in.WindowDuration != nil { | |
| + in, out := &in.WindowDuration, &out.WindowDuration | |
| + *out = new(v1.Duration) | |
| + **out = **in | |
| + } | |
| + return | |
| +} | |
| + | |
| +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertificateRenewalWindows. | |
| +func (in *CertificateRenewalWindows) DeepCopy() *CertificateRenewalWindows { | |
| + if in == nil { | |
| + return nil | |
| + } | |
| + out := new(CertificateRenewalWindows) | |
| + in.DeepCopyInto(out) | |
| + return out | |
| +} | |
| + | |
| // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. | |
| func (in *CertificateRequest) DeepCopyInto(out *CertificateRequest) { | |
| *out = *in | |
| func (in *CertificateSpec) DeepCopyInto(out *CertificateSpec) { | |
| *out = new(int32) | |
| **out = **in | |
| } | |
| + if in.Renewal != nil { | |
| + in, out := &in.Renewal, &out.Renewal | |
| + *out = new(CertificateRenewal) | |
| + (*in).DeepCopyInto(*out) | |
| + } | |
| if in.DNSNames != nil { | |
| in, out := &in.DNSNames, &out.DNSNames | |
| *out = make([]string, len(*in)) | |
| diff --git a/internal/controller/certificates/policies/checks.go b/internal/controller/certificates/policies/checks.go | |
| index 02d6fa980..83afaccf7 100644 | |
| --- a/internal/controller/certificates/policies/checks.go | |
| +++ b/internal/controller/certificates/policies/checks.go | |
| func CurrentCertificateNearingExpiry(c clock.Clock) Func { | |
| notBefore := metav1.NewTime(x509Cert.NotBefore) | |
| notAfter := metav1.NewTime(x509Cert.NotAfter) | |
| crt := input.Certificate | |
| - renewalTime := pki.RenewalTime(notBefore.Time, notAfter.Time, crt.Spec.RenewBefore, crt.Spec.RenewBeforePercentage) | |
| + | |
| + reason := Renewing | |
| + message := fmt.Sprintf("Renewing certificate as renewal was scheduled at %s", input.Certificate.Status.RenewalTime) | |
| + | |
| + renewalTime, err := pki.RenewalTime(notBefore.Time, notAfter.Time, crt.Spec.RenewBefore, crt.Spec.RenewBeforePercentage, crt.Spec.Renewal) | |
| + if err != nil { | |
| + reason = WindowError | |
| + message = err.Error() | |
| + } | |
| renewIn := renewalTime.Time.Sub(c.Now()) | |
| if renewIn > 0 { | |
| func CurrentCertificateNearingExpiry(c clock.Clock) Func { | |
| return "", "", false | |
| } | |
| - return Renewing, fmt.Sprintf("Renewing certificate as renewal was scheduled at %s", input.Certificate.Status.RenewalTime), true | |
| + return reason, message, true | |
| } | |
| } | |
| func formatIssuerRef(name, kind, group string) string { | |
| return fmt.Sprintf("%s.%s/%s", kind, group, name) | |
| } | |
| -const defaultIssuerKind = "Issuer" | |
| -const defaultIssuerGroup = "cert-manager.io" | |
| +const ( | |
| + defaultIssuerKind = "Issuer" | |
| + defaultIssuerGroup = "cert-manager.io" | |
| +) | |
| func issuerKindsEqual(l, r string) bool { | |
| if l == "" { | |
| diff --git a/internal/controller/certificates/policies/constants.go b/internal/controller/certificates/policies/constants.go | |
| index ba320fdc9..d6493d2cd 100644 | |
| --- a/internal/controller/certificates/policies/constants.go | |
| +++ b/internal/controller/certificates/policies/constants.go | |
| const ( | |
| // Expired is a policy violation reason for a scenario where Certificate has | |
| // expired. | |
| Expired string = "Expired" | |
| + // WindowError is a policy violation for a scenario where a time couldn't be | |
| + // found due to a cron misconfiguration or validation. | |
| + WindowError string = "WindowError" | |
| // SecretTemplateMismatch is a policy violation whereby the Certificate's | |
| // SecretTemplate is not reflected on the target Secret, either by having | |
| // extra, missing, or wrong Annotations or Labels. | |
| diff --git a/internal/cron/constantdelay.go b/internal/cron/constantdelay.go | |
| new file mode 100644 | |
| index 000000000..b359ce17b | |
| --- /dev/null | |
| +++ b/internal/cron/constantdelay.go | |
| +// +skip_license_check | |
| + | |
| +/* | |
| +This file contains portions of code directly taken from the 'robfig/cron' project. | |
| +A copy of the license for this code can be found in the file named LICENSE in | |
| +this directory. | |
| +*/ | |
| + | |
| +package cron | |
| + | |
| +import "time" | |
| + | |
| +// ConstantDelaySchedule represents a simple recurring duty cycle, e.g. "Every 5 minutes". | |
| +// It does not support jobs more frequent than once a second. | |
| +type ConstantDelaySchedule struct { | |
| + Delay time.Duration | |
| +} | |
| + | |
| +// Every returns a crontab Schedule that activates once every duration. | |
| +// Delays of less than a second are not supported (will round up to 1 second). | |
| +// Any fields less than a Second are truncated. | |
| +func Every(duration time.Duration) ConstantDelaySchedule { | |
| + if duration < time.Second { | |
| + duration = time.Second | |
| + } | |
| + return ConstantDelaySchedule{ | |
| + Delay: duration - time.Duration(duration.Nanoseconds())%time.Second, | |
| + } | |
| +} | |
| + | |
| +// Next returns the next time this should be run. | |
| +// This rounds so that the next activation time will be on the second. | |
| +func (schedule ConstantDelaySchedule) Next(t time.Time) time.Time { | |
| + return t.Add(schedule.Delay - time.Duration(t.Nanosecond())*time.Nanosecond) | |
| +} | |
| diff --git a/internal/cron/cron.go b/internal/cron/cron.go | |
| new file mode 100644 | |
| index 000000000..2f6f372b4 | |
| --- /dev/null | |
| +++ b/internal/cron/cron.go | |
| +// +skip_license_check | |
| + | |
| +/* | |
| +This file contains portions of code directly taken from the 'robfig/cron' project. | |
| +A copy of the license for this code can be found in the file named LICENSE in | |
| +this directory. | |
| +*/ | |
| + | |
| +package cron | |
| + | |
| +import ( | |
| + "context" | |
| + "sort" | |
| + "sync" | |
| + "time" | |
| +) | |
| + | |
| +// Cron keeps track of any number of entries, invoking the associated func as | |
| +// specified by the schedule. It may be started, stopped, and the entries may | |
| +// be inspected while running. | |
| +type Cron struct { | |
| + entries []*Entry | |
| + stop chan struct{} | |
| + add chan *Entry | |
| + remove chan EntryID | |
| + snapshot chan chan []Entry | |
| + running bool | |
| + logger Logger | |
| + runningMu sync.Mutex | |
| + location *time.Location | |
| + parser Parser | |
| + nextID EntryID | |
| + jobWaiter sync.WaitGroup | |
| +} | |
| + | |
| +// Job is an interface for submitted cron jobs. | |
| +type Job interface { | |
| + Run() | |
| +} | |
| + | |
| +// Schedule describes a job's duty cycle. | |
| +type Schedule interface { | |
| + // Next returns the next activation time, later than the given time. | |
| + // Next is invoked initially, and then each time the job is run. | |
| + Next(time.Time) time.Time | |
| +} | |
| + | |
| +// EntryID identifies an entry within a Cron instance | |
| +type EntryID int | |
| + | |
| +// Entry consists of a schedule and the func to execute on that schedule. | |
| +type Entry struct { | |
| + // ID is the cron-assigned ID of this entry, which may be used to look up a | |
| + // snapshot or remove it. | |
| + ID EntryID | |
| + | |
| + // Schedule on which this job should be run. | |
| + Schedule Schedule | |
| + | |
| + // Next time the job will run, or the zero time if Cron has not been | |
| + // started or this entry's schedule is unsatisfiable | |
| + Next time.Time | |
| + | |
| + // Prev is the last time this job was run, or the zero time if never. | |
| + Prev time.Time | |
| + | |
| + // WrappedJob is the thing to run when the Schedule is activated. | |
| + WrappedJob Job | |
| + | |
| + // Job is the thing that was submitted to cron. | |
| + // It is kept around so that user code that needs to get at the job later, | |
| + // e.g. via Entries() can do so. | |
| + Job Job | |
| +} | |
| + | |
| +// Valid returns true if this is not the zero entry. | |
| +func (e Entry) Valid() bool { return e.ID != 0 } | |
| + | |
| +// byTime is a wrapper for sorting the entry array by time | |
| +// (with zero time at the end). | |
| +type byTime []*Entry | |
| + | |
| +func (s byTime) Len() int { return len(s) } | |
| +func (s byTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] } | |
| +func (s byTime) Less(i, j int) bool { | |
| + // Two zero times should return false. | |
| + // Otherwise, zero is "greater" than any other time. | |
| + // (To sort it at the end of the list.) | |
| + if s[i].Next.IsZero() { | |
| + return false | |
| + } | |
| + if s[j].Next.IsZero() { | |
| + return true | |
| + } | |
| + return s[i].Next.Before(s[j].Next) | |
| +} | |
| + | |
| +// New returns a new Cron job runner, modified by the given options. | |
| +// | |
| +// Available Settings | |
| +// | |
| +// Time Zone | |
| +// Description: The time zone in which schedules are interpreted | |
| +// Default: time.Local | |
| +// | |
| +// Parser | |
| +// Description: Parser converts cron spec strings into cron.Schedules. | |
| +// Default: Accepts this spec: https://en.wikipedia.org/wiki/Cron | |
| +// | |
| +// Chain | |
| +// Description: Wrap submitted jobs to customize behavior. | |
| +// Default: A chain that recovers panics and logs them to stderr. | |
| +// | |
| +// See "cron.With*" to modify the default behavior. | |
| +func New(opts ...Option) *Cron { | |
| + c := &Cron{ | |
| + entries: nil, | |
| + add: make(chan *Entry), | |
| + stop: make(chan struct{}), | |
| + snapshot: make(chan chan []Entry), | |
| + remove: make(chan EntryID), | |
| + running: false, | |
| + runningMu: sync.Mutex{}, | |
| + logger: DefaultLogger, | |
| + location: time.Local, //nolint: gosmopolitan // This is just a default | |
| + parser: standardParser, | |
| + } | |
| + for _, opt := range opts { | |
| + opt(c) | |
| + } | |
| + return c | |
| +} | |
| + | |
| +// FuncJob is a wrapper that turns a func() into a cron.Job | |
| +type FuncJob func() | |
| + | |
| +func (f FuncJob) Run() { f() } | |
| + | |
| +// AddFunc adds a func to the Cron to be run on the given schedule. | |
| +// The spec is parsed using the time zone of this Cron instance as the default. | |
| +// An opaque ID is returned that can be used to later remove it. | |
| +func (c *Cron) AddFunc(spec string, cmd func()) (EntryID, error) { | |
| + return c.AddJob(spec, FuncJob(cmd)) | |
| +} | |
| + | |
| +// AddJob adds a Job to the Cron to be run on the given schedule. | |
| +// The spec is parsed using the time zone of this Cron instance as the default. | |
| +// An opaque ID is returned that can be used to later remove it. | |
| +func (c *Cron) AddJob(spec string, cmd Job) (EntryID, error) { | |
| + schedule, err := c.parser.Parse(spec) | |
| + if err != nil { | |
| + return 0, err | |
| + } | |
| + return c.Schedule(schedule, cmd), nil | |
| +} | |
| + | |
| +// Schedule adds a Job to the Cron to be run on the given schedule. | |
| +// The job is wrapped with the configured Chain. | |
| +func (c *Cron) Schedule(schedule Schedule, cmd Job) EntryID { | |
| + c.runningMu.Lock() | |
| + defer c.runningMu.Unlock() | |
| + c.nextID++ | |
| + entry := &Entry{ | |
| + ID: c.nextID, | |
| + Schedule: schedule, | |
| + Job: cmd, | |
| + } | |
| + if !c.running { | |
| + c.entries = append(c.entries, entry) | |
| + } else { | |
| + c.add <- entry | |
| + } | |
| + return entry.ID | |
| +} | |
| + | |
| +// Entries returns a snapshot of the cron entries. | |
| +func (c *Cron) Entries() []Entry { | |
| + c.runningMu.Lock() | |
| + defer c.runningMu.Unlock() | |
| + if c.running { | |
| + replyChan := make(chan []Entry, 1) | |
| + c.snapshot <- replyChan | |
| + return <-replyChan | |
| + } | |
| + return c.entrySnapshot() | |
| +} | |
| + | |
| +// Location gets the time zone location | |
| +func (c *Cron) Location() *time.Location { | |
| + return c.location | |
| +} | |
| + | |
| +// Entry returns a snapshot of the given entry, or nil if it couldn't be found. | |
| +func (c *Cron) Entry(id EntryID) Entry { | |
| + for _, entry := range c.Entries() { | |
| + if id == entry.ID { | |
| + return entry | |
| + } | |
| + } | |
| + return Entry{} | |
| +} | |
| + | |
| +// Remove an entry from being run in the future. | |
| +func (c *Cron) Remove(id EntryID) { | |
| + c.runningMu.Lock() | |
| + defer c.runningMu.Unlock() | |
| + if c.running { | |
| + c.remove <- id | |
| + } else { | |
| + c.removeEntry(id) | |
| + } | |
| +} | |
| + | |
| +// Start the cron scheduler in its own goroutine, or no-op if already started. | |
| +func (c *Cron) Start() { | |
| + c.runningMu.Lock() | |
| + defer c.runningMu.Unlock() | |
| + if c.running { | |
| + return | |
| + } | |
| + c.running = true | |
| + go c.run() | |
| +} | |
| + | |
| +// Run the cron scheduler, or no-op if already running. | |
| +func (c *Cron) Run() { | |
| + c.runningMu.Lock() | |
| + if c.running { | |
| + c.runningMu.Unlock() | |
| + return | |
| + } | |
| + c.running = true | |
| + c.runningMu.Unlock() | |
| + c.run() | |
| +} | |
| + | |
| +// run the scheduler.. this is private just due to the need to synchronize | |
| +// access to the 'running' state variable. | |
| +func (c *Cron) run() { | |
| + c.logger.Info("start") | |
| + | |
| + // Figure out the next activation times for each entry. | |
| + now := c.now() | |
| + for _, entry := range c.entries { | |
| + entry.Next = entry.Schedule.Next(now) | |
| + c.logger.Info("schedule", "now", now, "entry", entry.ID, "next", entry.Next) | |
| + } | |
| + | |
| + for { | |
| + // Determine the next entry to run. | |
| + sort.Sort(byTime(c.entries)) | |
| + | |
| + var timer *time.Timer | |
| + if len(c.entries) == 0 || c.entries[0].Next.IsZero() { | |
| + // If there are no entries yet, just sleep - it still handles new entries | |
| + // and stop requests. | |
| + timer = time.NewTimer(100000 * time.Hour) | |
| + } else { | |
| + timer = time.NewTimer(c.entries[0].Next.Sub(now)) | |
| + } | |
| + | |
| + for { | |
| + select { | |
| + case now = <-timer.C: | |
| + now = now.In(c.location) | |
| + c.logger.Info("wake", "now", now) | |
| + | |
| + // Run every entry whose next time was less than now | |
| + for _, e := range c.entries { | |
| + if e.Next.After(now) || e.Next.IsZero() { | |
| + break | |
| + } | |
| + c.startJob(e.WrappedJob) | |
| + e.Prev = e.Next | |
| + e.Next = e.Schedule.Next(now) | |
| + c.logger.Info("run", "now", now, "entry", e.ID, "next", e.Next) | |
| + } | |
| + | |
| + case newEntry := <-c.add: | |
| + timer.Stop() | |
| + now = c.now() | |
| + newEntry.Next = newEntry.Schedule.Next(now) | |
| + c.entries = append(c.entries, newEntry) | |
| + c.logger.Info("added", "now", now, "entry", newEntry.ID, "next", newEntry.Next) | |
| + | |
| + case replyChan := <-c.snapshot: | |
| + replyChan <- c.entrySnapshot() | |
| + continue | |
| + | |
| + case <-c.stop: | |
| + timer.Stop() | |
| + c.logger.Info("stop") | |
| + return | |
| + | |
| + case id := <-c.remove: | |
| + timer.Stop() | |
| + now = c.now() | |
| + c.removeEntry(id) | |
| + c.logger.Info("removed", "entry", id) | |
| + } | |
| + | |
| + break | |
| + } | |
| + } | |
| +} | |
| + | |
| +// startJob runs the given job in a new goroutine. | |
| +func (c *Cron) startJob(j Job) { | |
| + c.jobWaiter.Go(func() { | |
| + j.Run() | |
| + }) | |
| +} | |
| + | |
| +// now returns current time in c location | |
| +func (c *Cron) now() time.Time { | |
| + return time.Now().In(c.location) | |
| +} | |
| + | |
| +// Stop stops the cron scheduler if it is running; otherwise it does nothing. | |
| +// A context is returned so the caller can wait for running jobs to complete. | |
| +func (c *Cron) Stop() context.Context { | |
| + c.runningMu.Lock() | |
| + defer c.runningMu.Unlock() | |
| + if c.running { | |
| + c.stop <- struct{}{} | |
| + c.running = false | |
| + } | |
| + ctx, cancel := context.WithCancel(context.Background()) | |
| + go func() { | |
| + c.jobWaiter.Wait() | |
| + cancel() | |
| + }() | |
| + return ctx | |
| +} | |
| + | |
| +// entrySnapshot returns a copy of the current cron entry list. | |
| +func (c *Cron) entrySnapshot() []Entry { | |
| + var entries = make([]Entry, len(c.entries)) | |
| + for i, e := range c.entries { | |
| + entries[i] = *e | |
| + } | |
| + return entries | |
| +} | |
| + | |
| +func (c *Cron) removeEntry(id EntryID) { | |
| + var entries []*Entry | |
| + for _, e := range c.entries { | |
| + if e.ID != id { | |
| + entries = append(entries, e) | |
| + } | |
| + } | |
| + c.entries = entries | |
| +} | |
| diff --git a/internal/cron/logger.go b/internal/cron/logger.go | |
| new file mode 100644 | |
| index 000000000..565067f4d | |
| --- /dev/null | |
| +++ b/internal/cron/logger.go | |
| +// +skip_license_check | |
| + | |
| +/* | |
| +This file contains portions of code directly taken from the 'robfig/cron' project. | |
| +A copy of the license for this code can be found in the file named LICENSE in | |
| +this directory. | |
| +*/ | |
| + | |
| +package cron | |
| + | |
| +import ( | |
| + "io" | |
| + "log" | |
| + "os" | |
| + "strings" | |
| + "time" | |
| +) | |
| + | |
| +// DefaultLogger is used by Cron if none is specified. | |
| +var DefaultLogger Logger = PrintfLogger(log.New(os.Stdout, "cron: ", log.LstdFlags)) | |
| + | |
| +// DiscardLogger can be used by callers to discard all log messages. | |
| +var DiscardLogger Logger = PrintfLogger(log.New(io.Discard, "", 0)) | |
| + | |
| +// Logger is the interface used in this package for logging, so that any backend | |
| +// can be plugged in. It is a subset of the github.com/go-logr/logr interface. | |
| +type Logger interface { | |
| + // Info logs routine messages about cron's operation. | |
| + Info(msg string, keysAndValues ...any) | |
| + // Error logs an error condition. | |
| + Error(err error, msg string, keysAndValues ...any) | |
| +} | |
| + | |
| +// PrintfLogger wraps a Printf-based logger (such as the standard library "log") | |
| +// into an implementation of the Logger interface which logs errors only. | |
| +func PrintfLogger(l interface{ Printf(string, ...any) }) Logger { | |
| + return printfLogger{l, false} | |
| +} | |
| + | |
| +// VerbosePrintfLogger wraps a Printf-based logger (such as the standard library | |
| +// "log") into an implementation of the Logger interface which logs everything. | |
| +func VerbosePrintfLogger(l interface{ Printf(string, ...any) }) Logger { | |
| + return printfLogger{l, true} | |
| +} | |
| + | |
| +type printfLogger struct { | |
| + logger interface{ Printf(string, ...any) } | |
| + logInfo bool | |
| +} | |
| + | |
| +func (pl printfLogger) Info(msg string, keysAndValues ...any) { | |
| + if pl.logInfo { | |
| + keysAndValues = formatTimes(keysAndValues) | |
| + pl.logger.Printf( | |
| + formatString(len(keysAndValues)), | |
| + append([]any{msg}, keysAndValues...)...) | |
| + } | |
| +} | |
| + | |
| +func (pl printfLogger) Error(err error, msg string, keysAndValues ...any) { | |
| + keysAndValues = formatTimes(keysAndValues) | |
| + pl.logger.Printf( | |
| + formatString(len(keysAndValues)+2), | |
| + append([]any{msg, "error", err}, keysAndValues...)...) | |
| +} | |
| + | |
| +// formatString returns a logfmt-like format string for the number of | |
| +// key/values. | |
| +func formatString(numKeysAndValues int) string { | |
| + var sb strings.Builder | |
| + sb.WriteString("%s") | |
| + if numKeysAndValues > 0 { | |
| + sb.WriteString(", ") | |
| + } | |
| + for i := range numKeysAndValues / 2 { | |
| + if i > 0 { | |
| + sb.WriteString(", ") | |
| + } | |
| + sb.WriteString("%v=%v") | |
| + } | |
| + return sb.String() | |
| +} | |
| + | |
| +// formatTimes formats any time.Time values as RFC3339. | |
| +func formatTimes(keysAndValues []any) []any { | |
| + var formattedArgs []any | |
| + for _, arg := range keysAndValues { | |
| + if t, ok := arg.(time.Time); ok { | |
| + arg = t.Format(time.RFC3339) | |
| + } | |
| + formattedArgs = append(formattedArgs, arg) | |
| + } | |
| + return formattedArgs | |
| +} | |
| diff --git a/internal/cron/option.go b/internal/cron/option.go | |
| new file mode 100644 | |
| index 000000000..56739c499 | |
| --- /dev/null | |
| +++ b/internal/cron/option.go | |
| +// +skip_license_check | |
| + | |
| +/* | |
| +This file contains portions of code directly taken from the 'robfig/cron' project. | |
| +A copy of the license for this code can be found in the file named LICENSE in | |
| +this directory. | |
| +*/ | |
| + | |
| +package cron | |
| + | |
| +import ( | |
| + "time" | |
| +) | |
| + | |
| +// Option represents a modification to the default behavior of a Cron. | |
| +type Option func(*Cron) | |
| + | |
| +// WithLocation overrides the timezone of the cron instance. | |
| +func WithLocation(loc *time.Location) Option { | |
| + return func(c *Cron) { | |
| + c.location = loc | |
| + } | |
| +} | |
| + | |
| +// WithSeconds overrides the parser used for interpreting job schedules to | |
| +// include a seconds field as the first one. | |
| +func WithSeconds() Option { | |
| + return WithParser(NewParser( | |
| + Second | Minute | Hour | Dom | Month | Dow | Descriptor, | |
| + )) | |
| +} | |
| + | |
| +// WithParser overrides the parser used for interpreting job schedules. | |
| +func WithParser(p Parser) Option { | |
| + return func(c *Cron) { | |
| + c.parser = p | |
| + } | |
| +} | |
| + | |
| +// WithLogger uses the provided logger. | |
| +func WithLogger(logger Logger) Option { | |
| + return func(c *Cron) { | |
| + c.logger = logger | |
| + } | |
| +} | |
| diff --git a/internal/cron/parser.go b/internal/cron/parser.go | |
| new file mode 100644 | |
| index 000000000..ee05d3a22 | |
| --- /dev/null | |
| +++ b/internal/cron/parser.go | |
| +// +skip_license_check | |
| + | |
| +/* | |
| +This file contains portions of code directly taken from the 'robfig/cron' project. | |
| +A copy of the license for this code can be found in the file named LICENSE in | |
| +this directory. | |
| +*/ | |
| + | |
| +package cron | |
| + | |
| +import ( | |
| + "fmt" | |
| + "math" | |
| + "strconv" | |
| + "strings" | |
| + "time" | |
| +) | |
| + | |
| +// Configuration options for creating a parser. Most options specify which | |
| +// fields should be included, while others enable features. If a field is not | |
| +// included the parser will assume a default value. These options do not change | |
| +// the order fields are parse in. | |
| +type ParseOption int | |
| + | |
| +const ( | |
| + Second ParseOption = 1 << iota // Seconds field, default 0 | |
| + SecondOptional // Optional seconds field, default 0 | |
| + Minute // Minutes field, default 0 | |
| + Hour // Hours field, default 0 | |
| + Dom // Day of month field, default * | |
| + Month // Month field, default * | |
| + Dow // Day of week field, default * | |
| + DowOptional // Optional day of week field, default * | |
| + Descriptor // Allow descriptors such as @monthly, @weekly, etc. | |
| +) | |
| + | |
| +var places = []ParseOption{ | |
| + Second, | |
| + Minute, | |
| + Hour, | |
| + Dom, | |
| + Month, | |
| + Dow, | |
| +} | |
| + | |
| +var defaults = []string{ | |
| + "0", | |
| + "0", | |
| + "0", | |
| + "*", | |
| + "*", | |
| + "*", | |
| +} | |
| + | |
| +// A custom Parser that can be configured. | |
| +type Parser struct { | |
| + options ParseOption | |
| +} | |
| + | |
| +// NewParser creates a Parser with custom options. | |
| +// | |
| +// It panics if more than one Optional is given, since it would be impossible to | |
| +// correctly infer which optional is provided or missing in general. | |
| +// | |
| +// Examples | |
| +// | |
| +// // Standard parser without descriptors | |
| +// specParser := NewParser(Minute | Hour | Dom | Month | Dow) | |
| +// sched, err := specParser.Parse("0 0 15 */3 *") | |
| +// | |
| +// // Same as above, just excludes time fields | |
| +// subsParser := NewParser(Dom | Month | Dow) | |
| +// sched, err := specParser.Parse("15 */3 *") | |
| +// | |
| +// // Same as above, just makes Dow optional | |
| +// subsParser := NewParser(Dom | Month | DowOptional) | |
| +// sched, err := specParser.Parse("15 */3") | |
| +func NewParser(options ParseOption) Parser { | |
| + optionals := 0 | |
| + if options&DowOptional > 0 { | |
| + optionals++ | |
| + } | |
| + if options&SecondOptional > 0 { | |
| + optionals++ | |
| + } | |
| + if optionals > 1 { | |
| + panic("multiple optionals may not be configured") | |
| + } | |
| + return Parser{options} | |
| +} | |
| + | |
| +// Parse returns a new crontab schedule representing the given spec. | |
| +// It returns a descriptive error if the spec is not valid. | |
| +// It accepts crontab specs and features configured by NewParser. | |
| +func (p Parser) Parse(spec string) (Schedule, error) { | |
| + if len(spec) == 0 { | |
| + return nil, fmt.Errorf("empty spec string") | |
| + } | |
| + | |
| + // Extract timezone if present | |
| + //nolint: gosmopolitan // this makes sense as it also handles other locations below | |
| + var loc = time.Local | |
| + if strings.HasPrefix(spec, "TZ=") || strings.HasPrefix(spec, "CRON_TZ=") { | |
| + var err error | |
| + i := strings.Index(spec, " ") | |
| + eq := strings.Index(spec, "=") | |
| + if loc, err = time.LoadLocation(spec[eq+1 : i]); err != nil { | |
| + return nil, fmt.Errorf("provided bad location %s: %v", spec[eq+1:i], err) | |
| + } | |
| + spec = strings.TrimSpace(spec[i:]) | |
| + } | |
| + | |
| + // Handle named schedules (descriptors), if configured | |
| + if strings.HasPrefix(spec, "@") { | |
| + if p.options&Descriptor == 0 { | |
| + return nil, fmt.Errorf("parser does not accept descriptors: %v", spec) | |
| + } | |
| + return parseDescriptor(spec, loc) | |
| + } | |
| + | |
| + // Split on whitespace. | |
| + fields := strings.Fields(spec) | |
| + | |
| + // Validate & fill in any omitted or optional fields | |
| + var err error | |
| + fields, err = normalizeFields(fields, p.options) | |
| + if err != nil { | |
| + return nil, err | |
| + } | |
| + | |
| + field := func(field string, r bounds) uint64 { | |
| + if err != nil { | |
| + return 0 | |
| + } | |
| + var bits uint64 | |
| + bits, err = getField(field, r) | |
| + return bits | |
| + } | |
| + | |
| + var ( | |
| + second = field(fields[0], seconds) | |
| + minute = field(fields[1], minutes) | |
| + hour = field(fields[2], hours) | |
| + dayofmonth = field(fields[3], dom) | |
| + month = field(fields[4], months) | |
| + dayofweek = field(fields[5], dow) | |
| + ) | |
| + if err != nil { | |
| + return nil, err | |
| + } | |
| + | |
| + return &SpecSchedule{ | |
| + Second: second, | |
| + Minute: minute, | |
| + Hour: hour, | |
| + Dom: dayofmonth, | |
| + Month: month, | |
| + Dow: dayofweek, | |
| + Location: loc, | |
| + }, nil | |
| +} | |
| + | |
| +// normalizeFields takes a subset set of the time fields and returns the full set | |
| +// with defaults (zeroes) populated for unset fields. | |
| +// | |
| +// As part of performing this function, it also validates that the provided | |
| +// fields are compatible with the configured options. | |
| +func normalizeFields(fields []string, options ParseOption) ([]string, error) { | |
| + // Validate optionals & add their field to options | |
| + optionals := 0 | |
| + if options&SecondOptional > 0 { | |
| + options |= Second | |
| + optionals++ | |
| + } | |
| + if options&DowOptional > 0 { | |
| + options |= Dow | |
| + optionals++ | |
| + } | |
| + if optionals > 1 { | |
| + return nil, fmt.Errorf("multiple optionals may not be configured") | |
| + } | |
| + | |
| + // Figure out how many fields we need | |
| + maxField := 0 | |
| + for _, place := range places { | |
| + if options&place > 0 { | |
| + maxField++ | |
| + } | |
| + } | |
| + minField := maxField - optionals | |
| + | |
| + // Validate number of fields | |
| + if count := len(fields); count < minField || count > maxField { | |
| + if minField == maxField { | |
| + return nil, fmt.Errorf("expected exactly %d fields, found %d: %s", minField, count, fields) | |
| + } | |
| + return nil, fmt.Errorf("expected %d to %d fields, found %d: %s", minField, maxField, count, fields) | |
| + } | |
| + | |
| + // Populate the optional field if not provided | |
| + if minField < maxField && len(fields) == minField { | |
| + switch { | |
| + case options&DowOptional > 0: | |
| + fields = append(fields, defaults[5]) // TODO: improve access to default | |
| + case options&SecondOptional > 0: | |
| + fields = append([]string{defaults[0]}, fields...) | |
| + default: | |
| + return nil, fmt.Errorf("unknown optional field") | |
| + } | |
| + } | |
| + | |
| + // Populate all fields not part of options with their defaults | |
| + n := 0 | |
| + expandedFields := make([]string, len(places)) | |
| + copy(expandedFields, defaults) | |
| + for i, place := range places { | |
| + if options&place > 0 { | |
| + expandedFields[i] = fields[n] | |
| + n++ | |
| + } | |
| + } | |
| + return expandedFields, nil | |
| +} | |
| + | |
| +var standardParser = NewParser( | |
| + Minute | Hour | Dom | Month | Dow | Descriptor, | |
| +) | |
| + | |
| +// ParseStandard returns a new crontab schedule representing the given | |
| +// standardSpec (https://en.wikipedia.org/wiki/Cron). It requires 5 entries | |
| +// representing: minute, hour, day of month, month and day of week, in that | |
| +// order. It returns a descriptive error if the spec is not valid. | |
| +// | |
| +// It accepts | |
| +// - Standard crontab specs, e.g. "* * * * ?" | |
| +// - Descriptors, e.g. "@midnight", "@every 1h30m" | |
| +func ParseStandard(standardSpec string) (Schedule, error) { | |
| + return standardParser.Parse(standardSpec) | |
| +} | |
| + | |
| +// getField returns an Int with the bits set representing all of the times that | |
| +// the field represents or error parsing field value. A "field" is a comma-separated | |
| +// list of "ranges". | |
| +func getField(field string, r bounds) (uint64, error) { | |
| + var bits uint64 | |
| + ranges := strings.FieldsFunc(field, func(r rune) bool { return r == ',' }) | |
| + for _, expr := range ranges { | |
| + bit, err := getRange(expr, r) | |
| + if err != nil { | |
| + return bits, err | |
| + } | |
| + bits |= bit | |
| + } | |
| + return bits, nil | |
| +} | |
| + | |
| +// getRange returns the bits indicated by the given expression: | |
| +// | |
| +// number | number "-" number [ "/" number ] | |
| +// | |
| +// or error parsing range. | |
| +func getRange(expr string, r bounds) (uint64, error) { | |
| + var ( | |
| + start, end, step uint | |
| + rangeAndStep = strings.Split(expr, "/") | |
| + lowAndHigh = strings.Split(rangeAndStep[0], "-") | |
| + singleDigit = len(lowAndHigh) == 1 | |
| + err error | |
| + ) | |
| + | |
| + var extra uint64 | |
| + if lowAndHigh[0] == "*" || lowAndHigh[0] == "?" { | |
| + start = r.min | |
| + end = r.max | |
| + extra = starBit | |
| + } else { | |
| + start, err = parseIntOrName(lowAndHigh[0], r.names) | |
| + if err != nil { | |
| + return 0, err | |
| + } | |
| + switch len(lowAndHigh) { | |
| + case 1: | |
| + end = start | |
| + case 2: | |
| + end, err = parseIntOrName(lowAndHigh[1], r.names) | |
| + if err != nil { | |
| + return 0, err | |
| + } | |
| + default: | |
| + return 0, fmt.Errorf("too many hyphens: %s", expr) | |
| + } | |
| + } | |
| + | |
| + switch len(rangeAndStep) { | |
| + case 1: | |
| + step = 1 | |
| + case 2: | |
| + step, err = mustParseInt(rangeAndStep[1]) | |
| + if err != nil { | |
| + return 0, err | |
| + } | |
| + | |
| + // Special handling: "N/step" means "N-max/step". | |
| + if singleDigit { | |
| + end = r.max | |
| + } | |
| + if step > 1 { | |
| + extra = 0 | |
| + } | |
| + default: | |
| + return 0, fmt.Errorf("too many slashes: %s", expr) | |
| + } | |
| + | |
| + if start < r.min { | |
| + return 0, fmt.Errorf("beginning of range (%d) below minimum (%d): %s", start, r.min, expr) | |
| + } | |
| + if end > r.max { | |
| + return 0, fmt.Errorf("end of range (%d) above maximum (%d): %s", end, r.max, expr) | |
| + } | |
| + if start > end { | |
| + return 0, fmt.Errorf("beginning of range (%d) beyond end of range (%d): %s", start, end, expr) | |
| + } | |
| + if step == 0 { | |
| + return 0, fmt.Errorf("step of range should be a positive number: %s", expr) | |
| + } | |
| + | |
| + return getBits(start, end, step) | extra, nil | |
| +} | |
| + | |
| +// parseIntOrName returns the (possibly-named) integer contained in expr. | |
| +func parseIntOrName(expr string, names map[string]uint) (uint, error) { | |
| + if names != nil { | |
| + if namedInt, ok := names[strings.ToLower(expr)]; ok { | |
| + return namedInt, nil | |
| + } | |
| + } | |
| + return mustParseInt(expr) | |
| +} | |
| + | |
| +// mustParseInt parses the given expression as an int or returns an error. | |
| +func mustParseInt(expr string) (uint, error) { | |
| + num, err := strconv.Atoi(expr) | |
| + if err != nil { | |
| + return 0, fmt.Errorf("failed to parse int from %s: %s", expr, err) | |
| + } | |
| + if num < 0 { | |
| + return 0, fmt.Errorf("negative number (%d) not allowed: %s", num, expr) | |
| + } | |
| + | |
| + return uint(num), nil | |
| +} | |
| + | |
| +// getBits sets all bits in the range [min, max], modulo the given step size. | |
| +func getBits(minSize, maxSize, step uint) uint64 { | |
| + var bits uint64 | |
| + | |
| + // If step is 1, use shifts. | |
| + if step == 1 { | |
| + return ^(math.MaxUint64 << (maxSize + 1)) & (math.MaxUint64 << minSize) | |
| + } | |
| + | |
| + // Else, use a simple loop. | |
| + for i := minSize; i <= maxSize; i += step { | |
| + bits |= 1 << i | |
| + } | |
| + return bits | |
| +} | |
| + | |
| +// all returns all bits within the given bounds. (plus the star bit) | |
| +func all(r bounds) uint64 { | |
| + return getBits(r.min, r.max, 1) | starBit | |
| +} | |
| + | |
| +// parseDescriptor returns a predefined schedule for the expression, or error if none matches. | |
| +func parseDescriptor(descriptor string, loc *time.Location) (Schedule, error) { | |
| + switch descriptor { | |
| + case "@yearly", "@annually": | |
| + return &SpecSchedule{ | |
| + Second: 1 << seconds.min, | |
| + Minute: 1 << minutes.min, | |
| + Hour: 1 << hours.min, | |
| + Dom: 1 << dom.min, | |
| + Month: 1 << months.min, | |
| + Dow: all(dow), | |
| + Location: loc, | |
| + }, nil | |
| + | |
| + case "@monthly": | |
| + return &SpecSchedule{ | |
| + Second: 1 << seconds.min, | |
| + Minute: 1 << minutes.min, | |
| + Hour: 1 << hours.min, | |
| + Dom: 1 << dom.min, | |
| + Month: all(months), | |
| + Dow: all(dow), | |
| + Location: loc, | |
| + }, nil | |
| + | |
| + case "@weekly": | |
| + return &SpecSchedule{ | |
| + Second: 1 << seconds.min, | |
| + Minute: 1 << minutes.min, | |
| + Hour: 1 << hours.min, | |
| + Dom: all(dom), | |
| + Month: all(months), | |
| + Dow: 1 << dow.min, | |
| + Location: loc, | |
| + }, nil | |
| + | |
| + case "@daily", "@midnight": | |
| + return &SpecSchedule{ | |
| + Second: 1 << seconds.min, | |
| + Minute: 1 << minutes.min, | |
| + Hour: 1 << hours.min, | |
| + Dom: all(dom), | |
| + Month: all(months), | |
| + Dow: all(dow), | |
| + Location: loc, | |
| + }, nil | |
| + | |
| + case "@hourly": | |
| + return &SpecSchedule{ | |
| + Second: 1 << seconds.min, | |
| + Minute: 1 << minutes.min, | |
| + Hour: all(hours), | |
| + Dom: all(dom), | |
| + Month: all(months), | |
| + Dow: all(dow), | |
| + Location: loc, | |
| + }, nil | |
| + | |
| + } | |
| + | |
| + const every = "@every " | |
| + if strings.HasPrefix(descriptor, every) { | |
| + duration, err := time.ParseDuration(descriptor[len(every):]) | |
| + if err != nil { | |
| + return nil, fmt.Errorf("failed to parse duration %s: %s", descriptor, err) | |
| + } | |
| + return Every(duration), nil | |
| + } | |
| + | |
| + return nil, fmt.Errorf("unrecognized descriptor: %s", descriptor) | |
| +} | |
| diff --git a/internal/cron/spec.go b/internal/cron/spec.go | |
| new file mode 100644 | |
| index 000000000..00a355c04 | |
| --- /dev/null | |
| +++ b/internal/cron/spec.go | |
| +// +skip_license_check | |
| + | |
| +/* | |
| +This file contains portions of code directly taken from the 'robfig/cron' project. | |
| +A copy of the license for this code can be found in the file named LICENSE in | |
| +this directory. | |
| +*/ | |
| + | |
| +package cron | |
| + | |
| +import "time" | |
| + | |
| +// SpecSchedule specifies a duty cycle (to the second granularity), based on a | |
| +// traditional crontab specification. It is computed initially and stored as bit sets. | |
| +type SpecSchedule struct { | |
| + Second, Minute, Hour, Dom, Month, Dow uint64 | |
| + | |
| + // Override location for this schedule. | |
| + Location *time.Location | |
| +} | |
| + | |
| +// bounds provides a range of acceptable values (plus a map of name to value). | |
| +type bounds struct { | |
| + min, max uint | |
| + names map[string]uint | |
| +} | |
| + | |
| +// The bounds for each field. | |
| +var ( | |
| + seconds = bounds{0, 59, nil} | |
| + minutes = bounds{0, 59, nil} | |
| + hours = bounds{0, 23, nil} | |
| + dom = bounds{1, 31, nil} | |
| + months = bounds{1, 12, map[string]uint{ | |
| + "jan": 1, | |
| + "feb": 2, | |
| + "mar": 3, | |
| + "apr": 4, | |
| + "may": 5, | |
| + "jun": 6, | |
| + "jul": 7, | |
| + "aug": 8, | |
| + "sep": 9, | |
| + "oct": 10, | |
| + "nov": 11, | |
| + "dec": 12, | |
| + }} | |
| + dow = bounds{0, 6, map[string]uint{ | |
| + "sun": 0, | |
| + "mon": 1, | |
| + "tue": 2, | |
| + "wed": 3, | |
| + "thu": 4, | |
| + "fri": 5, | |
| + "sat": 6, | |
| + }} | |
| +) | |
| + | |
| +const ( | |
| + // Set the top bit if a star was included in the expression. | |
| + starBit = 1 << 63 | |
| +) | |
| + | |
| +// Next returns the next time this schedule is activated, greater than the given | |
| +// time. If no time can be found to satisfy the schedule, return the zero time. | |
| +func (s *SpecSchedule) Next(t time.Time) time.Time { | |
| + // General approach | |
| + // | |
| + // For Month, Day, Hour, Minute, Second: | |
| + // Check if the time value matches. If yes, continue to the next field. | |
| + // If the field doesn't match the schedule, then increment the field until it matches. | |
| + // While incrementing the field, a wrap-around brings it back to the beginning | |
| + // of the field list (since it is necessary to re-verify previous field | |
| + // values) | |
| + | |
| + // Convert the given time into the schedule's timezone, if one is specified. | |
| + // Save the original timezone so we can convert back after we find a time. | |
| + // Note that schedules without a time zone specified (time.Local) are treated | |
| + // as local to the time provided. | |
| + origLocation := t.Location() | |
| + loc := s.Location | |
| + //nolint: gosmopolitan // this makes sense as it also handles other locations below | |
| + if loc == time.Local { | |
| + loc = t.Location() | |
| + } | |
| + //nolint:gosmopolitan | |
| + if s.Location != time.Local { | |
| + t = t.In(s.Location) | |
| + } | |
| + | |
| + // Start at the earliest possible time (the upcoming second). | |
| + t = t.Add(1*time.Second - time.Duration(t.Nanosecond())*time.Nanosecond) | |
| + | |
| + // This flag indicates whether a field has been incremented. | |
| + added := false | |
| + | |
| + // If no time is found within five years, return zero. | |
| + yearLimit := t.Year() + 5 | |
| + | |
| +WRAP: | |
| + if t.Year() > yearLimit { | |
| + return time.Time{} | |
| + } | |
| + | |
| + // Find the first applicable month. | |
| + // If it's this month, then do nothing. | |
| + //nolint:gosec | |
| + for 1<<uint(t.Month())&s.Month == 0 { | |
| + // If we have to add a month, reset the other parts to 0. | |
| + if !added { | |
| + added = true | |
| + // Otherwise, set the date at the beginning (since the current time is irrelevant). | |
| + t = time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, loc) | |
| + } | |
| + t = t.AddDate(0, 1, 0) | |
| + | |
| + // Wrapped around. | |
| + if t.Month() == time.January { | |
| + goto WRAP | |
| + } | |
| + } | |
| + | |
| + // Now get a day in that month. | |
| + // | |
| + // NOTE: This causes issues for daylight savings regimes where midnight does | |
| + // not exist. For example: Sao Paulo has DST that transforms midnight on | |
| + // 11/3 into 1am. Handle that by noticing when the Hour ends up != 0. | |
| + for !dayMatches(s, t) { | |
| + if !added { | |
| + added = true | |
| + t = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, loc) | |
| + } | |
| + t = t.AddDate(0, 0, 1) | |
| + // Notice if the hour is no longer midnight due to DST. | |
| + // Add an hour if it's 23, subtract an hour if it's 1. | |
| + if t.Hour() != 0 { | |
| + if t.Hour() > 12 { | |
| + t = t.Add(time.Duration(24-t.Hour()) * time.Hour) | |
| + } else { | |
| + t = t.Add(time.Duration(-t.Hour()) * time.Hour) | |
| + } | |
| + } | |
| + | |
| + if t.Day() == 1 { | |
| + goto WRAP | |
| + } | |
| + } | |
| + | |
| + //nolint:gosec | |
| + for 1<<uint(t.Hour())&s.Hour == 0 { | |
| + if !added { | |
| + added = true | |
| + t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), 0, 0, 0, loc) | |
| + } | |
| + t = t.Add(1 * time.Hour) | |
| + | |
| + if t.Hour() == 0 { | |
| + goto WRAP | |
| + } | |
| + } | |
| + | |
| + //nolint:gosec | |
| + for 1<<uint(t.Minute())&s.Minute == 0 { | |
| + if !added { | |
| + added = true | |
| + t = t.Truncate(time.Minute) | |
| + } | |
| + t = t.Add(1 * time.Minute) | |
| + | |
| + if t.Minute() == 0 { | |
| + goto WRAP | |
| + } | |
| + } | |
| + | |
| + //nolint:gosec | |
| + for 1<<uint(t.Second())&s.Second == 0 { | |
| + if !added { | |
| + added = true | |
| + t = t.Truncate(time.Second) | |
| + } | |
| + t = t.Add(1 * time.Second) | |
| + | |
| + if t.Second() == 0 { | |
| + goto WRAP | |
| + } | |
| + } | |
| + | |
| + return t.In(origLocation) | |
| +} | |
| + | |
| +// dayMatches returns true if the schedule's day-of-week and day-of-month | |
| +// restrictions are satisfied by the given time. | |
| +func dayMatches(s *SpecSchedule, t time.Time) bool { | |
| + var ( | |
| + //nolint:gosec | |
| + domMatch = 1<<uint(t.Day())&s.Dom > 0 | |
| + //nolint:gosec | |
| + dowMatch = 1<<uint(t.Weekday())&s.Dow > 0 | |
| + ) | |
| + if s.Dom&starBit > 0 || s.Dow&starBit > 0 { | |
| + return domMatch && dowMatch | |
| + } | |
| + return domMatch || dowMatch | |
| +} | |
| diff --git a/internal/generated/openapi/zz_generated.openapi.go b/internal/generated/openapi/zz_generated.openapi.go | |
| index 37ffccbb1..274ac4a34 100644 | |
| --- a/internal/generated/openapi/zz_generated.openapi.go | |
| +++ b/internal/generated/openapi/zz_generated.openapi.go | |
| func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenA | |
| "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateKeystores": schema_pkg_apis_certmanager_v1_CertificateKeystores(ref), | |
| "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateList": schema_pkg_apis_certmanager_v1_CertificateList(ref), | |
| "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificatePrivateKey": schema_pkg_apis_certmanager_v1_CertificatePrivateKey(ref), | |
| + "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateRenewal": schema_pkg_apis_certmanager_v1_CertificateRenewal(ref), | |
| + "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateRenewalWindows": schema_pkg_apis_certmanager_v1_CertificateRenewalWindows(ref), | |
| "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateRequest": schema_pkg_apis_certmanager_v1_CertificateRequest(ref), | |
| "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateRequestCondition": schema_pkg_apis_certmanager_v1_CertificateRequestCondition(ref), | |
| "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateRequestList": schema_pkg_apis_certmanager_v1_CertificateRequestList(ref), | |
| func schema_pkg_apis_certmanager_v1_CertificatePrivateKey(ref common.ReferenceCa | |
| } | |
| } | |
| +func schema_pkg_apis_certmanager_v1_CertificateRenewal(ref common.ReferenceCallback) common.OpenAPIDefinition { | |
| + return common.OpenAPIDefinition{ | |
| + Schema: spec.Schema{ | |
| + SchemaProps: spec.SchemaProps{ | |
| + Type: []string{"object"}, | |
| + Properties: map[string]spec.Schema{ | |
| + "policy": { | |
| + SchemaProps: spec.SchemaProps{ | |
| + Description: "`policy` must be one of `Disabled`, `RenewBefore`.", | |
| + Type: []string{"string"}, | |
| + Format: "", | |
| + }, | |
| + }, | |
| + "windows": { | |
| + VendorExtensible: spec.VendorExtensible{ | |
| + Extensions: spec.Extensions{ | |
| + "x-kubernetes-list-type": "atomic", | |
| + }, | |
| + }, | |
| + SchemaProps: spec.SchemaProps{ | |
| + Description: "`windows` mentions the behavior of when the renewal must happen.", | |
| + Type: []string{"array"}, | |
| + Items: &spec.SchemaOrArray{ | |
| + Schema: &spec.Schema{ | |
| + SchemaProps: spec.SchemaProps{ | |
| + Default: map[string]interface{}{}, | |
| + Ref: ref("github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateRenewalWindows"), | |
| + }, | |
| + }, | |
| + }, | |
| + }, | |
| + }, | |
| + }, | |
| + }, | |
| + }, | |
| + Dependencies: []string{ | |
| + "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateRenewalWindows"}, | |
| + } | |
| +} | |
| + | |
| +func schema_pkg_apis_certmanager_v1_CertificateRenewalWindows(ref common.ReferenceCallback) common.OpenAPIDefinition { | |
| + return common.OpenAPIDefinition{ | |
| + Schema: spec.Schema{ | |
| + SchemaProps: spec.SchemaProps{ | |
| + Description: "CertificateRenewalWindows is the definition for renewal windows", | |
| + Type: []string{"object"}, | |
| + Properties: map[string]spec.Schema{ | |
| + "timezone": { | |
| + SchemaProps: spec.SchemaProps{ | |
| + Description: "`timezone` is IANA compliant timezone. For example America/Denver. If this field is not set, timezone is treated as UTC.", | |
| + Type: []string{"string"}, | |
| + Format: "", | |
| + }, | |
| + }, | |
| + "windowDuration": { | |
| + SchemaProps: spec.SchemaProps{ | |
| + Description: "`windowDuration` is how long the cron definition is active for. Value must be in units accepted by Go time.ParseDuration https://golang.org/pkg/time/#ParseDuration.", | |
| + Ref: ref(metav1.Duration{}.OpenAPIModelName()), | |
| + }, | |
| + }, | |
| + "cron": { | |
| + SchemaProps: spec.SchemaProps{ | |
| + Description: "`cron` is a cron compliant string to allow when the renewal should be allowed. Format is as shown below: * * * * * | | | | | | | | | day of the week (0–6) (Sunday to Saturday; | | | month (1–12) 7 is also Sunday on some systems) | | day of the month (1–31) | hour (0–23) minute (0–59)", | |
| + Type: []string{"string"}, | |
| + Format: "", | |
| + }, | |
| + }, | |
| + }, | |
| + Required: []string{"windowDuration", "cron"}, | |
| + }, | |
| + }, | |
| + Dependencies: []string{ | |
| + metav1.Duration{}.OpenAPIModelName()}, | |
| + } | |
| +} | |
| + | |
| func schema_pkg_apis_certmanager_v1_CertificateRequest(ref common.ReferenceCallback) common.OpenAPIDefinition { | |
| return common.OpenAPIDefinition{ | |
| Schema: spec.Schema{ | |
| func schema_pkg_apis_certmanager_v1_CertificateSpec(ref common.ReferenceCallback | |
| Format: "int32", | |
| }, | |
| }, | |
| + "renewal": { | |
| + SchemaProps: spec.SchemaProps{ | |
| + Description: "`renewal` allows configuration of how your certificate is renewed. If the policy mentioned is `RenewBefore` then the controller respects `renewBefore` and `renewBeforePercentage`.", | |
| + Ref: ref("github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateRenewal"), | |
| + }, | |
| + }, | |
| "dnsNames": { | |
| VendorExtensible: spec.VendorExtensible{ | |
| Extensions: spec.Extensions{ | |
| func schema_pkg_apis_certmanager_v1_CertificateSpec(ref common.ReferenceCallback | |
| }, | |
| }, | |
| Dependencies: []string{ | |
| - "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateAdditionalOutputFormat", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateKeystores", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificatePrivateKey", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateSecretTemplate", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.NameConstraints", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.OtherName", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.X509Subject", "github.com/cert-manager/cert-manager/pkg/apis/meta/v1.IssuerReference", metav1.Duration{}.OpenAPIModelName()}, | |
| + "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateAdditionalOutputFormat", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateKeystores", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificatePrivateKey", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateRenewal", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.CertificateSecretTemplate", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.NameConstraints", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.OtherName", "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1.X509Subject", "github.com/cert-manager/cert-manager/pkg/apis/meta/v1.IssuerReference", metav1.Duration{}.OpenAPIModelName()}, | |
| } | |
| } | |
| func schema_pkg_apis_meta_v1_IssuerReference(ref common.ReferenceCallback) commo | |
| return common.OpenAPIDefinition{ | |
| Schema: spec.Schema{ | |
| SchemaProps: spec.SchemaProps{ | |
| - Description: "IssuerReference is a reference to a certificate issuer object with a given name, kind and group.", | |
| + Description: "ObjectReference is a reference to an object with a given name, kind and group.\n\nDeprecated: Use IssuerReference instead.", | |
| Type: []string{"object"}, | |
| Properties: map[string]spec.Schema{ | |
| "name": { | |
| diff --git a/pkg/apis/certmanager/v1/types_certificate.go b/pkg/apis/certmanager/v1/types_certificate.go | |
| index 80e641520..6863b2a9c 100644 | |
| --- a/pkg/apis/certmanager/v1/types_certificate.go | |
| +++ b/pkg/apis/certmanager/v1/types_certificate.go | |
| type CertificateSpec struct { | |
| // +optional | |
| RenewBeforePercentage *int32 `json:"renewBeforePercentage,omitempty"` | |
| + // `renewal` allows configuration of how your certificate is renewed. If the policy mentioned is | |
| + // `RenewBefore` then the controller respects `renewBefore` and `renewBeforePercentage`. | |
| + // +optional | |
| + Renewal *CertificateRenewal `json:"renewal,omitempty"` | |
| + | |
| // Requested DNS subject alternative names. | |
| // +optional | |
| // +listType=atomic | |
| const ( | |
| Modern2023PKCS12Profile PKCS12Profile = "Modern2023" | |
| ) | |
| +type CertificateRenewal struct { | |
| + // `policy` must be one of `Disabled`, `RenewBefore`. | |
| + // +kubebuilder:validation:Enum=RenewBefore;Disabled | |
| + Policy CertificateRenewalPolicy `json:"policy,omitempty"` | |
| + | |
| + // `windows` mentions the behavior of when the renewal must happen. | |
| + // +listType=atomic | |
| + // +optional | |
| + Windows []CertificateRenewalWindows `json:"windows,omitempty"` | |
| +} | |
| + | |
| +type CertificateRenewalPolicy string | |
| + | |
| +const ( | |
| + CertificateRenewalPolicyRenewBefore CertificateRenewalPolicy = "RenewBefore" | |
| + CertificateRenewalPolicyDisabled CertificateRenewalPolicy = "Disabled" | |
| +) | |
| + | |
| +// CertificateRenewalWindows is the definition for renewal windows | |
| +type CertificateRenewalWindows struct { | |
| + // `timezone` is IANA compliant timezone. For example America/Denver. | |
| + // If this field is not set, timezone is treated as UTC. | |
| + // +kubebuilder:validation:MinLength=1 | |
| + // +optional | |
| + Timezone string `json:"timezone,omitempty"` | |
| + | |
| + // `windowDuration` is how long the cron definition is active for. | |
| + // Value must be in units accepted by Go time.ParseDuration https://golang.org/pkg/time/#ParseDuration. | |
| + // +kubebuilder:validation:Type=string | |
| + // +kubebuilder:validation:Pattern="^([0-9]+(\\.[0-9]+)?(s|m|h))+$" | |
| + // +required | |
| + WindowDuration *metav1.Duration `json:"windowDuration,omitempty"` | |
| + | |
| + // `cron` is a cron compliant string to allow when the renewal should be allowed. Format is as shown below: | |
| + // * * * * * | |
| + // | | | | | | |
| + // | | | | day of the week (0–6) (Sunday to Saturday; | |
| + // | | | month (1–12) 7 is also Sunday on some systems) | |
| + // | | day of the month (1–31) | |
| + // | hour (0–23) | |
| + // minute (0–59) | |
| + // +kubebuilder:validation:MinLength=1 | |
| + // +required | |
| + Cron string `json:"cron,omitempty"` | |
| +} | |
| + | |
| // CertificateStatus defines the observed state of Certificate | |
| type CertificateStatus struct { | |
| // List of status conditions to indicate the status of certificates. | |
| diff --git a/pkg/apis/certmanager/v1/zz_generated.deepcopy.go b/pkg/apis/certmanager/v1/zz_generated.deepcopy.go | |
| index e889ecf1a..306ccce0f 100644 | |
| --- a/pkg/apis/certmanager/v1/zz_generated.deepcopy.go | |
| +++ b/pkg/apis/certmanager/v1/zz_generated.deepcopy.go | |
| func (in *CertificatePrivateKey) DeepCopy() *CertificatePrivateKey { | |
| return out | |
| } | |
| +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. | |
| +func (in *CertificateRenewal) DeepCopyInto(out *CertificateRenewal) { | |
| + *out = *in | |
| + if in.Windows != nil { | |
| + in, out := &in.Windows, &out.Windows | |
| + *out = make([]CertificateRenewalWindows, len(*in)) | |
| + for i := range *in { | |
| + (*in)[i].DeepCopyInto(&(*out)[i]) | |
| + } | |
| + } | |
| + return | |
| +} | |
| + | |
| +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertificateRenewal. | |
| +func (in *CertificateRenewal) DeepCopy() *CertificateRenewal { | |
| + if in == nil { | |
| + return nil | |
| + } | |
| + out := new(CertificateRenewal) | |
| + in.DeepCopyInto(out) | |
| + return out | |
| +} | |
| + | |
| +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. | |
| +func (in *CertificateRenewalWindows) DeepCopyInto(out *CertificateRenewalWindows) { | |
| + *out = *in | |
| + if in.WindowDuration != nil { | |
| + in, out := &in.WindowDuration, &out.WindowDuration | |
| + *out = new(metav1.Duration) | |
| + **out = **in | |
| + } | |
| + return | |
| +} | |
| + | |
| +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertificateRenewalWindows. | |
| +func (in *CertificateRenewalWindows) DeepCopy() *CertificateRenewalWindows { | |
| + if in == nil { | |
| + return nil | |
| + } | |
| + out := new(CertificateRenewalWindows) | |
| + in.DeepCopyInto(out) | |
| + return out | |
| +} | |
| + | |
| // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. | |
| func (in *CertificateRequest) DeepCopyInto(out *CertificateRequest) { | |
| *out = *in | |
| func (in *CertificateSpec) DeepCopyInto(out *CertificateSpec) { | |
| *out = new(int32) | |
| **out = **in | |
| } | |
| + if in.Renewal != nil { | |
| + in, out := &in.Renewal, &out.Renewal | |
| + *out = new(CertificateRenewal) | |
| + (*in).DeepCopyInto(*out) | |
| + } | |
| if in.DNSNames != nil { | |
| in, out := &in.DNSNames, &out.DNSNames | |
| *out = make([]string, len(*in)) | |
| diff --git a/pkg/client/applyconfigurations/certmanager/v1/certificaterenewal.go b/pkg/client/applyconfigurations/certmanager/v1/certificaterenewal.go | |
| new file mode 100644 | |
| index 000000000..e52d91039 | |
| --- /dev/null | |
| +++ b/pkg/client/applyconfigurations/certmanager/v1/certificaterenewal.go | |
| +/* | |
| +Copyright The cert-manager 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. | |
| +*/ | |
| + | |
| +// Code generated by applyconfiguration-gen. DO NOT EDIT. | |
| + | |
| +package v1 | |
| + | |
| +import ( | |
| + certmanagerv1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" | |
| +) | |
| + | |
| +// CertificateRenewalApplyConfiguration represents a declarative configuration of the CertificateRenewal type for use | |
| +// with apply. | |
| +type CertificateRenewalApplyConfiguration struct { | |
| + // `policy` must be one of `Disabled`, `RenewBefore`. | |
| + Policy *certmanagerv1.CertificateRenewalPolicy `json:"policy,omitempty"` | |
| + // `windows` mentions the behavior of when the renewal must happen. | |
| + Windows []CertificateRenewalWindowsApplyConfiguration `json:"windows,omitempty"` | |
| +} | |
| + | |
| +// CertificateRenewalApplyConfiguration constructs a declarative configuration of the CertificateRenewal type for use with | |
| +// apply. | |
| +func CertificateRenewal() *CertificateRenewalApplyConfiguration { | |
| + return &CertificateRenewalApplyConfiguration{} | |
| +} | |
| + | |
| +// WithPolicy sets the Policy field in the declarative configuration to the given value | |
| +// and returns the receiver, so that objects can be built by chaining "With" function invocations. | |
| +// If called multiple times, the Policy field is set to the value of the last call. | |
| +func (b *CertificateRenewalApplyConfiguration) WithPolicy(value certmanagerv1.CertificateRenewalPolicy) *CertificateRenewalApplyConfiguration { | |
| + b.Policy = &value | |
| + return b | |
| +} | |
| + | |
| +// WithWindows adds the given value to the Windows field in the declarative configuration | |
| +// and returns the receiver, so that objects can be build by chaining "With" function invocations. | |
| +// If called multiple times, values provided by each call will be appended to the Windows field. | |
| +func (b *CertificateRenewalApplyConfiguration) WithWindows(values ...*CertificateRenewalWindowsApplyConfiguration) *CertificateRenewalApplyConfiguration { | |
| + for i := range values { | |
| + if values[i] == nil { | |
| + panic("nil value passed to WithWindows") | |
| + } | |
| + b.Windows = append(b.Windows, *values[i]) | |
| + } | |
| + return b | |
| +} | |
| diff --git a/pkg/client/applyconfigurations/certmanager/v1/certificaterenewalwindows.go b/pkg/client/applyconfigurations/certmanager/v1/certificaterenewalwindows.go | |
| new file mode 100644 | |
| index 000000000..b4b8dc509 | |
| --- /dev/null | |
| +++ b/pkg/client/applyconfigurations/certmanager/v1/certificaterenewalwindows.go | |
| +/* | |
| +Copyright The cert-manager 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. | |
| +*/ | |
| + | |
| +// Code generated by applyconfiguration-gen. DO NOT EDIT. | |
| + | |
| +package v1 | |
| + | |
| +import ( | |
| + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" | |
| +) | |
| + | |
| +// CertificateRenewalWindowsApplyConfiguration represents a declarative configuration of the CertificateRenewalWindows type for use | |
| +// with apply. | |
| +// | |
| +// CertificateRenewalWindows is the definition for renewal windows | |
| +type CertificateRenewalWindowsApplyConfiguration struct { | |
| + // `timezone` is IANA compliant timezone. For example America/Denver. | |
| + // If this field is not set, timezone is treated as UTC. | |
| + Timezone *string `json:"timezone,omitempty"` | |
| + // `windowDuration` is how long the cron definition is active for. | |
| + // Value must be in units accepted by Go time.ParseDuration https://golang.org/pkg/time/#ParseDuration. | |
| + WindowDuration *metav1.Duration `json:"windowDuration,omitempty"` | |
| + // `cron` is a cron compliant string to allow when the renewal should be allowed. Format is as shown below: | |
| + // * * * * * | |
| + // | | | | | | |
| + // | | | | day of the week (0–6) (Sunday to Saturday; | |
| + // | | | month (1–12) 7 is also Sunday on some systems) | |
| + // | | day of the month (1–31) | |
| + // | hour (0–23) | |
| + // minute (0–59) | |
| + Cron *string `json:"cron,omitempty"` | |
| +} | |
| + | |
| +// CertificateRenewalWindowsApplyConfiguration constructs a declarative configuration of the CertificateRenewalWindows type for use with | |
| +// apply. | |
| +func CertificateRenewalWindows() *CertificateRenewalWindowsApplyConfiguration { | |
| + return &CertificateRenewalWindowsApplyConfiguration{} | |
| +} | |
| + | |
| +// WithTimezone sets the Timezone field in the declarative configuration to the given value | |
| +// and returns the receiver, so that objects can be built by chaining "With" function invocations. | |
| +// If called multiple times, the Timezone field is set to the value of the last call. | |
| +func (b *CertificateRenewalWindowsApplyConfiguration) WithTimezone(value string) *CertificateRenewalWindowsApplyConfiguration { | |
| + b.Timezone = &value | |
| + return b | |
| +} | |
| + | |
| +// WithWindowDuration sets the WindowDuration field in the declarative configuration to the given value | |
| +// and returns the receiver, so that objects can be built by chaining "With" function invocations. | |
| +// If called multiple times, the WindowDuration field is set to the value of the last call. | |
| +func (b *CertificateRenewalWindowsApplyConfiguration) WithWindowDuration(value metav1.Duration) *CertificateRenewalWindowsApplyConfiguration { | |
| + b.WindowDuration = &value | |
| + return b | |
| +} | |
| + | |
| +// WithCron sets the Cron field in the declarative configuration to the given value | |
| +// and returns the receiver, so that objects can be built by chaining "With" function invocations. | |
| +// If called multiple times, the Cron field is set to the value of the last call. | |
| +func (b *CertificateRenewalWindowsApplyConfiguration) WithCron(value string) *CertificateRenewalWindowsApplyConfiguration { | |
| + b.Cron = &value | |
| + return b | |
| +} | |
| diff --git a/pkg/client/applyconfigurations/certmanager/v1/certificatespec.go b/pkg/client/applyconfigurations/certmanager/v1/certificatespec.go | |
| index 47adfb4e9..1e9c58e8a 100644 | |
| --- a/pkg/client/applyconfigurations/certmanager/v1/certificatespec.go | |
| +++ b/pkg/client/applyconfigurations/certmanager/v1/certificatespec.go | |
| type CertificateSpecApplyConfiguration struct { | |
| // minutes. | |
| // Cannot be set if the `renewBefore` field is set. | |
| RenewBeforePercentage *int32 `json:"renewBeforePercentage,omitempty"` | |
| + // `renewal` allows configuration of how your certificate is renewed. If the policy mentioned is | |
| + // `RenewBefore` then the controller respects `renewBefore` and `renewBeforePercentage`. | |
| + Renewal *CertificateRenewalApplyConfiguration `json:"renewal,omitempty"` | |
| // Requested DNS subject alternative names. | |
| DNSNames []string `json:"dnsNames,omitempty"` | |
| // Requested IP address subject alternative names. | |
| func (b *CertificateSpecApplyConfiguration) WithRenewBeforePercentage(value int3 | |
| return b | |
| } | |
| +// WithRenewal sets the Renewal field in the declarative configuration to the given value | |
| +// and returns the receiver, so that objects can be built by chaining "With" function invocations. | |
| +// If called multiple times, the Renewal field is set to the value of the last call. | |
| +func (b *CertificateSpecApplyConfiguration) WithRenewal(value *CertificateRenewalApplyConfiguration) *CertificateSpecApplyConfiguration { | |
| + b.Renewal = value | |
| + return b | |
| +} | |
| + | |
| // WithDNSNames adds the given value to the DNSNames field in the declarative configuration | |
| // and returns the receiver, so that objects can be build by chaining "With" function invocations. | |
| // If called multiple times, values provided by each call will be appended to the DNSNames field. | |
| diff --git a/pkg/client/applyconfigurations/internal/internal.go b/pkg/client/applyconfigurations/internal/internal.go | |
| index cac0cadc5..d76c344c7 100644 | |
| --- a/pkg/client/applyconfigurations/internal/internal.go | |
| +++ b/pkg/client/applyconfigurations/internal/internal.go | |
| var schemaYAML = typed.YAMLObject(`types: | |
| - name: size | |
| type: | |
| scalar: numeric | |
| +- name: com.github.cert-manager.cert-manager.pkg.apis.certmanager.v1.CertificateRenewal | |
| + map: | |
| + fields: | |
| + - name: policy | |
| + type: | |
| + scalar: string | |
| + - name: windows | |
| + type: | |
| + list: | |
| + elementType: | |
| + namedType: com.github.cert-manager.cert-manager.pkg.apis.certmanager.v1.CertificateRenewalWindows | |
| + elementRelationship: atomic | |
| +- name: com.github.cert-manager.cert-manager.pkg.apis.certmanager.v1.CertificateRenewalWindows | |
| + map: | |
| + fields: | |
| + - name: cron | |
| + type: | |
| + scalar: string | |
| + - name: timezone | |
| + type: | |
| + scalar: string | |
| + - name: windowDuration | |
| + type: | |
| + namedType: Duration.v1.meta.apis.pkg.apimachinery.k8s.io | |
| - name: com.github.cert-manager.cert-manager.pkg.apis.certmanager.v1.CertificateRequest | |
| map: | |
| fields: | |
| var schemaYAML = typed.YAMLObject(`types: | |
| - name: renewBeforePercentage | |
| type: | |
| scalar: numeric | |
| + - name: renewal | |
| + type: | |
| + namedType: com.github.cert-manager.cert-manager.pkg.apis.certmanager.v1.CertificateRenewal | |
| - name: revisionHistoryLimit | |
| type: | |
| scalar: numeric | |
| diff --git a/pkg/client/applyconfigurations/utils.go b/pkg/client/applyconfigurations/utils.go | |
| index 0729e915a..c38f34103 100644 | |
| --- a/pkg/client/applyconfigurations/utils.go | |
| +++ b/pkg/client/applyconfigurations/utils.go | |
| func ForKind(kind schema.GroupVersionKind) interface{} { | |
| return &applyconfigurationscertmanagerv1.CertificateKeystoresApplyConfiguration{} | |
| case certmanagerv1.SchemeGroupVersion.WithKind("CertificatePrivateKey"): | |
| return &applyconfigurationscertmanagerv1.CertificatePrivateKeyApplyConfiguration{} | |
| + case certmanagerv1.SchemeGroupVersion.WithKind("CertificateRenewal"): | |
| + return &applyconfigurationscertmanagerv1.CertificateRenewalApplyConfiguration{} | |
| + case certmanagerv1.SchemeGroupVersion.WithKind("CertificateRenewalWindows"): | |
| + return &applyconfigurationscertmanagerv1.CertificateRenewalWindowsApplyConfiguration{} | |
| case certmanagerv1.SchemeGroupVersion.WithKind("CertificateRequest"): | |
| return &applyconfigurationscertmanagerv1.CertificateRequestApplyConfiguration{} | |
| case certmanagerv1.SchemeGroupVersion.WithKind("CertificateRequestCondition"): | |
| diff --git a/pkg/controller/certificates/readiness/readiness_controller.go b/pkg/controller/certificates/readiness/readiness_controller.go | |
| index a5e7ac798..fc4f11576 100644 | |
| --- a/pkg/controller/certificates/readiness/readiness_controller.go | |
| +++ b/pkg/controller/certificates/readiness/readiness_controller.go | |
| import ( | |
| apiequality "k8s.io/apimachinery/pkg/api/equality" | |
| apierrors "k8s.io/apimachinery/pkg/api/errors" | |
| metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" | |
| + "k8s.io/apimachinery/pkg/labels" | |
| "k8s.io/apimachinery/pkg/types" | |
| "k8s.io/client-go/tools/cache" | |
| + "k8s.io/client-go/tools/record" | |
| "k8s.io/client-go/util/workqueue" | |
| internalcertificates "github.com/cert-manager/cert-manager/internal/controller/certificates" | |
| type controller struct { | |
| certificateRequestLister cmlisters.CertificateRequestLister | |
| secretLister internalinformers.SecretLister | |
| client cmclient.Interface | |
| + recorder record.EventRecorder | |
| gatherer *policies.Gatherer | |
| // policyEvaluator builds Ready condition of a Certificate based on policy evaluation | |
| policyEvaluator policyEvaluatorFunc | |
| func NewController( | |
| } | |
| // When a CertificateRequest resource changes, enqueue the Certificate resource that owns it. | |
| - if _, err := certificateRequestInformer.Informer().AddEventHandler( | |
| - controllerpkg.BlockingEventHandler( | |
| - certificates.EnqueueCertificatesForResourceUsingPredicates[*cmapi.CertificateRequest]( | |
| - log, queue, certificateInformer.Lister(), | |
| - predicate.ResourceOwnerOf, | |
| - ), | |
| - ), | |
| - ); err != nil { | |
| + if _, err := certificateRequestInformer.Informer().AddEventHandler(controllerpkg.BlockingEventHandler( | |
| + certificates.EnqueueCertificatesForResourceUsingPredicates(log, queue, certificateInformer.Lister(), labels.Everything(), predicate.ResourceOwnerOf), | |
| + )); err != nil { | |
| return nil, nil, nil, fmt.Errorf("error setting up event handler: %v", err) | |
| } | |
| // When a Secret resource changes, enqueue any Certificate resources that name it as spec.secretName. | |
| - if _, err := secretsInformer.Informer().AddEventHandler( | |
| - controllerpkg.BlockingEventHandler( | |
| - // Trigger reconciles on changes to the Secret named `spec.secretName` | |
| - certificates.EnqueueCertificatesForResourceUsingPredicates( | |
| - log, queue, certificateInformer.Lister(), | |
| - predicate.ExtractResourceName[*corev1.Secret](predicate.CertificateSecretName), | |
| - ), | |
| - ), | |
| - ); err != nil { | |
| + if _, err := secretsInformer.Informer().AddEventHandler(controllerpkg.BlockingEventHandler( | |
| + // Trigger reconciles on changes to the Secret named `spec.secretName` | |
| + certificates.EnqueueCertificatesForResourceUsingPredicates(log, queue, certificateInformer.Lister(), labels.Everything(), | |
| + predicate.ExtractResourceName(predicate.CertificateSecretName)), | |
| + )); err != nil { | |
| return nil, nil, nil, fmt.Errorf("error setting up event handler: %v", err) | |
| } | |
| func NewController( | |
| certificateRequestLister: certificateRequestInformer.Lister(), | |
| secretLister: secretsInformer.Lister(), | |
| client: ctx.CMClient, | |
| + recorder: ctx.Recorder, | |
| gatherer: &policies.Gatherer{ | |
| CertificateRequestLister: certificateRequestInformer.Lister(), | |
| SecretLister: secretsInformer.Lister(), | |
| func (c *controller) ProcessItem(ctx context.Context, key types.NamespacedName) | |
| notBefore := metav1.NewTime(x509cert.NotBefore) | |
| notAfter := metav1.NewTime(x509cert.NotAfter) | |
| - renewalTime := c.renewalTimeCalculator(x509cert.NotBefore, x509cert.NotAfter, crt.Spec.RenewBefore, crt.Spec.RenewBeforePercentage) | |
| + renewalTime, err := c.renewalTimeCalculator(x509cert.NotBefore, x509cert.NotAfter, crt.Spec.RenewBefore, crt.Spec.RenewBeforePercentage, crt.Spec.Renewal) | |
| + | |
| + if err != nil { | |
| + reason := policies.WindowError | |
| + message := fmt.Sprintf("Could not calculate renewal time: %v", err) | |
| + apiutil.SetCertificateCondition(crt, crt.Generation, cmapi.CertificateConditionReady, cmmeta.ConditionFalse, reason, message) | |
| + | |
| + c.recorder.Event(crt, corev1.EventTypeWarning, reason, message) | |
| + } | |
| // update Certificate's Status | |
| crt.Status.NotBefore = ¬Before | |
| diff --git a/pkg/controller/certificates/trigger/trigger_controller.go b/pkg/controller/certificates/trigger/trigger_controller.go | |
| index 5ffd2800d..1a6659c85 100644 | |
| --- a/pkg/controller/certificates/trigger/trigger_controller.go | |
| +++ b/pkg/controller/certificates/trigger/trigger_controller.go | |
| import ( | |
| corev1 "k8s.io/api/core/v1" | |
| k8sErrors "k8s.io/apimachinery/pkg/api/errors" | |
| metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" | |
| + "k8s.io/apimachinery/pkg/labels" | |
| "k8s.io/apimachinery/pkg/types" | |
| "k8s.io/client-go/tools/cache" | |
| "k8s.io/client-go/tools/record" | |
| func NewController( | |
| } | |
| // When a CertificateRequest resource changes, enqueue the Certificate resource that owns it. | |
| - if _, err := certificateRequestInformer.Informer().AddEventHandler( | |
| - controllerpkg.BlockingEventHandler( | |
| - certificates.EnqueueCertificatesForResourceUsingPredicates[*cmapi.CertificateRequest]( | |
| - log, queue, certificateInformer.Lister(), | |
| - predicate.ResourceOwnerOf, | |
| - ), | |
| - ), | |
| - ); err != nil { | |
| + if _, err := certificateRequestInformer.Informer().AddEventHandler(controllerpkg.BlockingEventHandler( | |
| + certificates.EnqueueCertificatesForResourceUsingPredicates(log, queue, certificateInformer.Lister(), labels.Everything(), predicate.ResourceOwnerOf), | |
| + )); err != nil { | |
| return nil, nil, nil, fmt.Errorf("error setting up event handler: %v", err) | |
| } | |
| // When a Secret resource changes, enqueue any Certificate resources that name it as spec.secretName. | |
| - if _, err := secretsInformer.Informer().AddEventHandler( | |
| - controllerpkg.BlockingEventHandler( | |
| - // Trigger reconciles on changes to the Secret named `spec.secretName` | |
| - certificates.EnqueueCertificatesForResourceUsingPredicates( | |
| - log, queue, certificateInformer.Lister(), | |
| - predicate.ExtractResourceName[*corev1.Secret](predicate.CertificateSecretName), | |
| - ), | |
| - ), | |
| - ); err != nil { | |
| + if _, err := secretsInformer.Informer().AddEventHandler(controllerpkg.BlockingEventHandler( | |
| + // Trigger reconciles on changes to the Secret named `spec.secretName` | |
| + certificates.EnqueueCertificatesForResourceUsingPredicates(log, queue, certificateInformer.Lister(), labels.Everything(), | |
| + predicate.ExtractResourceName(predicate.CertificateSecretName)), | |
| + )); err != nil { | |
| return nil, nil, nil, fmt.Errorf("error setting up event handler: %v", err) | |
| } | |
| func (c *controller) ProcessItem(ctx context.Context, key types.NamespacedName) | |
| } | |
| reason, message, reissue := c.shouldReissue(input) | |
| + if reason == policies.WindowError { | |
| + c.recorder.Event(crt, corev1.EventTypeWarning, reason, fmt.Sprintf("Renewing certificate without satisfying renewal windows due to %s", message)) | |
| + message = fmt.Sprintf("Renewing certificate without satisfying renewal windows at: %s", crt.Status.RenewalTime) | |
| + reason = policies.Renewing | |
| + } | |
| + | |
| if !reissue { | |
| - // no re-issuance required, return early | |
| return nil | |
| } | |
| diff --git a/pkg/util/pki/renewaltime.go b/pkg/util/pki/renewaltime.go | |
| index 6e558abca..1a8281021 100644 | |
| --- a/pkg/util/pki/renewaltime.go | |
| +++ b/pkg/util/pki/renewaltime.go | |
| limitations under the License. | |
| package pki | |
| import ( | |
| + "fmt" | |
| "time" | |
| metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" | |
| + | |
| + apiv1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" | |
| + "github.com/cert-manager/cert-manager/pkg/util" | |
| ) | |
| // RenewalTimeFunc is a custom function type for calculating renewal time of a certificate. | |
| -type RenewalTimeFunc func(time.Time, time.Time, *metav1.Duration, *int32) *metav1.Time | |
| +type RenewalTimeFunc func(time.Time, time.Time, *metav1.Duration, *int32, *apiv1.CertificateRenewal) (*metav1.Time, error) | |
| // RenewalTime calculates renewal time for a certificate. | |
| // If renewBefore is non-nil and less than the certificate's lifetime, renewal | |
| type RenewalTimeFunc func(time.Time, time.Time, *metav1.Duration, *int32) *metav | |
| // will be the computed period before expiry based on the renewBeforePercentage | |
| // value and certificate lifetime. | |
| // Default renewal time is 2/3 through certificate's lifetime. | |
| -func RenewalTime(notBefore, notAfter time.Time, renewBefore *metav1.Duration, renewBeforePercentage *int32) *metav1.Time { | |
| - // 1. Calculate how long before expiry a cert should be renewed | |
| +func RenewalTime(notBefore, notAfter time.Time, renewBefore *metav1.Duration, renewBeforePercentage *int32, renewalSpec *apiv1.CertificateRenewal) (*metav1.Time, error) { | |
| + // 1. Start calculation of desired renewal time based on renewBefore and renewBeforePercentage. | |
| + // 1.1: Calculate how long before expiry a cert should be renewed | |
| actualDuration := notAfter.Sub(notBefore) | |
| - actualRenewBefore := RenewBefore(actualDuration, renewBefore, renewBeforePercentage) | |
| - | |
| - // 2. Calculate when a cert should be renewed | |
| + actualRenewBefore := desiredRenewalTime(actualDuration, renewBefore, renewBeforePercentage) | |
| + // 1.2: Calculate when a cert should be renewed | |
| // Truncate the renewal time to nearest second. This is important | |
| // because the renewal time also gets stored on Certificate's status | |
| // where it is truncated to the nearest second. We use the renewal time | |
| func RenewalTime(notBefore, notAfter time.Time, renewBefore *metav1.Duration, re | |
| // causing Certificates to not be automatically renewed. See | |
| // https://github.com/cert-manager/cert-manager/pull/4399. | |
| rt := metav1.NewTime(notAfter.Add(-1 * actualRenewBefore).Truncate(time.Second)) | |
| - return &rt | |
| + | |
| + // 2. If there is no renewal spec then just return the desired renewal time calculated above. | |
| + if renewalSpec == nil { | |
| + return &rt, nil | |
| + } | |
| + | |
| + switch renewalSpec.Policy { | |
| + case apiv1.CertificateRenewalPolicyDisabled: | |
| + return nil, nil | |
| + case apiv1.CertificateRenewalPolicyRenewBefore: | |
| + return applyRenewBeforeWithWindows(notAfter, notBefore, rt.Time, renewalSpec.Windows) | |
| + default: | |
| + return nil, fmt.Errorf("unsupported renewal policy: %s", renewalSpec.Policy) | |
| + } | |
| } | |
| -// RenewBefore calculates how far before expiry a certificate should be renewed. | |
| +// desiredRenewalTime calculates how far before expiry a certificate should be renewed. | |
| // If renewBefore is non-nil and less than the certificate's lifetime, renewal | |
| // time will be the computed renewBefore period before expiry. | |
| // If renewBeforePercentage is non-nil and in the range (0,100), renewal time | |
| // will be the computed period before expiry based on the renewBeforePercentage | |
| // and actualDuration values. | |
| // Default is 2/3 through certificate's lifetime. | |
| -func RenewBefore(actualDuration time.Duration, renewBefore *metav1.Duration, renewBeforePercentage *int32) time.Duration { | |
| + | |
| +// Note that this function used to be called RenewBefore and was an exported function which would expose the renewal time. | |
| +// Currently, this function calculates the desired renewal time and feeds into the renewal windows logic called above. | |
| +func desiredRenewalTime(actualDuration time.Duration, renewBefore *metav1.Duration, renewBeforePercentage *int32) time.Duration { | |
| // If spec.renewBefore or spec.renewBeforePercentage was set (and is | |
| // valid) respect that. We don't want to prevent users from renewing | |
| // longer lived certs more frequently. | |
| func RenewBefore(actualDuration time.Duration, renewBefore *metav1.Duration, ren | |
| // Otherwise, default to renewing 2/3 through certificate's lifetime. | |
| return actualDuration / 3 | |
| } | |
| + | |
| +// applyRenewBeforeWithWindows calculates effective renewal time with windows in it. We want the logic to be as follows: | |
| +// Take in the desiredRenewalTime from the function above and look forward and backward to find a desirable time which satisfies | |
| +// the cron window along with the cronSeconds duration. If we find a time that is before the renewalTime we return that first. | |
| +func applyRenewBeforeWithWindows(notAfter, notBefore, desiredRenewalTime time.Time, windows []apiv1.CertificateRenewalWindows) (*metav1.Time, error) { | |
| + var ( | |
| + bestBefore *time.Time | |
| + bestAfter *time.Time | |
| + ) | |
| + | |
| + if len(windows) == 0 { | |
| + return &metav1.Time{Time: desiredRenewalTime}, nil | |
| + } | |
| + | |
| + for _, w := range windows { | |
| + loc := time.UTC | |
| + if w.Timezone != "" { | |
| + if tz, err := time.LoadLocation(w.Timezone); err == nil { | |
| + loc = tz | |
| + } else { | |
| + // This shouldn't get triggered as we validate timezones in the validation webhook. | |
| + return nil, fmt.Errorf("error parsing timezone in window %s", err.Error()) | |
| + } | |
| + } | |
| + | |
| + cronSched, err := util.CronParse(w.Cron, loc.String()) | |
| + if err != nil { | |
| + return nil, fmt.Errorf("error parsing cron in window %s", err.Error()) | |
| + } | |
| + | |
| + if w.WindowDuration == nil || w.WindowDuration.Duration <= 0 { | |
| + return nil, fmt.Errorf("windowDuration must be a positive duration in window %v", w) | |
| + } | |
| + | |
| + // Any renewal logic should only start after notBefore and before notAfter. Bounds are [notBefore - dur, notAfter + dur) | |
| + searchMin := notBefore.Add(-w.WindowDuration.Duration) | |
| + searchMax := notAfter.Add(w.WindowDuration.Duration) | |
| + | |
| + bestBefore = findBeforeDesired(cronSched, searchMin, searchMax, desiredRenewalTime, bestBefore, w.WindowDuration.Duration) | |
| + bestAfter = findAfterDesired(cronSched, searchMin, searchMax, desiredRenewalTime, bestAfter, w.WindowDuration.Duration) | |
| + } | |
| + | |
| + if bestBefore != nil { | |
| + return &metav1.Time{Time: *bestBefore}, nil | |
| + } | |
| + | |
| + if bestAfter != nil { | |
| + return &metav1.Time{Time: *bestAfter}, nil | |
| + } | |
| + | |
| + return &metav1.Time{Time: desiredRenewalTime}, fmt.Errorf("cannot find a time with the given windows between %s and %s for: %s", notBefore, notAfter, desiredRenewalTime) | |
| +} | |
| + | |
| +// bsFindEarliestWindowBeforeDesired performs a binary search over time to find | |
| +// the latest cron window start S such that: | |
| +// | |
| +// minTime <= S < maxTime | |
| +// | |
| +// where S is a time produced by sched.Next(..). | |
| +func bsFindLatestWindowBeforeDesired(sched util.CronSchedule, minTime, maxTime time.Time) *time.Time { | |
| + if !minTime.Before(maxTime) { | |
| + return nil | |
| + } | |
| + | |
| + // If the first instance that matches the cron is after the max bound then we don't have a earliest window before desired renewal. | |
| + if sched.Next(minTime.Add(-time.Second)).After(maxTime) { | |
| + return nil | |
| + } | |
| + | |
| + low := minTime | |
| + high := maxTime | |
| + | |
| + // We binary search on the time range [low, high), maintaining the invariant: | |
| + // | |
| + // There exists at least one cron start S such that: | |
| + // low <= S <= maxTime | |
| + // | |
| + // and S is produced by sched.Next(..). | |
| + for high.Sub(low) > time.Second { | |
| + mid := low.Add(high.Sub(low) / 2) | |
| + next := sched.Next(mid) | |
| + | |
| + if next.After(maxTime) { | |
| + high = mid | |
| + } else { | |
| + low = mid | |
| + } | |
| + } | |
| + | |
| + last := sched.Next(low.Add(-time.Second)) | |
| + if last.After(maxTime) { | |
| + return nil | |
| + } | |
| + | |
| + return &last | |
| +} | |
| + | |
| +// findBeforeDesired returns a time that matches the cron schedule before the desiredRenewalTime. This function makes use of a binary search | |
| +// algorithm, with the bounds defined by searchMin and searchMax (desiredRenewalTime if it's before searchMax), to find a time which matches the cron schedule. | |
| +// if the desiredRenewalTime is in [lastStart, lastStart+duration) we just return that else we return lastStart+duration. | |
| +func findBeforeDesired(cronSched util.CronSchedule, searchMin, searchMax, desiredRenewalTime time.Time, bestBefore *time.Time, duration time.Duration) *time.Time { | |
| + if desiredRenewalTime.Before(searchMin) { | |
| + return nil | |
| + } | |
| + var beforeMax time.Time | |
| + if desiredRenewalTime.Before(searchMax) { | |
| + beforeMax = desiredRenewalTime | |
| + } else { | |
| + beforeMax = searchMax | |
| + } | |
| + lastStart := bsFindLatestWindowBeforeDesired(cronSched, searchMin, beforeMax) | |
| + if lastStart != nil { | |
| + end := lastStart.Add(duration) | |
| + | |
| + var candidateBefore time.Time | |
| + if !desiredRenewalTime.Before(*lastStart) && desiredRenewalTime.Before(end) { | |
| + candidateBefore = desiredRenewalTime | |
| + } else { | |
| + candidateBefore = end | |
| + } | |
| + | |
| + // This is done to ensure that any candidateBefore is not before the desired renewal time. | |
| + if !candidateBefore.Before(desiredRenewalTime) { | |
| + if bestBefore == nil || candidateBefore.After(*bestBefore) { | |
| + c := candidateBefore | |
| + bestBefore = &c | |
| + } | |
| + } | |
| + } | |
| + | |
| + return bestBefore | |
| +} | |
| + | |
| +// findAfterDesired returns the first instance of time that matches the cronSched after the desiredRenewalTime. | |
| +func findAfterDesired(cronSched util.CronSchedule, searchMin, searchMax, desiredRenewalTime time.Time, bestAfter *time.Time, duration time.Duration) *time.Time { | |
| + var afterMin time.Time | |
| + if desiredRenewalTime.After(searchMin) { | |
| + afterMin = desiredRenewalTime | |
| + } else { | |
| + afterMin = searchMin | |
| + } | |
| + start := cronSched.Next(afterMin.Add(-time.Second)) | |
| + if start.After(searchMax) { | |
| + return nil | |
| + } | |
| + | |
| + end := start.Add(duration) | |
| + | |
| + var candidateAfter time.Time | |
| + switch { | |
| + case !desiredRenewalTime.Before(start) && desiredRenewalTime.Before(end): | |
| + candidateAfter = desiredRenewalTime | |
| + case desiredRenewalTime.Before(start): | |
| + candidateAfter = start | |
| + default: | |
| + candidateAfter = time.Time{} | |
| + } | |
| + | |
| + // This check ensures that candidateAfter is never before the desiredRenewalTime | |
| + if !candidateAfter.IsZero() && !candidateAfter.Before(desiredRenewalTime) { | |
| + if bestAfter == nil || candidateAfter.Before(*bestAfter) { | |
| + c := candidateAfter | |
| + bestAfter = &c | |
| + } | |
| + } | |
| + | |
| + return bestAfter | |
| +} | |
| diff --git a/pkg/util/util.go b/pkg/util/util.go | |
| index 7893e43b9..9161c62b9 100644 | |
| --- a/pkg/util/util.go | |
| +++ b/pkg/util/util.go | |
| import ( | |
| "net/url" | |
| "slices" | |
| "strings" | |
| + "time" | |
| + "github.com/cert-manager/cert-manager/internal/cron" | |
| cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" | |
| ) | |
| +// CronSchedule defines the minimal schedule behavior exposed by this package, | |
| +// decoupling callers from the internal cron implementation. | |
| +type CronSchedule interface { | |
| + Next(time.Time) time.Time | |
| +} | |
| + | |
| // genericEqualUnsorted reports whether two slices are identical up to reordering | |
| // using a comparison function. | |
| // If the lengths are different, genericEqualUnsorted returns false. Otherwise, the | |
| func SplitWithEscapeCSV(in string) ([]string, error) { | |
| return records[0], nil | |
| } | |
| + | |
| +// CronParse parses the given cron syntax to return a cron schedule interface. It also takes in an optional timezone which would parse the | |
| +// cron schedule in that timezone. timeZone must be an IANA compliant time zone (e.g. America/Denver). | |
| +func CronParse(origCronString, timeZone string) (CronSchedule, error) { | |
| + cronString := origCronString | |
| + if timeZone != "" { | |
| + cronString = fmt.Sprintf("CRON_TZ=%s %s", timeZone, origCronString) | |
| + } | |
| + s, err := cron. | |
| + NewParser(cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor). | |
| + Parse(cronString) | |
| + if err == nil { | |
| + return s, nil | |
| + } | |
| + return nil, fmt.Errorf("failed to parse cron spec '%s': %w", origCronString, err) | |
| +} | |