Flusso di lavoro con le funzioni Cloud Run

Prima di iniziare

Se non l'hai già fatto, configura un Google Cloud progetto 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 (2) bucket Cloud Storage nel tuo progetto

    Nel tuo progetto avrai bisogno di due bucket Cloud Storage: uno per i file di input e uno 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 workflow.

    Copia ed esegui i comandi elencati di seguito in una finestra del terminale locale o in Cloud Shell per creare e definire un modello di flusso di lavoro.

    Note:

    • I comandi specificano la regione "us-central1". Puoi specificare una regione diversa o eliminare il flag --region se in precedenza hai eseguito gcloud config set compute/region per impostare la proprietà regione.
    • La sequenza "-- " (barra spaziatrice) passa gli argomenti al file jar. Il comando wordcount input_bucket output_dir eseguirà l'applicazione di conteggio delle parole del file JAR sui file di testo contenuti nel input_bucket di Cloud Storage, quindi genererà file di conteggio delle parole in un output_bucket. Parametrizzerai l'argomento del bucket di input di conteggio parole per consentire alla funzione di fornirlo.

    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 visualizzato come segue: gs://your-output-bucket/wordcount-output".
      2. L'ID del 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 a nodo singolo gestito per eseguire il flusso di lavoro. Dataproc creerà il cluster, eseguirà il flusso di lavoro al suo interno, quindi lo eliminerà al termine del flusso di lavoro.

      gcloud dataproc workflow-templates set-managed-cluster wordcount-template \
          --cluster-name=wordcount \
          --single-node \
          --region=us-central1
      

    4. Fai clic sul nome wordcount-template nella pagina Dataproc Workflows nella console Google Cloud per aprire la pagina Dettagli del modello di flusso di lavoro. Conferma gli attributi wordcount-template.

    Parametrizza il modello di workflow.

    Parameterize la variabile del bucket di input da passare al modello di flusso di lavoro.

    1. Esporta il modello di flusso di lavoro 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 il valore INPUT_BUCKET_URI di Cloud Storage possa essere passato come args[1] al file binario di conteggio delle parole quando viene attivato il flusso di lavoro.

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

      1. Copia e incolla l'intero file per sostituire il file esportato wordcount.yaml 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 parametrizzato. Digita "Sì" quando ti viene chiesto di sovrascrivere il modello.
      gcloud dataproc workflow-templates import  wordcount-template \
          --source=wordcount.yaml \
          --region=us-central1
      

    Creare una funzione Cloud

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

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

      1. Nome: conteggioparole
      2. Memoria allocata:mantieni la selezione predefinita.
      3. Trigger:
        • Cloud Storage
        • Tipo di evento: Finalizza/crea
        • 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 attiverà il flusso di lavoro. Il flusso di lavoro eseguirà l'applicazione di conteggio delle parole, 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 codice riportato di seguito, quindi modifica la riga const projectId in modo da 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.

    Testa la funzione

    1. Copia il file pubblico rose.txt nel tuo bucket per attivare la funzione. Inserisciyour-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, quindi esegui il comando seguente 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 dell'elenco Funzioni nella Google Cloud console, fai clic sul nome della funzione wordcount e poi 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 rimangono nella console.Google Cloud Fai clic sul job count... elencato nella pagina Job di Dataproc per visualizzare i dettagli del job del flusso di lavoro.

    Pulizia

    Il flusso di lavoro in questo tutorial elimina il cluster gestito quando viene completato. Per evitare costi ricorrenti, puoi eliminare altre risorse associate a questo tutorial.

    Eliminazione di 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.

    Eliminazione dei 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.

    Eliminazione del modello di flusso di lavoro

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

    Eliminazione della funzione Cloud

    Apri la pagina Funzioni Cloud Run nella console Google Cloud , seleziona la casella a sinistra della funzione wordcount e poi fai clic su ELIMINA.

    Passaggi successivi