Menyiapkan gRPC Cloud Endpoints untuk Cloud Run dengan ESPv2

Halaman ini menunjukkan cara menyiapkan Cloud Endpoints untuk Cloud Run dengan backend gRPC. Endpoints menggunakan Extensible Service Proxy V2 (ESPv2) sebagai gateway API. Untuk menyediakan pengelolaan API bagi Cloud Run, Anda men-deploy container ESPv2 yang telah dibuat sebelumnya ke Cloud Run. Kemudian, Anda membantu mengamankan layanan dengan menggunakan IAM Cloud Run sehingga ESPv2 dapat memanggilnya.

Dengan penyiapan ini, ESPv2 mencegat semua permintaan ke layanan Anda dan melakukan pemeriksaan yang diperlukan (seperti autentikasi) sebelum memanggil layanan. Saat layanan merespons, ESPv2 mengumpulkan dan melaporkan telemetri, seperti yang ditunjukkan pada gambar di bawah. Anda dapat melihat metrik untuk layanan Anda di halaman Endpoints > Services di konsol Google Cloud .

Arsitektur endpoint

Untuk ringkasan Cloud Endpoints, lihat Tentang Endpoints dan Arsitektur Endpoints.

Bermigrasi ke ESPv2

Rilis Cloud Endpoints sebelumnya tidak mendukung gRPC di Cloud Run dengan ESP. Untuk menggunakan fitur ini, lakukan migrasi ke Extensible Service Proxy V2.

Daftar Tugas

Gunakan daftar tugas berikut saat Anda mengerjakan tutorial ini. Semua tugas diperlukan untuk menyelesaikan tutorial ini.

  1. Buat Google Cloud project, dan jika Anda belum men-deploy Cloud Run Anda sendiri, deploy layanan gRPC backend contoh. Lihat Sebelum memulai.
  2. Cadangkan nama host Cloud Run untuk layanan ESPv2. Lihat Mencadangkan nama host Cloud Run.
  3. Buat dokumen konfigurasi gRPC API yang menjelaskan API Anda, dan konfigurasi rute ke Cloud Run. Lihat Mengonfigurasi Endpoint.
  4. Deploy dokumen konfigurasi gRPC API untuk membuat layanan terkelola. Lihat Men-deploy konfigurasi Endpoints.
  5. Buat image Docker ESPv2 baru dengan konfigurasi layanan Endpoints Anda. Lihat Membangun image ESPv2 baru.
  6. Deploy container ESPv2 ke Cloud Run. Kemudian, berikan izin Identity and Access Management (IAM) kepada ESPv2 untuk memanggil layanan Anda. Lihat Men-deploy container ESPv2.
  7. Panggil layanan. Lihat Mengirim permintaan ke API.
  8. Melacak aktivitas ke layanan Anda. Lihat Melacak aktivitas API.
  9. Hindari timbulnya biaya pada akun Google Cloud Anda. Lihat Pembersihan.

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

Untuk menyiapkan:

  1. Di konsol Google Cloud , buka halaman Manage resources, lalu buat project.

    Buka halaman Kelola resource

  2. Pastikan penagihan diaktifkan untuk project Anda.

    Pelajari cara mengaktifkan penagihan

  3. Catat project ID karena akan diperlukan nanti. Di bagian selanjutnya dari halaman ini, project ID ini disebut sebagai ESPv2_PROJECT_ID.

  4. Catat nomor project karena akan diperlukan nanti. Di bagian lain halaman ini, nomor project ini disebut sebagai ESPv2_PROJECT_NUMBER.

  5. Download dan instal Google Cloud CLI.

    Download gcloud CLI

  6. Ikuti langkah-langkah di Panduan memulai gRPC Python untuk menginstal gRPC dan alat gRPC.

  7. Deploy contoh backend python-grpc-bookstore-server layanan gRPC Cloud Run untuk digunakan dengan tutorial ini. Layanan gRPC menggunakan image container berikut:

    gcr.io/endpointsv2/python-grpc-bookstore-server:2

    Ikuti langkah-langkah di Panduan memulai: Men-deploy Container Contoh yang Sudah Dibuat untuk men-deploy layanan. Pastikan untuk mengganti image container yang ditentukan dalam panduan memulai tersebut dengan gcr.io/endpointsv2/python-grpc-bookstore-server:2

    Catat region dan project ID tempat layanan Anda di-deploy. Di bagian selanjutnya dari halaman ini, project ID ini disebut sebagai BACKEND_PROJECT_ID. Nama layanan Cloud Run yang di-deploy disebut sebagai BACKEND_SERVICE_NAME. Nama host Cloud Run-nya disebut sebagai BACKEND_HOST_NAME.

