Skip to main content

Azure Batch Service - A job that runs an .exe application (part 2)

In the last post related to Azure Batch we talk about the theoretical parts. We discover what kind of batch tasks we can have, what is a merge task and many more.
In this blog post we will focus on how we can create a batch and how we can push our own logic into a batch. We will focus on Azure Batch using a .NET library for now – running an .exe application as a task logic.

Base Terminology
Before going forward it would a good idea to review the batch terminology:
Account - A uniquely identified entity within the service. All processing is done through a Batch account.
Pool – A collection of task virtual machines on which task applications run.
Task Virtual Machine - A machine that is assigned to a pool and is used by tasks that are assigned to jobs that run in the pool.
Task Virtual Machine User – A user account on a task virtual machine.
Workitem - Specifies how computation is performed on task virtual machines in a pool.
Job - A running instance of a work item and consists of a collection of tasks.
Task - An application that is associated with a job and runs on a task virtual machine.
File – Contains the information that is processed by a task.
Source: http://azure.microsoft.com/en-us/documentation/articles/batch-dotnet-get-started/

Azure Batch SDK
Before starting, you should download from Visual Studio Gallery (Tools->Extensions and Updates), the SDK for Azure Batch. This will contain a template that can be used to create a new Batch.

Create an Azure Batch Project
To be able to define an Azure Batch you will need to create a new VS project of type “Azure Batch Embarrassingly Parallel Cloud Application”. First step is to specify the Application Name and Job Name.

Entry Point
This information can be changed later on from ‘ApplicationDefinition’ that represent the main entry point in the application. Using this definition we can control:

  • Name of the Job
  • Name of the Application
  • Job Splitter – This step gives us the possibility to split a job in multiple tasks
  • Task Processor – The task logic itself 
public class ApplicationDefinition
{
    public static readonly CloudApplication Application = new ParallelCloudApplication
        {
            ApplicationName = "FooApp",
            JobType = "FooJob",
            JobSplitterType = typeof(AzureBatchCloudApplication1JobSplitter),
            TaskProcessorType = typeof(AzureBatchCloudApplication1TaskProcessor)
        };

}
Remarks: This template can be very useful, because we can hook directly our own logic, simple and clean.

Job Splitter
As the name says, this class will split your job in subtask. In this way you can run in parallel multiple tasks. Things that you should remember:

  • Task index - Is optionally, is used only to specify an index to each task
  • Task ID – Represent the Id of each task, you should specified this value
  • Parameters – Is a list of parameters that can be used to transmit different parameters to a task
  • RequiredFiles – Can be used to specify what files are needs to run the task
  • DependsOn – It is used when you want to specify that a task depends on another task. The ID of the depending task needs to be specified. In this way the current task will not start until the depending task has not run.
  • State – Is used to group multiple tasks in the same group. It is similar win ‘DependsOn’, but at collection level. In this way you can create a groups of tasks that will run in the order of State value. First, Azure Batch will run in parallel tasks with State value equal to 0, after that the one equal with 1 and so on. Using both solutions (DependsOn or State) you can create different execution model (similar with trees).
  • IsMerge – There can be only one task of this kind and is used to merge the result of the tasks. This task needs to be executed as the last task (by default, you don’t need to define this task, there is a default merge tasks implemented).
 protected override IEnumerable<TaskSpecifier> Split(IJob job, JobSplitSettings settings)
        {
            return new List<TaskSpecifier>
                {
                    new TaskSpecifier
                        {
                            RequiredFiles = job.Files,
                            TaskId = 1,
                            TaskIndex = 1,
                            State = 0
                            Parameters = job.Parameters,
                            
                        },
                    new TaskSpecifier
                        {
                            RequiredFiles = job.Files,
                            TaskId = 2,
                            TaskIndex = 2,
                            DependsOn = 1,
                            State = 0
                            Parameters = job.Parameters,
                        },
                    new TaskSpecifier
                        {
                            RequiredFiles = job.Files,
                            TaskId = 2,
                            TaskIndex = 2,
                            DependsOn = 1,
                            State = 1
                            Parameters = job.Parameters,
                        },
                    ...
                };
        }        

