Skip to content

Add auto-publish functionality for Function resources #36

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions apis/v1alpha1/ack-generate-metadata.yaml
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
ack_generate_info:
build_date: "2024-03-06T21:22:30Z"
build_hash: a5ba3c851434263128a1464a2c41e528779eeefa
go_version: go1.22.0
version: v0.32.1
api_directory_checksum: 86a18c0bfcc849ad234f64249fd8951ce418dd14
build_date: "2024-03-23T14:30:00Z"
build_hash: d86061f5f579fe5d3a07528917d95e34e79c4dc0
go_version: go1.22.1
version: v0.32.1-1-gd86061f
api_directory_checksum: 27fd205fbbd08711210430b8e19ed65ab91b5d32
api_version: v1alpha1
aws_sdk_go_version: v1.44.214
generator_config_info:
file_checksum: 250151346bb9c7a0bcd8cdcdb77f482f2eee0d03
file_checksum: 9b125128dc96ab9b6c92fb4d368a0562a3f549fb
original_file_name: generator.yaml
last_modification:
reason: API generation
24 changes: 24 additions & 0 deletions apis/v1alpha1/annotation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// 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.

package v1alpha1

import "fmt"

var (
// AutoPublishAnnotation is the annotation key for the auto-publish annotation
// for CloudFront functions. This annotation is used to indicate whether a
// function should be automatically published after a successful update or create
// operation.
AutoPublishAnnotation = fmt.Sprintf("%s/auto-publish", GroupVersion.Group)
)
4 changes: 4 additions & 0 deletions apis/v1alpha1/generator.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,10 @@ resources:
hooks:
sdk_read_one_post_set_output:
template_path: hooks/function/sdk_read_one_post_set_output.go.tpl
sdk_create_post_set_output:
template_path: hooks/function/sdk_create_post_set_output.go.tpl
sdk_update_post_set_output:
template_path: hooks/function/sdk_update_post_set_output.go.tpl
OriginRequestPolicy:
tags:
ignore: true
Expand Down
4 changes: 4 additions & 0 deletions generator.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,10 @@ resources:
hooks:
sdk_read_one_post_set_output:
template_path: hooks/function/sdk_read_one_post_set_output.go.tpl
sdk_create_post_set_output:
template_path: hooks/function/sdk_create_post_set_output.go.tpl
sdk_update_post_set_output:
template_path: hooks/function/sdk_update_post_set_output.go.tpl
OriginRequestPolicy:
tags:
ignore: true
Expand Down
38 changes: 38 additions & 0 deletions pkg/resource/function/hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ package function

