Job erstellen und ausführen, der Speichervolumes verwendet

In diesem Dokument wird beschrieben, wie Sie einen Batchjob erstellen und ausführen, der ein oder mehrere externe Speichervolumes verwendet. Zu den externen Speicheroptionen gehören neue oder vorhandene Persistent Disks, neue lokale SSDs, vorhandene Cloud Storage-Buckets und ein vorhandenes Netzwerkdateisystem (NFS) wie eine Filestore-Dateifreigabe.

Unabhängig davon, ob Sie externe Speichervolumes hinzufügen, hat jede Compute Engine-VM für einen Job ein Bootlaufwerk, das Speicher für das Betriebssystem-Image und die Anweisungen des Jobs bietet. Informationen zum Konfigurieren des Bootlaufwerks für einen Job finden Sie stattdessen unter VM-Betriebssystemumgebung – Übersicht.

Hinweise

  1. Wenn Sie Batch noch nicht verwendet haben, lesen Sie den Abschnitt Erste Schritte mit Batch und aktivieren Sie Batch, indem Sie die Voraussetzungen für Projekte und Nutzer erfüllen.
  2. Bitten Sie Ihren Administrator, Ihnen die folgenden IAM-Rollen zuzuweisen, um die Berechtigungen zu erhalten, die Sie zum Erstellen eines Jobs benötigen:

    Weitere Informationen zum Zuweisen von Rollen finden Sie unter Zugriff auf Projekte, Ordner und Organisationen verwalten.

    Sie können die erforderlichen Berechtigungen auch über benutzerdefinierte Rollen oder andere vordefinierte Rollen erhalten.

Job erstellen, der Speichervolumes verwendet

Optional kann ein Job einen oder mehrere der folgenden Typen von externen Speicher-Volumes verwenden. Weitere Informationen zu allen Arten von Speichervolumes sowie zu den Unterschieden und Einschränkungen für die einzelnen Typen finden Sie in der Dokumentation zu Speicheroptionen für Compute Engine-VMs.

Sie können einem Job die Verwendung jedes Speichervolumes erlauben, indem Sie es in die Definition des Jobs aufnehmen und seinen Bereitstellungspfad (mountPath) in den Runnables angeben. Informationen zum Erstellen eines Jobs, der Speichervolumes verwendet, finden Sie in einem oder mehreren der folgenden Abschnitte:

Nichtflüchtigen Speicher verwenden

Für einen Job, der nichtflüchtige Speicher verwendet, gelten die folgenden Einschränkungen:

  • Alle nichtflüchtigen Speicher: Einschränkungen für alle nichtflüchtigen Speicher

  • Neue und vorhandene nichtflüchtige Speicher: Jeder nichtflüchtige Speicher in einem Job kann entweder neu sein (im Job definiert und mit dem Job erstellt) oder bereits in Ihrem Projekt vorhanden und im Job angegeben sein. Damit ein nichtflüchtiger Speicher verwendet werden kann, muss er formatiert und auf den VMs des Jobs bereitgestellt werden. Die VMs müssen sich am selben Speicherort wie der nichtflüchtige Speicher befinden. Batch hängt alle nichtflüchtigen Speicher ein, die Sie in einen Job aufnehmen, und formatiert alle neuen nichtflüchtigen Speicher. Sie müssen jedoch alle vorhandenen nichtflüchtigen Speicher, die von einem Job verwendet werden sollen, formatieren und aushängen.

    Die unterstützten Standortoptionen, Formatierungsoptionen und Einbindungsoptionen variieren zwischen neuen und vorhandenen nichtflüchtigen Speichern, wie in der folgenden Tabelle beschrieben:

    Neue nichtflüchtige Speicher Vorhandene nichtflüchtige Speicher
    Formatoptionen

    Der nichtflüchtige Speicher wird automatisch mit einem ext4-Dateisystem formatiert.

    Sie müssen den nichtflüchtigen Speicher formatieren, um ein ext4-Dateisystem zu verwenden, bevor Sie ihn für einen Job verwenden.

    Bereitstellungsoptionen

    Alle Optionen werden unterstützt.

    Alle Optionen außer „Schreiben“ werden unterstützt. Dies liegt an den Einschränkungen des Modus für mehrere Autoren.

    Sie müssen den nichtflüchtigen Speicher von allen VMs trennen, an die er angehängt ist, bevor Sie ihn für einen Job verwenden.

    Speicherortoptionen

    Sie können nur zonale nichtflüchtige Speicher erstellen.

    Sie können jeden beliebigen Ort für Ihren Job auswählen. Die nichtflüchtigen Speicher werden in der Zone erstellt, in der Ihr Projekt ausgeführt wird.

    Sie können zonale und regionale nichtflüchtige Speicher auswählen.


    Sie müssen den Standort des Jobs (oder, falls angegeben, nur die zulässigen Standorte des Jobs) auf nur Standorte festlegen, die alle persistenten Datenträger des Jobs enthalten. Bei einem zonalen nichtflüchtigen Speicher muss sich der Job beispielsweise in der Zone des Laufwerks befinden. Bei einem regionalen nichtflüchtigen Speicher muss sich der Job entweder in der Region des Laufwerks oder, wenn Zonen angegeben werden, in einer oder beiden der spezifischen Zonen befinden, in denen sich der regionale nichtflüchtige Speicher befindet.

  • Instanzvorlagen: Wenn Sie beim Erstellen dieses Jobs eine VM-Instanzvorlage verwenden, müssen Sie alle nichtflüchtigen Speicher für diesen Job in der Instanzvorlage anhängen. Wenn Sie keine Instanzvorlage verwenden möchten, müssen Sie alle nichtflüchtigen Speicher direkt in der Jobdefinition anhängen.

Sie können einen Job erstellen, der eine persistente Festplatte verwendet, indem Sie dieGoogle Cloud Console, die gcloud CLI, die Batch API, C++, Go, Java, Node.js oder Python verwenden.

Console

Im folgenden Beispiel wird über die Google Cloud -Konsole ein Job erstellt, der ein Skript ausführt, um eine Datei von einem vorhandenen zonalen nichtflüchtigen Speicher zu lesen, der sich in der Zone us-central1-a befindet. Im Beispielskript wird davon ausgegangen, dass für den Job ein vorhandener zonaler nichtflüchtiger Speicher vorhanden ist, der im Stammverzeichnis eine Textdatei namens example.txt enthält.

Optional: Beispiel für einen zonalen nichtflüchtigen Speicher erstellen

Wenn Sie einen zonalen nichtflüchtigen Speicher erstellen möchten, den Sie zum Ausführen des Beispielskripts verwenden können, gehen Sie vor dem Erstellen des Jobs so vor:

  1. Hängen Sie einen neuen, leeren nichtflüchtigen Speicher mit dem Namen example-disk an eine Linux-VM in der Zone us-central1-a an und führen Sie dann Befehle auf der VM aus, um das Laufwerk zu formatieren und bereitzustellen. Eine Anleitung finden Sie unter Nichtflüchtigen Speicher zu Instanz hinzufügen.

    Trennen Sie die Verbindung zur VM noch nicht.

  2. Führen Sie die folgenden Befehle auf der VM aus, um example.txt auf dem nichtflüchtigen Speicher zu erstellen:

    1. Geben Sie den folgenden Befehl ein, um das aktuelle Arbeitsverzeichnis in das Stammverzeichnis des nichtflüchtigen Speichers zu ändern:

      cd VM_MOUNT_PATH
      

      Ersetzen Sie VM_MOUNT_PATH durch den Pfad zum Verzeichnis, in dem der nichtflüchtige Speicher im vorherigen Schritt auf dieser VM bereitgestellt wurde, z. B. /mnt/disks/example-disk.

    2. Drücken Sie Enter.

    3. Geben Sie den folgenden Befehl ein, um eine Datei mit dem Namen example.txt zu erstellen und zu definieren:

      cat > example.txt
      
    4. Drücken Sie Enter.

    5. Geben Sie den Inhalt der Datei ein. Geben Sie beispielsweise Hello world! ein.

    6. Drücken Sie zum Speichern der Datei Ctrl+D (oder Command+D unter macOS).

    Wenn Sie fertig sind, können Sie die Verbindung zur VM trennen.

  3. Trennen Sie den nichtflüchtigen Speicher von der VM.

    • Wenn Sie die VM nicht mehr benötigen, können Sie sie löschen. Dadurch wird die Verbindung zum nichtflüchtigen Speicher automatisch getrennt.

    • Trennen Sie andernfalls den nichtflüchtigen Speicher. Eine Anleitung finden Sie unter Bootlaufwerke trennen und wieder anhängen. Trennen Sie den nichtflüchtigen Speicher example-disk anstelle des Bootlaufwerks der VM.

Job erstellen, der den vorhandenen zonalen nichtflüchtigen Speicher verwendet

So erstellen Sie einen Job, der vorhandene zonale nichtflüchtige Speicher verwendet, mit derGoogle Cloud -Konsole:

  1. Rufen Sie in der Google Cloud Console die Seite Jobliste auf.

    Zur Jobliste

  2. Klicken Sie auf Erstellen. Die Seite Batchjob erstellen wird geöffnet. Im linken Bereich ist die Seite Jobdetails ausgewählt.

  3. Konfigurieren Sie die Seite Jobdetails:

    1. Optional: Passen Sie im Feld Jobname den Jobnamen an.

      Geben Sie beispielsweise example-disk-job ein.

    2. Konfigurieren Sie den Abschnitt Aufgabendetails:

      1. Fügen Sie im Fenster Neues Runnable mindestens ein Script oder einen Container hinzu, damit dieser Job ausgeführt werden kann.

        Wenn Sie beispielsweise ein Skript ausführen möchten, das den Inhalt einer Datei mit dem Namen example.txt ausgibt, die sich im Stammverzeichnis des nichtflüchtigen Speichers befindet, der von diesem Job verwendet wird, gehen Sie so vor:

        1. Klicken Sie das Kästchen Script an. Ein Textfeld wird angezeigt.

        2. Geben Sie das folgende Skript in das Textfeld ein:

          echo "Here is the content of the example.txt file in the persistent disk."
          cat MOUNT_PATH/example.txt
          

          Ersetzen Sie MOUNT_PATH durch den Pfad, unter dem Sie den nichtflüchtigen Speicher für diesen Job in den VMs einhängen möchten, z. B. /mnt/disks/example-disk.

        3. Klicken Sie auf Fertig.

      2. Geben Sie im Feld Anzahl der Aufgaben die Anzahl der Aufgaben für diesen Job ein.

        Geben Sie beispielsweise 1 (Standardeinstellung) ein.

      3. Geben Sie im Feld Parallelität die Anzahl der Aufgaben ein, die gleichzeitig ausgeführt werden sollen.

        Geben Sie beispielsweise 1 (Standardeinstellung) ein.

  4. Konfigurieren Sie die Seite Ressourcenspezifikationen:

    1. Klicken Sie im linken Bereich auf Ressourcenspezifikationen. Die Seite Ressourcenspezifikationen wird geöffnet.

    2. Wählen Sie den Standort für diesen Job aus. Wenn Sie einen vorhandenen zonalen nichtflüchtigen Speicher verwenden möchten, müssen sich die VMs eines Jobs in derselben Zone befinden.

      1. Wählen Sie im Feld Region eine Region aus.

        Wenn Sie beispielsweise den zonalen nichtflüchtigen Speicher aus dem Beispiel verwenden möchten, wählen Sie us-central1 (Iowa) (Standardeinstellung) aus.

      2. Wählen Sie im Feld Zone eine Zone aus.

        Wählen Sie beispielsweise us-central1-a (Iowa) aus.

  5. Konfigurieren Sie die Seite Zusätzliche Konfigurationen:

    1. Klicken Sie im linken Bereich auf Zusätzliche Konfigurationen. Die Seite Zusätzliche Konfigurationen wird geöffnet.

    2. Führen Sie für jeden vorhandenen zonalen nichtflüchtigen Speicher, den Sie in diesem Job bereitstellen möchten, die folgenden Schritte aus:

      1. Klicken Sie im Bereich Speichervolume auf Neues Volume hinzufügen. Das Fenster Neues Volume wird angezeigt.

      2. Führen Sie im Fenster Neues Volume die folgenden Schritte aus:

        1. Wählen Sie im Abschnitt Volume-Typ die Option Nichtflüchtiger Speicher (Standardeinstellung) aus.

        2. Wählen Sie in der Liste Laufwerk ein vorhandenes zonales nichtflüchtiges Laufwerk aus, das Sie in diesem Job einbinden möchten. Das Laufwerk muss sich in derselben Zone wie dieser Job befinden.

          Wählen Sie beispielsweise den vorhandenen zonalen nichtflüchtigen Speicher aus, den Sie vorbereitet haben. Er befindet sich in der Zone us-central1-a und enthält die Datei example.txt.

        3. Optional: So benennen Sie diesen zonalen nichtflüchtigen Speicher um:

          1. Wählen Sie Gerätenamen anpassen aus.

          2. Geben Sie im Feld Gerätename den neuen Namen für Ihr Laufwerk ein.

        4. Geben Sie im Feld Bereitstellungspfad den Bereitstellungspfad (MOUNT_PATH) für diesen nichtflüchtigen Speicher ein:

          Geben Sie beispielsweise Folgendes ein:

          /mnt/disks/EXISTING_PERSISTENT_DISK_NAME
          

          Ersetzen Sie EXISTING_PERSISTENT_DISK_NAME durch den Namen des Laufwerks. Wenn Sie den zonalen nichtflüchtigen Speicher umbenannt haben, verwenden Sie den neuen Namen.

          Ersetzen Sie beispielsweise EXISTING_PERSISTENT_DISK_NAME durch example-disk.

        5. Klicken Sie auf Fertig.

  6. Optional: Konfigurieren Sie die anderen Felder für diesen Job.

  7. Optional: Wenn Sie die Jobkonfiguration überprüfen möchten, klicken Sie im linken Bereich auf Vorschau.

  8. Klicken Sie auf Erstellen.

Auf der Seite Jobdetails wird der von Ihnen erstellte Job angezeigt.

gcloud

Im folgenden Beispiel wird mit der gcloud CLI ein Job erstellt, in dem ein vorhandener und ein neuer nichtflüchtiger Speicher angehängt und bereitgestellt werden. Der Job hat drei Aufgaben, die jeweils ein Skript ausführen, um eine Datei auf der neuen nichtflüchtigen Festplatte mit dem Namen output_task_TASK_INDEX.txt zu erstellen, wobei TASK_INDEX der Index der einzelnen Aufgaben ist: 0, 1 und 2.

