Sample to flush DCS cache on FunctionGraph deployment

This sample demonstrates how to create a FunctionGraph function that flushes DCS cache based on code deployment action.

Prerequisites

Before running this example, ensure you have the following:

Overview

Components

This sample consists of three FunctionGraph functions:

  • one for flushing the DCS cache fn-dcs-flush,

  • one for setting cache values fn-dcs-set,

  • one for retrieving cache values fn-dcs-get.

All functions require the dependencies specified in the fn_dependencies directory.

Function fn-dcs-flush

The function fn-dcs-flush is triggered by CTS on every function code deployment action.

The flush of cache on specified Namespace is only executed if the triggering function is listed in the FUNCTION_NAMES_TO_LISTEN environment variable and the function is in the Project specified by the FUNCTION_PROJECT_ID environment variable.

cts-flush-DCS-cache/fn_dcs_flush/src/index.py
# Function to flush DCS cache for a specific namespace.
# The function is triggered by a CTS event indicating an update to the function code
# It listens for updates to specific functions and flushes the corresponding DCS namespace cache.

from redis.backoff import ExponentialBackoff
from redis.retry import Retry
from redis.client import Redis
from redis.connection import BlockingConnectionPool
from redis.exceptions import BusyLoadingError, ConnectionError, TimeoutError

dcs_client = None


def create_dcs_client(context):
    # Get DCS connection details from user data
    DCS_HOST = context.getUserData("DCS_HOST")
    DCS_PORT = context.getUserData("DCS_PORT")
    DCS_PASSWORD = context.getUserData("DCS_PASSWORD")

    retry = Retry(ExponentialBackoff(), 3)
    pool = BlockingConnectionPool(
        host=DCS_HOST,
        port=DCS_PORT,
        password=DCS_PASSWORD,
        max_connections=20,
        timeout=3,
        socket_timeout=2,
        socket_connect_timeout=2,
        retry=retry,
        retry_on_error=[BusyLoadingError, ConnectionError, TimeoutError],
        health_check_interval=60,
        decode_responses=True,
    )
    return Redis(connection_pool=pool)


# function initializer for setting up the DCS client connection
def initializer(context):
    global dcs_client
    dcs_client = create_dcs_client(context)
    dcs_client.ping()


# function handler for processing CTS events and flushing DCS cache
def handler(event, context):
    logger = context.getLogger()
    output = {}

    logger.info(f"Received event: {event}")

    DCS_NAMESPACE = context.getUserData("DCS_NAMESPACE")

    # Get the project ID of the function to listen for
    # This is used to filter CTS events for the specific project
    FUNCTION_PROJECT_ID = context.getUserData("FUNCTION_PROJECT_ID")

    # Get the list of function names to listen for
    # This is used to filter CTS events for the specific functions
    FUNCTION_NAMES_TO_LISTEN = context.getUserData("FUNCTION_NAMES_TO_LISTEN")

    # Extract the CTS message from the event
    ctsmsg = event["cts"]

    # trace_name indicates the action performed on the function
    CTS_ACTION = ctsmsg["trace_name"]

    # check if the action is updateFunctionCode
    if CTS_ACTION != "updateFunctionCode":
        return {
            "status": "WARNING",
            "message": f"Invalid action - {CTS_ACTION}",
        }

    # resource_name is the name of the function being updated
    CTS_FUNCTION_NAME = ctsmsg["resource_name"]

    # resource_id is the project ID of the function being updated
    CTS_FUNCTION_PROJECT_ID = ctsmsg["resource_id"]

    # Check if the function project ID matches the expected project ID
    if CTS_FUNCTION_PROJECT_ID != FUNCTION_PROJECT_ID:
        return {
            "status": "WARNING",
            "message": f"Function project ID mismatch - {CTS_FUNCTION_PROJECT_ID} != {FUNCTION_PROJECT_ID}",
        }

    # Check if the function name is in the list of functions to listen for
    for fn in FUNCTION_NAMES_TO_LISTEN.split(","):
        if fn.strip().lower() == CTS_FUNCTION_NAME.lower():
            break
    else:
        return {
            "status": "WARNING",
            "message": f"Function {CTS_FUNCTION_NAME} is not in the list to listen",
        }

    try:
        cursor = 0
        pattern = f"{DCS_NAMESPACE}:*"
        batch_size = 100

        while True:
            cursor, keys = dcs_client.scan(
                cursor=cursor, match=pattern, count=batch_size
            )
            if keys:
                dcs_client.delete(*keys)

            if cursor == 0:
                break

        logger.info(f"Successfully flushed DCS for namespace {DCS_NAMESPACE}")

        output = {
            "status": "OK",
            "message": f"Successfully flushed DCS  for namespace {DCS_NAMESPACE}",
        }
    except ConnectionError as e:
        logger.error(f"Failed to flush DCS: {e}")
        output = {
            "status": "ERROR",
            "message": f"Failed to flush DCS: {e}",
        }

    return output

