diff --git a/Makefile b/Makefile index 3bd135e..efb0d19 100644 --- a/Makefile +++ b/Makefile @@ -47,9 +47,12 @@ LICENSE_PATH ?= hack/boilerplate.go.txt .PHONY: generate generate: controller-gen client-gen informer-gen lister-gen ## Generate code containing DeepCopy, DeepCopyInto, ClientSet, Client Informer and DeepCopyObject method implementations. - $(CONTROLLER_GEN) object:headerFile="$(LICENSE_PATH)" paths="./..." + # $(CONTROLLER_GEN) object:headerFile="$(LICENSE_PATH)" paths="./..." rm -rf ./pkg/client/clientset + rm -rf ./pkg/client/listers + rm -rf ./pkg/client/informers + $(CLIENT_GEN) --go-header-file $(LICENSE_PATH) \ --clientset-name versioned \ --input-base "" \ @@ -58,14 +61,12 @@ --output-package "$(MODULE_NAME)/pkg/client/clientset" \ --output-base ./ - rm -rf ./pkg/client/listers $(LISTER_GEN) --go-header-file $(LICENSE_PATH) \ --input-dirs $(INPUT_APIS) \ --trim-path-prefix=$(MODULE_NAME) \ --output-package $(MODULE_NAME)/pkg/client/listers \ --output-base ./ - rm -rf ./pkg/client/informers $(INFORMER_GEN) --go-header-file $(LICENSE_PATH) \ --input-dirs $(INPUT_APIS) \ --versioned-clientset-package $(MODULE_NAME)/pkg/client/clientset/versioned \ diff --git a/main.go b/main.go index 1877ef6..b995425 100644 --- a/main.go +++ b/main.go @@ -31,7 +31,6 @@ "sigs.k8s.io/controller-runtime/pkg/log/zap" anthoscertmanager "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/apis/anthoscertmanager/v1" - controllers "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/controller/certificates" logf "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/logs" //+kubebuilder:scaffold:imports ) @@ -92,13 +91,13 @@ os.Exit(1) } - if err = (&controllers.CertificateReconciler{ - Client: mgr.GetClient(), - Scheme: mgr.GetScheme(), - }).SetupWithManager(mgr); err != nil { - setupLog.Error(err, "unable to create controller", "controller", "Certificate") - os.Exit(1) - } + // if err = (&certificates.CertificateReconciler{ + // Client: mgr.GetClient(), + // Scheme: mgr.GetScheme(), + // }).SetupWithManager(mgr); err != nil { + // setupLog.Error(err, "unable to create controller", "controller", "Certificate") + // os.Exit(1) + // } //+kubebuilder:scaffold:builder if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil { diff --git a/pkg/apis/anthoscertmanager/v1/certificate_types.go b/pkg/apis/anthoscertmanager/v1/certificate_types.go index 7af6437..e45d54f 100644 --- a/pkg/apis/anthoscertmanager/v1/certificate_types.go +++ b/pkg/apis/anthoscertmanager/v1/certificate_types.go @@ -174,14 +174,113 @@ // is being issued. type PrivateKeyRotationPolicy string -// CertificateStatus defines the observed state of Certificate -type CertificateStatus struct { - // INSERT ADDITIONAL STATUS FIELD - define observed state of cluster - // Important: Run "make" to regenerate code after modifying this file +// CertificateConditionType represents an Certificate condition value. +type CertificateConditionType string + +// CertificateCondition contains condition information for an Certificate. +type CertificateCondition struct { + // Type of the condition, known values are (`Ready`, `Issuing`). + Type CertificateConditionType `json:"type"` + + // Status of the condition, one of (`True`, `False`, `Unknown`). + Status acmmeta.ConditionStatus `json:"status"` + + // LastTransitionTime is the timestamp corresponding to the last status + // change of this condition. + // +optional + LastTransitionTime *metav1.Time `json:"lastTransitionTime,omitempty"` + + // Reason is a brief machine readable explanation for the condition's last + // transition. + // +optional + Reason string `json:"reason,omitempty"` + + // Message is a human readable description of the details of the last + // transition, complementing reason. + // +optional + Message string `json:"message,omitempty"` + + // If set, this represents the .metadata.generation that the condition was + // set based upon. + // For instance, if .metadata.generation is currently 12, but the + // .status.condition[x].observedGeneration is 9, the condition is out of date + // with respect to the current state of the Certificate. + // +optional + ObservedGeneration int64 `json:"observedGeneration,omitempty"` } -//+kubebuilder:object:root=true -//+kubebuilder:subresource:status +// CertificateStatus defines the observed state of Certificate +type CertificateStatus struct { + // List of status conditions to indicate the status of certificates. + // Known condition types are `Ready` and `Issuing`. + // +listType=map + // +listMapKey=type + // +optional + Conditions []CertificateCondition `json:"conditions,omitempty"` + + // LastFailureTime is the time as recorded by the Certificate controller + // of the most recent failure to complete a CertificateRequest for this + // Certificate resource. + // If set, cert-manager will not re-request another Certificate until + // 1 hour has elapsed from this time. + // +optional + LastFailureTime *metav1.Time `json:"lastFailureTime,omitempty"` + + // The time after which the certificate stored in the secret named + // by this resource in spec.secretName is valid. + // +optional + NotBefore *metav1.Time `json:"notBefore,omitempty"` + + // The expiration time of the certificate stored in the secret named + // by this resource in `spec.secretName`. + // +optional + NotAfter *metav1.Time `json:"notAfter,omitempty"` + + // RenewalTime is the time at which the certificate will be next + // renewed. + // If not set, no upcoming renewal is scheduled. + // +optional + RenewalTime *metav1.Time `json:"renewalTime,omitempty"` + + // The current 'revision' of the certificate as issued. + // + // When a CertificateRequest resource is created, it will have the + // `cert-manager.io/certificate-revision` set to one greater than the + // current value of this field. + // + // Upon issuance, this field will be set to the value of the annotation + // on the CertificateRequest resource used to issue the certificate. + // + // Persisting the value on the CertificateRequest resource allows the + // certificates controller to know whether a request is part of an old + // issuance or if it is part of the ongoing revision's issuance by + // checking if the revision value in the annotation is greater than this + // field. + // +optional + Revision *int `json:"revision,omitempty"` + + // The name of the Secret resource containing the private key to be used + // for the next certificate iteration. + // The keymanager controller will automatically set this field if the + // `Issuing` condition is set to `True`. + // It will automatically unset this field when the Issuing condition is + // not set or False. + // +optional + NextPrivateKeySecretName *string `json:"nextPrivateKeySecretName,omitempty"` + + // The number of continuous failed issuance attempts up till now. This + // field gets removed (if set) on a successful issuance and gets set to + // 1 if unset and an issuance has failed. If an issuance has failed, the + // delay till the next issuance will be calculated using formula + // time.Hour * 2 ^ (failedIssuanceAttempts - 1). + // +optional + FailedIssuanceAttempts *int `json:"failedIssuanceAttempts,omitempty"` +} + +// +genclient +// +k8s:openapi-gen=true +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +kubebuilder:storageversion // Certificate is the Schema for the certificates API type Certificate struct { diff --git a/pkg/apis/anthoscertmanager/v1/certificaterequest_types.go b/pkg/apis/anthoscertmanager/v1/certificaterequest_types.go new file mode 100644 index 0000000..b2e1c9a --- /dev/null +++ b/pkg/apis/anthoscertmanager/v1/certificaterequest_types.go @@ -0,0 +1,195 @@ +package v1 + +import ( + acmmeta "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/apis/meta/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +const ( + // Pending indicates that a CertificateRequest is still in progress. + CertificateRequestReasonPending = "Pending" + + // Failed indicates that a CertificateRequest has failed, either due to + // timing out or some other critical failure. + CertificateRequestReasonFailed = "Failed" + + // Issued indicates that a CertificateRequest has been completed, and that + // the `status.certificate` field is set. + CertificateRequestReasonIssued = "Issued" + + // Denied is a Ready condition reason that indicates that a + // CertificateRequest has been denied, and the CertificateRequest will never + // be issued. + CertificateRequestReasonDenied = "Denied" +) + +// +genclient +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +kubebuilder:storageversion + +// A CertificateRequest is used to request a signed certificate from one of the +// configured issuers. +// +// All fields within the CertificateRequest's `spec` are immutable after creation. +// A CertificateRequest will either succeed or fail, as denoted by its `status.state` +// field. +// +// A CertificateRequest is a one-shot resource, meaning it represents a single +// point in time request for a certificate and cannot be re-used. +// +k8s:openapi-gen=true +type CertificateRequest struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + // Desired state of the CertificateRequest resource. + Spec CertificateRequestSpec `json:"spec"` + + // Status of the CertificateRequest. This is set and managed automatically. + // +optional + Status CertificateRequestStatus `json:"status"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// CertificateRequestList is a list of Certificates +type CertificateRequestList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata"` + + Items []CertificateRequest `json:"items"` +} + +// CertificateRequestSpec defines the desired state of CertificateRequest +type CertificateRequestSpec struct { + // The requested 'duration' (i.e. lifetime) of the Certificate. + // This option may be ignored/overridden by some issuer types. + // +optional + Duration *metav1.Duration `json:"duration,omitempty"` + + // IssuerRef is a reference to the issuer for this CertificateRequest. If + // the `kind` field is not set, or set to `Issuer`, an Issuer resource with + // the given name in the same namespace as the CertificateRequest will be + // used. If the `kind` field is set to `ClusterIssuer`, a ClusterIssuer with + // the provided name will be used. The `name` field in this stanza is + // required at all times. The group field refers to the API group of the + // issuer which defaults to `cert-manager.io` if empty. + IssuerRef acmmeta.ObjectReference `json:"issuerRef"` + + // The PEM-encoded x509 certificate signing request to be submitted to the + // CA for signing. + Request []byte `json:"request"` + + // IsCA will request to mark the certificate as valid for certificate signing + // when submitting to the issuer. + // This will automatically add the `cert sign` usage to the list of `usages`. + // +optional + IsCA bool `json:"isCA,omitempty"` + + // Usages is the set of x509 usages that are requested for the certificate. + // If usages are set they SHOULD be encoded inside the CSR spec + // Defaults to `digital signature` and `key encipherment` if not specified. + // +optional + Usages []KeyUsage `json:"usages,omitempty"` + + // Username contains the name of the user that created the CertificateRequest. + // Populated by the cert-manager webhook on creation and immutable. + // +optional + Username string `json:"username,omitempty"` + // UID contains the uid of the user that created the CertificateRequest. + // Populated by the cert-manager webhook on creation and immutable. + // +optional + UID string `json:"uid,omitempty"` + // Groups contains group membership of the user that created the CertificateRequest. + // Populated by the cert-manager webhook on creation and immutable. + // +listType=atomic + // +optional + Groups []string `json:"groups,omitempty"` + // Extra contains extra attributes of the user that created the CertificateRequest. + // Populated by the cert-manager webhook on creation and immutable. + // +optional + Extra map[string][]string `json:"extra,omitempty"` +} + +// CertificateRequestStatus defines the observed state of CertificateRequest and +// resulting signed certificate. +type CertificateRequestStatus struct { + // List of status conditions to indicate the status of a CertificateRequest. + // Known condition types are `Ready` and `InvalidRequest`. + // +listType=map + // +listMapKey=type + // +optional + Conditions []CertificateRequestCondition `json:"conditions,omitempty"` + + // The PEM encoded x509 certificate resulting from the certificate + // signing request. + // If not set, the CertificateRequest has either not been completed or has + // failed. More information on failure can be found by checking the + // `conditions` field. + // +optional + Certificate []byte `json:"certificate,omitempty"` + + // The PEM encoded x509 certificate of the signer, also known as the CA + // (Certificate Authority). + // This is set on a best-effort basis by different issuers. + // If not set, the CA is assumed to be unknown/not available. + // +optional + CA []byte `json:"ca,omitempty"` + + // FailureTime stores the time that this CertificateRequest failed. This is + // used to influence garbage collection and back-off. + // +optional + FailureTime *metav1.Time `json:"failureTime,omitempty"` +} + +// CertificateRequestCondition contains condition information for a CertificateRequest. +type CertificateRequestCondition struct { + // Type of the condition, known values are (`Ready`, `InvalidRequest`, + // `Approved`, `Denied`). + Type CertificateRequestConditionType `json:"type"` + + // Status of the condition, one of (`True`, `False`, `Unknown`). + Status acmmeta.ConditionStatus `json:"status"` + + // LastTransitionTime is the timestamp corresponding to the last status + // change of this condition. + // +optional + LastTransitionTime *metav1.Time `json:"lastTransitionTime,omitempty"` + + // Reason is a brief machine readable explanation for the condition's last + // transition. + // +optional + Reason string `json:"reason,omitempty"` + + // Message is a human readable description of the details of the last + // transition, complementing reason. + // +optional + Message string `json:"message,omitempty"` +} + +// CertificateRequestConditionType represents an Certificate condition value. +type CertificateRequestConditionType string + +const ( + // CertificateRequestConditionReady indicates that a certificate is ready for use. + // This is defined as: + // - The target certificate exists in CertificateRequest.Status + CertificateRequestConditionReady CertificateRequestConditionType = "Ready" + + // CertificateRequestConditionInvalidRequest indicates that a certificate + // signer has refused to sign the request due to at least one of the input + // parameters being invalid. Additional information about why the request + // was rejected can be found in the `reason` and `message` fields. + CertificateRequestConditionInvalidRequest CertificateRequestConditionType = "InvalidRequest" + + // CertificateRequestConditionApproved indicates that a certificate request + // is approved and ready for signing. Condition must never have a status of + // `False`, and cannot be modified once set. Cannot be set alongside + // `Denied`. + CertificateRequestConditionApproved CertificateRequestConditionType = "Approved" + + // CertificateRequestConditionDenied indicates that a certificate request is + // denied, and must never be signed. Condition must never have a status of + // `False`, and cannot be modified once set. Cannot be set alongside + // `Approved`. + CertificateRequestConditionDenied CertificateRequestConditionType = "Denied" +) diff --git a/pkg/apis/anthoscertmanager/v1/types.go b/pkg/apis/anthoscertmanager/v1/types.go new file mode 100644 index 0000000..fa46180 --- /dev/null +++ b/pkg/apis/anthoscertmanager/v1/types.go @@ -0,0 +1,228 @@ +package v1 + +// Common annotation keys added to resources. +const ( + // Annotation key for DNS subjectAltNames. + AltNamesAnnotationKey = "anthos-cert-manager.io/alt-names" + + // Annotation key for IP subjectAltNames. + IPSANAnnotationKey = "anthos-cert-manager.io/ip-sans" + + // Annotation key for URI subjectAltNames. + URISANAnnotationKey = "anthos-cert-manager.io/uri-sans" + + // Annotation key for certificate common name. + CommonNameAnnotationKey = "anthos-cert-manager.io/common-name" + + // Duration key for certificate duration. + DurationAnnotationKey = "anthos-cert-manager.io/duration" + + // Annotation key for certificate renewBefore. + RenewBeforeAnnotationKey = "anthos-cert-manager.io/renew-before" + + // Annotation key for certificate key usages. + UsagesAnnotationKey = "anthos-cert-manager.io/usages" + + // Annotation key the 'name' of the Issuer resource. + IssuerNameAnnotationKey = "anthos-cert-manager.io/issuer-name" + + // Annotation key for the 'kind' of the Issuer resource. + IssuerKindAnnotationKey = "anthos-cert-manager.io/issuer-kind" + + // Annotation key for the 'group' of the Issuer resource. + IssuerGroupAnnotationKey = "anthos-cert-manager.io/issuer-group" + + // Annotation key for the name of the certificate that a resource is related to. + CertificateNameKey = "anthos-cert-manager.io/certificate-name" + + // Annotation key used to denote whether a Secret is named on a Certificate + // as a 'next private key' Secret resource. + IsNextPrivateKeySecretLabelKey = "anthos-cert-manager.io/next-private-key" + + // Annotation key used to limit the number of CertificateRequests to be kept for a Certificate. + // Minimum value is 1. + // If unset all CertificateRequests will be kept. + RevisionHistoryLimitAnnotationKey = "anthos-cert-manager.io/revision-history-limit" + + // Annotation key used to set the PrivateKeyAlgorithm for a Certificate. + // If PrivateKeyAlgorithm is specified and `size` is not provided, + // key size of 256 will be used for `ECDSA` key algorithm and + // key size of 2048 will be used for `RSA` key algorithm. + // key size is ignored when using the `Ed25519` key algorithm. + // If unset an algorithm `RSA` will be used. + PrivateKeyAlgorithmAnnotationKey = "anthos-cert-manager.io/private-key-algorithm" + + // Annotation key used to set the PrivateKeyEncoding for a Certificate. + // If provided, allowed values are `PKCS1` and `PKCS8` standing for PKCS#1 + // and PKCS#8, respectively. + // If unset an encoding `PKCS1` will be used. + PrivateKeyEncodingAnnotationKey = "anthos-cert-manager.io/private-key-encoding" + + // Annotation key used to set the size of the private key for a Certificate. + // If PrivateKeyAlgorithm is set to `RSA`, valid values are `2048`, `4096` or `8192`, + // and will default to `2048` if not specified. + // If PrivateKeyAlgorithm is set to `ECDSA`, valid values are `256`, `384` or `521`, + // and will default to `256` if not specified. + // If PrivateKeyAlgorithm is set to `Ed25519`, Size is ignored. + // No other values are allowed. + PrivateKeySizeAnnotationKey = "anthos-cert-manager.io/private-key-size" + + // Annotation key used to set the PrivateKeyRotationPolicy for a Certificate. + // If unset a policy `Never` will be used. + PrivateKeyRotationPolicyAnnotationKey = "anthos-cert-manager.io/private-key-rotation-policy" +) + +const ( + // IngressIssuerNameAnnotationKey holds the issuerNameAnnotation value which can be + // used to override the issuer specified on the created Certificate resource. + IngressIssuerNameAnnotationKey = "anthos-cert-manager.io/issuer" + // IngressClusterIssuerNameAnnotationKey holds the clusterIssuerNameAnnotation value which + // can be used to override the issuer specified on the created Certificate resource. The Certificate + // will reference the specified *ClusterIssuer* instead of normal issuer. + IngressClusterIssuerNameAnnotationKey = "anthos-cert-manager.io/cluster-issuer" + // IngressACMEIssuerHTTP01IngressClassAnnotationKey holds the acmeIssuerHTTP01IngressClassAnnotation value + // which can be used to override the http01 ingressClass if the challenge type is set to http01 + IngressACMEIssuerHTTP01IngressClassAnnotationKey = "acme.anthos-cert-manager.io/http01-ingress-class" + + // IngressClassAnnotationKey picks a specific "class" for the Ingress. The + // controller only processes Ingresses with this annotation either unset, or + // set to either the configured value or the empty string. + IngressClassAnnotationKey = "kubernetes.io/ingress.class" +) + +// Annotation names for CertificateRequests +const ( + // Annotation added to CertificateRequest resources to denote the name of + // a Secret resource containing the private key used to sign the CSR stored + // on the resource. + // This annotation *may* not be present, and is used by the 'self signing' + // issuer type to self-sign certificates. + CertificateRequestPrivateKeyAnnotationKey = "anthos-cert-manager.io/private-key-secret-name" + + // Annotation to declare the CertificateRequest "revision", belonging to a Certificate Resource + CertificateRequestRevisionAnnotationKey = "anthos-cert-manager.io/certificate-revision" +) + +const ( + // IssueTemporaryCertificateAnnotation is an annotation that can be added to + // Certificate resources. + // If it is present, a temporary internally signed certificate will be + // stored in the target Secret resource whilst the real Issuer is processing + // the certificate request. + IssueTemporaryCertificateAnnotation = "anthos-cert-manager.io/issue-temporary-certificate" +) + +// Common/known resource kinds. +const ( + ClusterIssuerKind = "ClusterIssuer" + IssuerKind = "Issuer" + CertificateKind = "Certificate" + CertificateRequestKind = "CertificateRequest" +) + +const ( + // WantInjectAnnotation is the annotation that specifies that a particular + // object wants injection of CAs. It takes the form of a reference to a certificate + // as namespace/name. The certificate is expected to have the is-serving-for annotations. + WantInjectAnnotation = "anthos-cert-manager.io/inject-ca-from" + + // WantInjectAPIServerCAAnnotation will - if set to "true" - make the cainjector + // inject the CA certificate for the Kubernetes apiserver into the resource. + // It discovers the apiserver's CA by inspecting the service account credentials + // mounted into the cainjector pod. + WantInjectAPIServerCAAnnotation = "anthos-cert-manager.io/inject-apiserver-ca" + + // WantInjectFromSecretAnnotation is the annotation that specifies that a particular + // object wants injection of CAs. It takes the form of a reference to a Secret + // as namespace/name. + WantInjectFromSecretAnnotation = "anthos-cert-manager.io/inject-ca-from-secret" + + // AllowsInjectionFromSecretAnnotation is an annotation that must be added + // to Secret resource that want to denote that they can be directly + // injected into injectables that have a `inject-ca-from-secret` annotation. + // If an injectable references a Secret that does NOT have this annotation, + // the cainjector will refuse to inject the secret. + AllowsInjectionFromSecretAnnotation = "anthos-cert-manager.io/allow-direct-injection" +) + +// Issuer specific Annotations +const ( + // VenafiCustomFieldsAnnotationKey is the annotation that passes on JSON encoded custom fields to the Venafi issuer + // This will only work with Venafi TPP v19.3 and higher + // The value is an array with objects containing the name and value keys + // for example: `[{"name": "custom-field", "value": "custom-value"}]` + VenafiCustomFieldsAnnotationKey = "venafi.anthos-cert-manager.io/custom-fields" + + // VenafiPickupIDAnnotationKey is the annotation key used to record the + // Venafi Pickup ID of a certificate signing request that has been submitted + // to the Venafi API for collection later. + VenafiPickupIDAnnotationKey = "venafi.anthos-cert-manager.io/pickup-id" +) + +// KeyUsage specifies valid usage contexts for keys. +// See: +// https://tools.ietf.org/html/rfc5280#section-4.2.1.3 +// https://tools.ietf.org/html/rfc5280#section-4.2.1.12 +// +// Valid KeyUsage values are as follows: +// "signing", +// "digital signature", +// "content commitment", +// "key encipherment", +// "key agreement", +// "data encipherment", +// "cert sign", +// "crl sign", +// "encipher only", +// "decipher only", +// "any", +// "server auth", +// "client auth", +// "code signing", +// "email protection", +// "s/mime", +// "ipsec end system", +// "ipsec tunnel", +// "ipsec user", +// "timestamping", +// "ocsp signing", +// "microsoft sgc", +// "netscape sgc" +// +kubebuilder:validation:Enum="signing";"digital signature";"content commitment";"key encipherment";"key agreement";"data encipherment";"cert sign";"crl sign";"encipher only";"decipher only";"any";"server auth";"client auth";"code signing";"email protection";"s/mime";"ipsec end system";"ipsec tunnel";"ipsec user";"timestamping";"ocsp signing";"microsoft sgc";"netscape sgc" +type KeyUsage string + +const ( + UsageSigning KeyUsage = "signing" + UsageDigitalSignature KeyUsage = "digital signature" + UsageContentCommitment KeyUsage = "content commitment" + UsageKeyEncipherment KeyUsage = "key encipherment" + UsageKeyAgreement KeyUsage = "key agreement" + UsageDataEncipherment KeyUsage = "data encipherment" + UsageCertSign KeyUsage = "cert sign" + UsageCRLSign KeyUsage = "crl sign" + UsageEncipherOnly KeyUsage = "encipher only" + UsageDecipherOnly KeyUsage = "decipher only" + UsageAny KeyUsage = "any" + UsageServerAuth KeyUsage = "server auth" + UsageClientAuth KeyUsage = "client auth" + UsageCodeSigning KeyUsage = "code signing" + UsageEmailProtection KeyUsage = "email protection" + UsageSMIME KeyUsage = "s/mime" + UsageIPsecEndSystem KeyUsage = "ipsec end system" + UsageIPsecTunnel KeyUsage = "ipsec tunnel" + UsageIPsecUser KeyUsage = "ipsec user" + UsageTimestamping KeyUsage = "timestamping" + UsageOCSPSigning KeyUsage = "ocsp signing" + UsageMicrosoftSGC KeyUsage = "microsoft sgc" + UsageNetscapeSGC KeyUsage = "netscape sgc" +) + +// DefaultKeyUsages contains the default list of key usages +func DefaultKeyUsages() []KeyUsage { + // The serverAuth EKU is required as of Mac OS Catalina: https://support.apple.com/en-us/HT210176 + // Without this usage, certificates will _always_ flag a warning in newer Mac OS browsers. + // We don't explicitly add it here as it leads to strange behaviour when a user sets isCA: true + // (in which case, 'serverAuth' on the CA can break a lot of clients). + // CAs can (and often do) opt to automatically add usages. + return []KeyUsage{UsageDigitalSignature, UsageKeyEncipherment} +} diff --git a/pkg/apis/anthoscertmanager/v1/zz_generated.deepcopy.go b/pkg/apis/anthoscertmanager/v1/zz_generated.deepcopy.go index 8e00a8d..6001ee4 100644 --- a/pkg/apis/anthoscertmanager/v1/zz_generated.deepcopy.go +++ b/pkg/apis/anthoscertmanager/v1/zz_generated.deepcopy.go @@ -57,7 +57,7 @@ out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) - out.Status = in.Status + in.Status.DeepCopyInto(&out.Status) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Certificate. @@ -79,6 +79,25 @@ } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CertificateCondition) DeepCopyInto(out *CertificateCondition) { + *out = *in + if in.LastTransitionTime != nil { + in, out := &in.LastTransitionTime, &out.LastTransitionTime + *out = (*in).DeepCopy() + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertificateCondition. +func (in *CertificateCondition) DeepCopy() *CertificateCondition { + if in == nil { + return nil + } + out := new(CertificateCondition) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CertificateList) DeepCopyInto(out *CertificateList) { *out = *in out.TypeMeta = in.TypeMeta @@ -126,6 +145,171 @@ } // 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 + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertificateRequest. +func (in *CertificateRequest) DeepCopy() *CertificateRequest { + if in == nil { + return nil + } + out := new(CertificateRequest) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *CertificateRequest) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CertificateRequestCondition) DeepCopyInto(out *CertificateRequestCondition) { + *out = *in + if in.LastTransitionTime != nil { + in, out := &in.LastTransitionTime, &out.LastTransitionTime + *out = (*in).DeepCopy() + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertificateRequestCondition. +func (in *CertificateRequestCondition) DeepCopy() *CertificateRequestCondition { + if in == nil { + return nil + } + out := new(CertificateRequestCondition) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CertificateRequestList) DeepCopyInto(out *CertificateRequestList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]CertificateRequest, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertificateRequestList. +func (in *CertificateRequestList) DeepCopy() *CertificateRequestList { + if in == nil { + return nil + } + out := new(CertificateRequestList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *CertificateRequestList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CertificateRequestSpec) DeepCopyInto(out *CertificateRequestSpec) { + *out = *in + if in.Duration != nil { + in, out := &in.Duration, &out.Duration + *out = new(metav1.Duration) + **out = **in + } + out.IssuerRef = in.IssuerRef + if in.Request != nil { + in, out := &in.Request, &out.Request + *out = make([]byte, len(*in)) + copy(*out, *in) + } + if in.Usages != nil { + in, out := &in.Usages, &out.Usages + *out = make([]KeyUsage, len(*in)) + copy(*out, *in) + } + if in.Groups != nil { + in, out := &in.Groups, &out.Groups + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.Extra != nil { + in, out := &in.Extra, &out.Extra + *out = make(map[string][]string, len(*in)) + for key, val := range *in { + var outVal []string + if val == nil { + (*out)[key] = nil + } else { + in, out := &val, &outVal + *out = make([]string, len(*in)) + copy(*out, *in) + } + (*out)[key] = outVal + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertificateRequestSpec. +func (in *CertificateRequestSpec) DeepCopy() *CertificateRequestSpec { + if in == nil { + return nil + } + out := new(CertificateRequestSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CertificateRequestStatus) DeepCopyInto(out *CertificateRequestStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]CertificateRequestCondition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Certificate != nil { + in, out := &in.Certificate, &out.Certificate + *out = make([]byte, len(*in)) + copy(*out, *in) + } + if in.CA != nil { + in, out := &in.CA, &out.CA + *out = make([]byte, len(*in)) + copy(*out, *in) + } + if in.FailureTime != nil { + in, out := &in.FailureTime, &out.FailureTime + *out = (*in).DeepCopy() + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertificateRequestStatus. +func (in *CertificateRequestStatus) DeepCopy() *CertificateRequestStatus { + if in == nil { + return nil + } + out := new(CertificateRequestStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CertificateSecretTemplate) DeepCopyInto(out *CertificateSecretTemplate) { *out = *in if in.Annotations != nil { @@ -208,6 +392,44 @@ // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CertificateStatus) DeepCopyInto(out *CertificateStatus) { *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]CertificateCondition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.LastFailureTime != nil { + in, out := &in.LastFailureTime, &out.LastFailureTime + *out = (*in).DeepCopy() + } + if in.NotBefore != nil { + in, out := &in.NotBefore, &out.NotBefore + *out = (*in).DeepCopy() + } + if in.NotAfter != nil { + in, out := &in.NotAfter, &out.NotAfter + *out = (*in).DeepCopy() + } + if in.RenewalTime != nil { + in, out := &in.RenewalTime, &out.RenewalTime + *out = (*in).DeepCopy() + } + if in.Revision != nil { + in, out := &in.Revision, &out.Revision + *out = new(int) + **out = **in + } + if in.NextPrivateKeySecretName != nil { + in, out := &in.NextPrivateKeySecretName, &out.NextPrivateKeySecretName + *out = new(string) + **out = **in + } + if in.FailedIssuanceAttempts != nil { + in, out := &in.FailedIssuanceAttempts, &out.FailedIssuanceAttempts + *out = new(int) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertificateStatus. diff --git a/pkg/client/clientset/versioned/typed/anthoscertmanager/v1/anthoscertmanager_client.go b/pkg/client/clientset/versioned/typed/anthoscertmanager/v1/anthoscertmanager_client.go index 4cd9e16..c462f69 100644 --- a/pkg/client/clientset/versioned/typed/anthoscertmanager/v1/anthoscertmanager_client.go +++ b/pkg/client/clientset/versioned/typed/anthoscertmanager/v1/anthoscertmanager_client.go @@ -27,6 +27,8 @@ type AnthosCertmanagerV1Interface interface { RESTClient() rest.Interface + CertificatesGetter + CertificateRequestsGetter IssuersGetter } @@ -35,6 +37,14 @@ restClient rest.Interface } +func (c *AnthosCertmanagerV1Client) Certificates(namespace string) CertificateInterface { + return newCertificates(c, namespace) +} + +func (c *AnthosCertmanagerV1Client) CertificateRequests(namespace string) CertificateRequestInterface { + return newCertificateRequests(c, namespace) +} + func (c *AnthosCertmanagerV1Client) Issuers(namespace string) IssuerInterface { return newIssuers(c, namespace) } diff --git a/pkg/client/clientset/versioned/typed/anthoscertmanager/v1/certificate.go b/pkg/client/clientset/versioned/typed/anthoscertmanager/v1/certificate.go new file mode 100644 index 0000000..f0ed833 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/anthoscertmanager/v1/certificate.go @@ -0,0 +1,194 @@ +/* +Copyright 2022. + +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 client-gen. DO NOT EDIT. + +package v1 + +import ( + "context" + "time" + + v1 "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/apis/anthoscertmanager/v1" + scheme "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/client/clientset/versioned/scheme" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + rest "k8s.io/client-go/rest" +) + +// CertificatesGetter has a method to return a CertificateInterface. +// A group's client should implement this interface. +type CertificatesGetter interface { + Certificates(namespace string) CertificateInterface +} + +// CertificateInterface has methods to work with Certificate resources. +type CertificateInterface interface { + Create(ctx context.Context, certificate *v1.Certificate, opts metav1.CreateOptions) (*v1.Certificate, error) + Update(ctx context.Context, certificate *v1.Certificate, opts metav1.UpdateOptions) (*v1.Certificate, error) + UpdateStatus(ctx context.Context, certificate *v1.Certificate, opts metav1.UpdateOptions) (*v1.Certificate, error) + Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error + Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.Certificate, error) + List(ctx context.Context, opts metav1.ListOptions) (*v1.CertificateList, error) + Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Certificate, err error) + CertificateExpansion +} + +// certificates implements CertificateInterface +type certificates struct { + client rest.Interface + ns string +} + +// newCertificates returns a Certificates +func newCertificates(c *AnthosCertmanagerV1Client, namespace string) *certificates { + return &certificates{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the certificate, and returns the corresponding certificate object, and an error if there is any. +func (c *certificates) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Certificate, err error) { + result = &v1.Certificate{} + err = c.client.Get(). + Namespace(c.ns). + Resource("certificates"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(ctx). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of Certificates that match those selectors. +func (c *certificates) List(ctx context.Context, opts metav1.ListOptions) (result *v1.CertificateList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &v1.CertificateList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("certificates"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(ctx). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested certificates. +func (c *certificates) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("certificates"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch(ctx) +} + +// Create takes the representation of a certificate and creates it. Returns the server's representation of the certificate, and an error, if there is any. +func (c *certificates) Create(ctx context.Context, certificate *v1.Certificate, opts metav1.CreateOptions) (result *v1.Certificate, err error) { + result = &v1.Certificate{} + err = c.client.Post(). + Namespace(c.ns). + Resource("certificates"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(certificate). + Do(ctx). + Into(result) + return +} + +// Update takes the representation of a certificate and updates it. Returns the server's representation of the certificate, and an error, if there is any. +func (c *certificates) Update(ctx context.Context, certificate *v1.Certificate, opts metav1.UpdateOptions) (result *v1.Certificate, err error) { + result = &v1.Certificate{} + err = c.client.Put(). + Namespace(c.ns). + Resource("certificates"). + Name(certificate.Name). + VersionedParams(&opts, scheme.ParameterCodec). + Body(certificate). + Do(ctx). + Into(result) + return +} + +// UpdateStatus was generated because the type contains a Status member. +// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). +func (c *certificates) UpdateStatus(ctx context.Context, certificate *v1.Certificate, opts metav1.UpdateOptions) (result *v1.Certificate, err error) { + result = &v1.Certificate{} + err = c.client.Put(). + Namespace(c.ns). + Resource("certificates"). + Name(certificate.Name). + SubResource("status"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(certificate). + Do(ctx). + Into(result) + return +} + +// Delete takes name of the certificate and deletes it. Returns an error if one occurs. +func (c *certificates) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("certificates"). + Name(name). + Body(&opts). + Do(ctx). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *certificates) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { + var timeout time.Duration + if listOpts.TimeoutSeconds != nil { + timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second + } + return c.client.Delete(). + Namespace(c.ns). + Resource("certificates"). + VersionedParams(&listOpts, scheme.ParameterCodec). + Timeout(timeout). + Body(&opts). + Do(ctx). + Error() +} + +// Patch applies the patch and returns the patched certificate. +func (c *certificates) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Certificate, err error) { + result = &v1.Certificate{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("certificates"). + Name(name). + SubResource(subresources...). + VersionedParams(&opts, scheme.ParameterCodec). + Body(data). + Do(ctx). + Into(result) + return +} diff --git a/pkg/client/clientset/versioned/typed/anthoscertmanager/v1/certificaterequest.go b/pkg/client/clientset/versioned/typed/anthoscertmanager/v1/certificaterequest.go new file mode 100644 index 0000000..906e1c7 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/anthoscertmanager/v1/certificaterequest.go @@ -0,0 +1,194 @@ +/* +Copyright 2022. + +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 client-gen. DO NOT EDIT. + +package v1 + +import ( + "context" + "time" + + v1 "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/apis/anthoscertmanager/v1" + scheme "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/client/clientset/versioned/scheme" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + rest "k8s.io/client-go/rest" +) + +// CertificateRequestsGetter has a method to return a CertificateRequestInterface. +// A group's client should implement this interface. +type CertificateRequestsGetter interface { + CertificateRequests(namespace string) CertificateRequestInterface +} + +// CertificateRequestInterface has methods to work with CertificateRequest resources. +type CertificateRequestInterface interface { + Create(ctx context.Context, certificateRequest *v1.CertificateRequest, opts metav1.CreateOptions) (*v1.CertificateRequest, error) + Update(ctx context.Context, certificateRequest *v1.CertificateRequest, opts metav1.UpdateOptions) (*v1.CertificateRequest, error) + UpdateStatus(ctx context.Context, certificateRequest *v1.CertificateRequest, opts metav1.UpdateOptions) (*v1.CertificateRequest, error) + Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error + Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.CertificateRequest, error) + List(ctx context.Context, opts metav1.ListOptions) (*v1.CertificateRequestList, error) + Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.CertificateRequest, err error) + CertificateRequestExpansion +} + +// certificateRequests implements CertificateRequestInterface +type certificateRequests struct { + client rest.Interface + ns string +} + +// newCertificateRequests returns a CertificateRequests +func newCertificateRequests(c *AnthosCertmanagerV1Client, namespace string) *certificateRequests { + return &certificateRequests{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the certificateRequest, and returns the corresponding certificateRequest object, and an error if there is any. +func (c *certificateRequests) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.CertificateRequest, err error) { + result = &v1.CertificateRequest{} + err = c.client.Get(). + Namespace(c.ns). + Resource("certificaterequests"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(ctx). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of CertificateRequests that match those selectors. +func (c *certificateRequests) List(ctx context.Context, opts metav1.ListOptions) (result *v1.CertificateRequestList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &v1.CertificateRequestList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("certificaterequests"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(ctx). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested certificateRequests. +func (c *certificateRequests) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("certificaterequests"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch(ctx) +} + +// Create takes the representation of a certificateRequest and creates it. Returns the server's representation of the certificateRequest, and an error, if there is any. +func (c *certificateRequests) Create(ctx context.Context, certificateRequest *v1.CertificateRequest, opts metav1.CreateOptions) (result *v1.CertificateRequest, err error) { + result = &v1.CertificateRequest{} + err = c.client.Post(). + Namespace(c.ns). + Resource("certificaterequests"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(certificateRequest). + Do(ctx). + Into(result) + return +} + +// Update takes the representation of a certificateRequest and updates it. Returns the server's representation of the certificateRequest, and an error, if there is any. +func (c *certificateRequests) Update(ctx context.Context, certificateRequest *v1.CertificateRequest, opts metav1.UpdateOptions) (result *v1.CertificateRequest, err error) { + result = &v1.CertificateRequest{} + err = c.client.Put(). + Namespace(c.ns). + Resource("certificaterequests"). + Name(certificateRequest.Name). + VersionedParams(&opts, scheme.ParameterCodec). + Body(certificateRequest). + Do(ctx). + Into(result) + return +} + +// UpdateStatus was generated because the type contains a Status member. +// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). +func (c *certificateRequests) UpdateStatus(ctx context.Context, certificateRequest *v1.CertificateRequest, opts metav1.UpdateOptions) (result *v1.CertificateRequest, err error) { + result = &v1.CertificateRequest{} + err = c.client.Put(). + Namespace(c.ns). + Resource("certificaterequests"). + Name(certificateRequest.Name). + SubResource("status"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(certificateRequest). + Do(ctx). + Into(result) + return +} + +// Delete takes name of the certificateRequest and deletes it. Returns an error if one occurs. +func (c *certificateRequests) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("certificaterequests"). + Name(name). + Body(&opts). + Do(ctx). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *certificateRequests) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { + var timeout time.Duration + if listOpts.TimeoutSeconds != nil { + timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second + } + return c.client.Delete(). + Namespace(c.ns). + Resource("certificaterequests"). + VersionedParams(&listOpts, scheme.ParameterCodec). + Timeout(timeout). + Body(&opts). + Do(ctx). + Error() +} + +// Patch applies the patch and returns the patched certificateRequest. +func (c *certificateRequests) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.CertificateRequest, err error) { + result = &v1.CertificateRequest{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("certificaterequests"). + Name(name). + SubResource(subresources...). + VersionedParams(&opts, scheme.ParameterCodec). + Body(data). + Do(ctx). + Into(result) + return +} diff --git a/pkg/client/clientset/versioned/typed/anthoscertmanager/v1/fake/fake_anthoscertmanager_client.go b/pkg/client/clientset/versioned/typed/anthoscertmanager/v1/fake/fake_anthoscertmanager_client.go index f3fa423..33201ee 100644 --- a/pkg/client/clientset/versioned/typed/anthoscertmanager/v1/fake/fake_anthoscertmanager_client.go +++ b/pkg/client/clientset/versioned/typed/anthoscertmanager/v1/fake/fake_anthoscertmanager_client.go @@ -27,6 +27,14 @@ *testing.Fake } +func (c *FakeAnthosCertmanagerV1) Certificates(namespace string) v1.CertificateInterface { + return &FakeCertificates{c, namespace} +} + +func (c *FakeAnthosCertmanagerV1) CertificateRequests(namespace string) v1.CertificateRequestInterface { + return &FakeCertificateRequests{c, namespace} +} + func (c *FakeAnthosCertmanagerV1) Issuers(namespace string) v1.IssuerInterface { return &FakeIssuers{c, namespace} } diff --git a/pkg/client/clientset/versioned/typed/anthoscertmanager/v1/fake/fake_certificate.go b/pkg/client/clientset/versioned/typed/anthoscertmanager/v1/fake/fake_certificate.go new file mode 100644 index 0000000..139e92a --- /dev/null +++ b/pkg/client/clientset/versioned/typed/anthoscertmanager/v1/fake/fake_certificate.go @@ -0,0 +1,141 @@ +/* +Copyright 2022. + +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 client-gen. DO NOT EDIT. + +package fake + +import ( + "context" + + anthoscertmanagerv1 "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/apis/anthoscertmanager/v1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + schema "k8s.io/apimachinery/pkg/runtime/schema" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + testing "k8s.io/client-go/testing" +) + +// FakeCertificates implements CertificateInterface +type FakeCertificates struct { + Fake *FakeAnthosCertmanagerV1 + ns string +} + +var certificatesResource = schema.GroupVersionResource{Group: "anthos-cert-manager.io", Version: "v1", Resource: "certificates"} + +var certificatesKind = schema.GroupVersionKind{Group: "anthos-cert-manager.io", Version: "v1", Kind: "Certificate"} + +// Get takes name of the certificate, and returns the corresponding certificate object, and an error if there is any. +func (c *FakeCertificates) Get(ctx context.Context, name string, options v1.GetOptions) (result *anthoscertmanagerv1.Certificate, err error) { + obj, err := c.Fake. + Invokes(testing.NewGetAction(certificatesResource, c.ns, name), &anthoscertmanagerv1.Certificate{}) + + if obj == nil { + return nil, err + } + return obj.(*anthoscertmanagerv1.Certificate), err +} + +// List takes label and field selectors, and returns the list of Certificates that match those selectors. +func (c *FakeCertificates) List(ctx context.Context, opts v1.ListOptions) (result *anthoscertmanagerv1.CertificateList, err error) { + obj, err := c.Fake. + Invokes(testing.NewListAction(certificatesResource, certificatesKind, c.ns, opts), &anthoscertmanagerv1.CertificateList{}) + + if obj == nil { + return nil, err + } + + label, _, _ := testing.ExtractFromListOptions(opts) + if label == nil { + label = labels.Everything() + } + list := &anthoscertmanagerv1.CertificateList{ListMeta: obj.(*anthoscertmanagerv1.CertificateList).ListMeta} + for _, item := range obj.(*anthoscertmanagerv1.CertificateList).Items { + if label.Matches(labels.Set(item.Labels)) { + list.Items = append(list.Items, item) + } + } + return list, err +} + +// Watch returns a watch.Interface that watches the requested certificates. +func (c *FakeCertificates) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + return c.Fake. + InvokesWatch(testing.NewWatchAction(certificatesResource, c.ns, opts)) + +} + +// Create takes the representation of a certificate and creates it. Returns the server's representation of the certificate, and an error, if there is any. +func (c *FakeCertificates) Create(ctx context.Context, certificate *anthoscertmanagerv1.Certificate, opts v1.CreateOptions) (result *anthoscertmanagerv1.Certificate, err error) { + obj, err := c.Fake. + Invokes(testing.NewCreateAction(certificatesResource, c.ns, certificate), &anthoscertmanagerv1.Certificate{}) + + if obj == nil { + return nil, err + } + return obj.(*anthoscertmanagerv1.Certificate), err +} + +// Update takes the representation of a certificate and updates it. Returns the server's representation of the certificate, and an error, if there is any. +func (c *FakeCertificates) Update(ctx context.Context, certificate *anthoscertmanagerv1.Certificate, opts v1.UpdateOptions) (result *anthoscertmanagerv1.Certificate, err error) { + obj, err := c.Fake. + Invokes(testing.NewUpdateAction(certificatesResource, c.ns, certificate), &anthoscertmanagerv1.Certificate{}) + + if obj == nil { + return nil, err + } + return obj.(*anthoscertmanagerv1.Certificate), err +} + +// UpdateStatus was generated because the type contains a Status member. +// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). +func (c *FakeCertificates) UpdateStatus(ctx context.Context, certificate *anthoscertmanagerv1.Certificate, opts v1.UpdateOptions) (*anthoscertmanagerv1.Certificate, error) { + obj, err := c.Fake. + Invokes(testing.NewUpdateSubresourceAction(certificatesResource, "status", c.ns, certificate), &anthoscertmanagerv1.Certificate{}) + + if obj == nil { + return nil, err + } + return obj.(*anthoscertmanagerv1.Certificate), err +} + +// Delete takes name of the certificate and deletes it. Returns an error if one occurs. +func (c *FakeCertificates) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + _, err := c.Fake. + Invokes(testing.NewDeleteActionWithOptions(certificatesResource, c.ns, name, opts), &anthoscertmanagerv1.Certificate{}) + + return err +} + +// DeleteCollection deletes a collection of objects. +func (c *FakeCertificates) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + action := testing.NewDeleteCollectionAction(certificatesResource, c.ns, listOpts) + + _, err := c.Fake.Invokes(action, &anthoscertmanagerv1.CertificateList{}) + return err +} + +// Patch applies the patch and returns the patched certificate. +func (c *FakeCertificates) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *anthoscertmanagerv1.Certificate, err error) { + obj, err := c.Fake. + Invokes(testing.NewPatchSubresourceAction(certificatesResource, c.ns, name, pt, data, subresources...), &anthoscertmanagerv1.Certificate{}) + + if obj == nil { + return nil, err + } + return obj.(*anthoscertmanagerv1.Certificate), err +} diff --git a/pkg/client/clientset/versioned/typed/anthoscertmanager/v1/fake/fake_certificaterequest.go b/pkg/client/clientset/versioned/typed/anthoscertmanager/v1/fake/fake_certificaterequest.go new file mode 100644 index 0000000..e4d9205 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/anthoscertmanager/v1/fake/fake_certificaterequest.go @@ -0,0 +1,141 @@ +/* +Copyright 2022. + +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 client-gen. DO NOT EDIT. + +package fake + +import ( + "context" + + anthoscertmanagerv1 "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/apis/anthoscertmanager/v1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + schema "k8s.io/apimachinery/pkg/runtime/schema" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + testing "k8s.io/client-go/testing" +) + +// FakeCertificateRequests implements CertificateRequestInterface +type FakeCertificateRequests struct { + Fake *FakeAnthosCertmanagerV1 + ns string +} + +var certificaterequestsResource = schema.GroupVersionResource{Group: "anthos-cert-manager.io", Version: "v1", Resource: "certificaterequests"} + +var certificaterequestsKind = schema.GroupVersionKind{Group: "anthos-cert-manager.io", Version: "v1", Kind: "CertificateRequest"} + +// Get takes name of the certificateRequest, and returns the corresponding certificateRequest object, and an error if there is any. +func (c *FakeCertificateRequests) Get(ctx context.Context, name string, options v1.GetOptions) (result *anthoscertmanagerv1.CertificateRequest, err error) { + obj, err := c.Fake. + Invokes(testing.NewGetAction(certificaterequestsResource, c.ns, name), &anthoscertmanagerv1.CertificateRequest{}) + + if obj == nil { + return nil, err + } + return obj.(*anthoscertmanagerv1.CertificateRequest), err +} + +// List takes label and field selectors, and returns the list of CertificateRequests that match those selectors. +func (c *FakeCertificateRequests) List(ctx context.Context, opts v1.ListOptions) (result *anthoscertmanagerv1.CertificateRequestList, err error) { + obj, err := c.Fake. + Invokes(testing.NewListAction(certificaterequestsResource, certificaterequestsKind, c.ns, opts), &anthoscertmanagerv1.CertificateRequestList{}) + + if obj == nil { + return nil, err + } + + label, _, _ := testing.ExtractFromListOptions(opts) + if label == nil { + label = labels.Everything() + } + list := &anthoscertmanagerv1.CertificateRequestList{ListMeta: obj.(*anthoscertmanagerv1.CertificateRequestList).ListMeta} + for _, item := range obj.(*anthoscertmanagerv1.CertificateRequestList).Items { + if label.Matches(labels.Set(item.Labels)) { + list.Items = append(list.Items, item) + } + } + return list, err +} + +// Watch returns a watch.Interface that watches the requested certificateRequests. +func (c *FakeCertificateRequests) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + return c.Fake. + InvokesWatch(testing.NewWatchAction(certificaterequestsResource, c.ns, opts)) + +} + +// Create takes the representation of a certificateRequest and creates it. Returns the server's representation of the certificateRequest, and an error, if there is any. +func (c *FakeCertificateRequests) Create(ctx context.Context, certificateRequest *anthoscertmanagerv1.CertificateRequest, opts v1.CreateOptions) (result *anthoscertmanagerv1.CertificateRequest, err error) { + obj, err := c.Fake. + Invokes(testing.NewCreateAction(certificaterequestsResource, c.ns, certificateRequest), &anthoscertmanagerv1.CertificateRequest{}) + + if obj == nil { + return nil, err + } + return obj.(*anthoscertmanagerv1.CertificateRequest), err +} + +// Update takes the representation of a certificateRequest and updates it. Returns the server's representation of the certificateRequest, and an error, if there is any. +func (c *FakeCertificateRequests) Update(ctx context.Context, certificateRequest *anthoscertmanagerv1.CertificateRequest, opts v1.UpdateOptions) (result *anthoscertmanagerv1.CertificateRequest, err error) { + obj, err := c.Fake. + Invokes(testing.NewUpdateAction(certificaterequestsResource, c.ns, certificateRequest), &anthoscertmanagerv1.CertificateRequest{}) + + if obj == nil { + return nil, err + } + return obj.(*anthoscertmanagerv1.CertificateRequest), err +} + +// UpdateStatus was generated because the type contains a Status member. +// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). +func (c *FakeCertificateRequests) UpdateStatus(ctx context.Context, certificateRequest *anthoscertmanagerv1.CertificateRequest, opts v1.UpdateOptions) (*anthoscertmanagerv1.CertificateRequest, error) { + obj, err := c.Fake. + Invokes(testing.NewUpdateSubresourceAction(certificaterequestsResource, "status", c.ns, certificateRequest), &anthoscertmanagerv1.CertificateRequest{}) + + if obj == nil { + return nil, err + } + return obj.(*anthoscertmanagerv1.CertificateRequest), err +} + +// Delete takes name of the certificateRequest and deletes it. Returns an error if one occurs. +func (c *FakeCertificateRequests) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + _, err := c.Fake. + Invokes(testing.NewDeleteActionWithOptions(certificaterequestsResource, c.ns, name, opts), &anthoscertmanagerv1.CertificateRequest{}) + + return err +} + +// DeleteCollection deletes a collection of objects. +func (c *FakeCertificateRequests) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + action := testing.NewDeleteCollectionAction(certificaterequestsResource, c.ns, listOpts) + + _, err := c.Fake.Invokes(action, &anthoscertmanagerv1.CertificateRequestList{}) + return err +} + +// Patch applies the patch and returns the patched certificateRequest. +func (c *FakeCertificateRequests) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *anthoscertmanagerv1.CertificateRequest, err error) { + obj, err := c.Fake. + Invokes(testing.NewPatchSubresourceAction(certificaterequestsResource, c.ns, name, pt, data, subresources...), &anthoscertmanagerv1.CertificateRequest{}) + + if obj == nil { + return nil, err + } + return obj.(*anthoscertmanagerv1.CertificateRequest), err +} diff --git a/pkg/client/clientset/versioned/typed/anthoscertmanager/v1/generated_expansion.go b/pkg/client/clientset/versioned/typed/anthoscertmanager/v1/generated_expansion.go index 5498f37..5b1cf5c 100644 --- a/pkg/client/clientset/versioned/typed/anthoscertmanager/v1/generated_expansion.go +++ b/pkg/client/clientset/versioned/typed/anthoscertmanager/v1/generated_expansion.go @@ -17,4 +17,8 @@ package v1 +type CertificateExpansion interface{} + +type CertificateRequestExpansion interface{} + type IssuerExpansion interface{} diff --git a/pkg/client/informers/externalversions/anthoscertmanager/v1/certificate.go b/pkg/client/informers/externalversions/anthoscertmanager/v1/certificate.go new file mode 100644 index 0000000..d698bd1 --- /dev/null +++ b/pkg/client/informers/externalversions/anthoscertmanager/v1/certificate.go @@ -0,0 +1,89 @@ +/* +Copyright 2022. + +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 informer-gen. DO NOT EDIT. + +package v1 + +import ( + "context" + time "time" + + anthoscertmanagerv1 "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/apis/anthoscertmanager/v1" + versioned "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/client/clientset/versioned" + internalinterfaces "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/client/informers/externalversions/internalinterfaces" + v1 "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/client/listers/anthoscertmanager/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + cache "k8s.io/client-go/tools/cache" +) + +// CertificateInformer provides access to a shared informer and lister for +// Certificates. +type CertificateInformer interface { + Informer() cache.SharedIndexInformer + Lister() v1.CertificateLister +} + +type certificateInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewCertificateInformer constructs a new informer for Certificate type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewCertificateInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredCertificateInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredCertificateInformer constructs a new informer for Certificate type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredCertificateInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AnthosCertmanagerV1().Certificates(namespace).List(context.TODO(), options) + }, + WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AnthosCertmanagerV1().Certificates(namespace).Watch(context.TODO(), options) + }, + }, + &anthoscertmanagerv1.Certificate{}, + resyncPeriod, + indexers, + ) +} + +func (f *certificateInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredCertificateInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *certificateInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&anthoscertmanagerv1.Certificate{}, f.defaultInformer) +} + +func (f *certificateInformer) Lister() v1.CertificateLister { + return v1.NewCertificateLister(f.Informer().GetIndexer()) +} diff --git a/pkg/client/informers/externalversions/anthoscertmanager/v1/certificaterequest.go b/pkg/client/informers/externalversions/anthoscertmanager/v1/certificaterequest.go new file mode 100644 index 0000000..d6f4358 --- /dev/null +++ b/pkg/client/informers/externalversions/anthoscertmanager/v1/certificaterequest.go @@ -0,0 +1,89 @@ +/* +Copyright 2022. + +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 informer-gen. DO NOT EDIT. + +package v1 + +import ( + "context" + time "time" + + anthoscertmanagerv1 "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/apis/anthoscertmanager/v1" + versioned "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/client/clientset/versioned" + internalinterfaces "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/client/informers/externalversions/internalinterfaces" + v1 "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/client/listers/anthoscertmanager/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + cache "k8s.io/client-go/tools/cache" +) + +// CertificateRequestInformer provides access to a shared informer and lister for +// CertificateRequests. +type CertificateRequestInformer interface { + Informer() cache.SharedIndexInformer + Lister() v1.CertificateRequestLister +} + +type certificateRequestInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewCertificateRequestInformer constructs a new informer for CertificateRequest type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewCertificateRequestInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredCertificateRequestInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredCertificateRequestInformer constructs a new informer for CertificateRequest type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredCertificateRequestInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AnthosCertmanagerV1().CertificateRequests(namespace).List(context.TODO(), options) + }, + WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AnthosCertmanagerV1().CertificateRequests(namespace).Watch(context.TODO(), options) + }, + }, + &anthoscertmanagerv1.CertificateRequest{}, + resyncPeriod, + indexers, + ) +} + +func (f *certificateRequestInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredCertificateRequestInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *certificateRequestInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&anthoscertmanagerv1.CertificateRequest{}, f.defaultInformer) +} + +func (f *certificateRequestInformer) Lister() v1.CertificateRequestLister { + return v1.NewCertificateRequestLister(f.Informer().GetIndexer()) +} diff --git a/pkg/client/informers/externalversions/anthoscertmanager/v1/interface.go b/pkg/client/informers/externalversions/anthoscertmanager/v1/interface.go index 180eb13..95d5b86 100644 --- a/pkg/client/informers/externalversions/anthoscertmanager/v1/interface.go +++ b/pkg/client/informers/externalversions/anthoscertmanager/v1/interface.go @@ -23,6 +23,10 @@ // Interface provides access to all the informers in this group version. type Interface interface { + // Certificates returns a CertificateInformer. + Certificates() CertificateInformer + // CertificateRequests returns a CertificateRequestInformer. + CertificateRequests() CertificateRequestInformer // Issuers returns a IssuerInformer. Issuers() IssuerInformer } @@ -38,6 +42,16 @@ return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } +// Certificates returns a CertificateInformer. +func (v *version) Certificates() CertificateInformer { + return &certificateInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} + +// CertificateRequests returns a CertificateRequestInformer. +func (v *version) CertificateRequests() CertificateRequestInformer { + return &certificateRequestInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} + // Issuers returns a IssuerInformer. func (v *version) Issuers() IssuerInformer { return &issuerInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} diff --git a/pkg/client/informers/externalversions/generic.go b/pkg/client/informers/externalversions/generic.go index 8e475ba..ebe467b 100644 --- a/pkg/client/informers/externalversions/generic.go +++ b/pkg/client/informers/externalversions/generic.go @@ -52,6 +52,10 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) { switch resource { // Group=anthos-cert-manager.io, Version=v1 + case v1.SchemeGroupVersion.WithResource("certificates"): + return &genericInformer{resource: resource.GroupResource(), informer: f.AnthosCertmanager().V1().Certificates().Informer()}, nil + case v1.SchemeGroupVersion.WithResource("certificaterequests"): + return &genericInformer{resource: resource.GroupResource(), informer: f.AnthosCertmanager().V1().CertificateRequests().Informer()}, nil case v1.SchemeGroupVersion.WithResource("issuers"): return &genericInformer{resource: resource.GroupResource(), informer: f.AnthosCertmanager().V1().Issuers().Informer()}, nil diff --git a/pkg/client/listers/anthoscertmanager/v1/certificate.go b/pkg/client/listers/anthoscertmanager/v1/certificate.go new file mode 100644 index 0000000..62cb573 --- /dev/null +++ b/pkg/client/listers/anthoscertmanager/v1/certificate.go @@ -0,0 +1,98 @@ +/* +Copyright 2022. + +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 lister-gen. DO NOT EDIT. + +package v1 + +import ( + v1 "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/apis/anthoscertmanager/v1" + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" +) + +// CertificateLister helps list Certificates. +// All objects returned here must be treated as read-only. +type CertificateLister interface { + // List lists all Certificates in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1.Certificate, err error) + // Certificates returns an object that can list and get Certificates. + Certificates(namespace string) CertificateNamespaceLister + CertificateListerExpansion +} + +// certificateLister implements the CertificateLister interface. +type certificateLister struct { + indexer cache.Indexer +} + +// NewCertificateLister returns a new CertificateLister. +func NewCertificateLister(indexer cache.Indexer) CertificateLister { + return &certificateLister{indexer: indexer} +} + +// List lists all Certificates in the indexer. +func (s *certificateLister) List(selector labels.Selector) (ret []*v1.Certificate, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1.Certificate)) + }) + return ret, err +} + +// Certificates returns an object that can list and get Certificates. +func (s *certificateLister) Certificates(namespace string) CertificateNamespaceLister { + return certificateNamespaceLister{indexer: s.indexer, namespace: namespace} +} + +// CertificateNamespaceLister helps list and get Certificates. +// All objects returned here must be treated as read-only. +type CertificateNamespaceLister interface { + // List lists all Certificates in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1.Certificate, err error) + // Get retrieves the Certificate from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*v1.Certificate, error) + CertificateNamespaceListerExpansion +} + +// certificateNamespaceLister implements the CertificateNamespaceLister +// interface. +type certificateNamespaceLister struct { + indexer cache.Indexer + namespace string +} + +// List lists all Certificates in the indexer for a given namespace. +func (s certificateNamespaceLister) List(selector labels.Selector) (ret []*v1.Certificate, err error) { + err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.Certificate)) + }) + return ret, err +} + +// Get retrieves the Certificate from the indexer for a given namespace and name. +func (s certificateNamespaceLister) Get(name string) (*v1.Certificate, error) { + obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(v1.Resource("certificate"), name) + } + return obj.(*v1.Certificate), nil +} diff --git a/pkg/client/listers/anthoscertmanager/v1/certificaterequest.go b/pkg/client/listers/anthoscertmanager/v1/certificaterequest.go new file mode 100644 index 0000000..b6e540c --- /dev/null +++ b/pkg/client/listers/anthoscertmanager/v1/certificaterequest.go @@ -0,0 +1,98 @@ +/* +Copyright 2022. + +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 lister-gen. DO NOT EDIT. + +package v1 + +import ( + v1 "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/apis/anthoscertmanager/v1" + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" +) + +// CertificateRequestLister helps list CertificateRequests. +// All objects returned here must be treated as read-only. +type CertificateRequestLister interface { + // List lists all CertificateRequests in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1.CertificateRequest, err error) + // CertificateRequests returns an object that can list and get CertificateRequests. + CertificateRequests(namespace string) CertificateRequestNamespaceLister + CertificateRequestListerExpansion +} + +// certificateRequestLister implements the CertificateRequestLister interface. +type certificateRequestLister struct { + indexer cache.Indexer +} + +// NewCertificateRequestLister returns a new CertificateRequestLister. +func NewCertificateRequestLister(indexer cache.Indexer) CertificateRequestLister { + return &certificateRequestLister{indexer: indexer} +} + +// List lists all CertificateRequests in the indexer. +func (s *certificateRequestLister) List(selector labels.Selector) (ret []*v1.CertificateRequest, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1.CertificateRequest)) + }) + return ret, err +} + +// CertificateRequests returns an object that can list and get CertificateRequests. +func (s *certificateRequestLister) CertificateRequests(namespace string) CertificateRequestNamespaceLister { + return certificateRequestNamespaceLister{indexer: s.indexer, namespace: namespace} +} + +// CertificateRequestNamespaceLister helps list and get CertificateRequests. +// All objects returned here must be treated as read-only. +type CertificateRequestNamespaceLister interface { + // List lists all CertificateRequests in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1.CertificateRequest, err error) + // Get retrieves the CertificateRequest from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*v1.CertificateRequest, error) + CertificateRequestNamespaceListerExpansion +} + +// certificateRequestNamespaceLister implements the CertificateRequestNamespaceLister +// interface. +type certificateRequestNamespaceLister struct { + indexer cache.Indexer + namespace string +} + +// List lists all CertificateRequests in the indexer for a given namespace. +func (s certificateRequestNamespaceLister) List(selector labels.Selector) (ret []*v1.CertificateRequest, err error) { + err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.CertificateRequest)) + }) + return ret, err +} + +// Get retrieves the CertificateRequest from the indexer for a given namespace and name. +func (s certificateRequestNamespaceLister) Get(name string) (*v1.CertificateRequest, error) { + obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(v1.Resource("certificaterequest"), name) + } + return obj.(*v1.CertificateRequest), nil +} diff --git a/pkg/client/listers/anthoscertmanager/v1/expansion_generated.go b/pkg/client/listers/anthoscertmanager/v1/expansion_generated.go index a573a21..4ed83ef 100644 --- a/pkg/client/listers/anthoscertmanager/v1/expansion_generated.go +++ b/pkg/client/listers/anthoscertmanager/v1/expansion_generated.go @@ -17,6 +17,22 @@ package v1 +// CertificateListerExpansion allows custom methods to be added to +// CertificateLister. +type CertificateListerExpansion interface{} + +// CertificateNamespaceListerExpansion allows custom methods to be added to +// CertificateNamespaceLister. +type CertificateNamespaceListerExpansion interface{} + +// CertificateRequestListerExpansion allows custom methods to be added to +// CertificateRequestLister. +type CertificateRequestListerExpansion interface{} + +// CertificateRequestNamespaceListerExpansion allows custom methods to be added to +// CertificateRequestNamespaceLister. +type CertificateRequestNamespaceListerExpansion interface{} + // IssuerListerExpansion allows custom methods to be added to // IssuerLister. type IssuerListerExpansion interface{} diff --git a/pkg/controller/certificates/informers.go b/pkg/controller/certificates/informers.go new file mode 100644 index 0000000..deed188 --- /dev/null +++ b/pkg/controller/certificates/informers.go @@ -0,0 +1,52 @@ +package certificates + +import ( + acmlisters "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/client/listers/anthoscertmanager/v1" + controllerpkg "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/controller" + logf "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/logs" + "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/util/predicate" + "github.com/go-logr/logr" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/util/workqueue" +) + +// EnqueueCertificatesForResourceUsingPredicates will return a function +// that can be used as an OnAdd handler for a SharedIndexInformer. +// It should be used as a handler for resources that are referenced +// in some way by Certificates. +// The namespace of the object being processed will be used in the List +// call when enqueuing Certificate resources. +// If no predicate constructors are given, all Certificate resources will be +// enqueued on every invocation. +func EnqueueCertificatesForResourceUsingPredicates(log logr.Logger, queue workqueue.Interface, lister acmlisters.CertificateLister, selector labels.Selector, predicateBuilders ...predicate.ExtractorFunc) func(obj interface{}) { + return func(obj interface{}) { + s, ok := obj.(metav1.Object) + if !ok { + log.V(logf.ErrorLevel).Info("Non-Object type resource passed to EnqueueCertificatesForSecretUsingPredicates") + return + } + + // 'Construct' the predicate functions using the given Secret + predicates := make(predicate.Funcs, len(predicateBuilders)) + for i, b := range predicateBuilders { + predicates[i] = b(s.(runtime.Object)) + } + + certs, err := ListCertificatesMatchingPredicates(lister.Certificates(s.GetNamespace()), selector, predicates...) + if err != nil { + log.Error(err, "Failed listing Certificate resources") + return + } + + for _, cert := range certs { + key, err := controllerpkg.KeyFunc(cert) + if err != nil { + log.Error(err, "Error determining 'key' for resource") + continue + } + queue.Add(key) + } + } +} diff --git a/pkg/controller/certificates/issuing/issuing_controller.go b/pkg/controller/certificates/issuing/issuing_controller.go index 90d31b5..1ab56dc 100644 --- a/pkg/controller/certificates/issuing/issuing_controller.go +++ b/pkg/controller/certificates/issuing/issuing_controller.go @@ -2,11 +2,16 @@ import ( "context" + "time" acmapi "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/apis/anthoscertmanager/v1" + acmInformers "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/client/informers/externalversions" controllerpkg "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/controller" + "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/controller/certificates" "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/controller/certificates/issuing/internal" + "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/util/predicate" "github.com/go-logr/logr" + "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes" corelisters "k8s.io/client-go/listers/core/v1" @@ -38,15 +43,28 @@ log logr.Logger, kubeClient kubernetes.Interface, factory informers.SharedInformerFactory, + acmFactory acmInformers.SharedInformerFactory, clock clock.Clock, certificateControllerOptions controllerpkg.CertificateOptions, fieldManager string, ) (*controller, workqueue.RateLimitingInterface, []cache.InformerSynced) { - // // create a queue used to queue up items to be processed - // queue := workqueue.NewNamedRateLimitingQueue(workqueue.NewItemExponentialFailureRateLimiter(time.Second, time.Second*30), ControllerName) + // create a queue used to queue up items to be processed + queue := workqueue.NewNamedRateLimitingQueue(workqueue.NewItemExponentialFailureRateLimiter(time.Second, time.Second*30), ControllerName) - // // obtain references to all the informers used by this controller - // certificateInforomer := acmFa + // obtain references to all the informers used by this controller + certificateInformer := acmFactory.AnthosCertmanager().V1().Certificates() + certificateRequestInformer := acmFactory.AnthosCertmanager().V1().CertificateRequests() + secretsInformer := factory.Core().V1().Secrets() + + certificateInformer.Informer().AddEventHandler(&controllerpkg.QueuingEventHandler{Queue: queue}) + certificateRequestInformer.Informer().AddEventHandler(&controllerpkg.BlockingEventHandler{ + WorkFunc: certificates.EnqueueCertificatesForResourceUsingPredicates(log, queue, certificateInformer.Lister(), labels.Everything(), predicate.ResourceOwnerOf), + }) + secretsInformer.Informer().AddEventHandler(&controllerpkg.BlockingEventHandler{ + // Issuer reconciles on changes to the Secret named `spec.nextPrivateKeySecretName` + WorkFunc: certificates.EnqueueCertificatesForResourceUsingPredicates(log, queue, certificateInformer.Lister(), labels.Everything(), predicate.ResourceOwnerOf, predicate.ExtractResourceName(predicate.CertificateNextPrivateKeySecretName)), + }) + return nil, nil, nil } diff --git a/pkg/controller/certificates/lister.go b/pkg/controller/certificates/lister.go new file mode 100644 index 0000000..8ccf522 --- /dev/null +++ b/pkg/controller/certificates/lister.go @@ -0,0 +1,70 @@ +package certificates + +import ( + "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/util/predicate" + "k8s.io/apimachinery/pkg/labels" + + corev1 "k8s.io/api/core/v1" + + corelisters "k8s.io/client-go/listers/core/v1" + + acmapi "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/apis/anthoscertmanager/v1" + acmlisters "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/client/listers/anthoscertmanager/v1" +) + +// ListCertificateRequestsMatchingPredicates will list CertificateRequest +// resources using the provided lister, optionally applying the given predicate +// functions to filter the CertificateRequest resources returned. +func ListCertificateRequestsMatchingPredicates(lister acmlisters.CertificateRequestNamespaceLister, selector labels.Selector, predicates ...predicate.Func) ([]*acmapi.CertificateRequest, error) { + reqs, err := lister.List(selector) + if err != nil { + return nil, err + } + funcs := predicate.Funcs(predicates) + out := make([]*acmapi.CertificateRequest, 0) + for _, req := range reqs { + if funcs.Evaluate(req) { + out = append(out, req) + } + } + + return out, nil +} + +// ListCertificatesMatchingPredicates will list Certificate resources using +// the provided lister, optionally applying the given predicate functions to +// filter the Certificate resources returned. +func ListCertificatesMatchingPredicates(lister acmlisters.CertificateNamespaceLister, selector labels.Selector, predicates ...predicate.Func) ([]*acmapi.Certificate, error) { + reqs, err := lister.List(selector) + if err != nil { + return nil, err + } + funcs := predicate.Funcs(predicates) + out := make([]*acmapi.Certificate, 0) + for _, req := range reqs { + if funcs.Evaluate(req) { + out = append(out, req) + } + } + + return out, nil +} + +// ListSecretsMatchingPredicates will list Secret resources using +// the provided lister, optionally applying the given predicate functions to +// filter the Secret resources returned. +func ListSecretsMatchingPredicates(lister corelisters.SecretNamespaceLister, selector labels.Selector, predicates ...predicate.Func) ([]*corev1.Secret, error) { + reqs, err := lister.List(selector) + if err != nil { + return nil, err + } + funcs := predicate.Funcs(predicates) + out := make([]*corev1.Secret, 0) + for _, req := range reqs { + if funcs.Evaluate(req) { + out = append(out, req) + } + } + + return out, nil +} diff --git a/pkg/controller/certificates/suite_test.go b/pkg/controller/certificates/suite_test.go index d0a7a4f..2fac97f 100644 --- a/pkg/controller/certificates/suite_test.go +++ b/pkg/controller/certificates/suite_test.go @@ -14,7 +14,7 @@ limitations under the License. */ -package controllers +package certificates import ( "path/filepath" diff --git a/pkg/controller/util.go b/pkg/controller/util.go new file mode 100644 index 0000000..51166be --- /dev/null +++ b/pkg/controller/util.go @@ -0,0 +1,118 @@ +package controller + +import ( + "reflect" + "strings" + + "k8s.io/apimachinery/pkg/util/runtime" + "k8s.io/client-go/tools/cache" + "k8s.io/client-go/util/workqueue" +) + +var ( + // KeyFunc creates a key for an API object. The key can be passed to a + // worker function that processes an object from a queue such as + // ProcessItem. + KeyFunc = cache.DeletionHandlingMetaNamespaceKeyFunc +) + +// QueuingEventHandler is an implementation of cache.ResourceEventHandler that +// simply queues objects that are added/updated/deleted. +type QueuingEventHandler struct { + Queue workqueue.RateLimitingInterface +} + +// Enqueue adds a key for an object to the workqueue. +func (q *QueuingEventHandler) Enqueue(obj interface{}) { + key, err := KeyFunc(obj) + if err != nil { + runtime.HandleError(err) + return + } + q.Queue.Add(key) +} + +// OnAdd adds a newly created object to the workqueue. +func (q *QueuingEventHandler) OnAdd(obj interface{}) { + q.Enqueue(obj) +} + +// OnUpdate adds an updated object to the workqueue. +func (q *QueuingEventHandler) OnUpdate(old, new interface{}) { + if reflect.DeepEqual(old, new) { + return + } + q.Enqueue(new) +} + +// OnDelete adds a deleted object to the workqueue for processing. +func (q *QueuingEventHandler) OnDelete(obj interface{}) { + tombstone, ok := obj.(cache.DeletedFinalStateUnknown) + if ok { + obj = tombstone.Obj + } + q.Enqueue(obj) +} + +// BlockingEventHandler is an implementation of cache.ResourceEventHandler that +// simply synchronously calls it's WorkFunc upon calls to OnAdd, OnUpdate or +// OnDelete. +type BlockingEventHandler struct { + WorkFunc func(obj interface{}) +} + +// Enqueue synchronously adds a key for an object to the workqueue. +func (b *BlockingEventHandler) Enqueue(obj interface{}) { + b.WorkFunc(obj) +} + +// OnAdd synchronously adds a newly created object to the workqueue. +func (b *BlockingEventHandler) OnAdd(obj interface{}) { + b.WorkFunc(obj) +} + +// OnUpdate synchronously adds an updated object to the workqueue. +func (b *BlockingEventHandler) OnUpdate(old, new interface{}) { + if reflect.DeepEqual(old, new) { + return + } + b.WorkFunc(new) +} + +// OnDelete synchronously adds a deleted object to the workqueue. +func (b *BlockingEventHandler) OnDelete(obj interface{}) { + tombstone, ok := obj.(cache.DeletedFinalStateUnknown) + if ok { + obj = tombstone.Obj + } + b.WorkFunc(obj) +} + +// BuildAnnotationsCopy takes a map of annotations and a list of prefix +// filters and builds a filtered map of annotations. It is used to filter +// annotations to be copied from Certificate to CertificateRequest and from +// CertificateSigningRequest to Order. +func BuildAnnotationsToCopy(allAnnotations map[string]string, prefixes []string) map[string]string { + filteredAnnotations := make(map[string]string) + includeAll := false + for _, v := range prefixes { + if v == "*" { + includeAll = true + } + } + for _, annotation := range prefixes { + prefix := strings.TrimPrefix(annotation, "-") + for k, v := range allAnnotations { + if strings.HasPrefix(annotation, "-") { + if strings.HasPrefix(k, prefix) { + // If this is an annotation to not be copied. + delete(filteredAnnotations, k) + } + } else if includeAll || strings.HasPrefix(k, annotation) { + // If this is an annotation to be copied or if 'all' should be copied. + filteredAnnotations[k] = v + } + } + } + return filteredAnnotations +} diff --git a/pkg/util/predicate/certificate.go b/pkg/util/predicate/certificate.go new file mode 100644 index 0000000..5973175 --- /dev/null +++ b/pkg/util/predicate/certificate.go @@ -0,0 +1,30 @@ +package predicate + +import ( + "k8s.io/apimachinery/pkg/runtime" + + acmapi "gitbucket.jerxie.com/yangyangxie/AnthosCertManager/pkg/apis/anthoscertmanager/v1" +) + +// CertificateSecretName returns a predicate that used to filter Certificates +// to only those with the given 'spec.secretName'. +func CertificateSecretName(name string) Func { + return func(obj runtime.Object) bool { + crt := obj.(*acmapi.Certificate) + return crt.Spec.SecretName == name + } +} + +// CertificateSecretName returns a predicate that used to filter Certificates +// to only those with the given 'status.nextPrivateKeySecretName'. +// It is not possible to select Certificates with a 'nil' secret name using +// this predicate function. +func CertificateNextPrivateKeySecretName(name string) Func { + return func(obj runtime.Object) bool { + crt := obj.(*acmapi.Certificate) + if crt.Status.NextPrivateKeySecretName == nil { + return false + } + return *crt.Status.NextPrivateKeySecretName == name + } +} diff --git a/pkg/util/predicate/generic.go b/pkg/util/predicate/generic.go new file mode 100644 index 0000000..3f63429 --- /dev/null +++ b/pkg/util/predicate/generic.go @@ -0,0 +1,22 @@ +package predicate + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +// ResourceOwnedBy will filter returned results to only those with the +// given resource as an owner. +func ResourceOwnedBy(owner runtime.Object) Func { + return func(obj runtime.Object) bool { + return metav1.IsControlledBy(obj.(metav1.Object), owner.(metav1.Object)) + } +} + +// ResourceOwnerOf will filter returned results to only those that own the given +// resource. +func ResourceOwnerOf(obj runtime.Object) Func { + return func(ownerObj runtime.Object) bool { + return metav1.IsControlledBy(obj.(metav1.Object), ownerObj.(metav1.Object)) + } +} diff --git a/pkg/util/predicate/predicate.go b/pkg/util/predicate/predicate.go new file mode 100644 index 0000000..85bbd5f --- /dev/null +++ b/pkg/util/predicate/predicate.go @@ -0,0 +1,42 @@ +package predicate + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +// Func is a generic function used to filter various types of resources. +type Func func(obj runtime.Object) bool + +// Funcs is a list of predicates to be AND'd together. +type Funcs []Func + +// Evaluate will evaluate all the predicate functions in order, AND'ing +// together the results. +func (f Funcs) Evaluate(obj runtime.Object) bool { + for _, fn := range f { + if !fn(obj) { + return false + } + } + return true +} + +// An ExtractorFunc applies a transformation to a runtime.Object and creates a +// predicate function based on the result of the transformation. +// This can be used to apply complex lookup logic to determine which resources +// should be enqueued if another resource being watched changes, for example, +// enqueuing all Certificate resources that own a CertificateRequest that has +// been observed, or enqueuing all Certificate resources that specify +// `status.nextPrivateKeySecretName` as the name of the Secret being processed. +type ExtractorFunc func(obj runtime.Object) Func + +// ExtractResourceName is a helper function used to extract a name from a +// metav1.Object being enqueued to construct a Func that is variadic +// based on a string value. +func ExtractResourceName(p func(s string) Func) ExtractorFunc { + return func(obj runtime.Object) Func { + metaObj := obj.(metav1.Object) + return p(metaObj.GetName()) + } +}