Verwenden Sie den Befehl gcloud batch jobs submit, um einen Job zu erstellen, der nichtflüchtige Speicher verwendet. Geben Sie in der JSON-Konfigurationsdatei des Jobs die nichtflüchtigen Speicher im Feld instances an und stellen Sie den nichtflüchtigen Speicher im Feld volumes bereit.

  1. Erstellen Sie eine JSON-Datei.

    • Wenn Sie für diesen Job keine Instanzvorlage verwenden, erstellen Sie eine JSON-Datei mit folgendem Inhalt:

      {
          "allocationPolicy": {
              "instances": [
                  {
                      "policy": {
                          "disks": [
                              {
                                  "deviceName": "EXISTING_PERSISTENT_DISK_NAME",
                                  "existingDisk": "projects/PROJECT_ID/EXISTING_PERSISTENT_DISK_LOCATION/disks/EXISTING_PERSISTENT_DISK_NAME"
                              },
                              {
                                  "newDisk": {
                                      "sizeGb": NEW_PERSISTENT_DISK_SIZE,
                                      "type": "NEW_PERSISTENT_DISK_TYPE"
                                  },
                                  "deviceName": "NEW_PERSISTENT_DISK_NAME"
                              }
                          ]
                      }
                  }
              ],
              "location": {
                  "allowedLocations": [
                      "EXISTING_PERSISTENT_DISK_LOCATION"
                  ]
              }
          },
          "taskGroups": [
              {
                  "taskSpec": {
                      "runnables": [
                          {
                              "script": {
                                  "text": "echo Hello world from task ${BATCH_TASK_INDEX}. >> /mnt/disks/NEW_PERSISTENT_DISK_NAME/output_task_${BATCH_TASK_INDEX}.txt"
                              }
                          }
                      ],
                      "volumes": [
                          {
                              "deviceName": "NEW_PERSISTENT_DISK_NAME",
                              "mountPath": "/mnt/disks/NEW_PERSISTENT_DISK_NAME",
                              "mountOptions": "rw,async"
                          },
                          {
      
                              "deviceName": "EXISTING_PERSISTENT_DISK_NAME",
                              "mountPath": "/mnt/disks/EXISTING_PERSISTENT_DISK_NAME"
                          }
                      ]
                  },
                  "taskCount":3
              }
          ],
          "logsPolicy": {
              "destination": "CLOUD_LOGGING"
          }
      }
      

      Ersetzen Sie Folgendes:

      • PROJECT_ID: die Projekt-ID Ihres Projekts.
      • EXISTING_PERSISTENT_DISK_NAME: der Name eines vorhandenen nichtflüchtigen Speichers.
      • EXISTING_PERSISTENT_DISK_LOCATION: der Speicherort eines vorhandenen nichtflüchtigen Speichers. Für jeden vorhandenen zonalen nichtflüchtigen Speicher muss der Standort des Jobs die Zone des Laufwerks sein. Für jeden vorhandenen regionalen nichtflüchtigen Speicher muss der Standort des Jobs entweder die Region des Laufwerks oder, wenn Zonen angegeben werden, eine oder beide der spezifischen Zonen sein, in denen sich der regionale nichtflüchtige Speicher befindet. Wenn Sie keine vorhandenen persistenten Datenträger angeben, können Sie einen beliebigen Standort auswählen. Weitere Informationen zum Feld allowedLocations
      • NEW_PERSISTENT_DISK_SIZE: die Größe des neuen nichtflüchtigen Speichers in GB. Die zulässigen Größen hängen vom Typ des nichtflüchtigen Speichers ab. Das Minimum beträgt jedoch oft 10 GB (10) und das Maximum oft 64 TB (64000).
      • NEW_PERSISTENT_DISK_TYPE: der Laufwerkstyp des neuen nichtflüchtigen Speichers, entweder pd-standard, pd-balanced, pd-ssd oder pd-extreme. Der Standardlaufwerkstyp für nichtflüchtige Speicher, die nicht als Bootlaufwerk verwendet werden, ist pd-standard.
      • NEW_PERSISTENT_DISK_NAME: Name des neuen nichtflüchtigen Speichers.
    • Wenn Sie eine VM-Instanzvorlage für diesen Job verwenden, erstellen Sie eine JSON-Datei wie zuvor, ersetzen Sie jedoch das instances-Feld durch Folgendes:

      "instances": [
          {
              "instanceTemplate": "INSTANCE_TEMPLATE_NAME"
          }
      ],
      

      Dabei ist INSTANCE_TEMPLATE_NAME der Name der Instanzvorlage für diesen Job. Für einen Job, der nichtflüchtige Speicher verwendet, müssen in dieser Instanzvorlage die nichtflüchtigen Speicher definiert und angehängt werden, die der Job verwenden soll. In diesem Beispiel muss in der Vorlage ein neuer nichtflüchtiger Speicher mit dem Namen NEW_PERSISTENT_DISK_NAME definiert und angehängt werden. Außerdem muss ein vorhandener nichtflüchtiger Speicher mit dem Namen EXISTING_PERSISTENT_DISK_NAME angehängt werden.

  2. Führen Sie dazu diesen Befehl aus:

    gcloud batch jobs submit JOB_NAME \
      --location LOCATION \
      --config JSON_CONFIGURATION_FILE
    

    Ersetzen Sie Folgendes:

    • JOB_NAME: Der Name des Jobs.

    • LOCATION: Der Standort des Jobs.

    • JSON_CONFIGURATION_FILE: der Pfad zu einer JSON-Datei mit den Konfigurationsdetails des Jobs.

API

Im folgenden Beispiel wird mit der Batch API ein Job erstellt, mit dem ein vorhandener nichtflüchtiger Speicher und ein neuer nichtflüchtiger Speicher angehängt und bereitgestellt werden. Der Job hat drei Aufgaben, die jeweils ein Skript ausführen, um eine Datei auf der neuen nichtflüchtigen Festplatte mit dem Namen output_task_TASK_INDEX.txt zu erstellen, wobei TASK_INDEX der Index der einzelnen Aufgaben ist: 0, 1 und 2.

Wenn Sie mit der Batch API einen Job erstellen möchten, der nichtflüchtige Speicher verwendet, verwenden Sie die jobs.create-Methode. Geben Sie in der Anfrage die nichtflüchtigen Speicher im Feld instances an und stellen Sie den nichtflüchtigen Speicher im Feld volumes bereit.

  • Wenn Sie für diesen Job keine Instanzvorlage verwenden, stellen Sie die folgende Anfrage:

    POST https://batch.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/jobs?job_id=JOB_NAME
    
    {
        "allocationPolicy": {
            "instances": [
                {
                    "policy": {
                        "disks": [
                            {
                                "deviceName": "EXISTING_PERSISTENT_DISK_NAME",
                                "existingDisk": "projects/PROJECT_ID/EXISTING_PERSISTENT_DISK_LOCATION/disks/EXISTING_PERSISTENT_DISK_NAME"
                            },
                            {
                                "newDisk": {
                                    "sizeGb": NEW_PERSISTENT_DISK_SIZE,
                                    "type": "NEW_PERSISTENT_DISK_TYPE"
                                },
                                "deviceName": "NEW_PERSISTENT_DISK_NAME"
                            }
                        ]
                    }
                }
            ],
            "location": {
                "allowedLocations": [
                    "EXISTING_PERSISTENT_DISK_LOCATION"
                ]
            }
        },
        "taskGroups": [
            {
                "taskSpec": {
                    "runnables": [
                        {
                            "script": {
                                "text": "echo Hello world from task ${BATCH_TASK_INDEX}. >> /mnt/disks/NEW_PERSISTENT_DISK_NAME/output_task_${BATCH_TASK_INDEX}.txt"
                            }
                        }
                    ],
                    "volumes": [
                        {
                            "deviceName": "NEW_PERSISTENT_DISK_NAME",
                            "mountPath": "/mnt/disks/NEW_PERSISTENT_DISK_NAME",
                            "mountOptions": "rw,async"
                        },
                        {
    
                            "deviceName": "EXISTING_PERSISTENT_DISK_NAME",
                            "mountPath": "/mnt/disks/EXISTING_PERSISTENT_DISK_NAME"
                        }
                    ]
                },
                "taskCount":3
            }
        ],
        "logsPolicy": {
            "destination": "CLOUD_LOGGING"
        }
    }
    

    Ersetzen Sie Folgendes:

    • PROJECT_ID: die Projekt-ID Ihres Projekts.
    • LOCATION: Der Standort des Jobs.
    • JOB_NAME: Der Name des Jobs.
    • EXISTING_PERSISTENT_DISK_NAME: der Name eines vorhandenen nichtflüchtigen Speichers.
    • EXISTING_PERSISTENT_DISK_LOCATION: der Speicherort eines vorhandenen nichtflüchtigen Speichers. Für jeden vorhandenen zonalen nichtflüchtigen Speicher muss der Standort des Jobs die Zone des Laufwerks sein. Für jeden vorhandenen regionalen nichtflüchtigen Speicher muss der Standort des Jobs entweder die Region des Laufwerks oder, wenn Zonen angegeben werden, eine oder beide der spezifischen Zonen sein, in denen sich der regionale nichtflüchtige Speicher befindet. Wenn Sie keine vorhandenen nichtflüchtigen Speicher angeben, können Sie einen beliebigen Speicherort auswählen. Weitere Informationen zum Feld allowedLocations
    • NEW_PERSISTENT_DISK_SIZE: die Größe des neuen nichtflüchtigen Speichers in GB. Die zulässigen Größen hängen vom Typ des nichtflüchtigen Speichers ab. Das Minimum beträgt jedoch oft 10 GB (10) und das Maximum oft 64 TB (64000).
    • NEW_PERSISTENT_DISK_TYPE: der Laufwerkstyp des neuen nichtflüchtigen Speichers, entweder pd-standard, pd-balanced, pd-ssd oder pd-extreme. Der Standardlaufwerkstyp für nichtflüchtige Speicher, die nicht als Bootlaufwerk verwendet werden, ist pd-standard.
    • NEW_PERSISTENT_DISK_NAME: Name des neuen nichtflüchtigen Speichers.
  • Wenn Sie eine VM-Instanzvorlage für diesen Job verwenden, erstellen Sie eine JSON-Datei wie zuvor, ersetzen Sie jedoch das instances-Feld durch Folgendes:

    "instances": [
        {
            "instanceTemplate": "INSTANCE_TEMPLATE_NAME"
        }
    ],
    ...
    

    Dabei ist INSTANCE_TEMPLATE_NAME der Name der Instanzvorlage für diesen Job. Für einen Job, der nichtflüchtige Speicher verwendet, müssen in dieser Instanzvorlage die nichtflüchtigen Speicher definiert und angehängt werden, die der Job verwenden soll. In diesem Beispiel muss in der Vorlage ein neuer nichtflüchtiger Speicher mit dem Namen NEW_PERSISTENT_DISK_NAME definiert und angehängt werden. Außerdem muss ein vorhandener nichtflüchtiger Speicher mit dem Namen EXISTING_PERSISTENT_DISK_NAME angehängt werden.

C++

Wenn Sie einen Batch-Job erstellen möchten, der neue oder vorhandene persistenten Datenträger mit den Cloud-Clientbibliotheken für C++ verwendet, verwenden Sie die CreateJob-Funktion und fügen Sie Folgendes ein:

  • Wenn Sie nichtflüchtige Speicher an die VMs für einen Job anhängen möchten, fügen Sie eines der folgenden Elemente ein:
    • Wenn Sie für diesen Job keine VM-Instanzvorlage verwenden, verwenden Sie die Methode set_remote_path.
    • Wenn Sie für diesen Job eine VM-Instanzvorlage verwenden, verwenden Sie die Methode set_instance_template.
  • Wenn Sie die nichtflüchtigen Speicher für den Job einbinden möchten, verwenden Sie das Feld volumes mit den Feldern deviceName und mountPath. Verwenden Sie für neue nichtflüchtige Speicher auch das Feld mountOptions, um das Schreiben zu aktivieren.

Ein Codebeispiel für einen ähnlichen Anwendungsfall finden Sie unter Cloud Storage-Bucket verwenden.

Go

Wenn Sie einen Batchjob erstellen möchten, der neue oder vorhandene persistenten Datenträger mit den Cloud-Clientbibliotheken für Go verwendet, verwenden Sie die CreateJob-Funktion und fügen Sie Folgendes ein:

  • Wenn Sie nichtflüchtige Speicher an die VMs für einen Job anhängen möchten, fügen Sie eines der folgenden Elemente ein:
  • Wenn Sie die nichtflüchtigen Speicher für den Job bereitstellen möchten, verwenden Sie den Typ Volume mit dem Typ Volume_DeviceName und dem Feld MountPath. Verwenden Sie für neue nichtflüchtige Speicher auch das Feld MountOptions, um das Schreiben zu aktivieren.
import (
	"context"
	"fmt"
	"io"

	batch "cloud.google.com/go/batch/apiv1"
	"cloud.google.com/go/batch/apiv1/batchpb"
	durationpb "google.golang.org/protobuf/types/known/durationpb"
)

// Creates and runs a job with persistent disk
func createJobWithPD(w io.Writer, projectID, jobName, pdName string) error {
	// jobName := job-name
	// pdName := disk-name
	ctx := context.Background()
	batchClient, err := batch.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("batchClient error: %w", err)
	}
	defer batchClient.Close()

	runn := &batchpb.Runnable{
		Executable: &batchpb.Runnable_Script_{
			Script: &batchpb.Runnable_Script{
				Command: &batchpb.Runnable_Script_Text{
					Text: "echo Hello world from script 1 for task ${BATCH_TASK_INDEX}",
				},
			},
		},
	}
	volume := &batchpb.Volume{
		MountPath: fmt.Sprintf("/mnt/disks/%v", pdName),
		Source: &batchpb.Volume_DeviceName{
			DeviceName: pdName,
		},
	}

	// The disk type of the new persistent disk, either pd-standard,
	// pd-balanced, pd-ssd, or pd-extreme. For Batch jobs, the default is pd-balanced
	disk := &batchpb.AllocationPolicy_Disk{
		Type:   "pd-balanced",
		SizeGb: 10,
	}

	taskSpec := &batchpb.TaskSpec{
		ComputeResource: &batchpb.ComputeResource{
			// CpuMilli is milliseconds per cpu-second. This means the task requires 1 CPU.
			CpuMilli:  1000,
			MemoryMib: 16,
		},
		MaxRunDuration: &durationpb.Duration{
			Seconds: 3600,
		},
		MaxRetryCount: 2,
		Runnables:     []*batchpb.Runnable{runn},
		Volumes:       []*batchpb.Volume{volume},
	}

	taskGroups := []*batchpb.TaskGroup{
		{
			TaskCount: 4,
			TaskSpec:  taskSpec,
		},
	}

	labels := map[string]string{"env": "testing", "type": "container"}

	// Policies are used to define on what kind of virtual machines the tasks will run on.
	// Read more about local disks here: https://cloud.google.com/compute/docs/disks/persistent-disks
	allocationPolicy := &batchpb.AllocationPolicy{
		Instances: []*batchpb.AllocationPolicy_InstancePolicyOrTemplate{{
			PolicyTemplate: &batchpb.AllocationPolicy_InstancePolicyOrTemplate_Policy{
				Policy: &batchpb.AllocationPolicy_InstancePolicy{
					MachineType: "n1-standard-1",
					Disks: []*batchpb.AllocationPolicy_AttachedDisk{
						{
							Attached: &batchpb.AllocationPolicy_AttachedDisk_NewDisk{
								NewDisk: disk,
							},
							DeviceName: pdName,
						},
					},
				},
			},
		}},
	}

	// We use Cloud Logging as it's an out of the box available option
	logsPolicy := &batchpb.LogsPolicy{
		Destination: batchpb.LogsPolicy_CLOUD_LOGGING,
	}

	job := &batchpb.Job{
		Name:             jobName,
		TaskGroups:       taskGroups,
		AllocationPolicy: allocationPolicy,
		Labels:           labels,
		LogsPolicy:       logsPolicy,
	}

	request := &batchpb.CreateJobRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, "us-central1"),
		JobId:  jobName,
		Job:    job,
	}

	created_job, err := batchClient.CreateJob(ctx, request)
	if err != nil {
		return fmt.Errorf("unable to create job: %w", err)
	}

	fmt.Fprintf(w, "Job created: %v\n", created_job)
	return nil
}

