Sediakan simpul komputasi Linux di kumpulan Batch

Anda dapat menggunakan Azure Batch untuk menjalankan beban kerja komputasi paralel pada komputer virtual Linux dan Windows. Artikel ini menjelaskan cara membuat kumpulan simpul komputasi Linux di layanan Batch dengan menggunakan Batch Python dan Azure. Pustaka klien Compute.Batch.

Konfigurasi Mesin Virtual

Ketika membuat kumpulan simpul komputasi di Batch, Anda memiliki dua opsi untuk memilih ukuran simpul dan sistem operasi: Konfigurasi Layanan Cloud dan Konfigurasi Komputer Virtual. Kumpulan Konfigurasi Komputer Virtual terdiri dari VM Azure, yang dapat dibuat dari citra Linux atau Windows. Ketika membuat kumpulan dengan Konfigurasi Komputer Virtual, tentukan ukuran simpul komputasi yang tersedia, referensi citra komputer virtual yang akan diinstal pada simpul, dan agen simpul Batch SKU (program yang berjalan pada setiap simpul dan menyediakan antarmuka antara simpul dan layanan Batch).

Referensi citra mesin virtual

Layanan Batch menggunakan rangkaian skala komputer virtual untuk menyediakan simpul komputasi dalam Konfigurasi Komputer Virtual. Anda dapat menentukan gambar dari Marketplace Azure, atau menggunakan Azure Compute Gallery untuk menyiapkan gambar kustom.

Saat membuat referensi citra komputer virtual, Anda harus menentukan properti berikut:

Properti referensi gambar Contoh
Publisher kanonikal
Penawaran 0001-com-ubuntu-server-focal
SKU 20_04-lts
Versi terbaru

Tips

Anda dapat mempelajari selengkapnya tentang properti ini dan cara menentukan citra Marketplace di Cari citra Linux VM di Marketplace Azure dengan Azure CLI. Harap diperhatikan bahwa beberapa image Marketplace saat ini belum kompatibel dengan Batch.

Daftar citra komputer virtual

Tidak semua image Marketplace kompatibel dengan agen node Batch yang saat ini tersedia. Untuk membuat daftar semua image komputer virtual Marketplace yang didukung untuk layanan Batch beserta SKU agen node yang terkait, gunakan list_supported_images (Python), BatchClient.GetSupportedImagesAsync (Azure.Compute.Batch), atau API yang setara dalam SDK bahasa lain.

SKU agen simpul

Agen simpul Batch adalah program yang berjalan pada setiap simpul di kumpulan dan menyediakan antarmuka command-and-control antara simpul dan layanan Batch. Ada berbagai implementasi agen node yang dikenal sebagai SKU untuk sistem operasi yang berbeda. Pada dasarnya, ketika Anda membuat Konfigurasi Komputer Virtual, tentukan referensi citra komputer virtual terlebih dahulu, lalu tentukan agen simpul untuk diinstal pada citra. Biasanya, setiap agen simpul SKU kompatibel dengan beberapa citra komputer virtual. Untuk melihat SKU agen node yang didukung dan kompatibilitas image mesin virtual, Anda dapat menggunakan perintah Azure Batch CLI:

az batch pool supported-images list

Untuk informasi selengkapnya, Anda dapat merujuk ke Akun - Daftar Gambar yang Didukung - REST API (layanan Azure Batch) | Microsoft Docs.

Buat kumpulan Linux: Batch Python

Cuplikan kode berikut ini menunjukkan contoh cara menggunakan Microsoft Azure Batch Client Library for Python untuk membuat kumpulan simpul komputasi Ubuntu Server. Untuk detail selengkapnya tentang modul Batch Python, lihat dokumentasi referensi.

Cuplikan ini membuat BatchVmImageReference secara eksplisit dan menentukan setiap propertinya (penerbit, penawaran, SKU, versi). Namun, dalam kode produksi, kami menyarankan agar Anda menggunakan metode list_supported_images untuk memilih salah satu dari kombinasi SKU image dan agen node yang tersedia saat runtime.

# Import the required modules from the
# Azure Batch Client Library for Python
from azure.batch import BatchClient, models
from azure.core.credentials import AzureNamedKeyCredential

# Specify Batch account credentials
account = "<batch-account-name>"
key = "<batch-account-key>"
account_endpoint = "<batch-account-url>"

# Pool settings
pool_id = "LinuxNodesSamplePoolPython"
vm_size = "STANDARD_D2_V3"
node_count = 1

# Initialize the Batch client
creds = AzureNamedKeyCredential(account, key)
client = BatchClient(endpoint=account_endpoint, credential=creds)