Environment variable

Sample value

Description

DCS_HOST

The DCS host address.

DCS_PORT

6379

The DCS port number.

DCS_PASSWORD

The password for the DCS instance.

DCS_NAMESPACE

fn_dcs

The namespace for the DCS instance.

FUNCTION_NAMES_TO_LISTEN

fn-dcs-set

The names of the functions triggering a cache flush.

FUNCTION_PROJECT_ID

The ID of the project to which the function belongs.

Function fn-dcs-set

The function fn-dcs-set is used to set cache values in the specified DCS namespace.

cts-flush-DCS-cache/fn_dcs_set/src/index.py
# Function to set keys in DCS cache for a specific namespace
# the function sets 100 keys with the pattern {DCS_NAMESPACE}:key-{i} and corresponding values {value-{i}}

from redis.backoff import ExponentialBackoff
from redis.retry import Retry
from redis.client import Redis
from redis.connection import BlockingConnectionPool
from redis.exceptions import BusyLoadingError, ConnectionError, TimeoutError

dcs_client = None

def create_dcs_client(context):
    # Get DCS connection details from user data
    DCS_HOST = context.getUserData("DCS_HOST")
    DCS_PORT = context.getUserData("DCS_PORT")
    DCS_PASSWORD = context.getUserData("DCS_PASSWORD")

    retry = Retry(ExponentialBackoff(), 3)
    pool = BlockingConnectionPool(
        host=DCS_HOST,
        port=DCS_PORT,
        password=DCS_PASSWORD,
        max_connections=20,
        timeout=3,
        socket_timeout=2,
        socket_connect_timeout=2,
        retry=retry,
        retry_on_error=[BusyLoadingError, ConnectionError, TimeoutError],
        health_check_interval=60,
        decode_responses=True,
    )
    return Redis(connection_pool=pool)

# function initializer for setting up the DCS client connection
def initializer(context):
    global dcs_client
    dcs_client = create_dcs_client(context)
    dcs_client.ping()
    

# function handler for setting keys in DCS cache for a specific namespace
def handler(event, context):
    logger = context.getLogger()
    output = {}

    DCS_NAMESPACE = context.getUserData("DCS_NAMESPACE")    

    try:
        with dcs_client.pipeline() as pipe:
            for i in range(0, 100):
                pipe.set(f"{DCS_NAMESPACE}:key-{i}", f"value-{i}")
            pipe.execute()
        
        logger.info(
            f"Successfully set all keys in DCS instance for namespace {DCS_NAMESPACE}"
        )
        output = {
            "status": "OK",
            "message": f"Successfully set keys in namespace {DCS_NAMESPACE}",
        }

    except ConnectionError as e:
        logger.error(f"Failed to connect to DCS instance: {e}")
        output = {
            "status": "ERROR",
            "message": f"Failed to connect to DCS instance: {e}",
        }

    return output

Environment variable

Sample value

Description

DCS_HOST

The DCS host address.

DCS_PORT

6379

The DCS port number.

DCS_PASSWORD

The password for the DCS instance.

DCS_NAMESPACE

fn_dcs

The namespace for the DCS instance.

Function fn-dcs-get

The function fn-dcs-get is used to retrieve cache values from the specified DCS namespace.

cts-flush-DCS-cache/fn_dcs_get/src/index.py
# Function to get key/value pairs from DCS cache for a specific namespace
# the function retrieves all keys matching the specified namespace pattern

from redis.backoff import ExponentialBackoff
from redis.retry import Retry
from redis.client import Redis
from redis.connection import BlockingConnectionPool
from redis.exceptions import BusyLoadingError, ConnectionError, TimeoutError

dcs_client = None

def create_dcs_client(context):
    # Get DCS connection details from user data
    DCS_HOST = context.getUserData("DCS_HOST")
    DCS_PORT = context.getUserData("DCS_PORT")
    DCS_PASSWORD = context.getUserData("DCS_PASSWORD")

    retry = Retry(ExponentialBackoff(), 3)
    pool = BlockingConnectionPool(
        host=DCS_HOST,
        port=DCS_PORT,
        password=DCS_PASSWORD,
        max_connections=20,
        timeout=3,
        socket_timeout=2,
        socket_connect_timeout=2,
        retry=retry,
        retry_on_error=[BusyLoadingError, ConnectionError, TimeoutError],
        health_check_interval=60,
        decode_responses=True,
    )
    return Redis(connection_pool=pool)

