0% found this document useful (0 votes)
74 views76 pages

Alibaba Faas Programming Languages Intl en-US

Uploaded by

Riza Farwan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views76 pages

Alibaba Faas Programming Languages Intl en-US

Uploaded by

Riza Farwan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Alibaba Cloud

Alibaba Cloud

Function
Function Compute
Compute
Programming Languages
Programming Languages

Document Version: 20220712

Document Version: 20220712


Programming Languages· Legal discl
Funct ion Comput e
aimer

Legal disclaimer
Alibaba Cloud reminds you t o carefully read and fully underst and t he t erms and condit ions of t his legal
disclaimer before you read or use t his document . If you have read or used t his document , it shall be deemed
as your t ot al accept ance of t his legal disclaimer.

1. You shall download and obt ain t his document from t he Alibaba Cloud websit e or ot her Alibaba Cloud-
aut horized channels, and use t his document for your own legal business act ivit ies only. The cont ent of
t his document is considered confident ial informat ion of Alibaba Cloud. You shall st rict ly abide by t he
confident ialit y obligat ions. No part of t his document shall be disclosed or provided t o any t hird part y for
use wit hout t he prior writ t en consent of Alibaba Cloud.

2. No part of t his document shall be excerpt ed, t ranslat ed, reproduced, t ransmit t ed, or disseminat ed by
any organizat ion, company or individual in any form or by any means wit hout t he prior writ t en consent of
Alibaba Cloud.

3. The cont ent of t his document may be changed because of product version upgrade, adjust ment , or
ot her reasons. Alibaba Cloud reserves t he right t o modify t he cont ent of t his document wit hout not ice
and an updat ed version of t his document will be released t hrough Alibaba Cloud-aut horized channels
from t ime t o t ime. You should pay at t ent ion t o t he version changes of t his document as t hey occur and
download and obt ain t he most up-t o-dat e version of t his document from Alibaba Cloud-aut horized
channels.

4. This document serves only as a reference guide for your use of Alibaba Cloud product s and services.
Alibaba Cloud provides t his document based on t he "st at us quo", "being defect ive", and "exist ing
funct ions" of it s product s and services. Alibaba Cloud makes every effort t o provide relevant operat ional
guidance based on exist ing t echnologies. However, Alibaba Cloud hereby makes a clear st at ement t hat
it in no way guarant ees t he accuracy, int egrit y, applicabilit y, and reliabilit y of t he cont ent of t his
document , eit her explicit ly or implicit ly. Alibaba Cloud shall not t ake legal responsibilit y for any errors or
lost profit s incurred by any organizat ion, company, or individual arising from download, use, or t rust in
t his document . Alibaba Cloud shall not , under any circumst ances, t ake responsibilit y for any indirect ,
consequent ial, punit ive, cont ingent , special, or punit ive damages, including lost profit s arising from t he
use or t rust in t his document (even if Alibaba Cloud has been not ified of t he possibilit y of such a loss).

5. By law, all t he cont ent s in Alibaba Cloud document s, including but not limit ed t o pict ures, archit ect ure
design, page layout , and t ext descript ion, are int ellect ual propert y of Alibaba Cloud and/or it s
affiliat es. This int ellect ual propert y includes, but is not limit ed t o, t rademark right s, pat ent right s,
copyright s, and t rade secret s. No part of t his document shall be used, modified, reproduced, publicly
t ransmit t ed, changed, disseminat ed, dist ribut ed, or published wit hout t he prior writ t en consent of
Alibaba Cloud and/or it s affiliat es. The names owned by Alibaba Cloud shall not be used, published, or
reproduced for market ing, advert ising, promot ion, or ot her purposes wit hout t he prior writ t en consent of
Alibaba Cloud. The names owned by Alibaba Cloud include, but are not limit ed t o, "Alibaba Cloud",
"Aliyun", "HiChina", and ot her brands of Alibaba Cloud and/or it s affiliat es, which appear separat ely or in
combinat ion, as well as t he auxiliary signs and pat t erns of t he preceding brands, or anyt hing similar t o
t he company names, t rade names, t rademarks, product or service names, domain names, pat t erns,
logos, marks, signs, or special descript ions t hat t hird part ies ident ify as Alibaba Cloud and/or it s
affiliat es.

6. Please direct ly cont act Alibaba Cloud for any errors of t his document .

> Document Version: 20220712 I


Programming Languages· Document
Funct ion Comput e
convent ions

Document conventions
St yle Descript io n Example

A danger notice indicates a situation that Danger:


Danger will cause major system changes, faults,
Resetting will result in the loss of user
physical injuries, and other adverse
configuration data.
results.

W arning:
A warning notice indicates a situation
W arning that may cause major system changes, Restarting will cause business
faults, physical injuries, and other adverse interruption. About 10 minutes are
results. required to restart an instance.

A caution notice indicates warning No t ice:


No t ice information, supplementary instructions,
If the weight is set to 0, the server no
and other content that the user must
longer receives new requests.
understand.

A note indicates supplemental No t e:


No t e instructions, best practices, tips, and
You can use Ctrl + A to select all files.
other content.

Closing angle brackets are used to Click Set t ings > Net w o rk > Set net w o rk
>
indicate a multi-level menu cascade. t ype .

Bold formatting is used for buttons ,


Bo ld menus, page names, and other UI Click OK .
elements.

Run the cd /d C:/window command to


Courier font Courier font is used for commands
enter the Windows system folder.

bae log list --instanceid


Italic formatting is used for parameters
Italic
and variables.
Instance_ID

T his format is used for an optional value,


[] or [a|b] ipconfig [-all|-t]
where only one item can be selected.

T his format is used for a required value,


{} or {a|b} switch {active|stand}
where only one item can be selected.

> Document Version: 20220712 I


Programming Languages· Table of C
Funct ion Comput e
ont ent s

Table of Contents
1.Overview 07

2.Terms 08

3.Go 13

3.1. Runtime environment 13

3.2. Handlers 13

3.3. Event handlers 14

3.4. HT T P handlers 16

3.5. Context 18

3.6. Compilation and deployment of code packages 21

3.7. Logs 22

3.8. Error handling 23

3.9. Lifecycle callbacks for function instances 26

4.Custom Runtime 29

4.1. Overview 29

4.2. Basic principles 35

4.3. CDN 37

4.4. Event functions 37

4.5. HT T P functions 41

4.6. Lifecycle hooks for function instances 43

4.7. Specification details 44

5.Custom Container 49

5.1. Overview 49

5.2. Introduction 51

5.3. Event functions 53

5.4. HT T P functions 53

5.5. Create a function 54

> Document Version: 20220712 I


Programming Languages· Table of C
Funct ion Comput e
ont ent s

5.6. Accelerate image pull for Container Registry Personal Edition


… 57

5.7. Accelerate image pull for Container Registry Enterprise Edition


… 61

6.Programming model extensions 64

6.1. Feature overview 64

7.FAQ about code development 68

7.1. General FAQ 68

7.1.1. In which programming languages can I define functions?… 68

7.1.2. How does Function Compute ensure code security? 68

7.1.3. What do I do if the "The Access Key ID does not exist"…message


68 is returned

7.1.4. Considering that Function Compute only supports Node.js,


… how 69can I execut

7.1.5. How does Function Compute automatically install dependencies


… 69in a runtim

7.2. Custom Runtime FAQ 69

7.2.1. Must the listening port of a custom runtime be the same


… as that
70 of the HT

7.2.2. What do I do if the CAExited error occurs when the bootstrap


… file of a cus
70

7.2.3. What do I do if the CAFilePermission error occurs when


… I do not
70 have the

7.2.4. What do I do if the FunctionNotStarted error occurs when


… I invoke
71 a third-

7.2.5. What do I do if the HT T P server fails to start within 30s


… because
71 the HT T P
7.2.6. What format is required for the bootstrap file if I use …
the Windows
71 operati

7.2.7. What do I do if the "Process exited unexpectedly before


… completing
71 request

7.2.8. What do I do if a 404 error occurs when I use a browser


… or the
72 cU RL tool

7.2.9. What do I do if a 502 error that contains the "Process…exited unexpectedly


73

7.3. Custom Container FAQ 74

7.3.1. Must the listening port of a custom container runtime …


be the same
74 as that

7.3.2. What do I do if the FunctionNotStarted error occurs when


… I invoke
75 a third-
7.3.3. What do I do if the HT T P server fails to start within 30s
… because
75 the HT T P

7.3.4. What do I do if a 502 error that contains the "Process…exited unexpectedly


75

7.3.5. What do I do if a 404 error occurs when I use a browser


… or the
76 cU RL tool

7.3.6. What permissions must I grant to Function Compute service


… role
76 if Alibaba

II > Document Version: 20220712


Programming Languages· Table of C
Funct ion Comput e
ont ent s

> Document Version: 20220712 III


Funct ion Comput e Programming Languages· Overview

1.Overview
T his t opic describes informat ion about runt imes in mult iple programming languages t hat are support ed
by .

Background information
Runt imes provide environment s t hat run in t he execut ion environment for different programming
languages. As a relay bet ween and your funct ions, a runt ime passes t he values of t he event and t he
cont ext paramet ers, and t he response of a funct ion invocat ion. You can use a runt ime provided by .
You can also build a cust om runt ime or a cust om cont ainer image.

runtime

Custom runtime
T he following list provides examples of using a cust om runt ime for mult iple programming languages.
For more informat ion, see Overview .

Event f unct ions


HT T P f unct ions

Custom container
T he following list provides examples of using a cust om cont ainer for mult iple programming languages.
For more informat ion, see Overview .

Event f unct ions


HT T P f unct ions

> Document Version: 20220712 7


Programming Languages· Terms Funct ion Comput e

2.Terms
T his t opic describes some t erms of Funct ion Comput e, including t he funct ion handler, handler funct ion,
funct ion input paramet ers, log records, and t roubleshoot ing.

Function handler
When you creat e a funct ion, you must specify a handler for t he funct ion. Funct ion Comput e st art s
execut ing t he funct ion from it s handler. T he handler of a funct ion in Funct ion Comput e is in t he format
of [File name].[Function name] .

For example, when you creat e a Node.js funct ion wit h Handler set t o index.handler, Funct ion Comput e
loads t he handler funct ion defined in t he index.js file.

Handler function
A handler funct ion is a funct ion t hat is specified by a funct ion handler. T he handler funct ion is similar t o
t he main() funct ion in on-premises development . Handler funct ions must comply wit h t he programming
model provided by Funct ion Comput e.
A handler funct ion can be an event funct ion or an HT T P funct ion.

An event funct ion can be used as a regular handler funct ion t hat provides a segment of business
logic code. All handler funct ions are event funct ions except t hose for HT T P funct ions.
An HT T P funct ion is a funct ion t hat is configured wit h an HT T P t rigger. HT T P funct ions can direct ly
process HT T P request s and ret urn HT T P responses. T hey are suit able for creat ing web applicat ions.
T he programming model for HT T P funct ions is different from t hat for event funct ions.
T he following example shows an event funct ion t hat runs in a Pyt hon runt ime:

def handler(event, context):


return 'hello world'

In t his model, t he cust om event paramet er and t he plat form-defined cont ext paramet er are t he input
paramet ers of t he handler funct ion. T he handler funct ion must parse t he paramet ers and be able t o
invoke ot her funct ions defined in t he code. Except for t he definit ion, t he handler funct ion has t he same
code organizat ion logic as an on-premises funct ion.

For more informat ion about t he handler funct ion model for each programming language, see Overview .

Initializer function
Funct ion Comput e dynamically execut es funct ions on different inst ances based on request s. When a
funct ion is invoked in succession, t he funct ion can be execut ed on t he same inst ance for mult iple t imes.
An init ializer funct ion is used t o ensure t hat funct ions are execut ed on t he same inst ance only once.

In dat abase-relat ed scenarios, you can add t ime-consuming business logic t o t he init ializer funct ion,
such as t he business logic for creat ing a connect ion pool and loading funct ion dependency libraries.
T his prevent s such business logic from being repeat ed each t ime t he funct ion is invoked, and reduces
t he lat ency of t he funct ion.

Prior t o handler funct ions, init ializer funct ions are execut ed aft er Funct ion Comput e allocat es funct ions
t o be execut ed on different inst ances. Alt hough HT T P funct ions and event funct ions have different
programming models, t heir corresponding init ializer funct ions have t he same programming model.

For more informat ion about t he init ializer funct ion model for each programming language, see t he
corresponding programming language.

8 > Document Version: 20220712


Funct ion Comput e Programming Languages· Terms

Input parameters of functions


Input paramet ers of a funct ion are t he cont ent passed t o t he funct ion when t he funct ion is invoked.
Input paramet ers of a funct ion usually consist of t he event paramet er and t he cont ext paramet er.
However, t he number of input paramet ers may vary wit h t he programming language and environment .

event paramet er
T he event paramet er is a cust om input paramet er for a funct ion. It is passed t o t he funct ion in t he
format of byt e st reams. T he dat a st ruct ure of t he event paramet er can be cust omized and can be a
simple st ring, a JSON object , or a pict ure (which is binary dat a). Funct ion Comput e does not int erpret
t he cont ent of t he event paramet er. You must convert byt e st reams t o t he corresponding dat a t ype
in t he funct ion.
T he value of t he event paramet er varies based on t rigger condit ions.
If a funct ion is t riggered by an event source service, t he event source service passes t he event t o
t he funct ion as t he event paramet er in a format predefined by Funct ion Comput e. You can writ e
code in t his format and obt ain informat ion from t he event paramet er. For example, when you use
an Object St orage Service (OSS) event t rigger, OSS passes t he informat ion about t he bucket and it s
object s t o t he event paramet er in t he JSON format .
If a funct ion is invoked by using an SDK, you can cust omize t he event paramet er bet ween t he
invoker and t he funct ion code. T he invoker passes dat a in t he defined format , and t he funct ion
code obt ains t he dat a in t he same format . For example, you can define {"key":"val"} , a dat a
st ruct ure in t he JSON format , as t he event paramet er. When an invoker passes t he dat a {"key"
:"val"} , t he funct ion code convert s byt e st reams t o dat a in t he JSON format and t hen invokes
event["key"] t o obt ain t he value of t he val field.

T he following sample code provides an example on how t o use t he event paramet er in Pyt hon:

import json
def handler(event, context):
evt = json.loads(event)
print(evt['key'])
return 'success'

cont ext paramet er


T he cont ext paramet er is a funct ion input paramet er defined by Funct ion Comput e. Designed by
Funct ion Comput e, t he dat a st ruct ure of t he cont ext paramet er cont ains t he runt ime informat ion of
a funct ion. T he cont ext paramet er has t he following dat a st ruct ure:

> Document Version: 20220712 9


Programming Languages· Terms Funct ion Comput e

Dat a st ruct ure

{
requestId: '9cda63c3-1ac9-45ba-8a59-2593bb9bc101',
credentials: {
accessKeyId: 'xxx',
accessKeySecret: 'xxx',
securityToken: 'xxx'
},
function: {
name: 'xxx',
handler: 'index.handler',
memory: 512,
timeout: 60,
initializer: 'index.initializer',
initializationTimeout: 10
},
service: {
name: 'xxx',
logProject: 'xxx',
logStore: 'xxx',
qualifier: 'xxx',
versionId: 'xxx'
},
region: 'xxx',
accountId: 'xxx'
}

Scenarios
Obt ain t he t emporary AccessKey pair of a user from context.credentials and use t he
t emporary AccessKey pair in context t o access ot her Alibaba Cloud services, such as OSS. T his
prevent s t he use of hard-coded keys in code.
Obt ain t he basic informat ion of t he current execut ion from context . Such basic informat ion
includes t he request ID, service name, funct ion name, and service version or alias.