Java

Wenn Sie einen Batchjob erstellen möchten, der neue oder vorhandene persistenten Datenträger mit den Cloud-Clientbibliotheken für Java verwendet, verwenden Sie die CreateJobRequest-Klasse und fügen Sie Folgendes ein:

Verwenden Sie beispielsweise das folgende Codebeispiel:


import com.google.cloud.batch.v1.AllocationPolicy;
import com.google.cloud.batch.v1.AllocationPolicy.AttachedDisk;
import com.google.cloud.batch.v1.AllocationPolicy.Disk;
import com.google.cloud.batch.v1.AllocationPolicy.InstancePolicy;
import com.google.cloud.batch.v1.AllocationPolicy.InstancePolicyOrTemplate;
import com.google.cloud.batch.v1.AllocationPolicy.LocationPolicy;
import com.google.cloud.batch.v1.BatchServiceClient;
import com.google.cloud.batch.v1.CreateJobRequest;
import com.google.cloud.batch.v1.Job;
import com.google.cloud.batch.v1.LogsPolicy;
import com.google.cloud.batch.v1.Runnable;
import com.google.cloud.batch.v1.Runnable.Script;
import com.google.cloud.batch.v1.TaskGroup;
import com.google.cloud.batch.v1.TaskSpec;
import com.google.cloud.batch.v1.Volume;
import com.google.common.collect.Lists;
import com.google.protobuf.Duration;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreatePersistentDiskJob {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";
    // Name of the region you want to use to run the job. Regions that are
    // available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
    String region = "europe-central2";
    // The name of the job that will be created.
    // It needs to be unique for each project and region pair.
    String jobName = "JOB_NAME";
    // The size of the new persistent disk in GB.
    // The allowed sizes depend on the type of persistent disk,
    // but the minimum is often 10 GB (10) and the maximum is often 64 TB (64000).
    int diskSize = 10;
    // The name of the new persistent disk.
    String newPersistentDiskName = "DISK-NAME";
    // The name of an existing persistent disk.
    String existingPersistentDiskName = "EXISTING-DISK-NAME";
    // The location of an existing persistent disk. For more info :
    // https://cloud.google.com/batch/docs/create-run-job-storage#gcloud
    String location = "regions/us-central1";
    // The disk type of the new persistent disk, either pd-standard,
    // pd-balanced, pd-ssd, or pd-extreme. For Batch jobs, the default is pd-balanced.
    String newDiskType = "pd-balanced";

    createPersistentDiskJob(projectId, region, jobName, newPersistentDiskName,
            diskSize, existingPersistentDiskName, location, newDiskType);
  }

  // Creates a job that attaches and mounts an existing persistent disk and a new persistent disk
  public static Job createPersistentDiskJob(String projectId, String region, String jobName,
                                            String newPersistentDiskName, int diskSize,
                                            String existingPersistentDiskName,
                                            String location, String newDiskType)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (BatchServiceClient batchServiceClient = BatchServiceClient.create()) {
      // Define what will be done as part of the job.
      String text = "echo Hello world from task ${BATCH_TASK_INDEX}. "
              + ">> /mnt/disks/NEW_PERSISTENT_DISK_NAME/output_task_${BATCH_TASK_INDEX}.txt";
      Runnable runnable =
          Runnable.newBuilder()
              .setScript(
                  Script.newBuilder()
                      .setText(text)
                      // You can also run a script from a file. Just remember, that needs to be a
                      // script that's already on the VM that will be running the job.
                      // Using setText() and setPath() is mutually exclusive.
                      // .setPath("/tmp/test.sh")
                      .build())
              .build();

      TaskSpec task = TaskSpec.newBuilder()
              // Jobs can be divided into tasks. In this case, we have only one task.
              .addAllVolumes(volumes(newPersistentDiskName, existingPersistentDiskName))
              .addRunnables(runnable)
              .setMaxRetryCount(2)
              .setMaxRunDuration(Duration.newBuilder().setSeconds(3600).build())
              .build();

      // Tasks are grouped inside a job using TaskGroups.
      // Currently, it's possible to have only one task group.
      TaskGroup taskGroup = TaskGroup.newBuilder()
          .setTaskCount(3)
          .setParallelism(1)
          .setTaskSpec(task)
          .build();

      // Policies are used to define the type of virtual machines the tasks will run on.
      InstancePolicy policy = InstancePolicy.newBuilder()
              .addAllDisks(attachedDisks(newPersistentDiskName, diskSize, newDiskType,
                  projectId, location, existingPersistentDiskName))
              .build();

      AllocationPolicy allocationPolicy =
          AllocationPolicy.newBuilder()
              .addInstances(
                  InstancePolicyOrTemplate.newBuilder()
                      .setPolicy(policy))
                  .setLocation(LocationPolicy.newBuilder().addAllowedLocations(location))
              .build();

      Job job =
          Job.newBuilder()
              .addTaskGroups(taskGroup)
              .setAllocationPolicy(allocationPolicy)
              .putLabels("env", "testing")
              .putLabels("type", "script")
              // We use Cloud Logging as it's an out-of-the-box option.
              .setLogsPolicy(
                  LogsPolicy.newBuilder().setDestination(LogsPolicy.Destination.CLOUD_LOGGING))
              .build();

      CreateJobRequest createJobRequest =
          CreateJobRequest.newBuilder()
              // The job's parent is the region in which the job will run.
              .setParent(String.format("projects/%s/locations/%s", projectId, region))
              .setJob(job)
              .setJobId(jobName)
              .build();

      Job result =
          batchServiceClient
              .createJobCallable()
              .futureCall(createJobRequest)
              .get(5, TimeUnit.MINUTES);

      System.out.printf("Successfully created the job: %s", result.getName());

      return result;
    }
  }

  // Creates link to existing disk and creates configuration for new disk
  private static Iterable<AttachedDisk> attachedDisks(String newPersistentDiskName, int diskSize,
                                                      String newDiskType, String projectId,
                                                      String existingPersistentDiskLocation,
                                                      String existingPersistentDiskName) {
    AttachedDisk newDisk = AttachedDisk.newBuilder()
            .setDeviceName(newPersistentDiskName)
            .setNewDisk(Disk.newBuilder().setSizeGb(diskSize).setType(newDiskType))
            .build();

    String diskPath = String.format("projects/%s/%s/disks/%s", projectId,
            existingPersistentDiskLocation, existingPersistentDiskName);

    AttachedDisk existingDisk = AttachedDisk.newBuilder()
            .setDeviceName(existingPersistentDiskName)
            .setExistingDisk(diskPath)
            .build();

    return Lists.newArrayList(existingDisk, newDisk);
  }

  // Describes a volume and parameters for it to be mounted to a VM.
  private static Iterable<Volume> volumes(String newPersistentDiskName,
                                          String existingPersistentDiskName) {
    Volume newVolume = Volume.newBuilder()
            .setDeviceName(newPersistentDiskName)
            .setMountPath("/mnt/disks/" + newPersistentDiskName)
            .addMountOptions("rw")
            .addMountOptions("async")
            .build();

    Volume existingVolume = Volume.newBuilder()
            .setDeviceName(existingPersistentDiskName)
            .setMountPath("/mnt/disks/" + existingPersistentDiskName)
            .build();

    return Lists.newArrayList(newVolume, existingVolume);
  }
}

Node.js

Wenn Sie einen Batchjob erstellen möchten, der neue oder vorhandene nichtflüchtige Datenträger mit den Cloud-Clientbibliotheken für Node.js verwendet, verwenden Sie die createJob-Methode und fügen Sie Folgendes ein:

// Imports the Batch library
const batchLib = require('@google-cloud/batch');
const batch = batchLib.protos.google.cloud.batch.v1;

// Instantiates a client
const batchClient = new batchLib.v1.BatchServiceClient();

/**
 * TODO(developer): Update these variables before running the sample.
 */
// Project ID or project number of the Google Cloud project you want to use.
const projectId = await batchClient.getProjectId();
// The name of the job that will be created.
// It needs to be unique for each project and region pair.
const jobName = 'batch-create-persistent-disk-job';
// Name of the region you want to use to run the job. Regions that are
// available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
const region = 'europe-central2';
// The name of an existing persistent disk.
const existingPersistentDiskName = 'existing-persistent-disk-name';
// The name of the new persistent disk.
const newPersistentDiskName = 'new-persistent-disk-name';
// The size of the new persistent disk in GB.
// The allowed sizes depend on the type of persistent disk,
// but the minimum is often 10 GB (10) and the maximum is often 64 TB (64000).
const diskSize = 10;
// The location of an existing persistent disk. For more info :
// https://cloud.google.com/batch/docs/create-run-job-storage#gcloud
const location = 'regions/us-central1';
// The disk type of the new persistent disk, either pd-standard,
// pd-balanced, pd-ssd, or pd-extreme. For Batch jobs, the default is pd-balanced.
const newDiskType = 'pd-balanced';

// Define what will be done as part of the job.
const runnable = new batch.Runnable({
  script: new batch.Runnable.Script({
    commands: [
      '-c',
      'echo Hello world! This is task ${BATCH_TASK_INDEX}.' +
        '>> /mnt/disks/NEW_PERSISTENT_DISK_NAME/output_task_${BATCH_TASK_INDEX}.txt',
    ],
  }),
});

// Define volumes and their parameters to be mounted to a VM.
const newVolume = new batch.Volume({
  deviceName: newPersistentDiskName,
  mountPath: `/mnt/disks/${newPersistentDiskName}`,
  mountOptions: ['rw', 'async'],
});

const existingVolume = new batch.Volume({
  deviceName: existingPersistentDiskName,
  mountPath: `/mnt/disks/${existingPersistentDiskName}`,
});

const task = new batch.TaskSpec({
  runnables: [runnable],
  volumes: [newVolume, existingVolume],
  maxRetryCount: 2,
  maxRunDuration: {seconds: 3600},
});

// Tasks are grouped inside a job using TaskGroups.
const group = new batch.TaskGroup({
  taskCount: 3,
  taskSpec: task,
});

const newDisk = new batch.AllocationPolicy.Disk({
  type: newDiskType,
  sizeGb: diskSize,
});

// Policies are used to define on what kind of virtual machines the tasks will run on.
// Read more about local disks here: https://cloud.google.com/compute/docs/disks/persistent-disks
const instancePolicy = new batch.AllocationPolicy.InstancePolicy({
  disks: [
    // Create configuration for new disk
    new batch.AllocationPolicy.AttachedDisk({
      deviceName: newPersistentDiskName,
      newDisk,
    }),
    // Create link to existing disk
    new batch.AllocationPolicy.AttachedDisk({
      existingDisk: `projects/${projectId}/${location}/disks/${existingPersistentDiskName}`,
      deviceName: existingPersistentDiskName,
    }),
  ],
});

const locationPolicy = new batch.AllocationPolicy.LocationPolicy({
  allowedLocations: [location],
});

const allocationPolicy = new batch.AllocationPolicy.InstancePolicyOrTemplate({
  instances: [{policy: instancePolicy}],
  location: locationPolicy,
});

const job = new batch.Job({
  name: jobName,
  taskGroups: [group],
  labels: {env: 'testing', type: 'script'},
  allocationPolicy,
  // We use Cloud Logging as it's an option available out of the box
  logsPolicy: new batch.LogsPolicy({
    destination: batch.LogsPolicy.Destination.CLOUD_LOGGING,
  }),
});
// The job's parent is the project and region in which the job will run
const parent = `projects/${projectId}/locations/${region}`;

async function callCreateBatchPersistentDiskJob() {
  // Construct request
  const request = {
    parent,
    jobId: jobName,
    job,
  };

  // Run request
  const [response] = await batchClient.createJob(request);
  console.log(JSON.stringify(response));
}

await callCreateBatchPersistentDiskJob();

Python

Wenn Sie einen Batch-Job erstellen möchten, der neue oder vorhandene persistenten Datenträger mit den Cloud-Clientbibliotheken für Python verwendet, verwenden Sie die CreateJob-Funktion und fügen Sie Folgendes ein:

  • Wenn Sie nichtflüchtige Speicher an die VMs für einen Job anhängen möchten, fügen Sie eines der folgenden Elemente ein:
  • Wenn Sie die nichtflüchtigen Speicher im Job einbinden möchten, verwenden Sie die Klasse Volume mit dem Attribut device_name und dem Attribut mount_path. Verwenden Sie für neue nichtflüchtige Speicher auch das Attribut mount_options, um das Schreiben zu aktivieren.

Verwenden Sie beispielsweise das folgende Codebeispiel:

from google.cloud import batch_v1


