http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/b8ab3758/azurecompute/src/main/java/org/jclouds/azurecompute/binders/StorageServiceKeyTypeToXML.java ---------------------------------------------------------------------- diff --git a/azurecompute/src/main/java/org/jclouds/azurecompute/binders/StorageServiceKeyTypeToXML.java b/azurecompute/src/main/java/org/jclouds/azurecompute/binders/StorageServiceKeyTypeToXML.java deleted file mode 100644 index abc6da5..0000000 --- a/azurecompute/src/main/java/org/jclouds/azurecompute/binders/StorageServiceKeyTypeToXML.java +++ /dev/null @@ -1,43 +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.binders; - -import com.jamesmurty.utils.XMLBuilder; -import org.jclouds.azurecompute.domain.StorageServiceKeys; -import org.jclouds.http.HttpRequest; -import org.jclouds.rest.Binder; - -import static com.google.common.base.Throwables.propagate; - -public class StorageServiceKeyTypeToXML implements Binder { - - @Override - @SuppressWarnings("unchecked") - public <R extends HttpRequest> R bindToRequest(final R request, final Object input) { - final StorageServiceKeys.KeyType params = StorageServiceKeys.KeyType.class.cast(input); - - try { - final XMLBuilder builder = XMLBuilder.create( - "RegenerateKeys", "http://schemas.microsoft.com/windowsazure"). - e("KeyType").t(params.name()).up(); - return (R) request.toBuilder().payload(builder.asString()).build(); - } catch (Exception e) { - throw propagate(e); - } - } - -}
http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/b8ab3758/azurecompute/src/main/java/org/jclouds/azurecompute/binders/UpdateAffinityGroupParamsToXML.java ---------------------------------------------------------------------- diff --git a/azurecompute/src/main/java/org/jclouds/azurecompute/binders/UpdateAffinityGroupParamsToXML.java b/azurecompute/src/main/java/org/jclouds/azurecompute/binders/UpdateAffinityGroupParamsToXML.java deleted file mode 100644 index 8e8d591..0000000 --- a/azurecompute/src/main/java/org/jclouds/azurecompute/binders/UpdateAffinityGroupParamsToXML.java +++ /dev/null @@ -1,50 +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.binders; - -import static com.google.common.base.Throwables.propagate; - -import com.google.common.base.Charsets; -import com.google.common.io.BaseEncoding; - -import com.jamesmurty.utils.XMLBuilder; - -import org.jclouds.azurecompute.domain.UpdateAffinityGroupParams; -import org.jclouds.http.HttpRequest; -import org.jclouds.rest.Binder; - -public final class UpdateAffinityGroupParamsToXML implements Binder { - - @Override - @SuppressWarnings("unchecked") - public <R extends HttpRequest> R bindToRequest(final R request, final Object input) { - final UpdateAffinityGroupParams params = UpdateAffinityGroupParams.class.cast(input); - - try { - XMLBuilder builder = XMLBuilder.create("UpdateAffinityGroup", "http://schemas.microsoft.com/windowsazure"); - if (params.label() != null) { - builder.e("Label").t(BaseEncoding.base64().encode(params.label().getBytes(Charsets.UTF_8))).up(); - } - if (params.description() != null) { - builder.e("Description").t(params.description()).up(); - } - return (R) request.toBuilder().payload(builder.asString()).build(); - } catch (Exception e) { - throw propagate(e); - } - } -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/b8ab3758/azurecompute/src/main/java/org/jclouds/azurecompute/binders/UpdateStorageServiceParamsToXML.java ---------------------------------------------------------------------- diff --git a/azurecompute/src/main/java/org/jclouds/azurecompute/binders/UpdateStorageServiceParamsToXML.java b/azurecompute/src/main/java/org/jclouds/azurecompute/binders/UpdateStorageServiceParamsToXML.java deleted file mode 100644 index 4d80f9a..0000000 --- a/azurecompute/src/main/java/org/jclouds/azurecompute/binders/UpdateStorageServiceParamsToXML.java +++ /dev/null @@ -1,86 +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.binders; - -import static com.google.common.base.Throwables.propagate; - -import com.google.common.base.Charsets; -import com.google.common.io.BaseEncoding; -import com.jamesmurty.utils.XMLBuilder; - -import java.util.Map; - -import org.jclouds.http.HttpRequest; -import org.jclouds.rest.Binder; -import org.jclouds.azurecompute.domain.UpdateStorageServiceParams; - -public final class UpdateStorageServiceParamsToXML implements Binder { - - @Override - @SuppressWarnings("unchecked") - public <R extends HttpRequest> R bindToRequest(final R request, final Object input) { - final UpdateStorageServiceParams params = UpdateStorageServiceParams.class.cast(input); - - try { - final XMLBuilder builder = XMLBuilder.create( - "UpdateStorageServiceInput", "http://schemas.microsoft.com/windowsazure"); - - if (params.description() != null) { - builder.e("Description").t(params.description()).up(); - } - - if (params.label() != null) { - builder.e("Label").t(BaseEncoding.base64().encode(params.label().getBytes(Charsets.UTF_8))).up(); - } - - if (params.geoReplicationEnabled() != null) { - builder.e("geoReplicationEnabled").t(params.geoReplicationEnabled().toString()).up(); - } - - if (params.extendedProperties() != null) { - final XMLBuilder extProps = builder.e("ExtendedProperties"); - for (Map.Entry<String, String> entry : params.extendedProperties().entrySet()) { - final XMLBuilder extProp = extProps.e("ExtendedProperty"); - extProp.e("Name").t(entry.getKey()).up(); - extProp.e("Value").t(entry.getValue()).up(); - extProp.up(); - } - extProps.up(); - } - - if (params.customDomains() != null) { - final XMLBuilder custDomains = builder.e("CustomDomains"); - for (UpdateStorageServiceParams.CustomDomain domain : params.customDomains()) { - final XMLBuilder custDomain = custDomains.e("CustomDomain"); - custDomain.e("Name").t(domain.name()).up(); - custDomain.e("UseSubDomainName").t(domain.useSubDomainName().toString()).up(); - custDomain.up(); - } - custDomains.up(); - } - - if (params.accountType() != null) { - builder.e("AccountType").t(params.accountType().name()).up(); - } - - return (R) request.toBuilder().payload(builder.asString()).build(); - } catch (Exception e) { - throw propagate(e); - } - } - -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/b8ab3758/azurecompute/src/main/java/org/jclouds/azurecompute/binders/VMImageParamsToXML.java ---------------------------------------------------------------------- diff --git a/azurecompute/src/main/java/org/jclouds/azurecompute/binders/VMImageParamsToXML.java b/azurecompute/src/main/java/org/jclouds/azurecompute/binders/VMImageParamsToXML.java deleted file mode 100644 index 540faa8..0000000 --- a/azurecompute/src/main/java/org/jclouds/azurecompute/binders/VMImageParamsToXML.java +++ /dev/null @@ -1,97 +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.binders; - -import com.google.common.base.CaseFormat; -import com.jamesmurty.utils.XMLBuilder; -import org.jclouds.azurecompute.domain.RoleSize; -import org.jclouds.azurecompute.domain.VMImageParams; -import org.jclouds.http.HttpRequest; -import org.jclouds.rest.Binder; - -import java.net.URI; - -import static com.google.common.base.CaseFormat.UPPER_CAMEL; -import static com.google.common.base.Throwables.propagate; - -public final class VMImageParamsToXML implements Binder { - - @Override - public <R extends HttpRequest> R bindToRequest(R request, Object input) { - VMImageParams params = VMImageParams.class.cast(input); - - try { - XMLBuilder builder = XMLBuilder.create("VMImage", "http://schemas.microsoft.com/windowsazure"); - add(builder, "Name", params.name()); - add(builder, "Label", params.label()); - add(builder, "Description", params.description()); - //OSConfig - VMImageParams.OSDiskConfigurationParams osDiskConfig = params.osDiskConfiguration(); - if (osDiskConfig != null) { - String cache = CaseFormat.UPPER_UNDERSCORE.to(UPPER_CAMEL, osDiskConfig.hostCaching().toString()); - XMLBuilder osConfigBuilder = builder.e("OSDiskConfiguration"); - osConfigBuilder - .e("HostCaching").t(cache).up() - .e("OSState").t(osDiskConfig.osState().toString()).up() - .e("OS").t(osDiskConfig.os().toString()).up() - .e("MediaLink").t(osDiskConfig.mediaLink().toASCIIString()).up() - .up(); //OSDiskConfiguration - } - builder.up(); - builder.e("DataDiskConfigurations").up(); - add(builder, "Language", params.language()); - add(builder, "ImageFamily", params.imageFamily()); - - RoleSize.Type vmSize = params.recommendedVMSize(); - if (vmSize != null) { - String vmSizeText = params.recommendedVMSize().getText(); - builder.e("RecommendedVMSize").t(vmSizeText).up(); - } - - add(builder, "Eula", params.eula()); - add(builder, "IconUri", params.iconUri()); - add(builder, "SmallIconUri", params.smallIconUri()); - add(builder, "PrivacyUri", params.privacyUri()); - - if (params.showGui() != null) { - String showGuiText = params.showGui().toString(); - builder.e("ShowGui").t(showGuiText).up(); - } - builder.up(); - - return (R) request.toBuilder().payload(builder.asString()).build(); - } catch (Exception e) { - throw propagate(e); - } - } - - private XMLBuilder add(XMLBuilder xmlBuilder, String entity, String text) { - if (text != null) { - return xmlBuilder.e(entity).t(text).up(); - } else { - return xmlBuilder.e(entity).up(); - } - } - - private XMLBuilder add(XMLBuilder xmlBuilder, String entity, URI text) { - if (text != null) { - return xmlBuilder.e(entity).t(text.toASCIIString()).up(); - } else { - return xmlBuilder.e(entity).up(); - } - } -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/b8ab3758/azurecompute/src/main/java/org/jclouds/azurecompute/compute/AzureComputeServiceAdapter.java ---------------------------------------------------------------------- diff --git a/azurecompute/src/main/java/org/jclouds/azurecompute/compute/AzureComputeServiceAdapter.java b/azurecompute/src/main/java/org/jclouds/azurecompute/compute/AzureComputeServiceAdapter.java deleted file mode 100644 index 44f5f24..0000000 --- a/azurecompute/src/main/java/org/jclouds/azurecompute/compute/AzureComputeServiceAdapter.java +++ /dev/null @@ -1,536 +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.compute; - -import static com.google.common.base.MoreObjects.firstNonNull; -import static com.google.common.base.Predicates.notNull; -import static java.lang.String.format; -import static java.util.concurrent.TimeUnit.SECONDS; -import static org.jclouds.util.Predicates2.retry; -import java.net.URI; -import java.util.List; -import java.util.Set; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.azurecompute.AzureComputeApi; -import org.jclouds.azurecompute.compute.config.AzureComputeServiceContextModule.AzureComputeConstants; -import org.jclouds.azurecompute.compute.functions.OSImageToImage; -import org.jclouds.azurecompute.compute.options.AzureComputeTemplateOptions; -import org.jclouds.azurecompute.config.AzureComputeProperties; -import org.jclouds.azurecompute.domain.CloudService; -import org.jclouds.azurecompute.domain.Deployment; -import org.jclouds.azurecompute.domain.Deployment.RoleInstance; -import org.jclouds.azurecompute.domain.DeploymentParams; -import org.jclouds.azurecompute.domain.DeploymentParams.ExternalEndpoint; -import org.jclouds.azurecompute.domain.Location; -import org.jclouds.azurecompute.domain.OSImage; -import org.jclouds.azurecompute.domain.Role; -import org.jclouds.azurecompute.domain.RoleSize; -import org.jclouds.azurecompute.util.ConflictManagementPredicate; -import org.jclouds.compute.ComputeServiceAdapter; -import org.jclouds.compute.domain.OsFamily; -import org.jclouds.compute.domain.Template; -import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.domain.LoginCredentials; -import org.jclouds.logging.Logger; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.base.Splitter; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; - -/** - * Defines the connection between the {@link AzureComputeApi} implementation and the jclouds - * {@link org.jclouds.compute.ComputeService}. - */ -@Singleton -public class AzureComputeServiceAdapter implements ComputeServiceAdapter<Deployment, RoleSize, OSImage, Location> { - - private static final String DEFAULT_LOGIN_USER = "jclouds"; - - private static final String DEFAULT_LOGIN_PASSWORD = "Azur3Compute!"; - public static final String POST_SHUTDOWN_ACTION = "StoppedDeallocated"; - private static final String POST_SHUTDOWN_ACTION_NO_DEALLOCATE = "Stopped"; - - @Resource - @Named(ComputeServiceConstants.COMPUTE_LOGGER) - private Logger logger = Logger.NULL; - - private final AzureComputeApi api; - - private final Predicate<String> operationSucceededPredicate; - - private final AzureComputeConstants azureComputeConstants; - - @Inject - AzureComputeServiceAdapter(final AzureComputeApi api, - final Predicate<String> operationSucceededPredicate, final AzureComputeConstants azureComputeConstants) { - - this.api = api; - this.operationSucceededPredicate = operationSucceededPredicate; - this.azureComputeConstants = azureComputeConstants; - } - - @Override - public NodeAndInitialCredentials<Deployment> createNodeWithGroupEncodedIntoName( - final String group, final String name, final Template template) { - - // azure-specific options - final AzureComputeTemplateOptions templateOptions = template.getOptions().as(AzureComputeTemplateOptions.class); - - final String loginUser = firstNonNull(templateOptions.getLoginUser(), DEFAULT_LOGIN_USER); - final String loginPassword = firstNonNull(templateOptions.getLoginPassword(), DEFAULT_LOGIN_PASSWORD); - final String location = template.getLocation().getId(); - final int[] inboundPorts = template.getOptions().getInboundPorts(); - - final String storageAccountName = templateOptions.getStorageAccountName(); - - String message = String.format("Creating a cloud service with name '%s', label '%s' in location '%s'", name, name, location); - logger.debug(message); - final String createCloudServiceRequestId = api.getCloudServiceApi().createWithLabelInLocation(name, name, location); - if (!operationSucceededPredicate.apply(createCloudServiceRequestId)) { - final String exceptionMessage = generateIllegalStateExceptionMessage(message, createCloudServiceRequestId, azureComputeConstants.operationTimeout()); - logger.warn(exceptionMessage); - throw new IllegalStateException(exceptionMessage); - } - logger.info("Cloud Service (%s) created with operation id: %s", name, createCloudServiceRequestId); - - final OSImage.Type os = template.getImage().getOperatingSystem().getFamily() == OsFamily.WINDOWS ? - OSImage.Type.WINDOWS : OSImage.Type.LINUX; - final Set<ExternalEndpoint> externalEndpoints = Sets.newHashSet(); - for (int inboundPort : inboundPorts) { - externalEndpoints.add(ExternalEndpoint.inboundTcpToLocalPort(inboundPort, inboundPort)); - } - - final DeploymentParams.Builder paramsBuilder = DeploymentParams.builder() - .name(name) - .os(os) - .username(loginUser) - .password(loginPassword) - .sourceImageName(OSImageToImage.fromGeoName(template.getImage().getId())[0]) - .mediaLink(createMediaLink(storageAccountName, name)) - .size(RoleSize.Type.fromString(template.getHardware().getName())) - .externalEndpoints(externalEndpoints) - .virtualNetworkName(templateOptions.getVirtualNetworkName()) - .subnetNames(templateOptions.getSubnetNames()) - .provisionGuestAgent(templateOptions.getProvisionGuestAgent()); - if (os.equals(OSImage.Type.WINDOWS)) { - paramsBuilder.winrmUseHttps(templateOptions.getWinrmUseHttps()); - } - final DeploymentParams params = paramsBuilder.build(); - - message = String.format("Creating a deployment with params '%s' ...", params); - logger.debug(message); - - if (!new ConflictManagementPredicate(api) { - @Override - protected String operation() { - return api.getDeploymentApiForService(name).create(params); - } - }.apply(name)) { - final String illegalStateExceptionMessage = generateIllegalStateExceptionMessage(message, createCloudServiceRequestId, azureComputeConstants.operationTimeout()); - logger.warn(illegalStateExceptionMessage); - logger.debug("Deleting cloud service (%s) ...", name); - deleteCloudService(name); - logger.debug("Cloud service (%s) deleted.", name); - throw new IllegalStateException(illegalStateExceptionMessage); - } - - logger.info("Deployment created with name: %s", name); - - final Set<Deployment> deployments = Sets.newHashSet(); - if (!retry(new Predicate<String>() { - @Override - public boolean apply(final String name) { - final Deployment deployment = api.getDeploymentApiForService(name).get(name); - if (deployment != null) { - deployments.add(deployment); - } - return !deployments.isEmpty(); - } - }, azureComputeConstants.operationTimeout(), 1, SECONDS).apply(name)) { - final String illegalStateExceptionMessage = format("Deployment %s was not created within %sms so it will be destroyed.", - name, azureComputeConstants.operationTimeout()); - logger.warn(illegalStateExceptionMessage); - - api.getDeploymentApiForService(name).delete(name); - api.getCloudServiceApi().delete(name); - - throw new IllegalStateException(illegalStateExceptionMessage); - } - - final Deployment deployment = deployments.iterator().next(); - - // check if the role inside the deployment is ready - checkRoleStatusInDeployment(name, deployment); - - return new NodeAndInitialCredentials<Deployment>(deployment, name, - LoginCredentials.builder().user(loginUser).password(loginPassword).authenticateSudo(true).build()); - } - - @Override - public Iterable<RoleSize> listHardwareProfiles() { - return api.getSubscriptionApi().listRoleSizes(); - } - - @Override - public Iterable<OSImage> listImages() { - final List<OSImage> osImages = Lists.newArrayList(); - for (OSImage osImage : api.getOSImageApi().list()) { - if (osImage.location() == null) { - osImages.add(OSImage.create( - osImage.name(), - null, - osImage.affinityGroup(), - osImage.label(), - osImage.description(), - osImage.imageFamily(), - osImage.category(), - osImage.os(), - osImage.publisherName(), - osImage.mediaLink(), - osImage.logicalSizeInGB(), - osImage.eula() - )); - } else { - for (String actualLocation : Splitter.on(';').split(osImage.location())) { - osImages.add(OSImage.create( - OSImageToImage.toGeoName(osImage.name(), actualLocation), - actualLocation, - osImage.affinityGroup(), - osImage.label(), - osImage.description(), - osImage.imageFamily(), - osImage.category(), - osImage.os(), - osImage.publisherName(), - osImage.mediaLink(), - osImage.logicalSizeInGB(), - osImage.eula() - )); - } - } - } - return osImages; - } - - @Override - public OSImage getImage(final String id) { - final String[] idParts = OSImageToImage.fromGeoName(id); - final OSImage image = Iterables.find(api.getOSImageApi().list(), new Predicate<OSImage>() { - @Override - public boolean apply(final OSImage input) { - return idParts[0].equals(input.name()); - } - }); - - return image == null - ? null - : idParts[1] == null - ? image - : OSImage.create( - id, - idParts[1], - image.affinityGroup(), - image.label(), - image.description(), - image.imageFamily(), - image.category(), - image.os(), - image.publisherName(), - image.mediaLink(), - image.logicalSizeInGB(), - image.eula()); - } - - @Override - public Iterable<Location> listLocations() { - return api.getLocationApi().list(); - } - - /** Returns the {@code deployment} argument itself if already settled, otherwise {@code null}. */ - private Deployment isSettled(Deployment deployment) { - return deployment == null || deployment.roleInstanceList().isEmpty() - ? null - : FluentIterable.from(deployment.roleInstanceList()).allMatch( - new Predicate<RoleInstance>() { - @Override - public boolean apply(final RoleInstance input) { - return input != null && !input.instanceStatus().isTransient(); - } - }) - ? deployment - : null; - } - - @Override - public Deployment getNode(final String id) { - // all nodes created by this provider will always have a cloud service name equal to deployment name - final Deployment deployment = api.getDeploymentApiForService(id).get(id); - if (deployment != null) { - return isSettled(deployment); - } - - return FluentIterable.from(api.getCloudServiceApi().list()). - transform(new Function<CloudService, Deployment>() { - @Override - public Deployment apply(final CloudService input) { - final Deployment deployment = api.getDeploymentApiForService(input.name()).get(id); - return isSettled(deployment); - } - }). - firstMatch(notNull()). - orNull(); - } - - private void trackRequest(final String requestId) { - if (!operationSucceededPredicate.apply(requestId)) { - final String message = generateIllegalStateExceptionMessage( - "tracking request", requestId, azureComputeConstants.operationTimeout()); - logger.warn(message); - throw new IllegalStateException(message); - } - } - - public Deployment internalDestroyNode(final String nodeId) { - - Deployment deployment = getDeploymentFromNodeId(nodeId); - - if (deployment == null) return null; - - final String deploymentName = deployment.name(); - String message = String.format("Deleting deployment(%s) of cloud service (%s)", nodeId, deploymentName); - logger.debug(message); - - if (deployment != null) { - for (Role role : deployment.roleList()) { - trackRequest(api.getVirtualMachineApiForDeploymentInService(deploymentName, role.roleName()).shutdown(nodeId, POST_SHUTDOWN_ACTION)); - } - - deleteDeployment(deploymentName, nodeId); - - logger.debug("Deleting cloud service (%s) ...", deploymentName); - trackRequest(api.getCloudServiceApi().delete(deploymentName)); - logger.debug("Cloud service (%s) deleted.", deploymentName); - - for (Role role : deployment.roleList()) { - final Role.OSVirtualHardDisk disk = role.osVirtualHardDisk(); - if (disk != null) { - if (!new ConflictManagementPredicate(api, operationSucceededPredicate) { - - @Override - protected String operation() { - return api.getDiskApi().delete(disk.diskName()); - } - }.apply(nodeId)) { - final String illegalStateExceptionMessage = generateIllegalStateExceptionMessage("Delete disk " + disk.diskName(), - "Delete disk", azureComputeConstants.operationTimeout()); - logger.warn(illegalStateExceptionMessage); - } - } - } - } - return deployment; - } - - public Deployment getDeploymentFromNodeId(final String nodeId) { - final List<Deployment> nodes = Lists.newArrayList(); - retry(new Predicate<String>() { - @Override - public boolean apply(final String input) { - final Deployment deployment = getNode(nodeId); - if (deployment != null) { - nodes.add(deployment); - } - return !nodes.isEmpty(); - } - }, 30 * 60, 1, SECONDS).apply(nodeId); - - return Iterables.getFirst(nodes, null); - } - - @Override - public void destroyNode(final String id) { - logger.debug("Destroying %s ...", id); - if (internalDestroyNode(id) != null) { - logger.debug("Destroyed %s!", id); - } else { - logger.warn("Can't destroy %s!", id); - } - } - - @Override - public void rebootNode(final String id) { - final CloudService cloudService = api.getCloudServiceApi().get(id); - if (cloudService != null) { - logger.debug("Restarting %s ...", id); - trackRequest(api.getVirtualMachineApiForDeploymentInService(id, cloudService.name()).restart(id)); - logger.debug("Restarted %s", id); - } - } - - @Override - public void resumeNode(final String id) { - final CloudService cloudService = api.getCloudServiceApi().get(id); - if (cloudService != null) { - logger.debug("Resuming %s ...", id); - trackRequest(api.getVirtualMachineApiForDeploymentInService(id, cloudService.name()).start(id)); - - // it happens sometimes that even though the trackRequest call above returns successfully, - // the node is still in the process of starting and this.getNode(id) returns null - // - // this is a temporary workaround for JCLOUDS-1092 and should be removed once the issue is resolved properly - if (!retry(new Predicate<String>() { - @Override - public boolean apply(final String id) { - return getNode(id) != null; - } - }, azureComputeConstants.operationTimeout(), 1, SECONDS).apply(id)) { - final String message = generateIllegalStateExceptionMessage( - "waiting for node to resume", "", azureComputeConstants.operationTimeout()); - logger.warn(message); - throw new IllegalStateException(message); - } - - logger.debug("Resumed %s", id); - } - } - - @Override - public void suspendNode(final String id) { - final CloudService cloudService = api.getCloudServiceApi().get(id); - if (cloudService != null) { - logger.debug("Suspending %s ...", id); - String postShutdownAction = azureComputeConstants.deallocateWhenSuspending() - ? POST_SHUTDOWN_ACTION : POST_SHUTDOWN_ACTION_NO_DEALLOCATE; - trackRequest(api.getVirtualMachineApiForDeploymentInService(id, cloudService.name()).shutdown(id, postShutdownAction)); - logger.debug("Suspended %s", id); - } - } - - @Override - public Iterable<Deployment> listNodes() { - return FluentIterable.from(api.getCloudServiceApi().list()). - transform(new Function<CloudService, Deployment>() { - @Override - public Deployment apply(final CloudService cloudService) { - return api.getDeploymentApiForService(cloudService.name()).get(cloudService.name()); - } - }). - filter(notNull()). - toSet(); - } - - @Override - public Iterable<Deployment> listNodesByIds(final Iterable<String> ids) { - return Iterables.filter(listNodes(), new Predicate<Deployment>() { - @Override - public boolean apply(final Deployment input) { - return Iterables.contains(ids, input.name()); - } - }); - } - - @VisibleForTesting - public static URI createMediaLink(final String storageServiceName, final String diskName) { - return URI.create( - String.format("https://%s.blob.core.windows.net/vhds/disk-%s.vhd", storageServiceName, diskName)); - } - - private void deleteCloudService(final String name) { - if (!new ConflictManagementPredicate(api) { - - @Override - protected String operation() { - return api.getCloudServiceApi().delete(name); - } - - }.apply(name)) { - final String deleteMessage = generateIllegalStateExceptionMessage("Delete cloud service " + name, - "CloudService delete", azureComputeConstants.operationTimeout()); - logger.warn(deleteMessage); - throw new IllegalStateException(deleteMessage); - } - } - - private void deleteDeployment(final String id, final String cloudServiceName) { - if (!new ConflictManagementPredicate(api) { - - @Override - protected String operation() { - return api.getDeploymentApiForService(cloudServiceName).delete(id); - } - - }.apply(id)) { - final String deleteMessage = generateIllegalStateExceptionMessage("Delete deployment " + cloudServiceName, - "Deployment delete", azureComputeConstants.operationTimeout()); - logger.warn(deleteMessage); - throw new IllegalStateException(deleteMessage); - } - } - - - private void checkRoleStatusInDeployment(final String name, Deployment deployment) { - if (!retry(new Predicate<Deployment>() { - - @Override - public boolean apply(Deployment deployment) { - deployment = api.getDeploymentApiForService(deployment.name()).get(name); - if (deployment.roleInstanceList() == null || deployment.roleInstanceList().isEmpty()) return false; - return Iterables.all(deployment.roleInstanceList(), new Predicate<RoleInstance>() { - @Override - public boolean apply(RoleInstance input) { - if (input.instanceStatus() == Deployment.InstanceStatus.PROVISIONING_FAILED) { - final String message = format("Deployment %s is in provisioning failed status, so it will be destroyed.", name); - logger.warn(message); - - api.getDeploymentApiForService(name).delete(name); - api.getCloudServiceApi().delete(name); - - throw new IllegalStateException(message); - } - return input.instanceStatus() == Deployment.InstanceStatus.READY_ROLE; - } - }); - } - }, azureComputeConstants.operationTimeout(), 1, SECONDS).apply(deployment)) { - final String message = format("Role %s has not reached the READY_ROLE within %sms so it will be destroyed.", - deployment.name(), azureComputeConstants.operationTimeout()); - logger.warn(message); - - api.getDeploymentApiForService(name).delete(name); - api.getCloudServiceApi().delete(name); - - throw new IllegalStateException(message); - } - } - - public static String generateIllegalStateExceptionMessage(String prefix, final String operationId, final long timeout) { - final String warnMessage = format("%s - %s has not been completed within %sms.", prefix, operationId, timeout); - return format("%s. Please, try by increasing `%s` and try again", - warnMessage, AzureComputeProperties.OPERATION_TIMEOUT); - } - -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/b8ab3758/azurecompute/src/main/java/org/jclouds/azurecompute/compute/config/AzureComputeServiceContextModule.java ---------------------------------------------------------------------- diff --git a/azurecompute/src/main/java/org/jclouds/azurecompute/compute/config/AzureComputeServiceContextModule.java b/azurecompute/src/main/java/org/jclouds/azurecompute/compute/config/AzureComputeServiceContextModule.java deleted file mode 100644 index e6d8812..0000000 --- a/azurecompute/src/main/java/org/jclouds/azurecompute/compute/config/AzureComputeServiceContextModule.java +++ /dev/null @@ -1,155 +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.compute.config; - -import static org.jclouds.azurecompute.config.AzureComputeProperties.DEALLOCATE_WHEN_SUSPENDING; -import static org.jclouds.azurecompute.config.AzureComputeProperties.OPERATION_POLL_INITIAL_PERIOD; -import static org.jclouds.azurecompute.config.AzureComputeProperties.OPERATION_POLL_MAX_PERIOD; -import static org.jclouds.azurecompute.config.AzureComputeProperties.OPERATION_TIMEOUT; -import static org.jclouds.azurecompute.config.AzureComputeProperties.TCP_RULE_FORMAT; -import static org.jclouds.azurecompute.config.AzureComputeProperties.TCP_RULE_REGEXP; -import java.util.concurrent.TimeUnit; - -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.azurecompute.AzureComputeApi; -import org.jclouds.azurecompute.compute.AzureComputeServiceAdapter; -import org.jclouds.azurecompute.compute.extensions.AzureComputeSecurityGroupExtension; -import org.jclouds.azurecompute.compute.functions.DeploymentToNodeMetadata; -import org.jclouds.azurecompute.compute.functions.LocationToLocation; -import org.jclouds.azurecompute.compute.functions.OSImageToImage; -import org.jclouds.azurecompute.compute.functions.RoleSizeToHardware; -import org.jclouds.azurecompute.compute.options.AzureComputeTemplateOptions; -import org.jclouds.azurecompute.compute.strategy.GetOrCreateStorageServiceAndVirtualNetworkThenCreateNodes; -import org.jclouds.azurecompute.compute.strategy.UseNodeCredentialsButOverrideFromTemplate; -import org.jclouds.azurecompute.domain.Deployment; -import org.jclouds.azurecompute.domain.Location; -import org.jclouds.azurecompute.domain.OSImage; -import org.jclouds.azurecompute.domain.RoleSize; -import org.jclouds.azurecompute.util.ConflictManagementPredicate; -import org.jclouds.compute.ComputeServiceAdapter; -import org.jclouds.compute.config.ComputeServiceAdapterContextModule; -import org.jclouds.compute.domain.Hardware; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.extensions.SecurityGroupExtension; -import org.jclouds.compute.options.TemplateOptions; -import org.jclouds.compute.strategy.CreateNodesInGroupThenAddToSet; -import org.jclouds.compute.strategy.PrioritizeCredentialsFromTemplate; - -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.inject.Inject; -import com.google.inject.Provides; -import com.google.inject.TypeLiteral; - -public class AzureComputeServiceContextModule - extends ComputeServiceAdapterContextModule<Deployment, RoleSize, OSImage, Location> { - - @Override - protected void configure() { - super.configure(); - - bind(new TypeLiteral<ComputeServiceAdapter<Deployment, RoleSize, OSImage, Location>>() { - }).to(AzureComputeServiceAdapter.class); - bind(new TypeLiteral<Function<OSImage, org.jclouds.compute.domain.Image>>() { - }).to(OSImageToImage.class); - bind(new TypeLiteral<Function<RoleSize, Hardware>>() { - }).to(RoleSizeToHardware.class); - bind(new TypeLiteral<Function<Deployment, NodeMetadata>>() { - }).to(DeploymentToNodeMetadata.class); - - bind(PrioritizeCredentialsFromTemplate.class).to(UseNodeCredentialsButOverrideFromTemplate.class); - bind(new TypeLiteral<Function<Location, org.jclouds.domain.Location>>() { - }).to(LocationToLocation.class); - - bind(TemplateOptions.class).to(AzureComputeTemplateOptions.class); - - bind(new TypeLiteral<SecurityGroupExtension>() { - }).to(AzureComputeSecurityGroupExtension.class); - bind(CreateNodesInGroupThenAddToSet.class).to(GetOrCreateStorageServiceAndVirtualNetworkThenCreateNodes.class); - - // to have the compute service adapter override default locations - install(new LocationsFromComputeServiceAdapterModule<Deployment, RoleSize, OSImage, Location>() { - }); - } - - @Provides - @Singleton - protected Predicate<String> provideOperationSucceededPredicate( - final AzureComputeApi api, final AzureComputeConstants azureComputeConstants) { - return new ConflictManagementPredicate( - api, - azureComputeConstants.operationTimeout(), - azureComputeConstants.operationPollInitialPeriod(), - azureComputeConstants.operationPollMaxPeriod(), - TimeUnit.MILLISECONDS); - } - - @Singleton - public static class AzureComputeConstants { - - @Named(OPERATION_TIMEOUT) - @Inject - private String operationTimeoutProperty; - - @Named(OPERATION_POLL_INITIAL_PERIOD) - @Inject - private String operationPollInitialPeriodProperty; - - @Named(OPERATION_POLL_MAX_PERIOD) - @Inject - private String operationPollMaxPeriodProperty; - - @Named(TCP_RULE_FORMAT) - @Inject - private String tcpRuleFormatProperty; - - @Named(TCP_RULE_REGEXP) - @Inject - private String tcpRuleRegexpProperty; - - @Named(DEALLOCATE_WHEN_SUSPENDING) - @Inject - private String deallocateWhenSuspending; - - public Long operationTimeout() { - return Long.parseLong(operationTimeoutProperty); - } - - public Integer operationPollInitialPeriod() { - return Integer.parseInt(operationPollInitialPeriodProperty); - } - - public Integer operationPollMaxPeriod() { - return Integer.parseInt(operationPollMaxPeriodProperty); - } - - public String tcpRuleFormat() { - return tcpRuleFormatProperty; - } - - public String tcpRuleRegexp() { - return tcpRuleRegexpProperty; - } - - public boolean deallocateWhenSuspending() { - return Boolean.parseBoolean(deallocateWhenSuspending); - } - } - -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/b8ab3758/azurecompute/src/main/java/org/jclouds/azurecompute/compute/extensions/AzureComputeSecurityGroupExtension.java ---------------------------------------------------------------------- diff --git a/azurecompute/src/main/java/org/jclouds/azurecompute/compute/extensions/AzureComputeSecurityGroupExtension.java b/azurecompute/src/main/java/org/jclouds/azurecompute/compute/extensions/AzureComputeSecurityGroupExtension.java deleted file mode 100644 index f24c5fe..0000000 --- a/azurecompute/src/main/java/org/jclouds/azurecompute/compute/extensions/AzureComputeSecurityGroupExtension.java +++ /dev/null @@ -1,392 +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.compute.extensions; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.azurecompute.compute.AzureComputeServiceAdapter.generateIllegalStateExceptionMessage; -import java.util.List; -import java.util.Set; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; - -import org.jclouds.azurecompute.AzureComputeApi; -import org.jclouds.azurecompute.compute.config.AzureComputeServiceContextModule.AzureComputeConstants; -import org.jclouds.azurecompute.domain.Deployment; -import org.jclouds.azurecompute.domain.NetworkConfiguration; -import org.jclouds.azurecompute.domain.NetworkConfiguration.VirtualNetworkSite; -import org.jclouds.azurecompute.domain.NetworkSecurityGroup; -import org.jclouds.azurecompute.domain.Role; -import org.jclouds.azurecompute.domain.Rule; -import org.jclouds.azurecompute.util.ConflictManagementPredicate; -import org.jclouds.azurecompute.util.NetworkSecurityGroups; -import org.jclouds.compute.domain.SecurityGroup; -import org.jclouds.compute.domain.SecurityGroupBuilder; -import org.jclouds.compute.extensions.SecurityGroupExtension; -import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.domain.Location; -import org.jclouds.logging.Logger; -import org.jclouds.net.domain.IpPermission; -import org.jclouds.net.domain.IpProtocol; - -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.base.Splitter; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.Iterables; -import com.google.common.collect.Multimap; - -/** - * An extension to compute service to allow for the manipulation of {@link org.jclouds.compute.domain.SecurityGroup}s. - * Implementation is optional by providers. - * - * It considers only the custom rules added by the user and ignores the default rules created by Azure - */ -public class AzureComputeSecurityGroupExtension implements SecurityGroupExtension { - - protected final AzureComputeApi api; - - private final Predicate<String> operationSucceededPredicate; - - private final AzureComputeConstants azureComputeConstants; - - @Resource - @Named(ComputeServiceConstants.COMPUTE_LOGGER) - protected Logger logger = Logger.NULL; - - @Inject - AzureComputeSecurityGroupExtension(final AzureComputeApi api, - final Predicate<String> operationSucceededPredicate, final AzureComputeConstants azureComputeConstants) { - - this.api = api; - this.operationSucceededPredicate = operationSucceededPredicate; - this.azureComputeConstants = azureComputeConstants; - } - - @Override - public Set<SecurityGroup> listSecurityGroups() { - return FluentIterable.from(api.getNetworkSecurityGroupApi().list()) - .transform(new NetworkSecurityGroupSecurityGroupFunction()) - .toSet(); - } - - @Override - public Set<SecurityGroup> listSecurityGroupsInLocation(final Location location) { - return FluentIterable.from(api.getNetworkSecurityGroupApi().list()) - .transform(new NetworkSecurityGroupSecurityGroupFunction()) - .toSet(); - } - - /** - * @param name it represents both cloudservice and deployment name - * @return Set<SecurityGroup> - */ - @Override - public Set<SecurityGroup> listSecurityGroupsForNode(final String name) { - checkNotNull(name, "name"); - - final Deployment deployment = api.getDeploymentApiForService(name).get(name); - final String virtualNetworkName = deployment.virtualNetworkName(); - - final List<String> subnetNames = FluentIterable.from(deployment.roleList()) - .transformAndConcat(new Function<Role, Iterable<Role.ConfigurationSet>>() { - @Override - public Iterable<Role.ConfigurationSet> apply(final Role input) { - return input.configurationSets(); - } - }) - .transformAndConcat(new Function<Role.ConfigurationSet, Iterable<Role.ConfigurationSet.SubnetName>>() { - @Override - public Iterable<Role.ConfigurationSet.SubnetName> apply(final Role.ConfigurationSet input) { - return input.subnetNames(); - } - }) - .transform(new Function<Role.ConfigurationSet.SubnetName, String>() { - @Override - public String apply(final Role.ConfigurationSet.SubnetName input) { - return input.name(); - } - }) - .toList(); - - return FluentIterable.from(subnetNames) - .transform(new Function<String, NetworkSecurityGroup>() { - @Override - public NetworkSecurityGroup apply(final String input) { - return api.getNetworkSecurityGroupApi(). - getNetworkSecurityGroupAppliedToSubnet(virtualNetworkName, input); - } - }) - .transform(new NetworkSecurityGroupSecurityGroupFunction()) - .toSet(); - } - - @Override - public SecurityGroup getSecurityGroupById(final String id) { - return transformNetworkSecurityGroupToSecurityGroup(id); - } - - @Override - public SecurityGroup createSecurityGroup(final String name, final Location location) { - checkNotNull(name, "name"); - checkNotNull(location, "location"); - - final NetworkSecurityGroup networkSecurityGroup = NetworkSecurityGroup.create( - name, name, location.getId(), null, null); - final String createNSGRequestId = api.getNetworkSecurityGroupApi().create(networkSecurityGroup); - if (!operationSucceededPredicate.apply(createNSGRequestId)) { - final String message = generateIllegalStateExceptionMessage("Create NSG" + name, - createNSGRequestId, azureComputeConstants.operationTimeout()); - logger.warn(message); - throw new IllegalStateException(message); - } - return transformNetworkSecurityGroupToSecurityGroup(name); - } - - private SecurityGroup transformNetworkSecurityGroupToSecurityGroup(final String name) { - final NetworkSecurityGroup fullDetails = api.getNetworkSecurityGroupApi().getFullDetails(name); - return fullDetails == null - ? null - : new NetworkSecurityGroupSecurityGroupFunction().apply(fullDetails); - } - - @Override - public boolean removeSecurityGroup(final String id) { - final NetworkConfiguration networkConfiguration = api.getVirtualNetworkApi().getNetworkConfiguration(); - if (networkConfiguration != null) { - for (VirtualNetworkSite virtualNetworkSite - : networkConfiguration.virtualNetworkConfiguration().virtualNetworkSites()) { - - for (NetworkConfiguration.Subnet subnet : virtualNetworkSite.subnets()) { - final String virtualNetworkName = virtualNetworkSite.name(); - final String subnetName = subnet.name(); - if (virtualNetworkName != null && subnetName != null) { - final NetworkSecurityGroup networkSecurityGroupAppliedToSubnet = api.getNetworkSecurityGroupApi() - .getNetworkSecurityGroupAppliedToSubnet(virtualNetworkName, subnetName); - if (networkSecurityGroupAppliedToSubnet != null - && networkSecurityGroupAppliedToSubnet.name().equals(id)) { - logger.debug("Removing a networkSecurityGroup %s is already applied to subnet '%s' ...", - id, subnetName); - - // remove existing nsg from subnet - if (!new ConflictManagementPredicate(api, operationSucceededPredicate) { - @Override - protected String operation() { - return api.getNetworkSecurityGroupApi().removeFromSubnet( - virtualNetworkName, subnetName, id); - } - }.apply(id)) { - final String message = generateIllegalStateExceptionMessage("Remove NSG" + id + " from subnet " + subnetName, - "Remove security group from subnet", azureComputeConstants.operationTimeout()); - logger.warn(message); - throw new IllegalStateException(message); - } - } - } - } - } - } - String deleteRequestId = api.getNetworkSecurityGroupApi().delete(id); - return operationSucceededPredicate.apply(deleteRequestId); - } - - @Override - public SecurityGroup addIpPermission(final IpPermission ipPermission, final SecurityGroup group) { - checkNotNull(group, "group"); - checkNotNull(ipPermission, "ipPermission"); - - final String id = checkNotNull(group.getId(), "group.getId()"); - - final int priority = NetworkSecurityGroups.getFirstAvailablePriority( - NetworkSecurityGroups.getCustomRules(api.getNetworkSecurityGroupApi().getFullDetails(group.getName()))); - - final String ruleName = NetworkSecurityGroups.createRuleName( - azureComputeConstants.tcpRuleFormat(), ipPermission.getFromPort(), ipPermission.getToPort()); - - // add rule to NSG - addRuleToNetworkSecurityGroup(id, ruleName, priority, ipPermission); - - return transformNetworkSecurityGroupToSecurityGroup(id); - } - - @Override - public SecurityGroup addIpPermission( - final IpProtocol protocol, - final int startPort, - final int endPort, - final Multimap<String, String> tenantIdGroupNamePairs, - final Iterable<String> ipRanges, - final Iterable<String> groupIds, - final SecurityGroup group) { - - final IpPermission.Builder permBuilder = IpPermission.builder(); - permBuilder.ipProtocol(protocol); - permBuilder.fromPort(startPort); - permBuilder.toPort(endPort); - permBuilder.tenantIdGroupNamePairs(tenantIdGroupNamePairs); - permBuilder.cidrBlocks(ipRanges); - permBuilder.groupIds(groupIds); - - return addIpPermission(permBuilder.build(), group); - } - - @Override - public SecurityGroup removeIpPermission(final IpPermission ipPermission, final SecurityGroup group) { - checkNotNull(group, "group"); - checkNotNull(ipPermission, "ipPermission"); - - final String id = checkNotNull(group.getId(), "group.getId()"); - - final String ruleName = NetworkSecurityGroups.createRuleName( - azureComputeConstants.tcpRuleFormat(), ipPermission.getFromPort(), ipPermission.getToPort()); - - // remove rule to NSG - removeRuleFromNetworkSecurityGroup(id, ruleName); - - return transformNetworkSecurityGroupToSecurityGroup(id); - } - - @Override - public SecurityGroup removeIpPermission( - final IpProtocol protocol, - final int startPort, - final int endPort, - final Multimap<String, String> tenantIdGroupNamePairs, - final Iterable<String> ipRanges, - final Iterable<String> groupIds, - final SecurityGroup group) { - - final IpPermission.Builder permBuilder = IpPermission.builder(); - permBuilder.ipProtocol(protocol); - permBuilder.fromPort(startPort); - permBuilder.toPort(endPort); - permBuilder.tenantIdGroupNamePairs(tenantIdGroupNamePairs); - permBuilder.cidrBlocks(ipRanges); - permBuilder.groupIds(groupIds); - - return removeIpPermission(permBuilder.build(), group); - } - - @Override - public boolean supportsTenantIdGroupNamePairs() { - return false; - } - - @Override - public boolean supportsTenantIdGroupIdPairs() { - return false; - } - - @Override - public boolean supportsGroupIds() { - return false; - } - - @Override - public boolean supportsPortRangesForGroups() { - return false; - } - - @Override - public boolean supportsExclusionCidrBlocks() { - return false; - } - - private class RuleToIpPermission implements Function<Rule, IpPermission> { - - @Override - public IpPermission apply(final Rule rule) { - final IpPermission.Builder builder = IpPermission.builder(); - if (rule.name().matches(azureComputeConstants.tcpRuleRegexp())) { - builder.fromPort(extractPort(rule.name(), 0)) - .toPort(extractPort(rule.name(), 1)); - } - builder.ipProtocol(rule.protocol().equals(Rule.Protocol.ALL) - ? IpProtocol.ALL : IpProtocol.valueOf(rule.protocol().getValue())); - if (rule.destinationAddressPrefix().equals("*")) { - builder.cidrBlock("0.0.0.0/0"); - } else { - builder.cidrBlock(rule.destinationAddressPrefix()); - } - return builder.build(); - } - - private int extractPort(String ruleName, int position) { - return Integer.parseInt(Iterables.get(Splitter.on("-").omitEmptyStrings(). - split(ruleName.substring(4, ruleName.length())), position)); - } - } - - private class NetworkSecurityGroupSecurityGroupFunction implements Function<NetworkSecurityGroup, SecurityGroup> { - - @Override - public SecurityGroup apply(final NetworkSecurityGroup networkSecurityGroup) { - final SecurityGroupBuilder securityGroupBuilder = new SecurityGroupBuilder() - .id(networkSecurityGroup.name()) - .providerId(networkSecurityGroup.label()) - .name(networkSecurityGroup.name()); - if (networkSecurityGroup.rules() != null) { - final List<Rule> filteredRules = NetworkSecurityGroups.getCustomRules(networkSecurityGroup); - - final Iterable<IpPermission> permissions = Iterables.transform(filteredRules, new RuleToIpPermission()); - securityGroupBuilder.ipPermissions(permissions); - } - return securityGroupBuilder.build(); - } - } - - private void addRuleToNetworkSecurityGroup(final String networkSecurityGroupId, final String ruleName, - final int priority, final IpPermission ipPermission) { - - final String protocol = ipPermission.getIpProtocol().name(); - final String destinationPortRange = ipPermission.getFromPort() == ipPermission.getToPort() - ? String.valueOf(ipPermission.getToPort()) - : String.format("%s-%s", ipPermission.getFromPort(), ipPermission.getToPort()); - final String destinationAddressPrefix = ipPermission.getCidrBlocks().isEmpty() - || Iterables.get(ipPermission.getCidrBlocks(), 0).equals("0.0.0.0/0") - ? "*" - : Iterables.get(ipPermission.getCidrBlocks(), 0); - final String setRuleToNSGRequestId = api.getNetworkSecurityGroupApi(). - setRule(networkSecurityGroupId, ruleName, Rule.create(ruleName, // name - Rule.Type.Inbound, // type - String.valueOf(priority), // priority - Rule.Action.Allow, // action - "INTERNET", // sourceAddressPrefix - "*", // sourcePortRange - destinationAddressPrefix, // destinationAddressPrefix - destinationPortRange, // destinationPortRange - Rule.Protocol.fromString(protocol))); - if (!operationSucceededPredicate.apply(setRuleToNSGRequestId)) { - final String message = generateIllegalStateExceptionMessage("Add rule " + ruleName, - setRuleToNSGRequestId, azureComputeConstants.operationTimeout()); - logger.warn(message); - throw new IllegalStateException(message); - } - } - - private void removeRuleFromNetworkSecurityGroup(final String id, final String ruleName) { - String setRuleToNSGRequestId = api.getNetworkSecurityGroupApi().deleteRule(id, ruleName); - if (!operationSucceededPredicate.apply(setRuleToNSGRequestId)) { - final String message = generateIllegalStateExceptionMessage("Remove rule " + ruleName, - setRuleToNSGRequestId, azureComputeConstants.operationTimeout()); - logger.warn(message); - throw new IllegalStateException(message); - } - } - -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/b8ab3758/azurecompute/src/main/java/org/jclouds/azurecompute/compute/functions/DeploymentToNodeMetadata.java ---------------------------------------------------------------------- diff --git a/azurecompute/src/main/java/org/jclouds/azurecompute/compute/functions/DeploymentToNodeMetadata.java b/azurecompute/src/main/java/org/jclouds/azurecompute/compute/functions/DeploymentToNodeMetadata.java deleted file mode 100644 index 622fd9c..0000000 --- a/azurecompute/src/main/java/org/jclouds/azurecompute/compute/functions/DeploymentToNodeMetadata.java +++ /dev/null @@ -1,183 +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.compute.functions; - -import static com.google.common.base.Preconditions.checkNotNull; -import java.util.Map; -import java.util.Set; - -import javax.inject.Inject; - -import org.jclouds.azurecompute.AzureComputeApi; -import org.jclouds.azurecompute.domain.CloudService; -import org.jclouds.azurecompute.domain.Deployment; -import org.jclouds.azurecompute.domain.Deployment.RoleInstance; -import org.jclouds.collect.Memoized; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.functions.GroupNamingConvention; -import org.jclouds.domain.Credentials; -import org.jclouds.domain.Location; -import org.jclouds.location.predicates.LocationPredicates; - -import com.google.common.base.Function; -import com.google.common.base.Optional; -import com.google.common.base.Supplier; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Sets; - -public class DeploymentToNodeMetadata implements Function<Deployment, NodeMetadata> { - - private static final Map<Deployment.InstanceStatus, NodeMetadata.Status> INSTANCESTATUS_TO_NODESTATUS = - ImmutableMap.<Deployment.InstanceStatus, NodeMetadata.Status>builder(). - put(Deployment.InstanceStatus.BUSY_ROLE, NodeMetadata.Status.PENDING). - put(Deployment.InstanceStatus.CREATING_ROLE, NodeMetadata.Status.PENDING). - put(Deployment.InstanceStatus.CREATING_VM, NodeMetadata.Status.PENDING). - put(Deployment.InstanceStatus.CYCLING_ROLE, NodeMetadata.Status.PENDING). - put(Deployment.InstanceStatus.DELETING_VM, NodeMetadata.Status.PENDING). - put(Deployment.InstanceStatus.FAILED_STARTING_ROLE, NodeMetadata.Status.ERROR). - put(Deployment.InstanceStatus.FAILED_STARTING_VM, NodeMetadata.Status.ERROR). - put(Deployment.InstanceStatus.PREPARING, NodeMetadata.Status.PENDING). - put(Deployment.InstanceStatus.PROVISIONING, NodeMetadata.Status.PENDING). - put(Deployment.InstanceStatus.READY_ROLE, NodeMetadata.Status.RUNNING). - put(Deployment.InstanceStatus.RESTARTING_ROLE, NodeMetadata.Status.PENDING). - put(Deployment.InstanceStatus.STARTING_ROLE, NodeMetadata.Status.PENDING). - put(Deployment.InstanceStatus.STARTING_VM, NodeMetadata.Status.PENDING). - put(Deployment.InstanceStatus.STOPPED_DEALLOCATED, NodeMetadata.Status.SUSPENDED). - put(Deployment.InstanceStatus.STOPPED_VM, NodeMetadata.Status.SUSPENDED). - put(Deployment.InstanceStatus.STOPPING_ROLE, NodeMetadata.Status.PENDING). - put(Deployment.InstanceStatus.STOPPING_VM, NodeMetadata.Status.PENDING). - put(Deployment.InstanceStatus.ROLE_STATE_UNKNOWN, NodeMetadata.Status.UNRECOGNIZED). - put(Deployment.InstanceStatus.UNRECOGNIZED, NodeMetadata.Status.UNRECOGNIZED). - build(); - - private static final Map<Deployment.Status, NodeMetadata.Status> STATUS_TO_NODESTATUS = - ImmutableMap.<Deployment.Status, NodeMetadata.Status>builder(). - put(Deployment.Status.DELETING, NodeMetadata.Status.PENDING). - put(Deployment.Status.SUSPENDED_TRANSITIONING, NodeMetadata.Status.PENDING). - put(Deployment.Status.RUNNING_TRANSITIONING, NodeMetadata.Status.PENDING). - put(Deployment.Status.DEPLOYING, NodeMetadata.Status.PENDING). - put(Deployment.Status.STARTING, NodeMetadata.Status.PENDING). - put(Deployment.Status.SUSPENDED, NodeMetadata.Status.SUSPENDED). - put(Deployment.Status.RUNNING, NodeMetadata.Status.RUNNING). - put(Deployment.Status.UNRECOGNIZED, NodeMetadata.Status.UNRECOGNIZED). - build(); - - private final AzureComputeApi api; - - private final Supplier<Set<? extends Location>> locations; - - private final GroupNamingConvention nodeNamingConvention; - - private final OSImageToImage osImageToImage; - - private final RoleSizeToHardware roleSizeToHardware; - - private final Map<String, Credentials> credentialStore; - - @Inject - DeploymentToNodeMetadata( - AzureComputeApi api, - @Memoized Supplier<Set<? extends Location>> locations, - GroupNamingConvention.Factory namingConvention, OSImageToImage osImageToImage, - RoleSizeToHardware roleSizeToHardware, Map<String, Credentials> credentialStore) { - - this.nodeNamingConvention = namingConvention.createWithoutPrefix(); - this.locations = checkNotNull(locations, "locations"); - this.osImageToImage = osImageToImage; - this.roleSizeToHardware = roleSizeToHardware; - this.credentialStore = credentialStore; - this.api = api; - } - - @Override - public NodeMetadata apply(final Deployment from) { - final NodeMetadataBuilder builder = new NodeMetadataBuilder(); - builder.id(from.name()); - builder.providerId(from.name()); - builder.name(from.name()); - builder.hostname(getHostname(from)); - builder.group(nodeNamingConvention.groupInUniqueNameOrNull(getHostname(from))); - - // TODO: CloudService name is required (see JCLOUDS-849): waiting for JCLOUDS-853. - final CloudService cloudService = api.getCloudServiceApi().get(from.name()); - if (cloudService != null) { - final String location = cloudService.location() != null - ? cloudService.location() - : api.getAffinityGroupApi().get(cloudService.affinityGroup()).location(); - builder.location(FluentIterable.from(locations.get()). - firstMatch(LocationPredicates.idEquals(location)). - orNull()); - } - - /* TODO - if (from.getDatacenter() != null) { - builder.location(from(locations.get()).firstMatch( - LocationPredicates.idEquals(from.getDatacenter().getId() + "")).orNull()); - } - builder.hardware(roleSizeToHardware.apply(from.instanceSize())); - Image image = osImageToImage.apply(from); - if (image != null) { - builder.imageId(image.getId()); - builder.operatingSystem(image.getOperatingSystem()); - } - */ - if (from.status() != null) { - final Optional<RoleInstance> roleInstance = tryFindFirstRoleInstanceInDeployment(from); - if (roleInstance.isPresent() && roleInstance.get().instanceStatus() != null) { - builder.status(INSTANCESTATUS_TO_NODESTATUS.get(roleInstance.get().instanceStatus())); - } else { - builder.status(STATUS_TO_NODESTATUS.get(from.status())); - } - } else { - builder.status(NodeMetadata.Status.UNRECOGNIZED); - } - - final Set<String> publicIpAddresses = Sets.newLinkedHashSet(); - if (from.virtualIPs() != null) { - for (Deployment.VirtualIP virtualIP : from.virtualIPs()) { - publicIpAddresses.add(virtualIP.address()); - } - builder.publicAddresses(publicIpAddresses); - } - final Set<String> privateIpAddresses = Sets.newLinkedHashSet(); - if (from.roleInstanceList() != null) { - for (RoleInstance roleInstance : from.roleInstanceList()) { - if (roleInstance.ipAddress() != null) { - privateIpAddresses.add(roleInstance.ipAddress()); - } - } - builder.privateAddresses(privateIpAddresses); - } - return builder.build(); - } - - private String getHostname(final Deployment from) { - final Optional<RoleInstance> roleInstance = tryFindFirstRoleInstanceInDeployment(from); - return !roleInstance.isPresent() || roleInstance.get().hostname() == null - ? from.name() - : roleInstance.get().hostname(); - } - - private Optional<RoleInstance> tryFindFirstRoleInstanceInDeployment(final Deployment deployment) { - return (deployment.roleInstanceList() == null || deployment.roleInstanceList().isEmpty()) - ? Optional.<RoleInstance>absent() - : Optional.of(deployment.roleInstanceList().get(0)); - } - -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/b8ab3758/azurecompute/src/main/java/org/jclouds/azurecompute/compute/functions/LocationToLocation.java ---------------------------------------------------------------------- diff --git a/azurecompute/src/main/java/org/jclouds/azurecompute/compute/functions/LocationToLocation.java b/azurecompute/src/main/java/org/jclouds/azurecompute/compute/functions/LocationToLocation.java deleted file mode 100644 index f334ac8..0000000 --- a/azurecompute/src/main/java/org/jclouds/azurecompute/compute/functions/LocationToLocation.java +++ /dev/null @@ -1,63 +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.compute.functions; - -import static com.google.common.collect.Iterables.getOnlyElement; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.azurecompute.domain.Location; -import org.jclouds.azurecompute.domain.Region; -import org.jclouds.domain.LocationBuilder; -import org.jclouds.domain.LocationScope; -import org.jclouds.location.suppliers.all.JustProvider; - -import com.google.common.base.Function; -import com.google.common.collect.ImmutableSet; - -/** - * Converts an Location into a Location. - */ -@Singleton -public class LocationToLocation implements Function<Location, org.jclouds.domain.Location> { - - private final JustProvider justProvider; - - // allow us to lazy discover the provider of a resource - @Inject - LocationToLocation(JustProvider justProvider) { - this.justProvider = justProvider; - } - - @Override - public org.jclouds.domain.Location apply(final Location location) { - final LocationBuilder builder = new LocationBuilder(); - builder.id(location.name()); - builder.description(location.displayName()); - builder.parent(getOnlyElement(justProvider.get())); - - builder.scope(LocationScope.REGION); - final Region region = Region.byName(location.name()); - if (region != null) { - builder.iso3166Codes(ImmutableSet.of(region.iso3166Code())); - } - - return builder.build(); - } - -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/b8ab3758/azurecompute/src/main/java/org/jclouds/azurecompute/compute/functions/OSImageToImage.java ---------------------------------------------------------------------- diff --git a/azurecompute/src/main/java/org/jclouds/azurecompute/compute/functions/OSImageToImage.java b/azurecompute/src/main/java/org/jclouds/azurecompute/compute/functions/OSImageToImage.java deleted file mode 100644 index ed2d8ca..0000000 --- a/azurecompute/src/main/java/org/jclouds/azurecompute/compute/functions/OSImageToImage.java +++ /dev/null @@ -1,154 +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.compute.functions; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.util.Set; - -import org.jclouds.azurecompute.domain.OSImage; -import org.jclouds.collect.Memoized; -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.location.predicates.LocationPredicates; - -import com.google.common.base.Function; -import com.google.common.base.Splitter; -import com.google.common.base.Supplier; -import com.google.common.collect.FluentIterable; -import com.google.inject.Inject; - -public class OSImageToImage implements Function<OSImage, Image> { - - private static final String UNRECOGNIZED = "UNRECOGNIZED"; - - private static final String UBUNTU = "Ubuntu"; - - private static final String WINDOWS = "Windows"; - - private static final String OPENLOGIC = "openLogic"; - - private static final String CENTOS = "CentOS"; - - private static final String COREOS = "CoreOS"; - - private static final String OPENSUSE = "openSUSE"; - - private static final String SUSE = "SUSE"; - - private static final String SQL_SERVER = "SQL Server"; - - private static final String ORACLE_lINUX = "Oracle Linux"; - - public static String toGeoName(final String name, final String location) { - return name + "/" + location; - } - - public static String[] fromGeoName(final String geoName) { - final String[] parts = checkNotNull(geoName, "geoName").split("/"); - return (parts.length == 1) ? new String[]{geoName, null} : parts; - } - - private final Supplier<Set<? extends org.jclouds.domain.Location>> locations; - - @Inject - OSImageToImage(@Memoized final Supplier<Set<? extends org.jclouds.domain.Location>> locations) { - - this.locations = locations; - } - - @Override - public Image apply(final OSImage image) { - final ImageBuilder builder = new ImageBuilder() - .id(image.name()) - .name(image.label()) - .description(image.description()) - .status(Image.Status.AVAILABLE) - .uri(image.mediaLink()) - .providerId(image.name()) - .location(FluentIterable.from(locations.get()) - .firstMatch(LocationPredicates.idEquals(image.location())).orNull()); - - final OperatingSystem.Builder osBuilder = osFamily().apply(image); - return builder.operatingSystem(osBuilder.build()).build(); - } - - public static Function<OSImage, OperatingSystem.Builder> osFamily() { - return new Function<OSImage, OperatingSystem.Builder>() { - @Override - public OperatingSystem.Builder apply(final OSImage image) { - checkNotNull(image.label(), "label"); - final String label = Splitter.on('/').split(image.label()).iterator().next(); - - boolean is64Bit = false; - - OsFamily family = OsFamily.UNRECOGNIZED; - if (label.contains(CENTOS)) { - family = OsFamily.CENTOS; - is64Bit = image.name().contains("x64"); - } else if (label.contains(OPENLOGIC)) { - family = OsFamily.CENTOS; - } else if (label.contains(SUSE)) { - family = OsFamily.SUSE; - } else if (label.contains(UBUNTU)) { - family = OsFamily.UBUNTU; - is64Bit = image.name().contains("amd64"); - } else if (label.contains(WINDOWS)) { - family = OsFamily.WINDOWS; - is64Bit = true; - } else if (label.contains(ORACLE_lINUX)) { - family = OsFamily.OEL; - } - - String version = UNRECOGNIZED; - //ex: CoreOS Alpha -> Alpha - if (label.contains(COREOS)) { - version = label.replace("CoreOS ", ""); - } //openSUSE 13.1 -> 13.1 - else if (label.contains(OPENSUSE)) { - version = label.replace("openSUSE ", ""); - } //SUSE Linux Enterprise Server 11 SP3 (Premium Image) -> 11 SP3(Premium Image) - else if (label.contains(SUSE)) { - version = label.replace("SUSE ", ""); - } //Ubuntu Server 12.04 LTS -> 12.04 LTS - else if (label.contains(UBUNTU)) { - version = label.replace("Ubuntu Server ", ""); - } else if (label.contains(SQL_SERVER)) { - version = label; - } else if (label.contains(CENTOS)) { - version = label; - } else if (label.contains(WINDOWS)) { - version = label; - } else if (label.equals(ORACLE_lINUX)) { - version = label; - } - - return OperatingSystem.builder(). - family(family != OsFamily.UNRECOGNIZED - ? family - : image.os() == OSImage.Type.WINDOWS - ? OsFamily.WINDOWS - : OsFamily.LINUX). - version(version). - is64Bit(is64Bit). - description(image.description() + ""); - } - }; - } -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/b8ab3758/azurecompute/src/main/java/org/jclouds/azurecompute/compute/functions/RoleSizeToHardware.java ---------------------------------------------------------------------- diff --git a/azurecompute/src/main/java/org/jclouds/azurecompute/compute/functions/RoleSizeToHardware.java b/azurecompute/src/main/java/org/jclouds/azurecompute/compute/functions/RoleSizeToHardware.java deleted file mode 100644 index 5421531..0000000 --- a/azurecompute/src/main/java/org/jclouds/azurecompute/compute/functions/RoleSizeToHardware.java +++ /dev/null @@ -1,48 +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.compute.functions; - -import org.jclouds.azurecompute.domain.RoleSize; -import org.jclouds.compute.domain.Hardware; -import org.jclouds.compute.domain.HardwareBuilder; -import org.jclouds.compute.domain.Processor; -import org.jclouds.compute.domain.Volume; -import org.jclouds.compute.domain.VolumeBuilder; - -import com.google.common.base.Function; -import com.google.common.collect.ImmutableList; - -public class RoleSizeToHardware implements Function<RoleSize, Hardware> { - - @Override - public Hardware apply(RoleSize from) { - final HardwareBuilder builder = new HardwareBuilder(). - ids(from.name().name()). - name(from.name().name()). - hypervisor("Hyper-V"). - processors(ImmutableList.of(new Processor(from.cores(), 2))). - ram(from.memoryInMb()); - if (from.virtualMachineResourceDiskSizeInMb() != null) { - builder.volume(new VolumeBuilder() - .size(Float.valueOf(from.virtualMachineResourceDiskSizeInMb())) - .type(Volume.Type.LOCAL) - .build()); - } - return builder.build(); - } - -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/b8ab3758/azurecompute/src/main/java/org/jclouds/azurecompute/compute/functions/internal/OperatingSystems.java ---------------------------------------------------------------------- diff --git a/azurecompute/src/main/java/org/jclouds/azurecompute/compute/functions/internal/OperatingSystems.java b/azurecompute/src/main/java/org/jclouds/azurecompute/compute/functions/internal/OperatingSystems.java deleted file mode 100644 index 0cc1927..0000000 --- a/azurecompute/src/main/java/org/jclouds/azurecompute/compute/functions/internal/OperatingSystems.java +++ /dev/null @@ -1,95 +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.compute.functions.internal; - -import org.jclouds.azurecompute.domain.OSImage; -import org.jclouds.compute.domain.OsFamily; - -import com.google.common.base.Function; -import com.google.common.base.Splitter; -import com.google.common.collect.Iterables; - -public class OperatingSystems { - - protected static final String CENTOS = "CentOS"; - - protected static final String SUSE = "SUSE"; - - protected static final String OPENSUSE = "openSUSE"; - - protected static final String UBUNTU = "Ubuntu"; - - protected static final String WINDOWS = "Windows"; - - private static final String MICROSOFT = "Microsoft"; - - public static final String WINDOWS_SERVER = "Windows Server"; - - public static final String MICROSOFT_SQL_SERVER = "Microsoft SQL Server"; - - public static Function<String, OsFamily> osFamily() { - return new Function<String, OsFamily>() { - @Override - public OsFamily apply(final String label) { - if (label != null) { - if (label.contains(CENTOS)) { - return OsFamily.CENTOS; - } else if (label.contains(SUSE)) { - return OsFamily.SUSE; - } else if (label.contains(UBUNTU)) { - return OsFamily.UBUNTU; - } else if (label.contains(WINDOWS)) { - return OsFamily.WINDOWS; - } - } - return OsFamily.UNRECOGNIZED; - } - }; - } - - public static Function<OSImage, String> version() { - return new Function<OSImage, String>() { - @Override - public String apply(final OSImage osImage) { - if (osImage.category().matches("Canonical|OpenLogic")) { - return Iterables.get(Splitter.on(" ").split(osImage.label()), 2); - } else if (osImage.category().matches(SUSE)) { - if (osImage.label().startsWith(OPENSUSE)) { - return osImage.label().substring(OPENSUSE.length() + 1); - } - if (osImage.label().startsWith(SUSE)) { - return Iterables.get(Splitter.on("-").split(osImage.name()), 4); - } - } else if (osImage.category().matches(MICROSOFT)) { - if (osImage.label().startsWith(WINDOWS_SERVER)) { - return osImage.label().substring(WINDOWS_SERVER.length() + 1); - } - if (osImage.label().startsWith(MICROSOFT_SQL_SERVER)) { - return osImage.label().substring(MICROSOFT_SQL_SERVER.length() + 1); - } - } else if (osImage.category().matches("RightScale with Linux|Public ")) { - final Iterable<String> splittedLabel = Splitter.on("-").split(osImage.label()); - if (Iterables.size(splittedLabel) > 2) { - return Iterables.get(splittedLabel, 2); - } - } - return null; - } - }; - } - -}
