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

微服務觀測工具可讓您檢測應用程式,以便在 Cloud Monitoring、Cloud Logging 和 Cloud Trace 中,收集並呈現部署在 Google Cloud 和其他位置的 gRPC 工作負載遙測資料。微服務可觀測性適用於任何已啟用 Microservices API,並獲准存取 Monitoring、Logging 和 Trace 的部署作業。

在本教學課程中,您將瞭解如何使用微服務觀測功能,方法是在 Google Cloud 使用 Compute Engine 建構簡單的 gRPC 應用程式,並透過微服務觀測功能檢測應用程式,然後在 Monitoring 和 Logging 中即時查看結果。

目標

大致來說,您需要執行以下操作:

  • 服務開發人員可以:

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

    • 在 Trace 中查看追蹤記錄。
    • 在名為「微服務 (gRPC) 監控」的監控資訊主頁上查看指標。
    • 在 Metrics Explorer 中查看指標。
    • 在記錄檔探索工具中檢查記錄項目。

費用

在本文件中,您會使用下列 Google Cloud的計費元件:

如要根據預測用量估算費用,請使用 Pricing Calculator

初次使用 Google Cloud 的使用者可能符合免費試用期資格。

完成本文所述工作後,您可以刪除建立的資源,避免繼續計費,詳情請參閱「清除所用資源」。

事前準備

控制台

  1. 登入 Google Cloud 帳戶。如果您是 Google Cloud新手,歡迎 建立帳戶,親自評估產品在實際工作環境中的成效。新客戶還能獲得價值 $300 美元的免費抵免額,可用於執行、測試及部署工作負載。
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

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

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  5. Create a service account:

    1. Ensure that you have the Create Service Accounts IAM role (roles/iam.serviceAccountCreator) and the Project IAM Admin role (roles/resourcemanager.projectIamAdmin). Learn how to grant roles.
    2. In the Google Cloud console, go to the Create service account page.

      Go to Create service account
    3. Select your project.
    4. 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.

    5. Click Create and continue.
    6. 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.

    7. Click Continue.
    8. 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.

    9. 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.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  7. Verify that billing is enabled for your Google Cloud project.

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

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  9. Create a service account:

    1. Ensure that you have the Create Service Accounts IAM role (roles/iam.serviceAccountCreator) and the Project IAM Admin role (roles/resourcemanager.projectIamAdmin). Learn how to grant roles.
    2. In the Google Cloud console, go to the Create service account page.

      Go to Create service account
    3. Select your project.
    4. 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.

    5. Click Create and continue.
    6. 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.

    7. Click Continue.
    8. 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.

    9. Click Done to finish creating the service account.

  10. 請參閱「微服務可觀測性總覽」。
  11. 請參閱這篇文章,瞭解兩種支援的環境變數,決定要使用哪一種,並判斷環境變數所需的值。

