user guide€¦ · custom runtime functiongraph supports custom runtimes. you can use an executable...

112
FunctionGraph User Guide Issue 01 Date 2020-06-08 HUAWEI TECHNOLOGIES CO., LTD.

Upload: others

Post on 25-Jun-2020

24 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

FunctionGraph

User Guide

Issue 01

Date 2020-06-08

HUAWEI TECHNOLOGIES CO., LTD.

Page 2: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Copyright © Huawei Technologies Co., Ltd. 2020. All rights reserved.

No part of this document may be reproduced or transmitted in any form or by any means without priorwritten consent of Huawei Technologies Co., Ltd. Trademarks and Permissions

and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.All other trademarks and trade names mentioned in this document are the property of their respectiveholders. NoticeThe purchased products, services and features are stipulated by the contract made between Huawei andthe customer. All or part of the products, services and features described in this document may not bewithin the purchase scope or the usage scope. Unless otherwise specified in the contract, all statements,information, and recommendations in this document are provided "AS IS" without warranties, guaranteesor representations of any kind, either express or implied.

The information in this document is subject to change without notice. Every effort has been made in thepreparation of this document to ensure accuracy of the contents, but all statements, information, andrecommendations in this document do not constitute a warranty of any kind, express or implied.

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. i

Page 3: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Contents

1 Overview....................................................................................................................................11.1 How FunctionGraph Works?............................................................................................................................................... 11.2 Permissions Management.................................................................................................................................................... 31.2.1 Creating a User and Granting Permissions................................................................................................................. 31.3 Building a FunctionGraph Function.................................................................................................................................. 41.3.1 Programming Models......................................................................................................................................................... 41.3.2 Creating a Deployment Package.................................................................................................................................... 51.3.3 Creating a Function.......................................................................................................................................................... 111.3.4 Environment Variables.....................................................................................................................................................171.4 Triggering a Function.......................................................................................................................................................... 181.5 Logs........................................................................................................................................................................................... 181.6 Monitoring...............................................................................................................................................................................191.6.1 Function Monitoring.........................................................................................................................................................191.6.2 Function Metrics................................................................................................................................................................ 211.7 Versions and Aliases.............................................................................................................................................................221.8 Command Line Tools........................................................................................................................................................... 231.9 FunctionGraph and Other Services................................................................................................................................. 23

2 Getting Started...................................................................................................................... 252.1 Introduction............................................................................................................................................................................ 252.2 Creating and Initializing a Function............................................................................................................................... 252.3 Configuring VPC Access...................................................................................................................................................... 302.4 Using an SMN Trigger......................................................................................................................................................... 322.5 Using a DMS Trigger............................................................................................................................................................332.6 Using an APIG Trigger......................................................................................................................................................... 352.7 Using an OBS Trigger.......................................................................................................................................................... 382.8 Using a DIS Trigger.............................................................................................................................................................. 392.9 Using a Timer Trigger.......................................................................................................................................................... 422.10 Using a Kafka Trigger........................................................................................................................................................43

3 Basic Operations.................................................................................................................... 463.1 Dashboard............................................................................................................................................................................... 463.2 Function Management........................................................................................................................................................483.3 Integrated Function Development.................................................................................................................................. 60

FunctionGraphUser Guide Contents

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. ii

Page 4: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

3.4 Dependency Management................................................................................................................................................ 683.5 Trigger Management........................................................................................................................................................... 743.6 Test Management................................................................................................................................................................. 753.7 Version and Alias Management.......................................................................................................................................783.8 Function Monitoring............................................................................................................................................................ 813.9 RI Management..................................................................................................................................................................... 85

4 Advanced Operations........................................................................................................... 894.1 Function Templates.............................................................................................................................................................. 894.2 Mounting a File System...................................................................................................................................................... 894.3 Using a Custom Runtime................................................................................................................................................... 934.4 Environment Variables........................................................................................................................................................ 994.5 Tutorials................................................................................................................................................................................. 100

5 Appendixes............................................................................................................................1025.1 Creating an Agency............................................................................................................................................................1025.2 Creating an NFS Shared Directory on ECS.................................................................................................................1035.3 Cron Expression for a Function Timer Trigger.......................................................................................................... 105

FunctionGraphUser Guide Contents

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. iii

Page 5: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

1 Overview

1.1 How FunctionGraph Works?

Process FlowPerform the following procedure to build and execute a function on theFunctionGraph console, as shown in Figure 1-1:

1. Build and deploy an application.

a. Create a function on the FunctionGraph console.b. Write service code, package it, and upload it to the function.c. Add event sources such as Simple Message Notification (SMN),

Distributed Message Service (DMS), Data Ingestion Service (DIS), andObject Storage Service (OBS) event sources to the function.When the function is triggered by a specified RESTful API or cloud serviceevent, function instances are generated to implement service functions.FunctionGraph schedules resources during the function execution.

2. View the logs and metrics of the function.You pay only for the code execution duration, and there is no charge whenyour code is not running.

FunctionGraphUser Guide 1 Overview

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 1

Page 6: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Figure 1-1 Process flow

The process is explained as follows:

1. Write code in Node.js, Python, Java, Go, C#, or PHP. For details, see theFunctionGraph Developer Guide.

2. Alternatively, edit code inline, upload a local ZIP file or JAR file, or upload aZIP file from OBS. For details, see Table 3-4.

3. Set an API or cloud service event source to trigger your function. For details,see Using an SMN Trigger, Using a DMS Trigger, Using an APIG Trigger,Using an OBS Trigger, Using a DIS Trigger, Using a Timer Trigger, andUsing a Kafka Trigger.

4. During function execution, FunctionGraph scales automatically based on thenumber of requests without the need for any configurations. For details aboutthe maximum number of function instances that can be run concurrently, seeQuotas and Usage Restrictions.

5. View the run logs of your function. For details, see Querying Logs.6. View the graphical monitoring information about your function. For details,

see Viewing Function Metrics.7. After function execution, you will be billed based on the compute time you

consume. The billing is down to the 100 ms range.

FunctionGraphUser Guide 1 Overview

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 2

Page 7: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

1.2 Permissions Management

1.2.1 Creating a User and Granting PermissionsThis chapter describes how to use Identity and Access Management (IAM) toimplement fine-grained permissions control for your FunctionGraph resources.With IAM, you can:

● Create IAM users for employees based on the organizational structure of yourenterprise. Each IAM user has their own security credentials, providing accessto FunctionGraph resources.

● Grant only the permissions required for users to perform a task.● Entrust a HUAWEI CLOUD account or cloud service to perform professional

and efficient O&M on your FunctionGraph resources.

If your HUAWEI CLOUD account does not need individual IAM users, then youmay skip over this chapter.

This section describes the procedure for granting permissions (see Figure 1-2).

Prerequisites

Before assigning permissions to user groups, you should learn about the systempermissions listed in Permissions Description. For the system policies of otherservices, see System Permissions.

Process Flow

Figure 1-2 Process for granting FunctionGraph permissions

FunctionGraphUser Guide 1 Overview

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 3

Page 8: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

1. Creating a User Group and Assigning PermissionsCreate a user group on the IAM console, and assign the FunctionGraphInvoker role to the group.

2. Creating an IAM UserCreate a user on the IAM console and add the user to the group created in 1.

3. Logging In Using an IAM User and Verifying PermissionsLog in to the FunctionGraph console as the created user, and verify that itonly has read permissions for FunctionGraph.– Choose Service List > FunctionGraph. Then click Create Function on the

FunctionGraph console. If a message appears indicating insufficientpermissions to perform the operation, the FunctionGraph Invoker rolehas already taken effect.

– Choose any other service in the Service List. If a message appearsindicating insufficient permissions to access the service, theFunctionGraph Invoker role has already taken effect.

1.3 Building a FunctionGraph Function

1.3.1 Programming Models

Node.js

For details about Node.js 6.10, Node.js 10.16, Node.js 12.13, and Node.js 8.10programming, SDK APIs, and function development, see Developing Functions inNode.js.

Python

Currently, FunctionGraph supports Python 2.7 and Python 3.6. For details aboutPython function APIs, SDK APIs, and function development, see DevelopingFunctions in Python.

Java

For details about Java function APIs, SDK APIs, and function development, seeDeveloping Functions in Java.

Go

FunctionGraph supports only Go 1.8.3 currently. For details about Go functionAPIs, SDK APIs, and function development, see Developing Functions in Go.

C#

FunctionGraph supports C# (.NET Core 2.0), C# (.NET Core 2.1), and C# (.NETCore 3.1). For details about C# function APIs, SDK APIs, and function development,see Developing Functions in C#.

FunctionGraphUser Guide 1 Overview

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 4

Page 9: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

PHPFunctionGraph supports PHP 7.3. For details about PHP function APIs, SDK APIs,and function development, see Developing Functions in PHP.

Custom RuntimeFunctionGraph supports custom runtimes. You can use an executable file namedbootstrap to include a runtime in your function deployment package. The runtimeruns the function's handler method when the function is invoked. For moreinformation about custom runtimes, see Using a Custom Runtime.

1.3.2 Creating a Deployment PackageTo create a function, you must create a deployment package, a ZIP file thatincludes your code and all dependencies. You can create a deployment packagelocally or edit code on the FunctionGraph console. If you edit code inline,FunctionGraph automatically creates and uploads a deployment package for yourfunction. FunctionGraph allows you to edit function code in the same way asmanaging a project. You can create and edit files and file folders. After you uploada ZIP code package, you can view and edit the code on the console.

Table 1-1 lists the code entry modes supported by FunctionGraph for eachruntime.

Table 1-1 Code entry modes

Runtime Editing CodeInline

Uploading aZIP File

Uploading aJAR File

Uploading aZIP File fromOBS

Node.js Supported Supported Notsupported

Supported

Python Supported Supported Notsupported

Supported

Java Notsupported

Supported Supported Supported

Go Notsupported

Supported Notsupported

Supported

C# Notsupported

Supported Notsupported

Supported

PHP Supported Supported Notsupported

Supported

Custom Supported Supported Notsupported

Supported

FunctionGraphUser Guide 1 Overview

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 5

Page 10: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Node.js

Editing Code Inline

FunctionGraph provides an SDK for editing code in Node.js. If your custom codeuses only the SDK library, you can edit code using the inline editor on theFunctionGraph console. After you edit code inline and upload it to FunctionGraph,the console compresses your code and the related configurations into adeployment package that FunctionGraph can run.

When you edit code inline, FunctionGraph displays all your input information inplain text. For security purposes, do not include sensitive information in your code.

Uploading a Deployment Package

If your code uses other resources, such as a graphic library for image processing,you need to create a deployment package, and then upload the package to theFunctionGraph console. You can upload a Node.js deployment package in twoways.

NO TICE

When creating a ZIP file, place the handler file under the root directory to ensurethat your code can be run normally after decompressing.

● Uploading a local deployment package

After creating a ZIP deployment package, upload it to the FunctionGraphconsole. If the package size exceeds 10 MB, upload the package using an OBSbucket. For details about function resource limits, see Quotas and UsageRestrictions.

● Uploading a deployment package using an OBS bucket

After creating a ZIP deployment package, upload it to an OBS bucket in thesame region as your FunctionGraph, and then paste the link URL of the OBSbucket into the function. The maximum size of the ZIP file that can beuploaded to OBS is 10 MB. For details about function resource limits, seeQuotas and Usage Restrictions.

Python

Editing Code Inline

FunctionGraph provides an SDK for editing code in Python. If your custom codeuses only the SDK library, you can edit code using the inline editor on theFunctionGraph console. After you edit code inline and upload it to FunctionGraph,the console compresses your code and the related configurations into adeployment package that FunctionGraph can run.

FunctionGraphUser Guide 1 Overview

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 6

Page 11: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

When you edit code inline, FunctionGraph displays all your input information inplain text. For security purposes, do not include sensitive information in your code.

Uploading a Deployment Package

If your code uses other resources, such as a graphic library for image processing,you need to create a deployment package, and then upload the package to theFunctionGraph console. You can upload a Python deployment package in twoways.

NO TICE

● When creating a ZIP file, place the handler file under the root directory toensure that your code can be run normally after decompressing.

● When you write code in Python, do not name your package with the samesuffix as a standard Python library, such as json, lib, and os. Otherwise, an errorwill be reported indicating a module loading failure.

● Uploading a local deployment packageAfter creating a ZIP deployment package, upload it to the FunctionGraphconsole. If the package size exceeds 10 MB, upload the package using an OBSbucket.For details about function resource limits, see Quotas and UsageRestrictions.

● Uploading a deployment package using an OBS bucketAfter creating a ZIP deployment package, upload it to an OBS bucket in thesame region as your FunctionGraph, and then paste the link URL of the OBSbucket into the function. The maximum size of the ZIP file that can beuploaded to OBS is 10 MB.For details about function resource limits, see Quotas and UsageRestrictions.

JavaJava is a compiled language, which does not support editing code inline. You canonly upload a local deployment package using a ZIP file or an independent JARfile.

Uploading a JAR File

● If your function does not use any dependencies, you can upload a JAR file.● If your function uses other dependencies, you can upload them to an OBS

bucket, and then paste the link URL of the OBS bucket into your function andupload the function JAR file.

Uploading a ZIP File

If your function uses dependencies, compress the dependencies and the functionJAR file into a ZIP file, and then upload the ZIP file.

FunctionGraphUser Guide 1 Overview

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 7

Page 12: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

You can upload a Java deployment package in two ways.

NO TICE

When creating a ZIP file, place the handler file under the root directory to ensurethat your code can be run normally after decompressing.

● Uploading a local deployment packageAfter creating a ZIP deployment package, upload it to the FunctionGraphconsole. If the package size exceeds 10 MB, upload the package using an OBSbucket.For details about function resource limits, see Quotas and UsageRestrictions.

● Uploading a deployment package using an OBS bucketAfter creating a ZIP deployment package, upload it to an OBS bucket in thesame region as your FunctionGraph, and then paste the link URL of the OBSbucket into the function. The maximum size of the ZIP file that can beuploaded to OBS is 10 MB.For details about function resource limits, see Quotas and UsageRestrictions.

Go

Uploading a Deployment Package

You can only upload a Go deployment package in ZIP format, and you can uploadit in two ways.

NO TICE

When creating a ZIP file, place the handler file under the root directory to ensurethat your code can be run normally after decompressing.

● Uploading a local deployment packageAfter creating a ZIP deployment package, upload it to the FunctionGraphconsole. If the package size exceeds 10 MB, upload the package using an OBSbucket.For details about function resource limits, see Quotas and UsageRestrictions.

● Uploading a deployment package using an OBS bucketAfter creating a ZIP deployment package, upload it to an OBS bucket in thesame region as your FunctionGraph, and then paste the link URL of the OBSbucket into the function. The maximum size of the ZIP file that can beuploaded to OBS is 10 MB.For details about function resource limits, see Quotas and UsageRestrictions.

FunctionGraphUser Guide 1 Overview

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 8

Page 13: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

C#

Uploading a Deployment Package

You can only upload a C# deployment package in ZIP format, and you can uploadit in two ways.

NO TICE

When creating a ZIP file, place the handler file under the root directory to ensurethat your code can be run normally after decompressing.

● Uploading a local deployment package

After creating a ZIP deployment package, upload it to the FunctionGraphconsole. If the package size exceeds 10 MB, upload the package using an OBSbucket.

For details about function resource limits, see Quotas and UsageRestrictions.

● Uploading a deployment package using an OBS bucket

After creating a ZIP deployment package, upload it to an OBS bucket in thesame region as your FunctionGraph, and then paste the link URL of the OBSbucket into the function. The maximum size of the ZIP file that can beuploaded to OBS is 10 MB.

For details about function resource limits, see Quotas and UsageRestrictions.

PHP

Editing Code Inline

