Exportar (0) Imprimir
Expandir todo

Windows Azure Service Runtime with Java Overview

Actualizado: enero de 2014

The Windows Azure Service Runtime library provides functionality that allows your application to interact with the Windows Azure environment. It also allows your application to determine information about the roles, role instances, and role environment. Examples of where you would use the Service Runtime include:

  • Determining configuration settings, local resources, and role-related information.

  • Responding to role environment changes, for example a change to a configuration setting.

  • Requesting a recycle of a role instance.

The RoleEnvironment, RoleInstance, and Role classes are the main classes in the Service Runtime.

RoleEnvironment class

The RoleEnvironment class represents the Windows Azure environment in which an instance of a role is running. Use this class to retrieve configuration values, receive notification of configuration changes, request a recycle, or retrieve information about roles and role instances.

The RoleEnvironment.isAvailable method informs you whether your role instance is running in the Windows Azure environment. This method is useful if your code path sometimes executes in Windows Azure, and sometimes runs independent of Windows Azure. Note that if your role is running in either the Windows Azure compute emulator or Windows Azure itself, RoleEnvironment.isAvailable returns true. If RoleEnvironment.isAvailable returns false (indicating it is not available), do not call any other members of the RoleEnvironment class. An exception of type RoleEnvironmentNotAvailableException will be thrown if the role environment is not available and you try to call any RoleEnvironment method other than RoleEnvironment.isAvailable.

The RoleEnvironment.isEmulated method informs you whether your role is running in the Windows Azure compute emulator, or in Windows Azure itself. Use this property if your role has different needs based on whether the instance is running in the Windows Azure compute emulator or in Windows Azure.

Call the RoleEnvironment.requestRecycle method to request a stop and restart of your role instance.

The RoleEnvironment.getRoles method returns the set of roles (as Role objects) for which your role instance has visibility. Roles themselves are defined in the service definition file. The RoleEnvironment.getCurrentRoleInstance method returns the role instance, as a RoleInstance object, in which the role is running. Additional information about the Roles and CurrentRoleInstance properties is presented later in this topic.

The RoleEnvironment.getDeploymentId method returns the deployment ID for the role instance; this is a unique string identifying the deployment, and you may find it useful when examining logs. If your role instance is running in the Windows Azure compute emulator, the RoleEnvironment.getDeploymentId return value will be of the form ꞌdeployment(nn)ꞌ, where nn represents an integer. If your role instance is running in Windows Azure (not the compute emulator), the RoleEnvironment.getDeploymentId return value will be a GUID; this GUID can also be found in the deployment properties pane of the Portal de administración de Windows Azure.

The RoleEnvironment.getLocalResources method returns the set of local storage resources that have been reserved in the file system of the virtual machine in which the instance of the role is running. This method returns the set of local resources as a java.util.Map collection. The collection contains LocaResource objects, which are discussed later in this topic. As an example in Java, you could enumerate the local resources in the following manner:

Map<String, LocalResource> mapLocalResources = RoleEnvironment.getLocalResources();
Set set = mapLocalResources.entrySet(); 

Iterator itr = set.iterator();
LocalResource localResource;

while (itr.hasNext())
{
    Map.Entry entry = (Map.Entry)itr.next();

    localResource = (LocalResource) entry.getValue(); 

    System.out.println("Local resource:");
    System.out.println("\tName = " + localResource.getName());
    System.out.println("\tMax size in MBs = " + localResource.getMaximumSizeInMegabytes());
    System.out.println("\tRoot path = " + localResource.getRootPath());

};

Local resources are defined in the service definition file. Three of the methods in the LocalResource class are shown in the example above: LocalResource.getName, which returns the name of the local resource, LocalResource.getMaximumSizeInMegabytes, which returns the maximum size of the local resource, and LocalResource.getRootPath, which returns the complete path of the local resource. The LocalResource class also contains the LocalResource.toString method, which returns a concatenated string that contains the values returned by the getName, getMaximumSizeInMegabytes, and getRootPath methods. For more information on local resources, see How to Configure Local Storage Resources.

The RoleEnvironment.getConfigurationSettings method returns the set of configuration settings for the role instance. This method returns the set of configuration settings as a java.util.Map collection. As an example in Java, you can retrieve a configuration setting in the following manner:

Map<String, String> mapConfigSettings = RoleEnvironment.getConfigurationSettings();
String myValue = mapConfigSettings.get("mySettingName");

Names of configuration settings are defined in the service definition file, and their values are defined in the service configuration file.

