Workflow mit Cloud Run-Funktionen

Hinweise

Richten Sie ein Google Cloud Projekt und zwei (2) Cloud Storage-Buckets ein, falls Sie dies noch nicht getan haben.

Projekt einrichten

  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. Zwei (2) Cloud Storage-Buckets in Ihrem Projekt erstellen oder verwenden

    Sie benötigen zwei Cloud Storage-Buckets in Ihrem Projekt: einen für Eingabedateien und einen für die Ausgabe.

    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.

    Workflow-Vorlage erstellen

    Kopieren Sie die unten aufgeführten Befehle und führen Sie sie in einem lokalen Terminalfenster oder in Cloud Shell aus, um eine Workflow-Vorlage zu erstellen und zu definieren.

    Hinweise:

    • Die Befehle geben die Region "us-central1" an. Sie können eine andere Region angeben oder das Flag --region löschen, wenn Sie zuvor gcloud config set compute/region ausgeführt haben, um das Regionsattribut festzulegen.
    • Die Sequenz "-- " (Bindestrich-Bindestrich-Leerzeichen) übergibt Argumente an die JAR-Datei. Mit dem Befehl wordcount input_bucket output_dir wird die Wordcount-Anwendung der JAR-Datei von Textdateien ausgeführt, die im Cloud Storage-input_bucket enthalten sind, und gibt dann Wordcount-Dateien an eine output_bucket aus. Sie parametrisieren das Argument für den Wordcount-Eingabe-Bucket, damit die Funktion dieses Argument bereitstellen kann.

    1. Erstellen Sie die Workflow-Vorlage.

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

    2. Fügen Sie der Workflow-Vorlage den Wordcount-Job hinzu.
      1. Geben Sie output-bucket-name an, bevor Sie den Befehl ausführen. Die Funktion stellt den Eingabe-Bucket bereit. Nachdem Sie den Namen des Ausgabe-Buckets eingegeben haben, sollte das Argument des Ausgabe-Buckets so lauten: gs://your-output-bucket/wordcount-output".
      2. Die Schrittzahl "count" ist erforderlich und identifiziert den hinzugefügten Hadoop-Job.

      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. Führen Sie den Workflow mit einem verwalteten Einzelknoten aus. Dataproc erstellt den Cluster, führt den Workflow aus und löscht den Cluster, wenn der Workflow abgeschlossen ist.

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

    4. Klicken Sie in der Google Cloud Console auf der Dataproc-Seite Workflows auf den Namen wordcount-template, um die Seite Workflow-Vorlagendetails zu öffnen. Bestätigen Sie die Wordcount-template-Attribute.

    Workflow-Vorlage parametrisieren

    Parametrisieren Sie die Eingabe-Bucket-Variable, die an die Workflow-Vorlage übergeben werden soll.

    1. Exportieren Sie die Workflow-Vorlage zur Parametrisierung in eine wordcount.yaml-Textdatei.
      gcloud dataproc workflow-templates export wordcount-template \
          --destination=wordcount.yaml \
          --region=us-central1
      
    2. Öffnen Sie in einem Texteditor wordcount.yaml und fügen Sie am Ende der YAML-Datei einen parameters-Block hinzu, damit der Cloud Storage-INPUT_BUCKET_URI als args[1] an die Wordcount-Binärdatei übergeben werden kann, wenn der Workflow ausgelöst wird.

      Unten sehen Sie ein Beispiel für eine exportierte YAML-Datei. Sie haben zwei Möglichkeiten, Ihre Vorlage zu aktualisieren:

      1. Kopieren Sie dann die gesamte Datei und fügen Sie sie ein, um die exportierte Datei wordcount.yaml zu ersetzen, nachdem Sie your-output_bucket durch den Namen des Ausgabe-Buckets ersetzt haben, ODER
      2. Kopieren Sie den Abschnitt parameters und fügen Sie ihn an das Ende der exportierten wordcount.yaml-Datei ein.
      .
      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. Importieren Sie die parametrisierte wordcount.yaml-Textdatei. Geben Sie "Y" ein, wenn Sie aufgefordert werden, die Vorlage zu überschreiben.
      gcloud dataproc workflow-templates import  wordcount-template \
          --source=wordcount.yaml \
          --region=us-central1
      

    Cloud Functions-Funktion erstellen

    1. Öffnen Sie in derGoogle Cloud Console die Seite Cloud Run-Funktionen und klicken Sie auf „FUNKTION ERSTELLEN“.

    2. Geben Sie auf der Seite Funktion erstellen die folgenden Informationen ein oder wählen Sie sie aus:

      1. Name: Wortzahl
      2. Zugewiesener Speicher:Behalten Sie die Standardauswahl bei.
      3. Trigger:
        • cl
        • Ereignistyp: Abschluss/Erstellen
        • Bucket: Wählen Sie Ihren Eingabe-Bucket aus (siehe Cloud Storage-Bucket im Projekt erstellen). Wenn Sie diesem Bucket eine Datei hinzufügen, löst die Funktion den Workflow aus. Der Workflow führt die Wordcount-Anwendung aus, mit der alle Textdateien im Bucket verarbeitet werden.
      4. Quellcode:

        • Inline-Editor
        • Laufzeit: Node.js 8
        • Tab INDEX.JS: Ersetzen Sie das Standard-Code-Snippet durch den folgenden Code und bearbeiten Sie die Zeile const projectId, um Ihre -your-project-id- (ohne einen voran- oder nachgestellten "-") anzugeben.
        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);
          });
        };
        
        • Tab PACKAGE.JSON: Ersetzen Sie das Standard-Code-Snippet durch den folgenden Code.
        {
          "name": "dataproc-workflow",
          "version": "1.0.0",
          "dependencies":{ "@google-cloud/dataproc": ">=1.0.0"}
        }
        
        • Auszuführende Funktion: Eingabe: "startWorkflow".
      5. Klicken Sie auf ERSTELLEN.

    Funktion testen

    1. Kopieren Sie die öffentliche Datei rose.txt in Ihren Bucket, um die Funktion auszulösen. Fügen Sie in den Befehl your-input-bucket-name (den Bucket, der zum Auslösen der Funktion verwendet wird) ein.

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

    2. Warten Sie 30 Sekunden und führen Sie dann den folgenden Befehl aus, um zu prüfen, ob die Funktion erfolgreich ausgeführt wurde.

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

    3. Wenn Sie die Funktionslogs von der Listenseite Funktionen in der Google Cloud Console aus aufrufen möchten, klicken Sie auf den Funktionsnamen wordcount und dann auf der Seite Funktionsdetails auf „LOGS ANZEIGEN“.

    4. Sie können den Ordner wordcount-output in Ihrem Ausgabe-Bucket auf der Seite Storage-Browser in derGoogle Cloud Console ansehen.

    5. Nach Abschluss des Workflows bleiben die Jobdetails in derGoogle Cloud Console erhalten. Klicken Sie auf den count...-Job, der auf der Dataproc-Seite Jobs aufgeführt ist, um Details zum Workflow-Job anzuzeigen.

    Bereinigen

    Der Workflow in dieser Anleitung löscht den verwalteten Cluster, wenn der Workflow abgeschlossen ist. Sie können andere Ressourcen aus dieser Anleitung löschen, um wiederkehrende Kosten zu vermeiden.

    Ein Projekt löschen

    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.

    Cloud Storage-Buckets löschen

    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.

    Workflow-Vorlage löschen

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

    Ihre Cloud Functions-Funktion löschen

    Öffnen Sie in der Google Cloud Console die Seite Cloud Run-Funktionen, klicken Sie auf das Kästchen links neben der Funktion wordcount und klicken Sie dann auf LÖSCHEN.

    Nächste Schritte