Esegui un job batch utilizzando Workflows

Batch è un servizio completamente gestito che consente di pianificare, inserire in coda ed eseguire carichi di lavoro di elaborazione batch su istanze di macchine virtuali (VM) Compute Engine. Batch esegue il provisioning delle risorse e gestisce la capacità per tuo conto, consentendo l'esecuzione dei workload batch su larga scala.

Workflows ti consente di eseguire i servizi di cui hai bisogno in un ordine definito da te e descritto utilizzando la sintassi di Workflows.

In questo tutorial utilizzerai il connettore Workflows per Batch per pianificare ed eseguire un job Batch che esegue sei attività in parallelo su due VM Compute Engine. L'utilizzo sia di Batch che di Workflows ti consente di combinare i vantaggi che offrono e di eseguire il provisioning e l'orchestrazione dell'intero processo in modo efficiente.

Crea un repository Artifact Registry

Crea un repository per archiviare l'immagine container Docker.

Console

  1. Nella console Google Cloud , vai alla pagina Repository.

    Vai a Repository

  2. Fai clic su Crea repository.

  3. Inserisci containers come nome del repository.

  4. Per Formato, scegli Docker.

  5. Per Tipo di località, scegli Regione.

  6. Nell'elenco Regione, seleziona us-central1.

  7. Fai clic su Crea.

gcloud

Esegui questo comando:

  gcloud artifacts repositories create containers \
    --repository-format=docker \
    --location=us-central1

Hai creato un repository Artifact Registry denominato containers nella regione us-central1. Per saperne di più sulle regioni supportate, consulta Località di Artifact Registry.

Ottieni gli esempi di codice

Google Cloud memorizza il codice sorgente dell'applicazione per questo tutorial in GitHub. Puoi clonare il repository o scaricare gli esempi.

  1. Clona il repository dell'app di esempio sulla tua macchina locale:

    git clone https://github.com/GoogleCloudPlatform/batch-samples.git
    

    In alternativa, puoi scaricare gli esempi nel file main.zip ed estrarli.

  2. Passa alla directory che contiene il codice di esempio:

    cd batch-samples/primegen
    

Ora hai il codice sorgente dell'applicazione nel tuo ambiente di sviluppo.

Crea l'immagine Docker utilizzando Cloud Build

Il Dockerfile contiene le informazioni necessarie per creare un'immagine Docker utilizzando Cloud Build. Esegui questo comando per crearlo:

gcloud builds submit \
  -t us-central1-docker.pkg.dev/PROJECT_ID/containers/primegen-service:v1 PrimeGenService/

Sostituisci PROJECT_ID con l'ID progetto Google Cloud.

Al termine della build, dovresti visualizzare un output simile al seguente:

DONE
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ID: a54818cc-5d14-467b-bfda-5fc9590af68c
CREATE_TIME: 2022-07-29T01:48:50+00:00
DURATION: 48S
SOURCE: gs://project-name_cloudbuild/source/1659059329.705219-17aee3a424a94679937a7200fab15bcf.tgz
IMAGES: us-central1-docker.pkg.dev/project-name/containers/primegen-service:v1
STATUS: SUCCESS

Utilizzando un Dockerfile, hai creato un'immagine Docker denominata primegen-service e ne hai eseguito il push in un repository Artifact Registry denominato containers.

Esegui il deployment di un flusso di lavoro che pianifica ed esegue un job batch

Il seguente flusso di lavoro pianifica ed esegue un job batch che esegue un container Docker come sei attività in parallelo su due VM Compute Engine. Il risultato è la generazione di sei batch di numeri primi, archiviati in un bucket Cloud Storage.