Example
T he following sample Pyt hon code provides an example on how t o use t he personal informat ion in
t he context paramet er t o access OSS:

import json
import oss2
def handler(event, context):
creds = context.credentials
auth = oss2.StsAuth(creds.access_key_id, creds.access_key_secret, creds.security_to
ken)
bucket = oss2.Bucket(auth, 'oss-endpoint', 'your-bucket-name')
bucket.put_object('object-name', 'Awesome FC')
return 'success'

Log records

10 > Document Version: 20220712


Funct ion Comput e Programming Languages· Terms

Funct ion Comput e is int egrat ed wit h log records. Funct ion Comput e st ores all funct ion invocat ion
records and t he logs print ed in funct ion code int o Logst ores. You can make a record of funct ion logs by
execut ing t he logging st at ement s provided by Funct ion Comput e. T his helps you debug t he funct ion
and t roubleshoot issues.

Not e
You must configure a Logst ore at t he service level so t hat Funct ion Comput e sends funct ion
logs t o t he specified Logst ore.
Funct ion Comput e aut omat ically creat es and configures Logst ores for funct ions and
services t hat are creat ed in t he Funct ion Comput e console.

Built-in log printing Logging statement


Programming language statement of the provided by Function References
programming language Compute

Node.js console.log() console.log() Print logs

logging.getLogger().inf
Python print() HT T P handlers
o()

context.getLogger().inf
Java System.out.println() Print logs
o()

$GLOBALS['fcLogger']-
PHP echo "" . PHP_EOL Log printing
>info()

context.Logger.LogInfor
C# Console.WriteLine("") Print logs
mation()

Logs print ed by using t he built -in log print ing st at ement s of programming languages are also collect ed
t o Logst ores. T o facilit at e log filt ering, each log print ed by using t he logging st at ement s provided by
Funct ion Comput e is t agged wit h t he request ID.

# Log printed by using the built-in log printing statements of programming languages
# print('hello world')
message: hello world
# Log printed by using the logging statements provided by Function Compute
# logger.info('hello world')
message: 2020-03-13T04:06:49.099Z f84a9f4f-2dfb-41b0-9d6c-1682a2f3a650 [INFO] hello world

Log elements
A funct ion execut ion log cont ains t he service name, funct ion name, t he current funct ion version, alias,
and code logs.

T he following example shows t he dat a st ruct ure of a funct ion execut ion log:

> Document Version: 20220712 11


Programming Languages· Terms Funct ion Comput e

__source__:
__tag__:__receive_time__: 1584072413
__topic__: myService
functionName: myFunction
message: 2020-03-13T04:06:49.099Z f84a9f4f-2dfb-41b0-9d6c-1682a2f3a650 [INFO] hello world
qualifier: LATEST
serviceName: myService
versionId:

When t he execut ion of a funct ion st art s, t he syst em print s FC Invoke Start RequestId: f84a9f4f-2
dfb-41b0-9d6c-1682a2f3a650 , which indicat es t hat funct ion execut ion st art s.

When t he execut ion of a funct ion is complet e, t he syst em print s FC Invoke End RequestId: f84a9f4
f-2dfb-41b0-9d6c-1682a2f3a650 , which indicat es t hat funct ion execut ion ends.

Troubleshooting
Errors in Funct ion Comput e include t wo t ypes: HandledInvocationError and
UnhandledInvocationError .

HandledInvocat ionError
Only t he errors ret urned by t he callback paramet er in Node.js funct ions are of t he HandledInvoc
ationError t ype. Error informat ion is cont ained in responses.

'use strict';
module.exports.handler = function(event, context, callback) {
console.log('hello world');
callback('this is error', 'hello world');
}

T he following example shows a response t hat cont ains error informat ion.

{"errorMessage":"this is error"}

UnhandledInvocat ionError
All errors except t hose of t he HandledInvocationError t ype are of t he UnhandledInvocationErro
r t ype.
T he st ack t race of an UnhandledInvocationError error is print ed in logs. You can view t he logs t o
find t he corresponding st ack t race based on t he cont ext .

12 > Document Version: 20220712


Funct ion Comput e Programming Languages· Go

3.Go
3.1. Runtime environment
T his t opic describes t he runt ime environment for writ ing funct ion code in Go in .

Go runtime
support s Go 1.x. We recommend t hat you use Go 1.8 or lat er.

Name OS Architecture

Go 1.x Linux x86_64

Not ice T he Go runt ime must be used on Linux and does not support t he ARM64 archit ect ure.

SDK for Go and related tools


provides t he following SDK for Go and relat ed t ools:

Funct ion Comput e SDK for Go: t he implement at ion of t he programming model for t he Go runt ime.
processes handlers based on t he SDK.
fccont ext : t he auxiliary library t hat provides cont ext informat ion for funct ion execut ion.
examples: t he sample code for t he Go runt ime.

Related information
Handlers
Event handlers
HT T P handlers
Cont ext
Compilat ion and deployment of code packages
Logs
Error handling
Lifecycle callbacks for funct ion inst ances

3.2. Handlers
T his t opic describes handlers and how t o configure handlers in t he Go runt ime in .

What is a handler?
A handler for a funct ion in is t he met hod t hat is used t o process request s in t he funct ion code. When a
funct ion is invoked, uses t he handler t hat you configure t o process request s. You can configure a
handler by specifying a value for t he Request Handler paramet er in t he .

T he handler for funct ions in t he Go language is compiled int o an execut able binary file. You only need
t o set t he Request Handler paramet er of t he funct ion t o t he name of t he execut able file.

For more informat ion about t he definit ions and operat ions of funct ions in , see Manage functions.

Configure a handler

> Document Version: 20220712 13


Programming Languages· Go Funct ion Comput e

When you configure a handler, make sure t hat you follow t he configurat ion specificat ions t hat are
described in . T he configurat ion specificat ions vary based on t he handler t ype.

Handlers are classified int o event handlers and HT T P handlers. Event request s are generat ed by event
sources, and HT T P request s are generat ed by HT T P t riggers. For more informat ion, see Function types.

For more informat ion about how t o configure handlers, see Event handlers and HT T P handlers.

References
For more informat ion about how t o compile and deploy your code package t o , see Compilation and
deployment of code packages.

3.3. Event handlers


T his t opic describes t he st ruct ure and charact erist ics of event handlers for Go.

Sample code for using an event handler


Import an official SDK library named aliyun/serverless/fc-runtime-go-sdk/fc for Go and implement
t he handler and main funct ions. Sample code:

package main
import (
"fmt"
"context"
"github.com/aliyun/fc-runtime-go-sdk/fc"
)
type StructEvent struct {
Key string `json:"key"`
}
func HandleRequest(ctx context.Context, event StructEvent) (string, error) {
return fmt.Sprintf("hello, %s!", event.Key), nil
}
func main() {
fc.Start(HandleRequest)
}

T he value of t he event input paramet er is a JSON st ring t hat cont ains t he key informat ion, as
shown in t he following sample code:

{
"key": "value"
}

T he following cont ent describes t he code snippet s in t he sample code:

package main : t he main package. Each Go applicat ion cont ains a main package.
import : import s Funct ion Comput e dependencies. You need t o import t he following
dependencies:
github.com/aliyun/fc-runtime-go-sdk/fc : t he core library of SDK for Go.

context : t he cont ext object of SDK for Go.

func HandleRequest(ctx context.Context, event StructEvent) (string, error) : t he handler

14 > Document Version: 20220712


Funct ion Comput e Programming Languages· Go

used t o process event request s. T he handler cont ains t he code t o be run and involves t he following
paramet ers:
ctx context.Context : provides t he runt ime cont ext informat ion when a funct ion is invoked in .
For more informat ion, see Cont ext .
event StructEvent : specifies t he dat a t o be passed in when t he funct ion is invoked. Mult iple
dat a t ypes are support ed.
string, error : ret urns t he ST RING error t ype and t he error message. For more informat ion, see
Error handling.
return fmt.Sprintf("Hi,%s ! ", event.Key), nil : ret urns hello and t he value of t he eve
nt paramet er t hat is passed in. If nil is ret urned, no error occurs.

func main() : t he ent ry point for running funct ion code in . A Go applicat ion must cont ain t he ma
in funct ion. You can add fc.Start(HandleRequest) t o run your applicat ion in .

Not ice T he met hods used t o st art an HT T P handler and an event handlers are different .
T o st art an event handler, invoke t he fc.Start funct ion in t he main funct ion. T o st art an
HT T P handler, invoke t he fc.StartHttp funct ion in t he main funct ion.

Signatures for event handlers


T he following signat ures for event handlers are valid:

func ()

func () error

func (InputType) error

func () (OutputType, error)

func (InputType) (OutputType, error)

func (context.Context) error

func (context.Context, InputType) error

func (context.Context) (OutputType, error)

func (context.Context, InputType) (OutputType, error)

T he InputType and OutputType object s are compat ible wit h t he encoding/json st andard
library.

You must use an event handler based on t he following rules:

T he handler must be a funct ion.


T he handler can cont ain up t o t wo input paramet ers. If t he handler cont ains t wo input paramet ers,
t he first input paramet er must be context.Context .
T he handler can ret urn up t o t wo values. If only one value is ret urned, t he value must indicat e t he e
rror t ype. If t wo values are ret urned, t he second value must indicat e t he error message.

Sample code for event handlers for Go:

event -st ruct .go: t he sample code for a handler whose event object is of t he ST RUCT t ype.
event -st ring.go: t he sample code for a handler whose event object is of t he ST RING t ype.
event -map.go: t he sample code for a handler whose event object is of t he map[string]interfa

> Document Version: 20220712 15


Programming Languages· Go Funct ion Comput e

ce{} t ype.

For more informat ion about t he sample code for ot her handlers, visit examples.

Context
For more informat ion about t he cont ext , see Context .

3.4. HTTP handlers


You can use HT T P handlers t o efficient ly process HT T P request s. When you invoke a funct ion, runs t he
handler t hat you specify in t he funct ion code t o process request s. T his t opic describes t he st ruct ure
and charact erist ics of HT T P handlers for Go.

Sample code for using an HTTP handler


Import an official SDK library named aliyun/serverless/fc-runtime-go-sdk/fc for Go and implement
t he handler and main funct ions. Sample code:

package main
import (
"context"
"fmt"
"net/http"
"io/ioutil"
"github.com/aliyun/fc-runtime-go-sdk/fc"
)
func HandleHttpRequest(ctx context.Context, w http.ResponseWriter, req *http.Request) error
{
body, err := ioutil.ReadAll(req.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Header().Add("Content-Type", "text/plain")
w.Write([]byte(err.Error()))
return nil
}
w.WriteHeader(http.StatusOK)
w.Header().Add("Content-Type", "text/plain")
w.Write([]byte(fmt.Sprintf("Hi,%s! \n", body)))
return nil
}
func main() {
fc.StartHttp(HandleHttpRequest)
}

T he following cont ent describes t he code snippet s in t he sample code:

package main : t he main package. Each Go applicat ion cont ains a main package.
import : import s dependencies. You need t o import t he following dependencies:

github.com/aliyun/fc-runtime-go-sdk/fc : t he core library of SDK for Go.

context : t he cont ext object of SDK for Go.

net/http : provides t he Request and ResponseWrit er met hods in t he HT T P package for t he


HT T P handler.

16 > Document Version: 20220712


Funct ion Comput e Programming Languages· Go

HandleHttpRequest(ctx context.Context, w http.ResponseWriter, req *http.Request) error :


t he HT T P handler used t o process HT T P request s. T he handler cont ains t he code t o be run and
involves t he following paramet ers:
ctx context.Context : provides t he runt ime cont ext informat ion when a funct ion is invoked. For
more informat ion, see Cont ext .
w http.ResponseWriter : t he response met hod of t he HT T P handler. You can call t his met hod t o
set t he st at us code, response header, and response body. For more informat ion, see t he Response
met hod sect ion.
req *http. Request : t he request met hod of t he HT T P handler. You can call t his met hod t o set
t he request line, request header, and request body. For more informat ion, see Request st ruct .
w.WriteHeader(http.StatusOK) : Specify t he HT T P st at us code of t he response.

w.Header(). Add("Content-Type", "text/plain") : Specify t he response header.

w.Write([]byte(fmt.Sprintf("Hi,%s! \n", body))) : Specify t he response body.

return nil : ret urns a simple error message. If nil is ret urned, no error occurs. If an error
message is ret urned, a funct ion error occurs.

func main() : t he ent ry point for running funct ion code in . A Go applicat ion must cont ain t he ma
in funct ion. T o run your applicat ion in , invoke t he fc.StartHttp(HandleHttpRequest) funct ion in
t he main() funct ion.

Not ice T he met hods used t o st art an HT T P handler and an event handlers are different .
T o st art an event handler, invoke t he fc.Start funct ion in t he main funct ion. T o st art an
HT T P handler, invoke t he fc.StartHttp funct ion in t he main funct ion.

Definition
An HT T P handler for Go is defined based on Handler int erface for HT T P request s in t he Go st andard
library but cont ains an addit ional context paramet er. Synt ax of an HT T P handler:

function(ctx context.Context, w http.ResponseWriter, req *http.Request) error

An HT T P handler consist s of t he following t hree object s:

context : provides t he runt ime cont ext informat ion when a funct ion is invoked in . For more
informat ion, see Cont ext .
http.Request : t he request st ruct . For more informat ion, see Request st ruct .

http.ResponseWriter : t he response met hod. For more informat ion, see Response met hod.

Request struct
http.Request is t he HT T P object defined in t he Go st andard library. T he following t able describes
t he paramet ers t hat are support ed by t he ht t p.Request object .

Parameter T ype Description

T he HT T P request method, such


Method String
as PUT , POST , or DELET E.

URL *url.URL T he request URL.

> Document Version: 20220712 17


Programming Languages· Go Funct ion Comput e

Parameter T ype Description

T he key-value pair of the HT T P


Header http.Header
request header.

Body io.ReadCloser T he request struct.

T he data length in the request


ContentLength Int64
struct.

Response method
T he following sample code shows t he t hree met hods declared by http.ResponseWriter :

type ResponseWriter interface {


Header() Header
Write([]byte) (int, error)
WriteHeader(statusCode int)
}

Not e:

WriteHeader(statusCode int) : set s t he st at us code.

Header() Header : set s t he response header.

Write([]byte) (int, error) : set s t he response body.

Context
For more informat ion about t he cont ext , see Context .

3.5. Context
T his t opic describes t he cont ext in t he Go runt ime in and provides sample code.

What is context?
When runs your funct ion code, it passes t he cont ext object context.Context t o t he handler. T his
object cont ains informat ion about invocat ions, services, funct ions, t racing analysis, and runt ime
environment s.

You can use t he cont ext object as an input paramet er for event handlers and HT T P handlers. T he
format and cont ent of t he cont ext input paramet er for event handlers and HT T P handlers are t he
same. T he following t able describes t he paramet ers t hat are support ed by t he cont ext object .

Cont ext

Parameter Description

V ariables

T he unique ID of the request for invoking the


RequestID function. You can record the ID for troubleshooting
if an error occurs.

18 > Document Version: 20220712


Funct ion Comput e Programming Languages· Go

Parameter Description

T he temporary AccessKey pair that obtains by


assuming your service-linked role. T he temporary
AccessKey pair is valid for 5 minutes. You can use
credentials in your code to access related services
Credentials such as Object Storage Service (OSS). T his way, you
do not need to write your AccessKey pair in the
function code. For more information, see Grant
permissions across Alibaba Cloud accounts by using
a RAM role.