Mencadangkan nama host Cloud Run

Anda harus mencadangkan nama host Cloud Run untuk layanan ESPv2 agar dapat mengonfigurasi dokumen OpenAPI atau konfigurasi layanan gRPC. Untuk mencadangkan nama host, Anda akan men-deploy container contoh ke Cloud Run. Selanjutnya, Anda akan men-deploy container ESPv2 ke layanan Cloud Run yang sama.

  1. Pastikan gcloud CLI diizinkan untuk mengakses data dan layanan Anda.
    1. Log in.
      gcloud auth login
    2. Di tab browser baru yang terbuka, pilih akun yang memiliki peran Editor atau Pemilik di project yang Anda buat untuk men-deploy ESPv2 ke Cloud Run. Google Cloud
  2. Tetapkan region.
    gcloud config set run/region us-central1
  3. Deploy image contoh gcr.io/cloudrun/hello ke Cloud Run. Ganti ESPv2_CLOUD_RUN_SERVICE_NAME dengan nama yang ingin Anda gunakan untuk layanan.
    gcloud run deploy ESPv2_CLOUD_RUN_SERVICE_NAME \
        --image="gcr.io/cloudrun/hello" \
        --allow-unauthenticated \
        --platform managed \
        --project=ESPv2_PROJECT_ID
    

    Setelah berhasil diselesaikan, perintah akan menampilkan pesan yang mirip dengan berikut ini:

    Service [ESPv2_CLOUD_RUN_SERVICE_NAME] revision [ESPv2_CLOUD_RUN_SERVICE_NAME-REVISION_NUM] has been deployed and is serving traffic at CLOUD_RUN_SERVICE_URL

    Misalnya, jika Anda menetapkan ESPv2_CLOUD_RUN_SERVICE_NAME ke gateway:

    Service [gateway] revision [gateway-00001] has been deployed and is serving traffic at https://gateway-12345-uc.a.run.app

    Dalam contoh ini, https://gateway-12345-uc.a.run.app adalah CLOUD_RUN_SERVICE_URL dan gateway-12345-uc.a.run.app adalah v2_CLOUD_RUN_HOSTNAME.

  4. Catat ESPv2_CLOUD_RUN_SERVICE_NAME dan ESPv2_CLOUD_RUN_HOSTNAME. Selanjutnya, Anda akan men-deploy ESPv2 ke layanan Cloud Run ESPv2_CLOUD_RUN_SERVICE_NAME. Anda menentukan ESPv2_CLOUD_RUN_HOSTNAME di kolom host pada dokumen OpenAPI.

Mengonfigurasi Endpoint