Console

  1. Nella Google Cloud console, vai alla pagina Workflows.

    Vai a Flussi di lavoro

  2. Fai clic su Crea.

  3. Inserisci un nome per il nuovo flusso di lavoro, ad esempio batch-workflow.

  4. Nell'elenco Regione, seleziona us-central1.

  5. Seleziona il service account che hai creato in precedenza.

  6. Fai clic su Avanti.

  7. Nell'editor del workflow, inserisci la seguente definizione per il workflow:

    YAML

    main:
      params: [args]
      steps:
        - init:
            assign:
              - projectId: ${sys.get_env("GOOGLE_CLOUD_PROJECT_ID")}
              - region: "us-central1"
              - imageUri: ${region + "-docker.pkg.dev/" + projectId + "/containers/primegen-service:v1"}
              - jobId: ${"job-primegen-" + string(int(sys.now()))}
              - bucket: ${projectId + "-" + jobId}
        - createBucket:
            call: googleapis.storage.v1.buckets.insert
            args:
              query:
                project: ${projectId}
              body:
                name: ${bucket}
        - logCreateBucket:
            call: sys.log
            args:
              data: ${"Created bucket " + bucket}
        - logCreateBatchJob:
            call: sys.log
            args:
              data: ${"Creating and running the batch job " + jobId}
        - createAndRunBatchJob:
            call: googleapis.batch.v1.projects.locations.jobs.create
            args:
                parent: ${"projects/" + projectId + "/locations/" + region}
                jobId: ${jobId}
                body:
                  taskGroups:
                    taskSpec:
                      runnables:
                        - container:
                            imageUri: ${imageUri}
                          environment:
                            variables:
                              BUCKET: ${bucket}
                    # Run 6 tasks on 2 VMs
                    taskCount: 6
                    parallelism: 2
                  logsPolicy:
                    destination: CLOUD_LOGGING
            result: createAndRunBatchJobResponse
        # You can delete the batch job or keep it for debugging
        - logDeleteBatchJob:
            call: sys.log
            args:
              data: ${"Deleting the batch job " + jobId}
        - deleteBatchJob:
            call: googleapis.batch.v1.projects.locations.jobs.delete
            args:
                name: ${"projects/" + projectId + "/locations/" + region + "/jobs/" + jobId}
            result: deleteResult
        - returnResult:
            return:
              jobId: ${jobId}
              bucket: ${bucket}

    JSON

    {
      "main": {
        "params": [
          "args"
        ],
        "steps": [
          {
            "init": {
              "assign": [
                {
                  "projectId": "${sys.get_env(\"GOOGLE_CLOUD_PROJECT_ID\")}"
                },
                {
                  "region": "us-central1"
                },
                {
                  "imageUri": "${region + \"-docker.pkg.dev/\" + projectId + \"/containers/primegen-service:v1\"}"
                },
                {
                  "jobId": "${\"job-primegen-\" + string(int(sys.now()))}"
                },
                {
                  "bucket": "${projectId + \"-\" + jobId}"
                }
              ]
            }
          },
          {
            "createBucket": {
              "call": "googleapis.storage.v1.buckets.insert",
              "args": {
                "query": {
                  "project": "${projectId}"
                },
                "body": {
                  "name": "${bucket}"
                }
              }
            }
          },
          {
            "logCreateBucket": {
              "call": "sys.log",
              "args": {
                "data": "${\"Created bucket \" + bucket}"
              }
            }
          },
          {
            "logCreateBatchJob": {
              "call": "sys.log",
              "args": {
                "data": "${\"Creating and running the batch job \" + jobId}"
              }
            }
          },
          {
            "createAndRunBatchJob": {
              "call": "googleapis.batch.v1.projects.locations.jobs.create",
              "args": {
                "parent": "${\"projects/\" + projectId + \"/locations/\" + region}",
                "jobId": "${jobId}",
                "body": {
                  "taskGroups": {
                    "taskSpec": {
                      "runnables": [
                        {
                          "container": {
                            "imageUri": "${imageUri}"
                          },
                          "environment": {
                            "variables": {
                              "BUCKET": "${bucket}"
                            }
                          }
                        }
                      ]
                    },
                    "taskCount": 6,
                    "parallelism": 2
                  },
                  "logsPolicy": {
                    "destination": "CLOUD_LOGGING"
                  }
                }
              },
              "result": "createAndRunBatchJobResponse"
            }
          },
          {
            "logDeleteBatchJob": {
              "call": "sys.log",
              "args": {
                "data": "${\"Deleting the batch job \" + jobId}"
              }
            }
          },
          {
            "deleteBatchJob": {
              "call": "googleapis.batch.v1.projects.locations.jobs.delete",
              "args": {
                "name": "${\"projects/\" + projectId + \"/locations/\" + region + \"/jobs/\" + jobId}"
              },
              "result": "deleteResult"
            }
          },
          {
            "returnResult": {
              "return": {
                "jobId": "${jobId}",
                "bucket": "${bucket}"
              }
            }
          }
        ]
      }
    }
    
  8. Fai clic su Esegui il deployment.