# Configure the start task for the pool
start_task = models.BatchStartTask(
    command_line="printenv AZ_BATCH_NODE_STARTUP_DIR",
    user_identity=models.UserIdentity(
        auto_user=models.AutoUserSpecification(
            elevation_level=models.ElevationLevel.ADMIN,
            scope=models.AutoUserScope.POOL,
        )
    ),
)

# Create an ImageReference which specifies the Marketplace
# virtual machine image to install on the nodes
ir = models.BatchVmImageReference(
    publisher="canonical",
    offer="0001-com-ubuntu-server-focal",
    sku="20_04-lts",
    version="latest")

# Create the VirtualMachineConfiguration, specifying
# the VM image reference and the Batch node agent
# to install on the node
vmc = models.VirtualMachineConfiguration(
    image_reference=ir,
    node_agent_sku_id="batch.node.ubuntu 20.04")

# Create the unbound pool
new_pool = models.BatchPoolCreateOptions(
    id=pool_id,
    vm_size=vm_size,
    target_dedicated_nodes=node_count,
    virtual_machine_configuration=vmc,
    start_task=start_task,
)

# Create pool in the Batch service
client.create_pool(pool=new_pool)

Seperti disebutkan sebelumnya, kami menyarankan untuk menggunakan metode list_supported_images guna memilih secara dinamis dari kombinasi image agen node/Marketplace yang saat ini didukung (alih-alih membuat BatchVmImageReference secara eksplisit). Cuplikan Python berikut menunjukkan cara menggunakan metode ini.

# Get the list of supported images from the Batch service
images = list(client.list_supported_images())

# Obtain the desired image reference
image = None
for img in images:
  if (img.image_reference.publisher.lower() == "canonical" and
        img.image_reference.offer.lower() == "0001-com-ubuntu-server-focal" and
        img.image_reference.sku.lower() == "20_04-lts"):
    image = img
    break

if image is None:
  raise RuntimeError('invalid image reference for desired configuration')

# Create the VirtualMachineConfiguration, specifying the VM image
# reference and the Batch node agent to be installed on the node
vmc = models.VirtualMachineConfiguration(
    image_reference=image.image_reference,
    node_agent_sku_id=image.node_agent_sku_id)

Buat kumpulan Linux: Batch .NET

Cuplikan kode berikut menunjukkan contoh penggunaan pustaka klien Azure.Compute.Batch dan Azure.ResourceManager.Batch untuk membuat kumpulan node komputasi Ubuntu Server. Untuk detail selengkapnya, lihat dokumentasi referensi.

Cuplikan kode berikut menggunakan metode BatchClient.GetSupportedImages untuk memilih kombinasi image Marketplace dan SKU agen node dari daftar yang saat ini didukung. Teknik ini direkomendasikan, karena daftar kombinasi yang didukung dapat berubah dari waktu ke waktu. Pada umumnya, kombinasi yang didukung ditambahkan.

// Pool settings
const string poolId = "LinuxNodesSamplePoolDotNet";
const string vmSize = "STANDARD_D2_V3";
const int nodeCount = 1;

// Obtain a collection of all available node agent SKUs.
// This allows us to select from a list of supported
// VM image/node agent combinations.
List<BatchSupportedImage> images = new List<BatchSupportedImage>();
await foreach (BatchSupportedImage img in batchClient.GetSupportedImagesAsync())
{
    images.Add(img);
}

// Find the appropriate image information
BatchSupportedImage image = null;
foreach (var img in images)
{
    if (img.ImageReference.Publisher == "canonical" &&
        img.ImageReference.Offer == "0001-com-ubuntu-server-focal" &&
        img.ImageReference.Sku == "20_04-lts")
    {
        image = img;
        break;
    }
}

// Create the BatchVmConfiguration for use when actually creating the pool.
// Note that the data-plane discovery uses Azure.Compute.Batch.BatchVmImageReference
// but the ARM pool data type uses Azure.ResourceManager.Batch.Models.BatchImageReference.
BatchVmConfiguration vmConfiguration = new BatchVmConfiguration(
    imageReference: new BatchImageReference()
    {
        Publisher = image.ImageReference.Publisher,
        Offer = image.ImageReference.Offer,
        Sku = image.ImageReference.Sku,
        Version = image.ImageReference.Version
    },
    nodeAgentSkuId: image.NodeAgentSkuId);

BatchAccountPoolData poolData = new BatchAccountPoolData()
{
    VmSize = vmSize,
    DeploymentConfiguration = new BatchDeploymentConfiguration() { VmConfiguration = vmConfiguration },
    ScaleSettings = new BatchAccountPoolScaleSettings()
    {
        FixedScale = new BatchAccountFixedScaleSettings() { TargetDedicatedNodes = nodeCount }
    }
};