Contoh bookstore-grpc berisi file yang perlu Anda salin secara lokal dan dikonfigurasi.

  1. Create a self-contained protobuf descriptor file from your service .proto file:
    1. Save a copy of bookstore.proto from the example repository to your current working directory. This file defines the Bookstore service's API.
    2. Create the following directory under your working directory: mkdir generated_pb2
    3. Create the descriptor file, api_descriptor.pb, by using the protoc protocol buffers compiler. Run the following command in the directory where you saved bookstore.proto:
      python3 -m grpc_tools.protoc \
          --include_imports \
          --include_source_info \
          --proto_path=. \
          --descriptor_set_out=api_descriptor.pb \
          --python_out=generated_pb2 \
          --grpc_python_out=generated_pb2 \
          bookstore.proto

      In the preceding command, --proto_path is set to the current working directory. In your gRPC build environment, if you use a different directory for .proto input files, change --proto_path so the compiler searches the directory where you saved bookstore.proto.

  2. Create a text file called api_config.yaml in your current working directory (the same directory that contains bookstore.proto). For convenience, this page refers to the gRPC API configuration document by that file name, but you can name it something else if you prefer. Add the following contents to the file:
    # The configuration schema is defined by the service.proto file.
    # https://github.com/googleapis/googleapis/blob/master/google/api/service.proto
    
    type: google.api.Service
    config_version: 3
    name: CLOUD_RUN_HOSTNAME
    title: Cloud Endpoints + Cloud Run gRPC
    apis:
      - name: endpoints.examples.bookstore.Bookstore
    usage:
      rules:
      # ListShelves methods can be called without an API Key.
      - selector: endpoints.examples.bookstore.Bookstore.ListShelves
        allow_unregistered_calls: true
    backend:
      rules:
        - selector: "*"
          address: grpcs://BACKEND_HOST_NAME
    
    Indentation is important for yaml format. For example the name field must be at the same level as type.
  3. In the name field, specify CLOUD_RUN_HOSTNAME, the hostname portion of the URL that was reserved above in Reserving a Cloud Run hostname. Don't include the protocol identifier, such as https:// or grpcs://.

  4. In the address field in the backend.rules section, replace BACKEND_HOST_NAME with the actual gRPC Bookstore Cloud Run service created in Before you begin.

  5. Note the value of the title property in the api_config.yaml file:

    title: Cloud Endpoints + Cloud Run gRPC

    The value of the title property becomes the name of the Endpoints service after you deploy the configuration.

  6. Save your gRPC API configuration document.

Lihat Mengonfigurasi Endpoint untuk mengetahui informasi selengkapnya.

Men-deploy konfigurasi Endpoint

Untuk men-deploy konfigurasi Endpoints, Anda menggunakan perintah gcloud endpoints services deploy. Perintah ini menggunakan Service Management untuk membuat layanan terkelola.

  1. Make sure you are in the directory where the api_descriptor.pb and api_config.yaml files are located.
  2. Confirm that the default project that the gcloud command-line tool is currently using is the Google Cloud project that you want to deploy the Endpoints configuration to. Validate the project ID returned from the following command to make sure that the service doesn't get created in the wrong project.
    gcloud config list project
    

    If you need to change the default project, run the following command:

    gcloud config set project YOUR_PROJECT_ID
    
  3. Deploy the proto descriptor file and the configuration file by using the Google Cloud CLI:
    gcloud endpoints services deploy api_descriptor.pb api_config.yaml
    

    As it is creating and configuring the service, Service Management outputs information to the terminal. When the deployment completes, a message similar to the following is displayed:

    Service Configuration [CONFIG_ID] uploaded for service [bookstore.endpoints.example-project.cloud.goog]

    CONFIG_ID is the unique Endpoints service configuration ID created by the deployment. For example:

    Service Configuration [2017-02-13r0] uploaded for service [bookstore.endpoints.example-project.cloud.goog]
    

    In the previous example, 2017-02-13r0 is the service configuration ID and bookstore.endpoints.example-project.cloud.goog is the service name. The service configuration ID consists of a date stamp followed by a revision number. If you deploy the Endpoints configuration again on the same day, the revision number is incremented in the service configuration ID.

Memeriksa layanan yang diperlukan

Minimal, Endpoints dan ESP memerlukan layanan Google berikut diaktifkan:
Nama Judul
servicemanagement.googleapis.com Service Management API
servicecontrol.googleapis.com Service Control API

Dalam sebagian besar kasus, perintah gcloud endpoints services deploy akan mengaktifkan layanan yang diperlukan ini. Namun, perintah gcloud berhasil diselesaikan, tetapi tidak mengaktifkan layanan yang diperlukan dalam keadaan berikut:

  • Jika Anda menggunakan aplikasi pihak ketiga seperti Terraform, dan Anda tidak menyertakan layanan ini.

  • Anda men-deploy konfigurasi Endpoints ke projectGoogle Cloud yang sudah ada tempat layanan ini dinonaktifkan secara eksplisit.

