Flusso di lavoro con le funzioni Cloud Run

Prima di iniziare

Se non l'hai ancora fatto, configura un progetto Google Cloud e due (2) bucket Cloud Storage.

Configura il progetto

  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 Dataproc, Compute Engine, Cloud Storage, and Cloud Run functions APIs.

    Enable the APIs

  5. Install the Google Cloud CLI.

  6. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  7. To initialize the gcloud CLI, run the following command:

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

    Go to project selector

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

  10. Enable the Dataproc, Compute Engine, Cloud Storage, and Cloud Run functions APIs.

    Enable the APIs

  11. Install the Google Cloud CLI.

  12. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  13. To initialize the gcloud CLI, run the following command:

    gcloud init
  14. Crea o utilizza due bucket Cloud Storage nel tuo progetto

    Nel tuo progetto avrai bisogno di due bucket Cloud Storage: uno per i file di input e un altro per l'output.

    1. In the Google Cloud console, go to the Cloud Storage Buckets page.

      Go to Buckets

    2. Click Create.
    3. On the Create a bucket page, enter your bucket information. To go to the next step, click Continue.
      1. In the Get started section, do the following:
        • Enter a globally unique name that meets the bucket naming requirements.
        • To add a bucket label, expand the Labels section (), click Add label, and specify a key and a value for your label.
      2. In the Choose where to store your data section, do the following:
        1. Select a Location type.
        2. Choose a location where your bucket's data is permanently stored from the Location type drop-down menu.
        3. To set up cross-bucket replication, select Add cross-bucket replication via Storage Transfer Service and follow these steps:

          Set up cross-bucket replication

          1. In the Bucket menu, select a bucket.
          2. In the Replication settings section, click Configure to configure settings for the replication job.

            The Configure cross-bucket replication pane appears.

            • To filter objects to replicate by object name prefix, enter a prefix that you want to include or exclude objects from, then click Add a prefix.
            • To set a storage class for the replicated objects, select a storage class from the Storage class menu. If you skip this step, the replicated objects will use the destination bucket's storage class by default.
            • Click Done.
      3. In the Choose how to store your data section, do the following:
        1. Select a default storage class for the bucket or Autoclass for automatic storage class management of your bucket's data.
        2. To enable hierarchical namespace, in the Optimize storage for data-intensive workloads section, select Enable hierarchical namespace on this bucket.
      4. In the Choose how to control access to objects section, select whether or not your bucket enforces public access prevention, and select an access control method for your bucket's objects.
      5. In the Choose how to protect object data section, do the following:
        • Select any of the options under Data protection that you want to set for your bucket.
          • To enable soft delete, click the Soft delete policy (For data recovery) checkbox, and specify the number of days you want to retain objects after deletion.
          • To set Object Versioning, click the Object versioning (For version control) checkbox, and specify the maximum number of versions per object and the number of days after which the noncurrent versions expire.
          • To enable the retention policy on objects and buckets, click the Retention (For compliance) checkbox, and then do the following:
            • To enable Object Retention Lock, click the Enable object retention checkbox.
            • To enable Bucket Lock, click the Set bucket retention policy checkbox, and choose a unit of time and a length of time for your retention period.
        • To choose how your object data will be encrypted, expand the Data encryption section (), and select a Data encryption method.
    4. Click Create.

    Crea un modello di flusso di lavoro

    Per creare e definire un modello di flusso di lavoro, copia ed esegui i seguenti comandi in una finestra del terminale locale o in Cloud Shell.

    1. Crea il modello di workflow.
        gcloud dataproc workflow-templates create wordcount-template \
            --region=us-central1
        
    2. Aggiungi il job di conteggio parole al modello di workflow.
      1. Specifica output-bucket-name prima di eseguire il comando (la funzione fornirà il bucket di input). Dopo aver inserito il nome del bucket di output, l'argomento del bucket di output dovrebbe essere il seguente: gs://your-output-bucket/wordcount-output".
      2. L'ID passaggio "count" è obbligatorio e identifica il job Hadoop aggiunto.
                  gcloud dataproc workflow-templates add-job hadoop \
                      --workflow-template=wordcount-template \
                      --step-id=count \
                      --jar=file:///usr/lib/hadoop-mapreduce/hadoop-mapreduce-examples.jar \
                      --region=us-central1 \
                      -- wordcount gs://input-bucket gs://output-bucket-name/wordcount-output
                
    3. Utilizza un cluster gestito, a un singolo nodo per eseguire il flusso di lavoro. Dataproc creerà il cluster, eseguirà il workflow e lo eliminerà al termine del workflow.
          gcloud dataproc workflow-templates set-managed-cluster wordcount-template \
              --cluster-name=wordcount \
              --single-node \
              --region=us-central1
          
    4. Fai clic sul nome di wordcount-template nella pagina Workflows di Dataproc nella console Google Cloud per aprire la pagina Dettagli modello di flusso di lavoro. Conferma gli attributi wordcount-template. Pagina dei dettagli del modello di workflow

    Parametrizzare il modello di workflow

    Parametrizza la variabile del bucket di input da passare al modello di workflow.

    1. Esporta il modello di workflow in un file di testo wordcount.yaml per la parametrizzazione.
      gcloud dataproc workflow-templates export wordcount-template \
          --destination=wordcount.yaml \
          --region=us-central1
      
    2. Utilizzando un editor di testo, apri wordcount.yaml, quindi aggiungi un blocco parameters alla fine del file YAML in modo che l'INPUT_BUCKET_URI di Cloud Storage possa essere trasmesso come args[1] al binario wordcount quando viene attivato il flusso di lavoro.

      Di seguito è riportato un file YAML esportato di esempio. Per aggiornare il modello, puoi adottare uno dei due approcci seguenti:

      1. Copia e incolla l'intero file per sostituire il file wordcount.yaml esportato dopo aver sostituito your-output_bucket con il nome del bucket di output OPPURE
      2. Copia e incolla solo la sezione parameters alla fine del file wordcount.yaml esportato.
      .
      jobs:
      - hadoopJob:
          args:
          - wordcount
          - gs://input-bucket
          - gs://your-output-bucket/wordcount-output
          mainJarFileUri: file:///usr/lib/hadoop-mapreduce/hadoop-mapreduce-examples.jar
        stepId: count
      placement:
        managedCluster:
          clusterName: wordcount
          config:
            softwareConfig:
              properties:
                dataproc:dataproc.allow.zero.workers: 'true'
      parameters:
      - name: INPUT_BUCKET_URI
        description: wordcount input bucket URI
        fields:
        - jobs['count'].hadoopJob.args[1]
      
    3. Importa il file di testo wordcount.yaml con parametri. Digita "Y" per sovrascrivere il modello.
      gcloud dataproc workflow-templates import  wordcount-template \
          --source=wordcount.yaml \
          --region=us-central1
      

    Crea una funzione Cloud

    1. Apri la pagina Cloud Run Functions nella consoleGoogle Cloud , poi fai clic su CREA FUNZIONE.

    2. Nella pagina Crea funzione, inserisci o seleziona le seguenti informazioni:

      1. Name: wordcount
      2. Memoria allocata:mantieni la selezione predefinita.
      3. Trigger:
        • Cloud Storage
        • Tipo di evento: Finalizzazione/creazione
        • Bucket: seleziona il bucket di input (vedi Creare un bucket Cloud Storage nel tuo progetto). Quando un file viene aggiunto a questo bucket, la funzione attiva il flusso di lavoro. Il flusso di lavoro eseguirà l'applicazione wordcount, che elaborerà tutti i file di testo nel bucket.
      4. Codice sorgente:

        • Editor in linea
        • Runtime: Node.js 8
        • scheda INDEX.JS: sostituisci lo snippet di codice predefinito con il seguente codice, poi modifica la riga const projectId per fornire -your-project-id- (senza "-" iniziale o finale).
        const dataproc = require('@google-cloud/dataproc').v1;
        
        exports.startWorkflow = (data) => {
         const projectId = '-your-project-id-'
         const region = 'us-central1'
         const workflowTemplate = 'wordcount-template'
        
        const client = new dataproc.WorkflowTemplateServiceClient({
           apiEndpoint: `${region}-dataproc.googleapis.com`,
        });
        
        const file = data;
        console.log("Event: ", file);
        
        const inputBucketUri = `gs://${file.bucket}/${file.name}`;
        
        const request = {
          name: client.projectRegionWorkflowTemplatePath(projectId, region, workflowTemplate),
          parameters: {"INPUT_BUCKET_URI": inputBucketUri}
        };
        
        client.instantiateWorkflowTemplate(request)
          .then(responses => {
            console.log("Launched Dataproc Workflow:", responses[1]);
          })
          .catch(err => {
            console.error(err);
          });
        };
        
        • Scheda PACKAGE.JSON: sostituisci lo snippet di codice predefinito con il seguente codice.
        {
          "name": "dataproc-workflow",
          "version": "1.0.0",
          "dependencies":{ "@google-cloud/dataproc": ">=1.0.0"}
        }
        
        • Funzione da eseguire: inserisci "startWorkflow".
      5. Fai clic su CREA.

    Testare la funzione

    1. Copia il file pubblico rose.txt nel tuo bucket per attivare la funzione. Inserisci your-input-bucket-name (il bucket utilizzato per attivare la funzione) nel comando.

      gcloud storage cp gs://pub/shakespeare/rose.txt gs://your-input-bucket-name
      

    2. Attendi 30 secondi, poi esegui questo comando per verificare che la funzione sia stata completata correttamente.

      gcloud functions logs read wordcount
      
      ...
      Function execution took 1348 ms, finished with status: 'ok'
      

    3. Per visualizzare i log della funzione dalla pagina di elenco Funzioni nella console Google Cloud , fai clic sul nome della funzione wordcount, quindi su VISUALIZZA LOG nella pagina Dettagli funzione.

    4. Puoi visualizzare la cartella wordcount-output nel bucket di output dalla pagina Browser di archiviazione nella consoleGoogle Cloud .

    5. Al termine del flusso di lavoro, i dettagli del job vengono conservati nella consoleGoogle Cloud . Fai clic sul job count... elencato nella pagina Job di Dataproc per visualizzare i dettagli del job del flusso di lavoro.

    Esegui la pulizia

    Il flusso di lavoro di questo tutorial elimina il cluster gestito al termine del flusso di lavoro. Per evitare costi ricorrenti, puoi eliminare altre risorse associate a questo tutorial.

    Eliminare un progetto

    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.

    Elimina bucket Cloud Storage

    1. In the Google Cloud console, go to the Cloud Storage Buckets page.

      Go to Buckets

    2. Click the checkbox for the bucket that you want to delete.
    3. To delete the bucket, click Delete, and then follow the instructions.

    Eliminare il modello di workflow

    gcloud dataproc workflow-templates delete wordcount-template \
        --region=us-central1
    

    Elimina la funzione Cloud

    Apri la pagina Cloud Run Functions nella console Google Cloud , seleziona la casella a sinistra della funzione wordcount, quindi fai clic su Elimina.

    Passaggi successivi