すべてのプロダクト
Search
ドキュメントセンター

Function Compute:カスタム スパンを作成する

最終更新日:Mar 31, 2025

Managed Service for OpenTelemetry を有効にすると、Function Compute はシステムで消費された時間を記録します。この時間には、コールドスタート時間、Initializer フックの実行時間、および関数の実行時間が含まれます。ビジネス側で関数に消費された時間を記録するには、カスタム スパンを作成します。たとえば、関数内で ApsaraDB RDS や NAS ファイルシステム (NAS) などのサービスへのアクセスにかかった時間を記録できます。このトピックでは、Serverless Devs を使用してカスタム スパンを作成する方法について説明します。

前提条件

処理の説明

Function Compute のトレースに基づいてカスタム スパンを作成し、作成したスパンを Function Compute のトレースに接続できます。Function Compute の場合、Managed Service for OpenTelemetry は、OpenTracing 仕様の Jaeger 実装に基づいてカスタム スパンを作成するための次の 2 つの方法を提供します。

Jaeger と OpenTelemetry の詳細については、「Jaeger」と「OpenTelemetry」をご参照ください。

2 つの方法は、次の手順を含みます。

  1. Jaeger または OpenTelemetry の依存関係を関数に追加します。依存関係のインストール方法の詳細については、「関数のサードパーティ依存関係をインストールする」をご参照ください。

  2. 関数から Function Compute のトレースの SpanContext を取得し、Function Compute の SpanContext に基づいてカスタム スパンを作成し、実行時間を記録する必要があるコードフラグメントの前後にイベントトラッキングを追加します。

  3. [トレース分析] タブの [関数の詳細] ページ、または Managed Service for OpenTelemetry コンソール でトレース情報を表示します。

Jaeger SDK を使用する

次のトピックでは、対応するランタイムで Jaeger SDK を使用してカスタム スパンを作成するために使用されるサンプルコードを提供します。

このセクションでは、Serverless Devs を使用してカスタム スパンを作成し、Node.js ランタイムで関数をデプロイする方法について説明します。

説明

