diff --git a/apis/v1alpha1/ack-generate-metadata.yaml b/apis/v1alpha1/ack-generate-metadata.yaml index 41f6fd2d..19c9b36a 100755 --- a/apis/v1alpha1/ack-generate-metadata.yaml +++ b/apis/v1alpha1/ack-generate-metadata.yaml @@ -1,13 +1,13 @@ ack_generate_info: - build_date: "2021-11-08T15:45:27Z" + build_date: "2021-11-15T20:14:43Z" build_hash: 6ce1a672eabd3908bdaa4ace356e1b58ee3e80ba go_version: go1.16.4 version: v0.15.2 -api_directory_checksum: f6e7f2f06bc2cb9ab97c9e3839c73a2c995af16d +api_directory_checksum: 4428fa4b4df55d74a03fdf9a07175103b343fb05 api_version: v1alpha1 aws_sdk_go_version: v1.40.28 generator_config_info: - file_checksum: bc2d40d81838763eb9a73e7107eb3dd2ff089ee6 + file_checksum: b38e2f54cb069b91ac92cc95ff8945903ce1e1f2 original_file_name: generator.yaml last_modification: reason: API generation diff --git a/apis/v1alpha1/alias.go b/apis/v1alpha1/alias.go new file mode 100644 index 00000000..1abe0926 --- /dev/null +++ b/apis/v1alpha1/alias.go @@ -0,0 +1,92 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may +// not use this file except in compliance with the License. A copy of the +// License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file 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 ack-generate. DO NOT EDIT. + +package v1alpha1 + +import ( + ackv1alpha1 "github.com/aws-controllers-k8s/runtime/apis/core/v1alpha1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// AliasSpec defines the desired state of Alias. +// + +type AliasSpec struct { + // A description of the alias. + Description *string `json:"description,omitempty"` + // The name of the Lambda function. + // + // Name formats + // + // * Function name - MyFunction. + // + // * Function ARN - arn:aws:lambda:us-west-2:123456789012:function:MyFunction. + // + // * Partial ARN - 123456789012:function:MyFunction. + // + // The length constraint applies only to the full ARN. If you specify only the + // function name, it is limited to 64 characters in length. + // +kubebuilder:validation:Required + FunctionName *string `json:"functionName"` + // The function version that the alias invokes. + // +kubebuilder:validation:Required + FunctionVersion *string `json:"functionVersion"` + // The name of the alias. + // +kubebuilder:validation:Required + Name *string `json:"name"` + // The routing configuration (https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html#configuring-alias-routing) + // of the alias. + RoutingConfig *AliasRoutingConfiguration `json:"routingConfig,omitempty"` +} + +// AliasStatus defines the observed state of Alias +type AliasStatus struct { + // All CRs managed by ACK have a common `Status.ACKResourceMetadata` member + // that is used to contain resource sync state, account ownership, + // constructed ARN for the resource + // +kubebuilder:validation:Optional + ACKResourceMetadata *ackv1alpha1.ResourceMetadata `json:"ackResourceMetadata"` + // All CRS managed by ACK have a common `Status.Conditions` member that + // contains a collection of `ackv1alpha1.Condition` objects that describe + // the various terminal states of the CR and its backend AWS service API + // resource + // +kubebuilder:validation:Optional + Conditions []*ackv1alpha1.Condition `json:"conditions"` + // A unique identifier that changes when you update the alias. + // +kubebuilder:validation:Optional + RevisionID *string `json:"revisionID,omitempty"` +} + +// Alias is the Schema for the Aliases API +// +kubebuilder:object:root=true +// +kubebuilder:subresource:status +type Alias struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec AliasSpec `json:"spec,omitempty"` + Status AliasStatus `json:"status,omitempty"` +} + +// AliasList contains a list of Alias +// +kubebuilder:object:root=true +type AliasList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []Alias `json:"items"` +} + +func init() { + SchemeBuilder.Register(&Alias{}, &AliasList{}) +} diff --git a/apis/v1alpha1/generator.yaml b/apis/v1alpha1/generator.yaml index cde7480c..a2275665 100644 --- a/apis/v1alpha1/generator.yaml +++ b/apis/v1alpha1/generator.yaml @@ -1,7 +1,7 @@ ignore: resource_names: # Function - - Alias + # Alias - CodeSigningConfig - EventSourceMapping shape_names: @@ -22,4 +22,13 @@ resources: FunctionName: Name GetFunction: input_fields: - FunctionName: Name \ No newline at end of file + FunctionName: Name + Alias: + fields: + Name: + is_required: true + is_primary_key: true + FunctionName: + is_required: true + FunctionVersion: + is_required: true \ No newline at end of file diff --git a/apis/v1alpha1/types.go b/apis/v1alpha1/types.go index 10ae011a..b0b818ff 100644 --- a/apis/v1alpha1/types.go +++ b/apis/v1alpha1/types.go @@ -42,6 +42,24 @@ type AccountUsage struct { TotalCodeSize *int64 `json:"totalCodeSize,omitempty"` } +// Provides configuration information about a Lambda function alias (https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html). +type AliasConfiguration struct { + AliasARN *string `json:"aliasARN,omitempty"` + Description *string `json:"description,omitempty"` + FunctionVersion *string `json:"functionVersion,omitempty"` + Name *string `json:"name,omitempty"` + RevisionID *string `json:"revisionID,omitempty"` + // The traffic-shifting (https://docs.aws.amazon.com/lambda/latest/dg/lambda-traffic-shifting-using-aliases.html) + // configuration of a Lambda function alias. + RoutingConfig *AliasRoutingConfiguration `json:"routingConfig,omitempty"` +} + +// The traffic-shifting (https://docs.aws.amazon.com/lambda/latest/dg/lambda-traffic-shifting-using-aliases.html) +// configuration of a Lambda function alias. +type AliasRoutingConfiguration struct { + AdditionalVersionWeights map[string]*float64 `json:"additionalVersionWeights,omitempty"` +} + // Details about a Code signing configuration (https://docs.aws.amazon.com/lambda/latest/dg/configuration-codesigning.html). type CodeSigningConfig struct { CodeSigningConfigARN *string `json:"codeSigningConfigARN,omitempty"` diff --git a/apis/v1alpha1/zz_generated.deepcopy.go b/apis/v1alpha1/zz_generated.deepcopy.go index 7c9abfc2..c29d3af7 100644 --- a/apis/v1alpha1/zz_generated.deepcopy.go +++ b/apis/v1alpha1/zz_generated.deepcopy.go @@ -79,6 +79,216 @@ func (in *AccountUsage) DeepCopy() *AccountUsage { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Alias) DeepCopyInto(out *Alias) { + *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 Alias. +func (in *Alias) DeepCopy() *Alias { + if in == nil { + return nil + } + out := new(Alias) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Alias) 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 *AliasConfiguration) DeepCopyInto(out *AliasConfiguration) { + *out = *in + if in.AliasARN != nil { + in, out := &in.AliasARN, &out.AliasARN + *out = new(string) + **out = **in + } + if in.Description != nil { + in, out := &in.Description, &out.Description + *out = new(string) + **out = **in + } + if in.FunctionVersion != nil { + in, out := &in.FunctionVersion, &out.FunctionVersion + *out = new(string) + **out = **in + } + if in.Name != nil { + in, out := &in.Name, &out.Name + *out = new(string) + **out = **in + } + if in.RevisionID != nil { + in, out := &in.RevisionID, &out.RevisionID + *out = new(string) + **out = **in + } + if in.RoutingConfig != nil { + in, out := &in.RoutingConfig, &out.RoutingConfig + *out = new(AliasRoutingConfiguration) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AliasConfiguration. +func (in *AliasConfiguration) DeepCopy() *AliasConfiguration { + if in == nil { + return nil + } + out := new(AliasConfiguration) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *AliasList) DeepCopyInto(out *AliasList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Alias, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AliasList. +func (in *AliasList) DeepCopy() *AliasList { + if in == nil { + return nil + } + out := new(AliasList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *AliasList) 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 *AliasRoutingConfiguration) DeepCopyInto(out *AliasRoutingConfiguration) { + *out = *in + if in.AdditionalVersionWeights != nil { + in, out := &in.AdditionalVersionWeights, &out.AdditionalVersionWeights + *out = make(map[string]*float64, len(*in)) + for key, val := range *in { + var outVal *float64 + if val == nil { + (*out)[key] = nil + } else { + in, out := &val, &outVal + *out = new(float64) + **out = **in + } + (*out)[key] = outVal + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AliasRoutingConfiguration. +func (in *AliasRoutingConfiguration) DeepCopy() *AliasRoutingConfiguration { + if in == nil { + return nil + } + out := new(AliasRoutingConfiguration) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *AliasSpec) DeepCopyInto(out *AliasSpec) { + *out = *in + if in.Description != nil { + in, out := &in.Description, &out.Description + *out = new(string) + **out = **in + } + if in.FunctionName != nil { + in, out := &in.FunctionName, &out.FunctionName + *out = new(string) + **out = **in + } + if in.FunctionVersion != nil { + in, out := &in.FunctionVersion, &out.FunctionVersion + *out = new(string) + **out = **in + } + if in.Name != nil { + in, out := &in.Name, &out.Name + *out = new(string) + **out = **in + } + if in.RoutingConfig != nil { + in, out := &in.RoutingConfig, &out.RoutingConfig + *out = new(AliasRoutingConfiguration) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AliasSpec. +func (in *AliasSpec) DeepCopy() *AliasSpec { + if in == nil { + return nil + } + out := new(AliasSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *AliasStatus) DeepCopyInto(out *AliasStatus) { + *out = *in + if in.ACKResourceMetadata != nil { + in, out := &in.ACKResourceMetadata, &out.ACKResourceMetadata + *out = new(corev1alpha1.ResourceMetadata) + (*in).DeepCopyInto(*out) + } + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]*corev1alpha1.Condition, len(*in)) + for i := range *in { + if (*in)[i] != nil { + in, out := &(*in)[i], &(*out)[i] + *out = new(corev1alpha1.Condition) + (*in).DeepCopyInto(*out) + } + } + } + if in.RevisionID != nil { + in, out := &in.RevisionID, &out.RevisionID + *out = new(string) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AliasStatus. +func (in *AliasStatus) DeepCopy() *AliasStatus { + if in == nil { + return nil + } + out := new(AliasStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CodeSigningConfig) DeepCopyInto(out *CodeSigningConfig) { *out = *in diff --git a/cmd/controller/main.go b/cmd/controller/main.go index 590d0296..d157f77d 100644 --- a/cmd/controller/main.go +++ b/cmd/controller/main.go @@ -33,6 +33,7 @@ import ( svcresource "github.com/aws-controllers-k8s/lambda-controller/pkg/resource" ackv1alpha1 "github.com/aws-controllers-k8s/runtime/apis/core/v1alpha1" + _ "github.com/aws-controllers-k8s/lambda-controller/pkg/resource/alias" _ "github.com/aws-controllers-k8s/lambda-controller/pkg/resource/function" ) diff --git a/config/crd/bases/lambda.services.k8s.aws_aliases.yaml b/config/crd/bases/lambda.services.k8s.aws_aliases.yaml new file mode 100644 index 00000000..173e05ba --- /dev/null +++ b/config/crd/bases/lambda.services.k8s.aws_aliases.yaml @@ -0,0 +1,142 @@ + +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.7.0 + creationTimestamp: null + name: aliases.lambda.services.k8s.aws +spec: + group: lambda.services.k8s.aws + names: + kind: Alias + listKind: AliasList + plural: aliases + singular: alias + scope: Namespaced + versions: + - name: v1alpha1 + schema: + openAPIV3Schema: + description: Alias is the Schema for the Aliases API + properties: + apiVersion: + description: 'APIVersion defines the versioned schema of this representation + of an object. Servers should convert recognized schemas to the latest + internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' + type: string + kind: + description: 'Kind is a string value representing the REST resource this + object represents. Servers may infer this from the endpoint the client + submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' + type: string + metadata: + type: object + spec: + properties: + description: + description: A description of the alias. + type: string + functionName: + description: "The name of the Lambda function. \n Name formats \n + \ * Function name - MyFunction. \n * Function ARN - arn:aws:lambda:us-west-2:123456789012:function:MyFunction. + \n * Partial ARN - 123456789012:function:MyFunction. \n The length + constraint applies only to the full ARN. If you specify only the + function name, it is limited to 64 characters in length." + type: string + functionVersion: + description: The function version that the alias invokes. + type: string + name: + description: The name of the alias. + type: string + routingConfig: + description: The routing configuration (https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html#configuring-alias-routing) + of the alias. + properties: + additionalVersionWeights: + additionalProperties: + type: number + type: object + type: object + required: + - functionName + - functionVersion + - name + type: object + status: + description: AliasStatus defines the observed state of Alias + properties: + ackResourceMetadata: + description: All CRs managed by ACK have a common `Status.ACKResourceMetadata` + member that is used to contain resource sync state, account ownership, + constructed ARN for the resource + properties: + arn: + description: 'ARN is the Amazon Resource Name for the resource. + This is a globally-unique identifier and is set only by the + ACK service controller once the controller has orchestrated + the creation of the resource OR when it has verified that an + "adopted" resource (a resource where the ARN annotation was + set by the Kubernetes user on the CR) exists and matches the + supplied CR''s Spec field values. TODO(vijat@): Find a better + strategy for resources that do not have ARN in CreateOutputResponse + https://github.com/aws/aws-controllers-k8s/issues/270' + type: string + ownerAccountID: + description: OwnerAccountID is the AWS Account ID of the account + that owns the backend AWS service API resource. + type: string + required: + - ownerAccountID + type: object + conditions: + description: All CRS managed by ACK have a common `Status.Conditions` + member that contains a collection of `ackv1alpha1.Condition` objects + that describe the various terminal states of the CR and its backend + AWS service API resource + items: + description: Condition is the common struct used by all CRDs managed + by ACK service controllers to indicate terminal states of the + CR and its backend AWS service API resource + properties: + lastTransitionTime: + description: Last time the condition transitioned from one status + to another. + format: date-time + type: string + message: + description: A human readable message indicating details about + the transition. + type: string + reason: + description: The reason for the condition's last transition. + type: string + status: + description: Status of the condition, one of True, False, Unknown. + type: string + type: + description: Type is the type of the Condition + type: string + required: + - status + - type + type: object + type: array + revisionID: + description: A unique identifier that changes when you update the + alias. + type: string + type: object + type: object + served: true + storage: true + subresources: + status: {} +status: + acceptedNames: + kind: "" + plural: "" + conditions: [] + storedVersions: [] diff --git a/config/crd/kustomization.yaml b/config/crd/kustomization.yaml index 0227aaa0..f4193726 100644 --- a/config/crd/kustomization.yaml +++ b/config/crd/kustomization.yaml @@ -3,4 +3,5 @@ kind: Kustomization bases: - common resources: + - bases/lambda.services.k8s.aws_aliases.yaml - bases/lambda.services.k8s.aws_functions.yaml diff --git a/config/rbac/cluster-role-controller.yaml b/config/rbac/cluster-role-controller.yaml index 327249f4..c05750ed 100644 --- a/config/rbac/cluster-role-controller.yaml +++ b/config/rbac/cluster-role-controller.yaml @@ -22,6 +22,26 @@ rules: - get - list - watch +- apiGroups: + - lambda.services.k8s.aws + resources: + - aliases + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - lambda.services.k8s.aws + resources: + - aliases/status + verbs: + - get + - patch + - update - apiGroups: - lambda.services.k8s.aws resources: diff --git a/config/rbac/role-reader.yaml b/config/rbac/role-reader.yaml index dedbe0e5..75a7de1d 100644 --- a/config/rbac/role-reader.yaml +++ b/config/rbac/role-reader.yaml @@ -9,6 +9,7 @@ rules: - apiGroups: - lambda.services.k8s.aws resources: + - aliases - functions verbs: - get diff --git a/config/rbac/role-writer.yaml b/config/rbac/role-writer.yaml index 662d693b..18b4ce6a 100644 --- a/config/rbac/role-writer.yaml +++ b/config/rbac/role-writer.yaml @@ -9,6 +9,7 @@ rules: - apiGroups: - lambda.services.k8s.aws resources: + - aliases - functions verbs: - create @@ -21,6 +22,7 @@ rules: - apiGroups: - lambda.services.k8s.aws resources: + - aliases - functions verbs: - get diff --git a/generator.yaml b/generator.yaml index cde7480c..a2275665 100644 --- a/generator.yaml +++ b/generator.yaml @@ -1,7 +1,7 @@ ignore: resource_names: # Function - - Alias + # Alias - CodeSigningConfig - EventSourceMapping shape_names: @@ -22,4 +22,13 @@ resources: FunctionName: Name GetFunction: input_fields: - FunctionName: Name \ No newline at end of file + FunctionName: Name + Alias: + fields: + Name: + is_required: true + is_primary_key: true + FunctionName: + is_required: true + FunctionVersion: + is_required: true \ No newline at end of file diff --git a/helm/crds/lambda.services.k8s.aws_aliases.yaml b/helm/crds/lambda.services.k8s.aws_aliases.yaml new file mode 100644 index 00000000..173e05ba --- /dev/null +++ b/helm/crds/lambda.services.k8s.aws_aliases.yaml @@ -0,0 +1,142 @@ + +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.7.0 + creationTimestamp: null + name: aliases.lambda.services.k8s.aws +spec: + group: lambda.services.k8s.aws + names: + kind: Alias + listKind: AliasList + plural: aliases + singular: alias + scope: Namespaced + versions: + - name: v1alpha1 + schema: + openAPIV3Schema: + description: Alias is the Schema for the Aliases API + properties: + apiVersion: + description: 'APIVersion defines the versioned schema of this representation + of an object. Servers should convert recognized schemas to the latest + internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' + type: string + kind: + description: 'Kind is a string value representing the REST resource this + object represents. Servers may infer this from the endpoint the client + submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' + type: string + metadata: + type: object + spec: + properties: + description: + description: A description of the alias. + type: string + functionName: + description: "The name of the Lambda function. \n Name formats \n + \ * Function name - MyFunction. \n * Function ARN - arn:aws:lambda:us-west-2:123456789012:function:MyFunction. + \n * Partial ARN - 123456789012:function:MyFunction. \n The length + constraint applies only to the full ARN. If you specify only the + function name, it is limited to 64 characters in length." + type: string + functionVersion: + description: The function version that the alias invokes. + type: string + name: + description: The name of the alias. + type: string + routingConfig: + description: The routing configuration (https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html#configuring-alias-routing) + of the alias. + properties: + additionalVersionWeights: + additionalProperties: + type: number + type: object + type: object + required: + - functionName + - functionVersion + - name + type: object + status: + description: AliasStatus defines the observed state of Alias + properties: + ackResourceMetadata: + description: All CRs managed by ACK have a common `Status.ACKResourceMetadata` + member that is used to contain resource sync state, account ownership, + constructed ARN for the resource + properties: + arn: + description: 'ARN is the Amazon Resource Name for the resource. + This is a globally-unique identifier and is set only by the + ACK service controller once the controller has orchestrated + the creation of the resource OR when it has verified that an + "adopted" resource (a resource where the ARN annotation was + set by the Kubernetes user on the CR) exists and matches the + supplied CR''s Spec field values. TODO(vijat@): Find a better + strategy for resources that do not have ARN in CreateOutputResponse + https://github.com/aws/aws-controllers-k8s/issues/270' + type: string + ownerAccountID: + description: OwnerAccountID is the AWS Account ID of the account + that owns the backend AWS service API resource. + type: string + required: + - ownerAccountID + type: object + conditions: + description: All CRS managed by ACK have a common `Status.Conditions` + member that contains a collection of `ackv1alpha1.Condition` objects + that describe the various terminal states of the CR and its backend + AWS service API resource + items: + description: Condition is the common struct used by all CRDs managed + by ACK service controllers to indicate terminal states of the + CR and its backend AWS service API resource + properties: + lastTransitionTime: + description: Last time the condition transitioned from one status + to another. + format: date-time + type: string + message: + description: A human readable message indicating details about + the transition. + type: string + reason: + description: The reason for the condition's last transition. + type: string + status: + description: Status of the condition, one of True, False, Unknown. + type: string + type: + description: Type is the type of the Condition + type: string + required: + - status + - type + type: object + type: array + revisionID: + description: A unique identifier that changes when you update the + alias. + type: string + type: object + type: object + served: true + storage: true + subresources: + status: {} +status: + acceptedNames: + kind: "" + plural: "" + conditions: [] + storedVersions: [] diff --git a/helm/templates/cluster-role-controller.yaml b/helm/templates/cluster-role-controller.yaml index 7a971d0d..b7bd450b 100644 --- a/helm/templates/cluster-role-controller.yaml +++ b/helm/templates/cluster-role-controller.yaml @@ -28,6 +28,26 @@ rules: - get - list - watch +- apiGroups: + - lambda.services.k8s.aws + resources: + - aliases + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - lambda.services.k8s.aws + resources: + - aliases/status + verbs: + - get + - patch + - update - apiGroups: - lambda.services.k8s.aws resources: diff --git a/helm/templates/role-reader.yaml b/helm/templates/role-reader.yaml index eab7a84f..77204540 100644 --- a/helm/templates/role-reader.yaml +++ b/helm/templates/role-reader.yaml @@ -9,6 +9,7 @@ rules: - apiGroups: - lambda.services.k8s.aws resources: + - aliases - functions verbs: - get diff --git a/helm/templates/role-writer.yaml b/helm/templates/role-writer.yaml index 63faa708..d8da7c77 100644 --- a/helm/templates/role-writer.yaml +++ b/helm/templates/role-writer.yaml @@ -9,6 +9,8 @@ rules: - apiGroups: - lambda.services.k8s.aws resources: + - aliases + - functions verbs: @@ -22,6 +24,7 @@ rules: - apiGroups: - lambda.services.k8s.aws resources: + - aliases - functions verbs: - get diff --git a/pkg/resource/alias/delta.go b/pkg/resource/alias/delta.go new file mode 100644 index 00000000..140f022c --- /dev/null +++ b/pkg/resource/alias/delta.go @@ -0,0 +1,85 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may +// not use this file except in compliance with the License. A copy of the +// License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file 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 ack-generate. DO NOT EDIT. + +package alias + +import ( + "bytes" + "reflect" + + ackcompare "github.com/aws-controllers-k8s/runtime/pkg/compare" +) + +// Hack to avoid import errors during build... +var ( + _ = &bytes.Buffer{} + _ = &reflect.Method{} +) + +// newResourceDelta returns a new `ackcompare.Delta` used to compare two +// resources +func newResourceDelta( + a *resource, + b *resource, +) *ackcompare.Delta { + delta := ackcompare.NewDelta() + if (a == nil && b != nil) || + (a != nil && b == nil) { + delta.Add("", a, b) + return delta + } + + if ackcompare.HasNilDifference(a.ko.Spec.Description, b.ko.Spec.Description) { + delta.Add("Spec.Description", a.ko.Spec.Description, b.ko.Spec.Description) + } else if a.ko.Spec.Description != nil && b.ko.Spec.Description != nil { + if *a.ko.Spec.Description != *b.ko.Spec.Description { + delta.Add("Spec.Description", a.ko.Spec.Description, b.ko.Spec.Description) + } + } + if ackcompare.HasNilDifference(a.ko.Spec.FunctionName, b.ko.Spec.FunctionName) { + delta.Add("Spec.FunctionName", a.ko.Spec.FunctionName, b.ko.Spec.FunctionName) + } else if a.ko.Spec.FunctionName != nil && b.ko.Spec.FunctionName != nil { + if *a.ko.Spec.FunctionName != *b.ko.Spec.FunctionName { + delta.Add("Spec.FunctionName", a.ko.Spec.FunctionName, b.ko.Spec.FunctionName) + } + } + if ackcompare.HasNilDifference(a.ko.Spec.FunctionVersion, b.ko.Spec.FunctionVersion) { + delta.Add("Spec.FunctionVersion", a.ko.Spec.FunctionVersion, b.ko.Spec.FunctionVersion) + } else if a.ko.Spec.FunctionVersion != nil && b.ko.Spec.FunctionVersion != nil { + if *a.ko.Spec.FunctionVersion != *b.ko.Spec.FunctionVersion { + delta.Add("Spec.FunctionVersion", a.ko.Spec.FunctionVersion, b.ko.Spec.FunctionVersion) + } + } + if ackcompare.HasNilDifference(a.ko.Spec.Name, b.ko.Spec.Name) { + delta.Add("Spec.Name", a.ko.Spec.Name, b.ko.Spec.Name) + } else if a.ko.Spec.Name != nil && b.ko.Spec.Name != nil { + if *a.ko.Spec.Name != *b.ko.Spec.Name { + delta.Add("Spec.Name", a.ko.Spec.Name, b.ko.Spec.Name) + } + } + if ackcompare.HasNilDifference(a.ko.Spec.RoutingConfig, b.ko.Spec.RoutingConfig) { + delta.Add("Spec.RoutingConfig", a.ko.Spec.RoutingConfig, b.ko.Spec.RoutingConfig) + } else if a.ko.Spec.RoutingConfig != nil && b.ko.Spec.RoutingConfig != nil { + if ackcompare.HasNilDifference(a.ko.Spec.RoutingConfig.AdditionalVersionWeights, b.ko.Spec.RoutingConfig.AdditionalVersionWeights) { + delta.Add("Spec.RoutingConfig.AdditionalVersionWeights", a.ko.Spec.RoutingConfig.AdditionalVersionWeights, b.ko.Spec.RoutingConfig.AdditionalVersionWeights) + } else if a.ko.Spec.RoutingConfig.AdditionalVersionWeights != nil && b.ko.Spec.RoutingConfig.AdditionalVersionWeights != nil { + if !reflect.DeepEqual(a.ko.Spec.RoutingConfig.AdditionalVersionWeights, b.ko.Spec.RoutingConfig.AdditionalVersionWeights) { + delta.Add("Spec.RoutingConfig.AdditionalVersionWeights", a.ko.Spec.RoutingConfig.AdditionalVersionWeights, b.ko.Spec.RoutingConfig.AdditionalVersionWeights) + } + } + } + + return delta +} diff --git a/pkg/resource/alias/descriptor.go b/pkg/resource/alias/descriptor.go new file mode 100644 index 00000000..2a468b4f --- /dev/null +++ b/pkg/resource/alias/descriptor.go @@ -0,0 +1,154 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may +// not use this file except in compliance with the License. A copy of the +// License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file 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 ack-generate. DO NOT EDIT. + +package alias + +import ( + ackv1alpha1 "github.com/aws-controllers-k8s/runtime/apis/core/v1alpha1" + ackcompare "github.com/aws-controllers-k8s/runtime/pkg/compare" + acktypes "github.com/aws-controllers-k8s/runtime/pkg/types" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + k8sapirt "k8s.io/apimachinery/pkg/runtime" + k8sctrlutil "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + + svcapitypes "github.com/aws-controllers-k8s/lambda-controller/apis/v1alpha1" +) + +const ( + finalizerString = "finalizers.lambda.services.k8s.aws/Alias" +) + +var ( + GroupVersionResource = svcapitypes.GroupVersion.WithResource("aliases") + GroupKind = metav1.GroupKind{ + Group: "lambda.services.k8s.aws", + Kind: "Alias", + } +) + +// resourceDescriptor implements the +// `aws-service-operator-k8s/pkg/types.AWSResourceDescriptor` interface +type resourceDescriptor struct { +} + +// GroupKind returns a Kubernetes metav1.GroupKind struct that describes the +// API Group and Kind of CRs described by the descriptor +func (d *resourceDescriptor) GroupKind() *metav1.GroupKind { + return &GroupKind +} + +// EmptyRuntimeObject returns an empty object prototype that may be used in +// apimachinery and k8s client operations +func (d *resourceDescriptor) EmptyRuntimeObject() k8sapirt.Object { + return &svcapitypes.Alias{} +} + +// ResourceFromRuntimeObject returns an AWSResource that has been initialized +// with the supplied runtime.Object +func (d *resourceDescriptor) ResourceFromRuntimeObject( + obj k8sapirt.Object, +) acktypes.AWSResource { + return &resource{ + ko: obj.(*svcapitypes.Alias), + } +} + +// Delta returns an `ackcompare.Delta` object containing the difference between +// one `AWSResource` and another. +func (d *resourceDescriptor) Delta(a, b acktypes.AWSResource) *ackcompare.Delta { + return newResourceDelta(a.(*resource), b.(*resource)) +} + +// IsManaged returns true if the supplied AWSResource is under the management +// of an ACK service controller. What this means in practice is that the +// underlying custom resource (CR) in the AWSResource has had a +// resource-specific finalizer associated with it. +func (d *resourceDescriptor) IsManaged( + res acktypes.AWSResource, +) bool { + obj := res.RuntimeMetaObject() + if obj == nil { + // Should not happen. If it does, there is a bug in the code + panic("nil RuntimeMetaObject in AWSResource") + } + // Remove use of custom code once + // https://github.com/kubernetes-sigs/controller-runtime/issues/994 is + // fixed. This should be able to be: + // + // return k8sctrlutil.ContainsFinalizer(obj, finalizerString) + return containsFinalizer(obj, finalizerString) +} + +// Remove once https://github.com/kubernetes-sigs/controller-runtime/issues/994 +// is fixed. +func containsFinalizer(obj acktypes.RuntimeMetaObject, finalizer string) bool { + f := obj.GetFinalizers() + for _, e := range f { + if e == finalizer { + return true + } + } + return false +} + +// MarkManaged places the supplied resource under the management of ACK. What +// this typically means is that the resource manager will decorate the +// underlying custom resource (CR) with a finalizer that indicates ACK is +// managing the resource and the underlying CR may not be deleted until ACK is +// finished cleaning up any backend AWS service resources associated with the +// CR. +func (d *resourceDescriptor) MarkManaged( + res acktypes.AWSResource, +) { + obj := res.RuntimeMetaObject() + if obj == nil { + // Should not happen. If it does, there is a bug in the code + panic("nil RuntimeMetaObject in AWSResource") + } + k8sctrlutil.AddFinalizer(obj, finalizerString) +} + +// MarkUnmanaged removes the supplied resource from management by ACK. What +// this typically means is that the resource manager will remove a finalizer +// underlying custom resource (CR) that indicates ACK is managing the resource. +// This will allow the Kubernetes API server to delete the underlying CR. +func (d *resourceDescriptor) MarkUnmanaged( + res acktypes.AWSResource, +) { + obj := res.RuntimeMetaObject() + if obj == nil { + // Should not happen. If it does, there is a bug in the code + panic("nil RuntimeMetaObject in AWSResource") + } + k8sctrlutil.RemoveFinalizer(obj, finalizerString) +} + +// MarkAdopted places descriptors on the custom resource that indicate the +// resource was not created from within ACK. +func (d *resourceDescriptor) MarkAdopted( + res acktypes.AWSResource, +) { + obj := res.RuntimeMetaObject() + if obj == nil { + // Should not happen. If it does, there is a bug in the code + panic("nil RuntimeMetaObject in AWSResource") + } + curr := obj.GetAnnotations() + if curr == nil { + curr = make(map[string]string) + } + curr[ackv1alpha1.AnnotationAdopted] = "true" + obj.SetAnnotations(curr) +} diff --git a/pkg/resource/alias/identifiers.go b/pkg/resource/alias/identifiers.go new file mode 100644 index 00000000..b406eb03 --- /dev/null +++ b/pkg/resource/alias/identifiers.go @@ -0,0 +1,46 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may +// not use this file except in compliance with the License. A copy of the +// License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file 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 ack-generate. DO NOT EDIT. + +package alias + +import ( + ackv1alpha1 "github.com/aws-controllers-k8s/runtime/apis/core/v1alpha1" +) + +// resourceIdentifiers implements the +// `aws-service-operator-k8s/pkg/types.AWSResourceIdentifiers` interface +type resourceIdentifiers struct { + meta *ackv1alpha1.ResourceMetadata +} + +// ARN returns the AWS Resource Name for the backend AWS resource. If nil, +// this means the resource has not yet been created in the backend AWS +// service. +func (ri *resourceIdentifiers) ARN() *ackv1alpha1.AWSResourceName { + if ri.meta != nil { + return ri.meta.ARN + } + return nil +} + +// OwnerAccountID returns the AWS account identifier in which the +// backend AWS resource resides, or nil if this information is not known +// for the resource +func (ri *resourceIdentifiers) OwnerAccountID() *ackv1alpha1.AWSAccountID { + if ri.meta != nil { + return ri.meta.OwnerAccountID + } + return nil +} diff --git a/pkg/resource/alias/manager.go b/pkg/resource/alias/manager.go new file mode 100644 index 00000000..eb33b632 --- /dev/null +++ b/pkg/resource/alias/manager.go @@ -0,0 +1,304 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may +// not use this file except in compliance with the License. A copy of the +// License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file 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 ack-generate. DO NOT EDIT. + +package alias + +import ( + "context" + "fmt" + "time" + + ackv1alpha1 "github.com/aws-controllers-k8s/runtime/apis/core/v1alpha1" + ackcompare "github.com/aws-controllers-k8s/runtime/pkg/compare" + ackcondition "github.com/aws-controllers-k8s/runtime/pkg/condition" + ackcfg "github.com/aws-controllers-k8s/runtime/pkg/config" + ackerr "github.com/aws-controllers-k8s/runtime/pkg/errors" + ackmetrics "github.com/aws-controllers-k8s/runtime/pkg/metrics" + ackrequeue "github.com/aws-controllers-k8s/runtime/pkg/requeue" + ackrtlog "github.com/aws-controllers-k8s/runtime/pkg/runtime/log" + acktypes "github.com/aws-controllers-k8s/runtime/pkg/types" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/go-logr/logr" + corev1 "k8s.io/api/core/v1" + + svcsdk "github.com/aws/aws-sdk-go/service/lambda" + svcsdkapi "github.com/aws/aws-sdk-go/service/lambda/lambdaiface" +) + +// +kubebuilder:rbac:groups=lambda.services.k8s.aws,resources=aliases,verbs=get;list;watch;create;update;patch;delete +// +kubebuilder:rbac:groups=lambda.services.k8s.aws,resources=aliases/status,verbs=get;update;patch + +var lateInitializeFieldNames = []string{} + +// resourceManager is responsible for providing a consistent way to perform +// CRUD operations in a backend AWS service API for Book custom resources. +type resourceManager struct { + // cfg is a copy of the ackcfg.Config object passed on start of the service + // controller + cfg ackcfg.Config + // log refers to the logr.Logger object handling logging for the service + // controller + log logr.Logger + // metrics contains a collection of Prometheus metric objects that the + // service controller and its reconcilers track + metrics *ackmetrics.Metrics + // rr is the Reconciler which can be used for various utility + // functions such as querying for Secret values given a SecretReference + rr acktypes.Reconciler + // awsAccountID is the AWS account identifier that contains the resources + // managed by this resource manager + awsAccountID ackv1alpha1.AWSAccountID + // The AWS Region that this resource manager targets + awsRegion ackv1alpha1.AWSRegion + // sess is the AWS SDK Session object used to communicate with the backend + // AWS service API + sess *session.Session + // sdk is a pointer to the AWS service API interface exposed by the + // aws-sdk-go/services/{alias}/{alias}iface package. + sdkapi svcsdkapi.LambdaAPI +} + +// concreteResource returns a pointer to a resource from the supplied +// generic AWSResource interface +func (rm *resourceManager) concreteResource( + res acktypes.AWSResource, +) *resource { + // cast the generic interface into a pointer type specific to the concrete + // implementing resource type managed by this resource manager + return res.(*resource) +} + +// ReadOne returns the currently-observed state of the supplied AWSResource in +// the backend AWS service API. +func (rm *resourceManager) ReadOne( + ctx context.Context, + res acktypes.AWSResource, +) (acktypes.AWSResource, error) { + r := rm.concreteResource(res) + if r.ko == nil { + // Should never happen... if it does, it's buggy code. + panic("resource manager's ReadOne() method received resource with nil CR object") + } + observed, err := rm.sdkFind(ctx, r) + if err != nil { + if observed != nil { + return rm.onError(observed, err) + } + return rm.onError(r, err) + } + return rm.onSuccess(observed) +} + +// Create attempts to create the supplied AWSResource in the backend AWS +// service API, returning an AWSResource representing the newly-created +// resource +func (rm *resourceManager) Create( + ctx context.Context, + res acktypes.AWSResource, +) (acktypes.AWSResource, error) { + r := rm.concreteResource(res) + if r.ko == nil { + // Should never happen... if it does, it's buggy code. + panic("resource manager's Create() method received resource with nil CR object") + } + created, err := rm.sdkCreate(ctx, r) + if err != nil { + return rm.onError(r, err) + } + return rm.onSuccess(created) +} + +// Update attempts to mutate the supplied desired AWSResource in the backend AWS +// service API, returning an AWSResource representing the newly-mutated +// resource. +// Note for specialized logic implementers can check to see how the latest +// observed resource differs from the supplied desired state. The +// higher-level reonciler determines whether or not the desired differs +// from the latest observed and decides whether to call the resource +// manager's Update method +func (rm *resourceManager) Update( + ctx context.Context, + resDesired acktypes.AWSResource, + resLatest acktypes.AWSResource, + delta *ackcompare.Delta, +) (acktypes.AWSResource, error) { + desired := rm.concreteResource(resDesired) + latest := rm.concreteResource(resLatest) + if desired.ko == nil || latest.ko == nil { + // Should never happen... if it does, it's buggy code. + panic("resource manager's Update() method received resource with nil CR object") + } + updated, err := rm.sdkUpdate(ctx, desired, latest, delta) + if err != nil { + return rm.onError(latest, err) + } + return rm.onSuccess(updated) +} + +// Delete attempts to destroy the supplied AWSResource in the backend AWS +// service API, returning an AWSResource representing the +// resource being deleted (if delete is asynchronous and takes time) +func (rm *resourceManager) Delete( + ctx context.Context, + res acktypes.AWSResource, +) (acktypes.AWSResource, error) { + r := rm.concreteResource(res) + if r.ko == nil { + // Should never happen... if it does, it's buggy code. + panic("resource manager's Update() method received resource with nil CR object") + } + observed, err := rm.sdkDelete(ctx, r) + if err != nil { + if observed != nil { + return rm.onError(observed, err) + } + return rm.onError(r, err) + } + + return rm.onSuccess(observed) +} + +// ARNFromName returns an AWS Resource Name from a given string name. This +// is useful for constructing ARNs for APIs that require ARNs in their +// GetAttributes operations but all we have (for new CRs at least) is a +// name for the resource +func (rm *resourceManager) ARNFromName(name string) string { + return fmt.Sprintf( + "arn:aws:lambda:%s:%s:%s", + rm.awsRegion, + rm.awsAccountID, + name, + ) +} + +// LateInitialize returns an acktypes.AWSResource after setting the late initialized +// fields from the readOne call. This method will initialize the optional fields +// which were not provided by the k8s user but were defaulted by the AWS service. +// If there are no such fields to be initialized, the returned object is similar to +// object passed in the parameter. +func (rm *resourceManager) LateInitialize( + ctx context.Context, + latest acktypes.AWSResource, +) (acktypes.AWSResource, error) { + rlog := ackrtlog.FromContext(ctx) + // If there are no fields to late initialize, do nothing + if len(lateInitializeFieldNames) == 0 { + rlog.Debug("no late initialization required.") + return latest, nil + } + latestCopy := latest.DeepCopy() + lateInitConditionReason := "" + lateInitConditionMessage := "" + observed, err := rm.ReadOne(ctx, latestCopy) + if err != nil { + lateInitConditionMessage = "Unable to complete Read operation required for late initialization" + lateInitConditionReason = "Late Initialization Failure" + ackcondition.SetLateInitialized(latestCopy, corev1.ConditionFalse, &lateInitConditionMessage, &lateInitConditionReason) + return latestCopy, err + } + lateInitializedRes := rm.lateInitializeFromReadOneOutput(observed, latestCopy) + incompleteInitialization := rm.incompleteLateInitialization(lateInitializedRes) + if incompleteInitialization { + // Add the condition with LateInitialized=False + lateInitConditionMessage = "Late initialization did not complete, requeuing with delay of 5 seconds" + lateInitConditionReason = "Delayed Late Initialization" + ackcondition.SetLateInitialized(lateInitializedRes, corev1.ConditionFalse, &lateInitConditionMessage, &lateInitConditionReason) + return lateInitializedRes, ackrequeue.NeededAfter(nil, time.Duration(5)*time.Second) + } + // Set LateInitialized condition to True + lateInitConditionMessage = "Late initialization successful" + lateInitConditionReason = "Late initialization successful" + ackcondition.SetLateInitialized(lateInitializedRes, corev1.ConditionTrue, &lateInitConditionMessage, &lateInitConditionReason) + return lateInitializedRes, nil +} + +// incompleteLateInitialization return true if there are fields which were supposed to be +// late initialized but are not. If all the fields are late initialized, false is returned +func (rm *resourceManager) incompleteLateInitialization( + res acktypes.AWSResource, +) bool { + return false +} + +// lateInitializeFromReadOneOutput late initializes the 'latest' resource from the 'observed' +// resource and returns 'latest' resource +func (rm *resourceManager) lateInitializeFromReadOneOutput( + observed acktypes.AWSResource, + latest acktypes.AWSResource, +) acktypes.AWSResource { + return latest +} + +// newResourceManager returns a new struct implementing +// acktypes.AWSResourceManager +func newResourceManager( + cfg ackcfg.Config, + log logr.Logger, + metrics *ackmetrics.Metrics, + rr acktypes.Reconciler, + sess *session.Session, + id ackv1alpha1.AWSAccountID, + region ackv1alpha1.AWSRegion, +) (*resourceManager, error) { + return &resourceManager{ + cfg: cfg, + log: log, + metrics: metrics, + rr: rr, + awsAccountID: id, + awsRegion: region, + sess: sess, + sdkapi: svcsdk.New(sess), + }, nil +} + +// onError updates resource conditions and returns updated resource +// it returns nil if no condition is updated. +func (rm *resourceManager) onError( + r *resource, + err error, +) (acktypes.AWSResource, error) { + if r == nil { + return nil, err + } + r1, updated := rm.updateConditions(r, false, err) + if !updated { + return r, err + } + for _, condition := range r1.Conditions() { + if condition.Type == ackv1alpha1.ConditionTypeTerminal && + condition.Status == corev1.ConditionTrue { + // resource is in Terminal condition + // return Terminal error + return r1, ackerr.Terminal + } + } + return r1, err +} + +// onSuccess updates resource conditions and returns updated resource +// it returns the supplied resource if no condition is updated. +func (rm *resourceManager) onSuccess( + r *resource, +) (acktypes.AWSResource, error) { + if r == nil { + return nil, nil + } + r1, updated := rm.updateConditions(r, true, nil) + if !updated { + return r, nil + } + return r1, nil +} diff --git a/pkg/resource/alias/manager_factory.go b/pkg/resource/alias/manager_factory.go new file mode 100644 index 00000000..2e9c4144 --- /dev/null +++ b/pkg/resource/alias/manager_factory.go @@ -0,0 +1,96 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may +// not use this file except in compliance with the License. A copy of the +// License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file 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 ack-generate. DO NOT EDIT. + +package alias + +import ( + "fmt" + "sync" + + ackv1alpha1 "github.com/aws-controllers-k8s/runtime/apis/core/v1alpha1" + ackcfg "github.com/aws-controllers-k8s/runtime/pkg/config" + ackmetrics "github.com/aws-controllers-k8s/runtime/pkg/metrics" + acktypes "github.com/aws-controllers-k8s/runtime/pkg/types" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/go-logr/logr" + + svcresource "github.com/aws-controllers-k8s/lambda-controller/pkg/resource" +) + +// resourceManagerFactory produces resourceManager objects. It implements the +// `types.AWSResourceManagerFactory` interface. +type resourceManagerFactory struct { + sync.RWMutex + // rmCache contains resource managers for a particular AWS account ID + rmCache map[string]*resourceManager +} + +// ResourcePrototype returns an AWSResource that resource managers produced by +// this factory will handle +func (f *resourceManagerFactory) ResourceDescriptor() acktypes.AWSResourceDescriptor { + return &resourceDescriptor{} +} + +// ManagerFor returns a resource manager object that can manage resources for a +// supplied AWS account +func (f *resourceManagerFactory) ManagerFor( + cfg ackcfg.Config, + log logr.Logger, + metrics *ackmetrics.Metrics, + rr acktypes.Reconciler, + sess *session.Session, + id ackv1alpha1.AWSAccountID, + region ackv1alpha1.AWSRegion, +) (acktypes.AWSResourceManager, error) { + rmId := fmt.Sprintf("%s/%s", id, region) + f.RLock() + rm, found := f.rmCache[rmId] + f.RUnlock() + + if found { + return rm, nil + } + + f.Lock() + defer f.Unlock() + + rm, err := newResourceManager(cfg, log, metrics, rr, sess, id, region) + if err != nil { + return nil, err + } + f.rmCache[rmId] = rm + return rm, nil +} + +// IsAdoptable returns true if the resource is able to be adopted +func (f *resourceManagerFactory) IsAdoptable() bool { + return true +} + +// RequeueOnSuccessSeconds returns true if the resource should be requeued after specified seconds +// Default is false which means resource will not be requeued after success. +func (f *resourceManagerFactory) RequeueOnSuccessSeconds() int { + return 0 +} + +func newResourceManagerFactory() *resourceManagerFactory { + return &resourceManagerFactory{ + rmCache: map[string]*resourceManager{}, + } +} + +func init() { + svcresource.RegisterManagerFactory(newResourceManagerFactory()) +} diff --git a/pkg/resource/alias/resource.go b/pkg/resource/alias/resource.go new file mode 100644 index 00000000..31b44a83 --- /dev/null +++ b/pkg/resource/alias/resource.go @@ -0,0 +1,112 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may +// not use this file except in compliance with the License. A copy of the +// License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file 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 ack-generate. DO NOT EDIT. + +package alias + +import ( + ackv1alpha1 "github.com/aws-controllers-k8s/runtime/apis/core/v1alpha1" + ackerrors "github.com/aws-controllers-k8s/runtime/pkg/errors" + acktypes "github.com/aws-controllers-k8s/runtime/pkg/types" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + k8srt "k8s.io/apimachinery/pkg/runtime" + + svcapitypes "github.com/aws-controllers-k8s/lambda-controller/apis/v1alpha1" +) + +// Hack to avoid import errors during build... +var ( + _ = &ackerrors.MissingNameIdentifier +) + +// resource implements the `aws-controller-k8s/runtime/pkg/types.AWSResource` +// interface +type resource struct { + // The Kubernetes-native CR representing the resource + ko *svcapitypes.Alias +} + +// Identifiers returns an AWSResourceIdentifiers object containing various +// identifying information, including the AWS account ID that owns the +// resource, the resource's AWS Resource Name (ARN) +func (r *resource) Identifiers() acktypes.AWSResourceIdentifiers { + return &resourceIdentifiers{r.ko.Status.ACKResourceMetadata} +} + +// IsBeingDeleted returns true if the Kubernetes resource has a non-zero +// deletion timestemp +func (r *resource) IsBeingDeleted() bool { + return !r.ko.DeletionTimestamp.IsZero() +} + +// RuntimeObject returns the Kubernetes apimachinery/runtime representation of +// the AWSResource +func (r *resource) RuntimeObject() k8srt.Object { + return r.ko +} + +// MetaObject returns the Kubernetes apimachinery/apis/meta/v1.Object +// representation of the AWSResource +func (r *resource) MetaObject() metav1.Object { + return r.ko.GetObjectMeta() +} + +// RuntimeMetaObject returns an object that implements both the Kubernetes +// apimachinery/runtime.Object and the Kubernetes +// apimachinery/apis/meta/v1.Object interfaces +func (r *resource) RuntimeMetaObject() acktypes.RuntimeMetaObject { + return r.ko +} + +// Conditions returns the ACK Conditions collection for the AWSResource +func (r *resource) Conditions() []*ackv1alpha1.Condition { + return r.ko.Status.Conditions +} + +// ReplaceConditions sets the Conditions status field for the resource +func (r *resource) ReplaceConditions(conditions []*ackv1alpha1.Condition) { + r.ko.Status.Conditions = conditions +} + +// SetObjectMeta sets the ObjectMeta field for the resource +func (r *resource) SetObjectMeta(meta metav1.ObjectMeta) { + r.ko.ObjectMeta = meta +} + +// SetStatus will set the Status field for the resource +func (r *resource) SetStatus(desired acktypes.AWSResource) { + r.ko.Status = desired.(*resource).ko.Status +} + +// SetIdentifiers sets the Spec or Status field that is referenced as the unique +// resource identifier +func (r *resource) SetIdentifiers(identifier *ackv1alpha1.AWSIdentifiers) error { + if identifier.NameOrID == "" { + return ackerrors.MissingNameIdentifier + } + r.ko.Spec.Name = &identifier.NameOrID + + f0, f0ok := identifier.AdditionalKeys["functionName"] + if f0ok { + r.ko.Spec.FunctionName = &f0 + } + + return nil +} + +// DeepCopy will return a copy of the resource +func (r *resource) DeepCopy() acktypes.AWSResource { + koCopy := r.ko.DeepCopy() + return &resource{koCopy} +} diff --git a/pkg/resource/alias/sdk.go b/pkg/resource/alias/sdk.go new file mode 100644 index 00000000..38ef626a --- /dev/null +++ b/pkg/resource/alias/sdk.go @@ -0,0 +1,515 @@ +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may +// not use this file except in compliance with the License. A copy of the +// License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file 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 ack-generate. DO NOT EDIT. + +package alias + +import ( + "context" + "reflect" + "strings" + + ackv1alpha1 "github.com/aws-controllers-k8s/runtime/apis/core/v1alpha1" + ackcompare "github.com/aws-controllers-k8s/runtime/pkg/compare" + ackcondition "github.com/aws-controllers-k8s/runtime/pkg/condition" + ackerr "github.com/aws-controllers-k8s/runtime/pkg/errors" + ackrtlog "github.com/aws-controllers-k8s/runtime/pkg/runtime/log" + "github.com/aws/aws-sdk-go/aws" + svcsdk "github.com/aws/aws-sdk-go/service/lambda" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + svcapitypes "github.com/aws-controllers-k8s/lambda-controller/apis/v1alpha1" +) + +// Hack to avoid import errors during build... +var ( + _ = &metav1.Time{} + _ = strings.ToLower("") + _ = &aws.JSONValue{} + _ = &svcsdk.Lambda{} + _ = &svcapitypes.Alias{} + _ = ackv1alpha1.AWSAccountID("") + _ = &ackerr.NotFound + _ = &ackcondition.NotManagedMessage + _ = &reflect.Value{} +) + +// sdkFind returns SDK-specific information about a supplied resource +func (rm *resourceManager) sdkFind( + ctx context.Context, + r *resource, +) (latest *resource, err error) { + rlog := ackrtlog.FromContext(ctx) + exit := rlog.Trace("rm.sdkFind") + defer exit(err) + // If any required fields in the input shape are missing, AWS resource is + // not created yet. Return NotFound here to indicate to callers that the + // resource isn't yet created. + if rm.requiredFieldsMissingFromReadOneInput(r) { + return nil, ackerr.NotFound + } + + input, err := rm.newDescribeRequestPayload(r) + if err != nil { + return nil, err + } + + var resp *svcsdk.AliasConfiguration + resp, err = rm.sdkapi.GetAliasWithContext(ctx, input) + rm.metrics.RecordAPICall("READ_ONE", "GetAlias", err) + if err != nil { + if awsErr, ok := ackerr.AWSError(err); ok && awsErr.Code() == "ResourceNotFoundException" { + return nil, ackerr.NotFound + } + return nil, err + } + + // Merge in the information we read from the API call above to the copy of + // the original Kubernetes object we passed to the function + ko := r.ko.DeepCopy() + + if ko.Status.ACKResourceMetadata == nil { + ko.Status.ACKResourceMetadata = &ackv1alpha1.ResourceMetadata{} + } + if resp.AliasArn != nil { + arn := ackv1alpha1.AWSResourceName(*resp.AliasArn) + ko.Status.ACKResourceMetadata.ARN = &arn + } + if resp.Description != nil { + ko.Spec.Description = resp.Description + } else { + ko.Spec.Description = nil + } + if resp.FunctionVersion != nil { + ko.Spec.FunctionVersion = resp.FunctionVersion + } else { + ko.Spec.FunctionVersion = nil + } + if resp.Name != nil { + ko.Spec.Name = resp.Name + } else { + ko.Spec.Name = nil + } + if resp.RevisionId != nil { + ko.Status.RevisionID = resp.RevisionId + } else { + ko.Status.RevisionID = nil + } + if resp.RoutingConfig != nil { + f5 := &svcapitypes.AliasRoutingConfiguration{} + if resp.RoutingConfig.AdditionalVersionWeights != nil { + f5f0 := map[string]*float64{} + for f5f0key, f5f0valiter := range resp.RoutingConfig.AdditionalVersionWeights { + var f5f0val float64 + f5f0val = *f5f0valiter + f5f0[f5f0key] = &f5f0val + } + f5.AdditionalVersionWeights = f5f0 + } + ko.Spec.RoutingConfig = f5 + } else { + ko.Spec.RoutingConfig = nil + } + + rm.setStatusDefaults(ko) + return &resource{ko}, nil +} + +// requiredFieldsMissingFromReadOneInput returns true if there are any fields +// for the ReadOne Input shape that are required but not present in the +// resource's Spec or Status +func (rm *resourceManager) requiredFieldsMissingFromReadOneInput( + r *resource, +) bool { + return r.ko.Spec.FunctionName == nil || r.ko.Spec.Name == nil + +} + +// newDescribeRequestPayload returns SDK-specific struct for the HTTP request +// payload of the Describe API call for the resource +func (rm *resourceManager) newDescribeRequestPayload( + r *resource, +) (*svcsdk.GetAliasInput, error) { + res := &svcsdk.GetAliasInput{} + + if r.ko.Spec.FunctionName != nil { + res.SetFunctionName(*r.ko.Spec.FunctionName) + } + if r.ko.Spec.Name != nil { + res.SetName(*r.ko.Spec.Name) + } + + return res, nil +} + +// sdkCreate creates the supplied resource in the backend AWS service API and +// returns a copy of the resource with resource fields (in both Spec and +// Status) filled in with values from the CREATE API operation's Output shape. +func (rm *resourceManager) sdkCreate( + ctx context.Context, + desired *resource, +) (created *resource, err error) { + rlog := ackrtlog.FromContext(ctx) + exit := rlog.Trace("rm.sdkCreate") + defer exit(err) + input, err := rm.newCreateRequestPayload(ctx, desired) + if err != nil { + return nil, err + } + + var resp *svcsdk.AliasConfiguration + _ = resp + resp, err = rm.sdkapi.CreateAliasWithContext(ctx, input) + rm.metrics.RecordAPICall("CREATE", "CreateAlias", err) + if err != nil { + return nil, err + } + // Merge in the information we read from the API call above to the copy of + // the original Kubernetes object we passed to the function + ko := desired.ko.DeepCopy() + + if ko.Status.ACKResourceMetadata == nil { + ko.Status.ACKResourceMetadata = &ackv1alpha1.ResourceMetadata{} + } + if resp.AliasArn != nil { + arn := ackv1alpha1.AWSResourceName(*resp.AliasArn) + ko.Status.ACKResourceMetadata.ARN = &arn + } + if resp.Description != nil { + ko.Spec.Description = resp.Description + } else { + ko.Spec.Description = nil + } + if resp.FunctionVersion != nil { + ko.Spec.FunctionVersion = resp.FunctionVersion + } else { + ko.Spec.FunctionVersion = nil + } + if resp.Name != nil { + ko.Spec.Name = resp.Name + } else { + ko.Spec.Name = nil + } + if resp.RevisionId != nil { + ko.Status.RevisionID = resp.RevisionId + } else { + ko.Status.RevisionID = nil + } + if resp.RoutingConfig != nil { + f5 := &svcapitypes.AliasRoutingConfiguration{} + if resp.RoutingConfig.AdditionalVersionWeights != nil { + f5f0 := map[string]*float64{} + for f5f0key, f5f0valiter := range resp.RoutingConfig.AdditionalVersionWeights { + var f5f0val float64 + f5f0val = *f5f0valiter + f5f0[f5f0key] = &f5f0val + } + f5.AdditionalVersionWeights = f5f0 + } + ko.Spec.RoutingConfig = f5 + } else { + ko.Spec.RoutingConfig = nil + } + + rm.setStatusDefaults(ko) + return &resource{ko}, nil +} + +// newCreateRequestPayload returns an SDK-specific struct for the HTTP request +// payload of the Create API call for the resource +func (rm *resourceManager) newCreateRequestPayload( + ctx context.Context, + r *resource, +) (*svcsdk.CreateAliasInput, error) { + res := &svcsdk.CreateAliasInput{} + + if r.ko.Spec.Description != nil { + res.SetDescription(*r.ko.Spec.Description) + } + if r.ko.Spec.FunctionName != nil { + res.SetFunctionName(*r.ko.Spec.FunctionName) + } + if r.ko.Spec.FunctionVersion != nil { + res.SetFunctionVersion(*r.ko.Spec.FunctionVersion) + } + if r.ko.Spec.Name != nil { + res.SetName(*r.ko.Spec.Name) + } + if r.ko.Spec.RoutingConfig != nil { + f4 := &svcsdk.AliasRoutingConfiguration{} + if r.ko.Spec.RoutingConfig.AdditionalVersionWeights != nil { + f4f0 := map[string]*float64{} + for f4f0key, f4f0valiter := range r.ko.Spec.RoutingConfig.AdditionalVersionWeights { + var f4f0val float64 + f4f0val = *f4f0valiter + f4f0[f4f0key] = &f4f0val + } + f4.SetAdditionalVersionWeights(f4f0) + } + res.SetRoutingConfig(f4) + } + + return res, nil +} + +// sdkUpdate patches the supplied resource in the backend AWS service API and +// returns a new resource with updated fields. +func (rm *resourceManager) sdkUpdate( + ctx context.Context, + desired *resource, + latest *resource, + delta *ackcompare.Delta, +) (updated *resource, err error) { + rlog := ackrtlog.FromContext(ctx) + exit := rlog.Trace("rm.sdkUpdate") + defer exit(err) + input, err := rm.newUpdateRequestPayload(ctx, desired) + if err != nil { + return nil, err + } + + var resp *svcsdk.AliasConfiguration + _ = resp + resp, err = rm.sdkapi.UpdateAliasWithContext(ctx, input) + rm.metrics.RecordAPICall("UPDATE", "UpdateAlias", err) + if err != nil { + return nil, err + } + // Merge in the information we read from the API call above to the copy of + // the original Kubernetes object we passed to the function + ko := desired.ko.DeepCopy() + + if ko.Status.ACKResourceMetadata == nil { + ko.Status.ACKResourceMetadata = &ackv1alpha1.ResourceMetadata{} + } + if resp.AliasArn != nil { + arn := ackv1alpha1.AWSResourceName(*resp.AliasArn) + ko.Status.ACKResourceMetadata.ARN = &arn + } + if resp.Description != nil { + ko.Spec.Description = resp.Description + } else { + ko.Spec.Description = nil + } + if resp.FunctionVersion != nil { + ko.Spec.FunctionVersion = resp.FunctionVersion + } else { + ko.Spec.FunctionVersion = nil + } + if resp.Name != nil { + ko.Spec.Name = resp.Name + } else { + ko.Spec.Name = nil + } + if resp.RevisionId != nil { + ko.Status.RevisionID = resp.RevisionId + } else { + ko.Status.RevisionID = nil + } + if resp.RoutingConfig != nil { + f5 := &svcapitypes.AliasRoutingConfiguration{} + if resp.RoutingConfig.AdditionalVersionWeights != nil { + f5f0 := map[string]*float64{} + for f5f0key, f5f0valiter := range resp.RoutingConfig.AdditionalVersionWeights { + var f5f0val float64 + f5f0val = *f5f0valiter + f5f0[f5f0key] = &f5f0val + } + f5.AdditionalVersionWeights = f5f0 + } + ko.Spec.RoutingConfig = f5 + } else { + ko.Spec.RoutingConfig = nil + } + + rm.setStatusDefaults(ko) + return &resource{ko}, nil +} + +// newUpdateRequestPayload returns an SDK-specific struct for the HTTP request +// payload of the Update API call for the resource +func (rm *resourceManager) newUpdateRequestPayload( + ctx context.Context, + r *resource, +) (*svcsdk.UpdateAliasInput, error) { + res := &svcsdk.UpdateAliasInput{} + + if r.ko.Spec.Description != nil { + res.SetDescription(*r.ko.Spec.Description) + } + if r.ko.Spec.FunctionName != nil { + res.SetFunctionName(*r.ko.Spec.FunctionName) + } + if r.ko.Spec.FunctionVersion != nil { + res.SetFunctionVersion(*r.ko.Spec.FunctionVersion) + } + if r.ko.Spec.Name != nil { + res.SetName(*r.ko.Spec.Name) + } + if r.ko.Status.RevisionID != nil { + res.SetRevisionId(*r.ko.Status.RevisionID) + } + if r.ko.Spec.RoutingConfig != nil { + f5 := &svcsdk.AliasRoutingConfiguration{} + if r.ko.Spec.RoutingConfig.AdditionalVersionWeights != nil { + f5f0 := map[string]*float64{} + for f5f0key, f5f0valiter := range r.ko.Spec.RoutingConfig.AdditionalVersionWeights { + var f5f0val float64 + f5f0val = *f5f0valiter + f5f0[f5f0key] = &f5f0val + } + f5.SetAdditionalVersionWeights(f5f0) + } + res.SetRoutingConfig(f5) + } + + return res, nil +} + +// sdkDelete deletes the supplied resource in the backend AWS service API +func (rm *resourceManager) sdkDelete( + ctx context.Context, + r *resource, +) (latest *resource, err error) { + rlog := ackrtlog.FromContext(ctx) + exit := rlog.Trace("rm.sdkDelete") + defer exit(err) + input, err := rm.newDeleteRequestPayload(r) + if err != nil { + return nil, err + } + var resp *svcsdk.DeleteAliasOutput + _ = resp + resp, err = rm.sdkapi.DeleteAliasWithContext(ctx, input) + rm.metrics.RecordAPICall("DELETE", "DeleteAlias", err) + return nil, err +} + +// newDeleteRequestPayload returns an SDK-specific struct for the HTTP request +// payload of the Delete API call for the resource +func (rm *resourceManager) newDeleteRequestPayload( + r *resource, +) (*svcsdk.DeleteAliasInput, error) { + res := &svcsdk.DeleteAliasInput{} + + if r.ko.Spec.FunctionName != nil { + res.SetFunctionName(*r.ko.Spec.FunctionName) + } + if r.ko.Spec.Name != nil { + res.SetName(*r.ko.Spec.Name) + } + + return res, nil +} + +// setStatusDefaults sets default properties into supplied custom resource +func (rm *resourceManager) setStatusDefaults( + ko *svcapitypes.Alias, +) { + if ko.Status.ACKResourceMetadata == nil { + ko.Status.ACKResourceMetadata = &ackv1alpha1.ResourceMetadata{} + } + if ko.Status.ACKResourceMetadata.OwnerAccountID == nil { + ko.Status.ACKResourceMetadata.OwnerAccountID = &rm.awsAccountID + } + if ko.Status.Conditions == nil { + ko.Status.Conditions = []*ackv1alpha1.Condition{} + } +} + +// updateConditions returns updated resource, true; if conditions were updated +// else it returns nil, false +func (rm *resourceManager) updateConditions( + r *resource, + onSuccess bool, + err error, +) (*resource, bool) { + ko := r.ko.DeepCopy() + rm.setStatusDefaults(ko) + + // Terminal condition + var terminalCondition *ackv1alpha1.Condition = nil + var recoverableCondition *ackv1alpha1.Condition = nil + var syncCondition *ackv1alpha1.Condition = nil + for _, condition := range ko.Status.Conditions { + if condition.Type == ackv1alpha1.ConditionTypeTerminal { + terminalCondition = condition + } + if condition.Type == ackv1alpha1.ConditionTypeRecoverable { + recoverableCondition = condition + } + if condition.Type == ackv1alpha1.ConditionTypeResourceSynced { + syncCondition = condition + } + } + + if rm.terminalAWSError(err) || err == ackerr.SecretTypeNotSupported || err == ackerr.SecretNotFound { + if terminalCondition == nil { + terminalCondition = &ackv1alpha1.Condition{ + Type: ackv1alpha1.ConditionTypeTerminal, + } + ko.Status.Conditions = append(ko.Status.Conditions, terminalCondition) + } + var errorMessage = "" + if err == ackerr.SecretTypeNotSupported || err == ackerr.SecretNotFound { + errorMessage = err.Error() + } else { + awsErr, _ := ackerr.AWSError(err) + errorMessage = awsErr.Error() + } + terminalCondition.Status = corev1.ConditionTrue + terminalCondition.Message = &errorMessage + } else { + // Clear the terminal condition if no longer present + if terminalCondition != nil { + terminalCondition.Status = corev1.ConditionFalse + terminalCondition.Message = nil + } + // Handling Recoverable Conditions + if err != nil { + if recoverableCondition == nil { + // Add a new Condition containing a non-terminal error + recoverableCondition = &ackv1alpha1.Condition{ + Type: ackv1alpha1.ConditionTypeRecoverable, + } + ko.Status.Conditions = append(ko.Status.Conditions, recoverableCondition) + } + recoverableCondition.Status = corev1.ConditionTrue + awsErr, _ := ackerr.AWSError(err) + errorMessage := err.Error() + if awsErr != nil { + errorMessage = awsErr.Error() + } + recoverableCondition.Message = &errorMessage + } else if recoverableCondition != nil { + recoverableCondition.Status = corev1.ConditionFalse + recoverableCondition.Message = nil + } + } + // Required to avoid the "declared but not used" error in the default case + _ = syncCondition + if terminalCondition != nil || recoverableCondition != nil || syncCondition != nil { + return &resource{ko}, true // updated + } + return nil, false // not updated +} + +// terminalAWSError returns awserr, true; if the supplied error is an aws Error type +// and if the exception indicates that it is a Terminal exception +// 'Terminal' exception are specified in generator configuration +func (rm *resourceManager) terminalAWSError(err error) bool { + // No terminal_errors specified for this resource in generator config + return false +} diff --git a/test/e2e/resources/alias.yaml b/test/e2e/resources/alias.yaml new file mode 100644 index 00000000..3d5b682c --- /dev/null +++ b/test/e2e/resources/alias.yaml @@ -0,0 +1,11 @@ +apiVersion: lambda.services.k8s.aws/v1alpha1 +kind: Alias +metadata: + name: $ALIAS_NAME + annotations: + services.k8s.aws/region: $AWS_REGION +spec: + name: $ALIAS_NAME + functionName: $FUNCTION_NAME + functionVersion: $FUNCTION_VERSION + description: alias created by ACK lambda-controller e2e tests \ No newline at end of file diff --git a/test/e2e/tests/test_alias.py b/test/e2e/tests/test_alias.py new file mode 100644 index 00000000..aa007c1d --- /dev/null +++ b/test/e2e/tests/test_alias.py @@ -0,0 +1,154 @@ +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You may +# not use this file except in compliance with the License. A copy of the +# License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file 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. + +"""Integration tests for the Lambda alias API. +""" + +import boto3 +import pytest +import time +import logging +from typing import Dict, Tuple + +from acktest.resources import random_suffix_name +from acktest.aws.identity import get_region +from acktest.k8s import resource as k8s +from e2e import service_marker, CRD_GROUP, CRD_VERSION, load_lambda_resource +from e2e.replacement_values import REPLACEMENT_VALUES +from e2e.bootstrap_resources import get_bootstrap_resources + +RESOURCE_PLURAL = "aliases" + +CREATE_WAIT_AFTER_SECONDS = 10 +UPDATE_WAIT_AFTER_SECONDS = 10 +DELETE_WAIT_AFTER_SECONDS = 10 + +@pytest.fixture(scope="module") +def lambda_client(): + return boto3.client("lambda") + +@pytest.fixture(scope="module") +def lambda_function(): + resource_name = random_suffix_name("lambda-function", 24) + resources = get_bootstrap_resources() + + replacements = REPLACEMENT_VALUES.copy() + replacements["FUNCTION_NAME"] = resource_name + replacements["BUCKET_NAME"] = resources.FunctionsBucketName + replacements["LAMBDA_ROLE"] = resources.LambdaRoleARN + replacements["LAMBDA_FILE_NAME"] = resources.LambdaFunctionFileZip + replacements["AWS_REGION"] = get_region() + + # Load function CR + resource_data = load_lambda_resource( + "function", + additional_replacements=replacements, + ) + logging.debug(resource_data) + + # Create k8s resource + function_reference = k8s.CustomResourceReference( + CRD_GROUP, CRD_VERSION, "functions", + resource_name, namespace="default", + ) + + # Create lambda function + k8s.create_custom_resource(function_reference, resource_data) + function_resource = k8s.wait_resource_consumed_by_controller(function_reference) + + assert function_resource is not None + assert k8s.get_resource_exists(function_reference) + + time.sleep(CREATE_WAIT_AFTER_SECONDS) + + yield (function_reference, function_resource) + + _, deleted = k8s.delete_custom_resource(function_reference) + assert deleted + +@service_marker +@pytest.mark.canary +class TestAlias: + def get_alias(self, lambda_client, alias_name: str, function_name: str) -> dict: + try: + resp = lambda_client.get_alias( + Name=alias_name, + FunctionName=function_name + ) + return resp + + except Exception as e: + logging.debug(e) + return None + + def alias_exist(self, lambda_client, alias_name: str, function_name: str) -> bool: + return self.get_alias(lambda_client, alias_name, function_name) is not None + + def test_smoke(self, lambda_client, lambda_function): + (_, function_resource) = lambda_function + lambda_function_name = function_resource["spec"]["name"] + + resource_name = random_suffix_name("lambda-alias", 24) + + replacements = REPLACEMENT_VALUES.copy() + replacements["AWS_REGION"] = get_region() + replacements["ALIAS_NAME"] = resource_name + replacements["FUNCTION_NAME"] = lambda_function_name + replacements["FUNCTION_VERSION"] = "$LATEST" + + # Load alias CR + resource_data = load_lambda_resource( + "alias", + additional_replacements=replacements, + ) + logging.debug(resource_data) + + # Create k8s resource + ref = k8s.CustomResourceReference( + CRD_GROUP, CRD_VERSION, RESOURCE_PLURAL, + resource_name, namespace="default", + ) + k8s.create_custom_resource(ref, resource_data) + cr = k8s.wait_resource_consumed_by_controller(ref) + + assert cr is not None + assert k8s.get_resource_exists(ref) + + time.sleep(CREATE_WAIT_AFTER_SECONDS) + + # Check alias exists + alias = self.alias_exist(lambda_client, resource_name, lambda_function_name) + assert alias is not None + + # Update cr + cr["spec"]["description"] = "" + + # Patch k8s resource + k8s.patch_custom_resource(ref, cr) + time.sleep(UPDATE_WAIT_AFTER_SECONDS) + + # Check alias description + alias = self.get_alias(lambda_client, resource_name, lambda_function_name) + assert alias is not None + assert alias["Description"] == "" + + # Delete k8s resource + _, deleted = k8s.delete_custom_resource(ref) + assert deleted + + time.sleep(DELETE_WAIT_AFTER_SECONDS) + + # Check alias doesn't exists + exists = self.get_alias(lambda_client, resource_name, lambda_function_name) + assert not exists + diff --git a/test/e2e/tests/test_function.py b/test/e2e/tests/test_function.py index 3c13a27e..59d3f552 100644 --- a/test/e2e/tests/test_function.py +++ b/test/e2e/tests/test_function.py @@ -11,7 +11,7 @@ # express or implied. See the License for the specific language governing # permissions and limitations under the License. -"""Integration tests for the Lambda Repository API. +"""Integration tests for the Lambda function API. """ import boto3