FunctionGraph provides an SDK for editing code in PHP. If your custom code usesonly the SDK library, you can edit code using the inline editor on theFunctionGraph console. After you edit code inline and upload it to FunctionGraph,the console compresses your code and the related configurations into adeployment package that FunctionGraph can run.

When you edit code inline, FunctionGraph displays all your input information inplain text. For security purposes, do not include sensitive information in your code.

Uploading a Deployment Package

If your code uses other resources, such as a graphic library for image processing,you need to create a deployment package, and then upload the package to theFunctionGraph console. You can upload a PHP deployment package in two ways.

FunctionGraphUser Guide 1 Overview

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 9

Page 14: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

NO TICE

When creating a ZIP file, place the handler file under the root directory to ensurethat your code can be run normally after decompressing.

● Uploading a local deployment packageAfter creating a ZIP deployment package, upload it to the FunctionGraphconsole. If the package size exceeds 10 MB, upload the package using an OBSbucket.For details about function resource limits, see Quotas and UsageRestrictions.

● Uploading a deployment package using an OBS bucketAfter creating a ZIP deployment package, upload it to an OBS bucket in thesame region as your FunctionGraph, and then paste the link URL of the OBSbucket into the function. The maximum size of the ZIP file that can beuploaded to OBS is 10 MB.For details about function resource limits, see Quotas and UsageRestrictions.

CustomEditing Code Inline

After you edit code inline and upload it to FunctionGraph, the console compressesyour code and the related configurations into a deployment package thatFunctionGraph can run.

When you edit code inline, FunctionGraph displays all your input information inplain text. For security purposes, do not include sensitive information in your code.

Uploading a Deployment Package

If your code uses other resources, such as a graphic library for image processing,you need to create a deployment package, and then upload the package to theFunctionGraph console. You can upload a deployment package for a customruntime in two ways.

NO TICE

When creating a ZIP file, place the handler file under the root directory to ensurethat your code can be run normally after decompressing.

● Uploading a local deployment packageAfter creating a ZIP deployment package, upload it to the FunctionGraphconsole. If the package size exceeds 10 MB, upload the package using an OBSbucket.

FunctionGraphUser Guide 1 Overview

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 10

Page 15: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

For details about function resource limits, see Quotas and UsageRestrictions.

● Uploading a deployment package using an OBS bucketAfter creating a ZIP deployment package, upload it to an OBS bucket in thesame region as your FunctionGraph, and then paste the link URL of the OBSbucket into the function. The maximum size of the ZIP file that can beuploaded to OBS is 10 MB.For details about function resource limits, see Quotas and UsageRestrictions.

1.3.3 Creating a FunctionFunctionGraph manages the compute resources required for function execution.After editing code for your function, configure compute resources on theFunctionGraph console.

You can create a function from scratch or by using an existing template.

Creating a Function from ScratchWhen creating a function from scratch, configure the basic and code informationaccording to Table 1-2 and Table 1-3. The parameters marked with an asterisk (*)are mandatory.

For environment information, retain the default values, as shown in Table 1-5.After creating the function, you can modify it by following the procedure inModifying Function Configurations.

Table 1-2 Basic information

Parameter Description

Function Name Function name.

App Select an existing app or define a newapp to which the function belongs. Youcan create multiple functions under anapp.

Agency Used to delegate FunctionGraph toaccess other cloud services. Forexample, an agency is required whenFunctionGraph accesses cloud servicessuch as OBS or SMN.

Description Description of the function.

FunctionGraphUser Guide 1 Overview

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 11

Page 16: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

● For details on how to create an agency, see Creating an Agency.● You can specify an agency to delegate FunctionGraph to access other cloud services. To

reduce unnecessary performance consumption, specify different agencies for configuringand executing a function. Figure 1-3 shows the agency options.

Figure 1-3 Setting an agency

1. Configuration agency: Specify an agency with DMS or DIS permissions for a functionthat needs to use DMS or DIS triggers. If no such agency is specified or the specifiedagency does not exist, you cannot create DMS or DIS triggers for the function.

2. After specifying a function execution agency, you can use the context method in thefunction handler to obtain a token and AK/SK for accessing other cloud services.

Table 1-3 Code information

Parameter Description

Runtime FunctionGraph supports Python 2.7,Python 3.6, Node.js 6.10, Node.js 8.10,Node.js 10.16, Node.js 12.13, Java 8,Go 1.8, C# (.NET Core 2.0), C# (.NETCore 2.1), C# (.NET Core 3.1), and PHP7.3.

FunctionGraphUser Guide 1 Overview

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 12

Page 17: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Parameter Description

Handler ● For a Node.js, Python, or PHPfunction, the handler should benamed in the format of [file name].[function name], which mustcontain a period (.).Example: myfunction.handler

● For a Java function, the handlershould be named in the format of[package name].[file name].[function name].Example:com.xxxxx.exp.Myfunction.myHandler

● For a Go function, the handlershould be named in the format of[plug-in name].[function name].The function name can contain amaximum of 128 characters andmust start with an uppercase letter.Example: function.Handler

● For a C# function, the handlershould be named in the format of[.NET assembly file name]::[namespace and class of thehandler function]::[handler functionname].Example:HelloCsharp::Example.Hello::Handler

Code Entry Mode Method of entering the function code.For details about the supported codeentry modes, see Table 1-4.

Table 1-4 Code entry modes

Runtime Code Entry Mode Description

Node.js 6.10/Node.js8.10/Node.js 10.16/Node.js 12.13

Editing code Edit code in the codebox. For moreinformation, see Table3-2.

FunctionGraphUser Guide 1 Overview

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 13

Page 18: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Runtime Code Entry Mode Description

Upload ZIP file Click Select File andupload a local codepackage toFunctionGraph. The sizeof the ZIP file to beuploaded cannot exceed10 MB. If it exceeds 10MB, upload the ZIP fileusing an OBS bucket.

Upload file from OBS Paste the link URL of theOBS bucket storing acode ZIP file.

Python 2.7/Python 3.6 Editing code Edit code in the codebox. For moreinformation, see Table3-2.

Upload ZIP file Click Select File andupload a local codepackage toFunctionGraph. The sizeof the ZIP file to beuploaded cannot exceed10 MB. If it exceeds 10MB, upload the ZIP fileusing an OBS bucket.

Upload file from OBS Paste the link URL of theOBS bucket storing acode ZIP file.

Java 8 Upload ZIP file Click Select File andupload a local codepackage toFunctionGraph. The sizeof the ZIP file to beuploaded cannot exceed10 MB. If it exceeds 10MB, upload the ZIP fileusing an OBS bucket.

Uploading a JAR File Click Select File andupload a local JAR file toFunctionGraph. The sizeof the JAR file to beuploaded cannot exceed10 MB. If it exceeds 10MB, convert it into a ZIPfile, and upload the ZIPfile using an OBS bucket.

FunctionGraphUser Guide 1 Overview

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 14

Page 19: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Runtime Code Entry Mode Description

Upload file from OBS Paste the link URL of theOBS bucket storing acode ZIP file.

Go 1.8 Upload ZIP file Click Select File andupload a local codepackage toFunctionGraph. The sizeof the ZIP file to beuploaded cannot exceed10 MB. If it exceeds 10MB, upload the ZIP fileusing an OBS bucket.

Upload file from OBS Paste the link URL of theOBS bucket storing acode ZIP file.

C#(.NET Core 2.0)/C#(.NET Core 2.1)/C#(.NET Core 3.1)

Upload ZIP file Click Select File andupload a local codepackage toFunctionGraph. The sizeof the ZIP file to beuploaded cannot exceed10 MB. If it exceeds 10MB, upload the ZIP fileusing an OBS bucket.

Upload file from OBS Paste the link URL of theOBS bucket storing acode ZIP file.

Custom Editing code Edit code in the codebox. For moreinformation, see Table3-2.

Upload ZIP file Click Select File andupload a local codepackage toFunctionGraph. The sizeof the ZIP file to beuploaded cannot exceed10 MB. If it exceeds 10MB, upload the ZIP fileusing an OBS bucket.

Upload file from OBS Paste the link URL of theOBS bucket storing acode ZIP file.

FunctionGraphUser Guide 1 Overview

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 15

Page 20: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

NO TICE

● When you write code in Python, do not name your package with the samesuffix as a standard Python library, such as json, lib, and os. Otherwise, an errorwill be reported indicating a module loading failure.

● When you edit code inline, FunctionGraph displays all your input information inplain text. For security purposes, do not include sensitive information in yourcode.

Table 1-5 Environment information

Parameter Description

Memory (MB) Memory required for executing thefunction.

Initializer If you have enabled initialization forthe function on the Code tab page, setthe initializer.The initializer should be named in thesame way as the handler. For example,for Node.js, Python, or PHP functions,specify the initializer as [file name].[initialization function name].

Initialization Timeout (s) Maximum duration the function canbe initialized. Set this parameter if youhave enable initialization for thefunction.The value ranges from 1s to 300s.

Execution Timeout (s) Maximum duration the function canbe executed.The value ranges from 3s to 900s.

● When creating a function, you can retain the default values for the memory, timeout,and environment variables. After creating the function, you can modify these settingsaccording to Modifying Function Configurations.

● After a function is created, the default version is LATEST. Each function has the LATESTversion.

● FunctionGraph bills based on the memory and execution duration of your function.Please set the memory and timeout based on service requirements.

Creating a Function Using a TemplateFunctionGraph provides built-in function templates for typical scenarios. Thesetemplates contain code, configurations, environment, and trigger information.After you choose a template, FunctionGraph automatically loads the function

FunctionGraphUser Guide 1 Overview

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 16

Page 21: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

information, enabling you to quickly build an application. For details, see FunctionTemplates.

1.3.4 Environment VariablesYou can set environment variables to dynamically pass settings to your functioncode and libraries without making any changes to your code, as shown in Figure1-4.

Figure 1-4 Setting environment variables

Environment variables are key-value pairs that you can create and modify as partof your function configurations in FunctionGraph. FunctionGraph provides key-value pairs to your function code by using standard APIs supported by the relevantruntime, such as process.env for Node.js functions.

Environment variables can help libraries know which directory to install files in,where to store outputs, and how to store connection and logging settings. Thesesettings are decoupled from the application logic, so you do not need to updateyour function code when you change the settings.

● Environment variables are user-defined key-value pairs for storing functionsettings. A key can contain letters, digits, and underscores (_), and must startwith a letter.

● You can create a maximum of 20 environment variables, with not more than2048 characters.

● FunctionGraph displays all your input information in plain text. For securitypurposes, do not include sensitive information in your code.

FunctionGraphUser Guide 1 Overview

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 17

Page 22: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

1.4 Triggering a FunctionFunctionGraph applications are composed of functions and event sources. Eventsources are cloud services or user-defined applications that publish events, andfunctions are custom code for processing events.

FunctionGraph functions can be triggered by multiple cloud services. For details,see Supported Event Sources. After you configure event sources to trigger yourfunctions, FunctionGraph automatically invokes the functions when events occur.

FunctionGraph invokes functions in the following modes:

● Synchronous invocation

Clients wait for explicit responses to their requests from a function. Responsesare returned only after the function is invoked.

● Asynchronous invocation

Clients do not care about the function invocation results of their requests.After receiving a request, FunctionGraph puts it in a queue, returns aresponse, and processes requests in idle state.

If a function is invoked asynchronously and is throttled, FunctionGraphautomatically retries the throttled event, with delays between retries.Asynchronous events are queued before they are used to invoke a function.

With OBS triggers, functions are invoked asynchronously.

Table 1-6 lists the function invocation modes for supported event sources.

Table 1-6 Function invocation modes

Event Source Invocation Mode

SMN Asynchronous invocation

DMS Asynchronous invocation

API Gateway Synchronous invocation

OBS Asynchronous invocation

DIS Asynchronous invocation

Timer Asynchronous invocation

DMS for Kafka Synchronous invocation

1.5 LogsFunctionGraph is interconnected with Log Tank Service (LTS), allowing you to viewfunction logs without the need for any configurations.

FunctionGraphUser Guide 1 Overview

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 18

Page 23: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Function LogsOn the FunctionGraph console, view function logs in the following ways:

● Viewing logs on the execution result pageAfter creating a function, test it and view test logs on the execution resultpage, as shown in Figure 1-5. For details, see Test Management.The execution result page displays a maximum of 4 KB logs. To view morelogs of the function, go to the Logs tab page.

Figure 1-5 Test logs

● Viewing logs on the Logs tab pageOn the Logs tab page of a function, view all logs of the function and thecontext information of the logs. For details, see Querying Logs.

Downloading LogsAfter querying the logs of a function version within a specified date range, youcan download the logs for further analysis.

A maximum of 5000 logs can be downloaded at a time. When querying logs, select aproper time range to avoid the loss of logs.

1.6 Monitoring

1.6.1 Function MonitoringFunctionGraph is interconnected with Cloud Eye, allowing you to view functionmetrics without the need for any configurations.

Function MetricsFunctionGraph presents the monitoring information of all functions or of a singlefunction created using your account.

● Account-level metricsThe Dashboard page allows you to view metrics of all functions. The metricsinclude invocation count, execution duration (including the maximum,

FunctionGraphUser Guide 1 Overview

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 19

Page 24: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

average, and minimum durations), invocation errors, and throttledinvocations, as shown in Figure 1-6. For details, see Dashboard.

Figure 1-6 Account-level metrics

● Function-level metricsFunctionGraph differentiates the metrics of a function by version, allowingyou to query the metrics of a specific function version.View the metrics on the Monitoring tab page of a function. The metricsinclude invocation count, execution duration (including the maximum,average, and minimum durations), invocation errors, and throttledinvocations, as shown in Figure 1-7. For details, see Viewing FunctionMetrics.

Figure 1-7 Function-level metrics

– Creating an alarm rule

FunctionGraphUser Guide 1 Overview

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 20

Page 25: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Create an alarm rule for a function to report metrics to Cloud Eye for bettermonitoring.On the Monitoring tab page of the function details page, click Create AlarmRule. Select a metric and set an alarm policy. After the alarm rule is created,click View details in the displayed message to view details of the alarm ruleon the Cloud Eye console. On the Alarm Rules page, click View Graph in theOperation column of the alarm rule to view function metrics. Figure 1-8shows the function monitoring graph.

Figure 1-8 Viewing the monitoring graph

1.6.2 Function Metrics

Introduction

This section describes the function metrics that FunctionGraph can report to theCloud Eye service. You can view function metrics and alarms by using the CloudEye console or calling APIs.

Namespace

SYS.FunctionGraph

Function Metrics

Metric Name Description ValueRange

MonitoredObject

Monitoring Period(Minute)

count Invocations

Number offunctioninvocationsUnit: Count

≥ 0counts

Functions

1

failcount Errors Number ofinvocation errorsUnit: Count

≥ 0counts

Functions

1

FunctionGraphUser Guide 1 Overview

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 21

Page 26: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Metric Name Description ValueRange

MonitoredObject

Monitoring Period(Minute)

rejectcount Throttles Number offunction throttlesUnit: Count

≥ 0counts

Functions

1

duration Averageduration

Average durationof functioninvocationUnit: ms

≥ 0 ms Functions

1

maxDuration

Maximumduration

Maximumduration offunctioninvocationUnit: ms

≥ 0 ms Functions

1

minDuration Minimumduration

Minimum durationof functioninvocationUnit: ms

≥ 0 ms Functions

1

DimensionsKey Value

package-functionname App name-Function nameExample: default-myfunction_Python

1.7 Versions and Aliases

Version ControlFunctionGraph allows you to publish one or more versions throughout thedevelopment, test, and production processes to manage your function code. Thecode and environment variables of each version are saved as a snapshot. Thesettings of a published version cannot be modified.

To meet the changing application and configuration requirements, you can createnew versions for your function and update the environment variables beforepublishing the newest version. The current version of a function is LATEST.

For details about version management, see Managing Versions.

FunctionGraphUser Guide 1 Overview

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 22

