Cloud Functions を直接呼び出す

Cloud Functions では、迅速な開発サイクルとデバッグをサポートするために、コマンドライン インターフェースで call コマンド、Google Cloud コンソール UI でテスト機能を使用できます。これにより、関数を直接呼び出し、予期した動作が行われているかどうか確認できます。特定のイベントに応答するように関数がデプロイされている場合でも、関数がすぐに実行されます。

Google Cloud CLI を使用して関数をテストする

第 1 世代

gcloud CLI を使用して第 1 世代の関数を直接呼び出すには、gcloud functions call コマンドを使用し、関数が --data 引数で JSON として想定する任意のデータを指定します。次に例を示します。

gcloud functions call YOUR_FUNCTION_NAME --data '{"name":"Tristan"}'

YOUR_FUNCTION_NAME は実行する関数の名前です。--data 引数は、関数に次のように渡されます。

  • HTTP 関数の場合、指定したデータは POST リクエストの本体として送信されます。
  • バックグラウンド関数の場合、データがイベントデータとして関数に直接渡されます。バックグラウンド関数でイベントデータにアクセスする必要がある場合は、バックグラウンド関数のパラメータをご覧ください。
  • CloudEvent 関数の場合、データがイベントデータとして関数に直接渡されます。CloudEvent 関数でのイベントデータへのアクセスについて詳しくは、CloudEvent 関数のパラメータをご覧ください。

第 2 世代

gcloud CLI を使用して第 2 世代の関数を直接呼び出すには、gcloud functions call コマンドの第 2 世代バージョンを使用し、関数が --data 引数で JSON として想定する任意のデータを指定します。次に例を示します。

gcloud functions call YOUR_FUNCTION_NAME \
  --region=REGION --gen2 \
  --data '{"name":"Kalani"}'

以下のように置き換えます。

  • YOUR_FUNCTION_NAME: テスト対象の関数の名前
  • REGION: 関数がデプロイされる Google Cloud リージョン

--data 引数は、関数に次のように渡されます。

  • HTTP 関数の場合、指定したデータは POST リクエストの本体として送信されます。
  • CloudEvent 関数の場合、データがイベントデータとして関数に直接渡されます。CloudEvent 関数でのイベントデータへのアクセスについて詳しくは、CloudEvent 関数のパラメータをご覧ください。

詳細については、gcloud functions call のドキュメントをご覧ください。

Google Cloud Console を使用して関数をテストする

Google Cloud コンソールから関数を直接呼び出すには、次の操作を行います。

第 1 世代

  1. Cloud Functions の概要ページに移動

  2. 呼び出す関数の名前をクリックします。

  3. [テスト] タブをクリックします。

  4. [トリガー イベントを構成] フィールドに、関数が JSON として想定するデータを入力します。

  5. [関数をテストする] をクリックします。

関数からのレスポンスが [出力] フィールドに表示されます。個々の実行のログは、[ログ] フィールドに表示されます。

第 2 世代

  1. Cloud Functions の概要ページに移動

  2. リストで、呼び出す関数の名前をクリックします。[関数の詳細] ページに移動します。

  3. [テスト] タブをクリックします。

  4. [トリガー イベントを構成] フィールドに、関数が JSON として想定するデータを入力します。

  5. 必要に応じて、[+ クエリ パラメータを追加] ボタンと [+ ヘッダー パラメータを追加] ボタンをクリックして、関数呼び出しにクエリ パラメータとヘッダー パラメータを追加します。

    Google Cloud コンソールは、指定されたパラメータを CLI テストコマンド ウィンドウの gcloud functions call コマンドにまとめます。

  6. [Cloud Shell で実行] を選択して Cloud Shell ウィンドウを開き、このコマンドを実行します。

  7. Enter キーを押して、Cloud Shell ウィンドウに表示された gcloud functions call コマンドをトリガーします。

Cloud Pub/Sub イベント ドリブン関数の例

この例は、Cloud Pub/Sub イベントでトリガーされた第 1 世代のイベント ドリブン関数を直接呼び出す方法を示しています。

Node.js

/**
 * Background Cloud Function to be triggered by Pub/Sub.
 * This function is exported by index.js, and executed when
 * the trigger topic receives a message.
 *
 * @param {object} message The Pub/Sub message.
 * @param {object} context The event metadata.
 */
exports.helloPubSub = (message, context) => {
  const name = message.data
    ? Buffer.from(message.data, 'base64').toString()
    : 'World';

  console.log(`Hello, ${name}!`);
};

Python

def hello_pubsub(event, context):
    """Background Cloud Function to be triggered by Pub/Sub.
    Args:
         event (dict):  The dictionary with data specific to this type of
                        event. The `@type` field maps to
                         `type.googleapis.com/google.pubsub.v1.PubsubMessage`.
                        The `data` field maps to the PubsubMessage data
                        in a base64-encoded string. The `attributes` field maps
                        to the PubsubMessage attributes if any is present.
         context (google.cloud.functions.Context): Metadata of triggering event
                        including `event_id` which maps to the PubsubMessage
                        messageId, `timestamp` which maps to the PubsubMessage
                        publishTime, `event_type` which maps to
                        `google.pubsub.topic.publish`, and `resource` which is
                        a dictionary that describes the service API endpoint
                        pubsub.googleapis.com, the triggering topic's name, and
                        the triggering event type
                        `type.googleapis.com/google.pubsub.v1.PubsubMessage`.
    Returns:
        None. The output is written to Cloud Logging.
    """
    import base64

    print(
        """This Function was triggered by messageId {} published at {} to {}
    """.format(
            context.event_id, context.timestamp, context.resource["name"]
        )
    )

    if "data" in event:
        name = base64.b64decode(event["data"]).decode("utf-8")
    else:
        name = "World"
    print(f"Hello {name}!")