// Commit the pool to the Batch service via Azure.ResourceManager.Batch.
await batchAccount.GetBatchAccountPools().CreateOrUpdateAsync(WaitUntil.Completed, poolId, poolData);

Meskipun cuplikan sebelumnya menggunakan metode BatchClient.GetSupportedImages untuk mendaftar secara dinamis dan memilih dari kombinasi SKU image dan agen node yang didukung (direkomendasikan), Anda juga dapat mengonfigurasi objek BatchVmImageReference secara eksplisit:

BatchImageReference imageReference = new BatchImageReference()
{
    Publisher = "canonical",
    Offer = "0001-com-ubuntu-server-focal",
    Sku = "20_04-lts",
    Version = "latest"
};

Sambungkan ke simpul Linux menggunakan SSH

Selama pengembangan atau saat memecahkan masalah, Anda mungkin perlu masuk ke node dalam pool Anda. Tidak seperti simpul komputasi Windows, Anda tidak dapat menggunakan Protokol Desktop Jarak Jauh (RDP) untuk menyambungkan ke simpul Linux. Sebaliknya, layanan Batch memungkinkan akses SSH pada setiap simpul untuk koneksi jarak jauh.

Cuplikan kode Python berikut membuat pengguna pada setiap simpul dalam kumpulan, yang diperlukan untuk koneksi jarak jauh. Lalu mencetak informasi koneksi shell aman (SSH) untuk setiap simpul.

import datetime
import getpass
from azure.batch import BatchClient, models
from azure.core.credentials import AzureNamedKeyCredential

# Specify your own account credentials
batch_account_name = ''
batch_account_key = ''
batch_account_url = ''

# Specify the ID of an existing pool containing Linux nodes
# currently in the 'idle' state
pool_id = ''

# Specify the username and prompt for a password
username = 'linuxuser'
password = getpass.getpass()

# Create a BatchClient
credentials = AzureNamedKeyCredential(
    batch_account_name,
    batch_account_key
)
batch_client = BatchClient(
    endpoint=batch_account_url,
    credential=credentials
)

# Create the user that will be added to each node in the pool
user = models.BatchNodeUserCreateOptions(
    name=username,
    password=password,
    is_admin=True,
    expiry_time=(datetime.datetime.utcnow() + datetime.timedelta(days=30)),
)

# Get the list of nodes in the pool
nodes = batch_client.list_nodes(pool_id=pool_id)

# Add the user to each node in the pool and print
# the connection information for the node
for node in nodes:
    # Add the user to the node
    batch_client.create_node_user(pool_id=pool_id, node_id=node.id, user=user)

    # Obtain SSH login information for the node
    login = batch_client.get_node_remote_login_settings(pool_id=pool_id,
                                                        node_id=node.id)

    # Print the connection info for the node
    print("{0} | {1} | {2} | {3}".format(node.id,
                                         node.state,
                                         login.remote_login_ip_address,
                                         login.remote_login_port))

Kode ini akan memiliki output yang mirip dengan contoh berikut. Dalam kasus ini, pool berisi empat node Linux.

Password:
tvm-1219235766_1-20160414t192511z | ComputeNodeState.idle | 13.91.7.57 | 50000
tvm-1219235766_2-20160414t192511z | ComputeNodeState.idle | 13.91.7.57 | 50003
tvm-1219235766_3-20160414t192511z | ComputeNodeState.idle | 13.91.7.57 | 50002
tvm-1219235766_4-20160414t192511z | ComputeNodeState.idle | 13.91.7.57 | 50001

Alih-alih kata sandi, Anda dapat menentukan kunci publik SSH saat membuat pengguna pada simpul.

Di SDK Python, gunakan parameter ssh_public_key pada BatchNodeUserCreateOptions.

Di .NET, gunakan properti BatchNodeUserCreateOptions.SshPublicKey.

Harga

Azure Batch dibangun pada teknologi Azure Cloud Services dan Azure Virtual Machines. Layanan Batch itu sendiri ditawarkan tanpa biaya, yang berarti Anda hanya dikenakan biaya untuk sumber daya komputasi (dan biaya terkait) yang dikonsumsi solusi Batch Anda. Ketika memilih Konfigurasi Komputer Virtual, Anda dikenakan biaya berdasarkan struktur harga Komputer Virtual.

Jika menyebarkan aplikasi ke simpul Batch menggunakan paket aplikasi, Anda juga dikenakan biaya untuk sumber daya Azure Storage yang digunakan paket aplikasi Anda.

Langkah berikutnya