연습 - 컴퓨팅 노드의 애플리케이션 관리 및 배포

완료됨

Azure 일괄 처리 클라이언트 API를 사용하면 Azure Batch 계정의 모든 구성 요소를 프로그래밍 방식으로 제어할 수 있습니다.

회사의 콘솔 앱을 계속 향상시키면 이제 마지막 연습에서 업로드한 비디오를 변환하는 데 필요한 모든 구성 요소를 추가합니다.

Important

이 연습을 수행하려면 사용자의 Azure 구독이 필요하며 요금이 발생할 수 있습니다. Azure 구독이 아직 없는 경우 시작하기 전에 체험 계정을 만듭니다.

이 연습을 마치면 MP4 비디오를 애니메이션 GIF로 변환할 수 있는 Batch 프로세스가 작동하게 됩니다. 이 앱은 기존 풀에 작업을 추가하고, 비디오 변환 태스크를 추가 및 시작할 것입니다.

일괄 처리 클라이언트를 사용하여 코드 개선

  1. 다음과 같이 Cloud Shell에서 편집기를 사용하여 Program.cs 파일을 편집합니다.

    code Program.cs
    
  2. Batch 작업에서 사용할 JobId의 Program.cs 상수를 추가합니다.

    private const string JobId = "WinFFmpegJob";
    
  3. Main 메서드의 다음 줄을

        var batchClient = BatchClient.Open(sharedKeyCredentials);
    
        // Create the Batch pool, which contains the compute nodes that execute tasks.
        await CreateBatchPoolAsync(batchClient, PoolId);
    

    에 대한 using 블록 사용 batchClient

    using (BatchClient batchClient = BatchClient.Open(sharedKeyCredentials))
    {
        // Create the Batch pool, which contains the compute nodes that execute the tasks.
        await CreateBatchPoolAsync(batchClient, PoolId);
    
        // Create the job that runs the tasks.
        await CreateJobAsync(batchClient, JobId, PoolId);
    
        // Create a collection of tasks and add them to the Batch job.
        await AddTasksAsync(batchClient, JobId, inputFiles, outputContainerSasUrl);
    }
    

작업 만들기

  1. 이 새 메서드를 CreateJobAsync()추가하여 Program.cs 작업을 만들고 풀에 추가합니다.

    private static async Task CreateJobAsync(BatchClient batchClient, string jobId, string poolId)
    {
            Console.WriteLine("Creating job [{0}]...", jobId);
    
            CloudJob job = batchClient.JobOperations.CreateJob();
            job.Id = jobId;
            job.PoolInformation = new PoolInformation { PoolId = poolId };
    
            await job.CommitAsync();
    }
    

    위의 코드는 일괄 처리 클라이언트를 사용하여 작업을 만듭니다. 이 메서드는 지정된 작업 ID 및 풀에 대한 정보를 할당합니다.

