在 Google Cloud 上設定具備微服務可觀察性的 gRPC 應用程式


微服務觀測工具可讓您檢測應用程式,以便從部署在 Google Cloud 和其他位置的 gRPC 工作負載中,收集並在 Cloud Monitoring、Cloud Logging 和 Cloud Trace 中呈現遙測資料。微服務觀測功能可搭配任何已啟用 Microservices API 的部署作業,取得存取監控、記錄和追蹤記錄的權限。

在本教學課程中,您將瞭解如何使用微服務觀測功能,方法是使用 Compute Engine 建構簡單的 gRPC 應用程式,並為應用程式加入微服務觀測功能,然後在監控和記錄中查看這些功能。 Google Cloud

目標

整體來說,您需要執行以下操作:

  • 服務開發人員可以:

    • 使用您選擇的語言 (C++、Go 或 Java) 建立 gRPC 應用程式。
    • 選擇加入應用程式,並控管微服務可觀察性外掛程式。
    • 在 Compute Engine VM 上部署應用程式。
  • 服務營運商可透過各種方式使用收集到的資料:

    • 在 Trace 中查看追蹤記錄。
    • 在名為「Microservices (gRPC) Monitoring」的監控資訊主頁上查看指標。
    • 在 Metrics Explorer 中查看指標。
    • 在 Logs Explorer 中檢查記錄項目。

費用

In this document, you use the following billable components of Google Cloud:

To generate a cost estimate based on your projected usage, use the pricing calculator. New Google Cloud users might be eligible for a free trial.

When you finish the tasks that are described in this document, you can avoid continued billing by deleting the resources that you created. For more information, see Clean up.

事前準備

主控台

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Compute Engine, and Microservices API APIs.

    Enable the APIs

  5. Create a service account:

    1. In the Google Cloud console, go to the Create service account page.

      Go to Create service account
    2. Select your project.
    3. In the Service account name field, enter a name. The Google Cloud console fills in the Service account ID field based on this name.

      In the Service account description field, enter a description. For example, Service account for quickstart.

    4. Click Create and continue.
    5. Grant the following roles to the service account: Logging > Logs Viewer > Logs Writer, Monitoring > Monitoring Editor > Metrics Writer, Trace > Trace Admin > Trace Agent.

      To grant a role, find the Select a role list, then select the role.

      To grant additional roles, click Add another role and add each additional role.

    6. Click Continue.
    7. In the Service account users role field, enter the identifier for the principal that will attach the service account to other resources, such as Compute Engine instances.

      This is typically the email address for a Google Account.

    8. Click Done to finish creating the service account.

  6. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  7. Make sure that billing is enabled for your Google Cloud project.

  8. Enable the Compute Engine, and Microservices API APIs.

    Enable the APIs

  9. Create a service account:

    1. In the Google Cloud console, go to the Create service account page.

      Go to Create service account
    2. Select your project.
    3. In the Service account name field, enter a name. The Google Cloud console fills in the Service account ID field based on this name.

      In the Service account description field, enter a description. For example, Service account for quickstart.

    4. Click Create and continue.
    5. Grant the following roles to the service account: Logging > Logs Viewer > Logs Writer, Monitoring > Monitoring Editor > Metrics Writer, Trace > Trace Admin > Trace Agent.

      To grant a role, find the Select a role list, then select the role.

      To grant additional roles, click Add another role and add each additional role.

    6. Click Continue.
    7. In the Service account users role field, enter the identifier for the principal that will attach the service account to other resources, such as Compute Engine instances.

      This is typically the email address for a Google Account.

    8. Click Done to finish creating the service account.

  10. 閱讀微服務的可觀察性總覽
  11. 請參閱兩個支援的環境變數,決定要使用哪一個,並判斷環境變數所需的值。