Serverless Devs を使用して、依存関係をインストールし、コードをパッケージ化して Function Compute にデプロイできます。他の方法でコードをパッケージ化およびデプロイすることもできます。 Serverless Devs の詳細については、「Serverless Devs とは」をご参照ください。

  1. コードディレクトリを作成します。

    mkdir jaeger-demo
  2. Node.js ランタイムテンプレートを初期化します。

    1. 次のコマンドを実行して、コードディレクトリに移動します。

      cd jaeger-demo
    2. コードディレクトリで次のコマンドを実行して、Node.js 12 プロジェクトを初期化します。

      s init devsapp/start-fc-event-nodejs12

      サンプル出力は次のとおりです。

       Serverless Awesome: https://github.com/Serverless-Devs/package-awesome
      
       Please input your project name (init dir) (start-fc-event-nodejs12)
    3. プロジェクトの名前を指定し、Enter キーを押します。

      デフォルトでは、Serverless Devs は start-fc-event-nodejs12 という名前のプロジェクトを生成します。必要に応じて、プロジェクト名を変更できます。この例では、デフォルトのプロジェクト名が使用されています。

      サンプル出力は次のとおりです。

       Serverless Awesome: https://github.com/Serverless-Devs/package-awesome
      
       Please input your project name (init dir) start-fc-event-nodejs12
       file decompression completed
       please select credential alias (Use arrow keys)
      ❯ default
    4. エイリアスを選択し、Enter キーを押します。

    5. プロジェクトをデプロイするかどうかを指定します。

      この例では、プロジェクトの依存関係をインストールする必要があります。したがって、コマンド出力で Do you want to deploy the project immediately? (Y/n) が返されたら、n と入力します。

  3. 次のコマンドを実行して、プロジェクトのコードディレクトリに移動します。

    cd start-fc-event-nodejs12/code
  4. コードディレクトリで次のコマンドを実行して、package.json ファイルを初期化します。

    npm init -y

    サンプル出力は次のとおりです。

    Wrote to /test/jjyy/start-fc-event-nodejs12/code/package.json:
    
    {
      "name": "code",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "keywords": [],
      "author": "",
      "license": "ISC"
    }
  5. 次のコマンドを実行して、Jaeger の依存関係をインストールします。

    npm i jaeger-client --save

    サンプル出力は次のとおりです。

    added 15 packages in 1s
  6. 関数コードを編集します。

    次のコードが使用されます。

    var initTracer = require('jaeger-client').initTracer;
    var spanContext = require('jaeger-client').SpanContext;
    
    
    module.exports.handler = function(event, context, callback) 
    {
        console.log('invoking...',context.tracing); // 呼び出し中...
    
        var config = {
            serviceName: 'e2e-test',
            reporter: {
                // トレースエンドポイントを指定します。これにより、クライアントはコレクターに直接接続し、HTTP 経由でスパンを送信します。
                collectorEndpoint: context.tracing.jaegerEndpoint,
                flushIntervalMs: 10,
            },
            sampler: {
                type: "const",
                param: 1
            },
        };
        var options = {
            tags: {
                'version': 'fc-e2e-tags',
            },
        };
        var tracer = initTracer(config, options);
        var invokSpanContextStr = context.tracing.openTracingSpanContext;
        console.log('spanContext', invokSpanContextStr); // スパンコンテキスト
        var invokSpanContext = spanContext.fromString(invokSpanContextStr);
        var span = tracer.startSpan("CustomSpan", { // カスタムスパン
            childOf: invokSpanContext
        });
        span.finish();
        var params = {
            openTracingSpanContext: context.tracing.openTracingSpanContext,
            openTracingSpanBaggages: context.tracing.openTracingSpanBaggages,
            jaegerEndpoint: context.tracing.jaegerEndpoint
        }
       callback(null,'success')
    }
  7. s.yaml ファイルを編集します。

    1. 次のコマンドを実行して、プロジェクトのディレクトリに移動します。

      cd ..
    2. 次のコマンドを実行して、s.yaml ファイルを編集します。

      vim s.yaml

      次のサンプルコードは、ファイルの例を示しています。

      edition: 1.0.0
      name: hello-world-app
      access: default
      
      vars: # グローバル変数
        region: "cn-hangzhou"
        service:
          name: "hello-world-service"
          description: 'hello world by serverless devs'
          tracingConfig: Enable # Managed Service for OpenTelemetry を有効にする
      
      services:
        helloworld: # サービスまたはモジュールの名前
          component: fc # コンポーネントの名前。Serverless Devs はゲームコンソールと考えることができ、機能を拡張するには追加モジュールが必要です。各コンポーネントはゲームカードのように機能し、明確なビジネス機能を実現します。さまざまなコンポーネントを組み合わせることで、Serverless Devs の幅広い機能をアンロックできます。これは、ゲームコンソールがさまざまなカードでさまざまなゲームをプレイできるのとよく似ています。
          props:
            region: ${vars.region} # 変数の使用方法の詳細については、https://www.serverless-devs.com/serverless-devs/yaml をご覧ください。
            service: ${vars.service}
            function:
              name: "start-fc-event-nodejs14"
              description: 'hello world by serverless devs'
              runtime: nodejs12
              codeUri: ./code
              handler: index.handler
              memorySize: 128
              timeout: 60
  8. 次のコマンドを実行して、依存関係をインストールします。

    s build --use-docker

    サンプル出力は次のとおりです。

    [2021-11-12T18:33:43.856] [INFO ] [S-CLI] - Start ...
    [2021-11-12T18:33:44.677] [INFO ] [FC-BUILD] - Build artifact start...
    [2021-11-12T18:33:44.701] [INFO ] [FC-BUILD] - Use docker for building.
    [2021-11-12T18:33:44.988] [INFO ] [FC-BUILD] - Build function using image: registry.cn-beijing.aliyuncs.com/aliyunfc/runtime-nodejs12:build-1.9.21
    [2021-11-12T18:33:45.011] [INFO ] [FC-BUILD] - skip pulling image registry.cn-beijing.aliyuncs.com/aliyunfc/runtime-nodejs12:build-1.9.21...
    [2021-11-12T18:33:47.915] [INFO ] [FC-BUILD] - Build artifact successfully.
    
    Tips for next step
    ======================
    * Invoke Event Function: s local invoke
    * Invoke Http Function: s local start
    * Deploy Resources: s deploy
    End of method: build
  9. 次のコマンドを実行して、プロジェクトをデプロイします。

    s deploy -y

    サンプル出力は次のとおりです。

    [2021-11-12T18:35:26.015] [INFO ] [S-CLI] - Start ...
    [2021-11-12T18:35:26.633] [INFO ] [FC-DEPLOY] - Using region: cn-hangzhou
    [2021-11-12T18:35:26.634] [INFO ] [FC-DEPLOY] - Using access alias: default
    [2021-11-12T18:35:26.634] [INFO ] [FC-DEPLOY] - Using accessKeyID: yourAccessKeyID
    ......
     Make service fc-deploy-service success.
     Make function fc-deploy-service/event-nodejs12 success.
    [2021-11-12T18:35:37.661] [INFO ] [FC-DEPLOY] - Checking Service fc-deploy-service exists
    [2021-11-12T18:35:37.718] [INFO ] [FC-DEPLOY] - Checking Function event-nodejs12 exists
    
    Tips for next step
    ======================
    * Display information of the deployed resource: s info
    * Display metrics: s metrics
    * Display logs: s logs
    * Invoke remote function: s invoke
    * Remove Service: s remove service
    * Remove Function: s remove function
    * Remove Trigger: s remove trigger
    * Remove CustomDomain: s remove domain
    
    
    
    fc-deploy-test:
      region:   cn-hangzhou
      service:
        name: fc-deploy-service
      function:
        name:       event-nodejs12
        runtime:    nodejs12
        handler:    index.handler
        memorySize: 128
        timeout:    60
  10. 結果を確認します。

    Function Compute コンソールでトレースを表示します。作成したカスタム スパンは、Function Compute のスパンに接続されています。

    image