# function initializer for setting up the DCS client connection
def initializer(context):
    global dcs_client
    dcs_client = create_dcs_client(context)
    dcs_client.ping()


# function handler for retrieving key/value pairs from DCS cache for a specific namespace
def handler(event, context):
    logger = context.getLogger()
    output = {}
    
    DCS_NAMESPACE = context.getUserData("DCS_NAMESPACE")

    try:
        retrieved_items = []
        cursor = 0
        pattern = f"{DCS_NAMESPACE}:*"
        batch_size = 100

        while True:
            cursor, keys = dcs_client.scan(
                cursor=cursor, match=pattern, count=batch_size
            )
            for key in keys:
                value = dcs_client.get(key)
                retrieved_items.append({"key": key, "value": value})

            if cursor == 0:
                break

        logger.info(
            f"Successfully retrieved keys from DCS instance for namespace {DCS_NAMESPACE}"
        )
        output = {
            "status": "OK",
            "message": f"Successfully retrieved keys from DCS instance for namespace {DCS_NAMESPACE}",
            "keys": retrieved_items,
        }

    except ConnectionError as e:
        logger.error(f"Failed to connect to DCS instance: {e}")
        output = {
            "status": "ERROR",
            "message": f"Failed to connect to DCS instance: {e}",
        }

    return output

Environment variable

Sample value

Description

DCS_HOST

The DCS host address.

DCS_PORT

6379

The DCS port number.

DCS_PASSWORD

The password for the DCS instance.

DCS_NAMESPACE

fn_dcs

The namespace for the DCS instance.

Function dependencies

The functions in this sample rely on the following Python packages:

  • redis: The Redis client library for Python, used to interact with the DCS instance.

cts-flush-DCS-cache/fn_dependencies/requirements.txt
redis>=5.0.0

Terraform files

Terraform config files

cts-flush-DCS-cache/terraform/variables.tf
# prefix will be prepended to all resource names
variable "prefix" {
  type    = string
  description = "set in variables.tfvars"
}

# Resource tag:
variable "tag_app_group" {
  type    = string
  description = "set in variables.tfvars"
}

variable "DCS_HOST" {
  type    = string
  description = "set in variables.auto.tfvars"
}

variable "DCS_PORT" {
  type    = string
  description = "set in variables.auto.tfvars"
}

variable "DCS_PASSWORD" {
  type    = string
  description = "set in variables.auto.tfvars"
}

variable "TEST_USER_NAME" {
  type    = string
  description = "set in variables.auto.tfvars"
}

variable "TEST_USER_ID" {
  type    = string
  description = "set in variables.auto.tfvars"
}

variable "VPC_ID" {
  type    = string
  description = "set in variables.auto.tfvars"
}

variable "NETWORK_ID" {
  type    = string
  description = "set in variables.auto.tfvars"
}

variable "DCS_NAMESPACE" {
  type    = string
  description = "set in variables.auto.tfvars"
}

variable "PYTHON_RUNTIME" {
  type    = string
  default = "Python3.10"  
}

FunctionGraph deployment files