The ServiceRuntime library includes three listener interfaces that can be registered using the RoleEnvironment class. One listener interface is RoleEnvironmentStoppingListener, which allows your role instance to know when to execute shutdown code. The other two listener interfaces are RoleEnvironmentChangingListener and RoleEnvironmentChangedListener. RoleEnvironmentChangingListener allows your role to receive notification that a service configuration change is about to be applied, while RoleEnvironmentChangedListener allows your role to receive notification that a service configuration change has occurred. You register or unregister your event listeners through add or remove methods. For example, RoleEnvironment.addRoleEnvironmentStoppingListener adds a RoleEnvironmentStoppingListener to your role instance, while RoleEnvironment.removeRoleEnvironmentStoppingListener removes a RoleEnvironmentStoppingListener from your role instance. The following shows how to add a RoleEnvironmentStoppingListener to your application.

final class MyStoppingListener implements RoleEnvironmentStoppingListener
{

    // Method to handle the role environment stopping event.
    public void roleEnvironmentStopping()
    {
        // The stopping event is occurring.
        // This example just displays the role instance ID.
        System.out.println( "roleEnvironmentStopping has been called for "
            + RoleEnvironment.getCurrentRoleInstance().getId());

        // Take other shutdown action as needed by your application.

    }
}

MyStoppingListener stoppingListener = new MyStoppingListener();

// Add the listener to the role environment.
RoleEnvironment.addRoleEnvironmentStoppingListener(stoppingListener);

The following shows how to remove a RoleEnvironmentStoppingListener from your application.

// Remove the listener from the role environment.
RoleEnvironment.removeRoleEnvironmentStoppingListener(stoppingListener);

The RoleEnvironment class also contains two methods, RoleEnvironment.setStatus and RoleEnvironment.clearStatus, for setting and clearing the status of the role instance, respectively. These methods are discussed in the Role instance status section.

The RoleEnvironment.getRoles method returns the set of roles, as Role objects, defined for you service. The RoleEnvironment.getCurrentRoleInstance method returns the role instance, as a RoleIntance object, in which the code is currently running.

The RoleEnvironment class is a static class, so you can use its members without instantiating an instance of this class. For example, to retrieve the deployment ID, your Java code could be as the following:

String deploymentId = RoleEnvironment.getDeploymentId();

RoleInstance class

The RoleInstance class represents a specific role instance. It contains the getId method, which returns the ID of the role instance, and the getRole method, which returns the role associated with the role instance. The RoleInstance class also contains the getFaultDomain and getUpdateDomain methods, which return integers that indicate the fault domain and upgrade domain, respectively, in which this role instance resides. You cannot specify a number of fault domains for your application, but you can specify a number of upgrade domains within the service definition file, by setting the upgradeDomainCount attribute of the <ServiceDefinition> element. The maximum number of upgrade domains is 5. The RoleInstance class also contains the getInstanceEndpoints method, which returns the set of endpoints, as RoleInstanceEndpoint objects, associated with the role instance. The RoleInstanceEndpoint class is discussed later in this topic.

You can acquire a RoleInstance object by using the following code.

RoleInstance myRoleInstance = RoleEnvironment.getCurrentRoleInstance();

Another technique for acquiring a RoleInstance object is through the Role.getInstances method.

Role class

The Role class represents a role within your application. Roles, such as a web role or a worker role, are defined in the service definition file. The Role class contains two methods, Role.getName and Role.getInstances. Role.getName returns the name of the role (as defined in the service definition file). Role.getInstances returns the set of role instances, as RoleInstance objects, that are known to a role. A role must define at least one internal endpoint in order for its set of instances to be known at runtime.

You can acquire a Role object by using the following code.

Role myRole = RoleEnvironment.getCurrentRoleInstance().getRole();

Another technique for acquiring a Role object is through the RoleEnvironment.getRoles method.

How the RoleEnvironment, Role, and RoleInstance classes relate to each other

The RoleEnvironment, Role, and RoleInstance classes are related in the following manner:

  • The RoleEnvironment.getCurrentRoleInstance method returns the current role instance in the form of a RoleInstance object. Once you’ve retrieved the current role instance using RoleEnvironment.getCurrentRoleInstance, you can examine items such as the fault and upgrade domains, instance endpoints, and the role from which the instance is defined.

  • The RoleEnvironment.getRoles method returns the collection of roles defined for your service.

  • The RoleInstance.getRole method returns the role associated with a role instance. So for example in Java, you could retrieve the name of the role associated with the current role instance by the following:

    System.out.println("The name of the role is " 
        + RoleEnvironment.getCurrentRoleInstance().getRole().getName());
    
    
  • The Role.getRoleInstances method returns the collection of role instances which are running for a role.

Other classes, interfaces and enumerations in the Service Runtime

The RoleInstanceEndpoint class represents an endpoint for a role instance. This class contains the RoleInstanceEndpoint.getIpEndPoint method, which returns the IP address and port number for the endpoint. The RoleInstanceEndpoint class also contains the RoleInstanceEndpoint.getProtocol method, which returns the protocol for the endpoint, and the RoleInstanceEndpoint.getRoleInstance method, which returns the role instance associated with the endpoint. You can acquire the RoleInstanceEndpoint objects for a role instance by calling the RoleInstance.getInstanceEndpoints method.

