Menyiapkan aplikasi gRPC di Google Cloud dengan kemampuan observasi Microservices


Alat observasi microservices memberi Anda kemampuan untuk menginstrumentasikan aplikasi guna mengumpulkan dan menampilkan data telemetri di Cloud Monitoring, Cloud Logging, dan Cloud Trace dari workload gRPC yang di-deploy di Google Cloud dan di tempat lain. Kemampuan observasi microservice berfungsi dengan deployment apa pun yang telah diberikan izin untuk mengakses Monitoring, Logging, dan Trace dengan mengaktifkan Microservices API.

Dalam tutorial ini, Anda akan mempelajari cara menggunakan fitur visibilitas Microservices dengan mem-build aplikasi gRPC sederhana di Google Cloud menggunakan Compute Engine dan melengkapi aplikasi Anda dengan visibilitas Microservices, serta melihatnya muncul secara langsung di Monitoring dan Logging.

Tujuan

Pada tingkat tinggi, Anda melakukan hal berikut.

  • Sebagai developer layanan, Anda dapat:

    • Buat aplikasi gRPC dengan bahasa pilihan Anda (C++, Go, atau Java).
    • Ikut sertakan aplikasi Anda dan kontrol plugin Kemampuan observasi microservice.
    • Deploy aplikasi di VM Compute Engine.
  • Sebagai operator layanan, Anda menggunakan data yang dikumpulkan dengan berbagai cara:

    • Melihat rekaman aktivitas di Trace.
    • Lihat metrik di dasbor pemantauan yang disebut Pemantauan Microservices (gRPC).
    • Melihat metrik di Metrics Explorer.
    • Periksa entri log di Logs Explorer.

Biaya

Dalam dokumen ini, Anda akan menggunakan komponen Google Cloudyang dapat ditagih berikut:

Untuk membuat perkiraan biaya berdasarkan proyeksi penggunaan Anda, gunakan kalkulator harga. Pengguna Google Cloud baru mungkin memenuhi syarat untuk mendapatkan uji coba gratis.

Setelah menyelesaikan tugas yang dijelaskan dalam dokumen ini, Anda dapat menghindari penagihan berkelanjutan dengan menghapus resource yang Anda buat. Untuk mengetahui informasi selengkapnya, lihat Pembersihan.

Sebelum memulai

Konsol

  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. Baca Ringkasan kemampuan observasi microservice.
  11. Baca tentang dua variabel lingkungan yang didukung, tentukan variabel yang akan digunakan, dan tentukan nilai yang diperlukan oleh variabel lingkungan.

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. To initialize the gcloud CLI, run the following command:

    gcloud init
  4. 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.

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

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

    gcloud services enable compute.googleapis.com microservices.googleapis.com
  7. 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." --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. --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
  8. Install the Google Cloud CLI.
  9. To initialize the gcloud CLI, run the following command:

    gcloud init
  10. 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.

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

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

    gcloud services enable compute.googleapis.com microservices.googleapis.com
  13. 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." --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. --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
  14. Baca Ringkasan kemampuan observasi microservice.
  15. Baca tentang dua variabel lingkungan yang didukung, tentukan variabel yang akan digunakan, dan tentukan nilai yang diperlukan oleh variabel lingkungan.

Membuat dan terhubung ke VM Compute Engine

Gunakan petunjuk ini untuk membuat dan terhubung ke instance VM Compute Engine. Di VM, Anda men-deploy aplikasi, lalu melengkapi aplikasi dengan kemampuan observasi Microservices.

  1. Buat instance VM:

    gcloud compute instances create grpc-observability-vm \
      --image-family=debian-11 \
      --image-project=debian-cloud \
      --service-account=SERVICE_ACCOUNT_NAME@$PROJECT_ID.
    
  2. Hubungkan ke instance VM:

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

Men-deploy aplikasi ke VM Compute Engine

Anda dapat men-deploy aplikasi pilihan Anda ke VM Compute Engine yang Anda buat di langkah sebelumnya, lalu melewati langkah ini, atau Anda dapat menggunakan contoh untuk melanjutkan petunjuk dalam bahasa pilihan Anda.

C++

  1. Setelah Anda terhubung ke instance VM, jalankan perintah berikut.

    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. Pastikan Anda telah menginstal 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. Clone contoh gRPC-Go.

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