T he basic information of the invoked function, such


Function as the name, handler, memory, and timeout period
of the function.

T he information about the service to which the


function belongs, such as the name, the related
project and Logstore in Log Service, the version, and
Service the alias of the service. T he qualifier
parameter specifies the version or alias of the
service. T he version_id parameter specifies the
version of the service.

T he ID of the region in which the function is invoked.


For example, if the function is invoked in the China
Region
(Shanghai) region, the region ID is cn-shanghai. For
more information, see Endpoints.

T he ID of the Alibaba Cloud account that is used to


AccountId
invoke the function.

Met ho d

T he timeout period of function execution. T he value


deadline
is in the UNIX timestamp format. Unit: milliseconds.

For more informat ion about t he complet e dat a st ruct ure, see cont ext .go.

Sample code
Sample code for displaying the context information
Add t he context paramet er t o t he handler of your funct ion. passes t he variable informat ion
described in t he preceding Cont ext t able t o t he context paramet er. T hen, import t he aliyun/fc-
runtime-go-sdk/fccontext package and call t he fccontext.FromContext met hod t o obt ain
fccontext .

> Document Version: 20220712 19


Programming Languages· Go Funct ion Comput e

package main
import (
"context"
"encoding/json"
"log"
"github.com/aliyun/fc-runtime-go-sdk/fc"
"github.com/aliyun/fc-runtime-go-sdk/fccontext"
)
func main() {
fc.Start(echoContext)
}
func echoContext(ctx context.Context) (string, error) {
fctx, _ := fccontext.FromContext(ctx)
log.Println(fctx.AccountId)
log.Printf("%#v\n", fctx)
res, _ := json.Marshal(fctx)
return string(res), nil
}

Sample code for obtain the remaining execution time of a function


T he following sample code provides an example on how t o use t he deadline paramet er t o obt ain
t he remaining execut ion t ime of a funct ion:

package main
import (
"context"
"fmt"
"log"
"time"
"github.com/aliyun/fc-runtime-go-sdk/fc"
)
func LongRunningHandler(ctx context.Context) (string, error) {
deadline, _ := ctx.Deadline()
fmt.Printf("now: %s\ndeadline: %s\n", time.Now().String(), deadline.String())
deadline = deadline.Add(-100 * time.Millisecond)
timeoutChannel := time.After(time.Until(deadline))
for {
select {
case <-timeoutChannel:
return "Finished before timing out.", nil
default:
log.Print("hello!")
time.Sleep(50 * time.Millisecond)
}
}
}
func main() {
fc.Start(LongRunningHandler)
}

3.6. Compilation and deployment of


20 > Document Version: 20220712
Funct ion Comput e Programming Languages· Go

3.6. Compilation and deployment of


code packages
Go is a st at ic compilat ion language. If you use Go, you must locally compile and package your code in
t he ZIP format . T his t opic describes how t o package official SDK for Go wit h t he code t hat you compile.

Prerequisites
T he Go programming language is inst alled. support s Go 1.x. We recommend t hat you use Go 1.8 or lat er.

Compile and package code on Linux or macO S


1. Download SDK for Go.

go get github.com/aliyun/fc-runtime-go-sdk/fc

2. Compile files.

GOOS=linux go build main.go

Not e T he main.go file is only for reference. Replace it wit h your act ual file name.

Set t he GOOS paramet er t o linux so t hat t he compiled execut able files are compat ible wit h t he
Go runt ime of . Pay special at t ent ion t o t his when you compile your files in a non-Linux
environment .
Not e:
On Linux, we recommend t hat you use pure st at ic compilat ion and set t he CGO_ENABLED
paramet er t o 0. T his way, t he execut able files do not require ext ernal dependencies such as t he
libc library. T his prevent s incompat ibilit y bet ween t he compilat ion environment and t he
dependencies of t he Go runt ime. Sample code:

GOOS=linux CGO_ENABLED=0 go build main.go

If your machine uses M1 macOS or ot her ARM archit ect ures, set t he GOARCH paramet er t o
amd64 t o allow cross-plat form compilat ion. Sample code:

GOOS=linux GOARCH=amd64 go build main.go

3. Package t he files.

zip fc-golang-demo.zip main

Compile and package files on Windows


1. Compile t he execut able files.
i. Press t he Win+R keys t o open t he Run dialog box.
ii. Ent er cmd and press t he Ent er key.
iii. In t he command prompt window, run t he following commands:

set GOOS=linux
set GOARCH=amd64
go build -o main main.go

> Document Version: 20220712 21


Programming Languages· Go Funct ion Comput e

2. Use t he build-fc-zip t ool t o package t he files.


i. Run t he go get command t o download t he build-fc-zip t ool from Git Hub.

go get -u github.com/aliyun/fc-runtime-go-sdk/cmd/build-fc-zip

ii. Use t he build-fc-zip t ool t o package t he files. If you use t he default inst allat ion met hod for
Go , t he t ool is inst alled in t he %USERPROFILE%\go\bin direct ory.

~\go\bin\build-fc-zip.exe -output main.zip main

Configure function handlers in


1. Create a service.
2. Create a function. Set t he Runt ime Environment s t o Go 1 .

Go is a compilat ion language. You need t o upload t he execut able binary file aft er t he file is locally
compiled. When you configure t he function handler for a Go funct ion in t he , set t he Request
Handler paramet er t o [File name] . T he file name is t he name of t he compiled binary file. When
t he funct ion is invoked, execut es t he binary file.
T he following figure shows an example of t he ZIP package. In t his case, if you set t he Request
Handler paramet er t o main , execut es t he main binary file in t he root direct ory of t he ZIP
package.

If t he compiled binary file is not st ored in t he root direct ory of t he ZIP package but in anot her
direct ory such as bin/, you need t o set t he Request Handler paramet er t o bin/main .

For more informat ion about ot her deployment met hods, see t he following t opics:

Use SDKs t o deploy funct ions


Use Serverless Devs t o deploy funct ions

3.7. Logs
T his t opic describes how t o display logs in t he Go runt ime environment .

Display logs
T o display logs, you can use t he met hods provided by t he built -in logging library of Go, called log, or
ot her Logst ores t hat are used t o writ e logs t o st dout or st derr.

T he logs displayed by using t he met hods provided by t he log library cont ain t he dat e and t ime
informat ion. T he following sample code provides an example on how t o display logs by using t he
met hods provided by t he log library:

22 > Document Version: 20220712


Funct ion Comput e Programming Languages· Go

package main
import (
"log"
"aliyun/serverless/fc-runtime-go-sdk/fc"
)
func HandleRequest() (string, error) {
log.Println("hello world")
return "hello world", nil
}
func main() {
fc.Start(HandleRequest)
}

T he following logs are displayed:

FC Invoke Start RequestId: a15f8f85-9ed3-47c9-a61c-75678db61831


2022/02/17 04:29:02.228870 hello world
FC Invoke End RequestId: a15f8f85-9ed3-47c9-a61c-75678db61831

T he Go runt ime records t he St art and End lines and t he execut ion summary for each funct ion
invocat ion.

T he following t able describes t he paramet ers in t he execut ion summary.

Parameter Description

T he unique ID of the request for invoking the


Request ID
function.

T he verification code of the code package used for


Code verification code
invoking the function.

T he time that the function handler actually takes to


Function execution time
run.

T he amount of time in which you are charged for


Function billing time
invoking the function.

Function memory T he amount of memory allocated for the function.

T he maximum amount of memory that is actually


Actual memory usage
used by the function.

3.8. Error handling


T his t opic describes how t o handle errors in t he Go runt ime environment .

> Document Version: 20220712 23


Programming Languages· Go Funct ion Comput e

If an error occurs, t he HT T P response header cont ains X-Fc-Error-Type such as X-Fc-Error-Type:


UnhandledInvocationError . For more informat ion about error t ypes of , see Error handling.

can ret urn errors in t he following ways:

Specify t he error message t o ret urn in t he handler funct ion. Sample code:

package main
import (
"errors"
"fmt"
"aliyun/serverless/fc-runtime-go-sdk/fc"
)
func HandleRequest() error {
fmt.Println("hello world")
return errors.New("something is wrong")
}
func main() {
fc.Start(HandleRequest)
}

Aft er t he funct ion is invoked, t he following response is ret urned:

{
"errorMessage": "something is wrong!",
"errorType": "errorString"
}

Use panic t o ret urn an error message. Sample code:

package main
import (
"fmt"
"aliyun/serverless/fc-runtime-go-sdk/fc"
)
func HandleRequest() error {
fmt.Println("hello world")
panic("Error: something is wrong")
return nil
}
func main() {
fc.Start(HandleRequest)
}

Aft er t he funct ion is invoked, t he following response is ret urned. In t his example, some st ack
informat ion is omit t ed.

24 > Document Version: 20220712


Funct ion Comput e Programming Languages· Go

{
errorMessage: 'Error: something is wrong',
errorType: 'string',
stackTrace: [
{
path: 'aliyun/serverless/fc-runtime-go-sdk/fc/errors.go',
line: 39,
label: 'fcPanicResponse'
},
{
path: 'aliyun/serverless/fc-runtime-go-sdk/fc/function.go',
line: 84,
label: '(*Function).Invoke.func1'
},
...
...
...
{ path: 'code/main.go', line: 22, label: 'main' },
{ path: 'runtime/proc.go', line: 255, label: 'main' },
null
]
}

Use error handling code such as log.Fatal t hat cont ains os.Exit(1) .

Not ice We recommend t hat you do not use t his met hod. If you use t his met hod, no error
message or st ack informat ion is ret urned upon an exit .

package main
import (
"fmt"
"log"
"aliyun/serverless/fc-runtime-go-sdk/fc"
)
func HandleRequest() error {
fmt.Println("hello world")
log.Fatal("something is wrong")
return nil
}
func main() {
fc.Start(HandleRequest)
}

Aft er t he funct ion is invoked, t he following response is ret urned:

{
errorMessage: 'Process exited unexpectedly before completing request (duration: 0ms, ma
xMemoryUsage: 8MB)'
}

3.9. Lifecycle callbacks for function


> Document Version: 20220712 25
Programming Languages· Go Funct ion Comput e

3.9. Lifecycle callbacks for function


instances
T his t opic describes how t o invoke lifecycle callbacks for funct ion inst ances in t he Go runt ime
environment .

Context
Aft er you implement and configure a lifecycle callback for a funct ion inst ance, invokes t he callback if a
relat ed lifecycle event for t he inst ance occurs. A funct ion inst ance involves t he following lifecycle
callbacks: init ializer, PreFreeze, and PreSt op. T he Go runt ime support s only t he init ializer callback. For
more informat ion, see Lifecycle callbacks for funct ion inst ances.

Initializer callback
T he init ializer callback is invoked aft er t he funct ion inst ance is st art ed but before t he handler runs.
ensures t hat t he init ializer callback can be successfully invoked at most once wit hin t he lifecycle of a
funct ion inst ance. For example, if t he init ializer callback fails, t he syst em keeps ret rying unt il t he
init ializer callback is successfully invoked, and t hen runs your handler. Make sure t hat t he init ializer
callback can be successfully invoked when you implement t he init ializer callback.

T he init ializer callback cont ains only t he cont ext input paramet er and can be invoked in t he same way
as a handler.

function(ctx context.Context)

Use the initializer callback


T o use t he init ializer callback, perform t he following st eps:

1. Use fc.RegistryInitializerFunction(Init) in your applicat ion code t o regist er an init ializer


callback.
Sample code:

26 > Document Version: 20220712


Funct ion Comput e Programming Languages· Go

package main
import (
"context"
"log"
"github.com/aliyun/fc-runtime-go-sdk/fc"
)
var (
count int = 1
)
func Init(ctx context.Context) {
count += 1000
}
func main() {
fc.RegisterInitializerFunction(Init)
fc.Start(HandleRequest)
}
func HandleRequest() (int, error) {
count += 1
log.Println("count: ", count)
return count, nil
}

T he following cont ent describes t he code snippet s in t he sample code:


func Init(ctx context.Context) : t he init ializer callback. T he ctx context.Context
paramet er specifies t he runt ime informat ion for invoking a funct ion in . For more informat ion, see
Cont ext .
func main(): t he ent ry point for running funct ion code in . A Go applicat ion must cont ain t he ma
in funct ion. You can add fc.Start(HandleRequest) t o your code t o specify t he met hod t o
execut e t he handler, and add fc.RegisterInitializerFunction(Init) t o regist er t he
init ializer callback.

Not ice T he preceding sample code applies only t o an event handler. If you use an
HT T P handler, replace fc.Start(HandleRequest) in t he sample code wit h fc.StartHttp(
HandleRequest) .

2. Configure t he init ializer callback on t he funct ion configurat ion page of t he , as shown in t he
following figure.

For more informat ion, see Manage functions.

Sample code

> Document Version: 20220712 27


Programming Languages· Go Funct ion Comput e

provides sample code for invoking t he init ializer callback. T he sample code provides an example on how
t o use t he init ializer callback in t he Go runt ime environment t o init ialize a MySQL connect ion pool. In t he
sample code, t he MySQL dat abase is configured by using an environment variable of t he funct ion. For
more informat ion, see t he s.yaml file. T he init ializer callback obt ains t he dat abase configurat ion based
on t he environment variable, creat es a MySQL connect ion pool, and t hen t est s t he connect ivit y.

For more informat ion, see go-init ializer-mysql.

28 > Document Version: 20220712


Programming Languages· Cust om Ru
Funct ion Comput e
nt ime

4.Custom Runtime
4.1. Overview
T his t opic describes t he background informat ion, cont ainer environment , basic principles, configurat ion
requirement s, common request headers, and log format s of a cust om runt ime.

Background information
Cust om runt imes allow you t o define runt ime environment s. In a cust om runt ime, you can define t he
runt ime environment based on your requirement s. For example, you can perform t he following
operat ions:

Use a specified programming language, such as Lua.


Use a runt ime environment of t he specified version for a programming language, such as Node.js 16.

If you want t o creat e a cust om runt ime by using a language t hat is not a built -in language of t he
cust om runt ime, you must compress t he parser or runt ime of t he language and your code file int o a
package and deploy t he package in . For example, if t he runt ime environment is Node.js 16, you must
download t he int erpret er of Node.js 16, compress t he int erpret er and your code file int o a package,
and t hen deploy t he package in .

A cust om runt ime support s t he following built -in languages of t he specified versions. You can creat e
cust om runt imes of t he following languages wit hout t he need t o inst all t hird-part y int erpret ers:

Pyt hon 3.7.4


Node.js 10.16.2
Ruby 2.7
PowerShell 7.1.0
Nginx 1.10.3
OpenJDK 1.8.0_232
PHP 7.4.12
Built -in ext ensions for PHP

bcmath calendar Core

ctype curl date

dom exif FFI

fileinfo filter ftp

gd gettext hash

iconv imagick imap

intl json libxml

mbstring mcrypt memcached

mysqli mysqlnd openssl

pcntl pcre PDO

> Document Version: 20220712 29


Programming Languages· Cust om Ru
Funct ion Comput e
nt ime

pdo_mysql pdo_pgsql pdo_sqlite

pgsql Phar posix

protobuf readline redis

Reflection session shmop

SimpleXML soap sockets

sodium SPL sqlite3

standard swoole sysvmsg

sysvsem sysvshm tokenizer

xml xmlreader xmlrpc

xmlwriter xsl Zend OPcache

zip zlib

For more informat ion about t he built -in soft ware of a cust om runt ime, visit Git Hub.

Container environment
A cust om runt ime runs in t he following cont ainer environment :

Operat ing syst em: Debian 9


