Skip to main content

FaaS

Function as a Service (FaaS)

Introduction

Function as a Service (FaaS) is a serverless cloud computing paradigm that facilitates the swift development and deployment of functions or services. With FaaS, developers can write and deploy code expeditiously, eliminating the need to handle infrastructure management. This approach can substantially decrease the time required to introduce new features or applications to the market.

Function as a Service operates by allowing developers to focus solely on their code logic, without concerning themselves with the underlying server infrastructure. This serverless model enables automatic scaling and efficient resource utilization, making it an ideal choice for applications with varying workloads. By abstracting away infrastructure concerns, FaaS promotes agility and cost-effectiveness in software development and is particularly advantageous for microservices architectures and event-driven applications.

Runtimes

There are several official templates provided by E2E Networks, and the following are currently documented:

  • Python 3.11 [FastAPI]
  • Python 3.11 [Flask]
  • Node 20 [Express]
  • Node 18 [Express]
  • Python 3.11 [Http]
  • Node 20 [Http]
  • C# .Net 7.0 [Http]
  • PHP 8.2 [Http]
  • Go 1.21 [Http]
  • Python 3.9 [Http]
  • Python PyTorch 2.1.2 [FastAPI]
  • Python PyTorch 2.1.2 [Flask]
  • Python TensorFlow 2.19.0 [FastAPI]
  • Python TensorFlow 2.19.0 [Flask]
  • Custom Container Image

Please note that the given code setup should remain unchanged. The handler functions serve as the entry points for your code. You have the flexibility to extend the code as needed. This approach ensures organizational coherence and seamless integration with the existing codebase.

How to Create Functions

Python - 3.x

This is the recommended template for Python users.

  • Python 3.x is built on Debian Linux, featuring a larger image size. This characteristic is essential for accommodating native C modules such as SQL, Kafka, Pandas, and image manipulation libraries.
  • Python 3.11 is the current stable version for the template.
  • This template is designed to offer full control over the HTTP request and response.
  1. Go to ‘MyAccount’ and log in using your credentials. Click on Functions.

    Side Navigation Bar

  2. Click on Functions from the side navigation bar under the Compute section.

    Get Started

  3. Click on Get Started.

  4. Before creating a function, you must first activate the FaaS (Function as a Service) platform.

    Activate FaaS

  5. After successfully activating FaaS, you have two options for running functions: using either the CPU or the GPU.

  6. If you select CPU hardware, select the runtime template (e.g., Python), enter the function name, and write the code in the code tab.

    Python 3.x Template

    Python 3.x Code

Dedicated Replica

We are introducing a dedicated replicas feature for CPU functions. If enabled, you can select the number of replicas to create, generating copies of the specific CPU functions. The maximum number of replicas allowed is 5.

Enable Replica

You can see the number of dedicated replicas in the info section.

Dedicated Replica Info

Update Replica

You can update the number of replicas by clicking System Configuration.

Update Replica

Upload code through Zip File

An alternative way to input the code is by uploading your file. Click on the "Click to upload" option (Download sample zip files from Zip Guidelines).

Guidelines

File Structure

The zip file must only have one directory and it should follow zip file guidelines.

GPU Hardware Option

If you select GPU hardware, you can choose a runtime template such as Python with PyTorch or Python with TensorFlow. Then, enter the function name and write your code in the code tab.

Select GPU

Add Requirements

Click on the requirements.txt tab and write the required package.

Package Python

Function Configuration

Click on Function Configuration and add the required variables according to your code’s requirements.

Function Configuration

Once you have successfully created the function, you can conveniently access, edit, and manage your function.

After Creation - Function Management

After Creation - Function

Custom Container Image Options

If you select Custom Container Image, you can provide a public Docker image URL and create your Function.

Select Container

To use your custom image, set the desired public base image in the BASE_IMAGE argument in your Dockerfile.

Note: Your image must be compatible with --platform=linux/amd64. Ensure the base image supports this architecture, or the container may fail to start.

Dockerfile Example

# Set your desired public base image here
# Replace the value of BASE_IMAGE with your own Docker image URL
ARG BASE_IMAGE=e2efaasplatform/react-sample

FROM --platform=linux/amd64 ${BASE_IMAGE}

# ⚠️ Do not modify the following configurations
# These ensure the container runs securely as a non-root user
USER 1001

# You can add your custom instructions below this line (optional)
Note

The function handler is passed two arguments, event and context. "event" contains data about the request, including:

  • body(in bytes, see example below)
  • headers
  • method
  • query
  • path

"context" contains basic information about the function, including:

  • hostname

By default, the template will automatically attempt to set the correct Content-Type header for you based on the type of response. For example, returning a dict object type will automatically attach the header Content-Type: application/json and returning a string type will automatically attach the Content-Type: text/html, charset=utf-8 for you.

Note

The function handler is passed two arguments, event and context. "event" contains data about the request, including:

  • body(in bytes, see example below)
  • headers
  • method
  • query
  • path

"context" contains basic information about the function, including:

  • hostname

By default, the template will automatically attempt to set the correct Content-Type header for you based on the type of response. For example, returning a dict object type will automatically attach the header Content-Type: application/json and returning a string type will automatically attach the Content-Type: text/html, charset=utf-8 for you.

Example Codes

Request Body

# Accessing request body (you can also use json.loads(event.body) to convert into dict)
def handle(event, context):
return {
"statusCode": 200,
"body": "You said: " + str(event.body)
}

Request Method

        - Accessing request method
def handle(event, context):
if event.method == 'GET':
return {
"statusCode": 200,
"body": "GET request"
}
else:
return {
"statusCode": 405,
"body": "Method not allowed"
}

Request Query