Java

  1. Setelah terhubung ke instance VM, pastikan Anda telah menginstal Java 8 atau yang lebih baru.

    sudo apt update
    sudo apt upgrade
    sudo apt install git
    sudo apt-get install -y openjdk-11-jdk-headless
    
  2. Buat clone repositori grpc-java.

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

Membuat file konfigurasi gRPC Google Cloud Observability

Anda memerlukan file konfigurasi Observabilitas gRPC Google Cloud terpisah untuk mengaktifkan Observabilitas microservice untuk server dan klien. Lokasi file ini diekspor sebagai GRPC_GCP_OBSERVABILITY_CONFIG_FILE pada langkah berikutnya. Gunakan petunjuk berikut tentang cara menyiapkan berbagai parameter dalam file konfigurasi.

Contoh 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"
  }
}

Bagian berikut berisi petunjuk untuk mengaktifkan pengumpulan data dalam konfigurasi Anda untuk setiap komponen. Jika menggunakan contoh gRPC dalam tutorial ini, Anda dapat menggunakan konfigurasi ini apa adanya (setelah mengupdate your-project-here) atau menggunakannya sebagai template untuk aplikasi Anda.dan contoh yang menampilkan informasi konfigurasi dalam variabel lingkungan.

Mengaktifkan metrik

Untuk mengaktifkan metrik, tambahkan objek cloud_monitoring ke konfigurasi dan tetapkan nilainya ke {}.

Untuk mengetahui informasi selengkapnya tentang metrik, lihat Definisi metrik.

Mengaktifkan pelacakan

Untuk mengaktifkan pelacakan, lakukan hal berikut:

  1. Tambahkan objek cloud_trace ke konfigurasi.
  2. Tetapkan cloud_trace.sampling_rate ke 0.5 yang akan melacak 50% RPC secara acak.

Jika Anda berencana mengaktifkan pelacakan di seluruh layanan, pastikan layanan tersebut mendukung penyebaran konteks rekaman aktivitas yang diterima dari upstream (atau dimulai sendiri) ke downstream.

Untuk mengetahui informasi selengkapnya tentang rekaman aktivitas, lihat Definisi rekaman aktivitas.

Aktifkan logging

Untuk mengaktifkan logging, lakukan langkah berikut:

  1. Tambahkan objek cloud_logging ke konfigurasi.
  2. Tambahkan pola ke salah satu atau kedua client_rpc_events dan server_rpc_events yang menentukan kumpulan layanan atau metode yang ingin Anda buat logging peristiwa tingkat transpor dan jumlah byte yang akan dicatat ke dalam log untuk header dan pesan.

Untuk mengetahui informasi selengkapnya tentang logging, lihat Definisi kumpulan data log.

Menginstrumentasikan aplikasi untuk plugin observabilitas

Untuk melengkapi aplikasi Anda agar dapat menggunakan plugin observabilitas Layanan Mikro, gunakan petunjuk berikut untuk bahasa yang Anda inginkan.

C++

Anda dapat menggunakan C++ dengan kemampuan observasi Microservice mulai gRPC C++ v1.54. Repositori contoh berada di GitHub.

  1. Dukungan observasi hanya tersedia melalui sistem build Bazel. Tambahkan grpcpp_gcp_observability target sebagai dependensi.

  2. Mengaktifkan kemampuan observasi Microservices memerlukan dependensi tambahan (modul observasi) dan perubahan kode berikut pada klien, server, atau keduanya gRPC yang ada:

    #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
    }
    

    Sebelum operasi gRPC, termasuk membuat saluran, server, atau kredensial, panggil hal berikut:

    grpc::GcpObservability::Init();
    

    Tindakan ini akan menampilkan absl::StatusOr<GcpObservability> yang harus disimpan. Status ini membantu menentukan apakah visibilitas berhasil diinisialisasi. Objek GcpObservability yang menyertainya mengontrol masa aktif visibilitas, dan otomatis menutup serta menghapus data visibilitas saat keluar dari cakupan.

Go

  1. Plugin visibilitas microservice didukung untuk gRPC Go versi v1.54.0 dan yang lebih baru. Repositori contoh ada di GitHub.

Dengan modul Go, keikutsertaan dalam Kemampuan observasi microservice memerlukan modul observabilitas dan kode berikut:

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()
  
}

Panggilan observability.Start mengurai konfigurasi dari variabel lingkungan, membuat eksportir sebagaimana mestinya, dan memasukkan logika pengumpulan ke koneksi klien dan server yang dibuat setelah panggilan. Panggilanobservability.End yang ditangguhkan akan membersihkan resource dan memastikan data yang dibuffer dihapus sebelum aplikasi ditutup.