User permissions:
If funct ions are creat ed at and aft er 00:00:00 December 1, 2021, t he funct ions must be execut ed
by t he root user.
If funct ions are creat ed before 00:00:00 December 1, 2021, t he funct ions must be execut ed by a
non-root user.

Direct ory permissions:


If funct ions are creat ed at and aft er 00:00:00 December 1, 2021, all t he direct ories are writ able.
If funct ions are creat ed before 00:00:00 December 1, 2021, only t he /tmp direct ory is writ able.

Basic principles
T o creat e a cust om runt ime, you must creat e an execut able file named bootstrap t o st ore t he
command t hat is used t o st art an HT T P server whose default port is port 9000. Compress t he boot st rap
file and your code file int o a ZIP package, and t hen creat e a cust om runt ime funct ion by using t he ZIP
package as t he code package.

For example, you can name t he deployment package of a funct ion function.zip. T he following
examples show t he files cont ained in t he deployment package and t he cont ent of t he bootstrap file
based on t he programming language t hat is used t o develop t he funct ion.

Java or Spring Boot Pyt hon Node.js PHP

30 > Document Version: 20220712


Programming Languages· Cust om Ru
Funct ion Comput e
nt ime

Not e If an execut able bootstrap file is found in t he code package of a funct ion, execut es
t he file when a user invokes t he funct ion. If no boot st rap file is found in t he code package of a
funct ion or t he file is not execut able, Funct ion Comput e ret urns an error when a user invokes t he
funct ion.

T o cold st art t he cust om runt ime, calls t he bootstrap file by default t o st art your cust om HT T P server.
T hen, t he HT T P server t akes over all request s from , including t he invocat ions of event and HT T P
funct ions.
Before you develop t he logic of a funct ion, you must det ermine whet her t he funct ion is an event
funct ion or an HT T P funct ion. T he following figures show how an event funct ion and an HT T P funct ion
work.
Event funct ion

HT T P funct ion

Configuration requirements on an HTTP server


When you creat e an HT T P server, make sure t hat t he following requirement s are met :
Services t hat are st art ed in a cust om runt ime must list en on 0.0.0.0:CAPort or *:CAPort . If you
configure t he services t o list en on 127.0.0.1:CAPort , a request t imes out and t he following error
is ret urned:

{
"ErrorCode":"FunctionNotStarted",
"ErrorMessage":"The CA's http server cannot be started:ContainerStartDuration:250000000
00. Ping CA failed due to: dial tcp 21.0.5.7:9000: getsockopt: connection refused Logs :
2019-11-29T09:53:30.859837462Z Listening on port 9000"
}

T he default list ening port (CAPort ) of a cust om runt ime is port 9000. If a cust om runt ime uses t he
default list ening port , t he list ening port of it s HT T P server must be port 9000. If t he list ening port of
t he cust om runt ime is port 8080, t he list ening port of it s HT T P server must be port 8080.
If t he bootstrap file of t he cust om runt ime is a Shell script , add #!/bin/bash . Ot herwise, t he
following error is ret urned:

> Document Version: 20220712 31


Programming Languages· Cust om Ru
Funct ion Comput e
nt ime

{
"ErrorCode":"CAExited",
"ErrorMessage":"The CA process either cannot be started or exited:ContainerStartDurat
ion:25037266905. CA process cannot be started or exited already: rpc error: code = 106 de
sc = ContainerStartDuration:25000000000. Ping CA failed due to: dial tcp 21.0.7.2:9000: i
/o timeout Logs : 2019-11-29T07:27:50.759658265Z panic: standard_init_linux.go:178: exec
user process caused \"exec format error\"
}

If t he boot st rap file is a binary execut able file, such as a binary file compiled by using Go or C++, you
do not need t o add #!/bin/bash .
T he bootstrap file of a cust om runt ime must be execut able. Ot herwise, t he following error is
ret urned:

{
"ErrorCode":"CAFilePermission",
"ErrorMessage":"The CA process cannot be started due to bootstrap file don't have exe
cute permissions"
}

You can use one of t he following met hods t o resolve t he error:


Run t he chmod + x boot st rap or chmod 755 boot st rap command before you compress files.
If you use t he Windows operat ing syst em, convert t he format of t he bootstrap file t o UNIX.

You must set t he Connect ion paramet er t o Keep-Alive and t he request t imeout period t o 15 minut es
or longer. T he following sample code provides an example on how t o specify t he values:

// In this example, the express framework for Node.js is used.


var server = app.listen(PORT, HOST);
server.timeout = 0; // never timeout
server.keepAliveTimeout = 0; // keepalive, never timeout

T he HT T P server must complet e t he st art up wit hin 120 seconds.

Common request headers in Function Compute


T he following t able describes t he common request headers t hat a cust om runt ime may receive from . If
you want t o access ot her Alibaba Cloud services, you may need t o use t he request headers t hat specify
a t emporary AccessKey pair. If you migrat e exist ing applicat ions t o Funct ion Comput e, skip t he
following headers.

Not e
Bot h event funct ions and HT T P funct ions cont ain common request headers.
generat es common request headers t hat cont ain basic informat ion about permissions and
funct ions.

Header Description

x-fc-request-id T he ID of the request.

x-fc-access-key-id T he temporary AccessKey ID.

32 > Document Version: 20220712


Programming Languages· Cust om Ru
Funct ion Comput e
nt ime

Header Description

x-fc-access-key-secret T he temporary AccessKey secret.

x-fc-security-token T he temporary security token.

T he handler of the function. T his value is not


x-fc-function-handler
required if the custom runtime is a function.

x-fc-function-memory T he maximum memory that the function can use.

T he handler of the initializer function. T his value is


x-fc-function-initializer
not required if the custom runtime is a function.

x-fc-initialization-timeout T he timeout period of the initializer function.

x-fc-region T he region of the function.

x-fc-account-id T he UID of the function owner.

T he service version or alias that is specified when


x-fc-qualifier the function is invoked. For more information, see
View the version for a function.

x-fc-version-id T he version of the function.

T he name of the Function Compute service to which


x-fc-service-name
the function belongs.

T he Log Service project that is configured for the


x-fc-service-logproject Function Compute service to which the function
belongs.

T he Log Service Logstore that is configured for the


x-fc-service-logstore Function Compute service to which the function
belongs.

> Document Version: 20220712 33


Programming Languages· Cust om Ru
Funct ion Comput e
nt ime

Header Description

T he request type of the function.


For a custom runtime or custom container, you can
determine whether a request is used to invoke an
HT T P function or an event function based on the
value of this parameter. Valid values:
/invoke: T he request is used to invoke an event
function.
/http-invoke: T he request is used to invoke an
HT T P function. adds common headers to your
request that contains the request path, request
body, and request headers, and forwards the
x-fc-control-path
request to the custom runtime or custom
container. T hen, Function Compute forwards the
response headers and body returned by the
custom runtime or custom container to the client.
/initialize: T he request is automatically initiated
by to invoke an initializer function when a runtime
environment is created and runs for the first time.
Similar to a class constructor, the initializer
function is invoked only once in the lifecycle of a
container.

Function log formats


We recommend t hat you use Log Service when you creat e a service in Funct ion Comput e. T hen, all t he
generat ed st dout logs are st ored in t he specified Log Service project . For more informat ion, see
Configure the logging feature.

(Opt ional)If invokes a funct ion in a runt ime t hat is not a cust om runt ime or a cust om cont ainer, and t he
request cont ains t he x-fc-log-type" = "Tail" header, t he cont ent t hat cont ains t he x-fc-log-
result header in t he response is t he log generat ed when t he funct ion is execut ed. T he maximum size
of a log is 4 KB. You can view t he log in funct ion execut ion result s in t he . If you want t o view t he logs
of a cust om runt ime in funct ion execut ion result s in t he console, you must record t he st art and end logs
of request s in t he code.

Log content Required Code format

34 > Document Version: 20220712


Programming Languages· Cust om Ru
Funct ion Comput e
nt ime

Log content Required Code format

FunctionCompute ${runtime}
runtime inited.

No t e You can specify


No a custom value for
${runtime} . We
No t e T he cold start recommend that you do not
A runtime starts
flag of the function is specify an official language
recorded. name, such as Node.js,
Python, or PHP.

FC Invoke Start RequestId:


Invocation starts Yes
${RequestId}

FC Invoke End RequestId:


Invocation ends Yes
${RequestId}

No

No t e For an initializer FC Initialize Start


Initialization starts
function, this log must be RequestId: ${RequestId}
recorded.

No

No t e For an initializer FC Initialize End


Initialization ends
function, this log must be RequestId: ${RequestId}
recorded.

In addit ion t o t he preceding informat ion, we recommend t hat you include request IDs in your logs in t he
$utcdatetime(yyyy-MM-ddTHH:mm:ss.fff) $requestId [$Level] $message format for fut ure
t roubleshoot ing.

Not e T he API operat ion t o specify t he log level varies based on t he programming language.
For more informat ion, see Log records.

References
For more informat ion about t he limit s of cust om runt imes, see Limits.

4.2. Basic principles

> Document Version: 20220712 35


Programming Languages· Cust om Ru
Funct ion Comput e
nt ime

For a cust om runt ime, t he code file in t he ZIP format is an HT T P server program. T his t opic describes t he
basic principles of cold st art s of a cust om runt ime and t he requirement s for t he configurat ions of HT T P
servers.

Basic principles
For a cust om runt ime, t he code file in t he ZIP format is an HT T P server program. You need t o only
configure t he St art up Command and St art up Paramet er paramet ers for t he funct ion t o st art t he
HT T P server. When performs a cold st art in a cust om runt ime, t he St art up Command and St art up
Paramet er paramet ers are used t o st art your cust om HT T P server. T he HT T P server t akes over all
request s from . T he default port of an HT T P server is 9000. If you use anot her port , such as 8080, for
t he HT T P server, you can set t he list ening port in t he funct ion configurat ions t o 8080.

For example, t he name of t he code package of a funct ion is function.zip. T he following examples show
t he files t hat are cont ained in t he package and t he St art up Command and St art up Paramet er
paramet ers based on t he programming language t hat is used t o develop t he funct ion.

Java 8 or Spring Boot Pyt hon 3.7 Node.js 10 PHP 7.4

.
├── demo.jar

customRuntimeConfig:
command:
- java
args:
- '-jar'
- 'demo.jar'

Not e customRuntimeConfig specifies t he cust om st art up commands for t he funct ion.


command specifies t he st art up commands for t he cont ainer. args specifies t he st art up
paramet ers. concat enat es t he cont ent in command and args t o form a complet e st art up
command.

Requirements on HTTP server configurations


When you creat e an HT T P server, make sure t hat t he following requirement s are met :

Services t hat are st art ed in a cust om runt ime must list en on 0.0.0.0:CAPort or *:CAPort . If you
use t he 127.0.0.1:CAPort port , a request t imes out , and t he following error is ret urned:

{
"ErrorCode":"FunctionNotStarted",
"ErrorMessage":"The CA's http server cannot be started:ContainerStartDuration:250000000
00. Ping CA failed due to: dial tcp 21.0.XX.XX:9000: getsockopt: connection refused Logs
: 2019-11-29T09:53:30.859837462Z Listening on port 9000"
}

T he default list ening port of a cust om runt ime is port 9000. If a cust om runt ime uses t he default
list ening port , t he list ening port of it s HT T P server must be port 9000. If t he list ening port of t he
cust om runt ime is port 8080, t he list ening port of it s HT T P server must be port 8080.

36 > Document Version: 20220712


Programming Languages· Cust om Ru
Funct ion Comput e
nt ime

You must set t he connect ion t o t he keep-alive mode and t he request t imeout period t o 24 hours (t he
maximum funct ion running period) or longer. Sample code:

// In this example, the express framework for Node.js is used.


var server = app.listen(PORT, HOST);
server.timeout = 0; // never timeout
server.keepAliveTimeout = 0; // keepalive, never timeout

T he HT T P server must be st art ed wit hin 120 seconds.

4.3. CDN
Context

Procedure

4.4. Event functions


T his t opic describes how t o check and invoke event funct ions in a cust om runt ime and provides
examples.

Context
In a cust om runt ime, Funct ion Comput e forwards t he common headers, request body, POST met hod,
/invoke, and /initialize t o HT T P servers. You can build an input paramet er similar t o context in an
official runt ime based on t he informat ion in common headers and an input paramet er similar t o
event in an official runt ime based on t he request body of t he invoked funct ion.

Function invocation
When you invoke an event funct ion, only t he /invoke and /initialize pat hs need t o be
implement ed.

Not ice If you do not configure t he Initializer paramet er when you creat e a funct ion,
/initialize does not need t o be implement ed. Even if /initialize is implement ed by t he
HT T P server, you cannot invoke or execut e t he /initialize logic in t he code.

Path Request Expected response

> Document Version: 20220712 37


Programming Languages· Cust om Ru
Funct ion Comput e
nt ime

Path Request Expected response

Response body: the return value


of the function handler.
StatusCode
200: succeeded
404: failed

Header: x-fc-status
200: succeeded
404: failed

T he x-fc-status field in the


response header is used to
report the invocation result of
the function to Function
Compute.
Request body: the function If you do not configure the x
input, which is the payload -fc-status field, Function
that you specify when you call Compute considers the
the InvokeFunction operation. invocation successful by
Request header: common default. However, an exception
request headers. For more may occur in your function and
information, see Common the exception is not reported
POST /invoke to Function Compute. In this
request headers in Function
Compute. case, Function Compute
considers the function
invocation successful. T his may
No t ice Content-
not affect the business logic,
Type is set to applica
but affects the monitoring
tion/octet-stream . observability.
If you configure the x-fc-st
atus field, the function
execution failure is reported to
the function system by using
the x-fc-status field and
the error stack information is
recorded to logs if an
exception occurs in the
function.

No t e We recommend
that you specify both the
StatusCode and x-fc-status
fields in the HT T P response.

38 > Document Version: 20220712


Programming Languages· Cust om Ru
Funct ion Comput e
nt ime

Path Request Expected response

Request body: none. Response body: the return value


Request header: common of the initializer function.
request headers. For more StatusCode
(Optional) POST /initialize
information, see Common 200: succeeded
request headers in Function
404: failed
Compute.

Examples


PHP


Go


Node.js


Python


Ruby


C+ +


T ypeScript


Powershell

> Document Version: 20220712 39


Programming Languages· Cust om Ru
Funct ion Comput e
nt ime


Lua


Dart


Rust


PHP


Go


Node.js


Python


Ruby


C+ +


T ypeScript

40 > Document Version: 20220712


Programming Languages· Cust om Ru
Funct ion Comput e
nt ime


Powershell


Lua


Dart


Rust

FAQ
Must t he list ening port of a cust om runt ime be t he same as t hat of t he HT T P server of t he cust om
runt ime?
What do I do if t he CAExit ed error occurs when t he boot st rap file of a cust om runt ime is a shell script ?
What do I do if t he CAFilePermission error occurs when I do not have t he permissions t o execut e t he
boot st rap file of a cust om runt ime?
What do I do if t he Funct ionNot St art ed error occurs when I invoke a t hird-part y service in a service
st art ed in a cust om runt ime?
What do I do if t he HT T P server fails t o st art wit hin 30s because t he HT T P server implement at ion
t akes a long t ime?
What format is required for t he boot st rap file if I use t he Windows operat ing syst em?
What do I do if t he "Process exit ed unexpect edly before complet ing request " message is ret urned?
What do I do if a 404 error occurs when I use a browser or t he cURL t ool t o access a funct ion?

4.5. HTTP functions