- Accessing request query string arguments
def handle(event, context):
return {
"statusCode": 200,
"body": {
"name": event.query['name']
}
}

custom response headers


- Setting custom response headers
def handle(event, context):
return {
"statusCode": 200,
"body": {
"key": "value"
},
"headers": {
"Location": "https://www.example.com/"
}
}

import json

def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)

def handle(event, context):
if 'number' in event.query:
number = int(event.query['number'])
result = factorial(number)
return {
"statusCode": 200,
"body": {
"factorial": result
}
}
else:
return {
"statusCode": 400,
"body": "Number not provided in the query parameters."
}

Csharp/.NET

You can create functions in .NET Core using C# / CSharp.

  1. Click on the Create Function button to create a function.

    C# .NET Template

  2. Select the runtime template (Csharp/.NET), provide the function name, and write the code in the code tab.

  3. Click on the Function.csproj tab and write the required package.

    C# .NET Project

  4. Click on Environment Variables and add the required variables according to the code requirements.

    C# .NET Environment Variables

  5. Once you have successfully created the function, you will be redirected to the Functions page, where you can conveniently access and manage your function.

    C# .NET Function Created

Node.js

The Node.js template uses Express.js under the hood and the LTS version of Node.

  1. Click on the Create Function button to create a function.

    Node.js Template

  2. Select the runtime template (Node.js), provide the function name, and write the code in the code tab.

  3. Click on the package.json tab and write the required package.

    Node.js Package

  4. Click on Environment Variables and add the required variables according to the code requirements.

    Node.js Environment Variables

  5. Once you have successfully created the function, you will be redirected to the Functions page, where you can conveniently access and manage your function.

    Node.js Functions

Note

The event object has the following properties:

  • event.body - the body of the HTTP request, either as a string or a JSON object
  • event.headers - the HTTP headers as a JSON object, index them as a dictionary (e.g., event.headers["content-type"])
  • event.method - the HTTP method as a string
  • event.query - the query string as a JSON object, index them as a dictionary (e.g., event.query)
  • event.path - the path of the HTTP request

The context object has the following methods:

  • context.status(code) - set the HTTP status code
  • context.succeed(result) - set the HTTP response body and end the request
  • context.fail(error) - set the HTTP status code to 500 and end the request
  • context.headers(headers) - set the HTTP headers, passing in a JSON object

Example

Edit the function as follows:

   
'use strict';

const axios = require('axios');

module.exports = async (event, context) => {
const requestBody = JSON.parse(event.body);

if (!requestBody.url) {
return context
.status(400)
.fail('Missing "url" in the request body');
}

const result = {};

try {
const res = await axios({
method: 'GET',
url: requestBody.url,
validateStatus: () => true
});

result.body = res.data;
result.status = res.status;
} catch (e) {
return context
.status(500)
.fail(e);
}

return context
.status(result.status)
.succeed(result.body);
};

and update the Package.json file


{
"name": "openfaas-function",
"version": "1.0.0",
"description": "OpenFaaS Function",
"main": "handler.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 0"
},
"keywords": [],
"author": "OpenFaaS Ltd",
"license": "MIT",
"devDependencies": {
"chai": "^4.2.0",
"mocha": "^7.0.1",
"axios": "^0.16.2"
}
}

Functions Information

Info

You will be able to check all the basic details of your Function:

  • URL: The invocation URL of the function, which can be invoked from anywhere.
  • Version: The number of times the function has been updated/changed.
  • Memory: The memory limit assigned at the time of function creation.
  • Execution Timeout: The maximum function execution time selected at the time of creation.
  • Invocation Count: The total number of function invocations.

Function Details

Logs

Click on the logs tab to check all the log details of your Function.

Function Logs

Edit Function

If a user wants to edit function code, click on the function name.

Edit Function

After clicking on the function, navigate to the code tab and edit the code according to the requirement.

Click Function

An alternative way to edit the code is by uploading a file. Click "click to upload."

Edit Code Drag Drop

After editing the code, the user should click the save button to save the changes.

Save Edit


System Configuration

In this section, you can update the memory or timeout settings for a particular function.

System Configuration

After updating the memory or timeout, the user should click the save button to apply the changes.

System Configuration Save

Function States

FaaS Function can have these states:

  1. Deploying: The function is currently undergoing deployment, and the duration of this process is influenced by the number of requirements and the complexity of your function code.
  2. Running: The function is successfully deployed and ready to be invoked.
  3. Failed: The function encountered issues during deployment and execution. Potential causes include incorrect dependencies or syntax errors in the code. Detailed information about the failure can be found in the provided logs.

Failed State


Function Troubleshooting

Consider the following steps to identify and resolve problems:

Error: "Function is in failed state"

Description: This error signals the absence or misconfiguration of a crucial external dependency or library.

Resolution Steps:

  1. Verify the accurate installation of all essential dependencies within your function's environment.
  2. In the event of an error, meticulously inspect the values specified in the corresponding external package installation files for accuracy.
  3. Check if the environment variables are stated and fetched correctly in the code.

Error: "Can't reach the service function-name"

Description: This error is triggered when a function surpasses its designated execution time or resource limits.

Resolution Steps:

  1. Review and adjust the timeout and memory configurations for your function as needed.
  2. Evaluate your function code that might be causing longer execution times. Optimize your code to reduce processing time.

These outlined steps are intended to assist you in identifying and resolving common issues with your function. If you are still facing issues, we encourage you to seek further assistance by reaching out to our support team at cloud-support@e2enetworks.com.

Deactivate FaaS

To deactivate FaaS, you need to delete all the functions. After deleting all the functions, click on 'Deactivate FaaS Plan.'

Deactivate FaaS

Click on the Deactivate button.

Click Deactivate