Alibaba Faas Programming Languages Intl en-US
Alibaba Faas Programming Languages Intl en-US
Alibaba Cloud
Function
Function Compute
Compute
Programming Languages
Programming Languages
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 conventions
St yle Descript io n Example
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.
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 .
Table of Contents
1.Overview 07
2.Terms 08
3.Go 13
3.2. Handlers 13
3.4. HT T P handlers 16
3.5. Context 18
3.7. Logs 22
4.Custom Runtime 29
4.1. Overview 29
4.3. CDN 37
4.5. HT T P functions 41
5.Custom Container 49
5.1. Overview 49
5.2. Introduction 51
5.4. HT T P functions 53
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 .
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 .
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:
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.
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'
{
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
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.
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:
__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 .
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
Not ice T he Go runt ime must be used on Linux and does not support t he ARM64 archit ect ure.
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
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.
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"
}
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.
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.
func ()
func () error
T he InputType and OutputType object s are compat ible wit h t he encoding/json st andard
library.
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
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 .
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)
}
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:
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:
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 .
Response method
T he following sample code shows t he t hree met hods declared by http.ResponseWriter :
Not e:
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
Parameter Description
Met ho d
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 .
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
}
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)
}
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.
go get github.com/aliyun/fc-runtime-go-sdk/fc
2. Compile files.
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:
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:
3. Package t he files.
set GOOS=linux
set GOARCH=amd64
go build -o main main.go
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 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:
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:
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 Go runt ime records t he St art and End lines and t he execut ion summary for each funct ion
invocat ion.
Parameter Description
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)
}
{
"errorMessage": "something is wrong!",
"errorType": "errorString"
}
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.
{
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)
}
{
errorMessage: 'Process exited unexpectedly before completing request (duration: 0ms, ma
xMemoryUsage: 8MB)'
}
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)
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
}
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.
Sample code
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.
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:
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:
gd gettext hash
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 :
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.
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
{
"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:
{
"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 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:
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
Header Description
Header Description
(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.
FunctionCompute ${runtime}
runtime inited.
No
No
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.
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.
.
├── demo.jar
customRuntimeConfig:
command:
- java
args:
- '-jar'
- 'demo.jar'
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.
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:
4.3. CDN
Context
Procedure
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.
Header: x-fc-status
200: succeeded
404: failed
No t e We recommend
that you specify both the
StatusCode and x-fc-status
fields in the HT T P response.
Examples
PHP
Go
Node.js
Python
Ruby
C+ +
T ypeScript
Powershell
Lua
Dart
Rust
PHP
Go
Node.js
Python
Ruby
C+ +
T ypeScript
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?
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.
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.
Header Description
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
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.
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.
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.
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.
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
Header Description
HT T P st at us code ( StatusCode )
200 : succeeded
404 : failed
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.
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.
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.
No
No
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
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.
HT T P funct ion
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:
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.
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.
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
Background information
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
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.
cd /tmp
ii. Run t he following command in t he /tmp direct ory t o decompress t he sample project :
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 .
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 .
For more information about instance types, see Instance types and usage
modes.
Select the memory size used to execute the function. T he memory size
Memory
cannot be less than 512 MB.
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.
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:
# 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.
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.
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.
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.
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.
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:
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 .
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
(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:
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_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.
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.
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.
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.
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.
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'
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.
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.
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"
}
{
"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 .
{
"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.
{
"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"}
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:
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 .
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
https://123456789.cn-hangzhou.fc.aliyuncs.com/2016-08-15/proxy/CustomDemo/func-http/test
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:
A sample command:
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:
A sample command:
curl -v https://123456789.cn-hangzhou.fc.aliyuncs.com/2016-08-15/proxy/CustomDemo/f
unc-http/test
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.
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.
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"
}
{
"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"}
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.
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.
Solution
Procedure
1.