T his t opic describes how t o det ermine and invoke HT T P funct ions in a cust om runt ime and provides
sample code and limit s.

Context
Funct ion Comput e forwards your request s, including t he met hod, pat h, query, request headers, request
body, and common headers generat ed by Funct ion Comput e t o t he HT T P server. HT T P funct ions allow
you t o migrat e exist ing HT T P web applicat ions.

Invocations
T he invocat ion of an HT T P funct ion is like t he invocat ion of a web API. You can init iat e an invocat ion
request by using cURL, Post man, or a browser. For more informat ion about t he solut ion t o t he case
where t he relevant funct ion is downloaded in a forced manner when you use a browse t o access an
HT T P t rigger, see Solution.

> Document Version: 20220712 41


Programming Languages· Cust om Ru
Funct ion Comput e
nt ime

Not ice If t he initializer paramet er is not specified when a funct ion is creat ed,
/initialize does not need t o be implement ed. In t his case, even if /initialize is
implement ed by t he HT T P server, t he /initialize logic in t he code cannot be invoked or
execut ed.

Path Request Expected response

Request body: none. Response body: the return value


Request header: common of the function initializer .
request headers. For more StatusCode
(Optional) POST /initialize
information, see Common
200: succeeded.
request headers in Function
Compute. 404: failed.

Header Description

If a custom domain name is not specified, the x-fc-


(Optional) x-fc-base-path base-path value is /2016-08-
15/proxy/${servicename}/${functionname}/ .

If your HT T P function is not used for a migration but


as a new web API, it is similar to an event function.
(Optional) x-fc-status T he x-fc-status field can be used to report to
Function Compute whether the function invocation is
successful. For more information, see Overview.

Limits
Aft er an HT T P t rigger is set for a funct ion, ot her t ypes of t riggers cannot be set for t his funct ion.
Only one HT T P t rigger can be creat ed for each funct ion.
If version management is enabled for a funct ion, only one HT T P t rigger can be creat ed for each
version or alias of t he funct ion. In ot her words, one HT T P t rigger can be creat ed for one version or
one alias of a funct ion. For more informat ion about versions and aliases, see Int roduct ion t o versions.
T he following fields in a request header and request headers t hat st art wit h x-fc- cannot be
cust omized:
accept -encoding
connect ion
keep-alive
proxy-aut horizat ion
te
t railer
t ransfer-encoding

T he following fields in a response header and response headers t hat st art wit h x-fc- cannot be
cust omized:
connect ion
cont ent -lengt h

42 > Document Version: 20220712


Programming Languages· Cust om Ru
Funct ion Comput e
nt ime

cont ent -encoding


dat e
keep-alive
proxy-aut hent icat e
server
t railer
t ransfer-encoding
upgrade
cont ent -disposit ion:at t achment

Not e For securit y, when t he default aliyuncs.com domain name of Funct ion Comput e is
used, t he server forcibly adds t he cont ent -disposit ion: at t achment field t o t he response
header. T his field is used t o download t he ret urned result in t he browser as an at t achment . T o
remove t his limit , you must set a cust om domain name.

Limit s on HT T P request s
If a request exceeds one of t he following limit s, t he syst em ret urns st at us code 400 and error
code InvalidArgument .
Header size: T he t ot al size of all keys and values in t he headers cannot exceed 4 KB.
Pat h size: T he t ot al size of t he pat h, including all of t he query paramet ers, cannot exceed 4 KB.
Body size: T he t ot al size of t he HT T P request body cannot exceed 6 MB.

Limit s on HT T P responses
If a response exceeds one of t he following limit s, t he syst em ret urns st at us code 502 and error
code BadResponse .

Header size: T he t ot al size of all keys and values in t he headers cannot exceed 4 KB.

Ot her inst ruct ions


You can map different HT T P pat hs for HT T P funct ions by binding a cust om domain name. You can
also use API Gat eway, set t he backend service t ype t o HT T P, and configure t he HT T P funct ion pat h
as t he backend service address t o implement similar feat ures. For more informat ion, see Use Funct ion
Comput e as t he backend service of an API operat ion.

4.6. Lifecycle hooks for function


instances
T his t opic describes how t o implement lifecycle hooks for funct ion inst ances in a cust om runt ime.

Lifecycle hooks
Aft er you configure a lifecycle hook for a funct ion inst ance, invokes t he hook when a relat ed lifecycle
event for t he inst ance occurs. T he following lifecycle hooks can be configured for a funct ion inst ance:
Init ializer, PreFreeze, and PreSt op hooks. For more informat ion, see Function instance lifecycle.

Path Request Expected response

> Document Version: 20220712 43


Programming Languages· Cust om Ru
Funct ion Comput e
nt ime

Path Request Expected response

Response body: the return value


of the Initializer hook.
StatusCode
200: T he request succeeded.
404: T he request failed.
Sample code of initialize
in Python:
Request body: none. @app.route('/initialize',
Request header: common methods=['POST'])
request headers. For more def init_invoke():
(Optional) POST /initialize
information, see Common rid =
request headers in Function request.headers.get(x-fc-
Compute. request-id)
print("FC Initialize
Start RequestId: " + rid)
# do your things
print("FC Initialize
End RequestId: " + rid)
return "OK"

Request body: none. Response body: the return value


Request header: common of the PreFreeze hook.
request headers. For more StatusCode
(Optional) GET /pre-freeze
information, see Common 200: T he request succeeded.
request headers in Function
404: T he request failed.
Compute.

Request body: none. Response body: the return value


Request header: common of the PreStop function.
request headers. For more StatusCode
(Optional) GET /pre-stop
information, see Common 200: T he request succeeded.
request headers in Function
404: T he request failed.
Compute.

If you want t o use t he Init ializer hook in a cust om runt ime, you need t o only implement t he logic t hat
corresponds t o t he /initialize pat h and t he POST met hod in your HT T P server. You can refer t o
t he sample code for initialize in t he preceding t able.

Not ice If you do not configure t he Init ializer hook for t he funct ion, t he /initialize pat h
does not need t o be implement ed. Even if t he /initialize pat h is implement ed by t he HT T P
server, you cannot invoke or execut e t he /initialize logic in t he code.

T he PreFreeze and PreSt op met hods are used in t he same manner as t he Init ializer met hod.

4.7. Specification details


44 > Document Version: 20220712
Programming Languages· Cust om Ru
Funct ion Comput e
nt ime

T his t opic describes t he common request headers, HT T P st at us codes, response headers, and log
format s of a cust om runt ime.

Common request headers in Function Compute


T he following t able describes t he common request headers t hat forwards t o a cust om runt ime. If you
want t o access ot her Alibaba Cloud services, you may need t o use t he request headers t hat specify a
t emporary AccessKey pair. If you migrat e exist ing applicat ions t o Funct ion Comput e, skip t he following
informat ion.

Not e
Event funct ions and HT T P funct ions cont ain common request headers.
generat es common request headers t hat cont ain basic informat ion about permissions and
funct ions.

Header Description

x-fc-request-id T he ID of the request.

x-fc-access-key-id T he temporary AccessKey ID.

x-fc-access-key-secret T he temporary AccessKey secret.

x-fc-security-token T he temporary security token.

T he handler of the function. If the custom runtime is


x-fc-function-handler a function, you do not need to specify a value for
this header.

x-fc-function-memory T he maximum memory that the function can use.

T he handler of the initializer function. If the custom


x-fc-function-initializer runtime is a function, you do not need to specify a
value for this header.

x-fc-initialization-timeout T he timeout period of the initializer function.

x-fc-region T he region where the function resides.

x-fc-account-id T he user ID (UID) of the function owner.

T he service version or alias that you specify when


x-fc-qualifier you invoke the function. For more information, see
Overview.

x-fc-version-id T he version of the function.

T he name of the service to which the function


x-fc-service-name
belongs.

T he Log Service project that is configured for the


x-fc-service-logproject
service to which the function belongs.

> Document Version: 20220712 45


Programming Languages· Cust om Ru
Funct ion Comput e
nt ime

Header Description

T he Log Service Logstore that is configured for the


x-fc-service-logstore
service to which the function belongs.

T he request type of the function.


For a custom runtime or custom container, you can
check whether you sent a request to invoke an HT T P
function or an event function based on the value of
this parameter. Valid values:
/invoke: T he request is sent to invoke an event
function.
/http-invoke: T he request is sent to invoke an
HT T P function. adds common headers to your
request that contains the request path, request
x-fc-control-path body, and request headers, and forwards the
request to the custom runtime or custom
container. T hen, Function Compute forwards the
response headers and body that are returned by
the custom runtime or custom container to the
client.
/initialize: T he first time you create a runtime
environment, automatically initiates a request to
invoke an initializer function. Similar to a class
constructor, you can invoke the initializer function
only once during the lifecycle of a container.

HTTP status codes and response headers in Function Compute


A cust om runt ime can work as an HT T P server. Each funct ion invocat ion t hat you make is an HT T P
request . T his way, each response includes a response code and a response header.

HT T P st at us code ( StatusCode )
200 : succeeded

404 : failed

Response header ( x-fc-status )


200 : succeeded

404 : failed

You can include t he x-fc-status field in response headers t o report whet her t he local funct ion is
invoked t o .
If you do not specify a value for t he x-fc-status field, considers t he invocat ion successful. If an
error occurs during funct ion execut ion, t he syst em does not report t he error t o . In t his case, t he
business logic is not affect ed, but t he observabilit y of is affect ed. T he following figure provides an
example.

46 > Document Version: 20220712


Programming Languages· Cust om Ru
Funct ion Comput e
nt ime

If you specify a value for t he x-fc-status field, t he syst em report s funct ion invocat ion failures t o
by using t he x-fc-status field. If an error occurs during funct ion invocat ion, t he syst em records
t he error st ack informat ion in logs. T he following figure provides an example.

Not e We recommend t hat you specify t he StatusCode and x-fc-status fields in t he


HT T P response.

Function log formats


We recommend t hat you enable logging when you creat e a service in Funct ion Comput e. T his way, all
st dout logs t hat t he syst em generat es are st ored in t he specified Log Service project . For more
informat ion, see Configure the logging feature.
If invokes a funct ion in a runt ime t hat is not a cust om runt ime or a cust om cont ainer, and t he request
cont ains t he x-fc-log-type" = "Tail" header, t he response t hat cont ains t he x-fc-log-result
header is t he log t hat t he syst em generat es when t he syst em invokes t he funct ion. T he maximum size
of a log is 4 KB. You can view t he log in t he result s of t he funct ion invocat ion in t he . If you want t o
view t he logs of a cust om runt ime in t he result s of t he funct ion invocat ion in t he console, you must
record t he st art and end logs of t he request s.

> Document Version: 20220712 47


Programming Languages· Cust om Ru
Funct ion Comput e
nt ime

Log Required Code

FunctionCompute ${runtime}
runtime inited.

No
No t e You can specify
a custom value for the
No t e T he cold start
Start of the runtime ${runtime} parameter.
flag of the function is
We recommend that you do
recorded.
not specify an official
language name in , such as
Node.js, Python, or PHP.

FC Invoke Start RequestId:


Start log of function invocation Yes
${RequestId}

FC Invoke End RequestId:


End log of function invocation Yes
${RequestId}

No

No t e If you use an FC Initialize Start


Start log of function initialization
initializer function, record RequestId: ${RequestId}
this log.

No

No t e If you use an FC Initialize End


End log of function initialization
initializer function, record RequestId: ${RequestId}
this log.

We recommend t hat you also include t he request ID in your logs for diagnost ics in t he fut ure and t he
request ID in your logs is in t he $utcdatetime(yyyy-MM-ddTHH:mm:ss.fff) $requestId [$Level]
$message format .

Not e T he API operat ion t hat you can perform t o specify t he log level varies based on t he
programming language. For more informat ion, see Log records.

References
Overview
Basic principles
Event funct ions
HT T P funct ions
Lifecycle hooks for funct ion inst ances

48 > Document Version: 20220712


Programming Languages· Cust om Co
Funct ion Comput e
nt ainer

5.Custom Container
5.1. Overview
T his t opic describes t he background informat ion, basic principles, configurat ion requirement s on an
HT T P server, log format s, cold st art opt imizat ion, billing, and limit s of cust om cont ainers.

Background information
In t he cloud-nat ive era, cont ainer images have become a st andard t ool for soft ware deployment and
development . T o improve developer experience and t he development and delivery efficiency, allows
developers t o use cust om cont ainers as t he runt ime environment s of funct ions. T he developers can
deliver t heir funct ions as cont ainer images and int eract wit h over HT T P. Cust om cont ainers have t he
following benefit s:

You can perform cost -effect ive migrat ion and maint ain consist ency bet ween development and
product ion environment s wit hout modifying code or recompiling binary and shared object s (*.so).
Compressed images can be up t o 3 GB in size. T his allows you t o package code and dependencies
t oget her for easier dist ribut ion and deployment .
Cont ainer images are nat ively st ored in a cache hierarchy. T his improves t he efficiency of uploading
and pulling code.
St andard, replicable t hird-part y libraries can be used for referencing, sharing, building, code
uploading, st orage, and version management . T his offers a comprehensive open source ecosyst em
for cont inuous int egrat ion and cont inuous delivery (CI/CD).

Basic principles
T he basic principles of a cust om cont ainer are t he same as t hose of a custom runtime. Before init ializes
an inst ance, Funct ion Comput e assumes t he service role of t he funct ion t o obt ain a t emporary
username and password and pull an image. Aft er t he image is pulled, Funct ion Comput e st art s your
HT T P server by using t he specified st art up command (Command), paramet ers (Args), and CAPort (port
9000 by default ). T hen, t he HT T P server t akes over all request s from , including t he invocat ions of event
and HT T P funct ions.

Before you develop t he logic of a funct ion, you must det ermine whet her t he funct ion is an event
funct ion or an HT T P funct ion. T he following figures show how an event funct ion and an HT T P funct ion
work.

Event funct ion

HT T P funct ion

Configuration requirements on an HTTP server


Services t hat are st art ed in a cust om cont ainer must list en on 0.0.0.0:CAPort or *:CAPort . If

> Document Version: 20220712 49


Programming Languages· Cust om Co
Funct ion Comput e
nt ainer

you configure t he services t o list en on 127.0.0.1:CAPort , t he request t imes out , and t he following
error is ret urned:

{
"ErrorCode":"FunctionNotStarted",
"ErrorMessage":"The CA's http server cannot be started:ContainerStartDuration:250000000
00. Ping CA failed due to: dial tcp 21.0.5.7:9000: getsockopt: connection refused Logs :
2019-11-29T09:53:30.859837462Z Listening on port 9000"
}

T he default list ening port (CAPort ) of a cust om cont ainer is port 9000. If a cust om cont ainer uses t he
default list ening port , t he list ening port of it s HT T P server must be port 9000. If t he list ening port of
t he cust om cont ainer is port 8080, t he list ening port of it s HT T P server must be port 8080.
You must set t he Connect ion paramet er t o Keep-Alive and t he request t imeout period t o 15 minut es
or longer. T he following sample code provides an example on how t o specify t he values:

// In this example, the Express framework for Node.js is used.


var server = app.listen(PORT, HOST);
server.timeout = 0; // never timeout
server.keepAliveTimeout = 0; // keepalive, never timeout

T he HT T P server must complet e t he st art up wit hin 120 seconds.

Common request headers in Function Compute


T he common request headers t hat a cust om cont ainer can receive are t he same as t hose t hat a cust om
runt ime can receive. For more informat ion, see Common request headers in Function Compute.

Function log formats


A cust om cont ainer uses t he same log format s as a cust om runt ime. For more informat ion, see Function
log formats.

Best practices for cold start optimization


In comparison wit h code packages, cont ainer images rely on t he basic environment and consume
addit ional t ime t o download and decompress dat a. T o improve t he cold st art experience, we
recommend t he following best pract ices:

For opt imal lat ency and st abilit y when a cont ainer image is pulled, we recommend t hat you use a
virt ual privat e cloud (VPC) endpoint of t he cont ainer image in t he same region as . Example: registry-v
pc.cn-hangzhou.aliyuncs.com/fc-demo/helloworld:v1beta1.
T o minimize t he size of images, you can build cust om images based on minimized images such as
Alpine or Ubunt u. You can include only necessary dependencies in an image and exclude unnecessary
document s, dat a, and files.
You can use cont ainer images t oget her wit h provisioned inst ances. For more informat ion, see
Configure provisioned inst ances and aut o scaling rules.
When resources are sufficient and t hreads are secure, you can use an inst ance t o concurrent ly
process mult iple request s t o avoid unnecessary cold st art s and reduce cost s.

Billing
T he billable it ems for a cust om cont ainer are t he same as t hose for ot her t ypes of runt imes. For more
informat ion, see Billing.

50 > Document Version: 20220712


Programming Languages· Cust om Co
Funct ion Comput e
nt ainer

T he execut ion durat ion of an image resource is t he period from t he t ime when an inst ance st art s t o pull
t he image from t he image reposit ory t o t he t ime when t he image is pulled. For example, if an inst ance
configured wit h 1,024 MB of memory t akes 10 seconds t o pull an image, t he resource usage for t his pull
is 10 GB-s.

Cont ainer images are cached in a specific range for a specific period of t ime. T herefore, you may not be
charged for an image pull during a cold st art .

Limits
Image reposit ory
You can pull images from t he image reposit ories of Cont ainer Regist ry Ent erprise Edit ion and Personal
Edit ion. For more informat ion, see What is Container Registry? .
Image access
You can read images only from privat e image reposit ories in t he same region and wit hin t he same
account .
Read and writ e permissions on files in a cont ainer
By default , t he UID of run-as-user is t hat of t he root user. If you specify a user in Dockerfile, t he
specified user runs t he cont ainer image.
St orage space limit of t he writ able layer in a cont ainer
Dat a t hat is generat ed by a cont ainer cannot exceed 512 MB, excluding dat a in t he read-only image
layer.

Not e Dat a st ored in t he writ able layer of a cont ainer does not persist . If t he cont ainer is
delet ed, t he dat a is also delet ed. T o persist dat a, you can int egrat e wit h Apsara File St orage
NAS. For more informat ion, see Configure a NAS file syst em. You can also use ot her st orage
services t o persist dat a, such as Object St orage Service (OSS) or T ablest ore.

5.2. Introduction
T his t opic describes t he definit ion and paramet ers of a service.

Definition
A service is a resource management unit in Funct ion Comput e. In business scenarios, a single applicat ion
can be divided int o mult iple services. From t he resource ut ilizat ion perspect ive, a single service can
consist of mult iple funct ions. For example, a dat a processing service is divided int o dat a preparat ion
and dat a processing. During dat a preparat ion, you can select a low-specificat ion inst ance due t o
undemanding requirement s for funct ion resources. During dat a processing, however, you need t o select
a high-specificat ion inst ance due t o demanding requirement s for funct ion resources. Before you creat e
a funct ion, you must creat e a service. All funct ions of t he same service share t he same set t ings such as
service aut horizat ion and log configurat ion. You can creat e and manage services in t he Funct ion
Comput e console or by using t he Funcraft t ool. For more informat ion, see Manage services.

Service parameters
When you creat e a service, you must specify t he paramet ers described in t he following t able.

Parameter Required Description

> Document Version: 20220712 51


Programming Languages· Cust om Co
Funct ion Comput e
nt ainer

Parameter Required Description

T he name of the service. T he service name must be


unique in the same region and cannot be modified
after the service is created. Meanwhile, the service
name must comply with the following constraints:
T he name consists of letters, numbers (0-9),
ServiceName Yes underscores (_), and hyphens (-).
T he name must start with a letter or an
underscore (_).
T he name is case-sensitive.
T he name must be 1 to 128 characters in length.

Description No T he description of the service.

Network attached storage (NAS) settings for the


service. After you configure these settings, functions
NasConfig No of the specified service can access the NAS file
system in the same way as accessing a local file
system.

Grants required permissions for the Function


Compute instance to run functions for the service.
T his parameter is applicable to the following
scenarios:
Authorize the Function Compute instance to use
Role No your Log Service resources to store and analyze
function execution logs.
Authorize the Function Compute instance to
access other cloud resources.
For more information about permissions, see User
permission.

Specifies a log project and a Logstore of Log Service


to store and analyze function execution logs.
We recommend that you enable Log Service and
configure this parameter. Otherwise, you cannot
view function execution logs.

LogConfig No No t ice When you use Log Service, you


will be billed for reserved resources. T he
minimum fee is RMB 0.04 per day, even when no
logs are generated. For more information, see
Pay-as-you-go.

Configures Virtual Private Cloud (VPC) for the service.


VpcConfig No T his parameter allows functions to access the
specified VPC instance.

52 > Document Version: 20220712


Programming Languages· Cust om Co
Funct ion Comput e
nt ainer

Parameter Required Description

Specifies whether to allow functions to access the


InternetAccess No Internet. If this parameter is set to true, functions
can access the Internet.

5.3. Event functions


T his t opic describes t he background of event funct ions in a cust om cont ainer runt ime and provides
sample code and examples in mult iple languages.

Background information
In a cust om cont ainer runt ime, Funct ion Comput e forwards t he common headers, request body, POST
met hod, /invoke, and /initialize t o t he HT T P server in t he cont ainer. You can use funct ion signat ures, like
cont ext and event , of officially support ed runt imes such as Golang Runt ime. You can also use t he
request headers and body as input paramet ers t o define t he service logic of a funct ion. For more
informat ion, see Event functions.

Sample code
In t he following Node.js Express example, Funct ion Comput e calls t he POST met hod and t he /initialize
pat h t o init ialize a funct ion inst ance. T he POST met hod and t he /invoke pat h serve as handlers when
t he funct ion is invoked. Funct ion Comput e obt ains t he cont ext and event paramet ers from
req.headers and req.body , and ret urns t he result of funct ion invocat ion as an HT T P response.

'use strict';
const express = require('express');
// Constants
const PORT = 9000;
const HOST = '0.0.0.0';
const app = express();
// initialize example, need config Initializer in function meta
app.post('/initialize', (req, res) => {
res.send('Hello FunctionCompute, /initialize\n');
});
// Event function invocation
app.post('/invoke', (req, res) => {
res.send('Hello FunctionCompute, event function\n');
});
var server = app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);
server.timeout = 0; // never timeout
server.keepAliveTimeout = 0; // keepalive, never timeout

Examples

5.4. HTTP functions


T his t opic describes t he background and limit s of HT T P funct ions in a cust om cont ainer runt ime. T his
t opic also describes how t o det ermine and invoke HT T P funct ions, and provides sample code and
examples in mult iple languages.

Background information

> Document Version: 20220712 53


Programming Languages· Cust om Co
Funct ion Comput e
nt ainer

Background information
Funct ion Comput e forwards your request s, including t he met hod, pat h, query, request headers, request
body, and common headers generat ed by Funct ion Comput e t o t he HT T P server. HT T P funct ions
enable t he smoot h migrat ion of HT T P web applicat ions. For more informat ion, see HT T P functions.

Sample code
In t he following Node.js Express example, t he GET and POST met hods are rout ed t o different handlers.
You can map a pat h t o a handler t hat you need.

'use strict';
const express = require('express');
// Constants
const PORT = 9000;
const HOST = '0.0.0.0';
// HTTP function get
const app = express();
app.get('/*', (req, res) => {
res.send('Hello FunctionCompute, http GET');
});
app.post('/*', (req, res) => {
res.send('Hello FunctionCompute, http POST');
});
app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);