Gunakan perintah berikut untuk mengonfirmasi bahwa layanan yang diperlukan sudah diaktifkan:

gcloud services list

Jika Anda tidak melihat layanan yang diperlukan tercantum, aktifkan layanan tersebut:

gcloud services enable servicemanagement.googleapis.com
gcloud services enable servicecontrol.googleapis.com

Aktifkan juga layanan Endpoints Anda:

gcloud services enable ENDPOINTS_SERVICE_NAME

Untuk menentukan ENDPOINTS_SERVICE_NAME, Anda dapat:

  • Setelah men-deploy konfigurasi Endpoints, buka halaman Endpoints di Konsol Cloud. Daftar ENDPOINTS_SERVICE_NAME yang mungkin ditampilkan di kolom Nama layanan.

  • Untuk OpenAPI, ENDPOINTS_SERVICE_NAME adalah yang Anda tentukan di kolom host spesifikasi OpenAPI. Untuk gRPC, ENDPOINTS_SERVICE_NAME adalah yang Anda tentukan di kolom name konfigurasi gRPC Endpoints.

Untuk mengetahui informasi selengkapnya tentang perintah gcloud, lihat layanan gcloud.

Jika Anda menerima pesan error, lihat Memecahkan masalah deployment konfigurasi Endpoints.

Lihat Men-deploy konfigurasi Endpoints untuk mengetahui informasi tambahan.

Membangun image ESPv2 baru

Buat konfigurasi layanan Endpoints menjadi image Docker ESPv2 baru. Anda akan men-deploy image ini ke layanan Cloud Run yang dicadangkan nanti.

Untuk membuat konfigurasi layanan menjadi image Docker ESPv2 baru:

  1. Download skrip ini ke komputer lokal Anda tempat gcloud CLI diinstal.

  2. Jalankan skrip dengan perintah berikut:

    chmod +x gcloud_build_image
    
    ./gcloud_build_image -s ESPv2_CLOUD_RUN_HOSTNAME \
        -c CONFIG_ID -p ESPv2_PROJECT_ID

    Untuk ESPv2_CLOUD_RUN_HOSTNAME, tentukan nama host URL yang Anda pesan di atas dalam Memesan nama host Cloud Run. Jangan sertakan ID protokol, https://.

    Contoh:

    chmod +x gcloud_build_image
    
    ./gcloud_build_image -s gateway-12345-uc.a.run.app \
        -c 2019-02-01r0 -p your-project-id
  3. Skrip menggunakan perintah gcloud untuk mendownload konfigurasi layanan, membangun konfigurasi layanan menjadi image ESPv2 baru, dan mengupload image baru ke container registry project Anda. Skrip otomatis menggunakan rilis ESPv2 terbaru, yang ditunjukkan oleh ESPv2_VERSION dalam nama gambar output. Gambar output diupload ke:

    gcr.io/ESPv2_PROJECT_ID/endpoints-runtime-serverless:ESPv2_VERSION-ESPv2_CLOUD_RUN_HOSTNAME-CONFIG_ID

    Contoh:

    gcr.io/your-project-id/endpoints-runtime-serverless:2.14.0-gateway-12345-uc.a.run.app-2019-02-01r0"