Page 27: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Creating a Function Alias

You can create an alias for a specific function version. If you need to roll back to aprevious version, use the corresponding alias to represent the version instead ofmodifying the function code.

The same alias can be bound to two versions to distribute traffic according to aspecified weight.

For details about alias management, see Managing Aliases.

1.8 Command Line ToolsFunctionGraph provides the command line interface (CLI) and Huawei ServerlessSandbox (HSS) tools.

● CLI: manages functions, triggers, and aliases, and invokes functions.For details on how to download, configure, and use CLI, see Introduction toCLI.

● HSS: tests functions locally, verifies Huawei Serverless Application Model(HSAM) templates, and generates valid sample payloads for different eventsources.For details on how to download, configure, and use HSS, see Introduction toHSS.

1.9 FunctionGraph and Other ServicesFunctionGraph is interconnected with other cloud services to implement differentfunctions.

Cloud Eye

Cloud Eye is a multi-dimensional monitoring platform that monitors resourcessuch as Elastic Cloud Servers (ECSs) and bandwidth. With Cloud Eye, you can trackthe resource usage and running status of services running on the cloud platform,receive alarm notifications about errors, and react to changes immediately to keepyour services running smoothly.

FunctionGraph is interconnected with Cloud Eye to monitor the execution offunctions and workflows in real time.

● For details about the function metrics that can be monitored by Cloud Eye,see Function Monitoring.

● For details on how to view function metrics, see Function Monitoring.

CTS

CTS records operations of the resources created using your account. The operationrecords can help you perform security analysis, track resource changes, auditcompliance, and locate faults. To store operation records for a longer time, youcan subscribe to OBS and synchronize operation records to OBS in real time.

FunctionGraphUser Guide 1 Overview

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 23

Page 28: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

● FunctionGraph operations that can be recorded by CTSWith CTS, you can record operations associated with FunctionGraph for laterquery, audit, and backtrack operations. Table 1-7 lists the FunctionGraphoperations that can be recorded by CTS.

Table 1-7 FunctionGraph operations

Operation Resource Type Event Name

Creating a function Functions CreateFunction

Deleting a function Functions DeleteFunction

Modifying functioninformation

Functions ModifyFunctionMeta-data

Publishing a functionversion

FunctionVersions PublishFunctionVersion

Deleting a functionversion alias

FunctionVersionsAlias DeleteVersionAlias

Deleting a functiontrigger

Trigger DeleteTrigger

Creating a functiontrigger

Trigger CreateTrigger

Disabling a functiontrigger

Trigger DisabledTrigger

Enabling a functiontrigger

Trigger enabledTrigger

Executing a function FunctionInstance invokeFunction

● Audit logs

CTS starts recording operations on cloud resources once being enabled. TheCTS console stores the operation records for the last seven days. For details onhow to query operation records, see Querying Real-Time Traces.

FunctionGraphUser Guide 1 Overview

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 24

Page 29: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

2 Getting Started

2.1 IntroductionThis chapter assumes that you have the permissions required for all involvedoperations. For details about permissions, see Permissions Description.

2.2 Creating and Initializing a FunctionThis section describes how to create and test a HelloWorld function supportinginitialization.

Creating a Function

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click Create Function.

Step 3 Configure the function information by performing the following steps:

1. Configure the basic information according to Table 2-1. The parametermarked with an asterisk (*) is mandatory.

Table 2-1 Basic information

Parameter Description

Template This example uses no template.If you need to use a template, seeFunction Templates.

FunctionGraphUser Guide 2 Getting Started

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 25

Page 30: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Parameter Description

*Function Name Name of the function, which mustmeet the following requirements:– Consists of 1 to 60 characters,

and can contain letters, digits,hyphens (-), and underscores (_).

– Starts with a letter and ends witha letter or digit.

Enter HelloWorld.

*App App to which the function belongs.You can create multiple functionsunder an app. An app name mustmeet the following requirements:– Consists of 1 to 60 characters,

and can contain letters, digits,hyphens (-), and underscores (_).

– Starts with a letter and ends witha letter or digit.

Select default, the default app onFunctionGraph.

Agency An agency is required ifFunctionGraph accesses other cloudservices. For details on how to createan agency, see Creating an Agency.No agency is required ifFunctionGraph does not access anycloud services.For this example, select Use noagency.

Description Description of the function, whichcannot exceed 512 characters. Entertest.

FunctionGraphUser Guide 2 Getting Started

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 26

Page 31: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

– You can specify an agency to delegate FunctionGraph to access other cloudservices. To reduce unnecessary performance consumption, specify differentagencies for configuring and executing a function. Figure 2-1 shows the agencyoptions.

Figure 2-1 Setting agencies

1. Configuration agency: Specify an agency with DMS or DIS permissions for afunction that needs to use DMS or DIS triggers. If no such agency is specified orthe specified agency does not exist, you cannot create DMS or DIS triggers forthe function.

2. After specifying a function execution agency, you can use the context methodin the function handler to obtain a token and AK/SK for accessing other cloudservices.

2. Configure the code information according to Table 2-2. The parametermarked with an asterisk (*) is mandatory.

Table 2-2 Code information

Parameter Description

Runtime FunctionGraph supports Python 2.7,Python 3.6, Node.js 6.10, Node.js8.10, Node.js 10.16, Node.js 12.13,Java 8, Go 1.8, C# (.NET Core 2.0),C# (.NET Core 2.1), C# (.NET Core3.1), and PHP 7.3.For this example, select Node.js6.10.

*Handler For a Node.js function, the handlershould be named in the format of[file name].[function name], whichmust contain a period (.).Enter index.handler, which indicatesthat the file name is index.js andthe function name is handler.

Code Entry Mode Select Edit code inline, and use thedisplayed sample code.

FunctionGraphUser Guide 2 Getting Started

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 27

Page 32: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

NO TICE

When you write code in Python, do not name your package with the samesuffix as a standard Python library, such as json, lib, and os. Otherwise, anerror will be reported indicating a module loading failure.

When you edit code inline, FunctionGraph displays all your input informationin plain text. For security purposes, do not include sensitive information inyour code.

The sample code can obtain test events and print the test event information. The codeis as follows:exports.handler = function (event, context, callback) { const error = null; const output = `Hello message: ${JSON.stringify(event)}`; callback(error, output);}

Step 4 In the right pane of the page, review the function configuration and billinginformation, and click Create Now. Figure 2-2 shows the details.

Figure 2-2 Creating a function

FunctionGraphUser Guide 2 Getting Started

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 28

Page 33: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

After creating the function, set the memory to 128 MB and the timeout to 3s. To modifythe configurations, see Modifying Function Configurations.

----End

Enabling Function InitializationIf initialization is enabled for a function, the function will be initialized by invokingthe specified initializer, and then executed to process requests by invoking thehandler. For details on how to create a function, see Creating a Function.

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click the name of the created function.

Step 3 On the displayed function details page, enable Initialization, and configure thecode information, as shown in Figure 2-3.

Figure 2-3 Setting an initializer

● Set the initializer in the same way as the handler. For example, for Node.js or Pythonfunctions, specify the initializer as [file name].[initialization function name].

● For details on how to configure the code information, see Table 1-3.

Step 4 Click the Configuration tab, set the initialization timeout, as shown in Figure 2-4.

FunctionGraphUser Guide 2 Getting Started

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 29

Page 34: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Figure 2-4 Setting the initialization timeout

● The value ranges from 1s to 300s.● For details on how to configure the environment information, see Table 1-5.

Step 5 Click Save in the upper right corner to save the initialization settings.

----End

Testing the FunctionFor details about how to configure test events and test functions, see TestManagement.

2.3 Configuring VPC AccessFunctions can be configured to access resources in your Virtual Private Clouds(VPCs) or to access the Internet using elastic IP addresses bound through sourcenetwork address translation (SNAT).

Configuring VPC AccessTo configure VPC access for a function, perform the following steps:

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Create a function by following the instructions in Creating and Initializing aFunction.

Step 3 Click the name of the created function.

Step 4 On the displayed function details page, click the Configuration tab, enable VPCAccess, and select a VPC and subnet.

FunctionGraphUser Guide 2 Getting Started

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 30

Page 35: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

1. For details on how to create a VPC and subnet, see Creating a VPC.2. Specify an agency with VPC administrator permissions for the function. For details, see

Creating an Agency.3. All functions under a project can be bound to a maximum of five different subnets. To

bind more different subnets, submit a service ticket to increase the quota.

Step 5 Click Save.

----End

Example

The following is an example of configuring VPC access to connect to a DistributedCache Service (DCS) Redis instance.

Step 1 On the DCS console, view the VPC and subnet of the DCS Redis instance. If noRedis instances are available, purchase one immediately.

Step 2 On the FunctionGraph console, configure VPC access for the function as follows:● VPC Access: Enable VPC access.● VPC: Select the VPC queried in Step 1.● Subnet: Select the subnet queried in Step 1.

Step 3 After the configuration is complete, use the following code to access the Redisinstance:# -*- coding:utf-8 -*-import redis

def handler (event, context): r = redis.StrictRedis(host='192.168.1.143', port=6379, db=0) r.set('product', 'FunctionGraph') print r.keys('*') print r.get('product')

----End

Accessing the Internet from a VPCBy default, functions deployed in a VPC are isolated from the Internet. If afunction needs to access both internal and external networks, you can add an NATgateway for the VPC.

Prerequisites

1. You have already created a VPC and subnet according to Creating a VPC.2. You have obtained an elastic IP address according to Assigning an EIP.

Perform the following procedure to create an NAT gateway:

Step 1 Log in to the NAT Gateway console, and click Buy NAT Gateway.

Step 2 On the displayed page, specify the gateway information and select a VPC andsubnet (for example, vpc-01). For details, see Buying a NAT Gateway.

Step 3 On the NAT gateway details page, click Add SNAT Rule and click OK.

----End

FunctionGraphUser Guide 2 Getting Started

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 31

Page 36: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

2.4 Using an SMN TriggerThis section describes how to create an SMN trigger and publish a message totrigger a function.

For details about the SMN event source, see Supported Event Sources.

Prerequisites● You have created an SMN topic, for example, smn-test. For details, see

Creating a Topic.● You have created a FunctionGraph function. For details, see Creating and

Initializing a Function.

Creating an SMN Trigger

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click the HelloWorld function.

Step 3 On the function details page that is displayed, click the Triggers tab.

Step 4 Click Create Trigger.

Step 5 Set the following parameters:● Trigger Type: Select SMN.● Topic Name: Select a topic, for example, smn-test.

Step 6 Click OK.

After the SMN trigger is created, a subscription is generated for the corresponding topic onthe SMN console.

----End

Publishing a Message to Trigger the FunctionOn the SMN console, publish a message to the smn-test topic. For details, seePublishing a Text Message.

Table 2-3 describes the parameters required for publishing a message.

Table 2-3 Parameters required for publishing a message

Parameter Description

Subject Enter SMN-Test.

Message Format Select Text.

Message Enter {"message":"hello"}.

FunctionGraphUser Guide 2 Getting Started

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 32

Page 37: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

After message publishing, the function is triggered automatically. For details about exampleevents, see Supported Event Sources.

Viewing the Execution Result

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click the HelloWorld function.

Step 3 On the function details page that is displayed, click the Logs tab to query thefunction running logs.

Step 4 Click View Context in the same row as a log to view log details.

----End

2.5 Using a DMS TriggerThis section describes how to create a DMS trigger and message to trigger afunction.

For details about the DMS event source, see Supported Event Sources.

PrerequisitesBefore creating a DMS trigger, make sure you have prepared the following:

● You have created a message queue and consumer group, for example, thequeue-test queue and the group-dms consumer group. For details, seeCreating a Queue and Creating a Consumer Group.

● You have created a FunctionGraph function. For details, see Creating andInitializing a Function.

Setting an AgencyBefore creating a DMS trigger, set an agency to delegate FunctionGraph to accessDMS. If no agency is set, FunctionGraph will not be able to load the createdmessage queue or the message queue will be unavailable. For details on how tocreate an agency, see Creating an Agency.

Since you did not specify an agency while creating the HelloWorld function,specify one first.

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click the HelloWorld function.

Step 3 On the function details page that is displayed, click the Configuration tab.

Step 4 Set the agency to serverless-trust created in Creating an Agency. Click Save.

----End

FunctionGraphUser Guide 2 Getting Started

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 33

Page 38: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Creating a DMS Trigger

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click the HelloWorld function.

Step 3 On the function details page that is displayed, click the Triggers tab.

Step 4 Click Create Trigger.

Step 5 Set the following parameters:

● Trigger Type: Select DMS.

● Queue Name: Select a queue, for example, queue-test.

● Consumer Group: Select a consumer group, for example, group-dms.

● Pull Period: Set an interval at which the DMS trigger will poll for messages.

Step 6 Click OK.

----End

Creating a Message to Trigger the Function

Step 1 Log in to the DMS console, and choose Queue Manager in the navigation pane.

Step 2 On the Queue Manager page, click queue-test.

Step 3 Click Create Message.

Step 4 In the Create Message dialog box, configure the message information accordingto Table 2-4.

Table 2-4 Message information

Parameter Description

Message Body Enter {"message":"hello"}.

Message Labels For this example, leave this field blank.

Message Attributes For this example, leave this field blank.

For details about the parameters required for creating a message, see Creating a Message.

Step 5 Click OK.

Step 6 On the Consumer Groups tab page, check the value of Messages Available inthe same row as group-dms.

FunctionGraphUser Guide 2 Getting Started

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 34

Page 39: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

The DMS trigger polls for messages based on the pull period set in Creating a DMSTrigger. When messages are detected, they are retrieved to trigger the function. For detailsabout example events, see Supported Event Sources.

----End

Viewing the Execution Result

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click the HelloWorld function.

Step 3 On the function details page that is displayed, click the Logs tab to query thefunction running logs.

Step 4 Click View Context in the same row as a log to view log details.

----End

2.6 Using an APIG TriggerThis section describes how to create an APIG trigger and use the generated API toinvoke a function.

For details about the APIG event source, see Supported Event Sources.

PrerequisitesYou have created an API group, for example, APIGroup_test. For details, seeCreating an API Group.

Creating an APIG Trigger

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click Create Function.

Step 3 Set the following parameters:● Template: Select Create from scratch.● Function Name: Enter a function name, for example, apig.● App: Select default.● Agency: Select Use no agency.● Description: Enter additional information about the function. This parameter

is optional.● Runtime: Select Python 2.7.● Handler: Enter index.handler.● Code Entry Mode: Select Edit code inline and enter the code shown below.

# -*- coding:utf-8 -*-import json

FunctionGraphUser Guide 2 Getting Started

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 35

Page 40: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

def handler (event, context): body = "<html><title>Functiongraph Demo</title><body><p>Hello, FunctionGraph!</p></body></html>" print(body) return { "statusCode":200, "body":body, "headers": { "Content-Type": "text/html", }, "isBase64Encoded": False }

Step 4 Click Create Now.

Step 5 On the Triggers tab page, click Create Trigger.

Step 6 Configure the trigger information.

Table 2-5 Trigger information

Parameter Description

Trigger Type Select APIG.

API Name Enter an API name, for example, API_apig.

API Group An API group is a collection of APIs. You can manage APIsby API group.Select APIGroup_test.

Environment An API can be called in different environments, such asproduction, test, and development environments. APIGateway provides the environment management function,which allows you to define different request paths for anAPI in different environments.To ensure that the API can be called, select RELEASE.

SecurityAuthentication

There are three authentication modes:● App: AppKey and AppSecret high security authentication.

This authentication mode is recommended. For details,see App Authentication.

● IAM: IAM medium security authentication. This modegrants access to public cloud users only. For details, seeIAM Authentication.

● None: no authentication required. Access is granted toall users.

Select None.

Protocol There are two types of protocols:● HTTP● HTTPSSelect HTTPS.

Timeout (ms) Enter 5000.

