diff --git a/api/src/com/cloud/agent/api/CheckS2SVpnConnectionsAnswer.java b/api/src/com/cloud/agent/api/CheckS2SVpnConnectionsAnswer.java new file mode 100644 index 00000000000..b9e9a6638ab --- /dev/null +++ b/api/src/com/cloud/agent/api/CheckS2SVpnConnectionsAnswer.java @@ -0,0 +1,55 @@ +package com.cloud.agent.api; + +import java.util.HashMap; +import java.util.Map; + +public class CheckS2SVpnConnectionsAnswer extends Answer { + Map ipToConnected; + Map ipToDetail; + String details; + + protected CheckS2SVpnConnectionsAnswer() { + ipToConnected = new HashMap(); + ipToDetail = new HashMap(); + } + + public CheckS2SVpnConnectionsAnswer(CheckS2SVpnConnectionsCommand cmd, boolean result, String details) { + super(cmd, result, details); + ipToConnected = new HashMap(); + ipToDetail = new HashMap(); + this.details = details; + if (result) { + parseDetails(details); + } + } + + protected void parseDetails(String details) { + String[] lines = details.split("&"); + for (String line : lines) { + String[] words = line.split(":"); + if (words.length != 3) { + //Not something we can parse + return; + } + String ip = words[0]; + boolean connected = words[1].equals("0"); + String detail = words[2]; + ipToConnected.put(ip, connected); + ipToDetail.put(ip, detail); + } + } + + public boolean isConnected(String ip) { + if (this.getResult()) { + return ipToConnected.get(ip); + } + return false; + } + + public String getDetail(String ip) { + if (this.getResult()) { + return ipToDetail.get(ip); + } + return null; + } +} diff --git a/api/src/com/cloud/agent/api/CheckS2SVpnConnectionsCommand.java b/api/src/com/cloud/agent/api/CheckS2SVpnConnectionsCommand.java new file mode 100644 index 00000000000..9401b47be65 --- /dev/null +++ b/api/src/com/cloud/agent/api/CheckS2SVpnConnectionsCommand.java @@ -0,0 +1,23 @@ +package com.cloud.agent.api; + +import java.util.List; + +import com.cloud.agent.api.routing.NetworkElementCommand; + +public class CheckS2SVpnConnectionsCommand extends NetworkElementCommand { + List vpnIps; + + @Override + public boolean executeInSequence() { + return true; + } + + public CheckS2SVpnConnectionsCommand(List vpnIps) { + super(); + this.vpnIps = vpnIps; + } + + public List getVpnIps() { + return vpnIps; + } +} diff --git a/api/src/com/cloud/api/commands/CreateAutoScaleVmGroupCmd.java b/api/src/com/cloud/api/commands/CreateAutoScaleVmGroupCmd.java index ece0f03e4e9..f9f5710774f 100644 --- a/api/src/com/cloud/api/commands/CreateAutoScaleVmGroupCmd.java +++ b/api/src/com/cloud/api/commands/CreateAutoScaleVmGroupCmd.java @@ -120,7 +120,7 @@ public class CreateAutoScaleVmGroupCmd extends BaseAsyncCreateCmd { public long getEntityOwnerId() { LoadBalancer lb = _entityMgr.findById(LoadBalancer.class, getLbRuleId()); if (lb == null) { - throw new InvalidParameterValueException("Unable to find loadbalancer from lbRuleId=" + getLbRuleId()); + throw new InvalidParameterValueException("Unable to find loadbalancer by lbRuleId", null); } return lb.getAccountId(); } diff --git a/api/src/com/cloud/api/commands/CreateAutoScaleVmProfileCmd.java b/api/src/com/cloud/api/commands/CreateAutoScaleVmProfileCmd.java index 6d45463a30c..d49cfbf39f0 100644 --- a/api/src/com/cloud/api/commands/CreateAutoScaleVmProfileCmd.java +++ b/api/src/com/cloud/api/commands/CreateAutoScaleVmProfileCmd.java @@ -156,7 +156,7 @@ public class CreateAutoScaleVmProfileCmd extends BaseAsyncCreateCmd { for (String keyValue : keyValues) { // keyValue == "hostid=123" String[] keyAndValue = keyValue.split("="); // keyValue = hostid, 123 if (keyAndValue.length != 2) { - throw new InvalidParameterValueException("Invalid parameter in otherDeployParam : " + keyValue); + throw new InvalidParameterValueException("Invalid parameter in otherDeployParam : " + keyValue, null); } String paramName = keyAndValue[0]; // hostid String paramValue = keyAndValue[1]; // 123 diff --git a/api/src/com/cloud/api/commands/DisableAutoScaleVmGroupCmd.java b/api/src/com/cloud/api/commands/DisableAutoScaleVmGroupCmd.java index 02bbad3b3ee..086cfd29044 100644 --- a/api/src/com/cloud/api/commands/DisableAutoScaleVmGroupCmd.java +++ b/api/src/com/cloud/api/commands/DisableAutoScaleVmGroupCmd.java @@ -20,17 +20,19 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; import com.cloud.api.ApiConstants; +import com.cloud.api.BaseAsyncCmd; import com.cloud.api.BaseCmd; import com.cloud.api.IdentityMapper; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; import com.cloud.api.response.AutoScaleVmGroupResponse; +import com.cloud.event.EventTypes; import com.cloud.network.as.AutoScaleVmGroup; import com.cloud.user.Account; @Implementation(description = "Disables an AutoScale Vm Group", responseObject = AutoScaleVmGroupResponse.class) -public class DisableAutoScaleVmGroupCmd extends BaseCmd { +public class DisableAutoScaleVmGroupCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DisableAutoScaleVmGroupCmd.class.getName()); private static final String s_name = "disableautoscalevmGroupresponse"; @@ -38,8 +40,8 @@ public class DisableAutoScaleVmGroupCmd extends BaseCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "account") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, description = "Account id") + @IdentityMapper(entityTableName="autoscale_vmgroups") + @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the autoscale group") private Long id; // /////////////////////////////////////////////////// @@ -81,4 +83,13 @@ public class DisableAutoScaleVmGroupCmd extends BaseCmd { // tracked } + @Override + public String getEventType() { + return EventTypes.EVENT_AUTOSCALEVMGROUP_DISABLE; + } + + @Override + public String getEventDescription() { + return "Disabling AutoScale Vm Group. Vm Group Id: " + getId(); + } } diff --git a/api/src/com/cloud/api/commands/EnableAutoScaleVmGroupCmd.java b/api/src/com/cloud/api/commands/EnableAutoScaleVmGroupCmd.java index 4969df80b05..a7de00a859c 100644 --- a/api/src/com/cloud/api/commands/EnableAutoScaleVmGroupCmd.java +++ b/api/src/com/cloud/api/commands/EnableAutoScaleVmGroupCmd.java @@ -20,17 +20,19 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; import com.cloud.api.ApiConstants; +import com.cloud.api.BaseAsyncCmd; import com.cloud.api.BaseCmd; import com.cloud.api.IdentityMapper; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; import com.cloud.api.response.AutoScaleVmGroupResponse; +import com.cloud.event.EventTypes; import com.cloud.network.as.AutoScaleVmGroup; import com.cloud.user.Account; @Implementation(description = "Enables an AutoScale Vm Group", responseObject = AutoScaleVmGroupResponse.class) -public class EnableAutoScaleVmGroupCmd extends BaseCmd { +public class EnableAutoScaleVmGroupCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(EnableAutoScaleVmGroupCmd.class.getName()); private static final String s_name = "enableautoscalevmGroupresponse"; @@ -81,4 +83,14 @@ public class EnableAutoScaleVmGroupCmd extends BaseCmd { // tracked } + @Override + public String getEventType() { + return EventTypes.EVENT_AUTOSCALEVMGROUP_ENABLE; + } + + @Override + public String getEventDescription() { + return "Enabling AutoScale Vm Group. Vm Group Id: "+getId(); + } + } diff --git a/api/src/com/cloud/api/commands/ListAutoScaleVmGroupsCmd.java b/api/src/com/cloud/api/commands/ListAutoScaleVmGroupsCmd.java index 8103dedabab..cdb01dee321 100644 --- a/api/src/com/cloud/api/commands/ListAutoScaleVmGroupsCmd.java +++ b/api/src/com/cloud/api/commands/ListAutoScaleVmGroupsCmd.java @@ -92,7 +92,7 @@ public class ListAutoScaleVmGroupsCmd extends BaseListProjectAndAccountResources @Override public void execute() { if(id != null && (loadBalancerId != null || profileId != null || policyId != null)) - throw new InvalidParameterValueException("When id is specified other parameters need not be specified"); + throw new InvalidParameterValueException("When id is specified other parameters need not be specified", null); List autoScaleGroups = _autoScaleService.listAutoScaleVmGroups(this); ListResponse response = new ListResponse(); diff --git a/api/src/com/cloud/api/commands/UpdateAutoScalePolicyCmd.java b/api/src/com/cloud/api/commands/UpdateAutoScalePolicyCmd.java index 68c8ccb4b20..6c1ccbb83f4 100644 --- a/api/src/com/cloud/api/commands/UpdateAutoScalePolicyCmd.java +++ b/api/src/com/cloud/api/commands/UpdateAutoScalePolicyCmd.java @@ -99,7 +99,7 @@ public class UpdateAutoScalePolicyCmd extends BaseAsyncCmd { @Override public String getEventDescription() { - return "Updating Auto Scale Policy."; + return "Updating Auto Scale Policy. Policy Id: " + getId(); } @Override diff --git a/api/src/com/cloud/api/commands/UpdateAutoScaleVmGroupCmd.java b/api/src/com/cloud/api/commands/UpdateAutoScaleVmGroupCmd.java index df9a11ed636..a2a938fa0a6 100644 --- a/api/src/com/cloud/api/commands/UpdateAutoScaleVmGroupCmd.java +++ b/api/src/com/cloud/api/commands/UpdateAutoScaleVmGroupCmd.java @@ -113,12 +113,12 @@ public class UpdateAutoScaleVmGroupCmd extends BaseAsyncCmd { @Override public String getEventType() { - return "Update AutoScale Vm Group"; + return EventTypes.EVENT_AUTOSCALEVMGROUP_UPDATE; } @Override public String getEventDescription() { - return EventTypes.EVENT_AUTOSCALEVMGROUP_UPDATE; + return "Updating AutoScale Vm Group. Vm Group Id: "+getId(); } @Override diff --git a/api/src/com/cloud/api/commands/UpdateAutoScaleVmProfileCmd.java b/api/src/com/cloud/api/commands/UpdateAutoScaleVmProfileCmd.java index 3c6461d6c27..b6f32872544 100644 --- a/api/src/com/cloud/api/commands/UpdateAutoScaleVmProfileCmd.java +++ b/api/src/com/cloud/api/commands/UpdateAutoScaleVmProfileCmd.java @@ -116,7 +116,7 @@ public class UpdateAutoScaleVmProfileCmd extends BaseAsyncCmd { @Override public String getEventDescription() { - return "Updating AutoScale Vm Profile"; + return "Updating AutoScale Vm Profile. Vm Profile Id: " + getId(); } @Override diff --git a/awsapi.log.2012-07-25.gz b/awsapi.log.2012-07-25.gz new file mode 100644 index 00000000000..02fd067aac2 Binary files /dev/null and b/awsapi.log.2012-07-25.gz differ diff --git a/awsapi/src/com/cloud/stack/models/ApiConstants.java b/awsapi/src/com/cloud/stack/models/ApiConstants.java index 127a7fe7c08..38b630bb538 100644 --- a/awsapi/src/com/cloud/stack/models/ApiConstants.java +++ b/awsapi/src/com/cloud/stack/models/ApiConstants.java @@ -116,7 +116,7 @@ public class ApiConstants { public static final String DELETE_SSH_KEY_PAIR = "deleteSSHKeyPair"; public static final String DELETE_SSH_KEY_PAIR_RESPONSE = "deletesshkeypairresponse"; public static final String DELETE_TAGS = "deleteTags"; - public static final String DELETE_TAGS_RESPONSE = "deleteTagsresponse"; + public static final String DELETE_TAGS_RESPONSE = "deletetagsresponse"; public static final String DELETE_TEMPLATE = "deleteTemplate"; public static final String DELETE_TEMPLATE_RESPONSE = "deletetemplateresponse"; public static final String DELETE_VOLUME = "deleteVolume"; diff --git a/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java b/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java index 370477ff4c2..f09f23b65e7 100755 --- a/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java +++ b/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java @@ -38,6 +38,8 @@ import com.cloud.agent.api.Answer; import com.cloud.agent.api.BumpUpPriorityCommand; import com.cloud.agent.api.CheckRouterAnswer; import com.cloud.agent.api.CheckRouterCommand; +import com.cloud.agent.api.CheckS2SVpnConnectionsAnswer; +import com.cloud.agent.api.CheckS2SVpnConnectionsCommand; import com.cloud.agent.api.Command; import com.cloud.agent.api.GetDomRVersionAnswer; import com.cloud.agent.api.GetDomRVersionCmd; @@ -135,6 +137,8 @@ public class VirtualRoutingResource implements Manager { return execute((GetDomRVersionCmd)cmd); } else if (cmd instanceof Site2SiteVpnCfgCommand) { return execute((Site2SiteVpnCfgCommand)cmd); + } else if (cmd instanceof CheckS2SVpnConnectionsCommand) { + return execute((CheckS2SVpnConnectionsCommand)cmd); } else { return Answer.createUnsupportedCommandAnswer(cmd); @@ -506,6 +510,21 @@ public class VirtualRoutingResource implements Manager { return command.execute(); } + private CheckS2SVpnConnectionsAnswer execute(CheckS2SVpnConnectionsCommand cmd) { + final String routerIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); + + String args = ""; + for (String ip : cmd.getVpnIps()) { + args += " " + ip; + } + + final String result = routerProxyWithParser("checkbatchs2svpn.sh", routerIP, args); + if (result == null || result.isEmpty()) { + return new CheckS2SVpnConnectionsAnswer(cmd, false, "CheckS2SVpnConneciontsCommand failed"); + } + return new CheckS2SVpnConnectionsAnswer(cmd, true, result); + } + protected Answer execute(CheckRouterCommand cmd) { final String routerPrivateIPAddress = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); diff --git a/core/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java b/core/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java index 31cbf10c428..cf088c186c7 100755 --- a/core/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java +++ b/core/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java @@ -54,6 +54,8 @@ import com.cloud.agent.api.CheckOnHostAnswer; import com.cloud.agent.api.CheckOnHostCommand; import com.cloud.agent.api.CheckRouterAnswer; import com.cloud.agent.api.CheckRouterCommand; +import com.cloud.agent.api.CheckS2SVpnConnectionsAnswer; +import com.cloud.agent.api.CheckS2SVpnConnectionsCommand; import com.cloud.agent.api.CheckVirtualMachineAnswer; import com.cloud.agent.api.CheckVirtualMachineCommand; import com.cloud.agent.api.Command; @@ -443,6 +445,8 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa answer = execute((SetPortForwardingRulesVpcCommand) cmd); } else if (clz == Site2SiteVpnCfgCommand.class) { answer = execute((Site2SiteVpnCfgCommand) cmd); + } else if (clz == CheckS2SVpnConnectionsCommand.class) { + answer = execute((CheckS2SVpnConnectionsCommand) cmd); } else { answer = Answer.createUnsupportedCommandAnswer(cmd); } @@ -1567,6 +1571,35 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa return new Answer(cmd); } + protected CheckS2SVpnConnectionsAnswer execute(CheckS2SVpnConnectionsCommand cmd) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Executing resource CheckS2SVpnConnectionsCommand: " + _gson.toJson(cmd)); + s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /opt/cloud/bin/checkbatchs2svpn.sh "); + } + + Pair result; + try { + VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); + String controlIp = getRouterSshControlIp(cmd); + result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, + "/opt/cloud/bin/checkbatchs2svpn.sh "); + + if (!result.first()) { + s_logger.error("check site-to-site vpn connections command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second()); + + return new CheckS2SVpnConnectionsAnswer(cmd, false, result.second()); + } + + if (s_logger.isDebugEnabled()) { + s_logger.debug("check site-to-site vpn connections command on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed"); + } + } catch (Throwable e) { + String msg = "CheckS2SVpnConnectionsCommand failed due to " + VmwareHelper.getExceptionMessage(e); + s_logger.error(msg, e); + return new CheckS2SVpnConnectionsAnswer(cmd, false, "CheckS2SVpnConneciontsCommand failed"); + } + return new CheckS2SVpnConnectionsAnswer(cmd, true, result.second()); + } protected Answer execute(CheckRouterCommand cmd) { if (s_logger.isDebugEnabled()) { s_logger.debug("Executing resource CheckRouterCommand: " + _gson.toJson(cmd)); diff --git a/core/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java b/core/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java index 25a6ea148b5..9d0d94f1abb 100644 --- a/core/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java +++ b/core/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java @@ -66,6 +66,8 @@ import com.cloud.agent.api.CheckOnHostAnswer; import com.cloud.agent.api.CheckOnHostCommand; import com.cloud.agent.api.CheckRouterAnswer; import com.cloud.agent.api.CheckRouterCommand; +import com.cloud.agent.api.CheckS2SVpnConnectionsAnswer; +import com.cloud.agent.api.CheckS2SVpnConnectionsCommand; import com.cloud.agent.api.CheckVirtualMachineAnswer; import com.cloud.agent.api.CheckVirtualMachineCommand; import com.cloud.agent.api.CleanupNetworkRulesCmd; @@ -545,6 +547,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return execute((SetStaticRouteCommand) cmd); } else if (clazz == Site2SiteVpnCfgCommand.class) { return execute((Site2SiteVpnCfgCommand) cmd); + } else if (clazz == CheckS2SVpnConnectionsCommand.class) { + return execute((CheckS2SVpnConnectionsCommand) cmd); } else { return Answer.createUnsupportedCommandAnswer(cmd); } @@ -1386,6 +1390,19 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return new Answer(cmd); } + private CheckS2SVpnConnectionsAnswer execute(CheckS2SVpnConnectionsCommand cmd) { + Connection conn = getConnection(); + String args = "checkbatchs2svpn.sh " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); + for (String ip : cmd.getVpnIps()) { + args += " " + ip; + } + String result = callHostPlugin(conn, "vmops", "routerProxy", "args", args); + if (result == null || result.isEmpty()) { + return new CheckS2SVpnConnectionsAnswer(cmd, false, "CheckS2SVpnConneciontsCommand failed"); + } + return new CheckS2SVpnConnectionsAnswer(cmd, true, result); + } + private CheckRouterAnswer execute(CheckRouterCommand cmd) { Connection conn = getConnection(); String args = "checkrouter.sh " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); diff --git a/core/src/com/cloud/network/resource/NetscalerResource.java b/core/src/com/cloud/network/resource/NetscalerResource.java index 3bb3ef77b82..ab2c958ad6a 100644 --- a/core/src/com/cloud/network/resource/NetscalerResource.java +++ b/core/src/com/cloud/network/resource/NetscalerResource.java @@ -228,35 +228,12 @@ public class NetscalerResource implements ServerResource { } private ArrayList netscalerServices = new ArrayList(); - private com.citrix.netscaler.nitro.service.nitro_service login_get_service(Boolean forAutoScale) throws ExecutionException { - if(forAutoScale == null) { - return _netscalerService; - } - com.citrix.netscaler.nitro.service.nitro_service _netscalerService = null; - try { - _netscalerService = new com.citrix.netscaler.nitro.service.nitro_service(_ip, "https"); - _netscalerService.set_credential(_username, _password); - _netscalerService.set_timeout(_timeout); - base_response apiCallResult = _netscalerService.login(); - if (apiCallResult.errorcode != 0) { - throw new ExecutionException ("AuotoScale Failed to log in to Netscaler device at " + _ip + " due to error " + apiCallResult.errorcode + " and message " + apiCallResult.message); - } - } catch(ExecutionException ee) { - throw ee; - } - catch(Exception ee) { - throw new ExecutionException ("AutoScale Exception happend during login" + ee.getMessage()); - } - netscalerServices.add(_netscalerService); - return _netscalerService; - } - private void login() throws ExecutionException { try { if (!_isSdx) { _netscalerService = new com.citrix.netscaler.nitro.service.nitro_service(_ip, "https"); _netscalerService.set_credential(_username, _password); - _netscalerService.set_timeout(_timeout); + // _netscalerService.set_timeout(_timeout); apiCallResult = _netscalerService.login(); if (apiCallResult.errorcode != 0) { throw new ExecutionException ("Failed to log in to Netscaler device at " + _ip + " due to error " + apiCallResult.errorcode + " and message " + apiCallResult.message); @@ -281,7 +258,7 @@ public class NetscalerResource implements ServerResource { return; } try { - String[] features = login_get_service(true).get_enabled_features(); + String[] features = _netscalerService.get_enabled_features(); if (features != null) { for (String feature : features) { if (feature.equalsIgnoreCase("LB")) { @@ -293,7 +270,7 @@ public class NetscalerResource implements ServerResource { // enable load balancing on the device String[] feature = new String[1]; feature[0] = "LB"; - apiCallResult = login_get_service(true).enable_features(feature); + apiCallResult = _netscalerService.enable_features(feature); if (apiCallResult.errorcode != 0) { throw new ExecutionException("Enabling load balancing feature on the device failed."); } @@ -307,8 +284,8 @@ public class NetscalerResource implements ServerResource { private void validateInterfaces(String publicInterface, String privateInterface) throws ExecutionException { try { if (!_isSdx && !_cloudManaged) { - Interface publicIf = Interface.get(login_get_service(true), publicInterface); - Interface privateIf = Interface.get(login_get_service(true), privateInterface); + Interface publicIf = Interface.get(_netscalerService, publicInterface); + Interface privateIf = Interface.get(_netscalerService, privateInterface); if (publicIf != null || privateIf != null) { return; } else { @@ -329,7 +306,7 @@ public class NetscalerResource implements ServerResource { private void validateDeviceType(String deviceType) throws ExecutionException { try { if (!_isSdx && !_cloudManaged) { - nshardware nsHw = com.citrix.netscaler.nitro.resource.config.ns.nshardware.get(login_get_service(true)); + nshardware nsHw = com.citrix.netscaler.nitro.resource.config.ns.nshardware.get(_netscalerService); if (nsHw == null) { throw new ExecutionException("Failed to get the hardware description of the Netscaler device at " + _ip); } else { @@ -473,7 +450,7 @@ public class NetscalerResource implements ServerResource { timer_policy_binding.set_name(timerName); timer_policy_binding.set_policyname(policyName); timer_policy_binding.set_global("DEFAULT"); - timer_policy_binding.delete(login_get_service(true), timer_policy_binding); + timer_policy_binding.delete(_netscalerService, timer_policy_binding); } catch (Exception e) { // Ignore Exception throw e; @@ -484,7 +461,7 @@ public class NetscalerResource implements ServerResource { com.citrix.netscaler.nitro.resource.config.timer.timerpolicy timerPolicy = new com.citrix.netscaler.nitro.resource.config.timer.timerpolicy(); try { timerPolicy.set_name(policyName); - timerPolicy.delete(login_get_service(true), timerPolicy); + timerPolicy.delete(_netscalerService, timerPolicy); } catch (Exception e) { // Ignore Exception throw e; @@ -508,7 +485,7 @@ public class NetscalerResource implements ServerResource { try { vserver_servicegroup_binding.set_name(nsVirtualServerName); vserver_servicegroup_binding.set_servicegroupname(serviceGroupName); - vserver_servicegroup_binding.delete(login_get_service(true), vserver_servicegroup_binding); + vserver_servicegroup_binding.delete(_netscalerService, vserver_servicegroup_binding); } catch (Exception e) { // Ignore Exception throw e; @@ -518,7 +495,7 @@ public class NetscalerResource implements ServerResource { com.citrix.netscaler.nitro.resource.config.basic.servicegroup serviceGroup = new com.citrix.netscaler.nitro.resource.config.basic.servicegroup(); try { serviceGroup.set_servicegroupname(serviceGroupName); - serviceGroup.delete(login_get_service(true), serviceGroup); + serviceGroup.delete(_netscalerService, serviceGroup); } catch (Exception e) { // Ignore Exception throw e; @@ -531,7 +508,7 @@ public class NetscalerResource implements ServerResource { // lbvserver.set_name(nsVirtualServerName); // lbvserver.set_minautoscalemembers(0); // lbvserver.set_maxautoscalemembers(0); - // lbvserver.update(login_get_service(true), lbvserver); + // lbvserver.update(_netscalerService, lbvserver); // } catch (Exception e) { // // Ignore Exception // throw e; @@ -589,7 +566,7 @@ public class NetscalerResource implements ServerResource { com.citrix.netscaler.nitro.resource.config.autoscale.autoscaleaction scaleDownAction = new com.citrix.netscaler.nitro.resource.config.autoscale.autoscaleaction(); try { scaleDownAction.set_name(scaleDownActionName); - scaleDownAction.delete(login_get_service(true), scaleDownAction); + scaleDownAction.delete(_netscalerService, scaleDownAction); } catch (Exception e) { // Ignore Exception throw e; @@ -599,7 +576,7 @@ public class NetscalerResource implements ServerResource { com.citrix.netscaler.nitro.resource.config.autoscale.autoscaleaction scaleUpAction = new com.citrix.netscaler.nitro.resource.config.autoscale.autoscaleaction(); try { scaleUpAction.set_name(scaleUpActionName); - scaleUpAction.delete(login_get_service(true), scaleUpAction); + scaleUpAction.delete(_netscalerService, scaleUpAction); } catch (Exception e) { // Ignore Exception throw e; @@ -609,7 +586,7 @@ public class NetscalerResource implements ServerResource { com.citrix.netscaler.nitro.resource.config.timer.timertrigger timer = new com.citrix.netscaler.nitro.resource.config.timer.timertrigger(); try { timer.set_name(timerName); - timer.delete(login_get_service(true), timer); + timer.delete(_netscalerService, timer); } catch (Exception e) { // Ignore Exception throw e; @@ -619,7 +596,7 @@ public class NetscalerResource implements ServerResource { com.citrix.netscaler.nitro.resource.config.autoscale.autoscaleprofile autoscaleProfile = new com.citrix.netscaler.nitro.resource.config.autoscale.autoscaleprofile(); try { autoscaleProfile.set_name(profileName); - autoscaleProfile.delete(login_get_service(true), autoscaleProfile); + autoscaleProfile.delete(_netscalerService, autoscaleProfile); } catch (Exception e) { // Ignore Exception throw e; @@ -630,7 +607,7 @@ public class NetscalerResource implements ServerResource { try { monitor_servicegroup_binding.set_monitorname(monitorName); monitor_servicegroup_binding.set_servicegroupname(serviceGroupName); - monitor_servicegroup_binding.delete(login_get_service(true), monitor_servicegroup_binding); + monitor_servicegroup_binding.delete(_netscalerService, monitor_servicegroup_binding); } catch (Exception e) { // Ignore Exception throw e; @@ -642,7 +619,7 @@ public class NetscalerResource implements ServerResource { try { monitor.set_monitorname(monitorName); monitor.set_type("LOAD"); - monitor.delete(login_get_service(true), monitor); + monitor.delete(_netscalerService, monitor); } catch (Exception e) { // Ignore Exception throw e; @@ -652,7 +629,7 @@ public class NetscalerResource implements ServerResource { com.citrix.netscaler.nitro.resource.config.lb.lbmetrictable metricTable = new com.citrix.netscaler.nitro.resource.config.lb.lbmetrictable(); try { metricTable.set_metrictable(mtName); - metricTable.delete(login_get_service(true), metricTable); + metricTable.delete(_netscalerService, metricTable); } catch (Exception e) { // Ignore Exception throw e; @@ -686,7 +663,7 @@ public class NetscalerResource implements ServerResource { serviceGroup.set_servicetype(lbProtocol); serviceGroup.set_autoscale("POLICY"); // TODO: Values not displayed in API serviceGroup.set_memberport(memberPort); - serviceGroup.add(login_get_service(true), serviceGroup); + serviceGroup.add(_netscalerService, serviceGroup); } catch (Exception e) { // Ignore Exception throw e; @@ -699,7 +676,7 @@ public class NetscalerResource implements ServerResource { try { vserver_servicegroup_binding.set_name(nsVirtualServerName); vserver_servicegroup_binding.set_servicegroupname(serviceGroupName); - vserver_servicegroup_binding.add(login_get_service(true), vserver_servicegroup_binding); + vserver_servicegroup_binding.add(_netscalerService, vserver_servicegroup_binding); } catch (Exception e) { // Ignore Exception throw e; @@ -741,7 +718,7 @@ public class NetscalerResource implements ServerResource { lbvserver.set_name(nsVirtualServerName); lbvserver.set_minautoscalemembers(minAutoScaleMembers); lbvserver.set_maxautoscalemembers(maxAutoScaleMembers); - lbvserver.update(login_get_service(true), lbvserver); + lbvserver.update(_netscalerService, lbvserver); } catch (Exception e) { // Ignore Exception throw e; @@ -762,7 +739,7 @@ public class NetscalerResource implements ServerResource { autoscaleProfile.set_apikey(apiKey); autoscaleProfile.set_sharedsecret(secretKey); autoscaleProfile.set_url(url); - autoscaleProfile.add(login_get_service(true), autoscaleProfile); + autoscaleProfile.add(_netscalerService, autoscaleProfile); } catch (Exception e) { // Ignore Exception @@ -774,7 +751,7 @@ public class NetscalerResource implements ServerResource { try { timer.set_name(timerName); timer.set_interval(interval); - timer.add(login_get_service(true), timer); + timer.add(_netscalerService, timer); } catch (Exception e) { // Ignore Exception throw e; @@ -820,7 +797,7 @@ public class NetscalerResource implements ServerResource { ((profileTO.getOtherDeployParams() == null)? "" : (profileTO.getOtherDeployParams() + "&")) + "lbruleid=" + loadBalancerTO.getId(); scaleUpAction.set_parameters(scaleUpParameters); - scaleUpAction.add(login_get_service(true), scaleUpAction); + scaleUpAction.add(_netscalerService, scaleUpAction); } catch (Exception e) { // Ignore Exception throw e; @@ -839,7 +816,7 @@ public class NetscalerResource implements ServerResource { "lbruleid=" + loadBalancerTO.getId(); scaleDownAction.set_parameters(scaleDownParameters); scaleDownAction.set_vmdestroygraceperiod(destroyVmGracePeriod); - scaleDownAction.add(login_get_service(true), scaleDownAction); + scaleDownAction.add(_netscalerService, scaleDownAction); } catch (Exception e) { // Ignore Exception throw e; @@ -881,7 +858,7 @@ public class NetscalerResource implements ServerResource { com.citrix.netscaler.nitro.resource.config.lb.lbmetrictable metricTable = new com.citrix.netscaler.nitro.resource.config.lb.lbmetrictable(); try { metricTable.set_metrictable(mtName); - metricTable.add(login_get_service(true), metricTable); + metricTable.add(_netscalerService, metricTable); } catch (Exception e) { // Ignore Exception throw e; @@ -898,7 +875,7 @@ public class NetscalerResource implements ServerResource { monitor.set_snmpcommunity(snmpCommunity); monitor.set_metrictable(mtName); monitor.set_interval((int)(interval * 0.8)); - monitor.add(login_get_service(true), monitor); + monitor.add(_netscalerService, monitor); } catch (Exception e) { // Ignore Exception throw e; @@ -912,7 +889,7 @@ public class NetscalerResource implements ServerResource { monitor_servicegroup_binding.set_servicegroupname(serviceGroupName); monitor_servicegroup_binding.set_passive(true); // Mark the monitor to do only collect // metrics, basically use it for autoscaling purpose only. - monitor_servicegroup_binding.add(login_get_service(true), monitor_servicegroup_binding); + monitor_servicegroup_binding.add(_netscalerService, monitor_servicegroup_binding); } catch (Exception e) { // Ignore Exception throw e; @@ -933,7 +910,7 @@ public class NetscalerResource implements ServerResource { metrictable_metric_binding.set_metrictable(mtName); metrictable_metric_binding.set_metric(counterName); metrictable_metric_binding.set_Snmpoid(counterOid); - metrictable_metric_binding.add(login_get_service(true), metrictable_metric_binding); + metrictable_metric_binding.add(_netscalerService, metrictable_metric_binding); } catch (Exception e) { // Ignore Exception throw e; @@ -945,7 +922,7 @@ public class NetscalerResource implements ServerResource { monitor_metrictable_binding.set_monitorname(monitorName); monitor_metrictable_binding.set_metric(counterName); monitor_metrictable_binding.set_metricthreshold(1); // 1 is a dummy threshold - monitor_metrictable_binding.add(login_get_service(true), monitor_metrictable_binding); + monitor_metrictable_binding.add(_netscalerService, monitor_metrictable_binding); } catch (Exception e) { // Ignore Exception throw e; @@ -999,7 +976,7 @@ public class NetscalerResource implements ServerResource { timerPolicy.set_name(policyName); timerPolicy.set_action(action); timerPolicy.set_rule(policyExpression); - timerPolicy.add(login_get_service(true), timerPolicy); + timerPolicy.add(_netscalerService, timerPolicy); } catch (Exception e) { // Ignore Exception throw e; @@ -1021,7 +998,7 @@ public class NetscalerResource implements ServerResource { timer_policy_binding.set_thresholdsize(sampleSize); // We are not exposing this parameter as of now. // i.e. n(m) is not exposed to CS user. So thresholdSize == sampleSize timer_policy_binding.set_priority(priority); - timer_policy_binding.add(login_get_service(true), timer_policy_binding); + timer_policy_binding.add(_netscalerService, timer_policy_binding); } catch (Exception e) { // Ignore Exception throw e; @@ -1056,7 +1033,7 @@ public class NetscalerResource implements ServerResource { private boolean isAutoScaleSupportedInNetScaler() throws ExecutionException { autoscaleprofile autoscaleProfile = new autoscaleprofile(); try { - autoscaleProfile.get(login_get_service(true)); + autoscaleProfile.get(_netscalerService); } catch (Exception ex) { // Looks like autoscale is not supported in this netscaler. // TODO: Config team has introduce a new command to check @@ -1120,7 +1097,7 @@ public class NetscalerResource implements ServerResource { 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(login_get_service(null), nsServer); + 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); } @@ -1135,7 +1112,7 @@ public class NetscalerResource implements ServerResource { newService.set_state("ENABLED"); newService.set_servicetype(lbProtocol); - apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.service.add(login_get_service(null), newService); + 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); } @@ -1146,7 +1123,7 @@ public class NetscalerResource implements ServerResource { 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(login_get_service(null), svcBinding); + 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"); @@ -1157,13 +1134,13 @@ public class NetscalerResource implements ServerResource { } } 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(login_get_service(null), + 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(login_get_service(null), 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); @@ -1172,16 +1149,16 @@ public class NetscalerResource implements ServerResource { // 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(login_get_service(null), nsServiceName); + 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(login_get_service(null), nsServerName); + 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(login_get_service(null), nsServerName); + 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); } @@ -1196,33 +1173,33 @@ public class NetscalerResource implements ServerResource { 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(login_get_service(null), + 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(login_get_service(null), binding); + 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(login_get_service(null), serviceName); + 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(login_get_service(null), serviceName); + 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(login_get_service(null), nsServerName); + 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(login_get_service(null), nsServerName); + 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); } @@ -1341,7 +1318,7 @@ public class NetscalerResource implements ServerResource { try { nitro_service _netscalerService = new nitro_service(cmd.getLoadBalancerIP(), "https"); _netscalerService.set_credential(username, password); - _netscalerService.set_timeout(_timeout); + // _netscalerService.set_timeout(_timeout); apiCallResult = _netscalerService.login(); if (apiCallResult.errorcode == 0) { nsServiceUp = true; @@ -1537,7 +1514,7 @@ public class NetscalerResource implements ServerResource { if (!rule.revoked()) { try { - iNatRule = inat.get(login_get_service(null), iNatRuleName); + iNatRule = inat.get(_netscalerService, iNatRuleName); } catch (nitro_exception e) { if (e.getErrorCode() != NitroError.NS_RESOURCE_NOT_EXISTS) { throw e; @@ -1552,7 +1529,7 @@ public class NetscalerResource implements ServerResource { iNatRule.set_usnip("OFF"); iNatRule.set_usip("ON"); try { - apiCallResult = inat.add(login_get_service(null), iNatRule); + apiCallResult = inat.add(_netscalerService, iNatRule); } catch (nitro_exception e) { if (e.getErrorCode() != NitroError.NS_RESOURCE_EXISTS) { throw e; @@ -1562,7 +1539,7 @@ public class NetscalerResource implements ServerResource { } } else { try { - inat.delete(login_get_service(null), iNatRuleName); + inat.delete(_netscalerService, iNatRuleName); } catch (nitro_exception e) { if (e.getErrorCode() != NitroError.NS_RESOURCE_NOT_EXISTS) { throw e; @@ -1608,7 +1585,7 @@ public class NetscalerResource implements ServerResource { selfIp.set_ipaddress(snip); selfIp.set_netmask(netmask); selfIp.set_type("SNIP"); - apiCallResult = nsip.add(login_get_service(null), selfIp); + apiCallResult = nsip.add(_netscalerService, selfIp); if (apiCallResult.errorcode != 0) { throw new ExecutionException("Failed to add SNIP object on the Netscaler device due to "+ apiCallResult.message); } @@ -1626,7 +1603,7 @@ public class NetscalerResource implements ServerResource { try { vlan vlanObj = new vlan(); vlanObj.set_id(vlanTag); - apiCallResult = vlan.add(login_get_service(null), vlanObj); + apiCallResult = vlan.add(_netscalerService, vlanObj); if (apiCallResult.errorcode != 0) { throw new ExecutionException("Failed to add new vlan with tag:" + vlanTag + "on the NetScaler device due to " + apiCallResult.message); } @@ -1642,7 +1619,7 @@ public class NetscalerResource implements ServerResource { selfIp.set_ipaddress(vlanSelfIp); selfIp.set_netmask(vlanNetmask); selfIp.set_type("SNIP"); - apiCallResult = nsip.add(login_get_service(null), selfIp); + apiCallResult = nsip.add(_netscalerService, selfIp); if (apiCallResult.errorcode != 0) { throw new ExecutionException("Failed to add SNIP object for the guest network on the Netscaler device due to "+ apiCallResult.message); } @@ -1658,7 +1635,7 @@ public class NetscalerResource implements ServerResource { ipVlanBinding.set_id(vlanTag); ipVlanBinding.set_ipaddress(vlanSelfIp); ipVlanBinding.set_netmask(vlanNetmask); - apiCallResult = vlan_nsip_binding.add(login_get_service(null), ipVlanBinding); + apiCallResult = vlan_nsip_binding.add(_netscalerService, ipVlanBinding); if (apiCallResult.errorcode != 0) { throw new ExecutionException("Failed to bind VLAN with tag:" + vlanTag + " to the subnet due to " + apiCallResult.message); } @@ -1677,7 +1654,7 @@ public class NetscalerResource implements ServerResource { } vlanBinding.set_tagged(true); vlanBinding.set_id(vlanTag); - apiCallResult = vlan_interface_binding.add(login_get_service(null), vlanBinding); + apiCallResult = vlan_interface_binding.add(_netscalerService, vlanBinding); if (apiCallResult.errorcode != 0) { String vlanInterface = guestVlan ? _privateInterface : _publicInterface; throw new ExecutionException("Failed to bind vlan with tag:" + vlanTag + " with the interface " + vlanInterface + " due to " + apiCallResult.message); @@ -1706,7 +1683,7 @@ public class NetscalerResource implements ServerResource { vlanIfBinding.set_id(vlanTag); vlanIfBinding.set_ifnum(_privateInterface); vlanIfBinding.set_tagged(true); - apiCallResult = vlan_interface_binding.delete(login_get_service(null), vlanIfBinding); + apiCallResult = vlan_interface_binding.delete(_netscalerService, vlanIfBinding); if (apiCallResult.errorcode != 0) { throw new ExecutionException("Failed to unbind vlan:" + vlanTag + " with the private interface due to " + apiCallResult.message); } @@ -1723,7 +1700,7 @@ public class NetscalerResource implements ServerResource { vlanSnipBinding.set_netmask(vlanNetmask); vlanSnipBinding.set_ipaddress(vlanSelfIp); vlanSnipBinding.set_id(vlanTag); - apiCallResult = vlan_nsip_binding.delete(login_get_service(null), vlanSnipBinding); + apiCallResult = vlan_nsip_binding.delete(_netscalerService, vlanSnipBinding); if (apiCallResult.errorcode != 0) { throw new ExecutionException("Failed to unbind vlan:" + vlanTag + " with the subnet due to " + apiCallResult.message); } @@ -1736,8 +1713,8 @@ public class NetscalerResource implements ServerResource { // remove subnet IP try { - nsip subnetIp = nsip.get(login_get_service(null), vlanSelfIp); - apiCallResult = nsip.delete(login_get_service(null), subnetIp); + nsip subnetIp = nsip.get(_netscalerService, vlanSelfIp); + apiCallResult = nsip.delete(_netscalerService, subnetIp); if (apiCallResult.errorcode != 0) { throw new ExecutionException("Failed to remove subnet ip:" + vlanSelfIp + " from the NetScaler device due to" + apiCallResult.message); } @@ -1751,7 +1728,7 @@ public class NetscalerResource implements ServerResource { // remove the vlan from the NetScaler device if (nsVlanExists(vlanTag)) { // remove vlan - apiCallResult = com.citrix.netscaler.nitro.resource.config.network.vlan.delete(login_get_service(null), vlanTag); + apiCallResult = com.citrix.netscaler.nitro.resource.config.network.vlan.delete(_netscalerService, vlanTag); if (apiCallResult.errorcode != 0) { throw new ExecutionException("Failed to remove vlan with tag:" + vlanTag + "due to" + apiCallResult.message); } @@ -1765,7 +1742,7 @@ public class NetscalerResource implements ServerResource { private boolean nsVlanExists(long vlanTag) throws ExecutionException { try { - if (vlan.get(login_get_service(null), new Long(vlanTag)) != null) { + if (vlan.get(_netscalerService, new Long(vlanTag)) != null) { return true; } else { return false; @@ -1783,7 +1760,7 @@ public class NetscalerResource implements ServerResource { private boolean nsSnipExists(String subnetIP) throws ExecutionException { try { - nsip snip = nsip.get(login_get_service(null), subnetIP); + nsip snip = nsip.get(_netscalerService, subnetIP); return (snip != null); } catch (nitro_exception e) { if (e.getErrorCode() == NitroError.NS_RESOURCE_NOT_EXISTS) { @@ -1798,7 +1775,7 @@ public class NetscalerResource implements ServerResource { private boolean nsServerExists(String serverName) throws ExecutionException { try { - if (com.citrix.netscaler.nitro.resource.config.basic.server.get(login_get_service(null), serverName) != null) { + if (com.citrix.netscaler.nitro.resource.config.basic.server.get(_netscalerService, serverName) != null) { return true; } else { return false; @@ -1816,7 +1793,7 @@ public class NetscalerResource implements ServerResource { private boolean nsVlanNsipBindingExists(long vlanTag, String vlanSelfIp) throws ExecutionException { try { - vlan_nsip_binding[] vlanNsipBindings = vlan_nsip_binding.get(login_get_service(null), vlanTag); + vlan_nsip_binding[] vlanNsipBindings = vlan_nsip_binding.get(_netscalerService, vlanTag); if (vlanNsipBindings != null && vlanNsipBindings[0] != null && vlanNsipBindings[0].get_ipaddress().equalsIgnoreCase(vlanSelfIp)) { return true; } else { @@ -1835,7 +1812,7 @@ public class NetscalerResource implements ServerResource { private lbvserver getVirtualServerIfExisits(String lbVServerName ) throws ExecutionException { try { - return lbvserver.get(login_get_service(true), lbVServerName); + return lbvserver.get(_netscalerService, lbVServerName); } catch (nitro_exception e) { if (e.getErrorCode() == NitroError.NS_RESOURCE_NOT_EXISTS) { return null; @@ -1849,11 +1826,11 @@ public class NetscalerResource implements ServerResource { private boolean isServiceBoundToVirtualServer(String serviceName) throws ExecutionException { try { - lbvserver[] lbservers = lbvserver.get(login_get_service(null)); + lbvserver[] lbservers = lbvserver.get(_netscalerService); for (lbvserver vserver : lbservers) { filtervalue[] filter = new filtervalue[1]; filter[0] = new filtervalue("servicename", serviceName); - lbvserver_service_binding[] result = lbvserver_service_binding.get_filtered(login_get_service(null), vserver.get_name(), filter); + lbvserver_service_binding[] result = lbvserver_service_binding.get_filtered(_netscalerService, vserver.get_name(), filter); if (result != null && result.length > 0) { return true; } @@ -1866,7 +1843,7 @@ public class NetscalerResource implements ServerResource { private boolean nsServiceExists(String serviceName) throws ExecutionException { try { - if (com.citrix.netscaler.nitro.resource.config.basic.service.get(login_get_service(null), serviceName) != null) { + if (com.citrix.netscaler.nitro.resource.config.basic.service.get(_netscalerService, serviceName) != null) { return true; } else { return false; @@ -1884,7 +1861,7 @@ public class NetscalerResource implements ServerResource { private boolean nsServiceBindingExists(String lbVirtualServer, String serviceName) throws ExecutionException { try { - com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding[] serviceBindings = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.get(login_get_service(null), lbVirtualServer); + com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding[] serviceBindings = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.get(_netscalerService, lbVirtualServer); if (serviceBindings != null) { for (com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding binding : serviceBindings) { if (serviceName.equalsIgnoreCase(binding.get_servicename())) { @@ -1902,7 +1879,7 @@ public class NetscalerResource implements ServerResource { private void deleteServersInGuestVlan(long vlanTag, String vlanSelfIp, String vlanNetmask) throws ExecutionException { try { - com.citrix.netscaler.nitro.resource.config.basic.server[] serverList = com.citrix.netscaler.nitro.resource.config.basic.server.get(login_get_service(null)); + com.citrix.netscaler.nitro.resource.config.basic.server[] serverList = com.citrix.netscaler.nitro.resource.config.basic.server.get(_netscalerService); if (serverList == null) { return; @@ -1913,11 +1890,11 @@ public class NetscalerResource implements ServerResource { // check if server belong to same subnet as one associated with vlan if (NetUtils.sameSubnet(vlanSelfIp, server.get_ipaddress(), vlanNetmask)) { // first remove services associated with this server - com.citrix.netscaler.nitro.resource.config.basic.service serveicesList[] = com.citrix.netscaler.nitro.resource.config.basic.service.get(login_get_service(null)); + com.citrix.netscaler.nitro.resource.config.basic.service serveicesList[] = com.citrix.netscaler.nitro.resource.config.basic.service.get(_netscalerService); if (serveicesList != null) { for (com.citrix.netscaler.nitro.resource.config.basic.service svc : serveicesList) { if (svc.get_servername().equals(server.get_ipaddress())) { - apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.service.delete(login_get_service(null), svc.get_name()); + apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.service.delete(_netscalerService, svc.get_name()); if (apiCallResult.errorcode != 0) { throw new ExecutionException("Failed to remove service:" + svc.get_name()); } @@ -1925,7 +1902,7 @@ public class NetscalerResource implements ServerResource { } } // remove the server - apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.server.delete(login_get_service(null), server.get_name()); + apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.server.delete(_netscalerService, server.get_name()); if (apiCallResult.errorcode != 0) { throw new ExecutionException("Failed to remove server:" + server.get_name()); } @@ -2034,11 +2011,18 @@ public class NetscalerResource implements ServerResource { vserver.set_persistencetype("NONE"); } } + if(vmGroupTO != null) { + vserver.set_mysqlcharacterset(null); + vserver.set_mysqlprotocolversion(null); + vserver.set_mysqlservercapabilities(null); + vserver.set_mysqlserverversion(null); + } + if (vserverExisis) { - apiCallResult = lbvserver.update(login_get_service(vmGroupTO != null),vserver); + apiCallResult = lbvserver.update(_netscalerService,vserver); } else { - apiCallResult = lbvserver.add(login_get_service(vmGroupTO != null),vserver); + apiCallResult = lbvserver.add(_netscalerService,vserver); } if (apiCallResult.errorcode != 0) { throw new ExecutionException("Failed to create new load balancing virtual server:" + virtualServerName + " due to " + apiCallResult.message); @@ -2057,11 +2041,11 @@ public class NetscalerResource implements ServerResource { private void removeLBVirtualServer (String virtualServerName) throws ExecutionException { try { - lbvserver vserver = lbvserver.get(login_get_service(true), virtualServerName); + lbvserver vserver = lbvserver.get(_netscalerService, virtualServerName); if (vserver == null) { return; } - apiCallResult = lbvserver.delete(login_get_service(true), vserver); + apiCallResult = lbvserver.delete(_netscalerService, vserver); if (apiCallResult.errorcode != 0) { throw new ExecutionException("Failed to delete virtual server:" + virtualServerName + " due to " + apiCallResult.message); } @@ -2078,7 +2062,7 @@ public class NetscalerResource implements ServerResource { private void saveConfiguration() throws ExecutionException { try { - apiCallResult = nsconfig.save(login_get_service(true)); + apiCallResult = nsconfig.save(_netscalerService); if (apiCallResult.errorcode != 0) { throw new ExecutionException("Error occured while saving configuration changes to Netscaler device due to " + apiCallResult.message); } @@ -2093,7 +2077,7 @@ public class NetscalerResource implements ServerResource { ExternalNetworkResourceUsageAnswer answer = new ExternalNetworkResourceUsageAnswer(cmd); try { - lbvserver_stats[] stats = lbvserver_stats.get(login_get_service(null)); + lbvserver_stats[] stats = lbvserver_stats.get(_netscalerService); if (stats == null || stats.length == 0) { return answer; @@ -2101,7 +2085,7 @@ public class NetscalerResource implements ServerResource { for (lbvserver_stats stat_entry : stats) { String lbvserverName = stat_entry.get_name(); - lbvserver vserver = lbvserver.get(login_get_service(null), lbvserverName); + lbvserver vserver = lbvserver.get(_netscalerService, lbvserverName); if(vserver != null){ String lbVirtualServerIp = vserver.get_ipv46(); diff --git a/patches/systemvm/debian/config/opt/cloud/bin/checkbatchs2svpn.sh b/patches/systemvm/debian/config/opt/cloud/bin/checkbatchs2svpn.sh new file mode 100755 index 00000000000..bde9627ab59 --- /dev/null +++ b/patches/systemvm/debian/config/opt/cloud/bin/checkbatchs2svpn.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +for i in $* +do + info=`/opt/cloud/bin/checks2svpn.sh $i` + ret=$? + echo -n "$i:$ret:$info&" +done + diff --git a/patches/systemvm/debian/config/opt/cloud/bin/checks2svpn.sh b/patches/systemvm/debian/config/opt/cloud/bin/checks2svpn.sh index 3198824bc1b..e6bf9e52d31 100755 --- a/patches/systemvm/debian/config/opt/cloud/bin/checks2svpn.sh +++ b/patches/systemvm/debian/config/opt/cloud/bin/checks2svpn.sh @@ -12,20 +12,20 @@ cat /tmp/vpn-$1.status | grep "ISAKMP SA established" > /dev/null isakmpok=$? if [ $isakmpok -ne 0 ] then - echo "ISAKMP SA not found" + echo -n "ISAKMP SA not found" echo "Site-to-site VPN have not connected" exit 12 fi -echo "ISAKMP SA found" +echo -n "ISAKMP SA found;" cat /tmp/vpn-$1.status | grep "IPsec SA established" > /dev/null ipsecok=$? if [ $ipsecok -ne 0 ] then - echo "IPsec SA not found" + echo -n "IPsec SA not found;" echo "Site-to-site VPN have not connected" exit 11 fi -echo "IPsec SA found" +echo -n "IPsec SA found;" echo "Site-to-site VPN have connected" exit 0 diff --git a/server/src/com/cloud/baremetal/ExternalDhcpManagerImpl.java b/server/src/com/cloud/baremetal/ExternalDhcpManagerImpl.java index 37a88dd02f0..996289deb8b 100755 --- a/server/src/com/cloud/baremetal/ExternalDhcpManagerImpl.java +++ b/server/src/com/cloud/baremetal/ExternalDhcpManagerImpl.java @@ -12,6 +12,7 @@ // Automatically generated by addcopyright.py at 04/03/2012 package com.cloud.baremetal; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -44,6 +45,7 @@ import com.cloud.resource.ResourceManager; import com.cloud.resource.ResourceStateAdapter; import com.cloud.resource.ServerResource; import com.cloud.resource.UnableDeleteHostException; +import com.cloud.utils.IdentityProxy; import com.cloud.utils.component.Inject; import com.cloud.utils.db.DB; import com.cloud.utils.db.Transaction; @@ -58,192 +60,195 @@ import com.cloud.vm.dao.UserVmDao; @Local(value = {ExternalDhcpManager.class}) public class ExternalDhcpManagerImpl implements ExternalDhcpManager, ResourceStateAdapter { - private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalDhcpManagerImpl.class); - protected String _name; - @Inject DataCenterDao _dcDao; - @Inject HostDao _hostDao; - @Inject AgentManager _agentMgr; - @Inject HostPodDao _podDao; - @Inject UserVmDao _userVmDao; - @Inject ResourceManager _resourceMgr; - @Inject NicDao _nicDao; - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); - return true; - } + private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalDhcpManagerImpl.class); + protected String _name; + @Inject DataCenterDao _dcDao; + @Inject HostDao _hostDao; + @Inject AgentManager _agentMgr; + @Inject HostPodDao _podDao; + @Inject UserVmDao _userVmDao; + @Inject ResourceManager _resourceMgr; + @Inject NicDao _nicDao; - @Override - public boolean start() { - return true; - } + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); + return true; + } - @Override - public boolean stop() { - _resourceMgr.unregisterResourceStateAdapter(this.getClass().getSimpleName()); - return true; - } + @Override + public boolean start() { + return true; + } - @Override - public String getName() { - return _name; - } + @Override + public boolean stop() { + _resourceMgr.unregisterResourceStateAdapter(this.getClass().getSimpleName()); + return true; + } - protected String getDhcpServerGuid(String zoneId, String name, String ip) { - return zoneId + "-" + name + "-" + ip; - } - - - @Override @DB - public Host addDhcpServer(Long zoneId, Long podId, String type, String url, String username, String password) { - DataCenterVO zone = _dcDao.findById(zoneId); - if (zone == null) { - throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId); - } - - HostPodVO pod = _podDao.findById(podId); - if (pod == null) { - throw new InvalidParameterValueException("Could not find pod with ID: " + podId); - } - - List dhcps = _resourceMgr.listAllUpAndEnabledHosts(Host.Type.ExternalDhcp, null, podId, zoneId); - if (dhcps.size() != 0) { - throw new InvalidParameterValueException("Already had a DHCP server in Pod: " + podId + " zone: " + zoneId); - } - - - String ipAddress = url; - String guid = getDhcpServerGuid(Long.toString(zoneId) + "-" + Long.toString(podId), "ExternalDhcp", ipAddress); - Map params = new HashMap(); - params.put("type", type); - params.put("zone", Long.toString(zoneId)); - params.put("pod", podId.toString()); - params.put("ip", ipAddress); - params.put("username", username); - params.put("password", password); - params.put("guid", guid); - params.put("pod", Long.toString(podId)); - params.put("gateway", pod.getGateway()); - String dns = zone.getDns1(); - if (dns == null) { - dns = zone.getDns2(); - } - params.put("dns", dns); - - ServerResource resource = null; - try { - if (type.equalsIgnoreCase(DhcpServerType.Dnsmasq.getName())) { - resource = new DnsmasqResource(); - resource.configure("Dnsmasq resource", params); - } else if (type.equalsIgnoreCase(DhcpServerType.Dhcpd.getName())) { - resource = new DhcpdResource(); - resource.configure("Dhcpd resource", params); - } else { - throw new CloudRuntimeException("Unsupport DHCP server " + type); - } - } catch (Exception e) { - s_logger.debug(e); - throw new CloudRuntimeException(e.getMessage()); - } - - Host dhcpServer = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalDhcp, params); - if (dhcpServer == null) { - throw new CloudRuntimeException("Cannot add external Dhcp server as a host"); - } - - Transaction txn = Transaction.currentTxn(); + @Override + public String getName() { + return _name; + } + + protected String getDhcpServerGuid(String zoneId, String name, String ip) { + return zoneId + "-" + name + "-" + ip; + } + + + @Override @DB + public Host addDhcpServer(Long zoneId, Long podId, String type, String url, String username, String password) { + DataCenterVO zone = _dcDao.findById(zoneId); + if (zone == null) { + throw new InvalidParameterValueException("Could not find zone by ID", null); + } + + HostPodVO pod = _podDao.findById(podId); + if (pod == null) { + throw new InvalidParameterValueException("Could not find pod by ID", null); + } + + List dhcps = _resourceMgr.listAllUpAndEnabledHosts(Host.Type.ExternalDhcp, null, podId, zoneId); + if (dhcps.size() != 0) { + List idList = new ArrayList(); + idList.add(new IdentityProxy(pod, podId, "podId")); + idList.add(new IdentityProxy(zone, zoneId, "zoneId")); + throw new InvalidParameterValueException("Already had a DHCP server in Pod with specified podId in zone with specified zoneId", idList); + } + + + String ipAddress = url; + String guid = getDhcpServerGuid(Long.toString(zoneId) + "-" + Long.toString(podId), "ExternalDhcp", ipAddress); + Map params = new HashMap(); + params.put("type", type); + params.put("zone", Long.toString(zoneId)); + params.put("pod", podId.toString()); + params.put("ip", ipAddress); + params.put("username", username); + params.put("password", password); + params.put("guid", guid); + params.put("pod", Long.toString(podId)); + params.put("gateway", pod.getGateway()); + String dns = zone.getDns1(); + if (dns == null) { + dns = zone.getDns2(); + } + params.put("dns", dns); + + ServerResource resource = null; + try { + if (type.equalsIgnoreCase(DhcpServerType.Dnsmasq.getName())) { + resource = new DnsmasqResource(); + resource.configure("Dnsmasq resource", params); + } else if (type.equalsIgnoreCase(DhcpServerType.Dhcpd.getName())) { + resource = new DhcpdResource(); + resource.configure("Dhcpd resource", params); + } else { + throw new CloudRuntimeException("Unsupport DHCP server " + type); + } + } catch (Exception e) { + s_logger.debug(e); + throw new CloudRuntimeException(e.getMessage()); + } + + Host dhcpServer = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalDhcp, params); + if (dhcpServer == null) { + throw new CloudRuntimeException("Cannot add external Dhcp server as a host"); + } + + Transaction txn = Transaction.currentTxn(); txn.start(); pod.setExternalDhcp(true); _podDao.update(pod.getId(), pod); txn.commit(); - return dhcpServer; - } - - @Override - public DhcpServerResponse getApiResponse(Host dhcpServer) { - DhcpServerResponse response = new DhcpServerResponse(); - response.setId(dhcpServer.getId()); - return response; - } - - private void prepareBareMetalDhcpEntry(NicProfile nic, DhcpEntryCommand cmd) { - Long vmId = nic.getVmId(); - UserVmVO vm = _userVmDao.findById(vmId); - if (vm == null || vm.getHypervisorType() != HypervisorType.BareMetal) { - s_logger.debug("VM " + vmId + " is not baremetal machine, skip preparing baremetal DHCP entry"); - return; - } - - List servers = _resourceMgr.listAllUpAndEnabledHosts(Host.Type.PxeServer, null, vm.getPodIdToDeployIn(), vm.getDataCenterIdToDeployIn()); - if (servers.size() != 1) { - throw new CloudRuntimeException("Wrong number of PXE server found in zone " + vm.getDataCenterIdToDeployIn() - + " Pod " + vm.getPodIdToDeployIn() + ", number is " + servers.size()); - } - HostVO pxeServer = servers.get(0); - cmd.setNextServer(pxeServer.getPrivateIpAddress()); - s_logger.debug("Set next-server to " + pxeServer.getPrivateIpAddress() + " for VM " + vm.getId()); - } - - @Override - public boolean addVirtualMachineIntoNetwork(Network network, NicProfile nic, VirtualMachineProfile profile, DeployDestination dest, - ReservationContext context) throws ResourceUnavailableException { - Long zoneId = profile.getVirtualMachine().getDataCenterIdToDeployIn(); - Long podId = profile.getVirtualMachine().getPodIdToDeployIn(); - List hosts = _resourceMgr.listAllUpAndEnabledHosts(Type.ExternalDhcp, null, podId, zoneId); - if (hosts.size() == 0) { - throw new CloudRuntimeException("No external Dhcp found in zone " + zoneId + " pod " + podId); - } - - if (hosts.size() > 1) { - throw new CloudRuntimeException("Something wrong, more than 1 external Dhcp found in zone " + zoneId + " pod " + podId); - } - - HostVO h = hosts.get(0); - String dns = nic.getDns1(); - if (dns == null) { - dns = nic.getDns2(); - } - DhcpEntryCommand dhcpCommand = new DhcpEntryCommand(nic.getMacAddress(), nic.getIp4Address(), profile.getVirtualMachine().getHostName(), dns, nic.getGateway()); - String errMsg = String.format("Set dhcp entry on external DHCP %1$s failed(ip=%2$s, mac=%3$s, vmname=%4$s)", - h.getPrivateIpAddress(), nic.getIp4Address(), nic.getMacAddress(), profile.getVirtualMachine().getHostName()); - //prepareBareMetalDhcpEntry(nic, dhcpCommand); - try { - Answer ans = _agentMgr.send(h.getId(), dhcpCommand); - if (ans.getResult()) { - s_logger.debug(String.format("Set dhcp entry on external DHCP %1$s successfully(ip=%2$s, mac=%3$s, vmname=%4$s)", - h.getPrivateIpAddress(), nic.getIp4Address(), nic.getMacAddress(), profile.getVirtualMachine().getHostName())); - return true; - } else { - s_logger.debug(errMsg + " " + ans.getDetails()); - throw new ResourceUnavailableException(errMsg, DataCenter.class, zoneId); - } - } catch (Exception e) { - s_logger.debug(errMsg, e); - throw new ResourceUnavailableException(errMsg + e.getMessage(), DataCenter.class, zoneId); - } - } - - @Override - public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { - // TODO Auto-generated method stub - return null; + return dhcpServer; } - @Override + @Override + public DhcpServerResponse getApiResponse(Host dhcpServer) { + DhcpServerResponse response = new DhcpServerResponse(); + response.setId(dhcpServer.getId()); + return response; + } + + private void prepareBareMetalDhcpEntry(NicProfile nic, DhcpEntryCommand cmd) { + Long vmId = nic.getVmId(); + UserVmVO vm = _userVmDao.findById(vmId); + if (vm == null || vm.getHypervisorType() != HypervisorType.BareMetal) { + s_logger.debug("VM " + vmId + " is not baremetal machine, skip preparing baremetal DHCP entry"); + return; + } + + List servers = _resourceMgr.listAllUpAndEnabledHosts(Host.Type.PxeServer, null, vm.getPodIdToDeployIn(), vm.getDataCenterIdToDeployIn()); + if (servers.size() != 1) { + throw new CloudRuntimeException("Wrong number of PXE server found in zone " + vm.getDataCenterIdToDeployIn() + + " Pod " + vm.getPodIdToDeployIn() + ", number is " + servers.size()); + } + HostVO pxeServer = servers.get(0); + cmd.setNextServer(pxeServer.getPrivateIpAddress()); + s_logger.debug("Set next-server to " + pxeServer.getPrivateIpAddress() + " for VM " + vm.getId()); + } + + @Override + public boolean addVirtualMachineIntoNetwork(Network network, NicProfile nic, VirtualMachineProfile profile, DeployDestination dest, + ReservationContext context) throws ResourceUnavailableException { + Long zoneId = profile.getVirtualMachine().getDataCenterIdToDeployIn(); + Long podId = profile.getVirtualMachine().getPodIdToDeployIn(); + List hosts = _resourceMgr.listAllUpAndEnabledHosts(Type.ExternalDhcp, null, podId, zoneId); + if (hosts.size() == 0) { + throw new CloudRuntimeException("No external Dhcp found in zone " + zoneId + " pod " + podId); + } + + if (hosts.size() > 1) { + throw new CloudRuntimeException("Something wrong, more than 1 external Dhcp found in zone " + zoneId + " pod " + podId); + } + + HostVO h = hosts.get(0); + String dns = nic.getDns1(); + if (dns == null) { + dns = nic.getDns2(); + } + DhcpEntryCommand dhcpCommand = new DhcpEntryCommand(nic.getMacAddress(), nic.getIp4Address(), profile.getVirtualMachine().getHostName(), dns, nic.getGateway()); + String errMsg = String.format("Set dhcp entry on external DHCP %1$s failed(ip=%2$s, mac=%3$s, vmname=%4$s)", + h.getPrivateIpAddress(), nic.getIp4Address(), nic.getMacAddress(), profile.getVirtualMachine().getHostName()); + //prepareBareMetalDhcpEntry(nic, dhcpCommand); + try { + Answer ans = _agentMgr.send(h.getId(), dhcpCommand); + if (ans.getResult()) { + s_logger.debug(String.format("Set dhcp entry on external DHCP %1$s successfully(ip=%2$s, mac=%3$s, vmname=%4$s)", + h.getPrivateIpAddress(), nic.getIp4Address(), nic.getMacAddress(), profile.getVirtualMachine().getHostName())); + return true; + } else { + s_logger.debug(errMsg + " " + ans.getDetails()); + throw new ResourceUnavailableException(errMsg, DataCenter.class, zoneId); + } + } catch (Exception e) { + s_logger.debug(errMsg, e); + throw new ResourceUnavailableException(errMsg + e.getMessage(), DataCenter.class, zoneId); + } + } + + @Override + public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { + // TODO Auto-generated method stub + return null; + } + + @Override public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { if (!(startup[0] instanceof StartupExternalDhcpCommand)) { return null; } - + host.setType(Host.Type.ExternalDhcp); return host; } - @Override + @Override public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } } diff --git a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java index deb5595bbc7..8e8fdf19bc3 100755 --- a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java +++ b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java @@ -224,7 +224,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx RulesManager _rulesMgr; @Inject IPAddressDao _ipAddressDao; - + private ConsoleProxyListener _listener; private ServiceOfferingVO _serviceOffering; @@ -257,7 +257,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx private Map _zoneHostInfoMap; // map private Map _zoneProxyCountMap; // map private Map _zoneVmCountMap; // map - + private String _hashKey; private final GlobalLock _allocProxyLock = GlobalLock.getInternLock(getAllocProxyLockName()); @@ -879,26 +879,26 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx } if(!cmd.isReauthenticating()) { - String ticket = ConsoleProxyServlet.genAccessTicket(cmd.getHost(), cmd.getPort(), cmd.getSid(), cmd.getVmId()); - if (s_logger.isDebugEnabled()) { - s_logger.debug("Console authentication. Ticket in 1 minute boundary for " + cmd.getHost() + ":" + cmd.getPort() + "-" + cmd.getVmId() + " is " + ticket); - } - - if (!ticket.equals(ticketInUrl)) { - Date now = new Date(); - // considering of minute round-up - String minuteEarlyTicket = ConsoleProxyServlet.genAccessTicket(cmd.getHost(), cmd.getPort(), cmd.getSid(), cmd.getVmId(), new Date(now.getTime() - 60 * 1000)); - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Console authentication. Ticket in 2-minute boundary for " + cmd.getHost() + ":" + cmd.getPort() + "-" + cmd.getVmId() + " is " + minuteEarlyTicket); - } - - if (!minuteEarlyTicket.equals(ticketInUrl)) { - s_logger.error("Access ticket expired or has been modified. vmId: " + cmd.getVmId() + "ticket in URL: " + ticketInUrl + ", tickets to check against: " + ticket + "," - + minuteEarlyTicket); - return new ConsoleAccessAuthenticationAnswer(cmd, false); - } - } + String ticket = ConsoleProxyServlet.genAccessTicket(cmd.getHost(), cmd.getPort(), cmd.getSid(), cmd.getVmId()); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Console authentication. Ticket in 1 minute boundary for " + cmd.getHost() + ":" + cmd.getPort() + "-" + cmd.getVmId() + " is " + ticket); + } + + if (!ticket.equals(ticketInUrl)) { + Date now = new Date(); + // considering of minute round-up + String minuteEarlyTicket = ConsoleProxyServlet.genAccessTicket(cmd.getHost(), cmd.getPort(), cmd.getSid(), cmd.getVmId(), new Date(now.getTime() - 60 * 1000)); + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Console authentication. Ticket in 2-minute boundary for " + cmd.getHost() + ":" + cmd.getPort() + "-" + cmd.getVmId() + " is " + minuteEarlyTicket); + } + + if (!minuteEarlyTicket.equals(ticketInUrl)) { + s_logger.error("Access ticket expired or has been modified. vmId: " + cmd.getVmId() + "ticket in URL: " + ticketInUrl + ", tickets to check against: " + ticket + "," + + minuteEarlyTicket); + return new ConsoleAccessAuthenticationAnswer(cmd, false); + } + } } if (cmd.getVmId() != null && cmd.getVmId().isEmpty()) { @@ -935,38 +935,38 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx s_logger.warn("sid " + sid + " in url does not match stored sid " + vm.getVncPassword()); return new ConsoleAccessAuthenticationAnswer(cmd, false); } - + if(cmd.isReauthenticating()) { ConsoleAccessAuthenticationAnswer authenticationAnswer = new ConsoleAccessAuthenticationAnswer(cmd, true); authenticationAnswer.setReauthenticating(true); s_logger.info("Re-authentication request, ask host " + vm.getHostId() + " for new console info"); - GetVncPortAnswer answer = (GetVncPortAnswer) _agentMgr.easySend(vm.getHostId(), new - GetVncPortCommand(vm.getId(), vm.getInstanceName())); + GetVncPortAnswer answer = (GetVncPortAnswer) _agentMgr.easySend(vm.getHostId(), new + GetVncPortCommand(vm.getId(), vm.getInstanceName())); if (answer != null && answer.getResult()) { - Ternary parsedHostInfo = ConsoleProxyServlet.parseHostInfo(answer.getAddress()); - - if(parsedHostInfo.second() != null && parsedHostInfo.third() != null) { - + Ternary parsedHostInfo = ConsoleProxyServlet.parseHostInfo(answer.getAddress()); + + if(parsedHostInfo.second() != null && parsedHostInfo.third() != null) { + s_logger.info("Re-authentication result. vm: " + vm.getId() + ", tunnel url: " + parsedHostInfo.second() - + ", tunnel session: " + parsedHostInfo.third()); - - authenticationAnswer.setTunnelUrl(parsedHostInfo.second()); - authenticationAnswer.setTunnelSession(parsedHostInfo.third()); - } else { + + ", tunnel session: " + parsedHostInfo.third()); + + authenticationAnswer.setTunnelUrl(parsedHostInfo.second()); + authenticationAnswer.setTunnelSession(parsedHostInfo.third()); + } else { s_logger.info("Re-authentication result. vm: " + vm.getId() + ", host address: " + parsedHostInfo.first() - + ", port: " + answer.getPort()); - - authenticationAnswer.setHost(parsedHostInfo.first()); - authenticationAnswer.setPort(answer.getPort()); - } + + ", port: " + answer.getPort()); + + authenticationAnswer.setHost(parsedHostInfo.first()); + authenticationAnswer.setPort(answer.getPort()); + } } else { s_logger.warn("Re-authentication request failed"); - - authenticationAnswer.setSuccess(false); + + authenticationAnswer.setSuccess(false); } - + return authenticationAnswer; } @@ -1383,7 +1383,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx result = result && _hostDao.remove(host.getId()); } } - + return result; } catch (ResourceUnavailableException e) { s_logger.warn("Unable to expunge " + proxy, e); @@ -1497,7 +1497,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx _itMgr.registerGuru(VirtualMachine.Type.ConsoleProxy, this); boolean useLocalStorage = Boolean.parseBoolean(configs.get(Config.SystemVMUseLocalStorage.key())); - + //check if there is a default service offering configured String cpvmSrvcOffIdStr = configs.get(Config.ConsoleProxyServiceOffering.key()); if (cpvmSrvcOffIdStr != null) { @@ -1538,7 +1538,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx // verify parameters ConsoleProxyVO proxy = _consoleProxyDao.findById(proxyId); if (proxy == null) { - throw new InvalidParameterValueException("unable to find a console proxy with id " + proxyId); + throw new InvalidParameterValueException("unable to find a console proxy by id", null); } return destroyProxy(proxyId); @@ -1981,7 +1981,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx sc.addAnd(sc.getEntity().getName(), Op.EQ, name); return sc.find(); } - + public String getHashKey() { // although we may have race conditioning here, database transaction serialization should // give us the same key @@ -2007,15 +2007,15 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx throw new UnsupportedOperationException("Unplug nic is not supported for vm of type " + vm.getType()); } - @Override - public void prepareStop(VirtualMachineProfile profile) { - } + @Override + public void prepareStop(VirtualMachineProfile profile) { + } - @Override - public boolean recreateNeeded( - VirtualMachineProfile profile, long hostId, - Commands cmds, ReservationContext context) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean recreateNeeded( + VirtualMachineProfile profile, long hostId, + Commands cmds, ReservationContext context) { + // TODO Auto-generated method stub + return false; + } } diff --git a/server/src/com/cloud/netapp/NetappManagerImpl.java b/server/src/com/cloud/netapp/NetappManagerImpl.java index 4b6ea969926..49a2573db4c 100644 --- a/server/src/com/cloud/netapp/NetappManagerImpl.java +++ b/server/src/com/cloud/netapp/NetappManagerImpl.java @@ -48,59 +48,59 @@ import com.cloud.utils.exception.CloudRuntimeException; @Local(value = { NetappManager.class }) public class NetappManagerImpl implements NetappManager { - public enum Algorithm { roundrobin,leastfull } + public enum Algorithm { roundrobin,leastfull } protected String _name; - + public static final Logger s_logger = Logger.getLogger(NetappManagerImpl.class.getName()); @Inject public VolumeDao _volumeDao; @Inject public PoolDao _poolDao; @Inject public LunDao _lunDao; private NetappAllocator _netappAllocator = null; - + /** * Default constructor */ public NetappManagerImpl(){ } - + @Override public void createPool(String poolName, String algorithm) throws InvalidParameterValueException { - if(s_logger.isDebugEnabled()) - s_logger.debug("Request --> createPool "); - - PoolVO pool = null; - validAlgorithm(algorithm); - try { - pool = new PoolVO(poolName, algorithm); - _poolDao.persist(pool); - - if(s_logger.isDebugEnabled()) - s_logger.debug("Response --> createPool:success"); - - } catch (CloudRuntimeException cre){ - pool = _poolDao.findPool(poolName); - if (pool != null) { - throw new InvalidParameterValueException("Duplicate Pool Name"); - } else { - throw cre; - } - } + if(s_logger.isDebugEnabled()) + s_logger.debug("Request --> createPool "); + + PoolVO pool = null; + validAlgorithm(algorithm); + try { + pool = new PoolVO(poolName, algorithm); + _poolDao.persist(pool); + + if(s_logger.isDebugEnabled()) + s_logger.debug("Response --> createPool:success"); + + } catch (CloudRuntimeException cre){ + pool = _poolDao.findPool(poolName); + if (pool != null) { + throw new InvalidParameterValueException("Duplicate Pool Name", null); + } else { + throw cre; + } + } } - + /** * This method validates the algorithm used for allocation of the volume * @param algorithm -- algorithm type * @throws InvalidParameterValueException */ private void validAlgorithm(String algorithm) throws InvalidParameterValueException { - //TODO: use enum - if(!algorithm.equalsIgnoreCase("roundrobin") && !algorithm.equalsIgnoreCase("leastfull")){ - throw new InvalidParameterValueException("Unknown algorithm " + algorithm); - } + //TODO: use enum + if(!algorithm.equalsIgnoreCase("roundrobin") && !algorithm.equalsIgnoreCase("leastfull")){ + throw new InvalidParameterValueException("Unknown algorithm " + algorithm, null); + } } - + /** * Utility method to get the netapp server object * @param serverIp -- ip address of netapp box @@ -110,61 +110,61 @@ public class NetappManagerImpl implements NetappManager * @throws UnknownHostException */ private NaServer getServer(String serverIp, String userName, String password) throws UnknownHostException { - //Initialize connection to server, and - //request version 1.3 of the API set - NaServer s = new NaServer(serverIp, 1, 3); - s.setStyle(NaServer.STYLE_LOGIN_PASSWORD); - s.setAdminUser(userName, password); - - return s; + //Initialize connection to server, and + //request version 1.3 of the API set + NaServer s = new NaServer(serverIp, 1, 3); + s.setStyle(NaServer.STYLE_LOGIN_PASSWORD); + s.setAdminUser(userName, password); + + return s; } - + @Override public void modifyPool(String poolName, String algorithm) throws InvalidParameterValueException { - validAlgorithm(algorithm); - PoolVO pool = _poolDao.findPool(poolName); - - if(pool == null){ - throw new InvalidParameterValueException("Cannot find pool " + poolName); - } - - validAlgorithm(algorithm); - - pool.setAlgorithm(algorithm); - pool.setName(poolName); - - _poolDao.update(pool.getId(), pool); + validAlgorithm(algorithm); + PoolVO pool = _poolDao.findPool(poolName); + + if(pool == null){ + throw new InvalidParameterValueException("Cannot find pool " + poolName, null); + } + + validAlgorithm(algorithm); + + pool.setAlgorithm(algorithm); + pool.setName(poolName); + + _poolDao.update(pool.getId(), pool); } - + @Override public void deletePool(String poolName) throws InvalidParameterValueException, ResourceInUseException { - if(s_logger.isDebugEnabled()) - s_logger.debug("Request --> deletePool "); - - PoolVO pool = _poolDao.findPool(poolName); - if(pool == null){ - throw new InvalidParameterValueException("Cannot find pool " + poolName); - } - //check if pool is empty - int volCount = _volumeDao.listVolumes(poolName).size(); + if(s_logger.isDebugEnabled()) + s_logger.debug("Request --> deletePool "); - if(volCount==0){ - _poolDao.remove(pool.getId()); - if(s_logger.isDebugEnabled()) - s_logger.debug("Request --> deletePool: Success "); - - } else { - throw new ResourceInUseException("Cannot delete non-empty pool"); - } + PoolVO pool = _poolDao.findPool(poolName); + if(pool == null){ + throw new InvalidParameterValueException("Cannot find pool " + poolName, null); + } + //check if pool is empty + int volCount = _volumeDao.listVolumes(poolName).size(); + + if(volCount==0){ + _poolDao.remove(pool.getId()); + if(s_logger.isDebugEnabled()) + s_logger.debug("Request --> deletePool: Success "); + + } else { + throw new ResourceInUseException("Cannot delete non-empty pool"); + } } - + @Override public List listPools(){ - return _poolDao.listAll(); + return _poolDao.listAll(); } - + /** * This method destroys the volume on netapp filer * @param ipAddress -- ip address of filer @@ -180,90 +180,90 @@ public class NetappManagerImpl implements NetappManager @Override @DB public void destroyVolumeOnFiler(String ipAddress, String aggrName, String volName) throws ServerException, InvalidParameterValueException, ResourceInUseException{ - NaElement xi0; - NaElement xi1; - NetappVolumeVO volume = null; - - volume = _volumeDao.findVolume(ipAddress, aggrName, volName); - - if(volume==null) - { - s_logger.warn("The volume does not exist in our system"); - throw new InvalidParameterValueException("The given tuple:"+ipAddress+","+aggrName+","+volName+" doesn't exist in our system"); - } + NaElement xi0; + NaElement xi1; + NetappVolumeVO volume = null; - List lunsOnVol = _lunDao.listLunsByVolId(volume.getId()); - - if(lunsOnVol!=null && lunsOnVol.size()>0) - { - s_logger.warn("There are luns on the volume"); - throw new ResourceInUseException("There are luns on the volume"); - } - - final Transaction txn = Transaction.currentTxn(); - txn.start(); - PoolVO pool = _poolDao.findById(volume.getPoolId()); - if (pool == null) { - throw new InvalidParameterValueException("Failed to find pool for given volume"); - //FIXME: choose a better exception. this is a db integrity exception - } - pool = _poolDao.acquireInLockTable(pool.getId()); - if (pool == null) { - throw new ConcurrentModificationException("Failed to acquire lock on pool " + volume.getPoolId()); - } - NaServer s = null; - try - { - s = getServer(volume.getIpAddress(), volume.getUsername(), volume.getPassword()); - //bring the volume down - xi0 = new NaElement("volume-offline"); - xi0.addNewChild("name",volName); - s.invokeElem(xi0); + volume = _volumeDao.findVolume(ipAddress, aggrName, volName); - //now destroy it - xi1 = new NaElement("volume-destroy"); - xi1.addNewChild("name",volName); - s.invokeElem(xi1); + if(volume==null) + { + s_logger.warn("The volume does not exist in our system"); + throw new InvalidParameterValueException("The given tuple:"+ipAddress+","+aggrName+","+volName+" doesn't exist in our system", null); + } - //now delete from our records - _volumeDao.remove(volume.getId()); - txn.commit(); + List lunsOnVol = _lunDao.listLunsByVolId(volume.getId()); + + if(lunsOnVol!=null && lunsOnVol.size()>0) + { + s_logger.warn("There are luns on the volume"); + throw new ResourceInUseException("There are luns on the volume"); + } + + final Transaction txn = Transaction.currentTxn(); + txn.start(); + PoolVO pool = _poolDao.findById(volume.getPoolId()); + if (pool == null) { + throw new InvalidParameterValueException("Failed to find pool for given volume", null); + //FIXME: choose a better exception. this is a db integrity exception + } + pool = _poolDao.acquireInLockTable(pool.getId()); + if (pool == null) { + throw new ConcurrentModificationException("Failed to acquire lock on pool " + volume.getPoolId()); + } + NaServer s = null; + try + { + s = getServer(volume.getIpAddress(), volume.getUsername(), volume.getPassword()); + //bring the volume down + xi0 = new NaElement("volume-offline"); + xi0.addNewChild("name",volName); + s.invokeElem(xi0); + + //now destroy it + xi1 = new NaElement("volume-destroy"); + xi1.addNewChild("name",volName); + s.invokeElem(xi1); + + //now delete from our records + _volumeDao.remove(volume.getId()); + txn.commit(); + + } catch (UnknownHostException uhe) { + s_logger.warn("Unable to delete volume on filer " , uhe); + throw new ServerException("Unable to delete volume on filer", uhe); + }catch (NaAPIFailedException naf) { + s_logger.warn("Unable to delete volume on filer " , naf); + if( naf.getErrno() == 13040 ){ + s_logger.info("Deleting the volume: " + volName); + _volumeDao.remove(volume.getId()); + txn.commit(); + } + + throw new ServerException("Unable to delete volume on filer", naf); + } + catch (NaException nae) { + txn.rollback(); + s_logger.warn("Unable to delete volume on filer " , nae); + throw new ServerException("Unable to delete volume on filer", nae); + } catch (IOException ioe) { + txn.rollback(); + s_logger.warn("Unable to delete volume on filer " , ioe); + throw new ServerException("Unable to delete volume on filer", ioe); + } + finally + { + if (pool != null) { + _poolDao.releaseFromLockTable(pool.getId()); + } + if (s != null) + s.close(); + } - } catch (UnknownHostException uhe) { - s_logger.warn("Unable to delete volume on filer " , uhe); - throw new ServerException("Unable to delete volume on filer", uhe); - }catch (NaAPIFailedException naf) { - s_logger.warn("Unable to delete volume on filer " , naf); - if( naf.getErrno() == 13040 ){ - s_logger.info("Deleting the volume: " + volName); - _volumeDao.remove(volume.getId()); - txn.commit(); - } - - throw new ServerException("Unable to delete volume on filer", naf); - } - catch (NaException nae) { - txn.rollback(); - s_logger.warn("Unable to delete volume on filer " , nae); - throw new ServerException("Unable to delete volume on filer", nae); - } catch (IOException ioe) { - txn.rollback(); - s_logger.warn("Unable to delete volume on filer " , ioe); - throw new ServerException("Unable to delete volume on filer", ioe); - } - finally - { - if (pool != null) { - _poolDao.releaseFromLockTable(pool.getId()); - } - if (s != null) - s.close(); - } - } - + /** * This method creates a volume on netapp filer * @param ipAddress -- ip address of the filer @@ -280,169 +280,169 @@ public class NetappManagerImpl implements NetappManager */ @Override @DB - public void createVolumeOnFiler(String ipAddress, String aggName, String poolName, String volName, String volSize, String snapshotPolicy, Integer snapshotReservation, String username, String password) throws UnknownHostException, ServerException, InvalidParameterValueException - { - - if(s_logger.isDebugEnabled()) - s_logger.debug("Request --> createVolume "+"serverIp:"+ipAddress); - - boolean snapPolicy = false; - boolean snapshotRes = false; - boolean volumeCreated = false; - - NaServer s = getServer(ipAddress, username, password); - - NaElement xi = new NaElement("volume-create"); - xi.addNewChild("volume", volName); - xi.addNewChild("containing-aggr-name",aggName); - xi.addNewChild("size",volSize); - - NaElement xi1 = new NaElement("snapshot-set-reserve"); - if(snapshotReservation!=null) - { - snapshotRes = true; - xi1.addNewChild("percentage",snapshotReservation.toString()); - xi1.addNewChild("volume",volName); - } - - NaElement xi2 = new NaElement("snapshot-set-schedule"); - - if(snapshotPolicy!=null) - { - snapPolicy = true; - - String weeks = null; - String days = null; - String hours = null; - String whichHours = null; - String minutes = null; - String whichMinutes = null; - - StringTokenizer s1 = new StringTokenizer(snapshotPolicy," "); - - //count=4: weeks days hours@csi mins@csi - //count=3: weeks days hours@csi - //count=2: weeks days - //count=1: weeks - - if(s1.hasMoreTokens()) - { - weeks = s1.nextToken(); - } - if(weeks!=null && s1.hasMoreTokens()) - { - days = s1.nextToken(); - } - if(days!=null && s1.hasMoreTokens()) - { - String[] hoursArr = s1.nextToken().split("@"); - hours = hoursArr[0]; - whichHours = hoursArr[1]; - } - if(hours!=null && s1.hasMoreTokens()) - { - String[] minsArr = s1.nextToken().split("@"); - minutes = minsArr[0]; - whichMinutes = minsArr[1]; - } - - if(weeks!=null) - xi2.addNewChild("weeks",weeks); - if(days!=null) - xi2.addNewChild("days",days); - if(hours!=null) - xi2.addNewChild("hours",hours); - if(minutes!=null) - xi2.addNewChild("minutes",minutes); - xi2.addNewChild("volume",volName); - - if(whichHours!=null) - xi2.addNewChild("which-hours",whichHours); - if(whichMinutes!=null) - xi2.addNewChild("which-minutes",whichMinutes); - } - Long volumeId = null; - - final Transaction txn = Transaction.currentTxn(); - txn.start(); - NetappVolumeVO volume = null; - volume = _volumeDao.findVolume(ipAddress, aggName, volName); - - if(volume != null) { - throw new InvalidParameterValueException("The volume for the given ipAddress/aggregateName/volumeName tuple already exists"); - } - PoolVO pool = _poolDao.findPool(poolName); - if (pool == null) { - throw new InvalidParameterValueException("Cannot find pool " + poolName); - } - pool = _poolDao.acquireInLockTable(pool.getId()); - if (pool == null) { - s_logger.warn("Failed to acquire lock on pool " + poolName); - throw new ConcurrentModificationException("Failed to acquire lock on pool " + poolName); - } - volume = new NetappVolumeVO(ipAddress, aggName, pool.getId(), volName, volSize, "", 0, username, password,0,pool.getName()); - volume = _volumeDao.persist(volume); - - volumeId = volume.getId(); - try { - s.invokeElem(xi); - volumeCreated = true; - - if(snapshotRes) - { - s.invokeElem(xi1); - volume.setSnapshotReservation(snapshotReservation); - _volumeDao.update(volumeId, volume); - } + public void createVolumeOnFiler(String ipAddress, String aggName, String poolName, String volName, String volSize, String snapshotPolicy, Integer snapshotReservation, String username, String password) throws UnknownHostException, ServerException, InvalidParameterValueException + { + + if(s_logger.isDebugEnabled()) + s_logger.debug("Request --> createVolume "+"serverIp:"+ipAddress); + + boolean snapPolicy = false; + boolean snapshotRes = false; + boolean volumeCreated = false; + + NaServer s = getServer(ipAddress, username, password); + + NaElement xi = new NaElement("volume-create"); + xi.addNewChild("volume", volName); + xi.addNewChild("containing-aggr-name",aggName); + xi.addNewChild("size",volSize); + + NaElement xi1 = new NaElement("snapshot-set-reserve"); + if(snapshotReservation!=null) + { + snapshotRes = true; + xi1.addNewChild("percentage",snapshotReservation.toString()); + xi1.addNewChild("volume",volName); + } + + NaElement xi2 = new NaElement("snapshot-set-schedule"); + + if(snapshotPolicy!=null) + { + snapPolicy = true; + + String weeks = null; + String days = null; + String hours = null; + String whichHours = null; + String minutes = null; + String whichMinutes = null; + + StringTokenizer s1 = new StringTokenizer(snapshotPolicy," "); + + //count=4: weeks days hours@csi mins@csi + //count=3: weeks days hours@csi + //count=2: weeks days + //count=1: weeks + + if(s1.hasMoreTokens()) + { + weeks = s1.nextToken(); + } + if(weeks!=null && s1.hasMoreTokens()) + { + days = s1.nextToken(); + } + if(days!=null && s1.hasMoreTokens()) + { + String[] hoursArr = s1.nextToken().split("@"); + hours = hoursArr[0]; + whichHours = hoursArr[1]; + } + if(hours!=null && s1.hasMoreTokens()) + { + String[] minsArr = s1.nextToken().split("@"); + minutes = minsArr[0]; + whichMinutes = minsArr[1]; + } + + if(weeks!=null) + xi2.addNewChild("weeks",weeks); + if(days!=null) + xi2.addNewChild("days",days); + if(hours!=null) + xi2.addNewChild("hours",hours); + if(minutes!=null) + xi2.addNewChild("minutes",minutes); + xi2.addNewChild("volume",volName); + + if(whichHours!=null) + xi2.addNewChild("which-hours",whichHours); + if(whichMinutes!=null) + xi2.addNewChild("which-minutes",whichMinutes); + } + Long volumeId = null; + + final Transaction txn = Transaction.currentTxn(); + txn.start(); + NetappVolumeVO volume = null; + volume = _volumeDao.findVolume(ipAddress, aggName, volName); + + if(volume != null) { + throw new InvalidParameterValueException("The volume for the given ipAddress/aggregateName/volumeName tuple already exists", null); + } + PoolVO pool = _poolDao.findPool(poolName); + if (pool == null) { + throw new InvalidParameterValueException("Cannot find pool " + poolName, null); + } + pool = _poolDao.acquireInLockTable(pool.getId()); + if (pool == null) { + s_logger.warn("Failed to acquire lock on pool " + poolName); + throw new ConcurrentModificationException("Failed to acquire lock on pool " + poolName); + } + volume = new NetappVolumeVO(ipAddress, aggName, pool.getId(), volName, volSize, "", 0, username, password,0,pool.getName()); + volume = _volumeDao.persist(volume); + + volumeId = volume.getId(); + try { + s.invokeElem(xi); + volumeCreated = true; + + if(snapshotRes) + { + s.invokeElem(xi1); + volume.setSnapshotReservation(snapshotReservation); + _volumeDao.update(volumeId, volume); + } + + if(snapPolicy) + { + s.invokeElem(xi2); + volume.setSnapshotPolicy(snapshotPolicy); + _volumeDao.update(volumeId, volume); + } + txn.commit(); + } catch (NaException nae) { + //zapi call failed, log and throw e + s_logger.warn("Failed to create volume on the netapp filer:", nae); + txn.rollback(); + if(volumeCreated) { + try { + deleteRogueVolume(volName, s);//deletes created volume on filer + } catch (NaException e) { + s_logger.warn("Failed to cleanup created volume whilst rolling back on the netapp filer:", e); + throw new ServerException("Unable to create volume via cloudtools."+"Failed to cleanup created volume on netapp filer whilst rolling back on the cloud db:", e); + } catch (IOException e) { + s_logger.warn("Failed to cleanup created volume whilst rolling back on the netapp filer:", e); + throw new ServerException("Unable to create volume via cloudtools."+"Failed to cleanup created volume on netapp filer whilst rolling back on the cloud db:", e); + } + } + throw new ServerException("Unable to create volume", nae); + } catch (IOException ioe) { + s_logger.warn("Failed to create volume on the netapp filer:", ioe); + txn.rollback(); + if(volumeCreated) { + try { + deleteRogueVolume(volName, s);//deletes created volume on filer + } catch (NaException e) { + s_logger.warn("Failed to cleanup created volume whilst rolling back on the netapp filer:", e); + throw new ServerException("Unable to create volume via cloudtools."+"Failed to cleanup created volume on netapp filer whilst rolling back on the cloud db:", e); + } catch (IOException e) { + s_logger.warn("Failed to cleanup created volume whilst rolling back on the netapp filer:", e); + throw new ServerException("Unable to create volume via cloudtools."+"Failed to cleanup created volume on netapp filer whilst rolling back on the cloud db:", e); + } + } + throw new ServerException("Unable to create volume", ioe); + } + finally{ + if (s != null) + s.close(); + if (pool != null) + _poolDao.releaseFromLockTable(pool.getId()); + + } + } - if(snapPolicy) - { - s.invokeElem(xi2); - volume.setSnapshotPolicy(snapshotPolicy); - _volumeDao.update(volumeId, volume); - } - txn.commit(); - } catch (NaException nae) { - //zapi call failed, log and throw e - s_logger.warn("Failed to create volume on the netapp filer:", nae); - txn.rollback(); - if(volumeCreated) { - try { - deleteRogueVolume(volName, s);//deletes created volume on filer - } catch (NaException e) { - s_logger.warn("Failed to cleanup created volume whilst rolling back on the netapp filer:", e); - throw new ServerException("Unable to create volume via cloudtools."+"Failed to cleanup created volume on netapp filer whilst rolling back on the cloud db:", e); - } catch (IOException e) { - s_logger.warn("Failed to cleanup created volume whilst rolling back on the netapp filer:", e); - throw new ServerException("Unable to create volume via cloudtools."+"Failed to cleanup created volume on netapp filer whilst rolling back on the cloud db:", e); - } - } - throw new ServerException("Unable to create volume", nae); - } catch (IOException ioe) { - s_logger.warn("Failed to create volume on the netapp filer:", ioe); - txn.rollback(); - if(volumeCreated) { - try { - deleteRogueVolume(volName, s);//deletes created volume on filer - } catch (NaException e) { - s_logger.warn("Failed to cleanup created volume whilst rolling back on the netapp filer:", e); - throw new ServerException("Unable to create volume via cloudtools."+"Failed to cleanup created volume on netapp filer whilst rolling back on the cloud db:", e); - } catch (IOException e) { - s_logger.warn("Failed to cleanup created volume whilst rolling back on the netapp filer:", e); - throw new ServerException("Unable to create volume via cloudtools."+"Failed to cleanup created volume on netapp filer whilst rolling back on the cloud db:", e); - } - } - throw new ServerException("Unable to create volume", ioe); - } - finally{ - if (s != null) - s.close(); - if (pool != null) - _poolDao.releaseFromLockTable(pool.getId()); - - } - } - /** * This method is primarily used to cleanup volume created on the netapp filer, when createVol api command fails at snapshot reservation. * We roll back the db record, but the record on the netapp box still exists. We clean up that record using this helper method. @@ -452,40 +452,40 @@ public class NetappManagerImpl implements NetappManager * @throws IOException */ private void deleteRogueVolume(String volName, NaServer s) throws NaException, IOException { - //bring the volume down - NaElement xi0 = new NaElement("volume-offline"); - xi0.addNewChild("name",volName); - s.invokeElem(xi0); + //bring the volume down + NaElement xi0 = new NaElement("volume-offline"); + xi0.addNewChild("name",volName); + s.invokeElem(xi0); - //now destroy it - NaElement xi1 = new NaElement("volume-destroy"); - xi1.addNewChild("name",volName); - s.invokeElem(xi1); + //now destroy it + NaElement xi1 = new NaElement("volume-destroy"); + xi1.addNewChild("name",volName); + s.invokeElem(xi1); } - - /** - * This method lists all the volumes by pool name - * @param poolName - * @return -- volumes in that pool - */ - @Override - public List listVolumesOnFiler(String poolName){ - - List vols = _volumeDao.listVolumesAscending(poolName); - - for(NetappVolumeVO vol : vols){ - try { - String snapScheduleOnFiler = returnSnapshotSchedule(vol); - vol.setSnapshotPolicy(snapScheduleOnFiler); - - } catch (ServerException e) { - s_logger.warn("Error trying to get snapshot schedule for volume"+vol.getVolumeName()); - } - } - return vols; - } - + /** + * This method lists all the volumes by pool name + * @param poolName + * @return -- volumes in that pool + */ + @Override + public List listVolumesOnFiler(String poolName){ + + List vols = _volumeDao.listVolumesAscending(poolName); + + for(NetappVolumeVO vol : vols){ + try { + String snapScheduleOnFiler = returnSnapshotSchedule(vol); + vol.setSnapshotPolicy(snapScheduleOnFiler); + + } catch (ServerException e) { + s_logger.warn("Error trying to get snapshot schedule for volume"+vol.getVolumeName()); + } + } + return vols; + } + + /** * Utility method to return snapshot schedule for a volume * @param vol -- volume for the snapshot schedule creation @@ -494,543 +494,543 @@ public class NetappManagerImpl implements NetappManager */ private String returnSnapshotSchedule(NetappVolumeVO vol) throws ServerException{ - NaElement xi = new NaElement("snapshot-get-schedule"); - xi.addNewChild("volume", vol.getVolumeName()); - NaServer s = null; - try { - s = getServer(vol.getIpAddress(), vol.getUsername(), vol.getPassword()); - NaElement xo = s.invokeElem(xi); - String weeks = xo.getChildContent("weeks"); - String days = xo.getChildContent("days"); - String hours = xo.getChildContent("hours"); - String minutes = xo.getChildContent("minutes"); - String whichHours = xo.getChildContent("which-hours"); - String whichMinutes = xo.getChildContent("which-minutes"); - - StringBuilder sB = new StringBuilder(); - sB.append(weeks).append(" ").append(days).append(" ").append(hours).append("@").append(whichHours).append(" ").append(minutes).append("@").append(whichMinutes); - return sB.toString(); - } catch (NaException nae) { - s_logger.warn("Failed to get volume size ", nae); - throw new ServerException("Failed to get volume size", nae); - } catch (IOException ioe) { - s_logger.warn("Failed to get volume size ", ioe); - throw new ServerException("Failed to get volume size", ioe); - } - finally{ - if (s != null) - s.close(); - } + NaElement xi = new NaElement("snapshot-get-schedule"); + xi.addNewChild("volume", vol.getVolumeName()); + NaServer s = null; + try { + s = getServer(vol.getIpAddress(), vol.getUsername(), vol.getPassword()); + NaElement xo = s.invokeElem(xi); + String weeks = xo.getChildContent("weeks"); + String days = xo.getChildContent("days"); + String hours = xo.getChildContent("hours"); + String minutes = xo.getChildContent("minutes"); + String whichHours = xo.getChildContent("which-hours"); + String whichMinutes = xo.getChildContent("which-minutes"); + + StringBuilder sB = new StringBuilder(); + sB.append(weeks).append(" ").append(days).append(" ").append(hours).append("@").append(whichHours).append(" ").append(minutes).append("@").append(whichMinutes); + return sB.toString(); + } catch (NaException nae) { + s_logger.warn("Failed to get volume size ", nae); + throw new ServerException("Failed to get volume size", nae); + } catch (IOException ioe) { + s_logger.warn("Failed to get volume size ", ioe); + throw new ServerException("Failed to get volume size", ioe); + } + finally{ + if (s != null) + s.close(); + } } - /** - * This method returns the ascending order list of volumes based on their ids - * @param poolName -- name of pool - * @return -- ascending ordered list of volumes based on ids - */ + /** + * This method returns the ascending order list of volumes based on their ids + * @param poolName -- name of pool + * @return -- ascending ordered list of volumes based on ids + */ @Override - public List listVolumesAscending(String poolName){ - return _volumeDao.listVolumesAscending(poolName); - } - - /** - * This method returns the available size on the volume in terms of bytes - * @param volName -- name of volume - * @param userName -- username - * @param password -- password - * @param serverIp -- ip address of filer - * @throws UnknownHostException - * @return-- available size on the volume in terms of bytes; return -1 if volume is offline - * @throws ServerException - */ + public List listVolumesAscending(String poolName){ + return _volumeDao.listVolumesAscending(poolName); + } + + /** + * This method returns the available size on the volume in terms of bytes + * @param volName -- name of volume + * @param userName -- username + * @param password -- password + * @param serverIp -- ip address of filer + * @throws UnknownHostException + * @return-- available size on the volume in terms of bytes; return -1 if volume is offline + * @throws ServerException + */ @Override - public long returnAvailableVolumeSize(String volName, String userName, String password, String serverIp) throws ServerException { - long availableSize = 0; + public long returnAvailableVolumeSize(String volName, String userName, String password, String serverIp) throws ServerException { + long availableSize = 0; - NaElement xi = new NaElement("volume-list-info"); - xi.addNewChild("volume", volName); - NaServer s = null; - String volumeState = null; - try { - s = getServer(serverIp, userName, password); - NaElement xo = s.invokeElem(xi); - List volList = xo.getChildByName("volumes").getChildren(); - Iterator volIter = volList.iterator(); - while(volIter.hasNext()){ - NaElement volInfo=(NaElement)volIter.next(); - availableSize = volInfo.getChildLongValue("size-available", -1); - volumeState = volInfo.getChildContent("state"); - } - - if (volumeState != null) { - return volumeState.equalsIgnoreCase("online") ? availableSize : -1; //return -1 if volume is offline - } - else { - //catch all - //volume state unreported - return -1; // as good as volume offline - } - - - } catch (NaException nae) { - s_logger.warn("Failed to get volume size ", nae); - throw new ServerException("Failed to get volume size", nae); - } catch (IOException ioe) { - s_logger.warn("Failed to get volume size ", ioe); - throw new ServerException("Failed to get volume size", ioe); - } - finally{ - if (s != null) - s.close(); - } - } + NaElement xi = new NaElement("volume-list-info"); + xi.addNewChild("volume", volName); + NaServer s = null; + String volumeState = null; + try { + s = getServer(serverIp, userName, password); + NaElement xo = s.invokeElem(xi); + List volList = xo.getChildByName("volumes").getChildren(); + Iterator volIter = volList.iterator(); + while(volIter.hasNext()){ + NaElement volInfo=(NaElement)volIter.next(); + availableSize = volInfo.getChildLongValue("size-available", -1); + volumeState = volInfo.getChildContent("state"); + } - /** - * This method creates a lun on the netapp filer - * @param poolName -- name of the pool - * @param lunSize -- size of the lun to be created - * @return -- lun path - * @throws IOException - * @throws ResourceAllocationException - * @throws NaException - */ + if (volumeState != null) { + return volumeState.equalsIgnoreCase("online") ? availableSize : -1; //return -1 if volume is offline + } + else { + //catch all + //volume state unreported + return -1; // as good as volume offline + } + + + } catch (NaException nae) { + s_logger.warn("Failed to get volume size ", nae); + throw new ServerException("Failed to get volume size", nae); + } catch (IOException ioe) { + s_logger.warn("Failed to get volume size ", ioe); + throw new ServerException("Failed to get volume size", ioe); + } + finally{ + if (s != null) + s.close(); + } + } + + /** + * This method creates a lun on the netapp filer + * @param poolName -- name of the pool + * @param lunSize -- size of the lun to be created + * @return -- lun path + * @throws IOException + * @throws ResourceAllocationException + * @throws NaException + */ @Override @DB - public String[] createLunOnFiler(String poolName, Long lunSize) throws ServerException, InvalidParameterValueException, ResourceAllocationException { - String[] result = new String[3]; - StringBuilder lunName = new StringBuilder("lun-"); - LunVO lun = null; - final Transaction txn = Transaction.currentTxn(); - txn.start(); - PoolVO pool = _poolDao.findPool(poolName); - - if(pool == null){ - throw new InvalidParameterValueException("Cannot find pool " + poolName); - } + public String[] createLunOnFiler(String poolName, Long lunSize) throws ServerException, InvalidParameterValueException, ResourceAllocationException { + String[] result = new String[3]; + StringBuilder lunName = new StringBuilder("lun-"); + LunVO lun = null; + final Transaction txn = Transaction.currentTxn(); + txn.start(); + PoolVO pool = _poolDao.findPool(poolName); - if (lunSize <= 0) { - throw new InvalidParameterValueException("Please specify a valid lun size in Gb"); - } - - String algorithm = pool.getAlgorithm(); - NetappVolumeVO selectedVol = null; + if(pool == null){ + throw new InvalidParameterValueException("Cannot find pool " + poolName, null); + } - //sanity check - int numVolsInPool = _volumeDao.listVolumes(poolName).size(); + if (lunSize <= 0) { + throw new InvalidParameterValueException("Please specify a valid lun size in Gb", null); + } - if (numVolsInPool == 0) - { - throw new InvalidParameterValueException("No volumes exist in the given pool"); - } - pool = _poolDao.acquireInLockTable(pool.getId()); - if (pool == null) { - s_logger.warn("Failed to acquire lock on the pool " + poolName); - return result; - } - NaServer s = null; + String algorithm = pool.getAlgorithm(); + NetappVolumeVO selectedVol = null; - try - { - if(algorithm == null || algorithm.equals(Algorithm.roundrobin.toString())) - { - selectedVol = _netappAllocator.chooseVolumeFromPool(poolName, lunSize); - } - else if(algorithm.equals(Algorithm.leastfull.toString())) - { + //sanity check + int numVolsInPool = _volumeDao.listVolumes(poolName).size(); - selectedVol = _netappAllocator.chooseLeastFullVolumeFromPool(poolName, lunSize); - } + if (numVolsInPool == 0) + { + throw new InvalidParameterValueException("No volumes exist in the given pool", null); + } + pool = _poolDao.acquireInLockTable(pool.getId()); + if (pool == null) { + s_logger.warn("Failed to acquire lock on the pool " + poolName); + return result; + } + NaServer s = null; - if(selectedVol == null) - { - throw new ServerException("Could not find a suitable volume to create lun on"); - } + try + { + if(algorithm == null || algorithm.equals(Algorithm.roundrobin.toString())) + { + selectedVol = _netappAllocator.chooseVolumeFromPool(poolName, lunSize); + } + else if(algorithm.equals(Algorithm.leastfull.toString())) + { - if(s_logger.isDebugEnabled()) - s_logger.debug("Request --> createLun "+"serverIp:"+selectedVol.getIpAddress()); - - StringBuilder exportPath = new StringBuilder("/vol/"); - exportPath.append(selectedVol.getVolumeName()); - exportPath.append("/"); + selectedVol = _netappAllocator.chooseLeastFullVolumeFromPool(poolName, lunSize); + } - lun = new LunVO(exportPath.toString(), selectedVol.getId(), lunSize, "",""); - lun = _lunDao.persist(lun); - - //Lun id created: 6 digits right justified eg. 000045 - String lunIdStr = lun.getId().toString(); - String zeroStr = "000000"; - int length = lunIdStr.length(); - int offset = 6-length; - StringBuilder lunIdOnPath = new StringBuilder(); - lunIdOnPath.append(zeroStr.substring(0, offset)); - lunIdOnPath.append(lunIdStr); - exportPath.append("lun-").append(lunIdOnPath.toString()); - - lunName.append(lunIdOnPath.toString()); - - //update lun name - lun.setLunName(lunName.toString()); - _lunDao.update(lun.getId(), lun); - - NaElement xi; - NaElement xi1; + if(selectedVol == null) + { + throw new ServerException("Could not find a suitable volume to create lun on"); + } - long lSizeBytes = 1L*lunSize*1024*1024*1024; //This prevents integer overflow - Long lunSizeBytes = new Long(lSizeBytes); - - s = getServer(selectedVol.getIpAddress(), selectedVol.getUsername(),selectedVol.getPassword()); + if(s_logger.isDebugEnabled()) + s_logger.debug("Request --> createLun "+"serverIp:"+selectedVol.getIpAddress()); - //create lun - xi = new NaElement("lun-create-by-size"); - xi.addNewChild("ostype","linux"); - xi.addNewChild("path",exportPath.toString()); - xi.addNewChild("size", (lunSizeBytes.toString())); - - s.invokeElem(xi); + StringBuilder exportPath = new StringBuilder("/vol/"); + exportPath.append(selectedVol.getVolumeName()); + exportPath.append("/"); - try - { - //now create an igroup - xi1 = new NaElement("igroup-create"); - xi1.addNewChild("initiator-group-name", lunName .toString()); - xi1.addNewChild("initiator-group-type", "iscsi"); - xi1.addNewChild("os-type", "linux"); - s.invokeElem(xi1); - }catch(NaAPIFailedException e) - { - if(e.getErrno() == 9004) - { - //igroup already exists hence no error - s_logger.warn("Igroup already exists"); - } - } + lun = new LunVO(exportPath.toString(), selectedVol.getId(), lunSize, "",""); + lun = _lunDao.persist(lun); - //get target iqn - NaElement xi4 = new NaElement("iscsi-node-get-name"); - NaElement xo = s.invokeElem(xi4); - String iqn = xo.getChildContent("node-name"); - - lun.setTargetIqn(iqn); - _lunDao.update(lun.getId(), lun); - - //create lun mapping - //now map the lun to the igroup - NaElement xi3 = new NaElement("lun-map"); - xi3.addNewChild("force", "true"); - xi3.addNewChild("initiator-group", lunName.toString()); - xi3.addNewChild("path", lun.getPath() + lun.getLunName()); - - xi3.addNewChild("lun-id", lunIdStr); - s.invokeElem(xi3); - - txn.commit(); - //set the result - result[0] = lunName.toString();//lunname - result[1] = iqn;//iqn - result[2] = selectedVol.getIpAddress(); - - return result; - - } - catch (NaAPIFailedException naf) - { - if(naf.getErrno() == 9023){ //lun is already mapped to this group - result[0] = lunName.toString();//lunname; - result[1] = lun.getTargetIqn();//iqn - result[2] = selectedVol.getIpAddress(); - return result; - } - if(naf.getErrno() == 9024){ //another lun mapped at this group - result[0] = lunName.toString();//lunname; - result[1] = lun.getTargetIqn();//iqn - result[2] = selectedVol.getIpAddress(); - return result; - } - } - catch (NaException nae) - { - txn.rollback(); - throw new ServerException("Unable to create LUN", nae); - } - catch (IOException ioe) - { - txn.rollback(); - throw new ServerException("Unable to create LUN", ioe); - } - finally - { - if (pool != null) { - _poolDao.releaseFromLockTable(pool.getId()); - } - if (s != null) { - s.close(); - } - } + //Lun id created: 6 digits right justified eg. 000045 + String lunIdStr = lun.getId().toString(); + String zeroStr = "000000"; + int length = lunIdStr.length(); + int offset = 6-length; + StringBuilder lunIdOnPath = new StringBuilder(); + lunIdOnPath.append(zeroStr.substring(0, offset)); + lunIdOnPath.append(lunIdStr); + exportPath.append("lun-").append(lunIdOnPath.toString()); - return result; - } - - /** - * This method destroys a lun on the netapp filer - * @param lunName -- name of the lun to be destroyed - */ + lunName.append(lunIdOnPath.toString()); + + //update lun name + lun.setLunName(lunName.toString()); + _lunDao.update(lun.getId(), lun); + + NaElement xi; + NaElement xi1; + + long lSizeBytes = 1L*lunSize*1024*1024*1024; //This prevents integer overflow + Long lunSizeBytes = new Long(lSizeBytes); + + s = getServer(selectedVol.getIpAddress(), selectedVol.getUsername(),selectedVol.getPassword()); + + //create lun + xi = new NaElement("lun-create-by-size"); + xi.addNewChild("ostype","linux"); + xi.addNewChild("path",exportPath.toString()); + xi.addNewChild("size", (lunSizeBytes.toString())); + + s.invokeElem(xi); + + try + { + //now create an igroup + xi1 = new NaElement("igroup-create"); + xi1.addNewChild("initiator-group-name", lunName .toString()); + xi1.addNewChild("initiator-group-type", "iscsi"); + xi1.addNewChild("os-type", "linux"); + s.invokeElem(xi1); + }catch(NaAPIFailedException e) + { + if(e.getErrno() == 9004) + { + //igroup already exists hence no error + s_logger.warn("Igroup already exists"); + } + } + + //get target iqn + NaElement xi4 = new NaElement("iscsi-node-get-name"); + NaElement xo = s.invokeElem(xi4); + String iqn = xo.getChildContent("node-name"); + + lun.setTargetIqn(iqn); + _lunDao.update(lun.getId(), lun); + + //create lun mapping + //now map the lun to the igroup + NaElement xi3 = new NaElement("lun-map"); + xi3.addNewChild("force", "true"); + xi3.addNewChild("initiator-group", lunName.toString()); + xi3.addNewChild("path", lun.getPath() + lun.getLunName()); + + xi3.addNewChild("lun-id", lunIdStr); + s.invokeElem(xi3); + + txn.commit(); + //set the result + result[0] = lunName.toString();//lunname + result[1] = iqn;//iqn + result[2] = selectedVol.getIpAddress(); + + return result; + + } + catch (NaAPIFailedException naf) + { + if(naf.getErrno() == 9023){ //lun is already mapped to this group + result[0] = lunName.toString();//lunname; + result[1] = lun.getTargetIqn();//iqn + result[2] = selectedVol.getIpAddress(); + return result; + } + if(naf.getErrno() == 9024){ //another lun mapped at this group + result[0] = lunName.toString();//lunname; + result[1] = lun.getTargetIqn();//iqn + result[2] = selectedVol.getIpAddress(); + return result; + } + } + catch (NaException nae) + { + txn.rollback(); + throw new ServerException("Unable to create LUN", nae); + } + catch (IOException ioe) + { + txn.rollback(); + throw new ServerException("Unable to create LUN", ioe); + } + finally + { + if (pool != null) { + _poolDao.releaseFromLockTable(pool.getId()); + } + if (s != null) { + s.close(); + } + } + + return result; + } + + /** + * This method destroys a lun on the netapp filer + * @param lunName -- name of the lun to be destroyed + */ @Override @DB - public void destroyLunOnFiler(String lunName) throws InvalidParameterValueException, ServerException{ - - final Transaction txn = Transaction.currentTxn(); - txn.start(); - - LunVO lun = _lunDao.findByName(lunName); - - if(lun == null) - throw new InvalidParameterValueException("Cannot find lun"); - - NetappVolumeVO vol = _volumeDao.acquireInLockTable(lun.getVolumeId()); - if (vol == null) { - s_logger.warn("Failed to lock volume id= " + lun.getVolumeId()); - return; - } - NaServer s = null; - try { - s = getServer(vol.getIpAddress(), vol.getUsername(), vol.getPassword()); - - if(s_logger.isDebugEnabled()) - s_logger.debug("Request --> destroyLun "+":serverIp:"+vol.getIpAddress()); - - try { - //Unmap lun - NaElement xi2 = new NaElement("lun-unmap"); - xi2.addNewChild("initiator-group", lunName); - xi2.addNewChild("path", lun.getPath()+lun.getLunName()); - s.invokeElem(xi2); - } catch (NaAPIFailedException naf) { - if(naf.getErrno()==9016) - s_logger.warn("no map exists excpn 9016 caught in deletelun, continuing with delete"); - } + public void destroyLunOnFiler(String lunName) throws InvalidParameterValueException, ServerException{ - //destroy lun - NaElement xi = new NaElement("lun-destroy"); - xi.addNewChild("force","true"); - xi.addNewChild("path", lun.getPath()+lun.getLunName()); - s.invokeElem(xi); - - //destroy igroup - NaElement xi1 = new NaElement("igroup-destroy"); - //xi1.addNewChild("force","true"); - xi1.addNewChild("initiator-group-name",lunName); - s.invokeElem(xi1); - - _lunDao.remove(lun.getId()); - txn.commit(); - } catch(UnknownHostException uhe) { - txn.rollback(); - s_logger.warn("Failed to delete lun", uhe); - throw new ServerException("Failed to delete lun", uhe); - } catch ( IOException ioe) { - txn.rollback(); - s_logger.warn("Failed to delete lun", ioe); - throw new ServerException("Failed to delete lun", ioe); - }catch (NaAPIFailedException naf) { - if(naf.getErrno() == 9017){//no such group exists excpn - s_logger.warn("no such group exists excpn 9017 caught in deletelun, continuing with delete"); - _lunDao.remove(lun.getId()); - txn.commit(); - }else if(naf.getErrno() == 9029){//LUN maps for this initiator group exist - s_logger.warn("LUN maps for this initiator group exist errno 9029 caught in deletelun, continuing with delete"); - _lunDao.remove(lun.getId()); - txn.commit(); - }else{ - txn.rollback(); - s_logger.warn("Failed to delete lun", naf); - throw new ServerException("Failed to delete lun", naf); - } + final Transaction txn = Transaction.currentTxn(); + txn.start(); - } - catch (NaException nae) { - txn.rollback(); - s_logger.warn("Failed to delete lun", nae); - throw new ServerException("Failed to delete lun", nae); - } - finally{ - if (vol != null) { - _volumeDao.releaseFromLockTable(vol.getId()); - } - if (s != null) - s.close(); - } + LunVO lun = _lunDao.findByName(lunName); - } - - /** - * This method lists the luns on the netapp filer - * @param volId -- id of the containing volume - * @return -- list of netapp luns - * @throws NaException - * @throws IOException - */ + if(lun == null) + throw new InvalidParameterValueException("Cannot find lun", null); + + NetappVolumeVO vol = _volumeDao.acquireInLockTable(lun.getVolumeId()); + if (vol == null) { + s_logger.warn("Failed to lock volume id= " + lun.getVolumeId()); + return; + } + NaServer s = null; + try { + s = getServer(vol.getIpAddress(), vol.getUsername(), vol.getPassword()); + + if(s_logger.isDebugEnabled()) + s_logger.debug("Request --> destroyLun "+":serverIp:"+vol.getIpAddress()); + + try { + //Unmap lun + NaElement xi2 = new NaElement("lun-unmap"); + xi2.addNewChild("initiator-group", lunName); + xi2.addNewChild("path", lun.getPath()+lun.getLunName()); + s.invokeElem(xi2); + } catch (NaAPIFailedException naf) { + if(naf.getErrno()==9016) + s_logger.warn("no map exists excpn 9016 caught in deletelun, continuing with delete"); + } + + //destroy lun + NaElement xi = new NaElement("lun-destroy"); + xi.addNewChild("force","true"); + xi.addNewChild("path", lun.getPath()+lun.getLunName()); + s.invokeElem(xi); + + //destroy igroup + NaElement xi1 = new NaElement("igroup-destroy"); + //xi1.addNewChild("force","true"); + xi1.addNewChild("initiator-group-name",lunName); + s.invokeElem(xi1); + + _lunDao.remove(lun.getId()); + txn.commit(); + } catch(UnknownHostException uhe) { + txn.rollback(); + s_logger.warn("Failed to delete lun", uhe); + throw new ServerException("Failed to delete lun", uhe); + } catch ( IOException ioe) { + txn.rollback(); + s_logger.warn("Failed to delete lun", ioe); + throw new ServerException("Failed to delete lun", ioe); + }catch (NaAPIFailedException naf) { + if(naf.getErrno() == 9017){//no such group exists excpn + s_logger.warn("no such group exists excpn 9017 caught in deletelun, continuing with delete"); + _lunDao.remove(lun.getId()); + txn.commit(); + }else if(naf.getErrno() == 9029){//LUN maps for this initiator group exist + s_logger.warn("LUN maps for this initiator group exist errno 9029 caught in deletelun, continuing with delete"); + _lunDao.remove(lun.getId()); + txn.commit(); + }else{ + txn.rollback(); + s_logger.warn("Failed to delete lun", naf); + throw new ServerException("Failed to delete lun", naf); + } + + } + catch (NaException nae) { + txn.rollback(); + s_logger.warn("Failed to delete lun", nae); + throw new ServerException("Failed to delete lun", nae); + } + finally{ + if (vol != null) { + _volumeDao.releaseFromLockTable(vol.getId()); + } + if (s != null) + s.close(); + } + + } + + /** + * This method lists the luns on the netapp filer + * @param volId -- id of the containing volume + * @return -- list of netapp luns + * @throws NaException + * @throws IOException + */ @Override public List listLunsOnFiler(String poolName) - { - if(s_logger.isDebugEnabled()) - s_logger.debug("Request --> listLunsOnFiler "); - - List luns = new ArrayList(); - - List vols = _volumeDao.listVolumes(poolName); - - for(NetappVolumeVO vol : vols) - { - luns.addAll(_lunDao.listLunsByVolId(vol.getId())); - } - - if(s_logger.isDebugEnabled()) - s_logger.debug("Response --> listLunsOnFiler:success"); - - return luns; - } - + { + if(s_logger.isDebugEnabled()) + s_logger.debug("Request --> listLunsOnFiler "); - /** - * This method disassociates a lun from the igroup on the filer - * @param iGroup -- igroup name - * @param lunName -- lun name - */ + List luns = new ArrayList(); + + List vols = _volumeDao.listVolumes(poolName); + + for(NetappVolumeVO vol : vols) + { + luns.addAll(_lunDao.listLunsByVolId(vol.getId())); + } + + if(s_logger.isDebugEnabled()) + s_logger.debug("Response --> listLunsOnFiler:success"); + + return luns; + } + + + /** + * This method disassociates a lun from the igroup on the filer + * @param iGroup -- igroup name + * @param lunName -- lun name + */ @Override - public void disassociateLun(String iGroup, String lunName) throws ServerException, InvalidParameterValueException - { - NaElement xi; - LunVO lun = _lunDao.findByName(lunName); - - if(lun == null) - throw new InvalidParameterValueException("Cannot find LUN " + lunName); - - NetappVolumeVO vol = _volumeDao.findById(lun.getVolumeId()); - NaServer s = null; - try { - s = getServer(vol.getIpAddress(), vol.getUsername(), vol.getPassword()); - - if(s_logger.isDebugEnabled()) - s_logger.debug("Request --> disassociateLun "+":serverIp:"+vol.getIpAddress()); - - xi = new NaElement("igroup-remove"); - xi.addNewChild("force", "true"); - xi.addNewChild("initiator", iGroup); - xi.addNewChild("initiator-group-name", lunName); - s.invokeElem(xi); - - } catch(UnknownHostException uhe) { - throw new ServerException("Failed to disassociate lun", uhe); - } catch ( IOException ioe) { - throw new ServerException("Failed to disassociate lun", ioe); - } catch (NaException nae) { - throw new ServerException("Failed to disassociate lun", nae); - } finally{ - if (s != null) - s.close(); - } - - } - - /** - * This method associates a lun to a particular igroup - * @param iqn - * @param iGroup - * @param lunName - */ + public void disassociateLun(String iGroup, String lunName) throws ServerException, InvalidParameterValueException + { + NaElement xi; + LunVO lun = _lunDao.findByName(lunName); + + if(lun == null) + throw new InvalidParameterValueException("Cannot find LUN " + lunName, null); + + NetappVolumeVO vol = _volumeDao.findById(lun.getVolumeId()); + NaServer s = null; + try { + s = getServer(vol.getIpAddress(), vol.getUsername(), vol.getPassword()); + + if(s_logger.isDebugEnabled()) + s_logger.debug("Request --> disassociateLun "+":serverIp:"+vol.getIpAddress()); + + xi = new NaElement("igroup-remove"); + xi.addNewChild("force", "true"); + xi.addNewChild("initiator", iGroup); + xi.addNewChild("initiator-group-name", lunName); + s.invokeElem(xi); + + } catch(UnknownHostException uhe) { + throw new ServerException("Failed to disassociate lun", uhe); + } catch ( IOException ioe) { + throw new ServerException("Failed to disassociate lun", ioe); + } catch (NaException nae) { + throw new ServerException("Failed to disassociate lun", nae); + } finally{ + if (s != null) + s.close(); + } + + } + + /** + * This method associates a lun to a particular igroup + * @param iqn + * @param iGroup + * @param lunName + */ @Override - public String[] associateLun(String guestIqn, String lunName) throws ServerException, InvalidParameterValueException + public String[] associateLun(String guestIqn, String lunName) throws ServerException, InvalidParameterValueException - { - NaElement xi2; + { + NaElement xi2; - //get lun id from path - String[] splitLunName = lunName.split("-"); - String[] returnVal = new String[3]; - if(splitLunName.length != 2) - throw new InvalidParameterValueException("The lun id is malformed"); - - String lunIdStr = splitLunName[1]; + //get lun id from path + String[] splitLunName = lunName.split("-"); + String[] returnVal = new String[3]; + if(splitLunName.length != 2) + throw new InvalidParameterValueException("The lun id is malformed", null); - Long lId = new Long(lunIdStr); - - LunVO lun = _lunDao.findById(lId); - - if(lun == null) - throw new InvalidParameterValueException("Cannot find LUN " + lunName); - - NetappVolumeVO vol = _volumeDao.findById(lun.getVolumeId()); + String lunIdStr = splitLunName[1]; - //assert(vol != null); - - returnVal[0] = lunIdStr; - returnVal[1] = lun.getTargetIqn(); - returnVal[2] = vol.getIpAddress(); - - NaServer s = null; - - try - { - s = getServer(vol.getIpAddress(), vol.getUsername(), vol.getPassword()); - - if(s_logger.isDebugEnabled()) - s_logger.debug("Request --> associateLun "+":serverIp:"+vol.getIpAddress()); - - //add iqn to the group - xi2 = new NaElement("igroup-add"); - xi2.addNewChild("force", "true"); - xi2.addNewChild("initiator", guestIqn); - xi2.addNewChild("initiator-group-name", lunName); - s.invokeElem(xi2); - - return returnVal; - } catch (UnknownHostException uhe) { - s_logger.warn("Unable to associate LUN " , uhe); - throw new ServerException("Unable to associate LUN", uhe); - }catch (NaAPIFailedException naf){ - if(naf.getErrno() == 9008){ //initiator group already contains node - return returnVal; - } - s_logger.warn("Unable to associate LUN " , naf); - throw new ServerException("Unable to associate LUN", naf); - } - catch (NaException nae) { - s_logger.warn("Unable to associate LUN " , nae); - throw new ServerException("Unable to associate LUN", nae); - } catch (IOException ioe) { - s_logger.warn("Unable to associate LUN " , ioe); - throw new ServerException("Unable to associate LUN", ioe); - } - finally{ - if (s != null) - s.close(); - } - - } + Long lId = new Long(lunIdStr); - @Override - public boolean configure(String name, Map params) - throws ConfigurationException { + LunVO lun = _lunDao.findById(lId); - _name = name; - - _netappAllocator = new NetappDefaultAllocatorImpl( this ); + if(lun == null) + throw new InvalidParameterValueException("Cannot find LUN " + lunName, null); - return true; - } + NetappVolumeVO vol = _volumeDao.findById(lun.getVolumeId()); - @Override - public String getName() { - return _name; - } + //assert(vol != null); - @Override - public boolean start() { - return true; - } + returnVal[0] = lunIdStr; + returnVal[1] = lun.getTargetIqn(); + returnVal[2] = vol.getIpAddress(); + + NaServer s = null; + + try + { + s = getServer(vol.getIpAddress(), vol.getUsername(), vol.getPassword()); + + if(s_logger.isDebugEnabled()) + s_logger.debug("Request --> associateLun "+":serverIp:"+vol.getIpAddress()); + + //add iqn to the group + xi2 = new NaElement("igroup-add"); + xi2.addNewChild("force", "true"); + xi2.addNewChild("initiator", guestIqn); + xi2.addNewChild("initiator-group-name", lunName); + s.invokeElem(xi2); + + return returnVal; + } catch (UnknownHostException uhe) { + s_logger.warn("Unable to associate LUN " , uhe); + throw new ServerException("Unable to associate LUN", uhe); + }catch (NaAPIFailedException naf){ + if(naf.getErrno() == 9008){ //initiator group already contains node + return returnVal; + } + s_logger.warn("Unable to associate LUN " , naf); + throw new ServerException("Unable to associate LUN", naf); + } + catch (NaException nae) { + s_logger.warn("Unable to associate LUN " , nae); + throw new ServerException("Unable to associate LUN", nae); + } catch (IOException ioe) { + s_logger.warn("Unable to associate LUN " , ioe); + throw new ServerException("Unable to associate LUN", ioe); + } + finally{ + if (s != null) + s.close(); + } + + } + + @Override + public boolean configure(String name, Map params) + throws ConfigurationException { + + _name = name; + + _netappAllocator = new NetappDefaultAllocatorImpl( this ); + + return true; + } + + @Override + public String getName() { + return _name; + } + + @Override + public boolean start() { + return true; + } + + @Override + public boolean stop() { + return true; + } - @Override - public boolean stop() { - return true; - } - } diff --git a/server/src/com/cloud/network/CiscoNexusVSMDeviceManagerImpl.java b/server/src/com/cloud/network/CiscoNexusVSMDeviceManagerImpl.java index e00564f1f10..1f29c0643b4 100644 --- a/server/src/com/cloud/network/CiscoNexusVSMDeviceManagerImpl.java +++ b/server/src/com/cloud/network/CiscoNexusVSMDeviceManagerImpl.java @@ -12,41 +12,38 @@ // Automatically generated by addcopyright.py at 04/03/2012 package com.cloud.network; -import java.util.HashMap; - +import java.util.ArrayList; import java.util.List; -import java.util.Map; import org.apache.log4j.Logger; import com.cloud.agent.api.StartupCommand; -import com.cloud.api.ApiConstants; import com.cloud.dc.ClusterDetailsDao; import com.cloud.dc.ClusterVO; import com.cloud.dc.ClusterVSMMapVO; import com.cloud.dc.dao.ClusterDao; import com.cloud.dc.dao.ClusterVSMMapDao; import com.cloud.exception.InvalidParameterValueException; -import com.cloud.host.DetailVO; +import com.cloud.exception.ResourceInUseException; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDetailsDao; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.vmware.manager.VmwareManager; +import com.cloud.network.dao.CiscoNexusVSMDeviceDao; +import com.cloud.network.dao.PortProfileDao; import com.cloud.resource.ResourceManager; +import com.cloud.utils.IdentityProxy; +import com.cloud.utils.cisco.n1kv.vsm.NetconfHelper; import com.cloud.utils.component.AdapterBase; import com.cloud.utils.component.Inject; import com.cloud.utils.db.DB; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.network.dao.CiscoNexusVSMDeviceDao; -import com.cloud.network.dao.PortProfileDao; -import com.cloud.exception.ResourceInUseException; -import com.cloud.utils.cisco.n1kv.vsm.NetconfHelper; public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase { - @Inject + @Inject CiscoNexusVSMDeviceDao _ciscoNexusVSMDeviceDao; @Inject ClusterDao _clusterDao; @@ -54,8 +51,8 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase { ClusterVSMMapDao _clusterVSMDao; @Inject ResourceManager _resourceMgr; - @Inject - VmwareManager _vmwareMgr; + @Inject + VmwareManager _vmwareMgr; @Inject ClusterDetailsDao _clusterDetailsDao; @Inject @@ -63,126 +60,129 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase { @Inject PortProfileDao _ppDao; - + private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalLoadBalancerDeviceManagerImpl.class); - + @DB //public CiscoNexusVSMDeviceVO addCiscoNexusVSM(long clusterId, String ipaddress, String username, String password, ServerResource resource, String vsmName) { public CiscoNexusVSMDeviceVO addCiscoNexusVSM(long clusterId, String ipaddress, String username, String password, String vCenterIpaddr, String vCenterDcName) { - // In this function, we associate this VSM with each host - // in the clusterId specified. + // In this function, we associate this VSM with each host + // in the clusterId specified. - // First check if the cluster is of type vmware. If not, - // throw an exception. VSMs are tightly integrated with vmware clusters. - - ClusterVO cluster = _clusterDao.findById(clusterId); - if (cluster == null) { - throw new InvalidParameterValueException("Cluster with specified ID not found!"); - } - if (cluster.getHypervisorType() != HypervisorType.VMware) { - InvalidParameterValueException ex = new InvalidParameterValueException("Cluster with specified id is not a VMWare hypervisor cluster"); - throw ex; - } + // First check if the cluster is of type vmware. If not, + // throw an exception. VSMs are tightly integrated with vmware clusters. - // Next, check if the cluster already has a VSM associated with it. - // If so, throw an exception disallowing this operation. The user must first - // delete the current VSM and then only attempt to add the new one. - - if (_clusterVSMDao.findByClusterId(clusterId) != null) { - // We can't have two VSMs for the same cluster. Throw exception. - throw new InvalidParameterValueException("Cluster with specified id already has a VSM tied to it. Please remove that first and retry the operation."); - } + ClusterVO cluster = _clusterDao.findById(clusterId); + if (cluster == null) { + throw new InvalidParameterValueException("Cluster could not be found by id", null); + } + if (cluster.getHypervisorType() != HypervisorType.VMware) { + List idList = new ArrayList(); + idList.add(new IdentityProxy(cluster, clusterId, "clusterId")); + throw new InvalidParameterValueException("Cluster with specified id is not a VMWare hypervisor cluster", idList); + } - // TODO: Confirm whether we should be checking for VSM reachability here. - - // Next, check if this VSM is reachable. Use the XML-RPC VSM API Java bindings to talk to - // the VSM. - //NetconfHelper (String ip, String username, String password) + // Next, check if the cluster already has a VSM associated with it. + // If so, throw an exception disallowing this operation. The user must first + // delete the current VSM and then only attempt to add the new one. - NetconfHelper netconfClient; - try { - netconfClient = new NetconfHelper(ipaddress, username, password); - } catch(CloudRuntimeException e) { - String msg = "Failed to connect to Nexus VSM " + ipaddress + " with credentials of user " + username; - s_logger.error(msg); - throw new CloudRuntimeException(msg); - } + if (_clusterVSMDao.findByClusterId(clusterId) != null) { + // We can't have two VSMs for the same cluster. Throw exception. + List idList = new ArrayList(); + idList.add(new IdentityProxy(cluster, clusterId, "clusterId")); + throw new InvalidParameterValueException("Cluster with specified id already has a VSM tied to it. Please remove that first and retry the operation.", idList); + } - // Disconnect from the VSM. A VSM has a default of 8 maximum parallel connections that it allows. - netconfClient.disconnect(); + // TODO: Confirm whether we should be checking for VSM reachability here. - // Now, go ahead and associate the cluster with this VSM. - // First, check if VSM already exists in the table "virtual_supervisor_module". - // If it's not there already, create it. - // If it's there already, return success. - - // TODO - Right now, we only check if the ipaddress matches for both requests. - // We must really check whether every field of the VSM matches. Anyway, the - // advantage of our approach for now is that existing infrastructure using - // the existing VSM won't be affected if the new request to add the VSM - // assumed different information on the VSM (mgmt vlan, username, password etc). - CiscoNexusVSMDeviceVO VSMObj; - try { - VSMObj = _ciscoNexusVSMDeviceDao.getVSMbyIpaddress(ipaddress); - } catch (Exception e) { - throw new CloudRuntimeException(e.getMessage()); - } + // Next, check if this VSM is reachable. Use the XML-RPC VSM API Java bindings to talk to + // the VSM. + //NetconfHelper (String ip, String username, String password) + + NetconfHelper netconfClient; + try { + netconfClient = new NetconfHelper(ipaddress, username, password); + } catch(CloudRuntimeException e) { + String msg = "Failed to connect to Nexus VSM " + ipaddress + " with credentials of user " + username; + s_logger.error(msg); + throw new CloudRuntimeException(msg); + } + + // Disconnect from the VSM. A VSM has a default of 8 maximum parallel connections that it allows. + netconfClient.disconnect(); + + // Now, go ahead and associate the cluster with this VSM. + // First, check if VSM already exists in the table "virtual_supervisor_module". + // If it's not there already, create it. + // If it's there already, return success. + + // TODO - Right now, we only check if the ipaddress matches for both requests. + // We must really check whether every field of the VSM matches. Anyway, the + // advantage of our approach for now is that existing infrastructure using + // the existing VSM won't be affected if the new request to add the VSM + // assumed different information on the VSM (mgmt vlan, username, password etc). + CiscoNexusVSMDeviceVO VSMObj; + try { + VSMObj = _ciscoNexusVSMDeviceDao.getVSMbyIpaddress(ipaddress); + } catch (Exception e) { + throw new CloudRuntimeException(e.getMessage()); + } + + if (VSMObj == null) { + // Create the VSM record. For now, we aren't using the vsmName field. + VSMObj = new CiscoNexusVSMDeviceVO(ipaddress, username, password); + Transaction txn = Transaction.currentTxn(); + try { + txn.start(); + _ciscoNexusVSMDeviceDao.persist(VSMObj); + txn.commit(); + } catch (Exception e) { + txn.rollback(); + throw new CloudRuntimeException(e.getMessage()); + } + } + + // At this stage, we have a VSM record for sure. Connect the VSM to the cluster Id. + long vsmId = _ciscoNexusVSMDeviceDao.getVSMbyIpaddress(ipaddress).getId(); + ClusterVSMMapVO connectorObj = new ClusterVSMMapVO(clusterId, vsmId); + Transaction txn = Transaction.currentTxn(); + try { + txn.start(); + _clusterVSMDao.persist(connectorObj); + txn.commit(); + } catch (Exception e) { + txn.rollback(); + throw new CloudRuntimeException(e.getMessage()); + } + + // Now, get a list of all the ESXi servers in this cluster. + // This is effectively a select * from host where cluster_id=clusterId; + // All ESXi servers are stored in the host table, and their resource + // type is vmwareresource. - if (VSMObj == null) { - // Create the VSM record. For now, we aren't using the vsmName field. - VSMObj = new CiscoNexusVSMDeviceVO(ipaddress, username, password); - Transaction txn = Transaction.currentTxn(); - try { - txn.start(); - _ciscoNexusVSMDeviceDao.persist(VSMObj); - txn.commit(); - } catch (Exception e) { - txn.rollback(); - throw new CloudRuntimeException(e.getMessage()); - } - } - - // At this stage, we have a VSM record for sure. Connect the VSM to the cluster Id. - long vsmId = _ciscoNexusVSMDeviceDao.getVSMbyIpaddress(ipaddress).getId(); - ClusterVSMMapVO connectorObj = new ClusterVSMMapVO(clusterId, vsmId); - Transaction txn = Transaction.currentTxn(); - try { - txn.start(); - _clusterVSMDao.persist(connectorObj); - txn.commit(); - } catch (Exception e) { - txn.rollback(); - throw new CloudRuntimeException(e.getMessage()); - } - - // Now, get a list of all the ESXi servers in this cluster. - // This is effectively a select * from host where cluster_id=clusterId; - // All ESXi servers are stored in the host table, and their resource - // type is vmwareresource. - //List hosts = _resourceMgr.listAllHostsInCluster(clusterId); - + //TODO: Activate the code below if we make the Nexus VSM a separate resource. // Iterate through each of the hosts in this list. Each host has a host id. // Given this host id, we can reconfigure the in-memory resource representing // the host via the agent manager. Thus we inject VSM related information // into each host's resource. Also, we first configure each resource's // entries in the database to contain this VSM information before the injection. - + //for (HostVO host : hosts) { - // Create a host details VO object and write it out for this hostid. - //Long hostid = new Long(vsmId); - //DetailVO vsmDetail = new DetailVO(host.getId(), "vsmId", hostid.toString()); - //Transaction tx = Transaction.currentTxn(); - //try { - //tx.start(); - //_hostDetailDao.persist(vsmDetail); - //tx.commit(); - //} catch (Exception e) { - //tx.rollback(); - //throw new CloudRuntimeException(e.getMessage()); - //} + // Create a host details VO object and write it out for this hostid. + //Long hostid = new Long(vsmId); + //DetailVO vsmDetail = new DetailVO(host.getId(), "vsmId", hostid.toString()); + //Transaction tx = Transaction.currentTxn(); + //try { + //tx.start(); + //_hostDetailDao.persist(vsmDetail); + //tx.commit(); + //} catch (Exception e) { + //tx.rollback(); + //throw new CloudRuntimeException(e.getMessage()); + //} //} // Reconfigure the resource. //Map hostDetails = new HashMap(); @@ -191,40 +191,40 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase { //hostDetails.put(ApiConstants.USERNAME, username); //hostDetails.put(ApiConstants.PASSWORD, password); //_agentMrg.send(host.getId(), ) - + return VSMObj; - + } - + @DB public boolean deleteCiscoNexusVSM(long vsmId) throws ResourceInUseException { CiscoNexusVSMDeviceVO cisconexusvsm = _ciscoNexusVSMDeviceDao.findById(vsmId); if (cisconexusvsm == null) { - // This entry is already not present. Return success. - return true; + // This entry is already not present. Return success. + return true; } - + // First, check whether this VSM is part of any non-empty cluster. // Search ClusterVSMMap's table for a list of clusters using this vsmId. - + List clusterList = _clusterVSMDao.listByVSMId(vsmId); - + if (clusterList != null) { - for (ClusterVSMMapVO record : clusterList) { - // If this cluster id has any hosts in it, fail this operation. - Long clusterId = record.getClusterId(); - List hosts = _resourceMgr.listAllHostsInCluster(clusterId); - if (hosts != null && hosts.size() > 0) { - for (Host host: hosts) { - if (host.getType() == Host.Type.Routing) { - s_logger.info("Non-empty cluster with id" + clusterId + "still has a host that uses this VSM. Please empty the cluster first"); - throw new ResourceInUseException("Non-empty cluster with id" + clusterId + "still has a host that uses this VSM. Please empty the cluster first"); - } - } - } - } + for (ClusterVSMMapVO record : clusterList) { + // If this cluster id has any hosts in it, fail this operation. + Long clusterId = record.getClusterId(); + List hosts = _resourceMgr.listAllHostsInCluster(clusterId); + if (hosts != null && hosts.size() > 0) { + for (Host host: hosts) { + if (host.getType() == Host.Type.Routing) { + s_logger.info("Non-empty cluster with id" + clusterId + "still has a host that uses this VSM. Please empty the cluster first"); + throw new ResourceInUseException("Non-empty cluster with id" + clusterId + "still has a host that uses this VSM. Please empty the cluster first"); + } + } + } + } } - + // Iterate through the cluster list again, this time, delete the VSM. Transaction txn = Transaction.currentTxn(); try { @@ -237,8 +237,8 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase { // to notify any resources or remove host details. txn.commit(); } catch (Exception e) { - s_logger.info("Caught exception when trying to delete VSM record.." + e.getMessage()); - throw new CloudRuntimeException("Failed to delete VSM"); + s_logger.info("Caught exception when trying to delete VSM record.." + e.getMessage()); + throw new CloudRuntimeException("Failed to delete VSM"); } return true; } @@ -247,67 +247,67 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase { public CiscoNexusVSMDeviceVO enableCiscoNexusVSM(long vsmId) { CiscoNexusVSMDeviceVO cisconexusvsm = _ciscoNexusVSMDeviceDao.findById(vsmId); if (cisconexusvsm == null) { - throw new InvalidParameterValueException("Invalid vsm Id specified"); + throw new InvalidParameterValueException("Invalid vsm Id specified", null); } // Else, check if this db record shows that this VSM is enabled or not. if (cisconexusvsm.getvsmDeviceState() == CiscoNexusVSMDeviceVO.VSMDeviceState.Disabled) { - // it's currently disabled. So change it to enabled and write it out to the db. - cisconexusvsm.setVsmDeviceState(CiscoNexusVSMDeviceVO.VSMDeviceState.Enabled); - Transaction txn = Transaction.currentTxn(); - try { - txn.start(); - _ciscoNexusVSMDeviceDao.persist(cisconexusvsm); - txn.commit(); - } catch (Exception e) { - txn.rollback(); - throw new CloudRuntimeException(e.getMessage()); - } - } - + // it's currently disabled. So change it to enabled and write it out to the db. + cisconexusvsm.setVsmDeviceState(CiscoNexusVSMDeviceVO.VSMDeviceState.Enabled); + Transaction txn = Transaction.currentTxn(); + try { + txn.start(); + _ciscoNexusVSMDeviceDao.persist(cisconexusvsm); + txn.commit(); + } catch (Exception e) { + txn.rollback(); + throw new CloudRuntimeException(e.getMessage()); + } + } + return cisconexusvsm; } - + @DB public CiscoNexusVSMDeviceVO disableCiscoNexusVSM(long vsmId) { CiscoNexusVSMDeviceVO cisconexusvsm = _ciscoNexusVSMDeviceDao.findById(vsmId); if (cisconexusvsm == null) { - throw new InvalidParameterValueException("Invalid vsm Id specified"); + throw new InvalidParameterValueException("Invalid vsm Id specified", null); } // Else, check if this db record shows that this VSM is enabled or not. if (cisconexusvsm.getvsmDeviceState() == CiscoNexusVSMDeviceVO.VSMDeviceState.Enabled) { - // it's currently disabled. So change it to enabled and write it out to the db. - cisconexusvsm.setVsmDeviceState(CiscoNexusVSMDeviceVO.VSMDeviceState.Disabled); - Transaction txn = Transaction.currentTxn(); - try { - txn.start(); - _ciscoNexusVSMDeviceDao.persist(cisconexusvsm); - txn.commit(); - } catch (Exception e) { - txn.rollback(); - throw new CloudRuntimeException(e.getMessage()); - } - } - + // it's currently disabled. So change it to enabled and write it out to the db. + cisconexusvsm.setVsmDeviceState(CiscoNexusVSMDeviceVO.VSMDeviceState.Disabled); + Transaction txn = Transaction.currentTxn(); + try { + txn.start(); + _ciscoNexusVSMDeviceDao.persist(cisconexusvsm); + txn.commit(); + } catch (Exception e) { + txn.rollback(); + throw new CloudRuntimeException(e.getMessage()); + } + } + return cisconexusvsm; } - + @DB public CiscoNexusVSMDeviceVO getCiscoVSMbyVSMId(long vsmId) { - return _ciscoNexusVSMDeviceDao.findById(vsmId); + return _ciscoNexusVSMDeviceDao.findById(vsmId); } - + @DB public CiscoNexusVSMDeviceVO getCiscoVSMbyClusId(long clusterId) { - ClusterVSMMapVO mapVO = _clusterVSMDao.findByClusterId(clusterId); - if (mapVO == null) { - s_logger.info("Couldn't find a VSM associated with the specified cluster Id"); - return null; - } - // Else, pull out the VSM associated with the VSM id in mapVO. - CiscoNexusVSMDeviceVO result = _ciscoNexusVSMDeviceDao.findById(mapVO.getVsmId()); - return result; + ClusterVSMMapVO mapVO = _clusterVSMDao.findByClusterId(clusterId); + if (mapVO == null) { + s_logger.info("Couldn't find a VSM associated with the specified cluster Id"); + return null; + } + // Else, pull out the VSM associated with the VSM id in mapVO. + CiscoNexusVSMDeviceVO result = _ciscoNexusVSMDeviceDao.findById(mapVO.getVsmId()); + return result; } - + public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { // TODO Auto-generated method stub return null; diff --git a/server/src/com/cloud/network/ExternalFirewallDeviceManagerImpl.java b/server/src/com/cloud/network/ExternalFirewallDeviceManagerImpl.java index 932b17920bd..903b049793d 100644 --- a/server/src/com/cloud/network/ExternalFirewallDeviceManagerImpl.java +++ b/server/src/com/cloud/network/ExternalFirewallDeviceManagerImpl.java @@ -26,7 +26,6 @@ import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupExternalFirewallCommand; -import com.cloud.agent.api.StartupExternalLoadBalancerCommand; import com.cloud.agent.api.routing.IpAssocCommand; import com.cloud.agent.api.routing.NetworkElementCommand; import com.cloud.agent.api.routing.RemoteAccessVpnCfgCommand; @@ -55,10 +54,7 @@ import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; import com.cloud.host.dao.HostDetailsDao; -import com.cloud.network.ExternalFirewallDeviceVO.FirewallDeviceState; import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice; -import com.cloud.network.Network.Capability; -import com.cloud.network.Network.Service; import com.cloud.network.Networks.TrafficType; import com.cloud.network.dao.ExternalFirewallDeviceDao; import com.cloud.network.dao.IPAddressDao; @@ -151,12 +147,12 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl if ((ntwkDevice == null) || (url == null) || (username == null) || (resource == null) || (password == null) ) { throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," + - " server resource, zone id/physical network id) is not specified or a valid parameter."); + " server resource, zone id/physical network id) is not specified or a valid parameter.", null); } pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if (pNetwork == null) { - throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); + throw new InvalidParameterValueException("Could not find phyical network by ID", null); } zoneId = pNetwork.getDataCenterId(); @@ -174,7 +170,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl uri = new URI(url); } catch (Exception e) { s_logger.debug(e); - throw new InvalidParameterValueException(e.getMessage()); + throw new InvalidParameterValueException(e.getMessage(), null); } String ipAddress = uri.getHost(); @@ -205,7 +201,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl txn.start(); boolean dedicatedUse = (configParams.get(ApiConstants.FIREWALL_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.FIREWALL_DEVICE_DEDICATED)) : false; - long capacity = NumbersUtil.parseLong((String)configParams.get(ApiConstants.FIREWALL_DEVICE_CAPACITY), 0); + long capacity = NumbersUtil.parseLong(configParams.get(ApiConstants.FIREWALL_DEVICE_CAPACITY), 0); if (capacity == 0) { capacity = _defaultFwCapacity; } @@ -229,7 +225,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl public boolean deleteExternalFirewall(Long hostId) { HostVO externalFirewall = _hostDao.findById(hostId); if (externalFirewall == null) { - throw new InvalidParameterValueException("Could not find an external firewall with ID: " + hostId); + throw new InvalidParameterValueException("Could not find an external firewall by ID", null); } try { @@ -252,11 +248,11 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if (pNetwork == null) { - throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); + throw new InvalidParameterValueException("Could not find phyical network by ID", null); } if ((pNetwork == null) || (fwNetworkDevice == null)) { - throw new InvalidParameterValueException("Atleast one of ther required parameter physical networkId, device name is missing or invalid."); + throw new InvalidParameterValueException("Atleast one of ther required parameter physical networkId, device name is missing or invalid.", null); } PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), fwNetworkDevice.getNetworkServiceProvder()); @@ -270,7 +266,8 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl } return firewallHosts; } - + + @Override public ExternalFirewallDeviceVO getExternalFirewallForNetwork(Network network) { NetworkExternalFirewallVO fwDeviceForNetwork = _networkExternalFirewallDao.findByNetworkId(network.getId()); if (fwDeviceForNetwork != null) { @@ -366,17 +363,17 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl ExternalFirewallDeviceVO fwDeviceVO = getExternalFirewallForNetwork(network); if (fwDeviceVO == null) { s_logger.warn("Network shutdown requested on external firewall element, which did not implement the network." + - " Either network implement failed half way through or already network shutdown is completed."); + " Either network implement failed half way through or already network shutdown is completed."); return true; } externalFirewall = _hostDao.findById(fwDeviceVO.getHostId()); } Account account = _accountDao.findByIdIncludingRemoved(network.getAccountId()); - + NetworkOffering offering = _networkOfferingDao.findById(network.getNetworkOfferingId()); boolean sharedSourceNat = offering.getSharedSourceNat(); - + IPAddressVO sourceNatIp = null; if (!sharedSourceNat) { // Get the source NAT IP address for this account @@ -385,7 +382,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl if (sourceNatIps.size() != 1) { String errorMsg = "External firewall was unable to find the source NAT IP address for account " - + account.getAccountName(); + + account.getAccountName(); s_logger.error(errorMsg); return true; } else { @@ -431,18 +428,18 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl // Insert a new NIC for this guest network to reserve the gateway address savePlaceholderNic(network, network.getGateway()); } - + // Delete any mappings used for inline external load balancers in this network List nicsInNetwork = _nicDao.listByNetworkId(network.getId()); for (NicVO nic : nicsInNetwork) { InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByNicId(nic.getId()); - + if (mapping != null) { _nicDao.expunge(mapping.getNicId()); _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); } } - + String action = add ? "implemented" : "shut down"; s_logger.debug("External firewall has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag " + guestVlanTag); @@ -527,39 +524,39 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl if (externalFirewall == null) { return false; } - + // Create/delete VPN IpAddress ip = _networkMgr.getIp(vpn.getServerAddressId()); - + // Mask the IP range with the network's VLAN tag String[] ipRange = vpn.getIpRange().split("-"); DataCenterVO zone = _dcDao.findById(network.getDataCenterId()); int vlanTag = Integer.parseInt(network.getBroadcastUri().getHost()); int offset = getVlanOffset(network.getPhysicalNetworkId(), vlanTag); int cidrSize = getGloballyConfiguredCidrSize(); - + for (int i = 0; i < 2; i++) { ipRange[i] = NetUtils.long2Ip((NetUtils.ip2Long(ipRange[i]) & 0xff000000) | (offset << (32 - cidrSize))); } - + String maskedIpRange = ipRange[0] + "-" + ipRange[1]; - + RemoteAccessVpnCfgCommand createVpnCmd = new RemoteAccessVpnCfgCommand(create, ip.getAddress().addr(), vpn.getLocalIp(), maskedIpRange, vpn.getIpsecPresharedKey()); createVpnCmd.setAccessDetail(NetworkElementCommand.ACCOUNT_ID, String.valueOf(network.getAccountId())); createVpnCmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR, network.getCidr()); Answer answer = _agentMgr.easySend(externalFirewall.getId(), createVpnCmd); if (answer == null || !answer.getResult()) { - String details = (answer != null) ? answer.getDetails() : "details unavailable"; - String msg = "External firewall was unable to create a remote access VPN in zone " + zone.getName() + " due to: " + details + "."; - s_logger.error(msg); - throw new ResourceUnavailableException(msg, DataCenter.class, zone.getId()); + String details = (answer != null) ? answer.getDetails() : "details unavailable"; + String msg = "External firewall was unable to create a remote access VPN in zone " + zone.getName() + " due to: " + details + "."; + s_logger.error(msg); + throw new ResourceUnavailableException(msg, DataCenter.class, zone.getId()); } - + // Add/delete users List vpnUsers = _vpnUsersDao.listByAccount(vpn.getAccountId()); return manageRemoteAccessVpnUsers(network, vpn, vpnUsers); } - + public boolean manageRemoteAccessVpnUsers(Network network, RemoteAccessVpn vpn, List vpnUsers) throws ResourceUnavailableException { ExternalFirewallDeviceVO fwDeviceVO = getExternalFirewallForNetwork(network); HostVO externalFirewall = _hostDao.findById(fwDeviceVO.getHostId()); @@ -567,31 +564,31 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl if (externalFirewall == null) { return false; } - + List addUsers = new ArrayList(); List removeUsers = new ArrayList(); for (VpnUser user : vpnUsers) { if (user.getState() == VpnUser.State.Add || - user.getState() == VpnUser.State.Active) { + user.getState() == VpnUser.State.Active) { addUsers.add(user); } else if (user.getState() == VpnUser.State.Revoke) { removeUsers.add(user); } } - + VpnUsersCfgCommand addUsersCmd = new VpnUsersCfgCommand(addUsers, removeUsers); addUsersCmd.setAccessDetail(NetworkElementCommand.ACCOUNT_ID, String.valueOf(network.getAccountId())); addUsersCmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR, network.getCidr()); - + Answer answer = _agentMgr.easySend(externalFirewall.getId(), addUsersCmd); if (answer == null || !answer.getResult()) { - String details = (answer != null) ? answer.getDetails() : "details unavailable"; - DataCenterVO zone = _dcDao.findById(network.getDataCenterId()); - String msg = "External firewall was unable to add remote access users in zone " + zone.getName() + " due to: " + details + "."; - s_logger.error(msg); - throw new ResourceUnavailableException(msg, DataCenter.class, zone.getId()); + String details = (answer != null) ? answer.getDetails() : "details unavailable"; + DataCenterVO zone = _dcDao.findById(network.getDataCenterId()); + String msg = "External firewall was unable to add remote access users in zone " + zone.getName() + " due to: " + details + "."; + s_logger.error(msg); + throw new ResourceUnavailableException(msg, DataCenter.class, zone.getId()); } - + return true; } @@ -608,7 +605,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl int lowestVlanTag = Integer.valueOf(vlanRange[0]); return vlanTag - lowestVlanTag; } - + private NicVO savePlaceholderNic(Network network, String ipAddress) { NicVO nic = new NicVO(null, null, network.getId(), null); nic.setIp4Address(ipAddress); @@ -616,7 +613,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl nic.setState(State.Reserved); return _nicDao.persist(nic); } - + public int getGloballyConfiguredCidrSize() { try { String globalVlanBits = _configDao.getValue(Config.GuestVlanBits.key()); diff --git a/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java b/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java index 133bfb5c01a..ef35b8b244b 100644 --- a/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java +++ b/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java @@ -76,7 +76,6 @@ import com.cloud.network.dao.PhysicalNetworkDao; import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; import com.cloud.network.dao.PhysicalNetworkServiceProviderVO; import com.cloud.network.lb.LoadBalancingRule; -import com.cloud.network.lb.LoadBalancingRule.LbAutoScaleVmGroup; import com.cloud.network.lb.LoadBalancingRule.LbDestination; import com.cloud.network.resource.CreateLoadBalancerApplianceAnswer; import com.cloud.network.resource.DestroyLoadBalancerApplianceAnswer; @@ -184,12 +183,12 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase if ((ntwkDevice == null) || (url == null) || (username == null) || (resource == null) || (password == null)) { throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," + - " server resource, zone id/physical network id) is not specified or a valid parameter."); + " server resource, zone id/physical network id) is not specified or a valid parameter.", null); } pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if (pNetwork == null) { - throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); + throw new InvalidParameterValueException("Could not find phyical network by ID", null); } zoneId = pNetwork.getDataCenterId(); @@ -207,7 +206,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase uri = new URI(url); } catch (Exception e) { s_logger.debug(e); - throw new InvalidParameterValueException(e.getMessage()); + throw new InvalidParameterValueException(e.getMessage(), null); } String ipAddress = uri.getHost(); @@ -236,7 +235,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase boolean dedicatedUse = (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED)) : false; boolean inline = (configParams.get(ApiConstants.INLINE) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.INLINE)) : false; - long capacity = NumbersUtil.parseLong((String) configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0); + long capacity = NumbersUtil.parseLong(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0); if (capacity == 0) { capacity = _defaultLbCapacity; } @@ -264,7 +263,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase public boolean deleteExternalLoadBalancer(long hostId) { HostVO externalLoadBalancer = _hostDao.findById(hostId); if (externalLoadBalancer == null) { - throw new InvalidParameterValueException("Could not find an external load balancer with ID: " + hostId); + throw new InvalidParameterValueException("Could not find an external load balancer by ID", null); } DetailVO lbHostDetails = _hostDetailDao.findDetail(hostId, ApiConstants.LOAD_BALANCER_DEVICE_ID); @@ -314,7 +313,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase pNetwork = _physicalNetworkDao.findById(physicalNetworkId); if ((pNetwork == null) || (lbNetworkDevice == null)) { - throw new InvalidParameterValueException("Atleast one of the required parameter physical networkId, device name is invalid."); + throw new InvalidParameterValueException("Atleast one of the required parameter physical networkId, device name is invalid.", null); } PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index c8ce8cade45..cc2255dd3c6 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -537,12 +537,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return ipToReturn; } - + @Override public PublicIp assignVpnGatewayIpAddress(long dcId, Account owner, long vpcId) throws InsufficientAddressCapacityException, ConcurrentOperationException { return assignDedicateIpAddress(owner, null, vpcId, dcId, false); } - + @DB public PublicIp assignDedicateIpAddress(Account owner, Long guestNtwkId, Long vpcId, long dcId, boolean isSourceNat) @@ -1143,7 +1143,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public IPAddressVO associateIPToGuestNetwork(long ipId, long networkId, boolean releaseOnFailure) throws ResourceAllocationException, ResourceUnavailableException, - InsufficientAddressCapacityException, ConcurrentOperationException { + InsufficientAddressCapacityException, ConcurrentOperationException { Account caller = UserContext.current().getCaller(); Account owner = null; @@ -1467,7 +1467,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } - + if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworksNoLB) == null) { //remove LB service defaultVPCOffProviders.remove(Service.Lb); @@ -2282,7 +2282,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public void releaseNic(VirtualMachineProfile vmProfile, Nic nic) throws ConcurrentOperationException, ResourceUnavailableException { - + NicVO nicVO = _nicDao.findById(nic.getId()); releaseNic(vmProfile, nicVO); } @@ -2356,7 +2356,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (broadcastUri != null) { nic = _nicDao.findByNetworkIdInstanceIdAndBroadcastUri(networkId, vm.getId(), broadcastUri); } else { - nic = _nicDao.findByInstanceIdAndNetworkId(networkId, vm.getId()); + nic = _nicDao.findByInstanceIdAndNetworkId(networkId, vm.getId()); } NetworkVO network = _networksDao.findById(networkId); Integer networkRate = getNetworkRate(network.getId(), vm.getId()); @@ -3189,7 +3189,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Filter searchFilter = new Filter(NetworkVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder sb = _networksDao.createSearchBuilder(); - + if (forVpc != null) { if (forVpc) { sb.and("vpc", sb.entity().getVpcId(), Op.NNULL); @@ -4260,14 +4260,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) { - + long physicalNetworkId = 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()); + throw new InvalidParameterValueException("Unable to find physical network by id, with tag: " +requiredOfferings.get(0).getTags(), null); } - + s_logger.debug("Creating network for account " + owner + " from the network offering id=" + requiredOfferings.get(0).getId() + " as a part of createVlanIpRange process"); guestNetwork = createGuestNetwork(requiredOfferings.get(0).getId(), owner.getAccountName() + "-network" @@ -5301,7 +5301,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag txn.start(); // Create the new physical network in the database long id = _physicalNetworkDao.getNextInSequence(Long.class, "id"); - + PhysicalNetworkVO pNetwork = new PhysicalNetworkVO(id, zoneId, vnetRange, networkSpeed, domainId, broadcastDomainRange, name); pNetwork.setTags(tags); pNetwork.setIsolationMethods(isolationMethods); @@ -6954,7 +6954,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (networkId == null) { networkId = userIp.getAssociatedWithNetworkId(); } - + NetworkVO network = _networksDao.findById(networkId); NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId()); if (offering.getGuestType() != GuestType.Isolated) { @@ -7212,7 +7212,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (network.getVpcId() != null) { throw new InvalidParameterValueException("Can't assign ip to the network directly when network belongs" + - " to VPC.Specify vpcId to associate ip address to VPC", null); + " to VPC.Specify vpcId to associate ip address to VPC", null); } return associateIPToGuestNetwork(ipId, networkId, true); } @@ -7244,11 +7244,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (ipUsedInVpc(ip)) { return; } - + if (ip == null || ip.getVpcId() == null) { return; } - + s_logger.debug("Releasing VPC ip address " + ip + " from vpc network id=" + networkId); long vpcId = ip.getVpcId(); @@ -7389,41 +7389,41 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } return true; } - + @Override public NicProfile createNicForVm(Network network, NicProfile requested, ReservationContext context, VirtualMachineProfileImpl vmProfile, boolean prepare) - throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, - ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { - + throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, + ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { + VirtualMachine vm = vmProfile.getVirtualMachine(); NetworkVO networkVO = _networksDao.findById(network.getId()); DataCenter dc = _configMgr.getZone(network.getDataCenterId()); Host host = _hostDao.findById(vm.getHostId()); DeployDestination dest = new DeployDestination(dc, null, null, host); - + NicProfile nic = getNicProfileForVm(network, requested, vm); - + //1) allocate nic (if needed) if (nic == null) { int deviceId = _nicDao.countNics(vm.getId()); - + nic = allocateNic(requested, network, false, deviceId, vmProfile).first(); - + if (nic == null) { throw new CloudRuntimeException("Failed to allocate nic for vm " + vm + " in network " + network); } - + s_logger.debug("Nic is allocated successfully for vm " + vm + " in network " + network); } - + //2) prepare nic if (prepare) { nic = prepareNic(vmProfile, dest, context, nic.getId(), networkVO); s_logger.debug("Nic is prepared successfully for vm " + vm + " in network " + network); } - + return nic; } @@ -7446,5 +7446,5 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } return nic; } - + } diff --git a/server/src/com/cloud/network/NetworkUsageManagerImpl.java b/server/src/com/cloud/network/NetworkUsageManagerImpl.java index 6ba0bdbef2a..cafce2d2a0d 100755 --- a/server/src/com/cloud/network/NetworkUsageManagerImpl.java +++ b/server/src/com/cloud/network/NetworkUsageManagerImpl.java @@ -101,7 +101,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta @Inject HostDetailsDao _detailsDao; @Inject AccountManager _accountMgr; @Inject NetworkDao _networksDao = null; - @Inject ResourceManager _resourceMgr; + @Inject ResourceManager _resourceMgr; ScheduledExecutorService _executor; int _networkStatsInterval; String _TSinclZones; @@ -116,7 +116,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta DataCenterVO zone = _dcDao.findById(zoneId); String zoneName; if (zone == null) { - throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId); + throw new InvalidParameterValueException("Could not find zone by ID", null); } else { zoneName = zone.getName(); } @@ -124,7 +124,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta List trafficMonitorsInZone = _resourceMgr.listAllHostsInOneZoneByType(Host.Type.TrafficMonitor, zoneId); if (trafficMonitorsInZone.size() != 0) { - throw new InvalidParameterValueException("Already added an traffic monitor in zone: " + zoneName); + throw new InvalidParameterValueException("Already added an traffic monitor in zone: " + zoneName, null); } URI uri; @@ -132,7 +132,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta uri = new URI(cmd.getUrl()); } catch (Exception e) { s_logger.debug(e); - throw new InvalidParameterValueException(e.getMessage()); + throw new InvalidParameterValueException(e.getMessage(), null); } String ipAddress = uri.getHost(); @@ -161,13 +161,13 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta hostDetails.put("url", cmd.getUrl()); hostDetails.put("last_collection", ""+System.currentTimeMillis()); if(cmd.getInclZones() != null){ - hostDetails.put("inclZones", cmd.getInclZones()); + hostDetails.put("inclZones", cmd.getInclZones()); } if(cmd.getExclZones() != null){ - hostDetails.put("exclZones", cmd.getExclZones()); + hostDetails.put("exclZones", cmd.getExclZones()); } - - + + Host trafficMonitor = _resourceMgr.addHost(zoneId, resource, Host.Type.TrafficMonitor, hostDetails); return trafficMonitor; } @@ -182,12 +182,12 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta User caller = _accountMgr.getActiveUser(UserContext.current().getCallerUserId()); HostVO trafficMonitor = _hostDao.findById(hostId); if (trafficMonitor == null) { - throw new InvalidParameterValueException("Could not find an traffic monitor with ID: " + hostId); + throw new InvalidParameterValueException("Could not find an traffic monitor by ID", null); } - try { - if (_resourceMgr.maintain(hostId) && _resourceMgr.deleteHost(hostId, false, false)) { - return true; + try { + if (_resourceMgr.maintain(hostId) && _resourceMgr.deleteHost(hostId, false, false)) { + return true; } else { return false; } @@ -225,7 +225,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta networkJoin.and("guestType", networkJoin.entity().getGuestType(), Op.EQ); AllocatedIpSearch.join("network", networkJoin, AllocatedIpSearch.entity().getSourceNetworkId(), networkJoin.entity().getId(), JoinBuilder.JoinType.INNER); AllocatedIpSearch.done(); - + _networkStatsInterval = NumbersUtil.parseInt(_configDao.getValue(Config.DirectNetworkStatsInterval.key()), 86400); _TSinclZones = _configDao.getValue(Config.TrafficSentinelIncludeZones.key()); _TSexclZones = _configDao.getValue(Config.TrafficSentinelExcludeZones.key()); @@ -241,7 +241,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta @Override public boolean stop() { - _resourceMgr.unregisterResourceStateAdapter(this.getClass().getSimpleName()); + _resourceMgr.unregisterResourceStateAdapter(this.getClass().getSimpleName()); return true; } @@ -262,7 +262,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta private int _interval; - private long mgmtSrvrId = MacAddress.getMacAddress().toLong(); + private final long mgmtSrvrId = MacAddress.getMacAddress().toLong(); protected DirectNetworkStatsListener(int interval) { _interval = interval; @@ -324,7 +324,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta rightNow.add(Calendar.HOUR_OF_DAY, -2); Date now = rightNow.getTime(); - + if(lastCollection.after(now)){ s_logger.debug("Current time is less than 2 hours after last collection time : " + lastCollection.toString() + ". Skipping direct network usage collection"); return false; @@ -376,7 +376,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta } List collectedStats = new ArrayList(); - + //Get usage for Ips which were assigned for the entire duration if(fullDurationIpUsage.size() > 0){ DirectNetworkUsageCommand cmd = new DirectNetworkUsageCommand(IpList, lastCollection, now, _TSinclZones, _TSexclZones); @@ -441,8 +441,8 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta } if(collectedStats.size() == 0){ - s_logger.debug("No new direct network stats. No need to persist"); - return false; + s_logger.debug("No new direct network stats. No need to persist"); + return false; } //Persist all the stats and last_collection time in a single transaction Transaction txn = Transaction.open(Transaction.CLOUD_DB); @@ -496,9 +496,9 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta s_logger.debug("Sending RecurringNetworkUsageCommand to " + agentId); RecurringNetworkUsageCommand watch = new RecurringNetworkUsageCommand(_interval); try { - _agentMgr.send(agentId, new Commands(watch), this); + _agentMgr.send(agentId, new Commands(watch), this); } catch (AgentUnavailableException e) { - s_logger.debug("Can not process connect for host " + agentId, e); + s_logger.debug("Can not process connect for host " + agentId, e); } } return; @@ -516,34 +516,34 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta protected DirectNetworkStatsListener() { } - + } - @Override + @Override public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } - @Override + @Override public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { if (!(startup[0] instanceof StartupTrafficMonitorCommand)) { return null; } - + host.setType(Host.Type.TrafficMonitor); return host; } - @Override + @Override public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { - if(host.getType() != Host.Type.TrafficMonitor){ - return null; - } - - return new DeleteHostAnswer(true); + if(host.getType() != Host.Type.TrafficMonitor){ + return null; + } + + return new DeleteHostAnswer(true); } } diff --git a/server/src/com/cloud/network/PortProfileManagerImpl.java b/server/src/com/cloud/network/PortProfileManagerImpl.java index e7c6b36f8e8..7150829024c 100644 --- a/server/src/com/cloud/network/PortProfileManagerImpl.java +++ b/server/src/com/cloud/network/PortProfileManagerImpl.java @@ -15,107 +15,107 @@ package com.cloud.network; import org.apache.log4j.Logger; import com.cloud.exception.InvalidParameterValueException; -import com.cloud.utils.db.DB; -import com.cloud.utils.db.Transaction; -import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.network.PortProfileVO.BindingType; import com.cloud.network.PortProfileVO.PortType; import com.cloud.network.dao.PortProfileDaoImpl; +import com.cloud.utils.db.DB; +import com.cloud.utils.db.Transaction; +import com.cloud.utils.exception.CloudRuntimeException; public class PortProfileManagerImpl { - - private PortProfileDaoImpl _portProfileDao; - + + private final PortProfileDaoImpl _portProfileDao; + private static final org.apache.log4j.Logger s_logger = Logger.getLogger(PortProfileManagerImpl.class); - + public PortProfileManagerImpl() { - _portProfileDao = new PortProfileDaoImpl(); + _portProfileDao = new PortProfileDaoImpl(); } - + @DB public PortProfileVO addPortProfile(String portProfName, long vsmId, int vlanId, PortType pType, BindingType bType) { - // In this function, we create a port profile record in the port_profile table. - // First, check if a port profile with the given name already exists. If it does, throw an exception. - - if (_portProfileDao.findByName(portProfName) != null) { - s_logger.info("Port Profile with specified name: " + portProfName + " already exists"); - throw new InvalidParameterValueException("Port Profile with specified name: " + portProfName + " already exists"); - } - // Check if the VSM id is a valid one. - - // TODO: Should we also check whether a port profile for the specified vlanId already exists, and if so, - // fail this function? Do we want to enforce such a 1:1 mapping b/w port profile and vlanId? - - // Else, go ahead and create the port profile. - PortProfileVO portProfileObj = new PortProfileVO(portProfName, vsmId, vlanId, pType, bType); + // In this function, we create a port profile record in the port_profile table. + // First, check if a port profile with the given name already exists. If it does, throw an exception. - Transaction txn = Transaction.currentTxn(); - try { - txn.start(); - _portProfileDao.persist(portProfileObj); - txn.commit(); - } catch (Exception e) { - txn.rollback(); - throw new CloudRuntimeException(e.getMessage()); - } + if (_portProfileDao.findByName(portProfName) != null) { + s_logger.info("Port Profile with specified name: " + portProfName + " already exists"); + throw new InvalidParameterValueException("Port Profile with specified name: " + portProfName + " already exists", null); + } + // Check if the VSM id is a valid one. - // Return the PortProfileVO object created. + // TODO: Should we also check whether a port profile for the specified vlanId already exists, and if so, + // fail this function? Do we want to enforce such a 1:1 mapping b/w port profile and vlanId? + + // Else, go ahead and create the port profile. + PortProfileVO portProfileObj = new PortProfileVO(portProfName, vsmId, vlanId, pType, bType); + + Transaction txn = Transaction.currentTxn(); + try { + txn.start(); + _portProfileDao.persist(portProfileObj); + txn.commit(); + } catch (Exception e) { + txn.rollback(); + throw new CloudRuntimeException(e.getMessage()); + } + + // Return the PortProfileVO object created. return portProfileObj; } - + @DB public PortProfileVO addPortProfile(String portProfName, long vsmId, int lowVlanId, int highVlanId, PortType pType, BindingType bType) { - // In this function, we create a port profile record in the port_profile table. - - // First, check if a port profile with the given name already exists. If it does, throw an exception. - PortProfileVO portProfileObj; - - portProfileObj = _portProfileDao.findByName(portProfName); - - if (portProfileObj != null) { - s_logger.info("Port Profile with specified name: " + portProfName + " already exists"); - throw new InvalidParameterValueException("Port Profile with specified name: " + portProfName + " already exists"); - } + // In this function, we create a port profile record in the port_profile table. - // Next, check if there is any existing port profile that uses a VLAN ID range that clashes with the - // range passed to this function. If so, throw an exception. - - if (_portProfileDao.doesVlanRangeClash(lowVlanId, highVlanId) == true) { - s_logger.info("Port Profile's vlanId range clashes with an existing Port Profile's"); - throw new InvalidParameterValueException("Port Profile's vlanId range clashes with an existing Port Profile's"); - } - - // Else, go ahead and create the port profile. - portProfileObj = new PortProfileVO(portProfName, vsmId, lowVlanId, highVlanId, pType, bType); + // First, check if a port profile with the given name already exists. If it does, throw an exception. + PortProfileVO portProfileObj; - Transaction txn = Transaction.currentTxn(); - try { - txn.start(); - _portProfileDao.persist(portProfileObj); - txn.commit(); - } catch (Exception e) { - txn.rollback(); - throw new CloudRuntimeException(e.getMessage()); - } + portProfileObj = _portProfileDao.findByName(portProfName); - // Return the PortProfileVO object created. + if (portProfileObj != null) { + s_logger.info("Port Profile with specified name: " + portProfName + " already exists"); + throw new InvalidParameterValueException("Port Profile with specified name: " + portProfName + " already exists", null); + } + + // Next, check if there is any existing port profile that uses a VLAN ID range that clashes with the + // range passed to this function. If so, throw an exception. + + if (_portProfileDao.doesVlanRangeClash(lowVlanId, highVlanId) == true) { + s_logger.info("Port Profile's vlanId range clashes with an existing Port Profile's"); + throw new InvalidParameterValueException("Port Profile's vlanId range clashes with an existing Port Profile's", null); + } + + // Else, go ahead and create the port profile. + portProfileObj = new PortProfileVO(portProfName, vsmId, lowVlanId, highVlanId, pType, bType); + + Transaction txn = Transaction.currentTxn(); + try { + txn.start(); + _portProfileDao.persist(portProfileObj); + txn.commit(); + } catch (Exception e) { + txn.rollback(); + throw new CloudRuntimeException(e.getMessage()); + } + + // Return the PortProfileVO object created. return portProfileObj; } - + @DB public boolean deletePortProfile(long portProfileId) { PortProfileVO ppObj = _portProfileDao.findById(portProfileId); if (ppObj == null) { - // This entry is already not present. Return success. - return true; + // This entry is already not present. Return success. + return true; } - + //Else, remove it. // TODO: Should we be putting any checks here before removing // the port profile record from the db? - + Transaction txn = Transaction.currentTxn(); try { txn.start(); @@ -123,8 +123,8 @@ public class PortProfileManagerImpl { _portProfileDao.remove(portProfileId); txn.commit(); } catch (Exception e) { - s_logger.info("Caught exception when trying to delete Port Profile record.." + e.getMessage()); - throw new CloudRuntimeException("Failed to delete Port Profile"); + s_logger.info("Caught exception when trying to delete Port Profile record.." + e.getMessage()); + throw new CloudRuntimeException("Failed to delete Port Profile"); } return true; } diff --git a/server/src/com/cloud/network/PortProfileVO.java b/server/src/com/cloud/network/PortProfileVO.java index 38905a3c25e..fc0df446863 100644 --- a/server/src/com/cloud/network/PortProfileVO.java +++ b/server/src/com/cloud/network/PortProfileVO.java @@ -26,6 +26,7 @@ import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; + import com.cloud.exception.InvalidParameterValueException; /** @@ -36,56 +37,56 @@ import com.cloud.exception.InvalidParameterValueException; @Entity @Table(name="port_profile") public class PortProfileVO { - - // We need to know what properties a VSM has. Put them here. - + + // We need to know what properties a VSM has. Put them here. + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private long id; @Column(name="uuid") - private String uuid; + private final String uuid; @Column(name = "port_profile_name") private String portProfileName; @Column(name = "port_mode") private PortMode portMode; - + @Column(name = "vsm_id") private long vsmId; @Column(name = "trunk_low_vlan_id") private int lowVlanId; - + @Column(name = "trunk_high_vlan_id") private int highVlanId; - + @Column(name = "access_vlan_id") private int accessVlanId; - + @Column(name = "port_type") private PortType portType; - + @Column(name = "port_binding") private BindingType portBinding; public enum BindingType { - Static, - Ephemeral + Static, + Ephemeral } - + public enum PortType { - Ethernet, - vEthernet + Ethernet, + vEthernet } - + // This tells us whether the port trunks multiple VLANs // or carries traffic of a single VLAN. public enum PortMode { - Access, - Trunk + Access, + Trunk } // Accessor methods @@ -98,79 +99,79 @@ public class PortProfileVO { } public String getPortProfileName() { - return portProfileName; + return portProfileName; } - + public PortMode getPortMode() { - return portMode; + return portMode; } - + public long getVsmId() { - return vsmId; + return vsmId; } - + public int getLowVlanId() { - return lowVlanId; + return lowVlanId; } - + public int getHighVlanId() { - return highVlanId; + return highVlanId; } - + public int getAccessVlanId() { - return accessVlanId; + return accessVlanId; } - + public PortType getPortType() { - return portType; + return portType; } - + public BindingType getPortBinding() { - return portBinding; + return portBinding; } - + // Setter methods public void setPortProfileName(String name) { - portProfileName = name; + portProfileName = name; } - + public void setPortMode(PortMode mode) { - portMode = mode; + portMode = mode; } - + public void setVsmId(long id) { - vsmId = id; + vsmId = id; } - + public void setLowVlanId(int vlanId) { - lowVlanId = vlanId; + lowVlanId = vlanId; } - + public void setHighVlanId(int vlanId) { - highVlanId = vlanId; + highVlanId = vlanId; } - + public void setAccessVlanId(int vlanId) { - accessVlanId = vlanId; + accessVlanId = vlanId; } - + public void setPortType(PortType type) { - portType = type; + portType = type; } - + public void setPortBinding(BindingType bindingType) { - portBinding = bindingType; + portBinding = bindingType; } // Constructor methods. - + public PortProfileVO(String portProfName, long vsmId, int vlanId, PortType pType, BindingType bType) { - // Set the relevant portprofile properties here. - // When supplied with a single vlanId, we set this portprofile as an access port profile. - - this.setPortMode(PortMode.Access); - + // Set the relevant portprofile properties here. + // When supplied with a single vlanId, we set this portprofile as an access port profile. + + this.setPortMode(PortMode.Access); + this.uuid = UUID.randomUUID().toString(); this.setPortProfileName(portProfName); this.setVsmId(vsmId); @@ -178,16 +179,16 @@ public class PortProfileVO { this.setPortType(pType); this.setPortBinding(bType); } - + public PortProfileVO(String portProfName, long vsmId, int lowVlanId, int highVlanId, PortType pType, BindingType bType) { - // Set the relevant portprofile properties here. - // When supplied with a vlan range, we set this portprofile as a trunk port profile. - - if (lowVlanId >= highVlanId) { - throw new InvalidParameterValueException("Low Vlan Id cannot be greater than or equal to high Vlan Id"); - } - this.setPortMode(PortMode.Trunk); - + // Set the relevant portprofile properties here. + // When supplied with a vlan range, we set this portprofile as a trunk port profile. + + if (lowVlanId >= highVlanId) { + throw new InvalidParameterValueException("Low Vlan Id cannot be greater than or equal to high Vlan Id", null); + } + this.setPortMode(PortMode.Trunk); + this.uuid = UUID.randomUUID().toString(); this.setPortProfileName(portProfName); this.setVsmId(vsmId); @@ -196,7 +197,7 @@ public class PortProfileVO { this.setPortType(pType); this.setPortBinding(bType); } - + public PortProfileVO() { this.uuid = UUID.randomUUID().toString(); } diff --git a/server/src/com/cloud/network/Site2SiteVpnConnectionVO.java b/server/src/com/cloud/network/Site2SiteVpnConnectionVO.java index f38e2d8644b..8081ac8ccfb 100644 --- a/server/src/com/cloud/network/Site2SiteVpnConnectionVO.java +++ b/server/src/com/cloud/network/Site2SiteVpnConnectionVO.java @@ -5,6 +5,8 @@ import java.util.UUID; import javax.persistence.Column; import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @@ -30,6 +32,7 @@ public class Site2SiteVpnConnectionVO implements Site2SiteVpnConnection { private long customerGatewayId; @Column(name="state") + @Enumerated(value=EnumType.STRING) private State state; @Column(name="domain_id") diff --git a/server/src/com/cloud/network/StorageNetworkManagerImpl.java b/server/src/com/cloud/network/StorageNetworkManagerImpl.java index 816c5ed9e58..0e749e64a24 100755 --- a/server/src/com/cloud/network/StorageNetworkManagerImpl.java +++ b/server/src/com/cloud/network/StorageNetworkManagerImpl.java @@ -12,370 +12,366 @@ // Automatically generated by addcopyright.py at 04/03/2012 package com.cloud.network; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.List; -import java.util.Map; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; - -import org.apache.log4j.Logger; - -import com.cloud.api.commands.CreateStorageNetworkIpRangeCmd; -import com.cloud.api.commands.DeleteStorageNetworkIpRangeCmd; -import com.cloud.api.commands.UpdateStorageNetworkIpRangeCmd; -import com.cloud.api.commands.listStorageNetworkIpRangeCmd; -import com.cloud.dc.HostPodVO; -import com.cloud.dc.StorageNetworkIpRange; -import com.cloud.dc.StorageNetworkIpAddressVO; -import com.cloud.dc.StorageNetworkIpRangeVO; -import com.cloud.dc.dao.HostPodDao; -import com.cloud.dc.dao.StorageNetworkIpAddressDao; -import com.cloud.dc.dao.StorageNetworkIpRangeDao; -import com.cloud.exception.InsufficientAddressCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.host.HostVO; -import com.cloud.network.Networks.TrafficType; -import com.cloud.network.dao.NetworkDao; -import com.cloud.utils.Pair; -import com.cloud.utils.component.Inject; -import com.cloud.utils.db.DB; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteriaService; -import com.cloud.utils.db.Transaction; -import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.net.NetUtils; -import com.cloud.vm.SecondaryStorageVmVO; -import com.cloud.vm.VirtualMachine; -import com.cloud.vm.dao.SecondaryStorageVmDao; -import com.cloud.vm.dao.VMInstanceDao; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; + +import org.apache.log4j.Logger; + +import com.cloud.api.commands.CreateStorageNetworkIpRangeCmd; +import com.cloud.api.commands.DeleteStorageNetworkIpRangeCmd; +import com.cloud.api.commands.UpdateStorageNetworkIpRangeCmd; +import com.cloud.api.commands.listStorageNetworkIpRangeCmd; +import com.cloud.dc.HostPodVO; +import com.cloud.dc.StorageNetworkIpAddressVO; +import com.cloud.dc.StorageNetworkIpRange; +import com.cloud.dc.StorageNetworkIpRangeVO; +import com.cloud.dc.dao.HostPodDao; +import com.cloud.dc.dao.StorageNetworkIpAddressDao; +import com.cloud.dc.dao.StorageNetworkIpRangeDao; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.network.Networks.TrafficType; +import com.cloud.network.dao.NetworkDao; +import com.cloud.utils.component.Inject; +import com.cloud.utils.db.DB; +import com.cloud.utils.db.SearchCriteria.Op; +import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.SearchCriteriaService; +import com.cloud.utils.db.Transaction; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.net.NetUtils; +import com.cloud.vm.SecondaryStorageVmVO; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.dao.SecondaryStorageVmDao; @Local(value = {StorageNetworkManager.class, StorageNetworkService.class}) public class StorageNetworkManagerImpl implements StorageNetworkManager, StorageNetworkService { - private static final Logger s_logger = Logger.getLogger(StorageNetworkManagerImpl.class); - - String _name; - @Inject - StorageNetworkIpAddressDao _sNwIpDao; - @Inject - StorageNetworkIpRangeDao _sNwIpRangeDao; + private static final Logger s_logger = Logger.getLogger(StorageNetworkManagerImpl.class); + + String _name; + @Inject + StorageNetworkIpAddressDao _sNwIpDao; + @Inject + StorageNetworkIpRangeDao _sNwIpRangeDao; @Inject NetworkDao _networkDao; - @Inject - HostPodDao _podDao; - @Inject - SecondaryStorageVmDao _ssvmDao; - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _name = name; - return true; - } + @Inject + HostPodDao _podDao; + @Inject + SecondaryStorageVmDao _ssvmDao; - @Override - public boolean start() { - // TODO Auto-generated method stub - return true; - } + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _name = name; + return true; + } - @Override - public boolean stop() { - // TODO Auto-generated method stub - return true; - } + @Override + public boolean start() { + // TODO Auto-generated method stub + return true; + } - @Override - public String getName() { - // TODO Auto-generated method stub - return null; - } + @Override + public boolean stop() { + // TODO Auto-generated method stub + return true; + } - private void checkOverlapPrivateIpRange(long podId, String startIp, String endIp) { - HostPodVO pod = _podDao.findById(podId); - if (pod == null) { - throw new CloudRuntimeException("Cannot find pod " + podId); - } - String[] IpRange = pod.getDescription().split("-"); - if ((IpRange[0] == null || IpRange[1] == null) || (!NetUtils.isValidIp(IpRange[0]) || !NetUtils.isValidIp(IpRange[1]))) { - return; - } - if (NetUtils.ipRangesOverlap(startIp, endIp, IpRange[0], IpRange[1])) { - throw new InvalidParameterValueException("The Storage network Start IP and endIP address range overlap with private IP :" + IpRange[0] + ":" + IpRange[1]); + @Override + public String getName() { + // TODO Auto-generated method stub + return null; + } + + private void checkOverlapPrivateIpRange(long podId, String startIp, String endIp) { + HostPodVO pod = _podDao.findById(podId); + if (pod == null) { + throw new CloudRuntimeException("Cannot find pod " + podId); } - } - - private void checkOverlapStorageIpRange(long podId, String startIp, String endIp) { - List curRanges = _sNwIpRangeDao.listByPodId(podId); - for (StorageNetworkIpRangeVO range : curRanges) { - if (NetUtils.ipRangesOverlap(startIp, endIp, range.getStartIp(), range.getEndIp())) { - throw new InvalidParameterValueException("The Storage network Start IP and endIP address range overlap with private IP :" + range.getStartIp() + " - " + range.getEndIp()); - } - } - } - - private void createStorageIpEntires(Transaction txn, long rangeId, String startIp, String endIp, long zoneId) throws SQLException { + String[] IpRange = pod.getDescription().split("-"); + if ((IpRange[0] == null || IpRange[1] == null) || (!NetUtils.isValidIp(IpRange[0]) || !NetUtils.isValidIp(IpRange[1]))) { + return; + } + if (NetUtils.ipRangesOverlap(startIp, endIp, IpRange[0], IpRange[1])) { + throw new InvalidParameterValueException("The Storage network Start IP and endIP address range overlap with private IP :" + IpRange[0] + ":" + IpRange[1], null); + } + } + + private void checkOverlapStorageIpRange(long podId, String startIp, String endIp) { + List curRanges = _sNwIpRangeDao.listByPodId(podId); + for (StorageNetworkIpRangeVO range : curRanges) { + if (NetUtils.ipRangesOverlap(startIp, endIp, range.getStartIp(), range.getEndIp())) { + throw new InvalidParameterValueException("The Storage network Start IP and endIP address range overlap with private IP :" + range.getStartIp() + " - " + range.getEndIp(), null); + } + } + } + + private void createStorageIpEntires(Transaction txn, long rangeId, String startIp, String endIp, long zoneId) throws SQLException { long startIPLong = NetUtils.ip2Long(startIp); long endIPLong = NetUtils.ip2Long(endIp); - String insertSql = "INSERT INTO `cloud`.`op_dc_storage_network_ip_address` (range_id, ip_address, mac_address, taken) VALUES (?, ?, (select mac_address from `cloud`.`data_center` where id=?), ?)"; - String updateSql = "UPDATE `cloud`.`data_center` set mac_address = mac_address+1 where id=?"; - PreparedStatement stmt = null; - Connection conn = txn.getConnection(); - + String insertSql = "INSERT INTO `cloud`.`op_dc_storage_network_ip_address` (range_id, ip_address, mac_address, taken) VALUES (?, ?, (select mac_address from `cloud`.`data_center` where id=?), ?)"; + String updateSql = "UPDATE `cloud`.`data_center` set mac_address = mac_address+1 where id=?"; + PreparedStatement stmt = null; + Connection conn = txn.getConnection(); + while (startIPLong <= endIPLong) { - stmt = conn.prepareStatement(insertSql); - stmt.setLong(1, rangeId); - stmt.setString(2, NetUtils.long2Ip(startIPLong++)); - stmt.setLong(3, zoneId); - stmt.setNull(4, java.sql.Types.DATE); + stmt = conn.prepareStatement(insertSql); + stmt.setLong(1, rangeId); + stmt.setString(2, NetUtils.long2Ip(startIPLong++)); + stmt.setLong(3, zoneId); + stmt.setNull(4, java.sql.Types.DATE); stmt.executeUpdate(); stmt.close(); - + stmt = txn.prepareStatement(updateSql); stmt.setLong(1, zoneId); stmt.executeUpdate(); stmt.close(); } - } - - @Override - @DB + } + + @Override + @DB public StorageNetworkIpRange updateIpRange(UpdateStorageNetworkIpRangeCmd cmd) { - Integer vlan = cmd.getVlan(); - Long rangeId = cmd.getId(); - String startIp = cmd.getStartIp(); - String endIp = cmd.getEndIp(); - String netmask = cmd.getNetmask(); - - if (netmask != null && !NetUtils.isValidNetmask(netmask)) { - throw new CloudRuntimeException("Invalid netmask:" + netmask); - } - - if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) { - throw new CloudRuntimeException("Cannot update the range," + getInUseIpAddress(rangeId)); - } - - StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId); - if (range == null) { - throw new CloudRuntimeException("Cannot find storage ip range " + rangeId); - } - - if (startIp != null || endIp != null) { - long podId = range.getPodId(); - startIp = startIp == null ? range.getStartIp() : startIp; - endIp = endIp == null ? range.getEndIp() : endIp; - checkOverlapPrivateIpRange(podId, startIp, endIp); - checkOverlapStorageIpRange(podId, startIp, endIp); - } - - Transaction txn = Transaction.currentTxn(); - txn.start(); - try { - range = _sNwIpRangeDao.acquireInLockTable(range.getId()); - if (range == null) { - throw new CloudRuntimeException("Cannot acquire lock on storage ip range " + rangeId); - } - StorageNetworkIpRangeVO vo = _sNwIpRangeDao.createForUpdate(); - if (vlan != null) { - vo.setVlan(vlan); - } - if (startIp != null) { - vo.setStartIp(startIp); - } - if (endIp != null) { - vo.setEndIp(endIp); - } - if (netmask != null) { - vo.setNetmask(netmask); - } - _sNwIpRangeDao.update(rangeId, vo); - } finally { - if (range != null) { - _sNwIpRangeDao.releaseFromLockTable(range.getId()); - } - } - txn.commit(); - - return _sNwIpRangeDao.findById(rangeId); + Integer vlan = cmd.getVlan(); + Long rangeId = cmd.getId(); + String startIp = cmd.getStartIp(); + String endIp = cmd.getEndIp(); + String netmask = cmd.getNetmask(); + + if (netmask != null && !NetUtils.isValidNetmask(netmask)) { + throw new CloudRuntimeException("Invalid netmask:" + netmask); + } + + if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) { + throw new CloudRuntimeException("Cannot update the range," + getInUseIpAddress(rangeId)); + } + + StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId); + if (range == null) { + throw new CloudRuntimeException("Cannot find storage ip range " + rangeId); + } + + if (startIp != null || endIp != null) { + long podId = range.getPodId(); + startIp = startIp == null ? range.getStartIp() : startIp; + endIp = endIp == null ? range.getEndIp() : endIp; + checkOverlapPrivateIpRange(podId, startIp, endIp); + checkOverlapStorageIpRange(podId, startIp, endIp); + } + + Transaction txn = Transaction.currentTxn(); + txn.start(); + try { + range = _sNwIpRangeDao.acquireInLockTable(range.getId()); + if (range == null) { + throw new CloudRuntimeException("Cannot acquire lock on storage ip range " + rangeId); + } + StorageNetworkIpRangeVO vo = _sNwIpRangeDao.createForUpdate(); + if (vlan != null) { + vo.setVlan(vlan); + } + if (startIp != null) { + vo.setStartIp(startIp); + } + if (endIp != null) { + vo.setEndIp(endIp); + } + if (netmask != null) { + vo.setNetmask(netmask); + } + _sNwIpRangeDao.update(rangeId, vo); + } finally { + if (range != null) { + _sNwIpRangeDao.releaseFromLockTable(range.getId()); + } + } + txn.commit(); + + return _sNwIpRangeDao.findById(rangeId); } - - @Override - @DB - public StorageNetworkIpRange createIpRange(CreateStorageNetworkIpRangeCmd cmd) throws SQLException { - Long podId = cmd.getPodId(); - String startIp = cmd.getStartIp(); - String endIp = cmd.getEndIp(); - Integer vlan = cmd.getVlan(); - String netmask = cmd.getNetmask(); - if (endIp == null) { - endIp = startIp; - } - - if (!NetUtils.isValidNetmask(netmask)) { - throw new CloudRuntimeException("Invalid netmask:" + netmask); - } - - HostPodVO pod = _podDao.findById(podId); - if (pod == null) { - throw new CloudRuntimeException("Cannot find pod " + podId); - } - Long zoneId = pod.getDataCenterId(); - - List nws = _networkDao.listByZoneAndTrafficType(zoneId, TrafficType.Storage); - if (nws.size() == 0) { - throw new CloudRuntimeException("Cannot find storage network in zone " + zoneId); - } - if (nws.size() > 1) { - throw new CloudRuntimeException("Find more than one storage network in zone " + zoneId + "," + nws.size() + " found"); - } - NetworkVO nw = nws.get(0); - - checkOverlapPrivateIpRange(podId, startIp, endIp); - checkOverlapStorageIpRange(podId, startIp, endIp); + @Override + @DB + public StorageNetworkIpRange createIpRange(CreateStorageNetworkIpRangeCmd cmd) throws SQLException { + Long podId = cmd.getPodId(); + String startIp = cmd.getStartIp(); + String endIp = cmd.getEndIp(); + Integer vlan = cmd.getVlan(); + String netmask = cmd.getNetmask(); - Transaction txn = Transaction.currentTxn(); - StorageNetworkIpRangeVO range = null; + if (endIp == null) { + endIp = startIp; + } - txn.start(); - range = new StorageNetworkIpRangeVO(zoneId, podId, nw.getId(), startIp, endIp, vlan, netmask, cmd.getGateWay()); - _sNwIpRangeDao.persist(range); - try { - createStorageIpEntires(txn, range.getId(), startIp, endIp, zoneId); - } catch (SQLException e) { - txn.rollback(); - StringBuilder err = new StringBuilder(); - err.append("Create storage network range failed."); - err.append("startIp=" + startIp); - err.append("endIp=" + endIp); - err.append("netmask=" + netmask); - err.append("zoneId=" + zoneId); - s_logger.debug(err.toString(), e); - throw e; - } + if (!NetUtils.isValidNetmask(netmask)) { + throw new CloudRuntimeException("Invalid netmask:" + netmask); + } - txn.commit(); - - return range; - } - - private String getInUseIpAddress(long rangeId) { - List ips = _sNwIpDao.listInUseIpByRangeId(rangeId); - StringBuilder res = new StringBuilder(); - res.append("Below IP of range " + rangeId + " is still in use:"); - for (String ip : ips) { - res.append(ip).append(","); - } - return res.toString(); - } - - @Override - @DB + HostPodVO pod = _podDao.findById(podId); + if (pod == null) { + throw new CloudRuntimeException("Cannot find pod " + podId); + } + Long zoneId = pod.getDataCenterId(); + + List nws = _networkDao.listByZoneAndTrafficType(zoneId, TrafficType.Storage); + if (nws.size() == 0) { + throw new CloudRuntimeException("Cannot find storage network in zone " + zoneId); + } + if (nws.size() > 1) { + throw new CloudRuntimeException("Find more than one storage network in zone " + zoneId + "," + nws.size() + " found"); + } + NetworkVO nw = nws.get(0); + + checkOverlapPrivateIpRange(podId, startIp, endIp); + checkOverlapStorageIpRange(podId, startIp, endIp); + + Transaction txn = Transaction.currentTxn(); + StorageNetworkIpRangeVO range = null; + + txn.start(); + range = new StorageNetworkIpRangeVO(zoneId, podId, nw.getId(), startIp, endIp, vlan, netmask, cmd.getGateWay()); + _sNwIpRangeDao.persist(range); + try { + createStorageIpEntires(txn, range.getId(), startIp, endIp, zoneId); + } catch (SQLException e) { + txn.rollback(); + StringBuilder err = new StringBuilder(); + err.append("Create storage network range failed."); + err.append("startIp=" + startIp); + err.append("endIp=" + endIp); + err.append("netmask=" + netmask); + err.append("zoneId=" + zoneId); + s_logger.debug(err.toString(), e); + throw e; + } + + txn.commit(); + + return range; + } + + private String getInUseIpAddress(long rangeId) { + List ips = _sNwIpDao.listInUseIpByRangeId(rangeId); + StringBuilder res = new StringBuilder(); + res.append("Below IP of range " + rangeId + " is still in use:"); + for (String ip : ips) { + res.append(ip).append(","); + } + return res.toString(); + } + + @Override + @DB public void deleteIpRange(DeleteStorageNetworkIpRangeCmd cmd) { - long rangeId = cmd.getId(); - StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId); - if (range == null) { - throw new CloudRuntimeException("Can not find storage network ip range " + rangeId); - } - - if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) { - throw new CloudRuntimeException(getInUseIpAddress(rangeId)); - } + long rangeId = cmd.getId(); + StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId); + if (range == null) { + throw new CloudRuntimeException("Can not find storage network ip range " + rangeId); + } - final Transaction txn = Transaction.currentTxn(); - txn.start(); - try { - range = _sNwIpRangeDao.acquireInLockTable(rangeId); - if (range == null) { - String msg = "Unable to acquire lock on storage network ip range id=" + rangeId + ", delete failed"; - s_logger.warn(msg); - throw new CloudRuntimeException(msg); - } - /* entries in op_dc_storage_network_ip_address will be deleted automatically due to fk_storage_ip_address__range_id constraint key */ - _sNwIpRangeDao.remove(rangeId); - } finally { - if (range != null) { - _sNwIpRangeDao.releaseFromLockTable(rangeId); - } - } - txn.commit(); - } - - @Override + if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) { + throw new CloudRuntimeException(getInUseIpAddress(rangeId)); + } + + final Transaction txn = Transaction.currentTxn(); + txn.start(); + try { + range = _sNwIpRangeDao.acquireInLockTable(rangeId); + if (range == null) { + String msg = "Unable to acquire lock on storage network ip range id=" + rangeId + ", delete failed"; + s_logger.warn(msg); + throw new CloudRuntimeException(msg); + } + /* entries in op_dc_storage_network_ip_address will be deleted automatically due to fk_storage_ip_address__range_id constraint key */ + _sNwIpRangeDao.remove(rangeId); + } finally { + if (range != null) { + _sNwIpRangeDao.releaseFromLockTable(rangeId); + } + } + txn.commit(); + } + + @Override public List listIpRange(listStorageNetworkIpRangeCmd cmd) { - Long rangeId = cmd.getRangeId(); - Long podId = cmd.getPodId(); - Long zoneId = cmd.getZoneId(); - - List result = null; - if (rangeId != null) { - result = _sNwIpRangeDao.listByRangeId(rangeId); - } else if (podId != null) { - result = _sNwIpRangeDao.listByPodId(podId); - } else if (zoneId != null) { - result = _sNwIpRangeDao.listByDataCenterId(zoneId); - } else { - result = _sNwIpRangeDao.listAll(); - } - - return (List)result; - } + Long rangeId = cmd.getRangeId(); + Long podId = cmd.getPodId(); + Long zoneId = cmd.getZoneId(); - @Override - public void releaseIpAddress(String ip) { - _sNwIpDao.releaseIpAddress(ip); - } - - @Override + List result = null; + if (rangeId != null) { + result = _sNwIpRangeDao.listByRangeId(rangeId); + } else if (podId != null) { + result = _sNwIpRangeDao.listByPodId(podId); + } else if (zoneId != null) { + result = _sNwIpRangeDao.listByDataCenterId(zoneId); + } else { + result = _sNwIpRangeDao.listAll(); + } + + return result; + } + + @Override + public void releaseIpAddress(String ip) { + _sNwIpDao.releaseIpAddress(ip); + } + + @Override public StorageNetworkIpAddressVO acquireIpAddress(long podId) { - List ranges = _sNwIpRangeDao.listByPodId(podId); - for (StorageNetworkIpRangeVO r : ranges) { - try { - r = _sNwIpRangeDao.acquireInLockTable(r.getId()); - if (r == null) { - String msg = "Unable to acquire lock on storage network ip range id=" + r.getId() + ", delete failed"; - s_logger.warn(msg); - throw new CloudRuntimeException(msg); - } - - StorageNetworkIpAddressVO ip = _sNwIpDao.takeIpAddress(r.getId()); - if (ip != null) { - return ip; - } - } finally { - if (r != null) { - _sNwIpRangeDao.releaseFromLockTable(r.getId()); - } - } - } - - return null; + List ranges = _sNwIpRangeDao.listByPodId(podId); + for (StorageNetworkIpRangeVO r : ranges) { + try { + r = _sNwIpRangeDao.acquireInLockTable(r.getId()); + if (r == null) { + String msg = "Unable to acquire lock on storage network ip range id=" + r.getId() + ", delete failed"; + s_logger.warn(msg); + throw new CloudRuntimeException(msg); + } + + StorageNetworkIpAddressVO ip = _sNwIpDao.takeIpAddress(r.getId()); + if (ip != null) { + return ip; + } + } finally { + if (r != null) { + _sNwIpRangeDao.releaseFromLockTable(r.getId()); + } + } + } + + return null; } - @Override + @Override public boolean isStorageIpRangeAvailable(long zoneId) { - SearchCriteriaService sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class); - sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, zoneId); - List entries = sc.list(); - return entries.size() > 0; + SearchCriteriaService sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class); + sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, zoneId); + List entries = sc.list(); + return entries.size() > 0; } - @Override + @Override public List getSSVMWithNoStorageNetwork(long zoneId) { - List ssvms = _ssvmDao.getSecStorageVmListInStates(null, zoneId, VirtualMachine.State.Starting, VirtualMachine.State.Running, VirtualMachine.State.Stopping); - return ssvms; + List ssvms = _ssvmDao.getSecStorageVmListInStates(null, zoneId, VirtualMachine.State.Starting, VirtualMachine.State.Running, VirtualMachine.State.Stopping); + return ssvms; } - @Override + @Override public boolean isAnyStorageIpInUseInZone(long zoneId) { - List ranges = _sNwIpRangeDao.listByDataCenterId(zoneId); - for (StorageNetworkIpRangeVO r : ranges) { - if (_sNwIpDao.countInUseIpByRangeId(r.getId()) > 0) { - return true; - } - } - return false; + List ranges = _sNwIpRangeDao.listByDataCenterId(zoneId); + for (StorageNetworkIpRangeVO r : ranges) { + if (_sNwIpDao.countInUseIpByRangeId(r.getId()) > 0) { + return true; + } + } + return false; } } diff --git a/server/src/com/cloud/network/as/AutoScaleManagerImpl.java b/server/src/com/cloud/network/as/AutoScaleManagerImpl.java index ba1bce8e470..89d51de4f32 100644 --- a/server/src/com/cloud/network/as/AutoScaleManagerImpl.java +++ b/server/src/com/cloud/network/as/AutoScaleManagerImpl.java @@ -76,6 +76,7 @@ import com.cloud.user.User; import com.cloud.user.UserContext; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserDao; +import com.cloud.utils.IdentityProxy; import com.cloud.utils.Ternary; import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; @@ -172,7 +173,7 @@ public class AutoScaleManagerImpl implements AutoScaleService, Manager { for (Counter counter : counters) { if (!supportedCounters.contains(counter.getSource().name().toString())) { throw new InvalidParameterException("AutoScale counter with source='" + counter.getSource() + "' is not supported " + - "in the network where lb is configured"); + "in the network where lb is configured"); } } } @@ -183,7 +184,7 @@ public class AutoScaleManagerImpl implements AutoScaleService, Manager { VO vo = dao.findById(id); if (vo == null) { - throw new InvalidParameterValueException("Unable to find " + paramName); + throw new InvalidParameterValueException("Unable to find " + paramName, null); } _accountMgr.checkAccess(caller, null, false, (ControlledEntity) vo); @@ -215,25 +216,25 @@ public class AutoScaleManagerImpl implements AutoScaleService, Manager { } int duration = policy.getDuration(); if (duration < interval) { - throw new InvalidParameterValueException("duration : " + duration + " specified in a policy cannot be less than vm group's interval : " + interval); + throw new InvalidParameterValueException("duration : " + duration + " specified in a policy cannot be less than vm group's interval : " + interval, null); } if (quietTime < interval) { - throw new InvalidParameterValueException("quietTime : " + quietTime + " specified in a policy cannot be less than vm group's interval : " + interval); + throw new InvalidParameterValueException("quietTime : " + quietTime + " specified in a policy cannot be less than vm group's interval : " + interval, null); } if (quietTime != prevQuietTime) { - throw new InvalidParameterValueException("quietTime should be same for all the policies specified in " + paramName); + throw new InvalidParameterValueException("quietTime should be same for all the policies specified in " + paramName, null); } if (scaleUpPolicies) { if (!isAutoScaleScaleUpPolicy(policy)) { - throw new InvalidParameterValueException("Only scaleup policies can be specified in scaleuppolicyids"); + throw new InvalidParameterValueException("Only scaleup policies can be specified in scaleuppolicyids", null); } } else { if (isAutoScaleScaleUpPolicy(policy)) { - throw new InvalidParameterValueException("Only scaledown policies can be specified in scaledownpolicyids"); + throw new InvalidParameterValueException("Only scaledown policies can be specified in scaledownpolicyids", null); } } List policyConditionMapVOs = _autoScalePolicyConditionMapDao.listByAll(policy.getId(), null); @@ -255,16 +256,16 @@ public class AutoScaleManagerImpl implements AutoScaleService, Manager { VirtualMachineTemplate template = _templateMgr.getTemplate(templateId); // Make sure a valid template ID was specified if (template == null) { - throw new InvalidParameterValueException("Unable to use the given template."); + throw new InvalidParameterValueException("Unable to use the given template.", null); } if (destroyVmGraceperiod < 0) { - throw new InvalidParameterValueException("Destroy Vm Grace Period cannot be less than 0."); + throw new InvalidParameterValueException("Destroy Vm Grace Period cannot be less than 0.", null); } User user = _userDao.findById(autoscaleUserId); if (user.getAccountId() != vmProfile.getAccountId()) { - throw new InvalidParameterValueException("AutoScale User id does not belong to the same account"); + throw new InvalidParameterValueException("AutoScale User id does not belong to the same account", null); } String apiKey = user.getApiKey(); @@ -272,15 +273,15 @@ public class AutoScaleManagerImpl implements AutoScaleService, Manager { String csUrl = _configDao.getValue(Config.EndpointeUrl.key()); if(apiKey == null) { - throw new InvalidParameterValueException("apiKey for user: " + user.getUsername() + " is empty. Please generate it"); + throw new InvalidParameterValueException("apiKey for user: " + user.getUsername() + " is empty. Please generate it", null); } if(secretKey == null) { - throw new InvalidParameterValueException("secretKey for user: " + user.getUsername() + " is empty. Please generate it"); + throw new InvalidParameterValueException("secretKey for user: " + user.getUsername() + " is empty. Please generate it", null); } if(csUrl == null || csUrl.contains("localhost")) { - throw new InvalidParameterValueException("Global setting endpointe.url has to be set to the Management Server's API end point"); + throw new InvalidParameterValueException("Global setting endpointe.url has to be set to the Management Server's API end point", null); } vmProfile = _autoScaleVmProfileDao.persist(vmProfile); @@ -303,12 +304,12 @@ public class AutoScaleManagerImpl implements AutoScaleService, Manager { DataCenter zone = _configMgr.getZone(zoneId); if (zone == null) { - throw new InvalidParameterValueException("Unable to find zone by id=" + zoneId); + throw new InvalidParameterValueException("Unable to find zone by id", null); } ServiceOffering serviceOffering = _configMgr.getServiceOffering(serviceOfferingId); if (serviceOffering == null) { - throw new InvalidParameterValueException("Unable to find service offering: " + serviceOfferingId); + throw new InvalidParameterValueException("Unable to find service offering by id", null); } // validations @@ -368,7 +369,7 @@ public class AutoScaleManagerImpl implements AutoScaleService, Manager { List vmGroupList = _autoScaleVmGroupDao.listByAll(null, profileId); for (AutoScaleVmGroupVO vmGroupVO : vmGroupList) { if (vmGroupVO.getState().equals(AutoScaleVmGroup.State_Disabled)) { - throw new InvalidParameterValueException("The AutoScale Vm Profile can be updated only if the Vm Group it is associated with is disabled in state"); + throw new InvalidParameterValueException("The AutoScale Vm Profile can be updated only if the Vm Group it is associated with is disabled in state", null); } } @@ -384,7 +385,7 @@ public class AutoScaleManagerImpl implements AutoScaleService, Manager { /* Check if entity is in database */ getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Vm Profile", id, _autoScaleVmProfileDao); if (_autoScaleVmGroupDao.isProfileInUse(id)) { - throw new InvalidParameterValueException("Cannot delete AutoScale Vm Profile when it is in use by one more vm groups"); + throw new InvalidParameterValueException("Cannot delete AutoScale Vm Profile when it is in use by one more vm groups", null); } boolean success = _autoScaleVmProfileDao.remove(id); if (success) { @@ -425,11 +426,11 @@ public class AutoScaleManagerImpl implements AutoScaleService, Manager { int quietTime = autoScalePolicyVO.getQuietTime(); if (duration < 0) { - throw new InvalidParameterValueException("duration is an invalid value: " + duration); + throw new InvalidParameterValueException("duration is an invalid value: " + duration, null); } if (quietTime < 0) { - throw new InvalidParameterValueException("quiettime is an invalid value: " + quietTime); + throw new InvalidParameterValueException("quiettime is an invalid value: " + quietTime, null); } final Transaction txn = Transaction.currentTxn(); @@ -452,13 +453,13 @@ public class AutoScaleManagerImpl implements AutoScaleService, Manager { if (conditionIds.size() != conditions.size()) { // TODO report the condition id which could not be found - throw new InvalidParameterValueException("Unable to find the condition specified"); + throw new InvalidParameterValueException("Unable to find the condition specified", null); } ArrayList counterIds = new ArrayList(); for (ConditionVO condition : conditions) { if (counterIds.contains(condition.getCounterid())) { - throw new InvalidParameterValueException("atleast two conditions in the conditionids have the same counter. It is not right to apply two different conditions for the same counter"); + throw new InvalidParameterValueException("atleast two conditions in the conditionids have the same counter. It is not right to apply two different conditions for the same counter", null); } counterIds.add(condition.getCounterid()); } @@ -490,7 +491,7 @@ public class AutoScaleManagerImpl implements AutoScaleService, Manager { action = action.toLowerCase(); if (!NetUtils.isValidAutoScaleAction(action)) { - throw new InvalidParameterValueException("action is invalid, only 'scaleup' and 'scaledown' is supported"); + throw new InvalidParameterValueException("action is invalid, only 'scaleup' and 'scaledown' is supported", null); } AutoScalePolicyVO policyVO = new AutoScalePolicyVO(cmd.getDomainId(), cmd.getAccountId(), duration, quietTime, action); @@ -508,7 +509,7 @@ public class AutoScaleManagerImpl implements AutoScaleService, Manager { getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Policy", id, _autoScalePolicyDao); if (_autoScaleVmGroupPolicyMapDao.isAutoScalePolicyInUse(id)) { - throw new InvalidParameterValueException("Cannot delete AutoScale Policy when it is in use by one or more AutoScale Vm Groups"); + throw new InvalidParameterValueException("Cannot delete AutoScale Policy when it is in use by one or more AutoScale Vm Groups", null); } Transaction txn = Transaction.currentTxn(); @@ -535,7 +536,9 @@ public class AutoScaleManagerImpl implements AutoScaleService, Manager { Account caller = UserContext.current().getCaller(); Account owner = _accountDao.findActiveAccount(accountName, domainId); if (owner == null) { - throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", domainId, "domainId")); + throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain with specifed domainId", idList); } _accountMgr.checkAccess(caller, null, false, owner); } @@ -563,7 +566,7 @@ public class AutoScaleManagerImpl implements AutoScaleService, Manager { Account caller = UserContext.current().getCaller(); Ternary domainIdRecursiveListProject = new Ternary(domainId, isRecursive, null); + ListProjectResourcesCriteria>(domainId, isRecursive, null); _accountMgr.buildACLSearchParameters(caller, id, accountName, null, permittedAccounts, domainIdRecursiveListProject, listAll, false); domainId = domainIdRecursiveListProject.first(); @@ -661,13 +664,13 @@ public class AutoScaleManagerImpl implements AutoScaleService, Manager { } if (!vmGroupVO.getState().equals(AutoScaleVmGroup.State_Disabled)) { - throw new InvalidParameterValueException("The AutoScale Policy can be updated only if the Vm Group it is associated with is disabled in state"); + throw new InvalidParameterValueException("The AutoScale Policy can be updated only if the Vm Group it is associated with is disabled in state", null); } if (vmGroupVO.getInterval() < policy.getDuration()) { - throw new InvalidParameterValueException("duration is less than the associated AutoScaleVmGroup's interval"); + throw new InvalidParameterValueException("duration is less than the associated AutoScaleVmGroup's interval", null); } if (vmGroupVO.getInterval() < policy.getQuietTime()) { - throw new InvalidParameterValueException("quietTime is less than the associated AutoScaleVmGroup's interval"); + throw new InvalidParameterValueException("quietTime is less than the associated AutoScaleVmGroup's interval", null); } } @@ -692,11 +695,11 @@ public class AutoScaleManagerImpl implements AutoScaleService, Manager { Long zoneId = _ipAddressDao.findById(loadBalancer.getSourceIpAddressId()).getDataCenterId(); if (_autoScaleVmGroupDao.isAutoScaleLoadBalancer(loadBalancer.getId())) { - throw new InvalidParameterValueException("an AutoScaleVmGroup is already attached to the lb rule, the existing vm group has to be first deleted"); + throw new InvalidParameterValueException("an AutoScaleVmGroup is already attached to the lb rule, the existing vm group has to be first deleted", null); } if (_lb2VmMapDao.isVmAttachedToLoadBalancer(loadBalancer.getId())) { - throw new InvalidParameterValueException("there are Vms already bound to the specified LoadBalancing Rule. User bound Vms and AutoScaled Vm Group cannot co-exist on a Load Balancing Rule"); + throw new InvalidParameterValueException("there are Vms already bound to the specified LoadBalancing Rule. User bound Vms and AutoScaled Vm Group cannot co-exist on a Load Balancing Rule", null); } AutoScaleVmGroupVO vmGroupVO = new AutoScaleVmGroupVO(cmd.getLbRuleId(), zoneId, loadBalancer.getDomainId(), loadBalancer.getAccountId(), minMembers, maxMembers, @@ -729,7 +732,7 @@ public class AutoScaleManagerImpl implements AutoScaleService, Manager { } // This should never happen, because today loadbalancerruleid is manadatory for AutoScaleVmGroup. - throw new InvalidParameterValueException("Only LoadBalancer based AutoScale is supported"); + throw new InvalidParameterValueException("Only LoadBalancer based AutoScale is supported", null); } @Override @@ -829,19 +832,19 @@ public class AutoScaleManagerImpl implements AutoScaleService, Manager { List policyIds = new ArrayList(); if (minMembers < 0) { - throw new InvalidParameterValueException(ApiConstants.MIN_MEMBERS + " is an invalid value: " + minMembers); + throw new InvalidParameterValueException(ApiConstants.MIN_MEMBERS + " is an invalid value: " + minMembers, null); } if (maxMembers < 0) { - throw new InvalidParameterValueException(ApiConstants.MAX_MEMBERS + " is an invalid value: " + minMembers); + throw new InvalidParameterValueException(ApiConstants.MAX_MEMBERS + " is an invalid value: " + minMembers, null); } if (minMembers > maxMembers) { - throw new InvalidParameterValueException(ApiConstants.MIN_MEMBERS + " (" + minMembers + ")cannot be greater than " + ApiConstants.MAX_MEMBERS + " (" + maxMembers + ")"); + throw new InvalidParameterValueException(ApiConstants.MIN_MEMBERS + " (" + minMembers + ")cannot be greater than " + ApiConstants.MAX_MEMBERS + " (" + maxMembers + ")", null); } if (interval < 0) { - throw new InvalidParameterValueException("interval is an invalid value: " + interval); + throw new InvalidParameterValueException("interval is an invalid value: " + interval, null); } if (scaleUpPolicyIds != null) { @@ -906,7 +909,7 @@ public class AutoScaleManagerImpl implements AutoScaleService, Manager { AutoScaleVmGroupVO vmGroupVO = getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Vm Group", vmGroupId, _autoScaleVmGroupDao); if (!vmGroupVO.getState().equals(AutoScaleVmGroup.State_Disabled)) { - throw new InvalidParameterValueException("An AutoScale Vm Group can be updated only when it is in disabled state"); + throw new InvalidParameterValueException("An AutoScale Vm Group can be updated only when it is in disabled state", null); } if (minMembers != null) { @@ -936,7 +939,7 @@ public class AutoScaleManagerImpl implements AutoScaleService, Manager { AutoScaleVmGroupVO vmGroup = getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Vm Group", id, _autoScaleVmGroupDao); boolean success = false; if (!vmGroup.getState().equals(AutoScaleVmGroup.State_Disabled)) { - throw new InvalidParameterValueException("Only a AutoScale Vm Group which is in Disabled state can be enabled."); + throw new InvalidParameterValueException("Only a AutoScale Vm Group which is in Disabled state can be enabled.", null); } try { @@ -963,7 +966,7 @@ public class AutoScaleManagerImpl implements AutoScaleService, Manager { AutoScaleVmGroupVO vmGroup = getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Vm Group", id, _autoScaleVmGroupDao); boolean success = false; if (!vmGroup.getState().equals(AutoScaleVmGroup.State_Enabled)) { - throw new InvalidParameterValueException("Only a AutoScale Vm Group which is in Disabled state can be disabled."); + throw new InvalidParameterValueException("Only a AutoScale Vm Group which is in Disabled state can be disabled.", null); } try { @@ -993,7 +996,7 @@ public class AutoScaleManagerImpl implements AutoScaleService, Manager { try { src = Counter.Source.valueOf(source); } catch (Exception ex) { - throw new InvalidParameterValueException("The Source " + source + " does not exist; Unable to create Counter"); + throw new InvalidParameterValueException("The Source " + source + " does not exist; Unable to create Counter", null); } CounterVO counter = null; @@ -1017,14 +1020,14 @@ public class AutoScaleManagerImpl implements AutoScaleService, Manager { try { op = Condition.Operator.valueOf(opr); } catch (IllegalArgumentException ex) { - throw new InvalidParameterValueException("The Operator " + opr + " does not exist; Unable to create Condition."); + throw new InvalidParameterValueException("The Operator " + opr + " does not exist; Unable to create Condition.", null); } // TODO - Validate threshold CounterVO counter = _counterDao.findById(cid); if (counter == null) { - throw new InvalidParameterValueException("Unable to find counter"); + throw new InvalidParameterValueException("Unable to find counter", null); } ConditionVO condition = null; @@ -1090,7 +1093,7 @@ public class AutoScaleManagerImpl implements AutoScaleService, Manager { // Verify Counter id CounterVO counter = _counterDao.findById(counterId); if (counter == null) { - throw new InvalidParameterValueException("Unable to find Counter"); + throw new InvalidParameterValueException("Unable to find Counter", null); } // Verify if it is used in any Condition @@ -1115,7 +1118,7 @@ public class AutoScaleManagerImpl implements AutoScaleService, Manager { /* Check if entity is in database */ ConditionVO condition = getEntityInDatabase(UserContext.current().getCaller(), "Condition", conditionId, _conditionDao); if (condition == null) { - throw new InvalidParameterValueException("Unable to find Condition"); + throw new InvalidParameterValueException("Unable to find Condition", null); } // Verify if condition is used in any autoscale policy diff --git a/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java b/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java index 1b1cbf7aec7..f8824d951a5 100644 --- a/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java +++ b/server/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java @@ -73,8 +73,8 @@ import com.cloud.network.resource.F5BigIpResource; import com.cloud.network.rules.LbStickinessMethod; import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType; import com.cloud.offering.NetworkOffering; -import com.cloud.resource.ServerResource; import com.cloud.server.api.response.ExternalLoadBalancerResponse; +import com.cloud.utils.IdentityProxy; import com.cloud.utils.NumbersUtil; import com.cloud.utils.component.Inject; import com.cloud.utils.exception.CloudRuntimeException; @@ -123,7 +123,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan @Override public boolean implement(Network guestConfig, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException, - InsufficientNetworkCapacityException { + InsufficientNetworkCapacityException { if (!canHandle(guestConfig)) { return false; @@ -138,7 +138,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan @Override public boolean prepare(Network config, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, - InsufficientNetworkCapacityException, ResourceUnavailableException { + InsufficientNetworkCapacityException, ResourceUnavailableException { return true; } @@ -239,7 +239,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan @Override public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException { + ResourceUnavailableException { // TODO Auto-generated method stub return true; } @@ -265,18 +265,20 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan zone = _dcDao.findById(zoneId); if (zone == null) { - throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId); + throw new InvalidParameterValueException("Could not find zone by ID", null); } List physicalNetworks = _physicalNetworkDao.listByZone(zoneId); if ((physicalNetworks == null) || (physicalNetworks.size() > 1)) { - throw new InvalidParameterValueException("There are no physical networks or multiple physical networks configured in zone with ID: " - + zoneId + " to add this device."); + List idList = new ArrayList(); + idList.add(new IdentityProxy(zone, zoneId, "zoneId")); + throw new InvalidParameterValueException("There are no physical networks or multiple physical networks " + + "configured in zone with specified zoneId to add this device.", idList); } pNetwork = physicalNetworks.get(0); String deviceType = NetworkDevice.F5BigIpLoadBalancer.getName(); - lbDeviceVO = addExternalLoadBalancer(pNetwork.getId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), deviceType, (ServerResource) new F5BigIpResource()); + lbDeviceVO = addExternalLoadBalancer(pNetwork.getId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), deviceType, new F5BigIpResource()); if (lbDeviceVO != null) { lbHost = _hostDao.findById(lbDeviceVO.getHostId()); @@ -301,18 +303,21 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan if (zoneId != null) { zone = _dcDao.findById(zoneId); if (zone == null) { - throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId); + throw new InvalidParameterValueException("Could not find zone by ID", null); } List physicalNetworks = _physicalNetworkDao.listByZone(zoneId); if ((physicalNetworks == null) || (physicalNetworks.size() > 1)) { - throw new InvalidParameterValueException("There are no physical networks or multiple physical networks configured in zone with ID: " - + zoneId + " to add this device."); + List idList = new ArrayList(); + idList.add(new IdentityProxy(zone, zoneId, "zoneId")); + throw new InvalidParameterValueException("There are no physical networks or multiple " + + "physical networks configured in zone with specified zoneId " + + "to add this device.", idList); } pNetwork = physicalNetworks.get(0); return listExternalLoadBalancers(pNetwork.getId(), NetworkDevice.F5BigIpLoadBalancer.getName()); } else { - throw new InvalidParameterValueException("Zone Id must be specified to list the external load balancers"); + throw new InvalidParameterValueException("Zone Id must be specified to list the external load balancers", null); } } @@ -326,10 +331,10 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan public ExternalLoadBalancerDeviceVO addF5LoadBalancer(AddF5LoadBalancerCmd cmd) { String deviceName = cmd.getDeviceType(); if (!deviceName.equalsIgnoreCase(NetworkDevice.F5BigIpLoadBalancer.getName())) { - throw new InvalidParameterValueException("Invalid F5 load balancer device type"); + throw new InvalidParameterValueException("Invalid F5 load balancer device type", null); } - return addExternalLoadBalancer(cmd.getPhysicalNetworkId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), deviceName, (ServerResource) new F5BigIpResource()); + return addExternalLoadBalancer(cmd.getPhysicalNetworkId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), deviceName, new F5BigIpResource()); } @@ -339,7 +344,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan ExternalLoadBalancerDeviceVO lbDeviceVo = _lbDeviceDao.findById(lbDeviceId); if ((lbDeviceVo == null) || !lbDeviceVo.getDeviceName().equalsIgnoreCase(NetworkDevice.F5BigIpLoadBalancer.getName())) { - throw new InvalidParameterValueException("No F5 load balancer device found with ID: " + lbDeviceId); + throw new InvalidParameterValueException("Couldn't find F5 load balancer device by ID", null); } return deleteExternalLoadBalancer(lbDeviceVo.getHostId()); @@ -352,7 +357,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan ExternalLoadBalancerDeviceVO lbDeviceVo = _lbDeviceDao.findById(lbDeviceId); if ((lbDeviceVo == null) || !lbDeviceVo.getDeviceName().equalsIgnoreCase(NetworkDevice.F5BigIpLoadBalancer.getName())) { - throw new InvalidParameterValueException("No F5 load balancer device found with ID: " + lbDeviceId); + throw new InvalidParameterValueException("Couldn't find F5 load balancer device by ID", null); } if (capacity != null) { @@ -381,13 +386,13 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan List lbDevices = new ArrayList(); 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", null); } if (lbDeviceId != null) { ExternalLoadBalancerDeviceVO lbDeviceVo = _lbDeviceDao.findById(lbDeviceId); if (lbDeviceVo == null || !lbDeviceVo.getDeviceName().equalsIgnoreCase(NetworkDevice.F5BigIpLoadBalancer.getName())) { - throw new InvalidParameterValueException("Could not find F5 load balancer device with ID: " + lbDeviceId); + throw new InvalidParameterValueException("Could not find F5 load balancer device by ID", null); } lbDevices.add(lbDeviceVo); return lbDevices; @@ -396,7 +401,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan 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 by ID", null); } lbDevices = _lbDeviceDao.listByPhysicalNetworkAndProvider(physcialNetworkId, Provider.F5BigIp.getName()); return lbDevices; @@ -412,7 +417,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan ExternalLoadBalancerDeviceVO lbDeviceVo = _lbDeviceDao.findById(lbDeviceId); if (lbDeviceVo == null || !lbDeviceVo.getDeviceName().equalsIgnoreCase(NetworkDevice.F5BigIpLoadBalancer.getName())) { - throw new InvalidParameterValueException("Could not find F5 load balancer device with ID " + lbDeviceId); + throw new InvalidParameterValueException("Could not find F5 load balancer device by ID ", null); } List networkLbMaps = _networkLBDao.listByLoadBalancerDeviceId(lbDeviceId); diff --git a/server/src/com/cloud/network/element/VpcVirtualRouterElement.java b/server/src/com/cloud/network/element/VpcVirtualRouterElement.java index e6959b0f3ac..79795f25719 100644 --- a/server/src/com/cloud/network/element/VpcVirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VpcVirtualRouterElement.java @@ -288,11 +288,13 @@ public class VpcVirtualRouterElement extends VirtualRouterElement implements Vpc Map> capabilities = new HashMap>(); capabilities.putAll(VirtualRouterElement.capabilities); - Map sourceNatCapabilities = capabilities.get(Service.SourceNat); + Map sourceNatCapabilities = new HashMap(); + sourceNatCapabilities.putAll(capabilities.get(Service.SourceNat)); sourceNatCapabilities.put(Capability.RedundantRouter, "false"); capabilities.put(Service.SourceNat, sourceNatCapabilities); - Map vpnCapabilities = capabilities.get(Service.Vpn); + Map vpnCapabilities = new HashMap(); + vpnCapabilities.putAll(capabilities.get(Service.Vpn)); vpnCapabilities.put(Capability.VpnTypes, "s2svpn"); capabilities.put(Service.Vpn, vpnCapabilities); diff --git a/server/src/com/cloud/network/firewall/FirewallManagerImpl.java b/server/src/com/cloud/network/firewall/FirewallManagerImpl.java index f80cc578913..21eb1740217 100644 --- a/server/src/com/cloud/network/firewall/FirewallManagerImpl.java +++ b/server/src/com/cloud/network/firewall/FirewallManagerImpl.java @@ -462,9 +462,11 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma //remove the rule _firewallDao.remove(rule.getId()); - //if the rule is the last one for the ip address assigned to VPC, unassign it from the network - IpAddress ip = _ipAddressDao.findById(rule.getSourceIpAddressId()); - _networkMgr.unassignIPFromVpcNetwork(ip.getId(), rule.getNetworkId()); + if (rule.getSourceIpAddressId() != null) { + //if the rule is the last one for the ip address assigned to VPC, unassign it from the network + IpAddress ip = _ipAddressDao.findById(rule.getSourceIpAddressId()); + _networkMgr.unassignIPFromVpcNetwork(ip.getId(), rule.getNetworkId()); + } } @Override diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index 93baf7cae66..2a240ab5d92 100755 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -42,6 +42,8 @@ import com.cloud.agent.api.Answer; import com.cloud.agent.api.BumpUpPriorityCommand; import com.cloud.agent.api.CheckRouterAnswer; import com.cloud.agent.api.CheckRouterCommand; +import com.cloud.agent.api.CheckS2SVpnConnectionsAnswer; +import com.cloud.agent.api.CheckS2SVpnConnectionsCommand; import com.cloud.agent.api.Command; import com.cloud.agent.api.GetDomRVersionAnswer; import com.cloud.agent.api.GetDomRVersionCmd; @@ -127,6 +129,11 @@ import com.cloud.network.Networks.TrafficType; import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.network.PublicIpAddress; import com.cloud.network.RemoteAccessVpn; +import com.cloud.network.Site2SiteCustomerGateway; +import com.cloud.network.Site2SiteCustomerGatewayVO; +import com.cloud.network.Site2SiteVpnConnection; +import com.cloud.network.Site2SiteVpnConnectionVO; +import com.cloud.network.Site2SiteVpnGatewayVO; import com.cloud.network.SshKeysDistriMonitor; import com.cloud.network.VirtualNetworkApplianceService; import com.cloud.network.VirtualRouterProvider; @@ -160,6 +167,7 @@ import com.cloud.network.rules.StaticNat; import com.cloud.network.rules.StaticNatImpl; import com.cloud.network.rules.StaticNatRule; import com.cloud.network.rules.dao.PortForwardingRulesDao; +import com.cloud.network.vpn.Site2SiteVpnManager; import com.cloud.offering.ServiceOffering; import com.cloud.offerings.NetworkOfferingVO; import com.cloud.offerings.dao.NetworkOfferingDao; @@ -313,6 +321,8 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian Site2SiteVpnGatewayDao _s2sVpnGatewayDao; @Inject Site2SiteVpnConnectionDao _s2sVpnConnectionDao; + @Inject + Site2SiteVpnManager _s2sVpnMgr; int _routerRamSize; int _routerCpuMHz; @@ -896,7 +906,79 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian } } - + protected void updateSite2SiteVpnConnectionState(List routers) { + for (DomainRouterVO router : routers) { + List conns = _s2sVpnMgr.getConnectionsForRouter(router); + if (conns == null || conns.isEmpty()) { + continue; + } + if (router.getState() != State.Running) { + for (Site2SiteVpnConnectionVO conn : conns) { + conn.setState(Site2SiteVpnConnection.State.Disconnected); + _s2sVpnConnectionDao.persist(conn); + } + continue; + } + List ipList = new ArrayList(); + for (Site2SiteVpnConnectionVO conn : conns) { + if (conn.getState() != Site2SiteVpnConnection.State.Connected && + conn.getState() != Site2SiteVpnConnection.State.Disconnected) { + continue; + } + Site2SiteCustomerGateway gw = _s2sCustomerGatewayDao.findById(conn.getCustomerGatewayId()); + ipList.add(gw.getGatewayIp()); + } + String privateIP = router.getPrivateIpAddress(); + HostVO host = _hostDao.findById(router.getHostId()); + if (host == null || host.getStatus() != Status.Up) { + continue; + } else if (host.getManagementServerId() != ManagementServerNode.getManagementServerId()) { + /* Only cover hosts managed by this management server */ + continue; + } else if (privateIP != null) { + final CheckS2SVpnConnectionsCommand command = new CheckS2SVpnConnectionsCommand(ipList); + command.setAccessDetail(NetworkElementCommand.ROUTER_IP, getRouterControlIp(router.getId())); + command.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName()); + command.setWait(30); + final Answer origAnswer = _agentMgr.easySend(router.getHostId(), command); + CheckS2SVpnConnectionsAnswer answer = null; + if (origAnswer instanceof CheckS2SVpnConnectionsAnswer) { + answer = (CheckS2SVpnConnectionsAnswer)origAnswer; + } else { + s_logger.warn("Unable to update router " + router.getHostName() + "'s VPN connection status"); + continue; + } + if (!answer.getResult()) { + s_logger.warn("Unable to update router " + router.getHostName() + "'s VPN connection status"); + continue; + } + for (Site2SiteVpnConnectionVO conn : conns) { + if (conn.getState() != Site2SiteVpnConnection.State.Connected && + conn.getState() != Site2SiteVpnConnection.State.Disconnected) { + continue; + } + Site2SiteVpnConnection.State oldState = conn.getState(); + Site2SiteCustomerGateway gw = _s2sCustomerGatewayDao.findById(conn.getCustomerGatewayId()); + if (answer.isConnected(gw.getGatewayIp())) { + conn.setState(Site2SiteVpnConnection.State.Connected); + } else { + conn.setState(Site2SiteVpnConnection.State.Disconnected); + } + _s2sVpnConnectionDao.persist(conn); + if (oldState != conn.getState()) { + String title = "Site-to-site Vpn Connection to " + gw.getName() + + " just switch from " + oldState + " to " + conn.getState(); + String context = "Site-to-site Vpn Connection to " + gw.getName() + " on router " + router.getHostName() + + "(id: " + router.getId() + ") " + " just switch from " + oldState + " to " + conn.getState(); + s_logger.info(context); + _alertMgr.sendAlert(AlertManager.ALERT_TYPE_DOMAIN_ROUTER, + router.getDataCenterIdToDeployIn(), router.getPodIdToDeployIn(), title, context); + } + } + } + } + } + protected void updateRoutersRedundantState(List routers) { boolean updated = false; for (DomainRouterVO router : routers) { @@ -1089,6 +1171,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian s_logger.debug("Found " + routers.size() + " routers. "); updateRoutersRedundantState(routers); + updateSite2SiteVpnConnectionState(routers); /* FIXME assumed the a pair of redundant routers managed by same mgmt server, * then the update above can get the latest status */ diff --git a/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java index 42a7a2df8b0..e2143a8817f 100644 --- a/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java @@ -891,7 +891,7 @@ public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplian super.finalizeNetworkRulesForNetwork(cmds, router, provider, guestNetworkId); - if (router.getVpcId() == null) { + if (router.getVpcId() != null) { if (_networkMgr.isProviderSupportServiceInNetwork(guestNetworkId, Service.NetworkACL, Provider.VPCVirtualRouter)) { List networkACLs = _networkACLMgr.listNetworkACLs(guestNetworkId); s_logger.debug("Found " + networkACLs.size() + " network ACLs to apply as a part of VPC VR " + router diff --git a/server/src/com/cloud/network/vpc/VpcManagerImpl.java b/server/src/com/cloud/network/vpc/VpcManagerImpl.java index 201f24328d8..528f4b19185 100644 --- a/server/src/com/cloud/network/vpc/VpcManagerImpl.java +++ b/server/src/com/cloud/network/vpc/VpcManagerImpl.java @@ -917,7 +917,7 @@ public class VpcManagerImpl implements VpcManager, Manager{ && _ntwkMgr.areServicesSupportedByNetworkOffering(guestNtwkOff.getId(), Service.SourceNat))) { throw new InvalidParameterValueException("Only networks of type " + GuestType.Isolated + " with service " - + Service.SourceNat + + + Service.SourceNat.getName() + " can be added as a part of VPC", null); } diff --git a/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java b/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java index d99564fd24f..b5fa4ea7aab 100755 --- a/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java +++ b/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java @@ -61,6 +61,7 @@ import com.cloud.user.AccountManager; import com.cloud.user.DomainManager; import com.cloud.user.UserContext; import com.cloud.user.dao.AccountDao; +import com.cloud.utils.IdentityProxy; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.PasswordGenerator; @@ -81,7 +82,7 @@ import com.cloud.utils.net.NetUtils; public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manager { private final static Logger s_logger = Logger.getLogger(RemoteAccessVpnManagerImpl.class); String _name; - + @Inject AccountDao _accountDao; @Inject VpnUserDao _vpnUsersDao; @Inject RemoteAccessVpnDao _remoteAccessVpnDao; @@ -95,7 +96,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag @Inject FirewallRulesDao _rulesDao; @Inject FirewallManager _firewallMgr; @Inject UsageEventDao _usageEventDao; - + int _userLimit; int _pskLength; String _clientIpRange; @@ -110,26 +111,26 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag // make sure ip address exists PublicIpAddress ipAddr = _networkMgr.getPublicIpAddress(publicIpId); if (ipAddr == null) { - throw new InvalidParameterValueException("Unable to create remote access vpn, invalid public IP address id" + publicIpId); + throw new InvalidParameterValueException("Unable to create remote access vpn, invalid public IP address id" + publicIpId, null); } - + _accountMgr.checkAccess(caller, null, true, ipAddr); if (!ipAddr.readyToUse()) { - throw new InvalidParameterValueException("The Ip address is not ready to be used yet: " + ipAddr.getAddress()); + throw new InvalidParameterValueException("The Ip address is not ready to be used yet: " + ipAddr.getAddress(), null); } - + IPAddressVO ipAddress = _ipAddressDao.findById(publicIpId); _networkMgr.checkIpForService(ipAddress, Service.Vpn, null); RemoteAccessVpnVO vpnVO = _remoteAccessVpnDao.findByPublicIpAddress(publicIpId); - + if (vpnVO != null) { //if vpn is in Added state, return it to the api if (vpnVO.getState() == RemoteAccessVpn.State.Added) { return vpnVO; } - throw new InvalidParameterValueException("A Remote Access VPN already exists for this public Ip address"); + throw new InvalidParameterValueException("A Remote Access VPN already exists for this public Ip address", null); } // TODO: assumes one virtual network / domr per account per zone @@ -139,13 +140,15 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag if (vpnVO.getState() == RemoteAccessVpn.State.Added) { return vpnVO; } - throw new InvalidParameterValueException("A Remote Access VPN already exists for this account"); + throw new InvalidParameterValueException("A Remote Access VPN already exists for this account", null); } - + //Verify that vpn service is enabled for the network Network network = _networkMgr.getNetwork(networkId); if (!_networkMgr.areServicesSupportedInNetwork(network.getId(), Service.Vpn)) { - throw new InvalidParameterValueException("Vpn service is not supported in network id=" + ipAddr.getAssociatedWithNetworkId()); + List idList = new ArrayList(); + idList.add(new IdentityProxy(ipAddr, ipAddr.getAssociatedWithNetworkId(), "ipAddressId")); + throw new InvalidParameterValueException("Vpn service is not supported in network containing specified ipAddressId", idList); } if (ipRange == null) { @@ -153,13 +156,13 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag } String[] range = ipRange.split("-"); if (range.length != 2) { - throw new InvalidParameterValueException("Invalid ip range"); + throw new InvalidParameterValueException("Invalid ip range", null); } if (!NetUtils.isValidIp(range[0]) || !NetUtils.isValidIp(range[1])) { - throw new InvalidParameterValueException("Invalid ip in range specification " + ipRange); + throw new InvalidParameterValueException("Invalid ip in range specification " + ipRange, null); } if (!NetUtils.validIpRange(range[0], range[1])) { - throw new InvalidParameterValueException("Invalid ip range " + ipRange); + throw new InvalidParameterValueException("Invalid ip range " + ipRange, null); } Pair cidr = NetUtils.getCidr(network.getCidr()); @@ -169,7 +172,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag String[] guestIpRange = NetUtils.getIpRangeFromCidr(cidr.first(), cidr.second()); if (NetUtils.ipRangesOverlap(range[0], range[1], guestIpRange[0], guestIpRange[1])) { throw new InvalidParameterValueException("Invalid ip range: " + ipRange + " overlaps with guest ip range " + guestIpRange[0] + "-" - + guestIpRange[1]); + + guestIpRange[1], null); } // TODO: check sufficient range // TODO: check overlap with private and public ip ranges in datacenter @@ -212,21 +215,21 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag @Override @DB public void destroyRemoteAccessVpn(long ipId) throws ResourceUnavailableException { Account caller = UserContext.current().getCaller(); - + RemoteAccessVpnVO vpn = _remoteAccessVpnDao.findById(ipId); if (vpn == null) { s_logger.debug("vpn id=" + ipId + " does not exists "); return; } - + _accountMgr.checkAccess(caller, null, true, vpn); - + Network network = _networkMgr.getNetwork(vpn.getNetworkId()); - + vpn.setState(RemoteAccessVpn.State.Removed); _remoteAccessVpnDao.update(vpn.getServerAddressId(), vpn); - - + + List elements = _networkMgr.getRemoteAccessVpnElements(); boolean success = false; try { @@ -241,32 +244,32 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag //Cleanup corresponding ports List vpnFwRules = _rulesDao.listByIpAndPurpose(ipId, Purpose.Vpn); Transaction txn = Transaction.currentTxn(); - + boolean applyFirewall = false; List fwRules = new ArrayList(); //if related firewall rule is created for the first vpn port, it would be created for the 2 other ports as well, so need to cleanup the backend if (_rulesDao.findByRelatedId(vpnFwRules.get(0).getId()) != null) { applyFirewall = true; } - + if (applyFirewall) { txn.start(); - + for (FirewallRule vpnFwRule : vpnFwRules) { //don't apply on the backend yet; send all 3 rules in a banch _firewallMgr.revokeRelatedFirewallRule(vpnFwRule.getId(), false); fwRules.add(_rulesDao.findByRelatedId(vpnFwRule.getId())); } - + s_logger.debug("Marked " + fwRules.size() + " firewall rules as Revoked as a part of disable remote access vpn"); - + txn.commit(); - + //now apply vpn rules on the backend s_logger.debug("Reapplying firewall rules for ip id=" + ipId + " as a part of disable remote access vpn"); success = _firewallMgr.applyFirewallRules(ipId, caller); } - + if (success) { try { txn.start(); @@ -274,11 +277,11 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag // Stop billing of VPN users when VPN is removed. VPN_User_ADD events will be generated when VPN is created again List vpnUsers = _vpnUsersDao.listByAccount(vpn.getAccountId()); for(VpnUserVO user : vpnUsers){ - // VPN_USER_REMOVE event is already generated for users in Revoke state - if(user.getState() != VpnUser.State.Revoke){ - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VPN_USER_REMOVE, user.getAccountId(), 0, user.getId(), user.getUsername()); - _usageEventDao.persist(usageEvent); - } + // VPN_USER_REMOVE event is already generated for users in Revoke state + if(user.getState() != VpnUser.State.Revoke){ + UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VPN_USER_REMOVE, user.getAccountId(), 0, user.getId(), user.getUsername()); + _usageEventDao.persist(usageEvent); + } } if (vpnFwRules != null) { for (FirewallRule vpnFwRule : vpnFwRules) { @@ -303,30 +306,30 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag if (!username.matches("^[a-zA-Z0-9][a-zA-Z0-9@._-]{2,63}$")) { throw new InvalidParameterValueException( - "Username has to be begin with an alphabet have 3-64 characters including alphabets, numbers and the set '@.-_'"); + "Username has to be begin with an alphabet have 3-64 characters including alphabets, numbers and the set '@.-_'", null); } if (!password.matches("^[a-zA-Z0-9][a-zA-Z0-9@#+=._-]{2,31}$")) { - throw new InvalidParameterValueException("Password has to be 3-32 characters including alphabets, numbers and the set '@#+=.-_'"); + throw new InvalidParameterValueException("Password has to be 3-32 characters including alphabets, numbers and the set '@#+=.-_'", null); } Transaction txn = Transaction.currentTxn(); txn.start(); Account owner = _accountDao.lockRow(vpnOwnerId, true); if (owner == null) { - throw new InvalidParameterValueException("Unable to add vpn user: Another operation active"); + throw new InvalidParameterValueException("Unable to add vpn user: Another operation active", null); } _accountMgr.checkAccess(caller, null, true, owner); - + //don't allow duplicated user names for the same account VpnUserVO vpnUser = _vpnUsersDao.findByAccountAndUsername(owner.getId(), username); if (vpnUser != null) { - throw new InvalidParameterValueException("VPN User with name " + username + " is already added for account " + owner); + throw new InvalidParameterValueException("VPN User with name " + username + " is already added for account " + owner, null); } long userCount = _vpnUsersDao.getVpnUserCount(owner.getId()); if (userCount >= _userLimit) { throw new AccountLimitException("Cannot add more than " + _userLimit + " remote access vpn users"); } - + VpnUser user = _vpnUsersDao.persist(new VpnUserVO(vpnOwnerId, owner.getDomainId(), username, password)); UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VPN_USER_ADD, user.getAccountId(), 0, user.getId(), user.getUsername()); _usageEventDao.persist(usageEvent); @@ -340,7 +343,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag VpnUserVO user = _vpnUsersDao.findByAccountAndUsername(vpnOwnerId, username); if (user == null) { - throw new InvalidParameterValueException("Could not find vpn user " + username); + throw new InvalidParameterValueException("Could not find vpn user " + username, null); } _accountMgr.checkAccess(caller, null, true, user); Transaction txn = Transaction.currentTxn(); @@ -367,12 +370,12 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag RemoteAccessVpnVO vpn = _remoteAccessVpnDao.findById(vpnId); if (vpn == null) { - throw new InvalidParameterValueException("Unable to find your vpn: " + vpnId); + throw new InvalidParameterValueException("Unable to find your vpn by id", null); } _accountMgr.checkAccess(caller, null, true, vpn); - - + + Network network = _networkMgr.getNetwork(vpn.getNetworkId()); @@ -383,7 +386,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag if (openFirewall) { firewallOpened = _firewallMgr.applyFirewallRules(vpn.getServerAddressId(), caller); } - + if (firewallOpened) { for (RemoteAccessVPNServiceProvider element : elements) { if (element.startVpn(network, vpn)) { @@ -392,7 +395,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag } } } - + return vpn; } finally { if (started) { @@ -400,14 +403,14 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag txn.start(); vpn.setState(RemoteAccessVpn.State.Running); _remoteAccessVpnDao.update(vpn.getServerAddressId(), vpn); - + // Start billing of existing VPN users in ADD and Active state List vpnUsers = _vpnUsersDao.listByAccount(vpn.getAccountId()); for(VpnUserVO user : vpnUsers){ - if(user.getState() != VpnUser.State.Revoke){ - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VPN_USER_ADD, user.getAccountId(), 0, user.getId(), user.getUsername()); - _usageEventDao.persist(usageEvent); - } + if(user.getState() != VpnUser.State.Revoke){ + UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VPN_USER_ADD, user.getAccountId(), 0, user.getId(), user.getUsername()); + _usageEventDao.persist(usageEvent); + } } txn.commit(); } @@ -425,7 +428,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag List vpns = _remoteAccessVpnDao.findByAccount(vpnOwnerId); List users = _vpnUsersDao.listByAccount(vpnOwnerId); - + //If user is in Active state, we still have to resend them therefore their status has to be Add for (VpnUserVO user : users) { if (user.getState() == State.Active) { @@ -433,7 +436,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag _vpnUsersDao.update(user.getId(), user); } } - + List elements = _networkMgr.getRemoteAccessVpnElements(); boolean success = true; @@ -461,7 +464,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag } catch (ResourceUnavailableException e) { s_logger.warn("Unable to apply vpn users ", e); success= false; - + for (int i = 0; i < finals.length; i++) { finals[i] = false; } @@ -479,7 +482,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag _vpnUsersDao.remove(user.getId()); } } else { - if (user.getState() == State.Add) { + if (user.getState() == State.Add) { Transaction txn = Transaction.currentTxn(); txn.start(); _vpnUsersDao.remove(user.getId()); @@ -498,7 +501,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag public List searchForVpnUsers(ListVpnUsersCmd cmd) { String username = cmd.getUsername(); Long id = cmd.getId(); - + Account caller = UserContext.current().getCaller(); List permittedAccounts = new ArrayList(); @@ -511,14 +514,14 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag SearchBuilder sb = _vpnUsersDao.createSearchBuilder(); _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("username", sb.entity().getUsername(), SearchCriteria.Op.EQ); sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ); SearchCriteria sc = sb.create(); _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - + //list only active users sc.setParameters("state", State.Active); @@ -539,40 +542,40 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag Account caller = UserContext.current().getCaller(); Long ipAddressId = cmd.getPublicIpId(); List permittedAccounts = new ArrayList(); - + if (ipAddressId != null) { PublicIpAddress publicIp = _networkMgr.getPublicIpAddress(ipAddressId); if (publicIp == null) { - throw new InvalidParameterValueException("Unable to list remote access vpns, IP address " + ipAddressId + " not found."); + throw new InvalidParameterValueException("Unable to list remote access vpns, IP address " + ipAddressId + " not found.", null); } else { Long ipAddrAcctId = publicIp.getAccountId(); if (ipAddrAcctId == null) { throw new InvalidParameterValueException("Unable to list remote access vpns, IP address " + ipAddressId - + " is not associated with an account."); + + " is not associated with an account.", null); } } _accountMgr.checkAccess(caller, null, true, publicIp); } - + Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); Long domainId = domainIdRecursiveListProject.first(); Boolean isRecursive = domainIdRecursiveListProject.second(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - + Filter filter = new Filter(RemoteAccessVpnVO.class, "serverAddressId", false, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder sb = _remoteAccessVpnDao.createSearchBuilder(); _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - + sb.and("serverAddressId", sb.entity().getServerAddressId(), Op.EQ); sb.and("state", sb.entity().getState(), Op.EQ); - + SearchCriteria sc = sb.create(); _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); sc.setParameters("state", RemoteAccessVpn.State.Running); - + if (ipAddressId != null) { sc.setParameters("serverAddressId", ipAddressId); } @@ -620,12 +623,12 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag public String getName() { return _name; } - + @Override public List listRemoteAccessVpns(long networkId) { return _remoteAccessVpnDao.listByNetworkId(networkId); } - + @Override public RemoteAccessVpn getRemoteAccessVpn(long vpnId) { return _remoteAccessVpnDao.findById(vpnId); diff --git a/server/src/com/cloud/network/vpn/Site2SiteVpnManager.java b/server/src/com/cloud/network/vpn/Site2SiteVpnManager.java index a44c3615ad4..567b76549df 100644 --- a/server/src/com/cloud/network/vpn/Site2SiteVpnManager.java +++ b/server/src/com/cloud/network/vpn/Site2SiteVpnManager.java @@ -1,7 +1,13 @@ package com.cloud.network.vpn; +import java.util.List; + +import com.cloud.network.Site2SiteVpnConnectionVO; +import com.cloud.vm.DomainRouterVO; + public interface Site2SiteVpnManager extends Site2SiteVpnService { boolean cleanupVpnConnectionByVpc(long vpcId); boolean cleanupVpnGatewayByVpc(long vpcId); void markDisconnectVpnConnByVpc(long vpcId); + List getConnectionsForRouter(DomainRouterVO router); } diff --git a/server/src/com/cloud/network/vpn/Site2SiteVpnManagerImpl.java b/server/src/com/cloud/network/vpn/Site2SiteVpnManagerImpl.java index af2e3756eef..9121f14d1f3 100644 --- a/server/src/com/cloud/network/vpn/Site2SiteVpnManagerImpl.java +++ b/server/src/com/cloud/network/vpn/Site2SiteVpnManagerImpl.java @@ -9,6 +9,7 @@ import javax.naming.ConfigurationException; import org.apache.log4j.Logger; +import com.cloud.api.BaseListProjectAndAccountResourcesCmd; import com.cloud.api.commands.CreateVpnConnectionCmd; import com.cloud.api.commands.CreateVpnCustomerGatewayCmd; import com.cloud.api.commands.CreateVpnGatewayCmd; @@ -44,14 +45,23 @@ import com.cloud.network.element.Site2SiteVpnServiceProvider; import com.cloud.network.vpc.VpcManager; import com.cloud.network.vpc.VpcVO; import com.cloud.network.vpc.Dao.VpcDao; +import com.cloud.projects.Project.ListProjectResourcesCriteria; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.UserContext; import com.cloud.user.dao.AccountDao; +import com.cloud.utils.IdentityProxy; +import com.cloud.utils.Ternary; import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; +import com.cloud.utils.db.Filter; +import com.cloud.utils.db.GenericDao; +import com.cloud.utils.db.JoinBuilder; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; +import com.cloud.vm.DomainRouterVO; @Local(value = { Site2SiteVpnManager.class, Site2SiteVpnService.class } ) public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { @@ -66,9 +76,9 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { @Inject AccountDao _accountDao; @Inject VpcManager _vpcMgr; @Inject AccountManager _accountMgr; - + String _name; - + @Override public boolean configure(String name, Map params) throws ConfigurationException { _name = name; @@ -99,14 +109,16 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { //Verify that caller can perform actions in behalf of vpc owner _accountMgr.checkAccess(caller, null, false, owner); - Long vpcId = cmd.getVpcId(); + Long vpcId = cmd.getVpcId(); VpcVO vpc = _vpcDao.findById(vpcId); if (vpc == null) { - throw new InvalidParameterValueException("Invalid VPC " + vpcId + " for site to site vpn gateway creation!"); + throw new InvalidParameterValueException("Invalid VPC " + vpcId + " for site to site vpn gateway creation!", null); } Site2SiteVpnGatewayVO gws = _vpnGatewayDao.findByVpcId(vpcId); if (gws != null) { - throw new InvalidParameterValueException("The VPN gateway of VPC " + vpcId + " already existed!"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(vpc, vpcId, "vpcId")); + throw new InvalidParameterValueException("The VPN gateway of VPC with specified vpcId already exists!", idList); } Long accountId = cmd.getEntityOwnerId(); Long domainId = cmd.getDomainId(); @@ -118,7 +130,7 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { if (ips.size() != 1) { throw new CloudRuntimeException("Cannot found source nat ip of vpc " + vpcId); } - + Site2SiteVpnGatewayVO gw = new Site2SiteVpnGatewayVO(accountId, domainId, ips.get(0).getId(), vpcId); _vpnGatewayDao.persist(gw); return gw; @@ -136,23 +148,23 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { String name = cmd.getName(); String gatewayIp = cmd.getGatewayIp(); if (!NetUtils.isValidIp(gatewayIp)) { - throw new InvalidParameterValueException("The customer gateway ip " + gatewayIp + " is invalid!"); + throw new InvalidParameterValueException("The customer gateway ip " + gatewayIp + " is invalid!", null); } if (name == null) { name = "VPN-" + gatewayIp; } String guestCidrList = cmd.getGuestCidrList(); if (!NetUtils.validateGuestCidrList(guestCidrList)) { - throw new InvalidParameterValueException("The customer gateway guest cidr list " + guestCidrList + " is invalid guest cidr!"); + throw new InvalidParameterValueException("The customer gateway guest cidr list " + guestCidrList + " is invalid guest cidr!", null); } String ipsecPsk = cmd.getIpsecPsk(); String ikePolicy = cmd.getIkePolicy(); String espPolicy = cmd.getEspPolicy(); if (!NetUtils.isValidS2SVpnPolicy(ikePolicy)) { - throw new InvalidParameterValueException("The customer gateway IKE policy " + ikePolicy + " is invalid!"); + throw new InvalidParameterValueException("The customer gateway IKE policy " + ikePolicy + " is invalid!", null); } if (!NetUtils.isValidS2SVpnPolicy(espPolicy)) { - throw new InvalidParameterValueException("The customer gateway ESP policy " + espPolicy + " is invalid!"); + throw new InvalidParameterValueException("The customer gateway ESP policy " + espPolicy + " is invalid!", null); } Long lifetime = cmd.getLifetime(); if (lifetime == null) { @@ -160,13 +172,13 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { lifetime = (long) 86400; } if (lifetime > 86400) { - throw new InvalidParameterValueException("The lifetime " + lifetime + " of vpn connection is invalid!"); + throw new InvalidParameterValueException("The lifetime " + lifetime + " of vpn connection is invalid!", null); } if (_customerGatewayDao.findByGatewayIp(gatewayIp) != null) { - throw new InvalidParameterValueException("The customer gateway with ip " + gatewayIp + " already existed!"); + throw new InvalidParameterValueException("The customer gateway with ip " + gatewayIp + " already existed!", null); } if (_customerGatewayDao.findByName(name) != null) { - throw new InvalidParameterValueException("The customer gateway with name " + name + " already existed!"); + throw new InvalidParameterValueException("The customer gateway with name " + name + " already existed!", null); } Long accountId = cmd.getEntityOwnerId(); Long domainId = cmd.getDomainId(); @@ -191,20 +203,23 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { Long customerGatewayId = cmd.getCustomerGatewayId(); Site2SiteCustomerGateway customerGateway = _customerGatewayDao.findById(customerGatewayId); if (customerGateway == null) { - throw new InvalidParameterValueException("Unable to found specified Site to Site VPN customer gateway " + customerGatewayId + " !"); + throw new InvalidParameterValueException("Unable to find specified Site to Site VPN customer gateway by id!", null); } _accountMgr.checkAccess(caller, null, false, customerGateway); - + Long vpnGatewayId = cmd.getVpnGatewayId(); Site2SiteVpnGateway vpnGateway = _vpnGatewayDao.findById(vpnGatewayId); if (vpnGateway == null) { - throw new InvalidParameterValueException("Unable to found specified Site to Site VPN gateway " + vpnGatewayId + " !"); + throw new InvalidParameterValueException("Unable to find specified Site to Site VPN gateway by id", null); } _accountMgr.checkAccess(caller, null, false, vpnGateway); - + if (_vpnConnectionDao.findByVpnGatewayIdAndCustomerGatewayId(vpnGatewayId, customerGatewayId) != null) { - throw new InvalidParameterValueException("The vpn connection with customer gateway id " + customerGatewayId + " or vpn gateway id " - + vpnGatewayId + " already existed!"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(vpnGateway, vpnGatewayId, "vpnGatewayId")); + idList.add(new IdentityProxy(customerGateway, customerGatewayId, "customerGatewayId")); + throw new InvalidParameterValueException("The vpn connection with specified customer gateway id or vpn gateway id " + + " already exists!", idList); } Long accountId = cmd.getEntityOwnerId(); Long domainId = cmd.getDomainId(); @@ -221,7 +236,9 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { public Site2SiteVpnConnection startVpnConnection(long id) throws ResourceUnavailableException { Site2SiteVpnConnectionVO conn = _vpnConnectionDao.findById(id); if (conn.getState() != State.Pending && conn.getState() != State.Disconnected) { - throw new InvalidParameterValueException("Site to site VPN connection " + id + " not in correct state(pending or disconnected) to process!"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(conn, id, "connectionId")); + throw new InvalidParameterValueException("Site to site VPN connection with specified connectionId not in correct state(pending or disconnected) to process!", idList); } conn.setState(State.Pending); @@ -258,13 +275,15 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { Long id = cmd.getId(); Site2SiteCustomerGateway customerGateway = _customerGatewayDao.findById(id); if (customerGateway == null) { - throw new InvalidParameterValueException("Fail to find customer gateway with " + id + " !"); + throw new InvalidParameterValueException("Fail to find customer gateway by id", null); } _accountMgr.checkAccess(caller, null, false, customerGateway); - + List vpnConnections = _vpnConnectionDao.listByCustomerGatewayId(id); if (vpnConnections != null && vpnConnections.size() != 0) { - throw new InvalidParameterValueException("Unable to delete VPN customer gateway " + id + " because there is still related VPN connections!"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(customerGateway, id, "customerGatewayId")); + throw new InvalidParameterValueException("Unable to delete VPN customer gateway with specified id because there is still related VPN connections!", idList); } _customerGatewayDao.remove(id); return true; @@ -273,11 +292,13 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { protected void doDeleteVpnGateway(Site2SiteVpnGateway gw) { List conns = _vpnConnectionDao.listByVpnGatewayId(gw.getId()); if (conns != null && conns.size() != 0) { - throw new InvalidParameterValueException("Unable to delete VPN gateway " + gw.getId() + " because there is still related VPN connections!"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(gw, gw.getId(), "vpnGatewayId")); + throw new InvalidParameterValueException("Unable to delete VPN gateway with specified id because there is still related VPN connections!", idList); } _vpnGatewayDao.remove(gw.getId()); } - + @Override @ActionEvent(eventType = EventTypes.EVENT_S2S_VPN_GATEWAY_DELETE, eventDescription = "deleting s2s vpn gateway", create=true) public boolean deleteVpnGateway(DeleteVpnGatewayCmd cmd) { @@ -287,9 +308,9 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { Long id = cmd.getId(); Site2SiteVpnGateway vpnGateway = _vpnGatewayDao.findById(id); if (vpnGateway == null) { - throw new InvalidParameterValueException("Fail to find vpn gateway with " + id + " !"); + throw new InvalidParameterValueException("Fail to find vpn gateway by id", null); } - + _accountMgr.checkAccess(caller, null, false, vpnGateway); doDeleteVpnGateway(vpnGateway); @@ -305,7 +326,7 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { Long id = cmd.getId(); Site2SiteCustomerGatewayVO gw = _customerGatewayDao.findById(id); if (gw == null) { - throw new InvalidParameterValueException("Find to find customer gateway with id " + id); + throw new InvalidParameterValueException("Find to find customer gateway by id", null); } _accountMgr.checkAccess(caller, null, false, gw); @@ -313,26 +334,28 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { if (conns != null) { for (Site2SiteVpnConnection conn : conns) { if (conn.getState() != State.Disconnected || conn.getState() != State.Error) { - throw new InvalidParameterValueException("Unable to update customer gateway because there is active VPN connection " + conn.getId()); + List idList = new ArrayList(); + idList.add(new IdentityProxy(conn, conn.getId(), "vpnConnectionId")); + throw new InvalidParameterValueException("Unable to update customer gateway because there is an active VPN connection with specified vpn connection id", idList); } } } String gatewayIp = cmd.getGatewayIp(); if (!NetUtils.isValidIp(gatewayIp)) { - throw new InvalidParameterValueException("The customer gateway ip " + gatewayIp + " is invalid!"); + throw new InvalidParameterValueException("The customer gateway ip " + gatewayIp + " is invalid!", null); } String guestCidrList = cmd.getGuestCidrList(); if (!NetUtils.validateGuestCidrList(guestCidrList)) { - throw new InvalidParameterValueException("The customer gateway guest cidr list " + guestCidrList + " contains invalid guest cidr!"); + throw new InvalidParameterValueException("The customer gateway guest cidr list " + guestCidrList + " contains invalid guest cidr!", null); } String ipsecPsk = cmd.getIpsecPsk(); String ikePolicy = cmd.getIkePolicy(); String espPolicy = cmd.getEspPolicy(); if (!NetUtils.isValidS2SVpnPolicy(ikePolicy)) { - throw new InvalidParameterValueException("The customer gateway IKE policy" + ikePolicy + " is invalid!"); + throw new InvalidParameterValueException("The customer gateway IKE policy" + ikePolicy + " is invalid!", null); } if (!NetUtils.isValidS2SVpnPolicy(espPolicy)) { - throw new InvalidParameterValueException("The customer gateway ESP policy" + espPolicy + " is invalid!"); + throw new InvalidParameterValueException("The customer gateway ESP policy" + espPolicy + " is invalid!", null); } Long lifetime = cmd.getLifetime(); if (lifetime == null) { @@ -340,7 +363,7 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { lifetime = (long) 86400; } if (lifetime > 86400) { - throw new InvalidParameterValueException("The lifetime " + lifetime + " of vpn connection is invalid!"); + throw new InvalidParameterValueException("The lifetime " + lifetime + " of vpn connection is invalid!", null); } gw.setGatewayIp(gatewayIp); gw.setGuestCidrList(guestCidrList); @@ -361,9 +384,9 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { Long id = cmd.getId(); Site2SiteVpnConnectionVO conn = _vpnConnectionDao.findById(id); if (conn == null) { - throw new InvalidParameterValueException("Fail to find site to site VPN connection " + id + " to delete!"); + throw new InvalidParameterValueException("Fail to find site to site VPN connection to delete!", null); } - + _accountMgr.checkAccess(caller, null, false, conn); if (conn.getState() == State.Connected) { @@ -376,7 +399,9 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { private void stopVpnConnection(Long id) throws ResourceUnavailableException { Site2SiteVpnConnectionVO conn = _vpnConnectionDao.findById(id); if (conn.getState() != State.Connected && conn.getState() != State.Error) { - throw new InvalidParameterValueException("Site to site VPN connection " + id + " not in correct state(connected) to process disconnect!"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(conn, id, "vpnConnectionId")); + throw new InvalidParameterValueException("Site to site VPN connection with specified id is not in correct state(connected) to process disconnect!", idList); } List elements = _networkMgr.getSite2SiteVpnElements(); @@ -403,12 +428,14 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { Long id = cmd.getId(); Site2SiteVpnConnectionVO conn = _vpnConnectionDao.findById(id); if (conn == null) { - throw new InvalidParameterValueException("Fail to find site to site VPN connection " + id + " to reset!"); + throw new InvalidParameterValueException("Fail to find site to site VPN connection to reset!", null); } _accountMgr.checkAccess(caller, null, false, conn); if (conn.getState() == State.Pending) { - throw new InvalidParameterValueException("VPN connection " + id + " cannot be reseted when state is Pending!"); + List idList = new ArrayList(); + idList.add(new IdentityProxy(conn, id, "vpnConnectionId")); + throw new InvalidParameterValueException("VPN connection with specified id cannot be reseted when state is Pending!", idList); } if (conn.getState() == State.Connected || conn.getState() == State.Error) { stopVpnConnection(id); @@ -421,12 +448,38 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { @Override public List searchForCustomerGateways(ListVpnCustomerGatewaysCmd cmd) { Long id = cmd.getId(); - List results = new ArrayList(); + Long domainId = cmd.getDomainId(); + boolean isRecursive = cmd.isRecursive(); + String accountName = cmd.getAccountName(); + boolean listAll = cmd.listAll(); + long startIndex = cmd.getStartIndex(); + long pageSizeVal = cmd.getPageSizeVal(); + + Account caller = UserContext.current().getCaller(); + List permittedAccounts = new ArrayList(); + + Ternary domainIdRecursiveListProject = new Ternary(domainId, isRecursive, null); + _accountMgr.buildACLSearchParameters(caller, id, accountName, null, permittedAccounts, domainIdRecursiveListProject, listAll, false); + domainId = domainIdRecursiveListProject.first(); + isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + Filter searchFilter = new Filter(Site2SiteCustomerGatewayVO.class, "id", false, startIndex, pageSizeVal); + + SearchBuilder sb = _customerGatewayDao.createSearchBuilder(); + _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + + SearchCriteria sc = sb.create(); + _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + if (id != null) { - results.add(_customerGatewayDao.findById(cmd.getId())); - } else { - results.addAll(_customerGatewayDao.listAll()); + sc.addAnd("id", SearchCriteria.Op.EQ, id); } + + List results = new ArrayList(); + results.addAll(_customerGatewayDao.search(sc, searchFilter)); return results; } @@ -435,14 +488,43 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { Long id = cmd.getId(); Long vpcId = cmd.getVpcId(); - List results = new ArrayList(); + Long domainId = cmd.getDomainId(); + boolean isRecursive = cmd.isRecursive(); + String accountName = cmd.getAccountName(); + boolean listAll = cmd.listAll(); + long startIndex = cmd.getStartIndex(); + long pageSizeVal = cmd.getPageSizeVal(); + + Account caller = UserContext.current().getCaller(); + List permittedAccounts = new ArrayList(); + + Ternary domainIdRecursiveListProject = new Ternary(domainId, isRecursive, null); + _accountMgr.buildACLSearchParameters(caller, id, accountName, null, permittedAccounts, domainIdRecursiveListProject, listAll, false); + domainId = domainIdRecursiveListProject.first(); + isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + Filter searchFilter = new Filter(Site2SiteVpnGatewayVO.class, "id", false, startIndex, pageSizeVal); + + SearchBuilder sb = _vpnGatewayDao.createSearchBuilder(); + _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ); + + SearchCriteria sc = sb.create(); + _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + if (id != null) { - results.add(_vpnGatewayDao.findById(cmd.getId())); - } else if (vpcId != null) { - results.add(_vpnGatewayDao.findByVpcId(vpcId)); - } else { //id == null && vpcId == null - results.addAll(_vpnGatewayDao.listAll()); + sc.addAnd("id", SearchCriteria.Op.EQ, id); } + + if (vpcId != null) { + sc.addAnd("vpcId", SearchCriteria.Op.EQ, vpcId); + } + + List results = new ArrayList(); + results.addAll(_vpnGatewayDao.search(sc, searchFilter)); return results; } @@ -451,14 +533,48 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { Long id = cmd.getId(); Long vpcId = cmd.getVpcId(); - List results = new ArrayList(); - if (id != null) { - results.add(_vpnConnectionDao.findById(cmd.getId())); - } else if (vpcId != null) { - results.addAll(_vpnConnectionDao.listByVpcId(vpcId)); - } else { //id == null && vpcId == null - results.addAll(_vpnConnectionDao.listAll()); + Long domainId = cmd.getDomainId(); + boolean isRecursive = cmd.isRecursive(); + String accountName = cmd.getAccountName(); + boolean listAll = cmd.listAll(); + long startIndex = cmd.getStartIndex(); + long pageSizeVal = cmd.getPageSizeVal(); + + Account caller = UserContext.current().getCaller(); + List permittedAccounts = new ArrayList(); + + Ternary domainIdRecursiveListProject = new Ternary(domainId, isRecursive, null); + _accountMgr.buildACLSearchParameters(caller, id, accountName, null, permittedAccounts, domainIdRecursiveListProject, listAll, false); + domainId = domainIdRecursiveListProject.first(); + isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + Filter searchFilter = new Filter(Site2SiteVpnConnectionVO.class, "id", false, startIndex, pageSizeVal); + + SearchBuilder sb = _vpnConnectionDao.createSearchBuilder(); + _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + + if (vpcId != null) { + SearchBuilder gwSearch = _vpnGatewayDao.createSearchBuilder(); + gwSearch.and("vpcId", gwSearch.entity().getVpcId(), SearchCriteria.Op.EQ); + sb.join("gwSearch", gwSearch, sb.entity().getVpnGatewayId(), gwSearch.entity().getId(), JoinBuilder.JoinType.INNER); } + + SearchCriteria sc = sb.create(); + _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + if (id != null) { + sc.addAnd("id", SearchCriteria.Op.EQ, id); + } + + if (vpcId != null) { + sc.setJoinParameters("gwSearch", "vpcId", vpcId); + } + + List results = new ArrayList(); + results.addAll(_vpnConnectionDao.search(sc, searchFilter)); return results; } @@ -480,7 +596,7 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { doDeleteVpnGateway(gw); return true; } - + @Override public void markDisconnectVpnConnByVpc(long vpcId) { List conns = _vpnConnectionDao.listByVpcId(vpcId); @@ -494,4 +610,16 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { } } } + + @Override + public List getConnectionsForRouter(DomainRouterVO router) { + List conns = new ArrayList(); + // One router for one VPC + Long vpcId = router.getVpcId(); + if (router.getVpcId() == null) { + return conns; + } + conns.addAll(_vpnConnectionDao.listByVpcId(vpcId)); + return conns; + } } diff --git a/server/src/com/cloud/projects/ProjectManagerImpl.java b/server/src/com/cloud/projects/ProjectManagerImpl.java index 52d710af76b..57c33e184fa 100755 --- a/server/src/com/cloud/projects/ProjectManagerImpl.java +++ b/server/src/com/cloud/projects/ProjectManagerImpl.java @@ -67,6 +67,7 @@ import com.cloud.user.ResourceLimitService; import com.cloud.user.UserContext; import com.cloud.user.dao.AccountDao; import com.cloud.utils.DateUtil; +import com.cloud.utils.IdentityProxy; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Ternary; import com.cloud.utils.component.Inject; @@ -89,7 +90,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ public static final Logger s_logger = Logger.getLogger(ProjectManagerImpl.class); private String _name; private EmailInvite _emailInvite; - + @Inject private DomainDao _domainDao; @Inject @@ -112,24 +113,24 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ private ProjectInvitationDao _projectInvitationDao; @Inject protected ResourceTagDao _resourceTagDao; - + protected boolean _invitationRequired = false; protected long _invitationTimeOut = 86400000; protected boolean _allowUserToCreateProject = true; protected ScheduledExecutorService _executor; protected int _projectCleanupExpInvInterval = 60; //Interval defining how often project invitation cleanup thread is running - - + + @Override public boolean configure(final String name, final Map params) throws ConfigurationException { _name = name; - + Map configs = _configDao.getConfiguration(params); _invitationRequired = Boolean.valueOf(configs.get(Config.ProjectInviteRequired.key())); _invitationTimeOut = Long.valueOf(configs.get(Config.ProjectInvitationExpirationTime.key()))*1000; _allowUserToCreateProject = Boolean.valueOf(configs.get(Config.AllowUserToCreateProject.key())); - - + + // set up the email system for project invitations String smtpHost = configs.get("project.smtp.host"); @@ -147,13 +148,13 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ _emailInvite = new EmailInvite(smtpHost, smtpPort, useAuth, smtpUsername, smtpPassword, emailSender, smtpDebug); _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Project-ExpireInvitations")); - + return true; } - + @Override public boolean start() { - _executor.scheduleWithFixedDelay(new ExpiredInvitationsCleanup(), _projectCleanupExpInvInterval, _projectCleanupExpInvInterval, TimeUnit.SECONDS); + _executor.scheduleWithFixedDelay(new ExpiredInvitationsCleanup(), _projectCleanupExpInvInterval, _projectCleanupExpInvInterval, TimeUnit.SECONDS); return true; } @@ -166,98 +167,100 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ public String getName() { return _name; } - + @Override @ActionEvent(eventType = EventTypes.EVENT_PROJECT_CREATE, eventDescription = "creating project", create=true) @DB public Project createProject(String name, String displayText, String accountName, Long domainId) throws ResourceAllocationException{ Account caller = UserContext.current().getCaller(); Account owner = caller; - + //check if the user authorized to create the project if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL && !_allowUserToCreateProject) { - throw new PermissionDeniedException("Regular user is not permitted to create a project"); + throw new PermissionDeniedException("Regular user is not permitted to create a project"); } - + //Verify request parameters if ((accountName != null && domainId == null) || (domainId != null && accountName == null)) { - throw new InvalidParameterValueException("Account name and domain id must be specified together"); + throw new InvalidParameterValueException("Account name and domain id must be specified together", null); } - + if (accountName != null) { owner = _accountMgr.finalizeOwner(caller, accountName, domainId, null); } - + //don't allow 2 projects with the same name inside the same domain if (_projectDao.findByNameAndDomain(name, owner.getDomainId()) != null) { - throw new InvalidParameterValueException("Project with name " + name + " already exists in domain id=" + owner.getDomainId()); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", owner.getDomainId(), "domainId")); + throw new InvalidParameterValueException("Project with name " + name + " already exists in domain with specified domainId", idList); } - + //do resource limit check _resourceLimitMgr.checkResourceLimit(owner, ResourceType.project); - + Transaction txn = Transaction.currentTxn(); txn.start(); - + //Create an account associated with the project StringBuilder acctNm = new StringBuilder("PrjAcct-"); acctNm.append(name).append("-").append(owner.getDomainId()); - + Account projectAccount = _accountMgr.createAccount(acctNm.toString(), Account.ACCOUNT_TYPE_PROJECT, domainId, null, null); - + Project project = _projectDao.persist(new ProjectVO(name, displayText, owner.getDomainId(), projectAccount.getId())); - + //assign owner to the project assignAccountToProject(project, owner.getId(), ProjectAccount.Role.Admin); - + if (project != null) { UserContext.current().setEventDetails("Project id=" + project.getId()); } - + //Increment resource count _resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.project); - + txn.commit(); - + return project; } - - + + @Override @ActionEvent(eventType = EventTypes.EVENT_PROJECT_CREATE, eventDescription = "creating project", async=true) @DB public Project enableProject(long projectId){ Account caller = UserContext.current().getCaller(); - + ProjectVO project= getProject(projectId); //verify input parameters if (project == null) { - throw new InvalidParameterValueException("Unable to find project by id " + projectId); + throw new InvalidParameterValueException("Unable to find project by id", null); } - + _accountMgr.checkAccess(caller,AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); - + //at this point enabling project doesn't require anything, so just update the state project.setState(State.Active); _projectDao.update(projectId, project); - + return project; } - - + + @Override @ActionEvent(eventType = EventTypes.EVENT_PROJECT_DELETE, eventDescription = "deleting project", async = true) public boolean deleteProject(long projectId) { UserContext ctx = UserContext.current(); - + ProjectVO project= getProject(projectId); //verify input parameters if (project == null) { - throw new InvalidParameterValueException("Unable to find project by id " + projectId); + throw new InvalidParameterValueException("Unable to find project by id", null); } - + _accountMgr.checkAccess(ctx.getCaller(),AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); - + return deleteProject(ctx.getCaller(), ctx.getCallerUserId(), project); } @@ -275,9 +278,9 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ if (projectOwner != null) { _resourceLimitMgr.decrementResourceCount(projectOwner.getId(), ResourceType.project); } - + txn.commit(); - + if (updateResult) { if (!cleanupProject(project, _accountDao.findById(caller.getId()), callerUserId)) { s_logger.warn("Failed to cleanup project's id=" + project.getId() + " resources, not removing the project yet"); @@ -290,31 +293,31 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ return false; } } - + @DB private boolean cleanupProject(Project project, AccountVO caller, Long callerUserId) { boolean result=true; //Delete project's account AccountVO account = _accountDao.findById(project.getProjectAccountId()); s_logger.debug("Deleting projects " + project + " internal account id=" + account.getId() + " as a part of project cleanup..."); - + result = result && _accountMgr.deleteAccount(account, callerUserId, caller); - + if (result) { //Unassign all users from the project - + Transaction txn = Transaction.currentTxn(); txn.start(); - + s_logger.debug("Unassigning all accounts from project " + project + " as a part of project cleanup..."); List projectAccounts = _projectAccountDao.listByProjectId(project.getId()); for (ProjectAccount projectAccount : projectAccounts) { result = result && unassignAccountFromProject(projectAccount.getProjectId(), projectAccount.getAccountId()); } - + s_logger.debug("Removing all invitations for the project " + project + " as a part of project cleanup..."); - _projectInvitationDao.cleanupInvitations(project.getId()); - + _projectInvitationDao.cleanupInvitations(project.getId()); + txn.commit(); if (result) { s_logger.debug("Accounts are unassign successfully from project " + project + " as a part of project cleanup..."); @@ -322,10 +325,10 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } else { s_logger.warn("Failed to cleanup project's internal account"); } - + return result; } - + @Override public boolean unassignAccountFromProject(long projectId, long accountId) { ProjectAccountVO projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, accountId); @@ -333,7 +336,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ s_logger.debug("Account id=" + accountId + " is not assigned to project id=" + projectId + " so no need to unassign"); return true; } - + if ( _projectAccountDao.remove(projectAccount.getId())) { return true; } else { @@ -341,12 +344,12 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ return false; } } - + @Override public ProjectVO getProject (long projectId) { return _projectDao.findById(projectId); } - + @Override public List listProjects(Long id, String name, String displayText, String state, String accountName, Long domainId, String keyword, Long startIndex, Long pageSize, boolean listAll, @@ -354,15 +357,15 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ Account caller = UserContext.current().getCaller(); Long accountId = null; String path = null; - + Filter searchFilter = new Filter(ProjectVO.class, "id", false, startIndex, pageSize); SearchBuilder sb = _projectDao.createSearchBuilder(); - + if (_accountMgr.isAdmin(caller.getType())) { if (domainId != null) { DomainVO domain = _domainDao.findById(domainId); if (domain == null) { - throw new InvalidParameterValueException("Domain id=" + domainId + " doesn't exist in the system"); + throw new InvalidParameterValueException("Couldn't find domain by id", null); } _accountMgr.checkAccess(caller, domain); @@ -370,7 +373,9 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ if (accountName != null) { Account owner = _accountMgr.getActiveAccountByName(accountName, domainId); if (owner == null) { - throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); + List idList = new ArrayList(); + idList.add(new IdentityProxy(domain, domainId, "domainId")); + throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain with specified domainId", idList); } accountId = owner.getId(); } @@ -379,82 +384,82 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ if (accountName != null && !accountName.equals(caller.getAccountName())) { throw new PermissionDeniedException("Can't list account " + accountName + " projects; unauthorized"); } - + if (domainId != null && domainId.equals(caller.getDomainId())) { throw new PermissionDeniedException("Can't list domain id= " + domainId + " projects; unauthorized"); } - + accountId = caller.getId(); } - - if (domainId == null && accountId == null && (caller.getType() == Account.ACCOUNT_TYPE_NORMAL || !listAll)) { - accountId = caller.getId(); - } else if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || (isRecursive && !listAll)) { + + if (domainId == null && accountId == null && (caller.getType() == Account.ACCOUNT_TYPE_NORMAL || !listAll)) { + accountId = caller.getId(); + } else if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || (isRecursive && !listAll)) { DomainVO domain = _domainDao.findById(caller.getDomainId()); path = domain.getPath(); } - + if (path != null) { SearchBuilder domainSearch = _domainDao.createSearchBuilder(); domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); } - + if (accountId != null) { SearchBuilder projectAccountSearch = _projectAccountDao.createSearchBuilder(); projectAccountSearch.and("accountId", projectAccountSearch.entity().getAccountId(), SearchCriteria.Op.EQ); sb.join("projectAccountSearch", projectAccountSearch, sb.entity().getId(), projectAccountSearch.entity().getProjectId(), JoinBuilder.JoinType.INNER); } - + if (tags != null && !tags.isEmpty()) { SearchBuilder tagSearch = _resourceTagDao.createSearchBuilder(); - for (int count=0; count < tags.size(); count++) { - tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ); - tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ); - tagSearch.cp(); - } - tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ); - sb.groupBy(sb.entity().getId()); - sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER); + for (int count=0; count < tags.size(); count++) { + tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ); + tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ); + tagSearch.cp(); + } + tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ); + sb.groupBy(sb.entity().getId()); + sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER); } - + SearchCriteria sc = sb.create(); - + if (id != null) { sc.addAnd("id", Op.EQ, id); } - + if (domainId != null && !isRecursive) { sc.addAnd("domainId", Op.EQ, domainId); } - + if (name != null) { sc.addAnd("name", Op.EQ, name); } - + if (displayText != null) { sc.addAnd("displayText", Op.EQ, displayText); } - + if (accountId != null) { sc.setJoinParameters("projectAccountSearch", "accountId", accountId); } - + if (state != null) { sc.addAnd("state", Op.EQ, state); } - + if (keyword != null) { SearchCriteria ssc = _projectDao.createSearchCriteria(); ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%"); sc.addAnd("name", SearchCriteria.Op.SC, ssc); } - + if (path != null) { sc.setJoinParameters("domainSearch", "path", path); } - + if (tags != null && !tags.isEmpty()) { int count = 0; sc.setJoinParameters("tagSearch", "resourceType", TaggedResourceType.Project.toString()); @@ -464,25 +469,25 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ count++; } } - + return _projectDao.search(sc, searchFilter); } - + @Override public ProjectAccount assignAccountToProject(Project project, long accountId, ProjectAccount.Role accountRole) { return _projectAccountDao.persist(new ProjectAccountVO(project, accountId, accountRole)); } - + @Override @DB public boolean deleteAccountFromProject(long projectId, long accountId) { boolean success = true; Transaction txn = Transaction.currentTxn(); txn.start(); - + //remove account ProjectAccountVO projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, accountId); success = _projectAccountDao.remove(projectAccount.getId()); - + //remove all invitations for account if (success) { s_logger.debug("Removed account " + accountId + " from project " + projectId + " , cleaning up old invitations for account/project..."); @@ -491,31 +496,31 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ success = success && _projectInvitationDao.remove(invite.getId()); } } - + txn.commit(); return success; } - + @Override public Account getProjectOwner(long projectId) { ProjectAccount prAcct = _projectAccountDao.getProjectOwner(projectId); if (prAcct != null) { return _accountMgr.getAccount(prAcct.getAccountId()); } - + return null; } - + @Override public ProjectVO findByProjectAccountId(long projectAccountId) { return _projectDao.findByProjectAccountId(projectAccountId); } - + @Override public Project findByNameAndDomainId(String name, long domainId) { return _projectDao.findByNameAndDomain(name, domainId); } - + @Override public boolean canAccessProjectAccount(Account caller, long accountId) { //ROOT admin always can access the project @@ -526,10 +531,11 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ _accountMgr.checkAccess(caller, _domainDao.findById(owner.getDomainId())); return true; } - + return _projectAccountDao.canAccessProjectAccount(caller.getId(), accountId); } - + + @Override public boolean canModifyProjectAccount(Account caller, long accountId) { //ROOT admin always can access the project if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN) { @@ -541,103 +547,104 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } return _projectAccountDao.canModifyProjectAccount(caller.getId(), accountId); } - + @Override @DB @ActionEvent(eventType = EventTypes.EVENT_PROJECT_UPDATE, eventDescription = "updating project", async=true) public Project updateProject(long projectId, String displayText, String newOwnerName) throws ResourceAllocationException{ Account caller = UserContext.current().getCaller(); - + //check that the project exists ProjectVO project = getProject(projectId); - + if (project == null) { - throw new InvalidParameterValueException("Unable to find the project id=" + projectId); + throw new InvalidParameterValueException("Unable to find project by id", null); } - + //verify permissions _accountMgr.checkAccess(caller,AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); - + Transaction txn = Transaction.currentTxn(); txn.start(); if (displayText != null) { project.setDisplayText(displayText); _projectDao.update(projectId, project); } - + if (newOwnerName != null) { //check that the new owner exists Account futureOwnerAccount = _accountMgr.getActiveAccountByName(newOwnerName, project.getDomainId()); if (futureOwnerAccount == null) { - throw new InvalidParameterValueException("Unable to find account name=" + newOwnerName + " in domain id=" + project.getDomainId()); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", project.getDomainId(), "domainId")); + throw new InvalidParameterValueException("Unable to find account name=" + newOwnerName + + " in domain with specified domainId", idList); } Account currentOwnerAccount = getProjectOwner(projectId); if (currentOwnerAccount.getId() != futureOwnerAccount.getId()) { ProjectAccountVO futureOwner = _projectAccountDao.findByProjectIdAccountId(projectId, futureOwnerAccount.getAccountId()); if (futureOwner == null) { - throw new InvalidParameterValueException("Account " + newOwnerName + " doesn't belong to the project. Add it to the project first and then change the project's ownership"); + throw new InvalidParameterValueException("Account " + newOwnerName + " doesn't belong to the project. Add it to the project first and then change the project's ownership", null); } - + //do resource limit check _resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(futureOwnerAccount.getId()), ResourceType.project); - + //unset the role for the old owner ProjectAccountVO currentOwner = _projectAccountDao.findByProjectIdAccountId(projectId, currentOwnerAccount.getId()); currentOwner.setAccountRole(Role.Regular); _projectAccountDao.update(currentOwner.getId(), currentOwner); _resourceLimitMgr.decrementResourceCount(currentOwnerAccount.getId(), ResourceType.project); - + //set new owner futureOwner.setAccountRole(Role.Admin); _projectAccountDao.update(futureOwner.getId(), futureOwner); _resourceLimitMgr.incrementResourceCount(futureOwnerAccount.getId(), ResourceType.project); - + } else { s_logger.trace("Future owner " + newOwnerName + "is already the owner of the project id=" + projectId); } } - + txn.commit(); - + return _projectDao.findById(projectId); - + } - + @Override @ActionEvent(eventType = EventTypes.EVENT_PROJECT_ACCOUNT_ADD, eventDescription = "adding account to project", async=true) public boolean addAccountToProject(long projectId, String accountName, String email) { Account caller = UserContext.current().getCaller(); - + //check that the project exists Project project = getProject(projectId); - + if (project == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); - ex.addProxyObject(project, projectId, "projectId"); - throw ex; + throw new InvalidParameterValueException("Unable to find project with specified id", null); } - + //User can be added to Active project only if (project.getState() != Project.State.Active) { - InvalidParameterValueException ex = new InvalidParameterValueException("Can't add account to the specified project id in state=" + project.getState() + " as it's no longer active"); - ex.addProxyObject(project, projectId, "projectId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(project, projectId, "projectId")); + throw new InvalidParameterValueException("Can't add account to the specified project id in state=" + project.getState() + " as it's no longer active", idList); } - + //check that account-to-add exists Account account = null; if (accountName != null) { account = _accountMgr.getActiveAccountByName(accountName, project.getDomainId()); if (account == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find account name=" + accountName + " in specified domain id"); - // We don't have a DomainVO object with us, so just pass the tablename "domain" manually. - ex.addProxyObject("domain", project.getDomainId(), "domainId"); - throw ex; + List idList = new ArrayList(); + // We don't have a DomainVO object with us, so just pass the tablename "domain" manually. + idList.add(new IdentityProxy("domain", project.getDomainId(), "domainId")); + throw new InvalidParameterValueException("Unable to find account name=" + accountName + " in specified domain id", idList); } - + //verify permissions - only project owner can assign _accountMgr.checkAccess(caller, AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); - + //Check if the account already added to the project ProjectAccount projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, account.getId()); if (projectAccount != null) { @@ -645,12 +652,12 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ return true; } } - + if (_invitationRequired) { return inviteAccountToProject(project, account, email); } else { if (account == null) { - throw new InvalidParameterValueException("Account information is required for assigning account to the project"); + throw new InvalidParameterValueException("Account information is required for assigning account to the project", null); } if (assignAccountToProject(project, account.getId(), ProjectAccount.Role.Regular) != null) { return true; @@ -660,7 +667,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } } } - + private boolean inviteAccountToProject(Project project, Account account, String email) { if (account != null) { if (createAccountInvitation(project, account.getId()) != null) { @@ -670,135 +677,136 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ return false; } } - + if (email != null) { //generate the token String token = generateToken(10); if (generateTokenBasedInvitation(project, email, token) != null) { return true; } else { - s_logger.warn("Failed to generate invitation for email " + email + " to project id=" + project); - return false; + s_logger.warn("Failed to generate invitation for email " + email + " to project id=" + project); + return false; } } - + return false; } - + @Override @ActionEvent(eventType = EventTypes.EVENT_PROJECT_ACCOUNT_REMOVE, eventDescription = "removing account from project", async=true) public boolean deleteAccountFromProject(long projectId, String accountName) { Account caller = UserContext.current().getCaller(); - + //check that the project exists Project project = getProject(projectId); - + if (project == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); - ex.addProxyObject(project, projectId, "projectId"); - throw ex; + throw new InvalidParameterValueException("Unable to find project by id", null); } - + //check that account-to-remove exists Account account = _accountMgr.getActiveAccountByName(accountName, project.getDomainId()); if (account == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find account name=" + accountName + " in domain id=" + project.getDomainId()); - // Since we don't have a domainVO object, pass the table name manually. - ex.addProxyObject("domain", project.getDomainId(), "domainId"); + List idList = new ArrayList(); + idList.add(new IdentityProxy("domain", project.getDomainId(), "domainId")); + throw new InvalidParameterValueException("Unable to find account name=" + accountName + " in domain with specified domainId", idList); } - + //verify permissions _accountMgr.checkAccess(caller,AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); - + //Check if the account exists in the project ProjectAccount projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, account.getId()); if (projectAccount == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Account " + accountName + " is not assigned to the project with specified id"); - // Use the projectVO object and not the projectAccount object to inject the projectId. - ex.addProxyObject(project, projectId, "projectId"); - throw ex; + List idList = new ArrayList(); + // Use the projectVO object and not the projectAccount object to inject the projectId. + idList.add(new IdentityProxy(project, projectId, "projectId")); + throw new InvalidParameterValueException("Account " + accountName + " is not assigned to the project with specified id", idList); } - + //can't remove the owner of the project if (projectAccount.getAccountRole() == Role.Admin) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to delete account " + accountName + " from the project with specified id as the account is the owner of the project"); - ex.addProxyObject(project, projectId, "projectId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(project, projectId, "projectId")); + throw new InvalidParameterValueException("Unable to delete account " + accountName + " from the project with specified id as the account is the owner of the project", idList); } - + return deleteAccountFromProject(projectId, account.getId()); } - - + + @Override public List listProjectAccounts(long projectId, String accountName, String role, Long startIndex, Long pageSizeVal) { Account caller = UserContext.current().getCaller(); - + //check that the project exists Project project = getProject(projectId); - + if (project == null) { - throw new InvalidParameterValueException("Unable to find the project id=" + projectId); + throw new InvalidParameterValueException("Unable to find project by id", null); } - + //verify permissions - only accounts belonging to the project can list project's account if (!_accountMgr.isAdmin(caller.getType()) && _projectAccountDao.findByProjectIdAccountId(projectId, caller.getAccountId()) == null) { throw new PermissionDeniedException("Account " + caller + " is not authorized to list users of the project id=" + projectId); } - + Filter searchFilter = new Filter(ProjectAccountVO.class, "id", false, startIndex, pageSizeVal); SearchBuilder sb = _projectAccountDao.createSearchBuilder(); sb.and("accountRole", sb.entity().getAccountRole(), Op.EQ); sb.and("projectId", sb.entity().getProjectId(), Op.EQ); - + SearchBuilder accountSearch; if (accountName != null) { accountSearch = _accountDao.createSearchBuilder(); accountSearch.and("accountName", accountSearch.entity().getAccountName(), SearchCriteria.Op.EQ); sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); } - + SearchCriteria sc = sb.create(); - + sc.setParameters("projectId", projectId); - + if (role != null) { sc.setParameters("accountRole", role); } - + if (accountName != null) { sc.setJoinParameters("accountSearch", "accountName", accountName); } - + return _projectAccountDao.search(sc, searchFilter); } - + public ProjectInvitation createAccountInvitation(Project project, Long accountId) { if (activeInviteExists(project, accountId, null)) { - throw new InvalidParameterValueException("There is already a pending invitation for account id=" + accountId + " to the project id=" + project); + List idList = new ArrayList(); + idList.add(new IdentityProxy(project, project.getId(), "projectId")); + idList.add(new IdentityProxy("account", accountId, "accountId")); + throw new InvalidParameterValueException("There is already a pending invitation for specified accountId to the specified projectId", idList); } - + ProjectInvitation invitation= _projectInvitationDao.persist(new ProjectInvitationVO(project.getId(), accountId, project.getDomainId(), null, null)); - + return invitation; } @DB - public boolean activeInviteExists(Project project, Long accountId, String email) { - Transaction txn = Transaction.currentTxn(); - txn.start(); - //verify if the invitation was already generated - ProjectInvitationVO invite = null; - if (accountId != null) { - invite = _projectInvitationDao.findByAccountIdProjectId(accountId, project.getId()); - } else if (email != null) { - invite = _projectInvitationDao.findByEmailAndProjectId(email, project.getId()); - } - + public boolean activeInviteExists(Project project, Long accountId, String email) { + Transaction txn = Transaction.currentTxn(); + txn.start(); + //verify if the invitation was already generated + ProjectInvitationVO invite = null; + if (accountId != null) { + invite = _projectInvitationDao.findByAccountIdProjectId(accountId, project.getId()); + } else if (email != null) { + invite = _projectInvitationDao.findByEmailAndProjectId(email, project.getId()); + } + if (invite != null) { if (invite.getState() == ProjectInvitation.State.Completed || (invite.getState() == ProjectInvitation.State.Pending && _projectInvitationDao.isActive(invite.getId(), _invitationTimeOut))) { - return true; + return true; } else { if (invite.getState() == ProjectInvitation.State.Pending) { expireInvitation(invite); @@ -807,7 +815,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ if (accountId != null) { s_logger.debug("Removing invitation in state " + invite.getState() + " for account id=" + accountId + " to project " + project); } else if (email != null) { - s_logger.debug("Removing invitation in state " + invite.getState() + " for email " + email + " to project " + project); + s_logger.debug("Removing invitation in state " + invite.getState() + " for email " + email + " to project " + project); } _projectInvitationDao.expunge(invite.getId()); @@ -815,14 +823,16 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } txn.commit(); return false; - } - + } + public ProjectInvitation generateTokenBasedInvitation(Project project, String email, String token) { //verify if the invitation was already generated - if (activeInviteExists(project, null, email)) { - throw new InvalidParameterValueException("There is already a pending invitation for email " + email + " to the project id=" + project); - } - + if (activeInviteExists(project, null, email)) { + List idList = new ArrayList(); + idList.add(new IdentityProxy(project, project.getId(), "projectId")); + throw new InvalidParameterValueException("There is already a pending invitation for email " + email + " to the specified projectId", idList); + } + ProjectInvitation projectInvitation = _projectInvitationDao.persist(new ProjectInvitationVO(project.getId(), null, project.getDomainId(), email, token)); try { _emailInvite.sendInvite(token, email, project.getId()); @@ -831,27 +841,27 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ _projectInvitationDao.remove(projectInvitation.getId()); return null; } - + return projectInvitation; } - + private boolean expireInvitation(ProjectInvitationVO invite) { s_logger.debug("Expiring invitation id=" + invite.getId()); invite.setState(ProjectInvitation.State.Expired); return _projectInvitationDao.update(invite.getId(), invite); } - + @Override public List listProjectInvitations(Long id, Long projectId, String accountName, Long domainId, String state, boolean activeOnly, Long startIndex, Long pageSizeVal, boolean isRecursive, boolean listAll) { - Account caller = UserContext.current().getCaller(); + Account caller = UserContext.current().getCaller(); List permittedAccounts = new ArrayList(); - + Ternary domainIdRecursiveListProject = new Ternary(domainId, isRecursive, null); _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, listAll, true); domainId = domainIdRecursiveListProject.first(); isRecursive = domainIdRecursiveListProject.second(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - + Filter searchFilter = new Filter(ProjectInvitationVO.class, "id", true, startIndex, pageSizeVal); SearchBuilder sb = _projectInvitationDao.createSearchBuilder(); _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); @@ -864,61 +874,63 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ SearchCriteria sc = sb.create(); _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - + if (projectId != null){ sc.setParameters("projectId", projectId); } - + if (state != null) { sc.setParameters("state", state); } - + if (id != null) { sc.setParameters("id", id); } - + if (activeOnly) { sc.setParameters("state", ProjectInvitation.State.Pending); sc.setParameters("created", new Date((DateUtil.currentGMTTime().getTime()) - _invitationTimeOut)); } - + return _projectInvitationDao.search(sc, searchFilter); } - + @Override @DB @ActionEvent(eventType = EventTypes.EVENT_PROJECT_INVITATION_UPDATE, eventDescription = "updating project invitation", async=true) public boolean updateInvitation(long projectId, String accountName, String token, boolean accept) { Account caller = UserContext.current().getCaller(); Long accountId = null; boolean result = true; - + //if accountname and token are null, default accountname to caller's account name if (accountName == null && token == null) { accountName = caller.getAccountName(); } - + //check that the project exists Project project = getProject(projectId); - + if (project == null) { - throw new InvalidParameterValueException("Unable to find the project id=" + projectId); + throw new InvalidParameterValueException("Unable to find project by id", null); } - + if (accountName != null) { //check that account-to-remove exists Account account = _accountMgr.getActiveAccountByName(accountName, project.getDomainId()); if (account == null) { - throw new InvalidParameterValueException("Unable to find account name=" + accountName + " in domain id=" + project.getDomainId()); + List idList = new ArrayList(); + idList.add(new IdentityProxy(project, project.getDomainId(), "domainId")); + throw new InvalidParameterValueException("Unable to find account name=" + accountName + " in domain with specified domainId", idList); } - + //verify permissions _accountMgr.checkAccess(caller, null, true, account); - + accountId = account.getId(); } else { accountId = caller.getId(); } - + //check that invitation exists ProjectInvitationVO invite = null; if (token == null) { @@ -926,124 +938,126 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } else { invite = _projectInvitationDao.findPendingByTokenAndProjectId(token, projectId, ProjectInvitation.State.Pending); } - + if (invite != null) { if (!_projectInvitationDao.isActive(invite.getId(), _invitationTimeOut) && accept) { expireInvitation(invite); - throw new InvalidParameterValueException("Invitation is expired for account id=" + accountName + " to the project id=" + projectId); + List idList = new ArrayList(); + idList.add(new IdentityProxy(project, projectId, "projectId")); + throw new InvalidParameterValueException("Invitation is expired for account " + + accountName + " to the project with specified projectId", idList); } else { Transaction txn = Transaction.currentTxn(); txn.start(); - + ProjectInvitation.State newState = accept ? ProjectInvitation.State.Completed : ProjectInvitation.State.Declined; - - //update invitation - s_logger.debug("Marking invitation " + invite + " with state " + newState); - invite.setState(newState); - result = _projectInvitationDao.update(invite.getId(), invite); - - if (result && accept) { - //check if account already exists for the project (was added before invitation got accepted) - ProjectAccount projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, accountId); - if (projectAccount != null) { - s_logger.debug("Account " + accountName + " already added to the project id=" + projectId); - } else { - assignAccountToProject(project, accountId, ProjectAccount.Role.Regular); - } - } else { - s_logger.warn("Failed to update project invitation " + invite + " with state " + newState); - } - - txn.commit(); + + //update invitation + s_logger.debug("Marking invitation " + invite + " with state " + newState); + invite.setState(newState); + result = _projectInvitationDao.update(invite.getId(), invite); + + if (result && accept) { + //check if account already exists for the project (was added before invitation got accepted) + ProjectAccount projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, accountId); + if (projectAccount != null) { + s_logger.debug("Account " + accountName + " already added to the project id=" + projectId); + } else { + assignAccountToProject(project, accountId, ProjectAccount.Role.Regular); + } + } else { + s_logger.warn("Failed to update project invitation " + invite + " with state " + newState); + } + + txn.commit(); } } else { - throw new InvalidParameterValueException("Unable to find invitation for account name=" + accountName + " to the project id=" + projectId); + List idList = new ArrayList(); + idList.add(new IdentityProxy(project, projectId, "projectId")); + throw new InvalidParameterValueException("Unable to find invitation for account name=" + + accountName + " to the project with specified projectId", idList); } - + return result; } - + @Override public List listPermittedProjectAccounts(long accountId) { return _projectAccountDao.listPermittedAccountIds(accountId); } - + @Override @ActionEvent(eventType = EventTypes.EVENT_PROJECT_ACTIVATE, eventDescription = "activating project") @DB public Project activateProject(long projectId) { Account caller = UserContext.current().getCaller(); - + //check that the project exists ProjectVO project = getProject(projectId); - + if (project == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); - ex.addProxyObject(project, projectId, "projectId"); - throw ex; + throw new InvalidParameterValueException("Could not find project by id", null); } - + //verify permissions _accountMgr.checkAccess(caller,AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); - + //allow project activation only when it's in Suspended state Project.State currentState = project.getState(); - + if (currentState == State.Active) { s_logger.debug("The project id=" + projectId + " is already active, no need to activate it again"); return project; } - + if (currentState != State.Suspended) { - throw new InvalidParameterValueException("Can't activate the project in " + currentState + " state"); + throw new InvalidParameterValueException("Can't activate the project in " + currentState + " state", null); } - + Transaction txn = Transaction.currentTxn(); txn.start(); - + project.setState(Project.State.Active); _projectDao.update(projectId, project); - + _accountMgr.enableAccount(project.getProjectAccountId()); - + txn.commit(); - + return _projectDao.findById(projectId); } - - + + @Override @ActionEvent(eventType = EventTypes.EVENT_PROJECT_SUSPEND, eventDescription = "suspending project", async = true) public Project suspendProject (long projectId) throws ConcurrentOperationException, ResourceUnavailableException { Account caller = UserContext.current().getCaller(); - + ProjectVO project= getProject(projectId); //verify input parameters if (project == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); - ex.addProxyObject(project, projectId, "projectId"); - throw ex; + throw new InvalidParameterValueException("Unable to find project by id", null); } - + _accountMgr.checkAccess(caller,AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); - + if (suspendProject(project)) { s_logger.debug("Successfully suspended project id=" + projectId); return _projectDao.findById(projectId); } else { - CloudRuntimeException ex = new CloudRuntimeException("Failed to suspend project with specified id"); - ex.addProxyObject(project, projectId, "projectId"); + CloudRuntimeException ex = new CloudRuntimeException("Failed to suspend project with specified id"); + ex.addProxyObject(project, projectId, "projectId"); throw ex; } - + } - + private boolean suspendProject(ProjectVO project) throws ConcurrentOperationException, ResourceUnavailableException { - + s_logger.debug("Marking project " + project + " with state " + State.Suspended + " as a part of project suspend..."); project.setState(State.Suspended); boolean updateResult = _projectDao.update(project.getId(), project); - + if (updateResult) { long projectAccountId = project.getProjectAccountId(); if (!_accountMgr.disableAccount(projectAccountId)) { @@ -1054,8 +1068,8 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } return true; } - - + + public static String generateToken(int length) { String charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Random rand = new Random(System.currentTimeMillis()); @@ -1066,7 +1080,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } return sb.toString(); } - + class EmailInvite { private Session _smtpSession; private final String _smtpHost; @@ -1126,9 +1140,9 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ s_logger.error("Exception creating address for: " + email, ex); } } - + String content = "You've been invited to join the CloudStack project id=" + projectId + ". Please use token " + token + " to complete registration"; - + SMTPMessage msg = new SMTPMessage(_smtpSession); msg.setSender(new InternetAddress(_emailSender, _emailSender)); msg.setFrom(new InternetAddress(_emailSender, _emailSender)); @@ -1152,24 +1166,24 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } } } - - + + @Override @DB @ActionEvent(eventType = EventTypes.EVENT_PROJECT_INVITATION_REMOVE, eventDescription = "removing project invitation", async=true) public boolean deleteProjectInvitation(long id) { Account caller = UserContext.current().getCaller(); - + ProjectInvitation invitation = _projectInvitationDao.findById(id); if (invitation == null) { - throw new InvalidParameterValueException("Unable to find project invitation by id " + id); + throw new InvalidParameterValueException("Unable to find project invitation by id ", null); } - + //check that the project exists Project project = getProject(invitation.getProjectId()); - + //check permissions - only project owner can remove the invitations _accountMgr.checkAccess(caller, AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); - + if (_projectInvitationDao.remove(id)) { s_logger.debug("Project Invitation id=" + id + " is removed"); return true; @@ -1178,35 +1192,35 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ return false; } } - + public class ExpiredInvitationsCleanup implements Runnable { - @Override - public void run() { - try { - TimeZone.getDefault(); - List invitationsToExpire = _projectInvitationDao.listInvitationsToExpire(_invitationTimeOut); - if (!invitationsToExpire.isEmpty()) { - s_logger.debug("Found " + invitationsToExpire.size() + " projects to expire"); - for (ProjectInvitationVO invitationToExpire : invitationsToExpire) { - invitationToExpire.setState(ProjectInvitation.State.Expired); - _projectInvitationDao.update(invitationToExpire.getId(), invitationToExpire); - s_logger.trace("Expired project invitation id=" + invitationToExpire.getId()); - } - } - } catch (Exception ex) { - s_logger.warn("Exception while running expired invitations cleanup", ex); - } - } + @Override + public void run() { + try { + TimeZone.getDefault(); + List invitationsToExpire = _projectInvitationDao.listInvitationsToExpire(_invitationTimeOut); + if (!invitationsToExpire.isEmpty()) { + s_logger.debug("Found " + invitationsToExpire.size() + " projects to expire"); + for (ProjectInvitationVO invitationToExpire : invitationsToExpire) { + invitationToExpire.setState(ProjectInvitation.State.Expired); + _projectInvitationDao.update(invitationToExpire.getId(), invitationToExpire); + s_logger.trace("Expired project invitation id=" + invitationToExpire.getId()); + } + } + } catch (Exception ex) { + s_logger.warn("Exception while running expired invitations cleanup", ex); + } + } } @Override - public boolean projectInviteRequired() { - return _invitationRequired; - } + public boolean projectInviteRequired() { + return _invitationRequired; + } @Override public boolean allowUserToCreateProject() { - return _allowUserToCreateProject; + return _allowUserToCreateProject; } - + } diff --git a/server/src/com/cloud/resource/ResourceManagerImpl.java b/server/src/com/cloud/resource/ResourceManagerImpl.java index dcd9ce7367f..942247ed2e4 100755 --- a/server/src/com/cloud/resource/ResourceManagerImpl.java +++ b/server/src/com/cloud/resource/ResourceManagerImpl.java @@ -125,6 +125,7 @@ import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.User; import com.cloud.user.UserContext; +import com.cloud.utils.IdentityProxy; import com.cloud.utils.Pair; import com.cloud.utils.StringUtils; import com.cloud.utils.UriUtils; @@ -144,7 +145,6 @@ import com.cloud.utils.net.Ip; import com.cloud.utils.net.NetUtils; import com.cloud.utils.ssh.SSHCmdHelper; import com.cloud.utils.ssh.sshException; -import com.cloud.utils.AnnotationHelper; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.VirtualMachineManager; @@ -221,7 +221,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma protected ClusterVSMMapDao _clusterVSMMapDao; protected long _nodeId = ManagementServerNode.getManagementServerId(); - + protected HashMap _resourceStateAdapters = new HashMap(); protected HashMap> _lifeCycleListeners = new HashMap>(); @@ -233,14 +233,14 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma lst = new ArrayList(); _lifeCycleListeners.put(event, lst); } - + if (lst.contains(listener)) { throw new CloudRuntimeException("Duplicate resource lisener:" + listener.getClass().getSimpleName()); } - + lst.add(listener); } - + @Override public void registerResourceEvent(Integer event, ResourceListener listener) { synchronized (_lifeCycleListeners) { @@ -270,7 +270,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma } } } - + @Override public void unregisterResourceEvent(ResourceListener listener) { synchronized (_lifeCycleListeners) { @@ -282,7 +282,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma } } } - + protected void processResourceEvent(Integer event, Object...params) { List lst = _lifeCycleListeners.get(event); if (lst == null || lst.size() == 0) { @@ -321,7 +321,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma } s_logger.debug("Sent resource event " + eventName + " to listener " + l.getClass().getSimpleName()); } - + } @DB @@ -343,44 +343,42 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma // Check if the zone exists in the system DataCenterVO zone = _dcDao.findById(dcId); if (zone == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Can't find zone by the id specified"); - ex.addProxyObject(zone, dcId, "dcId"); - throw ex; + throw new InvalidParameterValueException("Can't find zone by id", null); } Account account = UserContext.current().getCaller(); if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(account.getType())) { - PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation, Zone with specified id is currently disabled"); - ex.addProxyObject(zone, dcId, "dcId"); + PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation, Zone with specified id is currently disabled"); + ex.addProxyObject(zone, dcId, "dcId"); throw ex; } HostPodVO pod = _podDao.findById(podId); if (pod == null) { - throw new InvalidParameterValueException("Can't find pod with specified podId " + podId); + throw new InvalidParameterValueException("Can't find pod by id", null); } - + // check if pod belongs to the zone if (!Long.valueOf(pod.getDataCenterId()).equals(dcId)) { - InvalidParameterValueException ex = new InvalidParameterValueException("Pod with specified id doesn't belong to the zone " + dcId); - ex.addProxyObject(pod, podId, "podId"); - ex.addProxyObject(zone, dcId, "dcId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(pod, podId, "podId")); + idList.add(new IdentityProxy(zone, dcId, "zoneId")); + throw new InvalidParameterValueException("Pod with specified podId doesn't belong to the zone with specified zoneId", idList); } // Verify cluster information and create a new cluster if needed if (clusterName == null || clusterName.isEmpty()) { - throw new InvalidParameterValueException("Please specify cluster name"); + throw new InvalidParameterValueException("Please specify cluster name", null); } if (cmd.getHypervisor() == null || cmd.getHypervisor().isEmpty()) { - throw new InvalidParameterValueException("Please specify a hypervisor"); + throw new InvalidParameterValueException("Please specify a hypervisor", null); } Hypervisor.HypervisorType hypervisorType = Hypervisor.HypervisorType.getType(cmd.getHypervisor()); if (hypervisorType == null) { s_logger.error("Unable to resolve " + cmd.getHypervisor() + " to a valid supported hypervisor type"); - throw new InvalidParameterValueException("Unable to resolve " + cmd.getHypervisor() + " to a supported "); + throw new InvalidParameterValueException("Unable to resolve " + cmd.getHypervisor() + " to a supported hypervisor type", null); } Cluster.ClusterType clusterType = null; @@ -396,7 +394,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma try { allocationState = Grouping.AllocationState.valueOf(cmd.getAllocationState()); } catch (IllegalArgumentException ex) { - throw new InvalidParameterValueException("Unable to resolve Allocation State '" + cmd.getAllocationState() + "' to a supported state"); + throw new InvalidParameterValueException("Unable to resolve Allocation State '" + cmd.getAllocationState() + "' to a supported state", null); } } if (allocationState == null) { @@ -405,8 +403,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma Discoverer discoverer = getMatchingDiscover(hypervisorType); if (discoverer == null) { - - throw new InvalidParameterValueException("Could not find corresponding resource manager for " + cmd.getHypervisor()); + throw new InvalidParameterValueException("Could not find corresponding resource manager for " + cmd.getHypervisor(), null); } List result = new ArrayList(); @@ -421,102 +418,102 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma cluster = _clusterDao.persist(cluster); } catch (Exception e) { // no longer tolerate exception during the cluster creation phase - CloudRuntimeException ex = new CloudRuntimeException("Unable to create cluster " + clusterName + " in pod and data center with specified ids", e); + CloudRuntimeException ex = new CloudRuntimeException("Unable to create cluster " + clusterName + " in pod and data center with specified ids", e); // Get the pod VO object's table name. - ex.addProxyObject(pod, podId, "podId"); + ex.addProxyObject(pod, podId, "podId"); ex.addProxyObject(zone, dcId, "dcId"); throw ex; } clusterId = cluster.getId(); result.add(cluster); - + // Check if we're associating a Cisco Nexus VSM with a vmware cluster. if (hypervisorType == HypervisorType.VMware && - Boolean.parseBoolean(_configDao.getValue(Config.VmwareUseNexusVSwitch.toString()))) { - String vsmIp = cmd.getVSMIpaddress(); + Boolean.parseBoolean(_configDao.getValue(Config.VmwareUseNexusVSwitch.toString()))) { + String vsmIp = cmd.getVSMIpaddress(); String vsmUser = cmd.getVSMUsername(); String vsmPassword = cmd.getVSMPassword(); - if(vsmIp != null && vsmUser != null && vsmPassword != null) { - NetconfHelper netconfClient; - try { - netconfClient = new NetconfHelper(vsmIp, vsmUser, vsmPassword); - netconfClient.disconnect(); - } catch (CloudRuntimeException e) { - String msg = "Invalid credentials supplied for user " + vsmUser + " for Cisco Nexus 1000v VSM at " + vsmIp; - s_logger.error(msg); - _clusterDao.remove(clusterId); - throw new CloudRuntimeException(msg); - } - - Transaction txn; - - // If VSM already exists and is mapped to a cluster, fail this operation. - CiscoNexusVSMDeviceVO vsm = _vsmDao.getVSMbyIpaddress(vsmIp); - if(vsm != null) { - List clusterList = _clusterVSMDao.listByVSMId(vsm.getId()); - if (clusterList != null && !clusterList.isEmpty()) { - s_logger.error("Failed to add cluster: specified Nexus VSM is already associated with another cluster"); - _clusterDao.remove(clusterId); - ResourceInUseException ex = new ResourceInUseException("Failed to add cluster: specified Nexus VSM is already associated with another cluster with specified Id"); - ex.addProxyObject("cluster", clusterList.get(0).getClusterId(), "clusterId"); - throw ex; - } - } - // persist credentials to database if the VSM entry is not already in the db. - if (_vsmDao.getVSMbyIpaddress(vsmIp) == null) { - vsm = new CiscoNexusVSMDeviceVO(vsmIp, vsmUser, vsmPassword); - txn = Transaction.currentTxn(); - try { - txn.start(); - vsm = _vsmDao.persist(vsm); - txn.commit(); - } catch (Exception e) { - txn.rollback(); - s_logger.error("Failed to persist Cisco Nexus 1000v VSM details to database. Exception: " + e.getMessage()); - // Removing the cluster record which was added already because the persistence of Nexus VSM credentials has failed. - _clusterDao.remove(clusterId); - throw new CloudRuntimeException(e.getMessage()); - } - } - // Create a mapping between the cluster and the vsm. - vsm = _vsmDao.getVSMbyIpaddress(vsmIp); - if (vsm != null) { - ClusterVSMMapVO connectorObj = new ClusterVSMMapVO(clusterId, vsm.getId()); - txn = Transaction.currentTxn(); - try { - txn.start(); - _clusterVSMDao.persist(connectorObj); - txn.commit(); - } catch (Exception e) { - txn.rollback(); - s_logger.error("Failed to associate Cisco Nexus 1000v VSM with cluster: " + clusterName + ". Exception: " + e.getMessage()); - _clusterDao.remove(clusterId); - throw new CloudRuntimeException(e.getMessage()); - } - } - } else { - String msg; - msg = "The global parameter " + Config.VmwareUseNexusVSwitch.toString() + - " is set to \"true\". Following mandatory parameters are not specified. "; - if(vsmIp == null) { - msg += "vsmipaddress: Management IP address of Cisco Nexus 1000v dvSwitch. "; - } - if(vsmUser == null) { - msg += "vsmusername: Name of a user account with admin privileges over Cisco Nexus 1000v dvSwitch. "; - } - if(vsmPassword == null) { - if(vsmUser != null) { - msg += "vsmpassword: Password of user account " + vsmUser + ". "; - } else { - msg += "vsmpassword: Password of user account with admin privileges over Cisco Nexus 1000v dvSwitch. "; - } - } - s_logger.error(msg); - // Cleaning up the cluster record as addCluster operation failed because Nexus dvSwitch credentials are supplied. - _clusterDao.remove(clusterId); - throw new CloudRuntimeException(msg); - } + if(vsmIp != null && vsmUser != null && vsmPassword != null) { + NetconfHelper netconfClient; + try { + netconfClient = new NetconfHelper(vsmIp, vsmUser, vsmPassword); + netconfClient.disconnect(); + } catch (CloudRuntimeException e) { + String msg = "Invalid credentials supplied for user " + vsmUser + " for Cisco Nexus 1000v VSM at " + vsmIp; + s_logger.error(msg); + _clusterDao.remove(clusterId); + throw new CloudRuntimeException(msg); + } + + Transaction txn; + + // If VSM already exists and is mapped to a cluster, fail this operation. + CiscoNexusVSMDeviceVO vsm = _vsmDao.getVSMbyIpaddress(vsmIp); + if(vsm != null) { + List clusterList = _clusterVSMDao.listByVSMId(vsm.getId()); + if (clusterList != null && !clusterList.isEmpty()) { + s_logger.error("Failed to add cluster: specified Nexus VSM is already associated with another cluster"); + _clusterDao.remove(clusterId); + ResourceInUseException ex = new ResourceInUseException("Failed to add cluster: specified Nexus VSM is already associated with another cluster with specified Id"); + ex.addProxyObject("cluster", clusterList.get(0).getClusterId(), "clusterId"); + throw ex; + } + } + // persist credentials to database if the VSM entry is not already in the db. + if (_vsmDao.getVSMbyIpaddress(vsmIp) == null) { + vsm = new CiscoNexusVSMDeviceVO(vsmIp, vsmUser, vsmPassword); + txn = Transaction.currentTxn(); + try { + txn.start(); + vsm = _vsmDao.persist(vsm); + txn.commit(); + } catch (Exception e) { + txn.rollback(); + s_logger.error("Failed to persist Cisco Nexus 1000v VSM details to database. Exception: " + e.getMessage()); + // Removing the cluster record which was added already because the persistence of Nexus VSM credentials has failed. + _clusterDao.remove(clusterId); + throw new CloudRuntimeException(e.getMessage()); + } + } + // Create a mapping between the cluster and the vsm. + vsm = _vsmDao.getVSMbyIpaddress(vsmIp); + if (vsm != null) { + ClusterVSMMapVO connectorObj = new ClusterVSMMapVO(clusterId, vsm.getId()); + txn = Transaction.currentTxn(); + try { + txn.start(); + _clusterVSMDao.persist(connectorObj); + txn.commit(); + } catch (Exception e) { + txn.rollback(); + s_logger.error("Failed to associate Cisco Nexus 1000v VSM with cluster: " + clusterName + ". Exception: " + e.getMessage()); + _clusterDao.remove(clusterId); + throw new CloudRuntimeException(e.getMessage()); + } + } + } else { + String msg; + msg = "The global parameter " + Config.VmwareUseNexusVSwitch.toString() + + " is set to \"true\". Following mandatory parameters are not specified. "; + if(vsmIp == null) { + msg += "vsmipaddress: Management IP address of Cisco Nexus 1000v dvSwitch. "; + } + if(vsmUser == null) { + msg += "vsmusername: Name of a user account with admin privileges over Cisco Nexus 1000v dvSwitch. "; + } + if(vsmPassword == null) { + if(vsmUser != null) { + msg += "vsmpassword: Password of user account " + vsmUser + ". "; + } else { + msg += "vsmpassword: Password of user account with admin privileges over Cisco Nexus 1000v dvSwitch. "; + } + } + s_logger.error(msg); + // Cleaning up the cluster record as addCluster operation failed because Nexus dvSwitch credentials are supplied. + _clusterDao.remove(clusterId); + throw new CloudRuntimeException(msg); + } } if (clusterType == Cluster.ClusterType.CloudManaged) { @@ -536,20 +533,20 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma try { uri = new URI(UriUtils.encodeURIComponent(url)); if (uri.getScheme() == null) { - throw new InvalidParameterValueException("uri.scheme is null " + url + ", add http:// as a prefix"); + throw new InvalidParameterValueException("uri.scheme is null " + url + ", add http:// as a prefix", null); } else if (uri.getScheme().equalsIgnoreCase("http")) { if (uri.getHost() == null || uri.getHost().equalsIgnoreCase("") || uri.getPath() == null || uri.getPath().equalsIgnoreCase("")) { - throw new InvalidParameterValueException("Your host and/or path is wrong. Make sure it's of the format http://hostname/path"); + throw new InvalidParameterValueException("Your host and/or path is wrong. Make sure it's of the format http://hostname/path", null); } } } catch (URISyntaxException e) { - throw new InvalidParameterValueException(url + " is not a valid uri"); + throw new InvalidParameterValueException(url + " is not a valid uri", null); } List hosts = new ArrayList(); Map> resources = null; resources = discoverer.find(dcId, podId, clusterId, uri, username, password, null); - + if (resources != null) { for (Map.Entry> entry : resources.entrySet()) { ServerResource resource = entry.getKey(); @@ -614,15 +611,13 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma if (clusterId != null) { ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster for specified clusterId"); - ex.addProxyObject(cluster, clusterId, "clusterId"); - throw ex; + InvalidParameterValueException ex = new InvalidParameterValueException("can not find cluster by Id", null); } else { if (cluster.getGuid() == null) { List hosts = listAllHostsInCluster(clusterId); if (!hosts.isEmpty()) { - CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); - ex.addProxyObject(cluster, clusterId, "clusterId"); + CloudRuntimeException ex = new CloudRuntimeException("Guid is not updated for cluster with specified cluster id; need to wait for hosts in this cluster to come up"); + ex.addProxyObject(cluster, clusterId, "clusterId"); throw ex; } } @@ -638,7 +633,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma String url = cmd.getUrl(); return discoverHostsFull(dcId, null, null, null, url, null, null, "SecondaryStorage", null, null); } - + @Override public Swift discoverSwift(AddSwiftCmd cmd) throws DiscoveryException { return _swiftMgr.addSwift(cmd); @@ -656,65 +651,65 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma // Check if the zone exists in the system DataCenterVO zone = _dcDao.findById(dcId); if (zone == null) { - throw new InvalidParameterValueException("Can't find zone by id " + dcId); + throw new InvalidParameterValueException("Can't find zone by id", null); } Account account = UserContext.current().getCaller(); if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(account.getType())) { - PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation, Zone with specified id is currently disabled"); - ex.addProxyObject(zone, dcId, "dcId"); + PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation, Zone with specified id is currently disabled"); + ex.addProxyObject(zone, dcId, "dcId"); throw ex; } - + // Check if the pod exists in the system if (podId != null) { HostPodVO pod = _podDao.findById(podId); if (pod == null) { - throw new InvalidParameterValueException("Can't find pod by id " + podId); + throw new InvalidParameterValueException("Can't find pod by id", null); } // check if pod belongs to the zone if (!Long.valueOf(pod.getDataCenterId()).equals(dcId)) { - InvalidParameterValueException ex = new InvalidParameterValueException("Pod with specified podId" + podId + " doesn't belong to the zone with specified zoneId" + dcId); - ex.addProxyObject(pod, podId, "podId"); - ex.addProxyObject(zone, dcId, "dcId"); - throw ex; + List idList = new ArrayList(); + idList.add(new IdentityProxy(pod, podId, "podId")); + idList.add(new IdentityProxy(zone, dcId, "zoneId")); + throw new InvalidParameterValueException("Pod with specified podId doesn't belong to the zone with specified zoneId", null); } } // Verify cluster information and create a new cluster if needed if (clusterName != null && clusterId != null) { - throw new InvalidParameterValueException("Can't specify cluster by both id and name"); + throw new InvalidParameterValueException("Can't specify cluster by both id and name", null); } if (hypervisorType == null || hypervisorType.isEmpty()) { - throw new InvalidParameterValueException("Need to specify Hypervisor Type"); + throw new InvalidParameterValueException("Need to specify Hypervisor Type", null); } if ((clusterName != null || clusterId != null) && podId == null) { - throw new InvalidParameterValueException("Can't specify cluster without specifying the pod"); + throw new InvalidParameterValueException("Can't specify cluster without specifying the pod", null); } if (clusterId != null) { if (_clusterDao.findById(clusterId) == null) { - throw new InvalidParameterValueException("Can't find cluster by id " + clusterId); + throw new InvalidParameterValueException("Can't find cluster by id", null); } - + if(hypervisorType.equalsIgnoreCase(HypervisorType.VMware.toString())) { - // VMware only allows adding host to an existing cluster, as we already have a lot of information - // in cluster object, to simplify user input, we will construct neccessary information here - Map clusterDetails = this._clusterDetailsDao.findDetails(clusterId); - username = clusterDetails.get("username"); - assert(username != null); - - password = clusterDetails.get("password"); - assert(password != null); - + // VMware only allows adding host to an existing cluster, as we already have a lot of information + // in cluster object, to simplify user input, we will construct neccessary information here + Map clusterDetails = this._clusterDetailsDao.findDetails(clusterId); + username = clusterDetails.get("username"); + assert(username != null); + + password = clusterDetails.get("password"); + assert(password != null); + try { uri = new URI(UriUtils.encodeURIComponent(url)); - + url = clusterDetails.get("url") + "/" + uri.getHost(); } catch (URISyntaxException e) { - throw new InvalidParameterValueException(url + " is not a valid uri"); + throw new InvalidParameterValueException(url + " is not a valid uri", null); } } } @@ -722,17 +717,17 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma if (clusterName != null) { HostPodVO pod = _podDao.findById(podId); if (pod == null) { - throw new InvalidParameterValueException("Can't find pod by id " + podId); + throw new InvalidParameterValueException("Can't find pod by id", null); } - ClusterVO cluster = new ClusterVO(dcId, podId, clusterName); + ClusterVO cluster = new ClusterVO(dcId, podId, clusterName); cluster.setHypervisorType(hypervisorType); try { cluster = _clusterDao.persist(cluster); } catch (Exception e) { cluster = _clusterDao.findBy(clusterName, podId); if (cluster == null) { - CloudRuntimeException ex = new CloudRuntimeException("Unable to create cluster " + clusterName + " in pod with specified podId and data center with specified dcID", e); - ex.addProxyObject(pod, podId, "podId"); + CloudRuntimeException ex = new CloudRuntimeException("Unable to create cluster " + clusterName + " in pod with specified podId and data center with specified dcID", e); + ex.addProxyObject(pod, podId, "podId"); ex.addProxyObject(zone, dcId, "dcId"); throw ex; } @@ -743,14 +738,14 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma try { uri = new URI(UriUtils.encodeURIComponent(url)); if (uri.getScheme() == null) { - throw new InvalidParameterValueException("uri.scheme is null " + url + ", add nfs:// as a prefix"); + throw new InvalidParameterValueException("uri.scheme is null " + url + ", add nfs:// as a prefix", null); } else if (uri.getScheme().equalsIgnoreCase("nfs")) { if (uri.getHost() == null || uri.getHost().equalsIgnoreCase("") || uri.getPath() == null || uri.getPath().equalsIgnoreCase("")) { - throw new InvalidParameterValueException("Your host and/or path is wrong. Make sure it's of the format nfs://hostname/path"); + throw new InvalidParameterValueException("Your host and/or path is wrong. Make sure it's of the format nfs://hostname/path", null); } } } catch (URISyntaxException e) { - throw new InvalidParameterValueException(url + " is not a valid uri"); + throw new InvalidParameterValueException(url + " is not a valid uri", null); } List hosts = new ArrayList(); @@ -773,12 +768,12 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma try { resources = discoverer.find(dcId, podId, clusterId, uri, username, password, hostTags); } catch(DiscoveryException e) { - throw e; + throw e; } catch (Exception e) { s_logger.info("Exception in host discovery process with discoverer: " + discoverer.getName() + ", skip to another discoverer if there is any"); } processResourceEvent(ResourceListener.EVENT_DISCOVER_AFTER, resources); - + if (resources != null) { for (Map.Entry> entry : resources.entrySet()) { ServerResource resource = entry.getKey(); @@ -803,7 +798,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma } return null; } - + HostVO host = (HostVO)createHostAndAgent(resource, entry.getValue(), true, hostTags, false); if (host != null) { hosts.add(host); @@ -835,10 +830,10 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma // Verify that host exists HostVO host = _hostDao.findById(hostId); if (host == null) { - throw new InvalidParameterValueException("Host with id " + hostId + " doesn't exist"); + throw new InvalidParameterValueException("Could not find host by id", null); } _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), host.getDataCenterId()); - + /* * TODO: check current agent status and updateAgentStatus to removed. If it was already removed, that means * someone is deleting host concurrently, return. And consider the situation of CloudStack shutdown during delete. @@ -849,21 +844,21 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma // Get storage pool host mappings here because they can be removed as a part of handleDisconnect later //TODO: find out the bad boy, what's a buggy logic! List pools = _storagePoolHostDao.listByHostIdIncludingRemoved(hostId); - + ResourceStateAdapter.DeleteHostAnswer answer = (ResourceStateAdapter.DeleteHostAnswer) dispatchToStateAdapters(ResourceStateAdapter.Event.DELETE_HOST, false, host, new Boolean(isForced), new Boolean(isForceDeleteStorage)); if (answer == null) { - throw new CloudRuntimeException("No resource adapter respond to DELETE_HOST event for " + host.getName() + " id = " + hostId + ", hypervisorType is " + host.getHypervisorType() + ", host type is " + host.getType()); + throw new CloudRuntimeException("No resource adapter respond to DELETE_HOST event for " + host.getName() + " id = " + hostId + ", hypervisorType is " + host.getHypervisorType() + ", host type is " + host.getType()); } - + if (answer.getIsException()) { return false; } - + if (!answer.getIsContinue()) { return true; } - + Transaction txn = Transaction.currentTxn(); txn.start(); @@ -888,12 +883,12 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma } } - try { - resourceStateTransitTo(host, ResourceState.Event.DeleteHost, _nodeId); - } catch (NoTransitionException e) { - s_logger.debug("Cannot transmit host " + host.getId() + "to Enabled state", e); - } - + try { + resourceStateTransitTo(host, ResourceState.Event.DeleteHost, _nodeId); + } catch (NoTransitionException e) { + s_logger.debug("Cannot transmit host " + host.getId() + "to Enabled state", e); + } + // Delete the associated entries in host ref table _storagePoolHostDao.deletePrimaryRecordsForHost(hostId); @@ -919,7 +914,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma txn.commit(); return true; } - + @Override public boolean deleteHost(long hostId, boolean isForced, boolean isForceDeleteStorage) { try { @@ -930,7 +925,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma } catch (AgentUnavailableException e) { return false; } - + return doDeleteHost(hostId, isForced, isForceDeleteStorage); } @@ -950,7 +945,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma } Hypervisor.HypervisorType hypervisorType = cluster.getHypervisorType(); - + List hosts = listAllHostsInCluster(cmd.getId()); if (hosts.size() > 0) { if (s_logger.isDebugEnabled()) { @@ -959,7 +954,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma txn.rollback(); throw new CloudRuntimeException("Cluster: " + cmd.getId() + " cannot be removed. Cluster still has hosts"); } - + //don't allow to remove the cluster if it has non-removed storage pools List storagePools = _storagePoolDao.listPoolsByCluster(cmd.getId()); if (storagePools.size() > 0) { @@ -975,19 +970,19 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma // If this cluster is of type vmware, and if the nexus vswitch global parameter setting is turned // on, remove the row in cluster_vsm_map for this cluster id. if (hypervisorType == HypervisorType.VMware && - Boolean.parseBoolean(_configDao.getValue(Config.VmwareUseNexusVSwitch.toString()))) { - _clusterVSMMapDao.removeByClusterId(cmd.getId()); + Boolean.parseBoolean(_configDao.getValue(Config.VmwareUseNexusVSwitch.toString()))) { + _clusterVSMMapDao.removeByClusterId(cmd.getId()); } } txn.commit(); return true; } catch(CloudRuntimeException e){ - throw e; + throw e; } catch (Throwable t) { - s_logger.error("Unable to delete cluster: " + cmd.getId(), t); - txn.rollback(); - return false; + s_logger.error("Unable to delete cluster: " + cmd.getId(), t); + txn.rollback(); + return false; } } @@ -1003,7 +998,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma Hypervisor.HypervisorType hypervisorType = Hypervisor.HypervisorType.getType(hypervisor); if (hypervisorType == null) { s_logger.error("Unable to resolve " + hypervisor + " to a valid supported hypervisor type"); - throw new InvalidParameterValueException("Unable to resolve " + hypervisor + " to a supported type"); + throw new InvalidParameterValueException("Unable to resolve " + hypervisor + " to a supported type", null); } else { cluster.setHypervisorType(hypervisor); doUpdate = true; @@ -1015,11 +1010,11 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma try { newClusterType = Cluster.ClusterType.valueOf(clusterType); } catch (IllegalArgumentException ex) { - throw new InvalidParameterValueException("Unable to resolve " + clusterType + " to a supported type"); + throw new InvalidParameterValueException("Unable to resolve " + clusterType + " to a supported type", null); } if (newClusterType == null) { s_logger.error("Unable to resolve " + clusterType + " to a valid supported cluster type"); - throw new InvalidParameterValueException("Unable to resolve " + clusterType + " to a supported type"); + throw new InvalidParameterValueException("Unable to resolve " + clusterType + " to a supported type", null); } else { cluster.setClusterType(newClusterType); doUpdate = true; @@ -1031,34 +1026,34 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma try { newAllocationState = Grouping.AllocationState.valueOf(allocationState); } catch (IllegalArgumentException ex) { - throw new InvalidParameterValueException("Unable to resolve Allocation State '" + allocationState + "' to a supported state"); + throw new InvalidParameterValueException("Unable to resolve Allocation State '" + allocationState + "' to a supported state", null); } if (newAllocationState == null) { s_logger.error("Unable to resolve " + allocationState + " to a valid supported allocation State"); - throw new InvalidParameterValueException("Unable to resolve " + allocationState + " to a supported state"); + throw new InvalidParameterValueException("Unable to resolve " + allocationState + " to a supported state", null); } else { _capacityDao.updateCapacityState(null, null, cluster.getId(), null, allocationState); cluster.setAllocationState(newAllocationState); doUpdate = true; } } - + Managed.ManagedState newManagedState = null; Managed.ManagedState oldManagedState = cluster.getManagedState(); if (managedstate != null && !managedstate.isEmpty()) { try { newManagedState = Managed.ManagedState.valueOf(managedstate); } catch (IllegalArgumentException ex) { - throw new InvalidParameterValueException("Unable to resolve Managed State '" + managedstate + "' to a supported state"); + throw new InvalidParameterValueException("Unable to resolve Managed State '" + managedstate + "' to a supported state", null); } if (newManagedState == null) { s_logger.error("Unable to resolve Managed State '" + managedstate + "' to a supported state"); - throw new InvalidParameterValueException("Unable to resolve Managed State '" + managedstate + "' to a supported state"); + throw new InvalidParameterValueException("Unable to resolve Managed State '" + managedstate + "' to a supported state", null); } else { doUpdate = true; } } - + if (doUpdate) { Transaction txn = Transaction.currentTxn(); try { @@ -1070,7 +1065,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma throw new CloudRuntimeException("Failed to update cluster. Please contact Cloud Support."); } } - + if( newManagedState != null && !newManagedState.equals(oldManagedState)) { Transaction txn = Transaction.currentTxn(); if( newManagedState.equals(Managed.ManagedState.Unmanaged) ) { @@ -1086,12 +1081,12 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma && !host.getStatus().equals(Status.Up) && !host.getStatus().equals(Status.Alert) ) { String msg = "host " + host.getPrivateIpAddress() + " should not be in " + host.getStatus().toString() + " status"; throw new CloudRuntimeException("PrepareUnmanaged Failed due to " + msg); - } + } } - + for( HostVO host : hosts ) { if ( host.getStatus().equals(Status.Up )) { - umanageHost(host.getId()); + umanageHost(host.getId()); } } int retry = 10; @@ -1130,9 +1125,9 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma _clusterDao.update(cluster.getId(), cluster); txn.commit(); } - + } - + return cluster; } @@ -1143,7 +1138,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma // verify input parameters HostVO host = _hostDao.findById(hostId); if (host == null || host.getRemoved() != null) { - throw new InvalidParameterValueException("Host with id " + hostId.toString() + " doesn't exist"); + throw new InvalidParameterValueException("Could not find host by id", null); } processResourceEvent(ResourceListener.EVENT_CANCEL_MAINTENANCE_BEFORE, hostId); @@ -1161,17 +1156,17 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma HostVO host = _hostDao.findById(hostId); if (host == null) { - throw new InvalidParameterValueException("Host with id " + hostId.toString() + " doesn't exist"); + throw new InvalidParameterValueException("Could not find host by id", null); + } + + //for kvm, need to log into kvm host, restart cloud-agent + if (host.getStatus() != Status.Up && host.getHypervisorType() == HypervisorType.KVM) { + return restartAgent(host) ? host : null; } - - //for kvm, need to log into kvm host, restart cloud-agent - if (host.getStatus() != Status.Up && host.getHypervisorType() == HypervisorType.KVM) { - return restartAgent(host) ? host : null; - } return (_agentMgr.reconnect(hostId) ? host : null); } - + @Override public boolean resourceStateTransitTo(Host host, ResourceState.Event event, long msId) throws NoTransitionException { ResourceState currentState = host.getResourceState(); @@ -1179,36 +1174,36 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma if (nextState == null) { throw new NoTransitionException("No next resource state found for current state =" + currentState + " event =" + event); } - + // TO DO - Make it more granular and have better conversion into capacity type if(host.getType() == Type.Routing && host.getClusterId() != null){ - AllocationState capacityState = _configMgr.findClusterAllocationState(ApiDBUtils.findClusterById(host.getClusterId())); - if (capacityState == AllocationState.Enabled && nextState != ResourceState.Enabled){ - capacityState = AllocationState.Disabled; - } - _capacityDao.updateCapacityState(null, null, null, host.getId(), capacityState.toString()); + AllocationState capacityState = _configMgr.findClusterAllocationState(ApiDBUtils.findClusterById(host.getClusterId())); + if (capacityState == AllocationState.Enabled && nextState != ResourceState.Enabled){ + capacityState = AllocationState.Disabled; + } + _capacityDao.updateCapacityState(null, null, null, host.getId(), capacityState.toString()); } return _hostDao.updateResourceState(currentState, event, nextState, host); } - + private boolean doMaintain(final long hostId) { HostVO host = _hostDao.findById(hostId); MaintainAnswer answer = (MaintainAnswer) _agentMgr.easySend(hostId, new MaintainCommand()); if (answer == null || !answer.getResult()) { s_logger.warn("Unable to send MaintainCommand to host: " + hostId); } - + try { - resourceStateTransitTo(host, ResourceState.Event.AdminAskMaintenace, _nodeId); + resourceStateTransitTo(host, ResourceState.Event.AdminAskMaintenace, _nodeId); } catch (NoTransitionException e) { String err = "Cannot transimit resource state of host " + host.getId() + " to " + ResourceState.Maintenance; s_logger.debug(err, e); throw new CloudRuntimeException(err + e.getMessage()); } - + _agentMgr.pullAgentToMaintenance(hostId); - + /*TODO: move below to listener */ if (host.getType() == Host.Type.Routing) { @@ -1230,16 +1225,17 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma return true; } - + + @Override public boolean maintain(final long hostId) throws AgentUnavailableException { Boolean result = _clusterMgr.propagateResourceEvent(hostId, ResourceState.Event.AdminAskMaintenace); if (result != null) { return result; } - + return doMaintain(hostId); } - + @Override public Host maintain(PrepareForMaintenanceCmd cmd) { Long hostId = cmd.getId(); @@ -1247,15 +1243,18 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma if (host == null) { s_logger.debug("Unable to find host " + hostId); - throw new InvalidParameterValueException("Unable to find host with ID: " + hostId + ". Please specify a valid host ID."); + throw new InvalidParameterValueException("Could not find host by id, please specify a valid host ID.", null); } if (_hostDao.countBy(host.getClusterId(), ResourceState.PrepareForMaintenance, ResourceState.ErrorInMaintenance) > 0) { - throw new InvalidParameterValueException("There are other servers in PrepareForMaintenance OR ErrorInMaintenance STATUS in cluster " + host.getClusterId()); + List idList = new ArrayList(); + idList.add(new IdentityProxy("cluster", host.getClusterId(), "clusterId")); + throw new InvalidParameterValueException("There are other servers in PrepareForMaintenance OR " + + "ErrorInMaintenance STATUS in cluster with specified clusterId", idList); } if (_storageMgr.isLocalStorageActiveOnHost(host)) { - throw new InvalidParameterValueException("There are active VMs using the host's local storage pool. Please stop all VMs on this host that use local storage."); + throw new InvalidParameterValueException("There are active VMs using the host's local storage pool. Please stop all VMs on this host that use local storage.", null); } try { @@ -1279,23 +1278,23 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma // Verify that the host exists HostVO host = _hostDao.findById(hostId); if (host == null) { - throw new InvalidParameterValueException("Host with id " + hostId + " doesn't exist"); + throw new InvalidParameterValueException("Could not find host by id", null); } - - if (cmd.getAllocationState() != null) { - ResourceState.Event resourceEvent = ResourceState.Event.toEvent(cmd.getAllocationState()); - if (resourceEvent != ResourceState.Event.Enable && resourceEvent != ResourceState.Event.Disable) { - throw new CloudRuntimeException("Invalid allocation state:" + cmd.getAllocationState() + ", only Enable/Disable are allowed"); - } - - resourceStateTransitTo(host, resourceEvent, _nodeId); - } - + + if (cmd.getAllocationState() != null) { + ResourceState.Event resourceEvent = ResourceState.Event.toEvent(cmd.getAllocationState()); + if (resourceEvent != ResourceState.Event.Enable && resourceEvent != ResourceState.Event.Disable) { + throw new CloudRuntimeException("Invalid allocation state:" + cmd.getAllocationState() + ", only Enable/Disable are allowed"); + } + + resourceStateTransitTo(host, resourceEvent, _nodeId); + } + if (guestOSCategoryId != null) { // Verify that the guest OS Category exists if (guestOSCategoryId > 0) { if (_guestOSCategoryDao.findById(guestOSCategoryId) == null) { - throw new InvalidParameterValueException("Please specify a valid guest OS category."); + throw new InvalidParameterValueException("Please specify a valid guest OS category.", null); } } @@ -1311,7 +1310,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma } _hostDetailsDao.persist(hostId, hostDetails); } - + List hostTags = cmd.getHostTags(); if (hostTags != null) { if(s_logger.isDebugEnabled()){ @@ -1319,10 +1318,10 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma } _hostTagsDao.persist(hostId, hostTags); } - + String url = cmd.getUrl(); if (url != null) { - _storageMgr.updateSecondaryStorage(cmd.getId(), cmd.getUrl()); + _storageMgr.updateSecondaryStorage(cmd.getId(), cmd.getUrl()); } HostVO updatedHost = _hostDao.findById(hostId); @@ -1355,397 +1354,397 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma public String getName() { return _name; } - + @Override public List getSupportedHypervisorTypes(long zoneId, boolean forVirtualRouter, Long podId) { List hypervisorTypes = new ArrayList(); - + List clustersForZone = new ArrayList(); if (podId != null) { - clustersForZone = _clusterDao.listByPodId(podId); + clustersForZone = _clusterDao.listByPodId(podId); } else { - clustersForZone = _clusterDao.listByZoneId(zoneId); + clustersForZone = _clusterDao.listByZoneId(zoneId); } - + for (ClusterVO cluster : clustersForZone) { - HypervisorType hType = cluster.getHypervisorType(); - if (!forVirtualRouter || (forVirtualRouter && hType != HypervisorType.BareMetal && hType != HypervisorType.Ovm)) { + HypervisorType hType = cluster.getHypervisorType(); + if (!forVirtualRouter || (forVirtualRouter && hType != HypervisorType.BareMetal && hType != HypervisorType.Ovm)) { hypervisorTypes.add(hType); - } + } } - + return hypervisorTypes; } - + @Override public HypervisorType getDefaultHypervisor(long zoneId) { - HypervisorType defaultHyper = HypervisorType.None; - if (_defaultSystemVMHypervisor != HypervisorType.None) { - defaultHyper = _defaultSystemVMHypervisor; - } - - DataCenterVO dc = _dcDao.findById(zoneId); - if (dc == null) { - return HypervisorType.None; - } - _dcDao.loadDetails(dc); - String defaultHypervisorInZone = dc.getDetail("defaultSystemVMHypervisorType"); - if (defaultHypervisorInZone != null) { - defaultHyper = HypervisorType.getType(defaultHypervisorInZone); - } - - List systemTemplates = _templateDao.listAllSystemVMTemplates(); - boolean isValid = false; - for (VMTemplateVO template : systemTemplates) { - if (template.getHypervisorType() == defaultHyper) { - isValid = true; - break; - } - } - - if (isValid) { - List clusters = _clusterDao.listByDcHyType(zoneId, defaultHyper.toString()); - if (clusters.size() <= 0) { - isValid = false; - } - } - - if (isValid) { - return defaultHyper; - } else { - return HypervisorType.None; - } + HypervisorType defaultHyper = HypervisorType.None; + if (_defaultSystemVMHypervisor != HypervisorType.None) { + defaultHyper = _defaultSystemVMHypervisor; + } + + DataCenterVO dc = _dcDao.findById(zoneId); + if (dc == null) { + return HypervisorType.None; + } + _dcDao.loadDetails(dc); + String defaultHypervisorInZone = dc.getDetail("defaultSystemVMHypervisorType"); + if (defaultHypervisorInZone != null) { + defaultHyper = HypervisorType.getType(defaultHypervisorInZone); + } + + List systemTemplates = _templateDao.listAllSystemVMTemplates(); + boolean isValid = false; + for (VMTemplateVO template : systemTemplates) { + if (template.getHypervisorType() == defaultHyper) { + isValid = true; + break; + } + } + + if (isValid) { + List clusters = _clusterDao.listByDcHyType(zoneId, defaultHyper.toString()); + if (clusters.size() <= 0) { + isValid = false; + } + } + + if (isValid) { + return defaultHyper; + } else { + return HypervisorType.None; + } } - + @Override public HypervisorType getAvailableHypervisor(long zoneId) { - HypervisorType defaultHype = getDefaultHypervisor(zoneId); - if (defaultHype == HypervisorType.None) { - List supportedHypes = getSupportedHypervisorTypes(zoneId, false, null); - if (supportedHypes.size() > 0) { - defaultHype = supportedHypes.get(0); - } - } - - if (defaultHype == HypervisorType.None) { - defaultHype = HypervisorType.Any; - } - return defaultHype; + HypervisorType defaultHype = getDefaultHypervisor(zoneId); + if (defaultHype == HypervisorType.None) { + List supportedHypes = getSupportedHypervisorTypes(zoneId, false, null); + if (supportedHypes.size() > 0) { + defaultHype = supportedHypes.get(0); + } + } + + if (defaultHype == HypervisorType.None) { + defaultHype = HypervisorType.Any; + } + return defaultHype; } - @Override - public void registerResourceStateAdapter(String name, ResourceStateAdapter adapter) { - if (_resourceStateAdapters.get(name) != null) { - throw new CloudRuntimeException(name + " has registered"); - } - - synchronized (_resourceStateAdapters) { - _resourceStateAdapters.put(name, adapter); - } - } + @Override + public void registerResourceStateAdapter(String name, ResourceStateAdapter adapter) { + if (_resourceStateAdapters.get(name) != null) { + throw new CloudRuntimeException(name + " has registered"); + } - @Override + synchronized (_resourceStateAdapters) { + _resourceStateAdapters.put(name, adapter); + } + } + + @Override public void unregisterResourceStateAdapter(String name) { synchronized (_resourceStateAdapters) { _resourceStateAdapters.remove(name); } } - - private Object dispatchToStateAdapters(ResourceStateAdapter.Event event, boolean singleTaker, Object... args) { - synchronized (_resourceStateAdapters) { - Iterator it = _resourceStateAdapters.entrySet().iterator(); - Object result = null; - while (it.hasNext()) { - Map.Entry item = (Map.Entry) it.next(); - ResourceStateAdapter adapter = item.getValue(); - - String msg = new String("Dispatching resource state event " + event + " to " + item.getKey()); - s_logger.debug(msg); - - if (event == ResourceStateAdapter.Event.CREATE_HOST_VO_FOR_CONNECTED) { - result = adapter.createHostVOForConnectedAgent((HostVO) args[0], (StartupCommand[]) args[1]); - if (result != null && singleTaker) { - break; - } - } else if (event == ResourceStateAdapter.Event.CREATE_HOST_VO_FOR_DIRECT_CONNECT) { - result = adapter.createHostVOForDirectConnectAgent((HostVO) args[0], (StartupCommand[]) args[1], (ServerResource) args[2], - (Map) args[3], (List) args[4]); - if (result != null && singleTaker) { - break; - } - } else if (event == ResourceStateAdapter.Event.DELETE_HOST) { - try { - result = adapter.deleteHost((HostVO) args[0], (Boolean) args[1], (Boolean) args[2]); - if (result != null) { - break; - } - } catch (UnableDeleteHostException e) { - s_logger.debug("Adapter " + adapter.getName() + " says unable to delete host", e); - result = new ResourceStateAdapter.DeleteHostAnswer(false, true); - } - } else { - throw new CloudRuntimeException("Unknown resource state event:" + event); - } - } - return result; - } - } + private Object dispatchToStateAdapters(ResourceStateAdapter.Event event, boolean singleTaker, Object... args) { + synchronized (_resourceStateAdapters) { + Iterator it = _resourceStateAdapters.entrySet().iterator(); + Object result = null; + while (it.hasNext()) { + Map.Entry item = (Map.Entry) it.next(); + ResourceStateAdapter adapter = item.getValue(); - @Override - public void checkCIDR(HostPodVO pod, DataCenterVO dc, String serverPrivateIP, String serverPrivateNetmask) throws IllegalArgumentException { - if (serverPrivateIP == null) { - return; - } - // Get the CIDR address and CIDR size - String cidrAddress = pod.getCidrAddress(); - long cidrSize = pod.getCidrSize(); + String msg = new String("Dispatching resource state event " + event + " to " + item.getKey()); + s_logger.debug(msg); - // If the server's private IP address is not in the same subnet as the - // pod's CIDR, return false - String cidrSubnet = NetUtils.getCidrSubNet(cidrAddress, cidrSize); - String serverSubnet = NetUtils.getSubNet(serverPrivateIP, serverPrivateNetmask); - if (!cidrSubnet.equals(serverSubnet)) { - s_logger.warn("The private ip address of the server (" + serverPrivateIP + ") is not compatible with the CIDR of pod: " + pod.getName() - + " and zone: " + dc.getName()); - throw new IllegalArgumentException("The private ip address of the server (" + serverPrivateIP + ") is not compatible with the CIDR of pod: " - + pod.getName() + " and zone: " + dc.getName()); - } - - // If the server's private netmask is less inclusive than the pod's CIDR - // netmask, return false - String cidrNetmask = NetUtils.getCidrSubNet("255.255.255.255", cidrSize); - long cidrNetmaskNumeric = NetUtils.ip2Long(cidrNetmask); - long serverNetmaskNumeric = NetUtils.ip2Long(serverPrivateNetmask); - if (serverNetmaskNumeric > cidrNetmaskNumeric) { - throw new IllegalArgumentException("The private ip address of the server (" + serverPrivateIP + ") is not compatible with the CIDR of pod: " - + pod.getName() + " and zone: " + dc.getName()); - } - - } - - private boolean checkCIDR(HostPodVO pod, String serverPrivateIP, String serverPrivateNetmask) { - if (serverPrivateIP == null) { - return true; - } - // Get the CIDR address and CIDR size - String cidrAddress = pod.getCidrAddress(); - long cidrSize = pod.getCidrSize(); - - // If the server's private IP address is not in the same subnet as the - // pod's CIDR, return false - String cidrSubnet = NetUtils.getCidrSubNet(cidrAddress, cidrSize); - String serverSubnet = NetUtils.getSubNet(serverPrivateIP, serverPrivateNetmask); - if (!cidrSubnet.equals(serverSubnet)) { - return false; - } - - // If the server's private netmask is less inclusive than the pod's CIDR - // netmask, return false - String cidrNetmask = NetUtils.getCidrSubNet("255.255.255.255", cidrSize); - long cidrNetmaskNumeric = NetUtils.ip2Long(cidrNetmask); - long serverNetmaskNumeric = NetUtils.ip2Long(serverPrivateNetmask); - if (serverNetmaskNumeric > cidrNetmaskNumeric) { - return false; - } - return true; - } - - protected HostVO createHostVO(StartupCommand[] cmds, ServerResource resource, Map details, List hostTags, - ResourceStateAdapter.Event stateEvent) { - StartupCommand startup = cmds[0]; - HostVO host = findHostByGuid(startup.getGuid()); - boolean isNew = false; - if (host == null) { - host = findHostByGuid(startup.getGuidWithoutResource()); - } - if (host == null) { - host = new HostVO(startup.getGuid()); - isNew = true; - } - - String dataCenter = startup.getDataCenter(); - String pod = startup.getPod(); - String cluster = startup.getCluster(); - - if (pod != null && dataCenter != null && pod.equalsIgnoreCase("default") && dataCenter.equalsIgnoreCase("default")) { - List pods = _podDao.listAllIncludingRemoved(); - for (HostPodVO hpv : pods) { - if (checkCIDR(hpv, startup.getPrivateIpAddress(), startup.getPrivateNetmask())) { - pod = hpv.getName(); - dataCenter = _dcDao.findById(hpv.getDataCenterId()).getName(); - break; - } - } - } - - long dcId = -1; - DataCenterVO dc = _dcDao.findByName(dataCenter); - if (dc == null) { - try { - dcId = Long.parseLong(dataCenter); - dc = _dcDao.findById(dcId); - } catch (final NumberFormatException e) { - } - } - if (dc == null) { - throw new IllegalArgumentException("Host " + startup.getPrivateIpAddress() + " sent incorrect data center: " + dataCenter); - } - dcId = dc.getId(); - - HostPodVO p = _podDao.findByName(pod, dcId); - if (p == null) { - try { - final long podId = Long.parseLong(pod); - p = _podDao.findById(podId); - } catch (final NumberFormatException e) { - } - } - /* - * ResourceStateAdapter is responsible for throwing Exception if Pod is - * null and non-null is required. for example, XcpServerDiscoever. - * Others, like PxeServer, ExternalFireware don't require Pod - */ - Long podId = (p == null ? null : p.getId()); - - Long clusterId = null; - if (cluster != null) { - try { - clusterId = Long.valueOf(cluster); - } catch (NumberFormatException e) { - ClusterVO c = _clusterDao.findBy(cluster, podId); - if (c == null) { - c = new ClusterVO(dcId, podId, cluster); - c = _clusterDao.persist(c); - } - clusterId = c.getId(); - } - } - - host.setDataCenterId(dc.getId()); - host.setPodId(podId); - host.setClusterId(clusterId); - host.setPrivateIpAddress(startup.getPrivateIpAddress()); - host.setPrivateNetmask(startup.getPrivateNetmask()); - host.setPrivateMacAddress(startup.getPrivateMacAddress()); - host.setPublicIpAddress(startup.getPublicIpAddress()); - host.setPublicMacAddress(startup.getPublicMacAddress()); - host.setPublicNetmask(startup.getPublicNetmask()); - host.setStorageIpAddress(startup.getStorageIpAddress()); - host.setStorageMacAddress(startup.getStorageMacAddress()); - host.setStorageNetmask(startup.getStorageNetmask()); - host.setVersion(startup.getVersion()); - host.setName(startup.getName()); - host.setManagementServerId(_nodeId); - host.setStorageUrl(startup.getIqn()); - host.setLastPinged(System.currentTimeMillis() >> 10); - host.setHostTags(hostTags); - host.setDetails(details); - if (startup.getStorageIpAddressDeux() != null) { - host.setStorageIpAddressDeux(startup.getStorageIpAddressDeux()); - host.setStorageMacAddressDeux(startup.getStorageMacAddressDeux()); - host.setStorageNetmaskDeux(startup.getStorageNetmaskDeux()); - } - if (resource != null) { - /* null when agent is connected agent */ - host.setResource(resource.getClass().getName()); - } - - host = (HostVO) dispatchToStateAdapters(stateEvent, true, host, cmds, resource, details, hostTags); - if (host == null) { - throw new CloudRuntimeException("No resource state adapter response"); - } - - if (isNew) { - host = _hostDao.persist(host); - } else { - _hostDao.update(host.getId(), host); - } - - try { - resourceStateTransitTo(host, ResourceState.Event.InternalCreated, _nodeId); - /* Agent goes to Connecting status */ - _agentMgr.agentStatusTransitTo(host, Status.Event.AgentConnected, _nodeId); - } catch (Exception e) { - s_logger.debug("Cannot transmit host " + host.getId() + " to Creating state", e); - _agentMgr.agentStatusTransitTo(host, Status.Event.Error, _nodeId); - try { - resourceStateTransitTo(host, ResourceState.Event.Error, _nodeId); - } catch (NoTransitionException e1) { - s_logger.debug("Cannot transmit host " + host.getId() + "to Error state", e); + if (event == ResourceStateAdapter.Event.CREATE_HOST_VO_FOR_CONNECTED) { + result = adapter.createHostVOForConnectedAgent((HostVO) args[0], (StartupCommand[]) args[1]); + if (result != null && singleTaker) { + break; + } + } else if (event == ResourceStateAdapter.Event.CREATE_HOST_VO_FOR_DIRECT_CONNECT) { + result = adapter.createHostVOForDirectConnectAgent((HostVO) args[0], (StartupCommand[]) args[1], (ServerResource) args[2], + (Map) args[3], (List) args[4]); + if (result != null && singleTaker) { + break; + } + } else if (event == ResourceStateAdapter.Event.DELETE_HOST) { + try { + result = adapter.deleteHost((HostVO) args[0], (Boolean) args[1], (Boolean) args[2]); + if (result != null) { + break; + } + } catch (UnableDeleteHostException e) { + s_logger.debug("Adapter " + adapter.getName() + " says unable to delete host", e); + result = new ResourceStateAdapter.DeleteHostAnswer(false, true); + } + } else { + throw new CloudRuntimeException("Unknown resource state event:" + event); + } } - } - - return host; - } - - private Host createHostAndAgent(ServerResource resource, Map details, boolean old, List hostTags, - boolean forRebalance) { - HostVO host = null; - AgentAttache attache = null; - StartupCommand[] cmds = null; - try { - cmds = resource.initialize(); - if (cmds == null) { - s_logger.info("Unable to fully initialize the agent because no StartupCommands are returned"); - return null; - } + return result; + } + } - if (s_logger.isDebugEnabled()) { - new Request(-1l, -1l, cmds, true, false).logD("Startup request from directly connected host: ", true); - } + @Override + public void checkCIDR(HostPodVO pod, DataCenterVO dc, String serverPrivateIP, String serverPrivateNetmask) throws IllegalArgumentException { + if (serverPrivateIP == null) { + return; + } + // Get the CIDR address and CIDR size + String cidrAddress = pod.getCidrAddress(); + long cidrSize = pod.getCidrSize(); - if (old) { - StartupCommand firstCmd = cmds[0]; - host = findHostByGuid(firstCmd.getGuid()); - if (host == null) { - host = findHostByGuid(firstCmd.getGuidWithoutResource()); - } - if (host != null && host.getRemoved() == null) { - s_logger.debug("Found the host " + host.getId() + " by guid: " + firstCmd.getGuid() + ", old host reconnected as new"); - return null; - } - } + // If the server's private IP address is not in the same subnet as the + // pod's CIDR, return false + String cidrSubnet = NetUtils.getCidrSubNet(cidrAddress, cidrSize); + String serverSubnet = NetUtils.getSubNet(serverPrivateIP, serverPrivateNetmask); + if (!cidrSubnet.equals(serverSubnet)) { + s_logger.warn("The private ip address of the server (" + serverPrivateIP + ") is not compatible with the CIDR of pod: " + pod.getName() + + " and zone: " + dc.getName()); + throw new IllegalArgumentException("The private ip address of the server (" + serverPrivateIP + ") is not compatible with the CIDR of pod: " + + pod.getName() + " and zone: " + dc.getName()); + } - host = createHostVO(cmds, resource, details, hostTags, ResourceStateAdapter.Event.CREATE_HOST_VO_FOR_DIRECT_CONNECT); - if (host != null) { - attache = _agentMgr.handleDirectConnectAgent(host, cmds, resource, forRebalance); - /* reload myself from database */ - host = _hostDao.findById(host.getId()); - } - } catch (Exception e) { - s_logger.warn("Unable to connect due to ", e); - } finally { - if (attache == null) { - if (cmds != null) { - resource.disconnected(); - } + // If the server's private netmask is less inclusive than the pod's CIDR + // netmask, return false + String cidrNetmask = NetUtils.getCidrSubNet("255.255.255.255", cidrSize); + long cidrNetmaskNumeric = NetUtils.ip2Long(cidrNetmask); + long serverNetmaskNumeric = NetUtils.ip2Long(serverPrivateNetmask); + if (serverNetmaskNumeric > cidrNetmaskNumeric) { + throw new IllegalArgumentException("The private ip address of the server (" + serverPrivateIP + ") is not compatible with the CIDR of pod: " + + pod.getName() + " and zone: " + dc.getName()); + } - if (host != null) { - /* Change agent status to Alert */ - _agentMgr.agentStatusTransitTo(host, Status.Event.AgentDisconnected, _nodeId); - /* Don't change resource state here since HostVO is already in database, which means resource state has had an appropriate value*/ - } - } - } + } + + private boolean checkCIDR(HostPodVO pod, String serverPrivateIP, String serverPrivateNetmask) { + if (serverPrivateIP == null) { + return true; + } + // Get the CIDR address and CIDR size + String cidrAddress = pod.getCidrAddress(); + long cidrSize = pod.getCidrSize(); + + // If the server's private IP address is not in the same subnet as the + // pod's CIDR, return false + String cidrSubnet = NetUtils.getCidrSubNet(cidrAddress, cidrSize); + String serverSubnet = NetUtils.getSubNet(serverPrivateIP, serverPrivateNetmask); + if (!cidrSubnet.equals(serverSubnet)) { + return false; + } + + // If the server's private netmask is less inclusive than the pod's CIDR + // netmask, return false + String cidrNetmask = NetUtils.getCidrSubNet("255.255.255.255", cidrSize); + long cidrNetmaskNumeric = NetUtils.ip2Long(cidrNetmask); + long serverNetmaskNumeric = NetUtils.ip2Long(serverPrivateNetmask); + if (serverNetmaskNumeric > cidrNetmaskNumeric) { + return false; + } + return true; + } + + protected HostVO createHostVO(StartupCommand[] cmds, ServerResource resource, Map details, List hostTags, + ResourceStateAdapter.Event stateEvent) { + StartupCommand startup = cmds[0]; + HostVO host = findHostByGuid(startup.getGuid()); + boolean isNew = false; + if (host == null) { + host = findHostByGuid(startup.getGuidWithoutResource()); + } + if (host == null) { + host = new HostVO(startup.getGuid()); + isNew = true; + } + + String dataCenter = startup.getDataCenter(); + String pod = startup.getPod(); + String cluster = startup.getCluster(); + + if (pod != null && dataCenter != null && pod.equalsIgnoreCase("default") && dataCenter.equalsIgnoreCase("default")) { + List pods = _podDao.listAllIncludingRemoved(); + for (HostPodVO hpv : pods) { + if (checkCIDR(hpv, startup.getPrivateIpAddress(), startup.getPrivateNetmask())) { + pod = hpv.getName(); + dataCenter = _dcDao.findById(hpv.getDataCenterId()).getName(); + break; + } + } + } + + long dcId = -1; + DataCenterVO dc = _dcDao.findByName(dataCenter); + if (dc == null) { + try { + dcId = Long.parseLong(dataCenter); + dc = _dcDao.findById(dcId); + } catch (final NumberFormatException e) { + } + } + if (dc == null) { + throw new IllegalArgumentException("Host " + startup.getPrivateIpAddress() + " sent incorrect data center: " + dataCenter); + } + dcId = dc.getId(); + + HostPodVO p = _podDao.findByName(pod, dcId); + if (p == null) { + try { + final long podId = Long.parseLong(pod); + p = _podDao.findById(podId); + } catch (final NumberFormatException e) { + } + } + /* + * ResourceStateAdapter is responsible for throwing Exception if Pod is + * null and non-null is required. for example, XcpServerDiscoever. + * Others, like PxeServer, ExternalFireware don't require Pod + */ + Long podId = (p == null ? null : p.getId()); + + Long clusterId = null; + if (cluster != null) { + try { + clusterId = Long.valueOf(cluster); + } catch (NumberFormatException e) { + ClusterVO c = _clusterDao.findBy(cluster, podId); + if (c == null) { + c = new ClusterVO(dcId, podId, cluster); + c = _clusterDao.persist(c); + } + clusterId = c.getId(); + } + } + + host.setDataCenterId(dc.getId()); + host.setPodId(podId); + host.setClusterId(clusterId); + host.setPrivateIpAddress(startup.getPrivateIpAddress()); + host.setPrivateNetmask(startup.getPrivateNetmask()); + host.setPrivateMacAddress(startup.getPrivateMacAddress()); + host.setPublicIpAddress(startup.getPublicIpAddress()); + host.setPublicMacAddress(startup.getPublicMacAddress()); + host.setPublicNetmask(startup.getPublicNetmask()); + host.setStorageIpAddress(startup.getStorageIpAddress()); + host.setStorageMacAddress(startup.getStorageMacAddress()); + host.setStorageNetmask(startup.getStorageNetmask()); + host.setVersion(startup.getVersion()); + host.setName(startup.getName()); + host.setManagementServerId(_nodeId); + host.setStorageUrl(startup.getIqn()); + host.setLastPinged(System.currentTimeMillis() >> 10); + host.setHostTags(hostTags); + host.setDetails(details); + if (startup.getStorageIpAddressDeux() != null) { + host.setStorageIpAddressDeux(startup.getStorageIpAddressDeux()); + host.setStorageMacAddressDeux(startup.getStorageMacAddressDeux()); + host.setStorageNetmaskDeux(startup.getStorageNetmaskDeux()); + } + if (resource != null) { + /* null when agent is connected agent */ + host.setResource(resource.getClass().getName()); + } + + host = (HostVO) dispatchToStateAdapters(stateEvent, true, host, cmds, resource, details, hostTags); + if (host == null) { + throw new CloudRuntimeException("No resource state adapter response"); + } + + if (isNew) { + host = _hostDao.persist(host); + } else { + _hostDao.update(host.getId(), host); + } + + try { + resourceStateTransitTo(host, ResourceState.Event.InternalCreated, _nodeId); + /* Agent goes to Connecting status */ + _agentMgr.agentStatusTransitTo(host, Status.Event.AgentConnected, _nodeId); + } catch (Exception e) { + s_logger.debug("Cannot transmit host " + host.getId() + " to Creating state", e); + _agentMgr.agentStatusTransitTo(host, Status.Event.Error, _nodeId); + try { + resourceStateTransitTo(host, ResourceState.Event.Error, _nodeId); + } catch (NoTransitionException e1) { + s_logger.debug("Cannot transmit host " + host.getId() + "to Error state", e); + } + } + + return host; + } + + private Host createHostAndAgent(ServerResource resource, Map details, boolean old, List hostTags, + boolean forRebalance) { + HostVO host = null; + AgentAttache attache = null; + StartupCommand[] cmds = null; + + try { + cmds = resource.initialize(); + if (cmds == null) { + s_logger.info("Unable to fully initialize the agent because no StartupCommands are returned"); + return null; + } + + if (s_logger.isDebugEnabled()) { + new Request(-1l, -1l, cmds, true, false).logD("Startup request from directly connected host: ", true); + } + + if (old) { + StartupCommand firstCmd = cmds[0]; + host = findHostByGuid(firstCmd.getGuid()); + if (host == null) { + host = findHostByGuid(firstCmd.getGuidWithoutResource()); + } + if (host != null && host.getRemoved() == null) { + s_logger.debug("Found the host " + host.getId() + " by guid: " + firstCmd.getGuid() + ", old host reconnected as new"); + return null; + } + } + + host = createHostVO(cmds, resource, details, hostTags, ResourceStateAdapter.Event.CREATE_HOST_VO_FOR_DIRECT_CONNECT); + if (host != null) { + attache = _agentMgr.handleDirectConnectAgent(host, cmds, resource, forRebalance); + /* reload myself from database */ + host = _hostDao.findById(host.getId()); + } + } catch (Exception e) { + s_logger.warn("Unable to connect due to ", e); + } finally { + if (attache == null) { + if (cmds != null) { + resource.disconnected(); + } + + if (host != null) { + /* Change agent status to Alert */ + _agentMgr.agentStatusTransitTo(host, Status.Event.AgentDisconnected, _nodeId); + /* Don't change resource state here since HostVO is already in database, which means resource state has had an appropriate value*/ + } + } + } + + return host; + } + + @Override + public Host createHostAndAgent(Long hostId, ServerResource resource, Map details, boolean old, List hostTags, boolean forRebalance) { + _agentMgr.tapLoadingAgents(hostId, TapAgentsAction.Add); + Host host = createHostAndAgent(resource, details, old, hostTags, forRebalance); + _agentMgr.tapLoadingAgents(hostId, TapAgentsAction.Del); + return host; + } - return host; - } - - @Override - public Host createHostAndAgent(Long hostId, ServerResource resource, Map details, boolean old, List hostTags, boolean forRebalance) { - _agentMgr.tapLoadingAgents(hostId, TapAgentsAction.Add); - Host host = createHostAndAgent(resource, details, old, hostTags, forRebalance); - _agentMgr.tapLoadingAgents(hostId, TapAgentsAction.Del); - return host; - } - @Override public Host addHost(long zoneId, ServerResource resource, Type hostType, Map hostDetails) { // Check if the zone exists in the system if (_dcDao.findById(zoneId) == null) { - throw new InvalidParameterValueException("Can't find zone with id " + zoneId); + throw new InvalidParameterValueException("Can't find zone by id", null); } Map details = hostDetails; @@ -1759,12 +1758,12 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma return createHostAndAgent(resource, hostDetails, true, null, false); } - + @Override public HostVO createHostVOForConnectedAgent(StartupCommand[] cmds) { return createHostVO(cmds, null, null, null, ResourceStateAdapter.Event.CREATE_HOST_VO_FOR_CONNECTED); } - + private void checkIPConflicts(HostPodVO pod, DataCenterVO dc, String serverPrivateIP, String serverPrivateNetmask, String serverPublicIP, String serverPublicNetmask) { // If the server's private IP is the same as is public IP, this host has // a host-only private network. Don't check for conflicts with the @@ -1797,7 +1796,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma } } } - + @Override public HostVO fillRoutingHostVO(HostVO host, StartupRoutingCommand ssCmd, HypervisorType hyType, Map details, List hostTags) { if (host.getPodId() == null) { @@ -1810,7 +1809,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma throw new IllegalArgumentException("Can't add host whose hypervisor type is: " + hyType + " into cluster: " + clusterVO.getId() + " whose hypervisor type is: " + clusterVO.getHypervisorType()); } - + final Map hostDetails = ssCmd.getHostDetails(); if (hostDetails != null) { if (details != null) { @@ -1819,7 +1818,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma details = hostDetails; } } - + HostPodVO pod = _podDao.findById(host.getPodId()); DataCenterVO dc = _dcDao.findById(host.getDataCenterId()); checkIPConflicts(pod, dc, ssCmd.getPrivateIpAddress(), ssCmd.getPublicIpAddress(), ssCmd.getPublicIpAddress(), ssCmd.getPublicNetmask()); @@ -1832,109 +1831,109 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma host.setHypervisorType(hyType); return host; } - - @Override - public void deleteRoutingHost(HostVO host, boolean isForced, boolean forceDestroyStorage) throws UnableDeleteHostException { - if (host.getType() != Host.Type.Routing) { - throw new CloudRuntimeException("Non-Routing host gets in deleteRoutingHost, id is " + host.getId()); - } - if (s_logger.isDebugEnabled()) { - s_logger.debug("Deleting Host: " + host.getId() + " Guid:" + host.getGuid()); - } + @Override + public void deleteRoutingHost(HostVO host, boolean isForced, boolean forceDestroyStorage) throws UnableDeleteHostException { + if (host.getType() != Host.Type.Routing) { + throw new CloudRuntimeException("Non-Routing host gets in deleteRoutingHost, id is " + host.getId()); + } - User caller = _accountMgr.getActiveUser(UserContext.current().getCallerUserId()); - if (forceDestroyStorage) { - // put local storage into mainenance mode, will set all the VMs on - // this local storage into stopped state - StoragePool storagePool = _storageMgr.findLocalStorageOnHost(host.getId()); - if (storagePool != null) { - if (storagePool.getStatus() == StoragePoolStatus.Up || storagePool.getStatus() == StoragePoolStatus.ErrorInMaintenance) { - try { - storagePool = _storageSvr.preparePrimaryStorageForMaintenance(storagePool.getId()); - if (storagePool == null) { - s_logger.debug("Failed to set primary storage into maintenance mode"); - throw new UnableDeleteHostException("Failed to set primary storage into maintenance mode"); - } - } catch (Exception e) { - s_logger.debug("Failed to set primary storage into maintenance mode, due to: " + e.toString()); - throw new UnableDeleteHostException("Failed to set primary storage into maintenance mode, due to: " + e.toString()); - } - } + if (s_logger.isDebugEnabled()) { + s_logger.debug("Deleting Host: " + host.getId() + " Guid:" + host.getGuid()); + } - List vmsOnLocalStorage = _storageMgr.listByStoragePool(storagePool.getId()); - for (VMInstanceVO vm : vmsOnLocalStorage) { - try { - if (!_vmMgr.destroy(vm, caller, _accountMgr.getAccount(vm.getAccountId()))) { - String errorMsg = "There was an error Destory the vm: " + vm + " as a part of hostDelete id=" + host.getId(); - s_logger.warn(errorMsg); - throw new UnableDeleteHostException(errorMsg); - } - } catch (Exception e) { - String errorMsg = "There was an error Destory the vm: " + vm + " as a part of hostDelete id=" + host.getId(); - s_logger.debug(errorMsg, e); - throw new UnableDeleteHostException(errorMsg + "," + e.getMessage()); - } - } - } - } else { - // Check if there are vms running/starting/stopping on this host - List vms = _vmDao.listByHostId(host.getId()); - if (!vms.isEmpty()) { - if (isForced) { - // Stop HA disabled vms and HA enabled vms in Stopping state - // Restart HA enabled vms - for (VMInstanceVO vm : vms) { - if (!vm.isHaEnabled() || vm.getState() == State.Stopping) { - s_logger.debug("Stopping vm: " + vm + " as a part of deleteHost id=" + host.getId()); - try { - if (!_vmMgr.advanceStop(vm, true, caller, _accountMgr.getAccount(vm.getAccountId()))) { - String errorMsg = "There was an error stopping the vm: " + vm + " as a part of hostDelete id=" + host.getId(); - s_logger.warn(errorMsg); - throw new UnableDeleteHostException(errorMsg); - } - } catch (Exception e) { - String errorMsg = "There was an error stopping the vm: " + vm + " as a part of hostDelete id=" + host.getId(); - s_logger.debug(errorMsg, e); - throw new UnableDeleteHostException(errorMsg + "," + e.getMessage()); - } - } else if (vm.isHaEnabled() && (vm.getState() == State.Running || vm.getState() == State.Starting)) { - s_logger.debug("Scheduling restart for vm: " + vm + " " + vm.getState() + " on the host id=" + host.getId()); - _haMgr.scheduleRestart(vm, false); - } - } - } else { - throw new UnableDeleteHostException("Unable to delete the host as there are vms in " + vms.get(0).getState() - + " state using this host and isForced=false specified"); - } - } - } - } - - private boolean restartAgent(HostVO host) { - //for kvm, need to log into kvm host, restart cloud-agent - _hostDao.loadDetails(host); - String password = host.getDetail("password"); - String username = host.getDetail("username"); - if (password == null || username == null) { - s_logger.debug("Can't find password/username"); - return false; - } - com.trilead.ssh2.Connection connection = SSHCmdHelper.acquireAuthorizedConnection(host.getPrivateIpAddress(), 22, username, password); - if (connection == null) { - s_logger.debug("Failed to connect to host: " + host.getPrivateIpAddress()); - return false; - } + User caller = _accountMgr.getActiveUser(UserContext.current().getCallerUserId()); + if (forceDestroyStorage) { + // put local storage into mainenance mode, will set all the VMs on + // this local storage into stopped state + StoragePool storagePool = _storageMgr.findLocalStorageOnHost(host.getId()); + if (storagePool != null) { + if (storagePool.getStatus() == StoragePoolStatus.Up || storagePool.getStatus() == StoragePoolStatus.ErrorInMaintenance) { + try { + storagePool = _storageSvr.preparePrimaryStorageForMaintenance(storagePool.getId()); + if (storagePool == null) { + s_logger.debug("Failed to set primary storage into maintenance mode"); + throw new UnableDeleteHostException("Failed to set primary storage into maintenance mode"); + } + } catch (Exception e) { + s_logger.debug("Failed to set primary storage into maintenance mode, due to: " + e.toString()); + throw new UnableDeleteHostException("Failed to set primary storage into maintenance mode, due to: " + e.toString()); + } + } + + List vmsOnLocalStorage = _storageMgr.listByStoragePool(storagePool.getId()); + for (VMInstanceVO vm : vmsOnLocalStorage) { + try { + if (!_vmMgr.destroy(vm, caller, _accountMgr.getAccount(vm.getAccountId()))) { + String errorMsg = "There was an error Destory the vm: " + vm + " as a part of hostDelete id=" + host.getId(); + s_logger.warn(errorMsg); + throw new UnableDeleteHostException(errorMsg); + } + } catch (Exception e) { + String errorMsg = "There was an error Destory the vm: " + vm + " as a part of hostDelete id=" + host.getId(); + s_logger.debug(errorMsg, e); + throw new UnableDeleteHostException(errorMsg + "," + e.getMessage()); + } + } + } + } else { + // Check if there are vms running/starting/stopping on this host + List vms = _vmDao.listByHostId(host.getId()); + if (!vms.isEmpty()) { + if (isForced) { + // Stop HA disabled vms and HA enabled vms in Stopping state + // Restart HA enabled vms + for (VMInstanceVO vm : vms) { + if (!vm.isHaEnabled() || vm.getState() == State.Stopping) { + s_logger.debug("Stopping vm: " + vm + " as a part of deleteHost id=" + host.getId()); + try { + if (!_vmMgr.advanceStop(vm, true, caller, _accountMgr.getAccount(vm.getAccountId()))) { + String errorMsg = "There was an error stopping the vm: " + vm + " as a part of hostDelete id=" + host.getId(); + s_logger.warn(errorMsg); + throw new UnableDeleteHostException(errorMsg); + } + } catch (Exception e) { + String errorMsg = "There was an error stopping the vm: " + vm + " as a part of hostDelete id=" + host.getId(); + s_logger.debug(errorMsg, e); + throw new UnableDeleteHostException(errorMsg + "," + e.getMessage()); + } + } else if (vm.isHaEnabled() && (vm.getState() == State.Running || vm.getState() == State.Starting)) { + s_logger.debug("Scheduling restart for vm: " + vm + " " + vm.getState() + " on the host id=" + host.getId()); + _haMgr.scheduleRestart(vm, false); + } + } + } else { + throw new UnableDeleteHostException("Unable to delete the host as there are vms in " + vms.get(0).getState() + + " state using this host and isForced=false specified"); + } + } + } + } + + private boolean restartAgent(HostVO host) { + //for kvm, need to log into kvm host, restart cloud-agent + _hostDao.loadDetails(host); + String password = host.getDetail("password"); + String username = host.getDetail("username"); + if (password == null || username == null) { + s_logger.debug("Can't find password/username"); + return false; + } + com.trilead.ssh2.Connection connection = SSHCmdHelper.acquireAuthorizedConnection(host.getPrivateIpAddress(), 22, username, password); + if (connection == null) { + s_logger.debug("Failed to connect to host: " + host.getPrivateIpAddress()); + return false; + } + + try { + SSHCmdHelper.sshExecuteCmdOneShot(connection, "service cloud-agent restart"); + return true; + } catch (sshException e) { + return false; + } + } - try { - SSHCmdHelper.sshExecuteCmdOneShot(connection, "service cloud-agent restart"); - return true; - } catch (sshException e) { - return false; - } - } - private boolean doCancelMaintenance(long hostId) { HostVO host; host = _hostDao.findById(hostId); @@ -1942,12 +1941,12 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma s_logger.warn("Unable to find host " + hostId); return true; } - + /*TODO: think twice about returning true or throwing out exception, I really prefer to exception that always exposes bugs */ if (host.getResourceState() != ResourceState.PrepareForMaintenance && host.getResourceState() != ResourceState.Maintenance && host.getResourceState() != ResourceState.ErrorInMaintenance) { throw new CloudRuntimeException("Cannot perform cancelMaintenance when resource state is " + host.getResourceState() + ", hostId = " + hostId); } - + /*TODO: move to listener */ _haMgr.cancelScheduledMigrations(host); List vms = _haMgr.findTakenMigrationWork(); @@ -1957,23 +1956,23 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma return false; } } - - try { - resourceStateTransitTo(host, ResourceState.Event.AdminCancelMaintenance, _nodeId); - _agentMgr.pullAgentOutMaintenance(hostId); - - //for kvm, need to log into kvm host, restart cloud-agent - if (host.getHypervisorType() == HypervisorType.KVM) { - restartAgent(host); - } - - return true; - } catch (NoTransitionException e) { - s_logger.debug("Cannot transmit host " + host.getId() + "to Enabled state", e); - return false; - } + + try { + resourceStateTransitTo(host, ResourceState.Event.AdminCancelMaintenance, _nodeId); + _agentMgr.pullAgentOutMaintenance(hostId); + + //for kvm, need to log into kvm host, restart cloud-agent + if (host.getHypervisorType() == HypervisorType.KVM) { + restartAgent(host); + } + + return true; + } catch (NoTransitionException e) { + s_logger.debug("Cannot transmit host " + host.getId() + "to Enabled state", e); + return false; + } } - + private boolean cancelMaintenance(long hostId) { try { Boolean result = _clusterMgr.propagateResourceEvent(hostId, ResourceState.Event.AdminCancelMaintenance); @@ -1984,10 +1983,10 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma } catch (AgentUnavailableException e) { return false; } - + return doCancelMaintenance(hostId); } - + @Override public boolean executeUserRequest(long hostId, ResourceState.Event event) throws AgentUnavailableException { if (event == ResourceState.Event.AdminAskMaintenace) { @@ -2005,23 +2004,23 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma throw new CloudRuntimeException("Received an resource event we are not handling now, " + event); } } - - private boolean doUmanageHost(long hostId) { - HostVO host = _hostDao.findById(hostId); - if (host == null) { - s_logger.debug("Cannot find host " + hostId + ", assuming it has been deleted, skip umanage"); - return true; - } - - if (host.getHypervisorType() == HypervisorType.KVM) { - MaintainAnswer answer = (MaintainAnswer) _agentMgr.easySend(hostId, new MaintainCommand()); - } - _agentMgr.disconnectWithoutInvestigation(hostId, Event.ShutdownRequested); - return true; + private boolean doUmanageHost(long hostId) { + HostVO host = _hostDao.findById(hostId); + if (host == null) { + s_logger.debug("Cannot find host " + hostId + ", assuming it has been deleted, skip umanage"); + return true; + } + + if (host.getHypervisorType() == HypervisorType.KVM) { + MaintainAnswer answer = (MaintainAnswer) _agentMgr.easySend(hostId, new MaintainCommand()); + } + + _agentMgr.disconnectWithoutInvestigation(hostId, Event.ShutdownRequested); + return true; } - - + + @Override public boolean umanageHost(long hostId) { try { @@ -2033,16 +2032,16 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma } catch (AgentUnavailableException e) { return false; } - + return doUmanageHost(hostId); } - + private boolean doUpdateHostPassword(long hostId) { AgentAttache attache = _agentMgr.findAttache(hostId); if (attache == null) { return false; } - + DetailVO nv = _hostDetailsDao.findDetail(hostId, ApiConstants.USERNAME); String username = nv.getValue(); nv = _hostDetailsDao.findDetail(hostId, ApiConstants.PASSWORD); @@ -2051,7 +2050,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma attache.updatePassword(cmd); return true; } - + @Override public boolean updateHostPassword(UpdateHostPasswordCmd cmd) { if (cmd.getClusterId() == null) { @@ -2063,7 +2062,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma } } catch (AgentUnavailableException e) { } - + return doUpdateHostPassword(cmd.getHostId()); } else { // get agents for the cluster @@ -2075,16 +2074,16 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma if (result != null) { return result; } - + doUpdateHostPassword(h.getId()); } catch (AgentUnavailableException e) { } } - + return true; } } - + @Override public boolean maintenanceFailed(long hostId) { HostVO host = _hostDao.findById(hostId); @@ -2103,140 +2102,140 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma } } - @Override + @Override public List findDirectlyConnectedHosts() { - /* The resource column is not null for direct connected resource */ - SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); - sc.addAnd(sc.getEntity().getResource(), Op.NNULL); - sc.addAnd(sc.getEntity().getResourceState(), Op.NIN, ResourceState.Disabled); - return sc.list(); + /* The resource column is not null for direct connected resource */ + SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); + sc.addAnd(sc.getEntity().getResource(), Op.NNULL); + sc.addAnd(sc.getEntity().getResourceState(), Op.NIN, ResourceState.Disabled); + return sc.list(); } - @Override + @Override public List listAllUpAndEnabledHosts(Type type, Long clusterId, Long podId, long dcId) { - SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); - if (type != null) { - sc.addAnd(sc.getEntity().getType(), Op.EQ, type); - } - if (clusterId != null) { - sc.addAnd(sc.getEntity().getClusterId(), Op.EQ, clusterId); - } - if (podId != null) { - sc.addAnd(sc.getEntity().getPodId(), Op.EQ, podId); - } - sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); - sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up); - sc.addAnd(sc.getEntity().getResourceState(), Op.EQ, ResourceState.Enabled); - return sc.list(); + SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); + if (type != null) { + sc.addAnd(sc.getEntity().getType(), Op.EQ, type); + } + if (clusterId != null) { + sc.addAnd(sc.getEntity().getClusterId(), Op.EQ, clusterId); + } + if (podId != null) { + sc.addAnd(sc.getEntity().getPodId(), Op.EQ, podId); + } + sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); + sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up); + sc.addAnd(sc.getEntity().getResourceState(), Op.EQ, ResourceState.Enabled); + return sc.list(); } - - @Override + + @Override public List listAllUpAndEnabledNonHAHosts(Type type, Long clusterId, Long podId, long dcId) { - String haTag = _haMgr.getHaTag(); + String haTag = _haMgr.getHaTag(); return _hostDao.listAllUpAndEnabledNonHAHosts(type, clusterId, podId, dcId, haTag); } - - @Override - public List findHostByGuid(long dcId, String guid) { - SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); - sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); - sc.addAnd(sc.getEntity().getGuid(), Op.EQ, guid); - return sc.list(); - } - @Override + @Override + public List findHostByGuid(long dcId, String guid) { + SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); + sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); + sc.addAnd(sc.getEntity().getGuid(), Op.EQ, guid); + return sc.list(); + } + + @Override public List listAllHostsInCluster(long clusterId) { - SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); - sc.addAnd(sc.getEntity().getClusterId(), Op.EQ, clusterId); - return sc.list(); + SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); + sc.addAnd(sc.getEntity().getClusterId(), Op.EQ, clusterId); + return sc.list(); } - @Override + @Override public List listHostsInClusterByStatus(long clusterId, Status status) { - SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); - sc.addAnd(sc.getEntity().getClusterId(), Op.EQ, clusterId); - sc.addAnd(sc.getEntity().getStatus(), Op.EQ, status); - return sc.list(); + SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); + sc.addAnd(sc.getEntity().getClusterId(), Op.EQ, clusterId); + sc.addAnd(sc.getEntity().getStatus(), Op.EQ, status); + return sc.list(); } - @Override + @Override public List listAllUpAndEnabledHostsInOneZoneByType(Type type, long dcId) { - SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); - sc.addAnd(sc.getEntity().getType(), Op.EQ, type); - sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); - sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up); - sc.addAnd(sc.getEntity().getResourceState(), Op.EQ, ResourceState.Enabled); - return sc.list(); + SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); + sc.addAnd(sc.getEntity().getType(), Op.EQ, type); + sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); + sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up); + sc.addAnd(sc.getEntity().getResourceState(), Op.EQ, ResourceState.Enabled); + return sc.list(); } - @Override + @Override public List listAllNotInMaintenanceHostsInOneZone(Type type, Long dcId) { - SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); - if (dcId != null){ - sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); - } - sc.addAnd(sc.getEntity().getType(), Op.EQ, type); - sc.addAnd(sc.getEntity().getResourceState(), Op.NIN, ResourceState.Maintenance, ResourceState.ErrorInMaintenance, ResourceState.PrepareForMaintenance, ResourceState.Error); - return sc.list(); + SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); + if (dcId != null){ + sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); + } + sc.addAnd(sc.getEntity().getType(), Op.EQ, type); + sc.addAnd(sc.getEntity().getResourceState(), Op.NIN, ResourceState.Maintenance, ResourceState.ErrorInMaintenance, ResourceState.PrepareForMaintenance, ResourceState.Error); + return sc.list(); } - - @Override + + @Override public List listAllHostsInOneZoneByType(Type type, long dcId) { - SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); - sc.addAnd(sc.getEntity().getType(), Op.EQ, type); - sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); - return sc.list(); + SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); + sc.addAnd(sc.getEntity().getType(), Op.EQ, type); + sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); + return sc.list(); } - @Override + @Override public List listAllHostsInAllZonesByType(Type type) { - SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); - sc.addAnd(sc.getEntity().getType(), Op.EQ, type); - return sc.list(); + SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); + sc.addAnd(sc.getEntity().getType(), Op.EQ, type); + return sc.list(); } - @Override + @Override public List listAvailHypervisorInZone(Long hostId, Long zoneId) { - SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); - if (zoneId != null) { - sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, zoneId); - } - if (hostId != null) { - sc.addAnd(sc.getEntity().getId(), Op.EQ, hostId); - } - sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.Routing); - List hosts = sc.list(); - - List hypers = new ArrayList(5); + SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); + if (zoneId != null) { + sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, zoneId); + } + if (hostId != null) { + sc.addAnd(sc.getEntity().getId(), Op.EQ, hostId); + } + sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.Routing); + List hosts = sc.list(); + + List hypers = new ArrayList(5); for (HostVO host : hosts) { hypers.add(host.getHypervisorType()); } return hypers; } - @Override + @Override public HostVO findHostByGuid(String guid) { - SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); - sc.addAnd(sc.getEntity().getGuid(), Op.EQ, guid); - return sc.find(); + SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); + sc.addAnd(sc.getEntity().getGuid(), Op.EQ, guid); + return sc.find(); } - @Override + @Override public HostVO findHostByName(String name) { - SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); - sc.addAnd(sc.getEntity().getName(), Op.EQ, name); - return sc.find(); + SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); + sc.addAnd(sc.getEntity().getName(), Op.EQ, name); + return sc.find(); } - @Override + @Override public List listHostsByNameLike(String name) { - SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); - sc.addAnd(sc.getEntity().getName(), Op.LIKE, "%" + name + "%"); - return sc.list(); + SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); + sc.addAnd(sc.getEntity().getName(), Op.LIKE, "%" + name + "%"); + return sc.list(); } - @Override - public Pair findPod(VirtualMachineTemplate template, ServiceOfferingVO offering, DataCenterVO dc, long accountId, Set avoids) { + @Override + public Pair findPod(VirtualMachineTemplate template, ServiceOfferingVO offering, DataCenterVO dc, long accountId, Set avoids) { final Enumeration en = _podAllocators.enumeration(); while (en.hasMoreElements()) { final PodAllocator allocator = (PodAllocator) en.nextElement(); @@ -2246,70 +2245,70 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma } } return null; - } + } - @Override - public HostStats getHostStatistics(long hostId) { - Answer answer = _agentMgr.easySend(hostId, new GetHostStatsCommand(_hostDao.findById(hostId).getGuid(), _hostDao.findById(hostId).getName(), hostId)); + @Override + public HostStats getHostStatistics(long hostId) { + Answer answer = _agentMgr.easySend(hostId, new GetHostStatsCommand(_hostDao.findById(hostId).getGuid(), _hostDao.findById(hostId).getName(), hostId)); - if (answer != null && (answer instanceof UnsupportedAnswer)) { - return null; - } + if (answer != null && (answer instanceof UnsupportedAnswer)) { + return null; + } - if (answer == null || !answer.getResult()) { - String msg = "Unable to obtain host " + hostId + " statistics. "; - s_logger.warn(msg); - return null; - } else { + if (answer == null || !answer.getResult()) { + String msg = "Unable to obtain host " + hostId + " statistics. "; + s_logger.warn(msg); + return null; + } else { - // now construct the result object - if (answer instanceof GetHostStatsAnswer) { - return ((GetHostStatsAnswer) answer).getHostStats(); - } - } - return null; - } + // now construct the result object + if (answer instanceof GetHostStatsAnswer) { + return ((GetHostStatsAnswer) answer).getHostStats(); + } + } + return null; + } - @Override - public Long getGuestOSCategoryId(long hostId) { - HostVO host = _hostDao.findById(hostId); - if (host == null) { - return null; - } else { - _hostDao.loadDetails(host); - DetailVO detail = _hostDetailsDao.findDetail(hostId, "guest.os.category.id"); - if (detail == null) { - return null; - } else { - return Long.parseLong(detail.getValue()); - } - } - } + @Override + public Long getGuestOSCategoryId(long hostId) { + HostVO host = _hostDao.findById(hostId); + if (host == null) { + return null; + } else { + _hostDao.loadDetails(host); + DetailVO detail = _hostDetailsDao.findDetail(hostId, "guest.os.category.id"); + if (detail == null) { + return null; + } else { + return Long.parseLong(detail.getValue()); + } + } + } - @Override - public String getHostTags(long hostId) { - List hostTags = _hostTagsDao.gethostTags(hostId); - if (hostTags == null) { - return null; - } else { - return StringUtils.listToCsvTags(hostTags); - } - } + @Override + public String getHostTags(long hostId) { + List hostTags = _hostTagsDao.gethostTags(hostId); + if (hostTags == null) { + return null; + } else { + return StringUtils.listToCsvTags(hostTags); + } + } - @Override - public List listByDataCenter(long dcId) { - List pods = _podDao.listByDataCenterId(dcId); - ArrayList pcs = new ArrayList(); - for (HostPodVO pod : pods) { - List clusters = _clusterDao.listByPodId(pod.getId()); - if (clusters.size() == 0) { - pcs.add(new PodCluster(pod, null)); - } else { - for (ClusterVO cluster : clusters) { - pcs.add(new PodCluster(pod, cluster)); - } - } - } - return pcs; - } + @Override + public List listByDataCenter(long dcId) { + List pods = _podDao.listByDataCenterId(dcId); + ArrayList pcs = new ArrayList(); + for (HostPodVO pod : pods) { + List clusters = _clusterDao.listByPodId(pod.getId()); + if (clusters.size() == 0) { + pcs.add(new PodCluster(pod, null)); + } else { + for (ClusterVO cluster : clusters) { + pcs.add(new PodCluster(pod, cluster)); + } + } + } + return pcs; + } } diff --git a/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java b/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java index 0972c76e790..55e389e0f20 100755 --- a/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java +++ b/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java @@ -61,6 +61,7 @@ import com.cloud.user.AccountVO; import com.cloud.user.ResourceLimitService; import com.cloud.user.UserContext; import com.cloud.user.dao.AccountDao; +import com.cloud.utils.IdentityProxy; import com.cloud.utils.NumbersUtil; import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; @@ -371,7 +372,7 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager { try { resourceType = ResourceType.values()[type]; } catch (ArrayIndexOutOfBoundsException e) { - throw new InvalidParameterValueException("Please specify a valid resource type."); + throw new InvalidParameterValueException("Please specify a valid resource type.", null); } } @@ -482,7 +483,7 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager { if (max == null) { max = new Long(Resource.RESOURCE_UNLIMITED); } else if (max.longValue() < Resource.RESOURCE_UNLIMITED) { - throw new InvalidParameterValueException("Please specify either '-1' for an infinite limit, or a limit that is at least '0'."); + throw new InvalidParameterValueException("Please specify either '-1' for an infinite limit, or a limit that is at least '0'.", null); } // Map resource type @@ -494,7 +495,7 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager { } } if (resourceType == null) { - throw new InvalidParameterValueException("Please specify valid resource type"); + throw new InvalidParameterValueException("Please specify valid resource type", null); } } @@ -504,17 +505,17 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager { if (accountId != null) { Account account = _entityMgr.findById(Account.class, accountId); if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { - throw new InvalidParameterValueException("Can't update system account"); + throw new InvalidParameterValueException("Can't update system account", null); } //only Unlimited value is accepted if account is Root Admin if (_accountMgr.isRootAdmin(account.getType()) && max.shortValue() != ResourceLimit.RESOURCE_UNLIMITED) { - throw new InvalidParameterValueException("Only " + ResourceLimit.RESOURCE_UNLIMITED + " limit is supported for Root Admin accounts"); + throw new InvalidParameterValueException("Only " + ResourceLimit.RESOURCE_UNLIMITED + " limit is supported for Root Admin accounts", null); } if ((caller.getAccountId() == accountId.longValue()) && - (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || - caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN)) { + (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || + caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN)) { // If the admin is trying to update his own account, disallow. throw new PermissionDeniedException("Unable to update resource limit for his own account " + accountId + ", permission denied"); } @@ -546,8 +547,11 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager { DomainVO parentDomain = _domainDao.findById(parentDomainId); long parentMaximum = findCorrectResourceLimitForDomain(parentDomain, resourceType); if ((parentMaximum >= 0) && (max.longValue() > parentMaximum)) { - throw new InvalidParameterValueException("Domain " + domain.getName() + "(id: " + parentDomain.getId() + ") has maximum allowed resource limit " + parentMaximum + " for " + resourceType - + ", please specify a value less that or equal to " + parentMaximum); + List idList = new ArrayList(); + idList.add(new IdentityProxy(parentDomain, parentDomain.getId(), "domainId")); + throw new InvalidParameterValueException("Domain " + domain.getName() + " with specified domainId " + + "has maximum allowed resource limit " + parentMaximum + " for " + resourceType + + ", please specify a value less that or equal to " + parentMaximum, idList); } } ownerType = ResourceOwnerType.Domain; @@ -555,7 +559,7 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager { } if (ownerId == null) { - throw new InvalidParameterValueException("AccountId or domainId have to be specified in order to update resource limit"); + throw new InvalidParameterValueException("AccountId or domainId have to be specified in order to update resource limit", null); } ResourceLimitVO limit = _resourceLimitDao.findByOwnerIdAndType(ownerId, ownerType, resourceType); @@ -584,13 +588,13 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager { } } if (resourceType == null) { - throw new InvalidParameterValueException("Please specify valid resource type"); + throw new InvalidParameterValueException("Please specify valid resource type", null); } } DomainVO domain = _domainDao.findById(domainId); if (domain == null) { - throw new InvalidParameterValueException("Please specify a valid domain ID."); + throw new InvalidParameterValueException("Please specify a valid domain ID.", null); } _accountMgr.checkAccess(callerAccount, domain); @@ -734,7 +738,7 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager { } else if (type == Resource.ResourceType.network) { newCount = _networkDao.countNetworksUserCanCreate(accountId); } else { - throw new InvalidParameterValueException("Unsupported resource type " + type); + throw new InvalidParameterValueException("Unsupported resource type " + type, null); } _resourceCountDao.setResourceCount(accountId, ResourceOwnerType.Account, type, (newCount == null) ? 0 : newCount.longValue()); diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java b/server/src/com/cloud/server/ConfigurationServerImpl.java index 9ad40833db4..103ee28dc9b 100755 --- a/server/src/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/com/cloud/server/ConfigurationServerImpl.java @@ -90,6 +90,7 @@ import com.cloud.user.Account; import com.cloud.user.AccountVO; import com.cloud.user.User; import com.cloud.user.dao.AccountDao; +import com.cloud.utils.IdentityProxy; import com.cloud.utils.PasswordGenerator; import com.cloud.utils.PropertiesUtil; import com.cloud.utils.component.ComponentLocator; @@ -373,7 +374,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { // now insert the user insertSql = "INSERT INTO `cloud`.`user` (id, username, password, account_id, firstname, lastname, created) " + - "VALUES (" + id + ",'" + username + "','" + sb.toString() + "', 2, '" + firstname + "','" + lastname + "',now())"; + "VALUES (" + id + ",'" + username + "','" + sb.toString() + "', 2, '" + firstname + "','" + lastname + "',now())"; txn = Transaction.currentTxn(); try { @@ -400,10 +401,10 @@ public class ConfigurationServerImpl implements ConfigurationServer { // save default security group if (tableName.equals("security_group")) { insertSql = "INSERT INTO " + tableName + " (name, description, account_id, domain_id) " + - "VALUES ('default', 'Default Security Group', 2, 1)"; + "VALUES ('default', 'Default Security Group', 2, 1)"; } else { insertSql = "INSERT INTO " + tableName + " (name, description, account_id, domain_id, account_name) " + - "VALUES ('default', 'Default Security Group', 2, 1, 'admin')"; + "VALUES ('default', 'Default Security Group', 2, 1, 'admin')"; } txn = Transaction.currentTxn(); @@ -561,8 +562,8 @@ public class ConfigurationServerImpl implements ConfigurationServer { try { String rpassword = PasswordGenerator.generatePresharedKey(8); String wSql = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " - + "VALUES ('Hidden','DEFAULT', 'management-server','system.vm.password', '" + rpassword - + "','randmon password generated each management server starts for system vm')"; + + "VALUES ('Hidden','DEFAULT', 'management-server','system.vm.password', '" + rpassword + + "','randmon password generated each management server starts for system vm')"; PreparedStatement stmt = txn.prepareAutoCloseStatement(wSql); stmt.executeUpdate(wSql); s_logger.info("Updated systemvm password in database"); @@ -635,9 +636,9 @@ public class ConfigurationServerImpl implements ConfigurationServer { String publicKey = new String(arr2).trim(); String insertSql1 = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " + - "VALUES ('Hidden','DEFAULT', 'management-server','ssh.privatekey', '" + DBEncryptionUtil.encrypt(privateKey) + "','Private key for the entire CloudStack')"; + "VALUES ('Hidden','DEFAULT', 'management-server','ssh.privatekey', '" + DBEncryptionUtil.encrypt(privateKey) + "','Private key for the entire CloudStack')"; String insertSql2 = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " + - "VALUES ('Hidden','DEFAULT', 'management-server','ssh.publickey', '" + DBEncryptionUtil.encrypt(publicKey) + "','Public key for the entire CloudStack')"; + "VALUES ('Hidden','DEFAULT', 'management-server','ssh.publickey', '" + DBEncryptionUtil.encrypt(publicKey) + "','Public key for the entire CloudStack')"; Transaction txn = Transaction.currentTxn(); try { @@ -749,7 +750,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { String password = PasswordGenerator.generateRandomPassword(12); String insertSql1 = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " + - "VALUES ('Hidden','DEFAULT', 'management-server','secstorage.copy.password', '" + DBEncryptionUtil.encrypt(password) + "','Password used to authenticate zone-to-zone template copy requests')"; + "VALUES ('Hidden','DEFAULT', 'management-server','secstorage.copy.password', '" + DBEncryptionUtil.encrypt(password) + "','Password used to authenticate zone-to-zone template copy requests')"; Transaction txn = Transaction.currentTxn(); try { @@ -818,12 +819,12 @@ public class ConfigurationServerImpl implements ConfigurationServer { String ipNums = _configDao.getValue("linkLocalIp.nums"); int nums = Integer.parseInt(ipNums); if (nums > 16 || nums <= 0) { - throw new InvalidParameterValueException("The linkLocalIp.nums: " + nums + "is wrong, should be 1~16"); + throw new InvalidParameterValueException("The linkLocalIp.nums: " + nums + "is wrong, should be 1~16", null); } /* local link ip address starts from 169.254.0.2 - 169.254.(nums) */ String[] linkLocalIpRanges = NetUtils.getLinkLocalIPRange(nums); if (linkLocalIpRanges == null) { - throw new InvalidParameterValueException("The linkLocalIp.nums: " + nums + "may be wrong, should be 1~16"); + throw new InvalidParameterValueException("The linkLocalIp.nums: " + nums + "may be wrong, should be 1~16", null); } else { _zoneDao.addLinkLocalIpAddress(zoneId, pod.getId(), linkLocalIpRanges[0], linkLocalIpRanges[1]); } @@ -977,7 +978,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { for (Service service : defaultIsolatedSourceNatEnabledNetworkOfferingProviders.keySet()) { NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO - (defaultIsolatedSourceNatEnabledNetworkOffering.getId(), service, defaultIsolatedSourceNatEnabledNetworkOfferingProviders.get(service)); + (defaultIsolatedSourceNatEnabledNetworkOffering.getId(), service, defaultIsolatedSourceNatEnabledNetworkOfferingProviders.get(service)); _ntwkOfferingServiceMapDao.persist(offService); s_logger.trace("Added service for the network offering: " + offService); } @@ -1041,7 +1042,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { for (Service service : defaultVpcNetworkOfferingProviders.keySet()) { NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO - (defaultNetworkOfferingForVpcNetworks.getId(), service, defaultVpcNetworkOfferingProviders.get(service)); + (defaultNetworkOfferingForVpcNetworks.getId(), service, defaultVpcNetworkOfferingProviders.get(service)); _ntwkOfferingServiceMapDao.persist(offService); s_logger.trace("Added service for the network offering: " + offService); } @@ -1070,7 +1071,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { for (Service service : defaultVpcNetworkOfferingProvidersNoLB.keySet()) { NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO - (defaultNetworkOfferingForVpcNetworksNoLB.getId(), service, defaultVpcNetworkOfferingProvidersNoLB.get(service)); + (defaultNetworkOfferingForVpcNetworksNoLB.getId(), service, defaultVpcNetworkOfferingProvidersNoLB.get(service)); _ntwkOfferingServiceMapDao.persist(offService); s_logger.trace("Added service for the network offering: " + offService); } @@ -1173,12 +1174,15 @@ public class ConfigurationServerImpl implements ConfigurationServer { } if (networkOfferingId == null) { - throw new InvalidParameterValueException("Unable to find system network offering with traffic type " + trafficType); + throw new InvalidParameterValueException("Unable to find system network offering with traffic type " + trafficType, null); } List networks = _networkDao.listBy(Account.ACCOUNT_ID_SYSTEM, networkOfferingId, zoneId); if (networks == null || networks.isEmpty()) { - throw new InvalidParameterValueException("Unable to find network with traffic type " + trafficType + " in zone " + zoneId); + List idList = new ArrayList(); + idList.add(new IdentityProxy("data_center", zoneId, "zoneId")); + throw new InvalidParameterValueException("Unable to find network with traffic type " + trafficType + + " in zone with specified zoneId", idList); } return networks.get(0).getId(); } diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index a94933fd899..606f69bf9b8 100755 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -2196,7 +2196,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // 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()); + throw new InvalidParameterValueException("Unable to find physical network by id and tag: " +requiredOfferings.get(0).getTags(), null); } s_logger.debug("Creating network for account " + owner + " from the network offering id=" + requiredOfferings.get(0).getId() + " as a part of deployVM process"); @@ -2429,7 +2429,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager String instanceName = VirtualMachineName.getVmName(id, owner.getId(), _instance); String uuidName = UUID.randomUUID().toString(); - + //verify hostname information if (hostName == null) { hostName = uuidName; @@ -2453,16 +2453,16 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager ntwkDomains.put(ntwkDomain, ntwkIds); } } - + for (String ntwkDomain : ntwkDomains.keySet()) { for (Long ntwkId : ntwkDomains.get(ntwkDomain)) { - //* get all vms hostNames in the network + //* get all vms hostNames in the network List hostNames = _vmInstanceDao.listDistinctHostNames(ntwkId); //* verify that there are no duplicates if (hostNames.contains(hostName)) { throw new InvalidParameterValueException("The vm with hostName " + hostName + " already exists in the network domain: " + ntwkDomain + "; network=" - + _networkMgr.getNetwork(ntwkId)); + + _networkMgr.getNetwork(ntwkId), null); } } } @@ -3259,7 +3259,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } return usesLocalStorage; } - + @Override @ActionEvent(eventType = EventTypes.EVENT_VM_MIGRATE, eventDescription = "migrating VM", async = true) public VirtualMachine migrateVirtualMachine(Long vmId, Host destinationHost) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException { @@ -3592,7 +3592,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (physicalNetwork == null) { throw new InvalidParameterValueException("Unable to find physical network with id: "+physicalNetworkId + " and tag: " +requiredOfferings.get(0).getTags()); } - + s_logger.debug("Creating network for account " + newAccount + " from the network offering id=" + requiredOfferings.get(0).getId() + " as a part of deployVM process"); Network newNetwork = _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(), @@ -3745,9 +3745,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } @Override public boolean recreateNeeded(VirtualMachineProfile profile, - long hostId, Commands cmds, ReservationContext context) { - // TODO Auto-generated method stub - return false; + long hostId, Commands cmds, ReservationContext context) { + // TODO Auto-generated method stub + return false; } } diff --git a/test/integration/component/test_stopped_vm.py b/test/integration/component/test_stopped_vm.py index 2d2ea05e271..8a4c45fa005 100644 --- a/test/integration/component/test_stopped_vm.py +++ b/test/integration/component/test_stopped_vm.py @@ -1884,8 +1884,7 @@ class TestUploadAttachVolume(cloudstackTestCase): 'Stopped', "Check VM state is Running or not" ) - try: + with self.assertRaises(Exception): virtual_machine.attach_volume(self.apiclient, volume) - except Exception as e: - self.fail("Failed to attach the volume: %s" % e) + self.debug("Failed to attach the volume as expected") return