cli

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. Install the Google Cloud CLI.

  3. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  4. To initialize the gcloud CLI, run the following command:

    gcloud init
  5. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Compute Engine, and Microservices API APIs:

    gcloud services enable compute.googleapis.com<wbr>&nbsp;microservices.googleapis.com
  8. Set up authentication:

    1. Create the service account:

      gcloud iam service-accounts create SERVICE_ACCOUNT_NAME

      Replace SERVICE_ACCOUNT_NAME with a name for the service account.

    2. Grant roles to the service account. Run the following command once for each of the following IAM roles: roles/logging.logWriter, roles/monitoring.metricWriter, roles/cloudtrace.agent:

      gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com" --role=ROLE

      Replace the following:

      • SERVICE_ACCOUNT_NAME: the name of the service account
      • PROJECT_ID: the project ID where you created the service account
      • ROLE: the role to grant
    3. Grant the required role to the principal that will attach the service account to other resources.

      gcloud iam service-accounts add-iam-policy-binding SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com --member="user:USER_EMAIL" --role=roles/iam.serviceAccountUser

      Replace the following:

      • SERVICE_ACCOUNT_NAME: the name of the service account
      • PROJECT_ID: the project ID where you created the service account
      • USER_EMAIL: the email address for a Google Account
  9. Install the Google Cloud CLI.

  10. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  11. To initialize the gcloud CLI, run the following command:

    gcloud init
  12. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  13. Make sure that billing is enabled for your Google Cloud project.

  14. Enable the Compute Engine, and Microservices API APIs:

    gcloud services enable compute.googleapis.com<wbr>&nbsp;microservices.googleapis.com
  15. Set up authentication:

    1. Create the service account:

      gcloud iam service-accounts create SERVICE_ACCOUNT_NAME

      Replace SERVICE_ACCOUNT_NAME with a name for the service account.

    2. Grant roles to the service account. Run the following command once for each of the following IAM roles: roles/logging.logWriter, roles/monitoring.metricWriter, roles/cloudtrace.agent:

      gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com" --role=ROLE

      Replace the following:

      • SERVICE_ACCOUNT_NAME: the name of the service account
      • PROJECT_ID: the project ID where you created the service account
      • ROLE: the role to grant
    3. Grant the required role to the principal that will attach the service account to other resources.

      gcloud iam service-accounts add-iam-policy-binding SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com --member="user:USER_EMAIL" --role=roles/iam.serviceAccountUser

      Replace the following:

      • SERVICE_ACCOUNT_NAME: the name of the service account
      • PROJECT_ID: the project ID where you created the service account
      • USER_EMAIL: the email address for a Google Account
  16. 閱讀微服務的可觀察性總覽
  17. 請參閱兩個支援的環境變數,決定要使用哪一個,並判斷環境變數所需的值。

建立及連線至 Compute Engine VM

請按照下列操作說明建立 Compute Engine VM 執行個體並連線。您可以在 VM 上部署應用程式,然後使用微服務觀測功能對應用程式進行檢測。

  1. 建立 VM 執行個體:

    gcloud compute instances create grpc-observability-vm \
      --image-family=debian-11 \
      --image-project=debian-cloud \
      --service-account=SERVICE_ACCOUNT_NAME@$PROJECT_ID.iam.gserviceaccount.com
    
  2. 連線至 VM 執行個體:

    gcloud compute ssh --project=$PROJECT_ID grpc-observability-vm
    

將應用程式部署至 Compute Engine VM

您可以將所選應用程式部署至先前步驟中建立的 Compute Engine VM,然後略過這個步驟,也可以使用範例,以您偏好的語言繼續操作說明。

C++

  1. 連線至 VM 執行個體後,請執行下列指令。

    sudo apt-get update -y
    sudo apt-get install -y git build-essential clang
    git clone -b v1.54.0 https://github.com/grpc/grpc.git --depth=1
    

Go

  1. 請確認您已安裝 Go。

    sudo apt-get install -y git
    sudo apt install wget
    wget https://go.dev/dl/go1.20.2.linux-amd64.tar.gz
    sudo rm -rf /usr/local/go && sudo tar -C /usr/local -xzf \
    go1.20.2.linux-amd64.tar.gz
    export PATH=$PATH:/usr/local/go/bin
    
  2. 複製 gRPC-Go 範例。

    git clone https://github.com/grpc/grpc-go.git
    cd grpc-go/
    git checkout -b run-observability-example
    875c97a94dca8093bf01ff2fef490fbdd576373d
    

Java

  1. 連線至 VM 執行個體後,請確認已安裝 Java 8 以上版本。

    sudo apt update
    sudo apt upgrade
    sudo apt install git
    sudo apt-get install -y openjdk-11-jdk-headless
    
  2. 複製 grpc-java 存放區。

    export EXAMPLES_VERSION=v1.54.1
    git clone -b $EXAMPLES_VERSION --single-branch --depth=1 \
    https://github.com/grpc/grpc-java.git
    

建立 gRPC Google Cloud 可觀察性設定檔

您需要個別的 gRPC 可觀察性設定檔,才能為伺服器和用戶端啟用微服務可觀察性。 Google Cloud 這個檔案的位置會在後續步驟中匯出為 GRPC_GCP_OBSERVABILITY_CONFIG_FILE。請參閱下列操作說明,瞭解如何在設定檔中設定不同的參數。

範例 GRPC_GCP_OBSERVABILITY_CONFIG_FILE