Go


// Package helloworld provides a set of Cloud Functions samples.
package helloworld

import (
	"context"
	"log"
)

// PubSubMessage is the payload of a Pub/Sub event.
// See the documentation for more details:
// https://cloud.google.com/pubsub/docs/reference/rest/v1/PubsubMessage
type PubSubMessage struct {
	Data []byte `json:"data"`
}

// HelloPubSub consumes a Pub/Sub message.
func HelloPubSub(ctx context.Context, m PubSubMessage) error {
	name := string(m.Data) // Automatically decoded from base64.
	if name == "" {
		name = "World"
	}
	log.Printf("Hello, %s!", name)
	return nil
}

Java


import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
import functions.eventpojos.PubsubMessage;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;

public class HelloPubSub implements BackgroundFunction<PubsubMessage> {
  private static final Logger logger = Logger.getLogger(HelloPubSub.class.getName());

  @Override
  public void accept(PubsubMessage message, Context context) {
    String name = "world";
    if (message != null && message.getData() != null) {
      name = new String(
          Base64.getDecoder().decode(message.getData().getBytes(StandardCharsets.UTF_8)),
          StandardCharsets.UTF_8);
    }
    logger.info(String.format("Hello %s!", name));
    return;
  }
}

C#

using CloudNative.CloudEvents;
using Google.Cloud.Functions.Framework;
using Google.Events.Protobuf.Cloud.PubSub.V1;
using Microsoft.Extensions.Logging;
using System.Threading;
using System.Threading.Tasks;

namespace HelloPubSub;

public class Function : ICloudEventFunction<MessagePublishedData>
{
    private readonly ILogger _logger;

    public Function(ILogger<Function> logger) =>
        _logger = logger;

    public Task HandleAsync(CloudEvent cloudEvent, MessagePublishedData data, CancellationToken cancellationToken)
    {
        string nameFromMessage = data.Message?.TextData;
        string name = string.IsNullOrEmpty(nameFromMessage) ? "world" : nameFromMessage;
        _logger.LogInformation("Hello {name}", name);
        return Task.CompletedTask;
    }
}

Ruby

require "functions_framework"
require "base64"

FunctionsFramework.cloud_event "hello_pubsub" do |event|
  # The event parameter is a CloudEvents::Event::V1 object.
  # See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.html
  name = Base64.decode64 event.data["message"]["data"] rescue "World"

  # A cloud_event function does not return a response, but you can log messages
  # or cause side effects such as sending additional events.
  logger.info "Hello, #{name}!"
end

PHP


use CloudEvents\V1\CloudEventInterface;
use Google\CloudFunctions\FunctionsFramework;

// Register the function with Functions Framework.
// This enables omitting the `FUNCTIONS_SIGNATURE_TYPE=cloudevent` environment
// variable when deploying. The `FUNCTION_TARGET` environment variable should
// match the first parameter.
FunctionsFramework::cloudEvent('helloworldPubsub', 'helloworldPubsub');

function helloworldPubsub(CloudEventInterface $event): void
{
    $log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');

    $cloudEventData = $event->getData();
    $pubSubData = base64_decode($cloudEventData['message']['data']);

    $name = $pubSubData ? htmlspecialchars($pubSubData) : 'World';
    fwrite($log, "Hello, $name!" . PHP_EOL);
}

関数を直接呼び出すには、base64 でエンコードされたデータを想定する PubsubMessage をイベントデータとして送信します。

Node.js

DATA=$(printf 'Hello!'|base64) && gcloud functions call helloPubSub --data '{"data":"'$DATA'"}'

Python

DATA=$(printf 'Hello!'|base64) && gcloud functions call hello_pubsub --data '{"data":"'$DATA'"}'

Go

DATA=$(printf 'Hello!'|base64) && gcloud functions call HelloPubSub --data '{"data":"'$DATA'"}'

Java

DATA=$(printf 'Hello!'|base64) && gcloud functions call java-hello-pubsub --data '{"data":"'$DATA'"}'

C#

DATA=$(printf 'Hello!'|base64) && gcloud functions call csharp-hello-pubsub --data '{"data":"'$DATA'"}'

Ruby

DATA=$(printf 'Hello!'|base64) && gcloud functions call hello_pubsub --data '{"data":"'$DATA'"}'

PHP

DATA=$(printf 'Hello!'|base64) && gcloud functions call helloworldPubsub --data '{"data":"'$DATA'"}'

この CLI の例では、bash または sh 構文を使用します。これは、Linux 環境と Mac 環境では動作しますが、Windows 環境では動作しません。

トリガー イベントフィールドと同じイベントデータを使用して、Google Cloud コンソールから関数を呼び出すこともできます。