Share via


Gerir clusters do Apache Hadoop no HDInsight com o SDK .NET

Saiba como gerir clusters do HDInsight com HDInsight.NET SDK.

Pré-requisitos

Antes de começar este artigo, tem de ter o seguinte:

Ligar ao Azure HDInsight

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 seguinte exemplo de código mostra-lhe como ligar ao Azure antes de poder administrar clusters do HDInsight na sua subscrição 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 AAD 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");
        }
    }
}

Verá uma mensagem quando executar este programa. Se não quiser ver o pedido, veja Criar aplicações .NET HDInsight de autenticação não interativa.

Listar clusters

O fragmento de código seguinte lista 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);
}

Eliminar clusters

Utilize o fragmento de código seguinte para eliminar 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

A funcionalidade de dimensionamento do cluster permite-lhe alterar o número de nós de trabalho utilizados por um cluster em execução no Azure HDInsight sem ter de recriar o cluster.

Nota

Apenas são suportados clusters com a versão 3.1.3 ou superior do HDInsight. Se não tiver a certeza da versão do cluster, pode verificar a página Propriedades. Veja Listar e mostrar clusters.

O impacto da alteração do número de nós de dados para cada tipo de cluster suportado pelo HDInsight:

  • Apache Hadoop

    Pode aumentar de forma totalmente integrada o número de nós de trabalho num cluster do Hadoop que está em execução sem afetar quaisquer tarefas pendentes ou em execução. As novas tarefas também podem ser submetidas enquanto a operação estiver em curso. As falhas numa operação de dimensionamento são processadas corretamente para que o cluster fique sempre num estado funcional.

    Quando um cluster do Hadoop é reduzido verticalmente ao reduzir o número de nós de dados, alguns dos serviços no cluster são reiniciados. Isto faz com que todas as tarefas em execução e pendentes falhem no final da operação de dimensionamento. No entanto, pode submeter novamente as tarefas assim que a operação estiver concluída.

  • Apache HBase

    Pode adicionar ou remover nós de forma totalmente integrada ao cluster do HBase enquanto está em execução. Os Servidores Regionais são automaticamente equilibrados dentro de alguns minutos após a conclusão da operação de dimensionamento. No entanto, também pode equilibrar manualmente os servidores regionais ao iniciar sessão no nó principal do cluster e executar os seguintes comandos a partir de uma janela da linha de comandos:

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

Atualizar credenciais de utilizador HTTP

É o mesmo procedimento que Conceder/revogar o acesso HTTP. Se tiver sido concedido acesso HTTP ao cluster, primeiro tem de o revogar. Em seguida, conceda o acesso com as novas credenciais de utilizador HTTP.

Localizar a conta de armazenamento predefinida

O fragmento de código seguinte demonstra como obter o nome da conta de armazenamento predefinido e a chave de conta de armazenamento predefinida 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]));
}

Submeter tarefas

Para submeter tarefas do MapReduce

Veja Executar exemplos do MapReduce no HDInsight.

Para submeter tarefas do Apache Hive

Veja Executar consultas do Apache Hive com o SDK .NET.

Para submeter tarefas do Apache Sqoop

Veja Utilizar o Apache Sqoop com o HDInsight.

Para submeter tarefas do Apache Oozie

Veja Utilizar o Apache Oozie com o Hadoop para definir e executar um fluxo de trabalho no HDInsight.

Carregar dados para o armazenamento de Blobs do Azure

Consulte Upload data to HDInsight (Carregar dados para o HDInsight).

Consulte também