■
■ Objective 3.2: Configure cloud services and roles
■
■ Objective 3.3: Deploy a cloud service
■
■ Objective 3.4: Monitor and debug a cloud service
Objective 3.1: Design and develop a cloud service
To develop a cloud service, install the Azure SDK. With the Azure SDK installed, you can develop a web or worker role and configure startup tasks within that role to perform addi- tional configuration when an instance starts up. All of these tasks are covered in this section.
This objective covers how to:
■
■ Install SDKs and emulators
■
■ Develop a web or worker role
■
■ Design and implement resiliency
■
■ Develop startup tasks
Installing SDKs and emulators
To design and develop cloud services, you need to install the Azure SDK. This section walks you through the process.
Assuming you already have Visual Studio installed, you first need to install Azure SDK. This SDK installs many different items, including emulators, tools, and APIs for several different Azure services. One approach to installing the Azure SDK is to create a new cloud project.
1. Open Visual Studio.
2. On the New Project screen, under Templates, click Visual C#.
3. Under Visual C#, click Cloud. On the right, click Get Microsoft Azure SDK For .NET, as shown in Figure 3-1. You can leave everything else the same. Click OK.
FIGURE 3-1 The Visual Studio New Project dialog box
4. In the download dialog box that appears, click Download Microsoft Azure SDK.
5. In the dialog box that appears, click Run.
6. If a security warning appears, click Run again.
Objective 3.1: Design and develop a cloud service CHAPTER 3 173 7. On the Web Platform Installer 5.0 welcome screen (see Figure 3-2), click Install.
FIGURE 3-2 The Web Platform Installer 5.0 welcome screen
8. Accept the licensing agreement. The Azure ADK will take a minute to download and install.
NOTE STAYING UP TO DATE
It is important to stay up to date on the latest SDK. This allows you to avoid backward com- patibility issues with your code base as the SDK evolves. As if this writing, you can get the latest SDK at http://azure.microsoft.com/en-us/downloads/archive-net-downloads/. Click the SDK that targets the Visual Studio version you’re using.
When the install completes, the SDK installs two emulators, the Azure Compute Emula- tor and the Azure Storage Emulator. These emulators are useful for debugging applications, which is covered in “Objective 3.4: Monitor and debug a cloud service.”
Developing a web or worker role
When you create a cloud service project, you can add one or more cloud service roles (roles) to the project to be included in the deployment package. The type of role defines the compo- sition of the deployment environment for the role. Cloud Services supports two kinds of roles:
■
■ Web roles Used for web server applications hosted in IIS, such as an ASP.NET MVC application or a Web API application
■
■ Worker roles Used for running a compute workload. It can be used to launch an executable process or for background worker implementations that work in a similar manner to a Windows service.
This section describes the templates available for creating a web or worker role and the process for creating each from within Visual Studio.
process for creating each from within Visual Studio.
MORE INFO CLOUD SERVICES TERMINOLOGY
The following link provides some terminology important to Cloud Services: http://azure.
microsoft.com/en-us/documentation/articles/cloud-services-what-is/.
EXAM TIP
PaaS cloud services discussed in this chapter are conceptually different from IaaS cloud services discussed in Chapter 2, “Create and manage virtual machines.” With PaaS cloud services, you are entrusting Azure to manage the operating system updates, patching, and deployment lifecycle of your applications. IaaS cloud services are a mechanism for grouping assets in your VM topology.
Choosing a cloud service template
When you create a new cloud service project from within Visual Studio, you choose the cloud service template and then select a role template as follows:
1. In Visual Studio, click File, and then click New Project.
2. In the New Project dialog box, click Installed, Templates, Visual C#, and then Cloud, and select the Azure Cloud Service template.
3. The New Microsoft Azure Cloud Service dialog box includes a list of role templates available, organized by language (Visual Basic, C#, or F#). Select one or more of the available templates and click the right arrow to add them to the cloud service project you are creating.
4. Optionally, rename each role to match the desired project name.
5. After you select the desired roles for the cloud service, click OK.
The cloud service template should be the startup project in the solution. It references the roles associated with the cloud service and holds the configuration settings for each role, in- cluding their operating system version, application configuration, topology for VM allocation, and any startup tasks required on VM provisioning.
Objective 3.1: Design and develop a cloud service CHAPTER 3 175 When creating the cloud service project, you can optionally create web or worker roles by
selecting from one of several role templates, including the following:
■
■ ASP.NET Web Role Used to create a new MVC, Web API, Single Page application, Web Forms application, or empty ASP.NET application
■
■ WCF Service Web Role Used to create an ASP.NET website that hosts a WCF Service over HTTP protocol with default configurations
■
■ Worker Role Used to create an empty background worker process where you provide the functionality in Run()
■
■ Worker Role with Service Bus Queue Used to create a background worker process that reads from a Service Bus queue using default configurations
Any of these role templates can be used as a starting point for producing a website or background worker deployed as part of a cloud service package. By default, adding multiple roles will result in multiple VMs. Each role then operates in isolation with its own configura- tion settings. It is possible to configure multiple roles to deploy to a single VM.
MORE INFO THE ROLEENTRYPOINT CLASS
Cloud service web and worker roles are projects that include a class that inherits the RoleEntryPoint base type from the Microsoft.WindowsAzure.ServiceRuntime namespace.
When each role is allocated to a VM, its entry point is invoked to initialize the environment.
There are three key methods to override when you implement RoleEntryPoint: OnStart(), Run(), and OnStop(). For more information about this type, see http://msdn.microsoft.com/
en-us/library/microsoft.windowsazure.serviceruntime.roleentrypoint.aspx.
Creating a new web role
To create a new cloud service project with a web role, complete the following steps:
1. In Visual Studio, click File, and then click New Project.
2. In the New Project dialog box, click Installed, Templates, Visual C#, and then Cloud, and then select the Azure Cloud Service template.
3. In the New Microsoft Azure Cloud Service dialog box, select ASP.NET Web Role, and click the right arrow. Edit the name of the web role to match the name you would give the ASP.NET project. Click OK.
4. Accept the defaults for the new ASP.NET Project and click OK. This creates a new MVC website based on the default template.
5. To run the project, click Debug and then click Start Debugging (or press F5).
The web role is running in the Azure Compute Emulator, but since this is a web role, a browser window also opens with the ASP.NET application loaded. Note that the ASP.NET project includes a class called WebRole that extends RoleEntryPoint, as follows:
public class WebRole : RoleEntryPoint {
public override bool OnStart() {
return base.OnStart();
} }
NOTE ROLE ENTRY POINT AND WEB ROLES
You are not required to modify the default implementation of RoleEntryPoint for a web role; however, it is common to add code that interacts with the RoleEnvironment. For example, you can write code to interact with role lifecycle events such as preventing a restart for certain configuration setting changes.
You can proceed to develop the ASP.NET project as you normally would with a few considerations in mind:
■
■ Consider putting some key configuration settings in the role configuration settings instead of in the web.config application settings. This makes it possible to surface those settings to the management portal for modification.
■
■ If your application has any dependencies that require installation on the destination VM or control over IIS-related settings, use a startup task to provide an unattended deployment for this configuration. Startup tasks are discussed in the following section.
NOTE STARTUP PROJECTS AND CLOUD SERVICES
Though you can run the ASP.NET project directly by making it the startup project, this may result in unexpected behaviors since it will not be running within the context of the cloud service RoleEnvironment. Any code that relies on the RoleEnvironment global configura- tion will fail when the project is not run as a cloud service.
Creating a new worker role
To create a new cloud service project with a worker role, complete the following steps:
1. In Visual Studio, click File and then click New Project.
2. In the New Project dialog box, click Installed, Templates, Visual C#, and then Cloud, and select the Azure Cloud Service template.
3. In the New Microsoft Azure Cloud Service dialog box, click Worker Role and click the right arrow. Edit the name of the worker role to match the name you would give the background worker project. Click OK.
Objective 3.1: Design and develop a cloud service CHAPTER 3 177 4. To run the project, click Debug and then click Start Debugging (or press F5).
5. The background worker runs in the Azure Compute Emulator. To view the emulator, from the task bar, select the arrow to show hidden icons and right-click the Microsoft Azure icon. From the context menu, select Show Compute Emulator UI (see Figure 3-3).
6. In the Azure Compute Emulator window, expand your cloud service project to reveal the worker role node (see Figure 3-4). Click this node to view the output from the default worker role implementation.
MORE INFO RUNNING THE AZURE COMPUTE EMULATOR FROM THE COMMAND LINE The Azure Compute Emulator automatically starts when you run a cloud service from within Visual Studio. You can also start the emulator from the command line as described at http://msdn.microsoft.com/en-us/library/azure/gg433001.aspx.
FIGURE 3-3 Showing the Azure Compute Emulator menu from the Microsoft Azure icon
FIGURE 3-4 The Azure Compute Emulator illustrating the output from the default worker role running
For a worker role, the RoleEntryPoint is the heart of its functionality; therefore, providing an implementation for OnStart(), Run(), and OnEnd(), among other interactions with RoleEn- vironment events, is implied. The default implementation for a basic worker role is as follows:
public class WorkerRole : RoleEntryPoint {
private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
private readonly ManualResetEvent runCompleteEvent = new ManualResetEvent(false);
public override void Run() {
Trace.TraceInformation("Worker is running");
try {
this.RunAsync(this.cancellationTokenSource.Token).Wait();
} finally {
this.runCompleteEvent.Set();
} }
public override bool OnStart() {
ServicePointManager.DefaultConnectionLimit = 12;
bool result = base.OnStart();
Trace.TraceInformation("Worker has been started");
return result;
}
public override void OnStop() {
Trace.TraceInformation("Worker is stopping");
this.cancellationTokenSource.Cancel();
this.runCompleteEvent.WaitOne();
base.OnStop();
Trace.TraceInformation("Worker has stopped");
}
private async Task RunAsync(CancellationToken cancellationToken) {
// TODO: Replace the following with your own logic.
while (!cancellationToken.IsCancellationRequested) {
Trace.TraceInformation("Working");
await Task.Delay(1000);
} }
Objective 3.1: Design and develop a cloud service CHAPTER 3 179 In a typical implementation, you customize the following from this default template:
■
■ OnStart() Initialize the environment here. You may hook some RoleEnvironment events, for example.
■
■ OnStop() Clean up anything you created before the role shuts down.
■
■ RunAsync() Provide your implementation here. For example, you may read from a storage queue, process messages, handle errors, and provide back-off polling when the queue is empty. See Chapter 5, “Manage application and network services,” for more information on storage queue processing.
MORE INFO THE ROLEENVIRONMENT OBJECT
For more information about the RoleEnvironment object, events you can handle, and information you can gather about the cloud service, see http://msdn.microsoft.com/en-gb/
library/microsoft.windowsazure.serviceruntime.roleenvironment.aspx.
Adding an existing project as a web role
If you have previously created a web application project such as an ASP.NET MVC or Web API project, you may want to associate that with a cloud service in order to deploy it as part of a package.
Create a new cloud service project without selecting a role template, or open an existing cloud service, and do the following:
1. In Solution Explorer, navigate to the cloud service project.
2. Right-click the Roles node, select Add, and then select Web Role Project In Solution. If this option is unavailable, a web project may not be available to select from within the solution.
3. In the Associate With Role Project dialog box, select the web project from the list. Click OK. A new role node is created under Roles.
MORE INFO ADDING A ROLE TO A CLOUD SERVICE
You can also add an existing worker role to a cloud service project using similar steps.
The Add and Worker Role Project In Solution menus will be enabled if a valid worker role project exists in the solution.
Reviewing cloud service project elements
The remainder of this chapter covers a few key features of a cloud service project. To provide you with a holistic view, this section reviews the key elements in the solution.
After creating a cloud service project with a web or worker role, navigate to Solution Explorer from within Visual Studio and review the following items:
■
■ At the root of the project is ServiceDefinition.csdef. This file, called the service defini- tion, holds the definition for the cloud service, including a list of any startup tasks you add and a definition for each web and worker role.
■
■ Also at the root of the project are two default service configuration files. One is used when you run ServiceConfiguration.Local.cscfg locally. The other, ServiceConfiguration.
Cloud.cscfg, is included when you publish to the cloud. These files are called the ser- vice configuration. Configuration settings are edited as you edit the role configuration in the role settings dialog box. You can also create additional or alternate configuration settings, for example for development, test, or production cloud deployments.
■
■ Expand the cloud service project and note the Roles node. When expanded, this will show one or more web or worker role nodes according to what you have added to the cloud service project.
■
■ Double-click any role node to open the role settings dialog box, where you can configure settings used for running locally or in the cloud published version.
Design and implement resiliency
As with websites (discussed in Chapter 1, “Design and implement websites”), you should design your cloud services to support the potential for increases in server load. While Azure provides you with an inherently scalable and available platform for hosting cloud service web roles and worker roles, their design and implementation plays an important role in the overall scalability, availability, and resiliency of the application.
This section covers how to apply those concepts to cloud services.
MORE INFO RESILIENT CLOUD ARCHITECTURES
The following reference provides additional insights, some specific to Azure, regarding designing resilient architectures for the cloud: http://msdn.microsoft.com/library/azure/
jj853352.aspx.
Selecting a pattern
Factors that influence resiliency of web roles and worker roles are similar to those discussed in
”Objective 1.6: Design and implement applications for scale and resilience” in Chapter 1. For both web roles and worker roles, the following patterns are useful to your availability, resiliency, and scalability strategy for cloud services:
■
■ Static Content Hosting pattern
■
■ Cache-Aside pattern
■
■ Health Endpoint Monitoring pattern
Objective 3.1: Design and develop a cloud service CHAPTER 3 181
■
■ Compensating Transaction pattern
■
■ Command and Query Responsibility Segregation pattern
Worker roles can be used for background work in a similar fashion to WebJobs. For these implementations, the same patterns that are useful to WebJobs are also useful to the worker role:
■
■ Competing Consumers pattern
■
■ Priority Queue pattern
■
■ Queue-Based Load Leveling pattern
■
■ Leader Election pattern
■
■ Scheduler Agent Supervisor pattern
Implementing transient fault handling
As with website implementations, cloud services should implement transient fault handling to improve resiliency. Specifically, application logic that accesses remote application services requires a form of retry logic to recover from transient connectivity issues. As discussed in Chapter 1, “Objective 1.6: Design and implement applications for scale and resilience,” you can leverage the Transient Fault Handling Application Block toassist with this type of imple- mentationfor Azure Storage and Azure SQL Database.
Developing startup tasks
Startup tasks are used to perform operations such as running scripts prior to starting a role.
The script can be a simple batch file that launches a process, adjusts registry settings, runs an MSI, or invokes Windows PowerShell scripts to configure any number of machine settings.
Since startup tasks are invoked prior to role startup, they are typically used to prepare the VM in advance of running your application code.
This section describes developing and running startup tasks for a web or worker role.
Starting a role and startup tasks
The process of starting a role follows this order:
1. A role enters “starting” state and does not receive traffic.
2. Startup tasks run according to their type. Simple tasks run in order. Background and foreground tasks start asynchronously.
3. Role host process starts. For a web role, IIS is initialized.
4. The RoleEntryPoint type OnStart() is called.
5. The role enters “ready” state and traffic is sent to the role endpoints.
6. The RoleEntryPoint type Run() method is called.
If any of the tasks do not complete with exit code 0, the role is not started.
MORE INFO LOGGING FROM STARTUP TASKS
Visibility into your startup task process is important if there are issues that require trouble- shooting. Log activity from your startup tasks to help with this. For more information on this and other helpful tips, see http://msdn.microsoft.com/en-us/library/azure/jj129545.
aspx.
Creating a batch file to run as a startup task
Each startup task typically references a batch file that contains the instructions to run. Within the batch file you can do things such as:
■
■ Install registry settings with a .reg file
■
■ Call a Windows PowerShell script
■
■ Install software using msiexec.exe
■
■ Launch a process
The following instructions step through creating a simple batch file that edits registry settings and launches a Windows PowerShell script:
1. Using NotePad.exe, create a new file called licensesettings.reg.
2. Add the following text to the file and save it:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\LicensedApplication]
“Expires”=”99999999”
“LicenseType”=”Business”
“Key”=”12345”
3. Using NotePad.exe, create a new file called startup.cmd.
4. Add the following text to the file and save it:
@echo off
regedit.exe /s licensesettings.reg exit /b 0
5. Copy both files to the root of your web or worker role project. Set the files to Copy Always so that they will be copied to the \bin folder when the solution is compiled.
You can now reference this file from the startup task configuration discussed in the next section.
MORE INFO EXAMPLES OF STARTUP TASK IMPLEMENTATIONS
See the following reference for an example of how to create batch files that run Windows PowerShell scripts and initialize IIS settings: http://msdn.microsoft.com/en-us/library/
azure/hh180155.aspx.