Examples

5.5. Create a function


T his t opic describes how t o creat e a cust om cont ainer funct ion in t he Funct ion Comput e console or by
using Funcraft .

Prerequisites
A Cont ainer Regist ry Ent erprise or Personal Edit ion inst ance is creat ed. We recommend t hat you creat e a
Cont ainer Regist ry Ent erprise Edit ion inst ance.
A namespace and an image reposit ory for t he Cont ainer Regist ry Ent erprise Edit ion inst ance are
creat ed. For more informat ion, see t he "St ep 4: Creat e a namespace" and "St ep 5: Creat e an image
reposit ory" sect ions of t he Use a Cont ainer Regist ry Ent erprise Edit ion inst ance t o push and pull
images t opic.
A namespace and an image reposit ory for t he Cont ainer Regist ry Personal Edit ion inst ance are
creat ed. For more informat ion, see Manage namespaces and St ep 2: Creat e a reposit ory.

Create a function in the Function Compute console


1. Push your funct ion image t o t he image reposit ory for t he default inst ance.
In t his example, t he sample project is in t he /tmp direct ory, t he region of Funct ion Comput e is China
(Shenzhen), and t he name of t he image reposit ory is nodejs-express.
i. Run t he following command t o go t o t he /tmp direct ory:

cd /tmp

54 > Document Version: 20220712


Programming Languages· Cust om Co
Funct ion Comput e
nt ainer

ii. Run t he following command in t he /tmp direct ory t o decompress t he sample project :

git clone https://github.com/awesome-fc/custom-container-docs.git

iii. Run t he following command t o go t o t he custom-container-docs/nodejs-express direct ory:

cd custom-container-docs/nodejs-express

iv. Run t he following command t o specify t he image reposit ory. Replace your ACR image name
wit h t he name of your image. For example, replace your ACR image name wit h registry.cn
-shenzhen.aliyuncs.com/fc-demo/nodejs-express:v0.2 .

export IMAGE_NAME="your ACR image name"

v. Run t he following command t o package t he image:

docker build -t $IMAGE_NAME .

vi. Run t he following command t o push t he image:

docker push $IMAGE_NAME

2. Creat e a service and configure permissions for it .


i. In t he Funct ion Comput e console, creat e a service. For more informat ion, see Create a service.
ii. At t ach t he AliyunCont ainerRegist ryReadOnlyAccess or
AliyunCont ainerRegist ryFullAccess policy t o t he service. For more informat ion, see Grant
Function Compute permissions to access other Alibaba Cloud services.

T he preceding policies allow Funct ion Comput e t o obt ain t he t emporary account for t he
default inst ance in Cont ainer Regist ry. T hen, Funct ion Comput e uses t he t emporary account t o
push t he image from your privat e image reposit ory.
3. Creat e a funct ion.
In t his example, an event funct ion is creat ed. HT T P funct ions use similar paramet er set t ings.
i. Log on t o t he Funct ion Comput e console.
ii. In t he left -side navigat ion pane, click Services and Funct ions.
iii. In t he t op navigat ion bar, select t he region where t he service resides.
iv. Click Creat e Funct ion. On t he Creat e Funct ion page, move t he point er over t he Event
Funct ion sect ion and click Conf igure and Deploy .
v. In t he Conf igure Funct ion sect ion, set t he paramet ers described in t he following t able and
click Creat e .

> Document Version: 20220712 55


Programming Languages· Cust om Co
Funct ion Comput e
nt ainer

Parameter Configuration method

Service Name Select the service that you created in Step 2.

Function Name Enter a custom function name.

Runtime Select Cust o m Co nt ainer from the drop-down list.

Select a type of instance used to execute the function. Valid values:


Elast ic Inst ance
Instance T ype Perf o rmance Inst ance

For more information about instance types, see Instance types and usage
modes.

Click Select Co nt ainer Image to select an image version on the


Inst ance o f Perso nal Edit io n or Inst ance o f Ent erprise Edit io n tab.

No t e If you select a Container Registry Enterprise Edition


Container Image instance, make sure that the default IP address to which the domain
name is resolved is the address in the same VPC as Function
Compute. T he domain name cannot be resolved by using Alibaba
Cloud DNS PrivateZone.

Enter a startup command, such as ["/code/myserver"] .


Command T his parameter is optional. If you do not set this parameter, the
ENT RYPOINT or CMD command included in the image is used.

Enter additional parameters, such as ["-arg1", "value1"] .


Args T his parameter is optional. If you do not set this parameter, the CMD
command included in the image is used.

56 > Document Version: 20220712


Programming Languages· Cust om Co
Funct ion Comput e
nt ainer

Parameter Configuration method

Select the memory size used to execute the function. T he memory size
Memory
cannot be less than 512 MB.

T imeout Enter the timeout period for requests.

Enter the maximum number of requests that can be concurrently


Single Instance processed by a single instance.
Concurrency For more information, see A single instance that concurrently processes
multiple requests.

Enter the port on which the server listens.


Listening Port T his parameter is optional. Default value: 9000. You can change the
listening port on this page without the need to modify the image.

Aft er t he funct ion is creat ed, you can view t he funct ion in t he funct ion list of t he
corresponding service.

Use Funcraft to create a function


You can use Funcraft t o build and push cont ainer images and deploy funct ions wit h a few clicks.
1. Run t he following command t o clone t he cust om-cont ainer-docs example:

git clone https://github.com/awesome-fc/custom-container-docs.git

2. Run t he following command t o go t o t he custom-container-docs/nodejs-express direct ory:

cd custom-container-docs/nodejs-express

3. In t he template.yml file, replace t he value of t he Image paramet er wit h t he address of your image
in Cont ainer Regist ry.
4. Run t he following command t o build an image:

fun build --use-docker

5. Run t he following command t o deploy a funct ion:

# Deploy the function, push the image via the internet registry host (the function conf
ig uses the VPC registry for faster image pulling).
fun deploy --push-registry acr-internet

Aft er t he funct ion is deployed, you can log on t o t he Funct ion Comput e console and view t he
funct ion in t he funct ion list of t he corresponding service.

5.6. Accelerate image pull for


Container Registry Personal Edition

> Document Version: 20220712 57


Programming Languages· Cust om Co
Funct ion Comput e
nt ainer

Compared wit h funct ion code packages, cont ainer images provide bet t er port abilit y and a more diverse
ecosyst em of t oolchains. However, t he irrelevant dat a cont ained makes t he cold st art of an image t hat
is gigabyt es in size last several minut es. When you enable t he image pull accelerat ion feat ure, t he cold
st art speed can be increased in t wo phases by approximat ely 90%, and t he period of t ime t hat is
required t o pull an image can be decreased from a few minut es t o a few seconds. T his t opic describes
how does image pull accelerat ion for Cont ainer Regist ry Personal Edit ion works and how t o configure
image pull accelerat ion.

Principles
If you enable t he image pull accelerat ion feat ure when you creat e or updat e a cont ainer image in
Cont ainer Regist ry Personal Edit ion for a funct ion t hat runs in a cust om cont ainer, assumes a RAM role,
uses a t emporary AccessKey pair t o pull t he image, and t hen t ransfers t he image t o t he image cache
service of . Aft er t he image is cached, t he speed for pulling t he image is improved.

