ここでは、Node.js の jimp 画像処理ライブラリを使用して画像を拡大/縮小する方法について説明します。この例では、以下について学習します。
- サードパーティの依存ライブラリをパックする方法
- 関数実行ログを有効にし確認する方法
この例では、関数コードが code ディレクトリに格納され、元画像と結果画像が data ディレクトリに格納され、”demo” サービスが Function Compute に存在するものとします。サービスの作成やその他の背景情報に精通していない場合は、「hello world アプリケーション例」 をご参照ください。
fcli shell
を実行して対話モードに入ります。
サードパーティの依存ライブラリをインストールする
Node.js の場合:
関数はサードパーティの画像処理ライブラリ jimp に依存しているため、コードディレクトリにインストールし、関数ソースコードでパックしてアップロードする必要があります。fcli はローカルのサンドボックス環境を提供します。これは Function Compute の関数実行環境と一致しています。サンドボックス環境では、サードパーティのライブラリを簡単にインストールしてローカルデバッグを実行できます。
sbox -d code -t nodejs6
を実行します。-d
は、コードのディレクトリを指定します。このディレクトリは、サンドボックス環境の “/code” の位置に付加されます。-t
は言語のタイプを指定します。サンドボックス環境で、
npm init -f
を実行して Node.js 6 が必要とする package.json を生成し、npm install jimp
を実行して依存ライブラリをインストールします。インストールが完了したら、
exit
を実行してサンドボックス環境を終了します。このとき、jimp はコードディレクトリにインストールされています。注意:
sbox コマンドを実行するには、まずホストに Docker をインストールする必要があります。Docker のインストール方法の詳細については、「関連ドキュメント」 をご参照ください。
sbox が使用するイメージは、公式の Docker イメージレジストリで利用できますが、中国のユーザーのこのレジストリへのアクセスは、遅くなる可能性があります。Alibaba Cloud イメージアクセラレーションサービスを使用することをお勧めします。
Linux で Docker を使用する場合は、root 許可が必要です。したがって、
sudo fcli shell
を使用してコマンドラインツールを起動するか、設定を変更して、非root ユーザーとして Docker を管理するために、「関連ドキュメント 」をご参照ください。サードパーティのライブラリをパックし、関数をテストし、サンドボックス環境で問題を調査することを、常にお勧めします。これにより、開発環境と実行環境の不一致による例外を防ぐことができます。特に、関数がバイナリファイルに依存する場合は、サンドボックス環境で関連する依存関係をコンパイルしてください。
>>> sbox -d code -t nodejs6
Entering the container. Your code is in the /code direcotry.
root@df9fc6428140:/code# npm init -f
npm info it worked if it ends with ok
npm info using npm@3.10.10
npm info using node@v6.10.3
npm WARN using --force I sure hope you know what you are doing.
Wrote to /code/package.json:
{
"name": "code",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"jimp": "^0.2.28"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
npm info init written successfully
npm info ok
root@df9fc6428140:/code# npm install jimp
npm info it worked if it ends with ok
...
npm info lifecycle jimp@0.2.28~postinstall: jimp@0.2.28
code@1.0.0 /code
-- jimp@0.2.28
npm WARN code@1.0.0 No description
npm WARN code@1.0.0 No repository field.
npm info ok
root@df9fc6428140:/code# exit
exit
Python の場合:
Python の場合では、 Wand 画像処理ライブラリがこの例で使用されています。現在、Function Compute の Python 実行環境には、既に Wand モジュールが含まれています。したがって、サードパーティ製のライブラリをサンドボックス環境にパックする必要はありません。Function Compute の Python 実行環境に含まれる共通モジュールの詳細については、「Python プログラミングガイド 」をご参照ください。
注意:問題が発生した場合は、このページの最後の行をクリックして、シェルの操作ビデオのデモ全体を表示してください。
コードを書く
コードディレクトリで、 image_process.js ファイルを作成して resize 関数を実装します。ソースイメージは、イベントパラメーターとしてインポートされます。
'use strict';
var jimp = require("jimp");
var fs = require("fs")
module.exports.resize = function(event, context, callback) {
// The imported event is a PNG image. Write it to the /tmp directory.
fs.writeFileSync("/tmp/serverless.png", event)
// Read the PNG image in the /tmp directory, call the jimp database to complete resize, and write the result image to the /tmp directory.
jimp.read("/tmp/serverless.png", function(err, image) {
if (err) {
console.error("failed to read image");
callback(err)
return
}
image.resize(128, 128)
.write("/tmp/serverless_128.png", function(err) {
if (err) {
console.error("failed to write image");
callback(err)
return
}
// Read the result image from the /tmp directory and return the result as the response.
callback(null, fs.readFileSync("/tmp/serverless_128.png"))
})
});
};
# -*- coding: utf-8 -*-
from wand.image import Image
def resize(event, context):
with Image(blob=event) as img:
with img.clone() as i:
i.resize(128, 128)
return i.make_blob()
Log Service Logstore を作成する
Function Compute は、ログを実行している関数を指定した Logstore に保存します。mkl -p fc -s demo
を実行してログプロジェクトの fc と Logstore の demo を Log Service 上に作成します。
注意:
まだ Log Service を有効にしていない場合は 、まず最初に有効にします。有効化されている場合は、延滞していないかどうかを確認してください。
既に Logstore が作成済みの場合は、この手順をスキップしてください。
上記のコマンドをコピーして実行すると、次のエラーが報告されることがあります。これは、Log Service がグローバルに一意のプロジェクト名を必要とするためです。この場合、プロジェクト名を変更する必要があります。詳細については、「 Log Serviceドキュメント」をご参照ください。
Error: {
"errorCode": "ProjectAlreadyExist",
"errorMessage": "Project fc already exist",
...
}
ログリソースを使用するには、別途料金を支払う必要があります。特に Log Service は特定のリソースの予約料金を課金します。つまり、ログを書き込まなくても、JPY 1.15/日が課金される可能性があります。課金の詳細については、「関連ドキュメント 」をご参照ください。
ログは、デバッグおよび故障診断の重要な情報であるため、Function Compute のログを保存するため、Log Service を有効化することを強くお勧めします。
songluo@demo $ ./fcli shell
Welcome to the function compute world. Have fun!
>>> mkl --help
mkl: create the log project/store
flags:
--help
-p, --project string the log project
--shard int the shard count of the log store (default 1)
-s, --store string the log store
--ttl int the ttl of the log store, in days (default 30)
>>> mkl -p fc -s demo
Note: you have to pay at least 0.04 RMB/day for the log store resource. For the detail billing info please refer to:
https://www.aliyun.com/price/product#/sls/detail
Do you want to create the log store? [y/n]
y
>>>
Function Compute Logstore に書き込み許可を与える
ログは個人のリソースです。したがって、Function Compute は、ログにアクセスする前に明示的な許可を必要とします。grant demo
を実行し、 Demo のログを実行している関数を、指定した Logstore に書き込むために Function Compute を承認します。Function Compute のロール認証は、Alibaba Cloud RAM に基づいています。詳細については、「関連ドキュメント」 をご参照ください。
注意: RAM サブアカウントを使用している場合、grant コマンドを実行すると、次のエラーが報告されることがあります。これは、アカウントにポリシーの作成許可がないためです。関連する操作を実行するには、プライマリアカウントによる承認が必要です。
Error: failed to create policy write-fc-logs due to {
"HttpStatus": 404,
"HostId": "ram.aliyuncs.com",
"Code": "Inactive",
"Message": "Account is inactive to this service"
}
songluo@demo $ ./fcli shell
Welcome to the function compute world. Have fun!
>>> grant demo
Please input the role name:
fc-logs
Please input the policy name:
write-demo-logs
Permission grant scenarios:
1. Allow FC write function logs to your log store.
2. Allow FC copy code from your OSS location.
Please input your choice [1-2]:
1
Please input the log project: fc
Please input the log store: demo
...grant success
>>> info /ram/roles/fc-logs
Role:
{
"RoleId": "338942517712635876",
"RoleName": "fc-logs",
"Arn": "acs:ram::12345678:role/fc-logs",
"Description": "create the role fc-logs",
"AssumeRolePolicyDocument": "{\n \"Statement\": [{\n \"Action\": \"sts:AssumeRole\",\n \"Effect\": \"Allow\",\n \"Principal\": {\"Service\": [\"fc.aliyuncs.com\"]}}],\n \"Version\": \"1\"}",
"CreateDate": "2017-09-19T09:12:12Z"
}
Attached policies:
[{write-demo-logs Custom create the policy write-demo-logs v5 0} {fc-copy-code-all Custom create the policy fc-copy-code-all v1 0} {fc-oss-rw Custom create the policy fc-oss-rw v1 0}]
関数の作成と呼び出し
mkf demo/resize -t nodejs6 -h image_process.resize -d code
を実行して、 demo サービスに属する Function Compute の resize 関数を作成します。[注意:Python バージョンでは、ランタイムは python2.7 に設定されています。
songluo@demo $ ./fcli shell
Welcome to the function compute world. Have fun!
>>> mkf demo/resize -t nodejs6 -h image_process.resize -d code
関数を呼び出してログを表示する
ソースイメージ serverless.png が data ディレクトリにある場合は、 invk demo/resize -f data/serverless.png -o data/serverless_128.png
を実行してイメージのサイズを変更します。
logs demo
を実行して demo サービス全体のログを表示し、logs demo/resize
を実行して、指定した関数のログを表示します。
songluo@demo $ ls
code data fcli
songluo@demo $ cd code
songluo@code $ ls
hello_world.js image_process.js node_modules
songluo@demo $ fcli shell
Welcome to the function compute world. Have fun!
>>> ls demo
resize
world
>>> invk demo/resize -f data/serverless.png -o data/serverless_128.png
>>> logs demo/resize
2017-09-28T15:54:35+08:00 serviceName:demo functionName:resize message:2017-09-28T07:54:35.426Z [info] FunctionCompute nodejs runtime inited.
2017-09-28T15:54:35+08:00 serviceName:demo functionName:resize message:FC Invoke Start RequestId: c3c4b57d-847b-42c3-daf0-4f3a8cc278e4
2017-09-28T15:54:35+08:00 serviceName:demo functionName:resize message:FC Invoke End RequestId: c3c4b57d-847b-42c3-daf0-4f3a8cc278e4
例 3 のデモ操作ビデオ全体を表示するには、image_process をクリックします。