The RoleEnvironmentChangedEvent class represents an event indicating a change to the service configuration has occurred. This class contains a single method, RoleEnvironmentChangedEvent.getChanges, which returns a collection of changes that have occurred as part of this event. The changes are represented by RoleEnvironmentConfigurationSettingChange or RoleEnvironmentTopologyChange objects. Both RoleEnvironmentConfigurationSettingChange and RoleEnvironmentTopologyChange are subclasses of the RoleEnvironmentChange class. The RoleEnvironmentConfigurationSettingChange class contains a single method, getConfigurationSettingName, that indicates which configuration setting has changed. The RoleEnvironmentTopologyChange class contains a single method, getRoleName, that indicates which role is affected by the change.

Similar to RoleEnvironmentChangedEvent, the Role class represents an event indicating a change to the service configuration is about to occur. Like RoleEnvironmentChangedEvent, RoleEnvironmentChangingEvent contains a getChanges method, but it is for changes that are about to occur. The RoleEnvironmentChangingEvent class also contains a method, cancel. The cancel method cancels the configuration change and causes the role instance to be immediately restarted; the configuration changes would then be applied when the role instance restarts.

The RoleInstanceStatus enumeration defines two enum constants, Busy and Ready, that indicate whether the role is busy (not available to handle requests) or ready (available to handle requests). This enumeration is discussed in the Role instance status section.

Also included in the Service Runtime is the LocalResource class, which is described in the RoleEnvironment class section above. The Service Runtime includes three listener interfaces, RoleEnvironmentStoppingListener, RoleEnvironmentChangingListener, and RoleEnvironmentChangedListener, which are also described in the RoleEnvironment class section.

The RoleEnvironmentNotAvailableException class represents an exception that is thrown when your code attempts to interact with the role environment when it is not available; call the RoleEnvironment.isAvailable method to determine if the role environment is available.

For the complete documentation of the Service Runtime classes and interfaces, see the Windows Azure Service Runtime library documentation.

Role instance status

Within a role instance, various processes may be running, but the role instance needs to ensure that Windows Azure has a consolidated status for the entire role instance. Within Windows Azure, statuses are determined at a per-application domain / native process level. The RoleEnvironment.setStatus method allows you to send a status to Windows Azure. When Windows Azure needs to determine the current status of a role instance, it examines the statuses as sent by the client, such as through RoleEnvironment.setStatus. The first parameter of the setStatus method is a value from the RoleInstanceStatus enumeration, either RoleInstanceStatus.Busy or RoleInstanceStatus.Ready. The second parameter of setStatus is an expiration date and time. To clear a status that you have previously set by calling setStatus, call the RoleEnvironment.clearStatus method. The clearStatus method takes no parameters, and it removes any statuses that you previously set through setStatus.

The following table summarizes the results of the various methods that impact the role instance status.

 

Method Impact to the role instance status

RoleEnvironment.setStatus

Windows Azure considers your role instance Busy or Ready, depending on the first parameter. If the first parameter is RoleInstanceStatus.Busy, then Windows Azure will consider your role instance unavailable (Busy) and will not send requests to your role instance. If the first parameter is RoleInstanceStatus.Ready, then Windows Azure will consider your role instance available (Ready) and will send requests to your role instance. If you do call setStatus, ensure that you take one of the following actions prior to the expiration, which is specified as the second parameter of the setStatus method:

  • make another call to RoleEnvironment.setStatus.

  • call RoleEnvironment.clearStatus.

noteNota
Failure to take one of the actions listed above prior to the expiration of a previous setStatus call will result in Windows Azure considering your role instance Unresponsive.

RoleEnvironment.clearStatus

Any previous calls to setStatus are discarded by Windows Azure and no longer used to determine the role instance status.

Note that you do not need to call setStatus, unless you want to report a status to Windows Azure. For example, if your role instance has no background processing or startup task dependency, it will cycle from Starting to Ready (assuming successful code execution) without requiring a call to setStatus, assuming within the Service Definition file you have set the setReadyOnProcessStart attribute of the <RoleEntryPoint> element to true. However, if your role instance needs to perform some processing that will make it undesirable to start or to continue to receive requests from Windows Azure, call the setStatus method to inform Windows Azure that your role instance is busy, and call the clearStatus method to inform Windows Azure when the previous setStatus call is no longer in effect.

Note that this topic focused on methods from within the Windows Azure ServiceRuntime library that impact the role instance status. Other items that can impact the role instance status include UI actions from within the Portal de administración (for example, requesting a recycle or stopping a role instance) or operations from the Service Management REST API (for example, calling the Reboot Role Instance operation).

Mostrar:
© 2014 Microsoft