FunctionGraphUser Guide 2 Getting Started

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 36

Page 41: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Step 7 Click OK.

Figure 2-5 APIG trigger

1. The URL of the APIG trigger is https://0ed9f61512d34982917a4f3cfe8ddd5d.apig.xxx.xxx.com/apig.

2. After the APIG trigger is created, an API named API_apig is generated on the APIGateway console. You can click the API name in the trigger list to go to the API Gatewayconsole.

----End

Invoking the Function

Step 1 Enter the URL (see Figure 2-6) of the APIG trigger in the address bar of a browser,and press Enter.

Figure 2-6 APIG trigger URL

Step 2 After the function is executed, check the execution result, as shown in Figure 2-7.

Figure 2-7 Return result

----End

Viewing the Execution Result

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

FunctionGraphUser Guide 2 Getting Started

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 37

Page 42: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Step 2 Click the name of the apig function to go to the function details page.

Step 3 On the function details page that is displayed, click the Logs tab to query thefunction running logs.

Step 4 Click View Context in the same row as a log to view log details.

----End

2.7 Using an OBS TriggerThis section describes how to create an OBS trigger and upload an image packageto a specified OBS bucket to trigger a function.

For details about the OBS event source, see Supported Event Sources.

Prerequisites

Before creating an OBS trigger, make sure you have prepared the following:

● You have created a FunctionGraph function. For details, see Creating andInitializing a Function.

● You have created an OBS bucket, for example, obs_cff. For details, seeCreating a Bucket.

Creating an OBS Trigger

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click the HelloWorld function.

Step 3 On the function details page that is displayed, click the Triggers tab.

Step 4 Click Create Trigger.

Step 5 Set the following parameters:● Trigger Type: Select OBS.● Bucket Name: Specify the OBS bucket to be used as an event source, for

example, obs-cff.● Events: Select events that will trigger the function. For this example, select

Put, Post, and Delete. When files are updated, uploaded, or deleted in theobs_cff bucket, the function is triggered.

● Event Notification Name: Specify the name of the event notification to besent by SMN when an event occurs.

● Prefix: Enter a keyword for limiting notifications to those about objects whosenames start with the matching characters. This limit can be used to filter thenames of OBS objects.

● Suffix: Keyword for limiting notifications to those about objects whose namesend with the matching characters. This limit can be used to filter the namesof OBS objects.

FunctionGraphUser Guide 2 Getting Started

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 38

Page 43: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Step 6 Click OK.

----End

Triggering the Function

On the OBS console, upload an image ZIP package to the obs-cff bucket. Fordetails, see Uploading a File.

After the ZIP package is uploaded to the obs-cff bucket, the HelloWorld function istriggered.

Viewing the Execution Result

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click the HelloWorld function.

Step 3 On the function details page that is displayed, click the Logs tab to query thefunction running logs.

Step 4 Click View Context in the same row as a log to view log details.

----End

2.8 Using a DIS TriggerThis section describes how to create a DIS trigger for a function, and configure aDIS event by using the built-in event template to trigger the function.

For details about the DIS event source, see Supported Event Sources.

Prerequisites

Before creating a DIS trigger, make sure you have prepared the following:

● You have created a FunctionGraph function. For details, see Creating andInitializing a Function.

● You have created a DIS stream, for example, dis-function. For details, seeCreating a DIS Stream.

Setting an Agency

Before creating a DIS trigger, set an agency to delegate FunctionGraph to accessDIS. For details on how to create an agency, see Creating an Agency.

Since you did not specify an agency while creating the HelloWorld function,specify one first.

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

FunctionGraphUser Guide 2 Getting Started

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 39

Page 44: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Step 2 Click the HelloWorld function.

Step 3 On the function details page that is displayed, click the Configuration tab.

Step 4 Set the agency to serverless-trust created in Creating an Agency.

Step 5 Click Save.

----End

Creating a DIS Trigger

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click the HelloWorld function.

Step 3 On the function details page that is displayed, click the Triggers tab.

Step 4 Click Create Trigger.

Step 5 Set the following parameters:

● Trigger Type: Select DIS.

● Stream Name: Select a DIS stream, for example, dis-function.

● Starting Position: Specify a position in the specified stream from which tostart reading data.

– TRIM_HORIZON: Data is read from the earliest valid records that arestored in the partition.

– LATEST: Data is read just after the most recent record in the partition.This setting ensures that you always read the most recent data in thepartition.

● Pull Period: Set a period for pulling data from the stream.

● Serial Data Processing: If this option is selected, FunctionGraph pulls datafrom the stream only after previous data is processed. If this option is notselected, FunctionGraph pulls data from the stream as long as the pull periodends.

Step 6 Click OK.

----End

Configuring a DIS Event to Trigger the Function

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click the HelloWorld function.

Step 3 On the function details page that is displayed, select a version and choose Selecttest event > Configure test event.

Step 4 Set the parameters described in Table 2-6 and click Save.

FunctionGraphUser Guide 2 Getting Started

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 40

Page 45: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Table 2-6 Test event information

Parameter Description

Configure Test Event You can choose to create a test event or edit anexisting one.Use the default option Create new test event.

Event Template Select dis-event-template.

Event Name An event name can contain a maximum of 25characters. Only letters and digits are allowed.Enter dis-test.

Event data The system automatically loads the built-in DISevent template, which is used in this examplewithout modifications. The code in this template isas follows:

The event template is as follows:{ "ShardID": "shardId-0000000000", "Message": { "next_partition_cursor": "eyJnZXRJdGVyYXRvclBhcmFtIjp7InN0cmVhbS1uYW1lIjoiZGlzLXN3dGVzdCIsInBhcnRpdGlvbi1pZCI6InNoYXJkSWQtMDAwMDAwMDAwMCIsImN1cnNvci10eXBlIjoiVFJJTV9IT1JJWk9OIiwic3RhcnRpbmctc2VxdWVuY2UtbnVtYmVyIjoiNCJ9LCJnZW5lcmF0ZVRpbWVzdGFtcCI6MTUwOTYwNjM5MjE5MX0", "records": [ { "partition_key": "shardId_0000000000", "data": "d2VsY29tZQ==", "sequence_number": "0" }, { "partition_key": "shardId_0000000000", "data": "dXNpbmc=", "sequence_number": "1" }, { "partition_key": "shardId_0000000000", "data": "RnVuY3Rpb25TdGFnZQ==", "sequence_number": "2" }, { "partition_key": "shardId_0000000000", "data": "c2VydmljZQ==", "sequence_number": "3" } ], "millis_behind_latest": "" }, "Tag": "latest", "StreamName": "dis-swtest"}

FunctionGraphUser Guide 2 Getting Started

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 41

Page 46: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Step 5 Click Test. The function test result is displayed, as shown in Figure 2-8.

Figure 2-8 Test result

----End

2.9 Using a Timer TriggerThis section describes how to create a timer trigger to invoke your function basedon a fixed rate or cron expression.

For details about the timer event source, see Supported Event Sources.

PrerequisitesA function has already been created. For details, see Creating and Initializing aFunction.

Creating a Timer Trigger

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click the HelloWorld function.

Step 3 On the function details page that is displayed, click the Triggers tab.

Step 4 Click Create Trigger.

Step 5 Set the following parameters:● Trigger Type: Select Timer.● Timer Name: Enter a timer name, for example, Timer.● Rule: Set a fixed rate or a Cron expression.

– Fixed rate: Triggers the function at a fixed rate of minutes, hours, ordays. You can set a fixed rate from 1 to 60 minutes, 1 to 24 hours, or 1 to30 days.

– Cron expression: Triggers the function based on a more complex rule. Forexample, executes the function at 08:30:00 every Monday through Friday.For more information, see Cron Expression for a Function TimerTrigger.

FunctionGraphUser Guide 2 Getting Started

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 42

Page 47: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

● Enable Trigger: Choose whether to enable the timer trigger.● Additional Information: The additional information you configure will be put

into the user_event field of the timer event source. For details, see SupportedEvent Sources.

Step 6 Click OK.

----End

Viewing the Execution Result

After the timer trigger is created, the HelloWorld function is executed every 1minute. View the function running logs by performing the following steps:

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click the HelloWorld function.

Step 3 On the function details page that is displayed, click the Logs tab to query thefunction running logs.

----End

2.10 Using a Kafka TriggerThis section describes how to create a Kafka trigger for a function.

Kafka triggers trigger FunctionGraph functions when messages are produced to aKafka instance topic and FunctionGraph retrieves such messages. For details aboutthe Kafka event source, see Supported Event Sources.

Prerequisites

Before creating a Kafka trigger, make sure you have prepared the following:

● A function has already been created. For details, see Creating and Initializinga Function.

● VPC access has been enabled for the function. For details, see ConfiguringVPC Access.

● You have created a Kafka trigger instance. For details, see Buying anInstance.

● You have created a topic under a Kafka trigger. For details, see Creating aTopic in a Kafka Premium Instance.

Creating a Kafka Trigger

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click the HelloWorld function.

Step 3 On the function details page that is displayed, click the Triggers tab.

FunctionGraphUser Guide 2 Getting Started

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 43

Page 48: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Step 4 Click Create Trigger.

Step 5 Set the following parameters:● Trigger Type: Select Kafka.● Instance: Select a Kafka premium instance.● Topic: Select a topic in the Kafka premium instance.● Batch Size: Set the number of messages to be consumed from the topic each

time.● Username: Enter the username of the instance if SSL has been enabled for it.● Password: Enter the password of the instance if SSL has been enabled for it.

Step 6 Click OK.

----End

Configuring a Kafka Event to Trigger the Function

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click the HelloWorld function.

Step 3 On the function details page that is displayed, select a version and choose Selecttest event > Configure test event.

Step 4 Set the parameters described in Table 2-7 and click Save.

Table 2-7 Test event information

Parameter Description

Configure Test Event You can choose to create a test event or edit an existingone.Use the default option Create new test event.

Event Template Select kafka-event-template.

Event Name Enter a maximum of 25 characters. Only letters anddigits are allowed.Enter kafka-test.

Event data The system automatically loads the built-in Kafka eventtemplate, which is used in this example withoutmodifications.

FunctionGraphUser Guide 2 Getting Started

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 44

Page 49: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

The event template is as follows:{ "event_version": "v1.0", "event_time": 1576737962, "trigger_type": "KAFKA", "region": "xx-xxxx-1", "messages": [ "kafka message1", "kafka message2", "kafka message3", "kafka message4", "kafka message5" ], "instance_id": "81335d56-b9fe-4679-ba95-7030949cc76b", "topic_id": "topic-test"}

Step 5 Click Test. The function test result is displayed.

----End

FunctionGraphUser Guide 2 Getting Started

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 45

Page 50: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

3 Basic Operations

3.1 DashboardThe Dashboard page presents your function resources, resource quota, andaccount-level metrics.

Using the Dashboard PageStep 1 Log in to the FunctionGraph console, and choose Dashboard in the navigation

pane.

Step 2 View your function resources, code storage, and quota information.

Step 3 To create a function, click Create Function. For details, see Creating a Function.

Step 4 To access a related cloud service console, click the icon in the Related Servicesarea.

Step 5 View the monthly statistics of your functions, as shown in Figure 3-1.

Figure 3-1 Monthly statistics

The monthly statistics area shows the monthly invocations and resource usage of aspecified period.

Step 6 To view the account-level function metrics, check the Metrics area, as shown inFigure 3-2.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 46

Page 51: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Figure 3-2 Metrics

FunctionGraph presents the following metrics: invocations, errors, duration, and throttles.

----End

Function MetricsTable 3-1 describes the function metrics.

Table 3-1 Function metrics

Metric Unit Description

Invocations Count Total number ofinvocation requests,including invocationerrors and throttledinvocations. Inasynchronous invocationmode, the count startsonly when a function isexecuted in response toa request.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 47

Page 52: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Metric Unit Description

Duration ms Maximum Duration: themaximum duration allfunctions are executed ata time within a period.Minimum Duration: theminimum duration allfunctions are executed ata time within a period.Average Duration: theaverage duration allfunctions are executed ata time within a period.

Errors Count Number of times thatyour functions failedwith error code 200being returned. Errorscaused by functionsyntax or execution arealso included.

Throttles Count Number of times thatFunctionGraph throttlesyour functions due to theresource limit.

3.2 Function ManagementFunction is a combination of code, runtime, resources, and settings required toachieve a specific purpose. It is the minimum unit that can run independently. Afunction can be triggered by triggers and automatically schedule requiredresources and environments to achieve expected results.

An app groups functions as a service logic unit for easier management. You cancreate multiple functions under an app.

Inline Code EditingFunctionGraph allows you to edit function code in the same way as managing aproject. You can create and edit files and file folders. After you upload a ZIP codepackage, you can view and edit the code on the console. Table 3-2 describes themenus of the inline editor.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 48

Page 53: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Table 3-2 Menu description of the inline editor

Menu Description

File Creates files and folders. You can create files, file templates, andPython modules, and close all files.

Edit Edits function code. You can undo or redo your editing, delete orjoin lines, add comments, fold and unfold lines, and sort lines inascending or descending order.

Find Finds and replaces code keywords.

Go to Goes to a certain location in the code. You can go to a specifiedline, the other bracket of a bracket pair, or the next problematicline.

View Provides common functions. You can view the command palette,and change the display theme.

Test Tests a function online, and displays the test result, digest, andlogs.

● Java is a compiled language, which does not support editing code inline. If your functiondoes not use any dependencies, you can upload a function JAR file. If your function usesdependencies, compress the dependencies and the function JAR file into a ZIP file, andthen upload the ZIP file.

● If you edit code in Go, compress the compiled file in ZIP format, and ensure that thename of the dynamic library file is consistent with the plug-in name of the handler. Forexample, if the name of the dynamic library file is function.so, set the handler tofunction.Handler according to Table 3-3.

● When creating a ZIP file, place the handler file under the root directory to ensure thatyour code can be run normally after decompressing.

● For details about editing code online, see Integrated Function Development.

Modifying Function CodeAfter a function is created, the default version is LATEST. Each function has theLATEST version. You can modify a function based only on its LATEST version.

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click a function name.

Step 3 (Optional) Select the LATEST version, and click the Code tab.

Step 4 On the Code tab page, modify the code information according to Table 3-3 andTable 3-4.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 49

Page 54: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Table 3-3 Code information

Parameter Description

Handler ● For a Node.js or Python function,the handler should be named in theformat of [file name].[functionname], which must contain a period(.). Enter myfunction.handler,which indicates that the file nameis myfunction.js (myfunction.pyfor a Python function andmyfunction.java for a Javafunction) and the function name ishandler.

● For a Java function, the handlershould be named in the format of[package name].[file name].[function name], for example,com.xxxxx.exp.Myfunction.myHandler.

● For a Go function, the handlershould be named in the format of[plug-in name].[function name], forexample, function.Handler. Thefunction name can contain amaximum of 128 characters andmust start with an uppercase letter.

● For a C# function, the handlershould be named in the format of[.NET assembly file name]::[Namespace and class of thehandler function]::[Handlerfunction name], for example,HelloCsharp::Example.Hello::Handler.

Initializer Function initialization can be enabledon the Code tab page after thefunction is created. Set the initializer inthe same way as the handler. Forexample, for Node.js or Pythonfunctions, specify the initializer as [filename].[initialization function name].NOTE

This parameter is not required if functioninitialization is disabled. For details on howto create an initialization function, seeEnabling Function Initialization.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 50

Page 55: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Parameter Description

Dependencies Third-party software packagesrequired by the function. You canmanage your dependencies byuploading them to FunctionGraph orOBS (if the dependencies are toolarge). For more information, seeDependent Libraries.NOTE

Except your private dependencies,FunctionGraph provides some commondependencies, which you can choose whencreating a function.

Code Entry Mode Method of entering the function code.For details about the supported codeentry modes, see Table 3-4.

Table 3-4 Code entry modes