cli

  1. 登入 Google Cloud 帳戶。如果您是 Google Cloud新手,歡迎 建立帳戶,親自評估產品在實際工作環境中的成效。新客戶還能獲得價值 $300 美元的免費抵免額,可用於執行、測試及部署工作負載。
  2. 安裝 Google Cloud CLI。

  3. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI

  4. 執行下列指令,初始化 gcloud CLI:

    gcloud init
  5. 建立或選取 Google Cloud 專案

    選取或建立專案所需的角色

    • 選取專案:選取專案時,不需要具備特定 IAM 角色,只要您已獲授角色,即可選取任何專案。
    • 建立專案:如要建立專案,您需要「專案建立者」角色 (roles/resourcemanager.projectCreator),其中包含 resourcemanager.projects.create 權限。瞭解如何授予角色
    • 建立 Google Cloud 專案:

      gcloud projects create PROJECT_ID

      PROJECT_ID 替換為您要建立的 Google Cloud 專案名稱。

    • 選取您建立的 Google Cloud 專案:

      gcloud config set project PROJECT_ID

      PROJECT_ID 替換為 Google Cloud 專案名稱。

  6. 確認專案已啟用計費功能 Google Cloud

  7. 啟用 Compute Engine 和 Microservices API:

    啟用 API 時所需的角色

    如要啟用 API,您需要具備服務使用情形管理員 IAM 角色 (roles/serviceusage.serviceUsageAdmin),其中包含 serviceusage.services.enable 權限。瞭解如何授予角色

    gcloud services enable compute.googleapis.com microservices.googleapis.com
  8. 設定驗證方法:

    1. 確認您具備「建立服務帳戶」身分與存取權管理角色 (roles/iam.serviceAccountCreator) 和「專案 IAM 管理員」角色 (roles/resourcemanager.projectIamAdmin)。瞭解如何授予角色
    2. 建立服務帳戶:

      gcloud iam service-accounts create SERVICE_ACCOUNT_NAME

      SERVICE_ACCOUNT_NAME 換成服務帳戶的名稱。

    3. 將角色授予服務帳戶。針對下列每個 IAM 角色,執行一次下列指令: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

      請替換下列項目:

      • SERVICE_ACCOUNT_NAME:服務帳戶名稱
      • PROJECT_ID:您建立服務帳戶的專案 ID
      • ROLE:要授予的角色
    4. 將必要角色指派給要將服務帳戶附加至其他資源的主體。

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

      更改下列內容:

      • SERVICE_ACCOUNT_NAME:服務帳戶名稱
      • PROJECT_ID:您建立服務帳戶的專案 ID
      • USER_EMAIL:Google 帳戶的電子郵件地址
  9. 安裝 Google Cloud CLI。

  10. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI

  11. 執行下列指令,初始化 gcloud CLI:

    gcloud init
  12. 建立或選取 Google Cloud 專案

    選取或建立專案所需的角色

    • 選取專案:選取專案時,不需要具備特定 IAM 角色,只要您已獲授角色,即可選取任何專案。
    • 建立專案:如要建立專案,您需要「專案建立者」角色 (roles/resourcemanager.projectCreator),其中包含 resourcemanager.projects.create 權限。瞭解如何授予角色
    • 建立 Google Cloud 專案:

      gcloud projects create PROJECT_ID

      PROJECT_ID 替換為您要建立的 Google Cloud 專案名稱。

    • 選取您建立的 Google Cloud 專案:

      gcloud config set project PROJECT_ID

      PROJECT_ID 替換為 Google Cloud 專案名稱。

  13. 確認專案已啟用計費功能 Google Cloud

  14. 啟用 Compute Engine 和 Microservices API:

    啟用 API 時所需的角色

    如要啟用 API,您需要具備服務使用情形管理員 IAM 角色 (roles/serviceusage.serviceUsageAdmin),其中包含 serviceusage.services.enable 權限。瞭解如何授予角色

    gcloud services enable compute.googleapis.com microservices.googleapis.com
  15. 設定驗證方法:

    1. 確認您具備「建立服務帳戶」身分與存取權管理角色 (roles/iam.serviceAccountCreator) 和「專案 IAM 管理員」角色 (roles/resourcemanager.projectIamAdmin)。瞭解如何授予角色
    2. 建立服務帳戶:

      gcloud iam service-accounts create SERVICE_ACCOUNT_NAME

      SERVICE_ACCOUNT_NAME 換成服務帳戶的名稱。

    3. 將角色授予服務帳戶。針對下列每個 IAM 角色,執行一次下列指令: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

      請替換下列項目:

      • SERVICE_ACCOUNT_NAME:服務帳戶名稱
      • PROJECT_ID:您建立服務帳戶的專案 ID
      • ROLE:要授予的角色
    4. 將必要角色指派給要將服務帳戶附加至其他資源的主體。

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

      更改下列內容:

      • SERVICE_ACCOUNT_NAME:服務帳戶名稱
      • PROJECT_ID:您建立服務帳戶的專案 ID
      • USER_EMAIL:Google 帳戶的電子郵件地址
  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_events 和/或 server_rpc_events 中新增模式,指定要產生傳輸層級事件記錄的服務或方法集,以及要記錄的標頭和訊息位元組數。

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

為可觀測性外掛程式檢測應用程式

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

C++

從 gRPC C++ v1.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. 在 examples 目錄中開啟 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 收取費用,請刪除含有相關資源的專案,或者保留專案但刪除個別資源。

刪除專案

    刪除 Google Cloud 專案:

    gcloud projects delete PROJECT_ID

刪除個別資源

  1. 刪除執行個體:
    gcloud compute instances delete INSTANCE_NAME

後續步驟