Compartilhar via


Gerenciar os clusters do Apache Hadoop no HDInsight ao usar .NET SDK

Saiba como gerenciar clusters do Azure HDInsight ao usar o HDInsight .NET SDK.

Pré-requisitos

Antes de começar este artigo, você deve ter:

  • Uma conta do Azure com uma assinatura ativa. Se você não tiver uma assinatura do Azure, crie uma conta gratuita antes de começar.

Conectar-se ao Azure HDInsight

Você precisa dos seguintes pacotes NuGet:

Install-Package Microsoft.Rest.ClientRuntime.Azure.Authentication -Pre
Install-Package Microsoft.Azure.Management.ResourceManager -Pre
Install-Package Microsoft.Azure.Management.HDInsight

O exemplo de código a seguir mostra como se conectar ao Azure antes que você possa administrar clusters do HDInsight em sua assinatura do Azure.

using System;
using Microsoft.Azure;
using Microsoft.Azure.Management.HDInsight;
using Microsoft.Azure.Management.HDInsight.Models;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Rest;
using Microsoft.Rest.Azure.Authentication;

namespace HDInsightManagement
{
    class Program
    {
        private static HDInsightManagementClient _hdiManagementClient;
        // Replace with your Azure Active Directory tenant ID if necessary.
        private const string TenantId = UserTokenProvider.CommonTenantId; 
        private const string SubscriptionId = "<Your Azure Subscription ID>";
        // This is the GUID for the PowerShell client. Used for interactive logins in this example.
        private const string ClientId = "1950a258-227b-4e31-a9cf-717495945fc2";

        static void Main(string[] args)
        {
            // Authenticate and get a token
            var authToken = Authenticate(TenantId, ClientId, SubscriptionId);
            // Flag subscription for HDInsight, if it isn't already.
            EnableHDInsight(authToken);
            // Get an HDInsight management client
            _hdiManagementClient = new HDInsightManagementClient(authToken);

            // insert code here

            System.Console.WriteLine("Press ENTER to continue");
            System.Console.ReadLine();
        }

        /// <summary>
        /// Authenticate to an Azure subscription and retrieve an authentication token
        /// </summary>
        static TokenCloudCredentials Authenticate(string TenantId, string ClientId, string SubscriptionId)
        {
            var authContext = new AuthenticationContext("https://login.microsoftonline.com/" + TenantId);
            var tokenAuthResult = authContext.AcquireToken("https://management.core.windows.net/", 
                ClientId, 
                new Uri("urn:ietf:wg:oauth:2.0:oob"), 
                PromptBehavior.Always, 
                UserIdentifier.AnyUser);
            return new TokenCloudCredentials(SubscriptionId, tokenAuthResult.AccessToken);
        }
        /// <summary>
        /// Marks your subscription as one that can use HDInsight, if it has not already been marked as such.
        /// </summary>
        /// <remarks>This is essentially a one-time action; if you have already done something with HDInsight
        /// on your subscription, then this isn't needed at all and will do nothing.</remarks>
        /// <param name="authToken">An authentication token for your Azure subscription</param>
        static void EnableHDInsight(TokenCloudCredentials authToken)
        {
            // Create a client for the Resource manager and set the subscription ID
            var resourceManagementClient = new ResourceManagementClient(new TokenCredentials(authToken.Token));
            resourceManagementClient.SubscriptionId = SubscriptionId;
            // Register the HDInsight provider
            var rpResult = resourceManagementClient.Providers.Register("Microsoft.HDInsight");
        }
    }
}

Você verá um aviso quando executar este programa. Se não quiser ver o aviso, consulte Criar aplicativos .NET do HDInsight com autenticação não interativa.

Listar clusters

O snippet de código a seguir lista os clusters e algumas propriedades:

var results = _hdiManagementClient.Clusters.List();
foreach (var name in results.Clusters) {
    Console.WriteLine("Cluster Name: " + name.Name);
    Console.WriteLine("\t Cluster type: " + name.Properties.ClusterDefinition.ClusterType);
    Console.WriteLine("\t Cluster location: " + name.Location);
    Console.WriteLine("\t Cluster version: " + name.Properties.ClusterVersion);
}

Excluir clusters

Use o seguinte snippet de código para excluir um cluster de forma síncrona ou assíncrona:

_hdiManagementClient.Clusters.Delete("<Resource Group Name>", "<Cluster Name>");
_hdiManagementClient.Clusters.DeleteAsync("<Resource Group Name>", "<Cluster Name>");

Dimensionar clusters

Use o recurso de dimensionamento de cluster para alterar o número de nós de trabalho usados por um cluster que está sendo executado no HDInsight sem precisar recriar o cluster.

Observação

Somente clusters HDInsight versão 3.1.3 ou superior são compatíveis. Se você não tiver certeza da versão de seu cluster, verifique a página Propriedades. Para obter mais informações, consulte Listar e mostrar clusters.

O efeito da alteração do número de nós de dados para cada tipo de cluster compatível com o HDInsight:

  • Apache Hadoop: Você pode aumentar continuamente o número de nós de trabalhador em um cluster do Hadoop que esteja em execução sem afetar nenhum trabalho pendente ou em execução. Você também pode enviar novos trabalhos enquanto a operação estiver em andamento. Falhas em uma operação de dimensionamento são normalmente manipuladas para que o cluster sempre seja deixado em um estado funcional.

    Quando um cluster Hadoop é reduzido verticalmente pela diminuição do número de nós de dados, alguns dos serviços no cluster são reiniciados. Todos os trabalhos em execução e pendentes falhem após a conclusão da operação de dimensionamento. Depois que a operação for concluída, você pode reenviar os trabalhos.

  • Apache HBase: Você pode adicionar ou remover nós do cluster HBase continuamente enquanto ele estiver em execução. Os servidores regionais são equilibrados automaticamente em poucos minutos após o término da operação de dimensionamento. Você também pode equilibrar manualmente os servidores regionais. Entre no nó principal de um cluster e execute os seguintes comandos em uma janela de prompt de comando:

    >pushd %HBASE_HOME%\bin
    >hbase shell
    >balancer
    

Atualizar credenciais de usuário HTTP

O procedimento de atualização é o mesmo que você usa para conceder ou revogar o acesso HTTP. Se o cluster tiver recebido acesso HTTP, você deverá primeiro revogá-lo. Em seguida, é possível conceder acesso com novas credenciais de usuário HTTP.

Encontrar a conta de armazenamento padrão

O trecho de código a seguir demonstra como obter o nome e a chave da conta de armazenamento padrão para um cluster.

var results = _hdiManagementClient.Clusters.GetClusterConfigurations(<Resource Group Name>, <Cluster Name>, "core-site");
foreach (var key in results.Configuration.Keys)
{
    Console.WriteLine(String.Format("{0} => {1}", key, results.Configuration[key]));
}

Enviar trabalhos

Saiba como enviar trabalhos para os seguintes produtos:

Carregar dados no Armazenamento de Blobs do Azure

Para fazer upload de dados, consulte Upload de dados no HDInsight.