Runtime Code Entry Mode Operation

Node.js 6.10/Node.js8.10/Node.js 10.16/Node.js 12.13

Edit code inline Edit code in the codebox. For moreinformation, see Table3-5.

Upload ZIP file Click Select File andupload a local codepackage toFunctionGraph. The sizeof the ZIP file to beuploaded cannot exceed10 MB. If it exceeds 10MB, upload the ZIP fileusing an OBS bucket.

Upload file from OBS Paste the link URL of theOBS bucket storing acode ZIP file.

Python 2.7/Python 3.6 Edit code inline Edit code in the codebox. For moreinformation, see Table3-5.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 51

Page 56: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Runtime Code Entry Mode Operation

Upload ZIP file Click Select File andupload a local codepackage toFunctionGraph. The sizeof the ZIP file to beuploaded cannot exceed10 MB. If it exceeds 10MB, upload the ZIP fileusing an OBS bucket.

Upload file from OBS Paste the link URL of theOBS bucket storing acode ZIP file.

Java 8 Upload ZIP file Click Select File andupload a local codepackage toFunctionGraph. The sizeof the ZIP file to beuploaded cannot exceed10 MB. If it exceeds 10MB, upload the ZIP fileusing an OBS bucket.

Uploading a JAR File Click Select File andupload a local JAR file toFunctionGraph. The sizeof the JAR file to beuploaded cannot exceed10 MB. If it exceeds 10MB, convert it into a ZIPfile, and upload the ZIPfile using an OBS bucket.

Upload file from OBS Paste the link URL of theOBS bucket storing acode ZIP file.

Go 1.8 Upload ZIP file Click Select File andupload a local codepackage toFunctionGraph. The sizeof the ZIP file to beuploaded cannot exceed10 MB. If it exceeds 10MB, upload the ZIP fileusing an OBS bucket.

Upload file from OBS Paste the link URL of theOBS bucket storing acode ZIP file.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 52

Page 57: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Runtime Code Entry Mode Operation

C#(.NET Core 2.0)/C#(.NET Core 2.1)/C#(.NET Core 3.1)

Upload ZIP file Click Select File andupload a local codepackage toFunctionGraph. The sizeof the ZIP file to beuploaded cannot exceed10 MB. If it exceeds 10MB, upload the ZIP fileusing an OBS bucket.

Upload file from OBS Paste the link URL of theOBS bucket storing acode ZIP file.

PHP 7.3 Upload ZIP file Click Select File andupload a local codepackage toFunctionGraph. The sizeof the ZIP file to beuploaded cannot exceed10 MB. If it exceeds 10MB, upload the ZIP fileusing an OBS bucket.

Upload file from OBS Paste the link URL of theOBS bucket storing acode ZIP file.

When you edit code inline, FunctionGraph displays all your input information inplain text. For security purposes, do not include sensitive information in your code.

Table 3-5 Menu description of the inline editor

Menu Description

File Creates files and folders. You can create files, file templates, andPython modules, and close all files.

Edit Edits function code. You can undo or redo your editing, delete orjoin lines, add comments, fold and unfold lines, and sort lines inascending or descending order.

Find Finds and replaces code keywords.

Go to Goes to a certain location in the code. You can go to a specifiedline, the other bracket of a bracket pair, or the next problematicline.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 53

Page 58: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Menu Description

View Provides common functions. You can view the command palette,and change the display theme.

Test Tests a function online, and displays the test result, digest, andlogs.

● Java is a compiled language, which does not support editing code inline. If your functiondoes not use any dependencies, you can upload a function JAR file. If your function usesdependencies, compress the dependencies and the function JAR file into a ZIP file, andthen upload the ZIP file.

● If you edit code in Go, compress the compiled file in ZIP format, and ensure that thename of the dynamic library file is consistent with the plug-in name of the handler. Forexample, if the name of the dynamic library file is function.so, set the handler tofunction.Handler according to Table 3-3.

● When creating a ZIP file, place the handler file under the root directory to ensure thatyour code can be run normally after decompressing.

● For details about editing code online, see Integrated Function Development.

Step 5 Click Save.

----End

Modifying Function ConfigurationsYou can define variables for your function and modify the function configurations.

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click a function name.

Step 3 (Optional) Select the LATEST version, and click the Configuration tab.

Step 4 Set the parameters described in Table 3-6.

Table 3-6 Configuration parameters

Parameter Description

Description Description of the function, whichcannot exceed 512 characters. Modifythe description as necessary.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 54

Page 59: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Parameter Description

Agency Used to delegate FunctionGraph toaccess other cloud services. Forexample, an agency is required whenFunctionGraph accesses cloud servicessuch as OBS or SMN.Select an agency from the drop-downlist. If there is no agency in the drop-down list, click Create Agency tocreate one on the IAM console.For details, see Creating an Agency.

Memory (MB) The options include 128, 256, 512, 768,1024, 1280, 1536, 1792, 2048, 2560,3072, 3584, and 4096. Modify thememory as necessary.

Initialization Timeout (s) Maximum duration the function canbe initialized. Set this parameter if youenable function initialization.The value ranges from 1s to 300s.

Execution Timeout (s) Maximum duration the function canbe executed.The value ranges from 3s to 900s.

VPC Access If VPC access is enabled for thefunction, specify an agency with VPCmanagement permissions.

Environment Variables Key-value pairs defined for thefunction. A key can contain onlyletters, digits, and hyphens (-), andmust start with a letter.Click here and set keys and values.To delete a key-value pair, click Deletenext to it.

● The maximum duration for returning a result is 90s. If the set timeout exceeds 90s andthe actual execution duration of a function also exceeds 90s, a message is displayedindicating that the function has timed out. However, the backend is still running. Youcan view the return result on the Logs tab page.

● When you define environment variables, FunctionGraph displays all your inputinformation in plain text. For security purposes, do not include sensitive information.

Step 5 Click Save.

----End

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 55

Page 60: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Exporting a FunctionYou can export the functions that you created.

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click a function name.

Step 3 On the function details page that is displayed, choose Operation > ExportFunction.

● A user can export only one function at a time.● The exported function resource package cannot exceed 50 MB.● The name of the exported function resource package is in the format of "function name

+MD5 (code).zip".● The exported function resource package does not include alias information.

----End

Importing a FunctionYou can create a function by importing a ZIP file that contains configurations andcode.

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click Import Function.

Step 3 In the Import Function dialog box, select an existing app or define a new app,and then upload a ZIP file.

Step 4 Click OK.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 56

Page 61: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

● You can import only one function at a time.

● The resource package to be imported must be a ZIP package that contains a YAMLconfiguration file and code file, as shown in Figure 3-3. The package cannot exceed 10MB.

Figure 3-3 Resource package

● The resource package must contain only one YAML configuration file.

● Fields in the YAML file must meet the same requirements as those configured when youcreate a function.

● The code file is located through the codeFilename field in the YAML file.

● The Resource field in the YAML file must specify only one function.

● When a dependency package is used, if the code in this package is pulled from OBS, theimporting is successful. Otherwise, the importing fails.

● You can import an exported resource package again, and must specify a unique functionname. The version of the imported function is LATEST by default.

The following shows an example YAML configuration file. The fields in this file aredescribed in Table 3-7.

HcCrmTemplateVersion: v1Resources: HelloWorld: Type: HC::Serverless::Function Properties: Handler: index.handler Runtime: Node.js6.10 CodeType: inline CodeFileName: index.js DependencyPkg: "" Description: "" MemorySize: 128 Timeout: 3 Version: latest Environment: Variables: {}

Table 3-7 YAML file description

Parameter Description

HcCrmTemplateVersion The value is fixed at v1.

Resources Function details.

Type The value is fixed at HC::Serverless::Function.

Properties Function properties.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 57

Page 62: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Parameter Description

Handler Handler of the function.

Runtime Running environment.

CodeType Code entry mode, which can be jar, zip, or inline.

CodeFileName Code file name.

DependencyPkg Dependency address.

Description Description of the function.

MemorySize Memory size.

Timeout Function timeout.

Version Function version.

Environment Environment variables.

----End

Disabling a FunctionDisabled functions can no longer be executed.

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click the name of the function you want to disable.

Step 3 Click Disable.

Step 4 On the displayed page, click Yes. The function is disabled.

● Only functions of the LATEST version can be disabled.● Versions published based on the disabled LATEST version of a function are also disabled

and can never be enabled.● After disabling a function, you can modify its code but cannot execute the function.

----End

Enabling a FunctionDisabled functions can be enabled again as required.

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click the name of the function you want to enable.

Step 3 Click Enable.

----End

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 58

Page 63: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Deleting a FunctionYou can delete unused functions to release resources.

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Select a search criterion (function name, runtime, or app name), enter a keyword,

and click to search for the function you want to delete.

Step 3 Click Delete in the same row as the function.

Step 4 In the Delete Function dialog box, enter DELETE, and click Yes to confirm thedeletion.

----End

Creating a Function AppStep 1 Log in to the FunctionGraph console, and choose Functions > Function List in the

navigation pane.

Step 2 Click Create Function.

Step 3 On the Create Function page, set the function information, including the functionapp. For more information, see Creating a Function.

Step 4 Click Create Now. A function and app are created.

1. Each function belongs to only one app.2. You can modify the description of the default app default, but you cannot delete this

app.3. You can create a maximum of 400 function apps in a project.4. When you create a function through an API, if the package field is left blank, the

function is created under the default app default. If the package field is set to an appthat does not exist, the app is created, and then the function is created under the newapp.

5. When you delete an app, you can determine whether to delete all the functions in theapp.

6. You can create functions with the same name in different apps.7. To add or modify a description for an app, click after the app and enter a description.

----End

Deleting a Function AppStep 1 Log in to the FunctionGraph console, and choose Functions > Function List in the

navigation pane.

Step 2 On the Functions page, click Delete App in the upper right corner of the desiredapp, as shown in Figure 3-4.

Figure 3-4 Deleting an app

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 59

Page 64: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Step 3 Enter DELETE, select the check box next to Delete all functions under the app,and then click Yes.

----End

3.3 Integrated Function DevelopmentFunctionGraph allows you to edit function code in the same way as managing aproject. You can create and edit files and file folders. With the inline editor, youcan edit function code from scratch, or modify the function code of an uploadedpackage. In addition, when the editor is displayed in full screen, you can save codemodifications, test functions online, and view the test result, digest, and logs.

Managing Folders and FilesChoose File from the menu bar, and create files or folders. Figure 3-5 shows theFile menu.

Figure 3-5 File menu

Choose New File from the drop-down list to create a file with a specified name.Figure 3-6 shows the new file.

Figure 3-6 New file

Choose New From Template from the drop-down list to create a file with atemplate. Figure 3-7 shows the New From Template submenu.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 60

Page 65: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Figure 3-7 Creating a template

Select a template, and create a file with a specified name. Figure 3-8 shows thenew file.

Figure 3-8 New file created based on a template

To rename a file or folder, right-click and choose Rename. To delete the file orfolder, right-click and choose Delete. Figure 3-9 shows the shortcut menu.

Figure 3-9 Renaming a file

Choose File > New Folder to create a folder with a specified name (see Figure3-5).

To create a file under the folder, right-click the folder and choose New File. Youcan also rename and delete folders and create Python modules. Figure 3-10shows the shortcut menu.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 61

Page 66: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Figure 3-10 Modifying a folder

Choose File > Close All File to close all files that are opened (see Figure 3-5).

You can quickly create a Python module in multiple levels, as shown in Figure3-11.

Figure 3-11 Multi-level Python module

EditThe Edit menu provides options for code editing. Choose Undo to cancel theprevious operation, choose Redo to restore the previous operation, and chooseCut to cut the selected code. Figure 3-12 highlights these options.

Figure 3-12 Edit menu

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 62

Page 67: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

In the Edit menu, choose Line to edit code by line. Figure 3-13 shows the Linesubmenu.

Figure 3-13 Editing code lines

In the Line submenu, choose Delete Line to delete a code line, choose Delete AllLeft to delete the code before the cursor in the current line, choose Delete AllRight to delete the code behind the cursor in the current line, and choose JoinLines to merge the current line with the next line.

Choose Edit > Comment to edit comments. Figure 3-14 highlights this option.

Figure 3-14 Editing comments

In the Comment submenu, choose Toggle Line Comment to open the commentof a code line, choose Toggle Block Comment to open the comment of a codeblock, choose Add Line Comment to add a comment to a code line, and chooseRemove Line Comment to delete the comment of a code line.

Choose Edit > Folding to expand or collapse code. Figure 3-15 shows the Foldingsubmenu.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 63

Page 68: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Figure 3-15 Folding or unfolding code

In the Folding submenu, choose Unfold or Fold to expand or collapse all code,and choose Fold Level XX to fold code by level.

Choose Edit > Sort to sort code. Figure 3-16 shows the Sort submenu.

Figure 3-16 Sorting code

In the Edit menu, you can also trim trailing spaces, transform codes to uppercaseor lowercase letters, and format documents.

Find and ReplaceChoose Find from the menu bar to find or replace a keyword. Figure 3-17 showsthe Find menu.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 64

Page 69: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Figure 3-17 Find menu

Choose Find > Find or Replace to find or replace a keyword. Figure 3-18 showsthe Find interface.

Figure 3-18 Finding a code keyword

Go toChoose Go to from the menu bar, and go to a specified position in the code.Figure 3-19 shows the Go to menu.

Figure 3-19 Go to menu

Choose Go to > Go to Line to go to a specified code line. Figure 3-20 shows theGo to Line interface.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 65

Page 70: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Figure 3-20 Going to a code line

For a large number of code lines, you can choose Go to Bracket or Go to NextProblem (Error, Warning, Info) to respectively switch to the other bracket of abracket pair or to the next problematic line.

Online Function TestAfter configuring a test event for a function, you can click Test in the full screenmode of the editor to test the function, and view the test result, digest, and logs,as shown in Figure 3-21.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 66

Page 71: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Figure 3-21 Online function test

Other Common Functions1. In the View menu, choose Theme to change the editor theme, and choose

Show Command Palette to view all commands. Figure 3-22 shows thecommand list.

Figure 3-22 Viewing all commands

2. The inline editor can autocomplete a keyword when you input only the firstseveral letters. Figure 3-23 shows the associated keywords.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 67

Page 72: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Figure 3-23 Associated keywords

3. The left pane can be adjusted to expand the working area. To open a localcode file, drag it to the editor.

3.4 Dependency ManagementFunctionGraph provides the dependency management function that enables youto manage all your dependencies. You can upload dependencies from a local path,or through OBS if they are too large, and specify names for them.

For details about how to generate function dependencies, see How Do I GenerateFunction Dependencies?

Creating a Dependency

Step 1 Log in to the FunctionGraph console, and choose Functions > Dependencies inthe navigation pane.

Step 2 Click Create Dependency.

Step 3 Set the following parameters:● Name: Enter a dependency name.● Runtime: Select the runtime of the dependency.● Description: Enter a description for the dependency. This parameter is

optional.● Upload Mode: Upload a ZIP file or upload a file from OBS.

Step 4 Click OK.

----End

Configuring Dependencies for a Function

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click the name of the desired function to go to the function details page.

Step 3 On the Code tab page, click Select next to Dependencies.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 68

Page 73: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Step 4 On the Select Dependency dialog box, select dependencies and click OK.

● You can add a maximum of 20 dependencies for a function.

● Except your private dependencies, FunctionGraph provides some common dependencies,which you can choose when creating a function.

Step 5 After configuring dependencies, click Save.

----End

Deleting a Dependency

Step 1 Log in to the FunctionGraph console, and choose Functions > Dependencies inthe navigation pane.

Step 2 In the same row as the dependency you want to delete, click Delete.

Step 3 Click Yes.

Dependencies referenced by functions cannot be deleted.

----End

Dependent Libraries

Supported Dependent Libraries

FunctionGraph supports standard and third-party libraries.