def create_with_pd_job(
    project_id: str,
    region: str,
    job_name: str,
    disk_name: str,
    zone: str,
    existing_disk_name=None,
) -> batch_v1.Job:
    """
    This method shows how to create a sample Batch Job that will run
    a simple command on Cloud Compute instances with mounted persistent disk.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        region: name of the region you want to use to run the job. Regions that are
            available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
        job_name: the name of the job that will be created.
            It needs to be unique for each project and region pair.
        disk_name: name of the disk to be mounted for your Job.
        existing_disk_name(optional): existing disk name, which you want to attach to a job

    Returns:
        A job object representing the job created.
    """
    client = batch_v1.BatchServiceClient()

    # Define what will be done as part of the job.
    task = batch_v1.TaskSpec()
    runnable = batch_v1.Runnable()
    runnable.script = batch_v1.Runnable.Script()
    runnable.script.text = (
        "echo Hello world from task ${BATCH_TASK_INDEX}. >> /mnt/disks/"
        + disk_name
        + "/output_task_${BATCH_TASK_INDEX}.txt"
    )
    task.runnables = [runnable]
    task.max_retry_count = 2
    task.max_run_duration = "3600s"

    volume = batch_v1.Volume()
    volume.device_name = disk_name
    volume.mount_path = f"/mnt/disks/{disk_name}"
    task.volumes = [volume]

    if existing_disk_name:
        volume2 = batch_v1.Volume()
        volume2.device_name = existing_disk_name
        volume2.mount_path = f"/mnt/disks/{existing_disk_name}"
        task.volumes.append(volume2)

    # Tasks are grouped inside a job using TaskGroups.
    # Currently, it's possible to have only one task group.
    group = batch_v1.TaskGroup()
    group.task_count = 4
    group.task_spec = task

    disk = batch_v1.AllocationPolicy.Disk()
    # The disk type of the new persistent disk, either pd-standard,
    # pd-balanced, pd-ssd, or pd-extreme. For Batch jobs, the default is pd-balanced
    disk.type_ = "pd-balanced"
    disk.size_gb = 10

    # Policies are used to define on what kind of virtual machines the tasks will run on.
    # Read more about local disks here: https://cloud.google.com/compute/docs/disks/persistent-disks
    policy = batch_v1.AllocationPolicy.InstancePolicy()
    policy.machine_type = "n1-standard-1"

    attached_disk = batch_v1.AllocationPolicy.AttachedDisk()
    attached_disk.new_disk = disk
    attached_disk.device_name = disk_name
    policy.disks = [attached_disk]

    if existing_disk_name:
        attached_disk2 = batch_v1.AllocationPolicy.AttachedDisk()
        attached_disk2.existing_disk = (
            f"projects/{project_id}/zones/{zone}/disks/{existing_disk_name}"
        )
        attached_disk2.device_name = existing_disk_name
        policy.disks.append(attached_disk2)

    instances = batch_v1.AllocationPolicy.InstancePolicyOrTemplate()
    instances.policy = policy

    allocation_policy = batch_v1.AllocationPolicy()
    allocation_policy.instances = [instances]

    location = batch_v1.AllocationPolicy.LocationPolicy()
    location.allowed_locations = [f"zones/{zone}"]
    allocation_policy.location = location

    job = batch_v1.Job()
    job.task_groups = [group]
    job.allocation_policy = allocation_policy
    job.labels = {"env": "testing", "type": "script"}

    create_request = batch_v1.CreateJobRequest()
    create_request.job = job
    create_request.job_id = job_name
    # The job's parent is the region in which the job will run
    create_request.parent = f"projects/{project_id}/locations/{region}"

    return client.create_job(create_request)

Lokale SSD verwenden

Für Jobs, die lokale SSDs verwenden, gelten die folgenden Einschränkungen:

Sie können einen Job erstellen, der eine lokale SSD verwendet, indem Sie die gcloud CLI, die Batch API, Java oder Python verwenden. Im folgenden Beispiel wird beschrieben, wie Sie einen Job erstellen, mit dem eine lokale SSD erstellt, angehängt und bereitgestellt wird. Der Job hat auch drei Aufgaben, die jeweils ein Skript ausführen, um eine Datei auf der lokalen SSD mit dem Namen output_task_TASK_INDEX.txt zu erstellen, wobei TASK_INDEX der Index der einzelnen Aufgaben ist: 0, 1 und 2.

gcloud

Verwenden Sie den gcloud CLI gcloud batch jobs submit, um einen Job zu erstellen, der lokale SSDs verwendet. Erstellen und hängen Sie die lokalen SSDs in der JSON-Konfigurationsdatei des Jobs im Feld instances an und stellen Sie die lokalen SSDs im Feld volumes bereit.

  1. Erstellen Sie eine JSON-Datei.

    • Wenn Sie für diesen Job keine Instanzvorlage verwenden, erstellen Sie eine JSON-Datei mit folgendem Inhalt:

      {
          "allocationPolicy": {
              "instances": [
                  {
                      "policy": {
                          "machineType": MACHINE_TYPE,
                          "disks": [
                              {
                                  "newDisk": {
                                      "sizeGb": LOCAL_SSD_SIZE,
                                      "type": "local-ssd"
                                  },
                                  "deviceName": "LOCAL_SSD_NAME"
                              }
                          ]
                      }
                  }
              ]
          },
          "taskGroups": [
              {
                  "taskSpec": {
                      "runnables": [
                          {
                              "script": {
                                  "text": "echo Hello world from task ${BATCH_TASK_INDEX}. >> /mnt/disks/LOCAL_SSD_NAME/output_task_${BATCH_TASK_INDEX}.txt"
                              }
                          }
                      ],
                      "volumes": [
                          {
                              "deviceName": "LOCAL_SSD_NAME",
                              "mountPath": "/mnt/disks/LOCAL_SSD_NAME",
                              "mountOptions": "rw,async"
                          }
                      ]
                  },
                  "taskCount":3
              }
          ],
          "logsPolicy": {
              "destination": "CLOUD_LOGGING"
          }
      }
      

      Ersetzen Sie Folgendes:

      • MACHINE_TYPE: Der Maschinentyp der VMs des Jobs. Dieser kann vordefiniert oder benutzerdefiniert sein. Die zulässige Anzahl lokaler SSDs hängt vom Maschinentyp der VMs für Ihren Job ab.
      • LOCAL_SSD_NAME: Der Name einer lokalen SSD, die für diesen Job erstellt wurde.
      • LOCAL_SSD_SIZE: Die Größe aller lokalen SSDs in GB. Jede lokale SSD ist 375 GB groß. Dieser Wert muss also ein Vielfaches von 375 GB sein. Wenn Sie beispielsweise zwei lokale SSDs verwenden, legen Sie diesen Wert auf 750 GB fest.
    • Wenn Sie eine VM-Instanzvorlage für diesen Job verwenden, erstellen Sie eine JSON-Datei wie zuvor, ersetzen Sie jedoch das instances-Feld durch Folgendes:

      "instances": [
          {
              "instanceTemplate": "INSTANCE_TEMPLATE_NAME"
          }
      ],
      

      Dabei ist INSTANCE_TEMPLATE_NAME der Name der Instanzvorlage für diesen Job. Für einen Job, der lokale SSDs verwendet, müssen in dieser Instanzvorlage die lokalen SSDs definiert und angehängt werden, die für den Job verwendet werden sollen. In diesem Beispiel muss in der Vorlage eine lokale SSD mit dem Namen LOCAL_SSD_NAME definiert und angehängt werden.

  2. Führen Sie dazu diesen Befehl aus:

    gcloud batch jobs submit JOB_NAME \
      --location LOCATION \
      --config JSON_CONFIGURATION_FILE
    

    Ersetzen Sie Folgendes:

    • JOB_NAME: Der Name des Jobs.
    • LOCATION: Der Standort des Jobs.
    • JSON_CONFIGURATION_FILE: der Pfad zu einer JSON-Datei mit den Konfigurationsdetails des Jobs.

API

Wenn Sie mit der Batch API einen Job erstellen möchten, der lokale SSDs verwendet, nutzen Sie die jobs.create-Methode. Erstellen und hängen Sie die lokalen SSDs in der Anfrage im Feld instances an und stellen Sie sie im Feld volumes bereit.

  • Wenn Sie für diesen Job keine Instanzvorlage verwenden, stellen Sie die folgende Anfrage:

    POST https://batch.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/jobs?job_id=JOB_NAME
    
    {
        "allocationPolicy": {
            "instances": [
                {
                    "policy": {
                        "machineType": MACHINE_TYPE,
                        "disks": [
                            {
                                "newDisk": {
                                    "sizeGb": LOCAL_SSD_SIZE,
                                    "type": "local-ssd"
                                },
                                "deviceName": "LOCAL_SSD_NAME"
                            }
                        ]
                    }
                }
            ]
        },
        "taskGroups": [
            {
                "taskSpec": {
                    "runnables": [
                        {
                            "script": {
                                "text": "echo Hello world from task ${BATCH_TASK_INDEX}. >> /mnt/disks/LOCAL_SSD_NAME/output_task_${BATCH_TASK_INDEX}.txt"
                            }
                        }
                    ],
                    "volumes": [
                        {
                            "deviceName": "LOCAL_SSD_NAME",
                            "mountPath": "/mnt/disks/LOCAL_SSD_NAME",
                            "mountOptions": "rw,async"
                        }
                    ]
                },
                "taskCount":3
            }
        ],
        "logsPolicy": {
            "destination": "CLOUD_LOGGING"
        }
    }
    

    Ersetzen Sie Folgendes:

    • PROJECT_ID: die Projekt-ID Ihres Projekts.
    • LOCATION: Der Standort des Jobs.
    • JOB_NAME: Der Name des Jobs.
    • MACHINE_TYPE: Der Maschinentyp der VMs des Jobs. Dieser kann vordefiniert oder benutzerdefiniert sein. Die zulässige Anzahl lokaler SSDs hängt vom Maschinentyp der VMs für Ihren Job ab.
    • LOCAL_SSD_NAME: Der Name einer lokalen SSD, die für diesen Job erstellt wurde.
    • LOCAL_SSD_SIZE: Die Größe aller lokalen SSDs in GB. Jede lokale SSD ist 375 GB groß. Dieser Wert muss also ein Vielfaches von 375 GB sein. Wenn Sie beispielsweise zwei lokale SSDs verwenden, legen Sie diesen Wert auf 750 GB fest.
  • Wenn Sie eine VM-Instanzvorlage für diesen Job verwenden, erstellen Sie eine JSON-Datei wie zuvor, ersetzen Sie jedoch das instances-Feld durch Folgendes:

    "instances": [
        {
            "instanceTemplate": "INSTANCE_TEMPLATE_NAME"
        }
    ],
    ...
    

    Dabei ist INSTANCE_TEMPLATE_NAME der Name der Instanzvorlage für diesen Job. Für einen Job, der lokale SSDs verwendet, müssen in dieser Instanzvorlage die lokalen SSDs definiert und angehängt werden, die für den Job verwendet werden sollen. In diesem Beispiel muss in der Vorlage eine lokale SSD mit dem Namen LOCAL_SSD_NAME definiert und angehängt werden.

Go

import (
	"context"
	"fmt"
	"io"

	batch "cloud.google.com/go/batch/apiv1"
	"cloud.google.com/go/batch/apiv1/batchpb"
	durationpb "google.golang.org/protobuf/types/known/durationpb"
)

// Creates and runs a job with local SSD
// Note: local SSD does not guarantee Local SSD data persistence.
// More details here: https://cloud.google.com/compute/docs/disks/local-ssd#data_persistence
func createJobWithSSD(w io.Writer, projectID, jobName, ssdName string) error {
	// jobName := job-name
	// ssdName := disk-name
	ctx := context.Background()
	batchClient, err := batch.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("batchClient error: %w", err)
	}
	defer batchClient.Close()

	runn := &batchpb.Runnable{
		Executable: &batchpb.Runnable_Script_{
			Script: &batchpb.Runnable_Script{
				Command: &batchpb.Runnable_Script_Text{
					Text: "echo Hello world from script 1 for task ${BATCH_TASK_INDEX}",
				},
			},
		},
	}
	volume := &batchpb.Volume{
		MountPath: fmt.Sprintf("/mnt/disks/%v", ssdName),
		Source: &batchpb.Volume_DeviceName{
			DeviceName: ssdName,
		},
	}

	// The size of all the local SSDs in GB. Each local SSD is 375 GB,
	// so this value must be a multiple of 375 GB.
	// For example, for 2 local SSDs, set this value to 750 GB.
	disk := &batchpb.AllocationPolicy_Disk{
		Type:   "local-ssd",
		SizeGb: 375,
	}

	taskSpec := &batchpb.TaskSpec{
		ComputeResource: &batchpb.ComputeResource{
			// CpuMilli is milliseconds per cpu-second. This means the task requires 1 CPU.
			CpuMilli:  1000,
			MemoryMib: 16,
		},
		MaxRunDuration: &durationpb.Duration{
			Seconds: 3600,
		},
		MaxRetryCount: 2,
		Runnables:     []*batchpb.Runnable{runn},
		Volumes:       []*batchpb.Volume{volume},
	}

	taskGroups := []*batchpb.TaskGroup{
		{
			TaskCount: 4,
			TaskSpec:  taskSpec,
		},
	}

	labels := map[string]string{"env": "testing", "type": "container"}

	allocationPolicy := &batchpb.AllocationPolicy{
		Instances: []*batchpb.AllocationPolicy_InstancePolicyOrTemplate{{
			PolicyTemplate: &batchpb.AllocationPolicy_InstancePolicyOrTemplate_Policy{
				Policy: &batchpb.AllocationPolicy_InstancePolicy{
					// The allowed number of local SSDs depends on the machine type for your job's VMs.
					// In this case, we tell the system to use "n1-standard-1" machine type, which require to attach local ssd manually.
					// Read more about local disks here: https://cloud.google.com/compute/docs/disks/local-ssd#lssd_disk_options
					MachineType: "n1-standard-1",
					Disks: []*batchpb.AllocationPolicy_AttachedDisk{
						{
							Attached: &batchpb.AllocationPolicy_AttachedDisk_NewDisk{
								NewDisk: disk,
							},
							DeviceName: ssdName,
						},
					},
				},
			},
		}},
	}

	// We use Cloud Logging as it's an out of the box available option
	logsPolicy := &batchpb.LogsPolicy{
		Destination: batchpb.LogsPolicy_CLOUD_LOGGING,
	}

	job := &batchpb.Job{
		Name:             jobName,
		TaskGroups:       taskGroups,
		AllocationPolicy: allocationPolicy,
		Labels:           labels,
		LogsPolicy:       logsPolicy,
	}

	request := &batchpb.CreateJobRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, "us-central1"),
		JobId:  jobName,
		Job:    job,
	}

	created_job, err := batchClient.CreateJob(ctx, request)
	if err != nil {
		return fmt.Errorf("unable to create job: %w", err)
	}

	fmt.Fprintf(w, "Job created: %v\n", created_job)
	return nil
}

Java