Usage notes
T he image pull accelerat ion feat ure is support ed in t he following regions: China (Beijing), China
(Zhangjiakou), China (Hangzhou), China (Shanghai), China (Shenzhen), China (Hong Kong), Singapore
(Singapore), US (Silicon Valley), and US (Virginia).
If you enable t he image pull accelerat ion feat ure, is aut horized t o pull images from your image
reposit ory and t ransfer t he images t o t he image cache service of . T o ensure dat a securit y, Cont ainer
Regist ry Personal Edit ion support s net work isolat ion and ident it y aut hent icat ion t o allow all users t o
encrypt t he dat a and rest rict access t o t he image. Before you enable t his feat ure, make sure t hat t he
operat ion of t ransferring images t o t he image cache service of complies wit h t he securit y regulat ions
and guidelines of your organizat ion.
Aft er you creat e or updat e a funct ion t hat uses a cont ainer image in Cont ainer Regist ry Personal
Edit ion, a period of t ime is required t o t ransfer t he image. T herefore, a cache miss may occur before
t he cached image becomes available. T he cached image becomes available approximat ely 5 minut es
aft er you creat e or updat e t he funct ion.

Configuration methods
You can configure image pull accelerat ion by using one of t he following met hods when you creat e or
updat e a funct ion:
Use t he console. For more informat ion, see Creat e a funct ion in t he console.

58 > Document Version: 20220712


Programming Languages· Cust om Co
Funct ion Comput e
nt ainer

T he following figure shows how t o configure t he image pull accelerat ion feat ure when you updat e a
funct ion.

Use Serverless Devs. For more informat ion, see YAML synt ax.
Add t he accelerationType paramet er t o t he CustomContainerConfig st ruct ure. Valid values:
Default : enables t he image pull accelerat ion feat ure.

None : disables t he image pull accelerat ion feat ure.

T he following sample code shows how t o enable t he image pull accelerat ion feat ure:

customContainerConfig:
image: registry-vpc.<regionId>.aliyuncs.com/fc-demo/python-flask:[Image version]
accelerationType: Default

For more informat ion about t he complet e procedure, see Sample project puppet eer-pdf.
Use SDKs.

View the status of image pull acceleration


You can view t he st at us of image pull accelerat ion by using one of t he following met hods t o det ermine
whet her t he cached image is available:
On t he Conf igurat ions t ab of t he funct ion det ails page in t he , view t he value of t he Image
Accelerat ion Preparat ion St at us paramet er in t he Environment Inf ormat ion sect ion. Valid
values:
Preparing : Image pull accelerat ion is being prepared.
Available : Image pull accelerat ion is ready.
Failed : Failed t o accelerat e t he image pull.

> Document Version: 20220712 59


Programming Languages· Cust om Co
Funct ion Comput e
nt ainer

Example:

Call t he Get Funct ion operat ion and check t he value of t he st at us paramet er in t he accelerat ionInfo
st ruct ure t o view t he st at us of image pull accelerat ion. Valid values:
Preparing : Image pull accelerat ion is being prepared. If you invoke t he funct ion now, t he
original image is pulled, and t he image pull is not accelerat ed.
Ready : Image pull accelerat ion is ready. If you invoke t he funct ion now, t he image pull is
accelerat ed.
Failed : Failed t o accelerat e t he image pull.

Best practices for versioning


If you use Cont ainer Regist ry Personal Edit ion and enable t he image pull accelerat ion feat ure, t he
t ransfer of t he new image is t riggered when you updat e t he image for t he funct ion. When you invoke
t he funct ion before t he cached image is available, t he original image is pulled and t he image pull is not
accelerat ed. You can syst emat ically publish t he funct ion by managing the function and managing versions:
1. Updat e t he funct ion. When you updat e t his funct ion, t he LAT EST version of t he service is also
updat ed.
2. Aft er t he st at us of image pull accelerat ion changes from Preparing t o Available , publish a new
service version.
3. Swit ch t he service alias t o t he new service version.

View the results of image pull acceleration


Aft er you enable t he image pull accelerat ion feat ure, t he cold st art speed is increased in t wo phases.

Sample project puppet eer-pdf provides an example on how t o combine Node.js Express and Puppet eer
t o convert a web page int o a PDF file.
Before t he image pull accelerat ion feat ure is enabled, t he process t akes 66.51s. Aft er you enable t he
image pull accelerat ion feat ure, t he process t akes only 15.2s for t he first phase and t he cold st art
speed is increased by 77.1%. T he process t akes only 4.3s for t he second phase and t he cold st art speed
is increased by 71.6%. T he cold st art speed is increased by 93.5% in t ot al. Sample code:

60 > Document Version: 20220712


Programming Languages· Cust om Co
Funct ion Comput e
nt ainer

time curl -H "x-fc-invocation-target: 2016-08-15/proxy/CustomContainerDemo/puppeteer-pdf-no


-accl" https://$ACCOUNT_ID.$REGION.fc.aliyuncs.com/generate-pdf\?url\=http://example.com -o
/tmp/fc-demo-puppeteer-pdf-no-accl.pdf
# Time spent: 0.06s user 0.09s system 0% cpu 1:06.51 total time
# First image cold start after the image pull acceleration feature is enabled
curl -H "x-fc-invocation-target: 2016-08-15/proxy/CustomContainerDemo/puppeteer-pdf-accl" h
ttps://$ACCOUNT_ID.$REGION.fc.aliyuncs.com/generate-pdf\?url\=http://example.com -o /tmp/fc
-demo-puppeteer-pdf-accl.pdf
# Time spent: 0.05s user 0.06s system 0% cpu 15.200 total time
# Cold start after a period of time
curl -H "x-fc-invocation-target: 2016-08-15/proxy/CustomContainerDemo/puppeteer-pdf-accl" h
ttps://$ACCOUNT_ID.$REGION.fc.aliyuncs.com/generate-pdf\?url\=http://example.com -o /tmp/fc
-demo-puppeteer-pdf-accl.pdf
# Time spent: 0.05s user 0.06s system 0% cpu 4.300 total time

Not e Errors may occur during t est ing. T he period of t ime t hat is required for an act ual
scenario may be different .

5.7. Accelerate image pull for


Container Registry Enterprise Edition
Compared wit h funct ion code packages, cont ainer images provide bet t er port abilit y and a more diverse
ecosyst em of t oolchains. However, t he irrelevant dat a cont ained makes t he cold st art of an image t hat
is gigabyt es in size last several minut es. When you enable t he image pull accelerat ion feat ure, t he cold
st art speed can be increased in t wo phases by approximat ely 90%, and t he period of t ime t hat is
required t o pull an image can be decreased from a few minut es t o a few seconds. T his t opic describes
how does image pull accelerat ion for Cont ainer Regist ry Ent erprise Edit ion works and how t o configure
image pull accelerat ion.

Benefits (compared with the image pull acceleration of Container


Registry Personal Edition)
Images in Cont ainer Regist ry Ent erprise Edit ion support all accelerat ion feat ures of Cont ainer Regist ry
Personal Edit ion and provide t he following benefit s:

Net work isolat ion is support ed. You can configure independent virt ual privat e cloud (VPC) securit y
rules t o manage access t o image reposit ories.
Exclusive bandwidt h helps improve t he flexibilit y of image pull t asks.
T he built -in image conversion feat ure of image reposit ories helps prevent occasional unaccelerat ed
cold st art s before a cached image is available in .

Principles
If you enable t he image pull accelerat ion feat ure for a funct ion t hat runs a cust om cont ainer and uses a
cont ainer image in Cont ainer Regist ry Ent erprise Edit ion, assumes a RAM role and uses a t emporary
AccessKey pair t o pull t he image when funct ion request s are processed. T he speed for pulling t he
image is improved.

Usage notes
T he image pull accelerat ion feat ure is support ed in t he following regions: China (Beijing), China

> Document Version: 20220712 61


Programming Languages· Cust om Co
Funct ion Comput e
nt ainer

(Zhangjiakou), China (Hangzhou), China (Shanghai), China (Shenzhen), China (Hong Kong), Singapore
(Singapore), US (Silicon Valley), and US (Virginia).
uses t he default VPC IP address of your image reposit ory t o resolve t he domain name of t he
cont ainer image in Cont ainer Regist ry Ent erprise Edit ion.
Aft er you creat e or updat e a funct ion t hat uses a cont ainer image in Cont ainer Regist ry Ent erprise
Edit ion, preferent ially pulls t he accelerat ed image from your image reposit ory.
If t he accelerat ed image does not exist in your image reposit ory, pulls t he original image in your image
reposit ory.

Configuration methods
1. St andard Edit ion and Advanced Edit ion inst ances of Cont ainer Regist ry Ent erprise Edit ion provide
t he image accelerat ion feat ure. You can enable t he image pull accelerat ion feat ure when you
creat e or updat e an image reposit ory. For more informat ion, see Enable image accelerat ion.
2. When you creat e or updat e a funct ion, we recommend t hat you use an accelerat ed image whose
name ends wit h _accelerated and enable t he image pull accelerat ion feat ure. Aft er t he
funct ion is configured, you can immediat ely call t he accelerat ed image. T his ensures t hat t he image
pull is accelerat ed when you invoke t he funct ion. You can configure image pull accelerat ion by
using one of t he following met hods when you creat e or updat e a funct ion:
Use t he console. For more informat ion, see Creat e a funct ion in t he console.
T he following figure shows how t o configure image pull accelerat ion when you creat e a
funct ion.

Use Serverless Devs. For more informat ion, see YAML synt ax.
T o configure image pull accelerat ion, add t he accelerationType paramet er t o t he
CustomContainerConfig st ruct ure. Valid values:

Default : enables t he image pull accelerat ion feat ure.

None : disables t he image pull accelerat ion feat ure.

T he following sample code shows how t o enable t he image pull accelerat ion feat ure:

62 > Document Version: 20220712


Programming Languages· Cust om Co
Funct ion Comput e
nt ainer

customContainerConfig:
image: registry-vpc.<regionId>.aliyuncs.com/fc-demo/python-flask:[Image version_acc
elerated]
accelerationType: Default

Use SDKs.

What to do next
You can log on t o t he or call t he GetFunction operat ion t o view t he st at us of image pull accelerat ion. For
more informat ion, see View the status of image pull acceleration.

> Document Version: 20220712 63


Programming Languages· Programmi
Funct ion Comput e
ng model ext ensions

6.Programming model
extensions
6.1. Feature overview
T his t opic describes t he runt ime ext ension feat ure of Funct ion Comput e t hat is developed based on
t radit ional long-running applicat ions t o help you eliminat e idle cost s.

Long-running applications and FaaS execution environment


T radit ional long-running virt ual machines or managed cont ainer services oft en use a billing int erval t hat
st art s when an inst ance is st art ed and ends when t he inst ance is st opped. You are charged even if no
request is execut ed during t his int erval. Funct ion Comput e charges you at a billing granularit y of 1 ms.
Inst ances are billed only during t he execut ion of act ual request s. T he inst ances are frozen in t ime
periods where no request s are execut ed. T his basically eliminat es t he idle cost s of a fully event -driven
billing model. However, t he freezing mechanism breaks t he assumpt ion of long-running processes in
t radit ional archit ect ures and increases t he difficult y in migrat ing applicat ions. For example, t he
commonly used open source dist ribut ed T racing Analysis libraries or t hird-part y applicat ion
performance management (APM) solut ions cannot correct ly report dat a due t o t he special execut ion
environment of Funct ion Comput e.

T he following pain point s hinder t he smoot h migrat ion of t radit ional applicat ions t o a serverless
archit ect ure:
Dat a of asynchronous background met rics is delayed or lost . If t he dat a fails t o be sent during t he
execut ion of a request , t he dat a may be delayed unt il t he next request or dat a point s are discarded.
T he lat ency is increased if met rics are sent synchronously. If a met hod similar t o Flush is called aft er
each request is complet ed, t his not only increases t he lat ency of each request , but also causes
unnecessary pressure on backend servers.
T o support graceful release of funct ions, applicat ions need t o close connect ions, st op processes,
and report st at us when inst ances are st opped. Developers do not know when inst ances are released
in Funct ion Comput e. In addit ion, no webhook is provided t o send not ificat ions about release event s
of funct ion inst ances.

64 > Document Version: 20220712


Programming Languages· Programmi
Funct ion Comput e
ng model ext ensions

Programming model extensions


Funct ion Comput e provides t he runt ime ext ension feat ure t o resolve t he preceding pain point s. T he
feat ure ext ends t he exist ing programming model for HT T P servers by adding t he PreFreeze and
PreSt op webhooks t o t he exist ing HT T P server model. Ext ension developers implement an HT T P handler
t o monit or lifecycle event s of funct ion inst ances.

PreFreeze: Each t ime Funct ion Comput e decides t o freeze t he current funct ion inst ance, Funct ion
Comput e sends an HT T P GET request t o t he /pre-freeze pat h. Ext ension developers implement t he
logic t o ensure t hat necessary operat ions are complet ed before t he inst ance is frozen. For example,
t he inst ance wait s unt il met rics are sent . T he funct ion invocat ion t ime does not include t he execut ion
t ime of t he PreFreeze webhook.

> Document Version: 20220712 65


Programming Languages· Programmi
Funct ion Comput e
ng model ext ensions

PreSt op: Each t ime Funct ion Comput e decides t o st op t he current funct ion inst ance, Funct ion
Comput e sends an HT T P GET request t o t he /pre-st op pat h. Ext ension developers implement t he
logic t o ensure t hat necessary operat ions are complet ed before t he inst ance is released. For
example, dat abase connect ions are closed and t he st at us is report ed or updat ed.

Billing
T he billing met hod for PreFreeze or PreSt op calls is t he same as t hat for InvokeFunct ion calls. You are
not charged for t he number of request s sent t o t he HT T P hooks. T he ext ensions are also applicable t o
scenarios in which mult iple concurrent request s are execut ed on a single inst ance. Assume t hat mult iple
invocat ion request s are concurrent ly execut ed on t he same inst ance. Aft er all t he request s are
complet ed, t he PreFreeze hook is called before t he inst ance is frozen. In t he example shown in t he
following figure, t he specificat ion of t he funct ion is 1 GB. Assume t hat t he period from t 1 when
PreFreeze st art s t o t 6 when Request 2 is complet ed is 1s. T he execut ion t ime of t he inst ance is
calculat ed based on t he following formula: t 6 - t 1. T he consumed resource is calculat ed based on t he
following formula: 1s × 1 GB = 1 CU.

66 > Document Version: 20220712


Programming Languages· Programmi
Funct ion Comput e
ng model ext ensions

> Document Version: 20220712 67


Programming Languages· FAQ about
Funct ion Comput e
code development

7.FAQ about code development


7.1. General FAQ
7.1.1. In which programming languages can I
define functions?

7.1.2. How does Function Compute ensure code


security?
Funct ion Comput e encrypt s code and st ores it in Object St orage Service (OSS). Funct ion Comput e
performs int egrit y checks whenever code is execut ed. Code execut ion is isolat ed from it s own file
syst em and net work namespace.

7.1.3. What do I do if the "The Access Key ID does


not exist" message is returned when I use the
information in the context parameter of a
function such as the AccessKey ID to access
other cloud resources?
T he cont ext paramet er of a funct ion includes a t emporary key t hat consist s of t he AccessKey ID,
AccessKey secret , and securit y t oken. If t he securit y t oken is not provided, t he "T he Access Key ID
does not exist " message is ret urned.

T he following example demonst rat es how t o access Object St orage Service (OSS) code in a Pyt hon
funct ion.

import json
import oss2
def my_handler(event, context):
evt = json.loads(event)
creds = context.credentials
# Do not omit the security token for authentication.
# Do not miss the "security_token" for the authentication!
auth = oss2.StsAuth(creds.access_key_id, creds.access_key_secret, creds.security_token)
bucket = oss2.Bucket(auth, evt['endpoint'], evt['bucket'])
bucket.put_object(evt['objectName'], evt['message'])
return 'success'

68 > Document Version: 20220712


Programming Languages· FAQ about
Funct ion Comput e
code development

7.1.4. Considering that Function Compute only


