Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright (C) 2013-2015 Dell, Inc ==================================================================== Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ====================================================================
  
  
  package org.dasein.cloud.azure.compute.vm;
  
  import  org.json.JSONArray;
  import  org.json.JSONException;
  import  org.json.JSONObject;
  import org.w3c.dom.Node;
  
  import  javax.annotation.Nonnegative;
  import  javax.annotation.Nonnull;
  import  javax.annotation.Nullable;
  import java.net.URI;
  import java.util.*;

Implements virtual machine support for Microsoft Azure.

Author(s):
George Reese (george.reese@imaginary.com)
Qunying Huang
Version:
2012.04.1
2012.09 updated for model changes
Since:
2012.04.1 initial version
  
  public class AzureVM extends AbstractVMSupport<Azure> {
      static private final Logger logger = Azure.getLogger(AzureVM.class);
  
      static public final String HOSTED_SERVICES = "/services/hostedservices";
      static public final String DEPLOYMENT_RESOURCE = "/services/hostedservices/%s/deployments/%s";
      static public final String OPERATIONS_RESOURCES = "/services/hostedservices/%s/deployments/%s/roleInstances/%s/Operations";
  
      public AzureVM(Azure provider) {
         super(provider);
     }
 
     @Override
     public void start(@Nonnull String vmIdthrows InternalExceptionCloudException {
         if(vmId == null)
             throw new InternalException("The id of the Virtual Machine to start cannot be null.");
 
         VirtualMachine vm = getVirtualMachine(vmId);
 
         ifvm == null ) {
             throw new CloudException("No such virtual machine: " + vmId);
         }
         ProviderContext ctx = getProvider().getContext();
 
         ifctx == null ) {
             throw new AzureConfigException("No context was set for this request");
         }
 
         String resourceUrl = String.format(vm.getTag("serviceName").toString(),
                 vm.getTag("deploymentName").toString(), vm.getTag("roleName").toString());
         AzureMethod azureMethod = new AzureMethod(getProvider());
 
         try
         {
             azureMethod.post(resourceUrlnew Operation.StartRoleOperation());
         }
         catch (JAXBException e)
         {
             .error(e.getMessage());
             throw new InternalException(e);
         }
     }
 
     @Override
     public VirtualMachine alterVirtualMachineProduct(@Nonnull String virtualMachineId, @Nonnull String productIdthrows InternalExceptionCloudException{
         if.isTraceEnabled() ) {
             .trace("ENTER: " + AzureVM.class.getName() + ".alterVM()");
         }
 
         if (virtualMachineId == null || productId == null) {
             throw new AzureConfigException("No virtual machine id and/or product id set for this operation");
         }
 
         if(!isValidProductId(productId))
             throw new InternalException("Product id invalid: should be one of ExtraSmall, Small, Medium, Large, ExtraLarge");
 
         VirtualMachine vm = getVirtualMachine(virtualMachineId);
 
         ifvm == null ) {
             throw new CloudException("No such virtual machine: " + virtualMachineId);
         }
         ProviderContext ctx = getProvider().getContext();
 
         ifctx == null ) {
             throw new AzureConfigException("No context was set for this request");
         }
         String serviceNamedeploymentNameroleName;
 
         serviceName = vm.getTag("serviceName").toString();
         deploymentName = vm.getTag("deploymentName").toString();
         roleName = vm.getTag("roleName").toString();
 
         String resourceDir =  + "/" + serviceName + "/deployments/" +  deploymentName + "/roles/" + roleName;
 
         try{
             AzureMethod method = new AzureMethod(getProvider());
 
             Document doc = method.getAsXML(ctx.getAccountNumber(), resourceDir);
             StringBuilder xml = new StringBuilder();
 
             NodeList roles = doc.getElementsByTagName("PersistentVMRole");
             Node role = roles.item(0);
 
             NodeList entries = role.getChildNodes();
             boolean changeProduct = false;
 
             for (int i = 0; i<entries.getLength(); i++) {
                 Node vn = entries.item(i);
                 String vnName = vn.getNodeName();
 
                 ifvnName.equalsIgnoreCase("RoleSize") && vn.hasChildNodes() ) {
                     if (!productId.equals(vn.getFirstChild().getNodeValue())) {
                         vn.getFirstChild().setNodeValue(productId);
                         changeProduct=true;
                     }
                     else {
                         .info("No product change required");
                     }
                     break;
                 }
             }
 
             String requestId=null;
 
             if (changeProduct) {
                 String output="";
                 try{
                     TransformerFactory tf = TransformerFactory.newInstance();
                     Transformer transformer = tf.newTransformer();
                     transformer.setOutputProperty(."yes");
                     StringWriter writer = new StringWriter();
                     transformer.transform(new DOMSource(doc), new StreamResult(writer));
                     output = writer.getBuffer().toString().replaceAll("\n|\r""");
                 }
                 catch (Exception e){
                     ..println(e);
                 }
                 xml.append(output);
 
                 .debug(xml);
                 .debug("___________________________________________________");
 
                 resourceDir =  + "/" + serviceName + "/deployments/" +  deploymentName + "/roles/" + roleName;
                 requestId = method.invoke("PUT"ctx.getAccountNumber(), resourceDirxml.toString());
             }
             else {
                 requestId="noChange";
             }
 
             if (requestId != null) {
                 int httpCode = -1;
                 if (!requestId.equals("noChange")) {
                     httpCode = method.getOperationStatus(requestId);
                     while (httpCode == -1) {
                         try {
                             Thread.sleep(15000L);
                         }
                         catch (InterruptedException ignored){}
                         httpCode = method.getOperationStatus(requestId);
                     }
                 }
             }
 
             return getVirtualMachine(virtualMachineId);
 
         }finally {
             if.isTraceEnabled() ) {
                 .trace("EXIT: " + AzureVM.class.getName() + ".alterVM()");
             }
         }
     }
 
     private boolean isValidProductId(String productIdthrows CloudExceptionInternalException {
         for (VirtualMachineProduct p : products) {
             if (p.getProviderProductId().equals(productId)) {
                 return true;
             }
         }
 
         return false;
     }
 
     @Override
     public @Nonnull VirtualMachine clone(@Nonnull String vmId, @Nonnull String intoDcId, @Nonnull String name, @Nonnull String descriptionboolean powerOn, @Nullable String... firewallIdsthrows InternalExceptionCloudException {
         throw new OperationNotSupportedException("Not supported in Microsoft Azure");
     }
 
     @Override
     public void disableAnalytics(String vmIdthrows InternalExceptionCloudException {
         // NO-OP
     }
 
     @Override
     public void enableAnalytics(String vmIdthrows InternalExceptionCloudException {
         // NO-OP
     }
 
     private transient volatile VMCapabilities capabilities;
     @Nonnull
     @Override
         if == null ) {
              = new VMCapabilities(getProvider());
         }
         return ;
     }
 
     @Override
     public @Nonnull String getConsoleOutput(@Nonnull String vmIdthrows InternalExceptionCloudException {
         return "";
     }
 
     @Override
     public @Nullable VirtualMachineProduct getProduct(@Nonnull String productIdthrows InternalExceptionCloudException {
         forVirtualMachineProduct product : listProducts(null.) ) {
             ifproduct.getProviderProductId().equals(productId) ) {            	
                 return product;
             }
         }
         return null;
     }
 
     @Override
     public @Nullable VirtualMachine getVirtualMachine(@Nonnull String vmIdthrows InternalExceptionCloudException {
         String[] parts = vmId.split(":");
         String sNamedeploymentNameroleName;
 
         if (parts.length == 3)    {
             sName = parts[0];
             deploymentName = parts[1];
             roleNameparts[2];
         }
         else ifparts.length == 2 ) {
             sName = parts[0];
             deploymentName = parts[1];
             roleName = sName;
         }
         else {
             sName = vmId;
             deploymentName = vmId;
             roleName = vmId;
         }
         DataCenter dc = null;
         AffinityGroup ag = null;
         ProviderContext ctx = getProvider().getContext();
 
         ifctx == null ) {
             throw new AzureConfigException("No context was specified for this request");
         }
         AzureMethod method = new AzureMethod(getProvider());
 
         Document doc = method.getAsXML(ctx.getAccountNumber(),  + "/"sName+"?embed-detail=true");
         if (doc == null) {
             return null;
         }
         NodeList entries = doc.getElementsByTagName("HostedService");
         for (int h = 0; h < entries.getLength(); h++) {
             Node entry = entries.item(h);
             NodeList attributes = entry.getChildNodes();
 
             boolean mediaLocationFound = false;
 
             forint i=0; i<attributes.getLength(); i++ ) {
                 Node attribute = attributes.item(i);
 
                 if(attribute.getNodeType() == .) {
                     continue;
                 }
                 ifattribute.getNodeName().equalsIgnoreCase("hostedserviceproperties") && attribute.hasChildNodes() ) {
                     NodeList properties = attribute.getChildNodes();
 
                     forint j=0; j<properties.getLength(); j++ ) {
                         Node property = properties.item(j);
 
                         if(property.getNodeType() == .) {
                             continue;
                         }
                         ifproperty.getNodeName().equalsIgnoreCase("AffinityGroup") && property.hasChildNodes() ) {
                             //get the region for this affinity group
                             String affinityGroup = property.getFirstChild().getNodeValue().trim();
                             if (affinityGroup != null && !affinityGroup.equals("")) {
                                 ag = getProvider().getComputeServices().getAffinityGroupSupport().get(affinityGroup);
                                 if(ag == null)
                                     return null;
 
                                 dc = getProvider().getDataCenterServices().getDataCenter(ag.getDataCenterId());
                                 if (dc != null && dc.getRegionId().equals(ctx.getRegionId())) {
                                     mediaLocationFound = true;
                                 }
                                 else {
                                     // not correct region/datacenter
                                     return null;
                                 }
                             }
                         }
                         else ifproperty.getNodeName().equalsIgnoreCase("location") && property.hasChildNodes() ) {
                             if( !mediaLocationFound && !ctx.getRegionId().equals(property.getFirstChild().getNodeValue().trim()) ) {
                                 return null;
                             }
                         }
                     }
                 }
             }
 
         }
 
         ArrayList<VirtualMachinelist = new ArrayList<VirtualMachine>();
         NodeList deployments = doc.getElementsByTagName("Deployments");
         for (int i = 0; i < deployments.getLength(); i++) {
             Node deployNode = deployments.item(i);
             NodeList deployAttributes = deployNode.getChildNodes();
 
             String depName = "";
             for (int j = 0; j<deployAttributes.getLength(); j++) {
                 Node deployment = deployAttributes.item(j);
 
 
                 if(deployment.getNodeType() == .) {
                     continue;
                 }
 
                 ifdeployment.getNodeName().equalsIgnoreCase("Deployment") && deployment.hasChildNodes() ) {
                     NodeList dAttribs = deployment.getChildNodes();
                     for (int k = 0; k<dAttribs.getLength(); k++) {
                         Node mynode = dAttribs.item(k);
 
                         if ( mynode.getNodeName().equalsIgnoreCase("name") && mynode.hasChildNodes() ) {
                             depName = mynode.getFirstChild().getNodeValue().trim();
                             if (depName.equals(deploymentName)) {
                                 parseDeployment(ctxctx.getRegionId(), sName + ":" + deploymentNamedeploymentlist);
                                 if (list != null && list.size() > 0) {
                                     for(VirtualMachine vm : list) {
                                         if (vm.getTag("roleName").toString().equalsIgnoreCase(roleName)) {
                                             if (dc != null) {
                                                 vm.setProviderDataCenterId(dc.getProviderDataCenterId());
                                             } else {
                                                 Collection<DataCenterdcs = getProvider().getDataCenterServices().listDataCenters(ctx.getRegionId());
                                                 vm.setProviderDataCenterId(dcs.iterator().next().getProviderDataCenterId());
                                             }
                                             if (ag != null) {
                                                 vm.setAffinityGroupId(ag.getAffinityGroupId());
                                             }
                                             return vm;
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
         return null;
     }
 
     @Override
     public @Nullable VmStatistics getVMStatistics(String vmIdlong fromlong tothrows InternalExceptionCloudException {
         return new VmStatistics();
     }
 
     @Override
     public @Nonnull Iterable<VmStatisticsgetVMStatisticsForPeriod(@Nonnull String vmId, @Nonnegative long from, @Nonnegative long tothrows InternalExceptionCloudException {
         return Collections.emptyList();
     }
 
     @Override
     public boolean isSubscribed() throws CloudExceptionInternalException {
     }
 
     @Override
     public @Nonnull VirtualMachine launch(VMLaunchOptions optionsthrows CloudExceptionInternalException {
         if.isTraceEnabled() ) {
             .trace("ENTER: " + AzureVM.class.getName() + ".launch(" + options + ")");
         }
         try {
             String storageEndpoint = getProvider().getStorageEndpoint();
 
             if(storageEndpoint == null || storageEndpoint.isEmpty()) {
                 getProvider().createDefaultStorageService();
                 storageEndpoint = getProvider().getStorageEndpoint();
             }
 
             .debug("----------------------------------------------------------");
             .debug("launching vm "+options.getHostName()+" with machine image id: "+options.getMachineImageId());
 
             ifimage == null ) {
                 throw new CloudException("No such image: " + options.getMachineImageId());
             }
             .debug("----------------------------------------------------------");
 
             ProviderContext ctx = getProvider().getContext();
 
             ifctx == null ) {
                 throw new AzureConfigException("No context was specified for this request");
             }
             String label;
 
             try {
                 label = new String(Base64.encodeBase64(options.getFriendlyName().getBytes("utf-8")));
             }
             catchUnsupportedEncodingException e ) {
                 throw new InternalException(e);
             }
             AzureMethod method = new AzureMethod(getProvider());
             String hostName = toUniqueId(options.getHostName(), methodctx);
             String deploymentSlot = (String)options.getMetaData().get("environment");
 
             String affinityGroupId = options.getAffinityGroupId();
 
             ifdeploymentSlot == null ) {
                 deploymentSlot = "Production";
             }
             else if( !deploymentSlot.equalsIgnoreCase("Production") && !deploymentSlot.equalsIgnoreCase("Staging") ) {
                 deploymentSlot = "Production";
             }
 
             CreateHostedService(options.getDescription(), ctx.getRegionId(), labelhostNameaffinityGroupId);
 
 
             String password = (options.getBootstrapPassword() == null ? getProvider().generateToken(8, 15) : options.getBootstrapPassword());
 
             Subnet subnet = null;
             String vlanName = null;
             if (options.getVlanId() != null) {
                 subnet = getProvider().getNetworkServices().getVlanSupport().getSubnet(options.getSubnetId());
                 if (subnet != null) {
                     vlanName = subnet.getTags().get("vlanName");
                 } else {
                     VLAN vlan = getProvider().getNetworkServices().getVlanSupport().getVlan(options.getVlanId());
                     if (vlan != null) {
                         vlanName = vlan.getName();
                     }
                 }
             }
 
             String requestId = null;
             try {
                 requestId = CreateDeployment(optionsstorageEndpointimagelabelhostNamedeploymentSlotsubnetvlanNamepassword);
             }
             catch (CloudException e) {
                 .error("Launch server failed - now cleaning up service");
                 DeleteHostedService(hostName);
                 throw e;
             }
 
             long timeout = System.currentTimeMillis() + (. * 10L);
             VirtualMachine vm = null ;
 
             if (requestId != null) {
                 int httpCode = method.getOperationStatus(requestId);
                 while (httpCode == -1) {
                     try {
                         Thread.sleep(15000L);
                     }
                     catch (InterruptedException ignored){}
                     httpCode = method.getOperationStatus(requestId);
                 }
                 if (httpCode == .) {
                     try { vm = getVirtualMachine(hostName + ":" + hostName+":"+hostName); }
                     catchThrowable ignore ) { }
                     ifvm != null ) {
                         vm.setRootUser("dasein");
                         vm.setRootPassword(password);
                     }
                 }
             }
             else {
                 whiletimeout > System.currentTimeMillis() ) {
                     try { vm = getVirtualMachine(hostName + ":" + hostName+":"+hostName); }
                     catchThrowable ignore ) { }
                     ifvm != null ) {
                         vm.setRootUser("dasein");
                         vm.setRootPassword(password);
                         break;
                     }
                     try { Thread.sleep(15000L); }
                     catchInterruptedException ignore ) { }
                 }
             }
             ifvm == null ) {
                 throw new CloudException("System timed out waiting for virtual machine to appear");
             }
             if..equals(vm.getCurrentState()) ) {
                 start(vm.getProviderVirtualMachineId());
             }
             return vm;
         }
         finally {
             if.isTraceEnabled() ) {
                 .trace("EXIT: " + AzureVM.class.getName() + ".launch()");
             }
         }
     }
 
     private void DeleteHostedService(String hostNamethrows InternalException {
         String resourceDir =  + "/" + hostName;
         long timeout = System.currentTimeMillis() + (. * 10L);
         whiletimeout > System.currentTimeMillis() ) {
             try{
                 if.isInfoEnabled() ) {
                     .info("Deleting hosted service " + hostName);
                 }
                 AzureMethod method = new AzureMethod(getProvider());
                 method.invoke("DELETE"getProvider().getContext().getAccountNumber(), resourceDir"");
                 break;
             }
             catchCloudException err ) {
                 .error("Unable to delete hosted service for " + hostName + ": " + err.getMessage());
                 .error("Retrying...");
                 try { Thread.sleep(30000L); }
                 catchInterruptedException ignore ) { }
                 continue;
             }
         }
     }
 
     private String CreateDeployment(VMLaunchOptions optionsString storageEndpointAzureMachineImage imageString labelString hostNameString deploymentSlotSubnet subnetString vlanNameString passwordthrows CloudExceptionInternalException {
         DeploymentModel deploymentModel = new DeploymentModel();
         deploymentModel.setName(hostName);
         deploymentModel.setDeploymentSlot(deploymentSlot);
         deploymentModel.setLabel(label);
 
         DeploymentModel.RoleModel roleModel = new DeploymentModel.RoleModel();
         roleModel.setRoleName(hostName);
         roleModel.setRoleType("PersistentVMRole");
 
         ArrayList<ConfigurationSetModelconfigurations = new ArrayList<ConfigurationSetModel>();
         if (image.getPlatform().isWindows())
         {
             ConfigurationSetModel windowsConfigurationSetModel = new ConfigurationSetModel();
             windowsConfigurationSetModel.setConfigurationSetType("WindowsProvisioningConfiguration");
             windowsConfigurationSetModel.setType("WindowsProvisioningConfigurationSet");
             windowsConfigurationSetModel.setComputerName(hostName);
             windowsConfigurationSetModel.setAdminPassword(password);
             windowsConfigurationSetModel.setEnableAutomaticUpdates("true");
             windowsConfigurationSetModel.setTimeZone("UTC");
             windowsConfigurationSetModel.setAdminUsername((options.getBootstrapUser() == null || options.getBootstrapUser().trim().length() == 0 || options.getBootstrapUser().equalsIgnoreCase("root") || options.getBootstrapUser().equalsIgnoreCase("admin") || options.getBootstrapUser().equalsIgnoreCase("administrator") ? "dasein" : options.getBootstrapUser()));
             //if(options.getUserData() != null && !options.getUserData().equals(""))windowsConfigurationSetModel.setCustomData(new String(Base64.encodeBase64(options.getUserData().getBytes())));
             configurations.add(windowsConfigurationSetModel);
         }
         else
         {
             ConfigurationSetModel unixConfigurationSetModel = new ConfigurationSetModel();
             unixConfigurationSetModel.setConfigurationSetType("LinuxProvisioningConfiguration");
             unixConfigurationSetModel.setType("LinuxProvisioningConfigurationSet");
             unixConfigurationSetModel.setHostName(hostName);
             unixConfigurationSetModel.setUserName((options.getBootstrapUser() == null || options.getBootstrapUser().trim().length() == 0 || options.getBootstrapUser().equals("root") ? "dasein" : options.getBootstrapUser()));
             unixConfigurationSetModel.setUserPassword(password);
             unixConfigurationSetModel.setDisableSshPasswordAuthentication("false");
             //if(options.getUserData() != null && !options.getUserData().equals(""))unixConfigurationSetModel.setCustomData(new String(Base64.encodeBase64(options.getUserData().getBytes())));
             configurations.add(unixConfigurationSetModel);
 
         }
 
 
         ConfigurationSetModel networkConfigurationSetModel = new ConfigurationSetModel();
         networkConfigurationSetModel.setConfigurationSetType("NetworkConfiguration");
         if(image.getPlatform().isWindows())
         {
             ConfigurationSetModel.InputEndpointModel inputEndpointModel = new ConfigurationSetModel.InputEndpointModel();
             inputEndpointModel.setLocalPort("3389");
             inputEndpointModel.setName("RemoteDesktop");
             inputEndpointModel.setPort("58622");
             inputEndpointModel.setProtocol("TCP");
             inputEndpointModels.add(inputEndpointModel);
         }
         else
         {
             ConfigurationSetModel.InputEndpointModel inputEndpointModel = new ConfigurationSetModel.InputEndpointModel();
             inputEndpointModel.setLocalPort("22");
             inputEndpointModel.setName("SSH");
             inputEndpointModel.setPort("22");
             inputEndpointModel.setProtocol("TCP");
             inputEndpointModels.add(inputEndpointModel);
         }
         networkConfigurationSetModel.setInputEndpoints(inputEndpointModels);
         if(subnet != null)
         {
             ArrayList<Stringsubnets = new ArrayList<String>();
             subnets.add(subnet.getName());
             networkConfigurationSetModel.setSubnetNames(subnets);
         }
         configurations.add(networkConfigurationSetModel);
 
         roleModel.setConfigurationsSets(configurations);
         if(image.getAzureImageType().equalsIgnoreCase("osimage"))
         {
             DeploymentModel.OSVirtualHardDiskModel osVirtualHardDiskModel = new DeploymentModel.OSVirtualHardDiskModel();
             osVirtualHardDiskModel.setHostCaching("ReadWrite");
             osVirtualHardDiskModel.setDiskLabel("OS");
             String vhdFileName = String.format("%s-%s-%s-%s.vhd"hostNamehostNamehostNamenew SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
             osVirtualHardDiskModel.setMediaLink(storageEndpoint + "vhds/" + vhdFileName);
             osVirtualHardDiskModel.setSourceImageName(options.getMachineImageId());
             roleModel.setOsVirtualDisk(osVirtualHardDiskModel);
         }
         else if(image.getAzureImageType().equalsIgnoreCase("vmimage"))
         {
             roleModel.setVmImageName(image.getProviderMachineImageId());
         }
         roleModel.setRoleSize(options.getStandardProductId());
 
         roles.add(roleModel);
         deploymentModel.setRoles(roles);
 
         if(options.getVlanId() != null)
         {
             deploymentModel.setVirtualNetworkName(vlanName);
         }
 
         try {
             AzureMethod method = new AzureMethod(getProvider());
             return method.post( + "/" + hostName + "/deployments"deploymentModel);
         } catch (JAXBException e) {
             .error(e.getMessage());
             throw new CloudException(e);
         }
     }
 
     private void CreateHostedService(String descriptionString regionId,String labelString hostNameString affinityGroupIdthrows CloudExceptionInternalException {
         CreateHostedServiceModel createHostedServiceModel = new CreateHostedServiceModel();
         createHostedServiceModel.setServiceName(hostName);
         createHostedServiceModel.setLabel(label);
         createHostedServiceModel.setDescription(description);
         if(affinityGroupId != null) {
             createHostedServiceModel.setAffinityGroup(affinityGroupId);
         } else {
             createHostedServiceModel.setLocation(regionId);
         }
 
         try {
             AzureMethod method = new AzureMethod(getProvider());
             method.post(createHostedServiceModel);
         } catch (JAXBException e) {
             .error(e.getMessage());
             throw new CloudException(e);
         }
     }
 
     @Override
     public @Nonnull Iterable<StringlistFirewalls(@Nonnull String vmIdthrows InternalExceptionCloudException {
         return Collections.emptyList();
     }
 
     @Override
     public @Nonnull Iterable<VirtualMachineProductlistProducts(@Nullable VirtualMachineProductFilterOptions options, @Nonnull Architecture architecturethrows InternalExceptionCloudException {
         APITrace.begin(getProvider(), "listVMProducts");
         try {
             Cache<VirtualMachineProductcache = Cache.getInstance(getProvider(), "products" + architecture.name(), VirtualMachineProduct.class.new TimePeriod<Day>(1, .));
             Iterable<VirtualMachineProductproducts = cache.get(getContext());
 
             ifproducts == null ) {
                 List<VirtualMachineProductlist = new ArrayList<VirtualMachineProduct>();
 
                 try {
                     String resource = ((Azure)getProvider()).getVMProductsResource();
                     InputStream input = AzureVM.class.getResourceAsStream(resource);
 
                     ifinput != null ) {
                         BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                         StringBuilder json = new StringBuilder();
                         String line;
 
                         while( (line = reader.readLine()) != null ) {
                             json.append(line);
                             json.append("\n");
                         }
                         JSONArray arr = new JSONArray(json.toString());
                         JSONObject toCache = null;
 
                         forint i=0; i<arr.length(); i++ ) {
                             JSONObject productSet = arr.getJSONObject(i);
                             String cloudprovider;
 
                             ifproductSet.has("cloud") ) {
                                 cloud = productSet.getString("cloud");
                             }
                             else {
                                 continue;
                             }
                             ifproductSet.has("provider") ) {
                                 provider = productSet.getString("provider");
                             }
                             else {
                                 continue;
                             }
                             if( !productSet.has("products") ) {
                                 continue;
                             }
                             iftoCache == null || (getProvider().equals("default") && cloud.equals("default")) ) {
                                 toCache = productSet;
                             }
                             ifprovider.equalsIgnoreCase(getProvider().getProviderName()) && cloud.equalsIgnoreCase(getProvider().getCloudName()) ) {
                                 toCache = productSet;
                                 break;
                             }
                         }
                         iftoCache == null ) {
                             .warn("No products were defined");
                             return Collections.emptyList();
                         }
                         JSONArray plist = toCache.getJSONArray("products");
 
                         forint i=0; i<plist.length(); i++ ) {
                             JSONObject product = plist.getJSONObject(i);
                             boolean supported = false;
 
                             ifproduct.has("architectures") ) {
                                 JSONArray architectures = product.getJSONArray("architectures");
 
                                 forint j=0; j<architectures.length(); j++ ) {
                                     String a = architectures.getString(j);
 
                                     ifarchitecture.name().equals(a) ) {
                                         supported = true;
                                         break;
                                     }
                                 }
                             }
                             if( !supported ) {
                                 continue;
                             }
                             ifproduct.has("excludesRegions") ) {
                                 JSONArray regions = product.getJSONArray("excludesRegions");
 
                                 forint j=0; j<regions.length(); j++ ) {
                                     String r = regions.getString(j);
 
                                     ifr.equals(getContext().getRegionId()) ) {
                                         supported = false;
                                         break;
                                     }
                                 }
                             }
                             if( !supported ) {
                                 continue;
                             }
                             VirtualMachineProduct prd = toProduct(product);
 
                             ifprd != null ) {
                                 ifoptions != null) {
                                     // Filter supplied, add matches only.
                                     ifoptions.matches(prd) ) {
                                         list.add(prd);
                                     }
                                 }
                                 else {
                                     // No filter supplied, add all survived.
                                     list.add(prd);
                                 }
                             }
                         }
                     }
                     else {
                         .warn("No standard products resource exists for " + resource);
                     }
 
                     products = list;
                     cache.put(getContext(), products);
                 }
                 catchIOException e ) {
                     throw new InternalException(e);
                 }
                 catch( JSONException e ) {
                     throw new InternalException(e);
                 }
             }
             return products;
         }
         finally {
             APITrace.end();
         }
     }
 
     @Nonnull
     @Override
         ProviderContext ctx = getProvider().getContext();
 
         ifctx == null ) {
             throw new AzureConfigException("No context was specified for this request");
         }
         AzureMethod method = new AzureMethod(getProvider());
 
         Document doc = method.getAsXML(ctx.getAccountNumber(), );
 
         ifdoc == null ) {
             return Collections.emptyList();
         }
         NodeList entries = doc.getElementsByTagName("HostedService");
         ArrayList<ResourceStatusstatus = new ArrayList<ResourceStatus>();
 
         forint i=0; i<entries.getLength(); i++ ) {
             parseHostedServiceForStatus(ctxentries.item(i), nullstatus);
         }
         return status;
     }
 
     @Override
     public @Nonnull Iterable<VirtualMachinelistVirtualMachines() throws InternalExceptionCloudException {
         ProviderContext ctx = getProvider().getContext();
 
         ifctx == null ) {
             throw new AzureConfigException("No context was specified for this request");
         }
         AzureMethod method = new AzureMethod(getProvider());
 
         Document doc = method.getAsXML(ctx.getAccountNumber(), );
 
         ifdoc == null ) {
             return Collections.emptyList();
         }
         NodeList entries = doc.getElementsByTagName("HostedService");
         ArrayList<VirtualMachinevms = new ArrayList<VirtualMachine>();
 
         forint i=0; i<entries.getLength(); i++ ) {
             parseHostedService(ctxentries.item(i), nullvms);
         }
         return vms;
     }
 
     @Nonnull
     @Override
     public Iterable<VirtualMachinelistVirtualMachines(@Nullable VMFilterOptions vmFilterOptionsthrows InternalExceptionCloudException {
         Iterable<VirtualMachinevms = listVirtualMachines();
         ArrayList<VirtualMachinelist = new ArrayList<VirtualMachine>();
         for (VirtualMachine vm : vms) {
             if (vm.getName().matches(vmFilterOptions.getRegex())) {
                 list.add(vm);
             }
         }
         return list;
     }
 
     private void parseDeployment(@Nonnull ProviderContext ctx, @Nonnull String regionId, @Nonnull String serviceName, @Nonnull Node node, @Nonnull List<VirtualMachinevirtualMachines) {
         ArrayList<VirtualMachinelist = new ArrayList<VirtualMachine>();
         NodeList attributes = node.getChildNodes();
         String deploymentSlot = null;
         String deploymentId = null;
         String dnsName = null;
         String vmRoleName = null;
         String imageId = null;
         String mediaLink = null;
         String vlan = null;
         String subnetName = null;
 
         forint i=0; i<attributes.getLength(); i++ ) {
             Node attribute = attributes.item(i);
 
             ifattribute.getNodeType() == .) {
                 continue;
             }
             ifattribute.getNodeName().equalsIgnoreCase("deploymentslot") && attribute.hasChildNodes() ) {
                 deploymentSlot = attribute.getFirstChild().getNodeValue().trim();
             }
             else ifattribute.getNodeName().equalsIgnoreCase("privateid") && attribute.hasChildNodes() ) {
                 deploymentId = attribute.getFirstChild().getNodeValue().trim();
             }
             else ifattribute.getNodeName().equalsIgnoreCase("url") && attribute.hasChildNodes() ) {
                 try {
                     URI u = new URI(attribute.getFirstChild().getNodeValue().trim());
 
                     dnsName = u.getHost();
                 }
                 catchURISyntaxException e ) {
                     // ignore
                 }
             }
             else ifattribute.getNodeName().equalsIgnoreCase("roleinstancelist") && attribute.hasChildNodes() ) {
                 NodeList roleInstances = attribute.getChildNodes();
 
                 forint j=0; j<roleInstances.getLength(); j++ ) {
                     Node roleInstance = roleInstances.item(j);
 
                     if(roleInstance.getNodeType() == .) {
                         continue;
                     }
                     ifroleInstance.getNodeName().equalsIgnoreCase("roleinstance") && roleInstance.hasChildNodes() ) {
                         VirtualMachine role = new VirtualMachine();
 
                         role.setArchitecture(.);
                         role.setClonable(false);
                         role.setCurrentState(.);
                         role.setImagable(false);
                         role.setPersistent(true);
                         role.setPlatform(.);
                         role.setProviderOwnerId(ctx.getAccountNumber());
                         role.setProviderRegionId(regionId);
                         role.setProviderDataCenterId(regionId);
 
                         NodeList roleAttributes = roleInstance.getChildNodes();
 
                         forint l=0; l<roleAttributes.getLength(); l++ ) {
                             Node roleAttribute = roleAttributes.item(l);
 
                             ifroleAttribute.getNodeType() == . ) {
                                 continue;
                             }
                             ifroleAttribute.getNodeName().equalsIgnoreCase("RoleName") && roleAttribute.hasChildNodes() ) {
                                 String vmId  = roleAttribute.getFirstChild().getNodeValue().trim();
 
                                 role.setProviderVirtualMachineId(serviceName + ":" + vmId);
                                 role.setName(vmId);
                             }
                             else ifroleAttribute.getNodeName().equalsIgnoreCase("instancesize") && roleAttribute.hasChildNodes() ) {
                                 role.setProductId(roleAttribute.getFirstChild().getNodeValue().trim());
                             }
                             else ifroleAttribute.getNodeName().equalsIgnoreCase("instanceupgradedomain") && roleAttribute.hasChildNodes() ) {
                                 role.setTag("UpgradeDomain"roleAttribute.getFirstChild().getNodeValue().trim());
                             }
                             else ifroleAttribute.getNodeName().equalsIgnoreCase("instanceerrorcode") && roleAttribute.hasChildNodes() ) {
                                 role.setTag("ErrorCode"roleAttribute.getFirstChild().