import com.google.cloud.batch.v1.AllocationPolicy;
import com.google.cloud.batch.v1.AllocationPolicy.AttachedDisk;
import com.google.cloud.batch.v1.AllocationPolicy.Disk;
import com.google.cloud.batch.v1.AllocationPolicy.InstancePolicy;
import com.google.cloud.batch.v1.AllocationPolicy.InstancePolicyOrTemplate;
import com.google.cloud.batch.v1.BatchServiceClient;
import com.google.cloud.batch.v1.CreateJobRequest;
import com.google.cloud.batch.v1.Job;
import com.google.cloud.batch.v1.LogsPolicy;
import com.google.cloud.batch.v1.Runnable;
import com.google.cloud.batch.v1.Runnable.Script;
import com.google.cloud.batch.v1.TaskGroup;
import com.google.cloud.batch.v1.TaskSpec;
import com.google.cloud.batch.v1.Volume;
import com.google.protobuf.Duration;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateLocalSsdJob {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";
    // Name of the region you want to use to run the job. Regions that are
    // available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
    String region = "europe-central2";
    // The name of the job that will be created.
    // It needs to be unique for each project and region pair.
    String jobName = "JOB_NAME";
    // The name of a local SSD created for this job.
    String localSsdName = "SSD-NAME";
    // The machine type, which can be predefined or custom, of the job's VMs.
    // The allowed number of local SSDs depends on the machine type
    // for your job's VMs are listed on: https://cloud.google.com/compute/docs/disks#localssds
    String machineType = "c3d-standard-8-lssd";
    // The size of all the local SSDs in GB. Each local SSD is 375 GB,
    // so this value must be a multiple of 375 GB.
    // For example, for 2 local SSDs, set this value to 750 GB.
    int ssdSize = 375;

    createLocalSsdJob(projectId, region, jobName, localSsdName, ssdSize, machineType);
  }

  // Create a job that uses local SSDs
  public static Job createLocalSsdJob(String projectId, String region, String jobName,
                                      String localSsdName, int ssdSize, String machineType)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (BatchServiceClient batchServiceClient = BatchServiceClient.create()) {
      // Define what will be done as part of the job.
      Runnable runnable =
          Runnable.newBuilder()
              .setScript(
                  Script.newBuilder()
                      .setText(
                          "echo Hello world! This is task ${BATCH_TASK_INDEX}. "
                                  + "This job has a total of ${BATCH_TASK_COUNT} tasks.")
                      // You can also run a script from a file. Just remember, that needs to be a
                      // script that's already on the VM that will be running the job.
                      // Using setText() and setPath() is mutually exclusive.
                      // .setPath("/tmp/test.sh")
                      .build())
              .build();

      Volume volume = Volume.newBuilder()
          .setDeviceName(localSsdName)
          .setMountPath("/mnt/disks/" + localSsdName)
          .addMountOptions("rw")
          .addMountOptions("async")
          .build();

      TaskSpec task = TaskSpec.newBuilder()
          // Jobs can be divided into tasks. In this case, we have only one task.
          .addVolumes(volume)
          .addRunnables(runnable)
          .setMaxRetryCount(2)
          .setMaxRunDuration(Duration.newBuilder().setSeconds(3600).build())
          .build();

      // Tasks are grouped inside a job using TaskGroups.
      // Currently, it's possible to have only one task group.
      TaskGroup taskGroup = TaskGroup.newBuilder()
          .setTaskCount(3)
          .setParallelism(1)
          .setTaskSpec(task)
          .build();

      // Policies are used to define on what kind of virtual machines the tasks will run on.
      InstancePolicy policy = InstancePolicy.newBuilder()
          .setMachineType(machineType)
          .addDisks(AttachedDisk.newBuilder()
              .setDeviceName(localSsdName)
              // For example, local SSD uses type "local-ssd".
              // Persistent disks and boot disks use "pd-balanced", "pd-extreme", "pd-ssd"
              // or "pd-standard".
              .setNewDisk(Disk.newBuilder().setSizeGb(ssdSize).setType("local-ssd")))
          .build();

      AllocationPolicy allocationPolicy =
          AllocationPolicy.newBuilder()
              .addInstances(
                  InstancePolicyOrTemplate.newBuilder()
                      .setPolicy(policy)
                      .build())
              .build();

      Job job =
          Job.newBuilder()
              .addTaskGroups(taskGroup)
              .setAllocationPolicy(allocationPolicy)
              .putLabels("env", "testing")
              .putLabels("type", "script")
              // We use Cloud Logging as it's an out of the box available option.
              .setLogsPolicy(
                  LogsPolicy.newBuilder().setDestination(LogsPolicy.Destination.CLOUD_LOGGING))
              .build();

      CreateJobRequest createJobRequest =
          CreateJobRequest.newBuilder()
              // The job's parent is the region in which the job will run.
              .setParent(String.format("projects/%s/locations/%s", projectId, region))
              .setJob(job)
              .setJobId(jobName)
              .build();

      Job result =
          batchServiceClient
              .createJobCallable()
              .futureCall(createJobRequest)
              .get(5, TimeUnit.MINUTES);

      System.out.printf("Successfully created the job: %s", result.getName());

      return result;
    }
  }
}

Node.js

// Imports the Batch library
const batchLib = require('@google-cloud/batch');
const batch = batchLib.protos.google.cloud.batch.v1;

// Instantiates a client
const batchClient = new batchLib.v1.BatchServiceClient();

/**
 * TODO(developer): Update these variables before running the sample.
 */
// Project ID or project number of the Google Cloud project you want to use.
const projectId = await batchClient.getProjectId();
// Name of the region you want to use to run the job. Regions that are
// available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
const region = 'europe-central2';
// The name of the job that will be created.
// It needs to be unique for each project and region pair.
const jobName = 'batch-local-ssd-job';
// The name of a local SSD created for this job.
const localSsdName = 'ssd-name';
// The machine type, which can be predefined or custom, of the job's VMs.
// The allowed number of local SSDs depends on the machine type
// for your job's VMs are listed on: https://cloud.google.com/compute/docs/disks#localssds
const machineType = 'c3d-standard-8-lssd';
// The size of all the local SSDs in GB. Each local SSD is 375 GB,
// so this value must be a multiple of 375 GB.
// For example, for 2 local SSDs, set this value to 750 GB.
const ssdSize = 375;

// Define what will be done as part of the job.
const runnable = new batch.Runnable({
  script: new batch.Runnable.Script({
    commands: [
      '-c',
      'echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks.',
    ],
  }),
});

const task = new batch.TaskSpec({
  runnables: [runnable],
  maxRetryCount: 2,
  maxRunDuration: {seconds: 3600},
});

// Tasks are grouped inside a job using TaskGroups.
const group = new batch.TaskGroup({
  taskCount: 3,
  taskSpec: task,
});

// Policies are used to define on what kind of virtual machines the tasks will run on.
const instancePolicy = new batch.AllocationPolicy.InstancePolicy({
  machineType,
  disks: [
    new batch.AllocationPolicy.AttachedDisk({
      deviceName: localSsdName,
      // For example, local SSD uses type "local-ssd".
      // Persistent disks and boot disks use "pd-balanced", "pd-extreme", "pd-ssd"
      // or "pd-standard".
      newDisk: new batch.AllocationPolicy.AttachedDisk({
        type: 'local-ssd',
        sizeGb: ssdSize,
      }),
    }),
  ],
});

const allocationPolicy = new batch.AllocationPolicy.InstancePolicyOrTemplate({
  instances: [{policy: instancePolicy}],
});

const job = new batch.Job({
  name: jobName,
  taskGroups: [group],
  labels: {env: 'testing', type: 'script'},
  allocationPolicy,
  // We use Cloud Logging as it's an option available out of the box
  logsPolicy: new batch.LogsPolicy({
    destination: batch.LogsPolicy.Destination.CLOUD_LOGGING,
  }),
});
// The job's parent is the project and region in which the job will run
const parent = `projects/${projectId}/locations/${region}`;

async function callCreateBatchGPUJob() {
  // Construct request
  const request = {
    parent,
    jobId: jobName,
    job,
  };

  // Run request
  const [response] = await batchClient.createJob(request);
  console.log(JSON.stringify(response));
}

await callCreateBatchGPUJob();

Python

from google.cloud import batch_v1


def create_local_ssd_job(
    project_id: str, region: str, job_name: str, ssd_name: str
) -> batch_v1.Job:
    """
    This method shows how to create a sample Batch Job that will run
    a simple command on Cloud Compute instances with mounted local SSD.
    Note: local SSD does not guarantee Local SSD data persistence.
    More details here: https://cloud.google.com/compute/docs/disks/local-ssd#data_persistence

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        region: name of the region you want to use to run the job. Regions that are
            available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
        job_name: the name of the job that will be created.
            It needs to be unique for each project and region pair.
        ssd_name: name of the local ssd to be mounted for your Job.

    Returns:
        A job object representing the job created.
    """
    client = batch_v1.BatchServiceClient()

    # Define what will be done as part of the job.
    task = batch_v1.TaskSpec()
    runnable = batch_v1.Runnable()
    runnable.script = batch_v1.Runnable.Script()
    runnable.script.text = "echo Hello world! This is task ${BATCH_TASK_INDEX}. This job has a total of ${BATCH_TASK_COUNT} tasks."
    task.runnables = [runnable]
    task.max_retry_count = 2
    task.max_run_duration = "3600s"

    volume = batch_v1.Volume()
    volume.device_name = ssd_name
    volume.mount_path = f"/mnt/disks/{ssd_name}"
    task.volumes = [volume]

    # Tasks are grouped inside a job using TaskGroups.
    # Currently, it's possible to have only one task group.
    group = batch_v1.TaskGroup()
    group.task_count = 4
    group.task_spec = task

    disk = batch_v1.AllocationPolicy.Disk()
    disk.type_ = "local-ssd"
    # The size of all the local SSDs in GB. Each local SSD is 375 GB,
    # so this value must be a multiple of 375 GB.
    # For example, for 2 local SSDs, set this value to 750 GB.
    disk.size_gb = 375
    assert disk.size_gb % 375 == 0

    # Policies are used to define on what kind of virtual machines the tasks will run on.
    # The allowed number of local SSDs depends on the machine type for your job's VMs.
    # In this case, we tell the system to use "n1-standard-1" machine type, which require to attach local ssd manually.
    # Read more about local disks here: https://cloud.google.com/compute/docs/disks/local-ssd#lssd_disk_options
    policy = batch_v1.AllocationPolicy.InstancePolicy()
    policy.machine_type = "n1-standard-1"

    attached_disk = batch_v1.AllocationPolicy.AttachedDisk()
    attached_disk.new_disk = disk
    attached_disk.device_name = ssd_name
    policy.disks = [attached_disk]

    instances = batch_v1.AllocationPolicy.InstancePolicyOrTemplate()
    instances.policy = policy

    allocation_policy = batch_v1.AllocationPolicy()
    allocation_policy.instances = [instances]

    job = batch_v1.Job()
    job.task_groups = [group]
    job.allocation_policy = allocation_policy
    job.labels = {"env": "testing", "type": "script"}
    # We use Cloud Logging as it's an out of the box available option
    job.logs_policy = batch_v1.LogsPolicy()
    job.logs_policy.destination = batch_v1.LogsPolicy.Destination.CLOUD_LOGGING

    create_request = batch_v1.CreateJobRequest()
    create_request.job = job
    create_request.job_id = job_name
    # The job's parent is the region in which the job will run
    create_request.parent = f"projects/{project_id}/locations/{region}"

    return client.create_job(create_request)

Cloud Storage-Bucket verwenden

Wenn Sie einen Job erstellen möchten, der einen vorhandenen Cloud Storage-Bucket verwendet, wählen Sie eine der folgenden Methoden aus:

  • Empfohlen: Stellen Sie einen Bucket direkt für die VMs Ihres Jobs bereit, indem Sie den Bucket in der Definition des Jobs angeben, wie in diesem Abschnitt gezeigt. Wenn der Job ausgeführt wird, wird der Bucket automatisch mit Cloud Storage FUSE auf den VMs für Ihren Job bereitgestellt.
  • Erstellen Sie einen Job mit Aufgaben, die direkt auf einen Cloud Storage-Bucket zugreifen. Verwenden Sie dazu die gcloud CLI oder Clientbibliotheken für die Cloud Storage API. Informationen zum direkten Zugriff auf einen Cloud Storage-Bucket über eine VM finden Sie in der Compute Engine-Dokumentation unter Daten in Cloud Storage-Buckets schreiben und daraus lesen.

Bevor Sie einen Job erstellen, der einen Bucket verwendet, müssen Sie einen Bucket erstellen oder einen vorhandenen Bucket auswählen. Weitere Informationen finden Sie unter Buckets erstellen und Buckets auflisten.

Sie können einen Job erstellen, der einen Cloud Storage-Bucket verwendet, indem Sie dieGoogle Cloud Console, die gcloud CLI, die Batch API, C++, Go, Java, Node.js oder Python verwenden.

Im folgenden Beispiel wird beschrieben, wie Sie einen Job erstellen, der einen Cloud Storage-Bucket einbindet. Der Job hat auch drei Aufgaben, bei denen jeweils ein Skript ausgeführt wird, um eine Datei im Bucket mit dem Namen output_task_TASK_INDEX.txt zu erstellen, wobei TASK_INDEX der Index der einzelnen Aufgaben ist: 0, 1 und 2.

Console

So erstellen Sie einen Job, der einen Cloud Storage-Bucket verwendet, mit derGoogle Cloud Console:

  1. Rufen Sie in der Google Cloud Console die Seite Jobliste auf.

    Zur Jobliste

  2. Klicken Sie auf Erstellen. Die Seite Batchjob erstellen wird geöffnet. Im linken Bereich ist die Seite Jobdetails ausgewählt.

  3. Konfigurieren Sie die Seite Jobdetails:

    1. Optional: Passen Sie im Feld Jobname den Jobnamen an.

      Geben Sie beispielsweise example-bucket-job ein.

    2. Konfigurieren Sie den Abschnitt Aufgabendetails:

      1. Fügen Sie im Fenster Neues Runnable mindestens ein Script oder einen Container hinzu, damit dieser Job ausgeführt werden kann.

        Führen Sie dazu z. B. folgende Schritte aus:

        1. Klicken Sie das Kästchen Script an. Ein Textfeld wird angezeigt.

        2. Geben Sie das folgende Skript in das Textfeld ein:

          echo Hello world from task ${BATCH_TASK_INDEX}. >> MOUNT_PATH/output_task_${BATCH_TASK_INDEX}.txt
          

          Ersetzen Sie MOUNT_PATH durch den Mount-Pfad, den die Runnables dieses Jobs für den Zugriff auf einen vorhandenen Cloud Storage-Bucket verwenden. Der Pfad muss mit /mnt/disks/ beginnen, gefolgt von einem Verzeichnis oder Pfad Ihrer Wahl. Wenn Sie diesen Bucket beispielsweise mit einem Verzeichnis namens my-bucket darstellen möchten, legen Sie den Mount-Pfad auf /mnt/disks/my-bucket fest.

        3. Klicken Sie auf Fertig.

      2. Geben Sie im Feld Anzahl der Aufgaben die Anzahl der Aufgaben für diesen Job ein.

        Geben Sie beispielsweise 3 ein.

      3. Geben Sie im Feld Parallelität die Anzahl der Aufgaben ein, die gleichzeitig ausgeführt werden sollen.

        Geben Sie beispielsweise 1 (Standardeinstellung) ein.

  4. Konfigurieren Sie die Seite Zusätzliche Konfigurationen:

    1. Klicken Sie im linken Bereich auf Zusätzliche Konfigurationen. Die Seite Zusätzliche Konfigurationen wird geöffnet.

    2. Führen Sie für jeden Cloud Storage-Bucket, den Sie für diesen Job bereitstellen möchten, die folgenden Schritte aus:

      1. Klicken Sie im Bereich Speichervolume auf Neues Volume hinzufügen. Das Fenster Neues Volume wird angezeigt.

      2. Führen Sie im Fenster Neues Volume die folgenden Schritte aus:

        1. Wählen Sie im Abschnitt Volume-Typ die Option Cloud Storage-Bucket aus.

        2. Geben Sie im Feld Name des Storage-Buckets den Namen eines vorhandenen Buckets ein.

          Geben Sie beispielsweise den Bucket ein, den Sie im ausführbaren Teil dieses Jobs angegeben haben.

        3. Geben Sie im Feld Bereitstellungspfad den Bereitstellungspfad des Buckets (MOUNT_PATH) ein, den Sie im ausführbaren Code angegeben haben.

        4. Klicken Sie auf Fertig.

  5. Optional: Konfigurieren Sie die anderen Felder für diesen Job.

  6. Optional: Wenn Sie die Jobkonfiguration überprüfen möchten, klicken Sie im linken Bereich auf Vorschau.

  7. Klicken Sie auf Erstellen.