import (
"context"
"strconv"

ackrtlog "github.com/aws-controllers-k8s/runtime/pkg/runtime/log"
svcsdk "github.com/aws/aws-sdk-go/service/cloudfront"
Expand Down Expand Up @@ -57,3 +58,40 @@ func (rm *resourceManager) setFunctionCode(ctx context.Context, r *v1alpha1.Func
r.Spec.FunctionCode = []byte(output.FunctionCode)
return nil
}

// publishFunction publishes the a CloudFront function.
func (rm *resourceManager) publishFunction(ctx context.Context, r *v1alpha1.Function) (err error) {
rlog := ackrtlog.FromContext(ctx)
exit := rlog.Trace("rm.publishFunction")
defer func() { exit(err) }()

_, err = rm.sdkapi.PublishFunctionWithContext(
ctx,
&svcsdk.PublishFunctionInput{
Name: r.Spec.Name,
IfMatch: r.Status.ETag,
},
)
rm.metrics.RecordAPICall("POST", "PublishFunction", err)
if err != nil {
return err
}
return nil
}

// functionAutoPublishEnabled returns true if the function should be
// automatically published after a successful update or create operation.
func functionAutoPublishEnabled(f *v1alpha1.Function) bool {
annotations := f.ObjectMeta.GetAnnotations()
if annotations == nil {
return false
}

autoPublish, ok := annotations[v1alpha1.AutoPublishAnnotation]
if ok {
return autoPublish == strconv.FormatBool(true)
}

// By default we do not auto-publish functions.
return false
}
10 changes: 10 additions & 0 deletions pkg/resource/function/sdk.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions templates/hooks/function/sdk_create_post_set_output.go.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
if functionAutoPublishEnabled(ko) {
if err := rm.publishFunction(ctx, ko); err != nil {
return nil, err
}
}
5 changes: 5 additions & 0 deletions templates/hooks/function/sdk_update_post_set_output.go.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
if functionAutoPublishEnabled(ko) {
if err := rm.publishFunction(ctx, ko); err != nil {
return nil, err
}
}
5 changes: 4 additions & 1 deletion test/e2e/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@

import boto3
import pytest

from acktest import k8s


def pytest_addoption(parser):
parser.addoption("--runslow", action="store_true", default=False, help="run slow tests")

Expand All @@ -26,6 +26,9 @@ def pytest_configure(config):
config.addinivalue_line(
"markers", "slow: mark test as slow to run"
)
config.addinivalue_line(
"markers", "function_overrides: mark test with function overrides"
)

def pytest_collection_modifyitems(config, items):
if config.getoption("--runslow"):
Expand Down
4 changes: 3 additions & 1 deletion test/e2e/resources/function.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ apiVersion: cloudfront.services.k8s.aws/v1alpha1
kind: Function
metadata:
name: $FUNCTION_NAME
annotations:
cloudfront.services.k8s.aws/auto-publish: "$AUTO_PUBLISH"
spec:
name: $FUNCTION_NAME
functionCode: ZnVuY3Rpb24gaGFuZGxlcihldmVudCkgewogIHJldHVybiB7CiAgICBzdGF0dXNDb2RlOiAzMDIsCiAgICBzdGF0dXNEZXNjcmlwdGlvbjogJ0ZvdW5kJywKICAgIGhlYWRlcnM6IHsKICAgICAgbG9jYXRpb246IHsgdmFsdWU6ICdodHRwczovLy8nIH0KICAgIH0KICB9Cn0K
functionConfig:
comment: function to redirect to $DOMAIN_NAME
runtime: $FUNCTION_RUNTIME
runtime: $FUNCTION_RUNTIME
59 changes: 53 additions & 6 deletions test/e2e/tests/test_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,27 +13,26 @@

"""Integration tests for the CloudFront Function resource"""

import logging
import time

import pytest

from acktest.aws import identity
from acktest.k8s import condition
from acktest.k8s import resource as k8s
from acktest.aws import identity
from acktest.resources import random_suffix_name
from e2e import service_marker, CRD_GROUP, CRD_VERSION, load_resource
from e2e import CRD_GROUP, CRD_VERSION, function, load_resource, service_marker
from e2e.bootstrap_resources import get_bootstrap_resources
from e2e.replacement_values import REPLACEMENT_VALUES
from e2e import function

FUNCTIONS_RESOURCE_PLURAL = "functions"
DELETE_WAIT_AFTER_SECONDS = 10
CHECK_STATUS_WAIT_SECONDS = 30
MODIFY_WAIT_AFTER_SECONDS = 30


@pytest.fixture(scope="module")
def simple_function():
@pytest.fixture
def simple_function(request):
function_name = random_suffix_name("my-function", 24)

# resources = get_bootstrap_resources()
Expand All @@ -46,6 +45,19 @@ def simple_function():
replacements['FUNCTION_RUNTIME'] = "cloudfront-js-2.0"
replacements['DOMAIN_NAME'] = "example.com"

# Another reason why we need to stop using python and pytest for
# e2e tests.
auto_publish = "false"
marker = request.node.get_closest_marker("function_overrides")
if marker is not None:
data = marker.args[0]
if 'auto_publish' in data:
if data['auto_publish'] == True:
logging.info("Auto publish is set to true")
auto_publish = "true"

replacements['AUTO_PUBLISH'] = auto_publish

resource_data = load_resource(
"function",
additional_replacements=replacements,
Expand Down Expand Up @@ -107,4 +119,39 @@ def test_crud(self, simple_function):

latest = function.get(function_name)
assert latest is not None
assert latest['Status'] == "UNPUBLISHED"
assert latest['FunctionConfig']['Comment'] == "New comment"

@pytest.mark.function_overrides({
'auto_publish': True,
})
def test_auto_publish(self, simple_function):
ref, res, function_name = simple_function

time.sleep(CHECK_STATUS_WAIT_SECONDS)

# Check that function exists
cr = k8s.get_resource(ref)
assert cr is not None

condition.assert_synced(ref)

latest = function.get(function_name)
assert latest is not None
assert latest['Status'] == "UNASSOCIATED"

updates = {
"spec": {
"functionConfig": {
"comment": "New comment"
}
},
}
k8s.patch_custom_resource(ref, updates)
time.sleep(MODIFY_WAIT_AFTER_SECONDS)

latest = function.get(function_name)
assert latest is not None
assert latest['FunctionConfig']['Comment'] == "New comment"
assert latest['Status'] == "UNASSOCIATED"