{
  "project_id": "your-project-here",
  "cloud_logging": {
    "client_rpc_events": [
    {
      "methods": ["google.pubsub.v1.Subscriber/Acknowledge", "google.pubsub.v1.Publisher/CreateTopic"],
      "exclude": true,
    },
    {
      "methods": ["google.pubsub.v1.Subscriber/*", "google.pubsub.v1.Publisher/*"],
      "max_metadata_bytes": 4096,
      "max_message_bytes": 4096,
    }],
    "server_rpc_events": [{
      "methods": ["*"],
      "max_metadata_bytes": 4096,
      "max_message_bytes": 4096
    }],
  },
  "cloud_monitoring": {},
  "cloud_trace": {
    "sampling_rate": 0.5,
  }
  "labels": {
    "SOURCE_VERSION": "J2e1Cf",
    "SERVICE_NAME": "payment-service-1Cf",
    "DATA_CENTER": "us-west1-a"
  }
}

以下各節提供操作說明,說明如何在個別元件的設定中啟用資料收集功能。如果您在本教學課程中使用 gRPC 範例,可以直接使用此設定 (更新 your-project-here 後),或將其做為應用程式的範本。此外,我們也提供範例,說明如何在環境變數中顯示設定資訊。

啟用指標

如要啟用指標,請將 cloud_monitoring 物件新增至設定,並將其值設為 {}

如要進一步瞭解指標,請參閱「指標定義」。

啟用追蹤功能

如要啟用追蹤功能,請按照下列步驟操作:

  1. cloud_trace 物件新增至設定。
  2. cloud_trace.sampling_rate 設為 0.5,即可隨機追蹤 50% 的 RPC。

如果您打算在各服務間啟用追蹤功能,請務必確保服務支援從上游 (或自行啟動) 收到的追蹤內容傳播至下游。

如要進一步瞭解追蹤功能,請參閱「追蹤定義」。

啟用記錄功能

如要啟用記錄功能,請按照下列步驟操作:

  1. cloud_logging 物件新增至設定。
  2. client_rpc_eventsserver_rpc_events 中新增圖案,指定要產生傳輸層級事件記錄的服務或方法組合,以及要記錄標頭和訊息的位元組數量。

如要進一步瞭解記錄功能,請參閱「記錄記錄定義」。

為觀測插件檢測應用程式

如要將應用程式納入檢測,以便使用微服務觀測外掛程式,請按照下列操作說明 (依照您偏好的語言) 操作。

C++

自 gRPC C++ 1.54 版起,您可以將 C++ 與微服務可觀察性搭配使用。範例存放區位於 GitHub 中。

  1. 觀測功能僅支援 Bazel 建構系統。將目標 grpcpp_gcp_observability 新增為依附元件。

  2. 如要啟用微服務的可觀察性,您必須使用額外的依附元件 (可觀察性模組),並將下列程式碼變更為現有的 gRPC 用戶端、伺服器或兩者:

    #include <grpcpp/ext/gcp_observability.h>
    
    int main(int argc, char** argv) {
      auto observability = grpc::GcpObservability::Init();
      assert(observability.ok());
      
      // Observability data flushed when object goes out of scope
    }
    

    在執行任何 gRPC 作業 (包括建立管道、伺服器或憑證) 之前,請先叫用下列項目:

    grpc::GcpObservability::Init();
    

    這會傳回應儲存的 absl::StatusOr<GcpObservability>。狀態可協助判斷觀察功能是否已成功初始化。隨附的 GcpObservability 物件會控制可觀察性生命週期,並在可觀察性資料超出範圍時自動關閉並清除。

Go

  1. 微服務觀測外掛程式支援 gRPC Go 版本 v1.54.0 以上版本。範例存放區位於 GitHub 中。

使用 Go 模組時,如果要啟用微服務的可觀察性,就必須使用可觀察性模組和下列程式碼:

import "google.golang.org/grpc/gcp/observability"

func main() {
  ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  defer cancel()
  if err := observability.Start(ctx); err != nil {
    log.Warning("Unable to start gRPC observability:", err)
  }
  defer observability.End()
  
}

observability.Start 呼叫會剖析環境變數中的設定,並據此建立匯出器,然後將收集邏輯注入用戶端連線和呼叫後建立的伺服器。延遲的 observability.End 呼叫會清理資源,並確保在應用程式關閉前,將緩衝資料刷出。

更新應用程式程式碼後,請執行下列指令來更新 go.mod 檔案。

go mod tidy

Java

如要搭配 Java 應用程式使用微服務觀測功能,請修改建構內容,加入 grpc-gcp-observability 構件。使用 gRPC 1.54.1 以上版本。

在 Gradle 和 Maven 建構工具區段的建構程式碼片段中,grpcVersion 會設為 1.54.1。

範例存放區位於 GitHub 中。

  1. 如要成功為微服務的可觀察性檢測 Java 應用程式,請將下列程式碼新增至 main()
...
import io.grpc.gcp.observability.GcpObservability;
...

// Main application class
...

