You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by sa...@apache.org on 2017/07/20 07:12:50 UTC
[cloudstack] 02/05: CLOUDSTACK-8672 : NCC Integration with
CloudStack.
This is an automated email from the ASF dual-hosted git repository.
sateesh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/cloudstack.git
commit b2f7f9abb6f710e1ec0ba9b03a645023abd0d649
Author: Priyank Parihar <pr...@citrix.com>
AuthorDate: Fri Aug 7 16:40:00 2015 +0530
CLOUDSTACK-8672 : NCC Integration with CloudStack.
---
api/src/com/cloud/agent/api/to/LoadBalancerTO.java | 18 +
.../admin/address/AcquirePodIpCmdByAdmin.java | 91 +++
.../admin/address/ReleasePodIpCmdByAdmin.java | 79 +++
.../api/response/AcquireIPAddressResponse.java | 291 ++++++++++
.../api/response/AcquirePodIpCmdResponse.java | 113 ++++
.../src/com/cloud/network/IpAddressManager.java | 44 +-
.../com/cloud/dc/dao/DataCenterIpAddressDao.java | 2 +
.../cloud/dc/dao/DataCenterIpAddressDaoImpl.java | 16 +
engine/schema/src/com/cloud/dc/dao/HostPodDao.java | 2 +
.../src/com/cloud/dc/dao/HostPodDaoImpl.java | 8 +
.../commands/DeleteServicePackageOfferingCmd.java | 95 ++++
.../commands/ListRegisteredServicePackageCmd.java | 81 +++
.../api/commands/RegisterServicePackageCmd.java | 14 +-
.../response/NetScalerServicePackageResponse.java | 6 +-
.../cloud/network/element/NetscalerElement.java | 617 ++++++++++++++-------
.../NetscalerLoadBalancerElementService.java | 46 +-
.../resource/NetScalerControlCenterResource.java | 522 +++++++----------
.../ExternalLoadBalancerDeviceManagerImpl.java | 45 +-
.../com/cloud/network/IpAddressManagerImpl.java | 575 ++++++++++---------
.../test/com/cloud/vpc/MockNetworkManagerImpl.java | 22 +
20 files changed, 1880 insertions(+), 807 deletions(-)
diff --git a/api/src/com/cloud/agent/api/to/LoadBalancerTO.java b/api/src/com/cloud/agent/api/to/LoadBalancerTO.java
index 4d5a2c0..aabff2f 100644
--- a/api/src/com/cloud/agent/api/to/LoadBalancerTO.java
+++ b/api/src/com/cloud/agent/api/to/LoadBalancerTO.java
@@ -45,6 +45,8 @@ public class LoadBalancerTO {
boolean revoked;
boolean alreadyAdded;
boolean inline;
+ String srcIpVlan;
+ Long networkId;
DestinationTO[] destinations;
private StickinessPolicyTO[] stickinessPolicies;
private HealthCheckPolicyTO[] healthCheckPolicies;
@@ -194,6 +196,22 @@ public class LoadBalancerTO {
return this.sslCert;
}
+ public String getSrcIpVlan() {
+ return srcIpVlan;
+ }
+
+ public void setSrcIpVlan(String srcIpVlan) {
+ this.srcIpVlan = srcIpVlan;
+ }
+
+ public Long getNetworkId() {
+ return networkId;
+ }
+
+ public void setNetworkId(long id) {
+ this.networkId = id;
+ }
+
public static class StickinessPolicyTO {
private String _methodName;
private List<Pair<String, String>> _paramsList;
diff --git a/api/src/org/apache/cloudstack/api/command/admin/address/AcquirePodIpCmdByAdmin.java b/api/src/org/apache/cloudstack/api/command/admin/address/AcquirePodIpCmdByAdmin.java
new file mode 100644
index 0000000..a461367
--- /dev/null
+++ b/api/src/org/apache/cloudstack/api/command/admin/address/AcquirePodIpCmdByAdmin.java
@@ -0,0 +1,91 @@
+// 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.cloudstack.api.command.admin.address;
+
+import org.apache.log4j.Logger;
+
+import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.ApiErrorCode;
+import org.apache.cloudstack.api.BaseCmd;
+import org.apache.cloudstack.api.Parameter;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.api.response.AcquirePodIpCmdResponse;
+import org.apache.cloudstack.api.response.ZoneResponse;
+import org.apache.cloudstack.context.CallContext;
+
+import com.cloud.exception.ConcurrentOperationException;
+import com.cloud.exception.ResourceAllocationException;
+import com.cloud.exception.ResourceUnavailableException;
+
+@APICommand(name = "acquirePodIpAddresses", description = "Allocates IP addresses in respective Pod of a Zone", responseObject = AcquirePodIpCmdResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
+public class AcquirePodIpCmdByAdmin extends BaseCmd {
+
+ public static final Logger s_logger = Logger.getLogger(AcquirePodIpCmdByAdmin.class.getName());
+ private static final String s_name = "acquirepodipaddress";
+
+ /////////////////////////////////////////////////////
+ //////////////// API parameters /////////////////////
+ /////////////////////////////////////////////////////
+
+ @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = true, description = "the ID of the zone in which your pod lies")
+ private Long zoneId;
+
+ @Parameter(name = ApiConstants.GUEST_CIDR_ADDRESS, type = CommandType.STRING, entityType = ZoneResponse.class, required = false, description = "CIDR for finding Pod")
+ private String cidr;
+
+ /////////////////////////////////////////////////////
+ /////////////////// Accessors ///////////////////////
+ /////////////////////////////////////////////////////
+
+ private long getZoneId() {
+ return zoneId;
+ }
+
+ private String getCidr() {
+ return cidr;
+ }
+
+ /////////////////////////////////////////////////////
+ /////////////// API Implementation///////////////////
+ /////////////////////////////////////////////////////
+
+ @Override
+ public String getCommandName() {
+ return s_name;
+ }
+
+ @Override
+ public void execute() throws ResourceUnavailableException, ResourceAllocationException, ConcurrentOperationException {
+ AcquirePodIpCmdResponse pod_ip = null;
+ pod_ip = _networkService.allocatePodIp(_accountService.getAccount(getEntityOwnerId()), getZoneId(), getCidr());
+ if (pod_ip != null) {
+ pod_ip.setResponseName(getCommandName());
+ pod_ip.setObjectName(getCommandName());
+ setResponseObject(pod_ip);
+ } else {
+ throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to assign IP address");
+ }
+ }
+
+ @Override
+ public long getEntityOwnerId() {
+ // TODO Auto-generated method stub
+ return CallContext.current().getCallingAccount().getAccountId();
+ }
+
+}
\ No newline at end of file
diff --git a/api/src/org/apache/cloudstack/api/command/admin/address/ReleasePodIpCmdByAdmin.java b/api/src/org/apache/cloudstack/api/command/admin/address/ReleasePodIpCmdByAdmin.java
new file mode 100644
index 0000000..750a85d
--- /dev/null
+++ b/api/src/org/apache/cloudstack/api/command/admin/address/ReleasePodIpCmdByAdmin.java
@@ -0,0 +1,79 @@
+//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.cloudstack.api.command.admin.address;
+
+import org.apache.log4j.Logger;
+
+import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.ApiErrorCode;
+import org.apache.cloudstack.api.BaseCmd;
+import org.apache.cloudstack.api.Parameter;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.api.command.admin.vlan.ReleasePublicIpRangeCmd;
+import org.apache.cloudstack.api.response.AcquireIPAddressResponse;
+import org.apache.cloudstack.api.response.SuccessResponse;
+
+import com.cloud.user.Account;
+
+@APICommand(name = "releasePodIpAddress", description = "Releases a Pod IP back to the Pod", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
+public class ReleasePodIpCmdByAdmin extends BaseCmd {
+ public static final Logger s_logger = Logger.getLogger(ReleasePublicIpRangeCmd.class.getName());
+
+ private static final String s_name = "releasepodipresponse";
+
+ /////////////////////////////////////////////////////
+ //////////////// API parameters /////////////////////
+ /////////////////////////////////////////////////////
+
+ @Parameter(name = ApiConstants.ID, type = CommandType.LONG, entityType = AcquireIPAddressResponse.class, required = true, description = "UUID of the Pod IP")
+ private Long id;
+
+ /////////////////////////////////////////////////////
+ /////////////////// Accessors ///////////////////////
+ /////////////////////////////////////////////////////
+
+ public long getId() {
+ return id;
+ }
+
+ /////////////////////////////////////////////////////
+ /////////////// API Implementation///////////////////
+ /////////////////////////////////////////////////////
+
+ @Override
+ public String getCommandName() {
+ return s_name;
+ }
+
+ @Override
+ public long getEntityOwnerId() {
+ return Account.ACCOUNT_ID_SYSTEM;
+ }
+
+ @Override
+ public void execute() {
+ boolean result = _networkService.releasePodIp(this);
+ if (result) {
+ SuccessResponse response = new SuccessResponse(getCommandName());
+ response.setDisplayText("IP is released sucessfully");
+ setResponseObject(response);
+ } else {
+ throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to release Pod ip ");
+ }
+ }
+}
\ No newline at end of file
diff --git a/api/src/org/apache/cloudstack/api/response/AcquireIPAddressResponse.java b/api/src/org/apache/cloudstack/api/response/AcquireIPAddressResponse.java
new file mode 100644
index 0000000..6d6a035
--- /dev/null
+++ b/api/src/org/apache/cloudstack/api/response/AcquireIPAddressResponse.java
@@ -0,0 +1,291 @@
+//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.cloudstack.api.response;
+
+import java.util.Date;
+import java.util.List;
+
+import org.apache.cloudstack.acl.RoleType;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.BaseResponse;
+import org.apache.cloudstack.api.EntityReference;
+
+import com.cloud.network.IpAddress;
+import com.cloud.serializer.Param;
+import com.google.gson.annotations.SerializedName;
+
+@EntityReference(value = IpAddress.class)
+@SuppressWarnings("unused")
+public class AcquireIPAddressResponse extends BaseResponse implements ControlledEntityResponse {
+ @SerializedName(ApiConstants.ID)
+ @Param(description = "public IP address id")
+ private String id;
+
+ @SerializedName(ApiConstants.IP_ADDRESS)
+ @Param(description = "public IP address")
+ private String ipAddress;
+
+ @SerializedName("allocated")
+ @Param(description = "date the public IP address was acquired")
+ private Date allocated;
+
+ @SerializedName(ApiConstants.ZONE_ID)
+ @Param(description = "the ID of the zone the public IP address belongs to")
+ private String zoneId;
+
+ @SerializedName(ApiConstants.ZONE_NAME)
+ @Param(description = "the name of the zone the public IP address belongs to")
+ private String zoneName;
+
+ @SerializedName("issourcenat")
+ @Param(description = "true if the IP address is a source nat address, false otherwise")
+ private Boolean sourceNat;
+
+ @SerializedName(ApiConstants.ACCOUNT)
+ @Param(description = "the account the public IP address is associated with")
+ private String accountName;
+
+ @SerializedName(ApiConstants.PROJECT_ID)
+ @Param(description = "the project id of the ipaddress")
+ private String projectId;
+
+ @SerializedName(ApiConstants.PROJECT)
+ @Param(description = "the project name of the address")
+ private String projectName;
+
+ @SerializedName(ApiConstants.DOMAIN_ID)
+ @Param(description = "the domain ID the public IP address is associated with")
+ private String domainId;
+
+ @SerializedName(ApiConstants.DOMAIN)
+ @Param(description = "the domain the public IP address is associated with")
+ private String domainName;
+
+ @SerializedName(ApiConstants.FOR_VIRTUAL_NETWORK)
+ @Param(description = "the virtual network for the IP address")
+ private Boolean forVirtualNetwork;
+
+ @SerializedName(ApiConstants.VLAN_ID)
+ @Param(description = "the ID of the VLAN associated with the IP address." + " This parameter is visible to ROOT admins only")
+ private String vlanId;
+
+ @SerializedName("vlanname")
+ @Param(description = "the VLAN associated with the IP address")
+ private String vlanName;
+
+ @SerializedName("isstaticnat")
+ @Param(description = "true if this ip is for static nat, false otherwise")
+ private Boolean staticNat;
+
+ @SerializedName(ApiConstants.IS_SYSTEM)
+ @Param(description = "true if this ip is system ip (was allocated as a part of deployVm or createLbRule)")
+ private Boolean isSystem;
+
+ @SerializedName(ApiConstants.VIRTUAL_MACHINE_ID)
+ @Param(description = "virutal machine id the ip address is assigned to (not null only for static nat Ip)")
+ private String virtualMachineId;
+
+ @SerializedName("vmipaddress")
+ @Param(description = "virutal machine (dnat) ip address (not null only for static nat Ip)")
+ private String virtualMachineIp;
+
+ @SerializedName("virtualmachinename")
+ @Param(description = "virutal machine name the ip address is assigned to (not null only for static nat Ip)")
+ private String virtualMachineName;
+
+ @SerializedName("virtualmachinedisplayname")
+ @Param(description = "virutal machine display name the ip address is assigned to (not null only for static nat Ip)")
+ private String virtualMachineDisplayName;
+
+ @SerializedName(ApiConstants.ASSOCIATED_NETWORK_ID)
+ @Param(description = "the ID of the Network associated with the IP address")
+ private String associatedNetworkId;
+
+ @SerializedName(ApiConstants.ASSOCIATED_NETWORK_NAME)
+ @Param(description = "the name of the Network associated with the IP address")
+ private String associatedNetworkName;
+
+ @SerializedName(ApiConstants.NETWORK_ID)
+ @Param(description = "the ID of the Network where ip belongs to")
+ private String networkId;
+
+ @SerializedName(ApiConstants.STATE)
+ @Param(description = "State of the ip address. Can be: Allocatin, Allocated and Releasing")
+ private String state;
+
+ @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID)
+ @Param(description = "the physical network this belongs to")
+ private String physicalNetworkId;
+
+ @SerializedName(ApiConstants.PURPOSE)
+ @Param(description = "purpose of the IP address. In Acton this value is not null for Ips with isSystem=true, and can have either StaticNat or LB value")
+ private String purpose;
+
+ @SerializedName(ApiConstants.VPC_ID)
+ @Param(description = "VPC the ip belongs to")
+ private String vpcId;
+ @SerializedName(ApiConstants.TAGS)
+ @Param(description = "the list of resource tags associated with ip address", responseObject = ResourceTagResponse.class)
+ private List<ResourceTagResponse> tags;
+
+ @SerializedName(ApiConstants.IS_PORTABLE)
+ @Param(description = "is public IP portable across the zones")
+ private Boolean isPortable;
+
+ @SerializedName(ApiConstants.FOR_DISPLAY)
+ @Param(description = "is public ip for display to the regular user", since = "4.4", authorized = {RoleType.Admin})
+ private Boolean forDisplay;
+
+ /*
+ @SerializedName(ApiConstants.JOB_ID) @Param(description="shows the current pending asynchronous job ID. This tag is not returned if no current pending jobs are acting on the volume")
+ private IdentityProxy jobId = new IdentityProxy("async_job");
+ */
+
+ public void setIpAddress(String ipAddress) {
+ this.ipAddress = ipAddress;
+ }
+
+ @Override
+ public String getObjectId() {
+ return this.getId();
+ }
+
+ public void setAllocated(Date allocated) {
+ this.allocated = allocated;
+ }
+
+ public void setZoneId(String zoneId) {
+ this.zoneId = zoneId;
+ }
+
+ public void setZoneName(String zoneName) {
+ this.zoneName = zoneName;
+ }
+
+ public void setSourceNat(Boolean sourceNat) {
+ this.sourceNat = sourceNat;
+ }
+
+ @Override
+ public void setAccountName(String accountName) {
+ this.accountName = accountName;
+ }
+
+ @Override
+ public void setDomainId(String domainId) {
+ this.domainId = domainId;
+ }
+
+ @Override
+ public void setDomainName(String domainName) {
+ this.domainName = domainName;
+ }
+
+ public void setForVirtualNetwork(Boolean forVirtualNetwork) {
+ this.forVirtualNetwork = forVirtualNetwork;
+ }
+
+ public void setVlanId(String vlanId) {
+ this.vlanId = vlanId;
+ }
+
+ public void setVlanName(String vlanName) {
+ this.vlanName = vlanName;
+ }
+
+ public void setStaticNat(Boolean staticNat) {
+ this.staticNat = staticNat;
+ }
+
+ public void setAssociatedNetworkId(String networkId) {
+ this.associatedNetworkId = networkId;
+ }
+
+ public void setNetworkId(String networkId) {
+ this.networkId = networkId;
+ }
+
+ public void setVirtualMachineId(String virtualMachineId) {
+ this.virtualMachineId = virtualMachineId;
+ }
+
+ public void setVirtualMachineIp(String virtualMachineIp) {
+ this.virtualMachineIp = virtualMachineIp;
+ }
+
+ public void setVirtualMachineName(String virtualMachineName) {
+ this.virtualMachineName = virtualMachineName;
+ }
+
+ public void setVirtualMachineDisplayName(String virtualMachineDisplayName) {
+ this.virtualMachineDisplayName = virtualMachineDisplayName;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public void setState(String state) {
+ this.state = state;
+ }
+
+ @Override
+ public void setProjectId(String projectId) {
+ this.projectId = projectId;
+ }
+
+ @Override
+ public void setProjectName(String projectName) {
+ this.projectName = projectName;
+ }
+
+ public void setPhysicalNetworkId(String physicalNetworkId) {
+ this.physicalNetworkId = physicalNetworkId;
+ }
+
+ public void setIsSystem(Boolean isSystem) {
+ this.isSystem = isSystem;
+ }
+
+ public void setPurpose(String purpose) {
+ this.purpose = purpose;
+ }
+
+ public void setVpcId(String vpcId) {
+ this.vpcId = vpcId;
+ }
+
+ public void setTags(List<ResourceTagResponse> tags) {
+ this.tags = tags;
+ }
+
+ public void setAssociatedNetworkName(String associatedNetworkName) {
+ this.associatedNetworkName = associatedNetworkName;
+ }
+
+ public void setPortable(Boolean portable) {
+ this.isPortable = portable;
+ }
+
+ public void setForDisplay(Boolean forDisplay) {
+ this.forDisplay = forDisplay;
+ }
+}
diff --git a/api/src/org/apache/cloudstack/api/response/AcquirePodIpCmdResponse.java b/api/src/org/apache/cloudstack/api/response/AcquirePodIpCmdResponse.java
new file mode 100644
index 0000000..3eece1d
--- /dev/null
+++ b/api/src/org/apache/cloudstack/api/response/AcquirePodIpCmdResponse.java
@@ -0,0 +1,113 @@
+//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.cloudstack.api.response;
+
+import com.google.gson.annotations.SerializedName;
+
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.BaseResponse;
+
+import com.cloud.serializer.Param;
+
+public class AcquirePodIpCmdResponse extends BaseResponse {
+
+ @SerializedName(ApiConstants.IP_ADDRESS)
+ @Param(description = "Allocated IP address")
+ private String ipAddress;
+
+ @SerializedName(ApiConstants.POD_ID)
+ @Param(description = "the ID of the pod the IP address belongs to")
+ private Long podId;
+
+ @SerializedName(ApiConstants.GATEWAY)
+ @Param(description = "Gateway for Pod ")
+ private String gateway;
+
+ @SerializedName(ApiConstants.CIDR)
+ @Param(description = "CIDR of the Pod")
+ private String cidrAddress;
+
+ @SerializedName(ApiConstants.NIC_ID)
+ @Param(description = "the ID of the nic")
+ private Long instanceId;
+
+ @SerializedName(ApiConstants.HOST_MAC)
+ @Param(description = "MAC address of the pod the IP")
+ private Long macAddress;
+
+ @SerializedName(ApiConstants.ID)
+ @Param(description = "the ID of the pod the IP address")
+ private long id;
+
+ public void setIpAddress(String ipAddress) {
+ this.ipAddress = ipAddress;
+ }
+
+ public void setInstanceId(Long instanceId) {
+ this.instanceId = instanceId;
+ }
+
+ public void setPodId(long podId) {
+ this.podId = podId;
+ }
+
+ public void setMacAddress(long macAddress) {
+ this.macAddress = macAddress;
+ }
+
+ public void setGateway(String gateway) {
+ this.gateway = gateway;
+ }
+
+ public void setCidrAddress(String cidrAddress) {
+ this.cidrAddress = cidrAddress;
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public Long getInstanceId() {
+ return instanceId;
+ }
+
+ public long getPodId() {
+ return podId;
+ }
+
+ public String getIpAddress() {
+ return ipAddress;
+ }
+
+ public long getMacAddress() {
+ return macAddress;
+ }
+
+ public String getCidrAddress() {
+ return cidrAddress;
+ }
+
+ public String getGateway() {
+ return gateway;
+ }
+
+ public void setId(long id) {
+ this.id = id;
+ }
+
+}
\ No newline at end of file
diff --git a/engine/components-api/src/com/cloud/network/IpAddressManager.java b/engine/components-api/src/com/cloud/network/IpAddressManager.java
index 0ab5ccc..bf97b34 100644
--- a/engine/components-api/src/com/cloud/network/IpAddressManager.java
+++ b/engine/components-api/src/com/cloud/network/IpAddressManager.java
@@ -18,7 +18,7 @@ package com.cloud.network;
import java.util.List;
-import com.cloud.utils.db.DB;
+import org.apache.cloudstack.api.response.AcquirePodIpCmdResponse;
import org.apache.cloudstack.framework.config.ConfigKey;
import com.cloud.dc.DataCenter;
@@ -34,14 +34,16 @@ import com.cloud.network.dao.IPAddressVO;
import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.StaticNat;
import com.cloud.user.Account;
+import com.cloud.utils.db.DB;
+import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.NicProfile;
import com.cloud.vm.VirtualMachineProfile;
public interface IpAddressManager {
static final String UseSystemPublicIpsCK = "use.system.public.ips";
static final ConfigKey<Boolean> UseSystemPublicIps = new ConfigKey<Boolean>("Advanced", Boolean.class, UseSystemPublicIpsCK, "true",
- "If true, when account has dedicated public ip range(s), once the ips dedicated to the account have been consumed ips will be acquired from the system pool",
- true, ConfigKey.Scope.Account);
+ "If true, when account has dedicated public ip range(s), once the ips dedicated to the account have been consumed ips will be acquired from the system pool",
+ true, ConfigKey.Scope.Account);
static final ConfigKey<Boolean> RulesContinueOnError = new ConfigKey<Boolean>("Advanced", Boolean.class, "network.rule.delete.ignoreerror", "true",
"When true, ip address delete (ipassoc) failures are ignored", true);
@@ -63,7 +65,7 @@ public interface IpAddressManager {
* @throws InsufficientAddressCapacityException
*/
PublicIp assignPublicIpAddress(long dcId, Long podId, Account owner, VlanType type, Long networkId, String requestedIp, boolean isSystem)
- throws InsufficientAddressCapacityException;
+ throws InsufficientAddressCapacityException;
/**
* Do all of the work of releasing public ip addresses. Note that if this method fails, there can be side effects.
@@ -77,7 +79,7 @@ public interface IpAddressManager {
boolean disassociatePublicIpAddress(long id, long userId, Account caller);
boolean applyRules(List<? extends FirewallRule> rules, FirewallRule.Purpose purpose, NetworkRuleApplier applier, boolean continueOnError)
- throws ResourceUnavailableException;
+ throws ResourceUnavailableException;
/**
* @throws ResourceAllocationException TODO
@@ -93,12 +95,12 @@ public interface IpAddressManager {
* @throws
*/
boolean associateIpAddressListToAccount(long userId, long accountId, long zoneId, Long vlanId, Network guestNetwork) throws InsufficientCapacityException,
- ConcurrentOperationException, ResourceUnavailableException, ResourceAllocationException;
+ ConcurrentOperationException, ResourceUnavailableException, ResourceAllocationException;
boolean applyIpAssociations(Network network, boolean continueOnError) throws ResourceUnavailableException;
boolean applyIpAssociations(Network network, boolean rulesRevoked, boolean continueOnError, List<? extends PublicIpAddress> publicIps)
- throws ResourceUnavailableException;
+ throws ResourceUnavailableException;
IPAddressVO markIpAsUnavailable(long addrId);
@@ -111,7 +113,7 @@ public interface IpAddressManager {
boolean handleSystemIpRelease(IpAddress ip);
void allocateDirectIp(NicProfile nic, DataCenter dc, VirtualMachineProfile vm, Network network, String requestedIpv4, String requestedIpv6)
- throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException;
+ throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException;
/**
* @param owner
@@ -128,23 +130,23 @@ public interface IpAddressManager {
* @param releaseOnFailure TODO
*/
IPAddressVO associateIPToGuestNetwork(long ipAddrId, long networkId, boolean releaseOnFailure) throws ResourceAllocationException, ResourceUnavailableException,
- InsufficientAddressCapacityException, ConcurrentOperationException;
+ InsufficientAddressCapacityException, ConcurrentOperationException;
IpAddress allocatePortableIp(Account ipOwner, Account caller, long dcId, Long networkId, Long vpcID) throws ConcurrentOperationException,
- ResourceAllocationException, InsufficientAddressCapacityException;
+ ResourceAllocationException, InsufficientAddressCapacityException;
boolean releasePortableIpAddress(long addrId);
IPAddressVO associatePortableIPToGuestNetwork(long ipAddrId, long networkId, boolean releaseOnFailure) throws ResourceAllocationException,
- ResourceUnavailableException, InsufficientAddressCapacityException, ConcurrentOperationException;
+ ResourceUnavailableException, InsufficientAddressCapacityException, ConcurrentOperationException;
IPAddressVO disassociatePortableIPToGuestNetwork(long ipAddrId, long networkId) throws ResourceAllocationException, ResourceUnavailableException,
- InsufficientAddressCapacityException, ConcurrentOperationException;
+ InsufficientAddressCapacityException, ConcurrentOperationException;
boolean isPortableIpTransferableFromNetwork(long ipAddrId, long networkId);
void transferPortableIP(long ipAddrId, long currentNetworkId, long newNetworkId) throws ResourceAllocationException, ResourceUnavailableException,
- InsufficientAddressCapacityException, ConcurrentOperationException;;
+ InsufficientAddressCapacityException, ConcurrentOperationException;;
/**
* @param addr
@@ -162,17 +164,18 @@ public interface IpAddressManager {
* @throws InsufficientAddressCapacityException
*/
PublicIp assignDedicateIpAddress(Account owner, Long guestNtwkId, Long vpcId, long dcId, boolean isSourceNat) throws ConcurrentOperationException,
- InsufficientAddressCapacityException;
+ InsufficientAddressCapacityException;
IpAddress allocateIp(Account ipOwner, boolean isSystem, Account caller, long callerId, DataCenter zone, Boolean displayIp) throws ConcurrentOperationException,
- ResourceAllocationException, InsufficientAddressCapacityException;
+ ResourceAllocationException, InsufficientAddressCapacityException;
+
PublicIp assignPublicIpAddressFromVlans(long dcId, Long podId, Account owner, VlanType type, List<Long> vlanDbIds, Long networkId, String requestedIp,
- boolean isSystem) throws InsufficientAddressCapacityException;
+ boolean isSystem) throws InsufficientAddressCapacityException;
@DB
void allocateNicValues(NicProfile nic, DataCenter dc, VirtualMachineProfile vm, Network network, String requestedIpv4,
- String requestedIpv6) throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException;
+ String requestedIpv6) throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException;
int getRuleCountForIp(Long addressId, FirewallRule.Purpose purpose, FirewallRule.State state);
@@ -180,4 +183,11 @@ public interface IpAddressManager {
String allocatePublicIpForGuestNic(Network network, Long podId, Account ipOwner, String requestedIp) throws InsufficientAddressCapacityException;
+ public AcquirePodIpCmdResponse allocatePodIp(Long zoneId, String cidr) throws ConcurrentOperationException,
+ ResourceAllocationException;
+
+ public void releasePodIp(Long id) throws CloudRuntimeException;
+
+
}
+
diff --git a/engine/schema/src/com/cloud/dc/dao/DataCenterIpAddressDao.java b/engine/schema/src/com/cloud/dc/dao/DataCenterIpAddressDao.java
index e5843b6..3b988da 100644
--- a/engine/schema/src/com/cloud/dc/dao/DataCenterIpAddressDao.java
+++ b/engine/schema/src/com/cloud/dc/dao/DataCenterIpAddressDao.java
@@ -47,4 +47,6 @@ public interface DataCenterIpAddressDao extends GenericDao<DataCenterIpAddressVO
boolean deleteIpAddressByPod(long podId);
+ void releasePodIpAddress(long id);
+
}
diff --git a/engine/schema/src/com/cloud/dc/dao/DataCenterIpAddressDaoImpl.java b/engine/schema/src/com/cloud/dc/dao/DataCenterIpAddressDaoImpl.java
index ae8ae0c..1feb6ad 100644
--- a/engine/schema/src/com/cloud/dc/dao/DataCenterIpAddressDaoImpl.java
+++ b/engine/schema/src/com/cloud/dc/dao/DataCenterIpAddressDaoImpl.java
@@ -177,6 +177,22 @@ public class DataCenterIpAddressDaoImpl extends GenericDaoBase<DataCenterIpAddre
}
@Override
+ public void releasePodIpAddress(long id) {
+ if (s_logger.isDebugEnabled()) {
+ s_logger.debug("Releasing ip address for ID=" + id);
+ }
+// SearchCriteria<DataCenterIpAddressVO> sc = AllFieldsSearch.create();
+// sc.setParameters("id", id);
+
+ DataCenterIpAddressVO vo = this.findById(id);
+ vo.setTakenAt(null);
+ vo.setInstanceId(null);
+ vo.setReservationId(null);
+ persist(vo);
+ //update(vo, sc);
+ }
+
+ @Override
public void releaseIpAddress(long nicId) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Releasing ip address for instance=" + nicId);
diff --git a/engine/schema/src/com/cloud/dc/dao/HostPodDao.java b/engine/schema/src/com/cloud/dc/dao/HostPodDao.java
index 1a000d8..b2e9b89 100644
--- a/engine/schema/src/com/cloud/dc/dao/HostPodDao.java
+++ b/engine/schema/src/com/cloud/dc/dao/HostPodDao.java
@@ -32,4 +32,6 @@ public interface HostPodDao extends GenericDao<HostPodVO, Long> {
public List<Long> listDisabledPods(long zoneId);
public List<Long> listAllPods(Long zoneId);
+
+ public List<HostPodVO> listAllPodsByCidr(long zoneId, String cidr);
}
diff --git a/engine/schema/src/com/cloud/dc/dao/HostPodDaoImpl.java b/engine/schema/src/com/cloud/dc/dao/HostPodDaoImpl.java
index 1c83b3a..3fbeb58 100644
--- a/engine/schema/src/com/cloud/dc/dao/HostPodDaoImpl.java
+++ b/engine/schema/src/com/cloud/dc/dao/HostPodDaoImpl.java
@@ -137,4 +137,12 @@ public class HostPodDaoImpl extends GenericDaoBase<HostPodVO, Long> implements H
}
return customSearch(sc, null);
}
+ @Override
+ public List<HostPodVO> listAllPodsByCidr(long zoneId, String cidr) {
+ SearchCriteria<HostPodVO> sc = DataCenterAndNameSearch.create();
+ sc.setParameters("dataCenterId", zoneId);
+ sc.setParameters("cidr_address", cidr);
+ return listBy(sc);
+ }
+
}
diff --git a/plugins/network-elements/netscaler/src/com/cloud/api/commands/DeleteServicePackageOfferingCmd.java b/plugins/network-elements/netscaler/src/com/cloud/api/commands/DeleteServicePackageOfferingCmd.java
new file mode 100644
index 0000000..1fbd899
--- /dev/null
+++ b/plugins/network-elements/netscaler/src/com/cloud/api/commands/DeleteServicePackageOfferingCmd.java
@@ -0,0 +1,95 @@
+// 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 com.cloud.api.commands;
+
+import javax.inject.Inject;
+import javax.persistence.EntityExistsException;
+
+import org.apache.log4j.Logger;
+
+import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.ApiErrorCode;
+import org.apache.cloudstack.api.BaseCmd;
+import org.apache.cloudstack.api.Parameter;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.context.CallContext;
+
+import org.apache.cloudstack.api.response.SuccessResponse;
+
+import com.cloud.api.response.NetScalerServicePackageResponse;
+import com.cloud.exception.ConcurrentOperationException;
+//import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.network.element.NetscalerLoadBalancerElementService;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+@APICommand(name = "deleteServicePackageOffering", responseObject = SuccessResponse.class, description = "Delete Service Package Offering")
+public class DeleteServicePackageOfferingCmd extends BaseCmd {
+
+ public static final Logger s_logger = Logger.getLogger(DeleteServicePackageOfferingCmd.class.getName());
+ private static final String s_name = "deleteServicePackageOffering";
+ @Inject
+ NetscalerLoadBalancerElementService _netsclarLbService;
+
+ /////////////////////////////////////////////////////
+ //////////////// API parameters /////////////////////
+ /////////////////////////////////////////////////////
+
+ @Parameter(name = ApiConstants.ID, type = CommandType.STRING, entityType = NetScalerServicePackageResponse.class, required = true, description = "the service offering ID")
+ private String ID;
+
+ @Override
+ public void execute() throws ServerApiException, ConcurrentOperationException, EntityExistsException {
+ SuccessResponse response = new SuccessResponse();
+ try {
+ boolean result = _netsclarLbService.deleteServicePackageOffering(this);
+
+ if (response != null && result) {
+ response.setDisplayText("Deleted Successfully");
+ response.setSuccess(result);
+ response.setResponseName(getCommandName());
+ this.setResponseObject(response);
+ }
+ } catch (CloudRuntimeException runtimeExcp) {
+ response.setDisplayText(runtimeExcp.getMessage());
+ response.setSuccess(false);
+ response.setResponseName(getCommandName());
+ this.setResponseObject(response);
+ return;
+ } catch (Exception e) {
+ throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete Service Package due to internal error.");
+ }
+ }
+
+ public String getId() {
+ return ID;
+ }
+
+ @Override
+ public String getCommandName() {
+ // TODO Auto-generated method stub
+ return s_name;
+ }
+
+ @Override
+ public long getEntityOwnerId() {
+ // TODO Auto-generated method stub
+ return CallContext.current().getCallingAccount().getId();
+ }
+
+}
diff --git a/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListRegisteredServicePackageCmd.java b/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListRegisteredServicePackageCmd.java
new file mode 100644
index 0000000..6838833
--- /dev/null
+++ b/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListRegisteredServicePackageCmd.java
@@ -0,0 +1,81 @@
+// 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 com.cloud.api.commands;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.inject.Inject;
+
+import org.apache.log4j.Logger;
+
+import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiErrorCode;
+import org.apache.cloudstack.api.BaseListCmd;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.api.response.ListResponse;
+
+import com.cloud.api.response.NetScalerServicePackageResponse;
+import com.cloud.exception.ConcurrentOperationException;
+import com.cloud.exception.InsufficientCapacityException;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.exception.ResourceAllocationException;
+import com.cloud.exception.ResourceUnavailableException;
+import com.cloud.network.element.NetscalerLoadBalancerElementService;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.network.NetScalerServicePackageVO;
+
+@APICommand(name = "listRegisteredServicePackages", responseObject = NetScalerServicePackageResponse.class, description = "lists registered service packages", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
+public class ListRegisteredServicePackageCmd extends BaseListCmd {
+
+ public static final Logger s_logger = Logger.getLogger(ListRegisteredServicePackageCmd.class.getName());
+ private static final String s_name = "listregisteredservicepackage";
+ @Inject
+ NetscalerLoadBalancerElementService _netsclarLbService;
+
+ @Override
+ public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException,
+ ConcurrentOperationException, ResourceAllocationException {
+ try {
+ List<NetScalerServicePackageVO> lrsPackages = _netsclarLbService.listRegisteredServicePackages(this);
+ ListResponse<NetScalerServicePackageResponse> response = new ListResponse<NetScalerServicePackageResponse>();
+ List<NetScalerServicePackageResponse> lbDevicesResponse = new ArrayList<NetScalerServicePackageResponse>();
+
+ if (lrsPackages != null && !lrsPackages.isEmpty()) {
+ for (NetScalerServicePackageVO lrsPackageVO : lrsPackages) {
+ NetScalerServicePackageResponse lbdeviceResponse = _netsclarLbService
+ .createRegisteredServicePackageResponse(lrsPackageVO);
+ lbDevicesResponse.add(lbdeviceResponse);
+ }
+ }
+
+ response.setResponses(lbDevicesResponse);
+ response.setResponseName(getCommandName());
+ this.setResponseObject(response);
+ } catch (InvalidParameterValueException invalidParamExcp) {
+ throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage());
+ } catch (CloudRuntimeException runtimeExcp) {
+ throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage());
+ }
+ }
+
+ @Override
+ public String getCommandName() {
+ return s_name;
+ }
+}
diff --git a/plugins/network-elements/netscaler/src/com/cloud/api/commands/RegisterServicePackageCmd.java b/plugins/network-elements/netscaler/src/com/cloud/api/commands/RegisterServicePackageCmd.java
index 52e8e5a..67c1c57 100644
--- a/plugins/network-elements/netscaler/src/com/cloud/api/commands/RegisterServicePackageCmd.java
+++ b/plugins/network-elements/netscaler/src/com/cloud/api/commands/RegisterServicePackageCmd.java
@@ -33,8 +33,7 @@ import com.cloud.exception.InvalidParameterValueException;
import com.cloud.network.element.NetscalerLoadBalancerElementService;
import com.cloud.utils.exception.CloudRuntimeException;
-@APICommand(name = "registerNetscalerServicePackage", responseObject = NetScalerServicePackageResponse.class,
- description = "Registers NCC Service Package")
+@APICommand(name = "registerNetscalerServicePackage", responseObject = NetScalerServicePackageResponse.class, description = "Registers NCC Service Package")
public class RegisterServicePackageCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(RegisterServicePackageCmd.class.getName());
@@ -50,10 +49,10 @@ public class RegisterServicePackageCmd extends BaseCmd {
@Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "Name of the service Package.")
private String spName;
- @Parameter(name = ApiConstants.DESCRIPTION , type = CommandType.STRING, required = true, description = "Description of Service Package")
+ @Parameter(name = ApiConstants.DESCRIPTION, type = CommandType.STRING, required = true, description = "Description of Service Package")
private String description;
-/* @Override
+ /* @Override
public String getEventType() {
return EventTypes.EVENT_NETSCALER_SERVICEPACKAGE_ADD;
}
@@ -62,12 +61,11 @@ public class RegisterServicePackageCmd extends BaseCmd {
public String getEventDescription() {
return "Adding Netscaler Service Package";
}
-*/
+ */
@Override
public void execute() throws ServerApiException, ConcurrentOperationException, EntityExistsException {
try {
- NetScalerServicePackageResponse response = _netsclarLbService.registerNetscalerServicePackage(this);
-
+ NetScalerServicePackageResponse response = _netsclarLbService.registerNetscalerServicePackage(this);
if (response != null) {
//NetScalerServicePackageResponse response = _netsclarLbService.createNetscalerServicePackageResponse(servicePackageVO);
response.setObjectName("netscalerservicepackage");
@@ -81,7 +79,7 @@ public class RegisterServicePackageCmd extends BaseCmd {
} catch (CloudRuntimeException runtimeExcp) {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage());
} catch (EntityExistsException runtimeExcp) {
- throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR , "Service Pacakge Already Exists with Name " + getSpName() );
+ throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Service Pacakge Already Exists with Name " + getSpName());
}
}
diff --git a/plugins/network-elements/netscaler/src/com/cloud/api/response/NetScalerServicePackageResponse.java b/plugins/network-elements/netscaler/src/com/cloud/api/response/NetScalerServicePackageResponse.java
index 4950875..ccd814b 100644
--- a/plugins/network-elements/netscaler/src/com/cloud/api/response/NetScalerServicePackageResponse.java
+++ b/plugins/network-elements/netscaler/src/com/cloud/api/response/NetScalerServicePackageResponse.java
@@ -24,6 +24,7 @@ import com.cloud.network.NetScalerServicePackageVO;
import com.cloud.serializer.Param;
public class NetScalerServicePackageResponse extends BaseResponse {
+
@SerializedName(ApiConstants.ID)
@Param(description = "Service Package UUID")
private String id;
@@ -36,7 +37,8 @@ public class NetScalerServicePackageResponse extends BaseResponse {
@Param(description = "Description of Service Package")
private String description;
- public NetScalerServicePackageResponse() {}
+ public NetScalerServicePackageResponse() {
+ }
public NetScalerServicePackageResponse(NetScalerServicePackageVO servicePackage) {
this.id = servicePackage.getUuid();
@@ -68,4 +70,4 @@ public class NetScalerServicePackageResponse extends BaseResponse {
this.description = description;
}
-}
+}
\ No newline at end of file
diff --git a/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java b/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java
index 60baa89..6f5a9a1 100644
--- a/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java
+++ b/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java
@@ -35,6 +35,10 @@ import org.json.JSONObject;
import com.google.gson.Gson;
import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.ApiErrorCode;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.api.command.admin.address.AcquirePodIpCmdByAdmin;
+import org.apache.cloudstack.api.command.admin.address.ReleasePodIpCmdByAdmin;
import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice;
@@ -54,12 +58,17 @@ import com.cloud.agent.api.to.StaticNatRuleTO;
import com.cloud.api.ApiDBUtils;
import com.cloud.api.commands.AddNetscalerLoadBalancerCmd;
import com.cloud.api.commands.ConfigureNetscalerLoadBalancerCmd;
+import com.cloud.api.commands.DeleteNetscalerControlCenterCmd;
import com.cloud.api.commands.DeleteNetscalerLoadBalancerCmd;
+import com.cloud.api.commands.DeleteServicePackageOfferingCmd;
+import com.cloud.api.commands.ListNetscalerControlCenterCmd;
import com.cloud.api.commands.ListNetscalerLoadBalancerNetworksCmd;
import com.cloud.api.commands.ListNetscalerLoadBalancersCmd;
+import com.cloud.api.commands.ListRegisteredServicePackageCmd;
import com.cloud.api.commands.RegisterNetscalerControlCenterCmd;
import com.cloud.api.commands.RegisterServicePackageCmd;
import com.cloud.api.response.NetScalerServicePackageResponse;
+import com.cloud.api.response.NetscalerControlCenterResponse;
import com.cloud.api.response.NetscalerLoadBalancerResponse;
import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager;
@@ -112,6 +121,7 @@ import com.cloud.network.dao.NetworkServiceMapDao;
import com.cloud.network.dao.NetworkVO;
import com.cloud.network.dao.PhysicalNetworkDao;
import com.cloud.network.dao.PhysicalNetworkVO;
+//import com.cloud.network.dao.RegisteredServicePackageVO;
import com.cloud.network.lb.LoadBalancingRule;
import com.cloud.network.lb.LoadBalancingRule.LbDestination;
import com.cloud.network.resource.NetScalerControlCenterResource;
@@ -124,9 +134,11 @@ import com.cloud.network.rules.StaticNat;
import com.cloud.offering.NetworkOffering;
import com.cloud.offerings.dao.NetworkOfferingDao;
import com.cloud.resource.ResourceManager;
+import com.cloud.resource.ResourceState;
import com.cloud.resource.ServerResource;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.db.DB;
+import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.TransactionCallback;
import com.cloud.utils.db.TransactionCallbackNoReturn;
@@ -160,6 +172,12 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
DataCenterDao _dcDao;
@Inject
ExternalLoadBalancerDeviceDao _lbDeviceDao;
+
+ // @Inject
+ // NetScalerServicePackageDao _lrsPackagesDao;
+
+ @Inject
+ NetScalerControlCenterDao _netscalerControlCenterDao;
@Inject
NetworkExternalLoadBalancerDao _networkLBDao;
@Inject
@@ -179,8 +197,6 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
@Inject
NetScalerServicePackageDao _netscalerServicePackageDao;
@Inject
- NetScalerControlCenterDao _netscalerControlCenterDao;
- @Inject
ResourceManager _resourceMgr;
@Inject
HostDetailsDao _hostDetailDao;
@@ -195,73 +211,83 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
DataCenter zone = _dcDao.findById(config.getDataCenterId());
// Create a NCC Resource on Demand for the zone.
- boolean handleInAdvanceZone =
- (zone.getNetworkType() == NetworkType.Advanced && (config.getGuestType() == Network.GuestType.Isolated || config.getGuestType() == Network.GuestType.Shared) && config.getTrafficType() == TrafficType.Guest);
- boolean handleInBasicZone =
- (zone.getNetworkType() == NetworkType.Basic && config.getGuestType() == Network.GuestType.Shared && config.getTrafficType() == TrafficType.Guest);
+ boolean handleInAdvanceZone = (zone.getNetworkType() == NetworkType.Advanced
+ && (config.getGuestType() == Network.GuestType.Isolated
+ || config.getGuestType() == Network.GuestType.Shared)
+ && config.getTrafficType() == TrafficType.Guest);
+ boolean handleInBasicZone = (zone.getNetworkType() == NetworkType.Basic
+ && config.getGuestType() == Network.GuestType.Shared && config.getTrafficType() == TrafficType.Guest);
if (!(handleInAdvanceZone || handleInBasicZone)) {
- s_logger.trace("Not handling network with Type " + config.getGuestType() + " and traffic type " + config.getTrafficType() + " in zone of type " +
- zone.getNetworkType());
+ s_logger.trace("Not handling network with Type " + config.getGuestType() + " and traffic type "
+ + config.getTrafficType() + " in zone of type " + zone.getNetworkType());
return false;
}
- return (_networkManager.isProviderForNetwork(getProvider(), config.getId()) && _ntwkSrvcDao.canProviderSupportServiceInNetwork(config.getId(), service,
- Network.Provider.Netscaler));
+ return (_networkManager.isProviderForNetwork(getProvider(), config.getId()) && _ntwkSrvcDao
+ .canProviderSupportServiceInNetwork(config.getId(), service, Network.Provider.Netscaler));
}
private boolean isBasicZoneNetwok(Network config) {
DataCenter zone = _dcDao.findById(config.getDataCenterId());
- return (zone.getNetworkType() == NetworkType.Basic && config.getGuestType() == Network.GuestType.Shared && config.getTrafficType() == TrafficType.Guest);
+ return (zone.getNetworkType() == NetworkType.Basic && config.getGuestType() == Network.GuestType.Shared
+ && config.getTrafficType() == TrafficType.Guest);
}
@Override
- public boolean implement(Network guestConfig, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException,
- ConcurrentOperationException, InsufficientNetworkCapacityException {
+ public boolean implement(Network guestConfig, NetworkOffering offering, DeployDestination dest,
+ ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException,
+ InsufficientNetworkCapacityException {
if (!canHandle(guestConfig, Service.Lb)) {
return false;
}
- if (_ntwkSrvcDao.canProviderSupportServiceInNetwork(guestConfig.getId(), Service.StaticNat, Network.Provider.Netscaler) && !isBasicZoneNetwok(guestConfig)) {
- s_logger.error("NetScaler provider can not be Static Nat service provider for the network " + guestConfig.getGuestType() + " and traffic type " +
- guestConfig.getTrafficType());
+ if (_ntwkSrvcDao.canProviderSupportServiceInNetwork(guestConfig.getId(), Service.StaticNat,
+ Network.Provider.Netscaler) && !isBasicZoneNetwok(guestConfig)) {
+ s_logger.error("NetScaler provider can not be Static Nat service provider for the network "
+ + guestConfig.getGuestType() + " and traffic type " + guestConfig.getTrafficType());
return false;
}
try {
- if(offering.getServicePackage() == null) {
+ if (offering.getServicePackage() == null) {
return manageGuestNetworkWithExternalLoadBalancer(true, guestConfig);
} else {
- // if the network offering has service package implement it with Netscaler Control Center
+ // if the network offering has service package implement it with
+ // Netscaler Control Center
manageGuestNetworkWithNetscalerControlCenter(true, guestConfig, offering);
return true;
}
} catch (InsufficientCapacityException capacityException) {
- throw new ResourceUnavailableException("There are no NetScaler load balancer devices with the free capacity for implementing this network", DataCenter.class,
- guestConfig.getDataCenterId());
+ throw new ResourceUnavailableException(
+ "There are no NetScaler load balancer devices with the free capacity for implementing this network",
+ DataCenter.class, guestConfig.getDataCenterId());
} catch (ConfigurationException e) {
- throw new ResourceUnavailableException("There are no NetScaler load balancer devices with the free capacity for implementing this network : " + e.getMessage(), DataCenter.class,
- guestConfig.getDataCenterId());
+ throw new ResourceUnavailableException(
+ "There are no NetScaler load balancer devices with the free capacity for implementing this network : "
+ + e.getMessage(),
+ DataCenter.class, guestConfig.getDataCenterId());
}
}
-
+ @Override
public HostVO getNetScalerControlCenterForNetwork(Network guestConfig) {
long zoneId = guestConfig.getDataCenterId();
return _hostDao.findByTypeNameAndZoneId(zoneId, "NetscalerControlCenter", Type.NetScalerControlCenter);
}
public HostVO allocateNCCResourceForNetwork(Network guestConfig) throws ConfigurationException {
+
Map<String, String> _configs;
- List<NetScalerControlCenterVO> ncc = _netscalerControlCenterDao.listAll();
+ List<NetScalerControlCenterVO> ncc = _netscalerControlCenterDao.listAll();
HostVO hostVO = null;
- Map<String, Object> params ;
- if(ncc.size() > 0) {
+ Map<String, Object> params;
+ if (ncc.size() > 0) {
NetScalerControlCenterVO nccVO = ncc.get(0);
String ipAddress = nccVO.getNccip();
Map hostDetails = new HashMap<String, String>();
- String hostName = "NetscalerControlCenter";
+ String hostName = "NetscalerControlCenter";
hostDetails.put("name", hostName);
hostDetails.put("guid", UUID.randomUUID().toString());
hostDetails.put("zoneId", Long.toString(guestConfig.getDataCenterId()));
@@ -278,7 +304,9 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
return hostVO;
}
- public boolean manageGuestNetworkWithNetscalerControlCenter(boolean add, Network guestConfig, NetworkOffering offering) throws ResourceUnavailableException, InsufficientCapacityException, ConfigurationException {
+ public boolean manageGuestNetworkWithNetscalerControlCenter(boolean add, Network guestConfig,
+ NetworkOffering offering)
+ throws ResourceUnavailableException, InsufficientCapacityException, ConfigurationException {
if (guestConfig.getTrafficType() != TrafficType.Guest) {
s_logger.trace("External load balancer can only be used for guest networks.");
@@ -291,19 +319,23 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
if (add) {
HostVO lbDeviceVO = null;
- // on restart network, device could have been allocated already, skip allocation if a device is assigned
+ // on restart network, device could have been allocated already,
+ // skip allocation if a device is assigned
lbDeviceVO = getNetScalerControlCenterForNetwork(guestConfig);
if (lbDeviceVO == null) {
// allocate a load balancer device for the network
lbDeviceVO = allocateNCCResourceForNetwork(guestConfig);
if (lbDeviceVO == null) {
- String msg = "failed to allocate Netscaler ControlCenter Resource for the zone in the network " + guestConfig.getId();
+ String msg = "failed to allocate Netscaler ControlCenter Resource for the zone in the network "
+ + guestConfig.getId();
s_logger.error(msg);
- throw new InsufficientNetworkCapacityException(msg, DataCenter.class, guestConfig.getDataCenterId());
+ throw new InsufficientNetworkCapacityException(msg, DataCenter.class,
+ guestConfig.getDataCenterId());
}
}
netscalerControlCenter = _hostDao.findById(lbDeviceVO.getId());
- s_logger.debug("Allocated Netscaler Control Center device:" + lbDeviceVO.getId() + " for the network: " + guestConfig.getId());
+ s_logger.debug("Allocated Netscaler Control Center device:" + lbDeviceVO.getId() + " for the network: "
+ + guestConfig.getId());
} else {
// find the load balancer device allocated for the network
@@ -311,13 +343,14 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
// on restart network, device could have been allocated already, skip allocation if a device is assigned
lbDeviceVO = getNetScalerControlCenterForNetwork(guestConfig);
if (lbDeviceVO == null) {
- s_logger.warn("Network shutdwon requested on external load balancer element, which did not implement the network."
- + " Either network implement failed half way through or already network shutdown is completed. So just returning.");
+ s_logger.warn(
+ "Network shutdwon requested on external load balancer element, which did not implement the network."
+ + " Either network implement failed half way through or already network shutdown is completed. So just returning.");
return true;
}
netscalerControlCenter = _hostDao.findById(lbDeviceVO.getId());
- assert (netscalerControlCenter != null) : "There is no device assigned to this network how did shutdown network ended up here??";
+ assert(netscalerControlCenter != null) : "There is no device assigned to this network how did shutdown network ended up here??";
}
JSONObject networkDetails = new JSONObject();
JSONObject networkPayload = new JSONObject();
@@ -339,7 +372,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
throw new InsufficientNetworkCapacityException(msg, Network.class, guestConfig.getId());
}
networkDetails.put("snip", selfIp);
- //TODO region is hardcoded make it dynamic
+ // TODO region is hardcoded make it dynamic
networkDetails.put("region_id", 1);
networkDetails.put("name", guestConfig.getName());
networkPayload.put("network", networkDetails);
@@ -350,35 +383,33 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
NetScalerImplementNetworkCommand cmd = new NetScalerImplementNetworkCommand(zoneId, netscalerControlCenter.getId(), networkPayload.toString());
Answer answer = _agentMgr.easySend(netscalerControlCenter.getId(), cmd);
- if(add) {
- //TODO After getting the answer check with the job id and do poll on the job and then save the selfip or acquired guest ip to the Nics table
- if(answer != null ) {
- if (add) {
- // Insert a new NIC for this guest network to reserve the self IP
- _networkService.savePlaceholderNic(guestConfig, selfIp, null, null);
- }
- }
- } else {
- // release the self-ip obtained from guest network
- /*Nic selfipNic = getPlaceholderNic(guestConfig);
- _nicDao.remove(selfipNic.getId());*/
- // release the load balancer allocated for the network
- return true;
- //write code to remove the self nic or the clean up work
- }
+ if (add) {
+ //TODO After getting the answer check with the job id and do poll on the job and then save the selfip or acquired guest ip to the Nics table
+ if (answer != null) {
+ if (add) {
+ // Insert a new NIC for this guest network to reserve the self IP
+ _networkService.savePlaceholderNic(guestConfig, selfIp, null, null);
+ }
+ }
+ } else {
+ // release the self-ip obtained from guest network
+ /*Nic selfipNic = getPlaceholderNic(guestConfig);
+ _nicDao.remove(selfipNic.getId());*/
+ // release the load balancer allocated for the network
+ return true;
+ //write code to remove the self nic or the clean up work
+ }
// Send a command to the external load balancer to implement or shutdown the guest network
-/* long guestVlanTag = Long.parseLong(BroadcastDomainType.getValue(guestConfig.getBroadcastUri()));
+ /* long guestVlanTag = Long.parseLong(BroadcastDomainType.getValue(guestConfig.getBroadcastUri()));
String selfIp = null;
String guestVlanNetmask = NetUtils.cidr2Netmask(guestConfig.getCidr());
Integer networkRate = _networkModel.getNetworkRate(guestConfig.getId(), null);
-
if (add) {
// on restart network, network could have already been implemented. If already implemented then return
Nic selfipNic = getPlaceholderNic(guestConfig);
if (selfipNic != null) {
return true;
}
-
// Acquire a self-ip address from the guest network IP address range
selfIp = _ipAddrMgr.acquireGuestIpAddress(guestConfig, null);
if (selfIp == null) {
@@ -396,17 +427,17 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
}
selfIp = selfipNic.getIp4Address();
}
-*/
+ */
// It's a hack, using isOneToOneNat field for indicate if it's inline or not
-/* boolean inline = _networkMgr.isNetworkInlineMode(guestConfig);
+ /* boolean inline = _networkMgr.isNetworkInlineMode(guestConfig);
IpAddressTO ip =
new IpAddressTO(guestConfig.getAccountId(), null, add, false, true, String.valueOf(guestVlanTag), selfIp, guestVlanNetmask, null, networkRate, inline);
IpAddressTO[] ips = new IpAddressTO[1];
ips[0] = ip;
IpAssocCommand cmd = new IpAssocCommand(ips);
Answer answer = _agentMgr.easySend(netscalerControlCenter.getId(), cmd);
-*/
-/* if (answer == null || !answer.getResult()) {
+ */
+ /* if (answer == null || !answer.getResult()) {
String action = add ? "implement" : "shutdown";
String answerDetails = (answer != null) ? answer.getDetails() : null;
answerDetails = (answerDetails != null) ? " due to " + answerDetails : "";
@@ -414,36 +445,95 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
s_logger.error(msg);
throw new ResourceUnavailableException(msg, Network.class, guestConfig.getId());
}
-
+ =======
+ NetScalerImplementNetworkCommand cmd = new NetScalerImplementNetworkCommand(zoneId,
+ netscalerControlCenter.getId(), networkPayload.toString());
+ >>>>>>> Stashed changes
if (add) {
- // Insert a new NIC for this guest network to reserve the self IP
- _networkMgr.savePlaceholderNic(guestConfig, selfIp, null, null);
- } else {
- // release the self-ip obtained from guest network
- Nic selfipNic = getPlaceholderNic(guestConfig);
- _nicDao.remove(selfipNic.getId());
-
- // release the load balancer allocated for the network
- boolean releasedLB = freeLoadBalancerForNetwork(guestConfig);
- if (!releasedLB) {
- String msg = "Failed to release the external load balancer used for the network: " + guestConfig.getId();
- s_logger.error(msg);
+ Answer answer = _agentMgr.easySend(netscalerControlCenter.getId(), cmd);
+ // TODO After getting the answer check with the job id and do poll
+ // on the job and then save the selfip or acquired guest ip to the
+ // Nics table
+ if (answer != null) {
+ if (add) {
+ // Insert a new NIC for this guest network to reserve the
+ // self IP
+ _networkService.savePlaceholderNic(guestConfig, selfIp, null, null);
+ }
}
}
-
- if (s_logger.isDebugEnabled()) {
- Account account = _accountDao.findByIdIncludingRemoved(guestConfig.getAccountId());
- String action = add ? "implemented" : "shut down";
- s_logger.debug("External load balancer has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() +
- ") with VLAN tag " + guestVlanTag);
- }*/
+ // Send a command to the external load balancer to implement or shutdown
+ // the guest network
+ /*
+ * long guestVlanTag =
+ * Long.parseLong(BroadcastDomainType.getValue(guestConfig.
+ * getBroadcastUri())); String selfIp = null; String guestVlanNetmask =
+ * NetUtils.cidr2Netmask(guestConfig.getCidr()); Integer networkRate =
+ * _networkModel.getNetworkRate(guestConfig.getId(), null); if (add) {
+ * // on restart network, network could have already been implemented.
+ * If already implemented then return Nic selfipNic =
+ * getPlaceholderNic(guestConfig); if (selfipNic != null) { return true;
+ * } // Acquire a self-ip address from the guest network IP address
+ * range selfIp = _ipAddrMgr.acquireGuestIpAddress(guestConfig, null);
+ * if (selfIp == null) { String msg =
+ * "failed to acquire guest IP address so not implementing the network on the external load balancer "
+ * ; s_logger.error(msg); throw new
+ * InsufficientNetworkCapacityException(msg, Network.class,
+ * guestConfig.getId()); } } else { // get the self-ip used by the load
+ * balancer Nic selfipNic = getPlaceholderNic(guestConfig); if
+ * (selfipNic == null) { s_logger.warn(
+ * "Network shutdwon requested on external load balancer element, which did not implement the network."
+ * +
+ * " Either network implement failed half way through or already network shutdown is completed. So just returning."
+ * ); return true; } selfIp = selfipNic.getIp4Address(); }
+ */
+ // It's a hack, using isOneToOneNat field for indicate if it's inline or
+ // not
+ /*
+ * boolean inline = _networkMgr.isNetworkInlineMode(guestConfig);
+ * IpAddressTO ip = new IpAddressTO(guestConfig.getAccountId(), null,
+ * add, false, true, String.valueOf(guestVlanTag), selfIp,
+ * guestVlanNetmask, null, networkRate, inline); IpAddressTO[] ips = new
+ * IpAddressTO[1]; ips[0] = ip; IpAssocCommand cmd = new
+ * IpAssocCommand(ips); Answer answer =
+ * _agentMgr.easySend(netscalerControlCenter.getId(), cmd);
+ */
+ /*
+ * if (answer == null || !answer.getResult()) { String action = add ?
+ * "implement" : "shutdown"; String answerDetails = (answer != null) ?
+ * answer.getDetails() : null; answerDetails = (answerDetails != null) ?
+ * " due to " + answerDetails : ""; String msg =
+ * "External load balancer was unable to " + action +
+ * " the guest network on the external load balancer in zone " +
+ * zone.getName() + answerDetails; s_logger.error(msg); throw new
+ * ResourceUnavailableException(msg, Network.class,
+ * guestConfig.getId()); } if (add) { // Insert a new NIC for this guest
+ * network to reserve the self IP
+ * _networkMgr.savePlaceholderNic(guestConfig, selfIp, null, null); }
+ * else { // release the self-ip obtained from guest network Nic
+ * selfipNic = getPlaceholderNic(guestConfig);
+ * _nicDao.remove(selfipNic.getId()); // release the load balancer
+ * allocated for the network boolean releasedLB =
+ * freeLoadBalancerForNetwork(guestConfig); if (!releasedLB) { String
+ * msg =
+ * "Failed to release the external load balancer used for the network: "
+ * + guestConfig.getId(); s_logger.error(msg); } } if
+ * (s_logger.isDebugEnabled()) { Account account =
+ * _accountDao.findByIdIncludingRemoved(guestConfig.getAccountId());
+ * String action = add ? "implemented" : "shut down"; s_logger.debug(
+ * "External load balancer has " + action +
+ * " the guest network for account " + account.getAccountName() +
+ * "(id = " + account.getAccountId() + ") with VLAN tag " +
+ * guestVlanTag); }
+ */
return true;
}
@Override
- public boolean prepare(Network config, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context)
- throws ConcurrentOperationException, InsufficientNetworkCapacityException, ResourceUnavailableException {
+ public boolean prepare(Network config, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest,
+ ReservationContext context) throws ConcurrentOperationException, InsufficientNetworkCapacityException,
+ ResourceUnavailableException {
return true;
}
@@ -453,7 +543,8 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
}
@Override
- public boolean shutdown(Network guestConfig, ReservationContext context, boolean cleanup) throws ResourceUnavailableException, ConcurrentOperationException {
+ public boolean shutdown(Network guestConfig, ReservationContext context, boolean cleanup)
+ throws ResourceUnavailableException, ConcurrentOperationException {
if (!canHandle(guestConfig, Service.Lb)) {
return false;
}
@@ -461,7 +552,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
try {
NetworkOffering networkOffering = _networkOfferingDao.findById(guestConfig.getNetworkOfferingId());
- if(networkOffering.getServicePackage() == null) {
+ if (networkOffering.getServicePackage() == null) {
return manageGuestNetworkWithExternalLoadBalancer(true, guestConfig);
} else {
// if the network offering has service package implement it with Netscaler Control Center
@@ -470,7 +561,8 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
}
//return manageGuestNetworkWithExternalLoadBalancer(false, guestConfig);
} catch (InsufficientCapacityException capacityException) {
- // TODO: handle out of capacity exception gracefully in case of multple providers available
+ // TODO: handle out of capacity exception gracefully in case of
+ // multple providers available
return false;
} catch (ConfigurationException e) {
// TODO Auto-generated catch block
@@ -520,27 +612,33 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
// Specifies that the RoundRobin and Leastconn algorithms are supported for load balancing rules
lbCapabilities.put(Capability.SupportedLBAlgorithms, "roundrobin, leastconn, source");
- // specifies that Netscaler network element can provided both shared and isolation modes
+ // specifies that Netscaler network element can provided both shared and
+ // isolation modes
lbCapabilities.put(Capability.SupportedLBIsolation, "dedicated, shared");
- // Specifies that load balancing rules can be made for either TCP or UDP traffic
+ // Specifies that load balancing rules can be made for either TCP or UDP
+ // traffic
lbCapabilities.put(Capability.SupportedProtocols, "tcp,udp");
- // Specifies that this element can measure network usage on a per public IP basis
+ // Specifies that this element can measure network usage on a per public
+ // IP basis
lbCapabilities.put(Capability.TrafficStatistics, "per public ip");
- // Specifies that load balancing rules can only be made with public IPs that aren't source NAT IPs
+ // Specifies that load balancing rules can only be made with public IPs
+ // that aren't source NAT IPs
lbCapabilities.put(Capability.LoadBalancingSupportedIps, "additional");
// Supports only Public load balancing
lbCapabilities.put(Capability.LbSchemes, LoadBalancerContainer.Scheme.Public.toString());
// Specifies that load balancing rules can support autoscaling and the list of counters it supports
+ // list of counters it supports
AutoScaleCounter counter;
List<AutoScaleCounter> counterList = new ArrayList<AutoScaleCounter>();
counter = new AutoScaleCounter(AutoScaleCounterSnmp);
counterList.add(counter);
- counter.addParam("snmpcommunity", true, "the community string that has to be used to do a SNMP GET on the AutoScaled Vm", false);
+ counter.addParam("snmpcommunity", true,
+ "the community string that has to be used to do a SNMP GET on the AutoScaled Vm", false);
counter.addParam("snmpport", false, "the port at which SNMP agent is running on the AutoScaled Vm", false);
counter = new AutoScaleCounter(AutoScaleCounterNetscaler);
@@ -552,15 +650,18 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
LbStickinessMethod method;
List<LbStickinessMethod> methodList = new ArrayList<LbStickinessMethod>();
- method = new LbStickinessMethod(StickinessMethodType.LBCookieBased, "This is cookie based sticky method, can be used only for http");
+ method = new LbStickinessMethod(StickinessMethodType.LBCookieBased,
+ "This is cookie based sticky method, can be used only for http");
methodList.add(method);
method.addParam("holdtime", false, "time period in minutes for which persistence is in effect.", false);
- method = new LbStickinessMethod(StickinessMethodType.AppCookieBased, "This is app session based sticky method, can be used only for http");
+ method = new LbStickinessMethod(StickinessMethodType.AppCookieBased,
+ "This is app session based sticky method, can be used only for http");
methodList.add(method);
method.addParam("name", true, "cookie name passed in http header by apllication to the client", false);
- method = new LbStickinessMethod(StickinessMethodType.SourceBased, "This is source based sticky method, can be used for any type of protocol.");
+ method = new LbStickinessMethod(StickinessMethodType.SourceBased,
+ "This is source based sticky method, can be used for any type of protocol.");
methodList.add(method);
method.addParam("holdtime", false, "time period for which persistence is in effect.", false);
@@ -568,7 +669,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
lbCapabilities.put(Capability.SupportedStickinessMethods, stickyMethodList);
lbCapabilities.put(Capability.ElasticLb, "true");
- //Setting HealthCheck Capability to True for Netscaler element
+ // Setting HealthCheck Capability to True for Netscaler element
lbCapabilities.put(Capability.HealthCheckPolicy, "true");
capabilities.put(Service.Lb, lbCapabilities);
@@ -601,15 +702,15 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
try {
uri = new URI(cmd.getUrl());
} catch (Exception e) {
- String msg = "Error parsing the url parameter specified in addNetscalerLoadBalancer command due to " + e.getMessage();
+ String msg = "Error parsing the url parameter specified in addNetscalerLoadBalancer command due to "
+ + e.getMessage();
s_logger.debug(msg);
throw new InvalidParameterValueException(msg);
}
Map<String, String> configParams = new HashMap<String, String>();
UrlUtil.parseQueryParameters(uri.getQuery(), false, configParams);
- boolean dedicatedUse =
- (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED))
- : false;
+ boolean dedicatedUse = (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null)
+ ? Boolean.parseBoolean(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED)) : false;
if (dedicatedUse && !deviceName.equals(NetworkDevice.NetscalerVPXLoadBalancer.getName())) {
String msg = "Only Netscaler VPX load balancers can be specified for dedicated use";
@@ -619,7 +720,8 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
if (cmd.isGslbProvider()) {
- if (!deviceName.equals(NetworkDevice.NetscalerVPXLoadBalancer.getName()) && !deviceName.equals(NetworkDevice.NetscalerMPXLoadBalancer.getName())) {
+ if (!deviceName.equals(NetworkDevice.NetscalerVPXLoadBalancer.getName())
+ && !deviceName.equals(NetworkDevice.NetscalerMPXLoadBalancer.getName())) {
String msg = "Only Netscaler VPX or MPX load balancers can be specified as GSLB service provider";
s_logger.debug(msg);
throw new InvalidParameterValueException(msg);
@@ -632,19 +734,21 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
}
if (dedicatedUse) {
- throw new InvalidParameterValueException("NetScaler provisioned to be GSLB service provider can only be configured for shared usage.");
+ throw new InvalidParameterValueException(
+ "NetScaler provisioned to be GSLB service provider can only be configured for shared usage.");
}
}
if (cmd.isExclusiveGslbProvider() && !cmd.isGslbProvider()) {
- throw new InvalidParameterValueException("NetScaler can be provisioned to be exclusive GSLB service provider" +
- " only if its being configured as GSLB service provider also.");
+ throw new InvalidParameterValueException(
+ "NetScaler can be provisioned to be exclusive GSLB service provider"
+ + " only if its being configured as GSLB service provider also.");
}
- ExternalLoadBalancerDeviceVO lbDeviceVO =
- addExternalLoadBalancer(cmd.getPhysicalNetworkId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), deviceName, new NetscalerResource(),
- cmd.isGslbProvider(), cmd.isExclusiveGslbProvider(), cmd.getSitePublicIp(), cmd.getSitePrivateIp());
+ ExternalLoadBalancerDeviceVO lbDeviceVO = addExternalLoadBalancer(cmd.getPhysicalNetworkId(), cmd.getUrl(),
+ cmd.getUsername(), cmd.getPassword(), deviceName, new NetscalerResource(), cmd.isGslbProvider(),
+ cmd.isExclusiveGslbProvider(), cmd.getSitePublicIp(), cmd.getSitePrivateIp());
return lbDeviceVO;
}
@@ -675,7 +779,8 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
}
@DB
- private ExternalLoadBalancerDeviceVO configureNetscalerLoadBalancer(final long lbDeviceId, Long capacity, Boolean dedicatedUse, List<Long> newPodsConfig) {
+ private ExternalLoadBalancerDeviceVO configureNetscalerLoadBalancer(final long lbDeviceId, Long capacity,
+ Boolean dedicatedUse, List<Long> newPodsConfig) {
final ExternalLoadBalancerDeviceVO lbDeviceVo = _lbDeviceDao.findById(lbDeviceId);
final Map<String, String> lbDetails = _detailsDao.findDetails(lbDeviceVo.getHostId());
@@ -716,10 +821,11 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
String deviceName = lbDeviceVo.getDeviceName();
if (dedicatedUse != null || capacity != null) {
- if (NetworkDevice.NetscalerSDXLoadBalancer.getName().equalsIgnoreCase(deviceName) ||
- NetworkDevice.NetscalerMPXLoadBalancer.getName().equalsIgnoreCase(deviceName)) {
+ if (NetworkDevice.NetscalerSDXLoadBalancer.getName().equalsIgnoreCase(deviceName)
+ || NetworkDevice.NetscalerMPXLoadBalancer.getName().equalsIgnoreCase(deviceName)) {
if (dedicatedUse != null && dedicatedUse == true) {
- throw new InvalidParameterValueException("Netscaler MPX and SDX device should be shared and can not be dedicated to a single account.");
+ throw new InvalidParameterValueException(
+ "Netscaler MPX and SDX device should be shared and can not be dedicated to a single account.");
}
}
@@ -727,11 +833,13 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
List<NetworkExternalLoadBalancerVO> networks = _networkLBDao.listByLoadBalancerDeviceId(lbDeviceId);
if ((networks != null) && !networks.isEmpty()) {
if (capacity != null && capacity < networks.size()) {
- throw new CloudRuntimeException("There are more number of networks already using this netscaler device than configured capacity");
+ throw new CloudRuntimeException(
+ "There are more number of networks already using this netscaler device than configured capacity");
}
if (dedicatedUse != null && dedicatedUse == true) {
- throw new CloudRuntimeException("There are networks already using this netscaler device to make device dedicated");
+ throw new CloudRuntimeException(
+ "There are networks already using this netscaler device to make device dedicated");
}
}
}
@@ -784,7 +892,12 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
cmdList.add(ListNetscalerLoadBalancersCmd.class);
cmdList.add(RegisterServicePackageCmd.class);
cmdList.add(RegisterNetscalerControlCenterCmd.class);
-
+ cmdList.add(ListRegisteredServicePackageCmd.class);
+ cmdList.add(ListNetscalerControlCenterCmd.class);
+ cmdList.add(DeleteServicePackageOfferingCmd.class);
+ cmdList.add(DeleteNetscalerControlCenterCmd.class);
+ cmdList.add(ReleasePodIpCmdByAdmin.class);
+ cmdList.add(AcquirePodIpCmdByAdmin.class);
return cmdList;
}
@@ -795,7 +908,8 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
ExternalLoadBalancerDeviceVO lbDeviceVo = _lbDeviceDao.findById(lbDeviceId);
if (lbDeviceVo == null || !isNetscalerDevice(lbDeviceVo.getDeviceName())) {
- throw new InvalidParameterValueException("Could not find Netscaler load balancer device with ID " + lbDeviceId);
+ throw new InvalidParameterValueException(
+ "Could not find Netscaler load balancer device with ID " + lbDeviceId);
}
List<NetworkExternalLoadBalancerVO> networkLbMaps = _networkLBDao.listByLoadBalancerDeviceId(lbDeviceId);
@@ -817,13 +931,15 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
List<ExternalLoadBalancerDeviceVO> lbDevices = new ArrayList<ExternalLoadBalancerDeviceVO>();
if (physcialNetworkId == null && lbDeviceId == null) {
- throw new InvalidParameterValueException("Either physical network Id or load balancer device Id must be specified");
+ throw new InvalidParameterValueException(
+ "Either physical network Id or load balancer device Id must be specified");
}
if (lbDeviceId != null) {
ExternalLoadBalancerDeviceVO lbDeviceVo = _lbDeviceDao.findById(lbDeviceId);
if (lbDeviceVo == null || !isNetscalerDevice(lbDeviceVo.getDeviceName())) {
- throw new InvalidParameterValueException("Could not find Netscaler load balancer device with ID: " + lbDeviceId);
+ throw new InvalidParameterValueException(
+ "Could not find Netscaler load balancer device with ID: " + lbDeviceId);
}
lbDevices.add(lbDeviceVo);
return lbDevices;
@@ -832,7 +948,8 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
if (physcialNetworkId != null) {
pNetwork = _physicalNetworkDao.findById(physcialNetworkId);
if (pNetwork == null) {
- throw new InvalidParameterValueException("Could not find phyical network with ID: " + physcialNetworkId);
+ throw new InvalidParameterValueException(
+ "Could not find phyical network with ID: " + physcialNetworkId);
}
lbDevices = _lbDeviceDao.listByPhysicalNetworkAndProvider(physcialNetworkId, Provider.Netscaler.getName());
return lbDevices;
@@ -842,11 +959,90 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
}
@Override
+ public List<NetScalerServicePackageVO> listRegisteredServicePackages(ListRegisteredServicePackageCmd cmd) {
+
+ List<NetScalerServicePackageVO> lrsPackages = new ArrayList<NetScalerServicePackageVO>();
+ lrsPackages = _netscalerServicePackageDao.listAll();
+ return lrsPackages;
+ }
+
+ @Override
+ public List<NetScalerControlCenterVO> listNetscalerControlCenter(ListNetscalerControlCenterCmd cmd) {
+ return _netscalerControlCenterDao.listAll();
+ }
+
+ @Override
+ public boolean deleteServicePackageOffering(DeleteServicePackageOfferingCmd cmd) throws CloudRuntimeException {
+ NetScalerServicePackageVO result = null;
+ boolean flag;
+ try {
+ result = _netscalerServicePackageDao.findByUuid(cmd.getId());
+ flag = _netscalerServicePackageDao.remove(result.getId());
+ } catch (Exception e) {
+ if (e instanceof InvalidParameterValueException)
+ throw new ServerApiException(ApiErrorCode.PARAM_ERROR, e.getMessage());
+ else if (result == null)
+ throw new CloudRuntimeException("Record does not Exists in the Table");
+ else
+ throw new CloudRuntimeException("Network offering is using the service package. First delete the nework offering and then delete ServicePackage");
+ }
+ return flag;
+
+ }
+
+ @DB
+ @Override
+ public boolean deleteNetscalerControlCenter(DeleteNetscalerControlCenterCmd cmd) throws CloudRuntimeException {
+
+ NetScalerControlCenterVO result = _netscalerControlCenterDao.findByUuid(cmd.getId());
+ if (result == null)
+ throw new CloudRuntimeException("External Netscaler Control Center Table does not contain record with this ID");
+ else {
+ List<Long> id_set_1 = _networkOfferingDao.listServicePackageUuid();
+ if (id_set_1.size() != 0) {
+ List<NetworkVO> id_set_2 = _networkDao.listNetworkOfferingId(id_set_1);
+ if (id_set_2 != null && id_set_2.size() != 0)
+ throw new CloudRuntimeException(
+ "ServicePackages published by NetScalerControlCenter are being used by NetworkOfferings. Try deleting NetworkOffering with ServicePackages and then delete NetScalerControlCenter.");
+ }
+ }
+ try {
+ _netscalerServicePackageDao.removeAll();
+ } catch (CloudRuntimeException ce) {
+ throw new CloudRuntimeException("Service Package is being used by Network Offering, Try deleting Network Offering and then delete Service Package.");
+ }
+
+ // delete Netscaler Control Center
+ _netscalerControlCenterDao.remove(result.getId());
+
+ //Removal of NCC from Host Table
+ SearchCriteria<HostVO> sc = _hostDao.createSearchCriteria();
+ sc.addAnd("type", SearchCriteria.Op.EQ, Host.Type.NetScalerControlCenter);
+ List<HostVO> ncc_list = _hostDao.search(sc, null);
+
+ if (ncc_list == null) {
+ throw new CloudRuntimeException("Could not find Netscaler Control Center in Database");
+ }
+ for (HostVO ncc : ncc_list) {
+ try {
+ // put the host in maintenance state in order for it to be deleted
+ ncc.setResourceState(ResourceState.Maintenance);
+ _hostDao.update(ncc.getId(), ncc);
+ _resourceMgr.deleteHost(ncc.getId(), false, false);
+ } catch (Exception e) {
+ s_logger.debug(e);
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ @Override
public NetscalerLoadBalancerResponse createNetscalerLoadBalancerResponse(ExternalLoadBalancerDeviceVO lbDeviceVO) {
NetscalerLoadBalancerResponse response = new NetscalerLoadBalancerResponse();
Host lbHost = _hostDao.findById(lbDeviceVO.getHostId());
Map<String, String> lbDetails = _detailsDao.findDetails(lbDeviceVO.getHostId());
-
response.setId(lbDeviceVO.getUuid());
response.setIpAddress(lbHost.getPrivateIpAddress());
PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(lbDeviceVO.getPhysicalNetworkId());
@@ -857,7 +1053,8 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
response.setPrivateInterface(lbDetails.get("privateInterface"));
response.setDeviceName(lbDeviceVO.getDeviceName());
if (lbDeviceVO.getCapacity() == 0) {
- long defaultLbCapacity = NumbersUtil.parseLong(_configDao.getValue(Config.DefaultExternalLoadBalancerCapacity.key()), 50);
+ long defaultLbCapacity = NumbersUtil
+ .parseLong(_configDao.getValue(Config.DefaultExternalLoadBalancerCapacity.key()), 50);
response.setDeviceCapacity(defaultLbCapacity);
} else {
response.setDeviceCapacity(lbDeviceVO.getCapacity());
@@ -884,15 +1081,35 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
}
@Override
+ public NetscalerControlCenterResponse createNetscalerControlCenterResponse(NetScalerControlCenterVO lncCentersVO) {
+ NetscalerControlCenterResponse response = new NetscalerControlCenterResponse(lncCentersVO);
+ response.setObjectName("netscalercontrolcenter");
+ return response;
+ }
+
+ @Override
+ public NetScalerServicePackageResponse createRegisteredServicePackageResponse(
+ NetScalerServicePackageVO lrsPackageVO) {
+ NetScalerServicePackageResponse response = new NetScalerServicePackageResponse();
+ response.setId(lrsPackageVO.getUuid());
+ response.setName(lrsPackageVO.getName());
+ response.setDescription(lrsPackageVO.getDescription());
+ response.setObjectName("registeredServicepackage");
+ return response;
+ }
+
+ @Override
public Provider getProvider() {
return Provider.Netscaler;
}
@Override
public boolean isReady(PhysicalNetworkServiceProvider provider) {
- List<ExternalLoadBalancerDeviceVO> lbDevices = _lbDeviceDao.listByPhysicalNetworkAndProvider(provider.getPhysicalNetworkId(), Provider.Netscaler.getName());
+ List<ExternalLoadBalancerDeviceVO> lbDevices = _lbDeviceDao
+ .listByPhysicalNetworkAndProvider(provider.getPhysicalNetworkId(), Provider.Netscaler.getName());
- // true if at-least one Netscaler device is added in to physical network and is in configured (in enabled state)
+ // true if at-least one Netscaler device is added in to physical network
+ // and is in configured (in enabled state)
// state
if (lbDevices != null && !lbDevices.isEmpty()) {
for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) {
@@ -905,9 +1122,10 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
}
@Override
- public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException,
- ResourceUnavailableException {
- // TODO reset the configuration on all of the netscaler devices in this physical network
+ public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context)
+ throws ConcurrentOperationException, ResourceUnavailableException {
+ // TODO reset the configuration on all of the netscaler devices in this
+ // physical network
return true;
}
@@ -917,9 +1135,9 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
}
private boolean isNetscalerDevice(String deviceName) {
- if ((deviceName == null) ||
- ((!deviceName.equalsIgnoreCase(NetworkDevice.NetscalerMPXLoadBalancer.getName())) &&
- (!deviceName.equalsIgnoreCase(NetworkDevice.NetscalerSDXLoadBalancer.getName())) && (!deviceName.equalsIgnoreCase(NetworkDevice.NetscalerVPXLoadBalancer.getName())))) {
+ if ((deviceName == null) || ((!deviceName.equalsIgnoreCase(NetworkDevice.NetscalerMPXLoadBalancer.getName()))
+ && (!deviceName.equalsIgnoreCase(NetworkDevice.NetscalerSDXLoadBalancer.getName()))
+ && (!deviceName.equalsIgnoreCase(NetworkDevice.NetscalerVPXLoadBalancer.getName())))) {
return false;
} else {
return true;
@@ -934,15 +1152,21 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
// NetScaler can only act as Lb and Static Nat service provider
if (services != null && !services.isEmpty() && !netscalerServices.containsAll(services)) {
- s_logger.warn("NetScaler network element can only support LB and Static NAT services and service combination " + services + " is not supported.");
+ s_logger.warn(
+ "NetScaler network element can only support LB and Static NAT services and service combination "
+ + services + " is not supported.");
StringBuffer buff = new StringBuffer();
for (Service service : services) {
buff.append(service.getName());
buff.append(" ");
}
- s_logger.warn("NetScaler network element can only support LB and Static NAT services and service combination " + buff.toString() + " is not supported.");
- s_logger.warn("NetScaler network element can only support LB and Static NAT services and service combination " + services + " is not supported.");
+ s_logger.warn(
+ "NetScaler network element can only support LB and Static NAT services and service combination "
+ + buff.toString() + " is not supported.");
+ s_logger.warn(
+ "NetScaler network element can only support LB and Static NAT services and service combination "
+ + services + " is not supported.");
return false;
}
@@ -950,8 +1174,10 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
}
@Override
- public boolean applyIps(Network network, List<? extends PublicIpAddress> ipAddress, Set<Service> service) throws ResourceUnavailableException {
- // return true, as IP will be associated as part of LB rule configuration
+ public boolean applyIps(Network network, List<? extends PublicIpAddress> ipAddress, Set<Service> service)
+ throws ResourceUnavailableException {
+ // return true, as IP will be associated as part of LB rule
+ // configuration
return true;
}
@@ -965,7 +1191,8 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
return this;
}
- public boolean applyElasticLoadBalancerRules(Network network, List<LoadBalancingRule> loadBalancingRules) throws ResourceUnavailableException {
+ public boolean applyElasticLoadBalancerRules(Network network, List<LoadBalancingRule> loadBalancingRules)
+ throws ResourceUnavailableException {
if (loadBalancingRules == null || loadBalancingRules.isEmpty()) {
return true;
@@ -977,7 +1204,8 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
try {
lbDeviceVO = allocateLoadBalancerForNetwork(network);
} catch (Exception e) {
- errMsg = "Could not allocate a NetSclaer load balancer for configuring elastic load balancer rules due to " + e.getMessage();
+ errMsg = "Could not allocate a NetSclaer load balancer for configuring elastic load balancer rules due to "
+ + e.getMessage();
s_logger.error(errMsg);
throw new ResourceUnavailableException(errMsg, this.getClass(), 0);
}
@@ -1001,9 +1229,9 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
List<LbDestination> destinations = rule.getDestinations();
if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) {
- LoadBalancerTO loadBalancer =
- new LoadBalancerTO(lbUuid, srcIp, srcPort, protocol, algorithm, revoked, false, false, destinations, rule.getStickinessPolicies(),
- rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol());
+ LoadBalancerTO loadBalancer = new LoadBalancerTO(lbUuid, srcIp, srcPort, protocol, algorithm, revoked,
+ false, false, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(),
+ rule.getLbSslCert(), rule.getLbProtocol());
if (rule.isAutoScaleConfig()) {
loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup());
}
@@ -1013,16 +1241,16 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
if (loadBalancersToApply.size() > 0) {
int numLoadBalancersForCommand = loadBalancersToApply.size();
- LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]);
+ LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply
+ .toArray(new LoadBalancerTO[numLoadBalancersForCommand]);
LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand, null);
HostVO externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId());
Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd);
if (answer == null || !answer.getResult()) {
String details = (answer != null) ? answer.getDetails() : "details unavailable";
- String msg =
- "Unable to apply elastic load balancer rules to the external load balancer appliance in zone " + network.getDataCenterId() + " due to: " + details +
- ".";
+ String msg = "Unable to apply elastic load balancer rules to the external load balancer appliance in zone "
+ + network.getDataCenterId() + " due to: " + details + ".";
s_logger.error(msg);
throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId());
}
@@ -1032,13 +1260,15 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
}
@Override
- public boolean applyStaticNats(Network config, List<? extends StaticNat> rules) throws ResourceUnavailableException {
+ public boolean applyStaticNats(Network config, List<? extends StaticNat> rules)
+ throws ResourceUnavailableException {
if (!canHandle(config, Service.StaticNat)) {
return false;
}
- boolean multiNetScalerDeployment = Boolean.valueOf(_configDao.getValue(Config.EIPWithMultipleNetScalersEnabled.key()));
+ boolean multiNetScalerDeployment = Boolean
+ .valueOf(_configDao.getValue(Config.EIPWithMultipleNetScalersEnabled.key()));
try {
if (!multiNetScalerDeployment) {
@@ -1048,7 +1278,8 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
try {
lbDevice = allocateLoadBalancerForNetwork(config);
} catch (Exception e) {
- errMsg = "Could not allocate a NetSclaer load balancer for configuring static NAT rules due to" + e.getMessage();
+ errMsg = "Could not allocate a NetSclaer load balancer for configuring static NAT rules due to"
+ + e.getMessage();
s_logger.error(errMsg);
throw new ResourceUnavailableException(errMsg, this.getClass(), 0);
}
@@ -1065,8 +1296,8 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
rulesTO = new ArrayList<StaticNatRuleTO>();
for (StaticNat rule : rules) {
IpAddress sourceIp = _networkMgr.getIp(rule.getSourceIpAddressId());
- StaticNatRuleTO ruleTO =
- new StaticNatRuleTO(0, sourceIp.getAddress().addr(), null, null, rule.getDestIpAddress(), null, null, null, rule.isForRevoke(), false);
+ StaticNatRuleTO ruleTO = new StaticNatRuleTO(0, sourceIp.getAddress().addr(), null, null,
+ rule.getDestIpAddress(), null, null, null, rule.isForRevoke(), false);
rulesTO.add(ruleTO);
}
}
@@ -1084,20 +1315,23 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
// validate if EIP rule can be configured.
ExternalLoadBalancerDeviceVO lbDevice = getNetScalerForEIP(rule);
if (lbDevice == null) {
- String errMsg = "There is no NetScaler device configured to perform EIP to guest IP address: " + rule.getDestIpAddress();
+ String errMsg = "There is no NetScaler device configured to perform EIP to guest IP address: "
+ + rule.getDestIpAddress();
s_logger.error(errMsg);
throw new ResourceUnavailableException(errMsg, this.getClass(), 0);
}
List<StaticNatRuleTO> rulesTO = new ArrayList<StaticNatRuleTO>();
IpAddress sourceIp = _networkMgr.getIp(rule.getSourceIpAddressId());
- StaticNatRuleTO ruleTO =
- new StaticNatRuleTO(0, sourceIp.getAddress().addr(), null, null, rule.getDestIpAddress(), null, null, null, rule.isForRevoke(), false);
+ StaticNatRuleTO ruleTO = new StaticNatRuleTO(0, sourceIp.getAddress().addr(), null, null,
+ rule.getDestIpAddress(), null, null, null, rule.isForRevoke(), false);
rulesTO.add(ruleTO);
SetStaticNatRulesCommand cmd = new SetStaticNatRulesCommand(rulesTO, null);
- // send commands to configure INAT rule on the NetScaler device
- SetStaticNatRulesAnswer answer = (SetStaticNatRulesAnswer)_agentMgr.send(lbDevice.getHostId(), cmd);
+ // send commands to configure INAT rule on the NetScaler
+ // device
+ SetStaticNatRulesAnswer answer = (SetStaticNatRulesAnswer)_agentMgr.send(lbDevice.getHostId(),
+ cmd);
if (answer == null) {
String errMsg = "Failed to configure INAT rule on NetScaler device " + lbDevice.getHostId();
s_logger.error(errMsg);
@@ -1114,7 +1348,8 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
}
}
- // returns configured NetScaler device that is associated with the pod that owns guest IP
+ // returns configured NetScaler device that is associated with the pod that
+ // owns guest IP
private ExternalLoadBalancerDeviceVO getNetScalerForEIP(StaticNat rule) {
String guestIP = rule.getDestIpAddress();
List<DataCenterIpAddressVO> dcGuestIps = _privateIpAddressDao.listAll();
@@ -1133,7 +1368,8 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
return null;
}
- public List<LoadBalancerTO> getElasticLBRulesHealthCheck(Network network, List<LoadBalancingRule> loadBalancingRules) throws ResourceUnavailableException {
+ public List<LoadBalancerTO> getElasticLBRulesHealthCheck(Network network,
+ List<LoadBalancingRule> loadBalancingRules) throws ResourceUnavailableException {
HealthCheckLBConfigAnswer answer = null;
@@ -1145,7 +1381,8 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network);
if (lbDeviceVO == null) {
- s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning");
+ s_logger.warn(
+ "There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning");
return null;
}
@@ -1167,16 +1404,17 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
List<LbDestination> destinations = rule.getDestinations();
if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) {
- LoadBalancerTO loadBalancer =
- new LoadBalancerTO(lbUuid, srcIp, srcPort, protocol, algorithm, revoked, false, false, destinations, null, rule.getHealthCheckPolicies(),
- rule.getLbSslCert(), rule.getLbProtocol());
+ LoadBalancerTO loadBalancer = new LoadBalancerTO(lbUuid, srcIp, srcPort, protocol, algorithm, revoked,
+ false, false, destinations, null, rule.getHealthCheckPolicies(), rule.getLbSslCert(),
+ rule.getLbProtocol());
loadBalancersToApply.add(loadBalancer);
}
}
if (loadBalancersToApply.size() > 0) {
int numLoadBalancersForCommand = loadBalancersToApply.size();
- LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]);
+ LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply
+ .toArray(new LoadBalancerTO[numLoadBalancersForCommand]);
HealthCheckLBConfigCommand cmd = new HealthCheckLBConfigCommand(loadBalancersForCommand);
HostVO externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId());
answer = (HealthCheckLBConfigAnswer)_agentMgr.easySend(externalLoadBalancer.getId(), cmd);
@@ -1211,16 +1449,37 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
}
@Override
- public List<LoadBalancerTO> getLBHealthChecks(Network network, List<LoadBalancingRule> rules) throws ResourceUnavailableException {
+ public List<LoadBalancerTO> getLBHealthChecks(Network network, List<LoadBalancingRule> rules)
+ throws ResourceUnavailableException {
return super.getLBHealthChecks(network, rules);
}
@Override
- public boolean applyGlobalLoadBalancerRule(long zoneId, long physicalNetworkId, GlobalLoadBalancerConfigCommand gslbConfigCmd) throws ResourceUnavailableException {
+ public NetScalerServicePackageResponse listNetscalerServicePackage(RegisterServicePackageCmd cmd) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public NetScalerServicePackageResponse deleteNetscalerServicePackage(RegisterServicePackageCmd cmd) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public NetScalerServicePackageResponse createNetscalerServicePackageResponse(NetScalerServicePackageVO servicePackageVO) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public boolean applyGlobalLoadBalancerRule(long zoneId, long physicalNetworkId,
+ GlobalLoadBalancerConfigCommand gslbConfigCmd) throws ResourceUnavailableException {
long zoneGslbProviderHosId = 0;
- // find the NetScaler device configured as gslb service provider in the zone
+ // find the NetScaler device configured as gslb service provider in the
+ // zone
ExternalLoadBalancerDeviceVO nsGslbProvider = findGslbProvider(zoneId, physicalNetworkId);
if (nsGslbProvider == null) {
String msg = "Unable to find a NetScaler configured as gslb service provider in zone " + zoneId;
@@ -1228,7 +1487,8 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
throw new ResourceUnavailableException(msg, DataCenter.class, zoneId);
}
- // get the host Id corresponding to NetScaler acting as GSLB service provider in the zone
+ // get the host Id corresponding to NetScaler acting as GSLB service
+ // provider in the zone
zoneGslbProviderHosId = nsGslbProvider.getHostId();
// send gslb configuration to NetScaler device
@@ -1246,13 +1506,14 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
List<PhysicalNetworkVO> pNtwks = _physicalNetworkDao.listByZoneAndTrafficType(zoneId, TrafficType.Guest);
if (pNtwks == null || pNtwks.isEmpty()) {
- throw new InvalidParameterValueException("Unable to get physical network: " + physicalNetworkId + " in zone id = " + zoneId);
+ throw new InvalidParameterValueException(
+ "Unable to get physical network: " + physicalNetworkId + " in zone id = " + zoneId);
} else {
for (PhysicalNetwork physicalNetwork : pNtwks) {
if (physicalNetwork.getId() == physicalNetworkId) {
PhysicalNetworkVO physNetwork = pNtwks.get(0);
- ExternalLoadBalancerDeviceVO nsGslbProvider =
- _externalLoadBalancerDeviceDao.findGslbServiceProvider(physNetwork.getId(), Provider.Netscaler.getName());
+ ExternalLoadBalancerDeviceVO nsGslbProvider = _externalLoadBalancerDeviceDao
+ .findGslbServiceProvider(physNetwork.getId(), Provider.Netscaler.getName());
return nsGslbProvider;
}
}
@@ -1265,7 +1526,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
public boolean isServiceEnabledInZone(long zoneId, long physicalNetworkId) {
ExternalLoadBalancerDeviceVO nsGslbProvider = findGslbProvider(zoneId, physicalNetworkId);
- //return true if a NetScaler device is configured in the zone
+ // return true if a NetScaler device is configured in the zone
return (nsGslbProvider != null);
}
@@ -1288,13 +1549,14 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
}
private boolean canHandleLbRules(List<LoadBalancingRule> rules) {
- Map<Capability, String> lbCaps = this.getCapabilities().get(Service.Lb);
+ Map<Capability, String> lbCaps = getCapabilities().get(Service.Lb);
if (!lbCaps.isEmpty()) {
String schemeCaps = lbCaps.get(Capability.LbSchemes);
if (schemeCaps != null) {
for (LoadBalancingRule rule : rules) {
if (!schemeCaps.contains(rule.getScheme().toString())) {
- s_logger.debug("Scheme " + rules.get(0).getScheme() + " is not supported by the provider " + this.getName());
+ s_logger.debug("Scheme " + rules.get(0).getScheme() + " is not supported by the provider "
+ + getName());
return false;
}
}
@@ -1313,35 +1575,17 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
}
@Override
- public NetScalerServicePackageResponse deleteNetscalerServicePackage(RegisterServicePackageCmd cmd) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public NetScalerServicePackageResponse listNetscalerServicePackage(RegisterServicePackageCmd cmd) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public NetScalerServicePackageResponse createNetscalerServicePackageResponse(NetScalerServicePackageVO servicePackageVO) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
@DB
public NetScalerControlCenterVO registerNetscalerControlCenter(RegisterNetscalerControlCenterCmd cmd) {
final RegisterNetscalerControlCenterCmd cmdinfo = cmd;
String ipAddress = cmd.getIpaddress();
Map hostDetails = new HashMap<String, String>();
- String hostName = "NetscalerControlCenter";
+ String hostName = "NetscalerControlCenter";
hostDetails.put("name", hostName);
hostDetails.put("guid", UUID.randomUUID().toString());
List<DataCenterVO> dcVO = _dcDao.listEnabledZones();
- if(dcVO.size() == 0) {
+ if (dcVO.size() == 0) {
throw new CloudRuntimeException("There is no single enabled zone. Please add a zone, enable it and then add Netscaler ControlCenter");
}
hostDetails.put("zoneId", "1");
@@ -1351,7 +1595,6 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl
hostDetails.put("deviceName", "Netscaler ControlCenter");
ServerResource resource = new NetScalerControlCenterResource();
try {
-
resource.configure(hostName, hostDetails);
return Transaction.execute(new TransactionCallback<NetScalerControlCenterVO>() {
@Override
diff --git a/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerLoadBalancerElementService.java b/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerLoadBalancerElementService.java
index 81c5b7c..c635f78 100644
--- a/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerLoadBalancerElementService.java
+++ b/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerLoadBalancerElementService.java
@@ -20,22 +20,61 @@ import java.util.List;
import com.cloud.api.commands.AddNetscalerLoadBalancerCmd;
import com.cloud.api.commands.ConfigureNetscalerLoadBalancerCmd;
+import com.cloud.api.commands.DeleteNetscalerControlCenterCmd;
import com.cloud.api.commands.DeleteNetscalerLoadBalancerCmd;
+import com.cloud.api.commands.DeleteServicePackageOfferingCmd;
+import com.cloud.api.commands.ListNetscalerControlCenterCmd;
import com.cloud.api.commands.ListNetscalerLoadBalancerNetworksCmd;
import com.cloud.api.commands.ListNetscalerLoadBalancersCmd;
+import com.cloud.api.commands.ListRegisteredServicePackageCmd;
import com.cloud.api.commands.RegisterNetscalerControlCenterCmd;
import com.cloud.api.commands.RegisterServicePackageCmd;
import com.cloud.api.response.NetscalerLoadBalancerResponse;
import com.cloud.api.response.NetScalerServicePackageResponse;
+import com.cloud.api.response.NetscalerControlCenterResponse;
import com.cloud.network.NetScalerControlCenterVO;
import com.cloud.network.NetScalerServicePackageVO;
import com.cloud.network.Network;
import com.cloud.network.dao.ExternalLoadBalancerDeviceVO;
import com.cloud.utils.component.PluggableService;
+import com.cloud.utils.exception.CloudRuntimeException;
public interface NetscalerLoadBalancerElementService extends PluggableService {
/**
+ * lists all Netscaler Control Center user Details
+ * @param ListNetscalerControlCenterCmd
+ * @return list of NetScalerControlCenterVO for Net Scaler Control Center which contains information about user and their network
+ * control center ID etc.
+ *
+ */
+ public List<NetScalerControlCenterVO> listNetscalerControlCenter(ListNetscalerControlCenterCmd cmd);
+
+ /**
+ * Lists all the list Registered Service Packages details in the Network.
+ * @param ListRegisteredServicePackageCmd
+ * @return list of NetScalerServicePackageVO for registered services in the network which contains details of services
+ */
+
+ public List<NetScalerServicePackageVO> listRegisteredServicePackages(ListRegisteredServicePackageCmd cmd);
+
+ /**
+ * Deletes Service Package Offering
+ *
+ * @param DeleteServicePackageOffering
+ * @return boolean value which tells deletion is successful or not.
+ */
+ public boolean deleteServicePackageOffering(DeleteServicePackageOfferingCmd cmd) throws CloudRuntimeException;
+
+ /**
+ * Deletes Netscaler Control Center if it is not in use.
+ *
+ * @param (DeleteNetscalerControlCenter
+ * @return boolean value which tells deletion is successful or not.
+ */
+ public boolean deleteNetscalerControlCenter(DeleteNetscalerControlCenterCmd cmd) throws CloudRuntimeException;
+
+ /**
* adds a Netscaler load balancer device in to a physical network
* @param AddNetscalerLoadBalancerCmd
* @return ExternalLoadBalancerDeviceVO object for the device added
@@ -84,6 +123,10 @@ public interface NetscalerLoadBalancerElementService extends PluggableService {
*/
public NetScalerServicePackageResponse registerNetscalerServicePackage(RegisterServicePackageCmd cmd);
+ public NetscalerControlCenterResponse createNetscalerControlCenterResponse(NetScalerControlCenterVO lncCentersVO);
+
+ public NetScalerServicePackageResponse createRegisteredServicePackageResponse(NetScalerServicePackageVO lrsPackageVO);
+
public NetScalerServicePackageResponse deleteNetscalerServicePackage(RegisterServicePackageCmd cmd);
public NetScalerServicePackageResponse listNetscalerServicePackage(RegisterServicePackageCmd cmd);
@@ -91,4 +134,5 @@ public interface NetscalerLoadBalancerElementService extends PluggableService {
public NetScalerServicePackageResponse createNetscalerServicePackageResponse(NetScalerServicePackageVO servicePackageVO);
public NetScalerControlCenterVO registerNetscalerControlCenter(RegisterNetscalerControlCenterCmd registerNetscalerControlCenterCmd);
-}
+
+}
\ No newline at end of file
diff --git a/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetScalerControlCenterResource.java b/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetScalerControlCenterResource.java
index 15342dc..a8b3fbf 100644
--- a/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetScalerControlCenterResource.java
+++ b/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetScalerControlCenterResource.java
@@ -17,14 +17,12 @@
package com.cloud.network.resource;
import java.io.IOException;
-import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
-import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
@@ -37,7 +35,6 @@ import java.util.Map;
import javax.naming.ConfigurationException;
-import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
@@ -56,7 +53,7 @@ import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.BasicClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
-import org.bouncycastle.openssl.PEMWriter;
+import org.json.JSONException;
import org.json.JSONObject;
import com.citrix.netscaler.nitro.exception.nitro_exception;
@@ -64,7 +61,6 @@ import com.citrix.netscaler.nitro.resource.base.base_response;
import com.citrix.netscaler.nitro.resource.config.autoscale.autoscaleaction;
import com.citrix.netscaler.nitro.resource.config.autoscale.autoscalepolicy;
import com.citrix.netscaler.nitro.resource.config.autoscale.autoscaleprofile;
-import com.citrix.netscaler.nitro.resource.config.basic.server_service_binding;
import com.citrix.netscaler.nitro.resource.config.basic.service_lbmonitor_binding;
import com.citrix.netscaler.nitro.resource.config.basic.servicegroup;
import com.citrix.netscaler.nitro.resource.config.basic.servicegroup_lbmonitor_binding;
@@ -100,7 +96,6 @@ import com.citrix.netscaler.nitro.service.nitro_service;
import com.citrix.netscaler.nitro.util.filtervalue;
import com.citrix.sdx.nitro.resource.config.ns.ns;
import com.citrix.sdx.nitro.resource.config.xen.xen_nsvpx_image;
-import com.google.common.collect.Lists;
import com.google.gson.Gson;
import org.apache.cloudstack.api.ApiConstants;
@@ -144,7 +139,6 @@ import com.cloud.agent.api.to.LoadBalancerTO.StickinessPolicyTO;
import com.cloud.agent.api.to.StaticNatRuleTO;
import com.cloud.host.Host;
import com.cloud.host.Host.Type;
-import com.cloud.network.lb.LoadBalancingRule.LbSslCert;
import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType;
import com.cloud.resource.ServerResource;
import com.cloud.serializer.GsonHelper;
@@ -153,7 +147,6 @@ import com.cloud.utils.Pair;
import com.cloud.utils.StringUtils;
import com.cloud.utils.exception.ExecutionException;
import com.cloud.utils.net.NetUtils;
-import com.cloud.utils.security.CertificateHelper;
import com.cloud.utils.ssh.SshHelper;
/*class NitroError {
@@ -178,6 +171,7 @@ public class NetScalerControlCenterResource implements ServerResource {
private String _publicInterface;
private String _privateInterface;
private Integer _numRetries;
+ private Long _nccCmdTimeout;
private String _guid;
private boolean _inline;
private boolean _isSdx;
@@ -194,7 +188,7 @@ public class NetScalerControlCenterResource implements ServerResource {
protected Gson _gson;
private final String _objectNamePathSep = "-";
final String protocol="https";
-
+ private static String nccsession;
// interface to interact with VPX and MPX devices
com.citrix.netscaler.nitro.service.nitro_service _netscalerService;
@@ -207,6 +201,17 @@ public class NetScalerControlCenterResource implements ServerResource {
_gson = GsonHelper.getGsonLogger();
}
+
+ public static String get_nccsession() {
+ return nccsession;
+ }
+
+
+ public static void set_nccsession(String nccsession) {
+ NetScalerControlCenterResource.nccsession = nccsession;
+ }
+
+
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
JSONObject jsonResponse = null;
@@ -221,11 +226,6 @@ public class NetScalerControlCenterResource implements ServerResource {
throw new ConfigurationException("Unable to find zone Id in the configuration parameters");
}
-/* _physicalNetworkId = (String)params.get("physicalNetworkId");
- if (_physicalNetworkId == null) {
- throw new ConfigurationException("Unable to find physical network id in the configuration parameters");
- }
-*/
_ip = (String)params.get("ip");
if (_ip == null) {
throw new ConfigurationException("Unable to find IP address in the configuration parameters");
@@ -252,23 +252,25 @@ public class NetScalerControlCenterResource implements ServerResource {
if (_deviceName == null) {
throw new ConfigurationException("Unable to find the device name in the configuration parameters");
}
+ _nccCmdTimeout = NumbersUtil.parseLong((String)params.get("numretries"), 600000);
// validate device configuration parameters
- String response = login();
+ login();
+ /*String response =
if(response == null) {
throw new ConfigurationException("No Response Received from the NetScalerControlCenter Device");
} else {
jsonResponse = new JSONObject(response);
org.json.JSONArray loginResponse = jsonResponse.getJSONArray("login");
- //loginResponse.getJSONObject(0);
_sessionid = jsonResponse.getJSONArray("login").getJSONObject(0).getString("sessionid");
- }
- // Make GET request with the new session to verify
- s_logger.debug("Making Request to get all Service packages");
- getServicePackages();
+ }*/
+
return true;
- } catch (Exception e) {
+ } catch (ConfigurationException e) {
throw new ConfigurationException(e.getMessage());
+ } catch (ExecutionException e) {
+ s_logger.debug("Execution Exception :" + e.getMessage());
+ throw new ConfigurationException("Failed to add the device. Please check the device is NCC and It is reachable from Management Server.");
}
}
@@ -320,8 +322,9 @@ public class NetScalerControlCenterResource implements ServerResource {
}
}
- private String login() throws ExecutionException {
+ private synchronized String login() throws ExecutionException{// , ConfigurationException {
String result = null;
+ JSONObject jsonResponse = null;
try {
// If a previous session was open, log it out.
//logout();
@@ -339,12 +342,26 @@ public class NetScalerControlCenterResource implements ServerResource {
jsonBody.put("login", jsonCredentials);
result = postHttpRequest(jsonBody.toString(), agentUri, _sessionid);
- s_logger.debug("NCC Device got Added:: " + result);
+ if (result == null) {
+ throw new ConfigurationException("No Response Received from the NetScalerControlCenter Device");
+ } else {
+ jsonResponse = new JSONObject(result);
+ org.json.JSONArray loginResponse = jsonResponse.getJSONArray("login");
+ _sessionid = jsonResponse.getJSONArray("login").getJSONObject(0).getString("sessionid");
+ s_logger.debug("New Session id from NCC :" + _sessionid);
+ set_nccsession(_sessionid);
+ s_logger.debug("session on Static Session variable" + get_nccsession());
+ }
+ s_logger.debug("Login to NCC Device response :: " + result);
return result;
} catch (URISyntaxException e) {
String errMsg = "Could not generate URI for Hyper-V agent";
s_logger.error(errMsg, e);
+ } catch (JSONException e) {
+ s_logger.debug("JSON Exception :" + e.getMessage());
+ //throw new ConfigurationException("Failed to add the device. Please check the device is NCC and It is reachable from Management Server.");
+ throw new ExecutionException("Failed to log in to NCC device at " + _ip + " due to " + e.getMessage());
} catch (Exception e) {
throw new ExecutionException("Failed to log in to NCC device at " + _ip + " due to " + e.getMessage());
}
@@ -406,6 +423,75 @@ public class NetScalerControlCenterResource implements ServerResource {
return new MaintainAnswer(cmd);
}
+ private String queryAsyncJob(String jobId) {
+ String result = null;
+ try {
+ // If a previous session was open, log it out.
+ //logout();
+/* Polling for async tasks:
+ URL: http://10.102.31.78/admin/v1/journalcontexts/ <job-id>
+ Rwsponse:
+
+ {
+ "journalcontext": {
+ "id": "ctxt-6cfd63ba-b4d2-413d-af2d-caa6f1dc5cd9",
+ "start_time": "2015-07-16T09:47:50.596664",
+ "end_time": "2015-07-16T09:47:50.636356",
+ "name": "Update devices",
+ "service_name": "admin",
+ "is_default": false,
+ "scopes": [],
+ "status": "Finished",
+ "message": "Done"
+ }
+ }
+*/
+
+ URI agentUri = null;
+ //String url = protocol + "://" + _ip +"/nitro/v2/config/login";
+ agentUri =
+ new URI("https", null, _ip, DEFAULT_PORT,
+ "/admin/v1/journalcontexts/" + jobId, null, null);
+
+ org.json.JSONObject jsonBody = new JSONObject();
+
+ long startTick = System.currentTimeMillis();
+ while (System.currentTimeMillis() - startTick < _nccCmdTimeout) {
+ result = getHttpRequest(jsonBody.toString(), agentUri, _sessionid);
+ JSONObject response = new JSONObject(result);
+ if(response != null ) {
+ s_logger.debug("Job Status result for ["+jobId + "]:: " + result + " Tick and currentTime :" + System.currentTimeMillis() +" -" + startTick + "job cmd timeout :" +_nccCmdTimeout);
+ String status = response.getJSONObject("journalcontext").getString("status");
+ s_logger.debug("Job Status Progress Status ["+ jobId + "]:: " + status);
+ switch(status) {
+ case "Finished":
+ return status;
+ case "In Progress":
+ break;
+ case "ERROR, ROLLBACK_IN_PROGRESS":
+ break;
+ //return status;
+ case "ERROR, ROLLBACK_COMPLETED":
+ break;
+ //return status;
+ case "ERROR, ROLLBACK_FAILED":
+ break;
+ //return status;
+ }
+ }
+ }
+
+ //s_logger.debug("List of Service Packages in NCC:: " + result);
+ //return result;
+ } catch (URISyntaxException e) {
+ String errMsg = "Could not generate URI for NetScaler ControlCenter";
+ s_logger.error(errMsg, e);
+
+ } catch (Exception e) {
+ //throw new ExecutionException("Failed to log in to NCC device at " + _ip + " due to " + e.getMessage());
+ }
+ return result;
+ }
private synchronized Answer execute(NetScalerImplementNetworkCommand cmd, int numRetries) {
String result = null;
try {
@@ -417,16 +503,35 @@ public class NetScalerControlCenterResource implements ServerResource {
//url: <ip>/cs/cca/networks
agentUri =
new URI("https", null, _ip, DEFAULT_PORT,
- "/cs/cca/networks", null, null);
+ "/cs/cca/v1/networks", null, null);
org.json.JSONObject jsonBody = new JSONObject(cmd.getDetails());
s_logger.debug("Sending Network Implement to NCC:: " + jsonBody);
result = postHttpRequest(jsonBody.toString(), agentUri, _sessionid);
s_logger.debug("Result of Network Implement to NCC:: " + result);
- //return result;
+ result = queryAsyncJob(result);
+ s_logger.debug("Done query async of network implement request :: " + result);
+ return new Answer(cmd, true, "Successfully allocated device");
} catch (URISyntaxException e) {
- String errMsg = "Could not generate URI for Hyper-V agent";
+ String errMsg = "Could not generate URI for NetScaler ControlCenter ";
s_logger.error(errMsg, e);
+ } catch (ExecutionException e) {
+ if(e.getMessage().equalsIgnoreCase("NOTFOUND")) {
+ return new Answer(cmd, true, "Successfully unallocated the device");
+ } else {
+ if (shouldRetry(numRetries)) {
+ s_logger.debug("Retrying the command NetScalerImplementNetworkCommand retry count: " + numRetries );
+ return retry(cmd, numRetries);
+ } else {
+ return new Answer(cmd, false, e.getMessage());
+ }
+ }
} catch (Exception e) {
+ if (shouldRetry(numRetries)) {
+ s_logger.debug("Retrying the command NetScalerImplementNetworkCommand retry count: " + numRetries );
+ return retry(cmd, numRetries);
+ } else {
+ return new Answer(cmd, false, e.getMessage());
+ }
}
return Answer.createUnsupportedCommandAnswer(cmd);
@@ -539,8 +644,16 @@ public class NetScalerControlCenterResource implements ServerResource {
if (loadBalancers == null) {
return new Answer(cmd);
}
+ JSONObject jsonCmd = new JSONObject(cmd);
+ URI agentUri = null;
+ //String url = protocol + "://" + _ip +"/nitro/v2/config/login";
+ agentUri =
+ new URI("https", null, _ip, DEFAULT_PORT,
+ "/nitro/v2/config/" + "login", null, null);
- for (LoadBalancerTO loadBalancer : loadBalancers) {
+ s_logger.debug("LB config cmd: " + jsonCmd.toString());
+ String result = postHttpRequest(jsonCmd.toString(), agentUri, _sessionid);
+ /*for (LoadBalancerTO loadBalancer : loadBalancers) {
String srcIp = loadBalancer.getSrcIp();
int srcPort = loadBalancer.getSrcPort();
String lbProtocol = getNetScalerProtocol(loadBalancer);
@@ -565,305 +678,11 @@ public class NetScalerControlCenterResource implements ServerResource {
}
}
- if (!loadBalancer.isRevoked() && destinationsToAdd) {
-
- // create a load balancing virtual server
- addLBVirtualServer(nsVirtualServerName, srcIp, srcPort, lbAlgorithm, lbProtocol, loadBalancer.getStickinessPolicies(), null);
- if (s_logger.isDebugEnabled()) {
- s_logger.debug("Created load balancing virtual server " + nsVirtualServerName + " on the Netscaler device");
- }
-
- // create a new monitor
- HealthCheckPolicyTO[] healthCheckPolicies = loadBalancer.getHealthCheckPolicies();
- if ((healthCheckPolicies != null) && (healthCheckPolicies.length > 0) && (healthCheckPolicies[0] != null)) {
-
- for (HealthCheckPolicyTO healthCheckPolicyTO : healthCheckPolicies) {
- if (!healthCheckPolicyTO.isRevoked()) {
- addLBMonitor(nsMonitorName, lbProtocol, healthCheckPolicyTO);
- hasMonitor = true;
- } else {
- deleteMonitor = true;
- hasMonitor = false;
- }
- }
-
- }
-
- for (DestinationTO destination : loadBalancer.getDestinations()) {
-
- String nsServerName = generateNSServerName(destination.getDestIp());
- String nsServiceName = generateNSServiceName(destination.getDestIp(), destination.getDestPort());
- if (!destination.isRevoked()) {
- // add a new destination to deployed load balancing rule
-
- // add a new server
- if (!nsServerExists(nsServerName)) {
- com.citrix.netscaler.nitro.resource.config.basic.server nsServer = new com.citrix.netscaler.nitro.resource.config.basic.server();
- nsServer.set_name(nsServerName);
- nsServer.set_ipaddress(destination.getDestIp());
- apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.server.add(_netscalerService, nsServer);
- if ((apiCallResult.errorcode != 0) && (apiCallResult.errorcode != NitroError.NS_RESOURCE_EXISTS)) {
- throw new ExecutionException("Failed to add server " + destination.getDestIp() + " due to" + apiCallResult.message);
- }
- }
-
- // create a new service using the server added
- if (!nsServiceExists(nsServiceName)) {
- com.citrix.netscaler.nitro.resource.config.basic.service newService = new com.citrix.netscaler.nitro.resource.config.basic.service();
- newService.set_name(nsServiceName);
- newService.set_port(destination.getDestPort());
- newService.set_servername(nsServerName);
- newService.set_state("ENABLED");
- if(lbProtocol.equalsIgnoreCase(NetUtils.SSL_PROTO)) {
- newService.set_servicetype(NetUtils.HTTP_PROTO);
- } else {
- newService.set_servicetype(lbProtocol);
- }
-
- apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.service.add(_netscalerService, newService);
- if (apiCallResult.errorcode != 0) {
- throw new ExecutionException("Failed to create service " + nsServiceName + " using server " + nsServerName + " due to" +
- apiCallResult.message);
- }
- }
-
- //bind service to load balancing virtual server
- if (!nsServiceBindingExists(nsVirtualServerName, nsServiceName)) {
- com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding svcBinding =
- new com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding();
- svcBinding.set_name(nsVirtualServerName);
- svcBinding.set_servicename(nsServiceName);
- apiCallResult = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.add(_netscalerService, svcBinding);
-
- if (apiCallResult.errorcode != 0) {
- throw new ExecutionException("Failed to bind service: " + nsServiceName + " to the lb virtual server: " + nsVirtualServerName +
- " on Netscaler device");
- }
- }
-
- // After binding the service to the LB Vserver
- // successfully, bind the created monitor to the
- // service.
- if (hasMonitor) {
- if (!isServiceBoundToMonitor(nsServiceName, nsMonitorName)) {
- bindServiceToMonitor(nsServiceName, nsMonitorName);
- }
- } else {
- // check if any monitor created by CS is already
- // existing, if yes, unbind it from services and
- // delete it.
- if (nsMonitorExist(nsMonitorName)) {
- // unbind the service from the monitor and
- // delete the monitor
- unBindServiceToMonitor(nsServiceName, nsMonitorName);
- deleteMonitor = true;
- }
-
- }
-
- if (sslCert != null && lbProtocol.equalsIgnoreCase(NetUtils.SSL_PROTO)) {
- if (sslCert.isRevoked()) {
- deleteCert = true;
- } else {
-
- // If there is a chain, that should go first to the NS
-
- String previousCertKeyName = null;
-
- if (sslCert.getChain() != null) {
- List<Certificate> chainList = CertificateHelper.parseChain(sslCert.getChain());
- // go from ROOT to intermediate CAs
- for (Certificate intermediateCert : Lists.reverse(chainList)) {
-
- String fingerPrint = CertificateHelper.generateFingerPrint(intermediateCert);
- String intermediateCertKeyName = generateSslCertKeyName(fingerPrint);
- String intermediateCertFileName = intermediateCertKeyName + ".pem";
-
- if (!SSL.isSslCertKeyPresent(_netscalerService, intermediateCertKeyName)) {
- intermediateCert.getEncoded();
- StringWriter textWriter = new StringWriter();
- PEMWriter pemWriter = new PEMWriter(textWriter);
- pemWriter.writeObject(intermediateCert);
- pemWriter.flush();
-
- SSL.uploadCert(_ip, _username, _password, intermediateCertFileName, textWriter.toString().getBytes());
- SSL.createSslCertKey(_netscalerService, intermediateCertFileName, null, intermediateCertKeyName, null);
- }
-
- if (previousCertKeyName != null && !SSL.certLinkExists(_netscalerService, intermediateCertKeyName, previousCertKeyName)) {
- SSL.linkCerts(_netscalerService, intermediateCertKeyName, previousCertKeyName);
- }
-
- previousCertKeyName = intermediateCertKeyName;
- }
- }
-
- String certFilename = generateSslCertName(sslCert.getFingerprint()) + ".pem"; //netscaler uses ".pem" format for "bundle" files
- String keyFilename = generateSslKeyName(sslCert.getFingerprint()) + ".pem"; //netscaler uses ".pem" format for "bundle" files
- String certKeyName = generateSslCertKeyName(sslCert.getFingerprint());
-
- ByteArrayOutputStream certDataStream = new ByteArrayOutputStream();
- certDataStream.write(sslCert.getCert().getBytes());
-
- if (!SSL.isSslCertKeyPresent(_netscalerService, certKeyName)) {
-
- SSL.uploadCert(_ip, _username, _password, certFilename, certDataStream.toByteArray());
- SSL.uploadKey(_ip, _username, _password, keyFilename, sslCert.getKey().getBytes());
- SSL.createSslCertKey(_netscalerService, certFilename, keyFilename, certKeyName, sslCert.getPassword());
- }
-
- if (previousCertKeyName != null && !SSL.certLinkExists(_netscalerService, certKeyName, previousCertKeyName)) {
- SSL.linkCerts(_netscalerService, certKeyName, previousCertKeyName);
- }
-
- SSL.bindCertKeyToVserver(_netscalerService, certKeyName, nsVirtualServerName);
- }
-
- }
-
- if (s_logger.isDebugEnabled()) {
- s_logger.debug("Successfully added LB destination: " + destination.getDestIp() + ":" + destination.getDestPort() + " to load balancer " +
- srcIp + ":" + srcPort);
- }
-
- } else {
- // remove a destination from the deployed load balancing rule
- com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding[] serviceBindings =
- com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.get(_netscalerService, nsVirtualServerName);
- if (serviceBindings != null) {
- for (com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding binding : serviceBindings) {
- if (nsServiceName.equalsIgnoreCase(binding.get_servicename())) {
- // delete the binding
- apiCallResult = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.delete(_netscalerService, binding);
- if (apiCallResult.errorcode != 0) {
- throw new ExecutionException("Failed to delete the binding between the virtual server: " + nsVirtualServerName +
- " and service:" + nsServiceName + " due to" + apiCallResult.message);
- }
-
- // check if service is bound to any other virtual server
- if (!isServiceBoundToVirtualServer(nsServiceName)) {
- // no lb virtual servers are bound to this service so delete it
- apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.service.delete(_netscalerService, nsServiceName);
- if (apiCallResult.errorcode != 0) {
- throw new ExecutionException("Failed to delete service: " + nsServiceName + " due to " + apiCallResult.message);
- }
- }
-
- // delete the server if there is no associated services
- server_service_binding[] services = server_service_binding.get(_netscalerService, nsServerName);
- if ((services == null) || (services.length == 0)) {
- apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.server.delete(_netscalerService, nsServerName);
- if (apiCallResult.errorcode != 0) {
- throw new ExecutionException("Failed to remove server:" + nsServerName + " due to " + apiCallResult.message);
- }
- }
- }
- }
- }
- }
- }
- } else {
- // delete the implemented load balancing rule and its destinations
- lbvserver lbserver = getVirtualServerIfExisits(nsVirtualServerName);
- if (lbserver != null) {
- //unbind the all services associated with this virtual server
- com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding[] serviceBindings =
- com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.get(_netscalerService, nsVirtualServerName);
-
- if (serviceBindings != null) {
- for (com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding binding : serviceBindings) {
- String serviceName = binding.get_servicename();
- apiCallResult = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.delete(_netscalerService, binding);
- if (apiCallResult.errorcode != 0) {
- throw new ExecutionException("Failed to unbind service from the lb virtual server: " + nsVirtualServerName + " due to " +
- apiCallResult.message);
- }
-
- com.citrix.netscaler.nitro.resource.config.basic.service svc =
- com.citrix.netscaler.nitro.resource.config.basic.service.get(_netscalerService, serviceName);
- String nsServerName = svc.get_servername();
-
- // check if service is bound to any other virtual server
- if (!isServiceBoundToVirtualServer(serviceName)) {
- // no lb virtual servers are bound to this service so delete it
- apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.service.delete(_netscalerService, serviceName);
- if (apiCallResult.errorcode != 0) {
- throw new ExecutionException("Failed to delete service: " + serviceName + " due to " + apiCallResult.message);
- }
- }
-
- //delete the server if no more services attached
- server_service_binding[] services = server_service_binding.get(_netscalerService, nsServerName);
- if ((services == null) || (services.length == 0)) {
- apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.server.delete(_netscalerService, nsServerName);
- if (apiCallResult.errorcode != 0) {
- throw new ExecutionException("Failed to remove server:" + nsServerName + " due to " + apiCallResult.message);
- }
- }
- }
- }
- removeLBVirtualServer(nsVirtualServerName);
- deleteMonitor = true;
- deleteCert = true;
- }
- }
- if (deleteMonitor) {
- removeLBMonitor(nsMonitorName);
- }
- if (sslCert != null && deleteCert) {
-
- String certFilename = generateSslCertName(sslCert.getFingerprint()) + ".pem"; //netscaler uses ".pem" format for "bundle" files
- String keyFilename = generateSslKeyName(sslCert.getFingerprint()) + ".pem"; //netscaler uses ".pem" format for "bundle" files
- String certKeyName = generateSslCertKeyName(sslCert.getFingerprint());
-
- // unbind before deleting
- if (nsVirtualServerExists(nsVirtualServerName) &&
- SSL.isSslCertKeyPresent(_netscalerService, certKeyName) &&
- SSL.isBoundToVserver(_netscalerService, certKeyName, nsVirtualServerName)) {
- SSL.unbindCertKeyFromVserver(_netscalerService, certKeyName, nsVirtualServerName);
- }
-
- if (SSL.isSslCertKeyPresent(_netscalerService, certKeyName)) {
-
- SSL.deleteSslCertKey(_netscalerService, certKeyName);
- SSL.deleteCertFile(_ip, _username, _password, certFilename);
- SSL.deleteKeyFile(_ip, _username, _password, keyFilename);
- }
-
- /*
- * Check and delete intermediate certs:
- * we can delete an intermediate cert if no other
- * cert references it as the athority
- */
-
- if (sslCert.getChain() != null) {
- List<Certificate> chainList = CertificateHelper.parseChain(sslCert.getChain());
- //go from intermediate CAs to ROOT
- for (Certificate intermediateCert : chainList) {
-
- String fingerPrint = CertificateHelper.generateFingerPrint(intermediateCert);
- String intermediateCertKeyName = generateSslCertKeyName(fingerPrint);
- String intermediateCertFileName = intermediateCertKeyName + ".pem";
-
- if (SSL.isSslCertKeyPresent(_netscalerService, intermediateCertKeyName) &&
- !SSL.isCaforCerts(_netscalerService, intermediateCertKeyName)) {
- SSL.deleteSslCertKey(_netscalerService, intermediateCertKeyName);
- SSL.deleteCertFile(_ip, _username, _password, intermediateCertFileName);
- } else {
- break;// if this cert has another certificate as a child then stop at this point because we need the whole chain
- }
-
- }
- }
- }
-
- }
-
if (s_logger.isInfoEnabled()) {
s_logger.info("Successfully executed resource LoadBalancerConfigCommand: " + _gson.toJson(cmd));
- }
+ }*/
- saveConfiguration();
+ //saveConfiguration();
return new Answer(cmd);
} catch (ExecutionException e) {
s_logger.error("Failed to execute LoadBalancerConfigCommand due to ", e);
@@ -3641,13 +3460,23 @@ public class NetScalerControlCenterResource implements ServerResource {
}
private boolean shouldRetry(int numRetries) {
+ //JSONObject jsonResponse = null;
try {
if (numRetries > 0) {
login();
+ /*if (response == null) {
+ throw new ConfigurationException("No Response Received from the NetScalerControlCenter Device");
+ } else {
+ jsonResponse = new JSONObject(response);
+ org.json.JSONArray loginResponse = jsonResponse.getJSONArray("login");
+ _sessionid = jsonResponse.getJSONArray("login").getJSONObject(0).getString("sessionid");
+ }*/
return true;
}
} catch (Exception e) {
- s_logger.error("Failed to log in to Netscaler device at " + _ip + " due to " + e.getMessage());
+ s_logger.error("Failed to log in to Netscaler ControlCenter device at " + _ip + " due to " + e.getMessage());
+ return false;
+ //throw new ConfigurationException("No Response Received from the NetScalerControlCenter Device");
}
return false;
}
@@ -3766,8 +3595,22 @@ public class NetScalerControlCenterResource implements ServerResource {
return null;
}
+ private boolean refreshNCCConnection() {
+ boolean ret = false;
+ try {
+ login();
+ return true;
+ } catch (ExecutionException ex) {
+ s_logger.error("Login to NCC failed", ex);
+ }
+ return ret;
+ }
+
@Override
public PingCommand getCurrentStatus(long id) {
+ /*if (!refreshNCCConnection()) {
+ return null;
+ }*/
return new PingCommand(Host.Type.NetScalerControlCenter, id);
}
@@ -3881,7 +3724,7 @@ public class NetScalerControlCenterResource implements ServerResource {
return httpClient;
}
- public static String getHttpRequest(final String jsonCmd, final URI agentUri, String sessionID) {
+ public static String getHttpRequest(final String jsonCmd, final URI agentUri, String sessionID) throws ExecutionException {
// Using Apache's HttpClient for HTTP POST
// Java-only approach discussed at on StackOverflow concludes with
// comment to use Apache HttpClient
@@ -3923,7 +3766,8 @@ public class NetScalerControlCenterResource implements ServerResource {
} else if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
String errMsg = "Failed send to " + agentUri.toString() + " : HTTP error code : " + response.getStatusLine().getStatusCode();
s_logger.error(errMsg);
- return null;
+ throw new ExecutionException("UNAUTHORIZED");
+ //return null;
} else {
result = EntityUtils.toString(response.getEntity());
String logResult = cleanPassword(StringEscapeUtils.unescapeJava(result));
@@ -3941,7 +3785,7 @@ public class NetScalerControlCenterResource implements ServerResource {
return result;
}
- public static String postHttpRequest(final String jsonCmd, final URI agentUri, String sessionID) {
+ public static String postHttpRequest(final String jsonCmd, final URI agentUri, String sessionID) throws ExecutionException {
// Using Apache's HttpClient for HTTP POST
// Java-only approach discussed at on StackOverflow concludes with
// comment to use Apache HttpClient
@@ -3954,7 +3798,7 @@ public class NetScalerControlCenterResource implements ServerResource {
// Create request
HttpClient httpClient = getHttpClient();
-/* TrustStrategy easyStrategy = new TrustStrategy() {
+ TrustStrategy easyStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
@@ -3977,7 +3821,7 @@ public class NetScalerControlCenterResource implements ServerResource {
} catch (KeyStoreException e) {
s_logger.error("failed to initialize http client " + e.getMessage());
}
-*/
+
String result = null;
// TODO: are there timeout settings and worker thread settings to tweak?
@@ -3998,15 +3842,25 @@ public class NetScalerControlCenterResource implements ServerResource {
// Unsupported commands will not route.
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
String errMsg = "Failed to send : HTTP error code : " + response.getStatusLine().getStatusCode();
- s_logger.error(errMsg);
+ throw new ExecutionException("NOT_FOUND");
+ /*s_logger.error(errMsg);
String unsupportMsg = "Unsupported command " + agentUri.getPath() + ". Are you sure you got the right type of" + " server?";
Answer ans = new UnsupportedAnswer(null, unsupportMsg);
- s_logger.error(ans);
- result = s_gson.toJson(new Answer[] {ans});
- } else if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
+ s_logger.error(ans);*/
+ //result = s_gson.toJson(new Answer[] {ans});
+ } else if ((response.getStatusLine().getStatusCode() != HttpStatus.SC_OK ) && (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED )) {
String errMsg = "Failed send to " + agentUri.toString() + " : HTTP error code : " + response.getStatusLine().getStatusCode();
s_logger.error(errMsg);
- return null;
+ throw new ExecutionException("UNAUTHORIZED");
+ //return null;
+ } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
+ //Successfully created the resource in the NCC, Now get the Job ID and send to the response
+ // make login request and store new session id
+ throw new ExecutionException("UNAUTHORIZED");
+ } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
+ //Successfully created the resource in the NCC, Now get the Job ID and send to the response
+ result = response.getFirstHeader("Job_id").getValue();
+ //"jobid : " +
} else {
result = EntityUtils.toString(response.getEntity());
String logResult = cleanPassword(StringEscapeUtils.unescapeJava(result));
diff --git a/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java b/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java
index f417283..85eda6b 100644
--- a/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java
+++ b/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java
@@ -53,6 +53,7 @@ import com.cloud.dc.DataCenterIpAddressVO;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.Pod;
import com.cloud.dc.Vlan.VlanType;
+import com.cloud.dc.VlanVO;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.HostPodDao;
import com.cloud.dc.dao.VlanDao;
@@ -63,6 +64,7 @@ import com.cloud.exception.ResourceUnavailableException;
import com.cloud.host.DetailVO;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
+import com.cloud.host.Host.Type;
import com.cloud.host.dao.HostDao;
import com.cloud.host.dao.HostDetailsDao;
import com.cloud.network.Network.Provider;
@@ -101,6 +103,7 @@ import com.cloud.network.rules.FirewallRule.Purpose;
import com.cloud.network.rules.StaticNat;
import com.cloud.network.rules.StaticNatImpl;
import com.cloud.network.rules.dao.PortForwardingRulesDao;
+import com.cloud.offering.NetworkOffering;
import com.cloud.offerings.NetworkOfferingVO;
import com.cloud.offerings.dao.NetworkOfferingDao;
import com.cloud.resource.ResourceManager;
@@ -864,6 +867,21 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
return nic;
}
+ private boolean isNccServiceProvider(Network network) {
+ NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId());
+ if(networkOffering.getServicePackage() != null ) {
+ return true;
+ }
+ else {
+ return false;
+ }
+ }
+
+ public HostVO getNetScalerControlCenterForNetwork(Network guestConfig) {
+ long zoneId = guestConfig.getDataCenterId();
+ return _hostDao.findByTypeNameAndZoneId(zoneId, "NetscalerControlCenter", Type.NetScalerControlCenter);
+ }
+
@Override
public boolean applyLoadBalancerRules(Network network, List<LoadBalancingRule> loadBalancingRules) throws ResourceUnavailableException {
// Find the external load balancer in this zone
@@ -874,13 +892,21 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
return true;
}
- ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network);
- if (lbDeviceVO == null) {
- s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning");
- return true;
+ HostVO externalLoadBalancer = null;
+
+ if(isNccServiceProvider(network)) {
+ externalLoadBalancer = getNetScalerControlCenterForNetwork(network);
+ } else {
+ ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network);
+ if (lbDeviceVO == null) {
+ s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning");
+ return true;
+ } else {
+ externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId());
+ }
}
- HostVO externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId());
+
boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network);
@@ -900,6 +926,13 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
String algorithm = rule.getAlgorithm();
String uuid = rule.getUuid();
String srcIp = rule.getSourceIp().addr();
+ String srcIpVlan = null;
+ //IpAddress ipAddress = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getVlanId();
+ Long vlanid = _networkModel.getPublicIpAddress(rule.getSourceIp().addr(), network.getDataCenterId()).getVlanId();
+ if(vlanid != null ) {
+ VlanVO publicVlan = _vlanDao.findById(vlanid);
+ srcIpVlan = publicVlan.getVlanTag();
+ }
int srcPort = rule.getSourcePortStart();
List<LbDestination> destinations = rule.getDestinations();
@@ -921,6 +954,8 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
LoadBalancerTO loadBalancer =
new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(),
rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol());
+ loadBalancer.setNetworkId(network.getId());
+ loadBalancer.setSrcIpVlan(srcIpVlan);
if (rule.isAutoScaleConfig()) {
loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup());
}
diff --git a/server/src/com/cloud/network/IpAddressManagerImpl.java b/server/src/com/cloud/network/IpAddressManagerImpl.java
index 8068421..d950cc4 100644
--- a/server/src/com/cloud/network/IpAddressManagerImpl.java
+++ b/server/src/com/cloud/network/IpAddressManagerImpl.java
@@ -29,8 +29,11 @@ import java.util.UUID;
import javax.inject.Inject;
+import org.apache.log4j.Logger;
+
import org.apache.cloudstack.acl.ControlledEntity.ACLType;
import org.apache.cloudstack.acl.SecurityChecker.AccessType;
+import org.apache.cloudstack.api.response.AcquirePodIpCmdResponse;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
import org.apache.cloudstack.framework.config.ConfigKey;
@@ -40,7 +43,6 @@ import org.apache.cloudstack.region.PortableIp;
import org.apache.cloudstack.region.PortableIpDao;
import org.apache.cloudstack.region.PortableIpVO;
import org.apache.cloudstack.region.Region;
-import org.apache.log4j.Logger;
import com.cloud.agent.AgentManager;
import com.cloud.alert.AlertManager;
@@ -51,6 +53,8 @@ import com.cloud.dc.AccountVlanMapVO;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenter.NetworkType;
import com.cloud.dc.DomainVlanMapVO;
+import com.cloud.dc.DataCenterIpAddressVO;
+import com.cloud.dc.HostPodVO;
import com.cloud.dc.Pod;
import com.cloud.dc.PodVlanMapVO;
import com.cloud.dc.Vlan;
@@ -58,8 +62,10 @@ import com.cloud.dc.Vlan.VlanType;
import com.cloud.dc.VlanVO;
import com.cloud.dc.dao.AccountVlanMapDao;
import com.cloud.dc.dao.DataCenterDao;
+import com.cloud.dc.dao.DataCenterIpAddressDao;
import com.cloud.dc.dao.DataCenterVnetDao;
import com.cloud.dc.dao.DomainVlanMapDao;
+import com.cloud.dc.dao.HostPodDao;
import com.cloud.dc.dao.PodVlanMapDao;
import com.cloud.dc.dao.VlanDao;
import com.cloud.deploy.DeployDestination;
@@ -279,6 +285,10 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
PortableIpDao _portableIpDao;
@Inject
VpcDao _vpcDao;
+ @Inject
+ DataCenterIpAddressDao _privateIPAddressDao;
+ HostPodDao _hpDao;
+
SearchBuilder<IPAddressVO> AssignIpAddressSearch;
SearchBuilder<IPAddressVO> AssignIpAddressFromPodVlanSearch;
@@ -401,7 +411,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
SearchBuilder<PodVlanMapVO> podVlanMapSB = _podVlanMapDao.createSearchBuilder();
podVlanMapSB.and("podId", podVlanMapSB.entity().getPodId(), Op.EQ);
AssignIpAddressFromPodVlanSearch.join("podVlanMapSB", podVlanMapSB, podVlanMapSB.entity().getVlanDbId(), AssignIpAddressFromPodVlanSearch.entity().getVlanId(),
- JoinType.INNER);
+ JoinType.INNER);
AssignIpAddressFromPodVlanSearch.join("vlan", podVlanSearch, podVlanSearch.entity().getId(), AssignIpAddressFromPodVlanSearch.entity().getVlanId(), JoinType.INNER);
AssignIpAddressFromPodVlanSearch.done();
@@ -417,7 +427,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
}
private IpAddress allocateIP(Account ipOwner, boolean isSystem, long zoneId) throws ResourceAllocationException, InsufficientAddressCapacityException,
- ConcurrentOperationException {
+ ConcurrentOperationException {
Account caller = CallContext.current().getCallingAccount();
long callerUserId = CallContext.current().getCallingUserId();
// check permissions
@@ -492,7 +502,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
@Override
public boolean applyRules(List<? extends FirewallRule> rules, FirewallRule.Purpose purpose, NetworkRuleApplier applier, boolean continueOnError)
- throws ResourceUnavailableException {
+ throws ResourceUnavailableException {
if (rules == null || rules.size() == 0) {
s_logger.debug("There are no rules to forward to the network elements");
return true;
@@ -641,21 +651,21 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
return Transaction.execute(new TransactionCallback<Boolean>() {
@Override
public Boolean doInTransaction(TransactionStatus status) {
- portableIpLock.lock(5);
- IPAddressVO ip = _ipAddressDao.findById(addrId);
+ portableIpLock.lock(5);
+ IPAddressVO ip = _ipAddressDao.findById(addrId);
- // unassign portable IP
- PortableIpVO portableIp = _portableIpDao.findByIpAddress(ip.getAddress().addr());
- _portableIpDao.unassignIpAddress(portableIp.getId());
+ // unassign portable IP
+ PortableIpVO portableIp = _portableIpDao.findByIpAddress(ip.getAddress().addr());
+ _portableIpDao.unassignIpAddress(portableIp.getId());
- // removed the provisioned vlan
- VlanVO vlan = _vlanDao.findById(ip.getVlanId());
- _vlanDao.remove(vlan.getId());
+ // removed the provisioned vlan
+ VlanVO vlan = _vlanDao.findById(ip.getVlanId());
+ _vlanDao.remove(vlan.getId());
- // remove the provisioned public ip address
- _ipAddressDao.remove(ip.getId());
+ // remove the provisioned public ip address
+ _ipAddressDao.remove(ip.getId());
- return true;
+ return true;
}
});
} finally {
@@ -665,20 +675,20 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
@Override
public PublicIp assignPublicIpAddress(long dcId, Long podId, Account owner, VlanType type, Long networkId, String requestedIp, boolean isSystem)
- throws InsufficientAddressCapacityException {
+ throws InsufficientAddressCapacityException {
return fetchNewPublicIp(dcId, podId, null, owner, type, networkId, false, true, requestedIp, isSystem, null, null);
}
@Override
public PublicIp assignPublicIpAddressFromVlans(long dcId, Long podId, Account owner, VlanType type, List<Long> vlanDbIds, Long networkId, String requestedIp, boolean isSystem)
- throws InsufficientAddressCapacityException {
+ throws InsufficientAddressCapacityException {
return fetchNewPublicIp(dcId, podId, vlanDbIds, owner, type, networkId, false, true, requestedIp, isSystem, null, null);
}
@DB
public PublicIp fetchNewPublicIp(final long dcId, final Long podId, final List<Long> vlanDbIds, final Account owner, final VlanType vlanUse, final Long guestNetworkId,
final boolean sourceNat, final boolean assign, final String requestedIp, final boolean isSystem, final Long vpcId, final Boolean displayIp)
- throws InsufficientAddressCapacityException {
+ throws InsufficientAddressCapacityException {
IPAddressVO addr = Transaction.execute(new TransactionCallbackWithException<IPAddressVO, InsufficientAddressCapacityException>() {
@Override
public IPAddressVO doInTransaction(TransactionStatus status) throws InsufficientAddressCapacityException {
@@ -709,11 +719,6 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
dedicatedVlanDbIds.add(map.getVlanDbId());
}
}
- List<DomainVlanMapVO> domainMaps = _domainVlanMapDao.listDomainVlanMapsByDomain(owner.getDomainId());
- for (DomainVlanMapVO map : domainMaps) {
- if (vlanDbIds == null || vlanDbIds.contains(map.getVlanDbId()))
- dedicatedVlanDbIds.add(map.getVlanDbId());
- }
List<VlanVO> nonDedicatedVlans = _vlanDao.listZoneWideNonDedicatedVlans(dcId);
for (VlanVO nonDedicatedVlan : nonDedicatedVlans) {
if (vlanDbIds == null || vlanDbIds.contains(nonDedicatedVlan.getId()))
@@ -722,10 +727,10 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
if (dedicatedVlanDbIds != null && !dedicatedVlanDbIds.isEmpty()) {
fetchFromDedicatedRange = true;
sc.setParameters("vlanId", dedicatedVlanDbIds.toArray());
- errorMessage.append(", vlanId id=" + Arrays.toString(dedicatedVlanDbIds.toArray()));
+ errorMessage.append(", vlanId id=" + Arrays.toString(dedicatedVlanDbIds.toArray()));
} else if (nonDedicatedVlanDbIds != null && !nonDedicatedVlanDbIds.isEmpty()) {
sc.setParameters("vlanId", nonDedicatedVlanDbIds.toArray());
- errorMessage.append(", vlanId id=" + Arrays.toString(nonDedicatedVlanDbIds.toArray()));
+ errorMessage.append(", vlanId id=" + Arrays.toString(nonDedicatedVlanDbIds.toArray()));
} else {
if (podId != null) {
InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException("Insufficient address capacity", Pod.class, podId);
@@ -763,7 +768,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
if (useSystemIps && nonDedicatedVlanDbIds != null && !nonDedicatedVlanDbIds.isEmpty()) {
fetchFromDedicatedRange = false;
sc.setParameters("vlanId", nonDedicatedVlanDbIds.toArray());
- errorMessage.append(", vlanId id=" + Arrays.toString(nonDedicatedVlanDbIds.toArray()));
+ errorMessage.append(", vlanId id=" + Arrays.toString(nonDedicatedVlanDbIds.toArray()));
addrs = _ipAddressDao.lockRows(sc, filter, true);
}
}
@@ -781,7 +786,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
throw ex;
}
- assert (addrs.size() == 1) : "Return size is incorrect: " + addrs.size();
+ assert(addrs.size() == 1) : "Return size is incorrect: " + addrs.size();
if (!fetchFromDedicatedRange && VlanType.VirtualNetwork.equals(vlanUse)) {
// Check that the maximum number of public IPs for the given accountId will not be exceeded
@@ -835,29 +840,30 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
- Account owner = _accountMgr.getAccount(addr.getAllocatedToAccountId());
- synchronized (this) {
- if (_ipAddressDao.lockRow(addr.getId(),true) != null) {
- IPAddressVO userIp = _ipAddressDao.findById(addr.getId());
- if (userIp.getState() == IpAddress.State.Allocating || addr.getState() == IpAddress.State.Free) {
- addr.setState(IpAddress.State.Allocated);
- _ipAddressDao.update(addr.getId(), addr);
- // Save usage event
- if (owner.getAccountId() != Account.ACCOUNT_ID_SYSTEM) {
- VlanVO vlan = _vlanDao.findById(addr.getVlanId());
- String guestType = vlan.getVlanType().toString();
- if (!isIpDedicated(addr)) {
- UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_IP_ASSIGN, owner.getId(), addr.getDataCenterId(), addr.getId(), addr.getAddress().toString(),
- addr.isSourceNat(), guestType, addr.getSystem(), addr.getClass().getName(), addr.getUuid());
- }
- if (updateIpResourceCount(addr)) {
- _resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.public_ip);
+ Account owner = _accountMgr.getAccount(addr.getAllocatedToAccountId());
+ synchronized (this) {
+ if (_ipAddressDao.lockRow(addr.getId(), true) != null) {
+ IPAddressVO userIp = _ipAddressDao.findById(addr.getId());
+ if (userIp.getState() == IpAddress.State.Allocating || addr.getState() == IpAddress.State.Free) {
+ addr.setState(IpAddress.State.Allocated);
+ _ipAddressDao.update(addr.getId(), addr);
+ // Save usage event
+ if (owner.getAccountId() != Account.ACCOUNT_ID_SYSTEM) {
+ VlanVO vlan = _vlanDao.findById(addr.getVlanId());
+ String guestType = vlan.getVlanType().toString();
+ if (!isIpDedicated(addr)) {
+ UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_IP_ASSIGN, owner.getId(), addr.getDataCenterId(), addr.getId(),
+ addr.getAddress().toString(),
+ addr.isSourceNat(), guestType, addr.getSystem(), addr.getClass().getName(), addr.getUuid());
+ }
+ if (updateIpResourceCount(addr)) {
+ _resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.public_ip);
+ }
}
}
}
}
}
- }
});
}
@@ -870,8 +876,8 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
@Override
public PublicIp assignSourceNatIpAddressToGuestNetwork(Account owner, Network guestNetwork) throws InsufficientAddressCapacityException, ConcurrentOperationException {
- assert (guestNetwork.getTrafficType() != null) : "You're asking for a source nat but your network "
- + "can't participate in source nat. What do you have to say for yourself?";
+ assert(guestNetwork.getTrafficType() != null) : "You're asking for a source nat but your network "
+ + "can't participate in source nat. What do you have to say for yourself?";
long dcId = guestNetwork.getDataCenterId();
IPAddressVO sourceNatIp = getExistingSourceNatInNetwork(owner.getId(), guestNetwork.getId());
@@ -900,15 +906,15 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
public PublicIp doInTransaction(TransactionStatus status) throws InsufficientAddressCapacityException {
Account owner = _accountDao.acquireInLockTable(ownerId);
- if (owner == null) {
- // this ownerId comes from owner or type Account. See the class "AccountVO" and the annotations in that class
- // to get the table name and field name that is queried to fill this ownerid.
- ConcurrentOperationException ex = new ConcurrentOperationException("Unable to lock account");
- throw ex;
- }
- if (s_logger.isDebugEnabled()) {
- s_logger.debug("lock account " + ownerId + " is acquired");
- }
+ if (owner == null) {
+ // this ownerId comes from owner or type Account. See the class "AccountVO" and the annotations in that class
+ // to get the table name and field name that is queried to fill this ownerid.
+ ConcurrentOperationException ex = new ConcurrentOperationException("Unable to lock account");
+ throw ex;
+ }
+ if (s_logger.isDebugEnabled()) {
+ s_logger.debug("lock account " + ownerId + " is acquired");
+ }
boolean displayIp = true;
if (guestNtwkId != null) {
Network ntwk = _networksDao.findById(guestNtwkId);
@@ -919,10 +925,10 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
}
PublicIp ip = fetchNewPublicIp(dcId, null, null, owner, VlanType.VirtualNetwork, guestNtwkId, isSourceNat, false, null, false, vpcId, displayIp);
- IPAddressVO publicIp = ip.ip();
+ IPAddressVO publicIp = ip.ip();
- markPublicIpAsAllocated(publicIp);
- _ipAddressDao.update(publicIp.getId(), publicIp);
+ markPublicIpAsAllocated(publicIp);
+ _ipAddressDao.update(publicIp.getId(), publicIp);
return ip;
}
@@ -974,7 +980,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
// but still be associated with the account. Its up to caller of this function to decide when to invoke IPAssociation
@Override
public boolean applyIpAssociations(Network network, boolean postApplyRules, boolean continueOnError, List<? extends PublicIpAddress> publicIps)
- throws ResourceUnavailableException {
+ throws ResourceUnavailableException {
boolean success = true;
Map<PublicIpAddress, Set<Service>> ipToServices = _networkModel.getIpToServices(publicIps, postApplyRules, true);
@@ -1018,9 +1024,72 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
@DB
@Override
+ public AcquirePodIpCmdResponse allocatePodIp(Long zoneId, String cidr) throws ConcurrentOperationException, ResourceAllocationException {
+
+ DataCenter zone = _entityMgr.findById(DataCenter.class, zoneId);
+ Account caller = CallContext.current().getCallingAccount();
+ if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
+ ResourceAllocationException ex = new ResourceAllocationException("Cannot perform this operation, " + "Zone is currently disabled" + "zoneId=" + zone.getUuid(),
+ ResourceType.network);
+ throw ex;
+ }
+
+ DataCenterIpAddressVO vo = null;
+ if (cidr != null) {
+ List<HostPodVO> pod_list = _hpDao.listAllPodsByCidr(zoneId, cidr);
+ if (pod_list.get(0) == null)
+ throw new ResourceAllocationException("No sush pod exists", ResourceType.network);
+ vo = _privateIPAddressDao.takeIpAddress(zoneId, pod_list.get(0).getId(), 0, caller.getId() + "");
+ if (vo.getIpAddress() == null)
+ throw new ResourceAllocationException("Unable to allocate IP from this Pod", ResourceType.network);
+ } else
+ vo = _privateIPAddressDao.takeDataCenterIpAddress(zoneId, caller.getId() + "");
+
+ HostPodVO pod_vo = _hpDao.findById(vo.getPodId());
+ AcquirePodIpCmdResponse ret = new AcquirePodIpCmdResponse();
+ ret.setCidrAddress(pod_vo.getCidrAddress());
+ ret.setGateway(pod_vo.getGateway());
+ ret.setInstanceId(vo.getInstanceId());
+ ret.setIpAddress(vo.getIpAddress());
+ ret.setMacAddress(vo.getMacAddress());
+ ret.setPodId(vo.getPodId());
+ ret.setId(vo.getId());
+
+ return ret;
+ }
+
+ @DB
+ @Override
+ public void releasePodIp(Long id) throws CloudRuntimeException {
+
+ // Verify input parameters
+ DataCenterIpAddressVO ipVO = _privateIPAddressDao.findById(id);
+ if (ipVO == null) {
+ throw new CloudRuntimeException("Unable to find ip address by id:" + id);
+ }
+
+ if (ipVO.getTakenAt() == null) {
+ s_logger.debug("Ip Address with id= " + id + " is not allocated, so do nothing.");
+ throw new CloudRuntimeException("Ip Address with id= " + id + " is not allocated, so do nothing.");
+ }
+ // Verify permission
+ DataCenter zone = _entityMgr.findById(DataCenter.class, ipVO.getDataCenterId());
+ Account caller = CallContext.current().getCallingAccount();
+ if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
+ throw new CloudRuntimeException("Cannot perform this operation, " + "Zone is currently disabled" + "zoneId=" + ipVO.getDataCenterId());
+ }
+ try {
+ _privateIPAddressDao.releasePodIpAddress(id);
+ } catch (Exception e) {
+ new CloudRuntimeException(e.getMessage());
+ }
+ }
+
+ @DB
+ @Override
public IpAddress allocateIp(final Account ipOwner, final boolean isSystem, Account caller, long callerUserId, final DataCenter zone, final Boolean displayIp)
throws ConcurrentOperationException,
- ResourceAllocationException, InsufficientAddressCapacityException {
+ ResourceAllocationException, InsufficientAddressCapacityException {
final VlanType vlanType = VlanType.VirtualNetwork;
final boolean assign = false;
@@ -1054,16 +1123,17 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
public PublicIp doInTransaction(TransactionStatus status) throws InsufficientAddressCapacityException {
PublicIp ip = fetchNewPublicIp(zone.getId(), null, null, ipOwner, vlanType, null, false, assign, null, isSystem, null, displayIp);
- if (ip == null) {
+ if (ip == null) {
InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException("Unable to find available public IP addresses", DataCenter.class, zone
.getId());
- ex.addProxyObject(ApiDBUtils.findZoneById(zone.getId()).getUuid());
- throw ex;
- }
- CallContext.current().setEventDetails("Ip Id: " + ip.getId());
- Ip ipAddress = ip.getAddress();
+ ex.addProxyObject(ApiDBUtils.findZoneById(zone.getId()).getUuid());
+ throw ex;
+
+ }
+ CallContext.current().setEventDetails("Ip Id: " + ip.getId());
+ Ip ipAddress = ip.getAddress();
- s_logger.debug("Got " + ipAddress + " to assign for account " + ipOwner.getId() + " in zone " + zone.getId());
+ s_logger.debug("Got " + ipAddress + " to assign for account " + ipOwner.getId() + " in zone " + zone.getId());
return ip;
}
@@ -1098,40 +1168,40 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
public IPAddressVO doInTransaction(TransactionStatus status) throws InsufficientAddressCapacityException {
PortableIpVO allocatedPortableIp;
- List<PortableIpVO> portableIpVOs = _portableIpDao.listByRegionIdAndState(1, PortableIp.State.Free);
- if (portableIpVOs == null || portableIpVOs.isEmpty()) {
+ List<PortableIpVO> portableIpVOs = _portableIpDao.listByRegionIdAndState(1, PortableIp.State.Free);
+ if (portableIpVOs == null || portableIpVOs.isEmpty()) {
InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException("Unable to find available portable IP addresses", Region.class,
new Long(1));
- throw ex;
- }
+ throw ex;
+ }
- // allocate first portable IP to the user
- allocatedPortableIp = portableIpVOs.get(0);
- allocatedPortableIp.setAllocatedTime(new Date());
- allocatedPortableIp.setAllocatedToAccountId(ipOwner.getAccountId());
- allocatedPortableIp.setAllocatedInDomainId(ipOwner.getDomainId());
- allocatedPortableIp.setState(PortableIp.State.Allocated);
- _portableIpDao.update(allocatedPortableIp.getId(), allocatedPortableIp);
-
- // To make portable IP available as a zone level resource we need to emulate portable IP's (which are
- // provisioned at region level) as public IP provisioned in a zone. user_ip_address and vlan combo give the
- // identity of a public IP in zone. Create entry for portable ip in these tables.
-
- // provision portable IP range VLAN into the zone
- long physicalNetworkId = _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(dcId, TrafficType.Public).getId();
- Network network = _networkModel.getSystemNetworkByZoneAndTrafficType(dcId, TrafficType.Public);
- String range = allocatedPortableIp.getAddress() + "-" + allocatedPortableIp.getAddress();
+ // allocate first portable IP to the user
+ allocatedPortableIp = portableIpVOs.get(0);
+ allocatedPortableIp.setAllocatedTime(new Date());
+ allocatedPortableIp.setAllocatedToAccountId(ipOwner.getAccountId());
+ allocatedPortableIp.setAllocatedInDomainId(ipOwner.getDomainId());
+ allocatedPortableIp.setState(PortableIp.State.Allocated);
+ _portableIpDao.update(allocatedPortableIp.getId(), allocatedPortableIp);
+
+ // To make portable IP available as a zone level resource we need to emulate portable IP's (which are
+ // provisioned at region level) as public IP provisioned in a zone. user_ip_address and vlan combo give the
+ // identity of a public IP in zone. Create entry for portable ip in these tables.
+
+ // provision portable IP range VLAN into the zone
+ long physicalNetworkId = _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(dcId, TrafficType.Public).getId();
+ Network network = _networkModel.getSystemNetworkByZoneAndTrafficType(dcId, TrafficType.Public);
+ String range = allocatedPortableIp.getAddress() + "-" + allocatedPortableIp.getAddress();
VlanVO vlan = new VlanVO(VlanType.VirtualNetwork, allocatedPortableIp.getVlan(), allocatedPortableIp.getGateway(), allocatedPortableIp.getNetmask(), dcId,
range, network.getId(), physicalNetworkId, null, null, null);
- vlan = _vlanDao.persist(vlan);
+ vlan = _vlanDao.persist(vlan);
- // provision the portable IP in to user_ip_address table
+ // provision the portable IP in to user_ip_address table
IPAddressVO ipaddr = new IPAddressVO(new Ip(allocatedPortableIp.getAddress()), dcId, networkId, vpcID, physicalNetworkId, network.getId(), vlan.getId(), true);
- ipaddr.setState(State.Allocated);
- ipaddr.setAllocatedTime(new Date());
- ipaddr.setAllocatedInDomainId(ipOwner.getDomainId());
- ipaddr.setAllocatedToAccountId(ipOwner.getId());
- ipaddr = _ipAddressDao.persist(ipaddr);
+ ipaddr.setState(State.Allocated);
+ ipaddr.setAllocatedTime(new Date());
+ ipaddr.setAllocatedInDomainId(ipOwner.getDomainId());
+ ipaddr.setAllocatedToAccountId(ipOwner.getId());
+ ipaddr = _ipAddressDao.persist(ipaddr);
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_PORTABLE_IP_ASSIGN, ipaddr.getId(), ipaddr.getDataCenterId(), ipaddr.getId(),
ipaddr.getAddress().toString(), ipaddr.isSourceNat(), null, ipaddr.getSystem(), ipaddr.getClass().getName(), ipaddr.getUuid());
@@ -1168,7 +1238,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
}
}
- assert (sourceNatIp != null) : "How do we get a bunch of ip addresses but none of them are source nat? " + "account=" + ownerId + "; networkId=" + networkId;
+ assert(sourceNatIp != null) : "How do we get a bunch of ip addresses but none of them are source nat? " + "account=" + ownerId + "; networkId=" + networkId;
}
return sourceNatIp;
@@ -1177,7 +1247,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
@DB
@Override
public IPAddressVO associateIPToGuestNetwork(long ipId, long networkId, boolean releaseOnFailure) throws ResourceAllocationException, ResourceUnavailableException,
- InsufficientAddressCapacityException, ConcurrentOperationException {
+ InsufficientAddressCapacityException, ConcurrentOperationException {
Account caller = CallContext.current().getCallingAccount();
Account owner = null;
@@ -1196,7 +1266,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
network);
} else {
throw new InvalidParameterValueException("IP can be associated with guest network of 'shared' type only if "
- + "network services Source Nat, Static Nat, Port Forwarding, Load balancing, firewall are enabled in the network");
+ + "network services Source Nat, Static Nat, Port Forwarding, Load balancing, firewall are enabled in the network");
}
}
} else {
@@ -1307,7 +1377,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
|| _networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.StaticNat)
|| _networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Firewall)
|| _networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.PortForwarding) || _networkModel.areServicesSupportedByNetworkOffering(
- networkOfferingId, Service.Lb))) {
+ networkOfferingId, Service.Lb))) {
return true;
}
return false;
@@ -1315,14 +1385,14 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
@Override
public IPAddressVO associatePortableIPToGuestNetwork(long ipAddrId, long networkId, boolean releaseOnFailure) throws ResourceAllocationException, ResourceUnavailableException,
- InsufficientAddressCapacityException, ConcurrentOperationException {
+ InsufficientAddressCapacityException, ConcurrentOperationException {
return associateIPToGuestNetwork(ipAddrId, networkId, releaseOnFailure);
}
@DB
@Override
public IPAddressVO disassociatePortableIPToGuestNetwork(long ipId, long networkId) throws ResourceAllocationException, ResourceUnavailableException,
- InsufficientAddressCapacityException, ConcurrentOperationException {
+ InsufficientAddressCapacityException, ConcurrentOperationException {
Account caller = CallContext.current().getCallingAccount();
Account owner = null;
@@ -1346,7 +1416,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
DataCenter zone = _entityMgr.findById(DataCenter.class, network.getDataCenterId());
if (zone.getNetworkType() == NetworkType.Advanced) {
if (network.getGuestType() == Network.GuestType.Shared) {
- assert (isSharedNetworkOfferingWithServices(network.getNetworkOfferingId()));
+ assert(isSharedNetworkOfferingWithServices(network.getNetworkOfferingId()));
_accountMgr.checkAccess(CallContext.current().getCallingAccount(), AccessType.UseEntry, false,
network);
}
@@ -1430,7 +1500,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
@DB
@Override
public void transferPortableIP(final long ipAddrId, long currentNetworkId, long newNetworkId) throws ResourceAllocationException, ResourceUnavailableException,
- InsufficientAddressCapacityException, ConcurrentOperationException {
+ InsufficientAddressCapacityException, ConcurrentOperationException {
Network srcNetwork = _networksDao.findById(currentNetworkId);
if (srcNetwork == null) {
@@ -1447,7 +1517,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
throw new InvalidParameterValueException("Invalid portable ip address id is given");
}
- assert (isPortableIpTransferableFromNetwork(ipAddrId, currentNetworkId));
+ assert(isPortableIpTransferableFromNetwork(ipAddrId, currentNetworkId));
// disassociate portable IP with current network/VPC network
if (srcNetwork.getVpcId() != null) {
@@ -1462,19 +1532,19 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
- long physicalNetworkId = _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(dstNetwork.getDataCenterId(), TrafficType.Public).getId();
- long publicNetworkId = _networkModel.getSystemNetworkByZoneAndTrafficType(dstNetwork.getDataCenterId(), TrafficType.Public).getId();
-
- ip.setDataCenterId(dstNetwork.getDataCenterId());
- ip.setPhysicalNetworkId(physicalNetworkId);
- ip.setSourceNetworkId(publicNetworkId);
- _ipAddressDao.update(ipAddrId, ip);
-
- VlanVO vlan = _vlanDao.findById(ip.getVlanId());
- vlan.setPhysicalNetworkId(physicalNetworkId);
- vlan.setNetworkId(publicNetworkId);
- vlan.setDataCenterId(dstNetwork.getDataCenterId());
- _vlanDao.update(ip.getVlanId(), vlan);
+ long physicalNetworkId = _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(dstNetwork.getDataCenterId(), TrafficType.Public).getId();
+ long publicNetworkId = _networkModel.getSystemNetworkByZoneAndTrafficType(dstNetwork.getDataCenterId(), TrafficType.Public).getId();
+
+ ip.setDataCenterId(dstNetwork.getDataCenterId());
+ ip.setPhysicalNetworkId(physicalNetworkId);
+ ip.setSourceNetworkId(publicNetworkId);
+ _ipAddressDao.update(ipAddrId, ip);
+
+ VlanVO vlan = _vlanDao.findById(ip.getVlanId());
+ vlan.setPhysicalNetworkId(physicalNetworkId);
+ vlan.setNetworkId(publicNetworkId);
+ vlan.setDataCenterId(dstNetwork.getDataCenterId());
+ _vlanDao.update(ip.getVlanId(), vlan);
}
});
}
@@ -1483,22 +1553,24 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
associatePortableIPToGuestNetwork(ipAddrId, newNetworkId, false);
Transaction.execute(new TransactionCallbackNoReturn() {
+
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
- if (dstNetwork.getVpcId() != null) {
- ip.setVpcId(dstNetwork.getVpcId());
- } else {
- ip.setVpcId(null);
- }
+ if (dstNetwork.getVpcId() != null) {
+ ip.setVpcId(dstNetwork.getVpcId());
+ } else {
+ ip.setVpcId(null);
+ }
- _ipAddressDao.update(ipAddrId, ip);
+ _ipAddressDao.update(ipAddrId, ip);
}
+
});
// trigger an action event for the transfer of portable IP across the networks, so that external entities
// monitoring for this event can initiate the route advertisement for the availability of IP from the zoe
ActionEventUtils.onActionEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, Domain.ROOT_DOMAIN, EventTypes.EVENT_PORTABLE_IP_TRANSFER,
- "Portable IP associated is transferred from network " + currentNetworkId + " to " + newNetworkId);
+ "Portable IP associated is transferred from network " + currentNetworkId + " to " + newNetworkId);
}
protected List<? extends Network> getIsolatedNetworksWithSourceNATOwnedByAccountInZone(long zoneId, Account owner) {
@@ -1525,30 +1597,30 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
boolean createNetwork = false;
Network guestNetwork = guestNetworkFinal;
- if (guestNetwork == null) {
- List<? extends Network> networks = getIsolatedNetworksWithSourceNATOwnedByAccountInZone(zoneId, owner);
- if (networks.size() == 0) {
- createNetwork = true;
- } else if (networks.size() == 1) {
- guestNetwork = networks.get(0);
- } else {
- throw new InvalidParameterValueException("Error, more than 1 Guest Isolated Networks with SourceNAT "
- + "service enabled found for this account, cannot assosiate the IP range, please provide the network ID");
- }
- }
+ if (guestNetwork == null) {
+ List<? extends Network> networks = getIsolatedNetworksWithSourceNATOwnedByAccountInZone(zoneId, owner);
+ if (networks.size() == 0) {
+ createNetwork = true;
+ } else if (networks.size() == 1) {
+ guestNetwork = networks.get(0);
+ } else {
+ throw new InvalidParameterValueException("Error, more than 1 Guest Isolated Networks with SourceNAT "
+ + "service enabled found for this account, cannot assosiate the IP range, please provide the network ID");
+ }
+ }
- // create new Virtual network (Isolated with SourceNAT) for the user if it doesn't exist
- List<NetworkOfferingVO> requiredOfferings = _networkOfferingDao.listByAvailability(Availability.Required, false);
- if (requiredOfferings.size() < 1) {
+ // create new Virtual network (Isolated with SourceNAT) for the user if it doesn't exist
+ List<NetworkOfferingVO> requiredOfferings = _networkOfferingDao.listByAvailability(Availability.Required, false);
+ if (requiredOfferings.size() < 1) {
throw new CloudRuntimeException("Unable to find network offering with availability=" + Availability.Required
+ " to automatically create the network as part of createVlanIpRange");
- }
- if (createNetwork) {
- if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) {
- long physicalNetworkId = _networkModel.findPhysicalNetworkId(zoneId, requiredOfferings.get(0).getTags(), requiredOfferings.get(0).getTrafficType());
- // Validate physical network
- PhysicalNetwork physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
- if (physicalNetwork == null) {
+ }
+ if (createNetwork) {
+ if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) {
+ long physicalNetworkId = _networkModel.findPhysicalNetworkId(zoneId, requiredOfferings.get(0).getTags(), requiredOfferings.get(0).getTrafficType());
+ // Validate physical network
+ PhysicalNetwork physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
+ if (physicalNetwork == null) {
throw new InvalidParameterValueException("Unable to find physical network with id: " + physicalNetworkId + " and tag: "
+ requiredOfferings.get(0).getTags());
}
@@ -1557,44 +1629,44 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
+ " as a part of createVlanIpRange process");
guestNetwork = _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName()
+ "-network", null, null, null, null, owner, null, physicalNetwork, zoneId, ACLType.Account, null, null, null, null, true, null);
- if (guestNetwork == null) {
- s_logger.warn("Failed to create default Virtual network for the account " + accountId + "in zone " + zoneId);
+ if (guestNetwork == null) {
+ s_logger.warn("Failed to create default Virtual network for the account " + accountId + "in zone " + zoneId);
throw new CloudRuntimeException("Failed to create a Guest Isolated Networks with SourceNAT "
+ "service enabled as a part of createVlanIpRange, for the account " + accountId + "in zone " + zoneId);
- }
- } else {
- throw new CloudRuntimeException("Required network offering id=" + requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled);
- }
- }
+ }
+ } else {
+ throw new CloudRuntimeException("Required network offering id=" + requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled);
+ }
+ }
- // Check if there is a source nat ip address for this account; if not - we have to allocate one
- boolean allocateSourceNat = false;
- List<IPAddressVO> sourceNat = _ipAddressDao.listByAssociatedNetwork(guestNetwork.getId(), true);
- if (sourceNat.isEmpty()) {
- allocateSourceNat = true;
- }
+ // Check if there is a source nat ip address for this account; if not - we have to allocate one
+ boolean allocateSourceNat = false;
+ List<IPAddressVO> sourceNat = _ipAddressDao.listByAssociatedNetwork(guestNetwork.getId(), true);
+ if (sourceNat.isEmpty()) {
+ allocateSourceNat = true;
+ }
- // update all ips with a network id, mark them as allocated and update resourceCount/usage
- List<IPAddressVO> ips = _ipAddressDao.listByVlanId(vlanId);
- boolean isSourceNatAllocated = false;
- for (IPAddressVO addr : ips) {
- if (addr.getState() != State.Allocated) {
- if (!isSourceNatAllocated && allocateSourceNat) {
- addr.setSourceNat(true);
- isSourceNatAllocated = true;
- } else {
- addr.setSourceNat(false);
- }
- addr.setAssociatedWithNetworkId(guestNetwork.getId());
- addr.setVpcId(guestNetwork.getVpcId());
- addr.setAllocatedTime(new Date());
- addr.setAllocatedInDomainId(owner.getDomainId());
- addr.setAllocatedToAccountId(owner.getId());
- addr.setSystem(false);
- addr.setState(IpAddress.State.Allocating);
- markPublicIpAsAllocated(addr);
- }
- }
+ // update all ips with a network id, mark them as allocated and update resourceCount/usage
+ List<IPAddressVO> ips = _ipAddressDao.listByVlanId(vlanId);
+ boolean isSourceNatAllocated = false;
+ for (IPAddressVO addr : ips) {
+ if (addr.getState() != State.Allocated) {
+ if (!isSourceNatAllocated && allocateSourceNat) {
+ addr.setSourceNat(true);
+ isSourceNatAllocated = true;
+ } else {
+ addr.setSourceNat(false);
+ }
+ addr.setAssociatedWithNetworkId(guestNetwork.getId());
+ addr.setVpcId(guestNetwork.getVpcId());
+ addr.setAllocatedTime(new Date());
+ addr.setAllocatedInDomainId(owner.getDomainId());
+ addr.setAllocatedToAccountId(owner.getId());
+ addr.setSystem(false);
+ addr.setState(IpAddress.State.Allocating);
+ markPublicIpAsAllocated(addr);
+ }
+ }
return new Ternary<Boolean, List<NetworkOfferingVO>, Network>(createNetwork, requiredOfferings, guestNetwork);
}
});
@@ -1629,7 +1701,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
} catch (Exception ex) {
s_logger.warn("Failed to implement network " + guestNetwork + " elements and resources as a part of" + " network provision due to ", ex);
CloudRuntimeException e = new CloudRuntimeException("Failed to implement network (with specified id)"
- + " elements and resources as a part of network provision for persistent network");
+ + " elements and resources as a part of network provision for persistent network");
e.addProxyObject(guestNetwork.getUuid(), "networkId");
throw e;
}
@@ -1652,20 +1724,20 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
@Override
public IPAddressVO doInTransaction(TransactionStatus status) {
if (updateIpResourceCount(ip)) {
- _resourceLimitMgr.decrementResourceCount(_ipAddressDao.findById(addrId).getAllocatedToAccountId(), ResourceType.public_ip);
- }
+ _resourceLimitMgr.decrementResourceCount(_ipAddressDao.findById(addrId).getAllocatedToAccountId(), ResourceType.public_ip);
+ }
- // Save usage event
- if (ip.getAllocatedToAccountId() != null && ip.getAllocatedToAccountId() != Account.ACCOUNT_ID_SYSTEM) {
- VlanVO vlan = _vlanDao.findById(ip.getVlanId());
+ // Save usage event
+ if (ip.getAllocatedToAccountId() != null && ip.getAllocatedToAccountId() != Account.ACCOUNT_ID_SYSTEM) {
+ VlanVO vlan = _vlanDao.findById(ip.getVlanId());
- String guestType = vlan.getVlanType().toString();
- if (!isIpDedicated(ip)) {
- String eventType = ip.isPortable() ? EventTypes.EVENT_PORTABLE_IP_RELEASE : EventTypes.EVENT_NET_IP_RELEASE;
+ String guestType = vlan.getVlanType().toString();
+ if (!isIpDedicated(ip)) {
+ String eventType = ip.isPortable() ? EventTypes.EVENT_PORTABLE_IP_RELEASE : EventTypes.EVENT_NET_IP_RELEASE;
UsageEventUtils.publishUsageEvent(eventType, ip.getAllocatedToAccountId(), ip.getDataCenterId(), addrId, ip.getAddress().addr(), ip.isSourceNat(),
guestType, ip.getSystem(), ip.getClass().getName(), ip.getUuid());
- }
- }
+ }
+ }
return _ipAddressDao.markAsUnavailable(addrId);
}
@@ -1880,80 +1952,77 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
Transaction.execute(new TransactionCallbackWithExceptionNoReturn<InsufficientAddressCapacityException>() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) throws InsufficientAddressCapacityException {
- //This method allocates direct ip for the Shared network in Advance zones
- boolean ipv4 = false;
-
- if (network.getGateway() != null) {
- if (nic.getIPv4Address() == null) {
- ipv4 = true;
- PublicIp ip = null;
-
- //Get ip address from the placeholder and don't allocate a new one
- if (requestedIpv4 != null && vm.getType() == VirtualMachine.Type.DomainRouter) {
- Nic placeholderNic = _networkModel.getPlaceholderNicForRouter(network, null);
- if (placeholderNic != null) {
- IPAddressVO userIp = _ipAddressDao.findByIpAndSourceNetworkId(network.getId(), placeholderNic.getIPv4Address());
- ip = PublicIp.createFromAddrAndVlan(userIp, _vlanDao.findById(userIp.getVlanId()));
- s_logger.debug("Nic got an ip address " + placeholderNic.getIPv4Address() + " stored in placeholder nic for the network " + network);
- }
- }
+ //This method allocates direct ip for the Shared network in Advance zones
+ boolean ipv4 = false;
- if (ip == null) {
- ip = assignPublicIpAddress(dc.getId(), null, vm.getOwner(), VlanType.DirectAttached, network.getId(), requestedIpv4, false);
- }
+ if (network.getGateway() != null) {
+ if (nic.getIp4Address() == null) {
+ ipv4 = true;
+ PublicIp ip = null;
+
+ //Get ip address from the placeholder and don't allocate a new one
+ if (requestedIpv4 != null && vm.getType() == VirtualMachine.Type.DomainRouter) {
+ Nic placeholderNic = _networkModel.getPlaceholderNicForRouter(network, null);
+ if (placeholderNic != null) {
+ IPAddressVO userIp = _ipAddressDao.findByIpAndSourceNetworkId(network.getId(), placeholderNic.getIp4Address());
+ ip = PublicIp.createFromAddrAndVlan(userIp, _vlanDao.findById(userIp.getVlanId()));
+ s_logger.debug("Nic got an ip address " + placeholderNic.getIp4Address() + " stored in placeholder nic for the network " + network);
+ }
+ }
- nic.setIPv4Address(ip.getAddress().toString());
- nic.setIPv4Gateway(ip.getGateway());
- nic.setIPv4Netmask(ip.getNetmask());
- nic.setIsolationUri(IsolationType.Vlan.toUri(ip.getVlanTag()));
- //nic.setBroadcastType(BroadcastDomainType.Vlan);
- //nic.setBroadcastUri(BroadcastDomainType.Vlan.toUri(ip.getVlanTag()));
- nic.setBroadcastType(network.getBroadcastDomainType());
+ if (ip == null) {
+ ip = assignPublicIpAddress(dc.getId(), null, vm.getOwner(), VlanType.DirectAttached, network.getId(), requestedIpv4, false);
+ }
+
+ nic.setIp4Address(ip.getAddress().toString());
+ nic.setGateway(ip.getGateway());
+ nic.setNetmask(ip.getNetmask());
+ nic.setIsolationUri(IsolationType.Vlan.toUri(ip.getVlanTag()));
+ //nic.setBroadcastType(BroadcastDomainType.Vlan);
+ //nic.setBroadcastUri(BroadcastDomainType.Vlan.toUri(ip.getVlanTag()));
+ nic.setBroadcastType(network.getBroadcastDomainType());
if (network.getBroadcastUri() != null)
- nic.setBroadcastUri(network.getBroadcastUri());
+ nic.setBroadcastUri(network.getBroadcastUri());
else
nic.setBroadcastUri(BroadcastDomainType.Vlan.toUri(ip.getVlanTag()));
- nic.setFormat(AddressFormat.Ip4);
- nic.setReservationId(String.valueOf(ip.getVlanTag()));
- nic.setMacAddress(ip.getMacAddress());
- }
- nic.setIPv4Dns1(dc.getDns1());
- nic.setIPv4Dns2(dc.getDns2());
- }
-
- //FIXME - get ipv6 address from the placeholder if it's stored there
- if (network.getIp6Gateway() != null) {
- if (nic.getIPv6Address() == null) {
- UserIpv6Address ip = _ipv6Mgr.assignDirectIp6Address(dc.getId(), vm.getOwner(), network.getId(), requestedIpv6);
- Vlan vlan = _vlanDao.findById(ip.getVlanId());
- nic.setIPv6Address(ip.getAddress().toString());
- nic.setIPv6Gateway(vlan.getIp6Gateway());
- nic.setIPv6Cidr(vlan.getIp6Cidr());
- if (ipv4) {
- nic.setFormat(AddressFormat.DualStack);
- } else {
- nic.setIsolationUri(IsolationType.Vlan.toUri(vlan.getVlanTag()));
- nic.setBroadcastType(BroadcastDomainType.Vlan);
- nic.setBroadcastUri(BroadcastDomainType.Vlan.toUri(vlan.getVlanTag()));
- nic.setFormat(AddressFormat.Ip6);
- nic.setReservationId(String.valueOf(vlan.getVlanTag()));
- nic.setMacAddress(ip.getMacAddress());
+ nic.setFormat(AddressFormat.Ip4);
+ nic.setReservationId(String.valueOf(ip.getVlanTag()));
+ nic.setMacAddress(ip.getMacAddress());
+ }
+ nic.setDns1(dc.getDns1());
+ nic.setDns2(dc.getDns2());
+ }
+
+ //FIXME - get ipv6 address from the placeholder if it's stored there
+ if (network.getIp6Gateway() != null) {
+ if (nic.getIp6Address() == null) {
+ UserIpv6Address ip = _ipv6Mgr.assignDirectIp6Address(dc.getId(), vm.getOwner(), network.getId(), requestedIpv6);
+ Vlan vlan = _vlanDao.findById(ip.getVlanId());
+ nic.setIp6Address(ip.getAddress().toString());
+ nic.setIp6Gateway(vlan.getIp6Gateway());
+ nic.setIp6Cidr(vlan.getIp6Cidr());
+ if (ipv4) {
+ nic.setFormat(AddressFormat.DualStack);
+ } else {
+ nic.setIsolationUri(IsolationType.Vlan.toUri(vlan.getVlanTag()));
+ nic.setBroadcastType(BroadcastDomainType.Vlan);
+ nic.setBroadcastUri(BroadcastDomainType.Vlan.toUri(vlan.getVlanTag()));
+ nic.setFormat(AddressFormat.Ip6);
+ nic.setReservationId(String.valueOf(vlan.getVlanTag()));
+ nic.setMacAddress(ip.getMacAddress());
+ }
+ }
+ nic.setIp6Dns1(dc.getIp6Dns1());
+ nic.setIp6Dns2(dc.getIp6Dns2());
}
- }
- nic.setIPv6Dns1(dc.getIp6Dns1());
- nic.setIPv6Dns2(dc.getIp6Dns2());
- }
}
});
}
-
-
-
@Override
@DB
public void allocateNicValues(final NicProfile nic, final DataCenter dc, final VirtualMachineProfile vm, final Network network, final String requestedIpv4,
- final String requestedIpv6) throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException {
+ final String requestedIpv6) throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException {
Transaction.execute(new TransactionCallbackWithExceptionNoReturn<InsufficientAddressCapacityException>() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) throws InsufficientAddressCapacityException {
@@ -1967,7 +2036,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
//Get ip address from the placeholder and don't allocate a new one
if (requestedIpv4 != null && vm.getType() == VirtualMachine.Type.DomainRouter) {
- s_logger.debug("There won't be nic assignment for VR id " + vm.getId() +" in this network " + network);
+ s_logger.debug("There won't be nic assignment for VR id " + vm.getId() + " in this network " + network);
}
@@ -1978,7 +2047,7 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage
List<VlanVO> vlan = _vlanDao.listVlansByNetworkId(network.getId());
//TODO: get vlan tag for the ntwork
- if (vlan != null && ! vlan.isEmpty()) {
+ if (vlan != null && !vlan.isEmpty()) {
nic.setIsolationUri(IsolationType.Vlan.toUri(vlan.get(0).getVlanTag()));
}
diff --git a/server/test/com/cloud/vpc/MockNetworkManagerImpl.java b/server/test/com/cloud/vpc/MockNetworkManagerImpl.java
index d61378b..75c181f 100644
--- a/server/test/com/cloud/vpc/MockNetworkManagerImpl.java
+++ b/server/test/com/cloud/vpc/MockNetworkManagerImpl.java
@@ -907,8 +907,30 @@ public class MockNetworkManagerImpl extends ManagerBase implements NetworkOrches
}
@Override
+<<<<<<< db052a96b18391ae5f972960d1f496f5396b8684
public List<? extends NicSecondaryIp> listVmNicSecondaryIps(ListNicsCmd listNicsCmd) {
return null;
+=======
+ public AcquirePodIpCmdResponse allocatePodIp(Account ipOwner, long zoneId, String cidr) throws ResourceAllocationException, ConcurrentOperationException {
+
+ Account caller = CallContext.current().getCallingAccount();
+ long callerUserId = CallContext.current().getCallingUserId();
+ DataCenter zone = _entityMgr.findById(DataCenter.class, zoneId);
+
+ if (zone == null)
+ throw new InvalidParameterValueException("Invalid zone Id is Null");
+ if (_accountMgr.checkAccessAndSpecifyAuthority(caller, zoneId) != zoneId)
+ throw new InvalidParameterValueException("Caller does not have permission for this Zone" + "(" + zoneId + ")");
+ if (s_logger.isDebugEnabled())
+ s_logger.debug("Associate IP address called by the user " + callerUserId + " account " + ipOwner.getId());
+ return _ipAddrMgr.allocatePodIp(zoneId, cidr);
+ }
+
+ @Override
+ public boolean releasePodIp(ReleasePodIpCmdByAdmin ip) throws CloudRuntimeException {
+ _ipAddrMgr.releasePodIp(ip.getId());
+ return true;
+>>>>>>> CLOUDSTACK-8672 : NCC Integration with CloudStack.
}
}
--
To stop receiving notification emails like this one, please contact
"commits@cloudstack.apache.org" <co...@cloudstack.apache.org>.