Define a task (ParallelTaskProcessor.RunExternalTaskProcess)
At this level you define the task itselft. In our case, at this level you need to specify the executable that contains the logic of task, input and output files. Don’t forget that input and output of each task is based on files (from blob storage).
When you can execute an external executable you can specify the fallowing information:

  • CommandPath – The path to the executable file (the task logic)
  • Arguments – The arguments that are send to executable file
  • WorkingDirectory – The directory used as working directory
  • CancellationToken – You obtain it from TaskExecutionSettings.CancellationToken and is used to transmit the cancelation token to you executable.
protected override TaskProcessResult RunExternalTaskProcess(ITask task, TaskExecutionSettings settings)
{
    string inputFile = task.RequiredFiles[0].Name;
    string outputFile = string.Format("{0}.scv", task.TaskId);

    ExternalProcess process = new ExternalProcess
        {
            CommandPath = ExecutablePath("fooTask.exe"),
            Arguments = string.Format("input:{0} output:{1}", inputFile, outputFile),
            WorkingDirectory = LocalStoragePath
        };

    ExternalProcessResult processOutput = process.Run();

    return TaskProcessResult.FromExternalProcessResult(processOutput);
}
At this level, based on how you define your job splitter, each task can use different input files and to generate different outputs.

Merge Task (ParallelTaskProcessor.RunExternalMergeProcess)
To implement the merge task you will need to override the above method. In theory this task should take all the output files from all tasks and merge it in only one task. The default merge task is merging all output files in one result.
protected override JobResult RunExternalMergeProcess(ITask mergeTask, TaskExecutionSettings settings)
{
    ...
}

In this post we saw how we can define a job that runs an Azure Batch Application. In the next post we will see how we can define an Azure Batch job using a library and not an .exe application

Comments

Popular posts from this blog

Windows Docker Containers can make WIN32 API calls, use COM and ASP.NET WebForms

After the last post , I received two interesting questions related to Docker and Windows. People were interested if we do Win32 API calls from a Docker container and if there is support for COM. WIN32 Support To test calls to WIN32 API, let’s try to populate SYSTEM_INFO class. [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision; } ... [DllImport("kernel32")] static extern void GetSystemInfo(ref SYSTEM_INFO pSI); ... SYSTEM_INFO pSI = new SYSTEM_INFO(...

How to audit an Azure Cosmos DB

In this post, we will talk about how we can audit an Azure Cosmos DB database. Before jumping into the problem let us define the business requirement: As an Administrator I want to be able to audit all changes that were done to specific collection inside my Azure Cosmos DB. The requirement is simple, but can be a little tricky to implement fully. First of all when you are using Azure Cosmos DB or any other storage solution there are 99% odds that you’ll have more than one system that writes data to it. This means that you have or not have control on the systems that are doing any create/update/delete operations. Solution 1: Diagnostic Logs Cosmos DB allows us activate diagnostics logs and stream the output a storage account for achieving to other systems like Event Hub or Log Analytics. This would allow us to have information related to who, when, what, response code and how the access operation to our Cosmos DB was done. Beside this there is a field that specifies what was th...

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills)

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills) The idea that moving to the cloud reduces the costs is a common misconception. The cloud infrastructure provides flexibility, scalability, and better CAPEX, but it does not guarantee lower costs without proper optimisation and management of the cloud services and infrastructure. Idle and unused resources, overprovisioning, oversize databases, and unnecessary data transfer can increase running costs. The regional pricing mode, multi-cloud complexity, and cost variety add extra complexity to the cost function. Cloud adoption without a cost governance strategy can result in unexpected expenses. Improper usage, combined with a pay-as-you-go model, can result in a nightmare for business stakeholders who cannot track and manage the monthly costs. Cloud-native services such as AI services, managed databases, and analytics platforms are powerful, provide out-of-the-shelve capabilities, and increase business agility and innovation. H...