Men-deploy container ESPv2

  1. Deploy layanan Cloud Run ESPv2 dengan image baru yang Anda buat di atas. Ganti CLOUD_RUN_SERVICE_NAME dengan nama layanan Cloud Run yang sama dengan yang Anda gunakan saat pertama kali mencadangkan nama host di atas dalam Mencadangkan nama host Cloud Run:

    gcloud run deploy CLOUD_RUN_SERVICE_NAME \
      --image="gcr.io/ESPv2_PROJECT_ID/endpoints-runtime-serverless:ESPv2_VERSION-CLOUD_RUN_HOSTNAME-CONFIG_ID" \
      --allow-unauthenticated \
      --platform managed \
      --project=ESPv2_PROJECT_ID
  2. Jika ingin mengonfigurasi Endpoints untuk menggunakan opsi startup ESPv2 tambahan, seperti mengaktifkan CORS, Anda dapat meneruskan argumen dalam variabel lingkungan ESPv2_ARGS:

    gcloud run deploy CLOUD_RUN_SERVICE_NAME \
      --image="gcr.io/ESPv2_PROJECT_ID/endpoints-runtime-serverless:ESPv2_VERSION-CLOUD_RUN_HOSTNAME-CONFIG_ID" \
      --set-env-vars=ESPv2_ARGS=--cors_preset=basic \
      --allow-unauthenticated \
      --platform managed \
      --project ESPv2_PROJECT_ID

    Untuk mengetahui informasi dan contoh selengkapnya tentang cara menyetel variabel lingkungan ESPv2_ARGS, termasuk daftar opsi yang tersedia dan informasi tentang cara menentukan beberapa opsi, lihat Flag Extensible Service Proxy V2.

  3. Beri ESPv2 izin untuk memanggil layanan Cloud Run Anda. Jalankan perintah berikut untuk setiap layanan. Dalam perintah berikut:
    • Ganti BACKEND_SERVICE_NAME dengan nama layanan Cloud Run yang dipanggil. Jika Anda menggunakan layanan yang dibuat dengan men-deploy `gcr.io/endpointsv2/python-grpc-bookstore-server:2`, gunakan python-grpc-bookstore-server sebagai nilai ini.
    • Ganti ESPv2_PROJECT_NUMBER dengan nomor project yang Anda buat untuk ESPv2. Salah satu cara untuk menemukannya adalah dengan membuka halaman IAM di konsol Google Cloud dan menemukan Akun layanan komputasi default, yang merupakan akun layanan yang digunakan dalam flag `member`.
    gcloud run services add-iam-policy-binding BACKEND_SERVICE_NAME \
      --member "serviceAccount:ESPv2_PROJECT_NUMBER-compute@developer.gserviceaccount.com" \
      --role "roles/run.invoker" \
      --platform managed \
      --project BACKEND_PROJECT_ID

Untuk mengetahui informasi selengkapnya, lihat Mengelola akses menggunakan IAM.

Mengirim permintaan ke API

To send requests to the sample API, you can use a sample gRPC client written in Python.

  1. Clone the git repo where the gRPC client code is hosted:

    git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git
  2. Change your working directory:

    cd python-docs-samples/endpoints/bookstore-grpc/
  3. Install dependencies:

    pip3 install virtualenv
    virtualenv env
    source env/bin/activate
    pip3 install -r requirements.txt
  4. Send a request to the sample API:

    python3 bookstore_client.py --host CLOUD_RUN_HOSTNAME --port 443 --use_tls true

    Specify the hostname of your ESPv2 Cloud Run service in CLOUD_RUN_HOSTNAME, without the protocol identifier. For example:

    python3 bookstore_client.py --host espv2-grpc-HASH-uc.a.run.app --port 443 --use_tls true

Jika Anda tidak mendapatkan respons yang berhasil, lihat Memecahkan masalah error respons.

Anda baru saja men-deploy dan menguji API di Endpoints.

Melacak aktivitas API

  1. Lihat grafik aktivitas untuk API Anda di halaman Endpoints > Service di konsol Google Cloud .

    Melihat grafik aktivitas Endpoint

    Mungkin perlu waktu beberapa saat agar permintaan ditampilkan dalam grafik.

  2. Lihat log permintaan untuk API Anda di halaman Logs Explorer.

    Melihat log permintaan Endpoints

Pembersihan

Agar akun Google Cloud Anda tidak dikenai biaya untuk resource yang digunakan pada halaman ini, ikuti langkah-langkah berikut.

Lihat Menghapus API dan instance API untuk mengetahui informasi tentang cara menghentikan layanan yang digunakan oleh tutorial ini.

Langkah berikutnya