cts-flush-DCS-cache/terraform/fn-dcs-set.tf
##########################################################
# Python event function to set dcs cache
##########################################################
resource "opentelekomcloud_fgs_function_v2" "fn_dcs_set" {

  name = format("%s_%s", var.prefix, "fn_dcs_set")
  app  = "default"

  handler = "src/index.handler"
  initializer_handler = "src/index.initializer"
  initializer_timeout = 60

  runtime = var.PYTHON_RUNTIME

  agency = opentelekomcloud_identity_agency_v3.agency.name

  code_type     = "zip"
  func_code     = filebase64(format("${path.module}/../fn_dcs_set/dist/%s", "code.zip"))
  code_filename = basename("code.zip")

  depend_list = [
    opentelekomcloud_fgs_dependency_version_v2.dependencies.version_id
  ]

  lifecycle {
    replace_triggered_by = [
      opentelekomcloud_fgs_dependency_version_v2.dependencies
    ]
  }

  description      = "Set data in DCS"
  memory_size      = 128
  timeout          = 30
  max_instance_num = 10
  enable_dynamic_memory = true

  log_group_id   = opentelekomcloud_lts_group_v2.LogGroup.id
  log_group_name = opentelekomcloud_lts_group_v2.LogGroup.group_name

  log_topic_id   = opentelekomcloud_lts_stream_v2.log_stream_fn_dcs_set.id
  log_topic_name = opentelekomcloud_lts_stream_v2.log_stream_fn_dcs_set.stream_name

  enable_lts_log = true
  lts_custom_tag = {
    "fn" = "fn_dcs_set"
  }

  # set some environment variables
  user_data = jsonencode({
    "DCS_HOST" : var.DCS_HOST,
    "DCS_PORT" : var.DCS_PORT,
    "DCS_NAMESPACE" : var.DCS_NAMESPACE,
    "DCS_PASSWORD" : var.DCS_PASSWORD
  })
  # encrypted_user_data = jsonencode({
  #   "DCS_PASSWORD" : var.DCS_PASSWORD
  # })

  network_id = var.NETWORK_ID
  vpc_id     = var.VPC_ID

  tags = {
    "app_group" = var.tag_app_group
  }

}

output "FN_DCS_SET_URN" {
  value = opentelekomcloud_fgs_function_v2.fn_dcs_set.urn
}

output "FN_DCS_SET_VERSION" {
  value = opentelekomcloud_fgs_function_v2.fn_dcs_set.version
}

Variables

Sample variables file:

cts-flush-DCS-cache/terraform/variables.tfvars
# Terraform variables

# prefix of all resources
prefix        = "py-cts-flush-dcs-cache"

# resources will be tagged with this app_group tag
tag_app_group = "fg-cts-flush-dcs-cache"

You might want to adjust the variables to your need.

Makefile

Sample Makefile:

cts-flush-DCS-cache/Makefile
# Makefile for Terraform deployment
SHELL := /bin/bash

# Terraform backend configuration
BACKEND_CONFIG_BUCKET := "doc-samples-tf-backend"
BACKEND_CONFIG_KEY := "terraform_state/python/fg-cts-flush-DCS-cache.tf"
BACKEND_CONFIG_REGION := "eu-de"
BACKEND_CONFIG_ENDPOINTS := "endpoints={s3=\"https://obs.eu-de.otc.t-systems.com\"}"

CURRENT_MAKEFILE := $(firstword $(MAKEFILE_LIST))

# IAC_TOOL can be set to "terraform" or "tofu" depending on which tool
# you want to use for deployment.
IAC_TOOL := terraform

SUBDIRS = fn_dependencies fn_dcs_flush fn_dcs_get fn_dcs_set

# Target to create packages for all subdirectories containing function code
create_packages:
	@for dir in $(SUBDIRS); do \
		cd $$dir && make create_package; \
		cd ..; \
	done

# Target to reconfigure the Terraform backend
tf_reconfigure:
	$(IAC_TOOL) -chdir=terraform \
	  init -reconfigure \
	  -backend-config=$(BACKEND_CONFIG_ENDPOINTS) \
	  -backend-config="bucket=$(BACKEND_CONFIG_BUCKET)" \
	  -backend-config="key=$(BACKEND_CONFIG_KEY)" \
	  -backend-config="region=$(BACKEND_CONFIG_REGION)"

# Target to init the Terraform backend
tf_init:
	$(IAC_TOOL) -chdir=terraform \
	  init \
	  -backend-config=$(BACKEND_CONFIG_ENDPOINTS) \
	  -backend-config="bucket=$(BACKEND_CONFIG_BUCKET)" \
	  -backend-config="key=$(BACKEND_CONFIG_KEY)" \
	  -backend-config="region=$(BACKEND_CONFIG_REGION)"

# Target to generate and show the Terraform execution plan
tf_plan:
	if [ ! -f "terraform/.terraform.lock.hcl" ]; then \
		$(MAKE) -f $(CURRENT_MAKEFILE) tf_init; \
	fi
	$(IAC_TOOL) -chdir=terraform \
	  plan \
	  -var-file="variables.tfvars"

# Target to apply Terraform configuration
tf_apply: create_packages
	if [ ! -f "terraform/.terraform.lock.hcl" ]; then \
		$(MAKE) -f $(CURRENT_MAKEFILE) tf_init; \
	fi
	$(IAC_TOOL) -chdir=terraform \
	  apply -auto-approve \
	  -var-file="variables.tfvars"