public static void main(String[] args) {
...
  // call GcpObservability.grpcInit() to initialize & get observability
  GcpObservability observability = GcpObservability.grpcInit();

...
  // call close() on the observability instance to shutdown observability
  observability.close();
...
}

請注意,您必須先呼叫 GcpObservability.grpcInit(),才能建立任何 gRPC 管道或伺服器。GcpObservability.grpcInit() 函式會讀取微服務的可觀察性設定,並使用該設定來設定全域攔截器和追蹤器,以便在建立的每個管道和伺服器中使用記錄、指標和追蹤功能。GcpObservability.grpcInit() 是執行緒安全的,且必須精確呼叫一次。它會傳回 GcpObservability 例項,您必須儲存該例項,才能稍後呼叫 close()

GcpObservability.close() 會取消分配資源。之後建立的任何管道或伺服器都不會執行任何記錄。

GcpObservability 會實作 java.lang.AutoCloseable,如果您使用 try-with-resource,系統會自動關閉 java.lang.AutoCloseable,如下所示:

...
import io.grpc.gcp.observability.GcpObservability;
...

// Main application class
...

public static void main(String[] args) {
...
  // call GcpObservability.grpcInit() to initialize & get observability
  try (GcpObservability observability = GcpObservability.grpcInit()) {

...
  } // observability.close() called implicitly
...
}

使用 Gradle 建構工具

如果您使用的是 Gradle 建構工具,請加入下列項目:

def grpcVersion = '1.54.1'

...

dependencies {
...
implementation "io.grpc:grpc-gcp-observability:${grpcVersion}"
...
}

使用 Maven 建構工具 (pom.xml)

如果您使用 Maven 建構工具,請加入下列項目:

<properties>
...
<grpc.version>1.54.1</grpc.version>
...
</properties>

...

<dependencies>
...
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-gcp-observability</artifactId>
<version>${grpc.version}</version>
</dependency>
...
</dependencies>

執行應用程式

只有在您使用教學課程的 gRPC 範例時,才需要按照本節的操作說明進行。您可以修改 run 指令,指定應用程式二進位檔。

執行伺服器

C++

  1. 在 VM 中建立 SSH 工作階段。
  2. 匯出環境變數。使用上述步驟建立 server_config.json

      export GOOGLE_CLOUD_PROJECT=$PROJECT_ID
      export GRPC_GCP_OBSERVABILITY_CONFIG_FILE="$(pwd)/examples/cpp/gcp_observability/helloworld/server_config.json"
    
  3. 執行伺服器應用程式 shell cd grpc tools/bazel run examples/cpp/gcp_observability/helloworld:greeter_server

Go

  1. 在 VM 中建立 SSH 工作階段。
  2. 匯出環境變數。使用上述步驟建立 server_config.json

    export GRPC_GCP_OBSERVABILITY_CONFIG_FILE=./server/serverConfig.json
    
  3. 執行伺服器應用程式 shell go run ./server/main.go

Java

  1. 在範例目錄中開啟 README 檔案,並按照檔案中的操作說明進行。
  2. 當指示您開啟另一個終端機視窗時,請發出以下指令: shell gcloud compute ssh --project=$PROJECT_ID grpc-observability-vm

執行用戶端

C++

  1. 在 VM 中建立另一個 SSH 工作階段。
  2. 匯出環境變數。使用上述步驟建立 client_config.json 檔案。

      export GOOGLE_CLOUD_PROJECT=$PROJECT_ID
      export GRPC_GCP_OBSERVABILITY_CONFIG_FILE="$(pwd)/examples/cpp/gcp_observability/helloworld/client_config.json"
    
  3. 執行用戶端應用程式

    cd grpc
    tools/bazel run examples/cpp/gcp_observability/helloworld:greeter_client
    

Go

  1. 在 VM 中建立另一個 SSH 工作階段。
  2. 匯出環境變數。使用上述步驟建立 client_config.json 檔案。 shell export GRPC_GCP_OBSERVABILITY_CONFIG_FILE=./client/clientConfig.json
  3. 執行用戶端應用程式

    cd grpc-go/examples/features/observability
    go run ./client/main.go
    

Java

  1. 在範例目錄中開啟 README 檔案,然後按照檔案中的操作說明進行。
  2. 當操作說明指示您開啟另一個終端機視窗時,請發出以下指令: shell gcloud compute ssh --project=$PROJECT_ID grpc-observability-vm

清除所用資源

如要避免系統向您的 Google Cloud 帳戶收取本教學課程中所用資源的相關費用,請刪除含有該項資源的專案,或者保留專案但刪除個別資源。

刪除專案

    Delete a Google Cloud project:

    gcloud projects delete PROJECT_ID

刪除個別資源

  1. Delete the instance:
    gcloud compute instances delete INSTANCE_NAME

後續步驟