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

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

../_images/package_python.png

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

../_images/python_create.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/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 want 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

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]].