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.

Runtime

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

  • Python 3.x

  • NodeJS

  • csharp/.NET

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.

Please go to ‘MyAccount’ and log in using your credentials and click on Functions.

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

../_images/side_nav.png

Click on ‘Get Started’ button to create function.

../_images/get_startedd.png

Select the runtime template like python, and enter the function name and write the code in the code tab.

../_images/python3x.png ../_images/python3x_code.png

Alternative way to input the code is by uploading your file. Click on “Click to upload” option, and the code will automatically appear in the code tab.

../_images/click_drag_drop.png

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

../_images/package_python.png

Alternative way to provide the requirement is by uploading your file. Click on “Click to upload” option, and the requirement will automatically appear in the requirement tab.

../_images/requirement_drag_drop.png

Click on Function Configuration and add the required variable according to code requirement.

../_images/python_create.png

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

../_images/python_after_creation_click_function.png ../_images/python_after_creation.png

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 ASPNET 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 reponse context.

  • GET method is not allowed for this template

Click on Create Function button to create a function.

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

../_images/cnet.png

Click on Function.csproj tab and write the requirement package.

../_images/cnett.png

Click on Environment variable. And Add the required variable according to code requirement.

../_images/cnetcreate.png

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

../_images/cnetcreated.png

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 so is not available to the function author.

  • Async/await is supported by the handler by default.

Click on Create Function button to create a function.

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

../_images/nodejs.png

Click on package.json tab and write the requirement package.

../_images/node_pakage.png

Click on Environment variable. And Add the required variable according to code requirement.

../_images/nodejs_create_1.png

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

../_images/Nodejs_Functions.png

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 i.e. 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 i.e. 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, pass in a JSON object

Example

Edit the function as:

'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 able to check all the basic details of your Function.

  • URL: The invocation URL of the function, can be invoked through 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.

../_images/nodejs_details_1.png

Logs

Click on logs tab.

You will able to check all the Logs details of your Function.

../_images/nodejs_logs.png

Edit Function

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

../_images/Edit_function.png

After clicking the function user go to the code tab and edit the code according the requirement.

../_images/Click_function.png

Alternative way to edit code, you can upload file by clicking ‘click to upload’.

../_images/edit_code_drag_drop.png

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

../_images/save_edit.png

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.

../_images/failedd.png

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 packange installation files for accuracy.

  3. Check if the environment variables are stated and fetched correctly in the code.

Error : “Can’t reach the serivce <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

Click on Secret icon.

../_images/click_secret.png

Once you click on the Secret icon, a popup window titled “Secret” will appear.

../_images/Secret_popup.png

To create a Secret, you need to click on the “Add” icon.

../_images/create_secret.png

Then, enter a name for the Secret and click on the “Create” button.

../_images/create_secrete1.png

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

../_images/receive_secret_key.png

How to attach secret to any functions

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

../_images/click_function_name.png

Afterwards, navigate to “Function Configuration” and select “Add secret.”

../_images/click_fun_configuration.png

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

../_images/select_secret.png

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.

../_images/save_secret.png

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

../_images/see_saved_secret.png

Remove secret from function

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

../_images/remove_secret.png