● Standard librariesWhen using standard libraries, you can import them to your inline code orpackage and upload them to FunctionGraph.

● Supported non-standard librariesFunctionGraph provides built-in third-party components, which are listed inTable 3-8 and Table 3-9. You can import these libraries to your inline code inthe same way as you import standard libraries.

Table 3-8 Third-party components integrated with the Node.js runtime

Name Usage Version

q Asynchronous methodencapsulation

1.5.1

co Asynchronous processcontrol

4.6.0

lodash Common tool and methodlibrary

4.17.10

esdk-obs-nodejs OBS SDK 2.1.5

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 69

Page 74: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Name Usage Version

express Simplified web-basedapplication developmentframework

4.16.4

fgs-express Provides a Node.jsapplication framework forFunctionGraph and APIGateway to run serverlessapplications and REST APIs.This component providesan example of using theExpress framework to buildserverless web applicationsor services and RESTfulAPIs.

1.0.1

request Simplifies HTTP invocationand supports HTTPS andredirection.

2.88.0

Table 3-9 Non-standard libraries supported by the Python SDK

Module Usage Version

dateutil Date and timeprocessing

2.6.0

requests HTTP library 2.7.0

httplib2 HTTP client 0.10.3

numpy Mathematicalcomputing

1.13.1

redis Redis client 2.10.5

obsclient OBS client -

smnsdk SMN access 1.0.1

● Other third-party libraries (FunctionGraph does not provide built-in non-

standard libraries.)Package the dependent third-party libraries and upload them to a specifiedOBS bucket. Paste the OBS link URL of the dependent libraries when creatinga function.

Importing Dependent Libraries

The code for processing images is as follows:

# -*- coding: utf-8 -*-from PIL import Image, ImageEnhance

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 70

Page 75: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

from com.obs.client.obs_client import ObsClient

import sysimport os

current_file_path = os.path.dirname(os.path.realpath(__file__))# append current path to search paths, so that we can import some third party libraries.sys.path.append(current_file_path)region = 'china'obs_server = 'obs.xxxxxxcloud.com'def newObsClient(context): ak = context.getAccessKey() sk = context.getSecretKey() return ObsClient(access_key_id=ak, secret_access_key=sk, server=obs_server, path_style=True, region=region, ssl_verify=False, max_retry_count=5, timeout=20)def downloadFile(obsClient, bucket, objName, localFile): resp = obsClient.getObject(bucket, objName, localFile) if resp.status < 300: print 'download file', file, 'succeed' else: print('download failed, errorCode: %s, errorMessage: %s, requestId: %s' % resp.errorCode, resp.errorMessage, resp.requestId)def uploadFileToObs(client, bucket, objName, file): resp = client.putFile(bucket, objName, file) if resp.status < 300: print 'upload file', file, 'succeed' else: print('upload failed, errorCode: %s, errorMessage: %s, requestId: %s' % resp.errorCode, resp.errorMessage, resp.requestId)def getObjInfoFromObsEvent(event): s3 = event['Records'][0]['s3'] eventName = event['Records'][0]['eventName'] bucket = s3['bucket']['name'] objName = s3['object']['key'] print "*** obsEventName: %s, srcBucketName: %s, objName: %s", eventName, bucket, objName return bucket, objNamedef set_opacity(im, opacity): """Set the transparency.""" if im.mode != "RGBA": im = im.convert('RGBA') else: im = im.copy() alpha = im.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(opacity) im.putalpha(alpha) return imdef watermark(im, mark, opacity=0.6): """Add a watermark.""" try: if opacity < 1: mark = set_opacity(mark, opacity) if im.mode != 'RGBA': im = im.convert('RGBA') if im.size[0] < mark.size[0] or im.size[1] < mark.size[1]: print "The mark image size is larger size than original image file." return False x = (im.size[0] - mark.size[0]) / 2 y = (im.size[1] - mark.size[1]) / 2

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 71

Page 76: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

layer = Image.new('RGBA', im.size, ) layer.paste(mark, (x, y)) return Image.composite(layer, im, layer) except Exception as e: print ">>>>>>>>>>> WaterMark EXCEPTION: " + str(e) return Falsedef watermark_image(localFile, fileName): im = Image.open(localFile) watermark_image_path = os.path.join(current_file_path, "watermark.png") mark = Image.open(watermark_image_path) out = watermark(im, mark) print "**********finish water mark" name = fileName.split('.') outFileName = name[0] + '-watermark.' + name[1] outFilePath = "/tmp/" + outFileName if out: out = out.convert('RGB') out.save(outFilePath) else: print "Sorry, Save watermarked file Failed." return outFileName, outFilePathdef handler(event, context): srcBucket, srcObjName = getObjInfoFromObsEvent(event) outputBucket = context.getUserData('obs_output_bucket') client = newObsClient(context) # download file uploaded by user from obs localFile = "/tmp/" + srcObjName downloadFile(client, srcBucket, srcObjName, localFile) outFileName, outFile = watermark_image(localFile, srcObjName) # Upload converted files to a new OBS bucket. uploadFileToObs(client, outputBucket, outFileName, outFile) return 'OK'

For standard libraries and supported non-standard libraries, you can directly usethem in your function.

For non-standard third-party libraries that are not provided by FunctionGraph, youcan use them by performing the following steps:

1. Package the dependent libraries into a ZIP file, upload the ZIP file to an OBSbucket, and obtain the OBS link URL.

2. Log in to the FunctionGraph console, and choose Functions > Dependenciesin the navigation pane.

3. Click Create Dependency.4. Set the dependency name and runtime, specify the OBS link as shown in

Figure 3-24, and click OK.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 72

Page 77: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Figure 3-24 Entering the OBS link URL

5. On the Code tab page of the function details page, click Select next toDependencies, select the dependency created in 4 (see Figure 3-25), andclick OK.

Figure 3-25 Selecting a dependency

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 73

Page 78: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

6. Reference the dependence in the function code, and click Save.

Each dependency package cannot contain a file with the same name as acode file. Otherwise, the two files may be incorrectly merged or overwritten.For example, if dependency package depends.zip contains a file namedindex.py, the handler of a function cannot be set to index.handler.Otherwise, a code file also named index.py will be generated.

3.5 Trigger Management

Enabling or Disabling a Trigger

You can enable or disable a trigger to control its status. SMN, OBS, and APIGtriggers cannot be disabled and can only be deleted.

Enable or disable a trigger using either of the following methods:

Method 1

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click the name of the desired function to go to the function details page.

Step 3 Click the Triggers tab.

Step 4 On the right of the desired trigger, click Enable or Disable.

----End

Method 2

Step 1 Log in to the FunctionGraph console, and choose Functions > Trigger List in thenavigation pane.

Step 2 Select a trigger type, for example, Timer. All triggers of the selected type aredisplayed.

Step 3 On the right of the desired trigger, click Enable or Disable.

----End

Deleting a Trigger

You can delete triggers that will no longer be used.

Delete a trigger using either of the following methods:

Method 1

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 74

Page 79: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Step 2 Click the name of the desired function to go to the function details page.

Step 3 Click the Triggers tab.

Step 4 On the right of the desired trigger, click Delete.

----End

Method 2

Step 1 Log in to the FunctionGraph console, and choose Functions > Trigger List in thenavigation pane.

Step 2 Select a trigger type, for example, Timer. All triggers of the selected type aredisplayed.

Step 3 On the right of the desired trigger, click Delete.

----End

3.6 Test Management

Precautions

Event data is passed to the handler of your function as an input. Afterconfiguration, event data is persisted for later use. Each function can have amaximum of 10 test events.

Creating a Test Event

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click a function name.

Step 3 On the displayed function details page, select a version and choose Select testevent > Configure test event, as shown in Figure 3-26.

Figure 3-26 Configuring a test event

Step 4 In the Configure Test Event dialog box, configure the test event informationaccording to Table 3-10. The parameter marked with an asterisk (*) is mandatory.

Table 3-10 Test event information

Parameter Description

Configure Test Event You can choose to create a test event or edit an existingone.Use the default option Create new test event.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 75

Page 80: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Parameter Description

Event Template If you select blank-template, you can create a test eventfrom scratch.If you select a template, the corresponding test event inthe template is automatically loaded. For details aboutevent templates, see Table 3-11.The OBS template obs-event-template can simulateOBS events to trigger functions.

*Event Name An event name can contain a maximum of 25 characters.Only letters and digits are allowed.

Event data Enter a test event.

Table 3-11 Event template description

Template Name Description

blank-template The template event is {"key":"value"}, which you can modify asnecessary.

apig-event-template Simulates an API Gateway event totrigger your function.

dms-event-template Simulates a DMS event to trigger yourfunction.

dis-event-template Simulates a DIS event to trigger yourfunction.

smn-event-template Simulates an SMN event to triggeryour function.

obs-event-template Simulates an OBS event to trigger yourfunction.

timer-event-template Simulates a timer event to trigger yourfunction.

kafka-event-template Simulates a Kafka event to triggeryour function.

porn-image-analyse Serves as an input for the porn-image-analysis function template.

voice-analyse Serves as an input for the voice-analysis function template.

image-tag Serves as an input for the image-tagand porn-image-analysis functiontemplates.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 76

Page 81: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Step 5 Click Save.

----End

Testing a Function

After creating a function, you can test it online to check whether it can runproperly as expected.

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click a function name.

Step 3 On the displayed function details page, select a version and test event, and clickTest.

Figure 3-27 Testing a function

Step 4 Click Test. The function test result is displayed, as shown in Figure 3-28.

Figure 3-28 Test result

The Log Output area displays a maximum of 4 KB logs. To view more logs, see QueryingLogs.

----End

Modifying a Test Event

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click a function name.

Step 3 On the displayed function details page, select a version and choose Select testevent > Configure test event.

Step 4 In the Configure Test Event dialog box, modify the test event informationaccording to Table 3-12.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 77

Page 82: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Table 3-12 Test event information

Parameter Description

Configure Test Event Select Edit saved test event.

Saved Test Event Select the test event you want to modify.

Event data Modify the test event code.

Step 5 Click Save.

----End

Deleting a Test Event

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click a function name.

Step 3 On the displayed function details page, select a version and choose Select testevent > Configure test event.

Step 4 In the Configure Test Event dialog box, select the test event you want to deleteaccording to Table 3-13.

Table 3-13 Test event information

Parameter Description

Configure Test Event Select Edit saved test event.

Saved Test Event Select the test event you want to delete.

Step 5 Click Delete.

----End

3.7 Version and Alias Management

Managing VersionsAfter a function is created, the default version of the function is LATEST. Eachfunction has the LATEST version. You can publish a version for a function whenthe function code becomes stable. The information (including the metadata andcode information) about a published version cannot be modified.

Publishing a Version

1. Log in to the FunctionGraph console, and choose Functions > Function Listin the navigation pane.

2. Click the name of the desired function to go to the function details page.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 78

Page 83: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

3. Select the LATEST version, and choose Operation > Publish new version.4. Set the following information.

– Version: Enter a version number. If no version number is specified, thesystem automatically generates a version number based on the currentdate, for example, v20170819-190658.

– Description: Enter a description for the version. This parameter isoptional.

5. Click Publish.

You can publish a maximum of 10 versions for a function.

Deleting a Version

1. Log in to the FunctionGraph console, and choose Functions > Function Listin the navigation pane.

2. Click the name of the desired function to go to the function details page.3. Select the version you want to delete, and choose Operation > Delete

version.

● The LATEST version of a function cannot be deleted.

● If a function with aliases is deleted, the aliases will also be deleted.

4. Enter DELETE and click Yes.

Deleted versions cannot be recovered. Exercise caution when performing thisoperation.

Managing Aliases

An alias represents a specific function version and can be used to invoke thisversion.

Creating an Alias

1. Log in to the FunctionGraph console, and choose Functions > Function Listin the navigation pane.

2. Click the name of the desired function to go to the function details page.3. Open the Create Alias dialog box in either of the following ways:

– Choose Operation > Create alias.– On the Aliases tab page, click Create Alias.

4. Set the following parameters:– Alias: Enter an alias.– Version: Select a version to be associated with the alias.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 79

Page 84: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

– Traffic Shifting: Choose whether to enable traffic shifting. After enablingthis function, you can specify an additional version to distribute a specificpercentage of traffic.

– Additional Version: Select another version to distribute traffic at aspecified percentage.

– Weight: Set a percentage for distributing traffic.– Description: Enter a description for the alias.

Figure 3-29 Specifying an additional version

5. Click OK.

You can create a maximum of 10 aliases for a function.

Modifying an Alias

1. Log in to the FunctionGraph console, and choose Functions > Function Listin the navigation pane.

2. Click the name of the desired function to go to the function details page.3. Select the version for which you want to modify the alias, and click the Alias

tab.4. In the same row as the alias, click Edit.5. Modify the alias information, and click OK.

Deleting an Alias

Delete an alias using either of the following methods:

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 80

Page 85: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Method 1:

1. Log in to the FunctionGraph console, and choose Functions > Function Listin the navigation pane.

2. Click the name of the desired function to go to the function details page.3. Select the alias you want to delete, and choose Operation > Delete alias.4. Enter DELETE and click Yes.

Method 2:

1. Log in to the FunctionGraph console, and choose Functions > Function Listin the navigation pane.

2. Click the name of the desired function to go to the function details page.3. Select the version whose alias is to be deleted, and click the Alias tab.4. In the same row as the alias you want to delete, click Delete.5. Enter DELETE and click Yes.

3.8 Function MonitoringAfter creating a function and trigger, you can monitor the real-time invocationand running statuses of the function.

Viewing Function MetricsFunctionGraph differentiates the metrics of a function by version, allowing you toquery the metrics of a specific function version.

Procedure

1. Log in to the FunctionGraph console, and choose Functions > Function Listin the navigation pane.

2. Click the name of the desired function to go to the function details page.3. Select a version or alias, and click the Monitoring tab.4. On the Monitoring tab page, select an interval (such as 5 minutes, 15

minutes, and 1 hour), and check the running status of the function.

FunctionGraph presents the following metrics: invocation count, invocation errors,invocation duration (including the maximum, average, and minimum invocationdurations), and throttled invocations.

Function metrics

Table 3-14 describes the function metrics.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 81

Page 86: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Table 3-14 Function metrics

Metric Unit Description

Invocations Count Total number ofinvocation requests,including invocationerrors and throttledinvocations. Inasynchronous invocationmode, the count startsonly when a function isexecuted in response toa request.

Duration ms Maximum Duration: themaximum duration afunction is executedwithin a period.Minimum Duration: theminimum duration afunction is executedwithin a period.Average Duration: theaverage duration afunction is executedwithin a period.

Errors Count Number of times thatyour functions failedwith error code 200being returned. Errorscaused by functionsyntax or execution arealso included.

Throttles Count Number of times thatFunctionGraph throttlesyour functions due to theresource limit.

Viewing Monitoring Graphs

Create an alarm rule for a function to report metrics to Cloud Eye so that you canview monitoring graphs and alarm messages on the Cloud Eye console.

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click the name of the desired function to go to the function details page.

Step 3 Select a version or alias, and click the Monitoring tab.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 82

Page 87: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Step 4 Click Create Alarm Rule.

Step 5 In the Create Alarm Rule dialog box, set alarm parameters and click Next, asshown in Figure 3-30.

Figure 3-30 Creating an alarm rule

Step 6 Set a rule name and click Create.

----End

Function Metrics

Table 3-15 lists the function metrics that can be monitored by Cloud Eye.

Table 3-15 Function metrics

Metric DisplayName

Description

Unit

UpperLimit

LowerLimit

RecommendedThreshold

ValueType

Dimension

count Invocations

Numberoffunctioninvocations

Count

- 0 - int package-functionname

failcount

Errors Numberofinvocation errors

Count

- 0 - int package-functionname

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 83

Page 88: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Metric DisplayName

Description

Unit