Setelah kode aplikasi diupdate, jalankan perintah berikut untuk mengupdate file go.mod.

go mod tidy

Java

Untuk menggunakan kemampuan observasi Microservices dengan aplikasi Java, ubah build Anda untuk menyertakan artefak grpc-gcp-observability. Gunakan gRPC versi 1.54.1 atau yang lebih baru.

Dalam cuplikan build di bagian alat build Gradle dan Maven, grpcVersion ditetapkan ke nilai 1.54.1.

Repositori contoh ada di GitHub.

  1. Agar berhasil melengkapi aplikasi Java untuk visibilitas Microservices, tambahkan kode berikut ke 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();
...
}

Perhatikan bahwa Anda harus memanggil GcpObservability.grpcInit() sebelum saluran atau server gRPC dibuat. Fungsi GcpObservability.grpcInit() membaca konfigurasi visibilitas Layanan Mikro dan menggunakannya untuk menyiapkan pengintersepsi dan pelacak global yang diperlukan untuk fitur logging, metrik, dan trace di setiap saluran dan server yang dibuat. GcpObservability.grpcInit() aman untuk thread dan harus dipanggil tepat sekali. Tindakan ini akan menampilkan instance GcpObservability yang harus Anda simpan untuk memanggil close() nanti.

GcpObservability.close() membatalkan alokasi resource. Setiap saluran atau server yang dibuat setelah itu tidak melakukan logging apa pun.

GcpObservability menerapkan java.lang.AutoCloseable, yang ditutup secara otomatis jika Anda menggunakan try-with-resource sebagai berikut:

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

Menggunakan alat build Gradle

Jika Anda menggunakan alat build Gradle, sertakan hal berikut:

def grpcVersion = '1.54.1'

...

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

Menggunakan alat build Maven (pom.xml)

Jika Anda menggunakan alat build Maven, sertakan hal berikut:

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

Menjalankan aplikasi

Ikuti petunjuk di bagian ini hanya jika Anda menggunakan contoh gRPC untuk tutorial. Anda dapat mengubah perintah run untuk menargetkan biner aplikasi.

Menjalankan Server

C++

  1. Buat sesi SSH ke VM.
  2. Mengekspor variabel lingkungan. Gunakan langkah-langkah yang ditentukan di atas untuk membuat 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. Menjalankan aplikasi server shell cd grpc tools/bazel run examples/cpp/gcp_observability/helloworld:greeter_server

Go

  1. Buat sesi SSH ke VM.
  2. Mengekspor variabel lingkungan. Gunakan langkah-langkah yang ditentukan di atas untuk membuat server_config.json.

    export GRPC_GCP_OBSERVABILITY_CONFIG_FILE=./server/serverConfig.json
    
  3. Menjalankan aplikasi server shell go run ./server/main.go

Java

  1. Di direktori contoh, buka file README dan ikuti petunjuk dalam file.
  2. Saat petunjuk meminta Anda untuk membuka jendela terminal lain, berikan perintah ini: shell gcloud compute ssh --project=$PROJECT_ID grpc-observability-vm

Menjalankan Klien

C++

  1. Buat sesi SSH lain ke VM.
  2. Mengekspor variabel lingkungan. Gunakan langkah-langkah yang ditentukan di atas untuk membuat file 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. Menjalankan aplikasi klien

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

Go

  1. Buat sesi SSH lain ke VM.
  2. Mengekspor variabel lingkungan. Gunakan langkah-langkah yang ditentukan di atas untuk membuat file client_config.json. shell export GRPC_GCP_OBSERVABILITY_CONFIG_FILE=./client/clientConfig.json
  3. Menjalankan aplikasi klien

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

Java

  1. Di direktori contoh, buka file README dan ikuti petunjuk dalam file.
  2. Saat petunjuk meminta Anda untuk membuka jendela terminal lain, berikan perintah ini: shell gcloud compute ssh --project=$PROJECT_ID grpc-observability-vm

Pembersihan

Agar tidak perlu membayar biaya pada akun Google Cloud Anda untuk resource yang digunakan dalam tutorial ini, hapus project yang berisi resource tersebut, atau simpan project dan hapus setiap resource.

Menghapus project

    Delete a Google Cloud project:

    gcloud projects delete PROJECT_ID

Menghapus resource satu per satu

  1. Hapus instance:
    gcloud compute instances delete INSTANCE_NAME

Langkah selanjutnya