태스크 추가

  1. 작업을 만들었으므로, 마지막으로 수행할 단계는 작업에 태스크를 추가하는 것입니다. 다음 메서드를 AddTaskAsync()Program.cs 추가합니다.

    private static async Task<List<CloudTask>> AddTasksAsync(BatchClient batchClient, string jobId, List<ResourceFile> inputFiles, string outputContainerSasUrl)
    {
        Console.WriteLine("Adding {0} tasks to job [{1}]...", inputFiles.Count, jobId);
    
        // Create a collection to hold the tasks added to the job
        List<CloudTask> tasks = new List<CloudTask>();
    
        for (int i = 0; i < inputFiles.Count; i++)
        {
            // Assign a task ID for each iteration
            string taskId = String.Format("Task{0}", i);
    
            // Define task command line to convert the video format from MP4 to animated GIF using ffmpeg.
            // Note that ffmpeg syntax specifies the format as the file extension of the input file
            // and the output file respectively. In this case inputs are MP4.
            string appPath = String.Format("%AZ_BATCH_APP_PACKAGE_{0}#{1}%", appPackageId, appPackageVersion);
            string inputMediaFile = inputFiles[i].FilePath;
            string outputMediaFile = String.Format("{0}{1}",
                System.IO.Path.GetFileNameWithoutExtension(inputMediaFile),
                ".gif");
    
            // This is the dos command built by using the ffmpeg application package, the paths from the input container
            string taskCommandLine = String.Format("cmd /c {0}\\ffmpeg-3.4-win64-static\\bin\\ffmpeg.exe -i {1} {2}", appPath, inputMediaFile, outputMediaFile);
    
            // Create a cloud task (with the task ID and command line) and add it to the task list
            CloudTask task = new CloudTask(taskId, taskCommandLine);
            task.ResourceFiles = new List<ResourceFile> { inputFiles[i] };
    
            // Task output file will be uploaded to the output container in Storage.
            List<OutputFile> outputFileList = new List<OutputFile>();
            OutputFileBlobContainerDestination outputContainer = new OutputFileBlobContainerDestination(outputContainerSasUrl);
            OutputFile outputFile = new OutputFile(outputMediaFile,
                                                    new OutputFileDestination(outputContainer),
                                                    new OutputFileUploadOptions(OutputFileUploadCondition.TaskSuccess));
            outputFileList.Add(outputFile);
            task.OutputFiles = outputFileList;
            tasks.Add(task);
        }
    
        // Call BatchClient.JobOperations.AddTask() to add the tasks as a collection rather than making a
        // separate call for each. Bulk task submission helps to ensure efficient underlying API
        // calls to the Batch service.
        await batchClient.JobOperations.AddTaskAsync(jobId, tasks);
    
        return tasks;
    }
    

    이 마지막 메서드는 앱의 모든 복잡한 작업을 수행합니다. 업로드된 각 파일의 작업에 태스크가 추가됩니다. 태스크는 셸 명령 형식을 사용합니다. 이 연습에서는 애플리케이션 패키지를 사용했기 때문에 특정 위치의 각 노드에 앱(ffmpeg)이 설치되었습니다. Batch 서비스는 이러한 위치를 노드의 환경 변수에 저장하므로 다음 명령을 통해 액세스할 수 있습니다.

    %AZ_BATCH_APP_PACKAGE_ffmpeg#3.4%

    이 방법을 사용하면 최신 버전의 앱을 쉽게 업로드하고 증분할 수 ffmpeg 있습니다. 이 명령은 zip 폴더를 들여다 보고 다음 명령을 실행합니다.

    ffmpeg.exe -i input-filename output-filename

    최상의 성능을 위해 태스크가 batchClient.JobOperations.AddTaskAsync에 목록으로 추가됩니다. 각 파일을 별도로 호출하는 것보다 이 방법이 효율적입니다.

콘솔 앱 테스트

  1. 코드 편집기에서 마우스 오른쪽 단추를 클릭하고 저장을 선택한 다음 마우스 오른쪽 단추를 클릭하고 종료를 선택합니다.

  2. 클라우드 셸에서 앱을 빌드하고 실행합니다.

    dotnet run
    
  3. 다음 메시지는 터미널에 기록됩니다.

    Creating container [input].
    Creating container [output].
    Uploading file ~\cutifypets\InputFiles\3.mp4 to container [input]...
    Uploading file ~\cutifypets\InputFiles\2.mp4 to container [input]...
    Uploading file ~\cutifypets\InputFiles\4.mp4 to container [input]...
    Uploading file ~\cutifypets\InputFiles\1.mp4 to container [input]...
    Uploading file ~\cutifypets\InputFiles\5.mp4 to container [input]...
    Uploading file ~\cutifypets\InputFiles\6.mp4 to container [input]...
    Creating pool [WinFFmpegPool]...
    Creating job [WinFFmpegJob]...
    Adding 6 tasks to job [WinFFmpegJob]...
    
  4. 콘솔 앱은 태스크를 추가하는 즉시 종료됩니다. Azure에서 풀, 노드, 작업 및 태스크가 생성됩니다. 앱이 종료되었기 때문에 앱 내에서 무슨 일이 벌어지고 있는지 모니터링할 수 있는 수단이 없습니다. 현재 변환 상태를 살펴보고 결과를 확인하기 위해 Azure Portal로 돌아갑니다.

  5. Azure Portal에서 대시보드에서 시작하는 cutify Batch 계정을 선택합니다.

    Screenshot of the Overview page of the Batch account.

  6. 상태 대시보드는 개요 페이지에 표시됩니다. 여기에서 현재 실행 중인 작업의 상태 노드 풀을 검사 수 있습니다.

  7. 왼쪽 메뉴에서 기능 아래의 작업을 선택한 다음 WinFFmpegJob을 선택합니다. 이 페이지에는 작업의 현재 상태가 표시됩니다.

  8. 작업이 완료되면 첫 번째 연습에서 만든 스토리지 계정으로 돌아갑니다.

  9. 왼쪽 메뉴에서 데이터 스토리지 아래의 컨테이너를 선택한 다음 출력 폴더를 선택합니다.

  10. 이 폴더에는 변환된 애니메이션 gif 파일이 포함됩니다. 파일을 다운로드하여 귀여운 애완 동물 비디오를 확인합니다.