UpperLimit

LowerLimit

RecommendedThreshold

ValueType

Dimension

rejectcount

Throttles

Numberoffunctionthrottles

Count

- 0 - int package-functionname

duration

AverageDuration

Averagedurationoffunctioninvocation

ms - 0 - int package-functionname

maxDuration

MaximumDuration

Maximumdurationoffunctioninvocation

ms - 0 - int package-functionname

minDuration

MinimumDuration

Minimumdurationoffunctioninvocation

ms - 0 - int package-functionname

Querying LogsAfter querying the logs of a function version within a specified date range, youcan download the logs for further analysis.

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click the name of the desired function to go to the function details page.

Step 3 Select a version or alias, and click the Logs tab.

Step 4 On the Logs tab page, set the search criteria.

1. You can query logs by time and keyword.2. FunctionGraph allows you to query logs of the last 5 minutes, 30 minutes, 1 hour, and

any time range.3. You can query the logs of a specific function version.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 84

Page 89: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Step 5 Click to search for logs.

● A log record includes an instance, a digest, and a context.

● In the Operation column, click View Context to view the detailed running informationof a log.

----End

Downloading Logs

Step 1 Log in to the FunctionGraph console, and choose Functions > Function List in thenavigation pane.

Step 2 Click the name of the desired function to go to the function details page.

Step 3 Click the Logs tab.

Step 4 Select a version and time range, and click Download Log.

A maximum of 5000 logs can be downloaded at a time. When querying logs, select aproper time range to avoid the loss of logs.

----End

3.9 RI Management

What Is an RI?

FunctionGraph provides reserved and pay-per-use instances.

● Pay-per-use instances are created and released by FunctionGraph. Uponreceiving a function invocation request, FunctionGraph automatically allocatesexecution resources to the request.

● For reserved instances (RIs), you can create and release them as required.After you create RIs for a function, FunctionGraph preferentially forwardsrequests for invoking the function to the RIs. If the number of requestsexceeds the processing capability of the RIs, FunctionGraph will forward theremaining requests to the pay-per-use instances of the function andautomatically allocates execution resources to these requests.After RIs are created for a function, the code, dependencies, and initializer ofthe function are automatically loaded. RIs are always alive in the executionenvironment and eliminate the influence of cold starts on your services.

By default, you do not have the permission to use the RI function. To use this function,submit a service ticket to whitelist your account.

You can directly create RIs or create them on the function configuration page.Differences between the two modes are described in the following table.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 85

Page 90: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Table 3-16 Differences between the two modes

Mode Advantage Disadvantage

Directly create You can create an RI withjust a few clicks.

Only a fixed number of RIs canbe created. The RIs may beinsufficient during peak hoursand become idle during off-peak hours.

Create on thefunctionconfigurationpage

You can create differentnumbers of RIs for differentperiods, preventing waste ofRIs while ensuring sufficientRIs during peak hours.

The procedure is complex.

Creating a Fixed Number of RIsBefore your create RIs, ensure that the function, for example, Objective-func, forwhich you want to create RIs already exists on the FunctionGraph console.

1. Log in to the FunctionGraph console, and choose Functions > ReservedInstances in the navigation pane.

2. Click Configure RI.3. Specify the RI information.

Table 3-17 RI information

Parameter Description

App Select the app to which the Objective-func functionbelongs.

Function Select Objective-func.

Version Select a version of the Objective-func function.

RI Quantity Enter the number of RIs to be created.To determine how many RIs you need to create, view thenumber of used instances in the Instance Statistics areaor check the usage of the Objective-func function.

4. Click OK.

After creating RIs for a function, you can only change the RI quantity rather than thefunction information of the RIs.

Creating RIs on the Function Configuration PageThe number of function instances varies between different periods. To ensuresufficient RIs during peak hours and prevent waste of RIs during off-peak hours,

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 86

Page 91: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

you can create a timer for invoking the corresponding function with differentnumber of RIs in different periods.

Before your create RIs, ensure that the function, for example, Objective-func, forwhich you want to create RIs already exists on the FunctionGraph console.

1. Log in to the FunctionGraph console, and choose Functions > Function Listin the navigation pane.

2. Click Create Function.3. Specify the function information.

Parameter Description

Template Select Create from scratch.

FunctionName

Enter a name to identify the function.

App Select default.

Agency Select Use no agency.

Description Enter a description for the function. This parameter isoptional.

Runtime Select Python 2.7.

Handler Enter index.handler.

Code EntryMode

Select Edit code inline and enter the code shown belowthis table.

# -*- coding:utf-8 -*-import jsonimport requestsdef handler (event, context): domainId = "https://{Endpoint}" url = "/v2/{project_id}/fgs/functions/{func-urn}/reservedinstances" token = context.getToken() requrl = domainId + url headerdata = {"Content-Type":"application/json","x-auth-token":token} r = requests.put(requrl, data=event["user_event"], headers=headerdata,verify=False)return r.json

Replace the following parameters with the actual values:– Endpoint: Endpoint of the Objective-func function. For details, see

Regions and Endpoints.– project_id: ID of the project to which the Objective-func function

belongs.– func-urn: URN of the objective-func function.

4. Click Create Now.5. On the Configuration tab page, click Create Agency on the right of the

Agency parameter.6. Create an agency and grant it the FunctionGraph User permission. For

details, see Creating an Agency.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 87

Page 92: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

7. On the Configuration tab page, select the agency created in 6, and clickSave.

8. Go to the Triggers tab page, and click Create Trigger.9. Specify the trigger information.

Parameter Description

Trigger Type Select Timer.

Timer Name Enter a name to identify the timer.

Rule Select Cron expression and enter a cron expression to suityour requirements.

Enable Trigger Retain the default setting to enable the trigger.

AdditionalInformation

Enter the number of RIs required in different periodsbased on the triggering rule.

Figure 3-31 Creating a timer trigger

Figure 3-31 shows a timer trigger that requests FunctionGraph to create twoRIs every 3 minutes.

10. Click OK.After trigger creation, different numbers of RIs will be created for theObjective-func function in different periods based on the triggering rule.

FunctionGraphUser Guide 3 Basic Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 88

Page 93: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

4 Advanced Operations

4.1 Function TemplatesFunctionGraph provides templates to automatically complete code, and runningenvironment configurations when you create a function, helping you quickly buildapplications.

Template UsageCreating a Function

1. Log in to the FunctionGraph console, and choose Templates in the navigationpane.

2. On the page that is displayed, select the FunctionGraph service, select thecontext-class-introduction template for Python 2.7, and click Configure.

3. After you select a function template, the built-in code and configurations ofthe template are automatically loaded. The Create Function page isdisplayed.

4. Set the function name to context, retain the default settings for otherparameters, and click Create Now.

Triggering a Function

1. On the Code tab page of the context function, click Test in the upper rightcorner.

2. In the Configure Test Event dialog box that is displayed, click Save and Test.After the test is complete, view the test result.

4.2 Mounting a File System

ScenariosYou can mount file systems to your function to provide scalable file storage. Thefunction can then read and write data to the file systems as it would do to localfile systems. Each file system can be shared by different functions and the

FunctionGraphUser Guide 4 Advanced Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 89

Page 94: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

instances of a specific function. All you need to do is specify a file system andaccess path for your function.

FunctionGraph supports the following three types of file systems:

● SFSScalable File Service (SFS) is a network-attached storage (NAS) service thatprovides scalable high-performance file storage. With SFS, shared access canbe achieved among multiple Elastic Cloud Servers (ECSs), Bare Metal Servers(BMSs), and containers created on Cloud Container Engine (CCE) and CloudContainer Instance (CCI). SFS is expandable to petabytes, and provides fullyhosted shared file storage. It features high availability and durability, andseamlessly handles data-intensive and bandwidth-intensive applications. SFSis suitable for high-performance computing (HPC), media processing, filesharing, content management and web services.

● SFS TurboSFS Turbo supports the following storage classes: classified into Standard,Standard-Enhanced, Performance, and Performance-Enhanced. SFS Turbo isexpandable to 320 TB, and provides fully hosted shared file storage. Itfeatures high availability and durability, and supports massive quantities ofsmall files and applications requiring low latency and high IOPS. SFS Turbo issuitable for high-performance websites, log storage, compression anddecompression, DevOps, enterprise offices, and container applications.

● ECSUse the network file system (NFS) service to specify a directory on an ECS asa shared file system (see Creating an NFS Shared Directory on ECS). Thenmount the directory to a function in the same VPC as the ECS so that thefunction can read data from or write data into the directory. ECS file systemsmake it possible for dynamic expansion of compute resources. This type of filesystem is suitable for low service demand scenarios.

Benefits from using these file systems:

● The execution space of each function can be expanded in addition tothe /tmp directory.

● A file system can be shared by multiple functions.● Stronger computing becomes possible thanks to ECS storage capacity

powered by dynamic compute resource expansion.

Creating an AgencyBefore adding file systems to a function, specify an agency with permissions foraccessing the file system services for the function.

There is a limit on the maximum number of agencies you can create, and cloudservice agencies cannot be modified. Therefore, you are advised to create anagency with high-level permissions, similar with Tenant Administrator, to allow afunction to access all resources in the selected region. For more information, seeCreating an Agency.

Mounting an SFS File SystemSpecifying an Agency

FunctionGraphUser Guide 4 Advanced Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 90

Page 95: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

On the Configuration tab page, select an agency that has been granted SFSAdministrator or Tenant Administrator permissions in the selected region.

If no agencies are available, create one in IAM.

Mounting a File System

On the File Systems tab page, click Mount. If this is your first time to mount afile system to the target function, you need to set the user ID and group ID.

User ID and group ID respectively correspond to the values of uid and gid in theLinux operating system. They will be used as the identity of a function to accessthe mounted file systems.

For example, an ECS has been mounted with an SFS file system, and the owner ofa directory in the file system is test-user. Then you can run the id test-usercommand to query the uid and gid.

Figure 4-1 Setting the user ID and user group ID

Select an SFS file system and set the access path.

Figure 4-2 Mounting an SFS file system

The access path can contain a maximum of two levels and start with /mnt or /home.

Mounting an SFS Turbo File SystemSpecifying an Agency

Before mounting an SFS Turbo file system to a function, specify an agency thathas been granted SFS Administrator and VPC Administrator permissions for thefunction. If no agencies are available, create one in IAM.

Configuring VPC Access

An SFS Turbo file system is accessible only in the VPC where it has been created.Before mounting such a file system to a function, enable access to the functionfrom the same VPC as the file system.

1. On the SFS console, obtain the information about the VPC and subnet wherea file system is to be mounted to your function. For details, see File SystemManagement.

FunctionGraphUser Guide 4 Advanced Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 91

Page 96: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

2. On the FunctionGraph console, go to the details page of the function, clickthe Configuration tab, enable VPC access, and specify the VPC and subnetobtained in 1.

Figure 4-3 Specifying the VPC and subnet

Mounting an SFS Turbo File System

SFS Turbo file system can be mounted in the same way as SFS file systems. Selecta file system and set the access path.

Figure 4-4 Mounting an SFS Turbo file system

Mounting an ECS Shared DirectorySpecifying an Agency

Before mounting an ECS shared directory to a function, specify an agency that hasbeen granted Tenant Guest and VPC Administrator permissions for the function. Ifno agencies are available, create one in IAM.

Configuring VPC Access

Before adding an ECS shared directory, specify the VPC where the ECS is deployed.View the VPC information on the details page of the ECS. Click the VPC name togo to the VPC details page, and view the subnet.

Set the acquired VPC and subnet for the function.

Mounting an ECS Directory

Enter the shared directory and access path, as shown in the following figure.

FunctionGraphUser Guide 4 Advanced Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 92

Page 97: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Figure 4-5 Specifying the shared directory

Follow-up Operations

A function can read and write into an access path as into the mounted file system.

Function logs can be persisted by configuring the log path as a subdirectory in theaccess path.

Create a function using the "Web-Server-Access-Log-Statistics" template toanalyze logs of the web server.

Figure 4-6 Function template

4.3 Using a Custom Runtime

Scenarios

A runtime runs the code of a function, reads the handler name from anenvironment variable, and reads invocation events from the runtime APIs ofFunctionGraph. The runtime passes event data to the function handler and returnsthe response from the handler to FunctionGraph.

FunctionGraph supports custom runtimes. You can use an executable file namedbootstrap to include a runtime in your function deployment package. The runtimeruns the function's handler method when the function is invoked.

Your runtime runs in the FunctionGraph execution environment. It can be a shellscript or a binary executable file that is compiled in Linux.

FunctionGraphUser Guide 4 Advanced Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 93

Page 98: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Runtime File bootstrap

If there is a file named bootstrap in your function deployment package,FunctionGraph executes that file. If the bootstrap file is not found or notexecutable, your function will return an error when invoked.

The runtime code is responsible for completing initialization tasks. It processesinvocation events in a loop until it is terminated.

The initialization tasks run once for each instance of the function to prepare theenvironment for handling invocations.

Runtime APIs

FunctionGraph provides HTTP runtime APIs to receive function invocation eventsand returns response data in the execution environment.

● Next Invocation

Method – POST

Path – http://$RUNTIME_API_ADDR/v1/runtime/invocation/request

This API is used to retrieve an invocation event. The response body containsthe event data. The following table describes additional data about theinvocation contained in the response header.

Table 4-1 Response header information

Parameter Description

X-Cff-Request-Id Request ID.

X-CFF-Access-Key AK of the account. An agency mustbe configured for the function if thisvariable is used.

X-CFF-Auth-Token Token of the account. An agencymust be configured for the functionif this variable is used.

X-CFF-Invoke-Type Invocation type of the function.

X-CFF-Secret-Key SK of the account. An agency mustbe configured for the function if thisvariable is used.

X-CFF-Security-Token Security token of the account. Anagency must be configured for thefunction if this variable is used.

● Invocation response

Method – POST

Path – http://$RUNTIME_API_ADDR/v1/runtime/invocation/response/$REQUEST_ID

FunctionGraphUser Guide 4 Advanced Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 94

Page 99: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

This API is used to send an invocation response to FunctionGraph. After theruntime invokes the function handler, it posts the response from the functionto the invocation response path.

● Invocation Error

Method – POST

Path – http://$RUNTIME_API_ADDR/v1/runtime/invocation/error/$REQUEST_ID

$REQUEST_ID is the value of variable X-Cff-Request-Id in the header of anevent retrieval response. For more information, see Table 4-1.

$RUNTIME_API_ADDR is a system environment variable. For moreinformation, see Table 4-2.

This API is used to send an invocation response to FunctionGraph. After theruntime invokes the function handler, it posts the response from the functionto the invocation response path.

Runtime Environment Variables

You can use both custom and runtime environment variables in function code. Thefollowing table lists the runtime environment variables that are used in theFunctionGraph execution environment.

Table 4-2 Runtime environment variables

Key Description

RUNTIME_PROJECT_ID Project ID

RUNTIME_FUNC_NAME Function name

RUNTIME_FUNC_VERSION Function version

RUNTIME_PACKAGE App to which the function belongs

RUNTIME_HANDLER Function handler

RUNTIME_TIMEOUT Function timeout duration

RUNTIME_USERDATA Value passed through an environmentvariable

RUNTIME_CPU Number of allocated CPU cores

RUNTIME_MEMORY Allocated memory

RUNTIME_CODE_ROOT Directory that stores the function code

RUNTIME_API_ADDR Host IP address and port of a customruntime API

The value of a custom environment variable can be retrieved in the same way asthe value of a FunctionGraph environment variable.

FunctionGraphUser Guide 4 Advanced Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 95

Page 100: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Example RuntimeThis example contains one file called bootstrap. The file is implemented in Bash.

The runtime loads the function script from the deployment package by using twovariables.

The bootstrap file is as follows:

#!/bin/sh

set -o pipefail