gcloud

  1. Crea un file di codice sorgente per il workflow:

    touch batch-workflow.JSON_OR_YAML

    Sostituisci JSON_OR_YAML con yaml o json a seconda del formato del workflow.

  2. In un editor di testo, copia il seguente flusso di lavoro nel file del codice sorgente:

    YAML

    main:
      params: [args]
      steps:
        - init:
            assign:
              - projectId: ${sys.get_env("GOOGLE_CLOUD_PROJECT_ID")}
              - region: "us-central1"
              - imageUri: ${region + "-docker.pkg.dev/" + projectId + "/containers/primegen-service:v1"}
              - jobId: ${"job-primegen-" + string(int(sys.now()))}
              - bucket: ${projectId + "-" + jobId}
        - createBucket:
            call: googleapis.storage.v1.buckets.insert
            args:
              query:
                project: ${projectId}
              body:
                name: ${bucket}
        - logCreateBucket:
            call: sys.log
            args:
              data: ${"Created bucket " + bucket}
        - logCreateBatchJob:
            call: sys.log
            args:
              data: ${"Creating and running the batch job " + jobId}
        - createAndRunBatchJob:
            call: googleapis.batch.v1.projects.locations.jobs.create
            args:
                parent: ${"projects/" + projectId + "/locations/" + region}
                jobId: ${jobId}
                body:
                  taskGroups:
                    taskSpec:
                      runnables:
                        - container:
                            imageUri: ${imageUri}
                          environment:
                            variables:
                              BUCKET: ${bucket}
                    # Run 6 tasks on 2 VMs
                    taskCount: 6
                    parallelism: 2
                  logsPolicy:
                    destination: CLOUD_LOGGING
            result: createAndRunBatchJobResponse
        # You can delete the batch job or keep it for debugging
        - logDeleteBatchJob:
            call: sys.log
            args:
              data: ${"Deleting the batch job " + jobId}
        - deleteBatchJob:
            call: googleapis.batch.v1.projects.locations.jobs.delete
            args:
                name: ${"projects/" + projectId + "/locations/" + region + "/jobs/" + jobId}
            result: deleteResult
        - returnResult:
            return:
              jobId: ${jobId}
              bucket: ${bucket}

    JSON

    {
      "main": {
        "params": [
          "args"
        ],
        "steps": [
          {
            "init": {
              "assign": [
                {
                  "projectId": "${sys.get_env(\"GOOGLE_CLOUD_PROJECT_ID\")}"
                },
                {
                  "region": "us-central1"
                },
                {
                  "imageUri": "${region + \"-docker.pkg.dev/\" + projectId + \"/containers/primegen-service:v1\"}"
                },
                {
                  "jobId": "${\"job-primegen-\" + string(int(sys.now()))}"
                },
                {
                  "bucket": "${projectId + \"-\" + jobId}"
                }
              ]
            }
          },
          {
            "createBucket": {
              "call": "googleapis.storage.v1.buckets.insert",
              "args": {
                "query": {
                  "project": "${projectId}"
                },
                "body": {
                  "name": "${bucket}"
                }
              }
            }
          },
          {
            "logCreateBucket": {
              "call": "sys.log",
              "args": {
                "data": "${\"Created bucket \" + bucket}"
              }
            }
          },
          {
            "logCreateBatchJob": {
              "call": "sys.log",
              "args": {
                "data": "${\"Creating and running the batch job \" + jobId}"
              }
            }
          },
          {
            "createAndRunBatchJob": {
              "call": "googleapis.batch.v1.projects.locations.jobs.create",
              "args": {
                "parent": "${\"projects/\" + projectId + \"/locations/\" + region}",
                "jobId": "${jobId}",
                "body": {
                  "taskGroups": {
                    "taskSpec": {
                      "runnables": [
                        {
                          "container": {
                            "imageUri": "${imageUri}"
                          },
                          "environment": {
                            "variables": {
                              "BUCKET": "${bucket}"
                            }
                          }
                        }
                      ]
                    },
                    "taskCount": 6,
                    "parallelism": 2
                  },
                  "logsPolicy": {
                    "destination": "CLOUD_LOGGING"
                  }
                }
              },
              "result": "createAndRunBatchJobResponse"
            }
          },
          {
            "logDeleteBatchJob": {
              "call": "sys.log",
              "args": {
                "data": "${\"Deleting the batch job \" + jobId}"
              }
            }
          },
          {
            "deleteBatchJob": {
              "call": "googleapis.batch.v1.projects.locations.jobs.delete",
              "args": {
                "name": "${\"projects/\" + projectId + \"/locations/\" + region + \"/jobs/\" + jobId}"
              },
              "result": "deleteResult"
            }
          },
          {
            "returnResult": {
              "return": {
                "jobId": "${jobId}",
                "bucket": "${bucket}"
              }
            }
          }
        ]
      }
    }
    
  3. Esegui il deployment del flusso di lavoro inserendo questo comando:

    gcloud workflows deploy batch-workflow \
      --source=batch-workflow.yaml \
      --location=us-central1 \
      --service-account=SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com

    Sostituisci SERVICE_ACCOUNT_NAME con il nome del account di servizio che hai creato in precedenza.

