Menyiapkan aplikasi gRPC di Google Cloud dengan kemampuan observasi Microservices


Alat observabilitas microservice memberi Anda kemampuan untuk menginstrumentasi aplikasi guna mengumpulkan dan menyajikan 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 diberi izin untuk mengakses Monitoring, Logging, dan Trace dengan mengaktifkan Microservices API.

Dalam tutorial ini, Anda akan mempelajari cara menggunakan fitur keobservasian Microservice dengan membuat aplikasi gRPC sederhana di Google Cloud menggunakan Compute Engine dan menginstrumentasikan aplikasi Anda dengan keobservasian Microservice, serta melihatnya muncul secara langsung di Monitoring dan Logging.

Tujuan

Pada intinya, Anda perlu melakukan tindakan berikut.

  • Sebagai developer layanan, Anda dapat:

    • Buat aplikasi gRPC dengan bahasa pilihan Anda (C++, Go, atau Java).
    • Ikut serta 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).
    • Lihat 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. Verify 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. Verify 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 dua variabel lingkungan yang didukung, tentukan mana 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. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Verify 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: roles/logging.logWriter, roles/monitoring.metricWriter, roles/cloudtrace.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. Install the Google Cloud CLI.

  7. Jika Anda menggunakan penyedia identitas (IdP) eksternal, Anda harus login ke gcloud CLI dengan identitas gabungan Anda terlebih dahulu.

  8. Untuk melakukan inisialisasi gcloud CLI, jalankan perintah berikut:

    gcloud init
  9. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

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

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

    Enable the APIs

  12. 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: roles/logging.logWriter, roles/monitoring.metricWriter, roles/cloudtrace.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.

  13. Install the Google Cloud CLI.

  14. Jika Anda menggunakan penyedia identitas (IdP) eksternal, Anda harus login ke gcloud CLI dengan identitas gabungan Anda terlebih dahulu.

  15. Untuk melakukan inisialisasi gcloud CLI, jalankan perintah berikut:

    gcloud init
  16. Baca Ringkasan kemampuan observasi microservice.
  17. Baca dua variabel lingkungan yang didukung, tentukan mana yang akan digunakan, dan tentukan nilai yang diperlukan oleh variabel lingkungan.

Membuat dan menghubungkan ke VM Compute Engine

Gunakan petunjuk ini untuk membuat dan menghubungkan ke instance VM Compute Engine. Di VM, Anda men-deploy aplikasi, lalu menginstrumentasikan aplikasi dengan kemampuan observasi Microservice.

  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 Anda ke VM Compute Engine

Anda dapat men-deploy aplikasi pilihan Anda ke VM Compute Engine yang Anda buat pada langkah sebelumnya, lalu lewati 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. Buat 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 Anda 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
    

Buat file konfigurasi gRPC Google Cloud Observability

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

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 memperbarui your-project-here) atau menggunakannya sebagai template untuk aplikasi Anda.Contoh yang menunjukkan 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 secara acak melacak 50% RPC.

Jika Anda berencana mengaktifkan pelacakan di seluruh layanan, pastikan layanan mendukung propagasi konteks rekaman aktivitas yang diterima dari hulu (atau dimulai dengan sendirinya) ke hilir.

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

Aktifkan logging

Untuk mengaktifkan logging, lakukan hal berikut:

  1. Tambahkan objek cloud_logging ke konfigurasi.
  2. Tambahkan pola ke client_rpc_events atau server_rpc_events atau keduanya yang menentukan kumpulan layanan atau metode yang ingin Anda buat pencatatan peristiwa tingkat transportasi dan jumlah byte yang akan dicatat untuk header dan pesan.

Untuk mengetahui informasi selengkapnya tentang logging, lihat Definisi rekaman log.

Melengkapi aplikasi Anda untuk plugin kemampuan observasi

Untuk menginstrumentasi aplikasi agar dapat menggunakan plugin observabilitas Microservices, gunakan petunjuk berikut untuk bahasa pilihan Anda.

C++

Anda dapat menggunakan C++ dengan kemampuan observasi Microservices mulai dari gRPC C++ v1.54. Repositori contoh ada di GitHub.

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

  2. Mengaktifkan kemampuan observasi Microservice memerlukan dependensi tambahan (modul observasi) dan perubahan kode berikut pada klien, server gRPC, atau keduanya yang sudah 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 melakukan operasi gRPC apa pun, termasuk membuat saluran, server, atau kredensial, panggil yang berikut:

    grpc::GcpObservability::Init();
    

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

Go

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

Dengan modul Go, memilih untuk mengaktifkan kemampuan observasi Microservice memerlukan modul kemampuan observasi 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 yang sesuai, dan menyisipkan logika pengumpulan ke koneksi klien dan server yang dibuat setelah panggilan. Panggilanobservability.End yang ditangguhkan membersihkan resource dan memastikan bahwa data yang di-buffer dikosongkan sebelum aplikasi ditutup.

Setelah kode aplikasi diperbarui, jalankan perintah berikut untuk memperbarui file go.mod.

go mod tidy

Java

Untuk menggunakan Kemampuan observasi microservice 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 disetel ke nilai 1.54.1.

Repositori contoh ada di GitHub.

  1. Agar berhasil melengkapi aplikasi Java untuk kemampuan pengamatan Microservice, 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 pengamatan Microservices dan menggunakannya untuk menyiapkan interceptor dan tracer global yang diperlukan untuk fitur logging, metrik, dan trace di setiap channel dan server yang dibuat. GcpObservability.grpcInit() aman untuk thread dan harus dipanggil tepat satu kali. Metode ini menampilkan instance GcpObservability yang harus Anda simpan untuk memanggil close() nanti.

GcpObservability.close() membatalkan alokasi resource. Channel atau server yang dibuat setelahnya tidak melakukan logging apa pun.

GcpObservability mengimplementasikan 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 kode 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 kode 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>

Jalankan aplikasi Anda

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

Menjalankan Server

C++

  1. Buat sesi SSH ke VM.
  2. Ekspor 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. Jalankan aplikasi server shell cd grpc tools/bazel run examples/cpp/gcp_observability/helloworld:greeter_server

Go

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

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

Java

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

Jalankan Klien

C++

  1. Buat sesi SSH lain ke VM.
  2. Ekspor 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. Ekspor 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 membuka jendela terminal lain, jalankan 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

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

Menghapus resource satu per satu

  1. In the Google Cloud console, go to the VM instances page.

    Go to VM instances

  2. Select the checkbox for the instance that you want to delete.
  3. To delete the instance, click More actions, click Delete, and then follow the instructions.

Langkah berikutnya