Skip to main content

Function as a Service (FaaS)

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, 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

  2. Click on Get Started.

    Get Started

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

    Activate FaaS

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

    • If you select CPU hardware, choose the runtime template like Python, enter the function name, and write the code in the code tab.

      Python 3.x Python 3.x Code

    • 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

  5. An alternative way to input the code is by uploading your file. Click on the "Click to upload" option, and the code will automatically appear in the code tab.

    Upload Code

  6. Click on the requirement.txt tab and write the required package.

    Package Python

  7. An alternative way to provide the requirement is by uploading your file. Click on the "Click to upload" option, and the requirement will automatically appear in the requirement tab.

    Upload Requirement

  8. Click on Function Configuration and add the required variables according to the code requirements.

    Function Configuration

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

    Access Function After Creation

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.

  • This template uses a middleware handler in an ASP.NET Core Web API. This allows additional context available in the request (by providing the full body to the handler) and more control over the response by passing it back to the HTTP response context.
  • GET method is not allowed for this template.
  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

Example

You could add the popular Newtonsoft.JSON package for formatting JSON objects.

   
using Microsoft.AspNetCore.Http;

using System.Threading.Tasks;

using Newtonsoft.Json;

namespace Function
{
public class SampleResponse
{
public string FunctionStatus { get; set; }
}

public class FunctionHandler
{
public Task<(int, string)> Handle(HttpRequest request)
{
var res = new SampleResponse();
res.FunctionStatus = "Success";

var output = JsonConvert.SerializeObject(res);

return Task.FromResult((200, output));
}
}
}

and update the Function.csproj file


<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
</Project>

Node.js

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

  • The event is used to obtain the original HTTP request, and the context is used to set the HTTP response.
  • The underlying Express.js object is an implementation detail and is not available to the function author.
  • Async/await is supported by the handler by default.
  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.


FaaS Secret

In a Function as a Service (FaaS) environment, a secret key refers to a piece of sensitive information, such as an API key or any other confidential data, that is securely stored and made available to functions at runtime. Secret keys are typically used to authenticate with external services, access sensitive resources, or encrypt and decrypt data within the function. They are managed separately from the function code to enhance security and ensure that sensitive information is not exposed in plaintext.

Utilizing a secret involves a two-step process. Initially, you create the secret via API. Subsequently, you bind that secret to a function and consume it within your code.

  • The same secret can be consumed by more than one function.
  • Secrets must exist in the cluster at deployment time.

How to Create Secret

  1. Click on the Secret icon.

    Click Secret

  2. Once you click on the Secret icon, a popup window titled "Secret" will appear.

    Secret Popup

  3. To create a Secret, click on the "Add" icon.

    Create Secret

  4. Enter a name for the Secret and click on the "Create" button.

    Create Secret 1

The Secret has been successfully created, and you will receive a Secret key.

Receive Secret Key

How to Attach Secret to Functions

  1. To attach a Secret to a function, choose the function you want to attach it to and click on that function name.

    Click Function Name

  2. Navigate to "Function Configuration" and select "Add secret."

    Click Function Configuration

  3. Click on the dropdown menu labeled "Select secrets" and choose the secret that you wish to add to your function.

    Select Secret

  4. After selecting the secret, click on the "Save" button. Upon attaching the secret to your function, it enters the "Deploying" state. After a few seconds, it transitions to the "Running" state, indicating that the secret has been successfully attached to the function.

    Save Secret

Below, you will find the attached secret within the function.

See Saved Secret

Remove Secret from Function

  1. To remove secrets from a function, select the function you want to detach it from and click on that function name.

    Click Function Name

  2. Navigate to "Function Configuration" and click on the delete icon.

    Remove Secret


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