Esegui il flusso di lavoro

L'esecuzione di un workflow esegue la definizione attuale del workflow associata al workflow.

Console

  1. Nella Google Cloud console, vai alla pagina Workflows.

    Vai a Flussi di lavoro

  2. Nella pagina Flussi di lavoro, fai clic sul workflow batch-workflow per accedere alla relativa pagina dei dettagli.

  3. Nella pagina Dettagli workflow, fai clic su Esegui.

  4. Fai di nuovo clic su Esegui.

    L'esecuzione del flusso di lavoro dovrebbe richiedere alcuni minuti.

  5. Visualizza i risultati del flusso di lavoro nel riquadro Output.

    I risultati dovrebbero essere simili ai seguenti:

    {
      "bucket": "project-name-job-primegen-TIMESTAMP",
      "jobId": "job-primegen-TIMESTAMP"
    }
    

gcloud

  1. Esegui il workflow:

    gcloud workflows run batch-workflow \
      --location=us-central1

    L'esecuzione del flusso di lavoro dovrebbe richiedere alcuni minuti.

  2. Puoi controllare lo stato di un'esecuzione a lunga esecuzione.

  3. Per ottenere lo stato dell'ultima esecuzione completata, esegui questo comando:

    gcloud workflows executions describe-last

    I risultati dovrebbero essere simili ai seguenti:

    name: projects/PROJECT_NUMBER/locations/us-central1/workflows/batch-workflow/executions/EXECUTION_ID
    result: '{"bucket":"project-name-job-primegen-TIMESTAMP","jobId":"job-primegen-TIMESTAMP"}'
    startTime: '2022-07-29T16:08:39.725306421Z'
    state: SUCCEEDED
    status:
      currentSteps:
      - routine: main
        step: returnResult
    workflowRevisionId: 000001-9ba
    

Elenca gli oggetti nel bucket di output

Puoi verificare che i risultati siano quelli previsti elencando gli oggetti nel bucket di output Cloud Storage.

Console

  1. Nella console Google Cloud , vai alla pagina Bucket in Cloud Storage.

    Vai a Bucket

  2. Nell'elenco dei bucket, fai clic sul nome del bucket di cui vuoi visualizzare i contenuti.

    I risultati dovrebbero essere simili ai seguenti, con sei file in totale e ciascuno contenente un batch di 10.000 numeri primi:

    primes-1-10000.txt
    primes-10001-20000.txt
    primes-20001-30000.txt
    primes-30001-40000.txt
    primes-40001-50000.txt
    primes-50001-60000.txt
    

gcloud

  1. Recupera il nome del bucket di output:

    gcloud storage ls

    L'output è simile al seguente:

    gs://PROJECT_ID-job-primegen-TIMESTAMP/

  2. Elenca gli oggetti nel bucket di output:

    gcloud storage ls gs://PROJECT_ID-job-primegen-TIMESTAMP/** --recursive

    Sostituisci TIMESTAMP con il timestamp restituito dal comando precedente.

    L'output dovrebbe essere simile al seguente, con sei file in totale e ciascuno contenente un batch di 10.000 numeri primi:

    gs://project-name-job-primegen-TIMESTAMP/primes-1-10000.txt
    gs://project-name-job-primegen-TIMESTAMP/primes-10001-20000.txt
    gs://project-name-job-primegen-TIMESTAMP/primes-20001-30000.txt
    gs://project-name-job-primegen-TIMESTAMP/primes-30001-40000.txt
    gs://project-name-job-primegen-TIMESTAMP/primes-40001-50000.txt
    gs://project-name-job-primegen-TIMESTAMP/primes-50001-60000.txt