#Processing requests loopwhile truedo HEADERS="$(mktemp)" # Get an event EVENT_DATA=$(curl-sS -LD "$HEADERS" -X GET"http://$RUNTIME_API_ADDR/v1/runtime/invocation/request") # Get request idfrom response header REQUEST_ID=$(grep-Fi x-cff-request-id "$HEADERS" | tr -d '[:space:]' | cut -d: -f2) if [ -z"$REQUEST_ID" ]; then continue fi # Process requestdata RESPONSE="Echoing request: '$EVENT_DATA'" # Put response curl -X POST"http://$RUNTIME_API_ADDR/v1/runtime/invocation/response/$REQUEST_ID"-d "$RESPONSE"done

After loading the script, the runtime processes invocation events in a loop until itis terminated. It uses the API to retrieve invocation events from FunctionGraph,passes the events to the handler, and then sends responses back toFunctionGraph.

To obtain the request ID, the runtime saves the API response header in atemporary file, and then reads the request ID from the x-cff-request-id headerfield. The runtime processes the retrieved event data and sends a response back toFunctionGraph.

The following is an example of source code in Go. It can be executed only aftercompilation.

package main

import ( "bytes" "encoding/json" "fmt" "io" "io/ioutil" "log" "net" "net/http" "os"

FunctionGraphUser Guide 4 Advanced Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 96

Page 101: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

"strings" "time")

var ( getRequestUrl = os.ExpandEnv("http://${RUNTIME_API_ADDR}/v1/runtime/invocation/request") putResponseUrl = os.ExpandEnv("http://${RUNTIME_API_ADDR}/v1/runtime/invocation/response/{REQUEST_ID}") putErrorResponseUrl = os.ExpandEnv("http://${RUNTIME_API_ADDR}/v1/runtime/invocation/error/{REQUEST_ID}") requestIdInvalidError = fmt.Errorf("request id invalid") noRequestAvailableError = fmt.Errorf("no request available") putResponseFailedError = fmt.Errorf("put response failed") functionPackage = os.Getenv("RUNTIME_PACKAGE") functionName = os.Getenv("RUNTIME_FUNC_NAME") functionVersion = os.Getenv("RUNTIME_FUNC_VERSION")

client = http.Client{ Transport: &http.Transport{ DialContext: (&net.Dialer{ Timeout: 3 * time.Second, }).DialContext, }, })

func main() { // main loop for processing requests. for { requestId, header, payload, err := getRequest() if err != nil { time.Sleep(50 * time.Millisecond) continue }

result, err := processRequestEvent(requestId, header, payload) err = putResponse(requestId, result, err) if err != nil { log.Printf("put response failed, err: %s.", err.Error()) } }}

// event processing functionfunc processRequestEvent(requestId string, header http.Header, evtBytes []byte) ([]byte, error) { log.Printf("processing request '%s'.", requestId) result := fmt.Sprintf("function: %s:%s:%s, request id: %s, headers: %+v, payload: %s", functionPackage, functionName, functionVersion, requestId, header, string(evtBytes)) var event FunctionEvent err := json.Unmarshal(evtBytes, &event) if err != nil { return (&ErrorMessage{ErrorType: "invalid event", ErrorMessage: "invalid json formated event"}).toJsonBytes(), err }

return (&APIGFormatResult{StatusCode: 200, Body: result}).toJsonBytes(), nil}

func getRequest() (string, http.Header, []byte, error) {

FunctionGraphUser Guide 4 Advanced Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 97

Page 102: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

resp, err := client.Get(getRequestUrl) if err != nil { log.Printf("get request error, err: %s.", err.Error()) return "", nil, nil, err } defer resp.Body.Close()

// get request id from response header requestId := resp.Header.Get("X-CFF-Request-Id") if requestId == "" { log.Printf("request id not found.") return "", nil, nil, requestIdInvalidError }

payload, err := ioutil.ReadAll(resp.Body) if err != nil { log.Printf("read request body error, err: %s.", err.Error()) return "", nil, nil, err }

if resp.StatusCode != 200 { log.Printf("get request failed, status: %d, message: %s.", resp.StatusCode, string(payload)) return "", nil, nil, noRequestAvailableError }

log.Printf("get request ok.") return requestId, resp.Header, payload, nil}

func putResponse(requestId string, payload []byte, err error) error { var body io.Reader if payload != nil && len(payload) > 0 { body = bytes.NewBuffer(payload) }

url := "" if err == nil { url = strings.Replace(putResponseUrl, "{REQUEST_ID}", requestId, -1) } else { url = strings.Replace(putErrorResponseUrl, "{REQUEST_ID}", requestId, -1) }

resp, err := client.Post(strings.Replace(url, "{REQUEST_ID}", requestId, -1), "", body) if err != nil { log.Printf("put response error, err: %s.", err.Error()) return err } defer resp.Body.Close()

responsePayload, err := ioutil.ReadAll(resp.Body) if err != nil { log.Printf("read request body error, err: %s.", err.Error()) return err }

if resp.StatusCode != 200 { log.Printf("put response failed, status: %d, message: %s.", resp.StatusCode, string(responsePayload)) return putResponseFailedError }

return nil

FunctionGraphUser Guide 4 Advanced Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 98

Page 103: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

}

type FunctionEvent struct { Type string `json:"type"` Name string `json:"name"`}

type APIGFormatResult struct { StatusCode int `json:"statusCode"` IsBase64Encoded bool `json:"isBase64Encoded"` Headers map[string]string `json:"headers,omitempty"` Body string `json:"body,omitempty"`}

func (result *APIGFormatResult) toJsonBytes() []byte { data, err := json.MarshalIndent(result, "", " ") if err != nil { return nil }

return data}

type ErrorMessage struct { ErrorType string `json:"errorType"` ErrorMessage string `json:"errorMessage"`}

func (errMsg *ErrorMessage) toJsonBytes() []byte { data, err := json.MarshalIndent(errMsg, "", " ") if err != nil { return nil }

return data}

Table 4-2 describes the environment variables used in the preceding code.

Table 4-3

Environment Variable Description

RUNTIME_FUNC_NAME Function name

RUNTIME_FUNC_VERSION Function version

RUNTIME_PACKAGE App to which the function belongs

4.4 Environment VariablesYou can use environment variables to configure which directory to install files in,where to store outputs, and how to store connection and logging settings. Thesesettings are decoupled from the application logic, so you do not need to updateyour function code when you change the settings.

In the following code snippet, obs_output_bucket is the bucket used for storingprocessed images.

FunctionGraphUser Guide 4 Advanced Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 99

Page 104: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

def handler(event, context): srcBucket, srcObjName = getObsObjInfo4OBSTrigger(event) obs_address = context.getUserData('obs_address') outputBucket = context.getUserData('obs_output_bucket') if obs_address is None: obs_address = '{obs_address_ip}' if outputBucket is None: outputBucket = 'casebucket-out' ak = context.getAccessKey() sk = context.getSecretKey()

# download file uploaded by user from obs GetObject(obs_address, srcBucket, srcObjName, ak, sk)

outFile = watermark_image(srcObjName) # Upload converted files to a new OBS bucket. PostObject (obs_address, outputBucket, outFile, ak, sk)

return 'OK'

Using environment variable obs_output_bucket, you can flexibly set the OBSbucket used for storing output images.

Figure 4-7 Setting an environment variable

4.5 TutorialsThe use cases provided on FunctionGraph will guide you through the wholeprocess of creating serverless applications in a variety of scenarios.

Each case (see Table 4-4) is provided with the following content:

1. Dynamic display of an architecture2. Dynamic display of actual effects3. Step-by-step demonstration of the application building process

FunctionGraphUser Guide 4 Advanced Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 100

Page 105: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Table 4-4 Case description

Case Category Case Name Description

Web applications andserverless APIs

Serverless webapplication forpornographic imageidentification

Builds a serverless webapplication thatidentifies pornographicimages uploaded byusers.

Serverless webapplication for speechrecognition

Builds a serverless webapplication that analyzesuploaded speeches andconverts them into texts.

Event-based real-timedata processing

Serverless real-timeimage classificationsystem

Builds a serverlesssystem thatautomatically classifiesuploaded images andstores them in differentdirectories in OBS.

FunctionGraphUser Guide 4 Advanced Operations

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 101

Page 106: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

5 Appendixes

5.1 Creating an AgencyAn agency is an entrusting relationship created to grant specific permissions toanother account for secure and efficient service management. After an entrustingrelationship is established, the administrator of the entrusted enterprise canmanage cloud resources on behalf of the entrusting enterprise by switching roles.

Creating an Agency

Perform the following steps to create an agency:

Step 1 Log in to the IAM console, and choose Agency in the navigation pane.

Step 2 On the Agencies page, click Create Agency.

Step 3 Set the agency information, as shown in Table 5-1. For details about theparameters required for creating an agency, see Creating an Agency.

Table 5-1 Agency information

Parameter Description

Agency Name Enter serverless-trust.

Agency Type Select Cloud service.

Cloud service Perform the following steps to select acloud service:1. Click Select.2. In the Select Cloud Service dialog

box, select FunctionGraph.3. Click OK.

Validity Period Select Unlimited.

Description For this example, leave this field blank.

FunctionGraphUser Guide 5 Appendixes

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 102

Page 107: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Parameter Description

Permissions Perform the following steps to setpermissions:1. Click Assign Permissions. On the

Assign Permissions page, selectTenant Administrator, as shown inFigure 5-1.

2. Click OK.

Figure 5-1 Assigning permissions

Users with the Tenant Administrator permission can perform any operations on all cloudresources of the enterprise.

Step 4 Click OK.

----End

ExampleSee Watermarking Images.

5.2 Creating an NFS Shared Directory on ECS

Linux OS● CentOS, SUSE, EulerOS, Fedora, or openSUSE

a. Run the following command to install nfs-utils:yum install nfs-utils

b. Create a shared directory.To create shared directory /sharedata, add the following configuration tothe /etc/exports file:/sharedata 192.168.0.0/24(rw,sync,no_root_squash)

The preceding configuration is used to share the /sharedata directory with otherservers in the 192.168.0.0/24 subnet.

FunctionGraphUser Guide 5 Appendixes

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 103

Page 108: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

c. Run the following commands to start the NFS server:systemctl start rpcbindservice nfs start

d. Create another shared directory.For example, to create the /home/myself/download directory, add thefollowing configuration to the /etc/exports file:/home/myself/download 192.168.0.0/24(rw,sync,no_root_squash)Restart the NFS service.service nfs restart

Alternatively, run the following command without restarting the NFSservice:exportfs -rv

e. (Optional) Enable automatic startup of the rpcbind service in the OS.Run the following command:systemctl enable rpcbind

● Ubuntu

a. Run the following commands to install nfs-kernel-server:sudo apt-get updatesudo apt install nfs-kernel-server

b. Create a shared directory.To create shared directory /sharedata, add the following configuration tothe /etc/exports file:/sharedata 192.168.0.0/24(rw,sync,no_root_squash)

The preceding configuration is used to share the /sharedata directory with otherservers in the 192.168.0.0/24 subnet.

c. Start the NFS service.service nfs-kernel-server restart

d. Create another shared directory.For example, to create the /home/myself/download directory, add thefollowing configuration to the /etc/exports file:/home/myself/download 192.168.0.0/24(rw,sync,no_root_squash)Restart the NFS service.service nfs restart

Alternatively, run the following command without restarting the NFSservice:exportfs -rv

Windows OS1. Install an NFS server.

Paid software: haneWIN. Download the software at haneWIN officialwebsite.Free software: FreeNFS and WinNFSd. Download the software at theSourceForge website.

2. Enable the NFS function.

FunctionGraphUser Guide 5 Appendixes

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 104

Page 109: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

– In the case of WinNFSd, see WinNFSd configuration.– In the case of haneWIN, perform the following steps:

i. Run nfsctl.exe as the administrator.ii. Right-click in the blank area and choose Insert from the shortcut

menu.

Figure 5-2 Insert

5.3 Cron Expression for a Function Timer TriggerYou can configure a cron expression in the following formats for a function timertrigger:● @every format

The format is "@every N unit". N is a positive integer. unit can be ns, µs, ms,s, m, or h. An @every expression means invoking a function every N units, asshown in Table 5-2.

Table 5-2 Example expressions

Expression Meaning

@every 30m Triggers a function every 30minutes.

@every 1.5h Triggers a function every 1.5 hours.

@every 2h30m Triggers a function every 2.5 hours.

● Standard format

The format is "seconds minutes hours day-of-month month day-of-week".day-of-week is optional. The fields must be separated from each other using aspace. Table 5-3 describes the fields in a standard cron expression.

FunctionGraphUser Guide 5 Appendixes

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 105

Page 110: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Table 5-3 Parameter description

Parameter Mandatory Value Range SpecialCharactersAllowed

Seconds Yes 0–59 , - * /

Minutes Yes 0–59 , - * /

Hours Yes 0–23 , - * /

Day-of-month Yes 1–31 , - * ? /

Month Yes 1–12 or Jan–Dec.The value iscase-insensitiveas shown inTable 5-4.

, - * /

Day-of-week No 0–6 or Sun–Sat.The value iscase-insensitiveas shown inTable 5-5. 0means Sunday.

, - * ? /

Table 5-4 Value description of the month field

Month Digit Abbreviation

January 1 Jan

February 2 Feb

March 3 Mar

April 4 Apr

May 5 May

June 6 Jun

July 7 Jul

August 8 Aug

September 9 Sep

October 10 Oct

November 11 Nov

December 12 Dec

FunctionGraphUser Guide 5 Appendixes

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 106

Page 111: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Table 5-5 Value description of the day-of-week field

Day of Week Digit Abbreviation

Monday 1 Mon

Tuesday 2 Tue

Wednesday 3 Wed

Thursday 4 Thu

Friday 5 Fri

Saturday 6 Sat

Sunday 0 Sun

Table 5-6 describes the special characters that can be used in a cronexpression.

Table 5-6 Special character description

Special Character Meaning Remarks

* Used to specify allvalues within a field.

* in the minutes fieldmeans every minute.

, Used to specifymultiple values, whichcan be discontinuous.

For example,"Jan,Apr,Jul,Oct" or"1,4,7,10" in the monthfield and "Sat,Sun" or"6,0" in the day-of-week field.

- Used to specify arange.

For example, "0-3" inthe minutes field.

? Used to specifysomething in one ofthe two fields in whichthe character isallowed, but not theother.

You can specifysomething only in theday-of-month or day-of-week field. Forexample, if you wantyour function to beexecuted on aparticular day (such asthe 10th) of the month,but do not care whatday of the week that is,then put "10" in theday-of-month field and"?" in the day-of-weekfield.

FunctionGraphUser Guide 5 Appendixes

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 107

Page 112: User Guide€¦ · Custom Runtime FunctionGraph supports custom runtimes. You can use an executable file named bootstrap to include a runtime in your function deployment package

Special Character Meaning Remarks

/ Used to specifyincrements. Thecharacter before theslash indicates when tostart, and the one afterthe slash represents theincrement.

For example, "1/3" inthe minutes fieldmeans triggering thefunction every 3minutes starting from00:01:00 of the hour.

Table 5-7 describes several example cron expressions.

Table 5-7 Example cron expressions

Cron Expression Meaning

0 15 2 * * ? Executes a function at 02:15:00every day.

0 30 8 ? * Mon-Fri Executes a function at 08:30:00every Monday through Friday.

0 45 7 1-3 * ? Executes a function at 07:45:00 onthe first three days of every month.

0 0/3 * ? * Mon,Wed,Fri,Sun Executes a function every 3 minuteson every Monday, Wednesday,Friday, and Sunday.

0 0/3 9-18 ? * Mon-Fri Executes a function every 3 minutesduring 09:00–18:00 every Mondaythrough Friday.

0 0/30 * * * ? Executes a function every 30minutes.

FunctionGraphUser Guide 5 Appendixes

Issue 01 (2020-06-08) Copyright © Huawei Technologies Co., Ltd. 108