Repository: jclouds-labs Updated Branches: refs/heads/fix/AzureTemplateBuilderLiveTest e450fd464 -> 8d223b1ee
remove DeploymentToNodemetadata - remove DeploymentToTemplateBuilder util - adjust the rest of the code, accordingly Project: http://git-wip-us.apache.org/repos/asf/jclouds-labs/repo Commit: http://git-wip-us.apache.org/repos/asf/jclouds-labs/commit/8d223b1e Tree: http://git-wip-us.apache.org/repos/asf/jclouds-labs/tree/8d223b1e Diff: http://git-wip-us.apache.org/repos/asf/jclouds-labs/diff/8d223b1e Branch: refs/heads/fix/AzureTemplateBuilderLiveTest Commit: 8d223b1ee45dbd496d3d4d6149a89c6fe4928f84 Parents: e450fd4 Author: Andrea Turli <[email protected]> Authored: Tue Oct 4 15:05:18 2016 +0200 Committer: Andrea Turli <[email protected]> Committed: Tue Oct 4 15:05:18 2016 +0200 ---------------------------------------------------------------------- .../azurecompute/arm/AzureComputeApi.java | 3 - .../arm/compute/AzureComputeServiceAdapter.java | 15 - .../functions/DeploymentToNodeMetadata.java | 219 -------- .../functions/DeploymentToVMDeployment.java | 122 ----- .../arm/config/AzureComputeHttpApiModule.java | 3 - .../arm/util/DeploymentTemplateBuilder.java | 547 ------------------- .../arm/features/DeploymentApiLiveTest.java | 47 +- .../features/DeploymentTemplateBuilderTest.java | 296 ---------- .../TemplateToDeploymentTemplateLiveTest.java | 281 ---------- 9 files changed, 33 insertions(+), 1500 deletions(-) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/8d223b1e/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/AzureComputeApi.java ---------------------------------------------------------------------- diff --git a/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/AzureComputeApi.java b/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/AzureComputeApi.java index 42749cf..7706737 100644 --- a/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/AzureComputeApi.java +++ b/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/AzureComputeApi.java @@ -17,7 +17,6 @@ package org.jclouds.azurecompute.arm; import org.jclouds.azurecompute.arm.features.DeploymentApi; -import org.jclouds.azurecompute.arm.util.DeploymentTemplateBuilder; import org.jclouds.azurecompute.arm.features.JobApi; import org.jclouds.azurecompute.arm.features.LocationApi; import org.jclouds.azurecompute.arm.features.NetworkInterfaceCardApi; @@ -165,6 +164,4 @@ public interface AzureComputeApi extends Closeable { @Delegate ResourceProviderApi getResourceProviderApi(); - @Provides - DeploymentTemplateBuilder.Factory deploymentTemplateFactory(); } http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/8d223b1e/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/AzureComputeServiceAdapter.java ---------------------------------------------------------------------- diff --git a/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/AzureComputeServiceAdapter.java b/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/AzureComputeServiceAdapter.java index 0b7072a..5ee484d 100644 --- a/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/AzureComputeServiceAdapter.java +++ b/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/AzureComputeServiceAdapter.java @@ -390,21 +390,6 @@ public class AzureComputeServiceAdapter implements ComputeServiceAdapter<Virtual @Override public Iterable<VirtualMachine> listNodes() { return api.getVirtualMachineApi(azureGroup).list(); - /* - return FluentIterable.from(api.getDeploymentApi(azureGroup).list()) - .filter(isDeploymentInRegions) - .filter(new Predicate<Deployment>() { - @Override - public boolean apply(Deployment deployment) { - Value storageAccountNameValue = deployment.properties().parameters().get("storageAccountName"); - String storageAccountName = storageAccountNameValue.value(); - String key = api.getStorageAccountApi(azureGroup).getKeys(storageAccountName).key1(); - return !BlobHelper.customImageExists(storageAccountName, key); - } - }) - .transform(deploymentToVMDeployment) - .toList(); - */ } @Override http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/8d223b1e/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/functions/DeploymentToNodeMetadata.java ---------------------------------------------------------------------- diff --git a/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/functions/DeploymentToNodeMetadata.java b/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/functions/DeploymentToNodeMetadata.java deleted file mode 100644 index f7e3b5b..0000000 --- a/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/functions/DeploymentToNodeMetadata.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.jclouds.azurecompute.arm.compute.functions; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; - -import org.jclouds.azurecompute.arm.AzureComputeApi; -import org.jclouds.azurecompute.arm.domain.Deployment; -import org.jclouds.azurecompute.arm.domain.ImageReference; -import org.jclouds.azurecompute.arm.domain.IpConfiguration; -import org.jclouds.azurecompute.arm.domain.NetworkInterfaceCard; -import org.jclouds.azurecompute.arm.domain.PublicIPAddress; -import org.jclouds.azurecompute.arm.domain.VMDeployment; -import org.jclouds.azurecompute.arm.domain.VirtualMachine; -import org.jclouds.azurecompute.arm.util.GetEnumValue; -import org.jclouds.collect.Memoized; -import org.jclouds.compute.domain.Hardware; -import org.jclouds.compute.domain.Image; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.functions.GroupNamingConvention; -import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.domain.Credentials; -import org.jclouds.domain.Location; -import org.jclouds.domain.LoginCredentials; -import org.jclouds.logging.Logger; - -import com.google.common.base.Function; -import com.google.common.base.Optional; -import com.google.common.base.Predicate; -import com.google.common.base.Splitter; -import com.google.common.base.Supplier; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Iterables; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.collect.Iterables.find; - -public class DeploymentToNodeMetadata implements Function<VMDeployment, NodeMetadata> { - - @Resource - @Named(ComputeServiceConstants.COMPUTE_LOGGER) - protected Logger logger = Logger.NULL; - - // When using the Deployment API to deploy an ARM template, the deployment goes through - // stages. Accepted -> Running -> Succeeded. Only when the deployment has SUCCEEDED is - // the resource deployed using the template actually ready. - // - // To get details about the resource(s) deployed via template, one needs to query the - // various resources after the deployment has "SUCCEEDED". - private static final Map<Deployment.ProvisioningState, NodeMetadata.Status> STATUS_TO_NODESTATUS = - ImmutableMap.<Deployment.ProvisioningState, NodeMetadata.Status>builder(). - put(Deployment.ProvisioningState.ACCEPTED, NodeMetadata.Status.PENDING). - put(Deployment.ProvisioningState.READY, NodeMetadata.Status.PENDING). - put(Deployment.ProvisioningState.RUNNING, NodeMetadata.Status.PENDING). - put(Deployment.ProvisioningState.CANCELED, NodeMetadata.Status.TERMINATED). - put(Deployment.ProvisioningState.FAILED, NodeMetadata.Status.ERROR). - put(Deployment.ProvisioningState.DELETED, NodeMetadata.Status.TERMINATED). - put(Deployment.ProvisioningState.SUCCEEDED, NodeMetadata.Status.RUNNING). - put(Deployment.ProvisioningState.UNRECOGNIZED, NodeMetadata.Status.UNRECOGNIZED). - build(); - - public static Deployment.ProvisioningState provisioningStateFromString(final String text) { - return (Deployment.ProvisioningState) GetEnumValue.fromValueOrDefault(text, Deployment.ProvisioningState.UNRECOGNIZED); - } - - private final AzureComputeApi api; - private final GroupNamingConvention nodeNamingConvention; - private final Supplier<Map<String, ? extends Image>> images; - private final Supplier<Set<? extends Location>> locations; - private final Supplier<Map<String, ? extends Hardware>> hardwares; - private final Map<String, Credentials> credentialStore; - - @Inject - DeploymentToNodeMetadata( - AzureComputeApi api, - GroupNamingConvention.Factory namingConvention, - Supplier<Map<String, ? extends Image>> images, - Supplier<Map<String, ? extends Hardware>> hardwares, - @Memoized Supplier<Set<? extends Location>> locations, Map<String, Credentials> credentialStore) { - this.api = api; - this.nodeNamingConvention = namingConvention.createWithoutPrefix(); - this.images = checkNotNull(images, "images cannot be null"); - this.locations = checkNotNull(locations, "locations cannot be null"); - this.hardwares = checkNotNull(hardwares, "hardwares cannot be null"); - this.credentialStore = credentialStore; - } - - @Override - public NodeMetadata apply(final VMDeployment from) { - final NodeMetadataBuilder builder = new NodeMetadataBuilder(); - VirtualMachine virtualMachine = from.virtualMachine(); - builder.id(from.deploymentId()); - builder.providerId(virtualMachine.id()); - builder.name(virtualMachine.name()); - //builder.hostname(deployment.name() + "pc"); - String group = this.nodeNamingConvention.extractGroup(virtualMachine.name()); - builder.group(group); - //builder.status(getStatus(virtualMachine.properties().provisioningState())); - - Credentials credentials = credentialStore.get("node#" + virtualMachine.name()); - builder.credentials(LoginCredentials.fromCredentials(credentials)); - - builder.publicAddresses(getPublicIpAddresses(from.ipAddressList())); - builder.privateAddresses(getPrivateIpAddresses(from.networkInterfaceCards())); - - if (virtualMachine != null) { - if (virtualMachine.tags() != null) { - Map<String, String> userMetaData = virtualMachine.tags(); - builder.userMetadata(userMetaData); - builder.tags(Splitter.on(",").split(userMetaData.get("tags"))); - } - String locationName = virtualMachine.location(); - builder.location(getLocation(locationName)); - - ImageReference imageReference = virtualMachine.properties().storageProfile().imageReference(); - Optional<? extends Image> image = findImage(imageReference, locationName); - if (image.isPresent()) { - builder.imageId(image.get().getId()); - builder.operatingSystem(image.get().getOperatingSystem()); - } else { - logger.info(">> image with id %s for virtualmachine %s was not found. " - + "This might be because the image that was used to create the virtualmachine has a new id.", - virtualMachine.id(), virtualMachine.id()); - } - - builder.hardware(getHardware(virtualMachine.properties().hardwareProfile().vmSize())); - } - - return builder.build(); - } - - private Iterable<String> getPrivateIpAddresses(List<NetworkInterfaceCard> networkInterfaceCards) { - return FluentIterable.from(networkInterfaceCards) - .filter(new Predicate<NetworkInterfaceCard>() { - @Override - public boolean apply(NetworkInterfaceCard nic) { - return nic != null && nic.properties() != null && nic.properties().ipConfigurations() != null; - } - }).transformAndConcat(new Function<NetworkInterfaceCard, Iterable<IpConfiguration>>() { - @Override - public Iterable<IpConfiguration> apply(NetworkInterfaceCard nic) { - return nic.properties().ipConfigurations(); - } - }).filter(new Predicate<IpConfiguration>() { - @Override - public boolean apply(IpConfiguration ip) { - return ip != null && ip.properties() != null && ip.properties().privateIPAddress() != null; - } - }).transform(new Function<IpConfiguration, String>() { - @Override - public String apply(IpConfiguration ipConfiguration) { - return ipConfiguration.properties().privateIPAddress(); - } - }).toSet(); - } - - private Iterable<String> getPublicIpAddresses(List<PublicIPAddress> publicIPAddresses) { - return FluentIterable.from(publicIPAddresses) - .filter(new Predicate<PublicIPAddress>() { - @Override - public boolean apply(PublicIPAddress publicIPAddress) { - return publicIPAddress != null && publicIPAddress.properties() != null && publicIPAddress.properties().ipAddress() != null; - } - }).transform(new Function<PublicIPAddress, String>() { - @Override - public String apply(PublicIPAddress publicIPAddress) { - return publicIPAddress.properties().ipAddress(); - } - }).toSet(); - } - - private NodeMetadata.Status getStatus(String provisioningState) { - return STATUS_TO_NODESTATUS.get(provisioningStateFromString(provisioningState)); - } - - protected Location getLocation(final String locationName) { - return find(locations.get(), new Predicate<Location>() { - @Override - public boolean apply(Location location) { - return locationName != null && locationName.equals(location.getId()); - } - }, null); - } - - protected Optional<? extends Image> findImage(ImageReference imageReference, String locatioName) { - return Optional.fromNullable(images.get().get(VMImageToImage.encodeFieldsToUniqueId(false, locatioName, imageReference))); - } - - protected Hardware getHardware(final String vmSize) { - return Iterables.find(hardwares.get().values(), new Predicate<Hardware>() { - @Override - public boolean apply(Hardware input) { - return input.getId().equals(vmSize); - } - }); - } -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/8d223b1e/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/functions/DeploymentToVMDeployment.java ---------------------------------------------------------------------- diff --git a/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/functions/DeploymentToVMDeployment.java b/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/functions/DeploymentToVMDeployment.java deleted file mode 100644 index 2e3d12c..0000000 --- a/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/functions/DeploymentToVMDeployment.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.jclouds.azurecompute.arm.compute.functions; - -import java.util.List; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.azurecompute.arm.AzureComputeApi; -import org.jclouds.azurecompute.arm.domain.Deployment; -import org.jclouds.azurecompute.arm.domain.Deployment.Dependency; -import org.jclouds.azurecompute.arm.domain.NetworkInterfaceCard; -import org.jclouds.azurecompute.arm.domain.PublicIPAddress; -import org.jclouds.azurecompute.arm.domain.VMDeployment; -import org.jclouds.azurecompute.arm.domain.VirtualMachine; - -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.Iterables; - -/** - * Converts an Deployment into a VMDeployment. - */ -@Singleton -public class DeploymentToVMDeployment implements Function<Deployment, VMDeployment> { - - private final AzureComputeApi api; - - @Inject - DeploymentToVMDeployment(AzureComputeApi api) { - this.api = api; - } - - @Override - public VMDeployment apply(final Deployment deployment) { - if (deployment.properties() == null || deployment.properties().dependencies() == null) return null; - List<Dependency> dependencies = deployment.properties().dependencies(); - String resourceGroup = getResourceGroupFromId(deployment.id()); - - VirtualMachine virtualMachine = getVirtualMachine(dependencies, resourceGroup); - - List<NetworkInterfaceCard> networkInterfaceCards = getNetworkInterfaceCards(dependencies, resourceGroup); - List<PublicIPAddress> ipAddressList = getPublicIPAddress(dependencies, resourceGroup); - - return VMDeployment.create(deployment.name(), virtualMachine, ipAddressList, networkInterfaceCards); - } - - private VirtualMachine getVirtualMachine(List<Dependency> dependencies, String resourceGroup) { - Dependency dependency = Iterables.find(dependencies, new DependencyPredicate("Microsoft.Compute/virtualMachines")); - return api.getVirtualMachineApi(resourceGroup).get(dependency.resourceName()); - } - - private List<PublicIPAddress> getPublicIPAddress(List<Dependency> dependencies, final String resourceGroup) { - List<PublicIPAddress> list = FluentIterable.from(dependencies) - .filter(new DependencyPredicate("Microsoft.Network/networkInterfaces")) - .transformAndConcat(new Function<Dependency, Iterable<Dependency>>() { - @Override - public Iterable<Dependency> apply(Dependency input) { - return input.dependsOn(); - } - }).filter(new DependencyPredicate("Microsoft.Network/publicIPAddresses")) - .transform(new Function<Dependency, PublicIPAddress>() { - @Override - public PublicIPAddress apply(Dependency input) { - return api.getPublicIPAddressApi(resourceGroup).get(input.resourceName()); - } - }).toList(); - return list; - } - - private String getResourceGroupFromId(String id) { - String searchStr = "/resourceGroups/"; - int indexStart = id.lastIndexOf(searchStr) + searchStr.length(); - searchStr = "/providers/"; - int indexEnd = id.lastIndexOf(searchStr); - - String resourceGroup = id.substring(indexStart, indexEnd); - return resourceGroup; - } - - private List<NetworkInterfaceCard> getNetworkInterfaceCards(List<Dependency> dependencies, final String resourceGroup) { - List<NetworkInterfaceCard> result = FluentIterable.from(dependencies) - .filter(new DependencyPredicate("Microsoft.Network/networkInterfaces")) - .transform(new Function<Dependency, NetworkInterfaceCard>() { - @Override - public NetworkInterfaceCard apply(Dependency input) { - return api.getNetworkInterfaceCardApi(resourceGroup).get(input.resourceName()); - } - }).toList(); - return result; - } - - private static class DependencyPredicate implements Predicate<Dependency> { - - private final String resourceType; - - public DependencyPredicate(String resourceType) { - this.resourceType = resourceType; - } - - @Override - public boolean apply(Dependency dependency) { - return dependency.resourceType().equals(resourceType); - } - } -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/8d223b1e/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/config/AzureComputeHttpApiModule.java ---------------------------------------------------------------------- diff --git a/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/config/AzureComputeHttpApiModule.java b/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/config/AzureComputeHttpApiModule.java index bd1750f..991c738 100644 --- a/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/config/AzureComputeHttpApiModule.java +++ b/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/config/AzureComputeHttpApiModule.java @@ -18,7 +18,6 @@ package org.jclouds.azurecompute.arm.config; import org.jclouds.azurecompute.arm.AzureComputeApi; import org.jclouds.azurecompute.arm.handlers.AzureComputeErrorHandler; -import org.jclouds.azurecompute.arm.util.DeploymentTemplateBuilder; import org.jclouds.http.HttpErrorHandler; import org.jclouds.http.annotation.ClientError; import org.jclouds.http.annotation.Redirection; @@ -30,7 +29,6 @@ import org.jclouds.rest.ConfiguresHttpApi; import org.jclouds.rest.config.HttpApiModule; import com.google.inject.Scopes; -import com.google.inject.assistedinject.FactoryModuleBuilder; @ConfiguresHttpApi public class AzureComputeHttpApiModule extends HttpApiModule<AzureComputeApi> { @@ -51,7 +49,6 @@ public class AzureComputeHttpApiModule extends HttpApiModule<AzureComputeApi> { @Override protected void configure() { - install(new FactoryModuleBuilder().build(DeploymentTemplateBuilder.Factory.class)); super.configure(); bind(OAuthScopes.class).toInstance(OAuthScopes.NoScopes.create()); } http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/8d223b1e/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/util/DeploymentTemplateBuilder.java ---------------------------------------------------------------------- diff --git a/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/util/DeploymentTemplateBuilder.java b/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/util/DeploymentTemplateBuilder.java deleted file mode 100644 index 08f3a87..0000000 --- a/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/util/DeploymentTemplateBuilder.java +++ /dev/null @@ -1,547 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.jclouds.azurecompute.arm.util; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import org.jclouds.azurecompute.arm.compute.extensions.AzureComputeImageExtension; -import org.jclouds.azurecompute.arm.compute.options.AzureTemplateOptions; -import org.jclouds.azurecompute.arm.domain.DataDisk; -import org.jclouds.azurecompute.arm.domain.DeploymentBody; -import org.jclouds.azurecompute.arm.domain.DeploymentProperties; -import org.jclouds.azurecompute.arm.domain.DeploymentTemplate; -import org.jclouds.azurecompute.arm.domain.DiagnosticsProfile; -import org.jclouds.azurecompute.arm.domain.DnsSettings; -import org.jclouds.azurecompute.arm.domain.HardwareProfile; -import org.jclouds.azurecompute.arm.domain.IdReference; -import org.jclouds.azurecompute.arm.domain.ImageReference; -import org.jclouds.azurecompute.arm.domain.IpConfiguration; -import org.jclouds.azurecompute.arm.domain.IpConfigurationProperties; -import org.jclouds.azurecompute.arm.domain.KeyVaultReference; -import org.jclouds.azurecompute.arm.domain.NetworkInterfaceCardProperties; -import org.jclouds.azurecompute.arm.domain.NetworkProfile; -import org.jclouds.azurecompute.arm.domain.NetworkSecurityGroupProperties; -import org.jclouds.azurecompute.arm.domain.NetworkSecurityRule; -import org.jclouds.azurecompute.arm.domain.NetworkSecurityRuleProperties; -import org.jclouds.azurecompute.arm.domain.OSDisk; -import org.jclouds.azurecompute.arm.domain.OSProfile; -import org.jclouds.azurecompute.arm.domain.PublicIPAddressProperties; -import org.jclouds.azurecompute.arm.domain.ResourceDefinition; -import org.jclouds.azurecompute.arm.domain.StorageProfile; -import org.jclouds.azurecompute.arm.domain.StorageService; -import org.jclouds.azurecompute.arm.domain.StorageService.StorageServiceProperties; -import org.jclouds.azurecompute.arm.domain.TemplateParameterType; -import org.jclouds.azurecompute.arm.domain.VHD; -import org.jclouds.azurecompute.arm.domain.VirtualMachineProperties; -import org.jclouds.compute.domain.Template; -import org.jclouds.domain.LoginCredentials; -import org.jclouds.json.Json; -import org.jclouds.predicates.Validator; -import org.jclouds.predicates.validators.DnsNameValidator; - -import com.google.common.base.Function; -import com.google.common.base.Joiner; -import com.google.common.base.Preconditions; -import com.google.common.base.Strings; -import com.google.common.collect.Lists; -import com.google.inject.Inject; -import com.google.inject.assistedinject.Assisted; - -import static com.google.common.io.BaseEncoding.base64; -import static org.jclouds.azurecompute.arm.compute.extensions.AzureComputeImageExtension.CUSTOM_IMAGE_PREFIX; -import static org.jclouds.azurecompute.arm.config.AzureComputeProperties.STORAGE_API_VERSION; - -public class DeploymentTemplateBuilder { - public interface Factory { - DeploymentTemplateBuilder create(@Assisted("group") String group, @Assisted("name") String name, Template template); - } - - private final String name; - private final Template template; - private final Json json; - private final LoginCredentials loginCredentials; - - private AzureTemplateOptions options; - private Iterable<String> tags; - private Map<String, String> userMetaData; - private List<ResourceDefinition> resources; - private Map<String, String> variables; - private String location; - - private static final String DEPLOYMENT_MODE = "Incremental"; - - @Inject - DeploymentTemplateBuilder(Json json, @Assisted("group") String group, @Assisted("name") String name, @Assisted Template template, Function<Template, LoginCredentials> templateToLoginCredentials) { - this.name = name; - this.template = template; - this.options = template.getOptions().as(AzureTemplateOptions.class); - this.tags = template.getOptions().getTags(); - this.userMetaData = template.getOptions().getUserMetadata(); - this.variables = new HashMap<String, String>(); - this.resources = new ArrayList<ResourceDefinition>(); - this.location = template.getLocation().getId(); - this.json = json; - this.loginCredentials = templateToLoginCredentials.apply(template); - } - - public Template getTemplate() { - return template; - } - - public DeploymentBody getDeploymentTemplate() { - - addStorageResource(); - addPublicIpAddress(); - addNetworkSecurityGroup(); - addNetworkInterfaceCard(); - addVirtualMachine(); - - - DeploymentTemplate.TemplateParameters templateParameters = null; - DeploymentTemplate.Parameters parameters = null; - - if (keyVaultInUse()){ - String[] keyVaultInfo = options.getKeyVaultIdAndSecret().split(":"); - Preconditions.checkArgument(keyVaultInfo.length == 2); - String vaultId = keyVaultInfo[0].trim(); - String secretName = keyVaultInfo[1].trim(); - - templateParameters = DeploymentTemplate.TemplateParameters.create(TemplateParameterType.create("securestring")); - parameters = DeploymentTemplate.Parameters.create(KeyVaultReference.create(KeyVaultReference.Reference.create(IdReference.create(vaultId), secretName))); - } else { - templateParameters = DeploymentTemplate.TemplateParameters.create(null); - parameters = DeploymentTemplate.Parameters.create(null); - } - - - DeploymentTemplate template = DeploymentTemplate.builder() - .schema("https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#") - .contentVersion("1.0.0.0") - .resources(resources) - .variables(variables) - .parameters(templateParameters) - .build(); - - DeploymentBody body = DeploymentBody.create(template, DEPLOYMENT_MODE, parameters); - - return body; - } - - public String getDeploymentTemplateJson(DeploymentProperties properties) { - return json.toJson(properties); - } - - private void addStorageResource() { - String storageAccountName = null; - - String imageName = template.getImage().getName(); - if (imageName.startsWith(CUSTOM_IMAGE_PREFIX)) { - storageAccountName = template.getImage().getVersion(); - } - - if (Strings.isNullOrEmpty(storageAccountName)) { - storageAccountName = generateStorageAccountName(name); - } - - Validator<String> validator = new DnsNameValidator(3, 24); - validator.validate(storageAccountName); - - variables.put("storageAccountName", storageAccountName); - - ResourceDefinition storageAccount = ResourceDefinition.builder() - .name("[variables('storageAccountName')]") - .type("Microsoft.Storage/storageAccounts") - .location(location) - .apiVersion(STORAGE_API_VERSION) - .properties( - StorageServiceProperties.builder() - .accountType(StorageService.AccountType.Standard_LRS) - .build() - ) - .build(); - - resources.add(storageAccount); - } - - private void addPublicIpAddress() { - String publicIPAddressName = name + "publicip"; - String dnsLabelPrefix = options.getDNSLabelPrefix(); - - PublicIPAddressProperties.Builder properties = PublicIPAddressProperties.builder(); - - if (!Strings.isNullOrEmpty(dnsLabelPrefix)) { - properties.dnsSettings(DnsSettings.builder().domainNameLabel(dnsLabelPrefix).build()); - variables.put("dnsLabelPrefix", dnsLabelPrefix); - } - - properties.publicIPAllocationMethod("Dynamic"); - variables.put("publicIPAddressName", publicIPAddressName); - variables.put("publicIPAddressReference", "[resourceId('Microsoft.Network/publicIPAddresses',variables('publicIPAddressName'))]"); - - ResourceDefinition publicIpAddress = ResourceDefinition.builder() - .name("[variables('publicIPAddressName')]") - .type("Microsoft.Network/publicIPAddresses") - .location(location) - .apiVersion(STORAGE_API_VERSION) - .properties(properties.build()) - .build(); - - resources.add(publicIpAddress); - } - - private void addNetworkInterfaceCard() { - - List<IpConfiguration> ipConfigurations = new ArrayList<IpConfiguration>(); - - String ipConfigurationName = name + "ipconfig"; - String subnetId = options.getSubnetId(); - - variables.put("ipConfigurationName", ipConfigurationName); - variables.put("subnetReference", subnetId); - - IpConfiguration ipConfig = IpConfiguration.create(ipConfigurationName, null, null, null, - IpConfigurationProperties.builder() - .privateIPAllocationMethod("Dynamic") - .publicIPAddress(IdReference.create("[variables('publicIPAddressReference')]")) - .subnet(IdReference.create("[variables('subnetReference')]")) - .build()); - - ipConfigurations.add(ipConfig); - - // Check to see if we have defined a network security group - IdReference networkSecurityGroup = null; - int ports[] = options.getInboundPorts(); - if ((ports != null) && (ports.length > 0)) { - networkSecurityGroup = IdReference.create("[variables('networkSecurityGroupNameReference')]"); - } - - ArrayList<String> depends = new ArrayList<String>(Arrays.asList("[concat('Microsoft.Network/publicIPAddresses/', variables('publicIPAddressName'))]")); - - NetworkInterfaceCardProperties.Builder networkInterfaceCardPropertiesBuilder = NetworkInterfaceCardProperties.builder(); - networkInterfaceCardPropertiesBuilder.ipConfigurations(ipConfigurations); - if (networkSecurityGroup != null) { - networkInterfaceCardPropertiesBuilder.networkSecurityGroup(networkSecurityGroup); - depends.add("[concat('Microsoft.Network/networkSecurityGroups/', variables('networkSecurityGroupName'))]"); - } - NetworkInterfaceCardProperties networkInterfaceCardProperties = networkInterfaceCardPropertiesBuilder.build(); - - String networkInterfaceCardName = name + "nic"; - variables.put("networkInterfaceCardName", networkInterfaceCardName); - variables.put("networkInterfaceCardReference", "[resourceId('Microsoft.Network/networkInterfaces',variables('networkInterfaceCardName'))]"); - - ResourceDefinition networkInterfaceCard = ResourceDefinition.builder() - .name("[variables('networkInterfaceCardName')]") - .type("Microsoft.Network/networkInterfaces") - .location(location) - .apiVersion(STORAGE_API_VERSION) - .dependsOn(depends) - .properties(networkInterfaceCardProperties) - .build(); - - resources.add(networkInterfaceCard); - } - - private void addNetworkSecurityGroup() { - int inboundPorts[] = options.getInboundPorts(); - if ((inboundPorts != null) && (inboundPorts.length > 0)) { - variables.put("networkSecurityGroupName", name + "nsg"); - variables.put("networkSecurityGroupNameReference", "[resourceId('Microsoft.Network/networkSecurityGroups',variables('networkSecurityGroupName'))]"); - - List<String> portRanges = simplifyPorts(inboundPorts); - - List<NetworkSecurityRule> rules = new ArrayList<NetworkSecurityRule>(); - int priority = 1234; - for (String portRange : portRanges) { - NetworkSecurityRuleProperties ruleProperties = NetworkSecurityRuleProperties.builder() - .description("default-allow-port-" + portRange) - .protocol(NetworkSecurityRuleProperties.Protocol.All) - .access(NetworkSecurityRuleProperties.Access.Allow) - .sourcePortRange("*") - .destinationPortRange(portRange) - .sourceAddressPrefix("*") - .destinationAddressPrefix("*") - .priority(priority) - .direction(NetworkSecurityRuleProperties.Direction.Inbound) - .build(); - - NetworkSecurityRule networkSecurityRule = NetworkSecurityRule.create( - "default-allow-port-" + portRange, - null, - null, - ruleProperties); - - rules.add(networkSecurityRule); - priority++; - } - - NetworkSecurityGroupProperties networkSecurityGroupProperties = NetworkSecurityGroupProperties.builder() - .securityRules(rules) - .build(); - - ResourceDefinition networkSecurityGroup = ResourceDefinition.builder() - .name("[variables('networkSecurityGroupName')]") - .type("Microsoft.Network/networkSecurityGroups").location(location) - .apiVersion(STORAGE_API_VERSION) - .properties(networkSecurityGroupProperties) - .build(); - resources.add(networkSecurityGroup); - } - - } - - /** - * Helper function for simplifying an array of ports to a list of ranges as list of strings - * @param ports array of int - * @return list of strings representing ranges - */ - public static List<String> simplifyPorts(int[] ports) { - Preconditions.checkArgument(ports != null && ports.length != 0); - ArrayList<String> output = new ArrayList<String>(); - Arrays.sort(ports); - - int range_start = ports[0]; - int range_end = ports[0]; - for (int i = 1; i < ports.length; i++) { - if ((ports[i - 1] == ports[i] - 1) || (ports[i - 1] == ports[i])){ - // Range continues. - range_end = ports[i]; - } - else { - // Range ends. - output.add(formatRange(range_start, range_end)); - range_start = ports[i]; - range_end = ports[i]; - } - } - // Make sure we get the last range. - output.add(formatRange(range_start, range_end)); - return output; - } - - private static String formatRange(int start, int finish) { - if (start == finish){ - return Integer.toString(start); - } - else { - return String.format("%s-%s", Integer.toString(start), Integer.toString(finish)); - } - } - - private void addVirtualMachine() { - //Build OS Profile - final String computerName = name + "pc"; - - variables.put("loginUser", loginCredentials.getUser()); - OSProfile.Builder profileBuilder = OSProfile.builder() - .adminUsername(loginCredentials.getUser()) - .computerName(computerName); - - boolean usePublicKey = options.getPublicKey() != null; - - if (usePublicKey || keyVaultInUse()) { - OSProfile.LinuxConfiguration configuration = OSProfile.LinuxConfiguration.create("true", - OSProfile.LinuxConfiguration.SSH.create(Arrays.asList( - OSProfile.LinuxConfiguration.SSH.SSHPublicKey.create( - "[concat('/home/',variables('loginUser'),'/.ssh/authorized_keys')]", - keyVaultInUse() ? "[parameters('publicKeyFromAzureKeyVault')]" : options.getPublicKey()) - )) - ); - profileBuilder.linuxConfiguration(configuration); - } else if (loginCredentials.getOptionalPassword().isPresent()) { - profileBuilder.adminPassword(loginCredentials.getOptionalPassword().get()); - } - - if (!Strings.isNullOrEmpty(options.getCustomData())){ - String encodedCustomData = base64().encode(options.getCustomData().getBytes()); - profileBuilder.customData(encodedCustomData); - } - - OSProfile osProfile = profileBuilder.build(); - - //Build OsDisk - final String storageAccountContainerName = name + "vhds"; - variables.put("storageAccountContainerName", storageAccountContainerName); - - final String osDiskName = name + "osdisk"; - variables.put("osDiskName", osDiskName); - - boolean usingMarketplaceImage = true; - String cusotomImageUri = ""; - - // Handle custom image case if description starts with CUSTOM_IMAGE_PREFIX - String vhd1 = template.getImage().getProviderId(); - String description = template.getImage().getDescription(); - if (description.substring(0, CUSTOM_IMAGE_PREFIX.length()).equals(CUSTOM_IMAGE_PREFIX)) { - String storageName = template.getImage().getVersion(); - cusotomImageUri = vhd1; - cusotomImageUri = "https://" + storageName + ".blob.core.windows.net/system/Microsoft.Compute/Images/" + AzureComputeImageExtension.CONTAINER_NAME + "/" + cusotomImageUri; - } - - if (!cusotomImageUri.isEmpty()) { - usingMarketplaceImage = false; - } - - OSDisk osDisk = getOsDisk("[concat('http://',variables('storageAccountName'),'.blob.core.windows.net/',variables('storageAccountContainerName'),'/',variables('osDiskName'),'.vhd')]", cusotomImageUri); - - //Create Data Disk(s) and add to list - final String dataDiskName = name + "datadisk"; - variables.put("dataDiskName", dataDiskName); - final String dataDiskSize = "100"; - - List<DataDisk> dataDisks = new ArrayList<DataDisk>(); - DataDisk dataDisk = DataDisk.builder() - .name("[variables('dataDiskName')]") - .diskSizeGB(dataDiskSize) - .lun(0) - .vhd( - VHD.create("[concat('http://',variables('storageAccountName'),'.blob.core.windows.net/',variables('storageAccountContainerName'),'/',variables('dataDiskName'),'.vhd')]") - ) - .createOption("Empty") - .build(); - - dataDisks.add(dataDisk); - - //Create Storage Profile - StorageProfile.Builder storageProfileBuilder = StorageProfile.builder() - .osDisk(osDisk) - .dataDisks(dataDisks); - - if (usingMarketplaceImage) { - //Build Image Reference if marketplace image is used - ImageReference imageReference = getImageReference(template.getImage().getProviderId(), - template.getImage().getName(), - template.getImage().getVersion()); - - storageProfileBuilder.imageReference(imageReference); - } - StorageProfile storageProfile = storageProfileBuilder.build(); - - - //Create Network Profile for this VM (links to network interface cards) - NetworkProfile networkProfile = NetworkProfile.create( - Arrays.asList( - IdReference.create("[variables('networkInterfaceCardReference')]") - )); - - //Boot Diagnostics - DiagnosticsProfile diagnosticsProfile = DiagnosticsProfile.create( - DiagnosticsProfile.BootDiagnostics.builder() - .enabled(true) - .storageUri("[concat('http://',variables('storageAccountName'),'.blob.core.windows.net')]") - .build()); - - //Build VirtualMachine properties based on above properties. - final String vmSize = template.getHardware().getId(); - HardwareProfile hw = HardwareProfile.create(vmSize); - - VirtualMachineProperties properties = VirtualMachineProperties.builder() - .hardwareProfile(hw) - .osProfile(osProfile) - .storageProfile(storageProfile) - .networkProfile(networkProfile) - .diagnosticsProfile(diagnosticsProfile) - .build(); - - - String tagString = Joiner.on(",").join(Lists.newArrayList(tags)); - if (tagString.isEmpty()) - tagString = "jclouds"; - userMetaData.put("tags", tagString); - - variables.put("virtualMachineName", name); - ResourceDefinition virtualMachine = ResourceDefinition.builder() - .name("[variables('virtualMachineName')]") - .type("Microsoft.Compute/virtualMachines") - .location(location) - .apiVersion("2015-06-15") - .dependsOn(Arrays.asList("[concat('Microsoft.Storage/storageAccounts/', variables('storageAccountName'))]", - "[concat('Microsoft.Network/networkInterfaces/', variables('networkInterfaceCardName'))]")) - .tags(userMetaData) - .properties(properties) - .build(); - - resources.add(virtualMachine); - } - - - private ImageReference getImageReference(String publisher, String offer, String sku) { - return ImageReference.builder() - .publisher(publisher) - .offer(offer) - .sku(sku) - .version("latest") - .build(); - - } - - private OSDisk getOsDisk(String vhdUri, String imageUri) { - OSDisk.Builder builder = OSDisk.builder(); - builder.name("[variables('osDiskName')]"); - builder.caching("ReadWrite"); - builder.createOption("FromImage"); - builder.vhd(VHD.create(vhdUri)); - - if (!imageUri.isEmpty()) { - builder.osType("Linux"); - builder.image(VHD.create(imageUri)); - } - return builder.build(); - } - - private boolean keyVaultInUse(){ - return !Strings.isNullOrEmpty(options.getKeyVaultIdAndSecret()); - } - - /** - * Generates a valid storage account - * - * Storage account names must be between 3 and 24 characters in length and may contain numbers and lowercase letters only. - * - * @param name the node name - * @return the storage account name starting from a sanitized name (with only numbers and lowercase letters only ). - * If sanitized name is between 3 and 24 characters, storage account name is equals to sanitized name. - * If sanitized name is less than 3 characters, storage account is sanitized name plus 4 random chars. - * If sanitized name is more than 24 characters, storage account is first 10 chars of sanitized name plus 4 random chars plus last 10 chars of sanitized name. - */ - public static String generateStorageAccountName(String name) { - String storageAccountName = name.replaceAll("[^a-z0-9]", ""); - int nameLength = storageAccountName.length(); - if (nameLength >= 3 && nameLength <= 24) { - return storageAccountName; - } - - String random = UUID.randomUUID().toString().replaceAll("[^a-z0-9]", "").substring(0, 4); - if (nameLength < 3) { - storageAccountName = new StringBuilder().append(storageAccountName).append(random).toString(); - } - if (nameLength > 24) { - storageAccountName = shorten(storageAccountName, random); - } - return storageAccountName; - } - - private static String shorten(String storageAccountName, String random) { - String prefix = storageAccountName.substring(0, 10); - String suffix = storageAccountName.substring(storageAccountName.length() - 10, storageAccountName.length()); - return String.format("%s%s%s", prefix, random, suffix); - } -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/8d223b1e/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/DeploymentApiLiveTest.java ---------------------------------------------------------------------- diff --git a/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/DeploymentApiLiveTest.java b/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/DeploymentApiLiveTest.java index 7476828..fe4c3ee 100644 --- a/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/DeploymentApiLiveTest.java +++ b/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/DeploymentApiLiveTest.java @@ -22,12 +22,9 @@ import java.util.List; import org.jclouds.azurecompute.arm.compute.options.AzureTemplateOptions; import org.jclouds.azurecompute.arm.domain.Deployment; import org.jclouds.azurecompute.arm.domain.Deployment.ProvisioningState; -import org.jclouds.azurecompute.arm.domain.DeploymentBody; -import org.jclouds.azurecompute.arm.domain.DeploymentProperties; import org.jclouds.azurecompute.arm.domain.Subnet; import org.jclouds.azurecompute.arm.domain.VirtualNetwork; import org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest; -import org.jclouds.azurecompute.arm.util.DeploymentTemplateBuilder; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.HardwareBuilder; import org.jclouds.compute.domain.Image; @@ -137,12 +134,6 @@ public class DeploymentApiLiveTest extends BaseAzureComputeApiLiveTest { return new TemplateImpl(image, hardware, region, options); } - private DeploymentTemplateBuilder getDeploymentTemplateBuilderWithOptions(TemplateOptions options) { - Template template = getTemplate(options); - DeploymentTemplateBuilder templateBuilder = api.deploymentTemplateFactory().create(resourceGroupName, deploymentName, template); - return templateBuilder; - } - @Test public void testValidate(){ Deployment deploymentInvalid = null; @@ -168,12 +159,40 @@ public class DeploymentApiLiveTest extends BaseAzureComputeApiLiveTest { AzureTemplateOptions options = new AzureTemplateOptions(); options.authorizePublicKey(rsakey); options.subnetId(subnetId); - DeploymentTemplateBuilder templateBuilder = getDeploymentTemplateBuilderWithOptions(options); - DeploymentBody deploymentTemplateBody = templateBuilder.getDeploymentTemplate(); - DeploymentProperties properties = DeploymentProperties.create(deploymentTemplateBody); - - String deploymentTemplate = templateBuilder.getDeploymentTemplateJson(properties); + String deploymentTemplate = "{\n" + + " \"id\": \"/subscriptions/04f7ec88-8e28-41ed-8537-5e17766001f5/resourceGroups/jims216group/providers/Microsoft.Resources/deployments/jcdep1458344383064\",\n" + + " \"name\": \"jcdep1458344383064\",\n" + + " \"properties\": {\n" + + " \"parameters\": {\n" + + " \"newStorageAccountName\": {\n" + + " \"type\": \"String\",\n" + + " \"value\": \"jcres1458344383064\"\n" + + " },\n" + + " \"storageAccountType\": {\n" + + " \"type\": \"String\",\n" + + " \"value\": \"Standard_LRS\"\n" + + " },\n" + + " \"location\": {\n" + + " \"type\": \"String\",\n" + + " \"value\": \"West US\"\n" + + " }\n" + + " },\n" + + " \"mode\": \"Incremental\",\n" + + " \"provisioningState\": \"Accepted\",\n" + + " \"timestamp\": \"2016-03-18T23:39:47.3048037Z\",\n" + + " \"duration\": \"PT2.4433028S\",\n" + + " \"correlationId\": \"8dee9711-8632-4948-9fe6-368bb75e6438\",\n" + + " \"providers\": [{\n" + + " \"namespace\": \"Microsoft.Storage\",\n" + + " \"resourceTypes\": [{\n" + + " \"resourceType\": \"storageAccounts\",\n" + + " \"locations\": [\"westus\"]\n" + + " }]\n" + + " }],\n" + + " \"dependencies\": []\n" + + " }\n" + + "}"; deploymentTemplate = UrlEscapers.urlFormParameterEscaper().escape(deploymentTemplate); Deployment deploymentValid = api().validate(deploymentName, deploymentTemplate); http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/8d223b1e/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/DeploymentTemplateBuilderTest.java ---------------------------------------------------------------------- diff --git a/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/DeploymentTemplateBuilderTest.java b/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/DeploymentTemplateBuilderTest.java deleted file mode 100644 index d14e3c6..0000000 --- a/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/DeploymentTemplateBuilderTest.java +++ /dev/null @@ -1,296 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.jclouds.azurecompute.arm.features; - -import java.util.List; -import java.util.Map; - -import org.jclouds.azurecompute.arm.compute.options.AzureTemplateOptions; -import org.jclouds.azurecompute.arm.domain.DeploymentBody; -import org.jclouds.azurecompute.arm.domain.ImageReference; -import org.jclouds.azurecompute.arm.domain.IpConfiguration; -import org.jclouds.azurecompute.arm.domain.IpConfigurationProperties; -import org.jclouds.azurecompute.arm.domain.NetworkInterfaceCardProperties; -import org.jclouds.azurecompute.arm.domain.PublicIPAddressProperties; -import org.jclouds.azurecompute.arm.domain.ResourceDefinition; -import org.jclouds.azurecompute.arm.domain.StorageService; -import org.jclouds.azurecompute.arm.domain.StorageService.StorageServiceProperties; -import org.jclouds.azurecompute.arm.domain.VirtualMachineProperties; -import org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest; -import org.jclouds.azurecompute.arm.util.DeploymentTemplateBuilder; -import org.jclouds.compute.domain.Hardware; -import org.jclouds.compute.domain.HardwareBuilder; -import org.jclouds.compute.domain.Image; -import org.jclouds.compute.domain.ImageBuilder; -import org.jclouds.compute.domain.OperatingSystem; -import org.jclouds.compute.domain.Template; -import org.jclouds.compute.domain.internal.TemplateImpl; -import org.jclouds.compute.options.TemplateOptions; -import org.jclouds.domain.Location; -import org.jclouds.domain.LocationBuilder; -import org.jclouds.domain.LocationScope; -import org.jclouds.domain.LoginCredentials; -import org.testng.Assert; -import org.testng.annotations.Test; - -import com.google.common.collect.Iterables; -import com.google.inject.Key; -import com.google.inject.name.Names; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; - -@Test(groups = "unit", testName = "DeploymentTemplateBuilderTest", singleThreaded = true) -public class DeploymentTemplateBuilderTest extends BaseAzureComputeApiMockTest { - - final String group = "jcgroup"; - final String vnetName = group + "virtualnetwork"; - final String subnetId = ""; - - @Test - public void testResourceGroup() { - DeploymentTemplateBuilder builder = getMockDeploymentTemplateBuilderWithEmptyOptions(); - DeploymentBody deploymentBody = builder.getDeploymentTemplate(); - List<ResourceDefinition> resources = deploymentBody.template().resources(); - Map<String, String> variables = deploymentBody.template().variables(); - - ResourceDefinition resource = getResourceByType(resources, "Microsoft.Storage/storageAccounts"); - - StorageServiceProperties properties = (StorageServiceProperties) resource.properties(); - assertEquals(properties.accountType(), StorageService.AccountType.Standard_LRS); - assertTrue(variables.containsKey(parseVariableName(resource.name()))); - } - - @Test - void testPublicIpAddress() { - DeploymentTemplateBuilder builder = getMockDeploymentTemplateBuilderWithEmptyOptions(); - DeploymentBody deploymentBody = builder.getDeploymentTemplate(); - List<ResourceDefinition> resources = deploymentBody.template().resources(); - Map<String, String> variables = deploymentBody.template().variables(); - - ResourceDefinition resource = getResourceByType(resources, "Microsoft.Network/publicIPAddresses"); - - PublicIPAddressProperties properties = (PublicIPAddressProperties) resource.properties(); - assertEquals(properties.publicIPAllocationMethod(), "Dynamic"); - assertTrue(variables.containsKey(parseVariableName(resource.name()))); - } - - @Test - void testNetworkInterfaceCard() { - DeploymentTemplateBuilder builder = getMockDeploymentTemplateBuilderWithEmptyOptions(); - DeploymentBody deploymentBody = builder.getDeploymentTemplate(); - List<ResourceDefinition> resources = deploymentBody.template().resources(); - Map<String, String> variables = deploymentBody.template().variables(); - - ResourceDefinition resource = getResourceByType(resources, "Microsoft.Network/networkInterfaces"); - - NetworkInterfaceCardProperties properties = (NetworkInterfaceCardProperties) resource.properties(); - List<IpConfiguration> ipConfigs = properties.ipConfigurations(); - assertTrue(ipConfigs.size() > 0); - IpConfigurationProperties ipProperties = ipConfigs.get(0).properties(); - assertEquals(ipProperties.privateIPAllocationMethod(), "Dynamic"); - assertNotNull(ipProperties.publicIPAddress()); - assertNotNull(ipProperties.subnet()); - - assertTrue(variables.containsKey(parseVariableName(resource.name()))); - } - - @Test - void testVirtualMachine() { - DeploymentTemplateBuilder builder = getMockDeploymentTemplateBuilderWithEmptyOptions(); - Template template = builder.getTemplate(); - - DeploymentBody deploymentBody = builder.getDeploymentTemplate(); - List<ResourceDefinition> resources = deploymentBody.template().resources(); - Map<String, String> variables = deploymentBody.template().variables(); - - ResourceDefinition resource = getResourceByType(resources, "Microsoft.Compute/virtualMachines"); - assertNotNull(resource); - - VirtualMachineProperties properties = (VirtualMachineProperties) resource.properties(); - assertEquals(properties.hardwareProfile().vmSize(), template.getHardware().getId()); - - ImageReference image = properties.storageProfile().imageReference(); - assertEquals(image.publisher(), template.getImage().getProviderId()); - assertEquals(image.offer(), template.getImage().getName()); - assertEquals(image.sku(), template.getImage().getVersion()); - assertEquals(image.version(), "latest"); - - assertTrue(variables.containsKey(parseVariableName(resource.name()))); - } - - @Test - void testAddStorageResourceWhenNameIsLongerThan24Chars() { - String name = "thishasmorethan24characters"; - DeploymentTemplateBuilder builder = getMockDeploymentTemplateBuilderWithEmptyOptions(name); - - DeploymentBody deploymentBody = builder.getDeploymentTemplate(); - assertTrue(Iterables.contains(deploymentBody.template().variables().keySet(), "storageAccountName")); - String storageAccountName = deploymentBody.template().variables().get("storageAccountName"); - assertEquals(storageAccountName.length(), 24); - assertEquals(storageAccountName.substring(0, 10), "thishasmor"); - assertEquals(storageAccountName.substring(storageAccountName.length() - 10, storageAccountName.length()), "characters"); - } - - @Test - void testAddStorageResourceWhenNameIsExactly24Chars() { - String name = "ithasexactly24characters"; - DeploymentTemplateBuilder builder = getMockDeploymentTemplateBuilderWithEmptyOptions(name); - - DeploymentBody deploymentBody = builder.getDeploymentTemplate(); - assertTrue(Iterables.contains(deploymentBody.template().variables().keySet(), "storageAccountName")); - assertEquals(deploymentBody.template().variables().get("storageAccountName").length(), 24); - assertEquals(deploymentBody.template().variables().get("storageAccountName"), name); - } - - @Test - void testAddStorageResourceWhenNameIsLessThan3Chars() { - String name = "3c"; - DeploymentTemplateBuilder builder = getMockDeploymentTemplateBuilderWithEmptyOptions(name); - - DeploymentBody deploymentBody = builder.getDeploymentTemplate(); - assertTrue(Iterables.contains(deploymentBody.template().variables().keySet(), "storageAccountName")); - assertEquals(deploymentBody.template().variables().get("storageAccountName").length(), 6); - assertEquals(deploymentBody.template().variables().get("storageAccountName").substring(0, 2), name); - } - - @Test - void testCustomOptions(){ - final String dnsLabelPrefix = "mydnslabel"; - final String customData = "echo customData"; - final String customData64 = "ZWNobyBjdXN0b21EYXRh"; - final String keyvaultString = "/url/to/vault/:publickeysecret"; - - AzureTemplateOptions options = new AzureTemplateOptions() - .customData(customData) - .DNSLabelPrefix(dnsLabelPrefix) - .keyVaultIdAndSecret(keyvaultString); - - options.virtualNetworkName(vnetName); - options.subnetId(subnetId); - - assertEquals(options.as(AzureTemplateOptions.class).getCustomData(), customData); - assertEquals(options.getDNSLabelPrefix(), dnsLabelPrefix); - assertEquals(options.as(AzureTemplateOptions.class).getKeyVaultIdAndSecret(), keyvaultString); - - DeploymentTemplateBuilder builder = getMockDeploymentTemplateBuilderWithOptions(options); - - DeploymentBody deploymentBody = builder.getDeploymentTemplate(); - - List<ResourceDefinition> resources = deploymentBody.template().resources(); - ResourceDefinition publicIpResource = getResourceByType(resources, "Microsoft.Network/publicIPAddresses"); - assertNotNull(publicIpResource); - - PublicIPAddressProperties ipProperties = (PublicIPAddressProperties) publicIpResource.properties(); - assertEquals(ipProperties.dnsSettings().domainNameLabel(), dnsLabelPrefix); - - ResourceDefinition vmResource = getResourceByType(resources, "Microsoft.Compute/virtualMachines"); - assertNotNull(vmResource); - - VirtualMachineProperties virtualMachineProperties = (VirtualMachineProperties) vmResource.properties(); - assertEquals(virtualMachineProperties.osProfile().customData(), customData64); - - //populated when keyvault is used to get public key. - assertNotNull(virtualMachineProperties.osProfile().linuxConfiguration().ssh().publicKeys()); - } - - @Test(expectedExceptions = IllegalArgumentException.class) - void testSimplifyPortsWithPortsNull() { - int[] ports = null; - DeploymentTemplateBuilder.simplifyPorts(ports); - } - - @Test(expectedExceptions = IllegalArgumentException.class) - void testSimplifyPortsWithPortsEmpty() { - int[] ports = new int[0]; - DeploymentTemplateBuilder.simplifyPorts(ports); - } - - @Test - void testSimplifyPorts() { - int[] ports = {8084, 22, 8081, 8080, 8082}; - List<String> ranges = DeploymentTemplateBuilder.simplifyPorts(ports); - assertEquals(ranges.size(), 3); - assertEquals(ranges.get(0), "22"); - assertEquals(ranges.get(1), "8080-8082"); - assertEquals(ranges.get(2), "8084"); - } - - private Template getMockTemplate(TemplateOptions options) { - options.as(AzureTemplateOptions.class).virtualNetworkName(vnetName); - options.as(AzureTemplateOptions.class).subnetId(subnetId); - - LoginCredentials defaultImageCredentials = context.utils().injector() - .getInstance(Key.get(LoginCredentials.class, Names.named("image"))); - - Location provider = (new LocationBuilder()).scope(LocationScope.PROVIDER).id("azurecompute-arm").description("azurecompute-arm").build(); - Location region = (new LocationBuilder()).scope(LocationScope.REGION).id("northeurope").description("North Europe").parent(provider).build(); - OperatingSystem os = OperatingSystem.builder().name("osName").version("osVersion").description("osDescription").arch("X86_32").build(); - //Note that version is set to "latest" - - Image image = (new ImageBuilder()).id("imageId").providerId("imageId").name("imageName") - .description("imageDescription").version("sku").operatingSystem(os).status(Image.Status.AVAILABLE) - .location(region).defaultCredentials(defaultImageCredentials).build(); - Hardware hardware = (new HardwareBuilder()).id("Standard_A0").build(); - return new TemplateImpl(image, hardware, region, options); - } - - private DeploymentTemplateBuilder getMockDeploymentTemplateBuilderWithEmptyOptions() { - return getMockDeploymentTemplateBuilderWithEmptyOptions("mydeployment"); - } - - private DeploymentTemplateBuilder getMockDeploymentTemplateBuilderWithEmptyOptions(String name) { - AzureTemplateOptions options = new AzureTemplateOptions(); - options.virtualNetworkName(vnetName); - options.subnetId(subnetId); - - Template template = getMockTemplate(options); - DeploymentTemplateBuilder templateBuilder = api.deploymentTemplateFactory().create(group, name, template); - return templateBuilder; - } - - private DeploymentTemplateBuilder getMockDeploymentTemplateBuilderWithOptions(TemplateOptions options) { - return getMockDeploymentTemplateBuilderWithOptions("mydeployment", options); - } - - private DeploymentTemplateBuilder getMockDeploymentTemplateBuilderWithOptions(String name, TemplateOptions options) { - ((AzureTemplateOptions)options).virtualNetworkName(vnetName); - ((AzureTemplateOptions)options).subnetId(subnetId); - - Template template = getMockTemplate(options); - DeploymentTemplateBuilder templateBuilder = api.deploymentTemplateFactory().create(group, name, template); - return templateBuilder; - } - - private ResourceDefinition getResourceByType(List<ResourceDefinition> resources, String type) { - for (ResourceDefinition r : resources) { - if (r.type().equals(type)) { - return r; - } - } - Assert.fail("Resource with type: " + type + " not found"); - return null; - } - - private String parseVariableName(String variable) { - String[] parts = variable.split("\'"); - assertTrue(parts.length == 3); - return parts[1]; - } -} - http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/8d223b1e/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/TemplateToDeploymentTemplateLiveTest.java ---------------------------------------------------------------------- diff --git a/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/TemplateToDeploymentTemplateLiveTest.java b/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/TemplateToDeploymentTemplateLiveTest.java deleted file mode 100644 index 3b87663..0000000 --- a/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/TemplateToDeploymentTemplateLiveTest.java +++ /dev/null @@ -1,281 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.jclouds.azurecompute.arm.features; - -import java.net.URI; - -import org.jclouds.azurecompute.arm.compute.options.AzureTemplateOptions; -import org.jclouds.azurecompute.arm.domain.Deployment; -import org.jclouds.azurecompute.arm.domain.DeploymentBody; -import org.jclouds.azurecompute.arm.domain.DeploymentProperties; -import org.jclouds.azurecompute.arm.domain.Subnet; -import org.jclouds.azurecompute.arm.domain.VirtualNetwork; -import org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest; -import org.jclouds.azurecompute.arm.util.DeploymentTemplateBuilder; -import org.jclouds.compute.domain.Hardware; -import org.jclouds.compute.domain.HardwareBuilder; -import org.jclouds.compute.domain.Image; -import org.jclouds.compute.domain.ImageBuilder; -import org.jclouds.compute.domain.OperatingSystem; -import org.jclouds.compute.domain.OsFamily; -import org.jclouds.compute.domain.Template; -import org.jclouds.compute.domain.internal.TemplateImpl; -import org.jclouds.compute.options.TemplateOptions; -import org.jclouds.domain.Location; -import org.jclouds.domain.LocationBuilder; -import org.jclouds.domain.LocationScope; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import com.google.common.net.UrlEscapers; - -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; - -@Test(groups = "live", testName = "TemplateToDeploymentTemplateLiveTest", singleThreaded = true) -public class TemplateToDeploymentTemplateLiveTest extends BaseAzureComputeApiLiveTest { - - private int maxTestDuration = 400; - private int pollingInterval = 3; // how frequently to poll for create status - private String resourceGroupName; - private String deploymentName; - private String vnetName; - private String subnetId; - private String virtualNetworkName; - - @BeforeClass - @Override - public void setup() { - super.setup(); - resourceGroupName = String.format("rg-%s-%s", this.getClass().getSimpleName().toLowerCase(), System.getProperty("user.name")); - assertNotNull(createResourceGroup(resourceGroupName)); - virtualNetworkName = String.format("vn-%s-%s", this.getClass().getSimpleName().toLowerCase(), System.getProperty("user.name")); - - //Subnets belong to a virtual network so that needs to be created first - VirtualNetwork vn = createDefaultVirtualNetwork(resourceGroupName, virtualNetworkName, "10.2.0.0/16", LOCATION); - assertNotNull(vn); - vnetName = vn.name(); - - //Subnet needs to be up & running before NIC can be created - String subnetName = String.format("s-%s-%s", this.getClass().getSimpleName().toLowerCase(), System.getProperty("user.name")); - Subnet subnet = createDefaultSubnet(resourceGroupName, subnetName, virtualNetworkName, "10.2.0.0/23"); - assertNotNull(subnet); - assertNotNull(subnet.id()); - subnetId = subnet.id(); - } - - @AfterClass - @Override - protected void tearDown() { - super.tearDown(); - URI uri = deleteResourceGroup(resourceGroupName); - assertResourceDeleted(uri); - } - - @Test - public void testValidateDeploymentTemplateLinuxNodeWithOptions() { - Long now = System.currentTimeMillis(); - deploymentName = "jc" + now; - - AzureTemplateOptions options = new AzureTemplateOptions(); - options.virtualNetworkName(vnetName); - options.subnetId(subnetId); - - options.inboundPorts(22, 8080); - - DeploymentTemplateBuilder templateBuilder = getDeploymentTemplateBuilderWithOptions(options); - - DeploymentBody deploymentTemplateBody = templateBuilder.getDeploymentTemplate(); - - DeploymentProperties properties = DeploymentProperties.create(deploymentTemplateBody); - - String deploymentTemplate = templateBuilder.getDeploymentTemplateJson(properties); - deploymentTemplate = UrlEscapers.urlFormParameterEscaper().escape(deploymentTemplate); - - //Validates that template is syntactically correct - Deployment deployment = api().validate(deploymentName, deploymentTemplate); - assertNotNull(deployment); - } - - @Test - public void testValidateDeploymentTemplateLinuxNode() { - Long now = System.currentTimeMillis(); - deploymentName = "jc" + now; - - DeploymentTemplateBuilder templateBuilder = getDeploymentTemplateBuilderWithEmptyOptions(); - - DeploymentBody deploymentTemplateBody = templateBuilder.getDeploymentTemplate(); - - DeploymentProperties properties = DeploymentProperties.create(deploymentTemplateBody); - - String deploymentTemplate = templateBuilder.getDeploymentTemplateJson(properties); - deploymentTemplate = UrlEscapers.urlFormParameterEscaper().escape(deploymentTemplate); - - //Validates that template is syntactically correct - Deployment deployment = api().validate(deploymentName, deploymentTemplate); - assertNotNull(deployment); - } - - @Test - public void testValidateDeploymentTemplateWithCustomOptions() { - Long now = System.currentTimeMillis(); - deploymentName = "jc" + now; - - String rsakey = new String("ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAQEAmfk/QSF0pvnrpdz+Ah2KulGruKU+8FFBdlw938MpOysRdmp7uwpH6Z7+5VNGNdxFIAyc/W3UaZXF9hTsU8+78TlwkZpsr2mzU+ycu37XLAQ8Uv7hjsAN0DkKKPrZ9lgUUfZVKV/8E/JIAs03gIbL6zO3y7eYJQ5fNeZb+nji7tQT+YLpGq/FDegvraPKVMQbCSCZhsHyWhdPLyFlu9/30npZ0ahYOPI/KyZxFDtM/pHp88+ZAk9Icq5owaLRWcJQqrBGWqjbZnHtjdDqvHZ+C0wPhdJZPyfkHOrSYTwSQBXfX4JLRRCz3J1jf62MbQWT1o6Y4JEs1ZP1Skxu6zR96Q== mocktest"); - TemplateOptions options = new AzureTemplateOptions() - .DNSLabelPrefix("mydnslabel") - .virtualNetworkAddressPrefix("10.0.0.0/20") - .subnetAddressPrefix("10.0.0.0/25") - .authorizePublicKey(rsakey); - - ((AzureTemplateOptions)options).virtualNetworkName(vnetName); - ((AzureTemplateOptions)options).subnetId(subnetId); - - DeploymentTemplateBuilder templateBuilder = getDeploymentTemplateBuilderWithOptions(options); - - DeploymentBody deploymentTemplateBody = templateBuilder.getDeploymentTemplate(); - - DeploymentProperties properties = DeploymentProperties.create(deploymentTemplateBody); - - String deploymentTemplate = templateBuilder.getDeploymentTemplateJson(properties); - deploymentTemplate = UrlEscapers.urlFormParameterEscaper().escape(deploymentTemplate); - - Deployment deployment = api().validate(deploymentName, deploymentTemplate); - assertNotNull(deployment); - } - - @Test - public void testValidateDeploymentTemplateLinuxNodeWithSSH() { - Long now = System.currentTimeMillis(); - deploymentName = "jc" + now; - - String rsakey = new String("ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAQEAmfk/QSF0pvnrpdz+Ah2KulGruKU+8FFBdlw938MpOysRdmp7uwpH6Z7+5VNGNdxFIAyc/W3UaZXF9hTsU8+78TlwkZpsr2mzU+ycu37XLAQ8Uv7hjsAN0DkKKPrZ9lgUUfZVKV/8E/JIAs03gIbL6zO3y7eYJQ5fNeZb+nji7tQT+YLpGq/FDegvraPKVMQbCSCZhsHyWhdPLyFlu9/30npZ0ahYOPI/KyZxFDtM/pHp88+ZAk9Icq5owaLRWcJQqrBGWqjbZnHtjdDqvHZ+C0wPhdJZPyfkHOrSYTwSQBXfX4JLRRCz3J1jf62MbQWT1o6Y4JEs1ZP1Skxu6zR96Q== mocktest"); - - AzureTemplateOptions options = new AzureTemplateOptions(); - options.virtualNetworkName(vnetName); - options.subnetId(subnetId); - - options.authorizePublicKey(rsakey); - DeploymentTemplateBuilder templateBuilder = getDeploymentTemplateBuilderWithOptions(options); - - DeploymentBody deploymentTemplateBody = templateBuilder.getDeploymentTemplate(); - - DeploymentProperties properties = DeploymentProperties.create(deploymentTemplateBody); - - String deploymentTemplate = templateBuilder.getDeploymentTemplateJson(properties); - deploymentTemplate = UrlEscapers.urlFormParameterEscaper().escape(deploymentTemplate); - - Deployment deployment = api().validate(deploymentName, deploymentTemplate); - assertNotNull(deployment); - } - - @Test - public void testCreateDeploymentTemplateLinuxNode() { - Long now = System.currentTimeMillis(); - deploymentName = "jc" + now; - - String rsakey = new String("ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAQEAmfk/QSF0pvnrpdz+Ah2KulGruKU+8FFBdlw938MpOysRdmp7uwpH6Z7+5VNGNdxFIAyc/W3UaZXF9hTsU8+78TlwkZpsr2mzU+ycu37XLAQ8Uv7hjsAN0DkKKPrZ9lgUUfZVKV/8E/JIAs03gIbL6zO3y7eYJQ5fNeZb+nji7tQT+YLpGq/FDegvraPKVMQbCSCZhsHyWhdPLyFlu9/30npZ0ahYOPI/KyZxFDtM/pHp88+ZAk9Icq5owaLRWcJQqrBGWqjbZnHtjdDqvHZ+C0wPhdJZPyfkHOrSYTwSQBXfX4JLRRCz3J1jf62MbQWT1o6Y4JEs1ZP1Skxu6zR96Q== mocktest"); - - AzureTemplateOptions options = new AzureTemplateOptions(); - options.virtualNetworkName(vnetName); - options.subnetId(subnetId); - - options.authorizePublicKey(rsakey); - options.inboundPorts(22, 8080); - DeploymentTemplateBuilder templateBuilder = getDeploymentTemplateBuilderWithOptions(options); - - DeploymentBody deploymentTemplateBody = templateBuilder.getDeploymentTemplate(); - DeploymentProperties properties = DeploymentProperties.create(deploymentTemplateBody); - - String deploymentTemplate = templateBuilder.getDeploymentTemplateJson(properties); - deploymentTemplate = UrlEscapers.urlFormParameterEscaper().escape(deploymentTemplate); - - //creates an actual VM using deployment template - Deployment deployment = api().create(deploymentName, deploymentTemplate); - - Deployment.ProvisioningState state = Deployment.ProvisioningState.fromValue(deployment.properties().provisioningState()); - int testTime = 0; - while (testTime < maxTestDuration) { - if ((state == Deployment.ProvisioningState.SUCCEEDED) || - (state == Deployment.ProvisioningState.CANCELED) || - (state == Deployment.ProvisioningState.DELETED) || - (state == Deployment.ProvisioningState.FAILED)) { - break; - } - - // sleep a little bit before polling, timeout after a fixed time - try { - Thread.sleep(pollingInterval * 1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - testTime += pollingInterval; - - deployment = api().get(deploymentName); - assertNotNull(deployment); - state = Deployment.ProvisioningState.fromValue(deployment.properties().provisioningState()); - } - assertTrue(state == Deployment.ProvisioningState.SUCCEEDED); - assertNotNull(deployment); - } - - private Template getTemplate(TemplateOptions options) { - Location provider = (new LocationBuilder()).scope(LocationScope.PROVIDER).id("azurecompute-arm").description("azurecompute-arm").build(); - Location region = (new LocationBuilder()).scope(LocationScope.REGION).id(LOCATION).description(LOCATIONDESCRIPTION).parent(provider).build(); - - OperatingSystem os = OperatingSystem.builder() - .family(OsFamily.UBUNTU) - .description("14.04.3-LTS") - .is64Bit(true) - .build(); - - Image image = (new ImageBuilder()) - .id("UbuntuServer14.04.3-LTS") - .providerId("Canonical") - .name("UbuntuServer") - .description("14.04.3-LTS") - .version("14.04.3-LTS") - .operatingSystem(os) - .status(Image.Status.AVAILABLE) - .location(region) - .build(); - - Hardware hardware = (new HardwareBuilder()).id("Standard_A0").build(); - return new TemplateImpl(image, hardware, region, options); - } - - private DeploymentTemplateBuilder getDeploymentTemplateBuilderWithEmptyOptions() { - AzureTemplateOptions options = new AzureTemplateOptions(); - options.virtualNetworkName(vnetName); - options.subnetId(subnetId); - - Template template = getTemplate(options); - DeploymentTemplateBuilder templateBuilder = api.deploymentTemplateFactory().create(resourceGroupName, deploymentName, template); - return templateBuilder; - } - - private DeploymentTemplateBuilder getDeploymentTemplateBuilderWithOptions(TemplateOptions options) { - Template template = getTemplate(options); - DeploymentTemplateBuilder templateBuilder = api.deploymentTemplateFactory().create(resourceGroupName, deploymentName, template); - return templateBuilder; - } - - private DeploymentApi api() { - return api.getDeploymentApi(resourceGroupName); - } -}