Auf der Seite Jobdetails wird der von Ihnen erstellte Job angezeigt.

gcloud

Verwenden Sie den gcloud batch jobs submit-Befehl, um einen Job zu erstellen, der einen Cloud Storage-Bucket verwendet. Hängen Sie den Bucket in der JSON-Konfigurationsdatei des Jobs im Feld volumes ein.

So erstellen Sie beispielsweise einen Job, der Dateien in Cloud Storage ausgibt:

  1. Erstellen Sie eine package.json-Datei mit folgendem Inhalt:

    {
        "taskGroups": [
            {
                "taskSpec": {
                    "runnables": [
                        {
                            "script": {
                                "text": "echo Hello world from task ${BATCH_TASK_INDEX}. >> MOUNT_PATH/output_task_${BATCH_TASK_INDEX}.txt"
                            }
                        }
                    ],
                    "volumes": [
                        {
                            "gcs": {
                                "remotePath": "BUCKET_PATH"
                            },
                            "mountPath": "MOUNT_PATH"
                        }
                    ]
                },
                "taskCount": 3
            }
        ],
        "logsPolicy": {
            "destination": "CLOUD_LOGGING"
        }
    }
    

    Ersetzen Sie Folgendes:

    • BUCKET_PATH: Der Pfad des Bucket-Verzeichnisses, auf das dieser Job zugreifen soll. Er muss mit dem Namen des Buckets beginnen. Für einen Bucket mit dem Namen BUCKET_NAME steht der Pfad BUCKET_NAME beispielsweise für das Stammverzeichnis des Buckets und der Pfad BUCKET_NAME/subdirectory für das Unterverzeichnis subdirectory.
    • MOUNT_PATH: Der Mount-Pfad, den die ausführbaren Dateien des Jobs verwenden, um auf diesen Bucket zuzugreifen. Der Pfad muss mit /mnt/disks/ beginnen, gefolgt von einem Verzeichnis oder Pfad Ihrer Wahl. Wenn Sie diesen Bucket beispielsweise mit einem Verzeichnis namens my-bucket darstellen möchten, legen Sie den Bereitstellungspfad auf /mnt/disks/my-bucket fest.
  2. Führen Sie dazu diesen Befehl aus:

    gcloud batch jobs submit JOB_NAME \
      --location LOCATION \
      --config JSON_CONFIGURATION_FILE
    

    Ersetzen Sie Folgendes:

    • JOB_NAME: Der Name des Jobs.
    • LOCATION: Der Standort des Jobs.
    • JSON_CONFIGURATION_FILE: der Pfad zu einer JSON-Datei mit den Konfigurationsdetails des Jobs.

API

Wenn Sie einen Job erstellen möchten, der einen Cloud Storage-Bucket mit der Batch API verwendet, verwenden Sie die jobs.create-Methode und hängen Sie den Bucket im Feld volumes ein.

POST https://batch.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/jobs?job_id=JOB_NAME

{
    "taskGroups": [
        {
            "taskSpec": {
                "runnables": [
                    {
                        "script": {
                            "text": "echo Hello world from task ${BATCH_TASK_INDEX}. >> MOUNT_PATH/output_task_${BATCH_TASK_INDEX}.txt"
                        }
                    }
                ],
                "volumes": [
                    {
                        "gcs": {
                            "remotePath": "BUCKET_PATH"
                        },
                        "mountPath": "MOUNT_PATH"
                    }
                ]
            },
            "taskCount": 3
        }
    ],
    "logsPolicy": {
            "destination": "CLOUD_LOGGING"
    }
}

Ersetzen Sie Folgendes:

  • PROJECT_ID: die Projekt-ID Ihres Projekts.
  • LOCATION: Der Standort des Jobs.
  • JOB_NAME: Der Name des Jobs.
  • BUCKET_PATH: Der Pfad des Bucket-Verzeichnisses, auf das dieser Job zugreifen soll. Er muss mit dem Namen des Buckets beginnen. Für einen Bucket mit dem Namen BUCKET_NAME stellt der Pfad BUCKET_NAME beispielsweise das Stammverzeichnis des Buckets und der Pfad BUCKET_NAME/subdirectory das Unterverzeichnis subdirectory dar.
  • MOUNT_PATH: Der Mount-Pfad, den die ausführbaren Dateien des Jobs verwenden, um auf diesen Bucket zuzugreifen. Der Pfad muss mit /mnt/disks/ beginnen, gefolgt von einem Verzeichnis oder Pfad Ihrer Wahl. Wenn Sie diesen Bucket beispielsweise mit einem Verzeichnis namens my-bucket darstellen möchten, legen Sie den Bereitstellungspfad auf /mnt/disks/my-bucket fest.

C++

C++

Weitere Informationen finden Sie in der Referenzdokumentation zur Batch C++ API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Batch zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

#include "google/cloud/batch/v1/batch_client.h"

  [](std::string const& project_id, std::string const& location_id,
     std::string const& job_id, std::string const& bucket_name) {
    // Initialize the request; start with the fields that depend on the sample
    // input.
    google::cloud::batch::v1::CreateJobRequest request;
    request.set_parent("projects/" + project_id + "/locations/" + location_id);
    request.set_job_id(job_id);
    // Most of the job description is fixed in this example; use a string to
    // initialize it, and then override the GCS remote path.
    auto constexpr kText = R"pb(
      task_groups {
        task_count: 4
        task_spec {
          compute_resource { cpu_milli: 500 memory_mib: 16 }
          max_retry_count: 2
          max_run_duration { seconds: 3600 }
          runnables {
            script {
              text: "echo Hello world from task ${BATCH_TASK_INDEX}. >> /mnt/share/output_task_${BATCH_TASK_INDEX}.txt"
            }
          }
          volumes { mount_path: "/mnt/share" }
        }
      }
      allocation_policy {
        instances {
          policy { machine_type: "e2-standard-4" provisioning_model: STANDARD }
        }
      }
      labels { key: "env" value: "testing" }
      labels { key: "type" value: "script" }
      logs_policy { destination: CLOUD_LOGGING }
    )pb";
    auto* job = request.mutable_job();
    if (!google::protobuf::TextFormat::ParseFromString(kText, job)) {
      throw std::runtime_error("Error parsing Job description");
    }
    job->mutable_task_groups(0)
        ->mutable_task_spec()
        ->mutable_volumes(0)
        ->mutable_gcs()
        ->set_remote_path(bucket_name);
    // Create a client and issue the request.
    auto client = google::cloud::batch_v1::BatchServiceClient(
        google::cloud::batch_v1::MakeBatchServiceConnection());
    auto response = client.CreateJob(request);
    if (!response) throw std::move(response).status();
    std::cout << "Job : " << response->DebugString() << "\n";
  }

Go

Go

Weitere Informationen finden Sie in der Referenzdokumentation zur Batch Go API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Batch zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

import (
	"context"
	"fmt"
	"io"

	batch "cloud.google.com/go/batch/apiv1"
	"cloud.google.com/go/batch/apiv1/batchpb"
	durationpb "google.golang.org/protobuf/types/known/durationpb"
)

// Creates and runs a job that executes the specified script
func createScriptJobWithBucket(w io.Writer, projectID, region, jobName, bucketName string) error {
	// projectID := "your_project_id"
	// region := "us-central1"
	// jobName := "some-job"
	// jobName := "some-bucket"

	ctx := context.Background()
	batchClient, err := batch.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer batchClient.Close()

	// Define what will be done as part of the job.
	command := &batchpb.Runnable_Script_Text{
		Text: "echo Hello world from task ${BATCH_TASK_INDEX}. >> /mnt/share/output_task_${BATCH_TASK_INDEX}.txt",
	}

	// Specify the Google Cloud Storage bucket to mount
	volume := &batchpb.Volume{
		Source: &batchpb.Volume_Gcs{
			Gcs: &batchpb.GCS{
				RemotePath: bucketName,
			},
		},
		MountPath:    "/mnt/share",
		MountOptions: []string{},
	}

	// We can specify what resources are requested by each task.
	resources := &batchpb.ComputeResource{
		// CpuMilli is milliseconds per cpu-second. This means the task requires 50% of a single CPUs.
		CpuMilli:  500,
		MemoryMib: 16,
	}

	taskSpec := &batchpb.TaskSpec{
		Runnables: []*batchpb.Runnable{{
			Executable: &batchpb.Runnable_Script_{
				Script: &batchpb.Runnable_Script{Command: command},
			},
		}},
		ComputeResource: resources,
		MaxRunDuration: &durationpb.Duration{
			Seconds: 3600,
		},
		MaxRetryCount: 2,
		Volumes:       []*batchpb.Volume{volume},
	}

	// Tasks are grouped inside a job using TaskGroups.
	taskGroups := []*batchpb.TaskGroup{
		{
			TaskCount: 4,
			TaskSpec:  taskSpec,
		},
	}

	// Policies are used to define on what kind of virtual machines the tasks will run on.
	// In this case, we tell the system to use "e2-standard-4" machine type.
	// Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
	allocationPolicy := &batchpb.AllocationPolicy{
		Instances: []*batchpb.AllocationPolicy_InstancePolicyOrTemplate{{
			PolicyTemplate: &batchpb.AllocationPolicy_InstancePolicyOrTemplate_Policy{
				Policy: &batchpb.AllocationPolicy_InstancePolicy{
					MachineType: "e2-standard-4",
				},
			},
		}},
	}

	// We use Cloud Logging as it's an out of the box available option
	logsPolicy := &batchpb.LogsPolicy{
		Destination: batchpb.LogsPolicy_CLOUD_LOGGING,
	}

	jobLabels := map[string]string{"env": "testing", "type": "script"}

	// The job's parent is the region in which the job will run
	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, region)

	job := batchpb.Job{
		TaskGroups:       taskGroups,
		AllocationPolicy: allocationPolicy,
		Labels:           jobLabels,
		LogsPolicy:       logsPolicy,
	}

	req := &batchpb.CreateJobRequest{
		Parent: parent,
		JobId:  jobName,
		Job:    &job,
	}

	created_job, err := batchClient.CreateJob(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to create job: %w", err)
	}

	fmt.Fprintf(w, "Job created: %v\n", created_job)

	return nil
}

Java

Java

Weitere Informationen finden Sie in der Referenzdokumentation zur Batch Java API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Batch zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