# Target to destroy all Terraform-managed resources
tf_destroy:
	$(IAC_TOOL) -chdir=terraform \
	  destroy -auto-approve \
	  -var-file="variables.tfvars"

# create log stream indices for DCS functions log
# apply this after tf_apply once.
create_log_stream_index:
	# getting Token for authentication from Username/Password...
	$(eval OTC_X_AUTH_TOKEN := $(shell ../utils/tokenFromUsername.sh))
	$(eval LOG_GROUP_ID := $(shell $(IAC_TOOL) -chdir=terraform output -raw LOG_GROUP_ID))
	$(eval LOG_STREAM_ID := $(shell $(IAC_TOOL) -chdir=terraform output -raw LOG_STREAM_FN_DCS_FLUSH_ID))	
	@bash ../utils/createLogStreamIndex.sh $(OTC_X_AUTH_TOKEN) $(LOG_GROUP_ID) $(LOG_STREAM_ID)
	$(eval LOG_STREAM_ID := $(shell $(IAC_TOOL) -chdir=terraform output -raw LOG_STREAM_FN_DCS_GET_ID))	
	@bash ../utils/createLogStreamIndex.sh $(OTC_X_AUTH_TOKEN) $(LOG_GROUP_ID) $(LOG_STREAM_ID)
	$(eval LOG_STREAM_ID := $(shell $(IAC_TOOL) -chdir=terraform output -raw LOG_STREAM_FN_DCS_SET_ID))	
	@bash ../utils/createLogStreamIndex.sh $(OTC_X_AUTH_TOKEN) $(LOG_GROUP_ID) $(LOG_STREAM_ID)
	
#########################################################################################
# Test targets for the DCS functions
#########################################################################################
test_get:
	$(eval FG_URN := $(shell $(IAC_TOOL) -chdir=terraform output -raw FN_DCS_GET_URN))
	$(eval FG_VERSION := $(shell $(IAC_TOOL) -chdir=terraform output -raw FN_DCS_GET_VERSION))
	@printf '%s' '{}' | bash ../utils/invokeFG.sh $(FG_URN):$(FG_VERSION)

test_set:
	$(eval FG_URN := $(shell $(IAC_TOOL) -chdir=terraform output -raw FN_DCS_SET_URN))
	$(eval FG_VERSION := $(shell $(IAC_TOOL) -chdir=terraform output -raw FN_DCS_SET_VERSION))
	@printf '%s' '{}' | bash ../utils/invokeFG.sh $(FG_URN):$(FG_VERSION)

test_flush:
	$(eval FG_URN := $(shell $(IAC_TOOL) -chdir=terraform output -raw FN_DCS_FLUSH_URN))
	$(eval FG_VERSION := $(shell $(IAC_TOOL) -chdir=terraform output -raw FN_DCS_FLUSH_VERSION))
	@set -o pipefail; \
	FUNCTION_NAME=py-cts-flush-dcs-cache_fn_dcs_set \
	TEST_USER_NAME=testuser \
	TEST_USER_ID=1a \
	envsubst < resources/event.json | \
	bash ../utils/invokeFG.sh $(FG_URN):$(FG_VERSION)

.PHONY: create_packages tf_init tf_plan tf_apply tf_destroy test_get test_set test_flush create_log_stream_index

You might want to adjust the following variables to your need:

# Terraform backend configuration
BACKEND_CONFIG_BUCKET := "doc-samples-tf-backend"
BACKEND_CONFIG_KEY := "terraform_state/python/custom-rule-cts-flush-DCS-cache.tf"
BACKEND_CONFIG_REGION := "eu-de"
BACKEND_CONFIG_ENDPOINTS := "endpoints={s3=\"https://obs.eu-de.otc.t-systems.com\"}"

Deploy

To deploy using Terraform run:

make tf_apply

To destroy the deployed resources using Terraform run:

make tf_destroy

Test

Test deployed resources

The following commands allow you to interact with the deployed DCS cache functions. To test the deployed resources the Makefile provides the following targets:

To set values in the cache, run: .. code-block:: bash

make test_set

To get values from the cache, run:

make test_get

To flush the cache, run:

make test_flush

Test CTS trigger behavior

  1. Write data to the cache using fn-dcs-set:
    make test_set
    
  2. Check data in DCS using fn-dcs-get:

    make test_get
    
  3. Apply changes to source code of fn-dcs-set and redeploy:

    make tf_apply
    

As soon as the changes to fn-dcs-set are applied and redeployed, the data in DCS will be deleted.

  1. Check data in DCS using fn-dcs-get again:

    make test_get