You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@stratos.apache.org by im...@apache.org on 2014/12/24 18:36:29 UTC
[06/12] stratos git commit: Renaming iaas classes and moving them to
new packages
http://git-wip-us.apache.org/repos/asf/stratos/blob/e195f2f1/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/iaases/JcloudsOpenstackIaas.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/iaases/JcloudsOpenstackIaas.java b/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/iaases/JcloudsOpenstackIaas.java
deleted file mode 100644
index 6a7bc24..0000000
--- a/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/iaases/JcloudsOpenstackIaas.java
+++ /dev/null
@@ -1,560 +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.apache.stratos.cloud.controller.iaases;
-
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.TimeoutException;
-
-import org.apache.commons.lang.StringUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.cloud.controller.domain.IaasProvider;
-import org.apache.stratos.cloud.controller.domain.NetworkInterface;
-import org.apache.stratos.cloud.controller.exception.CloudControllerException;
-import org.apache.stratos.cloud.controller.exception.InvalidHostException;
-import org.apache.stratos.cloud.controller.exception.InvalidRegionException;
-import org.apache.stratos.cloud.controller.exception.InvalidZoneException;
-import org.apache.stratos.cloud.controller.iaases.openstack.networking.NeutronNetworkingApi;
-import org.apache.stratos.cloud.controller.iaases.openstack.networking.NovaNetworkingApi;
-import org.apache.stratos.cloud.controller.iaases.openstack.networking.OpenstackNetworkingApi;
-import org.apache.stratos.cloud.controller.iaases.validators.OpenstackNovaPartitionValidator;
-import org.apache.stratos.cloud.controller.iaases.validators.PartitionValidator;
-import org.apache.stratos.cloud.controller.util.CloudControllerConstants;
-import org.apache.stratos.cloud.controller.util.ComputeServiceBuilderUtil;
-import org.jclouds.compute.ComputeService;
-import org.jclouds.compute.ComputeServiceContext;
-import org.jclouds.compute.domain.NodeMetadata;
-import org.jclouds.compute.domain.Template;
-import org.jclouds.compute.domain.TemplateBuilder;
-import org.jclouds.compute.options.TemplateOptions;
-import org.jclouds.openstack.nova.v2_0.NovaApi;
-import org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions;
-import org.jclouds.openstack.nova.v2_0.domain.HostAggregate;
-import org.jclouds.openstack.nova.v2_0.domain.KeyPair;
-import org.jclouds.openstack.nova.v2_0.domain.Network;
-import org.jclouds.openstack.nova.v2_0.domain.Volume;
-import org.jclouds.openstack.nova.v2_0.domain.VolumeAttachment;
-import org.jclouds.openstack.nova.v2_0.domain.zonescoped.AvailabilityZone;
-import org.jclouds.openstack.nova.v2_0.extensions.AvailabilityZoneApi;
-import org.jclouds.openstack.nova.v2_0.extensions.HostAggregateApi;
-import org.jclouds.openstack.nova.v2_0.extensions.KeyPairApi;
-import org.jclouds.openstack.nova.v2_0.extensions.VolumeApi;
-import org.jclouds.openstack.nova.v2_0.extensions.VolumeAttachmentApi;
-import org.jclouds.openstack.nova.v2_0.options.CreateVolumeOptions;
-
-import com.google.common.base.Optional;
-
-public class JcloudsOpenstackIaas extends JcloudsIaas {
-
- private static final Log log = LogFactory.getLog(JcloudsOpenstackIaas.class);
- private static final String SUCCESSFUL_LOG_LINE = "A key-pair is created successfully in ";
- private static final String FAILED_LOG_LINE = "Key-pair is unable to create in ";
-
- private OpenstackNetworkingApi openstackNetworkingApi;
-
- public JcloudsOpenstackIaas(IaasProvider iaasProvider) {
- super(iaasProvider);
- setOpenstackNetworkingApi(iaasProvider);
- }
-
- private void setOpenstackNetworkingApi(IaasProvider iaasProvider) {
- String openstackNetworkingProvider = iaasProvider.getProperty(CloudControllerConstants.OPENSTACK_NETWORKING_PROVIDER);
- if (openstackNetworkingProvider != null &&
- openstackNetworkingProvider.equals(CloudControllerConstants.OPENSTACK_NEUTRON_NETWORKING)) {
- if (log.isDebugEnabled()) {
- String msg = String.format("Openstack networking provider is %s. Trying to instanstiate %s",
- openstackNetworkingProvider, NeutronNetworkingApi.class.getName());
- log.debug(msg);
- }
- openstackNetworkingApi = new NeutronNetworkingApi(iaasProvider);
- } else {
- if (log.isDebugEnabled()) {
- String msg = String.format("Openstack networking provider is %s. Hence trying to instanstiate %s",
- openstackNetworkingProvider, NovaNetworkingApi.class.getName());
- log.debug(msg);
- }
- openstackNetworkingApi = new NovaNetworkingApi(iaasProvider);
- }
- }
-
- @Override
- public void buildComputeServiceAndTemplate() {
- // builds and sets Compute Service
- ComputeService computeService = ComputeServiceBuilderUtil.buildDefaultComputeService(getIaasProvider());
- getIaasProvider().setComputeService(computeService);
-
- // builds and sets Template
- buildTemplate();
- }
-
- public void buildTemplate() {
- IaasProvider iaasProvider = getIaasProvider();
-
- if (iaasProvider.getComputeService() == null) {
- throw new CloudControllerException(
- "Compute service is null for IaaS provider: "
- + iaasProvider.getName());
- }
-
- TemplateBuilder templateBuilder = iaasProvider.getComputeService()
- .templateBuilder();
- templateBuilder.imageId(iaasProvider.getImage());
- if(!(iaasProvider instanceof IaasProvider)) {
- templateBuilder.locationId(iaasProvider.getType());
- }
-
- // to avoid creation of template objects in each and every time, we
- // create all at once!
-
- String instanceType;
-
- // set instance type
- if (((instanceType = iaasProvider.getProperty(CloudControllerConstants.INSTANCE_TYPE)) != null)) {
-
- templateBuilder.hardwareId(instanceType);
- }
-
- Template template = templateBuilder.build();
-
- // In Openstack the call to IaaS should be blocking, in order to retrieve
- // IP addresses.
- boolean blockUntilRunning = true;
- if(iaasProvider.getProperty(CloudControllerConstants.BLOCK_UNTIL_RUNNING) != null) {
- blockUntilRunning = Boolean.parseBoolean(iaasProvider.getProperty(
- CloudControllerConstants.BLOCK_UNTIL_RUNNING));
- }
- template.getOptions().as(TemplateOptions.class)
- .blockUntilRunning(blockUntilRunning);
-
- // this is required in order to avoid creation of additional security
- // groups by Jclouds.
- template.getOptions().as(TemplateOptions.class)
- .inboundPorts(new int[] {});
-
- if (iaasProvider.getProperty(CloudControllerConstants.SECURITY_GROUPS) != null) {
- template.getOptions()
- .as(NovaTemplateOptions.class)
- .securityGroupNames(
- iaasProvider.getProperty(CloudControllerConstants.SECURITY_GROUPS).split(
- CloudControllerConstants.ENTRY_SEPARATOR));
- }
-
- if (iaasProvider.getProperty(CloudControllerConstants.KEY_PAIR) != null) {
- template.getOptions().as(NovaTemplateOptions.class)
- .keyPairName(iaasProvider.getProperty(CloudControllerConstants.KEY_PAIR));
- }
-
- if (iaasProvider.getNetworkInterfaces() != null) {
- Set<Network> novaNetworksSet = new LinkedHashSet<Network>(iaasProvider.getNetworkInterfaces().length);
- for (NetworkInterface ni:iaasProvider.getNetworkInterfaces()) {
- novaNetworksSet.add(Network.builder().networkUuid(ni.getNetworkUuid()).fixedIp(ni.getFixedIp())
- .portUuid(ni.getPortUuid()).build());
- }
- template.getOptions().as(NovaTemplateOptions.class).novaNetworks(novaNetworksSet);
- }
-
- if (iaasProvider.getProperty(CloudControllerConstants.AVAILABILITY_ZONE) != null) {
- template.getOptions().as(NovaTemplateOptions.class)
- .availabilityZone(iaasProvider.getProperty(CloudControllerConstants.AVAILABILITY_ZONE));
- }
-
- //TODO
-// if (iaas.getProperty(CloudControllerConstants.HOST) != null) {
-// template.getOptions().as(NovaTemplateOptions.class)
-// .(CloudControllerConstants.HOST);
-// }
-
- // set Template
- iaasProvider.setTemplate(template);
- }
-
- @Override
- public void setDynamicPayload(byte[] payload) {
- if (getIaasProvider().getTemplate() != null) {
- getIaasProvider().getTemplate().getOptions().as(NovaTemplateOptions.class).userData(payload);
- }
- }
-
- @Override
- public synchronized boolean createKeyPairFromPublicKey(String region, String keyPairName,
- String publicKey) {
-
- IaasProvider iaasInfo = getIaasProvider();
-
- String openstackNovaMsg = " Openstack-nova. Region: " + region
- + " - Name: ";
-
- ComputeServiceContext context = iaasInfo.getComputeService()
- .getContext();
- NovaApi novaApi = context.unwrapApi(NovaApi.class);
- KeyPairApi api = novaApi.getKeyPairExtensionForZone(region).get();
-
- KeyPair keyPair = api.createWithPublicKey(keyPairName, publicKey);
-
- if (keyPair != null) {
-
- iaasInfo.getTemplate().getOptions().as(NovaTemplateOptions.class)
- .keyPairName(keyPair.getName());
-
- log.info(SUCCESSFUL_LOG_LINE + openstackNovaMsg + keyPair.getName());
- return true;
- }
-
- log.error(FAILED_LOG_LINE + openstackNovaMsg);
- return false;
-
- }
-
- @Override
- public synchronized List<String> associateAddresses(NodeMetadata node) {
- //TODO return the list of IP addresses once the topology changes is done
- return openstackNetworkingApi.associateAddresses(node);
- }
-
- @Override
- public synchronized String associatePredefinedAddress (NodeMetadata node, String ip) {
- return openstackNetworkingApi.associatePredefinedAddress(node, ip);
- }
-
- @Override
- public synchronized void releaseAddress(String ip) {
- openstackNetworkingApi.releaseAddress(ip);
- }
-
- @Override
- public boolean isValidRegion(String region) throws InvalidRegionException {
- IaasProvider iaasInfo = getIaasProvider();
-
- // jclouds' zone = region in openstack
- if (region == null || iaasInfo == null) {
- String msg =
- "Region or IaaSProvider is null: region: " + region + " - IaaSProvider: " +
- iaasInfo;
- log.error(msg);
- throw new InvalidRegionException(msg);
- }
-
- ComputeServiceContext context = iaasInfo.getComputeService().getContext();
- NovaApi novaApi = context.unwrapApi(NovaApi.class);
- Set<String> zones = novaApi.getConfiguredZones();
- for (String configuredZone : zones) {
- if (region.equalsIgnoreCase(configuredZone)) {
- if (log.isDebugEnabled()) {
- log.debug("Found a matching region: " + region);
- }
- return true;
- }
- }
-
- String msg = "Invalid region: " + region +" in the iaas: "+iaasInfo.getType();
- log.error(msg);
- throw new InvalidRegionException(msg);
- }
-
- @Override
- public boolean isValidZone(String region, String zone) throws InvalidZoneException {
- IaasProvider iaasInfo = getIaasProvider();
-
- // jclouds availability zone = stratos zone
- if (region == null || zone == null || iaasInfo == null) {
- String msg = "Host or Zone or IaaSProvider is null: region: " + region + " - zone: " +
- zone + " - IaaSProvider: " + iaasInfo;
- log.error(msg);
- throw new InvalidZoneException(msg);
- }
- ComputeServiceContext context = iaasInfo.getComputeService().getContext();
- NovaApi novaApi = context.unwrapApi(NovaApi.class);
- Optional<? extends AvailabilityZoneApi> availabilityZoneApi = novaApi.getAvailabilityZoneApi(region);
- for (AvailabilityZone z : availabilityZoneApi.get().list()) {
-
- if (zone.equalsIgnoreCase(z.getName())) {
- if (log.isDebugEnabled()) {
- log.debug("Found a matching availability zone: " + zone);
- }
- return true;
- }
- }
-
- String msg = "Invalid zone: " + zone +" in the region: "+region+ " and of the iaas: "+iaasInfo.getType();
- log.error(msg);
- throw new InvalidZoneException(msg);
-
- }
-
- @Override
- public boolean isValidHost(String zone, String host) throws InvalidHostException {
- IaasProvider iaasInfo = getIaasProvider();
-
- if (host == null || zone == null || iaasInfo == null) {
- String msg = String.format("Host or Zone or IaaSProvider is null: host: %s - zone: %s - IaaSProvider: %s", host, zone, iaasInfo);
- log.error(msg);
- throw new InvalidHostException(msg);
- }
- ComputeServiceContext context = iaasInfo.getComputeService().getContext();
- NovaApi novaApi = context.unwrapApi(NovaApi.class);
- HostAggregateApi hostApi = novaApi.getHostAggregateExtensionForZone(zone).get();
- for (HostAggregate hostAggregate : hostApi.list()) {
- for (String configuredHost : hostAggregate.getHosts()) {
- if (host.equalsIgnoreCase(configuredHost)) {
- if (log.isDebugEnabled()) {
- log.debug("Found a matching host: " + host);
- }
- return true;
- }
- }
- }
-
- String msg = String.format("Invalid host: %s in the zone: %s and of the iaas: %s", host, zone, iaasInfo.getType());
- log.error(msg);
- throw new InvalidHostException(msg);
- }
-
- @Override
- public PartitionValidator getPartitionValidator() {
- return new OpenstackNovaPartitionValidator();
- }
-
- @Override
- public String createVolume(int sizeGB, String snapshotId) {
- IaasProvider iaasInfo = getIaasProvider();
-
- if (iaasInfo == null) {
- log.fatal(String.format("Cannot create a new volume with snapshot ID : %s", snapshotId));
- return null;
- }
-
- String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);
- String zone = ComputeServiceBuilderUtil.extractZone(iaasInfo);
-
- if (region == null) {
- log.fatal(String.format("Cannot create a new volume. Extracted region is null for Iaas : %s", iaasInfo));
- return null;
- }
- ComputeServiceContext context = iaasInfo.getComputeService().getContext();
-
- NovaApi novaApi = context.unwrapApi(NovaApi.class);
- VolumeApi volumeApi = novaApi.getVolumeExtensionForZone(region).get();
- Volume volume;
- if(StringUtils.isEmpty(snapshotId)){
- if(log.isDebugEnabled()){
- log.info("Creating a volume in the zone " + zone);
- }
- volume = volumeApi.create(sizeGB, CreateVolumeOptions.Builder.availabilityZone(zone));
- }else{
- if(log.isDebugEnabled()){
- log.info("Creating a volume in the zone " + zone + " from the shanpshot " + snapshotId);
- }
- volume = volumeApi.create(sizeGB, CreateVolumeOptions.Builder.availabilityZone(zone).snapshotId(snapshotId));
- }
-
- if (volume == null) {
- log.fatal(String.format("Volume creation was unsuccessful. [region] : %s [zone] : %s of Iaas : %s", region, zone, iaasInfo));
- return null;
- }
-
- String volumeId = volume.getId();
- /*
- Volume.Status volumeStatus = this.getVolumeStatus(volumeApi, volumeId);
-
- if(!(volumeStatus == Volume.Status.AVAILABLE || volumeStatus == Volume.Status.CREATING)){
- log.error(String.format("Error while creating [volume id] %s. Volume status is %s", volumeId, volumeStatus));
- return volumeId;
- }
- try {
- if(!waitForStatus(volumeApi, volumeId, Volume.Status.AVAILABLE)){
- log.error("Volume did not become AVAILABLE. Current status is " + volume.getStatus());
- }
- } catch (TimeoutException e) {
- log.error("[Volume ID] " + volumeId + "did not become AVAILABLE within expected timeout");
- return volumeId;
- }
- */
- log.info(String.format("Successfully created a new volume [id]: %s in [region] : %s [zone] : %s of Iaas : %s [Volume ID]%s", volume.getId(), region, zone, iaasInfo, volume.getId()));
- return volumeId;
- }
-
- private boolean waitForStatus(String volumeId, Volume.Status expectedStatus, int timeoutInMins) throws TimeoutException {
- int timeout = 1000 * 60 * timeoutInMins;
- long timout = System.currentTimeMillis() + timeout;
-
- IaasProvider iaasInfo = getIaasProvider();
- String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);
- ComputeServiceContext context = iaasInfo.getComputeService().getContext();
- NovaApi novaApi = context.unwrapApi(NovaApi.class);
- VolumeApi volumeApi = novaApi.getVolumeExtensionForZone(region).get();
- Volume.Status volumeStatus = this.getVolumeStatus(volumeApi, volumeId);
-
- while(volumeStatus != expectedStatus){
- try {
- if(log.isDebugEnabled()){
- log.debug(String.format("Volume %s is still NOT in %s. Current State=%s", volumeId, expectedStatus, volumeStatus));
- }
- if(volumeStatus == Volume.Status.ERROR){
- log.error("Volume " + volumeId + " is in state ERROR");
- return false;
- }
- Thread.sleep(1000);
- volumeStatus = this.getVolumeStatus(volumeApi, volumeId);
- if (System.currentTimeMillis()> timout) {
- throw new TimeoutException();
- }
- } catch (InterruptedException e) {
- // Ignoring the exception
- }
- }
- if(log.isDebugEnabled()){
- log.debug(String.format("Volume %s status became %s", volumeId, expectedStatus));
- }
-
- return true;
- }
-
- @Override
- public String attachVolume(String instanceId, String volumeId, String deviceName) {
- IaasProvider iaasInfo = getIaasProvider();
-
- if (StringUtils.isEmpty(volumeId)) {
- log.error("Volume provided to attach can not be null");
- }
-
- if (StringUtils.isEmpty(instanceId)) {
- log.error("Instance provided to attach can not be null");
- }
-
- ComputeServiceContext context = iaasInfo.getComputeService()
- .getContext();
- String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);
- String device = deviceName == null ? "/dev/vdc" : deviceName;
-
- if (region == null) {
- log.fatal(String.format("Cannot attach the volume [id]: %s. Extracted region is null for Iaas : %s", volumeId, iaasInfo));
- return null;
- }
-
- NovaApi novaApi = context.unwrapApi(NovaApi.class);
- VolumeApi volumeApi = novaApi.getVolumeExtensionForZone(region).get();
- VolumeAttachmentApi volumeAttachmentApi = novaApi.getVolumeAttachmentExtensionForZone(region).get();
-
- Volume.Status volumeStatus = this.getVolumeStatus(volumeApi, volumeId);
-
- if (log.isDebugEnabled()) {
- log.debug("Volume " + volumeId + " is in state " + volumeStatus);
- }
-
- if (!(volumeStatus == Volume.Status.AVAILABLE || volumeStatus == Volume.Status.CREATING)) {
- log.error(String.format("Volume %s can not be attached. Volume status is %s", volumeId, volumeStatus));
- return null;
- }
-
- boolean volumeBecameAvailable = false, volumeBecameAttached = false;
- try {
- volumeBecameAvailable = waitForStatus(volumeId, Volume.Status.AVAILABLE, 5);
- } catch (TimeoutException e) {
- log.error("[Volume ID] " + volumeId + "did not become AVAILABLE within expected timeout");
- }
-
- VolumeAttachment attachment = null;
- if (volumeBecameAvailable) {
- attachment = volumeAttachmentApi.attachVolumeToServerAsDevice(volumeId, instanceId, device);
-
- try {
- volumeBecameAttached = waitForStatus(volumeId, Volume.Status.IN_USE, 2);
- } catch (TimeoutException e) {
- log.error("[Volume ID] " + volumeId + "did not become IN_USE within expected timeout");
- }
- }
- try {
- // waiting 5seconds till volumes are actually attached.
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
-
- if (attachment == null) {
- log.fatal(String.format("Volume [id]: %s attachment for instance [id]: %s was unsuccessful. [region] : %s of Iaas : %s", volumeId, instanceId, region, iaasInfo));
- return null;
- }
-
- if(! volumeBecameAttached){
- log.error(String.format("[Volume ID] %s attachment is called, but not yet became attached", volumeId));
- }
-
- log.info(String.format("Volume [id]: %s attachment for instance [id]: %s was successful [status]: Attaching. [region] : %s of Iaas : %s", volumeId, instanceId, region, iaasInfo));
- return "Attaching";
- }
-
- @Override
- public void detachVolume(String instanceId, String volumeId) {
- IaasProvider iaasInfo = getIaasProvider();
-
- ComputeServiceContext context = iaasInfo.getComputeService()
- .getContext();
-
- String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);
-
- if(region == null) {
- log.fatal(String.format("Cannot detach the volume [id]: %s from the instance [id]: %s. Extracted region is null for Iaas : %s", volumeId, instanceId, iaasInfo));
- return;
- }
- if(log.isDebugEnabled()) {
- log.debug(String.format("Starting to detach volume %s from the instance %s", volumeId, instanceId));
- }
-
- NovaApi novaApi = context.unwrapApi(NovaApi.class);
- VolumeAttachmentApi api = novaApi.getVolumeAttachmentExtensionForZone(region).get();
- if (api.detachVolumeFromServer(volumeId, instanceId)) {
- log.info(String.format("Detachment of Volume [id]: %s from instance [id]: %s was successful. [region] : %s of Iaas : %s", volumeId, instanceId, region, iaasInfo));
- }else{
- log.error(String.format("Detachment of Volume [id]: %s from instance [id]: %s was unsuccessful. [volume Status] : %s", volumeId, instanceId, region, iaasInfo));
- }
-
- }
-
- @Override
- public void deleteVolume(String volumeId) {
- IaasProvider iaasInfo = getIaasProvider();
-
- ComputeServiceContext context = iaasInfo.getComputeService()
- .getContext();
-
- String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);
-
- if(region == null) {
- log.fatal(String.format("Cannot delete the volume [id]: %s. Extracted region is null for Iaas : %s", volumeId, iaasInfo));
- return;
- }
-
- NovaApi novaApi = context.unwrapApi(NovaApi.class);
- VolumeApi api = novaApi.getVolumeExtensionForZone(region).get();
- if (api.delete(volumeId)) {
- log.info(String.format("Deletion of Volume [id]: %s was successful. [region] : %s of Iaas : %s", volumeId, region, iaasInfo));
- }
- }
-
- @Override
- public String getIaasDevice(String device) {
- return device;
- }
-
- private Volume.Status getVolumeStatus(VolumeApi volumeApi, String volumeId){
- return volumeApi.get(volumeId).getStatus();
- }
-}
http://git-wip-us.apache.org/repos/asf/stratos/blob/e195f2f1/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/iaases/JcloudsVCloudIaas.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/iaases/JcloudsVCloudIaas.java b/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/iaases/JcloudsVCloudIaas.java
deleted file mode 100644
index d45e114..0000000
--- a/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/iaases/JcloudsVCloudIaas.java
+++ /dev/null
@@ -1,262 +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.apache.stratos.cloud.controller.iaases;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang.StringUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.cloud.controller.exception.CloudControllerException;
-import org.apache.stratos.cloud.controller.util.ComputeServiceBuilderUtil;
-import org.apache.stratos.cloud.controller.domain.IaasProvider;
-import org.apache.stratos.cloud.controller.iaases.validators.PartitionValidator;
-import org.apache.stratos.cloud.controller.iaases.validators.VCloudPartitionValidator;
-import org.jclouds.compute.ComputeService;
-import org.jclouds.compute.domain.NodeMetadata;
-import org.jclouds.compute.domain.Template;
-import org.jclouds.compute.domain.TemplateBuilder;
-import org.jclouds.compute.options.TemplateOptions;
-import org.jclouds.vcloud.compute.options.VCloudTemplateOptions;
-import org.jclouds.vcloud.domain.network.IpAddressAllocationMode;
-import org.wso2.carbon.utils.CarbonUtils;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.List;
-
-public class JcloudsVCloudIaas extends JcloudsIaas {
-
-
- private static final Log log = LogFactory.getLog(JcloudsVCloudIaas.class);
-
- private static final String SHELL_TYPE = "shellType";
- private static final String SCRIPTS_PATH = "scripts";
- private static final String CUSTOMIZATION_SCRIPT = "customization";
- private static final String PAYLOAD = "PAYLOAD";
-
- public JcloudsVCloudIaas(IaasProvider iaasProvider) {
- super(iaasProvider);
- }
-
- @Override
- public void buildComputeServiceAndTemplate() {
- // builds and sets Compute Service
- ComputeService computeService = ComputeServiceBuilderUtil.buildDefaultComputeService(getIaasProvider());
- getIaasProvider().setComputeService(computeService);
-
- // builds and sets Template
- buildTemplate();
-
- }
-
- public void buildTemplate() {
- IaasProvider iaasInfo = getIaasProvider();
-
- if (iaasInfo.getComputeService() == null) {
- String msg = "Compute service is null for IaaS provider: "
- + iaasInfo.getName();
- log.fatal(msg);
- throw new CloudControllerException(msg);
- }
-
- TemplateBuilder templateBuilder = iaasInfo.getComputeService()
- .templateBuilder();
-
- // set image id specified
- templateBuilder.imageId(iaasInfo.getImage());
-
- // build the Template
- Template template = templateBuilder.build();
-
- // if you wish to auto assign IPs, instance spawning call should be
- // blocking, but if you
- // wish to assign IPs manually, it can be non-blocking.
- // is auto-assign-ip mode or manual-assign-ip mode? - default mode is
- // non-blocking
- boolean blockUntilRunning = Boolean.parseBoolean(iaasInfo
- .getProperty("autoAssignIp"));
- template.getOptions().as(TemplateOptions.class)
- .blockUntilRunning(blockUntilRunning);
-
- // this is required in order to avoid creation of additional security
- // groups by Jclouds.
- template.getOptions().as(TemplateOptions.class)
- .inboundPorts(22, 80, 8080, 443, 8243);
-
- template.getOptions().as(VCloudTemplateOptions.class)
- .ipAddressAllocationMode(IpAddressAllocationMode.POOL);
-
- // set Template
- iaasInfo.setTemplate(template);
- }
-
- @Override
- public void setDynamicPayload(byte[] payload) {
- // in vCloud case we need to run a script
- IaasProvider iaasProvider = getIaasProvider();
-
- if (iaasProvider.getTemplate() == null) {
- if (log.isDebugEnabled()) {
- log.debug("Payload for vCloud not found");
- }
- return;
- }
-
- String shellType = iaasProvider.getProperty(SHELL_TYPE);
-
- if (shellType == null || shellType.isEmpty()) {
- if (log.isDebugEnabled()) {
- log.debug("Shell Type for vCloud Customization script not found from properties");
- }
- return;
- }
-
- if (log.isDebugEnabled()) {
- log.debug(String.format("Shell Type '%s' will be used for vCloud Customization script", shellType));
- }
-
- // Payload is a String value
- String payloadStr = new String(payload);
-
- if (log.isDebugEnabled()) {
- log.debug(String.format("Payload '%s' will be used for vCloud Customization script", payload));
- }
-
- Template template = iaasProvider.getTemplate();
-
- File scriptPath = new File(CarbonUtils.getCarbonConfigDirPath(), SCRIPTS_PATH);
-
- File customizationScriptFile = new File(new File(scriptPath, shellType), CUSTOMIZATION_SCRIPT);
-
- if (!customizationScriptFile.exists()) {
- if (log.isWarnEnabled()) {
- log.warn(String.format("The vCloud Customization script '%s' does not exist",
- customizationScriptFile.getAbsolutePath()));
- }
- return;
- }
-
- String customizationScript = null;
-
- try {
- customizationScript = FileUtils.readFileToString(customizationScriptFile);
- } catch (IOException e) {
- if (log.isErrorEnabled()) {
- log.error(
- String.format("Error reading the vCloud Customization script '%s'",
- customizationScriptFile.getAbsolutePath()), e);
- }
- }
-
- if (StringUtils.isEmpty(customizationScript)) {
- if (log.isDebugEnabled()) {
- log.debug("No content vCloud Customization script not found from properties");
- }
- return;
- }
-
- // Set payload
- customizationScript = customizationScript.replaceAll(PAYLOAD, payloadStr);
-
- if (log.isDebugEnabled()) {
- log.debug(String.format("The vCloud Customization script\n%s", customizationScript));
- }
-
- // Run the script
- template.getOptions().runScript(customizationScript);
- }
-
- @Override
- public boolean createKeyPairFromPublicKey(String region, String keyPairName, String publicKey) {
-
- // TODO
- return false;
- }
-
- @Override
- public List<String> associateAddresses(NodeMetadata node) {
-
- // TODO
- return null;
-
- }
-
- @Override
- public String associatePredefinedAddress(NodeMetadata node, String ip) {
- return "";
- }
-
- @Override
- public void releaseAddress(String ip) {
- // TODO
- }
-
- @Override
- public boolean isValidRegion(String region) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean isValidZone(String region, String zone) {
- // TODO Auto-generated method stub
- return true;
- }
-
- @Override
- public boolean isValidHost(String zone, String host) {
- // TODO Auto-generated method stub
- return true;
- }
-
- @Override
- public PartitionValidator getPartitionValidator() {
- return new VCloudPartitionValidator();
- }
-
- @Override
- public String createVolume(int sizeGB, String snapshotId) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String attachVolume(String instanceId, String volumeId, String deviceName) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public void detachVolume(String instanceId, String volumeId) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void deleteVolume(String volumeId) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public String getIaasDevice(String device) {
- return device;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/stratos/blob/e195f2f1/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/iaases/KubernetesIaas.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/iaases/KubernetesIaas.java b/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/iaases/KubernetesIaas.java
deleted file mode 100644
index 2ae3a85..0000000
--- a/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/iaases/KubernetesIaas.java
+++ /dev/null
@@ -1,600 +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.apache.stratos.cloud.controller.iaases;
-
-import org.apache.commons.lang.NotImplementedException;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.cloud.controller.concurrent.ScheduledThreadExecutor;
-import org.apache.stratos.cloud.controller.context.CloudControllerContext;
-import org.apache.stratos.cloud.controller.domain.*;
-import org.apache.stratos.cloud.controller.domain.Cartridge;
-import org.apache.stratos.cloud.controller.domain.kubernetes.KubernetesClusterContext;
-import org.apache.stratos.cloud.controller.exception.*;
-import org.apache.stratos.cloud.controller.functions.ContainerClusterContextToReplicationController;
-import org.apache.stratos.cloud.controller.iaases.validators.KubernetesPartitionValidator;
-import org.apache.stratos.cloud.controller.iaases.validators.PartitionValidator;
-import org.apache.stratos.cloud.controller.services.impl.CloudControllerServiceUtil;
-import org.apache.stratos.cloud.controller.util.CloudControllerUtil;
-import org.apache.stratos.cloud.controller.util.PodActivationWatcher;
-import org.apache.stratos.common.beans.NameValuePair;
-import org.apache.stratos.common.constants.StratosConstants;
-import org.apache.stratos.cloud.controller.domain.kubernetes.KubernetesCluster;
-import org.apache.stratos.cloud.controller.domain.kubernetes.PortRange;
-import org.apache.stratos.kubernetes.client.KubernetesApiClient;
-import org.apache.stratos.kubernetes.client.exceptions.KubernetesClientException;
-import org.apache.stratos.kubernetes.client.model.*;
-import org.apache.stratos.kubernetes.client.model.Service;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.locks.Lock;
-
-/**
- * Kubernetes iaas implementation.
- */
-public class KubernetesIaas extends Iaas {
-
- private static final Log log = LogFactory.getLog(KubernetesIaas.class);
- private static final long POD_CREATION_TIMEOUT = 120000; // 1 min
- public static final String PAYLOAD_PARAMETER_SEPARATOR = ",";
- public static final String PAYLOAD_PARAMETER_NAME_VALUE_SEPARATOR = "=";
-
- private PartitionValidator partitionValidator;
- private List<NameValuePair> payload;
-
- public KubernetesIaas(IaasProvider iaasProvider) {
- super(iaasProvider);
- partitionValidator = new KubernetesPartitionValidator();
- payload = new ArrayList<NameValuePair>();
- }
-
- @Override
- public void initialize() {
- }
-
- @Override
- public void setDynamicPayload(byte[] payloadByteArray) {
- // Clear existing payload parameters
- payload.clear();
-
- if(payloadByteArray != null) {
- String payloadString = new String(payloadByteArray);
- String[] parameterArray = payloadString.split(PAYLOAD_PARAMETER_SEPARATOR);
- if(parameterArray != null) {
- for(String parameter : parameterArray) {
- if(parameter != null) {
- String[] nameValueArray = parameter.split(PAYLOAD_PARAMETER_NAME_VALUE_SEPARATOR);
- if ((nameValueArray != null) && (nameValueArray.length == 2)) {
- NameValuePair nameValuePair = new NameValuePair(nameValueArray[0], nameValueArray[1]);
- payload.add(nameValuePair);
- }
- }
- }
- if(log.isDebugEnabled()) {
- log.debug("Dynamic payload is set: " + payload.toString());
- }
- }
- }
- }
-
- @Override
- public MemberContext startInstance(MemberContext memberContext) throws CartridgeNotFoundException {
- return startContainer(memberContext);
- }
-
- @Override
- public PartitionValidator getPartitionValidator() {
- return partitionValidator;
- }
-
- @Override
- public void terminateInstance(MemberContext memberContext) throws InvalidCartridgeTypeException,
- InvalidMemberException, MemberTerminationFailedException {
- terminateContainer(memberContext.getMemberId());
- }
-
- public MemberContext startContainer(MemberContext memberContext)
- throws CartridgeNotFoundException {
- Lock lock = null;
- try {
- lock = CloudControllerContext.getInstance().acquireMemberContextWriteLock();
-
- handleNullObject(memberContext, "Could not start container, member context is null");
- if (log.isInfoEnabled()) {
- log.info(String.format("Starting container: [cartridge-type] %s", memberContext.getCartridgeType()));
- }
-
- // Validate cluster id
- String clusterId = memberContext.getClusterId();
- String memberId = memberContext.getMemberId();
- handleNullObject(clusterId, "Could not start containers, cluster id is null in member context");
-
- // Validate cluster context
- ClusterContext clusterContext = CloudControllerContext.getInstance().getClusterContext(clusterId);
- handleNullObject(clusterContext, "Could not start containers, cluster context not found: [cluster-id] "
- + clusterId + " [member-id] " + memberId);
-
- // Validate partition
- Partition partition = memberContext.getPartition();
- handleNullObject(partition, "Could not start containers, partition not found in member context: " +
- "[cluster-id] " + clusterId + " [member-id] " + memberId);
-
- // Validate cartridge
- String cartridgeType = clusterContext.getCartridgeType();
- Cartridge cartridge = CloudControllerContext.getInstance().getCartridge(cartridgeType);
- if (cartridge == null) {
- String msg = "Could not start containers, cartridge not found: [cartridge-type] " + cartridgeType + " " +
- "[cluster-id] " + clusterId + " [member-id] " + memberId;
- log.error(msg);
- throw new CartridgeNotFoundException(msg);
- }
-
- try {
- String kubernetesClusterId = partition.getKubernetesClusterId();
- KubernetesCluster kubernetesCluster = CloudControllerContext.getInstance().
- getKubernetesCluster(kubernetesClusterId);
- handleNullObject(kubernetesCluster, "Could not start container, kubernetes cluster not found: " +
- "[kubernetes-cluster-id] " + kubernetesClusterId + " [cluster-id] " + clusterId +
- " [member-id] " + memberId);
-
- // Prepare kubernetes context
- String kubernetesMasterIp = kubernetesCluster.getKubernetesMaster().getHostIpAddress();
- PortRange kubernetesPortRange = kubernetesCluster.getPortRange();
- String kubernetesMasterPort = CloudControllerUtil.getProperty(
- kubernetesCluster.getKubernetesMaster().getProperties(), StratosConstants.KUBERNETES_MASTER_PORT,
- StratosConstants.KUBERNETES_MASTER_DEFAULT_PORT);
-
- KubernetesClusterContext kubClusterContext = getKubernetesClusterContext(kubernetesClusterId,
- kubernetesMasterIp, kubernetesMasterPort, kubernetesPortRange.getUpper(),
- kubernetesPortRange.getLower());
-
- // Get kubernetes API
- KubernetesApiClient kubernetesApi = kubClusterContext.getKubApi();
-
- // Create proxy services for port mappings
- List<Service> services = createProxyServices(clusterContext, kubClusterContext, kubernetesApi);
- clusterContext.setKubernetesServices(services);
- CloudControllerContext.getInstance().updateClusterContext(clusterContext);
-
- // Create replication controller
- createReplicationController(memberContext, clusterId, kubernetesApi);
-
- // Wait for pod to be created
- List<Pod> pods = waitForPodToBeCreated(memberContext, kubernetesApi);
- if (pods.size() != 1) {
- if (log.isDebugEnabled()) {
- log.debug(String.format("Pod did not create within %d sec, hence deleting the service: " +
- "[cluster-id] %s [member-id] %s", ((int)POD_CREATION_TIMEOUT/1000), clusterId, memberId));
- }
- try {
- terminateContainers(clusterId);
- } catch (Exception e) {
- String message = "Could not terminate containers which were partially created";
- log.error(message, e);
- throw new RuntimeException(message, e);
- }
- }
- Pod pod = pods.get(0);
- if (log.isDebugEnabled()) {
- log.debug(String.format("Pod created: [cluster-id] %s [member-id] %s [pod-id] %s",
- clusterId, memberId, pod.getId()));
- }
-
- // Create member context
- MemberContext newMemberContext = createNewMemberContext(memberContext, pod);
- CloudControllerContext.getInstance().addMemberContext(newMemberContext);
-
- // wait till pod status turns to running and send member spawned.
- ScheduledThreadExecutor exec = ScheduledThreadExecutor.getInstance();
- if (log.isDebugEnabled()) {
- log.debug("Cloud Controller is starting the instance start up thread.");
- }
- CloudControllerContext.getInstance().addScheduledFutureJob(newMemberContext.getMemberId(),
- exec.schedule(new PodActivationWatcher(pod.getId(), newMemberContext, kubernetesApi), 5000));
-
- // persist in registry
- CloudControllerContext.getInstance().persist();
- log.info("Container started successfully: [cluster-id] " + clusterId + " [member-id] " +
- memberContext.getMemberId());
-
- return newMemberContext;
- } catch (Exception e) {
- String msg = String.format("Could not start container: [cartridge-type] %s [member-id] %s",
- memberContext.getCartridgeType(), memberContext.getMemberId());
- log.error(msg, e);
- throw new IllegalStateException(msg, e);
- }
- } finally {
- if (lock != null) {
- CloudControllerContext.getInstance().releaseWriteLock(lock);
- }
- }
- }
-
- private MemberContext createNewMemberContext(MemberContext memberContext, Pod pod) {
- MemberContext newMemberContext = new MemberContext();
- newMemberContext.setCartridgeType(memberContext.getCartridgeType());
- newMemberContext.setClusterId(memberContext.getClusterId());
- newMemberContext.setClusterInstanceId(memberContext.getClusterInstanceId());
- newMemberContext.setMemberId(memberContext.getMemberId());
- newMemberContext.setNetworkPartitionId(memberContext.getNetworkPartitionId());
- newMemberContext.setPartition(memberContext.getPartition());
- newMemberContext.setInstanceId(pod.getId());
- newMemberContext.setDefaultPrivateIP(pod.getCurrentState().getHostIP());
- newMemberContext.setPrivateIPs(new String[]{pod.getCurrentState().getHostIP()});
- newMemberContext.setDefaultPublicIP(pod.getCurrentState().getHostIP());
- newMemberContext.setPublicIPs(new String[]{pod.getCurrentState().getHostIP()});
- newMemberContext.setInitTime(memberContext.getInitTime());
- newMemberContext.setProperties(memberContext.getProperties());
- return newMemberContext;
- }
-
- private List<Pod> waitForPodToBeCreated(MemberContext memberContext, KubernetesApiClient kubernetesApi) throws KubernetesClientException, InterruptedException {
- Labels labels = new Labels();
- labels.setName(memberContext.getClusterId());
- List<Pod> podList = new ArrayList<Pod>();
- long startTime = System.currentTimeMillis();
- while (podList.size() == 0) {
- Pod[] pods = kubernetesApi.queryPods(new Labels[]{labels});
- if((pods != null) && (pods.length > 0)){
- for(Pod pod : pods) {
- if(pod != null) {
- podList.add(pod);
- }
- }
- }
- if (log.isDebugEnabled()) {
- log.debug("Member pod: [member-id] " + memberContext.getMemberId() + " [count] " + podList.size());
- }
- if ((System.currentTimeMillis() - startTime) > POD_CREATION_TIMEOUT) {
- break;
- }
- Thread.sleep(5000);
- }
- return podList;
- }
-
- /**
- * Create new replication controller for the cluster and generate environment variables using member context.
- * @param memberContext
- * @param clusterId
- * @param kubernetesApi
- * @throws KubernetesClientException
- */
- private ReplicationController createReplicationController(MemberContext memberContext, String clusterId,
- KubernetesApiClient kubernetesApi)
- throws KubernetesClientException {
- if (log.isDebugEnabled()) {
- log.debug("Creating kubernetes replication controller: [cluster-id] " + clusterId);
- }
-
- // Add dynamic payload to the member context
- memberContext.setDynamicPayload(payload);
- ContainerClusterContextToReplicationController controllerFunction =
- new ContainerClusterContextToReplicationController();
-
- // Create replication controller
- ReplicationController replicationController = controllerFunction.apply(memberContext);
- kubernetesApi.createReplicationController(replicationController);
- if (log.isInfoEnabled()) {
- log.info("Kubernetes replication controller successfully created: [cluster-id] " + clusterId);
- }
- return replicationController;
- }
-
- /**
- * Create proxy services for the cluster and add them to the cluster context.
- * @param clusterContext
- * @param kubernetesClusterContext
- * @param kubernetesApi
- * @return
- * @throws KubernetesClientException
- */
- private List<Service> createProxyServices(ClusterContext clusterContext,
- KubernetesClusterContext kubernetesClusterContext,
- KubernetesApiClient kubernetesApi) throws KubernetesClientException {
- List<Service> services = new ArrayList<Service>();
-
- String clusterId = clusterContext.getClusterId();
- Cartridge cartridge = CloudControllerContext.getInstance().getCartridge(clusterContext.getCartridgeType());
- if(cartridge == null) {
- String message = "Could not create kubernetes services, cartridge not found: [cartridge-type] " +
- clusterContext.getCartridgeType();
- log.error(message);
- throw new RuntimeException(message);
- }
-
- List<PortMapping> portMappings = cartridge.getPortMappings();
- for(PortMapping portMapping : portMappings) {
- String serviceId = prepareKubernetesServiceId(clusterId, portMapping);
- int nextServicePort = kubernetesClusterContext.getNextServicePort();
- if(nextServicePort == -1) {
- throw new RuntimeException(String.format("Could not generate service port: [cluster-id] %s ",
- clusterContext.getClusterId()));
- }
-
- if (log.isInfoEnabled()) {
- log.info(String.format("Creating kubernetes service: [cluster-id] %s [service-id] %s " +
- "[protocol] %s [service-port] %d [container-port] %s [proxy-port] %s", clusterId,
- serviceId, portMapping.getProtocol(), nextServicePort, portMapping.getPort(),
- portMapping.getProxyPort()));
- }
-
- Service service = new Service();
- service.setId(serviceId);
- service.setApiVersion("v1beta1");
- service.setKind("Service");
- service.setPort(nextServicePort);
- service.setContainerPort(portMapping.getPort());
-
- Selector selector = new Selector();
- selector.setName(clusterId);
- service.setSelector(selector);
-
- kubernetesApi.createService(service);
- services.add(service);
-
- if (log.isInfoEnabled()) {
- log.info(String.format("Kubernetes service successfully created: [cluster-id] %s [service-id] %s " +
- "[protocol] %s [service-port] %d [container-port] %s [proxy-port] %s", clusterId,
- service.getId(), portMapping.getProtocol(), service.getPort(), portMapping.getPort(),
- portMapping.getProxyPort()));
- }
- }
- return services;
- }
-
- /**
- * Prepare kubernetes service id using clusterId, port protocol and port.
- * @param portMapping
- * @return
- */
- private String prepareKubernetesServiceId(String clusterId, PortMapping portMapping) {
- String serviceId = String.format("%s-%s-%s", clusterId, portMapping.getProtocol(), portMapping.getPort());
- if(serviceId.contains(".")) {
- serviceId = serviceId.replace(".", "-");
- }
- return serviceId;
- }
-
- /**
- * Terminate all the containers belong to a cluster by cluster id.
- * @param clusterId
- * @return
- * @throws InvalidClusterException
- */
- public MemberContext[] terminateContainers(String clusterId)
- throws InvalidClusterException {
- Lock lock = null;
- try {
- lock = CloudControllerContext.getInstance().acquireMemberContextWriteLock();
-
- ClusterContext clusterContext = CloudControllerContext.getInstance().getClusterContext(clusterId);
- handleNullObject(clusterContext, "Could not terminate containers, cluster not found: [cluster-id] " + clusterId);
-
- String kubernetesClusterId = CloudControllerUtil.getProperty(clusterContext.getProperties(),
- StratosConstants.KUBERNETES_CLUSTER_ID);
- handleNullObject(kubernetesClusterId, "Could not terminate containers, kubernetes cluster id not found: " +
- "[cluster-id] " + clusterId);
-
- KubernetesClusterContext kubClusterContext = CloudControllerContext.getInstance().getKubernetesClusterContext(kubernetesClusterId);
- handleNullObject(kubClusterContext, "Could not terminate containers, kubernetes cluster not found: " +
- "[kubernetes-cluster-id] " + kubernetesClusterId);
-
- KubernetesApiClient kubApi = kubClusterContext.getKubApi();
-
- // Remove the services
- List<Service> services = clusterContext.getKubernetesServices();
- if (services != null) {
- for (Service service : services) {
- try {
- kubApi.deleteService(service.getId());
- int allocatedPort = service.getPort();
- kubClusterContext.deallocatePort(allocatedPort);
- } catch (KubernetesClientException e) {
- log.error("Could not remove kubernetes service: [cluster-id] " + clusterId, e);
- }
- }
- }
-
- List<MemberContext> memberContextsRemoved = new ArrayList<MemberContext>();
- List<MemberContext> memberContexts = CloudControllerContext.getInstance().getMemberContextsOfClusterId(clusterId);
- for(MemberContext memberContext : memberContexts) {
- try {
- MemberContext memberContextRemoved = terminateContainer(memberContext.getMemberId());
- memberContextsRemoved.add(memberContextRemoved);
- } catch (MemberTerminationFailedException e) {
- String message = "Could not terminate container: [member-id] " + memberContext.getMemberId();
- log.error(message);
- }
- }
-
- // persist
- CloudControllerContext.getInstance().persist();
- return memberContextsRemoved.toArray(new MemberContext[memberContextsRemoved.size()]);
- } finally {
- if (lock != null) {
- CloudControllerContext.getInstance().releaseWriteLock(lock);
- }
- }
- }
-
- /**
- * Terminate a container by member id
- * @param memberId
- * @return
- * @throws MemberTerminationFailedException
- */
- public MemberContext terminateContainer(String memberId) throws MemberTerminationFailedException {
- Lock lock = null;
- try {
- lock = CloudControllerContext.getInstance().acquireMemberContextWriteLock();
- handleNullObject(memberId, "Could not terminate container, member id is null");
-
- MemberContext memberContext = CloudControllerContext.getInstance().getMemberContextOfMemberId(memberId);
- handleNullObject(memberContext, "Could not terminate container, member context not found: [member-id] " + memberId);
-
- String clusterId = memberContext.getClusterId();
- handleNullObject(clusterId, "Could not terminate container, cluster id is null: [member-id] " + memberId);
-
- ClusterContext clusterContext = CloudControllerContext.getInstance().getClusterContext(clusterId);
- handleNullObject(clusterContext, String.format("Could not terminate container, cluster context not found: " +
- "[cluster-id] %s [member-id] %s", clusterId, memberId));
-
- String kubernetesClusterId = CloudControllerUtil.getProperty(clusterContext.getProperties(),
- StratosConstants.KUBERNETES_CLUSTER_ID);
- handleNullObject(kubernetesClusterId, String.format("Could not terminate container, kubernetes cluster " +
- "context id is null: [cluster-id] %s [member-id] %s", clusterId, memberId));
-
- KubernetesClusterContext kubernetesClusterContext = CloudControllerContext.getInstance().getKubernetesClusterContext(kubernetesClusterId);
- handleNullObject(kubernetesClusterContext, String.format("Could not terminate container, kubernetes cluster " +
- "context not found: [cluster-id] %s [member-id] %s", clusterId, memberId));
- KubernetesApiClient kubApi = kubernetesClusterContext.getKubApi();
-
- // Remove the pod forcefully
- try {
- Labels l = new Labels();
- l.setName(memberId);
- // execute the label query
- Pod[] pods = kubApi.queryPods(new Labels[]{l});
- for (Pod pod : pods) {
- try {
- // delete pods forcefully
- kubApi.deletePod(pod.getId());
- } catch (KubernetesClientException ignore) {
- // we can't do nothing here
- log.warn(String.format("Could not delete pod: [pod-id] %s", pod.getId()));
- }
- }
- } catch (KubernetesClientException e) {
- // we're not going to throw this error, but proceed with other deletions
- log.error("Could not delete pods of cluster: [cluster-id] " + clusterId, e);
- }
-
- // Remove the replication controller
- try {
- kubApi.deleteReplicationController(memberContext.getMemberId());
- MemberContext memberToBeRemoved = CloudControllerContext.getInstance().getMemberContextOfMemberId(memberId);
- CloudControllerServiceUtil.executeMemberTerminationPostProcess(memberToBeRemoved);
- return memberToBeRemoved;
- } catch (KubernetesClientException e) {
- String msg = String.format("Failed to terminate member: [cluster-id] %s [member-id] %s", clusterId, memberId);
- log.error(msg, e);
- throw new MemberTerminationFailedException(msg, e);
- }
- } finally {
- if (lock != null) {
- CloudControllerContext.getInstance().releaseWriteLock(lock);
- }
- }
- }
-
- /**
- * Get kubernetes cluster context
- * @param kubernetesClusterId
- * @param kubernetesMasterIp
- * @param kubernetesMasterPort
- * @param upperPort
- * @param lowerPort
- * @return
- */
- private KubernetesClusterContext getKubernetesClusterContext(String kubernetesClusterId, String kubernetesMasterIp,
- String kubernetesMasterPort, int upperPort, int lowerPort) {
-
- KubernetesClusterContext kubernetesClusterContext = CloudControllerContext.getInstance().
- getKubernetesClusterContext(kubernetesClusterId);
- if (kubernetesClusterContext != null) {
- return kubernetesClusterContext;
- }
-
- kubernetesClusterContext = new KubernetesClusterContext(kubernetesClusterId, kubernetesMasterIp,
- kubernetesMasterPort, lowerPort, upperPort);
- CloudControllerContext.getInstance().addKubernetesClusterContext(kubernetesClusterContext);
- return kubernetesClusterContext;
- }
-
- private String readProperty(String property, org.apache.stratos.common.Properties properties, String object) {
- String propVal = CloudControllerUtil.getProperty(properties, property);
- handleNullObject(propVal, "Property validation failed. Could not find property: '" + property + " in " + object);
- return propVal;
-
- }
-
- private void handleNullObject(Object obj, String errorMsg) {
- if (obj == null) {
- log.error(errorMsg);
- throw new IllegalArgumentException(errorMsg);
- }
- }
-
- @Override
- public void releaseAddress(String ip) {
-
- }
-
- @Override
- public boolean isValidRegion(String region) throws InvalidRegionException {
- // No regions in kubernetes cluster
- return true;
- }
-
- @Override
- public boolean isValidZone(String region, String zone) throws InvalidZoneException, InvalidRegionException {
- // No zones in kubernetes cluster
- return true;
- }
-
- @Override
- public boolean isValidHost(String zone, String host) throws InvalidHostException {
- // No zones in kubernetes cluster
- return true;
- }
-
- @Override
- public String createVolume(int sizeGB, String snapshotId) {
- throw new NotImplementedException();
- }
-
- @Override
- public String attachVolume(String instanceId, String volumeId, String deviceName) {
- throw new NotImplementedException();
- }
-
- @Override
- public void detachVolume(String instanceId, String volumeId) {
- throw new NotImplementedException();
- }
-
- @Override
- public void deleteVolume(String volumeId) {
- throw new NotImplementedException();
- }
-
- @Override
- public String getIaasDevice(String device) {
- throw new NotImplementedException();
- }
-
- @Override
- public void allocateIpAddress(String clusterId, MemberContext memberContext, Partition partition) {
-
- }
-}
http://git-wip-us.apache.org/repos/asf/stratos/blob/e195f2f1/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/iaases/MockIaas.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/iaases/MockIaas.java b/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/iaases/MockIaas.java
deleted file mode 100644
index 0c86ad2..0000000
--- a/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/iaases/MockIaas.java
+++ /dev/null
@@ -1,111 +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.apache.stratos.cloud.controller.iaases;
-
-import org.apache.stratos.cloud.controller.domain.IaasProvider;
-import org.apache.stratos.cloud.controller.domain.MemberContext;
-import org.apache.stratos.cloud.controller.domain.Partition;
-import org.apache.stratos.cloud.controller.exception.*;
-import org.apache.stratos.cloud.controller.iaases.mock.MockIaasService;
-import org.apache.stratos.cloud.controller.iaases.validators.PartitionValidator;
-
-/**
- * Mock IaaS client for invoking mock IaaS service.
- */
-public class MockIaas extends Iaas {
-
- public MockIaas(IaasProvider iaasProvider) {
- super(iaasProvider);
- }
-
- @Override
- public void initialize() {
- }
-
- @Override
- public MemberContext startInstance(MemberContext memberContext) {
- return MockIaasService.getInstance().createInstance(memberContext);
- }
-
- @Override
- public void releaseAddress(String ip) {
- MockIaasService.getInstance().releaseAddress(ip);
- }
-
- @Override
- public boolean isValidRegion(String region) throws InvalidRegionException {
- return MockIaasService.getInstance().isValidRegion(region);
- }
-
- @Override
- public boolean isValidZone(String region, String zone) throws InvalidZoneException, InvalidRegionException {
- return MockIaasService.getInstance().isValidZone(region, zone);
- }
-
- @Override
- public boolean isValidHost(String zone, String host) throws InvalidHostException {
- return MockIaasService.getInstance().isValidHost(zone, host);
- }
-
- @Override
- public PartitionValidator getPartitionValidator() {
- return MockIaasService.getInstance().getPartitionValidator();
- }
-
- @Override
- public String createVolume(int sizeGB, String snapshotId) {
- return MockIaasService.getInstance().createVolume(sizeGB, snapshotId);
- }
-
- @Override
- public String attachVolume(String instanceId, String volumeId, String deviceName) {
- return MockIaasService.getInstance().attachVolume(instanceId, volumeId, deviceName);
- }
-
- @Override
- public void detachVolume(String instanceId, String volumeId) {
- MockIaasService.getInstance().detachVolume(instanceId, volumeId);
- }
-
- @Override
- public void deleteVolume(String volumeId) {
- MockIaasService.getInstance().deleteVolume(volumeId);
- }
-
- @Override
- public String getIaasDevice(String device) {
- return MockIaasService.getInstance().getIaasDevice(device);
- }
-
- @Override
- public void allocateIpAddress(String clusterId, MemberContext memberContext, Partition partition) {
- MockIaasService.getInstance().allocateIpAddress(clusterId, memberContext, partition);
- }
-
- @Override
- public void setDynamicPayload(byte[] payload) {
- MockIaasService.getInstance().setDynamicPayload(payload);
- }
-
- @Override
- public void terminateInstance(MemberContext memberContext) throws InvalidCartridgeTypeException, InvalidMemberException {
- MockIaasService.getInstance().terminateInstance(memberContext);
- }
-}
http://git-wip-us.apache.org/repos/asf/stratos/blob/e195f2f1/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/iaases/PartitionValidator.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/iaases/PartitionValidator.java b/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/iaases/PartitionValidator.java
new file mode 100644
index 0000000..cb7765a
--- /dev/null
+++ b/components/org.apache.stratos.cloud.controller/src/main/java/org/apache/stratos/cloud/controller/iaases/PartitionValidator.java
@@ -0,0 +1,48 @@
+/*
+ * 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.apache.stratos.cloud.controller.iaases;
+
+import java.util.Properties;
+
+import org.apache.stratos.cloud.controller.domain.Partition;
+import org.apache.stratos.cloud.controller.exception.InvalidPartitionException;
+import org.apache.stratos.cloud.controller.domain.IaasProvider;
+
+/**
+ * All the IaaSes needs to write a partition validator which implements this interface.
+ */
+public interface PartitionValidator {
+
+ /**
+ * set the IaasProvider reference.
+ *
+ * @param iaasProvider {@link IaasProvider}
+ */
+ public abstract void setIaasProvider(IaasProvider iaasProvider);
+
+ /**
+ * Validate the given properties for its existent in this partition.
+ *
+ * @param partition partition.
+ * @param properties set of properties to be validated.
+ * @return cloned and modified {@link IaasProvider} which maps to the given partition.
+ * @throws InvalidPartitionException if at least one property is evaluated to be invalid.
+ */
+ public abstract IaasProvider validate(Partition partition, Properties properties) throws InvalidPartitionException;
+}