import com.google.cloud.batch.v1.AllocationPolicy;
import com.google.cloud.batch.v1.AllocationPolicy.InstancePolicy;
import com.google.cloud.batch.v1.AllocationPolicy.InstancePolicyOrTemplate;
import com.google.cloud.batch.v1.BatchServiceClient;
import com.google.cloud.batch.v1.ComputeResource;
import com.google.cloud.batch.v1.CreateJobRequest;
import com.google.cloud.batch.v1.GCS;
import com.google.cloud.batch.v1.Job;
import com.google.cloud.batch.v1.LogsPolicy;
import com.google.cloud.batch.v1.LogsPolicy.Destination;
import com.google.cloud.batch.v1.Runnable;
import com.google.cloud.batch.v1.Runnable.Script;
import com.google.cloud.batch.v1.TaskGroup;
import com.google.cloud.batch.v1.TaskSpec;
import com.google.cloud.batch.v1.Volume;
import com.google.protobuf.Duration;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateWithMountedBucket {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";

    // Name of the region you want to use to run the job. Regions that are
    // available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
    String region = "europe-central2";

    // The name of the job that will be created.
    // It needs to be unique for each project and region pair.
    String jobName = "JOB_NAME";

    // Name of the bucket to be mounted for your Job.
    String bucketName = "BUCKET_NAME";

    createScriptJobWithBucket(projectId, region, jobName, bucketName);
  }

  // This method shows how to create a sample Batch Job that will run
  // a simple command on Cloud Compute instances.
  public static void createScriptJobWithBucket(String projectId, String region, String jobName,
      String bucketName)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `batchServiceClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (BatchServiceClient batchServiceClient = BatchServiceClient.create()) {

      // Define what will be done as part of the job.
      Runnable runnable =
          Runnable.newBuilder()
              .setScript(
                  Script.newBuilder()
                      .setText(
                          "echo Hello world from task ${BATCH_TASK_INDEX}. >> "
                              + "/mnt/share/output_task_${BATCH_TASK_INDEX}.txt")
                      // You can also run a script from a file. Just remember, that needs to be a
                      // script that's already on the VM that will be running the job.
                      // Using setText() and setPath() is mutually exclusive.
                      // .setPath("/tmp/test.sh")
                      .build())
              .build();

      Volume volume = Volume.newBuilder()
          .setGcs(GCS.newBuilder()
              .setRemotePath(bucketName)
              .build())
          .setMountPath("/mnt/share")
          .build();

      // We can specify what resources are requested by each task.
      ComputeResource computeResource =
          ComputeResource.newBuilder()
              // In milliseconds per cpu-second. This means the task requires 50% of a single CPUs.
              .setCpuMilli(500)
              // In MiB.
              .setMemoryMib(16)
              .build();

      TaskSpec task =
          TaskSpec.newBuilder()
              // Jobs can be divided into tasks. In this case, we have only one task.
              .addRunnables(runnable)
              .addVolumes(volume)
              .setComputeResource(computeResource)
              .setMaxRetryCount(2)
              .setMaxRunDuration(Duration.newBuilder().setSeconds(3600).build())
              .build();

      // Tasks are grouped inside a job using TaskGroups.
      // Currently, it's possible to have only one task group.
      TaskGroup taskGroup = TaskGroup.newBuilder().setTaskCount(4).setTaskSpec(task).build();

      // Policies are used to define on what kind of virtual machines the tasks will run on.
      // In this case, we tell the system to use "e2-standard-4" machine type.
      // Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
      InstancePolicy instancePolicy =
          InstancePolicy.newBuilder().setMachineType("e2-standard-4").build();

      AllocationPolicy allocationPolicy =
          AllocationPolicy.newBuilder()
              .addInstances(InstancePolicyOrTemplate.newBuilder().setPolicy(instancePolicy).build())
              .build();

      Job job =
          Job.newBuilder()
              .addTaskGroups(taskGroup)
              .setAllocationPolicy(allocationPolicy)
              .putLabels("env", "testing")
              .putLabels("type", "script")
              .putLabels("mount", "bucket")
              // We use Cloud Logging as it's an out of the box available option.
              .setLogsPolicy(
                  LogsPolicy.newBuilder().setDestination(Destination.CLOUD_LOGGING).build())
              .build();

      CreateJobRequest createJobRequest =
          CreateJobRequest.newBuilder()
              // The job's parent is the region in which the job will run.
              .setParent(String.format("projects/%s/locations/%s", projectId, region))
              .setJob(job)
              .setJobId(jobName)
              .build();

      Job result =
          batchServiceClient
              .createJobCallable()
              .futureCall(createJobRequest)
              .get(5, TimeUnit.MINUTES);

      System.out.printf("Successfully created the job: %s", result.getName());
    }
  }
}

Node.js

Node.js

Weitere Informationen finden Sie in der Referenzdokumentation zur Batch Node.js API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Batch zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
/**
 * The region you want to the job to run in. The regions that support Batch are listed here:
 * https://cloud.google.com/batch/docs/get-started#locations
 */
// const region = 'us-central-1';
/**
 * The name of the job that will be created.
 * It needs to be unique for each project and region pair.
 */
// const jobName = 'YOUR_JOB_NAME';
/**
 * The name of the bucket to be mounted.
 */
// const bucketName = 'YOUR_BUCKET_NAME';

// Imports the Batch library
const batchLib = require('@google-cloud/batch');
const batch = batchLib.protos.google.cloud.batch.v1;

// Instantiates a client
const batchClient = new batchLib.v1.BatchServiceClient();

// Define what will be done as part of the job.
const task = new batch.TaskSpec();
const runnable = new batch.Runnable();
runnable.script = new batch.Runnable.Script();
runnable.script.text =
  'echo Hello world from task ${BATCH_TASK_INDEX}. >> /mnt/share/output_task_${BATCH_TASK_INDEX}.txt';
// You can also run a script from a file. Just remember, that needs to be a script that's
// already on the VM that will be running the job. Using runnable.script.text and runnable.script.path is mutually
// exclusive.
// runnable.script.path = '/tmp/test.sh'
task.runnables = [runnable];

const gcsBucket = new batch.GCS();
gcsBucket.remotePath = bucketName;
const gcsVolume = new batch.Volume();
gcsVolume.gcs = gcsBucket;
gcsVolume.mountPath = '/mnt/share';
task.volumes = [gcsVolume];

// We can specify what resources are requested by each task.
const resources = new batch.ComputeResource();
resources.cpuMilli = 2000; // in milliseconds per cpu-second. This means the task requires 2 whole CPUs.
resources.memoryMib = 16;
task.computeResource = resources;

task.maxRetryCount = 2;
task.maxRunDuration = {seconds: 3600};

// Tasks are grouped inside a job using TaskGroups.
const group = new batch.TaskGroup();
group.taskCount = 4;
group.taskSpec = task;

// Policies are used to define on what kind of virtual machines the tasks will run on.
// In this case, we tell the system to use "e2-standard-4" machine type.
// Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
const allocationPolicy = new batch.AllocationPolicy();
const policy = new batch.AllocationPolicy.InstancePolicy();
policy.machineType = 'e2-standard-4';
const instances = new batch.AllocationPolicy.InstancePolicyOrTemplate();
instances.policy = policy;
allocationPolicy.instances = [instances];

const job = new batch.Job();
job.name = jobName;
job.taskGroups = [group];
job.allocationPolicy = allocationPolicy;
job.labels = {env: 'testing', type: 'script'};
// We use Cloud Logging as it's an option available out of the box
job.logsPolicy = new batch.LogsPolicy();
job.logsPolicy.destination = batch.LogsPolicy.Destination.CLOUD_LOGGING;

// The job's parent is the project and region in which the job will run
const parent = `projects/${projectId}/locations/${region}`;

async function callCreateJob() {
  // Construct request
  const request = {
    parent,
    jobId: jobName,
    job,
  };

  // Run request
  const response = await batchClient.createJob(request);
  console.log(response);
}

await callCreateJob();

Python

Python

Weitere Informationen finden Sie in der Referenzdokumentation zur Batch Python API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Batch zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

from google.cloud import batch_v1


def create_script_job_with_bucket(
    project_id: str, region: str, job_name: str, bucket_name: str
) -> batch_v1.Job:
    """
    This method shows how to create a sample Batch Job that will run
    a simple command on Cloud Compute instances.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        region: name of the region you want to use to run the job. Regions that are
            available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
        job_name: the name of the job that will be created.
            It needs to be unique for each project and region pair.
        bucket_name: name of the bucket to be mounted for your Job.

    Returns:
        A job object representing the job created.
    """
    client = batch_v1.BatchServiceClient()

    # Define what will be done as part of the job.
    task = batch_v1.TaskSpec()
    runnable = batch_v1.Runnable()
    runnable.script = batch_v1.Runnable.Script()
    runnable.script.text = "echo Hello world from task ${BATCH_TASK_INDEX}. >> /mnt/share/output_task_${BATCH_TASK_INDEX}.txt"
    task.runnables = [runnable]

    gcs_bucket = batch_v1.GCS()
    gcs_bucket.remote_path = bucket_name
    gcs_volume = batch_v1.Volume()
    gcs_volume.gcs = gcs_bucket
    gcs_volume.mount_path = "/mnt/share"
    task.volumes = [gcs_volume]

    # We can specify what resources are requested by each task.
    resources = batch_v1.ComputeResource()
    resources.cpu_milli = 500  # in milliseconds per cpu-second. This means the task requires 50% of a single CPUs.
    resources.memory_mib = 16
    task.compute_resource = resources

    task.max_retry_count = 2
    task.max_run_duration = "3600s"

    # Tasks are grouped inside a job using TaskGroups.
    # Currently, it's possible to have only one task group.
    group = batch_v1.TaskGroup()
    group.task_count = 4
    group.task_spec = task

    # Policies are used to define on what kind of virtual machines the tasks will run on.
    # In this case, we tell the system to use "e2-standard-4" machine type.
    # Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
    allocation_policy = batch_v1.AllocationPolicy()
    policy = batch_v1.AllocationPolicy.InstancePolicy()
    policy.machine_type = "e2-standard-4"
    instances = batch_v1.AllocationPolicy.InstancePolicyOrTemplate()
    instances.policy = policy
    allocation_policy.instances = [instances]

    job = batch_v1.Job()
    job.task_groups = [group]
    job.allocation_policy = allocation_policy
    job.labels = {"env": "testing", "type": "script", "mount": "bucket"}
    # We use Cloud Logging as it's an out of the box available option
    job.logs_policy = batch_v1.LogsPolicy()
    job.logs_policy.destination = batch_v1.LogsPolicy.Destination.CLOUD_LOGGING

    create_request = batch_v1.CreateJobRequest()
    create_request.job = job
    create_request.job_id = job_name
    # The job's parent is the region in which the job will run
    create_request.parent = f"projects/{project_id}/locations/{region}"

    return client.create_job(create_request)

Netzwerkdateisystem verwenden

Sie können einen Job erstellen, der ein vorhandenes Netzwerkdateisystem (NFS) wie eine Filestore-Dateifreigabe verwendet, indem Sie die Google Cloud Console, die gcloud CLI oder die Batch API verwenden.

Bevor Sie einen Job erstellen, der ein NFS verwendet, müssen Sie dafür sorgen, dass die Firewall Ihres Netzwerks richtig konfiguriert ist, um Traffic zwischen den VMs Ihres Jobs und dem NFS zuzulassen. Weitere Informationen finden Sie unter Firewallregeln für Filestore konfigurieren.

Im folgenden Beispiel wird beschrieben, wie Sie einen Job erstellen, in dem ein NFS angegeben und eingebunden wird. Der Job hat auch drei Aufgaben, die jeweils ein Skript ausführen, um eine Datei im NFS mit dem Namen output_task_TASK_INDEX.txt zu erstellen, wobei TASK_INDEX der Index jeder Aufgabe ist: 0, 1 und 2.

Console

So erstellen Sie einen Job, der ein NFS verwendet, mit der Google Cloud -Konsole:

  1. Rufen Sie in der Google Cloud Console die Seite Jobliste auf.

    Zur Jobliste

  2. Klicken Sie auf Erstellen. Die Seite Batchjob erstellen wird geöffnet. Im linken Bereich ist die Seite Jobdetails ausgewählt.

  3. Konfigurieren Sie die Seite Jobdetails:

    1. Optional: Passen Sie im Feld Jobname den Jobnamen an.

      Geben Sie beispielsweise example-nfs-job ein.

    2. Konfigurieren Sie den Abschnitt Aufgabendetails:

      1. Fügen Sie im Fenster Neues Runnable mindestens ein Script oder einen Container hinzu, damit dieser Job ausgeführt werden kann.

        Führen Sie dazu z. B. folgende Schritte aus:

        1. Klicken Sie das Kästchen Script an. Ein Textfeld wird angezeigt.

        2. Geben Sie das folgende Skript in das Textfeld ein:

          echo Hello world from task ${BATCH_TASK_INDEX}. >> MOUNT_PATH/output_task_${BATCH_TASK_INDEX}.txt
          

          Ersetzen Sie MOUNT_PATH durch den Mount-Pfad, den die ausführbare Datei des Jobs für den Zugriff auf dieses NFS verwendet. Der Pfad muss mit /mnt/disks/ beginnen, gefolgt von einem Verzeichnis oder Pfad Ihrer Wahl. Wenn Sie dieses NFS beispielsweise mit einem Verzeichnis namens my-nfs darstellen möchten, legen Sie den Bereitstellungspfad auf /mnt/disks/my-nfs fest.

        3. Klicken Sie auf Fertig.

      2. Geben Sie im Feld Anzahl der Aufgaben die Anzahl der Aufgaben für diesen Job ein.

        Geben Sie beispielsweise 3 ein.

      3. Geben Sie im Feld Parallelität die Anzahl der Aufgaben ein, die gleichzeitig ausgeführt werden sollen.

        Geben Sie beispielsweise 1 (Standardeinstellung) ein.

  4. Konfigurieren Sie die Seite Zusätzliche Konfigurationen:

    1. Klicken Sie im linken Bereich auf Zusätzliche Konfigurationen. Die Seite Zusätzliche Konfigurationen wird geöffnet.

    2. Führen Sie für jeden Cloud Storage-Bucket, den Sie für diesen Job bereitstellen möchten, die folgenden Schritte aus:

      1. Klicken Sie im Bereich Speichervolume auf Neues Volume hinzufügen. Das Fenster Neues Volume wird angezeigt.

      2. Führen Sie im Fenster Neues Volume die folgenden Schritte aus:

        1. Wählen Sie im Bereich Volume-Typ die Option Network File System aus.

        2. Geben Sie im Feld File server die IP-Adresse des Servers ein, auf dem sich das in diesem Job angegebene ausführbare NFS befindet.

          Wenn Ihr NFS beispielsweise eine Filestore-Dateifreigabe ist, geben Sie die IP-Adresse der Filestore-Instanz an, die Sie durch Beschreiben der Filestore-Instanz abrufen können.

        3. Geben Sie im Feld Remote-Pfad einen Pfad ein, über den auf das NFS zugegriffen werden kann, das Sie im vorherigen Schritt angegeben haben.

          Der Pfad des NFS-Verzeichnisses muss mit einem / beginnen, gefolgt vom Stammverzeichnis des NFS.

        4. Geben Sie im Feld Bereitstellungspfad den Bereitstellungspfad zum NFS (MOUNT_PATH) ein, den Sie im vorherigen Schritt angegeben haben.

    3. Klicken Sie auf Fertig.

  5. Optional: Konfigurieren Sie die anderen Felder für diesen Job.

  6. Optional: Wenn Sie die Jobkonfiguration überprüfen möchten, klicken Sie im linken Bereich auf Vorschau.

  7. Klicken Sie auf Erstellen.

Auf der Seite Jobdetails wird der von Ihnen erstellte Job angezeigt.

gcloud

Verwenden Sie den gcloud CLI gcloud batch jobs submit, um einen Job zu erstellen, der ein NFS verwendet. Hängen Sie in der JSON-Konfigurationsdatei des Jobs das NFS im Feld volumes ein.

  1. Erstellen Sie eine package.json-Datei mit folgendem Inhalt:

    {
        "taskGroups": [
            {
                "taskSpec": {
                    "runnables": [
                        {
                            "script": {
                                "text": "echo Hello world from task ${BATCH_TASK_INDEX}. >> MOUNT_PATH/output_task_${BATCH_TASK_INDEX}.txt"
                            }
                        }
                    ],
                    "volumes": [
                        {
                            "nfs": {
                                "server": "NFS_IP_ADDRESS",
                                "remotePath": "NFS_PATH"
                            },
                            "mountPath": "MOUNT_PATH"
                        }
                    ]
                },
                "taskCount": 3
            }
        ],
        "logsPolicy": {
            "destination": "CLOUD_LOGGING"
        }
    }
    

    Ersetzen Sie Folgendes:

    • NFS_IP_ADDRESS: Die IP-Adresse des NFS. Wenn Ihr NFS beispielsweise eine Filestore-Dateifreigabe ist, geben Sie die IP-Adresse der Filestore-Instanz an, die Sie durch Beschreiben der Filestore-Instanz abrufen können.
    • NFS_PATH: Der Pfad des NFS-Verzeichnisses, auf das dieser Job zugreifen soll. Er muss mit einem / gefolgt vom Stammverzeichnis des NFS beginnen. Für eine Filestore-Dateifreigabe mit dem Namen FILE_SHARE_NAME stellt der Pfad /FILE_SHARE_NAME beispielsweise das Stammverzeichnis der Dateifreigabe und der Pfad /FILE_SHARE_NAME/subdirectory das Unterverzeichnis subdirectory dar.
    • MOUNT_PATH: Der Bereitstellungspfad, über den die Runnables des Jobs auf dieses NFS zugreifen. Der Pfad muss mit /mnt/disks/ beginnen, gefolgt von einem Verzeichnis oder Pfad Ihrer Wahl. Wenn Sie dieses NFS-Volume beispielsweise mit einem Verzeichnis namens my-nfs darstellen möchten, legen Sie den Bereitstellungspfad auf /mnt/disks/my-nfs fest.
  2. Führen Sie dazu diesen Befehl aus:

    gcloud batch jobs submit JOB_NAME \
      --location LOCATION \
      --config JSON_CONFIGURATION_FILE
    

    Ersetzen Sie Folgendes:

    • JOB_NAME: Der Name des Jobs.
    • LOCATION: Der Standort des Jobs.
    • JSON_CONFIGURATION_FILE: der Pfad zu einer JSON-Datei mit den Konfigurationsdetails des Jobs.

API

Wenn Sie mit der Batch API einen Job erstellen möchten, der ein NFS verwendet, verwenden Sie die jobs.create-Methode und hängen Sie das NFS im Feld volumes ein.

POST https://batch.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/jobs?job_id=JOB_NAME

   {
    "taskGroups": [
        {
            "taskSpec": {
                "runnables": [
                    {
                        "script": {
                            "text": "echo Hello world from task ${BATCH_TASK_INDEX}. >> MOUNT_PATH/output_task_${BATCH_TASK_INDEX}.txt"
                        }
                    }
                ],
                "volumes": [
                    {
                        "nfs": {
                            "server": "NFS_IP_ADDRESS",
                            "remotePath": "NFS_PATH"
                        },
                        "mountPath": "MOUNT_PATH"
                    }
                ]
            },
            "taskCount": 3
        }
    ],
    "logsPolicy": {
        "destination": "CLOUD_LOGGING"
    }
}

Ersetzen Sie Folgendes:

  • PROJECT_ID: die Projekt-ID Ihres Projekts.
  • LOCATION: Der Standort des Jobs.
  • JOB_NAME: Der Name des Jobs.
  • NFS_IP_ADDRESS: die IP-Adresse des Network File System. Wenn Ihr NFS beispielsweise eine Filestore-Dateifreigabe ist, geben Sie die IP-Adresse der Filestore-Instanz an, die Sie durch Beschreiben der Filestore-Instanz abrufen können.
  • NFS_PATH: Der Pfad des NFS-Verzeichnisses, auf das dieser Job zugreifen soll. Er muss mit einem / gefolgt vom Stammverzeichnis des NFS beginnen. Für eine Filestore-Dateifreigabe mit dem Namen FILE_SHARE_NAME stellt der Pfad /FILE_SHARE_NAME beispielsweise das Stammverzeichnis der Dateifreigabe und der Pfad /FILE_SHARE_NAME/subdirectory ein Unterverzeichnis dar.
  • MOUNT_PATH: Der Bereitstellungspfad, über den die Runnables des Jobs auf dieses NFS zugreifen. Der Pfad muss mit /mnt/disks/ beginnen, gefolgt von einem Verzeichnis oder Pfad Ihrer Wahl. Wenn Sie dieses NFS-Volume beispielsweise mit einem Verzeichnis namens my-nfs darstellen möchten, legen Sie den Bereitstellungspfad auf /mnt/disks/my-nfs fest.

Java


import com.google.cloud.batch.v1.AllocationPolicy;
import com.google.cloud.batch.v1.BatchServiceClient;
import com.google.cloud.batch.v1.ComputeResource;
import com.google.cloud.batch.v1.CreateJobRequest;
import com.google.cloud.batch.v1.Job;
import com.google.cloud.batch.v1.LogsPolicy;
import com.google.cloud.batch.v1.NFS;
import com.google.cloud.batch.v1.Runnable;
import com.google.cloud.batch.v1.TaskGroup;
import com.google.cloud.batch.v1.TaskSpec;
import com.google.cloud.batch.v1.Volume;
import com.google.protobuf.Duration;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateScriptJobWithNfs {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";

    // Name of the region you want to use to run the job. Regions that are
    // available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
    String region = "europe-central2";

    // The name of the job that will be created.
    // It needs to be unique for each project and region pair.
    String jobName = "JOB_NAME";

    // The path of the NFS directory that you want this job to access.
    String nfsPath = "NFS_PATH";
    // The IP address of the Network File System.
    String nfsIpAddress = "NFS_IP_ADDRESS";

    createScriptJobWithNfs(projectId, region, jobName, nfsPath, nfsIpAddress);
  }

  // This method shows how to create a batch script job that specifies and mounts a NFS.
  public static Job createScriptJobWithNfs(String projectId, String region, String jobName,
                                            String nfsPath, String nfsIpAddress)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (BatchServiceClient batchServiceClient = BatchServiceClient.create()) {

      // Define what will be done as part of the job.
      Runnable runnable =
          Runnable.newBuilder()
              .setScript(
                  Runnable.Script.newBuilder()
                      .setText(
                          "echo Hello world from task ${BATCH_TASK_INDEX}. >> "
                              + "/mnt/share/output_task_${BATCH_TASK_INDEX}.txt")
                      // You can also run a script from a file. Just remember, that needs to be a
                      // script that's already on the VM that will be running the job.
                      // Using setText() and setPath() is mutually exclusive.
                      // .setPath("/tmp/test.sh")
                      .build())
              .build();

      // Describes a volume and parameters for it to be mounted to a VM.
      Volume volume = Volume.newBuilder()
          .setNfs(NFS.newBuilder()
              .setServer(nfsIpAddress)
              .setRemotePath(nfsPath)
              .build())
          .setMountPath("/mnt/share")
          .build();

      // We can specify what resources are requested by each task.
      ComputeResource computeResource =
          ComputeResource.newBuilder()
              // In milliseconds per cpu-second. This means the task requires 50% of a single CPUs.
              .setCpuMilli(500)
              // In MiB.
              .setMemoryMib(16)
              .build();

      TaskSpec task =
          TaskSpec.newBuilder()
              // Jobs can be divided into tasks. In this case, we have only one task.
              .addRunnables(runnable)
              .addVolumes(volume)
              .setComputeResource(computeResource)
              .setMaxRetryCount(2)
              .setMaxRunDuration(Duration.newBuilder().setSeconds(3600).build())
              .build();

      // Tasks are grouped inside a job using TaskGroups.
      // Currently, it's possible to have only one task group.
      TaskGroup taskGroup = TaskGroup.newBuilder().setTaskCount(4).setTaskSpec(task).build();

      // Policies are used to define on what kind of virtual machines the tasks will run on.
      // In this case, we tell the system to use "e2-standard-4" machine type.
      // Read more about machine types here:
      // https://cloud.google.com/compute/docs/machine-types
      AllocationPolicy.InstancePolicy instancePolicy =
          AllocationPolicy.InstancePolicy.newBuilder().setMachineType("e2-standard-4").build();

      AllocationPolicy allocationPolicy =
          AllocationPolicy.newBuilder()
              .addInstances(AllocationPolicy.InstancePolicyOrTemplate.newBuilder()
                      .setPolicy(instancePolicy).build())
              .build();

      Job job =
          Job.newBuilder()
              .addTaskGroups(taskGroup)
              .setAllocationPolicy(allocationPolicy)
              .putLabels("env", "testing")
              .putLabels("type", "script")
              .putLabels("mount", "bucket")
              // We use Cloud Logging as it's an out of the box available option.
              .setLogsPolicy(LogsPolicy.newBuilder()
                      .setDestination(LogsPolicy.Destination.CLOUD_LOGGING).build())
              .build();

      CreateJobRequest createJobRequest =
          CreateJobRequest.newBuilder()
              // The job's parent is the region in which the job will run.
              .setParent(String.format("projects/%s/locations/%s", projectId, region))
              .setJob(job)
              .setJobId(jobName)
              .build();

      Job result =
          batchServiceClient
              .createJobCallable()
              .futureCall(createJobRequest)
              .get(5, TimeUnit.MINUTES);

      System.out.printf("Successfully created the job: %s", result.getName());

      return result;
    }
  }
}

Node.js

// Imports the Batch library
const batchLib = require('@google-cloud/batch');
const batch = batchLib.protos.google.cloud.batch.v1;

// Instantiates a client
const batchClient = new batchLib.v1.BatchServiceClient();

/**
 * TODO(developer): Update these variables before running the sample.
 */
// Project ID or project number of the Google Cloud project you want to use.
const projectId = await batchClient.getProjectId();
// Name of the region you want to use to run the job. Regions that are
// available for Batch are listed on: https://cloud.google.com/batch/docs/get-started#locations
const region = 'europe-central2';
// The name of the job that will be created.
// It needs to be unique for each project and region pair.
const jobName = 'batch-nfs-job';
// The path of the NFS directory that you want this job to access.
const nfsPath = '/your_nfs_path';
// The IP address of the Network File System.
const nfsIpAddress = '0.0.0.0';
// The mount path that the job's tasks use to access the NFS.
const mountPath = '/mnt/disks';

// Define what will be done as part of the job.
const runnable = new batch.Runnable({
  script: new batch.Runnable.Script({
    commands: [
      '-c',
      'echo Hello world from task ${BATCH_TASK_INDEX}. >> ' +
        '/mnt/share/output_task_${BATCH_TASK_INDEX}.txt',
    ],
  }),
});

// Define a volume that uses NFS.
const volume = new batch.Volume({
  nfs: new batch.NFS({
    server: nfsIpAddress,
    remotePath: nfsPath,
  }),
  mountPath,
});

// Specify what resources are requested by each task.
const computeResource = new batch.ComputeResource({
  // In milliseconds per cpu-second. This means the task requires 50% of a single CPUs.
  cpuMilli: 500,
  // In MiB.
  memoryMib: 16,
});

const task = new batch.TaskSpec({
  runnables: [runnable],
  volumes: [volume],
  computeResource,
  maxRetryCount: 2,
  maxRunDuration: {seconds: 3600},
});

// Tasks are grouped inside a job using TaskGroups.
const group = new batch.TaskGroup({
  taskCount: 3,
  taskSpec: task,
});

// Policies are used to define on what kind of virtual machines the tasks will run on.
// In this case, we tell the system to use "e2-standard-4" machine type.
// Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
const instancePolicy = new batch.AllocationPolicy.InstancePolicy({
  machineType: 'e2-standard-4',
});

const allocationPolicy = new batch.AllocationPolicy.InstancePolicyOrTemplate({
  instances: [{policy: instancePolicy}],
});

const job = new batch.Job({
  name: jobName,
  taskGroups: [group],
  allocationPolicy,
  labels: {env: 'testing', type: 'script'},
  // We use Cloud Logging as it's an option available out of the box
  logsPolicy: new batch.LogsPolicy({
    destination: batch.LogsPolicy.Destination.CLOUD_LOGGING,
  }),
});

// The job's parent is the project and region in which the job will run
const parent = `projects/${projectId}/locations/${region}`;

async function callCreateBatchNfsJob() {
  // Construct request
  const request = {
    parent,
    jobId: jobName,
    job,
  };

  // Run request
  const [response] = await batchClient.createJob(request);
  console.log(JSON.stringify(response));
}

await callCreateBatchNfsJob();

Python

from google.cloud import batch_v1


def create_job_with_network_file_system(
    project_id: str,
    region: str,
    job_name: str,
    mount_path: str,
    nfs_ip_address: str,
    nfs_path: str,
) -> batch_v1.Job:
    """
    Creates a Batch job with status events that mounts a Network File System (NFS).
    Function mounts an NFS volume using the provided NFS server, IP address and path.

    Args:
        project_id (str): project ID or project number of the Cloud project you want to use.
        region (str): name of the region you want to use to run the job. Regions that are
            available for Batch are listed on: https://cloud.google.com/batch/docs/locations
        job_name (str): the name of the job that will be created.
            It needs to be unique for each project and region pair.
        mount_path (str): The mount path that the job's tasks use to access the NFS.
        nfs_ip_address (str): The IP address of the NFS server (e.g., Filestore instance).
            Documentation on how to create a
            Filestore instance is available here: https://cloud.google.com/filestore/docs/create-instance-gcloud
        nfs_path (str): The path of the NFS directory that the job accesses.
            The path must start with a / followed by the root directory of the NFS.

    Returns:
        batch_v1.Job: The created Batch job object containing configuration details.
    """
    client = batch_v1.BatchServiceClient()

    # Create a runnable with a script that writes a message to a file
    runnable = batch_v1.Runnable()
    runnable.script = batch_v1.Runnable.Script()
    runnable.script.text = f"echo Hello world from task ${{BATCH_TASK_INDEX}}. >> {mount_path}/output_task_${{BATCH_TASK_INDEX}}.txt"

    # Define a volume that uses NFS
    volume = batch_v1.Volume()
    volume.nfs = batch_v1.NFS(server=nfs_ip_address, remote_path=nfs_path)
    volume.mount_path = mount_path

    # Create a task specification and assign the runnable and volume to it
    task = batch_v1.TaskSpec()
    task.runnables = [runnable]
    task.volumes = [volume]

    # Specify what resources are requested by each task.
    resources = batch_v1.ComputeResource()
    resources.cpu_milli = 2000  # in milliseconds per cpu-second. This means the task requires 2 whole CPUs.
    resources.memory_mib = 16  # in MiB
    task.compute_resource = resources

    task.max_retry_count = 2
    task.max_run_duration = "3600s"

    # Create a task group and assign the task specification to it
    group = batch_v1.TaskGroup()
    group.task_count = 1
    group.task_spec = task

    # Policies are used to define on what kind of virtual machines the tasks will run on.
    # In this case, we tell the system to use "e2-standard-4" machine type.
    # Read more about machine types here: https://cloud.google.com/compute/docs/machine-types
    policy = batch_v1.AllocationPolicy.InstancePolicy()
    policy.machine_type = "e2-standard-4"
    instances = batch_v1.AllocationPolicy.InstancePolicyOrTemplate()
    instances.policy = policy
    allocation_policy = batch_v1.AllocationPolicy()
    allocation_policy.instances = [instances]

    # Create the job and assign the task group and allocation policy to it
    job = batch_v1.Job()
    job.task_groups = [group]
    job.allocation_policy = allocation_policy
    job.labels = {"env": "testing", "type": "container"}
    # We use Cloud Logging as it's an out of the box available option
    job.logs_policy = batch_v1.LogsPolicy()
    job.logs_policy.destination = batch_v1.LogsPolicy.Destination.CLOUD_LOGGING

    # Create the job request and set the job and job ID
    create_request = batch_v1.CreateJobRequest()
    create_request.job = job
    create_request.job_id = job_name
    # The job's parent is the region in which the job will run
    create_request.parent = f"projects/{project_id}/locations/{region}"

    return client.create_job(create_request)

Nächste Schritte