OpenTelemetry を使用する

次のトピックでは、対応するランタイムで OpenTelemetry を使用してカスタム スパンを作成するために使用されるサンプルコードを提供します。

このセクションでは、Serverless Devs を使用してカスタム スパンを作成し、Python ランタイムで関数をデプロイする方法について説明します。

説明

Serverless Devs を使用して、依存関係をインストールし、コードをパッケージ化して Function Compute にデプロイできます。他の方法でコードをパッケージ化およびデプロイすることもできます。 Serverless Devs の詳細については、「Serverless Devs とは」をご参照ください。

  1. コードディレクトリを作成します。

    mkdir opentelemetry-demo
  2. コードディレクトリに移動します。

    cd opentelemetry-demo
  3. Python ランタイムテンプレートを初期化します。

    1. 次のコマンドを実行して、Python 3 プロジェクトを初期化します。

      s init devsapp/start-fc-event-python3

      サンプル出力は次のとおりです。

       Serverless Awesome: https://github.com/Serverless-Devs/package-awesome
      
       Please input your project name (init dir) (start-fc-event-python3)
    2. プロジェクトの名前を指定し、Enter キーを押します。

      デフォルトでは、Serverless Devs は start-fc-event-python3 という名前のプロジェクトを生成します。必要に応じて、プロジェクト名を変更できます。この例では、デフォルトのプロジェクト名が使用されています。

      サンプル出力は次のとおりです。

       Serverless Awesome: https://github.com/Serverless-Devs/package-awesome
      
       Please input your project name (init dir) start-fc-event-python3
       file decompression completed
       please select credential alias (Use arrow keys)
      ❯ default
    3. エイリアスを選択し、Enter キーを押します。

    4. プロジェクトをデプロイするかどうかを指定します。

      この例では、プロジェクトの依存関係をインストールする必要があります。したがって、コマンド出力で Do you want to deploy the project immediately? (Y/n) が返されたら、n と入力します。

  4. OpenTelemetry の依存関係をインストールします。

    1. 次のコマンドを実行して、コードディレクトリに移動します。

      cd start-fc-event-python3/code
    2. コードディレクトリに requirements.txt ファイルを作成し、ファイルを編集します。ファイルには次の情報が含まれています。

      opentelemetry-api==1.12.0
      opentelemetry-sdk==1.12.0
      opentelemetry-exporter-jaeger==1.12.0
  5. 次のコマンドを実行して、関数コードを編集します。

    vim index.py

    次のコードが使用されます。

    # -*- coding: utf-8 -*-
    import time
    from opentelemetry import trace
    from opentelemetry.exporter.jaeger.thrift import JaegerExporter
    from opentelemetry.sdk.resources import SERVICE_NAME, Resource
    from opentelemetry.sdk.trace import TracerProvider
    from opentelemetry.sdk.trace.export import SimpleSpanProcessor
    from opentelemetry.trace import NonRecordingSpan
    
    # トレースプロバイダーを設定
    trace.set_tracer_provider(
        TracerProvider(
            resource=Resource.create({SERVICE_NAME: "my-helloworld-service"})
        )
    )
    tracer = trace.get_tracer(__name__)
    
    
    def handler(event, context):
        init_tracer(context.tracing.jaeger_endpoint)
        span_context = get_fc_span(context.tracing.span_context)
        start_my_span(trace.set_span_in_context(NonRecordingSpan(span_context)))
        return 'hello world'
    
    
    def init_tracer(endpoint):
        # JaegerExporter を作成
        jaeger_exporter = JaegerExporter(
            collector_endpoint=endpoint
        )
    
        # SimpleSpanProcessor を作成し、エクスポーターを追加
        span_processor = SimpleSpanProcessor(jaeger_exporter)
    
        # トレーサーに追加
        trace.get_tracer_provider().add_span_processor(span_processor)
    
    
    def get_fc_span(jaeger_span_context):
        jaeger_span_context_arr = jaeger_span_context.split(":")
        tid = int(jaeger_span_context_arr[0], 16)
        sid = int(jaeger_span_context_arr[1], 16)
    
        span_context = trace.SpanContext(
            trace_id=tid,
            span_id=sid,
            is_remote=True,
            trace_flags=trace.TraceFlags(0x01),
        )
        return span_context
    
    
    def start_my_span(context):
        # カスタムスパンを開始
        with tracer.start_as_current_span(name="fc-operation", context=context):
            time.sleep(0.15)
            with tracer.start_as_current_span("child"): # 子スパン
                time.sleep(0.1)

    :wq と入力し、Enter キーを押して編集ページを終了します。

  6. s.yaml ファイルを編集します。

    1. 次のコマンドを実行して、プロジェクトのディレクトリに移動します。

      cd ..
    2. 次のコマンドを実行して、s.yaml ファイルを編集します。

      vim s.yaml

      次のサンプルコードは、ファイルの例を示しています。

      edition: 1.0.0
      name: hello-world-app
      access: default
      
      vars: # グローバル変数
        region: "cn-hangzhou"
        service:
          name: "hello-world-service"
          description: 'hello world by serverless devs'
          tracingConfig: Enable # Managed Service for OpenTelemetry を有効にする
      
      services:
        helloworld: # サービスまたはモジュールの名前
          component: fc # コンポーネントの名前。Serverless Devs はゲームコンソールと考えることができ、機能を拡張するには追加モジュールが必要です。各コンポーネントはゲームカードのように機能し、明確なビジネス機能を実現します。さまざまなコンポーネントを組み合わせることで、Serverless Devs の幅広い機能をアンロックできます。これは、ゲームコンソールがさまざまなカードでさまざまなゲームをプレイできるのとよく似ています。
          props:
            region: ${vars.region} # 変数の使用方法の詳細については、https://www.serverless-devs.com/serverless-devs/yaml#Variable value をご覧ください。
            service: ${vars.service}
            function:
              name: "start-fc-event-python3"
              description: 'hello world by serverless devs'
              runtime: python3.9
              codeUri: ./code
              handler: index.handler
              memorySize: 128
              timeout: 60

      :wq と入力し、Enter キーを押して編集ページを終了します。

  7. 依存関係をインストールします。

    s build --use-docker

    サンプル出力は次のとおりです。

    [2021-11-12T18:53:05.818] [INFO ] [S-CLI] - Start ...
    [2021-11-12T18:53:06.638] [INFO ] [FC-BUILD] - Build artifact start...
    [2021-11-12T18:53:06.659] [INFO ] [FC-BUILD] - Use docker for building.
    [2021-11-12T18:53:06.888] [INFO ] [FC-BUILD] - Build function using image: registry.cn-beijing.aliyuncs.com/aliyunfc/runtime-python3.6:build-1.9.21
    [2021-11-12T18:53:06.942] [INFO ] [FC-BUILD] - skip pulling image registry.cn-beijing.aliyuncs.com/aliyunfc/runtime-python3.6:build-1.9.21...
    [2021-11-12T18:53:10.570] [INFO ] [FC-BUILD] - Build artifact successfully.
    
    Tips for next step
    ======================
    * Invoke Event Function: s local invoke
    * Invoke Http Function: s local start
    * Deploy Resources: s deploy
    End of method: build
  8. 次のコマンドを実行して、プロジェクトをデプロイします。

    s deploy -y

    サンプル出力は次のとおりです。

    [2021-11-12T18:55:02.640] [INFO ] [S-CLI] - Start ...
    [2021-11-12T18:55:03.455] [INFO ] [FC-DEPLOY] - Using region: cn-hangzhou
    [2021-11-12T18:55:03.456] [INFO ] [FC-DEPLOY] - Using access alias: default
    [2021-11-12T18:55:03.456] [INFO ] [FC-DEPLOY] - Using accessKeyID: yourAccessKeyID
    [2021-11-12T18:55:03.457] [INFO ] [FC-DEPLOY] - Using accessKeySecret: yourAccessKeySecret
     Using fc deploy type: sdk, If you want to deploy with pulumi, you can [s cli fc-default set deploy-type pulumi] to switch.
    [2021-11-12T18:55:04.142] [INFO ] [FC-DEPLOY] - Checking Service fc-deploy-service exists
    [2021-11-12T18:55:04.722] [INFO ] [FC-DEPLOY] - Checking Function event-py3 exists
    [2021-11-12T18:55:04.831] [INFO ] [FC-DEPLOY] - Fc detects that you have run build command for function: event-py3.
    [2021-11-12T18:55:04.831] [INFO ] [FC-DEPLOY] - Using codeUri: /test/jjyy/opentelemetry-demo/start-fc-event-python3/.s/build/artifacts/fc-deploy-service/event-py3
    [2021-11-12T18:55:04.835] [INFO ] [FC-DEPLOY] - Fc add/append some content to your origin environment variables for finding dependencies generated by build command.
    {
      "LD_LIBRARY_PATH": "/code/.s/root/usr/local/lib:/code/.s/root/usr/lib:/code/.s/root/usr/lib/x86_64-linux-gnu:/code/.s/root/usr/lib64:/code/.s/root/lib:/code/.s/root/lib/x86_64-linux-gnu:/code/.s/root/python/lib/python2.7/site-packages:/code/.s/root/python/lib/python3.6/site-packages:/code:/code/lib:/usr/local/lib",
      "PATH": "/code/.s/root/usr/local/bin:/code/.s/root/usr/local/sbin:/code/.s/root/usr/bin:/code/.s/root/usr/sbin:/code/.s/root/sbin:/code/.s/root/bin:/code:/code/node_modules/.bin:/code/.s/python/bin:/code/.s/node_modules/.bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/sbin:/bin",
      "NODE_PATH": "/code/node_modules:/usr/local/lib/node_modules",
      "PYTHONUSERBASE": "/code/.s/python"
    }
     Make service fc-deploy-service success.
     Make function fc-deploy-service/event-py3 success.
    [2021-11-12T18:55:10.693] [INFO ] [FC-DEPLOY] - Checking Service fc-deploy-service exists
    [2021-11-12T18:55:10.737] [INFO ] [FC-DEPLOY] - Checking Function event-py3 exists
    
    Tips for next step
    ======================
    * Display information of the deployed resource: s info
    * Display metrics: s metrics
    * Display logs: s logs
    * Invoke remote function: s invoke
    * Remove Service: s remove service
    * Remove Function: s remove function
    * Remove Trigger: s remove trigger
    * Remove CustomDomain: s remove domain
    
    
    
    fc-deploy-test:
      region:   cn-hangzhou
      service:
        name: fc-deploy-service
      function:
        name:       event-py3
        runtime:    python3
        handler:    index.handler
        memorySize: 128
        timeout:    60
  9. 結果を確認します。

    Function Compute コンソールでトレースを表示します。作成したカスタム スパンは Function Compute のスパンに接続されています。

    image