supports Node.js, how can I execute C++ code?
Funct ion Comput e support s various programming languages. For more informat ion about t he
programming languages support ed by Funct ion Comput e, see Overview . T he following list describes
how t o run programs t hat are writ t en in an unsupport ed language:

Redefine your code in a language t hat Funct ion Comput e support s. Node.js and Pyt hon are efficient
programming languages t hat have a rich variet y of class libraries.
Use a cust om runt ime environment . For more informat ion, see Cust om runt ime environment .
Compile your C or C++ program as an execut able file and use syst em calls such as fork t o run t he file.
Compile your C or C++ module as a shared library and creat e a Pyt hon binding t o int erface wit h t he
library.

T he following t able describes t he advant ages and disadvant ages of t hese met hods.

Method Difficulty Performance Loss Scenario

Depends on program Depends on language Applications that are


Redefine code
complexity and scenario not complex

Custom Runtime Low Low All

Latency-insensitive
applications, such as
Call an executable file Low High asynchronous
processing of files in
the background

High-performance
Call a shared library High Low
applications

If t hese met hods are not sat isfact ory, contact us.

7.1.5. How does Function Compute automatically


install dependencies in a runtime environment?
You must include all t he dependencies in t he code package t hat you upload t o . T he met hods of
package management vary wit h t he programming language. For example, in Node.js, you can use npm
t o inst all dependencies in t he code direct ory and compress t he dependencies and t he code int o a
package. You can inst all t hird-part y dependencies by using or Serverless Devs. For more informat ion, see
Install third-party dependencies on Function Compute.

7.2. Custom Runtime FAQ

> Document Version: 20220712 69


Programming Languages· FAQ about
Funct ion Comput e
code development

7.2.1. Must the listening port of a custom runtime


be the same as that of the HTTP server of the
custom runtime?
Yes. T he default list ening port (CAPort ) of a cust om runt ime is 9000. If a cust om runt ime uses t he
default list ening port , t he list ening port of it s HT T P server must be 9000. If t he list ening port of t he
cust om runt ime is 8080, t he list ening port of it s HT T P server must be 8080.

T he HT T P server st art ed in a cust om runt ime must list en on t he 0.0.0.0:CAPort or *:CAPort port .
If you select t he 127.0.0.1:CAPort port , t he request t imes out and t he following error occurs:

{
"ErrorCode":"FunctionNotStarted",
"ErrorMessage":"The CA's http server cannot be started:ContainerStartDuration:25000000000
. Ping CA failed due to: dial tcp 21.0.5.7:9000: getsockopt: connection refused Logs : 2019
-11-29T09:53:30.859837462Z Listening on port 9000"
}

7.2.2. What do I do if the CAExited error occurs


when the bootstrap file of a custom runtime is a
shell script?
If t he bootstrap file of a cust om runt ime is a shell script and t he following error occurs, you must add
t his cont ent t o t he bootstrap file of t he cust om runt ime: #!/bin/bash .

{
"ErrorCode":"CAExited",
"ErrorMessage":"The CA process either cannot be started or exited:ContainerStartDuratio
n:25037266905. CA process cannot be started or exited already: rpc error: code = 106 desc =
ContainerStartDuration:25000000000. Ping CA failed due to: dial tcp 21.0.7.2:9000: i/o time
out Logs : 2019-11-29T07:27:50.759658265Z panic: standard_init_linux.go:178: exec user proc
ess caused \"exec format error\"
}

If t he boot st rap file is a binary execut able file, such as a binary file compiled by using Go or C++, you do
not need t o add #!/bin/bash .

7.2.3. What do I do if the CAFilePermission error


occurs when I do not have the permissions to
execute the bootstrap file of a custom runtime?
T o execut e t he bootstrap file of a cust om runt ime, you must have t he 777 or 755 permissions.
Ot herwise, t he following error occurs:

70 > Document Version: 20220712


Programming Languages· FAQ about
Funct ion Comput e
code development

{
"ErrorCode":"CAFilePermission",
"ErrorMessage":"The CA process cannot be started due to bootstrap file don't have execu
te permissions
}

You can run t he chmod 777 boot st rap or chmod 755 boot st rap command t o obt ain t he
permissions before packaging files.

7.2.4. What do I do if the FunctionNotStarted


error occurs when I invoke a third-party service in
a service started in a custom runtime?
Check whet her t he t hird-part y service has connect ion rest rict ions. If connect ion rest rict ions exist or a
connect ion t imeout occurs, t he logic for st art ing t he HT T P server is not complet e and t he following
error occurs.

{
"ErrorCode":"FunctionNotStarted",
"ErrorMessage":"The CA's http server cannot be started:ContainerStartDuration:250000000
00. Ping CA failed due to: dial tcp 21.0.3.1:9000: getsockopt: connection refused"}

7.2.5. What do I do if the HTTP server fails to start


within 30s because the HTTP server
implementation takes a long time?
We recommend t hat you opt imize t he st art up speed of t he HT T P server.

7.2.6. What format is required for the bootstrap


file if I use the Windows operating system?
If you use t he Windows operat ing syst em, t he bootstrap file must be in t he UNIX format .

7.2.7. What do I do if the "Process exited


unexpectedly before completing request"
message is returned?
If t he preceding message is ret urned, you can t roubleshoot t he error in t he following ways:

If t he message is ret urned for a cust om runt ime, you can check t he set t ings of t he Connect ion header
and server.
Keep-Alive must be set in t he Connect ion header and t he t imeout value must be 15 minut es or more
at t he server side. Example:

> Document Version: 20220712 71


Programming Languages· FAQ about
Funct ion Comput e
code development

var server = app.listen(PORT, HOST);


server.timeout = 0; // never timeout
server.keepAliveTimeout = 0; // keepalive, never timeout

T he client t hat invokes t he funct ion init iat es t he cancel operat ion. For example, t he execut ion period
of t he funct ion is 10s, but t he T imeout value for SDK t o invoke t he funct ion is set t o 5s at t he client
side. We recommend t hat you set a t imeout value t hat is great er t han t he execut ion period of t he
funct ion on t he client t hat invokes t he funct ion.
T he logic problem of t he funct ion causes t he execut ion environment t o exit .

7.2.8. What do I do if a 404 error occurs when I


use a browser or the cURL tool to access a
function?
Problem description
I creat e an HT T P funct ion for a cust om runt ime. T he service name is CustomDemo and t he funct ion
name is func-http. An anonymous HT T P t rigger is specified. T he following sample rout ing code can be
used t o implement t he HT T P server of t he cust om runt ime:
@app.route('/test', methods = ['POST','GET'])
def test():

When I use t he cURL t ool or a browser t o access t he URL of t he HT T P funct ion, a 404 error occurs.
Use t he cURL t ool t o access t he HT T P funct ion.

curl -v https://123456789.cn-hangzhou.fc.aliyuncs.com/2016-08-15/proxy/CustomDemo/func-
http/test

Use a browser t o access t he HT T P funct ion.

https://123456789.cn-hangzhou.fc.aliyuncs.com/2016-08-15/proxy/CustomDemo/func-http/test

Not e T he URL format of t he HT T P funct ion is https://$ACCOUNT_ID.$REGION.fc.aliyuncs.co


m/2016-08-15/proxy/$ServiceName/$functionName/$path.

Solution

Procedure
1. You can use one of t he following met hods t o solve t his problem:
Add a header named x-fc-invocation-target t o t he command. Command synt ax:

curl -v "x-fc-invocation-target: 2016-08-15/proxy/$ServiceName/$functionName" https:/


/$ACCOUNT_ID.$REGION.fc.aliyuncs.com/$path

A sample command:

curl -v -H "x-fc-invocation-target: 2016-08-15/proxy/CustomDemo/func-http" https://12


3456789.cn-hangzhou.fc.aliyuncs.com/test

72 > Document Version: 20220712


Programming Languages· FAQ about
Funct ion Comput e
code development

Bind a cust om domain name t o t he funct ion. T hen, run t he following command t o access t he
funct ion again. For more informat ion about how t o bind a domain name, see .
If t he domain name is test.abc.com , t he following command can be used:

curl -v https://test.abc.com/$path

A sample command:

curl -v https://test.abc.com/test

Not ice T he pat h must be /* . T he service name is CustomDemo and t he funct ion
name is func-http.

Modify your funct ion code and deploy t he funct ion. T hen, use t he default URL t o access t he
funct ion again. An example of modified funct ion code:

@app.route('/2016-08-15/proxy/CustomDemo/func-http/test', methods = ['POST','GET'])


def test():

A sample command:

curl -v https://123456789.cn-hangzhou.fc.aliyuncs.com/2016-08-15/proxy/CustomDemo/f
unc-http/test

7.2.9. What do I do if a 502 error that contains the


"Process exited unexpectedly before completing
request" error message is returned?
Causes
T he HT T P server connect ion is closed. Possible causes:
T he keep-alive mode is not configured for t he connect ion.
T he connect ion is closed aft er t he HT T P server st ays idle for a period of t ime.
T he connect ion is closed when a read/writ e operat ion t imes out or an error occurs.

Solutions

Procedure
1. uses t he keep-alive mode t o ensure t hat t he connect ion t o t he HT T P servers remains est ablished in
t he cust om runt ime. For idempot ent request s such as t he GET , HEAD, OPT IONS, and T RACE
request s, t he syst em ret ries t o est ablish t he connect ion when an error occurs such as EOF and
connection reset by peer . However, for non-idempot ent request s such as t he POST and PAT CH
request s, a 502 error is ret urned when t he connect ion fails. T o prevent 502 errors, configure t he
following paramet ers on t he server on which t he cust om runt ime runs:
Set t he connect ion mode t o keep-alive.
Disable t he idle t imeout feat ure of t he HT T P server or set t he idle t imeout period t o more t han
15 minut es.

> Document Version: 20220712 73


Programming Languages· FAQ about
Funct ion Comput e
code development

For different HT T P server frameworks, t he configurat ions of t he preceding paramet ers may be
different . For example, for t he GoFrame framework, you must configure t he SetIdletimeout , R
eadTimeout , and python uvicorn paramet ers. You must set t he value of Set Idlet imeout t o 0,
and configure t he --timeout-keep-alive paramet er in t he command line of python uvicorn .
We recommend t hat you check whet her t he HT T P server is disconnect ed when sparse invocat ions
are performed by an HT T P client in t he keep-alive mode.

Causes
T he process exit ed because a funct ion error occurred. Possible causes:
T he exit operat ion is called.
T he exception t hat occurred during t he operat ion was not capt ured.

Solutions

Procedure
1. You can perform t he following operat ions:
Check whet her an act ive exit logic is specified in your code.
Add except ion capt ure or overwrit e mechanism at t he t op level of t he process in t he runt ime
environment t o prevent processes from exit ing when an exception occurs.

7.3. Custom Container FAQ


7.3.1. Must the listening port of a custom
container runtime be the same as that of the
HTTP server started in the custom container
runtime?
Yes, t he list ening port s of t he cust om cont ainer and t he HT T P server in t he cust om cont ainer must be
t he same. T he default list ening port (CAPort ) of a cust om cont ainer is 9000. If a cust om cont ainer uses
t he default list ening port , t he list ening port of t he HT T P server st art ed in t he cust om cont ainer must
also be 9000. If t he list ening port of t he cust om cont ainer is 8080, t he list ening port of t he HT T P server
st art ed in t he cust om cont ainer must also be 8080.

T he HT T P server st art ed in a cust om cont ainer must list en on t he 0.0.0.0:CAPort or *:CAPort port . If you
select t he 127.0.0.1:CAPort port , t he request t imes out and t he following error occurs:

{
"ErrorCode":"FunctionNotStarted",
"ErrorMessage":"The CA's http server cannot be started:ContainerStartDuration:25000000000
. Ping CA failed due to: dial tcp 21.0.5.7:9000: getsockopt: connection refused Logs : 2019
-11-29T09:53:30.859837462Z Listening on port 9000"
}

74 > Document Version: 20220712


Programming Languages· FAQ about
Funct ion Comput e
code development

7.3.2. What do I do if the FunctionNotStarted


error occurs when I invoke a third-party service in
a service started in a custom container runtime?
Check whet her t he t hird-part y service has connect ion rest rict ions. If connect ion rest rict ions exist or a
connect ion t imeout occurs, t he logic for st art ing t he HT T P server is not complet e and t he following
error occurs.

{
"ErrorCode":"FunctionNotStarted",
"ErrorMessage":"The CA's http server cannot be started:ContainerStartDuration:250000000
00. Ping CA failed due to: dial tcp 21.0.3.1:9000: getsockopt: connection refused"}

7.3.3. What do I do if the HTTP server fails to start


within 30s because the HTTP server
implementation takes a long time?
We recommend t hat you opt imize t he st art up speed of t he HT T P server.

7.3.4. What do I do if a 502 error that contains the


"Process exited unexpectedly before completing
request" error message is returned?
Causes
T he HT T P server connect ion is closed. Possible causes:
T he keep-alive mode is not configured for t he connect ion.
T he connect ion is closed aft er t he HT T P server st ays idle for a period of t ime.
T he connect ion is closed when a read/writ e operat ion t imes out or an error occurs.

Solutions

Procedure
1. uses t he keep-alive mode t o ensure t hat t he connect ions t o t he HT T P servers remains est ablished
in t he cust om cont ainer. For idempot ent request s such as t he GET , HEAD, OPT IONS, and T RACE
request s, t he syst em ret ries t o est ablish t he connect ion when an error such as EOF and connect
ion reset by peer occurs. However, for non-idempot ent request s such as t he POST and PAT CH
request s, a 502 error is ret urned when t he connect ion fails. T o prevent 502 errors, configure t he
following paramet ers on t he server on which t he cust om cont ainer runs:
Set t he connect ion mode t o keep-alive.
Disable t he idle t imeout feat ure of t he HT T P server or set t he idle t imeout period t o more t han
15 minut es.

> Document Version: 20220712 75


Programming Languages· FAQ about
Funct ion Comput e
code development

For different HT T P server frameworks, t he configurat ions of t he preceding paramet ers may be
different . For example, for t he GoFrame framework, you must configure t he SetIdletimeout , R
eadTimeout , and python uvicorn paramet ers. You must set Set Idlet imeout t o 0, and configure
t he --timeout-keep-alive paramet er in t he command line of python uvicorn . We
recommend t hat you check whet her t he HT T P server is disconnect ed when sparse invocat ions are
request ed from an HT T P client in t he keep-alive mode.

Causes
T he process exit ed because a funct ion error occurred. Possible causes:
T he exit operat ion is called.
T he exception t hat occurred during t he funct ion execut ion was not capt ured.

Solutions

Procedure
1. You can perform t he following operat ions:
Check whet her an act ive exit logic is specified in your code.
Add except ion capt ure or overwrit e mechanisms at t he t op level of t he process in t he runt ime
environment t o prevent processes from exit ing when an exception occurs.

7.3.5. What do I do if a 404 error occurs when I


use a browser or the cURL tool to access a
function?
Problem description
I creat e an HT T P funct ion for a cust om cont ainer runt ime. T he service name is CustomDemo and t he
funct ion name is func-http. An anonymous HT T P t rigger is specified. T he following sample rout ing code
can be used t o implement t he HT T P server of t he cust om cont ainer runt ime:

Solution

Procedure
1.

7.3.6. What permissions must I grant to Function


Compute service role if Alibaba Cloud public
container images are not used?
You must grant t he AliyunContainerRegistryReadOnlyAccess or
AliyunContainerRegistryFullAccess permissions t o t he service role. For more informat ion, see Grant
Function Compute permissions to access other Alibaba Cloud services.

76 > Document Version: 20220712

You might also like